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