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