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