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