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