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