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