merged with 1697 revision of trunk (which is post-rc1 but pre-rc2
[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 */
19
20 #include <cmath>
21 #include <climits>
22 #include <cfloat>
23
24 #include <set>
25
26 #include <sigc++/bind.h>
27 #include <sigc++/class_slot.h>
28
29 #include <glibmm/thread.h>
30
31 #include <pbd/basename.h>
32 #include <pbd/xml++.h>
33 #include <pbd/stacktrace.h>
34 #include <pbd/enumwriter.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/region_factory.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         listen_to_my_curves ();
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         listen_to_my_curves ();
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         listen_to_my_curves ();
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         listen_to_my_curves ();
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         listen_to_my_curves ();
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         listen_to_my_curves ();
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         listen_to_my_curves ();
305 }
306
307 AudioRegion::~AudioRegion ()
308 {
309         boost::shared_ptr<Playlist> pl (playlist());
310
311         if (pl) {
312                 for (SourceList::const_iterator i = sources.begin(); i != sources.end(); ++i) {
313                         (*i)->remove_playlist (pl);
314                 }
315         }
316
317         notify_callbacks ();
318         GoingAway (); /* EMIT SIGNAL */
319 }
320
321 void
322 AudioRegion::listen_to_my_curves ()
323 {
324         _envelope.StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
325         _fade_in.StateChanged.connect (mem_fun (*this, &AudioRegion::fade_in_changed));
326         _fade_out.StateChanged.connect (mem_fun (*this, &AudioRegion::fade_out_changed));
327 }
328
329 bool
330 AudioRegion::verify_length (nframes_t len)
331 {
332         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source());
333
334         if (afs && afs->destructive()) {
335                 return true;
336         }
337
338         for (uint32_t n=0; n < sources.size(); ++n) {
339                 if (_start > sources[n]->length() - len) {
340                         return false;
341                 }
342         }
343         return true;
344 }
345
346 bool
347 AudioRegion::verify_start_and_length (nframes_t new_start, nframes_t new_length)
348 {
349         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source());
350
351         if (afs && afs->destructive()) {
352                 return true;
353         }
354
355         for (uint32_t n=0; n < sources.size(); ++n) {
356                 if (new_length > sources[n]->length() - new_start) {
357                         return false;
358                 }
359         }
360         return true;
361 }
362 bool
363 AudioRegion::verify_start (nframes_t pos)
364 {
365         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source());
366
367         if (afs && afs->destructive()) {
368                 return true;
369         }
370
371         for (uint32_t n=0; n < sources.size(); ++n) {
372                 if (pos > sources[n]->length() - _length) {
373                         return false;
374                 }
375         }
376         return true;
377 }
378
379 bool
380 AudioRegion::verify_start_mutable (nframes_t& new_start)
381 {
382         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source());
383
384         if (afs && afs->destructive()) {
385                 return true;
386         }
387
388         for (uint32_t n=0; n < sources.size(); ++n) {
389                 if (new_start > sources[n]->length() - _length) {
390                         new_start = sources[n]->length() - _length;
391                 }
392         }
393         return true;
394 }
395 void
396 AudioRegion::set_envelope_active (bool yn)
397 {
398         if (envelope_active() != yn) {
399                 char buf[64];
400                 if (yn) {
401                         snprintf (buf, sizeof (buf), "envelope active");
402                         _flags = Flag (_flags|EnvelopeActive);
403                 } else {
404                         snprintf (buf, sizeof (buf), "envelope off");
405                         _flags = Flag (_flags & ~EnvelopeActive);
406                 }
407                 send_change (EnvelopeActiveChanged);
408         }
409 }
410
411 nframes_t
412 AudioRegion::read_peaks (PeakData *buf, nframes_t npeaks, nframes_t offset, nframes_t cnt, uint32_t chan_n, double samples_per_unit) const
413 {
414         if (chan_n >= sources.size()) {
415                 return 0; 
416         }
417
418         if (sources[chan_n]->read_peaks (buf, npeaks, offset, cnt, samples_per_unit)) {
419                 return 0;
420         } else {
421                 if (_scale_amplitude != 1.0) {
422                         for (nframes_t n = 0; n < npeaks; ++n) {
423                                 buf[n].max *= _scale_amplitude;
424                                 buf[n].min *= _scale_amplitude;
425                         }
426                 }
427                 return cnt;
428         }
429 }
430
431 nframes_t
432 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer, nframes_t position, 
433                       nframes_t cnt, 
434                       uint32_t chan_n, nframes_t read_frames, nframes_t skip_frames) const
435 {
436         return _read_at (sources, buf, mixdown_buffer, gain_buffer, position, cnt, chan_n, read_frames, skip_frames);
437 }
438
439 nframes_t
440 AudioRegion::master_read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer, nframes_t position, 
441                              nframes_t cnt, uint32_t chan_n) const
442 {
443         return _read_at (master_sources, buf, mixdown_buffer, gain_buffer, position, cnt, chan_n, 0, 0);
444 }
445
446 nframes_t
447 AudioRegion::_read_at (const SourceList& srcs, Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
448                        nframes_t position, nframes_t cnt, 
449                        uint32_t chan_n, nframes_t read_frames, nframes_t skip_frames) const
450 {
451         nframes_t internal_offset;
452         nframes_t buf_offset;
453         nframes_t to_read;
454
455         if (muted()) {
456                 return 0; /* read nothing */
457         }
458
459         /* precondition: caller has verified that we cover the desired section */
460
461         if (position < _position) {
462                 internal_offset = 0;
463                 buf_offset = _position - position;
464                 cnt -= buf_offset;
465         } else {
466                 internal_offset = position - _position;
467                 buf_offset = 0;
468         }
469
470         if (internal_offset >= _length) {
471                 return 0; /* read nothing */
472         }
473
474         if ((to_read = min (cnt, _length - internal_offset)) == 0) {
475                 return 0; /* read nothing */
476         }
477
478         if (opaque()) {
479                 /* overwrite whatever is there */
480                 mixdown_buffer = buf + buf_offset;
481         } else {
482                 mixdown_buffer += buf_offset;
483         }
484
485         _read_data_count = 0;
486
487         if (chan_n < n_channels()) {
488
489                 if (srcs[chan_n]->read (mixdown_buffer, _start + internal_offset, to_read) != to_read) {
490                         
491                         return 0; /* "read nothing" */
492                 }
493                 
494                 _read_data_count += srcs[chan_n]->read_data_count();
495
496         } else {
497                 
498                 /* track is N-channel, this region has less channels; silence the ones
499                    we don't have.
500                 */
501
502                 memset (mixdown_buffer, 0, sizeof (Sample) * cnt);
503
504                 /* no fades required */
505
506                 goto merge;
507         }
508
509         /* fade in */
510
511         if (_flags & FadeIn) {
512
513                 nframes_t fade_in_length = (nframes_t) _fade_in.back()->when;
514                 
515                 /* see if this read is within the fade in */
516
517                 if (internal_offset < fade_in_length) {
518                 
519                         nframes_t limit;
520
521                         limit = min (to_read, fade_in_length - internal_offset);
522
523                         _fade_in.get_vector (internal_offset, internal_offset+limit, gain_buffer, limit);
524
525                         for (nframes_t n = 0; n < limit; ++n) {
526                                 mixdown_buffer[n] *= gain_buffer[n];
527                         }
528                 }
529         }
530         
531         /* fade out */
532
533         if (_flags & FadeOut) {
534         
535                 /* see if some part of this read is within the fade out */
536
537                 /* .................        >|            REGION
538                                             _length
539                                             
540                                  {           }            FADE
541                                              fade_out_length
542                                  ^                                           
543                                _length - fade_out_length
544                         |--------------|
545                         ^internal_offset
546                                        ^internal_offset + to_read
547
548                   we need the intersection of [internal_offset,internal_offset+to_read] with
549                   [_length - fade_out_length, _length]
550
551                 */
552
553         
554                 nframes_t fade_out_length = (nframes_t) _fade_out.back()->when;
555                 nframes_t fade_interval_start = max(internal_offset, _length-fade_out_length);
556                 nframes_t fade_interval_end   = min(internal_offset + to_read, _length);
557
558                 if (fade_interval_end > fade_interval_start) {
559                         /* (part of the) the fade out is  in this buffer */
560                         
561                         nframes_t limit = fade_interval_end - fade_interval_start;
562                         nframes_t curve_offset = fade_interval_start - (_length-fade_out_length);
563                         nframes_t fade_offset = fade_interval_start - internal_offset;
564                                                                        
565                         _fade_out.get_vector (curve_offset,curve_offset+limit, gain_buffer, limit);
566
567                         for (nframes_t n = 0, m = fade_offset; n < limit; ++n, ++m) {
568                                 mixdown_buffer[m] *= gain_buffer[n];
569                         }
570                 } 
571
572         }
573
574         /* Regular gain curves */
575
576         if (envelope_active())  {
577                 _envelope.get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
578                 
579                 if (_scale_amplitude != 1.0f) {
580                         for (nframes_t n = 0; n < to_read; ++n) {
581                                 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
582                         }
583                 } else {
584                         for (nframes_t n = 0; n < to_read; ++n) {
585                                 mixdown_buffer[n] *= gain_buffer[n];
586                         }
587                 }
588         } else if (_scale_amplitude != 1.0f) {
589                 Session::apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
590         }
591
592   merge:
593
594         if (!opaque()) {
595
596                 /* gack. the things we do for users.
597                  */
598
599                 buf += buf_offset;
600                 
601                 for (nframes_t n = 0; n < to_read; ++n) {
602                         buf[n] += mixdown_buffer[n];
603                 }
604         } 
605         
606         return to_read;
607 }
608         
609 XMLNode&
610 AudioRegion::state (bool full)
611 {
612         XMLNode& node (Region::state (full));
613         XMLNode *child;
614         char buf[64];
615         char buf2[64];
616         LocaleGuard lg (X_("POSIX"));
617         
618         node.add_property ("flags", enum_2_string (_flags));
619
620         snprintf (buf, sizeof(buf), "%.12g", _scale_amplitude);
621         node.add_property ("scale-gain", buf);
622
623         for (uint32_t n=0; n < sources.size(); ++n) {
624                 snprintf (buf2, sizeof(buf2), "source-%d", n);
625                 sources[n]->id().print (buf, sizeof (buf));
626                 node.add_property (buf2, buf);
627         }
628
629         snprintf (buf, sizeof (buf), "%u", (uint32_t) sources.size());
630         node.add_property ("channels", buf);
631
632         if (full) {
633         
634                 child = node.add_child (X_("FadeIn"));
635                 
636                 if ((_flags & DefaultFadeIn)) {
637                         child->add_property (X_("default"), X_("yes"));
638                 } else {
639                         child->add_child_nocopy (_fade_in.get_state ());
640                 }
641
642                 child->add_property (X_("active"), _fade_in_disabled ? X_("no") : X_("yes"));
643                 
644                 child = node.add_child (X_("FadeOut"));
645                 
646                 if ((_flags & DefaultFadeOut)) {
647                         child->add_property (X_("default"), X_("yes"));
648                 } else {
649                         child->add_child_nocopy (_fade_out.get_state ());
650                 }
651                 
652                 child->add_property (X_("active"), _fade_out_disabled ? X_("no") : X_("yes"));
653         }
654         
655         child = node.add_child ("Envelope");
656
657         if (full) {
658                 bool default_env = false;
659                 
660                 // If there are only two points, the points are in the start of the region and the end of the region
661                 // so, if they are both at 1.0f, that means the default region.
662
663                 if (_envelope.size() == 2 &&
664                     _envelope.front()->value == 1.0f &&
665                     _envelope.back()->value==1.0f) {
666                         if (_envelope.front()->when == 0 && _envelope.back()->when == _length) {
667                                 default_env = true;
668                         }
669                 } 
670                 
671                 if (default_env) {
672                         child->add_property ("default", "yes");
673                 } else {
674                         child->add_child_nocopy (_envelope.get_state ());
675                 }
676
677         } else {
678                 child->add_property ("default", "yes");
679         }
680
681         if (full && _extra_xml) {
682                 node.add_child_copy (*_extra_xml);
683         }
684
685         return node;
686 }
687
688 int
689 AudioRegion::set_live_state (const XMLNode& node, Change& what_changed, bool send)
690 {
691         const XMLNodeList& nlist = node.children();
692         const XMLProperty *prop;
693         LocaleGuard lg (X_("POSIX"));
694
695         Region::set_live_state (node, what_changed, false);
696
697         uint32_t old_flags = _flags;
698                 
699         if ((prop = node.property ("flags")) != 0) {
700                 _flags = Flag (string_2_enum (prop->value(), _flags));
701
702                 //_flags = Flag (strtol (prop->value().c_str(), (char **) 0, 16));
703
704                 _flags = Flag (_flags & ~Region::LeftOfSplit);
705                 _flags = Flag (_flags & ~Region::RightOfSplit);
706         }
707
708         if ((old_flags ^ _flags) & Muted) {
709                 what_changed = Change (what_changed|MuteChanged);
710         }
711         if ((old_flags ^ _flags) & Opaque) {
712                 what_changed = Change (what_changed|OpacityChanged);
713         }
714         if ((old_flags ^ _flags) & Locked) {
715                 what_changed = Change (what_changed|LockChanged);
716         }
717
718         if ((prop = node.property ("scale-gain")) != 0) {
719                 _scale_amplitude = atof (prop->value().c_str());
720         } else {
721                 _scale_amplitude = 1.0;
722         }
723         
724         /* Now find envelope description and other misc child items */
725                                 
726         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
727                 
728                 XMLNode *child;
729                 XMLProperty *prop;
730                 
731                 child = (*niter);
732                 
733                 if (child->name() == "Envelope") {
734                         
735                         _envelope.clear ();
736
737                         if ((prop = child->property ("default")) != 0 || _envelope.set_state (*child)) {
738                                 set_default_envelope ();
739                         }
740
741                         _envelope.set_max_xval (_length);
742                         _envelope.truncate_end (_length);
743
744                 } else if (child->name() == "FadeIn") {
745                         
746                         _fade_in.clear ();
747                         
748                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0 || _fade_in.set_state (*child)) {
749                                 set_default_fade_in ();
750                         } 
751
752                 } else if (child->name() == "FadeOut") {
753                         
754                         _fade_out.clear ();
755
756                         if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0 || _fade_out.set_state (*child)) {
757                                 set_default_fade_out ();
758                         } 
759                 } 
760         }
761
762         if (send) {
763                 send_change (what_changed);
764         }
765
766         return 0;
767 }
768
769 int
770 AudioRegion::set_state (const XMLNode& node)
771 {
772         /* Region::set_state() calls the virtual set_live_state(),
773            which will get us back to AudioRegion::set_live_state()
774            to handle the relevant stuff.
775         */
776
777         return Region::set_state (node);
778 }
779
780 void
781 AudioRegion::set_fade_in_shape (FadeShape shape)
782 {
783         set_fade_in (shape, (nframes_t) _fade_in.back()->when);
784 }
785
786 void
787 AudioRegion::set_fade_out_shape (FadeShape shape)
788 {
789         set_fade_out (shape, (nframes_t) _fade_out.back()->when);
790 }
791
792 void
793 AudioRegion::set_fade_in (FadeShape shape, nframes_t len)
794 {
795         _fade_in.freeze ();
796         _fade_in.clear ();
797
798         switch (shape) {
799         case Linear:
800                 _fade_in.fast_simple_add (0.0, 0.0);
801                 _fade_in.fast_simple_add (len, 1.0);
802                 break;
803
804         case Fast:
805                 _fade_in.fast_simple_add (0, 0);
806                 _fade_in.fast_simple_add (len * 0.389401, 0.0333333);
807                 _fade_in.fast_simple_add (len * 0.629032, 0.0861111);
808                 _fade_in.fast_simple_add (len * 0.829493, 0.233333);
809                 _fade_in.fast_simple_add (len * 0.9447, 0.483333);
810                 _fade_in.fast_simple_add (len * 0.976959, 0.697222);
811                 _fade_in.fast_simple_add (len, 1);
812                 break;
813
814         case Slow:
815                 _fade_in.fast_simple_add (0, 0);
816                 _fade_in.fast_simple_add (len * 0.0207373, 0.197222);
817                 _fade_in.fast_simple_add (len * 0.0645161, 0.525);
818                 _fade_in.fast_simple_add (len * 0.152074, 0.802778);
819                 _fade_in.fast_simple_add (len * 0.276498, 0.919444);
820                 _fade_in.fast_simple_add (len * 0.481567, 0.980556);
821                 _fade_in.fast_simple_add (len * 0.767281, 1);
822                 _fade_in.fast_simple_add (len, 1);
823                 break;
824
825         case LogA:
826                 _fade_in.fast_simple_add (0, 0);
827                 _fade_in.fast_simple_add (len * 0.0737327, 0.308333);
828                 _fade_in.fast_simple_add (len * 0.246544, 0.658333);
829                 _fade_in.fast_simple_add (len * 0.470046, 0.886111);
830                 _fade_in.fast_simple_add (len * 0.652074, 0.972222);
831                 _fade_in.fast_simple_add (len * 0.771889, 0.988889);
832                 _fade_in.fast_simple_add (len, 1);
833                 break;
834
835         case LogB:
836                 _fade_in.fast_simple_add (0, 0);
837                 _fade_in.fast_simple_add (len * 0.304147, 0.0694444);
838                 _fade_in.fast_simple_add (len * 0.529954, 0.152778);
839                 _fade_in.fast_simple_add (len * 0.725806, 0.333333);
840                 _fade_in.fast_simple_add (len * 0.847926, 0.558333);
841                 _fade_in.fast_simple_add (len * 0.919355, 0.730556);
842                 _fade_in.fast_simple_add (len, 1);
843                 break;
844         }
845
846         _fade_in.thaw ();
847         _fade_in_shape = shape;
848
849         send_change (FadeInChanged);
850 }
851
852 void
853 AudioRegion::set_fade_out (FadeShape shape, nframes_t len)
854 {
855         _fade_out.freeze ();
856         _fade_out.clear ();
857
858         switch (shape) {
859         case Fast:
860                 _fade_out.fast_simple_add (len * 0, 1);
861                 _fade_out.fast_simple_add (len * 0.023041, 0.697222);
862                 _fade_out.fast_simple_add (len * 0.0553,   0.483333);
863                 _fade_out.fast_simple_add (len * 0.170507, 0.233333);
864                 _fade_out.fast_simple_add (len * 0.370968, 0.0861111);
865                 _fade_out.fast_simple_add (len * 0.610599, 0.0333333);
866                 _fade_out.fast_simple_add (len * 1, 0);
867                 break;
868
869         case LogA:
870                 _fade_out.fast_simple_add (len * 0, 1);
871                 _fade_out.fast_simple_add (len * 0.228111, 0.988889);
872                 _fade_out.fast_simple_add (len * 0.347926, 0.972222);
873                 _fade_out.fast_simple_add (len * 0.529954, 0.886111);
874                 _fade_out.fast_simple_add (len * 0.753456, 0.658333);
875                 _fade_out.fast_simple_add (len * 0.9262673, 0.308333);
876                 _fade_out.fast_simple_add (len * 1, 0);
877                 break;
878
879         case Slow:
880                 _fade_out.fast_simple_add (len * 0, 1);
881                 _fade_out.fast_simple_add (len * 0.305556, 1);
882                 _fade_out.fast_simple_add (len * 0.548611, 0.991736);
883                 _fade_out.fast_simple_add (len * 0.759259, 0.931129);
884                 _fade_out.fast_simple_add (len * 0.918981, 0.68595);
885                 _fade_out.fast_simple_add (len * 0.976852, 0.22865);
886                 _fade_out.fast_simple_add (len * 1, 0);
887                 break;
888
889         case LogB:
890                 _fade_out.fast_simple_add (len * 0, 1);
891                 _fade_out.fast_simple_add (len * 0.080645, 0.730556);
892                 _fade_out.fast_simple_add (len * 0.277778, 0.289256);
893                 _fade_out.fast_simple_add (len * 0.470046, 0.152778);
894                 _fade_out.fast_simple_add (len * 0.695853, 0.0694444);
895                 _fade_out.fast_simple_add (len * 1, 0);
896                 break;
897
898         case Linear:
899                 _fade_out.fast_simple_add (len * 0, 1);
900                 _fade_out.fast_simple_add (len * 1, 0);
901                 break;
902         }
903
904         _fade_out.thaw ();
905         _fade_out_shape = shape;
906
907         send_change (FadeOutChanged);
908 }
909
910 void
911 AudioRegion::set_fade_in_length (nframes_t len)
912 {
913         bool changed = _fade_in.extend_to (len);
914
915         if (changed) {
916                 _flags = Flag (_flags & ~DefaultFadeIn);
917                 send_change (FadeInChanged);
918         }
919 }
920
921 void
922 AudioRegion::set_fade_out_length (nframes_t len)
923 {
924         bool changed =  _fade_out.extend_to (len);
925
926         if (changed) {
927                 _flags = Flag (_flags & ~DefaultFadeOut);
928         }
929
930         send_change (FadeOutChanged);
931 }
932
933 void
934 AudioRegion::set_fade_in_active (bool yn)
935 {
936         if (yn == (_flags & FadeIn)) {
937                 return;
938         }
939         if (yn) {
940                 _flags = Flag (_flags|FadeIn);
941         } else {
942                 _flags = Flag (_flags & ~FadeIn);
943         }
944
945         send_change (FadeInActiveChanged);
946 }
947
948 void
949 AudioRegion::set_fade_out_active (bool yn)
950 {
951         if (yn == (_flags & FadeOut)) {
952                 return;
953         }
954         if (yn) {
955                 _flags = Flag (_flags | FadeOut);
956         } else {
957                 _flags = Flag (_flags & ~FadeOut);
958         }
959
960         send_change (FadeOutActiveChanged);
961 }
962
963 bool
964 AudioRegion::fade_in_is_default () const
965 {
966         return _fade_in_shape == Linear && _fade_in.back()->when == 64;
967 }
968
969 bool
970 AudioRegion::fade_out_is_default () const
971 {
972         return _fade_out_shape == Linear && _fade_out.back()->when == 64;
973 }
974
975 void
976 AudioRegion::set_default_fade_in ()
977 {
978         set_fade_in (Linear, 64);
979 }
980
981 void
982 AudioRegion::set_default_fade_out ()
983 {
984         set_fade_out (Linear, 64);
985 }
986
987 void
988 AudioRegion::set_default_fades ()
989 {
990         _fade_in_disabled = 0;
991         _fade_out_disabled = 0;
992         set_default_fade_in ();
993         set_default_fade_out ();
994 }
995
996 void
997 AudioRegion::set_default_envelope ()
998 {
999         _envelope.freeze ();
1000         _envelope.clear ();
1001         _envelope.fast_simple_add (0, 1.0f);
1002         _envelope.fast_simple_add (_length, 1.0f);
1003         _envelope.thaw ();
1004 }
1005
1006 void
1007 AudioRegion::recompute_at_end ()
1008 {
1009         /* our length has changed. recompute a new final point by interpolating 
1010            based on the the existing curve.
1011         */
1012         
1013         _envelope.freeze ();
1014         _envelope.truncate_end (_length);
1015         _envelope.set_max_xval (_length);
1016         _envelope.thaw ();
1017
1018         if (_fade_in.back()->when > _length) {
1019                 _fade_in.extend_to (_length);
1020                 send_change (FadeInChanged);
1021         }
1022
1023         if (_fade_out.back()->when > _length) {
1024                 _fade_out.extend_to (_length);
1025                 send_change (FadeOutChanged);
1026         }
1027 }       
1028
1029 void
1030 AudioRegion::recompute_at_start ()
1031 {
1032         /* as above, but the shift was from the front */
1033
1034         _envelope.truncate_start (_length);
1035
1036         if (_fade_in.back()->when > _length) {
1037                 _fade_in.extend_to (_length);
1038                 send_change (FadeInChanged);
1039         }
1040
1041         if (_fade_out.back()->when > _length) {
1042                 _fade_out.extend_to (_length);
1043                 send_change (FadeOutChanged);
1044         }
1045 }
1046
1047 int
1048 AudioRegion::separate_by_channel (Session& session, vector<boost::shared_ptr<AudioRegion> >& v) const
1049 {
1050         SourceList srcs;
1051         string new_name;
1052         int n;
1053
1054         if (sources.size() < 2) {
1055                 return 0;
1056         }
1057
1058         n = 0;
1059
1060         for (SourceList::const_iterator i = sources.begin(); i != sources.end(); ++i) {
1061
1062                 srcs.clear ();
1063                 srcs.push_back (*i);
1064
1065                 new_name = _name;
1066
1067                 if (sources.size() == 2) {
1068                         if (n == 0) {
1069                                 new_name += "-L";
1070                         } else {
1071                                 new_name += "-R";
1072                         }
1073                 } else {
1074                         new_name += '-';
1075                         new_name += ('0' + n + 1);
1076                 }
1077
1078                 /* create a copy with just one source. prevent if from being thought of as "whole file" even if 
1079                    it covers the entire source file(s).
1080                  */
1081
1082                 Flag f = Flag (_flags & ~WholeFile);
1083
1084                 boost::shared_ptr<Region> r = RegionFactory::create (srcs, _start, _length, new_name, _layer, f);
1085                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (r);
1086
1087                 v.push_back (ar);
1088                 
1089                 ++n;
1090         }
1091
1092         return 0;
1093 }
1094
1095 void
1096 AudioRegion::source_deleted ()
1097 {
1098         sources.clear ();
1099         drop_references ();
1100 }
1101
1102 vector<string>
1103 AudioRegion::master_source_names ()
1104 {
1105         SourceList::iterator i;
1106
1107         vector<string> names;
1108         for (i = master_sources.begin(); i != master_sources.end(); ++i) {
1109                 names.push_back((*i)->name());
1110         }
1111
1112         return names;
1113 }
1114
1115 bool
1116 AudioRegion::source_equivalent (boost::shared_ptr<const Region> o) const
1117 {
1118         boost::shared_ptr<const AudioRegion> other = boost::dynamic_pointer_cast<const AudioRegion>(o);
1119
1120         if (!other)
1121                 return false;
1122
1123         SourceList::const_iterator i;
1124         SourceList::const_iterator io;
1125
1126         for (i = sources.begin(), io = other->sources.begin(); i != sources.end() && io != other->sources.end(); ++i, ++io) {
1127                 if ((*i)->id() != (*io)->id()) {
1128                         return false;
1129                 }
1130         }
1131
1132         for (i = master_sources.begin(), io = other->master_sources.begin(); i != master_sources.end() && io != other->master_sources.end(); ++i, ++io) {
1133                 if ((*i)->id() != (*io)->id()) {
1134                         return false;
1135                 }
1136         }
1137
1138         return true;
1139 }
1140
1141 int
1142 AudioRegion::apply (AudioFilter& filter)
1143 {
1144         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (shared_from_this());
1145         return filter.run (ar);
1146 }
1147
1148 int
1149 AudioRegion::exportme (Session& session, AudioExportSpecification& spec)
1150 {
1151         const nframes_t blocksize = 4096;
1152         nframes_t to_read;
1153         int status = -1;
1154
1155         spec.channels = sources.size();
1156
1157         if (spec.prepare (blocksize, session.frame_rate())) {
1158                 goto out;
1159         }
1160
1161         spec.pos = 0;
1162         spec.total_frames = _length;
1163
1164         while (spec.pos < _length && !spec.stop) {
1165                 
1166                 
1167                 /* step 1: interleave */
1168                 
1169                 to_read = min (_length - spec.pos, blocksize);
1170                 
1171                 if (spec.channels == 1) {
1172
1173                         if (sources.front()->read (spec.dataF, _start + spec.pos, to_read) != to_read) {
1174                                 goto out;
1175                         }
1176
1177                 } else {
1178
1179                         Sample buf[blocksize];
1180
1181                         for (uint32_t chan = 0; chan < spec.channels; ++chan) {
1182                                 
1183                                 if (sources[chan]->read (buf, _start + spec.pos, to_read) != to_read) {
1184                                         goto out;
1185                                 }
1186                                 
1187                                 for (nframes_t x = 0; x < to_read; ++x) {
1188                                         spec.dataF[chan+(x*spec.channels)] = buf[x];
1189                                 }
1190                         }
1191                 }
1192                 
1193                 if (spec.process (to_read)) {
1194                         goto out;
1195                 }
1196                 
1197                 spec.pos += to_read;
1198                 spec.progress = (double) spec.pos /_length;
1199                 
1200         }
1201         
1202         status = 0;
1203
1204   out:  
1205         spec.running = false;
1206         spec.status = status;
1207         spec.clear();
1208         
1209         return status;
1210 }
1211
1212 boost::shared_ptr<Region>
1213 AudioRegion::get_parent() const
1214 {
1215         boost::shared_ptr<Playlist> pl (playlist());
1216
1217         if (pl) {
1218                 boost::shared_ptr<AudioRegion> ar;
1219                 boost::shared_ptr<AudioRegion const> grrr2 = boost::dynamic_pointer_cast<AudioRegion const> (shared_from_this());
1220                 
1221                 if (grrr2 && (ar = pl->session().find_whole_file_parent (grrr2))) {
1222                         return boost::static_pointer_cast<Region> (ar);
1223                 }
1224         }
1225         
1226         return boost::shared_ptr<Region>();
1227 }
1228
1229 void
1230 AudioRegion::set_scale_amplitude (gain_t g)
1231 {
1232         boost::shared_ptr<Playlist> pl (playlist());
1233
1234         _scale_amplitude = g;
1235
1236         /* tell the diskstream we're in */
1237         
1238         if (pl) {
1239                 pl->Modified();
1240         }
1241
1242         /* tell everybody else */
1243
1244         send_change (ScaleAmplitudeChanged);
1245 }
1246
1247 void
1248 AudioRegion::normalize_to (float target_dB)
1249 {
1250         const nframes_t blocksize = 64 * 1024;
1251         Sample buf[blocksize];
1252         nframes_t fpos;
1253         nframes_t fend;
1254         nframes_t to_read;
1255         double maxamp = 0;
1256         gain_t target = dB_to_coefficient (target_dB);
1257
1258         if (target == 1.0f) {
1259                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1260                    that we may have clipped.
1261                 */
1262                 target -= FLT_EPSILON;
1263         }
1264
1265         fpos = _start;
1266         fend = _start + _length;
1267
1268         /* first pass: find max amplitude */
1269
1270         while (fpos < fend) {
1271
1272                 uint32_t n;
1273
1274                 to_read = min (fend - fpos, blocksize);
1275
1276                 for (n = 0; n < n_channels(); ++n) {
1277
1278                         /* read it in */
1279
1280                         if (source (n)->read (buf, fpos, to_read) != to_read) {
1281                                 return;
1282                         }
1283                         
1284                         maxamp = Session::compute_peak (buf, to_read, maxamp);
1285                 }
1286
1287                 fpos += to_read;
1288         };
1289
1290         if (maxamp == 0.0f) {
1291                 /* don't even try */
1292                 return;
1293         }
1294
1295         if (maxamp == target) {
1296                 /* we can't do anything useful */
1297                 return;
1298         }
1299
1300         /* compute scale factor */
1301
1302         _scale_amplitude = target/maxamp;
1303
1304         /* tell the diskstream we're in */
1305
1306         boost::shared_ptr<Playlist> pl (playlist());
1307
1308         if (pl) {
1309                 pl->Modified();
1310         }
1311
1312         /* tell everybody else */
1313
1314         send_change (ScaleAmplitudeChanged);
1315 }
1316
1317 void
1318 AudioRegion::fade_in_changed ()
1319 {
1320         send_change (FadeInChanged);
1321 }
1322
1323 void
1324 AudioRegion::fade_out_changed ()
1325 {
1326         send_change (FadeOutChanged);
1327 }
1328
1329 void
1330 AudioRegion::envelope_changed ()
1331 {
1332         send_change (EnvelopeChanged);
1333 }
1334
1335 void
1336 AudioRegion::suspend_fade_in ()
1337 {
1338         if (++_fade_in_disabled == 1) {
1339                 if (fade_in_is_default()) {
1340                         set_fade_in_active (false);
1341                 }
1342         }
1343 }
1344
1345 void
1346 AudioRegion::resume_fade_in ()
1347 {
1348         if (--_fade_in_disabled == 0 && _fade_in_disabled) {
1349                 set_fade_in_active (true);
1350         }
1351 }
1352
1353 void
1354 AudioRegion::suspend_fade_out ()
1355 {
1356         if (++_fade_out_disabled == 1) {
1357                 if (fade_out_is_default()) {
1358                         set_fade_out_active (false);
1359                 }
1360         }
1361 }
1362
1363 void
1364 AudioRegion::resume_fade_out ()
1365 {
1366         if (--_fade_out_disabled == 0 &&_fade_out_disabled) {
1367                 set_fade_out_active (true);
1368         }
1369 }
1370
1371 bool
1372 AudioRegion::speed_mismatch (float sr) const
1373 {
1374         if (sources.empty()) {
1375                 /* impossible, but ... */
1376                 return false;
1377         }
1378
1379         float fsr = sources.front()->sample_rate();
1380
1381         return fsr != sr;
1382 }
1383
1384 void
1385 AudioRegion::source_offset_changed ()
1386 {
1387         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(sources.front());
1388
1389         if (afs && afs->destructive()) {
1390                 // set_start (source()->natural_position(), this);
1391                 set_position (source()->natural_position(), this);
1392         } 
1393 }
1394
1395 void
1396 AudioRegion::set_playlist (boost::weak_ptr<Playlist> wpl)
1397 {
1398         boost::shared_ptr<Playlist> old_playlist = (_playlist.lock());
1399
1400         boost::shared_ptr<Playlist> pl (wpl.lock());
1401
1402         if (old_playlist == pl) {
1403                 return;
1404         }
1405
1406         Region::set_playlist (wpl);
1407
1408         if (pl) {
1409                 if (old_playlist) {
1410                         for (SourceList::const_iterator i = sources.begin(); i != sources.end(); ++i) {
1411                                 (*i)->remove_playlist (_playlist);      
1412                                 (*i)->add_playlist (pl);
1413                         }
1414                 } else {
1415                         for (SourceList::const_iterator i = sources.begin(); i != sources.end(); ++i) {
1416                                 (*i)->add_playlist (pl);
1417                         }
1418                 }
1419         } else {
1420                 if (old_playlist) {
1421                         for (SourceList::const_iterator i = sources.begin(); i != sources.end(); ++i) {
1422                                 (*i)->remove_playlist (old_playlist);
1423                         }
1424                 }
1425         }
1426 }
1427
1428 extern "C" {
1429
1430         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) 
1431 {
1432         return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (nframes_t) npeaks, (nframes_t) start, (nframes_t) cnt, n_chan,samples_per_unit);
1433 }
1434
1435 uint32_t region_length_from_c (void *arg)
1436 {
1437
1438         return ((AudioRegion *) arg)->length();
1439 }
1440
1441 uint32_t sourcefile_length_from_c (void *arg, double zoom_factor)
1442 {
1443         return ( (AudioRegion *) arg)->source()->available_peaks (zoom_factor) ;
1444 }
1445
1446 } /* extern "C" */