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