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