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