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