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