add explicit inverse fade in/out curves for use when doing constant power xfading
[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 framecnt_t
357 AudioRegion::read (Sample* buf, framepos_t timeline_position, framecnt_t cnt, int channel) const
358 {
359         /* raw read, no fades, no gain, nada */
360         /* XXX: xfade: passes no mixbuf... */
361         return _read_at (_sources, _length, buf, 0, 0, _position + timeline_position, cnt, channel, ReadOps (0));
362 }
363
364 framecnt_t
365 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
366                       framepos_t position, framecnt_t cnt, uint32_t chan_n) const
367 {
368         /* regular diskstream/butler read complete with fades etc */
369         return _read_at (_sources, _length, buf, mixdown_buffer, gain_buffer,
370                          position, cnt, chan_n, ReadOps (~0));
371 }
372
373 framecnt_t
374 AudioRegion::master_read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
375                              framepos_t position, framecnt_t cnt, uint32_t chan_n) const
376 {
377         /* do not read gain/scaling/fades and do not count this disk i/o in statistics */
378
379         assert (cnt >= 0);
380
381         return _read_at (_master_sources, _master_sources.front()->length(_master_sources.front()->timeline_position()),
382                          buf, mixdown_buffer, gain_buffer, position, cnt, chan_n, ReadOps (0));
383 }
384
385 /** @param position Position within the session to read from.
386  *  @param cnt Number of frames to read.
387  */
388 framecnt_t
389 AudioRegion::_read_at (const SourceList& srcs, framecnt_t limit,
390                        Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
391                        framepos_t position,
392                        framecnt_t cnt,
393                        uint32_t chan_n,
394                        ReadOps rops) const
395 {
396         /* We are reading data from this region into buf (possibly via mixdown_buffer).
397            The caller has verified that we cover the desired section.
398         */
399
400         /* See doc/region_read.svg for a drawing which might help to explain
401            what is going on.
402         */
403
404         assert (cnt >= 0);
405         
406         if (n_channels() == 0) {
407                 return 0;
408         }
409
410         if (muted() && rops != ReadOpsNone) {
411                 return 0; /* read nothing */
412         }
413
414         
415         /* WORK OUT WHERE TO GET DATA FROM */
416
417         framecnt_t to_read;
418
419         assert (position >= _position);
420         frameoffset_t const internal_offset = position - _position;
421
422         if (internal_offset >= limit) {
423                 return 0; /* read nothing */
424         }
425
426         if ((to_read = min (cnt, limit - internal_offset)) == 0) {
427                 return 0; /* read nothing */
428         }
429
430
431         /* COMPUTE DETAILS OF ANY FADES INVOLVED IN THIS READ */
432
433         /* Amount of fade in that we are dealing with in this read */
434         framecnt_t fade_in_limit = 0;
435
436         /* Offset from buf / mixdown_buffer of the start
437            of any fade out that we are dealing with
438         */
439         frameoffset_t fade_out_offset = 0;
440         
441         /* Amount of fade in that we are dealing with in this read */
442         framecnt_t fade_out_limit = 0;
443
444         framecnt_t fade_interval_start = 0;
445
446         if (rops & ReadOpsFades) {
447
448                 /* Fade in */
449                 
450                 if (_fade_in_active && _session.config.get_use_region_fades()) {
451
452                         framecnt_t fade_in_length = (framecnt_t) _fade_in->back()->when;
453
454                         /* see if this read is within the fade in */
455
456                         if (internal_offset < fade_in_length) {
457                                 fade_in_limit = min (to_read, fade_in_length - internal_offset);
458                         }
459                 }
460
461                 /* Fade out */
462
463                 if (_fade_out_active && _session.config.get_use_region_fades()) {
464
465                         /* see if some part of this read is within the fade out */
466
467                 /* .................        >|            REGION
468                                              limit
469
470                                  {           }            FADE
471                                              fade_out_length
472                                  ^
473                                  limit - fade_out_length
474                         |--------------|
475                         ^internal_offset
476                                        ^internal_offset + to_read
477
478                                        we need the intersection of [internal_offset,internal_offset+to_read] with
479                                        [limit - fade_out_length, limit]
480
481                 */
482
483
484                         fade_interval_start = max (internal_offset, limit - framecnt_t (_fade_out->back()->when));
485                         framecnt_t fade_interval_end   = min(internal_offset + to_read, limit);
486
487                         if (fade_interval_end > fade_interval_start) {
488                                 /* (part of the) the fade out is in this buffer */
489                                 fade_out_limit = fade_interval_end - fade_interval_start;
490                                 fade_out_offset = fade_interval_start - internal_offset;
491                         }
492                 }
493         }
494
495         /* READ DATA FROM THE SOURCE INTO mixdown_buffer.
496            We can never read directly into buf, since it may contain data
497            from a transparent region `below' this one in the stack; we
498            must always mix.
499         */
500
501         if (chan_n < n_channels()) {
502
503                 boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[chan_n]);
504                 if (src->read (mixdown_buffer, _start + internal_offset, to_read) != to_read) {
505                         return 0; /* "read nothing" */
506                 }
507
508         } else {
509
510                 /* track is N-channel, this region has fewer channels; silence the ones
511                    we don't have.
512                 */
513
514                 if (Config->get_replicate_missing_region_channels()) {
515                         /* track is N-channel, this region has less channels, so use a relevant channel
516                          */
517
518                         uint32_t channel = n_channels() % chan_n;
519                         boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[channel]);
520
521                         if (src->read (mixdown_buffer, _start + internal_offset, to_read) != to_read) {
522                                 return 0; /* "read nothing" */
523                         }
524                 }
525         }
526
527         /* APPLY REGULAR GAIN CURVES AND SCALING TO mixdown_buffer */
528
529         if ((rops & ReadOpsOwnAutomation) && envelope_active())  {
530                 _envelope->curve().get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
531
532                 if ((rops & ReadOpsOwnScaling) && _scale_amplitude != 1.0f) {
533                         for (framecnt_t n = 0; n < to_read; ++n) {
534                                 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
535                         }
536                 } else {
537                         for (framecnt_t n = 0; n < to_read; ++n) {
538                                 mixdown_buffer[n] *= gain_buffer[n];
539                         }
540                 }
541         } else if ((rops & ReadOpsOwnScaling) && _scale_amplitude != 1.0f) {
542                 apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
543         }
544
545
546         /* APPLY FADES TO THE DATA IN mixdown_buffer AND MIX THE RESULTS INTO
547          * buf. The key things to realize here: (1) the fade being applied is
548          * (as of April 26th 2012) just the inverse of the fade in curve (2) 
549          * "buf" contains data from lower regions already. So this operation
550          * fades out the existing material.
551          */
552
553         if (fade_in_limit != 0) {
554                 if (_inverse_fade_in) {
555
556                         /* explicit inverse fade in curve (e.g. for constant
557                          * power), so we have to fetch it.
558                          */
559
560                         _inverse_fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
561
562                         /* Fade the data from lower layers out */
563                         for (framecnt_t n = 0; n < fade_in_limit; ++n) {
564                                 buf[n] *= gain_buffer[n];
565                         }
566
567                         /* refill gain buffer with the fade in */
568
569                         _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
570
571                 } else {
572
573                         /* no explicit inverse fade in, so just use (1 - fade
574                          * in) for the fade out of lower layers
575                          */
576
577                         _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
578
579                         for (framecnt_t n = 0; n < fade_in_limit; ++n) {
580                                 buf[n] *= 1 - gain_buffer[n];
581                         }
582                 }
583
584                 /* Mix our newly-read data in, with the fade */
585                 for (framecnt_t n = 0; n < fade_in_limit; ++n) {
586                         buf[n] += mixdown_buffer[n] * gain_buffer[n];
587                 }
588         }
589
590         if (fade_out_limit != 0) {
591
592                 framecnt_t const curve_offset = fade_interval_start - (limit - _fade_out->back()->when);
593
594                 if (_inverse_fade_out) {
595
596                         _inverse_fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
597
598                         /* Fade the data from lower levels out */
599                         for (framecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
600                                 buf[m] *= gain_buffer[n];
601                         }
602
603                         /* fetch the actual fade out */
604
605                         _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
606
607                 } else {
608                         
609                         /* no explicit inverse fade out, so just use (1 - fade
610                          * out) for the fade in of lower layers
611                          */
612
613                         _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
614                 
615                         for (framecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
616                                 buf[m] *= 1 - gain_buffer[n];
617                         }
618                 }
619
620                 /* Mix our newly-read data out, with the fade */
621                 for (framecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
622                         buf[m] += mixdown_buffer[m] * gain_buffer[n];
623                 }
624         }
625
626         
627         /* MIX THE REGION BODY FROM mixdown_buffer INTO buf */
628
629         mix_buffers_no_gain (buf + fade_in_limit, mixdown_buffer + fade_in_limit, to_read - fade_in_limit - fade_out_limit);
630
631         return to_read;
632 }
633
634 XMLNode&
635 AudioRegion::state ()
636 {
637         XMLNode& node (Region::state ());
638         XMLNode *child;
639         char buf[64];
640         LocaleGuard lg (X_("POSIX"));
641
642         snprintf (buf, sizeof (buf), "%u", (uint32_t) _sources.size());
643         node.add_property ("channels", buf);
644
645         Stateful::add_properties (node);
646
647         child = node.add_child ("Envelope");
648
649         bool default_env = false;
650
651         // If there are only two points, the points are in the start of the region and the end of the region
652         // so, if they are both at 1.0f, that means the default region.
653
654         if (_envelope->size() == 2 &&
655             _envelope->front()->value == 1.0f &&
656             _envelope->back()->value==1.0f) {
657                 if (_envelope->front()->when == 0 && _envelope->back()->when == _length) {
658                         default_env = true;
659                 }
660         }
661
662         if (default_env) {
663                 child->add_property ("default", "yes");
664         } else {
665                 child->add_child_nocopy (_envelope->get_state ());
666         }
667
668         child = node.add_child (X_("FadeIn"));
669
670         if (_default_fade_in) {
671                 child->add_property ("default", "yes");
672         } else {
673                 child->add_child_nocopy (_fade_in->get_state ());
674         }
675
676         child = node.add_child (X_("FadeOut"));
677
678         if (_default_fade_out) {
679                 child->add_property ("default", "yes");
680         } else {
681                 child->add_child_nocopy (_fade_out->get_state ());
682         }
683
684         return node;
685 }
686
687 int
688 AudioRegion::_set_state (const XMLNode& node, int version, PropertyChange& what_changed, bool send)
689 {
690         const XMLNodeList& nlist = node.children();
691         const XMLProperty *prop;
692         LocaleGuard lg (X_("POSIX"));
693         boost::shared_ptr<Playlist> the_playlist (_playlist.lock());
694
695         suspend_property_changes ();
696
697         if (the_playlist) {
698                 the_playlist->freeze ();
699         }
700
701
702         /* this will set all our State members and stuff controlled by the Region.
703            It should NOT send any changed signals - that is our responsibility.
704         */
705
706         Region::_set_state (node, version, what_changed, false);
707
708         if ((prop = node.property ("scale-gain")) != 0) {
709                 float a = atof (prop->value().c_str());
710                 if (a != _scale_amplitude) {
711                         _scale_amplitude = a;
712                         what_changed.add (Properties::scale_amplitude);
713                 }
714         }
715
716         /* Now find envelope description and other related child items */
717
718         _envelope->freeze ();
719
720         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
721                 XMLNode *child;
722                 XMLProperty *prop;
723
724                 child = (*niter);
725
726                 if (child->name() == "Envelope") {
727
728                         _envelope->clear ();
729
730                         if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child, version)) {
731                                 set_default_envelope ();
732                         }
733
734                         _envelope->truncate_end (_length);
735
736
737                 } else if (child->name() == "FadeIn") {
738
739                         _fade_in->clear ();
740
741                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0) {
742                                 set_default_fade_in ();
743                         } else {
744                                 XMLNode* grandchild = child->child ("AutomationList");
745                                 if (grandchild) {
746                                         _fade_in->set_state (*grandchild, version);
747                                 }
748                         }
749
750                         if ((prop = child->property ("active")) != 0) {
751                                 if (string_is_affirmative (prop->value())) {
752                                         set_fade_in_active (true);
753                                 } else {
754                                         set_fade_in_active (false);
755                                 }
756                         }
757
758                 } else if (child->name() == "FadeOut") {
759
760                         _fade_out->clear ();
761
762                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0) {
763                                 set_default_fade_out ();
764                         } else {
765                                 XMLNode* grandchild = child->child ("AutomationList");
766                                 if (grandchild) {
767                                         _fade_out->set_state (*grandchild, version);
768                                 }
769                         }
770
771                         if ((prop = child->property ("active")) != 0) {
772                                 if (string_is_affirmative (prop->value())) {
773                                         set_fade_out_active (true);
774                                 } else {
775                                         set_fade_out_active (false);
776                                 }
777                         }
778
779                 }
780         }
781
782         _envelope->thaw ();
783         resume_property_changes ();
784
785         if (send) {
786                 send_change (what_changed);
787         }
788
789         if (the_playlist) {
790                 the_playlist->thaw ();
791         }
792
793         return 0;
794 }
795
796 int
797 AudioRegion::set_state (const XMLNode& node, int version)
798 {
799         PropertyChange what_changed;
800         return _set_state (node, version, what_changed, true);
801 }
802
803 void
804 AudioRegion::set_fade_in_shape (FadeShape shape)
805 {
806         set_fade_in (shape, (framecnt_t) _fade_in->back()->when);
807 }
808
809 void
810 AudioRegion::set_fade_out_shape (FadeShape shape)
811 {
812         set_fade_out (shape, (framecnt_t) _fade_out->back()->when);
813 }
814
815 void
816 AudioRegion::set_fade_in (boost::shared_ptr<AutomationList> f)
817 {
818         _fade_in->freeze ();
819         *_fade_in = *f;
820         _fade_in->thaw ();
821
822         send_change (PropertyChange (Properties::fade_in));
823 }
824
825 void
826 AudioRegion::set_fade_in (FadeShape shape, framecnt_t len)
827 {
828         _fade_in->freeze ();
829         _fade_in->clear ();
830
831         switch (shape) {
832         case FadeLinear:
833                 _fade_in->fast_simple_add (0.0, 0.0);
834                 _fade_in->fast_simple_add (len, 1.0);
835                 _inverse_fade_in.reset ();
836                 break;
837
838         case FadeFast:
839                 _fade_in->fast_simple_add (0, 0);
840                 _fade_in->fast_simple_add (len * 0.389401, 0.0333333);
841                 _fade_in->fast_simple_add (len * 0.629032, 0.0861111);
842                 _fade_in->fast_simple_add (len * 0.829493, 0.233333);
843                 _fade_in->fast_simple_add (len * 0.9447, 0.483333);
844                 _fade_in->fast_simple_add (len * 0.976959, 0.697222);
845                 _fade_in->fast_simple_add (len, 1);
846                 _inverse_fade_in.reset ();
847                 break;
848
849         case FadeSlow:
850                 _fade_in->fast_simple_add (0, 0);
851                 _fade_in->fast_simple_add (len * 0.0207373, 0.197222);
852                 _fade_in->fast_simple_add (len * 0.0645161, 0.525);
853                 _fade_in->fast_simple_add (len * 0.152074, 0.802778);
854                 _fade_in->fast_simple_add (len * 0.276498, 0.919444);
855                 _fade_in->fast_simple_add (len * 0.481567, 0.980556);
856                 _fade_in->fast_simple_add (len * 0.767281, 1);
857                 _fade_in->fast_simple_add (len, 1);
858                 _inverse_fade_in.reset ();
859                 break;
860
861         case FadeLogA:
862                 _fade_in->fast_simple_add (0, 0);
863                 _fade_in->fast_simple_add (len * 0.0737327, 0.308333);
864                 _fade_in->fast_simple_add (len * 0.246544, 0.658333);
865                 _fade_in->fast_simple_add (len * 0.470046, 0.886111);
866                 _fade_in->fast_simple_add (len * 0.652074, 0.972222);
867                 _fade_in->fast_simple_add (len * 0.771889, 0.988889);
868                 _fade_in->fast_simple_add (len, 1);
869                 _inverse_fade_in.reset ();
870                 break;
871
872         case FadeLogB:
873                 _fade_in->fast_simple_add (0, 0);
874                 _fade_in->fast_simple_add (len * 0.304147, 0.0694444);
875                 _fade_in->fast_simple_add (len * 0.529954, 0.152778);
876                 _fade_in->fast_simple_add (len * 0.725806, 0.333333);
877                 _fade_in->fast_simple_add (len * 0.847926, 0.558333);
878                 _fade_in->fast_simple_add (len * 0.919355, 0.730556);
879                 _fade_in->fast_simple_add (len, 1);
880                 _inverse_fade_in.reset ();
881                 break;
882
883         case FadeConstantPowerMinus3dB:
884                 _fade_in->fast_simple_add (0.0, 0.0);
885                 _fade_in->fast_simple_add ((len * 0.166667), 0.282192);
886                 _fade_in->fast_simple_add ((len * 0.333333), 0.518174);
887                 _fade_in->fast_simple_add ((len * 0.500000), 0.707946);
888                 _fade_in->fast_simple_add ((len * 0.666667), 0.851507);
889                 _fade_in->fast_simple_add ((len * 0.833333), 0.948859);
890                 _fade_in->fast_simple_add (len, 1.0);
891
892                 /* setup complementary fade out for lower layers */
893
894                 if (!_inverse_fade_in) {
895                         _inverse_fade_in.reset (new AutomationList (Evoral::Parameter (FadeInAutomation)));
896                 }
897
898                 _inverse_fade_in->clear ();
899                 _inverse_fade_in->fast_simple_add (0.0, 1.0);
900                 _inverse_fade_in->fast_simple_add ((len * 0.166667), 0.948859);
901                 _inverse_fade_in->fast_simple_add ((len * 0.333333), 0.851507);
902                 _inverse_fade_in->fast_simple_add ((len * 0.500000), 0.707946);
903                 _inverse_fade_in->fast_simple_add ((len * 0.666667), 0.518174);
904                 _inverse_fade_in->fast_simple_add ((len * 0.833333), 0.282192);
905                 _inverse_fade_in->fast_simple_add (len, 0.0);
906
907                 break;
908                 
909         case FadeConstantPowerMinus6dB:
910                 _fade_in->fast_simple_add (0.0, 0.0);
911                 _fade_in->fast_simple_add ((len * 0.166667), 0.166366);
912                 _fade_in->fast_simple_add ((len * 0.333333), 0.332853);
913                 _fade_in->fast_simple_add ((len * 0.500000), 0.499459);
914                 _fade_in->fast_simple_add ((len * 0.666667), 0.666186);
915                 _fade_in->fast_simple_add ((len * 0.833333), 0.833033);
916                 _fade_in->fast_simple_add (len, 1.0);
917
918                 /* setup complementary fade out for lower layers */
919
920                 if (!_inverse_fade_in) {
921                         _inverse_fade_in.reset (new AutomationList (Evoral::Parameter (FadeInAutomation)));
922                 }
923
924                 _inverse_fade_in->clear ();
925                 _inverse_fade_in->fast_simple_add (0.0, 1.0);
926                 _inverse_fade_in->fast_simple_add ((len * 0.166667), 0.833033);
927                 _inverse_fade_in->fast_simple_add ((len * 0.333333), 0.666186);
928                 _inverse_fade_in->fast_simple_add ((len * 0.500000), 0.499459);
929                 _inverse_fade_in->fast_simple_add ((len * 0.666667), 0.332853);
930                 _inverse_fade_in->fast_simple_add ((len * 0.833333), 0.166366);
931                 _inverse_fade_in->fast_simple_add (len, 0.0);
932
933                 break;
934         }
935
936         _fade_in->thaw ();
937         send_change (PropertyChange (Properties::fade_in));
938 }
939
940 void
941 AudioRegion::set_fade_out (boost::shared_ptr<AutomationList> f)
942 {
943         _fade_out->freeze ();
944         *_fade_out = *f;
945         _fade_out->thaw ();
946
947         send_change (PropertyChange (Properties::fade_in));
948 }
949
950 void
951 AudioRegion::set_fade_out (FadeShape shape, framecnt_t len)
952 {
953         _fade_out->freeze ();
954         _fade_out->clear ();
955
956         switch (shape) {
957         case FadeFast:
958                 _fade_out->fast_simple_add (0.0, 1.0);
959                 _fade_out->fast_simple_add (len * 0.023041, 0.697222);
960                 _fade_out->fast_simple_add (len * 0.0553,   0.483333);
961                 _fade_out->fast_simple_add (len * 0.170507, 0.233333);
962                 _fade_out->fast_simple_add (len * 0.370968, 0.0861111);
963                 _fade_out->fast_simple_add (len * 0.610599, 0.0333333);
964                 _fade_out->fast_simple_add (1.0, 0.0);
965                 _inverse_fade_out.reset ();
966                 break;
967
968         case FadeLogA:
969                 _fade_out->fast_simple_add (0, 1.0);
970                 _fade_out->fast_simple_add (len * 0.228111, 0.988889);
971                 _fade_out->fast_simple_add (len * 0.347926, 0.972222);
972                 _fade_out->fast_simple_add (len * 0.529954, 0.886111);
973                 _fade_out->fast_simple_add (len * 0.753456, 0.658333);
974                 _fade_out->fast_simple_add (len * 0.9262673, 0.308333);
975                 _fade_out->fast_simple_add (len, 0.0);
976                 _inverse_fade_out.reset ();
977                 break;
978
979         case FadeSlow:
980                 _fade_out->fast_simple_add (0.0, 1.0);
981                 _fade_out->fast_simple_add (len * 0.305556, 1);
982                 _fade_out->fast_simple_add (len * 0.548611, 0.991736);
983                 _fade_out->fast_simple_add (len * 0.759259, 0.931129);
984                 _fade_out->fast_simple_add (len * 0.918981, 0.68595);
985                 _fade_out->fast_simple_add (len * 0.976852, 0.22865);
986                 _fade_out->fast_simple_add (len, 0.0);
987                 _inverse_fade_out.reset ();
988                 break;
989
990         case FadeLogB:
991                 _fade_out->fast_simple_add (0.0, 1.0);
992                 _fade_out->fast_simple_add (len * 0.080645, 0.730556);
993                 _fade_out->fast_simple_add (len * 0.277778, 0.289256);
994                 _fade_out->fast_simple_add (len * 0.470046, 0.152778);
995                 _fade_out->fast_simple_add (len * 0.695853, 0.0694444);
996                 _fade_out->fast_simple_add (len, 0.0);
997                 _inverse_fade_out.reset ();     
998                 break;
999
1000         case FadeLinear:
1001                 _fade_out->fast_simple_add (0.0, 1.0);
1002                 _fade_out->fast_simple_add (len, 0.0);
1003                 _inverse_fade_out.reset ();
1004                 break;
1005
1006         case FadeConstantPowerMinus3dB:
1007                 _fade_out->fast_simple_add (0.0, 1.0);
1008                 _fade_out->fast_simple_add ((len * 0.166667), 0.948859);
1009                 _fade_out->fast_simple_add ((len * 0.333333), 0.851507);
1010                 _fade_out->fast_simple_add ((len * 0.500000), 0.707946);
1011                 _fade_out->fast_simple_add ((len * 0.666667), 0.518174);
1012                 _fade_out->fast_simple_add ((len * 0.833333), 0.282192);
1013                 _fade_out->fast_simple_add (len, 0.0);
1014
1015                 /* setup complementary fade in for lower layers */
1016
1017                 if (!_inverse_fade_out) {
1018                         _inverse_fade_out.reset (new AutomationList (Evoral::Parameter (FadeInAutomation)));
1019                 }
1020
1021                 _inverse_fade_out->clear ();
1022                 _inverse_fade_out->fast_simple_add (0.0, 0.0);
1023                 _inverse_fade_out->fast_simple_add ((len * 0.166667), 0.166366);
1024                 _inverse_fade_out->fast_simple_add ((len * 0.333333), 0.332853);
1025                 _inverse_fade_out->fast_simple_add ((len * 0.500000), 0.499459);
1026                 _inverse_fade_out->fast_simple_add ((len * 0.666667), 0.666186);
1027                 _inverse_fade_out->fast_simple_add ((len * 0.833333), 0.833033);
1028                 _inverse_fade_out->fast_simple_add (len, 1.0);
1029
1030                 break;
1031
1032         case FadeConstantPowerMinus6dB:
1033                 _fade_out->fast_simple_add (0.0, 1.0);
1034                 _fade_out->fast_simple_add ((len * 0.166667), 0.833033);
1035                 _fade_out->fast_simple_add ((len * 0.333333), 0.666186);
1036                 _fade_out->fast_simple_add ((len * 0.500000), 0.499459);
1037                 _fade_out->fast_simple_add ((len * 0.666667), 0.332853);
1038                 _fade_out->fast_simple_add ((len * 0.833333), 0.166366);
1039                 _fade_out->fast_simple_add (len, 0.0);
1040
1041                 /* setup complementary fade in for lower layers */
1042
1043                 if (!_inverse_fade_out) {
1044                         _inverse_fade_out.reset (new AutomationList (Evoral::Parameter (FadeInAutomation)));
1045                 }
1046
1047                 _inverse_fade_out->clear ();
1048                 _inverse_fade_out->fast_simple_add (0.0, 0.0);
1049                 _inverse_fade_out->fast_simple_add ((len * 0.166667), 0.166366);
1050                 _inverse_fade_out->fast_simple_add ((len * 0.333333), 0.332853);
1051                 _inverse_fade_out->fast_simple_add ((len * 0.500000), 0.499459);
1052                 _inverse_fade_out->fast_simple_add ((len * 0.666667), 0.666186);
1053                 _inverse_fade_out->fast_simple_add ((len * 0.833333), 0.833033);
1054                 _inverse_fade_out->fast_simple_add (len, 1.0);
1055
1056                 break;
1057         }
1058
1059         _fade_out->thaw ();
1060         send_change (PropertyChange (Properties::fade_in));
1061 }
1062
1063 void
1064 AudioRegion::set_fade_in_length (framecnt_t len)
1065 {
1066         if (len > _length) {
1067                 len = _length - 1;
1068         }
1069
1070         bool changed = _fade_in->extend_to (len);
1071
1072         if (changed) {
1073                 _default_fade_in = false;
1074                 send_change (PropertyChange (Properties::fade_in));
1075         }
1076 }
1077
1078 void
1079 AudioRegion::set_fade_out_length (framecnt_t len)
1080 {
1081         if (len > _length) {
1082                 len = _length - 1;
1083         }
1084
1085         bool changed =  _fade_out->extend_to (len);
1086
1087         if (changed) {
1088                 _default_fade_out = false;
1089                 send_change (PropertyChange (Properties::fade_out));
1090         }
1091 }
1092
1093 void
1094 AudioRegion::set_fade_in_active (bool yn)
1095 {
1096         if (yn == _fade_in_active) {
1097                 return;
1098         }
1099
1100         _fade_in_active = yn;
1101         send_change (PropertyChange (Properties::fade_in_active));
1102 }
1103
1104 void
1105 AudioRegion::set_fade_out_active (bool yn)
1106 {
1107         if (yn == _fade_out_active) {
1108                 return;
1109         }
1110         _fade_out_active = yn;
1111         send_change (PropertyChange (Properties::fade_out_active));
1112 }
1113
1114 bool
1115 AudioRegion::fade_in_is_default () const
1116 {
1117         return _fade_in->size() == 2 && _fade_in->front()->when == 0 && _fade_in->back()->when == 64;
1118 }
1119
1120 bool
1121 AudioRegion::fade_out_is_default () const
1122 {
1123         return _fade_out->size() == 2 && _fade_out->front()->when == 0 && _fade_out->back()->when == 64;
1124 }
1125
1126 void
1127 AudioRegion::set_default_fade_in ()
1128 {
1129         _fade_in_suspended = 0;
1130         _fade_in_is_xfade = false;
1131         set_fade_in (FadeLinear, 64);
1132 }
1133
1134 void
1135 AudioRegion::set_default_fade_out ()
1136 {
1137         _fade_out_suspended = 0;
1138         _fade_out_is_xfade = false;
1139         set_fade_out (FadeLinear, 64);
1140 }
1141
1142 void
1143 AudioRegion::set_default_fades ()
1144 {
1145         set_default_fade_in ();
1146         set_default_fade_out ();
1147 }
1148
1149 void
1150 AudioRegion::set_default_envelope ()
1151 {
1152         _envelope->freeze ();
1153         _envelope->clear ();
1154         _envelope->fast_simple_add (0, 1.0f);
1155         _envelope->fast_simple_add (_length, 1.0f);
1156         _envelope->thaw ();
1157 }
1158
1159 void
1160 AudioRegion::recompute_at_end ()
1161 {
1162         /* our length has changed. recompute a new final point by interpolating
1163            based on the the existing curve.
1164         */
1165
1166         _envelope->freeze ();
1167         _envelope->truncate_end (_length);
1168         _envelope->thaw ();
1169
1170         suspend_property_changes();
1171
1172         if (_left_of_split) {
1173                 set_default_fade_out ();
1174                 _left_of_split = false;
1175         } else if (_fade_out->back()->when > _length) {
1176                 _fade_out->extend_to (_length);
1177                 send_change (PropertyChange (Properties::fade_out));
1178         }
1179
1180         if (_fade_in->back()->when > _length) {
1181                 _fade_in->extend_to (_length);
1182                 send_change (PropertyChange (Properties::fade_in));
1183         }
1184
1185         resume_property_changes();
1186 }
1187
1188 void
1189 AudioRegion::recompute_at_start ()
1190 {
1191         /* as above, but the shift was from the front */
1192
1193         _envelope->truncate_start (_length);
1194
1195         suspend_property_changes();
1196
1197         if (_right_of_split) {
1198                 set_default_fade_in ();
1199                 _right_of_split = false;
1200         } else if (_fade_in->back()->when > _length) {
1201                 _fade_in->extend_to (_length);
1202                 send_change (PropertyChange (Properties::fade_in));
1203         }
1204
1205         if (_fade_out->back()->when > _length) {
1206                 _fade_out->extend_to (_length);
1207                 send_change (PropertyChange (Properties::fade_out));
1208         }
1209
1210         resume_property_changes();
1211 }
1212
1213 int
1214 AudioRegion::separate_by_channel (Session& /*session*/, vector<boost::shared_ptr<Region> >& v) const
1215 {
1216         SourceList srcs;
1217         string new_name;
1218         int n = 0;
1219
1220         if (_sources.size() < 2) {
1221                 return 0;
1222         }
1223
1224         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1225                 srcs.clear ();
1226                 srcs.push_back (*i);
1227
1228                 new_name = _name;
1229
1230                 if (_sources.size() == 2) {
1231                         if (n == 0) {
1232                                 new_name += "-L";
1233                         } else {
1234                                 new_name += "-R";
1235                         }
1236                 } else {
1237                         new_name += '-';
1238                         new_name += ('0' + n + 1);
1239                 }
1240
1241                 /* create a copy with just one source. prevent if from being thought of as
1242                    "whole file" even if it covers the entire source file(s).
1243                  */
1244
1245                 PropertyList plist;
1246
1247                 plist.add (Properties::start, _start.val());
1248                 plist.add (Properties::length, _length.val());
1249                 plist.add (Properties::name, new_name);
1250                 plist.add (Properties::layer, layer ());
1251
1252                 v.push_back(RegionFactory::create (srcs, plist));
1253                 v.back()->set_whole_file (false);
1254
1255                 ++n;
1256         }
1257
1258         return 0;
1259 }
1260
1261 framecnt_t
1262 AudioRegion::read_raw_internal (Sample* buf, framepos_t pos, framecnt_t cnt, int channel) const
1263 {
1264         return audio_source(channel)->read (buf, pos, cnt);
1265 }
1266
1267 void
1268 AudioRegion::set_scale_amplitude (gain_t g)
1269 {
1270         boost::shared_ptr<Playlist> pl (playlist());
1271
1272         _scale_amplitude = g;
1273
1274         /* tell the diskstream we're in */
1275
1276         if (pl) {
1277                 pl->ContentsChanged();
1278         }
1279
1280         /* tell everybody else */
1281
1282         send_change (PropertyChange (Properties::scale_amplitude));
1283 }
1284
1285 /** @return the maximum (linear) amplitude of the region, or a -ve
1286  *  number if the Progress object reports that the process was cancelled.
1287  */
1288 double
1289 AudioRegion::maximum_amplitude (Progress* p) const
1290 {
1291         framepos_t fpos = _start;
1292         framepos_t const fend = _start + _length;
1293         double maxamp = 0;
1294
1295         framecnt_t const blocksize = 64 * 1024;
1296         Sample buf[blocksize];
1297
1298         while (fpos < fend) {
1299
1300                 uint32_t n;
1301
1302                 framecnt_t const to_read = min (fend - fpos, blocksize);
1303
1304                 for (n = 0; n < n_channels(); ++n) {
1305
1306                         /* read it in */
1307
1308                         if (read_raw_internal (buf, fpos, to_read, n) != to_read) {
1309                                 return 0;
1310                         }
1311
1312                         maxamp = compute_peak (buf, to_read, maxamp);
1313                 }
1314
1315                 fpos += to_read;
1316                 if (p) {
1317                         p->set_progress (float (fpos - _start) / _length);
1318                         if (p->cancelled ()) {
1319                                 return -1;
1320                         }
1321                 }
1322         }
1323
1324         return maxamp;
1325 }
1326
1327 /** Normalize using a given maximum amplitude and target, so that region
1328  *  _scale_amplitude becomes target / max_amplitude.
1329  */
1330 void
1331 AudioRegion::normalize (float max_amplitude, float target_dB)
1332 {
1333         gain_t target = dB_to_coefficient (target_dB);
1334
1335         if (target == 1.0f) {
1336                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1337                    that we may have clipped.
1338                 */
1339                 target -= FLT_EPSILON;
1340         }
1341
1342         if (max_amplitude == 0.0f) {
1343                 /* don't even try */
1344                 return;
1345         }
1346
1347         if (max_amplitude == target) {
1348                 /* we can't do anything useful */
1349                 return;
1350         }
1351
1352         set_scale_amplitude (target / max_amplitude);
1353 }
1354
1355 void
1356 AudioRegion::fade_in_changed ()
1357 {
1358         send_change (PropertyChange (Properties::fade_in));
1359 }
1360
1361 void
1362 AudioRegion::fade_out_changed ()
1363 {
1364         send_change (PropertyChange (Properties::fade_out));
1365 }
1366
1367 void
1368 AudioRegion::envelope_changed ()
1369 {
1370         send_change (PropertyChange (Properties::envelope));
1371 }
1372
1373 void
1374 AudioRegion::suspend_fade_in ()
1375 {
1376         if (++_fade_in_suspended == 1) {
1377                 if (fade_in_is_default()) {
1378                         set_fade_in_active (false);
1379                 }
1380         }
1381 }
1382
1383 void
1384 AudioRegion::resume_fade_in ()
1385 {
1386         if (--_fade_in_suspended == 0 && _fade_in_suspended) {
1387                 set_fade_in_active (true);
1388         }
1389 }
1390
1391 void
1392 AudioRegion::suspend_fade_out ()
1393 {
1394         if (++_fade_out_suspended == 1) {
1395                 if (fade_out_is_default()) {
1396                         set_fade_out_active (false);
1397                 }
1398         }
1399 }
1400
1401 void
1402 AudioRegion::resume_fade_out ()
1403 {
1404         if (--_fade_out_suspended == 0 &&_fade_out_suspended) {
1405                 set_fade_out_active (true);
1406         }
1407 }
1408
1409 bool
1410 AudioRegion::speed_mismatch (float sr) const
1411 {
1412         if (_sources.empty()) {
1413                 /* impossible, but ... */
1414                 return false;
1415         }
1416
1417         float fsr = audio_source()->sample_rate();
1418
1419         return fsr != sr;
1420 }
1421
1422 void
1423 AudioRegion::source_offset_changed ()
1424 {
1425         /* XXX this fixes a crash that should not occur. It does occur
1426            becauses regions are not being deleted when a session
1427            is unloaded. That bug must be fixed.
1428         */
1429
1430         if (_sources.empty()) {
1431                 return;
1432         }
1433
1434         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1435
1436         if (afs && afs->destructive()) {
1437                 // set_start (source()->natural_position(), this);
1438                 set_position (source()->natural_position());
1439         }
1440 }
1441
1442 boost::shared_ptr<AudioSource>
1443 AudioRegion::audio_source (uint32_t n) const
1444 {
1445         // Guaranteed to succeed (use a static cast for speed?)
1446         return boost::dynamic_pointer_cast<AudioSource>(source(n));
1447 }
1448
1449 int
1450 AudioRegion::adjust_transients (frameoffset_t delta)
1451 {
1452         for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1453                 (*x) = (*x) + delta;
1454         }
1455
1456         send_change (PropertyChange (Properties::valid_transients));
1457
1458         return 0;
1459 }
1460
1461 int
1462 AudioRegion::update_transient (framepos_t old_position, framepos_t new_position)
1463 {
1464         for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1465                 if ((*x) == old_position) {
1466                         (*x) = new_position;
1467                         send_change (PropertyChange (Properties::valid_transients));
1468
1469                         break;
1470                 }
1471         }
1472
1473         return 0;
1474 }
1475
1476 void
1477 AudioRegion::add_transient (framepos_t where)
1478 {
1479         _transients.push_back(where);
1480         _valid_transients = true;
1481
1482         send_change (PropertyChange (Properties::valid_transients));
1483 }
1484
1485 void
1486 AudioRegion::remove_transient (framepos_t where)
1487 {
1488         _transients.remove(where);
1489         _valid_transients = true;
1490
1491         send_change (PropertyChange (Properties::valid_transients));
1492 }
1493
1494 int
1495 AudioRegion::set_transients (AnalysisFeatureList& results)
1496 {
1497         _transients.clear();
1498         _transients = results;
1499         _valid_transients = true;
1500
1501         send_change (PropertyChange (Properties::valid_transients));
1502
1503         return 0;
1504 }
1505
1506 int
1507 AudioRegion::get_transients (AnalysisFeatureList& results, bool force_new)
1508 {
1509         boost::shared_ptr<Playlist> pl = playlist();
1510
1511         if (!pl) {
1512                 return -1;
1513         }
1514
1515         if (_valid_transients && !force_new) {
1516                 results = _transients;
1517                 return 0;
1518         }
1519
1520         SourceList::iterator s;
1521
1522         for (s = _sources.begin() ; s != _sources.end(); ++s) {
1523                 if (!(*s)->has_been_analysed()) {
1524                         cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
1525                         break;
1526                 }
1527         }
1528
1529         if (s == _sources.end()) {
1530                 /* all sources are analyzed, merge data from each one */
1531
1532                 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1533
1534                         /* find the set of transients within the bounds of this region */
1535
1536                         AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
1537                                                                          (*s)->transients.end(),
1538                                                                          _start);
1539
1540                         AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
1541                                                                           (*s)->transients.end(),
1542                                                                           _start + _length);
1543
1544                         /* and add them */
1545
1546                         results.insert (results.end(), low, high);
1547                 }
1548
1549                 TransientDetector::cleanup_transients (results, pl->session().frame_rate(), 3.0);
1550
1551                 /* translate all transients to current position */
1552
1553                 for (AnalysisFeatureList::iterator x = results.begin(); x != results.end(); ++x) {
1554                         (*x) -= _start;
1555                         (*x) += _position;
1556                 }
1557
1558                 _transients = results;
1559                 _valid_transients = true;
1560
1561                 return 0;
1562         }
1563
1564         /* no existing/complete transient info */
1565
1566         static bool analyse_dialog_shown = false; /* global per instance of Ardour */
1567
1568         if (!Config->get_auto_analyse_audio()) {
1569                 if (!analyse_dialog_shown) {
1570                         pl->session().Dialog (_("\
1571 You have requested an operation that requires audio analysis.\n\n\
1572 You currently have \"auto-analyse-audio\" disabled, which means \
1573 that transient data must be generated every time it is required.\n\n\
1574 If you are doing work that will require transient data on a \
1575 regular basis, you should probably enable \"auto-analyse-audio\" \
1576 then quit ardour and restart.\n\n\
1577 This dialog will not display again.  But you may notice a slight delay \
1578 in this and future transient-detection operations.\n\
1579 "));
1580                         analyse_dialog_shown = true;
1581                 }
1582         }
1583
1584         TransientDetector t (pl->session().frame_rate());
1585         bool existing_results = !results.empty();
1586
1587         _transients.clear ();
1588         _valid_transients = false;
1589
1590         for (uint32_t i = 0; i < n_channels(); ++i) {
1591
1592                 AnalysisFeatureList these_results;
1593
1594                 t.reset ();
1595
1596                 if (t.run ("", this, i, these_results)) {
1597                         return -1;
1598                 }
1599
1600                 /* translate all transients to give absolute position */
1601
1602                 for (AnalysisFeatureList::iterator i = these_results.begin(); i != these_results.end(); ++i) {
1603                         (*i) += _position;
1604                 }
1605
1606                 /* merge */
1607
1608                 _transients.insert (_transients.end(), these_results.begin(), these_results.end());
1609         }
1610
1611         if (!results.empty()) {
1612                 if (existing_results) {
1613
1614                         /* merge our transients into the existing ones, then clean up
1615                            those.
1616                         */
1617
1618                         results.insert (results.end(), _transients.begin(), _transients.end());
1619                         TransientDetector::cleanup_transients (results, pl->session().frame_rate(), 3.0);
1620                 }
1621
1622                 /* make sure ours are clean too */
1623
1624                 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1625
1626         } else {
1627
1628                 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1629                 results = _transients;
1630         }
1631
1632         _valid_transients = true;
1633
1634         return 0;
1635 }
1636
1637 /** Find areas of `silence' within a region.
1638  *
1639  *  @param threshold Threshold below which signal is considered silence (as a sample value)
1640  *  @param min_length Minimum length of silent period to be reported.
1641  *  @return Silent intervals, measured relative to the region start in the source
1642  */
1643
1644 AudioIntervalResult
1645 AudioRegion::find_silence (Sample threshold, framecnt_t min_length, InterThreadInfo& itt) const
1646 {
1647         framecnt_t const block_size = 64 * 1024;
1648         boost::scoped_array<Sample> loudest (new Sample[block_size]);
1649         boost::scoped_array<Sample> buf (new Sample[block_size]);
1650
1651         framepos_t pos = _start;
1652         framepos_t const end = _start + _length - 1;
1653
1654         AudioIntervalResult silent_periods;
1655
1656         bool in_silence = false;
1657         frameoffset_t silence_start = 0;
1658
1659         while (pos < end && !itt.cancel) {
1660
1661                 /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
1662                 memset (loudest.get(), 0, sizeof (Sample) * block_size);
1663                 for (uint32_t n = 0; n < n_channels(); ++n) {
1664
1665                         read_raw_internal (buf.get(), pos, block_size, n);
1666                         for (framecnt_t i = 0; i < block_size; ++i) {
1667                                 loudest[i] = max (loudest[i], abs (buf[i]));
1668                         }
1669                 }
1670
1671                 /* now look for silence */
1672                 for (framecnt_t i = 0; i < block_size; ++i) {
1673                         bool const silence = abs (loudest[i]) < threshold;
1674                         if (silence && !in_silence) {
1675                                 /* non-silence to silence */
1676                                 in_silence = true;
1677                                 silence_start = pos + i;
1678                         } else if (!silence && in_silence) {
1679                                 /* silence to non-silence */
1680                                 in_silence = false;
1681                                 if (pos + i - 1 - silence_start >= min_length) {
1682                                         silent_periods.push_back (std::make_pair (silence_start, pos + i - 1));
1683                                 }
1684                         }
1685                 }
1686
1687                 pos += block_size;
1688                 itt.progress = (end-pos)/(double)_length;
1689         }
1690
1691         if (in_silence && end - 1 - silence_start >= min_length) {
1692                 /* last block was silent, so finish off the last period */
1693                 silent_periods.push_back (std::make_pair (silence_start, end));
1694         }
1695
1696         itt.done = true;
1697
1698         return silent_periods;
1699 }
1700
1701 Evoral::Range<framepos_t>
1702 AudioRegion::body_range () const
1703 {
1704         return Evoral::Range<framepos_t> (first_frame() + _fade_in->back()->when, last_frame() - _fade_out->back()->when);
1705 }
1706
1707 void
1708 AudioRegion::set_fade_in_is_xfade (bool yn)
1709 {
1710         _fade_in_is_xfade = yn;
1711 }
1712
1713 void
1714 AudioRegion::set_fade_out_is_xfade (bool yn)
1715 {
1716         _fade_out_is_xfade = yn;
1717 }
1718
1719 extern "C" {
1720
1721         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)
1722 {
1723         return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (framecnt_t) npeaks, (framepos_t) start, (framecnt_t) cnt, n_chan,samples_per_unit);
1724 }
1725
1726 uint32_t region_length_from_c (void *arg)
1727 {
1728
1729         return ((AudioRegion *) arg)->length();
1730 }
1731
1732 uint32_t sourcefile_length_from_c (void *arg, double zoom_factor)
1733 {
1734         return ( (AudioRegion *) arg)->audio_source()->available_peaks (zoom_factor) ;
1735 }
1736
1737 } /* extern "C" */