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