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