add control port to ardour.rc.in and fix crash bug caused by bad shared_ptr<Region...
[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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 (mem_fun (*this, &AudioRegion::source_deleted));
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 ()
1121 {
1122         sources.clear ();
1123         drop_references ();
1124 }
1125
1126 vector<string>
1127 AudioRegion::master_source_names ()
1128 {
1129         SourceList::iterator i;
1130
1131         vector<string> names;
1132         for (i = master_sources.begin(); i != master_sources.end(); ++i) {
1133                 names.push_back((*i)->name());
1134         }
1135
1136         return names;
1137 }
1138
1139 bool
1140 AudioRegion::source_equivalent (boost::shared_ptr<const Region> o) const
1141 {
1142         boost::shared_ptr<const AudioRegion> other = boost::dynamic_pointer_cast<const AudioRegion>(o);
1143
1144         if (!other)
1145                 return false;
1146
1147         SourceList::const_iterator i;
1148         SourceList::const_iterator io;
1149
1150         for (i = sources.begin(), io = other->sources.begin(); i != sources.end() && io != other->sources.end(); ++i, ++io) {
1151                 if ((*i)->id() != (*io)->id()) {
1152                         return false;
1153                 }
1154         }
1155
1156         for (i = master_sources.begin(), io = other->master_sources.begin(); i != master_sources.end() && io != other->master_sources.end(); ++i, ++io) {
1157                 if ((*i)->id() != (*io)->id()) {
1158                         return false;
1159                 }
1160         }
1161
1162         return true;
1163 }
1164
1165 int
1166 AudioRegion::apply (AudioFilter& filter)
1167 {
1168         return filter.run (boost::shared_ptr<AudioRegion> (this));
1169 }
1170
1171 int
1172 AudioRegion::exportme (Session& session, AudioExportSpecification& spec)
1173 {
1174         const nframes_t blocksize = 4096;
1175         nframes_t to_read;
1176         int status = -1;
1177
1178         spec.channels = sources.size();
1179
1180         if (spec.prepare (blocksize, session.frame_rate())) {
1181                 goto out;
1182         }
1183
1184         spec.pos = 0;
1185         spec.total_frames = _length;
1186
1187         while (spec.pos < _length && !spec.stop) {
1188                 
1189                 
1190                 /* step 1: interleave */
1191                 
1192                 to_read = min (_length - spec.pos, blocksize);
1193                 
1194                 if (spec.channels == 1) {
1195
1196                         if (sources.front()->read (spec.dataF, _start + spec.pos, to_read) != to_read) {
1197                                 goto out;
1198                         }
1199
1200                 } else {
1201
1202                         Sample buf[blocksize];
1203
1204                         for (uint32_t chan = 0; chan < spec.channels; ++chan) {
1205                                 
1206                                 if (sources[chan]->read (buf, _start + spec.pos, to_read) != to_read) {
1207                                         goto out;
1208                                 }
1209                                 
1210                                 for (nframes_t x = 0; x < to_read; ++x) {
1211                                         spec.dataF[chan+(x*spec.channels)] = buf[x];
1212                                 }
1213                         }
1214                 }
1215                 
1216                 if (spec.process (to_read)) {
1217                         goto out;
1218                 }
1219                 
1220                 spec.pos += to_read;
1221                 spec.progress = (double) spec.pos /_length;
1222                 
1223         }
1224         
1225         status = 0;
1226
1227   out:  
1228         spec.running = false;
1229         spec.status = status;
1230         spec.clear();
1231         
1232         return status;
1233 }
1234
1235 boost::shared_ptr<Region>
1236 AudioRegion::get_parent()
1237 {
1238         boost::shared_ptr<Region> r;
1239
1240         if (_playlist) {
1241                 boost::shared_ptr<AudioRegion> ar;
1242                 boost::shared_ptr<AudioRegion> grrr2 = boost::dynamic_pointer_cast<AudioRegion> (shared_from_this());
1243                 
1244                 if (grrr2 && (ar = _playlist->session().find_whole_file_parent (grrr2))) {
1245                         return boost::static_pointer_cast<Region> (ar);
1246                 }
1247         }
1248         
1249         return r;
1250 }
1251
1252 void
1253 AudioRegion::set_scale_amplitude (gain_t g)
1254 {
1255         _scale_amplitude = g;
1256
1257         /* tell the diskstream we're in */
1258
1259         if (_playlist) {
1260                 _playlist->Modified();
1261         }
1262
1263         /* tell everybody else */
1264
1265         send_change (ScaleAmplitudeChanged);
1266 }
1267
1268 void
1269 AudioRegion::normalize_to (float target_dB)
1270 {
1271         const nframes_t blocksize = 64 * 1024;
1272         Sample buf[blocksize];
1273         nframes_t fpos;
1274         nframes_t fend;
1275         nframes_t to_read;
1276         double maxamp = 0;
1277         gain_t target = dB_to_coefficient (target_dB);
1278
1279         if (target == 1.0f) {
1280                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1281                    that we may have clipped.
1282                 */
1283                 target -= FLT_EPSILON;
1284         }
1285
1286         fpos = _start;
1287         fend = _start + _length;
1288
1289         /* first pass: find max amplitude */
1290
1291         while (fpos < fend) {
1292
1293                 uint32_t n;
1294
1295                 to_read = min (fend - fpos, blocksize);
1296
1297                 for (n = 0; n < n_channels(); ++n) {
1298
1299                         /* read it in */
1300
1301                         if (source (n)->read (buf, fpos, to_read) != to_read) {
1302                                 return;
1303                         }
1304                         
1305                         maxamp = Session::compute_peak (buf, to_read, maxamp);
1306                 }
1307
1308                 fpos += to_read;
1309         };
1310
1311         if (maxamp == 0.0f) {
1312                 /* don't even try */
1313                 return;
1314         }
1315
1316         if (maxamp == target) {
1317                 /* we can't do anything useful */
1318                 return;
1319         }
1320
1321         /* compute scale factor */
1322
1323         _scale_amplitude = target/maxamp;
1324
1325         if (!_frozen) {
1326                 char buf[64];
1327                 snprintf (buf, sizeof (buf), _("normalized to %.2fdB"), target_dB);
1328                 save_state (buf);
1329         }
1330
1331         /* tell the diskstream we're in */
1332
1333         if (_playlist) {
1334                 _playlist->Modified();
1335         }
1336
1337         /* tell everybody else */
1338
1339         send_change (ScaleAmplitudeChanged);
1340 }
1341
1342 void
1343 AudioRegion::envelope_changed (Change ignored)
1344 {
1345         save_state (_("envelope change"));
1346         send_change (EnvelopeChanged);
1347 }
1348
1349 void
1350 AudioRegion::suspend_fade_in ()
1351 {
1352         if (++_fade_in_disabled == 1) {
1353                 set_fade_in_active (false);
1354         }
1355 }
1356
1357 void
1358 AudioRegion::resume_fade_in ()
1359 {
1360         if (_fade_in_disabled && --_fade_in_disabled == 0) {
1361                 set_fade_in_active (true);
1362         }
1363 }
1364
1365 void
1366 AudioRegion::suspend_fade_out ()
1367 {
1368         if (++_fade_out_disabled == 1) {
1369                 set_fade_out_active (false);
1370         }
1371 }
1372
1373 void
1374 AudioRegion::resume_fade_out ()
1375 {
1376         if (_fade_out_disabled && --_fade_out_disabled == 0) {
1377                 set_fade_out_active (true);
1378         }
1379 }
1380
1381 bool
1382 AudioRegion::speed_mismatch (float sr) const
1383 {
1384         if (sources.empty()) {
1385                 /* impossible, but ... */
1386                 return false;
1387         }
1388
1389         float fsr = sources.front()->sample_rate();
1390
1391         return fsr != sr;
1392 }
1393
1394 void
1395 AudioRegion::source_offset_changed ()
1396 {
1397         if (boost::dynamic_pointer_cast<DestructiveFileSource>(sources.front())) {
1398                 set_start (source()->natural_position(), this);
1399                 set_position (source()->natural_position(), this);
1400         } 
1401 }
1402
1403 extern "C" {
1404
1405         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) 
1406 {
1407         return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (nframes_t) npeaks, (nframes_t) start, (nframes_t) cnt, n_chan,samples_per_unit);
1408 }
1409
1410 uint32_t region_length_from_c (void *arg)
1411 {
1412
1413         return ((AudioRegion *) arg)->length();
1414 }
1415
1416 uint32_t sourcefile_length_from_c (void *arg, double zoom_factor)
1417 {
1418         return ( (AudioRegion *) arg)->source()->available_peaks (zoom_factor) ;
1419 }
1420
1421 } /* extern "C" */