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