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