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