fix SVN merge SNAFU causing double deletion
[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     $Id$
19 */
20
21 #include <cmath>
22 #include <climits>
23 #include <cfloat>
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
36 #include <ardour/audioregion.h>
37 #include <ardour/session.h>
38 #include <ardour/gain.h>
39 #include <ardour/dB.h>
40 #include <ardour/playlist.h>
41 #include <ardour/audiofilter.h>
42 #include <ardour/audiofilesource.h>
43 #include <ardour/destructive_filesource.h>
44
45 #include "i18n.h"
46 #include <locale.h>
47
48 using namespace std;
49 using namespace ARDOUR;
50
51 /* a Session will reset these to its chosen defaults by calling AudioRegion::set_default_fade() */
52
53 Change AudioRegion::FadeInChanged         = ARDOUR::new_change();
54 Change AudioRegion::FadeOutChanged        = ARDOUR::new_change();
55 Change AudioRegion::FadeInActiveChanged   = ARDOUR::new_change();
56 Change AudioRegion::FadeOutActiveChanged  = ARDOUR::new_change();
57 Change AudioRegion::EnvelopeActiveChanged = ARDOUR::new_change();
58 Change AudioRegion::ScaleAmplitudeChanged = ARDOUR::new_change();
59 Change AudioRegion::EnvelopeChanged       = ARDOUR::new_change();
60
61 AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, nframes_t start, nframes_t length)
62         : Region (start, length, PBD::basename_nosuffix(src->name()), 0,  Region::Flag(Region::DefaultFlags|Region::External)),
63           _fade_in (0.0, 2.0, 1.0, false),
64           _fade_out (0.0, 2.0, 1.0, false),
65           _envelope (0.0, 2.0, 1.0, false)
66 {
67         /* basic AudioRegion constructor */
68
69         sources.push_back (src);
70         master_sources.push_back (src);
71         src->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
72
73         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (src);
74         if (afs) {
75                 afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
76         }
77
78         _scale_amplitude = 1.0;
79
80         set_default_fades ();
81         set_default_envelope ();
82
83         _envelope.StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
84 }
85
86 AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, nframes_t start, nframes_t length, const string& name, layer_t layer, Flag flags)
87         : Region (start, length, name, layer, flags),
88           _fade_in (0.0, 2.0, 1.0, false),
89           _fade_out (0.0, 2.0, 1.0, false),
90           _envelope (0.0, 2.0, 1.0, false)
91 {
92         /* basic AudioRegion constructor */
93
94         sources.push_back (src);
95         master_sources.push_back (src);
96         src->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
97
98         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (src);
99         if (afs) {
100                 afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
101         }
102
103         _scale_amplitude = 1.0;
104
105         set_default_fades ();
106         set_default_envelope ();
107
108         _envelope.StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
109 }
110
111 AudioRegion::AudioRegion (SourceList& srcs, nframes_t start, nframes_t length, const string& name, layer_t layer, Flag flags)
112         : Region (start, length, name, layer, flags),
113           _fade_in (0.0, 2.0, 1.0, false),
114           _fade_out (0.0, 2.0, 1.0, false),
115           _envelope (0.0, 2.0, 1.0, false)
116 {
117         /* basic AudioRegion constructor */
118
119         for (SourceList::iterator i=srcs.begin(); i != srcs.end(); ++i) {
120                 sources.push_back (*i);
121                 master_sources.push_back (*i);
122                 (*i)->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
123                 
124                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> ((*i));
125                 if (afs) {
126                         afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
127                 }
128         }
129
130         _scale_amplitude = 1.0;
131
132         set_default_fades ();
133         set_default_envelope ();
134
135         _envelope.StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
136 }
137
138
139 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, nframes_t offset, nframes_t length, const string& name, layer_t layer, Flag flags)
140         : Region (other, offset, length, name, layer, flags),
141           _fade_in (other->_fade_in),
142           _fade_out (other->_fade_out),
143           _envelope (other->_envelope, (double) offset, (double) offset + length) 
144 {
145         /* create a new AudioRegion, that is part of an existing one */
146         
147         set<boost::shared_ptr<AudioSource> > unique_srcs;
148
149         for (SourceList::const_iterator i= other->sources.begin(); i != other->sources.end(); ++i) {
150                 sources.push_back (*i);
151                 (*i)->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
152
153                 pair<set<boost::shared_ptr<AudioSource> >::iterator,bool> result;
154
155                 result = unique_srcs.insert (*i);
156
157                 if (result.second) {
158                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
159                         if (afs) {
160                                 afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
161                         }
162                 }
163         }
164
165         for (SourceList::const_iterator i = other->master_sources.begin(); i != other->master_sources.end(); ++i) {
166                 if (unique_srcs.find (*i) == unique_srcs.end()) {
167                         (*i)->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
168                 }
169                 master_sources.push_back (*i);
170         }
171
172         /* return to default fades if the existing ones are too long */
173         _fade_in_disabled = 0;
174         _fade_out_disabled = 0;
175
176
177         if (_flags & LeftOfSplit) {
178                 if (_fade_in.back()->when >= _length) {
179                         set_default_fade_in ();
180                 } else {
181                         _fade_in_disabled = other->_fade_in_disabled;
182                 }
183                 set_default_fade_out ();
184                 _flags = Flag (_flags & ~Region::LeftOfSplit);
185         }
186
187         if (_flags & RightOfSplit) {
188                 if (_fade_out.back()->when >= _length) {
189                         set_default_fade_out ();
190                 } else {
191                         _fade_out_disabled = other->_fade_out_disabled;
192                 }
193                 set_default_fade_in ();
194                 _flags = Flag (_flags & ~Region::RightOfSplit);
195         }
196
197         _scale_amplitude = other->_scale_amplitude;
198
199         _envelope.StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
200 }
201
202 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other)
203         : Region (other),
204           _fade_in (other->_fade_in),
205           _fade_out (other->_fade_out),
206           _envelope (other->_envelope) 
207 {
208         /* Pure copy constructor */
209
210         set<boost::shared_ptr<AudioSource> > unique_srcs;
211
212         for (SourceList::const_iterator i = other->sources.begin(); i != other->sources.end(); ++i) {
213                 sources.push_back (*i);
214                 (*i)->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
215                 pair<set<boost::shared_ptr<AudioSource> >::iterator,bool> result;
216
217                 result = unique_srcs.insert (*i);
218
219                 if (result.second) {
220                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
221                         if (afs) {
222                                 afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
223                         }
224                 }
225         }
226
227         for (SourceList::const_iterator i = other->master_sources.begin(); i != other->master_sources.end(); ++i) {
228                 master_sources.push_back (*i);
229                 if (unique_srcs.find (*i) == unique_srcs.end()) {
230                         (*i)->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
231                 }
232         }
233
234         _scale_amplitude = other->_scale_amplitude;
235         _envelope = other->_envelope;
236
237         _fade_in_disabled = 0;
238         _fade_out_disabled = 0;
239         
240         _envelope.StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
241 }
242
243 AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, const XMLNode& node)
244         : Region (node),
245           _fade_in (0.0, 2.0, 1.0, false),
246           _fade_out (0.0, 2.0, 1.0, false),
247           _envelope (0.0, 2.0, 1.0, false)
248 {
249         sources.push_back (src);
250         master_sources.push_back (src);
251         src->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
252
253         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (src);
254         if (afs) {
255                 afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
256         }
257
258         set_default_fades ();
259
260         if (set_state (node)) {
261                 throw failed_constructor();
262         }
263
264         _envelope.StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
265 }
266
267 AudioRegion::AudioRegion (SourceList& srcs, const XMLNode& node)
268         : Region (node),
269           _fade_in (0.0, 2.0, 1.0, false),
270           _fade_out (0.0, 2.0, 1.0, false),
271           _envelope (0.0, 2.0, 1.0, false)
272 {
273         set<boost::shared_ptr<AudioSource> > unique_srcs;
274
275         for (SourceList::iterator i=srcs.begin(); i != srcs.end(); ++i) {
276                 sources.push_back (*i);
277                 (*i)->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
278                 pair<set<boost::shared_ptr<AudioSource> >::iterator,bool> result;
279
280                 result = unique_srcs.insert (*i);
281
282                 if (result.second) {
283                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
284                         if (afs) {
285                                 afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
286                         }
287                 }
288         }
289
290         for (SourceList::iterator i = srcs.begin(); i != srcs.end(); ++i) {
291                 master_sources.push_back (*i);
292                 if (unique_srcs.find (*i) == unique_srcs.end()) {
293                         (*i)->GoingAway.connect (mem_fun (*this, &AudioRegion::source_deleted));
294                 }
295         }
296
297         set_default_fades ();
298         _scale_amplitude = 1.0;
299
300         if (set_state (node)) {
301                 throw failed_constructor();
302         }
303
304         _envelope.StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
305 }
306
307 AudioRegion::~AudioRegion ()
308 {
309         notify_callbacks ();
310         GoingAway (); /* EMIT SIGNAL */
311 }
312
313 bool
314 AudioRegion::verify_length (nframes_t len)
315 {
316         if (boost::dynamic_pointer_cast<DestructiveFileSource>(source())) {
317                 return true;
318         }
319
320         for (uint32_t n=0; n < sources.size(); ++n) {
321                 if (_start > sources[n]->length() - len) {
322                         return false;
323                 }
324         }
325         return true;
326 }
327
328 bool
329 AudioRegion::verify_start_and_length (nframes_t new_start, nframes_t new_length)
330 {
331         if (boost::dynamic_pointer_cast<DestructiveFileSource>(source())) {
332                 return true;
333         }
334
335         for (uint32_t n=0; n < sources.size(); ++n) {
336                 if (new_length > sources[n]->length() - new_start) {
337                         return false;
338                 }
339         }
340         return true;
341 }
342 bool
343 AudioRegion::verify_start (nframes_t pos)
344 {
345         if (boost::dynamic_pointer_cast<DestructiveFileSource>(source())) {
346                 return true;
347         }
348
349         for (uint32_t n=0; n < sources.size(); ++n) {
350                 if (pos > sources[n]->length() - _length) {
351                         return false;
352                 }
353         }
354         return true;
355 }
356
357 bool
358 AudioRegion::verify_start_mutable (nframes_t& new_start)
359 {
360         if (boost::dynamic_pointer_cast<DestructiveFileSource>(source())) {
361                 return true;
362         }
363
364         for (uint32_t n=0; n < sources.size(); ++n) {
365                 if (new_start > sources[n]->length() - _length) {
366                         new_start = sources[n]->length() - _length;
367                 }
368         }
369         return true;
370 }
371 void
372 AudioRegion::set_envelope_active (bool yn)
373 {
374         if (envelope_active() != yn) {
375                 char buf[64];
376                 if (yn) {
377                         snprintf (buf, sizeof (buf), "envelope active");
378                         _flags = Flag (_flags|EnvelopeActive);
379                 } else {
380                         snprintf (buf, sizeof (buf), "envelope off");
381                         _flags = Flag (_flags & ~EnvelopeActive);
382                 }
383                 send_change (EnvelopeActiveChanged);
384         }
385 }
386
387 nframes_t
388 AudioRegion::read_peaks (PeakData *buf, nframes_t npeaks, nframes_t offset, nframes_t cnt, uint32_t chan_n, double samples_per_unit) const
389 {
390         if (chan_n >= sources.size()) {
391                 return 0; 
392         }
393         
394         if (sources[chan_n]->read_peaks (buf, npeaks, offset, cnt, samples_per_unit)) {
395                 return 0;
396         } else {
397                 if (_scale_amplitude != 1.0) {
398                         for (nframes_t n = 0; n < npeaks; ++n) {
399                                 buf[n].max *= _scale_amplitude;
400                                 buf[n].min *= _scale_amplitude;
401                         }
402                 }
403                 return cnt;
404         }
405 }
406
407 nframes_t
408 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer, nframes_t position, 
409                       nframes_t cnt, 
410                       uint32_t chan_n, nframes_t read_frames, nframes_t skip_frames) const
411 {
412         return _read_at (sources, buf, mixdown_buffer, gain_buffer, position, cnt, chan_n, read_frames, skip_frames);
413 }
414
415 nframes_t
416 AudioRegion::master_read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer, nframes_t position, 
417                              nframes_t cnt, uint32_t chan_n) const
418 {
419         return _read_at (master_sources, buf, mixdown_buffer, gain_buffer, position, cnt, chan_n, 0, 0);
420 }
421
422 nframes_t
423 AudioRegion::_read_at (const SourceList& srcs, Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
424                        nframes_t position, nframes_t cnt, 
425                        uint32_t chan_n, nframes_t read_frames, nframes_t skip_frames) const
426 {
427         nframes_t internal_offset;
428         nframes_t buf_offset;
429         nframes_t to_read;
430
431         /* precondition: caller has verified that we cover the desired section */
432
433         if (chan_n >= sources.size()) {
434                 return 0; /* read nothing */
435         }
436         
437         if (position < _position) {
438                 internal_offset = 0;
439                 buf_offset = _position - position;
440                 cnt -= buf_offset;
441         } else {
442                 internal_offset = position - _position;
443                 buf_offset = 0;
444         }
445
446         if (internal_offset >= _length) {
447                 return 0; /* read nothing */
448         }
449
450         if ((to_read = min (cnt, _length - internal_offset)) == 0) {
451                 return 0; /* read nothing */
452         }
453
454         if (opaque()) {
455                 /* overwrite whatever is there */
456                 mixdown_buffer = buf + buf_offset;
457         } else {
458                 mixdown_buffer += buf_offset;
459         }
460
461         if (muted()) {
462                 return 0; /* read nothing */
463         }
464
465         _read_data_count = 0;
466
467         if (srcs[chan_n]->read (mixdown_buffer, _start + internal_offset, to_read) != to_read) {
468                 return 0; /* "read nothing" */
469         }
470
471         _read_data_count += srcs[chan_n]->read_data_count();
472
473         /* fade in */
474
475         if (_flags & FadeIn) {
476
477                 nframes_t fade_in_length = (nframes_t) _fade_in.back()->when;
478                 
479                 /* see if this read is within the fade in */
480
481                 if (internal_offset < fade_in_length) {
482                         
483                         nframes_t limit;
484
485                         limit = min (to_read, fade_in_length - internal_offset);
486
487                         _fade_in.get_vector (internal_offset, internal_offset+limit, gain_buffer, limit);
488
489                         for (nframes_t n = 0; n < limit; ++n) {
490                                 mixdown_buffer[n] *= gain_buffer[n];
491                         }
492                 }
493         }
494         
495         /* fade out */
496
497         if (_flags & FadeOut) {
498         
499                 /* see if some part of this read is within the fade out */
500
501                 /* .................        >|            REGION
502                                             _length
503                                             
504                                  {           }            FADE
505                                              fade_out_length
506                                  ^                                           
507                                _length - fade_out_length
508                         |--------------|
509                         ^internal_offset
510                                        ^internal_offset + to_read
511
512                   we need the intersection of [internal_offset,internal_offset+to_read] with
513                   [_length - fade_out_length, _length]
514
515                 */
516
517         
518                 nframes_t fade_out_length = (nframes_t) _fade_out.back()->when;
519                 nframes_t fade_interval_start = max(internal_offset, _length-fade_out_length);
520                 nframes_t fade_interval_end   = min(internal_offset + to_read, _length);
521
522                 if (fade_interval_end > fade_interval_start) {
523                         /* (part of the) the fade out is  in this buffer */
524                         
525                         nframes_t limit = fade_interval_end - fade_interval_start;
526                         nframes_t curve_offset = fade_interval_start - (_length-fade_out_length);
527                         nframes_t fade_offset = fade_interval_start - internal_offset;
528                                                                        
529                         _fade_out.get_vector (curve_offset,curve_offset+limit, gain_buffer, limit);
530
531                         for (nframes_t n = 0, m = fade_offset; n < limit; ++n, ++m) {
532                                 mixdown_buffer[m] *= gain_buffer[n];
533                         }
534                 } 
535
536         }
537
538         /* Regular gain curves */
539
540         if (envelope_active())  {
541                 _envelope.get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
542                 
543                 if (_scale_amplitude != 1.0f) {
544                         for (nframes_t n = 0; n < to_read; ++n) {
545                                 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
546                         }
547                 } else {
548                         for (nframes_t n = 0; n < to_read; ++n) {
549                                 mixdown_buffer[n] *= gain_buffer[n];
550                         }
551                 }
552         } else if (_scale_amplitude != 1.0f) {
553                 Session::apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
554         }
555
556         if (!opaque()) {
557
558                 /* gack. the things we do for users.
559                  */
560
561                 buf += buf_offset;
562
563                 for (nframes_t n = 0; n < to_read; ++n) {
564                         buf[n] += mixdown_buffer[n];
565                 }
566         } 
567         
568         return to_read;
569 }
570         
571 XMLNode&
572 AudioRegion::state (bool full)
573 {
574         XMLNode& node (Region::state (full));
575         XMLNode *child;
576         char buf[64];
577         char buf2[64];
578         LocaleGuard lg (X_("POSIX"));
579         
580         snprintf (buf, sizeof (buf), "0x%x", (int) _flags);
581         node.add_property ("flags", buf);
582         snprintf (buf, sizeof(buf), "%.12g", _scale_amplitude);
583         node.add_property ("scale-gain", buf);
584
585         for (uint32_t n=0; n < sources.size(); ++n) {
586                 snprintf (buf2, sizeof(buf2), "source-%d", n);
587                 sources[n]->id().print (buf, sizeof (buf));
588                 node.add_property (buf2, buf);
589         }
590
591         snprintf (buf, sizeof (buf), "%u", (uint32_t) sources.size());
592         node.add_property ("channels", buf);
593
594         if (full) {
595         
596                 child = node.add_child (X_("FadeIn"));
597                 
598                 if ((_flags & DefaultFadeIn)) {
599                         child->add_property (X_("default"), X_("yes"));
600                 } else {
601                         child->add_child_nocopy (_fade_in.get_state ());
602                 }
603
604                 child->add_property (X_("active"), _fade_in_disabled ? X_("no") : X_("yes"));
605                 
606                 child = node.add_child (X_("FadeOut"));
607                 
608                 if ((_flags & DefaultFadeOut)) {
609                         child->add_property (X_("default"), X_("yes"));
610                 } else {
611                         child->add_child_nocopy (_fade_out.get_state ());
612                 }
613                 
614                 child->add_property (X_("active"), _fade_out_disabled ? X_("no") : X_("yes"));
615         }
616         
617         child = node.add_child ("Envelope");
618
619         if (full) {
620                 bool default_env = false;
621                 
622                 // If there are only two points, the points are in the start of the region and the end of the region
623                 // so, if they are both at 1.0f, that means the default region.
624
625                 if (_envelope.size() == 2 &&
626                     _envelope.front()->value == 1.0f &&
627                     _envelope.back()->value==1.0f) {
628                         if (_envelope.front()->when == 0 && _envelope.back()->when == _length) {
629                                 default_env = true;
630                         }
631                 } 
632                 
633                 if (default_env) {
634                         child->add_property ("default", "yes");
635                 } else {
636                         child->add_child_nocopy (_envelope.get_state ());
637                 }
638
639         } else {
640                 child->add_property ("default", "yes");
641         }
642
643         if (full && _extra_xml) {
644                 node.add_child_copy (*_extra_xml);
645         }
646
647         return node;
648 }
649
650 int
651 AudioRegion::set_live_state (const XMLNode& node, Change& what_changed, bool send)
652 {
653         const XMLNodeList& nlist = node.children();
654         const XMLProperty *prop;
655         LocaleGuard lg (X_("POSIX"));
656
657         Region::set_live_state (node, what_changed, false);
658
659         uint32_t old_flags = _flags;
660                 
661         if ((prop = node.property ("flags")) != 0) {
662                 _flags = Flag (strtol (prop->value().c_str(), (char **) 0, 16));
663
664                 _flags = Flag (_flags & ~Region::LeftOfSplit);
665                 _flags = Flag (_flags & ~Region::RightOfSplit);
666         }
667
668         if ((old_flags ^ _flags) & Muted) {
669                 what_changed = Change (what_changed|MuteChanged);
670         }
671         if ((old_flags ^ _flags) & Opaque) {
672                 what_changed = Change (what_changed|OpacityChanged);
673         }
674         if ((old_flags ^ _flags) & Locked) {
675                 what_changed = Change (what_changed|LockChanged);
676         }
677
678         if ((prop = node.property ("scale-gain")) != 0) {
679                 _scale_amplitude = atof (prop->value().c_str());
680         } else {
681                 _scale_amplitude = 1.0;
682         }
683         
684         /* Now find envelope description and other misc child items */
685                                 
686         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
687                 
688                 XMLNode *child;
689                 XMLProperty *prop;
690                 
691                 child = (*niter);
692                 
693                 if (child->name() == "Envelope") {
694                         
695                         _envelope.clear ();
696
697                         if ((prop = child->property ("default")) != 0) {
698                                 set_default_envelope ();
699                         } else {
700                                 _envelope.set_state (*child);
701                         }
702
703                         _envelope.set_max_xval (_length);
704                         _envelope.truncate_end (_length);
705                         
706                 } else if (child->name() == "FadeIn") {
707                         
708                         _fade_in.clear ();
709                         
710                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0) {
711                                 set_default_fade_in ();
712                         } else {
713                                 _fade_in.set_state (*child);
714                         }
715
716                 } else if (child->name() == "FadeOut") {
717                         
718                         _fade_out.clear ();
719
720                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0) {
721                                 set_default_fade_out ();
722                         } else {
723                                 _fade_out.set_state (*child);
724                         }
725                 } 
726         }
727
728         if (send) {
729                 send_change (what_changed);
730         }
731
732         return 0;
733 }
734
735 int
736 AudioRegion::set_state (const XMLNode& node)
737 {
738         /* Region::set_state() calls the virtual set_live_state(),
739            which will get us back to AudioRegion::set_live_state()
740            to handle the relevant stuff.
741         */
742
743         return Region::set_state (node);
744 }
745
746 void
747 AudioRegion::set_fade_in_shape (FadeShape shape)
748 {
749         set_fade_in (shape, (nframes_t) _fade_in.back()->when);
750 }
751
752 void
753 AudioRegion::set_fade_out_shape (FadeShape shape)
754 {
755         set_fade_out (shape, (nframes_t) _fade_out.back()->when);
756 }
757
758 void
759 AudioRegion::set_fade_in (FadeShape shape, nframes_t len)
760 {
761         _fade_in.freeze ();
762         _fade_in.clear ();
763
764         switch (shape) {
765         case Linear:
766                 _fade_in.add (0.0, 0.0);
767                 _fade_in.add (len, 1.0);
768                 break;
769
770         case Fast:
771                 _fade_in.add (0, 0);
772                 _fade_in.add (len * 0.389401, 0.0333333);
773                 _fade_in.add (len * 0.629032, 0.0861111);
774                 _fade_in.add (len * 0.829493, 0.233333);
775                 _fade_in.add (len * 0.9447, 0.483333);
776                 _fade_in.add (len * 0.976959, 0.697222);
777                 _fade_in.add (len, 1);
778                 break;
779
780         case Slow:
781                 _fade_in.add (0, 0);
782                 _fade_in.add (len * 0.0207373, 0.197222);
783                 _fade_in.add (len * 0.0645161, 0.525);
784                 _fade_in.add (len * 0.152074, 0.802778);
785                 _fade_in.add (len * 0.276498, 0.919444);
786                 _fade_in.add (len * 0.481567, 0.980556);
787                 _fade_in.add (len * 0.767281, 1);
788                 _fade_in.add (len, 1);
789                 break;
790
791         case LogA:
792                 _fade_in.add (0, 0);
793                 _fade_in.add (len * 0.0737327, 0.308333);
794                 _fade_in.add (len * 0.246544, 0.658333);
795                 _fade_in.add (len * 0.470046, 0.886111);
796                 _fade_in.add (len * 0.652074, 0.972222);
797                 _fade_in.add (len * 0.771889, 0.988889);
798                 _fade_in.add (len, 1);
799                 break;
800
801         case LogB:
802                 _fade_in.add (0, 0);
803                 _fade_in.add (len * 0.304147, 0.0694444);
804                 _fade_in.add (len * 0.529954, 0.152778);
805                 _fade_in.add (len * 0.725806, 0.333333);
806                 _fade_in.add (len * 0.847926, 0.558333);
807                 _fade_in.add (len * 0.919355, 0.730556);
808                 _fade_in.add (len, 1);
809                 break;
810         }
811
812         _fade_in.thaw ();
813         _fade_in_shape = shape;
814
815         send_change (FadeInChanged);
816 }
817
818 void
819 AudioRegion::set_fade_out (FadeShape shape, nframes_t len)
820 {
821         _fade_out.freeze ();
822         _fade_out.clear ();
823
824         switch (shape) {
825         case Fast:
826                 _fade_out.add (len * 0, 1);
827                 _fade_out.add (len * 0.023041, 0.697222);
828                 _fade_out.add (len * 0.0553,   0.483333);
829                 _fade_out.add (len * 0.170507, 0.233333);
830                 _fade_out.add (len * 0.370968, 0.0861111);
831                 _fade_out.add (len * 0.610599, 0.0333333);
832                 _fade_out.add (len * 1, 0);
833                 break;
834
835         case LogA:
836                 _fade_out.add (len * 0, 1);
837                 _fade_out.add (len * 0.228111, 0.988889);
838                 _fade_out.add (len * 0.347926, 0.972222);
839                 _fade_out.add (len * 0.529954, 0.886111);
840                 _fade_out.add (len * 0.753456, 0.658333);
841                 _fade_out.add (len * 0.9262673, 0.308333);
842                 _fade_out.add (len * 1, 0);
843                 break;
844
845         case Slow:
846                 _fade_out.add (len * 0, 1);
847                 _fade_out.add (len * 0.305556, 1);
848                 _fade_out.add (len * 0.548611, 0.991736);
849                 _fade_out.add (len * 0.759259, 0.931129);
850                 _fade_out.add (len * 0.918981, 0.68595);
851                 _fade_out.add (len * 0.976852, 0.22865);
852                 _fade_out.add (len * 1, 0);
853                 break;
854
855         case LogB:
856                 _fade_out.add (len * 0, 1);
857                 _fade_out.add (len * 0.080645, 0.730556);
858                 _fade_out.add (len * 0.277778, 0.289256);
859                 _fade_out.add (len * 0.470046, 0.152778);
860                 _fade_out.add (len * 0.695853, 0.0694444);
861                 _fade_out.add (len * 1, 0);
862                 break;
863
864         case Linear:
865                 _fade_out.add (len * 0, 1);
866                 _fade_out.add (len * 1, 0);
867                 break;
868         }
869
870         _fade_out.thaw ();
871         _fade_out_shape = shape;
872
873         send_change (FadeOutChanged);
874 }
875
876 void
877 AudioRegion::set_fade_in_length (nframes_t len)
878 {
879         bool changed = _fade_in.extend_to (len);
880
881         if (changed) {
882                 _flags = Flag (_flags & ~DefaultFadeIn);
883                 send_change (FadeInChanged);
884         }
885 }
886
887 void
888 AudioRegion::set_fade_out_length (nframes_t len)
889 {
890         bool changed =  _fade_out.extend_to (len);
891
892         if (changed) {
893                 _flags = Flag (_flags & ~DefaultFadeOut);
894         }
895
896         send_change (FadeOutChanged);
897 }
898
899 void
900 AudioRegion::set_fade_in_active (bool yn)
901 {
902         if (yn == (_flags & FadeIn)) {
903                 return;
904         }
905         if (yn) {
906                 _flags = Flag (_flags|FadeIn);
907         } else {
908                 _flags = Flag (_flags & ~FadeIn);
909         }
910
911         send_change (FadeInActiveChanged);
912 }
913
914 void
915 AudioRegion::set_fade_out_active (bool yn)
916 {
917         if (yn == (_flags & FadeOut)) {
918                 return;
919         }
920         if (yn) {
921                 _flags = Flag (_flags | FadeOut);
922         } else {
923                 _flags = Flag (_flags & ~FadeOut);
924         }
925
926         send_change (FadeOutActiveChanged);
927 }
928
929 void
930 AudioRegion::set_default_fade_in ()
931 {
932         set_fade_in (Linear, 64);
933 }
934
935 void
936 AudioRegion::set_default_fade_out ()
937 {
938         set_fade_out (Linear, 64);
939 }
940
941 void
942 AudioRegion::set_default_fades ()
943 {
944         _fade_in_disabled = 0;
945         _fade_out_disabled = 0;
946         set_default_fade_in ();
947         set_default_fade_out ();
948 }
949
950 void
951 AudioRegion::set_default_envelope ()
952 {
953         _envelope.freeze ();
954         _envelope.clear ();
955         _envelope.add (0, 1.0f);
956         _envelope.add (_length, 1.0f);
957         _envelope.thaw ();
958 }
959
960 void
961 AudioRegion::recompute_at_end ()
962 {
963         /* our length has changed. recompute a new final point by interpolating 
964            based on the the existing curve.
965         */
966         
967         _envelope.freeze ();
968         _envelope.truncate_end (_length);
969         _envelope.set_max_xval (_length);
970         _envelope.thaw ();
971
972         if (_fade_in.back()->when > _length) {
973                 _fade_in.extend_to (_length);
974                 send_change (FadeInChanged);
975         }
976
977         if (_fade_out.back()->when > _length) {
978                 _fade_out.extend_to (_length);
979                 send_change (FadeOutChanged);
980         }
981 }       
982
983 void
984 AudioRegion::recompute_at_start ()
985 {
986         /* as above, but the shift was from the front */
987
988         _envelope.truncate_start (_length);
989
990         if (_fade_in.back()->when > _length) {
991                 _fade_in.extend_to (_length);
992                 send_change (FadeInChanged);
993         }
994
995         if (_fade_out.back()->when > _length) {
996                 _fade_out.extend_to (_length);
997                 send_change (FadeOutChanged);
998         }
999 }
1000
1001 int
1002 AudioRegion::separate_by_channel (Session& session, vector<AudioRegion*>& v) const
1003 {
1004         SourceList srcs;
1005         string new_name;
1006
1007         for (SourceList::const_iterator i = master_sources.begin(); i != master_sources.end(); ++i) {
1008
1009                 srcs.clear ();
1010                 srcs.push_back (*i);
1011
1012                 /* generate a new name */
1013                 
1014                 if (session.region_name (new_name, _name)) {
1015                         return -1;
1016                 }
1017
1018                 /* create a copy with just one source */
1019
1020                 v.push_back (new AudioRegion (srcs, _start, _length, new_name, _layer, _flags));
1021         }
1022
1023         return 0;
1024 }
1025
1026 void
1027 AudioRegion::source_deleted ()
1028 {
1029         sources.clear ();
1030         drop_references ();
1031 }
1032
1033 vector<string>
1034 AudioRegion::master_source_names ()
1035 {
1036         SourceList::iterator i;
1037
1038         vector<string> names;
1039         for (i = master_sources.begin(); i != master_sources.end(); ++i) {
1040                 names.push_back((*i)->name());
1041         }
1042
1043         return names;
1044 }
1045
1046 bool
1047 AudioRegion::source_equivalent (boost::shared_ptr<const Region> o) const
1048 {
1049         boost::shared_ptr<const AudioRegion> other = boost::dynamic_pointer_cast<const AudioRegion>(o);
1050
1051         if (!other)
1052                 return false;
1053
1054         SourceList::const_iterator i;
1055         SourceList::const_iterator io;
1056
1057         for (i = sources.begin(), io = other->sources.begin(); i != sources.end() && io != other->sources.end(); ++i, ++io) {
1058                 if ((*i)->id() != (*io)->id()) {
1059                         return false;
1060                 }
1061         }
1062
1063         for (i = master_sources.begin(), io = other->master_sources.begin(); i != master_sources.end() && io != other->master_sources.end(); ++i, ++io) {
1064                 if ((*i)->id() != (*io)->id()) {
1065                         return false;
1066                 }
1067         }
1068
1069         return true;
1070 }
1071
1072 int
1073 AudioRegion::apply (AudioFilter& filter)
1074 {
1075         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (shared_from_this());
1076         return filter.run (ar);
1077 }
1078
1079 int
1080 AudioRegion::exportme (Session& session, AudioExportSpecification& spec)
1081 {
1082         const nframes_t blocksize = 4096;
1083         nframes_t to_read;
1084         int status = -1;
1085
1086         spec.channels = sources.size();
1087
1088         if (spec.prepare (blocksize, session.frame_rate())) {
1089                 goto out;
1090         }
1091
1092         spec.pos = 0;
1093         spec.total_frames = _length;
1094
1095         while (spec.pos < _length && !spec.stop) {
1096                 
1097                 
1098                 /* step 1: interleave */
1099                 
1100                 to_read = min (_length - spec.pos, blocksize);
1101                 
1102                 if (spec.channels == 1) {
1103
1104                         if (sources.front()->read (spec.dataF, _start + spec.pos, to_read) != to_read) {
1105                                 goto out;
1106                         }
1107
1108                 } else {
1109
1110                         Sample buf[blocksize];
1111
1112                         for (uint32_t chan = 0; chan < spec.channels; ++chan) {
1113                                 
1114                                 if (sources[chan]->read (buf, _start + spec.pos, to_read) != to_read) {
1115                                         goto out;
1116                                 }
1117                                 
1118                                 for (nframes_t x = 0; x < to_read; ++x) {
1119                                         spec.dataF[chan+(x*spec.channels)] = buf[x];
1120                                 }
1121                         }
1122                 }
1123                 
1124                 if (spec.process (to_read)) {
1125                         goto out;
1126                 }
1127                 
1128                 spec.pos += to_read;
1129                 spec.progress = (double) spec.pos /_length;
1130                 
1131         }
1132         
1133         status = 0;
1134
1135   out:  
1136         spec.running = false;
1137         spec.status = status;
1138         spec.clear();
1139         
1140         return status;
1141 }
1142
1143 boost::shared_ptr<Region>
1144 AudioRegion::get_parent()
1145 {
1146         boost::shared_ptr<Region> r;
1147
1148         if (_playlist) {
1149                 boost::shared_ptr<AudioRegion> ar;
1150                 boost::shared_ptr<AudioRegion> grrr2 = boost::dynamic_pointer_cast<AudioRegion> (shared_from_this());
1151                 
1152                 if (grrr2 && (ar = _playlist->session().find_whole_file_parent (grrr2))) {
1153                         return boost::static_pointer_cast<Region> (ar);
1154                 }
1155         }
1156         
1157         return r;
1158 }
1159
1160 void
1161 AudioRegion::set_scale_amplitude (gain_t g)
1162 {
1163         _scale_amplitude = g;
1164
1165         /* tell the diskstream we're in */
1166
1167         if (_playlist) {
1168                 _playlist->Modified();
1169         }
1170
1171         /* tell everybody else */
1172
1173         send_change (ScaleAmplitudeChanged);
1174 }
1175
1176 void
1177 AudioRegion::normalize_to (float target_dB)
1178 {
1179         const nframes_t blocksize = 64 * 1024;
1180         Sample buf[blocksize];
1181         nframes_t fpos;
1182         nframes_t fend;
1183         nframes_t to_read;
1184         double maxamp = 0;
1185         gain_t target = dB_to_coefficient (target_dB);
1186
1187         if (target == 1.0f) {
1188                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1189                    that we may have clipped.
1190                 */
1191                 target -= FLT_EPSILON;
1192         }
1193
1194         fpos = _start;
1195         fend = _start + _length;
1196
1197         /* first pass: find max amplitude */
1198
1199         while (fpos < fend) {
1200
1201                 uint32_t n;
1202
1203                 to_read = min (fend - fpos, blocksize);
1204
1205                 for (n = 0; n < n_channels(); ++n) {
1206
1207                         /* read it in */
1208
1209                         if (source (n)->read (buf, fpos, to_read) != to_read) {
1210                                 return;
1211                         }
1212                         
1213                         maxamp = Session::compute_peak (buf, to_read, maxamp);
1214                 }
1215
1216                 fpos += to_read;
1217         };
1218
1219         if (maxamp == 0.0f) {
1220                 /* don't even try */
1221                 return;
1222         }
1223
1224         if (maxamp == target) {
1225                 /* we can't do anything useful */
1226                 return;
1227         }
1228
1229         /* compute scale factor */
1230
1231         _scale_amplitude = target/maxamp;
1232
1233         /* tell the diskstream we're in */
1234
1235         if (_playlist) {
1236                 _playlist->Modified();
1237         }
1238
1239         /* tell everybody else */
1240
1241         send_change (ScaleAmplitudeChanged);
1242 }
1243
1244 void
1245 AudioRegion::envelope_changed (Change ignored)
1246 {
1247         send_change (EnvelopeChanged);
1248 }
1249
1250 void
1251 AudioRegion::suspend_fade_in ()
1252 {
1253         if (++_fade_in_disabled == 1) {
1254                 set_fade_in_active (false);
1255         }
1256 }
1257
1258 void
1259 AudioRegion::resume_fade_in ()
1260 {
1261         if (_fade_in_disabled && --_fade_in_disabled == 0) {
1262                 set_fade_in_active (true);
1263         }
1264 }
1265
1266 void
1267 AudioRegion::suspend_fade_out ()
1268 {
1269         if (++_fade_out_disabled == 1) {
1270                 set_fade_out_active (false);
1271         }
1272 }
1273
1274 void
1275 AudioRegion::resume_fade_out ()
1276 {
1277         if (_fade_out_disabled && --_fade_out_disabled == 0) {
1278                 set_fade_out_active (true);
1279         }
1280 }
1281
1282 bool
1283 AudioRegion::speed_mismatch (float sr) const
1284 {
1285         if (sources.empty()) {
1286                 /* impossible, but ... */
1287                 return false;
1288         }
1289
1290         float fsr = sources.front()->sample_rate();
1291
1292         return fsr != sr;
1293 }
1294
1295 void
1296 AudioRegion::source_offset_changed ()
1297 {
1298         if (boost::dynamic_pointer_cast<DestructiveFileSource>(sources.front())) {
1299                 set_start (source()->natural_position(), this);
1300                 set_position (source()->natural_position(), this);
1301         } 
1302 }
1303
1304 extern "C" {
1305
1306         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) 
1307 {
1308         return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (nframes_t) npeaks, (nframes_t) start, (nframes_t) cnt, n_chan,samples_per_unit);
1309 }
1310
1311 uint32_t region_length_from_c (void *arg)
1312 {
1313
1314         return ((AudioRegion *) arg)->length();
1315 }
1316
1317 uint32_t sourcefile_length_from_c (void *arg, double zoom_factor)
1318 {
1319         return ( (AudioRegion *) arg)->source()->available_peaks (zoom_factor) ;
1320 }
1321
1322 } /* extern "C" */