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