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