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