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