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