a02eb3720b293213a6ab2b9c9fb80803d4eaa8ae
[ardour.git] / libs / ardour / audioregion.cc
1 /*
2     Copyright (C) 2000-2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <cmath>
21 #include <climits>
22 #include <cfloat>
23 #include <algorithm>
24
25 #include <set>
26
27 #include <boost/scoped_array.hpp>
28
29 #include <glibmm/threads.h>
30
31 #include "pbd/basename.h"
32 #include "pbd/xml++.h"
33 #include "pbd/stacktrace.h"
34 #include "pbd/enumwriter.h"
35 #include "pbd/convert.h"
36
37 #include "evoral/Curve.hpp"
38
39 #include "ardour/audioregion.h"
40 #include "ardour/session.h"
41 #include "ardour/dB.h"
42 #include "ardour/debug.h"
43 #include "ardour/playlist.h"
44 #include "ardour/audiofilesource.h"
45 #include "ardour/region_factory.h"
46 #include "ardour/runtime_functions.h"
47 #include "ardour/transient_detector.h"
48 #include "ardour/progress.h"
49
50 #include "i18n.h"
51 #include <locale.h>
52
53 using namespace std;
54 using namespace ARDOUR;
55 using namespace PBD;
56
57 namespace ARDOUR {
58         namespace Properties {
59                 PBD::PropertyDescriptor<bool> envelope_active;
60                 PBD::PropertyDescriptor<bool> default_fade_in;
61                 PBD::PropertyDescriptor<bool> default_fade_out;
62                 PBD::PropertyDescriptor<bool> fade_in_active;
63                 PBD::PropertyDescriptor<bool> fade_out_active;
64                 PBD::PropertyDescriptor<float> scale_amplitude;
65                 PBD::PropertyDescriptor<bool> fade_out_is_xfade;
66                 PBD::PropertyDescriptor<bool> fade_out_is_short;
67                 PBD::PropertyDescriptor<bool> fade_in_is_xfade;
68                 PBD::PropertyDescriptor<bool> fade_in_is_short;
69                 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > fade_in;
70                 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > inverse_fade_in;
71                 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > fade_out;
72                 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > inverse_fade_out;
73                 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > envelope;
74         }
75 }
76
77 static const double VERY_SMALL_SIGNAL = 0.0000001;  //-140dB
78
79 /* Curve manipulations */
80
81 static void
82 reverse_curve (boost::shared_ptr<Evoral::ControlList> dst, boost::shared_ptr<const Evoral::ControlList> src)
83 {
84         size_t len = src->back()->when;
85         for (Evoral::ControlList::const_reverse_iterator it = src->rbegin(); it!=src->rend(); it++) {
86                 dst->fast_simple_add (len - (*it)->when, (*it)->value);
87         }
88 }
89
90 static void
91 generate_inverse_power_curve (boost::shared_ptr<Evoral::ControlList> dst, boost::shared_ptr<const Evoral::ControlList> src)
92 {
93         // calc inverse curve using sum of squares
94         for (Evoral::ControlList::const_iterator it = src->begin(); it!=src->end(); ++it ) {
95                 float value = (*it)->value;
96                 value = 1 - powf(value,2);
97                 value = sqrtf(value);
98                 dst->fast_simple_add ( (*it)->when, value );
99         }
100 }
101
102 static void
103 generate_db_fade (boost::shared_ptr<Evoral::ControlList> dst, double len, int num_steps, float dB_drop)
104 {
105         dst->clear ();
106         dst->fast_simple_add (0, 1);
107
108         //generate a fade-out curve by successively applying a gain drop
109         float fade_speed = dB_to_coefficient(dB_drop / (float) num_steps);
110         for (int i = 1; i < (num_steps-1); i++) {
111                 float coeff = 1.0;
112                 for (int j = 0; j < i; j++) {
113                         coeff *= fade_speed;
114                 }
115                 dst->fast_simple_add (len*(double)i/(double)num_steps, coeff);
116         }
117
118         dst->fast_simple_add (len, VERY_SMALL_SIGNAL);
119 }
120
121 static void
122 merge_curves (boost::shared_ptr<Evoral::ControlList> dst, 
123               boost::shared_ptr<const Evoral::ControlList> curve1, 
124               boost::shared_ptr<const Evoral::ControlList> curve2)
125 {
126         Evoral::ControlList::EventList::size_type size = curve1->size();
127
128         //curve lengths must match for now
129         if (size != curve2->size()) {
130                 return;
131         }
132         
133         Evoral::ControlList::const_iterator c1 = curve1->begin();
134         int count = 0;
135         for (Evoral::ControlList::const_iterator c2 = curve2->begin(); c2!=curve2->end(); c2++ ) {
136                 float v1 = accurate_coefficient_to_dB((*c1)->value);
137                 float v2 = accurate_coefficient_to_dB((*c2)->value);
138                 
139                 double interp = v1 * ( 1.0-( (double)count / (double)size) );
140                 interp += v2 * ( (double)count / (double)size );
141
142                 interp = dB_to_coefficient(interp);
143                 dst->fast_simple_add ( (*c1)->when, interp );
144                 c1++;
145                 count++;
146         }
147 }
148
149 void
150 AudioRegion::make_property_quarks ()
151 {
152         Properties::envelope_active.property_id = g_quark_from_static_string (X_("envelope-active"));
153         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for envelope-active = %1\n",     Properties::envelope_active.property_id));
154         Properties::default_fade_in.property_id = g_quark_from_static_string (X_("default-fade-in"));
155         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for default-fade-in = %1\n",     Properties::default_fade_in.property_id));
156         Properties::default_fade_out.property_id = g_quark_from_static_string (X_("default-fade-out"));
157         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for default-fade-out = %1\n",    Properties::default_fade_out.property_id));
158         Properties::fade_in_active.property_id = g_quark_from_static_string (X_("fade-in-active"));
159         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-in-active = %1\n",      Properties::fade_in_active.property_id));
160         Properties::fade_out_active.property_id = g_quark_from_static_string (X_("fade-out-active"));
161         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-out-active = %1\n",     Properties::fade_out_active.property_id));
162         Properties::scale_amplitude.property_id = g_quark_from_static_string (X_("scale-amplitude"));
163         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for scale-amplitude = %1\n",     Properties::scale_amplitude.property_id));
164         Properties::fade_out_is_xfade.property_id = g_quark_from_static_string (X_("fade-out-is-xfade"));
165         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-out-is-xfade = %1\n",   Properties::fade_out_is_xfade.property_id));
166         Properties::fade_out_is_short.property_id = g_quark_from_static_string (X_("fade-out-is-short"));
167         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-out-is-short = %1\n",   Properties::fade_out_is_short.property_id));
168         Properties::fade_in_is_xfade.property_id = g_quark_from_static_string (X_("fade-in-is-xfade"));
169         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-in-is-xfade = %1\n",    Properties::fade_in_is_xfade.property_id));
170         Properties::fade_in_is_short.property_id = g_quark_from_static_string (X_("fade-in-is-short"));
171         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-in-is-short = %1\n",    Properties::fade_in_is_short.property_id));
172         Properties::fade_in.property_id = g_quark_from_static_string (X_("FadeIn"));
173         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for FadeIn = %1\n",              Properties::fade_in.property_id));
174         Properties::inverse_fade_in.property_id = g_quark_from_static_string (X_("InverseFadeIn"));
175         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for InverseFadeIn = %1\n",       Properties::inverse_fade_in.property_id));
176         Properties::fade_out.property_id = g_quark_from_static_string (X_("FadeOut"));
177         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for FadeOut = %1\n",             Properties::fade_out.property_id));
178         Properties::inverse_fade_out.property_id = g_quark_from_static_string (X_("InverseFadeOut"));
179         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for InverseFadeOut = %1\n",      Properties::inverse_fade_out.property_id));
180         Properties::envelope.property_id = g_quark_from_static_string (X_("Envelope"));
181         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for Envelope = %1\n",            Properties::envelope.property_id));
182 }
183
184 void
185 AudioRegion::register_properties ()
186 {
187         /* no need to register parent class properties */
188
189         add_property (_envelope_active);
190         add_property (_default_fade_in);
191         add_property (_default_fade_out);
192         add_property (_fade_in_active);
193         add_property (_fade_out_active);
194         add_property (_scale_amplitude);
195         add_property (_fade_out_is_xfade);
196         add_property (_fade_out_is_short);
197         add_property (_fade_in_is_xfade);
198         add_property (_fade_in_is_short);
199         add_property (_fade_in);
200         add_property (_inverse_fade_in);
201         add_property (_fade_out);
202         add_property (_inverse_fade_out);
203         add_property (_envelope);
204 }
205
206 #define AUDIOREGION_STATE_DEFAULT \
207         _envelope_active (Properties::envelope_active, false) \
208         , _default_fade_in (Properties::default_fade_in, true) \
209         , _default_fade_out (Properties::default_fade_out, true) \
210         , _fade_in_active (Properties::fade_in_active, true) \
211         , _fade_out_active (Properties::fade_out_active, true) \
212         , _scale_amplitude (Properties::scale_amplitude, 1.0) \
213         , _fade_in_is_xfade (Properties::fade_in_is_xfade, false) \
214         , _fade_out_is_xfade (Properties::fade_out_is_xfade, false) \
215         , _fade_in_is_short (Properties::fade_in_is_short, false) \
216         , _fade_out_is_short (Properties::fade_out_is_short, false) \
217         , _fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeInAutomation)))) \
218         , _inverse_fade_in (Properties::inverse_fade_in, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeInAutomation)))) \
219         , _fade_out (Properties::fade_out, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeOutAutomation)))) \
220         , _inverse_fade_out (Properties::inverse_fade_out, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeOutAutomation))))
221
222 #define AUDIOREGION_COPY_STATE(other) \
223         _envelope_active (Properties::envelope_active, other->_envelope_active) \
224         , _default_fade_in (Properties::default_fade_in, other->_default_fade_in) \
225         , _default_fade_out (Properties::default_fade_out, other->_default_fade_out) \
226         , _fade_in_active (Properties::fade_in_active, other->_fade_in_active) \
227         , _fade_out_active (Properties::fade_out_active, other->_fade_out_active) \
228         , _scale_amplitude (Properties::scale_amplitude, other->_scale_amplitude) \
229         , _fade_in_is_xfade (Properties::fade_in_is_xfade, other->_fade_in_is_xfade) \
230         , _fade_out_is_xfade (Properties::fade_out_is_xfade, other->_fade_out_is_xfade) \
231         , _fade_in_is_short (Properties::fade_in_is_short, other->_fade_in_is_short) \
232         , _fade_out_is_short (Properties::fade_out_is_short, other->_fade_out_is_short) \
233         , _fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_fade_in.val()))) \
234         , _inverse_fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_inverse_fade_in.val()))) \
235         , _fade_out (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_fade_out.val()))) \
236         , _inverse_fade_out (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_inverse_fade_out.val())))
237 /* a Session will reset these to its chosen defaults by calling AudioRegion::set_default_fade() */
238
239 void
240 AudioRegion::init ()
241 {
242         register_properties ();
243
244         suspend_property_changes();
245         set_default_fades ();
246         set_default_envelope ();
247         resume_property_changes();
248
249         listen_to_my_curves ();
250         connect_to_analysis_changed ();
251         connect_to_header_position_offset_changed ();
252 }
253
254 /** Constructor for use by derived types only */
255 AudioRegion::AudioRegion (Session& s, framepos_t start, framecnt_t len, std::string name)
256         : Region (s, start, len, name, DataType::AUDIO)
257         , AUDIOREGION_STATE_DEFAULT
258         , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter(EnvelopeAutomation))))
259         , _automatable (s)
260         , _fade_in_suspended (0)
261         , _fade_out_suspended (0)
262 {
263         init ();
264         assert (_sources.size() == _master_sources.size());
265 }
266
267 /** Basic AudioRegion constructor */
268 AudioRegion::AudioRegion (const SourceList& srcs)
269         : Region (srcs)
270         , AUDIOREGION_STATE_DEFAULT
271         , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter(EnvelopeAutomation))))
272         , _automatable(srcs[0]->session())
273         , _fade_in_suspended (0)
274         , _fade_out_suspended (0)
275 {
276         init ();
277         assert (_sources.size() == _master_sources.size());
278 }
279
280 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other)
281         : Region (other)
282         , AUDIOREGION_COPY_STATE (other)
283           /* As far as I can see, the _envelope's times are relative to region position, and have nothing
284              to do with sources (and hence _start).  So when we copy the envelope, we just use the supplied offset.
285           */
286         , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val(), 0, other->_length)))
287         , _automatable (other->session())
288         , _fade_in_suspended (0)
289         , _fade_out_suspended (0)
290 {
291         /* don't use init here, because we got fade in/out from the other region
292         */
293         register_properties ();
294         listen_to_my_curves ();
295         connect_to_analysis_changed ();
296         connect_to_header_position_offset_changed ();
297
298         assert(_type == DataType::AUDIO);
299         assert (_sources.size() == _master_sources.size());
300 }
301
302 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, framecnt_t offset)
303         : Region (other, offset)
304         , AUDIOREGION_COPY_STATE (other)
305           /* As far as I can see, the _envelope's times are relative to region position, and have nothing
306              to do with sources (and hence _start).  So when we copy the envelope, we just use the supplied offset.
307           */
308         , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val(), offset, other->_length)))
309         , _automatable (other->session())
310         , _fade_in_suspended (0)
311         , _fade_out_suspended (0)
312 {
313         /* don't use init here, because we got fade in/out from the other region
314         */
315         register_properties ();
316         listen_to_my_curves ();
317         connect_to_analysis_changed ();
318         connect_to_header_position_offset_changed ();
319
320         assert(_type == DataType::AUDIO);
321         assert (_sources.size() == _master_sources.size());
322 }
323
324 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, const SourceList& srcs)
325         : Region (boost::static_pointer_cast<const Region>(other), srcs)
326         , AUDIOREGION_COPY_STATE (other)
327         , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val())))
328         , _automatable (other->session())
329         , _fade_in_suspended (0)
330         , _fade_out_suspended (0)
331 {
332         /* make-a-sort-of-copy-with-different-sources constructor (used by audio filter) */
333
334         register_properties ();
335
336         listen_to_my_curves ();
337         connect_to_analysis_changed ();
338         connect_to_header_position_offset_changed ();
339
340         assert (_sources.size() == _master_sources.size());
341 }
342
343 AudioRegion::AudioRegion (SourceList& srcs)
344         : Region (srcs)
345         , AUDIOREGION_STATE_DEFAULT
346         , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList(Evoral::Parameter(EnvelopeAutomation))))
347         , _automatable(srcs[0]->session())
348         , _fade_in_suspended (0)
349         , _fade_out_suspended (0)
350 {
351         init ();
352
353         assert(_type == DataType::AUDIO);
354         assert (_sources.size() == _master_sources.size());
355 }
356
357 AudioRegion::~AudioRegion ()
358 {
359 }
360
361 void
362 AudioRegion::post_set (const PropertyChange& /*ignored*/)
363 {
364         if (!_sync_marked) {
365                 _sync_position = _start;
366         }
367
368         /* return to default fades if the existing ones are too long */
369
370         if (_left_of_split) {
371                 if (_fade_in->back()->when >= _length) {
372                         set_default_fade_in ();
373                 }
374                 set_default_fade_out ();
375                 _left_of_split = false;
376         }
377
378         if (_right_of_split) {
379                 if (_fade_out->back()->when >= _length) {
380                         set_default_fade_out ();
381                 }
382
383                 set_default_fade_in ();
384                 _right_of_split = false;
385         }
386
387         /* If _length changed, adjust our gain envelope accordingly */
388         _envelope->truncate_end (_length);
389 }
390
391 void
392 AudioRegion::connect_to_analysis_changed ()
393 {
394         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
395                 (*i)->AnalysisChanged.connect_same_thread (*this, boost::bind (&AudioRegion::invalidate_transients, this));
396         }
397 }
398
399 void
400 AudioRegion::connect_to_header_position_offset_changed ()
401 {
402         set<boost::shared_ptr<Source> > unique_srcs;
403
404         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
405
406                 /* connect only once to HeaderPositionOffsetChanged, even if sources are replicated
407                  */
408
409                 if (unique_srcs.find (*i) == unique_srcs.end ()) {
410                         unique_srcs.insert (*i);
411                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
412                         if (afs) {
413                                 afs->HeaderPositionOffsetChanged.connect_same_thread (*this, boost::bind (&AudioRegion::source_offset_changed, this));
414                         }
415                 }
416         }
417 }
418
419 void
420 AudioRegion::listen_to_my_curves ()
421 {
422         _envelope->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::envelope_changed, this));
423         _fade_in->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::fade_in_changed, this));
424         _fade_out->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::fade_out_changed, this));
425 }
426
427 void
428 AudioRegion::set_envelope_active (bool yn)
429 {
430         if (envelope_active() != yn) {
431                 _envelope_active = yn;
432                 send_change (PropertyChange (Properties::envelope_active));
433         }
434 }
435
436 ARDOUR::framecnt_t
437 AudioRegion::read_peaks (PeakData *buf, framecnt_t npeaks, framecnt_t offset, framecnt_t cnt, uint32_t chan_n, double samples_per_unit) const
438 {
439         if (chan_n >= _sources.size()) {
440                 return 0;
441         }
442
443         if (audio_source(chan_n)->read_peaks (buf, npeaks, offset, cnt, samples_per_unit)) {
444                 return 0;
445         } else {
446                 if (_scale_amplitude != 1.0f) {
447                         for (framecnt_t n = 0; n < npeaks; ++n) {
448                                 buf[n].max *= _scale_amplitude;
449                                 buf[n].min *= _scale_amplitude;
450                         }
451                 }
452                 return cnt;
453         }
454 }
455
456 /** @param buf Buffer to write data to (existing data will be overwritten).
457  *  @param pos Position to read from as an offset from the region position.
458  *  @param cnt Number of frames to read.
459  *  @param channel Channel to read from.
460  */
461 framecnt_t
462 AudioRegion::read (Sample* buf, framepos_t pos, framecnt_t cnt, int channel) const
463 {
464         /* raw read, no fades, no gain, nada */
465         return read_from_sources (_sources, _length, buf, _position + pos, cnt, channel);
466 }
467
468 framecnt_t
469 AudioRegion::master_read_at (Sample *buf, Sample* /*mixdown_buffer*/, float* /*gain_buffer*/,
470                              framepos_t position, framecnt_t cnt, uint32_t chan_n) const
471 {
472         /* do not read gain/scaling/fades and do not count this disk i/o in statistics */
473
474         assert (cnt >= 0);
475         return read_from_sources (
476                 _master_sources, _master_sources.front()->length (_master_sources.front()->timeline_position()),
477                 buf, position, cnt, chan_n
478                 );
479 }
480
481 /** @param buf Buffer to mix data into.
482  *  @param mixdown_buffer Scratch buffer for audio data.
483  *  @param gain_buffer Scratch buffer for gain data.
484  *  @param position Position within the session to read from.
485  *  @param cnt Number of frames to read.
486  *  @param chan_n Channel number to read.
487  */
488 framecnt_t
489 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
490                       framepos_t position,
491                       framecnt_t cnt,
492                       uint32_t chan_n) const
493 {
494         /* We are reading data from this region into buf (possibly via mixdown_buffer).
495            The caller has verified that we cover the desired section.
496         */
497
498         /* See doc/region_read.svg for a drawing which might help to explain
499            what is going on.
500         */
501
502         assert (cnt >= 0);
503         
504         if (n_channels() == 0) {
505                 return 0;
506         }
507
508         if (muted()) {
509                 return 0; /* read nothing */
510         }
511
512         
513         /* WORK OUT WHERE TO GET DATA FROM */
514
515         framecnt_t to_read;
516
517         assert (position >= _position);
518         frameoffset_t const internal_offset = position - _position;
519
520         if (internal_offset >= _length) {
521                 return 0; /* read nothing */
522         }
523
524         if ((to_read = min (cnt, _length - internal_offset)) == 0) {
525                 return 0; /* read nothing */
526         }
527
528
529         /* COMPUTE DETAILS OF ANY FADES INVOLVED IN THIS READ */
530
531         /* Amount (length) of fade in that we are dealing with in this read */
532         framecnt_t fade_in_limit = 0;
533
534         /* Offset from buf / mixdown_buffer of the start
535            of any fade out that we are dealing with
536         */
537         frameoffset_t fade_out_offset = 0;
538         
539         /* Amount (length) of fade out that we are dealing with in this read */
540         framecnt_t fade_out_limit = 0;
541
542         framecnt_t fade_interval_start = 0;
543
544         /* Fade in */
545         
546         if (_fade_in_active && _session.config.get_use_region_fades()) {
547                 
548                 framecnt_t fade_in_length = (framecnt_t) _fade_in->back()->when;
549
550                 /* see if this read is within the fade in */
551                 
552                 if (internal_offset < fade_in_length) {
553                         fade_in_limit = min (to_read, fade_in_length - internal_offset);
554                 }
555         }
556         
557         /* Fade out */
558         
559         if (_fade_out_active && _session.config.get_use_region_fades()) {
560                 
561                 /* see if some part of this read is within the fade out */
562
563                 /* .................        >|            REGION
564                                              _length
565
566                                  {           }            FADE
567                                              fade_out_length
568                                  ^
569                                  _length - fade_out_length
570                         |--------------|
571                         ^internal_offset
572                                        ^internal_offset + to_read
573
574                                        we need the intersection of [internal_offset,internal_offset+to_read] with
575                                        [_length - fade_out_length, _length]
576
577                 */
578
579
580                 fade_interval_start = max (internal_offset, _length - framecnt_t (_fade_out->back()->when));
581                 framecnt_t fade_interval_end = min(internal_offset + to_read, _length.val());
582                 
583                 if (fade_interval_end > fade_interval_start) {
584                         /* (part of the) the fade out is in this buffer */
585                         fade_out_limit = fade_interval_end - fade_interval_start;
586                         fade_out_offset = fade_interval_start - internal_offset;
587                 }
588         }
589
590         /* READ DATA FROM THE SOURCE INTO mixdown_buffer.
591            We can never read directly into buf, since it may contain data
592            from a region `below' this one in the stack, and our fades (if they exist)
593            may need to mix with the existing data.
594         */
595
596         if (read_from_sources (_sources, _length, mixdown_buffer, position, to_read, chan_n) != to_read) {
597                 return 0;
598         }
599
600         /* APPLY REGULAR GAIN CURVES AND SCALING TO mixdown_buffer */
601
602         if (envelope_active())  {
603                 _envelope->curve().get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
604
605                 if (_scale_amplitude != 1.0f) {
606                         for (framecnt_t n = 0; n < to_read; ++n) {
607                                 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
608                         }
609                 } else {
610                         for (framecnt_t n = 0; n < to_read; ++n) {
611                                 mixdown_buffer[n] *= gain_buffer[n];
612                         }
613                 }
614         } else if (_scale_amplitude != 1.0f) {
615                 apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
616         }
617
618         /* APPLY FADES TO THE DATA IN mixdown_buffer AND MIX THE RESULTS INTO
619          * buf. The key things to realize here: (1) the fade being applied is
620          * (as of April 26th 2012) just the inverse of the fade in curve (2) 
621          * "buf" contains data from lower regions already. So this operation
622          * fades out the existing material.
623          */
624
625         if (fade_in_limit != 0) {
626
627                 if (opaque()) {
628                         if (_inverse_fade_in) {
629
630                                 /* explicit inverse fade in curve (e.g. for constant
631                                  * power), so we have to fetch it.
632                                  */
633                                 
634                                 _inverse_fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
635                                 
636                                 /* Fade the data from lower layers out */
637                                 for (framecnt_t n = 0; n < fade_in_limit; ++n) {
638                                         buf[n] *= gain_buffer[n];
639                                 }
640                                 
641                                 /* refill gain buffer with the fade in */
642                                 
643                                 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
644                                 
645                         } else {
646                                 
647                                 /* no explicit inverse fade in, so just use (1 - fade
648                                  * in) for the fade out of lower layers
649                                  */
650                                 
651                                 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
652                                 
653                                 for (framecnt_t n = 0; n < fade_in_limit; ++n) {
654                                         buf[n] *= 1 - gain_buffer[n];
655                                 }
656                         }
657                 } else {
658                         _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
659                 }
660
661                 /* Mix our newly-read data in, with the fade */
662                 for (framecnt_t n = 0; n < fade_in_limit; ++n) {
663                         buf[n] += mixdown_buffer[n] * gain_buffer[n];
664                 }
665         }
666
667         if (fade_out_limit != 0) {
668
669                 framecnt_t const curve_offset = fade_interval_start - (_length - _fade_out->back()->when);
670
671                 if (opaque()) {
672                         if (_inverse_fade_out) {
673                                 
674                                 _inverse_fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
675                                 
676                                 /* Fade the data from lower levels in */
677                                 for (framecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
678                                         buf[m] *= gain_buffer[n];
679                                 }
680                                 
681                                 /* fetch the actual fade out */
682
683                                 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
684                                 
685                         } else {
686
687                                 /* no explicit inverse fade out (which is
688                                  * actually a fade in), so just use (1 - fade
689                                  * out) for the fade in of lower layers
690                                  */
691                                 
692                                 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
693                                 
694                                 for (framecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
695                                         buf[m] *= 1 - gain_buffer[n];
696                                 }
697                         }
698                 } else {
699                         _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
700                 }
701
702                 /* Mix our newly-read data with whatever was already there,
703                    with the fade out applied to our data.
704                 */
705                 for (framecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
706                         buf[m] += mixdown_buffer[m] * gain_buffer[n];
707                 }
708         }
709         
710         /* MIX OR COPY THE REGION BODY FROM mixdown_buffer INTO buf */
711
712         framecnt_t const N = to_read - fade_in_limit - fade_out_limit;
713         if (N > 0) {
714                 if (opaque ()) {
715                         DEBUG_TRACE (DEBUG::AudioPlayback, string_compose ("Region %1 memcpy into buf @ %2 + %3, from mixdown buffer @ %4 + %5, len = %6 cnt was %7\n",
716                                                                            name(), buf, fade_in_limit, mixdown_buffer, fade_in_limit, N, cnt));
717                         memcpy (buf + fade_in_limit, mixdown_buffer + fade_in_limit, N * sizeof (Sample));
718                 } else {
719                         mix_buffers_no_gain (buf + fade_in_limit, mixdown_buffer + fade_in_limit, N);
720                 }
721         }
722
723         return to_read;
724 }
725
726 /** Read data directly from one of our sources, accounting for the situation when the track has a different channel
727  *  count to the region.
728  *
729  *  @param srcs Source list to get our source from.
730  *  @param limit Furthest that we should read, as an offset from the region position.
731  *  @param buf Buffer to write data into (existing contents of the buffer will be overwritten)
732  *  @param position Position to read from, in session frames.
733  *  @param cnt Number of frames to read.
734  *  @param chan_n Channel to read from.
735  *  @return Number of frames read.
736  */
737
738 framecnt_t
739 AudioRegion::read_from_sources (SourceList const & srcs, framecnt_t limit, Sample* buf, framepos_t position, framecnt_t cnt, uint32_t chan_n) const
740 {
741         frameoffset_t const internal_offset = position - _position;
742         if (internal_offset >= limit) {
743                 return 0;
744         }
745
746         framecnt_t const to_read = min (cnt, limit - internal_offset);
747         if (to_read == 0) {
748                 return 0;
749         }
750         
751         if (chan_n < n_channels()) {
752
753                 boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[chan_n]);
754                 if (src->read (buf, _start + internal_offset, to_read) != to_read) {
755                         return 0; /* "read nothing" */
756                 }
757
758         } else {
759
760                 /* track is N-channel, this region has fewer channels; silence the ones
761                    we don't have.
762                 */
763
764                 if (Config->get_replicate_missing_region_channels()) {
765
766                         /* copy an existing channel's data in for this non-existant one */
767
768                         uint32_t channel = n_channels() % chan_n;
769                         boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[channel]);
770
771                         if (src->read (buf, _start + internal_offset, to_read) != to_read) {
772                                 return 0; /* "read nothing" */
773                         }
774
775                 } else {
776                         
777                         /* use silence */
778                         memset (buf, 0, sizeof (Sample) * to_read);
779                 }
780         }
781
782         return to_read;
783 }
784
785 XMLNode&
786 AudioRegion::state ()
787 {
788         XMLNode& node (Region::state ());
789         XMLNode *child;
790         char buf[64];
791         LocaleGuard lg (X_("POSIX"));
792
793         snprintf (buf, sizeof (buf), "%u", (uint32_t) _sources.size());
794         node.add_property ("channels", buf);
795
796         Stateful::add_properties (node);
797
798         child = node.add_child ("Envelope");
799
800         bool default_env = false;
801
802         // If there are only two points, the points are in the start of the region and the end of the region
803         // so, if they are both at 1.0f, that means the default region.
804
805         if (_envelope->size() == 2 &&
806             _envelope->front()->value == 1.0f &&
807             _envelope->back()->value==1.0f) {
808                 if (_envelope->front()->when == 0 && _envelope->back()->when == _length) {
809                         default_env = true;
810                 }
811         }
812
813         if (default_env) {
814                 child->add_property ("default", "yes");
815         } else {
816                 child->add_child_nocopy (_envelope->get_state ());
817         }
818
819         child = node.add_child (X_("FadeIn"));
820
821         if (_default_fade_in) {
822                 child->add_property ("default", "yes");
823         } else {
824                 child->add_child_nocopy (_fade_in->get_state ());
825         }
826
827         if (_inverse_fade_in) {
828                 child = node.add_child (X_("InvFadeIn"));
829                 child->add_child_nocopy (_inverse_fade_in->get_state ());
830         }
831
832         child = node.add_child (X_("FadeOut"));
833
834         if (_default_fade_out) {
835                 child->add_property ("default", "yes");
836         } else {
837                 child->add_child_nocopy (_fade_out->get_state ());
838         }
839
840         if (_inverse_fade_out) {
841                 child = node.add_child (X_("InvFadeOut"));
842                 child->add_child_nocopy (_inverse_fade_out->get_state ());
843         }
844
845         return node;
846 }
847
848 int
849 AudioRegion::_set_state (const XMLNode& node, int version, PropertyChange& what_changed, bool send)
850 {
851         const XMLNodeList& nlist = node.children();
852         const XMLProperty *prop;
853         LocaleGuard lg (X_("POSIX"));
854         boost::shared_ptr<Playlist> the_playlist (_playlist.lock());
855
856         suspend_property_changes ();
857
858         if (the_playlist) {
859                 the_playlist->freeze ();
860         }
861
862
863         /* this will set all our State members and stuff controlled by the Region.
864            It should NOT send any changed signals - that is our responsibility.
865         */
866
867         Region::_set_state (node, version, what_changed, false);
868
869         if ((prop = node.property ("scale-gain")) != 0) {
870                 float a = atof (prop->value().c_str());
871                 if (a != _scale_amplitude) {
872                         _scale_amplitude = a;
873                         what_changed.add (Properties::scale_amplitude);
874                 }
875         }
876
877         /* Now find envelope description and other related child items */
878
879         _envelope->freeze ();
880
881         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
882                 XMLNode *child;
883                 XMLProperty *prop;
884
885                 child = (*niter);
886
887                 if (child->name() == "Envelope") {
888
889                         _envelope->clear ();
890
891                         if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child, version)) {
892                                 set_default_envelope ();
893                         }
894
895                         _envelope->truncate_end (_length);
896
897
898                 } else if (child->name() == "FadeIn") {
899
900                         _fade_in->clear ();
901
902                         if (((prop = child->property ("default")) != 0 && string_is_affirmative (prop->value())) || (prop = child->property ("steepness")) != 0) {
903                                 set_default_fade_in ();
904                         } else {
905                                 XMLNode* grandchild = child->child ("AutomationList");
906                                 if (grandchild) {
907                                         _fade_in->set_state (*grandchild, version);
908                                 }
909                         }
910
911                         if ((prop = child->property ("active")) != 0) {
912                                 if (string_is_affirmative (prop->value())) {
913                                         set_fade_in_active (true);
914                                 } else {
915                                         set_fade_in_active (false);
916                                 }
917                         }
918
919                         /* legacy a3 */
920
921                         if ((prop = child->property ("is-xfade")) != 0) {
922                                 _fade_in_is_xfade = string_is_affirmative (prop->value());
923                         }
924
925                 } else if (child->name() == "FadeOut") {
926
927                         _fade_out->clear ();
928
929                         if (((prop = child->property ("default")) != 0 && (string_is_affirmative (prop->value()))) || (prop = child->property ("steepness")) != 0) {
930                                 set_default_fade_out ();
931                         } else {
932                                 XMLNode* grandchild = child->child ("AutomationList");
933                                 if (grandchild) {
934                                         _fade_out->set_state (*grandchild, version);
935                                 }
936                         }
937                         
938                         if ((prop = child->property ("active")) != 0) {
939                                 if (string_is_affirmative (prop->value())) {
940                                         set_fade_out_active (true);
941                                 } else {
942                                         set_fade_out_active (false);
943                                 }
944                         }
945
946                         /* legacy a3 */
947
948                         if ((prop = child->property ("is-xfade")) != 0) {
949                                 _fade_out_is_xfade = string_is_affirmative (prop->value());
950                         }
951                         
952                 } else if (child->name() == "InvFadeIn") {
953                         XMLNode* grandchild = child->child ("AutomationList");
954                         if (grandchild) {
955                                 _inverse_fade_in->set_state (*grandchild, version);
956                         }
957                 } else if (child->name() == "InvFadeOut") {
958                         XMLNode* grandchild = child->child ("AutomationList");
959                         if (grandchild) {
960                                 _inverse_fade_out->set_state (*grandchild, version);
961                         }
962                 }
963         }
964
965         _envelope->thaw ();
966         resume_property_changes ();
967
968         if (send) {
969                 send_change (what_changed);
970         }
971
972         if (the_playlist) {
973                 the_playlist->thaw ();
974         }
975
976         return 0;
977 }
978
979 int
980 AudioRegion::set_state (const XMLNode& node, int version)
981 {
982         PropertyChange what_changed;
983         return _set_state (node, version, what_changed, true);
984 }
985
986 void
987 AudioRegion::set_fade_in_shape (FadeShape shape)
988 {
989         set_fade_in (shape, (framecnt_t) _fade_in->back()->when);
990 }
991
992 void
993 AudioRegion::set_fade_out_shape (FadeShape shape)
994 {
995         set_fade_out (shape, (framecnt_t) _fade_out->back()->when);
996 }
997
998 void
999 AudioRegion::set_fade_in (boost::shared_ptr<AutomationList> f)
1000 {
1001         _fade_in->freeze ();
1002         *(_fade_in.val()) = *f;
1003         _fade_in->thaw ();
1004         _default_fade_in = false;
1005
1006         send_change (PropertyChange (Properties::fade_in));
1007 }
1008
1009 void
1010 AudioRegion::set_fade_in (FadeShape shape, framecnt_t len)
1011 {
1012         boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeInAutomation));
1013         boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeInAutomation));
1014         boost::shared_ptr<Evoral::ControlList> c3 (new Evoral::ControlList (FadeInAutomation));
1015
1016         _fade_in->freeze ();
1017         _fade_in->clear ();
1018         _inverse_fade_in->clear ();
1019
1020         switch (shape) {
1021         case FadeLinear:
1022                 _fade_in->fast_simple_add (0.0, 0.0);
1023                 _fade_in->fast_simple_add (len, 1.0);
1024                 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1025                 break;
1026
1027         case FadeFast:
1028                 generate_db_fade (_fade_in.val(), len, 10, -60);
1029                 reverse_curve (c1, _fade_in.val());
1030                 _fade_in->copy_events (*c1);
1031                 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1032                 break;
1033
1034         case FadeSlow:
1035                 generate_db_fade (c1, len, 10, -1);  // start off with a slow fade
1036                 generate_db_fade (c2, len, 10, -80); // end with a fast fade
1037                 merge_curves (_fade_in.val(), c1, c2);
1038                 reverse_curve (c3, _fade_in.val());
1039                 _fade_in->copy_events (*c3);
1040                 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1041                 break;
1042
1043         case FadeConstantPower:
1044                 for (int i = 0; i < 9; ++i) {
1045                         float dist = (float) i / 10.0f;
1046                         _fade_in->fast_simple_add (len*dist, sin (dist*M_PI/2));
1047                 }
1048                 _fade_in->fast_simple_add (len, 1.0);
1049                 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1050                 break;
1051                 
1052         case FadeSymmetric:
1053                 //start with a nearly linear cuve
1054                 _fade_in->fast_simple_add (0, 1);
1055                 _fade_in->fast_simple_add (0.5*len, 0.6);
1056                 //now generate a fade-out curve by successively applying a gain drop
1057                 const float breakpoint = 0.7;  //linear for first 70%
1058                 const int num_steps = 9;
1059                 for (int i = 2; i < num_steps; i++) {
1060                         float coeff = (1.0-breakpoint);
1061                         for (int j = 0; j < i; j++) {
1062                                 coeff *= 0.5;  //6dB drop per step
1063                         }
1064                         _fade_in->fast_simple_add (len* (breakpoint+((1.0-breakpoint)*(double)i/(double)num_steps)), coeff);
1065                 }
1066                 _fade_in->fast_simple_add (len, VERY_SMALL_SIGNAL);
1067                 reverse_curve (c3, _fade_in.val());
1068                 _fade_in->copy_events (*c3);
1069                 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1070                 break;
1071         }
1072
1073         _default_fade_in = false;
1074         _fade_in->thaw ();
1075         send_change (PropertyChange (Properties::fade_in));
1076 }
1077
1078 void
1079 AudioRegion::set_fade_out (boost::shared_ptr<AutomationList> f)
1080 {
1081         _fade_out->freeze ();
1082         *(_fade_out.val()) = *f;
1083         _fade_out->thaw ();
1084         _default_fade_out = false;
1085
1086         send_change (PropertyChange (Properties::fade_in));
1087 }
1088
1089 void
1090 AudioRegion::set_fade_out (FadeShape shape, framecnt_t len)
1091 {
1092         boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeOutAutomation));
1093         boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeOutAutomation));
1094
1095         _fade_out->freeze ();
1096         _fade_out->clear ();
1097         _inverse_fade_out->clear ();
1098
1099         switch (shape) {
1100         case FadeLinear:
1101                 _fade_out->fast_simple_add (0.0, 1.0);
1102                 _fade_out->fast_simple_add (len, VERY_SMALL_SIGNAL);
1103                 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1104                 break;
1105                 
1106         case FadeFast: 
1107                 generate_db_fade (_fade_out.val(), len, 10, -60);
1108                 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1109                 break;
1110                 
1111         case FadeSlow: 
1112                 generate_db_fade (c1, len, 10, -1);  //start off with a slow fade
1113                 generate_db_fade (c2, len, 10, -80);  //end with a fast fade
1114                 merge_curves (_fade_out.val(), c1, c2);
1115                 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1116                 break;
1117
1118         case FadeConstantPower:
1119                 //constant-power fades use a sin/cos relationship
1120                 //the cutoff is abrupt but it has the benefit of being symmetrical
1121                 _fade_out->fast_simple_add (0.0, 1.0);
1122                 for (int i = 1; i < 9; i++ ) {
1123                         float dist = (float)i/10.0;
1124                         _fade_out->fast_simple_add ((len * dist), cos(dist*M_PI/2));
1125                 }
1126                 _fade_out->fast_simple_add (len, VERY_SMALL_SIGNAL);
1127                 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1128                 break;
1129                 
1130         case FadeSymmetric:
1131                 //start with a nearly linear cuve
1132                 _fade_out->fast_simple_add (0, 1);
1133                 _fade_out->fast_simple_add (0.5*len, 0.6);
1134
1135                 //now generate a fade-out curve by successively applying a gain drop
1136                 const float breakpoint = 0.7;  //linear for first 70%
1137                 const int num_steps = 9;
1138                 for (int i = 2; i < num_steps; i++) {
1139                         float coeff = (1.0-breakpoint);
1140                         for (int j = 0; j < i; j++) {
1141                                 coeff *= 0.5;  //6dB drop per step
1142                         }
1143                         _fade_out->fast_simple_add (len* (breakpoint+((1.0-breakpoint)*(double)i/(double)num_steps)), coeff);
1144                 }
1145                 _fade_out->fast_simple_add (len, VERY_SMALL_SIGNAL);
1146                 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1147                 break;
1148         }
1149
1150         _default_fade_out = false;
1151         _fade_out->thaw ();
1152         send_change (PropertyChange (Properties::fade_out));
1153 }
1154
1155 void
1156 AudioRegion::set_fade_in_length (framecnt_t len)
1157 {
1158         if (len > _length) {
1159                 len = _length - 1;
1160         }
1161         
1162         if (len < 64) {
1163                 len = 64;
1164         }
1165
1166         bool changed = _fade_in->extend_to (len);
1167
1168         if (changed) {
1169                 if (_inverse_fade_in) {
1170                         _inverse_fade_in->extend_to (len);
1171                 }
1172
1173                 if (_session.config.get_xfade_model() == FullCrossfade &&
1174                     _session.config.get_auto_xfade() && 
1175                     _fade_in_is_xfade && !_fade_in_is_short) {
1176
1177                         /* trim a single other region below us to the new start
1178                            of the fade.
1179                         */
1180
1181                         boost::shared_ptr<Region> other = get_single_other_xfade_region (true);
1182                         if (other) {
1183                                 other->trim_end (position() + len);
1184                         }
1185                 }
1186
1187                 _default_fade_in = false;
1188                 send_change (PropertyChange (Properties::fade_in));
1189         }
1190 }
1191
1192 void
1193 AudioRegion::set_fade_out_length (framecnt_t len)
1194 {
1195         if (len > _length) {
1196                 len = _length - 1;
1197         }
1198
1199         if (len < 64) {
1200                 len = 64;
1201         }
1202
1203         bool changed =  _fade_out->extend_to (len);
1204
1205         if (changed) {
1206                 
1207                 if (_inverse_fade_out) {
1208                         _inverse_fade_out->extend_to (len);
1209                 }
1210                 _default_fade_out = false;
1211                 
1212                 if (_session.config.get_xfade_model() == FullCrossfade &&
1213                     _session.config.get_auto_xfade() && 
1214                     _fade_out_is_xfade && !_fade_out_is_short) {
1215
1216                         /* trim a single other region below us to the new start
1217                            of the fade.
1218                         */
1219
1220                         boost::shared_ptr<Region> other = get_single_other_xfade_region (false);
1221                         if (other) {
1222                                 other->trim_front (last_frame() - len);
1223                         }
1224                 }
1225
1226                 send_change (PropertyChange (Properties::fade_out));
1227         }
1228 }
1229
1230 void
1231 AudioRegion::set_fade_in_active (bool yn)
1232 {
1233         if (yn == _fade_in_active) {
1234                 return;
1235         }
1236
1237         _fade_in_active = yn;
1238         send_change (PropertyChange (Properties::fade_in_active));
1239 }
1240
1241 void
1242 AudioRegion::set_fade_out_active (bool yn)
1243 {
1244         if (yn == _fade_out_active) {
1245                 return;
1246         }
1247         _fade_out_active = yn;
1248         send_change (PropertyChange (Properties::fade_out_active));
1249 }
1250
1251 bool
1252 AudioRegion::fade_in_is_default () const
1253 {
1254         return _fade_in->size() == 2 && _fade_in->front()->when == 0 && _fade_in->back()->when == 64;
1255 }
1256
1257 bool
1258 AudioRegion::fade_out_is_default () const
1259 {
1260         return _fade_out->size() == 2 && _fade_out->front()->when == 0 && _fade_out->back()->when == 64;
1261 }
1262
1263 void
1264 AudioRegion::set_default_fade_in ()
1265 {
1266         _fade_in_suspended = 0;
1267         _fade_in_is_xfade = false;
1268         _fade_in_is_short = true;
1269         set_fade_in (FadeLinear, 64);
1270 }
1271
1272 void
1273 AudioRegion::set_default_fade_out ()
1274 {
1275         _fade_out_suspended = 0;
1276         _fade_out_is_xfade = false;
1277         _fade_out_is_short = true;
1278         set_fade_out (FadeLinear, 64);
1279 }
1280
1281 void
1282 AudioRegion::set_default_fades ()
1283 {
1284         set_default_fade_in ();
1285         set_default_fade_out ();
1286 }
1287
1288 void
1289 AudioRegion::set_default_envelope ()
1290 {
1291         _envelope->freeze ();
1292         _envelope->clear ();
1293         _envelope->fast_simple_add (0, 1.0f);
1294         _envelope->fast_simple_add (_length, 1.0f);
1295         _envelope->thaw ();
1296 }
1297
1298 void
1299 AudioRegion::recompute_at_end ()
1300 {
1301         /* our length has changed. recompute a new final point by interpolating
1302            based on the the existing curve.
1303         */
1304
1305         _envelope->freeze ();
1306         _envelope->truncate_end (_length);
1307         _envelope->thaw ();
1308
1309         suspend_property_changes();
1310
1311         if (_left_of_split) {
1312                 set_default_fade_out ();
1313                 _left_of_split = false;
1314         } else if (_fade_out->back()->when > _length) {
1315                 _fade_out->extend_to (_length);
1316                 send_change (PropertyChange (Properties::fade_out));
1317         }
1318
1319         if (_fade_in->back()->when > _length) {
1320                 _fade_in->extend_to (_length);
1321                 send_change (PropertyChange (Properties::fade_in));
1322         }
1323
1324         resume_property_changes();
1325 }
1326
1327 void
1328 AudioRegion::recompute_at_start ()
1329 {
1330         /* as above, but the shift was from the front */
1331
1332         _envelope->truncate_start (_length);
1333
1334         suspend_property_changes();
1335
1336         if (_right_of_split) {
1337                 set_default_fade_in ();
1338                 _right_of_split = false;
1339         } else if (_fade_in->back()->when > _length) {
1340                 _fade_in->extend_to (_length);
1341                 send_change (PropertyChange (Properties::fade_in));
1342         }
1343
1344         if (_fade_out->back()->when > _length) {
1345                 _fade_out->extend_to (_length);
1346                 send_change (PropertyChange (Properties::fade_out));
1347         }
1348
1349         resume_property_changes();
1350 }
1351
1352 int
1353 AudioRegion::separate_by_channel (Session& /*session*/, vector<boost::shared_ptr<Region> >& v) const
1354 {
1355         SourceList srcs;
1356         string new_name;
1357         int n = 0;
1358
1359         if (_sources.size() < 2) {
1360                 return 0;
1361         }
1362
1363         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1364                 srcs.clear ();
1365                 srcs.push_back (*i);
1366
1367                 new_name = _name;
1368
1369                 if (_sources.size() == 2) {
1370                         if (n == 0) {
1371                                 new_name += "-L";
1372                         } else {
1373                                 new_name += "-R";
1374                         }
1375                 } else {
1376                         new_name += '-';
1377                         new_name += ('0' + n + 1);
1378                 }
1379
1380                 /* create a copy with just one source. prevent if from being thought of as
1381                    "whole file" even if it covers the entire source file(s).
1382                  */
1383
1384                 PropertyList plist;
1385
1386                 plist.add (Properties::start, _start.val());
1387                 plist.add (Properties::length, _length.val());
1388                 plist.add (Properties::name, new_name);
1389                 plist.add (Properties::layer, layer ());
1390
1391                 v.push_back(RegionFactory::create (srcs, plist));
1392                 v.back()->set_whole_file (false);
1393
1394                 ++n;
1395         }
1396
1397         return 0;
1398 }
1399
1400 framecnt_t
1401 AudioRegion::read_raw_internal (Sample* buf, framepos_t pos, framecnt_t cnt, int channel) const
1402 {
1403         return audio_source(channel)->read (buf, pos, cnt);
1404 }
1405
1406 void
1407 AudioRegion::set_scale_amplitude (gain_t g)
1408 {
1409         boost::shared_ptr<Playlist> pl (playlist());
1410
1411         _scale_amplitude = g;
1412
1413         /* tell the diskstream we're in */
1414
1415         if (pl) {
1416                 pl->ContentsChanged();
1417         }
1418
1419         /* tell everybody else */
1420
1421         send_change (PropertyChange (Properties::scale_amplitude));
1422 }
1423
1424 /** @return the maximum (linear) amplitude of the region, or a -ve
1425  *  number if the Progress object reports that the process was cancelled.
1426  */
1427 double
1428 AudioRegion::maximum_amplitude (Progress* p) const
1429 {
1430         framepos_t fpos = _start;
1431         framepos_t const fend = _start + _length;
1432         double maxamp = 0;
1433
1434         framecnt_t const blocksize = 64 * 1024;
1435         Sample buf[blocksize];
1436
1437         while (fpos < fend) {
1438
1439                 uint32_t n;
1440
1441                 framecnt_t const to_read = min (fend - fpos, blocksize);
1442
1443                 for (n = 0; n < n_channels(); ++n) {
1444
1445                         /* read it in */
1446
1447                         if (read_raw_internal (buf, fpos, to_read, n) != to_read) {
1448                                 return 0;
1449                         }
1450
1451                         maxamp = compute_peak (buf, to_read, maxamp);
1452                 }
1453
1454                 fpos += to_read;
1455                 if (p) {
1456                         p->set_progress (float (fpos - _start) / _length);
1457                         if (p->cancelled ()) {
1458                                 return -1;
1459                         }
1460                 }
1461         }
1462
1463         return maxamp;
1464 }
1465
1466 /** Normalize using a given maximum amplitude and target, so that region
1467  *  _scale_amplitude becomes target / max_amplitude.
1468  */
1469 void
1470 AudioRegion::normalize (float max_amplitude, float target_dB)
1471 {
1472         gain_t target = dB_to_coefficient (target_dB);
1473
1474         if (target == 1.0f) {
1475                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1476                    that we may have clipped.
1477                 */
1478                 target -= FLT_EPSILON;
1479         }
1480
1481         if (max_amplitude == 0.0f) {
1482                 /* don't even try */
1483                 return;
1484         }
1485
1486         if (max_amplitude == target) {
1487                 /* we can't do anything useful */
1488                 return;
1489         }
1490
1491         set_scale_amplitude (target / max_amplitude);
1492 }
1493
1494 void
1495 AudioRegion::fade_in_changed ()
1496 {
1497         send_change (PropertyChange (Properties::fade_in));
1498 }
1499
1500 void
1501 AudioRegion::fade_out_changed ()
1502 {
1503         send_change (PropertyChange (Properties::fade_out));
1504 }
1505
1506 void
1507 AudioRegion::envelope_changed ()
1508 {
1509         send_change (PropertyChange (Properties::envelope));
1510 }
1511
1512 void
1513 AudioRegion::suspend_fade_in ()
1514 {
1515         if (++_fade_in_suspended == 1) {
1516                 if (fade_in_is_default()) {
1517                         set_fade_in_active (false);
1518                 }
1519         }
1520 }
1521
1522 void
1523 AudioRegion::resume_fade_in ()
1524 {
1525         if (--_fade_in_suspended == 0 && _fade_in_suspended) {
1526                 set_fade_in_active (true);
1527         }
1528 }
1529
1530 void
1531 AudioRegion::suspend_fade_out ()
1532 {
1533         if (++_fade_out_suspended == 1) {
1534                 if (fade_out_is_default()) {
1535                         set_fade_out_active (false);
1536                 }
1537         }
1538 }
1539
1540 void
1541 AudioRegion::resume_fade_out ()
1542 {
1543         if (--_fade_out_suspended == 0 &&_fade_out_suspended) {
1544                 set_fade_out_active (true);
1545         }
1546 }
1547
1548 bool
1549 AudioRegion::speed_mismatch (float sr) const
1550 {
1551         if (_sources.empty()) {
1552                 /* impossible, but ... */
1553                 return false;
1554         }
1555
1556         float fsr = audio_source()->sample_rate();
1557
1558         return fsr != sr;
1559 }
1560
1561 void
1562 AudioRegion::source_offset_changed ()
1563 {
1564         /* XXX this fixes a crash that should not occur. It does occur
1565            becauses regions are not being deleted when a session
1566            is unloaded. That bug must be fixed.
1567         */
1568
1569         if (_sources.empty()) {
1570                 return;
1571         }
1572
1573         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1574
1575         if (afs && afs->destructive()) {
1576                 // set_start (source()->natural_position(), this);
1577                 set_position (source()->natural_position());
1578         }
1579 }
1580
1581 boost::shared_ptr<AudioSource>
1582 AudioRegion::audio_source (uint32_t n) const
1583 {
1584         // Guaranteed to succeed (use a static cast for speed?)
1585         return boost::dynamic_pointer_cast<AudioSource>(source(n));
1586 }
1587
1588 int
1589 AudioRegion::adjust_transients (frameoffset_t delta)
1590 {
1591         for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1592                 (*x) = (*x) + delta;
1593         }
1594
1595         send_change (PropertyChange (Properties::valid_transients));
1596
1597         return 0;
1598 }
1599
1600 int
1601 AudioRegion::update_transient (framepos_t old_position, framepos_t new_position)
1602 {
1603         for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1604                 if ((*x) == old_position) {
1605                         (*x) = new_position;
1606                         send_change (PropertyChange (Properties::valid_transients));
1607
1608                         break;
1609                 }
1610         }
1611
1612         return 0;
1613 }
1614
1615 void
1616 AudioRegion::add_transient (framepos_t where)
1617 {
1618         _transients.push_back(where);
1619         _valid_transients = true;
1620
1621         send_change (PropertyChange (Properties::valid_transients));
1622 }
1623
1624 void
1625 AudioRegion::remove_transient (framepos_t where)
1626 {
1627         _transients.remove(where);
1628         _valid_transients = true;
1629
1630         send_change (PropertyChange (Properties::valid_transients));
1631 }
1632
1633 int
1634 AudioRegion::set_transients (AnalysisFeatureList& results)
1635 {
1636         _transients.clear();
1637         _transients = results;
1638         _valid_transients = true;
1639
1640         send_change (PropertyChange (Properties::valid_transients));
1641
1642         return 0;
1643 }
1644
1645 int
1646 AudioRegion::get_transients (AnalysisFeatureList& results, bool force_new)
1647 {
1648         boost::shared_ptr<Playlist> pl = playlist();
1649
1650         if (!pl) {
1651                 return -1;
1652         }
1653
1654         if (_valid_transients && !force_new) {
1655                 results = _transients;
1656                 return 0;
1657         }
1658
1659         SourceList::iterator s;
1660
1661         for (s = _sources.begin() ; s != _sources.end(); ++s) {
1662                 if (!(*s)->has_been_analysed()) {
1663                         cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
1664                         break;
1665                 }
1666         }
1667
1668         if (s == _sources.end()) {
1669                 /* all sources are analyzed, merge data from each one */
1670
1671                 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1672
1673                         /* find the set of transients within the bounds of this region */
1674
1675                         AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
1676                                                                          (*s)->transients.end(),
1677                                                                          _start);
1678
1679                         AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
1680                                                                           (*s)->transients.end(),
1681                                                                           _start + _length);
1682
1683                         /* and add them */
1684
1685                         results.insert (results.end(), low, high);
1686                 }
1687
1688                 TransientDetector::cleanup_transients (results, pl->session().frame_rate(), 3.0);
1689
1690                 /* translate all transients to current position */
1691
1692                 for (AnalysisFeatureList::iterator x = results.begin(); x != results.end(); ++x) {
1693                         (*x) -= _start;
1694                         (*x) += _position;
1695                 }
1696
1697                 _transients = results;
1698                 _valid_transients = true;
1699
1700                 return 0;
1701         }
1702
1703         /* no existing/complete transient info */
1704
1705         static bool analyse_dialog_shown = false; /* global per instance of Ardour */
1706
1707         if (!Config->get_auto_analyse_audio()) {
1708                 if (!analyse_dialog_shown) {
1709                         pl->session().Dialog (_("\
1710 You have requested an operation that requires audio analysis.\n\n\
1711 You currently have \"auto-analyse-audio\" disabled, which means \
1712 that transient data must be generated every time it is required.\n\n\
1713 If you are doing work that will require transient data on a \
1714 regular basis, you should probably enable \"auto-analyse-audio\" \
1715 then quit ardour and restart.\n\n\
1716 This dialog will not display again.  But you may notice a slight delay \
1717 in this and future transient-detection operations.\n\
1718 "));
1719                         analyse_dialog_shown = true;
1720                 }
1721         }
1722
1723         TransientDetector t (pl->session().frame_rate());
1724         bool existing_results = !results.empty();
1725
1726         _transients.clear ();
1727         _valid_transients = false;
1728
1729         for (uint32_t i = 0; i < n_channels(); ++i) {
1730
1731                 AnalysisFeatureList these_results;
1732
1733                 t.reset ();
1734
1735                 if (t.run ("", this, i, these_results)) {
1736                         return -1;
1737                 }
1738
1739                 /* translate all transients to give absolute position */
1740
1741                 for (AnalysisFeatureList::iterator i = these_results.begin(); i != these_results.end(); ++i) {
1742                         (*i) += _position;
1743                 }
1744
1745                 /* merge */
1746
1747                 _transients.insert (_transients.end(), these_results.begin(), these_results.end());
1748         }
1749
1750         if (!results.empty()) {
1751                 if (existing_results) {
1752
1753                         /* merge our transients into the existing ones, then clean up
1754                            those.
1755                         */
1756
1757                         results.insert (results.end(), _transients.begin(), _transients.end());
1758                         TransientDetector::cleanup_transients (results, pl->session().frame_rate(), 3.0);
1759                 }
1760
1761                 /* make sure ours are clean too */
1762
1763                 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1764
1765         } else {
1766
1767                 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1768                 results = _transients;
1769         }
1770
1771         _valid_transients = true;
1772
1773         return 0;
1774 }
1775
1776 /** Find areas of `silence' within a region.
1777  *
1778  *  @param threshold Threshold below which signal is considered silence (as a sample value)
1779  *  @param min_length Minimum length of silent period to be reported.
1780  *  @return Silent intervals, measured relative to the region start in the source
1781  */
1782
1783 AudioIntervalResult
1784 AudioRegion::find_silence (Sample threshold, framecnt_t min_length, InterThreadInfo& itt) const
1785 {
1786         framecnt_t const block_size = 64 * 1024;
1787         boost::scoped_array<Sample> loudest (new Sample[block_size]);
1788         boost::scoped_array<Sample> buf (new Sample[block_size]);
1789
1790         framepos_t pos = _start;
1791         framepos_t const end = _start + _length - 1;
1792
1793         AudioIntervalResult silent_periods;
1794
1795         bool in_silence = false;
1796         frameoffset_t silence_start = 0;
1797
1798         while (pos < end && !itt.cancel) {
1799
1800                 /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
1801                 memset (loudest.get(), 0, sizeof (Sample) * block_size);
1802                 for (uint32_t n = 0; n < n_channels(); ++n) {
1803
1804                         read_raw_internal (buf.get(), pos, block_size, n);
1805                         for (framecnt_t i = 0; i < block_size; ++i) {
1806                                 loudest[i] = max (loudest[i], abs (buf[i]));
1807                         }
1808                 }
1809
1810                 /* now look for silence */
1811                 for (framecnt_t i = 0; i < block_size; ++i) {
1812                         bool const silence = abs (loudest[i]) < threshold;
1813                         if (silence && !in_silence) {
1814                                 /* non-silence to silence */
1815                                 in_silence = true;
1816                                 silence_start = pos + i;
1817                         } else if (!silence && in_silence) {
1818                                 /* silence to non-silence */
1819                                 in_silence = false;
1820                                 if (pos + i - 1 - silence_start >= min_length) {
1821                                         silent_periods.push_back (std::make_pair (silence_start, pos + i - 1));
1822                                 }
1823                         }
1824                 }
1825
1826                 pos += block_size;
1827                 itt.progress = (end-pos)/(double)_length;
1828         }
1829
1830         if (in_silence && end - 1 - silence_start >= min_length) {
1831                 /* last block was silent, so finish off the last period */
1832                 silent_periods.push_back (std::make_pair (silence_start, end));
1833         }
1834
1835         itt.done = true;
1836
1837         return silent_periods;
1838 }
1839
1840 Evoral::Range<framepos_t>
1841 AudioRegion::body_range () const
1842 {
1843         return Evoral::Range<framepos_t> (first_frame() + _fade_in->back()->when + 1, last_frame() - _fade_out->back()->when);
1844 }
1845
1846 void
1847 AudioRegion::set_fade_in_is_xfade (bool yn)
1848 {
1849         if (yn == _fade_in_is_xfade) {
1850                 return;
1851         }
1852
1853         _fade_in_is_xfade = yn;
1854         send_change (PropertyChange (Properties::fade_in_is_xfade));
1855 }
1856
1857 void
1858 AudioRegion::set_fade_out_is_xfade (bool yn)
1859 {
1860         if (yn == _fade_out_is_xfade) {
1861                 return;
1862         }
1863
1864         _fade_out_is_xfade = yn;
1865         send_change (PropertyChange (Properties::fade_out_is_xfade));
1866 }
1867
1868 void
1869 AudioRegion::set_fade_in_is_short (bool yn)
1870 {
1871         if (yn == _fade_in_is_short) {
1872                 return;
1873         }
1874
1875         _fade_in_is_short = yn;
1876         send_change (PropertyChange (Properties::fade_in_is_short));
1877
1878 }
1879
1880 void
1881 AudioRegion::set_fade_out_is_short (bool yn)
1882 {
1883         if (yn == _fade_out_is_short) {
1884                 return;
1885         }
1886
1887         _fade_out_is_short = yn;
1888         send_change (PropertyChange (Properties::fade_out_is_short));
1889 }
1890
1891 boost::shared_ptr<Region>
1892 AudioRegion::get_single_other_xfade_region (bool start) const
1893 {
1894         boost::shared_ptr<Playlist> pl (playlist());
1895
1896         if (!pl) {
1897                 /* not currently in a playlist - xfade length is unbounded
1898                    (and irrelevant)
1899                 */
1900                 return boost::shared_ptr<AudioRegion> ();
1901         }
1902
1903         boost::shared_ptr<RegionList> rl;
1904
1905         if (start) {
1906                 rl = pl->regions_at (position());
1907         } else {
1908                 rl = pl->regions_at (last_frame());
1909         }
1910         
1911         RegionList::iterator i;
1912         boost::shared_ptr<Region> other;
1913         uint32_t n = 0;
1914
1915         /* count and find the other region in a single pass through the list */
1916
1917         for (i = rl->begin(); i != rl->end(); ++i) {
1918                 if ((*i).get() != this) {
1919                         other = *i;
1920                 }
1921                 ++n;
1922         }
1923
1924         if (n != 2) {
1925                 /* zero or multiple regions stacked here - don't care about xfades */
1926                 return boost::shared_ptr<AudioRegion> ();
1927         }
1928
1929         return other;
1930 }
1931
1932 framecnt_t
1933 AudioRegion::verify_xfade_bounds (framecnt_t len, bool start)
1934 {
1935         /* this is called from a UI to check on whether a new proposed
1936            length for an xfade is legal or not. it returns the legal
1937            length corresponding to @a len which may be shorter than or
1938            equal to @a len itself.
1939         */
1940
1941         boost::shared_ptr<Region> other = get_single_other_xfade_region (start);
1942         framecnt_t maxlen;
1943
1944         if (!other) {
1945                 /* zero or > 2 regions here, don't care about len, but
1946                    it can't be longer than the region itself.
1947                  */
1948                 return min (length(), len);
1949         }
1950
1951         /* we overlap a single region. clamp the length of an xfade to
1952            the maximum possible duration of the overlap (if the other
1953            region were trimmed appropriately).
1954         */
1955
1956         if (start) {
1957                 maxlen = other->latest_possible_frame() - position();
1958         } else {
1959                 maxlen = last_frame() - other->earliest_possible_position();
1960         }
1961
1962         return min (length(), min (maxlen, len));
1963                 
1964 }
1965
1966 extern "C" {
1967
1968         int region_read_peaks_from_c (void *arg, uint32_t npeaks, uint32_t start, uint32_t cnt, intptr_t data, uint32_t n_chan, double samples_per_unit)
1969 {
1970         return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (framecnt_t) npeaks, (framepos_t) start, (framecnt_t) cnt, n_chan,samples_per_unit);
1971 }
1972
1973 uint32_t region_length_from_c (void *arg)
1974 {
1975
1976         return ((AudioRegion *) arg)->length();
1977 }
1978
1979 uint32_t sourcefile_length_from_c (void *arg, double zoom_factor)
1980 {
1981         return ( (AudioRegion *) arg)->audio_source()->available_peaks (zoom_factor) ;
1982 }
1983
1984 } /* extern "C" */