Genericificationalizeified AudioFilter (now Filter).
[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 (nframes_t start, nframes_t length, string name)
74         : Region (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         } else {
605                 _scale_amplitude = 1.0;
606         }
607         
608         /* Now find envelope description and other misc child items */
609                                 
610         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
611                 
612                 XMLNode *child;
613                 XMLProperty *prop;
614                 
615                 child = (*niter);
616                 
617                 if (child->name() == "Envelope") {
618                         
619                         _envelope->clear ();
620
621                         if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child)) {
622                                 set_default_envelope ();
623                         }
624
625                         _envelope->set_max_xval (_length);
626                         _envelope->truncate_end (_length);
627
628                 } else if (child->name() == "FadeIn") {
629                         
630                         _fade_in->clear ();
631                         
632                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0 || _fade_in->set_state (*child)) {
633                                 set_default_fade_in ();
634                         } 
635
636                 } else if (child->name() == "FadeOut") {
637                         
638                         _fade_out->clear ();
639
640                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0 || _fade_out->set_state (*child)) {
641                                 set_default_fade_out ();
642                         } 
643                 } 
644         }
645
646         if (send) {
647                 send_change (what_changed);
648         }
649
650         return 0;
651 }
652
653 int
654 AudioRegion::set_state (const XMLNode& node)
655 {
656         /* Region::set_state() calls the virtual set_live_state(),
657            which will get us back to AudioRegion::set_live_state()
658            to handle the relevant stuff.
659         */
660
661         return Region::set_state (node);
662 }
663
664 void
665 AudioRegion::set_fade_in_shape (FadeShape shape)
666 {
667         set_fade_in (shape, (nframes_t) _fade_in->back()->when);
668 }
669
670 void
671 AudioRegion::set_fade_out_shape (FadeShape shape)
672 {
673         set_fade_out (shape, (nframes_t) _fade_out->back()->when);
674 }
675
676 void
677 AudioRegion::set_fade_in (FadeShape shape, nframes_t len)
678 {
679         _fade_in->freeze ();
680         _fade_in->clear ();
681
682         switch (shape) {
683         case Linear:
684                 _fade_in->fast_simple_add (0.0, 0.0);
685                 _fade_in->fast_simple_add (len, 1.0);
686                 break;
687
688         case Fast:
689                 _fade_in->fast_simple_add (0, 0);
690                 _fade_in->fast_simple_add (len * 0.389401, 0.0333333);
691                 _fade_in->fast_simple_add (len * 0.629032, 0.0861111);
692                 _fade_in->fast_simple_add (len * 0.829493, 0.233333);
693                 _fade_in->fast_simple_add (len * 0.9447, 0.483333);
694                 _fade_in->fast_simple_add (len * 0.976959, 0.697222);
695                 _fade_in->fast_simple_add (len, 1);
696                 break;
697
698         case Slow:
699                 _fade_in->fast_simple_add (0, 0);
700                 _fade_in->fast_simple_add (len * 0.0207373, 0.197222);
701                 _fade_in->fast_simple_add (len * 0.0645161, 0.525);
702                 _fade_in->fast_simple_add (len * 0.152074, 0.802778);
703                 _fade_in->fast_simple_add (len * 0.276498, 0.919444);
704                 _fade_in->fast_simple_add (len * 0.481567, 0.980556);
705                 _fade_in->fast_simple_add (len * 0.767281, 1);
706                 _fade_in->fast_simple_add (len, 1);
707                 break;
708
709         case LogA:
710                 _fade_in->fast_simple_add (0, 0);
711                 _fade_in->fast_simple_add (len * 0.0737327, 0.308333);
712                 _fade_in->fast_simple_add (len * 0.246544, 0.658333);
713                 _fade_in->fast_simple_add (len * 0.470046, 0.886111);
714                 _fade_in->fast_simple_add (len * 0.652074, 0.972222);
715                 _fade_in->fast_simple_add (len * 0.771889, 0.988889);
716                 _fade_in->fast_simple_add (len, 1);
717                 break;
718
719         case LogB:
720                 _fade_in->fast_simple_add (0, 0);
721                 _fade_in->fast_simple_add (len * 0.304147, 0.0694444);
722                 _fade_in->fast_simple_add (len * 0.529954, 0.152778);
723                 _fade_in->fast_simple_add (len * 0.725806, 0.333333);
724                 _fade_in->fast_simple_add (len * 0.847926, 0.558333);
725                 _fade_in->fast_simple_add (len * 0.919355, 0.730556);
726                 _fade_in->fast_simple_add (len, 1);
727                 break;
728         }
729
730         _fade_in->thaw ();
731         _fade_in_shape = shape;
732
733         send_change (FadeInChanged);
734 }
735
736 void
737 AudioRegion::set_fade_out (FadeShape shape, nframes_t len)
738 {
739         _fade_out->freeze ();
740         _fade_out->clear ();
741
742         switch (shape) {
743         case Fast:
744                 _fade_out->fast_simple_add (len * 0, 1);
745                 _fade_out->fast_simple_add (len * 0.023041, 0.697222);
746                 _fade_out->fast_simple_add (len * 0.0553,   0.483333);
747                 _fade_out->fast_simple_add (len * 0.170507, 0.233333);
748                 _fade_out->fast_simple_add (len * 0.370968, 0.0861111);
749                 _fade_out->fast_simple_add (len * 0.610599, 0.0333333);
750                 _fade_out->fast_simple_add (len * 1, 0);
751                 break;
752
753         case LogA:
754                 _fade_out->fast_simple_add (len * 0, 1);
755                 _fade_out->fast_simple_add (len * 0.228111, 0.988889);
756                 _fade_out->fast_simple_add (len * 0.347926, 0.972222);
757                 _fade_out->fast_simple_add (len * 0.529954, 0.886111);
758                 _fade_out->fast_simple_add (len * 0.753456, 0.658333);
759                 _fade_out->fast_simple_add (len * 0.9262673, 0.308333);
760                 _fade_out->fast_simple_add (len * 1, 0);
761                 break;
762
763         case Slow:
764                 _fade_out->fast_simple_add (len * 0, 1);
765                 _fade_out->fast_simple_add (len * 0.305556, 1);
766                 _fade_out->fast_simple_add (len * 0.548611, 0.991736);
767                 _fade_out->fast_simple_add (len * 0.759259, 0.931129);
768                 _fade_out->fast_simple_add (len * 0.918981, 0.68595);
769                 _fade_out->fast_simple_add (len * 0.976852, 0.22865);
770                 _fade_out->fast_simple_add (len * 1, 0);
771                 break;
772
773         case LogB:
774                 _fade_out->fast_simple_add (len * 0, 1);
775                 _fade_out->fast_simple_add (len * 0.080645, 0.730556);
776                 _fade_out->fast_simple_add (len * 0.277778, 0.289256);
777                 _fade_out->fast_simple_add (len * 0.470046, 0.152778);
778                 _fade_out->fast_simple_add (len * 0.695853, 0.0694444);
779                 _fade_out->fast_simple_add (len * 1, 0);
780                 break;
781
782         case Linear:
783                 _fade_out->fast_simple_add (len * 0, 1);
784                 _fade_out->fast_simple_add (len * 1, 0);
785                 break;
786         }
787
788         _fade_out->thaw ();
789         _fade_out_shape = shape;
790
791         send_change (FadeOutChanged);
792 }
793
794 void
795 AudioRegion::set_fade_in_length (nframes_t len)
796 {
797         bool changed = _fade_in->extend_to (len);
798
799         if (changed) {
800                 _flags = Flag (_flags & ~DefaultFadeIn);
801                 send_change (FadeInChanged);
802         }
803 }
804
805 void
806 AudioRegion::set_fade_out_length (nframes_t len)
807 {
808         bool changed =  _fade_out->extend_to (len);
809
810         if (changed) {
811                 _flags = Flag (_flags & ~DefaultFadeOut);
812         }
813
814         send_change (FadeOutChanged);
815 }
816
817 void
818 AudioRegion::set_fade_in_active (bool yn)
819 {
820         if (yn == (_flags & FadeIn)) {
821                 return;
822         }
823         if (yn) {
824                 _flags = Flag (_flags|FadeIn);
825         } else {
826                 _flags = Flag (_flags & ~FadeIn);
827         }
828
829         send_change (FadeInActiveChanged);
830 }
831
832 void
833 AudioRegion::set_fade_out_active (bool yn)
834 {
835         if (yn == (_flags & FadeOut)) {
836                 return;
837         }
838         if (yn) {
839                 _flags = Flag (_flags | FadeOut);
840         } else {
841                 _flags = Flag (_flags & ~FadeOut);
842         }
843
844         send_change (FadeOutActiveChanged);
845 }
846
847 bool
848 AudioRegion::fade_in_is_default () const
849 {
850         return _fade_in_shape == Linear && _fade_in->back()->when == 64;
851 }
852
853 bool
854 AudioRegion::fade_out_is_default () const
855 {
856         return _fade_out_shape == Linear && _fade_out->back()->when == 64;
857 }
858
859 void
860 AudioRegion::set_default_fade_in ()
861 {
862         set_fade_in (Linear, 64);
863 }
864
865 void
866 AudioRegion::set_default_fade_out ()
867 {
868         set_fade_out (Linear, 64);
869 }
870
871 void
872 AudioRegion::set_default_fades ()
873 {
874         _fade_in_disabled = 0;
875         _fade_out_disabled = 0;
876         set_default_fade_in ();
877         set_default_fade_out ();
878 }
879
880 void
881 AudioRegion::set_default_envelope ()
882 {
883         _envelope->freeze ();
884         _envelope->clear ();
885         _envelope->fast_simple_add (0, 1.0f);
886         _envelope->fast_simple_add (_length, 1.0f);
887         _envelope->thaw ();
888 }
889
890 void
891 AudioRegion::recompute_at_end ()
892 {
893         /* our length has changed. recompute a new final point by interpolating 
894            based on the the existing curve.
895         */
896         
897         _envelope->freeze ();
898         _envelope->truncate_end (_length);
899         _envelope->set_max_xval (_length);
900         _envelope->thaw ();
901
902         if (_fade_in->back()->when > _length) {
903                 _fade_in->extend_to (_length);
904                 send_change (FadeInChanged);
905         }
906
907         if (_fade_out->back()->when > _length) {
908                 _fade_out->extend_to (_length);
909                 send_change (FadeOutChanged);
910         }
911 }       
912
913 void
914 AudioRegion::recompute_at_start ()
915 {
916         /* as above, but the shift was from the front */
917
918         _envelope->truncate_start (_length);
919
920         if (_fade_in->back()->when > _length) {
921                 _fade_in->extend_to (_length);
922                 send_change (FadeInChanged);
923         }
924
925         if (_fade_out->back()->when > _length) {
926                 _fade_out->extend_to (_length);
927                 send_change (FadeOutChanged);
928         }
929 }
930
931 int
932 AudioRegion::separate_by_channel (Session& session, vector<boost::shared_ptr<AudioRegion> >& v) const
933 {
934         SourceList srcs;
935         string new_name;
936         int n;
937
938         if (_sources.size() < 2) {
939                 return 0;
940         }
941
942         n = 0;
943
944         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
945
946                 srcs.clear ();
947                 srcs.push_back (*i);
948
949                 new_name = _name;
950
951                 if (_sources.size() == 2) {
952                         if (n == 0) {
953                                 new_name += "-L";
954                         } else {
955                                 new_name += "-R";
956                         }
957                 } else {
958                         new_name += '-';
959                         new_name += ('0' + n + 1);
960                 }
961
962                 /* create a copy with just one source. prevent if from being thought of as "whole file" even if 
963                    it covers the entire source file(s).
964                  */
965
966                 Flag f = Flag (_flags & ~WholeFile);
967
968                 boost::shared_ptr<Region> r = RegionFactory::create (srcs, _start, _length, new_name, _layer, f);
969                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (r);
970
971                 v.push_back (ar);
972                 
973                 ++n;
974         }
975
976         return 0;
977 }
978
979 nframes_t
980 AudioRegion::read_raw_internal (Sample* buf, nframes_t pos, nframes_t cnt) const
981 {
982         return audio_source()->read  (buf, pos, cnt);
983 }
984
985 int
986 AudioRegion::exportme (Session& session, AudioExportSpecification& spec)
987 {
988         const nframes_t blocksize = 4096;
989         nframes_t to_read;
990         int status = -1;
991
992         spec.channels = _sources.size();
993
994         if (spec.prepare (blocksize, session.frame_rate())) {
995                 goto out;
996         }
997
998         spec.pos = 0;
999         spec.total_frames = _length;
1000
1001         while (spec.pos < _length && !spec.stop) {
1002                 
1003                 
1004                 /* step 1: interleave */
1005                 
1006                 to_read = min (_length - spec.pos, blocksize);
1007                 
1008                 if (spec.channels == 1) {
1009
1010                         if (read_raw_internal (spec.dataF, _start + spec.pos, to_read) != to_read) {
1011                                 goto out;
1012                         }
1013
1014                 } else {
1015
1016                         Sample buf[blocksize];
1017
1018                         for (uint32_t chan = 0; chan < spec.channels; ++chan) {
1019                                 
1020                                 if (audio_source(chan)->read (buf, _start + spec.pos, to_read) != to_read) {
1021                                         goto out;
1022                                 }
1023                                 
1024                                 for (nframes_t x = 0; x < to_read; ++x) {
1025                                         spec.dataF[chan+(x*spec.channels)] = buf[x];
1026                                 }
1027                         }
1028                 }
1029                 
1030                 if (spec.process (to_read)) {
1031                         goto out;
1032                 }
1033                 
1034                 spec.pos += to_read;
1035                 spec.progress = (double) spec.pos /_length;
1036                 
1037         }
1038         
1039         status = 0;
1040
1041   out:  
1042         spec.running = false;
1043         spec.status = status;
1044         spec.clear();
1045         
1046         return status;
1047 }
1048
1049 void
1050 AudioRegion::set_scale_amplitude (gain_t g)
1051 {
1052         boost::shared_ptr<Playlist> pl (playlist());
1053
1054         _scale_amplitude = g;
1055
1056         /* tell the diskstream we're in */
1057         
1058         if (pl) {
1059                 pl->Modified();
1060         }
1061
1062         /* tell everybody else */
1063
1064         send_change (ScaleAmplitudeChanged);
1065 }
1066
1067 void
1068 AudioRegion::normalize_to (float target_dB)
1069 {
1070         const nframes_t blocksize = 64 * 1024;
1071         Sample buf[blocksize];
1072         nframes_t fpos;
1073         nframes_t fend;
1074         nframes_t to_read;
1075         double maxamp = 0;
1076         gain_t target = dB_to_coefficient (target_dB);
1077
1078         if (target == 1.0f) {
1079                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1080                    that we may have clipped.
1081                 */
1082                 target -= FLT_EPSILON;
1083         }
1084
1085         fpos = _start;
1086         fend = _start + _length;
1087
1088         /* first pass: find max amplitude */
1089
1090         while (fpos < fend) {
1091
1092                 uint32_t n;
1093
1094                 to_read = min (fend - fpos, blocksize);
1095
1096                 for (n = 0; n < n_channels(); ++n) {
1097
1098                         /* read it in */
1099
1100                         if (read_raw_internal (buf, fpos, to_read) != to_read) {
1101                                 return;
1102                         }
1103                         
1104                         maxamp = compute_peak (buf, to_read, maxamp);
1105                 }
1106
1107                 fpos += to_read;
1108         };
1109
1110         if (maxamp == 0.0f) {
1111                 /* don't even try */
1112                 return;
1113         }
1114
1115         if (maxamp == target) {
1116                 /* we can't do anything useful */
1117                 return;
1118         }
1119
1120         /* compute scale factor */
1121
1122         _scale_amplitude = target/maxamp;
1123
1124         /* tell the diskstream we're in */
1125
1126         boost::shared_ptr<Playlist> pl (playlist());
1127
1128         if (pl) {
1129                 pl->Modified();
1130         }
1131
1132         /* tell everybody else */
1133
1134         send_change (ScaleAmplitudeChanged);
1135 }
1136
1137 void
1138 AudioRegion::fade_in_changed ()
1139 {
1140         send_change (FadeInChanged);
1141 }
1142
1143 void
1144 AudioRegion::fade_out_changed ()
1145 {
1146         send_change (FadeOutChanged);
1147 }
1148
1149 void
1150 AudioRegion::envelope_changed ()
1151 {
1152         send_change (EnvelopeChanged);
1153 }
1154
1155 void
1156 AudioRegion::suspend_fade_in ()
1157 {
1158         if (++_fade_in_disabled == 1) {
1159                 if (fade_in_is_default()) {
1160                         set_fade_in_active (false);
1161                 }
1162         }
1163 }
1164
1165 void
1166 AudioRegion::resume_fade_in ()
1167 {
1168         if (--_fade_in_disabled == 0 && _fade_in_disabled) {
1169                 set_fade_in_active (true);
1170         }
1171 }
1172
1173 void
1174 AudioRegion::suspend_fade_out ()
1175 {
1176         if (++_fade_out_disabled == 1) {
1177                 if (fade_out_is_default()) {
1178                         set_fade_out_active (false);
1179                 }
1180         }
1181 }
1182
1183 void
1184 AudioRegion::resume_fade_out ()
1185 {
1186         if (--_fade_out_disabled == 0 &&_fade_out_disabled) {
1187                 set_fade_out_active (true);
1188         }
1189 }
1190
1191 bool
1192 AudioRegion::speed_mismatch (float sr) const
1193 {
1194         if (_sources.empty()) {
1195                 /* impossible, but ... */
1196                 return false;
1197         }
1198
1199         float fsr = audio_source()->sample_rate();
1200
1201         return fsr != sr;
1202 }
1203
1204 void
1205 AudioRegion::source_offset_changed ()
1206 {
1207         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1208
1209         if (afs && afs->destructive()) {
1210                 // set_start (source()->natural_position(), this);
1211                 set_position (source()->natural_position(), this);
1212         } 
1213 }
1214
1215 boost::shared_ptr<AudioSource>
1216 AudioRegion::audio_source (uint32_t n) const
1217 {
1218         // Guaranteed to succeed (use a static cast for speed?)
1219         return boost::dynamic_pointer_cast<AudioSource>(source(n));
1220 }
1221
1222 extern "C" {
1223
1224         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) 
1225 {
1226         return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (nframes_t) npeaks, (nframes_t) start, (nframes_t) cnt, n_chan,samples_per_unit);
1227 }
1228
1229 uint32_t region_length_from_c (void *arg)
1230 {
1231
1232         return ((AudioRegion *) arg)->length();
1233 }
1234
1235 uint32_t sourcefile_length_from_c (void *arg, double zoom_factor)
1236 {
1237         return ( (AudioRegion *) arg)->audio_source()->available_peaks (zoom_factor) ;
1238 }
1239
1240 } /* extern "C" */