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