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