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