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