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