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