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