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