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