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