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