2 Copyright (C) 2000-2006 Paul Davis
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.
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.
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.
27 #include <boost/scoped_array.hpp>
28 #include <boost/shared_ptr.hpp>
30 #include <glibmm/threads.h>
32 #include "pbd/basename.h"
33 #include "pbd/xml++.h"
34 #include "pbd/stacktrace.h"
35 #include "pbd/enumwriter.h"
36 #include "pbd/convert.h"
38 #include "evoral/Curve.hpp"
40 #include "ardour/audioregion.h"
41 #include "ardour/session.h"
42 #include "ardour/dB.h"
43 #include "ardour/debug.h"
44 #include "ardour/event_type_map.h"
45 #include "ardour/playlist.h"
46 #include "ardour/audiofilesource.h"
47 #include "ardour/region_factory.h"
48 #include "ardour/runtime_functions.h"
49 #include "ardour/transient_detector.h"
50 #include "ardour/parameter_descriptor.h"
51 #include "ardour/progress.h"
53 #include "ardour/sndfilesource.h"
55 #include "ardour/coreaudiosource.h"
56 #endif // HAVE_COREAUDIO
62 using namespace ARDOUR;
66 namespace Properties {
67 PBD::PropertyDescriptor<bool> envelope_active;
68 PBD::PropertyDescriptor<bool> default_fade_in;
69 PBD::PropertyDescriptor<bool> default_fade_out;
70 PBD::PropertyDescriptor<bool> fade_in_active;
71 PBD::PropertyDescriptor<bool> fade_out_active;
72 PBD::PropertyDescriptor<float> scale_amplitude;
73 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > fade_in;
74 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > inverse_fade_in;
75 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > fade_out;
76 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > inverse_fade_out;
77 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > envelope;
81 /* Curve manipulations */
84 reverse_curve (boost::shared_ptr<Evoral::ControlList> dst, boost::shared_ptr<const Evoral::ControlList> src)
86 size_t len = src->back()->when;
87 for (Evoral::ControlList::const_reverse_iterator it = src->rbegin(); it!=src->rend(); it++) {
88 dst->fast_simple_add (len - (*it)->when, (*it)->value);
93 generate_inverse_power_curve (boost::shared_ptr<Evoral::ControlList> dst, boost::shared_ptr<const Evoral::ControlList> src)
95 // calc inverse curve using sum of squares
96 for (Evoral::ControlList::const_iterator it = src->begin(); it!=src->end(); ++it ) {
97 float value = (*it)->value;
98 value = 1 - powf(value,2);
100 dst->fast_simple_add ( (*it)->when, value );
105 generate_db_fade (boost::shared_ptr<Evoral::ControlList> dst, double len, int num_steps, float dB_drop)
108 dst->fast_simple_add (0, 1);
110 //generate a fade-out curve by successively applying a gain drop
111 float fade_speed = dB_to_coefficient(dB_drop / (float) num_steps);
112 float coeff = GAIN_COEFF_UNITY;
113 for (int i = 1; i < (num_steps-1); i++) {
115 dst->fast_simple_add (len*(double)i/(double)num_steps, coeff);
118 dst->fast_simple_add (len, GAIN_COEFF_SMALL);
122 merge_curves (boost::shared_ptr<Evoral::ControlList> dst,
123 boost::shared_ptr<const Evoral::ControlList> curve1,
124 boost::shared_ptr<const Evoral::ControlList> curve2)
126 Evoral::ControlList::EventList::size_type size = curve1->size();
128 //curve lengths must match for now
129 if (size != curve2->size()) {
133 Evoral::ControlList::const_iterator c1 = curve1->begin();
135 for (Evoral::ControlList::const_iterator c2 = curve2->begin(); c2!=curve2->end(); c2++ ) {
136 float v1 = accurate_coefficient_to_dB((*c1)->value);
137 float v2 = accurate_coefficient_to_dB((*c2)->value);
139 double interp = v1 * ( 1.0-( (double)count / (double)size) );
140 interp += v2 * ( (double)count / (double)size );
142 interp = dB_to_coefficient(interp);
143 dst->fast_simple_add ( (*c1)->when, interp );
150 AudioRegion::make_property_quarks ()
152 Properties::envelope_active.property_id = g_quark_from_static_string (X_("envelope-active"));
153 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for envelope-active = %1\n", Properties::envelope_active.property_id));
154 Properties::default_fade_in.property_id = g_quark_from_static_string (X_("default-fade-in"));
155 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for default-fade-in = %1\n", Properties::default_fade_in.property_id));
156 Properties::default_fade_out.property_id = g_quark_from_static_string (X_("default-fade-out"));
157 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for default-fade-out = %1\n", Properties::default_fade_out.property_id));
158 Properties::fade_in_active.property_id = g_quark_from_static_string (X_("fade-in-active"));
159 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-in-active = %1\n", Properties::fade_in_active.property_id));
160 Properties::fade_out_active.property_id = g_quark_from_static_string (X_("fade-out-active"));
161 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-out-active = %1\n", Properties::fade_out_active.property_id));
162 Properties::scale_amplitude.property_id = g_quark_from_static_string (X_("scale-amplitude"));
163 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for scale-amplitude = %1\n", Properties::scale_amplitude.property_id));
164 Properties::fade_in.property_id = g_quark_from_static_string (X_("FadeIn"));
165 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for FadeIn = %1\n", Properties::fade_in.property_id));
166 Properties::inverse_fade_in.property_id = g_quark_from_static_string (X_("InverseFadeIn"));
167 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for InverseFadeIn = %1\n", Properties::inverse_fade_in.property_id));
168 Properties::fade_out.property_id = g_quark_from_static_string (X_("FadeOut"));
169 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for FadeOut = %1\n", Properties::fade_out.property_id));
170 Properties::inverse_fade_out.property_id = g_quark_from_static_string (X_("InverseFadeOut"));
171 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for InverseFadeOut = %1\n", Properties::inverse_fade_out.property_id));
172 Properties::envelope.property_id = g_quark_from_static_string (X_("Envelope"));
173 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for Envelope = %1\n", Properties::envelope.property_id));
177 AudioRegion::register_properties ()
179 /* no need to register parent class properties */
181 add_property (_envelope_active);
182 add_property (_default_fade_in);
183 add_property (_default_fade_out);
184 add_property (_fade_in_active);
185 add_property (_fade_out_active);
186 add_property (_scale_amplitude);
187 add_property (_fade_in);
188 add_property (_inverse_fade_in);
189 add_property (_fade_out);
190 add_property (_inverse_fade_out);
191 add_property (_envelope);
194 #define AUDIOREGION_STATE_DEFAULT \
195 _envelope_active (Properties::envelope_active, false) \
196 , _default_fade_in (Properties::default_fade_in, true) \
197 , _default_fade_out (Properties::default_fade_out, true) \
198 , _fade_in_active (Properties::fade_in_active, true) \
199 , _fade_out_active (Properties::fade_out_active, true) \
200 , _scale_amplitude (Properties::scale_amplitude, 1.0) \
201 , _fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeInAutomation)))) \
202 , _inverse_fade_in (Properties::inverse_fade_in, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeInAutomation)))) \
203 , _fade_out (Properties::fade_out, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeOutAutomation)))) \
204 , _inverse_fade_out (Properties::inverse_fade_out, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeOutAutomation))))
206 #define AUDIOREGION_COPY_STATE(other) \
207 _envelope_active (Properties::envelope_active, other->_envelope_active) \
208 , _default_fade_in (Properties::default_fade_in, other->_default_fade_in) \
209 , _default_fade_out (Properties::default_fade_out, other->_default_fade_out) \
210 , _fade_in_active (Properties::fade_in_active, other->_fade_in_active) \
211 , _fade_out_active (Properties::fade_out_active, other->_fade_out_active) \
212 , _scale_amplitude (Properties::scale_amplitude, other->_scale_amplitude) \
213 , _fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_fade_in.val()))) \
214 , _inverse_fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_inverse_fade_in.val()))) \
215 , _fade_out (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_fade_out.val()))) \
216 , _inverse_fade_out (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_inverse_fade_out.val()))) \
217 /* a Session will reset these to its chosen defaults by calling AudioRegion::set_default_fade() */
222 register_properties ();
224 suspend_property_changes();
225 set_default_fades ();
226 set_default_envelope ();
227 resume_property_changes();
229 listen_to_my_curves ();
230 connect_to_analysis_changed ();
231 connect_to_header_position_offset_changed ();
234 /** Constructor for use by derived types only */
235 AudioRegion::AudioRegion (Session& s, samplepos_t start, samplecnt_t len, std::string name)
236 : Region (s, start, len, name, DataType::AUDIO)
237 , AUDIOREGION_STATE_DEFAULT
238 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter(EnvelopeAutomation))))
240 , _fade_in_suspended (0)
241 , _fade_out_suspended (0)
244 assert (_sources.size() == _master_sources.size());
247 /** Basic AudioRegion constructor */
248 AudioRegion::AudioRegion (const SourceList& srcs)
250 , AUDIOREGION_STATE_DEFAULT
251 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter(EnvelopeAutomation))))
252 , _automatable(srcs[0]->session())
253 , _fade_in_suspended (0)
254 , _fade_out_suspended (0)
257 assert (_sources.size() == _master_sources.size());
260 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other)
262 , AUDIOREGION_COPY_STATE (other)
263 /* As far as I can see, the _envelope's times are relative to region position, and have nothing
264 to do with sources (and hence _start). So when we copy the envelope, we just use the supplied offset.
266 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val(), 0, other->_length)))
267 , _automatable (other->session())
268 , _fade_in_suspended (0)
269 , _fade_out_suspended (0)
271 /* don't use init here, because we got fade in/out from the other region
273 register_properties ();
274 listen_to_my_curves ();
275 connect_to_analysis_changed ();
276 connect_to_header_position_offset_changed ();
278 assert(_type == DataType::AUDIO);
279 assert (_sources.size() == _master_sources.size());
282 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, MusicSample offset)
283 : Region (other, offset)
284 , AUDIOREGION_COPY_STATE (other)
285 /* As far as I can see, the _envelope's times are relative to region position, and have nothing
286 to do with sources (and hence _start). So when we copy the envelope, we just use the supplied offset.
288 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val(), offset.sample, other->_length)))
289 , _automatable (other->session())
290 , _fade_in_suspended (0)
291 , _fade_out_suspended (0)
293 /* don't use init here, because we got fade in/out from the other region
295 register_properties ();
296 listen_to_my_curves ();
297 connect_to_analysis_changed ();
298 connect_to_header_position_offset_changed ();
300 assert(_type == DataType::AUDIO);
301 assert (_sources.size() == _master_sources.size());
304 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, const SourceList& srcs)
305 : Region (boost::static_pointer_cast<const Region>(other), srcs)
306 , AUDIOREGION_COPY_STATE (other)
307 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val())))
308 , _automatable (other->session())
309 , _fade_in_suspended (0)
310 , _fade_out_suspended (0)
312 /* make-a-sort-of-copy-with-different-sources constructor (used by audio filter) */
314 register_properties ();
316 listen_to_my_curves ();
317 connect_to_analysis_changed ();
318 connect_to_header_position_offset_changed ();
320 assert (_sources.size() == _master_sources.size());
323 AudioRegion::AudioRegion (SourceList& srcs)
325 , AUDIOREGION_STATE_DEFAULT
326 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList(Evoral::Parameter(EnvelopeAutomation))))
327 , _automatable(srcs[0]->session())
328 , _fade_in_suspended (0)
329 , _fade_out_suspended (0)
333 assert(_type == DataType::AUDIO);
334 assert (_sources.size() == _master_sources.size());
337 AudioRegion::~AudioRegion ()
342 AudioRegion::post_set (const PropertyChange& /*ignored*/)
345 _sync_position = _start;
348 /* return to default fades if the existing ones are too long */
350 if (_left_of_split) {
351 if (_fade_in->back()->when >= _length) {
352 set_default_fade_in ();
354 set_default_fade_out ();
355 _left_of_split = false;
358 if (_right_of_split) {
359 if (_fade_out->back()->when >= _length) {
360 set_default_fade_out ();
363 set_default_fade_in ();
364 _right_of_split = false;
367 /* If _length changed, adjust our gain envelope accordingly */
368 _envelope->truncate_end (_length);
372 AudioRegion::connect_to_analysis_changed ()
374 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
375 (*i)->AnalysisChanged.connect_same_thread (*this, boost::bind (&AudioRegion::maybe_invalidate_transients, this));
380 AudioRegion::connect_to_header_position_offset_changed ()
382 set<boost::shared_ptr<Source> > unique_srcs;
384 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
386 /* connect only once to HeaderPositionOffsetChanged, even if sources are replicated
389 if (unique_srcs.find (*i) == unique_srcs.end ()) {
390 unique_srcs.insert (*i);
391 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
393 afs->HeaderPositionOffsetChanged.connect_same_thread (*this, boost::bind (&AudioRegion::source_offset_changed, this));
400 AudioRegion::listen_to_my_curves ()
402 _envelope->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::envelope_changed, this));
403 _fade_in->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::fade_in_changed, this));
404 _fade_out->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::fade_out_changed, this));
408 AudioRegion::set_envelope_active (bool yn)
410 if (envelope_active() != yn) {
411 _envelope_active = yn;
412 send_change (PropertyChange (Properties::envelope_active));
416 /** @param buf Buffer to put peak data in.
417 * @param npeaks Number of peaks to read (ie the number of PeakDatas in buf)
418 * @param offset Start position, as an offset from the start of this region's source.
419 * @param cnt Number of samples to read.
420 * @param chan_n Channel.
421 * @param samples_per_pixel Number of samples to use to generate one peak value.
425 AudioRegion::read_peaks (PeakData *buf, samplecnt_t npeaks, samplecnt_t offset, samplecnt_t cnt, uint32_t chan_n, double samples_per_pixel) const
427 if (chan_n >= _sources.size()) {
431 if (audio_source(chan_n)->read_peaks (buf, npeaks, offset, cnt, samples_per_pixel)) {
435 if (_scale_amplitude != 1.0f) {
436 for (samplecnt_t n = 0; n < npeaks; ++n) {
437 buf[n].max *= _scale_amplitude;
438 buf[n].min *= _scale_amplitude;
445 /** @param buf Buffer to write data to (existing data will be overwritten).
446 * @param pos Position to read from as an offset from the region position.
447 * @param cnt Number of samples to read.
448 * @param channel Channel to read from.
451 AudioRegion::read (Sample* buf, samplepos_t pos, samplecnt_t cnt, int channel) const
453 /* raw read, no fades, no gain, nada */
454 return read_from_sources (_sources, _length, buf, _position + pos, cnt, channel);
458 AudioRegion::master_read_at (Sample *buf, Sample* /*mixdown_buffer*/, float* /*gain_buffer*/,
459 samplepos_t position, samplecnt_t cnt, uint32_t chan_n) const
461 /* do not read gain/scaling/fades and do not count this disk i/o in statistics */
464 return read_from_sources (
465 _master_sources, _master_sources.front()->length (_master_sources.front()->timeline_position()),
466 buf, position, cnt, chan_n
470 /** @param buf Buffer to mix data into.
471 * @param mixdown_buffer Scratch buffer for audio data.
472 * @param gain_buffer Scratch buffer for gain data.
473 * @param position Position within the session to read from.
474 * @param cnt Number of samples to read.
475 * @param chan_n Channel number to read.
478 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
479 samplepos_t position,
481 uint32_t chan_n) const
483 /* We are reading data from this region into buf (possibly via mixdown_buffer).
484 The caller has verified that we cover the desired section.
487 /* See doc/region_read.svg for a drawing which might help to explain
493 if (n_channels() == 0) {
497 /* WORK OUT WHERE TO GET DATA FROM */
501 assert (position >= _position);
502 sampleoffset_t const internal_offset = position - _position;
504 if (internal_offset >= _length) {
505 return 0; /* read nothing */
508 if ((to_read = min (cnt, _length - internal_offset)) == 0) {
509 return 0; /* read nothing */
513 /* COMPUTE DETAILS OF ANY FADES INVOLVED IN THIS READ */
515 /* Amount (length) of fade in that we are dealing with in this read */
516 samplecnt_t fade_in_limit = 0;
518 /* Offset from buf / mixdown_buffer of the start
519 of any fade out that we are dealing with
521 sampleoffset_t fade_out_offset = 0;
523 /* Amount (length) of fade out that we are dealing with in this read */
524 samplecnt_t fade_out_limit = 0;
526 samplecnt_t fade_interval_start = 0;
530 if (_fade_in_active && _session.config.get_use_region_fades()) {
532 samplecnt_t fade_in_length = (samplecnt_t) _fade_in->back()->when;
534 /* see if this read is within the fade in */
536 if (internal_offset < fade_in_length) {
537 fade_in_limit = min (to_read, fade_in_length - internal_offset);
543 if (_fade_out_active && _session.config.get_use_region_fades()) {
545 /* see if some part of this read is within the fade out */
547 /* ................. >| REGION
553 * _length - fade_out_length
557 * ^internal_offset + to_read
559 * we need the intersection of [internal_offset,internal_offset+to_read] with
560 * [_length - fade_out_length, _length]
564 fade_interval_start = max (internal_offset, _length - samplecnt_t (_fade_out->back()->when));
565 samplecnt_t fade_interval_end = min(internal_offset + to_read, _length.val());
567 if (fade_interval_end > fade_interval_start) {
568 /* (part of the) the fade out is in this buffer */
569 fade_out_limit = fade_interval_end - fade_interval_start;
570 fade_out_offset = fade_interval_start - internal_offset;
574 /* READ DATA FROM THE SOURCE INTO mixdown_buffer.
575 We can never read directly into buf, since it may contain data
576 from a region `below' this one in the stack, and our fades (if they exist)
577 may need to mix with the existing data.
580 if (read_from_sources (_sources, _length, mixdown_buffer, position, to_read, chan_n) != to_read) {
584 /* APPLY REGULAR GAIN CURVES AND SCALING TO mixdown_buffer */
586 if (envelope_active()) {
587 _envelope->curve().get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
589 if (_scale_amplitude != 1.0f) {
590 for (samplecnt_t n = 0; n < to_read; ++n) {
591 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
594 for (samplecnt_t n = 0; n < to_read; ++n) {
595 mixdown_buffer[n] *= gain_buffer[n];
598 } else if (_scale_amplitude != 1.0f) {
599 apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
602 /* APPLY FADES TO THE DATA IN mixdown_buffer AND MIX THE RESULTS INTO
603 * buf. The key things to realize here: (1) the fade being applied is
604 * (as of April 26th 2012) just the inverse of the fade in curve (2)
605 * "buf" contains data from lower regions already. So this operation
606 * fades out the existing material.
609 if (fade_in_limit != 0) {
612 if (_inverse_fade_in) {
614 /* explicit inverse fade in curve (e.g. for constant
615 * power), so we have to fetch it.
618 _inverse_fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
620 /* Fade the data from lower layers out */
621 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
622 buf[n] *= gain_buffer[n];
625 /* refill gain buffer with the fade in */
627 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
631 /* no explicit inverse fade in, so just use (1 - fade
632 * in) for the fade out of lower layers
635 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
637 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
638 buf[n] *= 1 - gain_buffer[n];
642 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
645 /* Mix our newly-read data in, with the fade */
646 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
647 buf[n] += mixdown_buffer[n] * gain_buffer[n];
651 if (fade_out_limit != 0) {
653 samplecnt_t const curve_offset = fade_interval_start - (_length - _fade_out->back()->when);
656 if (_inverse_fade_out) {
658 _inverse_fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
660 /* Fade the data from lower levels in */
661 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
662 buf[m] *= gain_buffer[n];
665 /* fetch the actual fade out */
667 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
671 /* no explicit inverse fade out (which is
672 * actually a fade in), so just use (1 - fade
673 * out) for the fade in of lower layers
676 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
678 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
679 buf[m] *= 1 - gain_buffer[n];
683 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
686 /* Mix our newly-read data with whatever was already there,
687 with the fade out applied to our data.
689 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
690 buf[m] += mixdown_buffer[m] * gain_buffer[n];
694 /* MIX OR COPY THE REGION BODY FROM mixdown_buffer INTO buf */
696 samplecnt_t const N = to_read - fade_in_limit - fade_out_limit;
699 DEBUG_TRACE (DEBUG::AudioPlayback, string_compose ("Region %1 memcpy into buf @ %2 + %3, from mixdown buffer @ %4 + %5, len = %6 cnt was %7\n",
700 name(), buf, fade_in_limit, mixdown_buffer, fade_in_limit, N, cnt));
701 memcpy (buf + fade_in_limit, mixdown_buffer + fade_in_limit, N * sizeof (Sample));
703 mix_buffers_no_gain (buf + fade_in_limit, mixdown_buffer + fade_in_limit, N);
710 /** Read data directly from one of our sources, accounting for the situation when the track has a different channel
711 * count to the region.
713 * @param srcs Source list to get our source from.
714 * @param limit Furthest that we should read, as an offset from the region position.
715 * @param buf Buffer to write data into (existing contents of the buffer will be overwritten)
716 * @param position Position to read from, in session samples.
717 * @param cnt Number of samples to read.
718 * @param chan_n Channel to read from.
719 * @return Number of samples read.
723 AudioRegion::read_from_sources (SourceList const & srcs, samplecnt_t limit, Sample* buf, samplepos_t position, samplecnt_t cnt, uint32_t chan_n) const
725 sampleoffset_t const internal_offset = position - _position;
726 if (internal_offset >= limit) {
730 samplecnt_t const to_read = min (cnt, limit - internal_offset);
735 if (chan_n < n_channels()) {
737 boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[chan_n]);
738 if (src->read (buf, _start + internal_offset, to_read) != to_read) {
739 return 0; /* "read nothing" */
744 /* track is N-channel, this region has fewer channels; silence the ones
748 if (Config->get_replicate_missing_region_channels()) {
750 /* copy an existing channel's data in for this non-existant one */
752 uint32_t channel = chan_n % n_channels();
753 boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[channel]);
755 if (src->read (buf, _start + internal_offset, to_read) != to_read) {
756 return 0; /* "read nothing" */
762 memset (buf, 0, sizeof (Sample) * to_read);
770 AudioRegion::get_basic_state ()
772 XMLNode& node (Region::state ());
774 node.set_property ("channels", (uint32_t)_sources.size());
780 AudioRegion::state ()
782 XMLNode& node (get_basic_state());
785 child = node.add_child ("Envelope");
787 bool default_env = false;
789 // If there are only two points, the points are in the start of the region and the end of the region
790 // so, if they are both at 1.0f, that means the default region.
792 if (_envelope->size() == 2 &&
793 _envelope->front()->value == GAIN_COEFF_UNITY &&
794 _envelope->back()->value==GAIN_COEFF_UNITY) {
795 if (_envelope->front()->when == 0 && _envelope->back()->when == _length) {
801 child->set_property ("default", "yes");
803 child->add_child_nocopy (_envelope->get_state ());
806 child = node.add_child (X_("FadeIn"));
808 if (_default_fade_in) {
809 child->set_property ("default", "yes");
811 child->add_child_nocopy (_fade_in->get_state ());
814 if (_inverse_fade_in) {
815 child = node.add_child (X_("InverseFadeIn"));
816 child->add_child_nocopy (_inverse_fade_in->get_state ());
819 child = node.add_child (X_("FadeOut"));
821 if (_default_fade_out) {
822 child->set_property ("default", "yes");
824 child->add_child_nocopy (_fade_out->get_state ());
827 if (_inverse_fade_out) {
828 child = node.add_child (X_("InverseFadeOut"));
829 child->add_child_nocopy (_inverse_fade_out->get_state ());
836 AudioRegion::_set_state (const XMLNode& node, int version, PropertyChange& what_changed, bool send)
838 const XMLNodeList& nlist = node.children();
839 boost::shared_ptr<Playlist> the_playlist (_playlist.lock());
841 suspend_property_changes ();
844 the_playlist->freeze ();
848 /* this will set all our State members and stuff controlled by the Region.
849 It should NOT send any changed signals - that is our responsibility.
852 Region::_set_state (node, version, what_changed, false);
855 if (node.get_property ("scale-gain", val)) {
856 if (val != _scale_amplitude) {
857 _scale_amplitude = val;
858 what_changed.add (Properties::scale_amplitude);
862 /* Now find envelope description and other related child items */
864 _envelope->freeze ();
866 for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
868 XMLProperty const * prop;
872 if (child->name() == "Envelope") {
876 if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child, version)) {
877 set_default_envelope ();
880 _envelope->truncate_end (_length);
883 } else if (child->name() == "FadeIn") {
888 if ((child->get_property ("default", is_default) && is_default) || (prop = child->property ("steepness")) != 0) {
889 set_default_fade_in ();
891 XMLNode* grandchild = child->child ("AutomationList");
893 _fade_in->set_state (*grandchild, version);
898 if (child->get_property ("active", is_active)) {
899 set_fade_in_active (is_active);
902 } else if (child->name() == "FadeOut") {
907 if ((child->get_property ("default", is_default) && is_default) || (prop = child->property ("steepness")) != 0) {
908 set_default_fade_out ();
910 XMLNode* grandchild = child->child ("AutomationList");
912 _fade_out->set_state (*grandchild, version);
917 if (child->get_property ("active", is_active)) {
918 set_fade_out_active (is_active);
921 } else if ( (child->name() == "InverseFadeIn") || (child->name() == "InvFadeIn") ) {
922 XMLNode* grandchild = child->child ("AutomationList");
924 _inverse_fade_in->set_state (*grandchild, version);
926 } else if ( (child->name() == "InverseFadeOut") || (child->name() == "InvFadeOut") ) {
927 XMLNode* grandchild = child->child ("AutomationList");
929 _inverse_fade_out->set_state (*grandchild, version);
935 resume_property_changes ();
938 send_change (what_changed);
942 the_playlist->thaw ();
949 AudioRegion::set_state (const XMLNode& node, int version)
951 PropertyChange what_changed;
952 return _set_state (node, version, what_changed, true);
956 AudioRegion::fade_range (samplepos_t start, samplepos_t end)
960 switch (coverage (start, end)) {
961 case Evoral::OverlapStart:
965 set_fade_in (FadeConstantPower, e - s);
967 case Evoral::OverlapEnd:
970 e = _position + _length;
971 set_fade_out (FadeConstantPower, e - s);
973 case Evoral::OverlapInternal:
974 /* needs addressing, perhaps. Difficult to do if we can't
975 * control one edge of the fade relative to the relevant edge
976 * of the region, which we cannot - fades are currently assumed
977 * to start/end at the start/end of the region
986 AudioRegion::set_fade_in_shape (FadeShape shape)
988 set_fade_in (shape, (samplecnt_t) _fade_in->back()->when);
992 AudioRegion::set_fade_out_shape (FadeShape shape)
994 set_fade_out (shape, (samplecnt_t) _fade_out->back()->when);
998 AudioRegion::set_fade_in (boost::shared_ptr<AutomationList> f)
1000 _fade_in->freeze ();
1001 *(_fade_in.val()) = *f;
1003 _default_fade_in = false;
1005 send_change (PropertyChange (Properties::fade_in));
1009 AudioRegion::set_fade_in (FadeShape shape, samplecnt_t len)
1011 const ARDOUR::ParameterDescriptor desc(FadeInAutomation);
1012 boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeInAutomation, desc));
1013 boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeInAutomation, desc));
1014 boost::shared_ptr<Evoral::ControlList> c3 (new Evoral::ControlList (FadeInAutomation, desc));
1016 _fade_in->freeze ();
1018 _inverse_fade_in->clear ();
1020 const int num_steps = 32;
1024 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1025 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1026 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1030 generate_db_fade (_fade_in.val(), len, num_steps, -60);
1031 reverse_curve (c1, _fade_in.val());
1032 _fade_in->copy_events (*c1);
1033 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1037 generate_db_fade (c1, len, num_steps, -1); // start off with a slow fade
1038 generate_db_fade (c2, len, num_steps, -80); // end with a fast fade
1039 merge_curves (_fade_in.val(), c1, c2);
1040 reverse_curve (c3, _fade_in.val());
1041 _fade_in->copy_events (*c3);
1042 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1045 case FadeConstantPower:
1046 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1047 for (int i = 1; i < num_steps; ++i) {
1048 const float dist = i / (num_steps + 1.f);
1049 _fade_in->fast_simple_add (len * dist, sin (dist * M_PI / 2.0));
1051 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1052 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1056 //start with a nearly linear cuve
1057 _fade_in->fast_simple_add (0, 1);
1058 _fade_in->fast_simple_add (0.5 * len, 0.6);
1059 //now generate a fade-out curve by successively applying a gain drop
1060 const double breakpoint = 0.7; //linear for first 70%
1061 for (int i = 2; i < 9; ++i) {
1062 const float coeff = (1.f - breakpoint) * powf (0.5, i);
1063 _fade_in->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1065 _fade_in->fast_simple_add (len, GAIN_COEFF_SMALL);
1066 reverse_curve (c3, _fade_in.val());
1067 _fade_in->copy_events (*c3);
1068 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1072 _fade_in->set_interpolation(Evoral::ControlList::Curved);
1073 _inverse_fade_in->set_interpolation(Evoral::ControlList::Curved);
1075 _default_fade_in = false;
1077 send_change (PropertyChange (Properties::fade_in));
1081 AudioRegion::set_fade_out (boost::shared_ptr<AutomationList> f)
1083 _fade_out->freeze ();
1084 *(_fade_out.val()) = *f;
1086 _default_fade_out = false;
1088 send_change (PropertyChange (Properties::fade_out));
1092 AudioRegion::set_fade_out (FadeShape shape, samplecnt_t len)
1094 const ARDOUR::ParameterDescriptor desc(FadeOutAutomation);
1095 boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeOutAutomation, desc));
1096 boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeOutAutomation, desc));
1098 _fade_out->freeze ();
1099 _fade_out->clear ();
1100 _inverse_fade_out->clear ();
1102 const int num_steps = 32;
1106 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1107 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1108 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1112 generate_db_fade (_fade_out.val(), len, num_steps, -60);
1113 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1117 generate_db_fade (c1, len, num_steps, -1); //start off with a slow fade
1118 generate_db_fade (c2, len, num_steps, -80); //end with a fast fade
1119 merge_curves (_fade_out.val(), c1, c2);
1120 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1123 case FadeConstantPower:
1124 //constant-power fades use a sin/cos relationship
1125 //the cutoff is abrupt but it has the benefit of being symmetrical
1126 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1127 for (int i = 1; i < num_steps; ++i) {
1128 const float dist = i / (num_steps + 1.f);
1129 _fade_out->fast_simple_add (len * dist, cos (dist * M_PI / 2.0));
1131 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1132 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1136 //start with a nearly linear cuve
1137 _fade_out->fast_simple_add (0, 1);
1138 _fade_out->fast_simple_add (0.5 * len, 0.6);
1139 //now generate a fade-out curve by successively applying a gain drop
1140 const double breakpoint = 0.7; //linear for first 70%
1141 for (int i = 2; i < 9; ++i) {
1142 const float coeff = (1.f - breakpoint) * powf (0.5, i);
1143 _fade_out->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1145 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1146 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1150 _fade_out->set_interpolation(Evoral::ControlList::Curved);
1151 _inverse_fade_out->set_interpolation(Evoral::ControlList::Curved);
1153 _default_fade_out = false;
1155 send_change (PropertyChange (Properties::fade_out));
1159 AudioRegion::set_fade_in_length (samplecnt_t len)
1161 if (len > _length) {
1169 bool changed = _fade_in->extend_to (len);
1172 if (_inverse_fade_in) {
1173 _inverse_fade_in->extend_to (len);
1176 _default_fade_in = false;
1177 send_change (PropertyChange (Properties::fade_in));
1182 AudioRegion::set_fade_out_length (samplecnt_t len)
1184 if (len > _length) {
1192 bool changed = _fade_out->extend_to (len);
1196 if (_inverse_fade_out) {
1197 _inverse_fade_out->extend_to (len);
1199 _default_fade_out = false;
1201 send_change (PropertyChange (Properties::fade_out));
1206 AudioRegion::set_fade_in_active (bool yn)
1208 if (yn == _fade_in_active) {
1212 _fade_in_active = yn;
1213 send_change (PropertyChange (Properties::fade_in_active));
1217 AudioRegion::set_fade_out_active (bool yn)
1219 if (yn == _fade_out_active) {
1222 _fade_out_active = yn;
1223 send_change (PropertyChange (Properties::fade_out_active));
1227 AudioRegion::fade_in_is_default () const
1229 return _fade_in->size() == 2 && _fade_in->front()->when == 0 && _fade_in->back()->when == 64;
1233 AudioRegion::fade_out_is_default () const
1235 return _fade_out->size() == 2 && _fade_out->front()->when == 0 && _fade_out->back()->when == 64;
1239 AudioRegion::set_default_fade_in ()
1241 _fade_in_suspended = 0;
1242 set_fade_in (Config->get_default_fade_shape(), 64);
1246 AudioRegion::set_default_fade_out ()
1248 _fade_out_suspended = 0;
1249 set_fade_out (Config->get_default_fade_shape(), 64);
1253 AudioRegion::set_default_fades ()
1255 set_default_fade_in ();
1256 set_default_fade_out ();
1260 AudioRegion::set_default_envelope ()
1262 _envelope->freeze ();
1263 _envelope->clear ();
1264 _envelope->fast_simple_add (0, GAIN_COEFF_UNITY);
1265 _envelope->fast_simple_add (_length, GAIN_COEFF_UNITY);
1270 AudioRegion::recompute_at_end ()
1272 /* our length has changed. recompute a new final point by interpolating
1273 based on the the existing curve.
1276 _envelope->freeze ();
1277 _envelope->truncate_end (_length);
1280 suspend_property_changes();
1282 if (_left_of_split) {
1283 set_default_fade_out ();
1284 _left_of_split = false;
1285 } else if (_fade_out->back()->when > _length) {
1286 _fade_out->extend_to (_length);
1287 send_change (PropertyChange (Properties::fade_out));
1290 if (_fade_in->back()->when > _length) {
1291 _fade_in->extend_to (_length);
1292 send_change (PropertyChange (Properties::fade_in));
1295 resume_property_changes();
1299 AudioRegion::recompute_at_start ()
1301 /* as above, but the shift was from the front */
1303 _envelope->truncate_start (_length);
1305 suspend_property_changes();
1307 if (_right_of_split) {
1308 set_default_fade_in ();
1309 _right_of_split = false;
1310 } else if (_fade_in->back()->when > _length) {
1311 _fade_in->extend_to (_length);
1312 send_change (PropertyChange (Properties::fade_in));
1315 if (_fade_out->back()->when > _length) {
1316 _fade_out->extend_to (_length);
1317 send_change (PropertyChange (Properties::fade_out));
1320 resume_property_changes();
1324 AudioRegion::separate_by_channel (vector<boost::shared_ptr<Region> >& v) const
1330 if (_sources.size() < 2) {
1334 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1336 srcs.push_back (*i);
1340 if (_sources.size() == 2) {
1348 new_name += ('0' + n + 1);
1351 /* create a copy with just one source. prevent if from being thought of as
1352 "whole file" even if it covers the entire source file(s).
1357 plist.add (Properties::start, _start.val());
1358 plist.add (Properties::length, _length.val());
1359 plist.add (Properties::name, new_name);
1360 plist.add (Properties::layer, layer ());
1362 v.push_back(RegionFactory::create (srcs, plist));
1363 v.back()->set_whole_file (false);
1372 AudioRegion::read_raw_internal (Sample* buf, samplepos_t pos, samplecnt_t cnt, int channel) const
1374 return audio_source(channel)->read (buf, pos, cnt);
1378 AudioRegion::set_scale_amplitude (gain_t g)
1380 boost::shared_ptr<Playlist> pl (playlist());
1382 _scale_amplitude = g;
1384 /* tell the diskstream we're in */
1387 pl->ContentsChanged();
1390 /* tell everybody else */
1392 send_change (PropertyChange (Properties::scale_amplitude));
1396 AudioRegion::maximum_amplitude (Progress* p) const
1398 samplepos_t fpos = _start;
1399 samplepos_t const fend = _start + _length;
1402 samplecnt_t const blocksize = 64 * 1024;
1403 Sample buf[blocksize];
1405 while (fpos < fend) {
1409 samplecnt_t const to_read = min (fend - fpos, blocksize);
1411 for (n = 0; n < n_channels(); ++n) {
1415 if (read_raw_internal (buf, fpos, to_read, n) != to_read) {
1419 maxamp = compute_peak (buf, to_read, maxamp);
1424 p->set_progress (float (fpos - _start) / _length);
1425 if (p->cancelled ()) {
1435 AudioRegion::rms (Progress* p) const
1437 samplepos_t fpos = _start;
1438 samplepos_t const fend = _start + _length;
1439 uint32_t const n_chan = n_channels ();
1442 samplecnt_t const blocksize = 64 * 1024;
1443 Sample buf[blocksize];
1445 samplecnt_t total = 0;
1447 if (n_chan == 0 || fend == fpos) {
1451 while (fpos < fend) {
1452 samplecnt_t const to_read = min (fend - fpos, blocksize);
1453 for (uint32_t c = 0; c < n_chan; ++c) {
1454 if (read_raw_internal (buf, fpos, to_read, c) != to_read) {
1457 for (samplepos_t i = 0; i < to_read; ++i) {
1458 rms += buf[i] * buf[i];
1464 p->set_progress (float (fpos - _start) / _length);
1465 if (p->cancelled ()) {
1470 return sqrt (2. * rms / (double)(total * n_chan));
1473 /** Normalize using a given maximum amplitude and target, so that region
1474 * _scale_amplitude becomes target / max_amplitude.
1477 AudioRegion::normalize (float max_amplitude, float target_dB)
1479 gain_t target = dB_to_coefficient (target_dB);
1481 if (target == GAIN_COEFF_UNITY) {
1482 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1483 that we may have clipped.
1485 target -= FLT_EPSILON;
1488 if (max_amplitude < GAIN_COEFF_SMALL) {
1489 /* don't even try */
1493 if (max_amplitude == target) {
1494 /* we can't do anything useful */
1498 set_scale_amplitude (target / max_amplitude);
1502 AudioRegion::fade_in_changed ()
1504 send_change (PropertyChange (Properties::fade_in));
1508 AudioRegion::fade_out_changed ()
1510 send_change (PropertyChange (Properties::fade_out));
1514 AudioRegion::envelope_changed ()
1516 send_change (PropertyChange (Properties::envelope));
1520 AudioRegion::suspend_fade_in ()
1522 if (++_fade_in_suspended == 1) {
1523 if (fade_in_is_default()) {
1524 set_fade_in_active (false);
1530 AudioRegion::resume_fade_in ()
1532 if (--_fade_in_suspended == 0 && _fade_in_suspended) {
1533 set_fade_in_active (true);
1538 AudioRegion::suspend_fade_out ()
1540 if (++_fade_out_suspended == 1) {
1541 if (fade_out_is_default()) {
1542 set_fade_out_active (false);
1548 AudioRegion::resume_fade_out ()
1550 if (--_fade_out_suspended == 0 &&_fade_out_suspended) {
1551 set_fade_out_active (true);
1556 AudioRegion::speed_mismatch (float sr) const
1558 if (_sources.empty()) {
1559 /* impossible, but ... */
1563 float fsr = audio_source()->sample_rate();
1569 AudioRegion::source_offset_changed ()
1571 /* XXX this fixes a crash that should not occur. It does occur
1572 becauses regions are not being deleted when a session
1573 is unloaded. That bug must be fixed.
1576 if (_sources.empty()) {
1580 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1582 if (afs && afs->destructive()) {
1583 // set_start (source()->natural_position(), this);
1584 set_position (source()->natural_position());
1588 boost::shared_ptr<AudioSource>
1589 AudioRegion::audio_source (uint32_t n) const
1591 // Guaranteed to succeed (use a static cast for speed?)
1592 return boost::dynamic_pointer_cast<AudioSource>(source(n));
1596 AudioRegion::get_related_audio_file_channel_count () const
1598 uint32_t chan_count = 0;
1599 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1601 boost::shared_ptr<SndFileSource> sndf = boost::dynamic_pointer_cast<SndFileSource>(*i);
1604 if (sndf->channel_count() > chan_count) {
1605 chan_count = sndf->channel_count();
1608 #ifdef HAVE_COREAUDIO
1610 boost::shared_ptr<CoreAudioSource> cauf = boost::dynamic_pointer_cast<CoreAudioSource>(*i);
1612 if (cauf->channel_count() > chan_count) {
1613 chan_count = cauf->channel_count();
1617 #endif // HAVE_COREAUDIO
1624 AudioRegion::clear_transients () // yet unused
1626 _user_transients.clear ();
1627 _valid_transients = false;
1628 send_change (PropertyChange (Properties::valid_transients));
1632 AudioRegion::add_transient (samplepos_t where)
1634 if (where < first_sample () || where >= last_sample ()) {
1639 if (!_valid_transients) {
1640 _transient_user_start = _start;
1641 _valid_transients = true;
1643 sampleoffset_t offset = _transient_user_start - _start;
1645 if (where < offset) {
1649 // region start changed (extend to front), shift points and offset
1650 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1653 _transient_user_start -= offset;
1657 const samplepos_t p = where - offset;
1658 _user_transients.push_back(p);
1659 send_change (PropertyChange (Properties::valid_transients));
1663 AudioRegion::update_transient (samplepos_t old_position, samplepos_t new_position)
1665 bool changed = false;
1666 if (!_onsets.empty ()) {
1667 const samplepos_t p = old_position - _position;
1668 AnalysisFeatureList::iterator x = std::find (_onsets.begin (), _onsets.end (), p);
1669 if (x != _transients.end ()) {
1670 (*x) = new_position - _position;
1675 if (_valid_transients) {
1676 const sampleoffset_t offset = _position + _transient_user_start - _start;
1677 const samplepos_t p = old_position - offset;
1678 AnalysisFeatureList::iterator x = std::find (_user_transients.begin (), _user_transients.end (), p);
1679 if (x != _transients.end ()) {
1680 (*x) = new_position - offset;
1686 send_change (PropertyChange (Properties::valid_transients));
1691 AudioRegion::remove_transient (samplepos_t where)
1693 bool changed = false;
1694 if (!_onsets.empty ()) {
1695 const samplepos_t p = where - _position;
1696 AnalysisFeatureList::iterator i = std::find (_onsets.begin (), _onsets.end (), p);
1697 if (i != _transients.end ()) {
1703 if (_valid_transients) {
1704 const samplepos_t p = where - (_position + _transient_user_start - _start);
1705 AnalysisFeatureList::iterator i = std::find (_user_transients.begin (), _user_transients.end (), p);
1706 if (i != _transients.end ()) {
1707 _transients.erase (i);
1713 send_change (PropertyChange (Properties::valid_transients));
1718 AudioRegion::set_onsets (AnalysisFeatureList& results)
1722 send_change (PropertyChange (Properties::valid_transients));
1726 AudioRegion::build_transients ()
1728 _transients.clear ();
1729 _transient_analysis_start = _transient_analysis_end = 0;
1731 boost::shared_ptr<Playlist> pl = playlist();
1737 /* check analyzed sources first */
1738 SourceList::iterator s;
1739 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1740 if (!(*s)->has_been_analysed()) {
1742 cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
1748 if (s == _sources.end()) {
1749 /* all sources are analyzed, merge data from each one */
1750 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1752 /* find the set of transients within the bounds of this region */
1753 AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
1754 (*s)->transients.end(),
1757 AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
1758 (*s)->transients.end(),
1762 _transients.insert (_transients.end(), low, high);
1765 TransientDetector::cleanup_transients (_transients, pl->session().sample_rate(), 3.0);
1767 /* translate all transients to current position */
1768 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1772 _transient_analysis_start = _start;
1773 _transient_analysis_end = _start + _length;
1777 /* no existing/complete transient info */
1779 static bool analyse_dialog_shown = false; /* global per instance of Ardour */
1781 if (!Config->get_auto_analyse_audio()) {
1782 if (!analyse_dialog_shown) {
1783 pl->session().Dialog (string_compose (_("\
1784 You have requested an operation that requires audio analysis.\n\n\
1785 You currently have \"auto-analyse-audio\" disabled, which means \
1786 that transient data must be generated every time it is required.\n\n\
1787 If you are doing work that will require transient data on a \
1788 regular basis, you should probably enable \"auto-analyse-audio\" \
1789 in Preferences > Audio > Regions, then quit %1 and restart.\n\n\
1790 This dialog will not display again. But you may notice a slight delay \
1791 in this and future transient-detection operations.\n\
1793 analyse_dialog_shown = true;
1798 TransientDetector t (pl->session().sample_rate());
1799 for (uint32_t i = 0; i < n_channels(); ++i) {
1801 AnalysisFeatureList these_results;
1805 /* this produces analysis result relative to current position
1806 * ::read() sample 0 is at _position */
1807 if (t.run ("", this, i, these_results)) {
1812 _transients.insert (_transients.end(), these_results.begin(), these_results.end());
1815 error << string_compose(_("Transient Analysis failed for %1."), _("Audio Region")) << endmsg;
1819 TransientDetector::cleanup_transients (_transients, pl->session().sample_rate(), 3.0);
1820 _transient_analysis_start = _start;
1821 _transient_analysis_end = _start + _length;
1824 /* Transient analysis uses ::read() which is relative to _start,
1825 * at the time of analysis and spans _length samples.
1827 * This is true for RhythmFerret::run_analysis and the
1828 * TransientDetector here.
1830 * We store _start and length in _transient_analysis_start,
1831 * _transient_analysis_end in case the region is trimmed or split after analysis.
1833 * Various methods (most notably Playlist::find_next_transient and
1834 * RhythmFerret::do_split_action) span multiple regions and *merge/combine*
1836 * We therefore need to translate the analysis timestamps to absolute session-time
1837 * and include the _position of the region.
1839 * Note: we should special case the AudioRegionView. The region-view itself
1840 * is located at _position (currently ARV subtracts _position again)
1843 AudioRegion::get_transients (AnalysisFeatureList& results)
1845 boost::shared_ptr<Playlist> pl = playlist();
1850 Region::merge_features (results, _user_transients, _position + _transient_user_start - _start);
1852 if (!_onsets.empty ()) {
1853 // onsets are invalidated when start or length changes
1854 merge_features (results, _onsets, _position);
1858 if ((_transient_analysis_start == _transient_analysis_end)
1859 || _transient_analysis_start > _start
1860 || _transient_analysis_end < _start + _length) {
1861 build_transients ();
1864 merge_features (results, _transients, _position + _transient_analysis_start - _start);
1867 /** Find areas of `silence' within a region.
1869 * @param threshold Threshold below which signal is considered silence (as a sample value)
1870 * @param min_length Minimum length of silent period to be reported.
1871 * @return Silent intervals, measured relative to the region start in the source
1875 AudioRegion::find_silence (Sample threshold, samplecnt_t min_length, samplecnt_t fade_length, InterThreadInfo& itt) const
1877 samplecnt_t const block_size = 64 * 1024;
1878 boost::scoped_array<Sample> loudest (new Sample[block_size]);
1879 boost::scoped_array<Sample> buf (new Sample[block_size]);
1881 assert (fade_length >= 0);
1882 assert (min_length > 0);
1884 samplepos_t pos = _start;
1885 samplepos_t const end = _start + _length;
1887 AudioIntervalResult silent_periods;
1889 bool in_silence = true;
1890 sampleoffset_t silence_start = _start;
1892 while (pos < end && !itt.cancel) {
1894 samplecnt_t cur_samples = 0;
1895 samplecnt_t const to_read = min (end - pos, block_size);
1896 /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
1897 memset (loudest.get(), 0, sizeof (Sample) * block_size);
1899 for (uint32_t n = 0; n < n_channels(); ++n) {
1901 cur_samples = read_raw_internal (buf.get(), pos, to_read, n);
1902 for (samplecnt_t i = 0; i < cur_samples; ++i) {
1903 loudest[i] = max (loudest[i], abs (buf[i]));
1907 /* now look for silence */
1908 for (samplecnt_t i = 0; i < cur_samples; ++i) {
1909 bool const silence = abs (loudest[i]) < threshold;
1910 if (silence && !in_silence) {
1911 /* non-silence to silence */
1913 silence_start = pos + i + fade_length;
1914 } else if (!silence && in_silence) {
1915 /* silence to non-silence */
1917 sampleoffset_t silence_end = pos + i - 1 - fade_length;
1919 if (silence_end - silence_start >= min_length) {
1920 silent_periods.push_back (std::make_pair (silence_start, silence_end));
1926 itt.progress = (end - pos) / (double)_length;
1928 if (cur_samples == 0) {
1929 assert (pos >= end);
1934 if (in_silence && !itt.cancel) {
1935 /* last block was silent, so finish off the last period */
1936 if (end - 1 - silence_start >= min_length + fade_length) {
1937 silent_periods.push_back (std::make_pair (silence_start, end - 1));
1943 return silent_periods;
1946 Evoral::Range<samplepos_t>
1947 AudioRegion::body_range () const
1949 return Evoral::Range<samplepos_t> (first_sample() + _fade_in->back()->when + 1, last_sample() - _fade_out->back()->when);
1952 boost::shared_ptr<Region>
1953 AudioRegion::get_single_other_xfade_region (bool start) const
1955 boost::shared_ptr<Playlist> pl (playlist());
1958 /* not currently in a playlist - xfade length is unbounded
1961 return boost::shared_ptr<AudioRegion> ();
1964 boost::shared_ptr<RegionList> rl;
1967 rl = pl->regions_at (position());
1969 rl = pl->regions_at (last_sample());
1972 RegionList::iterator i;
1973 boost::shared_ptr<Region> other;
1976 /* count and find the other region in a single pass through the list */
1978 for (i = rl->begin(); i != rl->end(); ++i) {
1979 if ((*i).get() != this) {
1986 /* zero or multiple regions stacked here - don't care about xfades */
1987 return boost::shared_ptr<AudioRegion> ();
1994 AudioRegion::verify_xfade_bounds (samplecnt_t len, bool start)
1996 /* this is called from a UI to check on whether a new proposed
1997 length for an xfade is legal or not. it returns the legal
1998 length corresponding to @a len which may be shorter than or
1999 equal to @a len itself.
2002 boost::shared_ptr<Region> other = get_single_other_xfade_region (start);
2006 /* zero or > 2 regions here, don't care about len, but
2007 it can't be longer than the region itself.
2009 return min (length(), len);
2012 /* we overlap a single region. clamp the length of an xfade to
2013 the maximum possible duration of the overlap (if the other
2014 region were trimmed appropriately).
2018 maxlen = other->latest_possible_sample() - position();
2020 maxlen = last_sample() - other->earliest_possible_position();
2023 return min (length(), min (maxlen, len));