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