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, framepos_t start, framecnt_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, framecnt_t offset, const int32_t sub_num)
283 : Region (other, offset, sub_num)
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, 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 frames_per_pixel Number of samples to use to generate one peak value.
425 AudioRegion::read_peaks (PeakData *buf, framecnt_t npeaks, framecnt_t offset, framecnt_t cnt, uint32_t chan_n, double frames_per_pixel) const
427 if (chan_n >= _sources.size()) {
431 if (audio_source(chan_n)->read_peaks (buf, npeaks, offset, cnt, frames_per_pixel)) {
435 if (_scale_amplitude != 1.0f) {
436 for (framecnt_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 frames to read.
448 * @param channel Channel to read from.
451 AudioRegion::read (Sample* buf, framepos_t pos, framecnt_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 framepos_t position, framecnt_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 frames to read.
475 * @param chan_n Channel number to read.
478 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
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 frameoffset_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 framecnt_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 frameoffset_t fade_out_offset = 0;
523 /* Amount (length) of fade out that we are dealing with in this read */
524 framecnt_t fade_out_limit = 0;
526 framecnt_t fade_interval_start = 0;
530 if (_fade_in_active && _session.config.get_use_region_fades()) {
532 framecnt_t fade_in_length = (framecnt_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 - framecnt_t (_fade_out->back()->when));
565 framecnt_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 (framecnt_t n = 0; n < to_read; ++n) {
591 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
594 for (framecnt_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 (framecnt_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 (framecnt_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 (framecnt_t n = 0; n < fade_in_limit; ++n) {
647 buf[n] += mixdown_buffer[n] * gain_buffer[n];
651 if (fade_out_limit != 0) {
653 framecnt_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 (framecnt_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 (framecnt_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 (framecnt_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 framecnt_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 frames.
717 * @param cnt Number of frames to read.
718 * @param chan_n Channel to read from.
719 * @return Number of frames read.
723 AudioRegion::read_from_sources (SourceList const & srcs, framecnt_t limit, Sample* buf, framepos_t position, framecnt_t cnt, uint32_t chan_n) const
725 frameoffset_t const internal_offset = position - _position;
726 if (internal_offset >= limit) {
730 framecnt_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 ());
776 snprintf (buf, sizeof (buf), "%u", (uint32_t) _sources.size());
777 node.add_property ("channels", buf);
783 AudioRegion::state ()
785 XMLNode& node (get_basic_state());
789 child = node.add_child ("Envelope");
791 bool default_env = false;
793 // If there are only two points, the points are in the start of the region and the end of the region
794 // so, if they are both at 1.0f, that means the default region.
796 if (_envelope->size() == 2 &&
797 _envelope->front()->value == GAIN_COEFF_UNITY &&
798 _envelope->back()->value==GAIN_COEFF_UNITY) {
799 if (_envelope->front()->when == 0 && _envelope->back()->when == _length) {
805 child->add_property ("default", "yes");
807 child->add_child_nocopy (_envelope->get_state ());
810 child = node.add_child (X_("FadeIn"));
812 if (_default_fade_in) {
813 child->add_property ("default", "yes");
815 child->add_child_nocopy (_fade_in->get_state ());
818 if (_inverse_fade_in) {
819 child = node.add_child (X_("InverseFadeIn"));
820 child->add_child_nocopy (_inverse_fade_in->get_state ());
823 child = node.add_child (X_("FadeOut"));
825 if (_default_fade_out) {
826 child->add_property ("default", "yes");
828 child->add_child_nocopy (_fade_out->get_state ());
831 if (_inverse_fade_out) {
832 child = node.add_child (X_("InverseFadeOut"));
833 child->add_child_nocopy (_inverse_fade_out->get_state ());
840 AudioRegion::_set_state (const XMLNode& node, int version, PropertyChange& what_changed, bool send)
842 const XMLNodeList& nlist = node.children();
843 XMLProperty const * prop;
845 boost::shared_ptr<Playlist> the_playlist (_playlist.lock());
847 suspend_property_changes ();
850 the_playlist->freeze ();
854 /* this will set all our State members and stuff controlled by the Region.
855 It should NOT send any changed signals - that is our responsibility.
858 Region::_set_state (node, version, what_changed, false);
860 if ((prop = node.property ("scale-gain")) != 0) {
861 float a = atof (prop->value().c_str());
862 if (a != _scale_amplitude) {
863 _scale_amplitude = a;
864 what_changed.add (Properties::scale_amplitude);
868 /* Now find envelope description and other related child items */
870 _envelope->freeze ();
872 for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
874 XMLProperty const * prop;
878 if (child->name() == "Envelope") {
882 if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child, version)) {
883 set_default_envelope ();
886 _envelope->truncate_end (_length);
889 } else if (child->name() == "FadeIn") {
893 if (((prop = child->property ("default")) != 0 && string_is_affirmative (prop->value())) || (prop = child->property ("steepness")) != 0) {
894 set_default_fade_in ();
896 XMLNode* grandchild = child->child ("AutomationList");
898 _fade_in->set_state (*grandchild, version);
902 if ((prop = child->property ("active")) != 0) {
903 if (string_is_affirmative (prop->value())) {
904 set_fade_in_active (true);
906 set_fade_in_active (false);
910 } else if (child->name() == "FadeOut") {
914 if (((prop = child->property ("default")) != 0 && (string_is_affirmative (prop->value()))) || (prop = child->property ("steepness")) != 0) {
915 set_default_fade_out ();
917 XMLNode* grandchild = child->child ("AutomationList");
919 _fade_out->set_state (*grandchild, version);
923 if ((prop = child->property ("active")) != 0) {
924 if (string_is_affirmative (prop->value())) {
925 set_fade_out_active (true);
927 set_fade_out_active (false);
931 } else if ( (child->name() == "InverseFadeIn") || (child->name() == "InvFadeIn") ) {
932 XMLNode* grandchild = child->child ("AutomationList");
934 _inverse_fade_in->set_state (*grandchild, version);
936 } else if ( (child->name() == "InverseFadeOut") || (child->name() == "InvFadeOut") ) {
937 XMLNode* grandchild = child->child ("AutomationList");
939 _inverse_fade_out->set_state (*grandchild, version);
945 resume_property_changes ();
948 send_change (what_changed);
952 the_playlist->thaw ();
959 AudioRegion::set_state (const XMLNode& node, int version)
961 PropertyChange what_changed;
962 return _set_state (node, version, what_changed, true);
966 AudioRegion::fade_range (framepos_t start, framepos_t end)
970 switch (coverage (start, end)) {
971 case Evoral::OverlapStart:
975 set_fade_in (FadeConstantPower, e - s);
977 case Evoral::OverlapEnd:
980 e = _position + _length;
981 set_fade_out (FadeConstantPower, e - s);
983 case Evoral::OverlapInternal:
984 /* needs addressing, perhaps. Difficult to do if we can't
985 * control one edge of the fade relative to the relevant edge
986 * of the region, which we cannot - fades are currently assumed
987 * to start/end at the start/end of the region
996 AudioRegion::set_fade_in_shape (FadeShape shape)
998 set_fade_in (shape, (framecnt_t) _fade_in->back()->when);
1002 AudioRegion::set_fade_out_shape (FadeShape shape)
1004 set_fade_out (shape, (framecnt_t) _fade_out->back()->when);
1008 AudioRegion::set_fade_in (boost::shared_ptr<AutomationList> f)
1010 _fade_in->freeze ();
1011 *(_fade_in.val()) = *f;
1013 _default_fade_in = false;
1015 send_change (PropertyChange (Properties::fade_in));
1019 AudioRegion::set_fade_in (FadeShape shape, framecnt_t len)
1021 const ARDOUR::ParameterDescriptor desc(FadeInAutomation);
1022 boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeInAutomation, desc));
1023 boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeInAutomation, desc));
1024 boost::shared_ptr<Evoral::ControlList> c3 (new Evoral::ControlList (FadeInAutomation, desc));
1026 _fade_in->freeze ();
1028 _inverse_fade_in->clear ();
1030 const int num_steps = 32;
1034 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1035 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1036 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1040 generate_db_fade (_fade_in.val(), len, num_steps, -60);
1041 reverse_curve (c1, _fade_in.val());
1042 _fade_in->copy_events (*c1);
1043 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1047 generate_db_fade (c1, len, num_steps, -1); // start off with a slow fade
1048 generate_db_fade (c2, len, num_steps, -80); // end with a fast fade
1049 merge_curves (_fade_in.val(), c1, c2);
1050 reverse_curve (c3, _fade_in.val());
1051 _fade_in->copy_events (*c3);
1052 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1055 case FadeConstantPower:
1056 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1057 for (int i = 1; i < num_steps; ++i) {
1058 const float dist = i / (num_steps + 1.f);
1059 _fade_in->fast_simple_add (len * dist, sin (dist * M_PI / 2.0));
1061 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1062 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1066 //start with a nearly linear cuve
1067 _fade_in->fast_simple_add (0, 1);
1068 _fade_in->fast_simple_add (0.5 * len, 0.6);
1069 //now generate a fade-out curve by successively applying a gain drop
1070 const double breakpoint = 0.7; //linear for first 70%
1071 for (int i = 2; i < 9; ++i) {
1072 const float coeff = (1.f - breakpoint) * powf (0.5, i);
1073 _fade_in->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1075 _fade_in->fast_simple_add (len, GAIN_COEFF_SMALL);
1076 reverse_curve (c3, _fade_in.val());
1077 _fade_in->copy_events (*c3);
1078 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1082 _fade_in->set_interpolation(Evoral::ControlList::Curved);
1083 _inverse_fade_in->set_interpolation(Evoral::ControlList::Curved);
1085 _default_fade_in = false;
1087 send_change (PropertyChange (Properties::fade_in));
1091 AudioRegion::set_fade_out (boost::shared_ptr<AutomationList> f)
1093 _fade_out->freeze ();
1094 *(_fade_out.val()) = *f;
1096 _default_fade_out = false;
1098 send_change (PropertyChange (Properties::fade_in));
1102 AudioRegion::set_fade_out (FadeShape shape, framecnt_t len)
1104 const ARDOUR::ParameterDescriptor desc(FadeOutAutomation);
1105 boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeOutAutomation, desc));
1106 boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeOutAutomation, desc));
1108 _fade_out->freeze ();
1109 _fade_out->clear ();
1110 _inverse_fade_out->clear ();
1112 const int num_steps = 32;
1116 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1117 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1118 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1122 generate_db_fade (_fade_out.val(), len, num_steps, -60);
1123 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1127 generate_db_fade (c1, len, num_steps, -1); //start off with a slow fade
1128 generate_db_fade (c2, len, num_steps, -80); //end with a fast fade
1129 merge_curves (_fade_out.val(), c1, c2);
1130 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1133 case FadeConstantPower:
1134 //constant-power fades use a sin/cos relationship
1135 //the cutoff is abrupt but it has the benefit of being symmetrical
1136 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1137 for (int i = 1; i < num_steps; ++i) {
1138 const float dist = i / (num_steps + 1.f);
1139 _fade_out->fast_simple_add (len * dist, cos (dist * M_PI / 2.0));
1141 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1142 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1146 //start with a nearly linear cuve
1147 _fade_out->fast_simple_add (0, 1);
1148 _fade_out->fast_simple_add (0.5 * len, 0.6);
1149 //now generate a fade-out curve by successively applying a gain drop
1150 const double breakpoint = 0.7; //linear for first 70%
1151 for (int i = 2; i < 9; ++i) {
1152 const float coeff = (1.f - breakpoint) * powf (0.5, i);
1153 _fade_out->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1155 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1156 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1160 _fade_out->set_interpolation(Evoral::ControlList::Curved);
1161 _inverse_fade_out->set_interpolation(Evoral::ControlList::Curved);
1163 _default_fade_out = false;
1165 send_change (PropertyChange (Properties::fade_out));
1169 AudioRegion::set_fade_in_length (framecnt_t len)
1171 if (len > _length) {
1179 bool changed = _fade_in->extend_to (len);
1182 if (_inverse_fade_in) {
1183 _inverse_fade_in->extend_to (len);
1186 _default_fade_in = false;
1187 send_change (PropertyChange (Properties::fade_in));
1192 AudioRegion::set_fade_out_length (framecnt_t len)
1194 if (len > _length) {
1202 bool changed = _fade_out->extend_to (len);
1206 if (_inverse_fade_out) {
1207 _inverse_fade_out->extend_to (len);
1209 _default_fade_out = false;
1211 send_change (PropertyChange (Properties::fade_out));
1216 AudioRegion::set_fade_in_active (bool yn)
1218 if (yn == _fade_in_active) {
1222 _fade_in_active = yn;
1223 send_change (PropertyChange (Properties::fade_in_active));
1227 AudioRegion::set_fade_out_active (bool yn)
1229 if (yn == _fade_out_active) {
1232 _fade_out_active = yn;
1233 send_change (PropertyChange (Properties::fade_out_active));
1237 AudioRegion::fade_in_is_default () const
1239 return _fade_in->size() == 2 && _fade_in->front()->when == 0 && _fade_in->back()->when == 64;
1243 AudioRegion::fade_out_is_default () const
1245 return _fade_out->size() == 2 && _fade_out->front()->when == 0 && _fade_out->back()->when == 64;
1249 AudioRegion::set_default_fade_in ()
1251 _fade_in_suspended = 0;
1252 set_fade_in (Config->get_default_fade_shape(), 64);
1256 AudioRegion::set_default_fade_out ()
1258 _fade_out_suspended = 0;
1259 set_fade_out (Config->get_default_fade_shape(), 64);
1263 AudioRegion::set_default_fades ()
1265 set_default_fade_in ();
1266 set_default_fade_out ();
1270 AudioRegion::set_default_envelope ()
1272 _envelope->freeze ();
1273 _envelope->clear ();
1274 _envelope->fast_simple_add (0, GAIN_COEFF_UNITY);
1275 _envelope->fast_simple_add (_length, GAIN_COEFF_UNITY);
1280 AudioRegion::recompute_at_end ()
1282 /* our length has changed. recompute a new final point by interpolating
1283 based on the the existing curve.
1286 _envelope->freeze ();
1287 _envelope->truncate_end (_length);
1290 suspend_property_changes();
1292 if (_left_of_split) {
1293 set_default_fade_out ();
1294 _left_of_split = false;
1295 } else if (_fade_out->back()->when > _length) {
1296 _fade_out->extend_to (_length);
1297 send_change (PropertyChange (Properties::fade_out));
1300 if (_fade_in->back()->when > _length) {
1301 _fade_in->extend_to (_length);
1302 send_change (PropertyChange (Properties::fade_in));
1305 resume_property_changes();
1309 AudioRegion::recompute_at_start ()
1311 /* as above, but the shift was from the front */
1313 _envelope->truncate_start (_length);
1315 suspend_property_changes();
1317 if (_right_of_split) {
1318 set_default_fade_in ();
1319 _right_of_split = false;
1320 } else if (_fade_in->back()->when > _length) {
1321 _fade_in->extend_to (_length);
1322 send_change (PropertyChange (Properties::fade_in));
1325 if (_fade_out->back()->when > _length) {
1326 _fade_out->extend_to (_length);
1327 send_change (PropertyChange (Properties::fade_out));
1330 resume_property_changes();
1334 AudioRegion::separate_by_channel (Session& /*session*/, vector<boost::shared_ptr<Region> >& v) const
1340 if (_sources.size() < 2) {
1344 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1346 srcs.push_back (*i);
1350 if (_sources.size() == 2) {
1358 new_name += ('0' + n + 1);
1361 /* create a copy with just one source. prevent if from being thought of as
1362 "whole file" even if it covers the entire source file(s).
1367 plist.add (Properties::start, _start.val());
1368 plist.add (Properties::length, _length.val());
1369 plist.add (Properties::name, new_name);
1370 plist.add (Properties::layer, layer ());
1372 v.push_back(RegionFactory::create (srcs, plist));
1373 v.back()->set_whole_file (false);
1382 AudioRegion::read_raw_internal (Sample* buf, framepos_t pos, framecnt_t cnt, int channel) const
1384 return audio_source(channel)->read (buf, pos, cnt);
1388 AudioRegion::set_scale_amplitude (gain_t g)
1390 boost::shared_ptr<Playlist> pl (playlist());
1392 _scale_amplitude = g;
1394 /* tell the diskstream we're in */
1397 pl->ContentsChanged();
1400 /* tell everybody else */
1402 send_change (PropertyChange (Properties::scale_amplitude));
1405 /** @return the maximum (linear) amplitude of the region, or a -ve
1406 * number if the Progress object reports that the process was cancelled.
1409 AudioRegion::maximum_amplitude (Progress* p) const
1411 framepos_t fpos = _start;
1412 framepos_t const fend = _start + _length;
1415 framecnt_t const blocksize = 64 * 1024;
1416 Sample buf[blocksize];
1418 while (fpos < fend) {
1422 framecnt_t const to_read = min (fend - fpos, blocksize);
1424 for (n = 0; n < n_channels(); ++n) {
1428 if (read_raw_internal (buf, fpos, to_read, n) != to_read) {
1432 maxamp = compute_peak (buf, to_read, maxamp);
1437 p->set_progress (float (fpos - _start) / _length);
1438 if (p->cancelled ()) {
1447 /** Normalize using a given maximum amplitude and target, so that region
1448 * _scale_amplitude becomes target / max_amplitude.
1451 AudioRegion::normalize (float max_amplitude, float target_dB)
1453 gain_t target = dB_to_coefficient (target_dB);
1455 if (target == GAIN_COEFF_UNITY) {
1456 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1457 that we may have clipped.
1459 target -= FLT_EPSILON;
1462 if (max_amplitude < GAIN_COEFF_SMALL) {
1463 /* don't even try */
1467 if (max_amplitude == target) {
1468 /* we can't do anything useful */
1472 set_scale_amplitude (target / max_amplitude);
1476 AudioRegion::fade_in_changed ()
1478 send_change (PropertyChange (Properties::fade_in));
1482 AudioRegion::fade_out_changed ()
1484 send_change (PropertyChange (Properties::fade_out));
1488 AudioRegion::envelope_changed ()
1490 send_change (PropertyChange (Properties::envelope));
1494 AudioRegion::suspend_fade_in ()
1496 if (++_fade_in_suspended == 1) {
1497 if (fade_in_is_default()) {
1498 set_fade_in_active (false);
1504 AudioRegion::resume_fade_in ()
1506 if (--_fade_in_suspended == 0 && _fade_in_suspended) {
1507 set_fade_in_active (true);
1512 AudioRegion::suspend_fade_out ()
1514 if (++_fade_out_suspended == 1) {
1515 if (fade_out_is_default()) {
1516 set_fade_out_active (false);
1522 AudioRegion::resume_fade_out ()
1524 if (--_fade_out_suspended == 0 &&_fade_out_suspended) {
1525 set_fade_out_active (true);
1530 AudioRegion::speed_mismatch (float sr) const
1532 if (_sources.empty()) {
1533 /* impossible, but ... */
1537 float fsr = audio_source()->sample_rate();
1543 AudioRegion::source_offset_changed ()
1545 /* XXX this fixes a crash that should not occur. It does occur
1546 becauses regions are not being deleted when a session
1547 is unloaded. That bug must be fixed.
1550 if (_sources.empty()) {
1554 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1556 if (afs && afs->destructive()) {
1557 // set_start (source()->natural_position(), this);
1558 set_position (source()->natural_position());
1562 boost::shared_ptr<AudioSource>
1563 AudioRegion::audio_source (uint32_t n) const
1565 // Guaranteed to succeed (use a static cast for speed?)
1566 return boost::dynamic_pointer_cast<AudioSource>(source(n));
1570 AudioRegion::get_related_audio_file_channel_count () const
1572 uint32_t chan_count = 0;
1573 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1575 boost::shared_ptr<SndFileSource> sndf = boost::dynamic_pointer_cast<SndFileSource>(*i);
1578 if (sndf->channel_count() > chan_count) {
1579 chan_count = sndf->channel_count();
1582 #ifdef HAVE_COREAUDIO
1584 boost::shared_ptr<CoreAudioSource> cauf = boost::dynamic_pointer_cast<CoreAudioSource>(*i);
1586 if (cauf->channel_count() > chan_count) {
1587 chan_count = cauf->channel_count();
1591 #endif // HAVE_COREAUDIO
1598 AudioRegion::clear_transients () // yet unused
1600 _user_transients.clear ();
1601 _valid_transients = false;
1602 send_change (PropertyChange (Properties::valid_transients));
1606 AudioRegion::add_transient (framepos_t where)
1608 if (where < first_frame () || where >= last_frame ()) {
1613 if (!_valid_transients) {
1614 _transient_user_start = _start;
1615 _valid_transients = true;
1617 frameoffset_t offset = _transient_user_start - _start;
1619 if (where < offset) {
1623 // region start changed (extend to front), shift points and offset
1624 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1627 _transient_user_start -= offset;
1631 const framepos_t p = where - offset;
1632 _user_transients.push_back(p);
1633 send_change (PropertyChange (Properties::valid_transients));
1637 AudioRegion::update_transient (framepos_t old_position, framepos_t new_position)
1639 bool changed = false;
1640 if (!_onsets.empty ()) {
1641 const framepos_t p = old_position - _position;
1642 AnalysisFeatureList::iterator x = std::find (_onsets.begin (), _onsets.end (), p);
1643 if (x != _transients.end ()) {
1644 (*x) = new_position - _position;
1649 if (_valid_transients) {
1650 const frameoffset_t offset = _position + _transient_user_start - _start;
1651 const framepos_t p = old_position - offset;
1652 AnalysisFeatureList::iterator x = std::find (_user_transients.begin (), _user_transients.end (), p);
1653 if (x != _transients.end ()) {
1654 (*x) = new_position - offset;
1660 send_change (PropertyChange (Properties::valid_transients));
1665 AudioRegion::remove_transient (framepos_t where)
1667 bool changed = false;
1668 if (!_onsets.empty ()) {
1669 const framepos_t p = where - _position;
1670 AnalysisFeatureList::iterator i = std::find (_onsets.begin (), _onsets.end (), p);
1671 if (i != _transients.end ()) {
1677 if (_valid_transients) {
1678 const framepos_t p = where - (_position + _transient_user_start - _start);
1679 AnalysisFeatureList::iterator i = std::find (_user_transients.begin (), _user_transients.end (), p);
1680 if (i != _transients.end ()) {
1681 _transients.erase (i);
1687 send_change (PropertyChange (Properties::valid_transients));
1692 AudioRegion::set_onsets (AnalysisFeatureList& results)
1696 send_change (PropertyChange (Properties::valid_transients));
1700 AudioRegion::build_transients ()
1702 _transients.clear ();
1703 _transient_analysis_start = _transient_analysis_end = 0;
1705 boost::shared_ptr<Playlist> pl = playlist();
1711 /* check analyzed sources first */
1712 SourceList::iterator s;
1713 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1714 if (!(*s)->has_been_analysed()) {
1716 cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
1722 if (s == _sources.end()) {
1723 /* all sources are analyzed, merge data from each one */
1724 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1726 /* find the set of transients within the bounds of this region */
1727 AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
1728 (*s)->transients.end(),
1731 AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
1732 (*s)->transients.end(),
1736 _transients.insert (_transients.end(), low, high);
1739 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1741 /* translate all transients to current position */
1742 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1746 _transient_analysis_start = _start;
1747 _transient_analysis_end = _start + _length;
1751 /* no existing/complete transient info */
1753 static bool analyse_dialog_shown = false; /* global per instance of Ardour */
1755 if (!Config->get_auto_analyse_audio()) {
1756 if (!analyse_dialog_shown) {
1757 pl->session().Dialog (string_compose (_("\
1758 You have requested an operation that requires audio analysis.\n\n\
1759 You currently have \"auto-analyse-audio\" disabled, which means \
1760 that transient data must be generated every time it is required.\n\n\
1761 If you are doing work that will require transient data on a \
1762 regular basis, you should probably enable \"auto-analyse-audio\" \
1763 in Preferences > Audio > Regions, then quit %1 and restart.\n\n\
1764 This dialog will not display again. But you may notice a slight delay \
1765 in this and future transient-detection operations.\n\
1767 analyse_dialog_shown = true;
1772 TransientDetector t (pl->session().frame_rate());
1773 for (uint32_t i = 0; i < n_channels(); ++i) {
1775 AnalysisFeatureList these_results;
1779 /* this produces analysis result relative to current position
1780 * ::read() sample 0 is at _position */
1781 if (t.run ("", this, i, these_results)) {
1786 _transients.insert (_transients.end(), these_results.begin(), these_results.end());
1789 error << string_compose(_("Transient Analysis failed for %1."), _("Audio Region")) << endmsg;
1793 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1794 _transient_analysis_start = _start;
1795 _transient_analysis_end = _start + _length;
1798 /* Transient analysis uses ::read() which is relative to _start,
1799 * at the time of analysis and spans _length samples.
1801 * This is true for RhythmFerret::run_analysis and the
1802 * TransientDetector here.
1804 * We store _start and length in _transient_analysis_start,
1805 * _transient_analysis_end in case the region is trimmed or split after analysis.
1807 * Various methods (most notably Playlist::find_next_transient and
1808 * RhythmFerret::do_split_action) span multiple regions and *merge/combine*
1810 * We therefore need to translate the analysis timestamps to absolute session-time
1811 * and include the _position of the region.
1813 * Note: we should special case the AudioRegionView. The region-view itself
1814 * is located at _position (currently ARV subtracts _position again)
1817 AudioRegion::get_transients (AnalysisFeatureList& results)
1819 boost::shared_ptr<Playlist> pl = playlist();
1824 Region::merge_features (results, _user_transients, _position + _transient_user_start - _start);
1826 if (!_onsets.empty ()) {
1827 // onsets are invalidated when start or length changes
1828 merge_features (results, _onsets, _position);
1832 if ((_transient_analysis_start == _transient_analysis_end)
1833 || _transient_analysis_start > _start
1834 || _transient_analysis_end < _start + _length) {
1835 build_transients ();
1838 merge_features (results, _transients, _position + _transient_analysis_start - _start);
1841 /** Find areas of `silence' within a region.
1843 * @param threshold Threshold below which signal is considered silence (as a sample value)
1844 * @param min_length Minimum length of silent period to be reported.
1845 * @return Silent intervals, measured relative to the region start in the source
1849 AudioRegion::find_silence (Sample threshold, framecnt_t min_length, framecnt_t fade_length, InterThreadInfo& itt) const
1851 framecnt_t const block_size = 64 * 1024;
1852 boost::scoped_array<Sample> loudest (new Sample[block_size]);
1853 boost::scoped_array<Sample> buf (new Sample[block_size]);
1855 assert (fade_length >= 0);
1856 assert (min_length > 0);
1858 framepos_t pos = _start;
1859 framepos_t const end = _start + _length;
1861 AudioIntervalResult silent_periods;
1863 bool in_silence = true;
1864 frameoffset_t silence_start = _start;
1866 while (pos < end && !itt.cancel) {
1868 framecnt_t cur_samples = 0;
1869 framecnt_t const to_read = min (end - pos, block_size);
1870 /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
1871 memset (loudest.get(), 0, sizeof (Sample) * block_size);
1873 for (uint32_t n = 0; n < n_channels(); ++n) {
1875 cur_samples = read_raw_internal (buf.get(), pos, to_read, n);
1876 for (framecnt_t i = 0; i < cur_samples; ++i) {
1877 loudest[i] = max (loudest[i], abs (buf[i]));
1881 /* now look for silence */
1882 for (framecnt_t i = 0; i < cur_samples; ++i) {
1883 bool const silence = abs (loudest[i]) < threshold;
1884 if (silence && !in_silence) {
1885 /* non-silence to silence */
1887 silence_start = pos + i + fade_length;
1888 } else if (!silence && in_silence) {
1889 /* silence to non-silence */
1891 frameoffset_t silence_end = pos + i - 1 - fade_length;
1893 if (silence_end - silence_start >= min_length) {
1894 silent_periods.push_back (std::make_pair (silence_start, silence_end));
1900 itt.progress = (end - pos) / (double)_length;
1902 if (cur_samples == 0) {
1903 assert (pos >= end);
1908 if (in_silence && !itt.cancel) {
1909 /* last block was silent, so finish off the last period */
1910 if (end - 1 - silence_start >= min_length + fade_length) {
1911 silent_periods.push_back (std::make_pair (silence_start, end - 1));
1917 return silent_periods;
1920 Evoral::Range<framepos_t>
1921 AudioRegion::body_range () const
1923 return Evoral::Range<framepos_t> (first_frame() + _fade_in->back()->when + 1, last_frame() - _fade_out->back()->when);
1926 boost::shared_ptr<Region>
1927 AudioRegion::get_single_other_xfade_region (bool start) const
1929 boost::shared_ptr<Playlist> pl (playlist());
1932 /* not currently in a playlist - xfade length is unbounded
1935 return boost::shared_ptr<AudioRegion> ();
1938 boost::shared_ptr<RegionList> rl;
1941 rl = pl->regions_at (position());
1943 rl = pl->regions_at (last_frame());
1946 RegionList::iterator i;
1947 boost::shared_ptr<Region> other;
1950 /* count and find the other region in a single pass through the list */
1952 for (i = rl->begin(); i != rl->end(); ++i) {
1953 if ((*i).get() != this) {
1960 /* zero or multiple regions stacked here - don't care about xfades */
1961 return boost::shared_ptr<AudioRegion> ();
1968 AudioRegion::verify_xfade_bounds (framecnt_t len, bool start)
1970 /* this is called from a UI to check on whether a new proposed
1971 length for an xfade is legal or not. it returns the legal
1972 length corresponding to @a len which may be shorter than or
1973 equal to @a len itself.
1976 boost::shared_ptr<Region> other = get_single_other_xfade_region (start);
1980 /* zero or > 2 regions here, don't care about len, but
1981 it can't be longer than the region itself.
1983 return min (length(), len);
1986 /* we overlap a single region. clamp the length of an xfade to
1987 the maximum possible duration of the overlap (if the other
1988 region were trimmed appropriately).
1992 maxlen = other->latest_possible_frame() - position();
1994 maxlen = last_frame() - other->earliest_possible_position();
1997 return min (length(), min (maxlen, len));