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