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