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