initial fixes to get build to work without new JACK MIDI, and to get it running with...
[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         if (muted()) {
336                 return 0; /* read nothing */
337         }
338
339         /* precondition: caller has verified that we cover the desired section */
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         _read_data_count = 0;
366
367         if (chan_n < n_channels()) {
368                 
369                 boost::shared_ptr<AudioSource> src = audio_source(chan_n);
370                 if (src->read (mixdown_buffer, _start + internal_offset, to_read) != to_read) {
371
372                         return 0; /* "read nothing" */
373                 }
374
375                 _read_data_count += src->read_data_count();
376
377         } else {
378                 
379                 /* track is N-channel, this region has less channels; silence the ones
380                    we don't have.
381                 */
382
383                 memset (mixdown_buffer, 0, sizeof (Sample) * cnt);
384
385                 /* no fades required */
386
387                 goto merge;
388         }
389
390         /* fade in */
391
392         if (_flags & FadeIn) {
393
394                 nframes_t fade_in_length = (nframes_t) _fade_in.back()->when;
395                 
396                 /* see if this read is within the fade in */
397
398                 if (internal_offset < fade_in_length) {
399                 
400                         nframes_t limit;
401
402                         limit = min (to_read, fade_in_length - internal_offset);
403
404                         _fade_in.get_vector (internal_offset, internal_offset+limit, gain_buffer, limit);
405
406                         for (nframes_t n = 0; n < limit; ++n) {
407                                 mixdown_buffer[n] *= gain_buffer[n];
408                         }
409                 }
410         }
411         
412         /* fade out */
413
414         if (_flags & FadeOut) {
415         
416                 /* see if some part of this read is within the fade out */
417
418                 /* .................        >|            REGION
419                                             _length
420                                             
421                                  {           }            FADE
422                                              fade_out_length
423                                  ^                                           
424                                _length - fade_out_length
425                         |--------------|
426                         ^internal_offset
427                                        ^internal_offset + to_read
428
429                   we need the intersection of [internal_offset,internal_offset+to_read] with
430                   [_length - fade_out_length, _length]
431
432                 */
433
434         
435                 nframes_t fade_out_length = (nframes_t) _fade_out.back()->when;
436                 nframes_t fade_interval_start = max(internal_offset, _length-fade_out_length);
437                 nframes_t fade_interval_end   = min(internal_offset + to_read, _length);
438
439                 if (fade_interval_end > fade_interval_start) {
440                         /* (part of the) the fade out is  in this buffer */
441                         
442                         nframes_t limit = fade_interval_end - fade_interval_start;
443                         nframes_t curve_offset = fade_interval_start - (_length-fade_out_length);
444                         nframes_t fade_offset = fade_interval_start - internal_offset;
445                                                                        
446                         _fade_out.get_vector (curve_offset,curve_offset+limit, gain_buffer, limit);
447
448                         for (nframes_t n = 0, m = fade_offset; n < limit; ++n, ++m) {
449                                 mixdown_buffer[m] *= gain_buffer[n];
450                         }
451                 } 
452
453         }
454
455         /* Regular gain curves */
456
457         if (envelope_active())  {
458                 _envelope.get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
459                 
460                 if (_scale_amplitude != 1.0f) {
461                         for (nframes_t n = 0; n < to_read; ++n) {
462                                 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
463                         }
464                 } else {
465                         for (nframes_t n = 0; n < to_read; ++n) {
466                                 mixdown_buffer[n] *= gain_buffer[n];
467                         }
468                 }
469         } else if (_scale_amplitude != 1.0f) {
470                 Session::apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
471         }
472
473   merge:
474
475         if (!opaque()) {
476
477                 /* gack. the things we do for users.
478                  */
479
480                 buf += buf_offset;
481                 
482                 for (nframes_t n = 0; n < to_read; ++n) {
483                         buf[n] += mixdown_buffer[n];
484                 }
485         } 
486         
487         return to_read;
488 }
489         
490 XMLNode&
491 AudioRegion::state (bool full)
492 {
493         XMLNode& node (Region::state (full));
494         XMLNode *child;
495         char buf[64];
496         char buf2[64];
497         LocaleGuard lg (X_("POSIX"));
498         
499         node.add_property ("flags", enum_2_string (_flags));
500
501         snprintf (buf, sizeof(buf), "%.12g", _scale_amplitude);
502         node.add_property ("scale-gain", buf);
503
504         for (uint32_t n=0; n < _sources.size(); ++n) {
505                 snprintf (buf2, sizeof(buf2), "source-%d", n);
506                 _sources[n]->id().print (buf, sizeof (buf));
507                 node.add_property (buf2, buf);
508         }
509
510         snprintf (buf, sizeof (buf), "%u", (uint32_t) _sources.size());
511         node.add_property ("channels", buf);
512
513         if (full) {
514         
515                 child = node.add_child (X_("FadeIn"));
516                 
517                 if ((_flags & DefaultFadeIn)) {
518                         child->add_property (X_("default"), X_("yes"));
519                 } else {
520                         child->add_child_nocopy (_fade_in.get_state ());
521                 }
522
523                 child->add_property (X_("active"), _fade_in_disabled ? X_("no") : X_("yes"));
524                 
525                 child = node.add_child (X_("FadeOut"));
526                 
527                 if ((_flags & DefaultFadeOut)) {
528                         child->add_property (X_("default"), X_("yes"));
529                 } else {
530                         child->add_child_nocopy (_fade_out.get_state ());
531                 }
532                 
533                 child->add_property (X_("active"), _fade_out_disabled ? X_("no") : X_("yes"));
534         }
535         
536         child = node.add_child ("Envelope");
537
538         if (full) {
539                 bool default_env = false;
540                 
541                 // If there are only two points, the points are in the start of the region and the end of the region
542                 // so, if they are both at 1.0f, that means the default region.
543
544                 if (_envelope.size() == 2 &&
545                     _envelope.front()->value == 1.0f &&
546                     _envelope.back()->value==1.0f) {
547                         if (_envelope.front()->when == 0 && _envelope.back()->when == _length) {
548                                 default_env = true;
549                         }
550                 } 
551                 
552                 if (default_env) {
553                         child->add_property ("default", "yes");
554                 } else {
555                         child->add_child_nocopy (_envelope.get_state ());
556                 }
557
558         } else {
559                 child->add_property ("default", "yes");
560         }
561
562         if (full && _extra_xml) {
563                 node.add_child_copy (*_extra_xml);
564         }
565
566         return node;
567 }
568
569 int
570 AudioRegion::set_live_state (const XMLNode& node, Change& what_changed, bool send)
571 {
572         const XMLNodeList& nlist = node.children();
573         const XMLProperty *prop;
574         LocaleGuard lg (X_("POSIX"));
575
576         Region::set_live_state (node, what_changed, false);
577
578         uint32_t old_flags = _flags;
579                 
580         if ((prop = node.property ("flags")) != 0) {
581                 _flags = Flag (string_2_enum (prop->value(), _flags));
582
583                 //_flags = Flag (strtol (prop->value().c_str(), (char **) 0, 16));
584
585                 _flags = Flag (_flags & ~Region::LeftOfSplit);
586                 _flags = Flag (_flags & ~Region::RightOfSplit);
587         }
588
589         if ((old_flags ^ _flags) & Muted) {
590                 what_changed = Change (what_changed|MuteChanged);
591         }
592         if ((old_flags ^ _flags) & Opaque) {
593                 what_changed = Change (what_changed|OpacityChanged);
594         }
595         if ((old_flags ^ _flags) & Locked) {
596                 what_changed = Change (what_changed|LockChanged);
597         }
598
599         if ((prop = node.property ("scale-gain")) != 0) {
600                 _scale_amplitude = atof (prop->value().c_str());
601         } else {
602                 _scale_amplitude = 1.0;
603         }
604         
605         /* Now find envelope description and other misc child items */
606                                 
607         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
608                 
609                 XMLNode *child;
610                 XMLProperty *prop;
611                 
612                 child = (*niter);
613                 
614                 if (child->name() == "Envelope") {
615                         
616                         _envelope.clear ();
617
618                         if ((prop = child->property ("default")) != 0 || _envelope.set_state (*child)) {
619                                 set_default_envelope ();
620                         }
621
622                         _envelope.set_max_xval (_length);
623                         _envelope.truncate_end (_length);
624
625                 } else if (child->name() == "FadeIn") {
626                         
627                         _fade_in.clear ();
628                         
629                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0 || _fade_in.set_state (*child)) {
630                                 set_default_fade_in ();
631                         } 
632
633                 } else if (child->name() == "FadeOut") {
634                         
635                         _fade_out.clear ();
636
637                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0 || _fade_out.set_state (*child)) {
638                                 set_default_fade_out ();
639                         } 
640                 } 
641         }
642
643         if (send) {
644                 send_change (what_changed);
645         }
646
647         return 0;
648 }
649
650 int
651 AudioRegion::set_state (const XMLNode& node)
652 {
653         /* Region::set_state() calls the virtual set_live_state(),
654            which will get us back to AudioRegion::set_live_state()
655            to handle the relevant stuff.
656         */
657
658         return Region::set_state (node);
659 }
660
661 void
662 AudioRegion::set_fade_in_shape (FadeShape shape)
663 {
664         set_fade_in (shape, (nframes_t) _fade_in.back()->when);
665 }
666
667 void
668 AudioRegion::set_fade_out_shape (FadeShape shape)
669 {
670         set_fade_out (shape, (nframes_t) _fade_out.back()->when);
671 }
672
673 void
674 AudioRegion::set_fade_in (FadeShape shape, nframes_t len)
675 {
676         _fade_in.freeze ();
677         _fade_in.clear ();
678
679         switch (shape) {
680         case Linear:
681                 _fade_in.fast_simple_add (0.0, 0.0);
682                 _fade_in.fast_simple_add (len, 1.0);
683                 break;
684
685         case Fast:
686                 _fade_in.fast_simple_add (0, 0);
687                 _fade_in.fast_simple_add (len * 0.389401, 0.0333333);
688                 _fade_in.fast_simple_add (len * 0.629032, 0.0861111);
689                 _fade_in.fast_simple_add (len * 0.829493, 0.233333);
690                 _fade_in.fast_simple_add (len * 0.9447, 0.483333);
691                 _fade_in.fast_simple_add (len * 0.976959, 0.697222);
692                 _fade_in.fast_simple_add (len, 1);
693                 break;
694
695         case Slow:
696                 _fade_in.fast_simple_add (0, 0);
697                 _fade_in.fast_simple_add (len * 0.0207373, 0.197222);
698                 _fade_in.fast_simple_add (len * 0.0645161, 0.525);
699                 _fade_in.fast_simple_add (len * 0.152074, 0.802778);
700                 _fade_in.fast_simple_add (len * 0.276498, 0.919444);
701                 _fade_in.fast_simple_add (len * 0.481567, 0.980556);
702                 _fade_in.fast_simple_add (len * 0.767281, 1);
703                 _fade_in.fast_simple_add (len, 1);
704                 break;
705
706         case LogA:
707                 _fade_in.fast_simple_add (0, 0);
708                 _fade_in.fast_simple_add (len * 0.0737327, 0.308333);
709                 _fade_in.fast_simple_add (len * 0.246544, 0.658333);
710                 _fade_in.fast_simple_add (len * 0.470046, 0.886111);
711                 _fade_in.fast_simple_add (len * 0.652074, 0.972222);
712                 _fade_in.fast_simple_add (len * 0.771889, 0.988889);
713                 _fade_in.fast_simple_add (len, 1);
714                 break;
715
716         case LogB:
717                 _fade_in.fast_simple_add (0, 0);
718                 _fade_in.fast_simple_add (len * 0.304147, 0.0694444);
719                 _fade_in.fast_simple_add (len * 0.529954, 0.152778);
720                 _fade_in.fast_simple_add (len * 0.725806, 0.333333);
721                 _fade_in.fast_simple_add (len * 0.847926, 0.558333);
722                 _fade_in.fast_simple_add (len * 0.919355, 0.730556);
723                 _fade_in.fast_simple_add (len, 1);
724                 break;
725         }
726
727         _fade_in.thaw ();
728         _fade_in_shape = shape;
729
730         send_change (FadeInChanged);
731 }
732
733 void
734 AudioRegion::set_fade_out (FadeShape shape, nframes_t len)
735 {
736         _fade_out.freeze ();
737         _fade_out.clear ();
738
739         switch (shape) {
740         case Fast:
741                 _fade_out.fast_simple_add (len * 0, 1);
742                 _fade_out.fast_simple_add (len * 0.023041, 0.697222);
743                 _fade_out.fast_simple_add (len * 0.0553,   0.483333);
744                 _fade_out.fast_simple_add (len * 0.170507, 0.233333);
745                 _fade_out.fast_simple_add (len * 0.370968, 0.0861111);
746                 _fade_out.fast_simple_add (len * 0.610599, 0.0333333);
747                 _fade_out.fast_simple_add (len * 1, 0);
748                 break;
749
750         case LogA:
751                 _fade_out.fast_simple_add (len * 0, 1);
752                 _fade_out.fast_simple_add (len * 0.228111, 0.988889);
753                 _fade_out.fast_simple_add (len * 0.347926, 0.972222);
754                 _fade_out.fast_simple_add (len * 0.529954, 0.886111);
755                 _fade_out.fast_simple_add (len * 0.753456, 0.658333);
756                 _fade_out.fast_simple_add (len * 0.9262673, 0.308333);
757                 _fade_out.fast_simple_add (len * 1, 0);
758                 break;
759
760         case Slow:
761                 _fade_out.fast_simple_add (len * 0, 1);
762                 _fade_out.fast_simple_add (len * 0.305556, 1);
763                 _fade_out.fast_simple_add (len * 0.548611, 0.991736);
764                 _fade_out.fast_simple_add (len * 0.759259, 0.931129);
765                 _fade_out.fast_simple_add (len * 0.918981, 0.68595);
766                 _fade_out.fast_simple_add (len * 0.976852, 0.22865);
767                 _fade_out.fast_simple_add (len * 1, 0);
768                 break;
769
770         case LogB:
771                 _fade_out.fast_simple_add (len * 0, 1);
772                 _fade_out.fast_simple_add (len * 0.080645, 0.730556);
773                 _fade_out.fast_simple_add (len * 0.277778, 0.289256);
774                 _fade_out.fast_simple_add (len * 0.470046, 0.152778);
775                 _fade_out.fast_simple_add (len * 0.695853, 0.0694444);
776                 _fade_out.fast_simple_add (len * 1, 0);
777                 break;
778
779         case Linear:
780                 _fade_out.fast_simple_add (len * 0, 1);
781                 _fade_out.fast_simple_add (len * 1, 0);
782                 break;
783         }
784
785         _fade_out.thaw ();
786         _fade_out_shape = shape;
787
788         send_change (FadeOutChanged);
789 }
790
791 void
792 AudioRegion::set_fade_in_length (nframes_t len)
793 {
794         bool changed = _fade_in.extend_to (len);
795
796         if (changed) {
797                 _flags = Flag (_flags & ~DefaultFadeIn);
798                 send_change (FadeInChanged);
799         }
800 }
801
802 void
803 AudioRegion::set_fade_out_length (nframes_t len)
804 {
805         bool changed =  _fade_out.extend_to (len);
806
807         if (changed) {
808                 _flags = Flag (_flags & ~DefaultFadeOut);
809         }
810
811         send_change (FadeOutChanged);
812 }
813
814 void
815 AudioRegion::set_fade_in_active (bool yn)
816 {
817         if (yn == (_flags & FadeIn)) {
818                 return;
819         }
820         if (yn) {
821                 _flags = Flag (_flags|FadeIn);
822         } else {
823                 _flags = Flag (_flags & ~FadeIn);
824         }
825
826         send_change (FadeInActiveChanged);
827 }
828
829 void
830 AudioRegion::set_fade_out_active (bool yn)
831 {
832         if (yn == (_flags & FadeOut)) {
833                 return;
834         }
835         if (yn) {
836                 _flags = Flag (_flags | FadeOut);
837         } else {
838                 _flags = Flag (_flags & ~FadeOut);
839         }
840
841         send_change (FadeOutActiveChanged);
842 }
843
844 bool
845 AudioRegion::fade_in_is_default () const
846 {
847         return _fade_in_shape == Linear && _fade_in.back()->when == 64;
848 }
849
850 bool
851 AudioRegion::fade_out_is_default () const
852 {
853         return _fade_out_shape == Linear && _fade_out.back()->when == 64;
854 }
855
856 void
857 AudioRegion::set_default_fade_in ()
858 {
859         set_fade_in (Linear, 64);
860 }
861
862 void
863 AudioRegion::set_default_fade_out ()
864 {
865         set_fade_out (Linear, 64);
866 }
867
868 void
869 AudioRegion::set_default_fades ()
870 {
871         _fade_in_disabled = 0;
872         _fade_out_disabled = 0;
873         set_default_fade_in ();
874         set_default_fade_out ();
875 }
876
877 void
878 AudioRegion::set_default_envelope ()
879 {
880         _envelope.freeze ();
881         _envelope.clear ();
882         _envelope.fast_simple_add (0, 1.0f);
883         _envelope.fast_simple_add (_length, 1.0f);
884         _envelope.thaw ();
885 }
886
887 void
888 AudioRegion::recompute_at_end ()
889 {
890         /* our length has changed. recompute a new final point by interpolating 
891            based on the the existing curve.
892         */
893         
894         _envelope.freeze ();
895         _envelope.truncate_end (_length);
896         _envelope.set_max_xval (_length);
897         _envelope.thaw ();
898
899         if (_fade_in.back()->when > _length) {
900                 _fade_in.extend_to (_length);
901                 send_change (FadeInChanged);
902         }
903
904         if (_fade_out.back()->when > _length) {
905                 _fade_out.extend_to (_length);
906                 send_change (FadeOutChanged);
907         }
908 }       
909
910 void
911 AudioRegion::recompute_at_start ()
912 {
913         /* as above, but the shift was from the front */
914
915         _envelope.truncate_start (_length);
916
917         if (_fade_in.back()->when > _length) {
918                 _fade_in.extend_to (_length);
919                 send_change (FadeInChanged);
920         }
921
922         if (_fade_out.back()->when > _length) {
923                 _fade_out.extend_to (_length);
924                 send_change (FadeOutChanged);
925         }
926 }
927
928 int
929 AudioRegion::separate_by_channel (Session& session, vector<boost::shared_ptr<AudioRegion> >& v) const
930 {
931         SourceList srcs;
932         string new_name;
933         int n;
934
935         if (_sources.size() < 2) {
936                 return 0;
937         }
938
939         n = 0;
940
941         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
942
943                 srcs.clear ();
944                 srcs.push_back (*i);
945
946                 new_name = _name;
947
948                 if (_sources.size() == 2) {
949                         if (n == 0) {
950                                 new_name += "-L";
951                         } else {
952                                 new_name += "-R";
953                         }
954                 } else {
955                         new_name += '-';
956                         new_name += ('0' + n + 1);
957                 }
958
959                 /* create a copy with just one source. prevent if from being thought of as "whole file" even if 
960                    it covers the entire source file(s).
961                  */
962
963                 Flag f = Flag (_flags & ~WholeFile);
964
965                 boost::shared_ptr<Region> r = RegionFactory::create (srcs, _start, _length, new_name, _layer, f);
966                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (r);
967
968                 v.push_back (ar);
969                 
970                 ++n;
971         }
972
973         return 0;
974 }
975
976 int
977 AudioRegion::apply (AudioFilter& filter)
978 {
979         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (shared_from_this());
980         return filter.run (ar);
981 }
982
983 int
984 AudioRegion::exportme (Session& session, AudioExportSpecification& spec)
985 {
986         const nframes_t blocksize = 4096;
987         nframes_t to_read;
988         int status = -1;
989
990         spec.channels = _sources.size();
991
992         if (spec.prepare (blocksize, session.frame_rate())) {
993                 goto out;
994         }
995
996         spec.pos = 0;
997         spec.total_frames = _length;
998
999         while (spec.pos < _length && !spec.stop) {
1000                 
1001                 
1002                 /* step 1: interleave */
1003                 
1004                 to_read = min (_length - spec.pos, blocksize);
1005                 
1006                 if (spec.channels == 1) {
1007
1008                         if (audio_source()->read (spec.dataF, _start + spec.pos, to_read) != to_read) {
1009                                 goto out;
1010                         }
1011
1012                 } else {
1013
1014                         Sample buf[blocksize];
1015
1016                         for (uint32_t chan = 0; chan < spec.channels; ++chan) {
1017                                 
1018                                 if (audio_source(chan)->read (buf, _start + spec.pos, to_read) != to_read) {
1019                                         goto out;
1020                                 }
1021                                 
1022                                 for (nframes_t x = 0; x < to_read; ++x) {
1023                                         spec.dataF[chan+(x*spec.channels)] = buf[x];
1024                                 }
1025                         }
1026                 }
1027                 
1028                 if (spec.process (to_read)) {
1029                         goto out;
1030                 }
1031                 
1032                 spec.pos += to_read;
1033                 spec.progress = (double) spec.pos /_length;
1034                 
1035         }
1036         
1037         status = 0;
1038
1039   out:  
1040         spec.running = false;
1041         spec.status = status;
1042         spec.clear();
1043         
1044         return status;
1045 }
1046
1047 void
1048 AudioRegion::set_scale_amplitude (gain_t g)
1049 {
1050         boost::shared_ptr<Playlist> pl (playlist());
1051
1052         _scale_amplitude = g;
1053
1054         /* tell the diskstream we're in */
1055         
1056         if (pl) {
1057                 pl->Modified();
1058         }
1059
1060         /* tell everybody else */
1061
1062         send_change (ScaleAmplitudeChanged);
1063 }
1064
1065 void
1066 AudioRegion::normalize_to (float target_dB)
1067 {
1068         const nframes_t blocksize = 64 * 1024;
1069         Sample buf[blocksize];
1070         nframes_t fpos;
1071         nframes_t fend;
1072         nframes_t to_read;
1073         double maxamp = 0;
1074         gain_t target = dB_to_coefficient (target_dB);
1075
1076         if (target == 1.0f) {
1077                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1078                    that we may have clipped.
1079                 */
1080                 target -= FLT_EPSILON;
1081         }
1082
1083         fpos = _start;
1084         fend = _start + _length;
1085
1086         /* first pass: find max amplitude */
1087
1088         while (fpos < fend) {
1089
1090                 uint32_t n;
1091
1092                 to_read = min (fend - fpos, blocksize);
1093
1094                 for (n = 0; n < n_channels(); ++n) {
1095
1096                         /* read it in */
1097
1098                         if (audio_source (n)->read (buf, fpos, to_read) != to_read) {
1099                                 return;
1100                         }
1101                         
1102                         maxamp = Session::compute_peak (buf, to_read, maxamp);
1103                 }
1104
1105                 fpos += to_read;
1106         };
1107
1108         if (maxamp == 0.0f) {
1109                 /* don't even try */
1110                 return;
1111         }
1112
1113         if (maxamp == target) {
1114                 /* we can't do anything useful */
1115                 return;
1116         }
1117
1118         /* compute scale factor */
1119
1120         _scale_amplitude = target/maxamp;
1121
1122         /* tell the diskstream we're in */
1123
1124         boost::shared_ptr<Playlist> pl (playlist());
1125
1126         if (pl) {
1127                 pl->Modified();
1128         }
1129
1130         /* tell everybody else */
1131
1132         send_change (ScaleAmplitudeChanged);
1133 }
1134
1135 void
1136 AudioRegion::fade_in_changed ()
1137 {
1138         send_change (FadeInChanged);
1139 }
1140
1141 void
1142 AudioRegion::fade_out_changed ()
1143 {
1144         send_change (FadeOutChanged);
1145 }
1146
1147 void
1148 AudioRegion::envelope_changed ()
1149 {
1150         send_change (EnvelopeChanged);
1151 }
1152
1153 void
1154 AudioRegion::suspend_fade_in ()
1155 {
1156         if (++_fade_in_disabled == 1) {
1157                 if (fade_in_is_default()) {
1158                         set_fade_in_active (false);
1159                 }
1160         }
1161 }
1162
1163 void
1164 AudioRegion::resume_fade_in ()
1165 {
1166         if (--_fade_in_disabled == 0 && _fade_in_disabled) {
1167                 set_fade_in_active (true);
1168         }
1169 }
1170
1171 void
1172 AudioRegion::suspend_fade_out ()
1173 {
1174         if (++_fade_out_disabled == 1) {
1175                 if (fade_out_is_default()) {
1176                         set_fade_out_active (false);
1177                 }
1178         }
1179 }
1180
1181 void
1182 AudioRegion::resume_fade_out ()
1183 {
1184         if (--_fade_out_disabled == 0 &&_fade_out_disabled) {
1185                 set_fade_out_active (true);
1186         }
1187 }
1188
1189 bool
1190 AudioRegion::speed_mismatch (float sr) const
1191 {
1192         if (_sources.empty()) {
1193                 /* impossible, but ... */
1194                 return false;
1195         }
1196
1197         float fsr = audio_source()->sample_rate();
1198
1199         return fsr != sr;
1200 }
1201
1202 void
1203 AudioRegion::source_offset_changed ()
1204 {
1205         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1206
1207         if (afs && afs->destructive()) {
1208                 // set_start (source()->natural_position(), this);
1209                 set_position (source()->natural_position(), this);
1210         } 
1211 }
1212
1213 boost::shared_ptr<AudioSource>
1214 AudioRegion::audio_source (uint32_t n) const
1215 {
1216         // Guaranteed to succeed (use a static cast for speed?)
1217         return boost::dynamic_pointer_cast<AudioSource>(source(n));
1218 }
1219
1220 extern "C" {
1221
1222         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) 
1223 {
1224         return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (nframes_t) npeaks, (nframes_t) start, (nframes_t) cnt, n_chan,samples_per_unit);
1225 }
1226
1227 uint32_t region_length_from_c (void *arg)
1228 {
1229
1230         return ((AudioRegion *) arg)->length();
1231 }
1232
1233 uint32_t sourcefile_length_from_c (void *arg, double zoom_factor)
1234 {
1235         return ( (AudioRegion *) arg)->audio_source()->available_peaks (zoom_factor) ;
1236 }
1237
1238 } /* extern "C" */