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