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