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