84709d7bb2d0bdc6df3e3b99c3d4532348f94b7a
[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 #include "ardour/progress.h"
49
50 #include "i18n.h"
51 #include <locale.h>
52
53 using namespace std;
54 using namespace ARDOUR;
55 using namespace PBD;
56
57 namespace ARDOUR {
58         namespace Properties {
59                 PBD::PropertyDescriptor<bool> envelope_active;
60                 PBD::PropertyDescriptor<bool> default_fade_in;
61                 PBD::PropertyDescriptor<bool> default_fade_out;
62                 PBD::PropertyDescriptor<bool> fade_in_active;
63                 PBD::PropertyDescriptor<bool> fade_out_active;
64                 PBD::PropertyDescriptor<float> scale_amplitude;
65         }
66 }
67
68 void
69 AudioRegion::make_property_quarks ()
70 {
71         Properties::envelope_active.property_id = g_quark_from_static_string (X_("envelope-active"));
72         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for envelope-active = %1\n",     Properties::envelope_active.property_id));
73         Properties::default_fade_in.property_id = g_quark_from_static_string (X_("default-fade-in"));
74         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for default-fade-in = %1\n",     Properties::default_fade_in.property_id));
75         Properties::default_fade_out.property_id = g_quark_from_static_string (X_("default-fade-out"));
76         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for default-fade-out = %1\n",    Properties::default_fade_out.property_id));
77         Properties::fade_in_active.property_id = g_quark_from_static_string (X_("fade-in-active"));
78         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-in-active = %1\n",      Properties::fade_in_active.property_id));
79         Properties::fade_out_active.property_id = g_quark_from_static_string (X_("fade-out-active"));
80         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-out-active = %1\n",     Properties::fade_out_active.property_id));
81         Properties::scale_amplitude.property_id = g_quark_from_static_string (X_("scale-amplitude"));
82         DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for scale-amplitude = %1\n",     Properties::scale_amplitude.property_id));
83 }
84
85 void
86 AudioRegion::register_properties ()
87 {
88         /* no need to register parent class properties */
89
90         add_property (_envelope_active);
91         add_property (_default_fade_in);
92         add_property (_default_fade_out);
93         add_property (_fade_in_active);
94         add_property (_fade_out_active);
95         add_property (_scale_amplitude);
96 }
97
98 #define AUDIOREGION_STATE_DEFAULT \
99         _envelope_active (Properties::envelope_active, false) \
100         , _default_fade_in (Properties::default_fade_in, true) \
101         , _default_fade_out (Properties::default_fade_out, true) \
102         , _fade_in_active (Properties::fade_in_active, true) \
103         , _fade_out_active (Properties::fade_out_active, true) \
104         , _scale_amplitude (Properties::scale_amplitude, 1.0)
105         
106 #define AUDIOREGION_COPY_STATE(other) \
107         _envelope_active (Properties::envelope_active, other->_envelope_active) \
108         , _default_fade_in (Properties::default_fade_in, other->_default_fade_in) \
109         , _default_fade_out (Properties::default_fade_out, other->_default_fade_out) \
110         , _fade_in_active (Properties::fade_in_active, other->_fade_in_active) \
111         , _fade_out_active (Properties::fade_out_active, other->_fade_out_active) \
112         , _scale_amplitude (Properties::scale_amplitude, other->_scale_amplitude)
113 /* a Session will reset these to its chosen defaults by calling AudioRegion::set_default_fade() */
114
115 void
116 AudioRegion::init ()
117 {
118         register_properties ();
119
120         suspend_property_changes();
121         set_default_fades ();
122         set_default_envelope ();
123         resume_property_changes();
124
125         listen_to_my_curves ();
126         connect_to_analysis_changed ();
127         connect_to_header_position_offset_changed ();
128 }
129
130 /** Constructor for use by derived types only */
131 AudioRegion::AudioRegion (Session& s, framepos_t start, framecnt_t len, std::string name)
132         : Region (s, start, len, name, DataType::AUDIO)
133         , AUDIOREGION_STATE_DEFAULT
134         , _automatable (s)
135         , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
136         , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
137         , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
138         , _fade_in_suspended (0)
139         , _fade_out_suspended (0)
140 {
141         init ();
142         assert (_sources.size() == _master_sources.size());
143 }
144
145 /** Basic AudioRegion constructor */
146 AudioRegion::AudioRegion (const SourceList& srcs)
147         : Region (srcs)
148         , AUDIOREGION_STATE_DEFAULT
149         , _automatable(srcs[0]->session())
150         , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
151         , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
152         , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
153         , _fade_in_suspended (0)
154         , _fade_out_suspended (0)
155 {
156         init ();
157         assert (_sources.size() == _master_sources.size());
158 }
159
160 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, framecnt_t offset, bool offset_relative)
161         : Region (other, offset, offset_relative)
162         , AUDIOREGION_COPY_STATE (other)
163         , _automatable (other->session())
164         , _fade_in (new AutomationList (*other->_fade_in))
165         , _fade_out (new AutomationList (*other->_fade_out))
166           /* As far as I can see, the _envelope's times are relative to region position, and have nothing
167              to do with sources (and hence _start).  So when we copy the envelope, we just use the supplied offset.
168           */
169         , _envelope (new AutomationList (*other->_envelope, offset, other->_length))
170         , _fade_in_suspended (0)
171         , _fade_out_suspended (0)
172 {
173         /* don't use init here, because we got fade in/out from the other region
174         */
175         register_properties ();
176         listen_to_my_curves ();
177         connect_to_analysis_changed ();
178         connect_to_header_position_offset_changed ();
179
180         assert(_type == DataType::AUDIO);
181         assert (_sources.size() == _master_sources.size());
182 }
183
184 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, const SourceList& srcs)
185         : Region (boost::static_pointer_cast<const Region>(other), srcs)
186         , AUDIOREGION_COPY_STATE (other)
187         , _automatable (other->session())
188         , _fade_in (new AutomationList (*other->_fade_in))
189         , _fade_out (new AutomationList (*other->_fade_out))
190         , _envelope (new AutomationList (*other->_envelope))
191         , _fade_in_suspended (0)
192         , _fade_out_suspended (0)
193 {
194         /* make-a-sort-of-copy-with-different-sources constructor (used by audio filter) */
195
196         register_properties ();
197
198         listen_to_my_curves ();
199         connect_to_analysis_changed ();
200         connect_to_header_position_offset_changed ();
201
202         assert (_sources.size() == _master_sources.size());
203 }
204
205 AudioRegion::AudioRegion (SourceList& srcs)
206         : Region (srcs)
207         , AUDIOREGION_STATE_DEFAULT
208         , _automatable(srcs[0]->session())
209         , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
210         , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
211         , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
212         , _fade_in_suspended (0)
213         , _fade_out_suspended (0)
214 {
215         init ();
216
217         assert(_type == DataType::AUDIO);
218         assert (_sources.size() == _master_sources.size());
219 }
220
221 AudioRegion::~AudioRegion ()
222 {
223 }
224
225 void
226 AudioRegion::post_set ()
227 {
228         if (!_sync_marked) {
229                 _sync_position = _start;
230         }
231
232         /* return to default fades if the existing ones are too long */
233
234         if (_left_of_split) {
235                 if (_fade_in->back()->when >= _length) {
236                         set_default_fade_in ();
237                 } 
238                 set_default_fade_out ();
239                 _left_of_split = false;
240         }
241
242         if (_right_of_split) {
243                 if (_fade_out->back()->when >= _length) {
244                         set_default_fade_out ();
245                 } 
246
247                 set_default_fade_in ();
248                 _right_of_split = false;
249         }
250
251         /* If _length changed, adjust our gain envelope accordingly */
252         _envelope->truncate_end (_length);
253 }
254
255 void
256 AudioRegion::connect_to_analysis_changed ()
257 {
258         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
259                 (*i)->AnalysisChanged.connect_same_thread (*this, boost::bind (&AudioRegion::invalidate_transients, this));
260         }
261 }
262
263 void
264 AudioRegion::connect_to_header_position_offset_changed ()
265 {
266         set<boost::shared_ptr<Source> > unique_srcs;
267
268         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
269
270                 /* connect only once to HeaderPositionOffsetChanged, even if sources are replicated
271                  */
272
273                 if (unique_srcs.find (*i) == unique_srcs.end ()) {
274                         unique_srcs.insert (*i);
275                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
276                         if (afs) {
277                                 afs->HeaderPositionOffsetChanged.connect_same_thread (*this, boost::bind (&AudioRegion::source_offset_changed, this));
278                         }
279                 }
280         }
281 }
282
283 void
284 AudioRegion::listen_to_my_curves ()
285 {
286         _envelope->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::envelope_changed, this));
287         _fade_in->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::fade_in_changed, this));
288         _fade_out->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::fade_out_changed, this));
289 }
290
291 void
292 AudioRegion::set_envelope_active (bool yn)
293 {
294         if (envelope_active() != yn) {
295                 _envelope_active = yn;
296                 send_change (PropertyChange (Properties::envelope_active));
297         }
298 }
299
300 ARDOUR::framecnt_t
301 AudioRegion::read_peaks (PeakData *buf, framecnt_t npeaks, framecnt_t offset, framecnt_t cnt, uint32_t chan_n, double samples_per_unit) const
302 {
303         if (chan_n >= _sources.size()) {
304                 return 0;
305         }
306
307         if (audio_source(chan_n)->read_peaks (buf, npeaks, offset, cnt, samples_per_unit)) {
308                 return 0;
309         } else {
310                 if (_scale_amplitude != 1.0f) {
311                         for (framecnt_t n = 0; n < npeaks; ++n) {
312                                 buf[n].max *= _scale_amplitude;
313                                 buf[n].min *= _scale_amplitude;
314                         }
315                 }
316                 return cnt;
317         }
318 }
319
320 framecnt_t
321 AudioRegion::read (Sample* buf, framepos_t timeline_position, framecnt_t cnt, int channel) const
322 {
323         /* raw read, no fades, no gain, nada */
324         return _read_at (_sources, _length, buf, 0, 0, _position + timeline_position, cnt, channel, 0, 0, ReadOps (0));
325 }
326
327 framecnt_t
328 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
329                       framepos_t file_position, framecnt_t cnt, uint32_t chan_n,
330                       framecnt_t read_frames, framecnt_t skip_frames) const
331 {
332         /* regular diskstream/butler read complete with fades etc */
333         return _read_at (_sources, _length, buf, mixdown_buffer, gain_buffer,
334                         file_position, cnt, chan_n, read_frames, skip_frames, ReadOps (~0));
335 }
336
337 framecnt_t
338 AudioRegion::master_read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
339                              framepos_t position, framecnt_t cnt, uint32_t chan_n) const
340 {
341         /* do not read gain/scaling/fades and do not count this disk i/o in statistics */
342
343         return _read_at (_master_sources, _master_sources.front()->length(_master_sources.front()->timeline_position()),
344                          buf, mixdown_buffer, gain_buffer, position, cnt, chan_n, 0, 0, ReadOps (0));
345 }
346
347 framecnt_t
348 AudioRegion::_read_at (const SourceList& /*srcs*/, framecnt_t limit,
349                        Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
350                        framepos_t position, 
351                        framecnt_t cnt,
352                        uint32_t chan_n,
353                        framecnt_t /*read_frames*/,
354                        framecnt_t /*skip_frames*/,
355                        ReadOps rops) const
356 {
357         frameoffset_t internal_offset;
358         frameoffset_t buf_offset;
359         framecnt_t to_read;
360         bool raw = (rops == ReadOpsNone);
361
362         if (n_channels() == 0) {
363                 return 0;
364         }
365
366         if (muted() && !raw) {
367                 return 0; /* read nothing */
368         }
369
370         /* precondition: caller has verified that we cover the desired section */
371
372         if (position < _position) {
373                 internal_offset = 0;
374                 buf_offset = _position - position;
375                 cnt -= buf_offset;
376         } else {
377                 internal_offset = position - _position;
378                 buf_offset = 0;
379         }
380
381         if (internal_offset >= limit) {
382                 return 0; /* read nothing */
383         }
384
385         if ((to_read = min (cnt, limit - internal_offset)) == 0) {
386                 return 0; /* read nothing */
387         }
388
389         if (opaque() || raw) {
390                 /* overwrite whatever is there */
391                 mixdown_buffer = buf + buf_offset;
392         } else {
393                 mixdown_buffer += buf_offset;
394         }
395
396         if (rops & ReadOpsCount) {
397                 _read_data_count = 0;
398         }
399
400         if (chan_n < n_channels()) {
401
402                 boost::shared_ptr<AudioSource> src = audio_source(chan_n);
403                 if (src->read (mixdown_buffer, _start + internal_offset, to_read) != to_read) {
404                         return 0; /* "read nothing" */
405                 }
406
407                 if (rops & ReadOpsCount) {
408                         _read_data_count += src->read_data_count();
409                 }
410
411         } else {
412
413                 /* track is N-channel, this region has less channels; silence the ones
414                    we don't have.
415                 */
416
417                 if (Config->get_replicate_missing_region_channels()) {
418                        /* track is N-channel, this region has less channels, so use a relevant channel
419                         */
420                         
421                         uint32_t channel = n_channels() % chan_n;
422                         boost::shared_ptr<AudioSource> src = audio_source (channel);
423
424                         if (src->read (mixdown_buffer, _start + internal_offset, to_read) != to_read) {
425                                 return 0; /* "read nothing" */
426                         }
427
428                         /* adjust read data count appropriately since this was a duplicate read */
429                         src->dec_read_data_count (to_read);
430                 } else {
431                         memset (mixdown_buffer, 0, sizeof (Sample) * cnt);
432                 }
433         }
434
435         if (rops & ReadOpsFades) {
436
437                 /* fade in */
438
439                 if (_fade_in_active && _session.config.get_use_region_fades()) {
440
441                         framecnt_t fade_in_length = (framecnt_t) _fade_in->back()->when;
442
443                         /* see if this read is within the fade in */
444
445                         if (internal_offset < fade_in_length) {
446
447                                 framecnt_t fi_limit;
448
449                                 fi_limit = min (to_read, fade_in_length - internal_offset);
450
451                                 _fade_in->curve().get_vector (internal_offset, internal_offset+fi_limit, gain_buffer, fi_limit);
452
453                                 for (framecnt_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                         framecnt_t fade_out_length = (framecnt_t) _fade_out->back()->when;
483                         framecnt_t fade_interval_start = max(internal_offset, limit-fade_out_length);
484                         framecnt_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                                 framecnt_t fo_limit = fade_interval_end - fade_interval_start;
490                                 framecnt_t curve_offset = fade_interval_start - (limit-fade_out_length);
491                                 framecnt_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 (framecnt_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 (framecnt_t n = 0; n < to_read; ++n) {
510                                 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
511                         }
512                 } else {
513                         for (framecnt_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 (framecnt_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 (framecnt_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, (framecnt_t) _fade_in->back()->when);
716 }
717
718 void
719 AudioRegion::set_fade_out_shape (FadeShape shape)
720 {
721         set_fade_out (shape, (framecnt_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 framecnt_t blocksize = 4096;
1066 //      framecnt_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 (framecnt_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, or a -ve
1146  *  number if the Progress object reports that the process was cancelled.
1147  */
1148 double
1149 AudioRegion::maximum_amplitude (Progress* p) const
1150 {
1151         framepos_t fpos = _start;
1152         framepos_t const fend = _start + _length;
1153         double maxamp = 0;
1154
1155         framecnt_t const blocksize = 64 * 1024;
1156         Sample buf[blocksize];
1157         
1158         while (fpos < fend) {
1159
1160                 uint32_t n;
1161
1162                 framecnt_t const to_read = min (fend - fpos, blocksize);
1163
1164                 for (n = 0; n < n_channels(); ++n) {
1165
1166                         /* read it in */
1167
1168                         if (read_raw_internal (buf, fpos, to_read, 0) != to_read) {
1169                                 return 0;
1170                         }
1171
1172                         maxamp = compute_peak (buf, to_read, maxamp);
1173                 }
1174
1175                 fpos += to_read;
1176                 if (p) {
1177                         p->set_progress (float (fpos - _start) / _length);
1178                         if (p->cancelled ()) {
1179                                 return -1;
1180                         }
1181                 }
1182         }
1183
1184         return maxamp;
1185 }
1186
1187 /** Normalize using a given maximum amplitude and target, so that region
1188  *  _scale_amplitude becomes target / max_amplitude.
1189  */
1190 void
1191 AudioRegion::normalize (float max_amplitude, float target_dB)
1192 {
1193         gain_t target = dB_to_coefficient (target_dB);
1194
1195         if (target == 1.0f) {
1196                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1197                    that we may have clipped.
1198                 */
1199                 target -= FLT_EPSILON;
1200         }
1201
1202         if (max_amplitude == 0.0f) {
1203                 /* don't even try */
1204                 return;
1205         }
1206
1207         if (max_amplitude == target) {
1208                 /* we can't do anything useful */
1209                 return;
1210         }
1211
1212         set_scale_amplitude (target / max_amplitude);
1213 }
1214
1215 void
1216 AudioRegion::fade_in_changed ()
1217 {
1218         send_change (PropertyChange (Properties::fade_in));
1219 }
1220
1221 void
1222 AudioRegion::fade_out_changed ()
1223 {
1224         send_change (PropertyChange (Properties::fade_out));
1225 }
1226
1227 void
1228 AudioRegion::envelope_changed ()
1229 {
1230         send_change (PropertyChange (Properties::envelope));
1231 }
1232
1233 void
1234 AudioRegion::suspend_fade_in ()
1235 {
1236         if (++_fade_in_suspended == 1) {
1237                 if (fade_in_is_default()) {
1238                         set_fade_in_active (false);
1239                 }
1240         }
1241 }
1242
1243 void
1244 AudioRegion::resume_fade_in ()
1245 {
1246         if (--_fade_in_suspended == 0 && _fade_in_suspended) {
1247                 set_fade_in_active (true);
1248         }
1249 }
1250
1251 void
1252 AudioRegion::suspend_fade_out ()
1253 {
1254         if (++_fade_out_suspended == 1) {
1255                 if (fade_out_is_default()) {
1256                         set_fade_out_active (false);
1257                 }
1258         }
1259 }
1260
1261 void
1262 AudioRegion::resume_fade_out ()
1263 {
1264         if (--_fade_out_suspended == 0 &&_fade_out_suspended) {
1265                 set_fade_out_active (true);
1266         }
1267 }
1268
1269 bool
1270 AudioRegion::speed_mismatch (float sr) const
1271 {
1272         if (_sources.empty()) {
1273                 /* impossible, but ... */
1274                 return false;
1275         }
1276
1277         float fsr = audio_source()->sample_rate();
1278
1279         return fsr != sr;
1280 }
1281
1282 void
1283 AudioRegion::source_offset_changed ()
1284 {
1285         /* XXX this fixes a crash that should not occur. It does occur
1286            becauses regions are not being deleted when a session
1287            is unloaded. That bug must be fixed.
1288         */
1289
1290         if (_sources.empty()) {
1291                 return;
1292         }
1293
1294         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1295
1296         if (afs && afs->destructive()) {
1297                 // set_start (source()->natural_position(), this);
1298                 set_position (source()->natural_position(), this);
1299         }
1300 }
1301
1302 boost::shared_ptr<AudioSource>
1303 AudioRegion::audio_source (uint32_t n) const
1304 {
1305         // Guaranteed to succeed (use a static cast for speed?)
1306         return boost::dynamic_pointer_cast<AudioSource>(source(n));
1307 }
1308
1309 int 
1310 AudioRegion::adjust_transients (frameoffset_t delta)
1311 {
1312         for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1313                 (*x) = (*x) + delta;
1314         }
1315         
1316         send_change (PropertyChange (Properties::valid_transients));
1317         
1318         return 0;  
1319
1320
1321 int
1322 AudioRegion::update_transient (framepos_t old_position, framepos_t new_position)
1323 {
1324         for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1325                 if ((*x) == old_position) {
1326                         (*x) = new_position;
1327                         send_change (PropertyChange (Properties::valid_transients));
1328                         
1329                         break;
1330                 }
1331         }
1332         
1333         return 0;
1334 }
1335
1336 void
1337 AudioRegion::add_transient (framepos_t where)
1338 {
1339         _transients.push_back(where);
1340         _valid_transients = true;
1341         
1342         send_change (PropertyChange (Properties::valid_transients));
1343 }
1344
1345 void
1346 AudioRegion::remove_transient (framepos_t where)
1347 {
1348         _transients.remove(where);
1349         _valid_transients = true;
1350         
1351         send_change (PropertyChange (Properties::valid_transients));
1352 }
1353
1354 int
1355 AudioRegion::set_transients (AnalysisFeatureList& results)
1356 {
1357         _transients.clear();
1358         _transients = results;
1359         _valid_transients = true;
1360         
1361         send_change (PropertyChange (Properties::valid_transients));
1362         
1363         return 0;
1364 }
1365
1366 int
1367 AudioRegion::get_transients (AnalysisFeatureList& results, bool force_new)
1368 {
1369         boost::shared_ptr<Playlist> pl = playlist();
1370
1371         if (!pl) {
1372                 return -1;
1373         }
1374
1375         if (_valid_transients && !force_new) {
1376                 results = _transients;
1377                 return 0;
1378         }
1379
1380         SourceList::iterator s;
1381
1382         for (s = _sources.begin() ; s != _sources.end(); ++s) {
1383                 if (!(*s)->has_been_analysed()) {
1384                         cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
1385                         break;
1386                 }
1387         }
1388
1389         if (s == _sources.end()) {
1390                 /* all sources are analyzed, merge data from each one */
1391
1392                 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1393
1394                         /* find the set of transients within the bounds of this region */
1395
1396                         AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
1397                                                                          (*s)->transients.end(),
1398                                                                          _start);
1399
1400                         AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
1401                                                                           (*s)->transients.end(),
1402                                                                           _start + _length);
1403
1404                         /* and add them */
1405
1406                         results.insert (results.end(), low, high);
1407                 }
1408
1409                 TransientDetector::cleanup_transients (results, pl->session().frame_rate(), 3.0);
1410
1411                 /* translate all transients to current position */
1412
1413                 for (AnalysisFeatureList::iterator x = results.begin(); x != results.end(); ++x) {
1414                         (*x) -= _start;
1415                         (*x) += _position;
1416                 }
1417
1418                 _transients = results;
1419                 _valid_transients = true;
1420
1421                 return 0;
1422         }
1423
1424         /* no existing/complete transient info */
1425
1426         static bool analyse_dialog_shown = false; /* global per instance of Ardour */
1427
1428         if (!Config->get_auto_analyse_audio()) {
1429                 if (!analyse_dialog_shown) {
1430                         pl->session().Dialog (_("\
1431 You have requested an operation that requires audio analysis.\n\n\
1432 You currently have \"auto-analyse-audio\" disabled, which means \
1433 that transient data must be generated every time it is required.\n\n\
1434 If you are doing work that will require transient data on a \
1435 regular basis, you should probably enable \"auto-analyse-audio\" \
1436 then quit ardour and restart.\n\n\
1437 This dialog will not display again.  But you may notice a slight delay \
1438 in this and future transient-detection operations.\n\
1439 "));
1440                         analyse_dialog_shown = true;
1441                 }
1442         }
1443
1444         TransientDetector t (pl->session().frame_rate());
1445         bool existing_results = !results.empty();
1446
1447         _transients.clear ();
1448         _valid_transients = false;
1449
1450         for (uint32_t i = 0; i < n_channels(); ++i) {
1451
1452                 AnalysisFeatureList these_results;
1453
1454                 t.reset ();
1455
1456                 if (t.run ("", this, i, these_results)) {
1457                         return -1;
1458                 }
1459
1460                 /* translate all transients to give absolute position */
1461
1462                 for (AnalysisFeatureList::iterator i = these_results.begin(); i != these_results.end(); ++i) {
1463                         (*i) += _position;
1464                 }
1465
1466                 /* merge */
1467
1468                 _transients.insert (_transients.end(), these_results.begin(), these_results.end());
1469         }
1470
1471         if (!results.empty()) {
1472                 if (existing_results) {
1473
1474                         /* merge our transients into the existing ones, then clean up
1475                            those.
1476                         */
1477
1478                         results.insert (results.end(), _transients.begin(), _transients.end());
1479                         TransientDetector::cleanup_transients (results, pl->session().frame_rate(), 3.0);
1480                 }
1481
1482                 /* make sure ours are clean too */
1483
1484                 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1485
1486         } else {
1487
1488                 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1489                 results = _transients;
1490         }
1491
1492         _valid_transients = true;
1493
1494         return 0;
1495 }
1496
1497 /** Find areas of `silence' within a region.
1498  *
1499  *  @param threshold Threshold below which signal is considered silence (as a sample value)
1500  *  @param min_length Minimum length of silent period to be reported.
1501  *  @return Silent intervals
1502  */
1503
1504 AudioIntervalResult
1505 AudioRegion::find_silence (Sample threshold, framecnt_t min_length, InterThreadInfo& itt) const
1506 {
1507         framecnt_t const block_size = 64 * 1024;
1508         Sample loudest[block_size];
1509         Sample buf[block_size];
1510
1511         framepos_t pos = _start;
1512         framepos_t const end = _start + _length - 1;
1513         
1514         AudioIntervalResult silent_periods;
1515
1516         bool in_silence = false;
1517         frameoffset_t silence_start = 0;
1518         bool silence;
1519
1520         while (pos < end && !itt.cancel) {
1521
1522                 /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
1523                 memset (loudest, 0, sizeof (Sample) * block_size);
1524                 for (uint32_t n = 0; n < n_channels(); ++n) {
1525
1526                         read_raw_internal (buf, pos, block_size, n);
1527                         for (framecnt_t i = 0; i < block_size; ++i) {
1528                                 loudest[i] = max (loudest[i], abs (buf[i]));
1529                         }
1530                 }
1531
1532                 /* now look for silence */
1533                 for (framecnt_t i = 0; i < block_size; ++i) {
1534                         silence = abs (loudest[i]) < threshold;
1535                         if (silence && !in_silence) {
1536                                 /* non-silence to silence */
1537                                 in_silence = true;
1538                                 silence_start = pos + i;
1539                         } else if (!silence && in_silence) {
1540                                 /* silence to non-silence */
1541                                 in_silence = false;
1542                                 if (pos + i - 1 - silence_start >= min_length) {
1543                                         silent_periods.push_back (std::make_pair (silence_start, pos + i - 1));
1544                                 }
1545                         }
1546                 }
1547
1548                 pos += block_size;
1549                 itt.progress = (end-pos)/(double)_length;
1550         }
1551
1552         if (in_silence && end - 1 - silence_start >= min_length) {
1553                 /* last block was silent, so finish off the last period */
1554                 silent_periods.push_back (std::make_pair (silence_start, end));
1555         }
1556
1557         itt.done = true;
1558
1559         return silent_periods;
1560 }
1561
1562
1563
1564 extern "C" {
1565
1566         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)
1567 {
1568         return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (framecnt_t) npeaks, (framepos_t) start, (framecnt_t) cnt, n_chan,samples_per_unit);
1569 }
1570
1571 uint32_t region_length_from_c (void *arg)
1572 {
1573
1574         return ((AudioRegion *) arg)->length();
1575 }
1576
1577 uint32_t sourcefile_length_from_c (void *arg, double zoom_factor)
1578 {
1579         return ( (AudioRegion *) arg)->audio_source()->available_peaks (zoom_factor) ;
1580 }
1581
1582 } /* extern "C" */