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