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