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, MusicFrame 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.frame, 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 ());
775 node.set_property ("channels", (uint32_t)_sources.size());
781 AudioRegion::state ()
783 XMLNode& node (get_basic_state());
787 child = node.add_child ("Envelope");
789 bool default_env = false;
791 // If there are only two points, the points are in the start of the region and the end of the region
792 // so, if they are both at 1.0f, that means the default region.
794 if (_envelope->size() == 2 &&
795 _envelope->front()->value == GAIN_COEFF_UNITY &&
796 _envelope->back()->value==GAIN_COEFF_UNITY) {
797 if (_envelope->front()->when == 0 && _envelope->back()->when == _length) {
803 child->set_property ("default", "yes");
805 child->add_child_nocopy (_envelope->get_state ());
808 child = node.add_child (X_("FadeIn"));
810 if (_default_fade_in) {
811 child->set_property ("default", "yes");
813 child->add_child_nocopy (_fade_in->get_state ());
816 if (_inverse_fade_in) {
817 child = node.add_child (X_("InverseFadeIn"));
818 child->add_child_nocopy (_inverse_fade_in->get_state ());
821 child = node.add_child (X_("FadeOut"));
823 if (_default_fade_out) {
824 child->set_property ("default", "yes");
826 child->add_child_nocopy (_fade_out->get_state ());
829 if (_inverse_fade_out) {
830 child = node.add_child (X_("InverseFadeOut"));
831 child->add_child_nocopy (_inverse_fade_out->get_state ());
838 AudioRegion::_set_state (const XMLNode& node, int version, PropertyChange& what_changed, bool send)
840 const XMLNodeList& nlist = node.children();
842 boost::shared_ptr<Playlist> the_playlist (_playlist.lock());
844 suspend_property_changes ();
847 the_playlist->freeze ();
851 /* this will set all our State members and stuff controlled by the Region.
852 It should NOT send any changed signals - that is our responsibility.
855 Region::_set_state (node, version, what_changed, false);
858 if (node.get_property ("scale-gain", val)) {
859 if (val != _scale_amplitude) {
860 _scale_amplitude = val;
861 what_changed.add (Properties::scale_amplitude);
865 /* Now find envelope description and other related child items */
867 _envelope->freeze ();
869 for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
871 XMLProperty const * prop;
875 if (child->name() == "Envelope") {
879 if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child, version)) {
880 set_default_envelope ();
883 _envelope->truncate_end (_length);
886 } else if (child->name() == "FadeIn") {
891 if ((child->get_property ("default", is_default) && is_default) || (prop = child->property ("steepness")) != 0) {
892 set_default_fade_in ();
894 XMLNode* grandchild = child->child ("AutomationList");
896 _fade_in->set_state (*grandchild, version);
901 if (child->get_property ("active", is_active)) {
902 set_fade_in_active (is_active);
905 } else if (child->name() == "FadeOut") {
910 if ((child->get_property ("default", is_default) && is_default) || (prop = child->property ("steepness")) != 0) {
911 set_default_fade_out ();
913 XMLNode* grandchild = child->child ("AutomationList");
915 _fade_out->set_state (*grandchild, version);
920 if (child->get_property ("active", is_active)) {
921 set_fade_out_active (is_active);
924 } else if ( (child->name() == "InverseFadeIn") || (child->name() == "InvFadeIn") ) {
925 XMLNode* grandchild = child->child ("AutomationList");
927 _inverse_fade_in->set_state (*grandchild, version);
929 } else if ( (child->name() == "InverseFadeOut") || (child->name() == "InvFadeOut") ) {
930 XMLNode* grandchild = child->child ("AutomationList");
932 _inverse_fade_out->set_state (*grandchild, version);
938 resume_property_changes ();
941 send_change (what_changed);
945 the_playlist->thaw ();
952 AudioRegion::set_state (const XMLNode& node, int version)
954 PropertyChange what_changed;
955 return _set_state (node, version, what_changed, true);
959 AudioRegion::fade_range (framepos_t start, framepos_t end)
963 switch (coverage (start, end)) {
964 case Evoral::OverlapStart:
968 set_fade_in (FadeConstantPower, e - s);
970 case Evoral::OverlapEnd:
973 e = _position + _length;
974 set_fade_out (FadeConstantPower, e - s);
976 case Evoral::OverlapInternal:
977 /* needs addressing, perhaps. Difficult to do if we can't
978 * control one edge of the fade relative to the relevant edge
979 * of the region, which we cannot - fades are currently assumed
980 * to start/end at the start/end of the region
989 AudioRegion::set_fade_in_shape (FadeShape shape)
991 set_fade_in (shape, (framecnt_t) _fade_in->back()->when);
995 AudioRegion::set_fade_out_shape (FadeShape shape)
997 set_fade_out (shape, (framecnt_t) _fade_out->back()->when);
1001 AudioRegion::set_fade_in (boost::shared_ptr<AutomationList> f)
1003 _fade_in->freeze ();
1004 *(_fade_in.val()) = *f;
1006 _default_fade_in = false;
1008 send_change (PropertyChange (Properties::fade_in));
1012 AudioRegion::set_fade_in (FadeShape shape, framecnt_t len)
1014 const ARDOUR::ParameterDescriptor desc(FadeInAutomation);
1015 boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeInAutomation, desc));
1016 boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeInAutomation, desc));
1017 boost::shared_ptr<Evoral::ControlList> c3 (new Evoral::ControlList (FadeInAutomation, desc));
1019 _fade_in->freeze ();
1021 _inverse_fade_in->clear ();
1023 const int num_steps = 32;
1027 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1028 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1029 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1033 generate_db_fade (_fade_in.val(), len, num_steps, -60);
1034 reverse_curve (c1, _fade_in.val());
1035 _fade_in->copy_events (*c1);
1036 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1040 generate_db_fade (c1, len, num_steps, -1); // start off with a slow fade
1041 generate_db_fade (c2, len, num_steps, -80); // end with a fast fade
1042 merge_curves (_fade_in.val(), c1, c2);
1043 reverse_curve (c3, _fade_in.val());
1044 _fade_in->copy_events (*c3);
1045 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1048 case FadeConstantPower:
1049 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1050 for (int i = 1; i < num_steps; ++i) {
1051 const float dist = i / (num_steps + 1.f);
1052 _fade_in->fast_simple_add (len * dist, sin (dist * M_PI / 2.0));
1054 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1055 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1059 //start with a nearly linear cuve
1060 _fade_in->fast_simple_add (0, 1);
1061 _fade_in->fast_simple_add (0.5 * len, 0.6);
1062 //now generate a fade-out curve by successively applying a gain drop
1063 const double breakpoint = 0.7; //linear for first 70%
1064 for (int i = 2; i < 9; ++i) {
1065 const float coeff = (1.f - breakpoint) * powf (0.5, i);
1066 _fade_in->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1068 _fade_in->fast_simple_add (len, GAIN_COEFF_SMALL);
1069 reverse_curve (c3, _fade_in.val());
1070 _fade_in->copy_events (*c3);
1071 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1075 _fade_in->set_interpolation(Evoral::ControlList::Curved);
1076 _inverse_fade_in->set_interpolation(Evoral::ControlList::Curved);
1078 _default_fade_in = false;
1080 send_change (PropertyChange (Properties::fade_in));
1084 AudioRegion::set_fade_out (boost::shared_ptr<AutomationList> f)
1086 _fade_out->freeze ();
1087 *(_fade_out.val()) = *f;
1089 _default_fade_out = false;
1091 send_change (PropertyChange (Properties::fade_out));
1095 AudioRegion::set_fade_out (FadeShape shape, framecnt_t len)
1097 const ARDOUR::ParameterDescriptor desc(FadeOutAutomation);
1098 boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeOutAutomation, desc));
1099 boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeOutAutomation, desc));
1101 _fade_out->freeze ();
1102 _fade_out->clear ();
1103 _inverse_fade_out->clear ();
1105 const int num_steps = 32;
1109 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1110 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1111 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1115 generate_db_fade (_fade_out.val(), len, num_steps, -60);
1116 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1120 generate_db_fade (c1, len, num_steps, -1); //start off with a slow fade
1121 generate_db_fade (c2, len, num_steps, -80); //end with a fast fade
1122 merge_curves (_fade_out.val(), c1, c2);
1123 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1126 case FadeConstantPower:
1127 //constant-power fades use a sin/cos relationship
1128 //the cutoff is abrupt but it has the benefit of being symmetrical
1129 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1130 for (int i = 1; i < num_steps; ++i) {
1131 const float dist = i / (num_steps + 1.f);
1132 _fade_out->fast_simple_add (len * dist, cos (dist * M_PI / 2.0));
1134 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1135 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1139 //start with a nearly linear cuve
1140 _fade_out->fast_simple_add (0, 1);
1141 _fade_out->fast_simple_add (0.5 * len, 0.6);
1142 //now generate a fade-out curve by successively applying a gain drop
1143 const double breakpoint = 0.7; //linear for first 70%
1144 for (int i = 2; i < 9; ++i) {
1145 const float coeff = (1.f - breakpoint) * powf (0.5, i);
1146 _fade_out->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1148 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1149 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1153 _fade_out->set_interpolation(Evoral::ControlList::Curved);
1154 _inverse_fade_out->set_interpolation(Evoral::ControlList::Curved);
1156 _default_fade_out = false;
1158 send_change (PropertyChange (Properties::fade_out));
1162 AudioRegion::set_fade_in_length (framecnt_t len)
1164 if (len > _length) {
1172 bool changed = _fade_in->extend_to (len);
1175 if (_inverse_fade_in) {
1176 _inverse_fade_in->extend_to (len);
1179 _default_fade_in = false;
1180 send_change (PropertyChange (Properties::fade_in));
1185 AudioRegion::set_fade_out_length (framecnt_t len)
1187 if (len > _length) {
1195 bool changed = _fade_out->extend_to (len);
1199 if (_inverse_fade_out) {
1200 _inverse_fade_out->extend_to (len);
1202 _default_fade_out = false;
1204 send_change (PropertyChange (Properties::fade_out));
1209 AudioRegion::set_fade_in_active (bool yn)
1211 if (yn == _fade_in_active) {
1215 _fade_in_active = yn;
1216 send_change (PropertyChange (Properties::fade_in_active));
1220 AudioRegion::set_fade_out_active (bool yn)
1222 if (yn == _fade_out_active) {
1225 _fade_out_active = yn;
1226 send_change (PropertyChange (Properties::fade_out_active));
1230 AudioRegion::fade_in_is_default () const
1232 return _fade_in->size() == 2 && _fade_in->front()->when == 0 && _fade_in->back()->when == 64;
1236 AudioRegion::fade_out_is_default () const
1238 return _fade_out->size() == 2 && _fade_out->front()->when == 0 && _fade_out->back()->when == 64;
1242 AudioRegion::set_default_fade_in ()
1244 _fade_in_suspended = 0;
1245 set_fade_in (Config->get_default_fade_shape(), 64);
1249 AudioRegion::set_default_fade_out ()
1251 _fade_out_suspended = 0;
1252 set_fade_out (Config->get_default_fade_shape(), 64);
1256 AudioRegion::set_default_fades ()
1258 set_default_fade_in ();
1259 set_default_fade_out ();
1263 AudioRegion::set_default_envelope ()
1265 _envelope->freeze ();
1266 _envelope->clear ();
1267 _envelope->fast_simple_add (0, GAIN_COEFF_UNITY);
1268 _envelope->fast_simple_add (_length, GAIN_COEFF_UNITY);
1273 AudioRegion::recompute_at_end ()
1275 /* our length has changed. recompute a new final point by interpolating
1276 based on the the existing curve.
1279 _envelope->freeze ();
1280 _envelope->truncate_end (_length);
1283 suspend_property_changes();
1285 if (_left_of_split) {
1286 set_default_fade_out ();
1287 _left_of_split = false;
1288 } else if (_fade_out->back()->when > _length) {
1289 _fade_out->extend_to (_length);
1290 send_change (PropertyChange (Properties::fade_out));
1293 if (_fade_in->back()->when > _length) {
1294 _fade_in->extend_to (_length);
1295 send_change (PropertyChange (Properties::fade_in));
1298 resume_property_changes();
1302 AudioRegion::recompute_at_start ()
1304 /* as above, but the shift was from the front */
1306 _envelope->truncate_start (_length);
1308 suspend_property_changes();
1310 if (_right_of_split) {
1311 set_default_fade_in ();
1312 _right_of_split = false;
1313 } else if (_fade_in->back()->when > _length) {
1314 _fade_in->extend_to (_length);
1315 send_change (PropertyChange (Properties::fade_in));
1318 if (_fade_out->back()->when > _length) {
1319 _fade_out->extend_to (_length);
1320 send_change (PropertyChange (Properties::fade_out));
1323 resume_property_changes();
1327 AudioRegion::separate_by_channel (Session& /*session*/, vector<boost::shared_ptr<Region> >& v) const
1333 if (_sources.size() < 2) {
1337 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1339 srcs.push_back (*i);
1343 if (_sources.size() == 2) {
1351 new_name += ('0' + n + 1);
1354 /* create a copy with just one source. prevent if from being thought of as
1355 "whole file" even if it covers the entire source file(s).
1360 plist.add (Properties::start, _start.val());
1361 plist.add (Properties::length, _length.val());
1362 plist.add (Properties::name, new_name);
1363 plist.add (Properties::layer, layer ());
1365 v.push_back(RegionFactory::create (srcs, plist));
1366 v.back()->set_whole_file (false);
1375 AudioRegion::read_raw_internal (Sample* buf, framepos_t pos, framecnt_t cnt, int channel) const
1377 return audio_source(channel)->read (buf, pos, cnt);
1381 AudioRegion::set_scale_amplitude (gain_t g)
1383 boost::shared_ptr<Playlist> pl (playlist());
1385 _scale_amplitude = g;
1387 /* tell the diskstream we're in */
1390 pl->ContentsChanged();
1393 /* tell everybody else */
1395 send_change (PropertyChange (Properties::scale_amplitude));
1399 AudioRegion::maximum_amplitude (Progress* p) const
1401 framepos_t fpos = _start;
1402 framepos_t const fend = _start + _length;
1405 framecnt_t const blocksize = 64 * 1024;
1406 Sample buf[blocksize];
1408 while (fpos < fend) {
1412 framecnt_t const to_read = min (fend - fpos, blocksize);
1414 for (n = 0; n < n_channels(); ++n) {
1418 if (read_raw_internal (buf, fpos, to_read, n) != to_read) {
1422 maxamp = compute_peak (buf, to_read, maxamp);
1427 p->set_progress (float (fpos - _start) / _length);
1428 if (p->cancelled ()) {
1438 AudioRegion::rms (Progress* p) const
1440 framepos_t fpos = _start;
1441 framepos_t const fend = _start + _length;
1442 uint32_t const n_chan = n_channels ();
1445 framecnt_t const blocksize = 64 * 1024;
1446 Sample buf[blocksize];
1448 framecnt_t total = 0;
1450 if (n_chan == 0 || fend == fpos) {
1454 while (fpos < fend) {
1455 framecnt_t const to_read = min (fend - fpos, blocksize);
1456 for (uint32_t c = 0; c < n_chan; ++c) {
1457 if (read_raw_internal (buf, fpos, to_read, c) != to_read) {
1460 for (framepos_t i = 0; i < to_read; ++i) {
1461 rms += buf[i] * buf[i];
1467 p->set_progress (float (fpos - _start) / _length);
1468 if (p->cancelled ()) {
1473 return sqrt (2. * rms / (double)(total * n_chan));
1476 /** Normalize using a given maximum amplitude and target, so that region
1477 * _scale_amplitude becomes target / max_amplitude.
1480 AudioRegion::normalize (float max_amplitude, float target_dB)
1482 gain_t target = dB_to_coefficient (target_dB);
1484 if (target == GAIN_COEFF_UNITY) {
1485 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1486 that we may have clipped.
1488 target -= FLT_EPSILON;
1491 if (max_amplitude < GAIN_COEFF_SMALL) {
1492 /* don't even try */
1496 if (max_amplitude == target) {
1497 /* we can't do anything useful */
1501 set_scale_amplitude (target / max_amplitude);
1505 AudioRegion::fade_in_changed ()
1507 send_change (PropertyChange (Properties::fade_in));
1511 AudioRegion::fade_out_changed ()
1513 send_change (PropertyChange (Properties::fade_out));
1517 AudioRegion::envelope_changed ()
1519 send_change (PropertyChange (Properties::envelope));
1523 AudioRegion::suspend_fade_in ()
1525 if (++_fade_in_suspended == 1) {
1526 if (fade_in_is_default()) {
1527 set_fade_in_active (false);
1533 AudioRegion::resume_fade_in ()
1535 if (--_fade_in_suspended == 0 && _fade_in_suspended) {
1536 set_fade_in_active (true);
1541 AudioRegion::suspend_fade_out ()
1543 if (++_fade_out_suspended == 1) {
1544 if (fade_out_is_default()) {
1545 set_fade_out_active (false);
1551 AudioRegion::resume_fade_out ()
1553 if (--_fade_out_suspended == 0 &&_fade_out_suspended) {
1554 set_fade_out_active (true);
1559 AudioRegion::speed_mismatch (float sr) const
1561 if (_sources.empty()) {
1562 /* impossible, but ... */
1566 float fsr = audio_source()->sample_rate();
1572 AudioRegion::source_offset_changed ()
1574 /* XXX this fixes a crash that should not occur. It does occur
1575 becauses regions are not being deleted when a session
1576 is unloaded. That bug must be fixed.
1579 if (_sources.empty()) {
1583 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1585 if (afs && afs->destructive()) {
1586 // set_start (source()->natural_position(), this);
1587 set_position (source()->natural_position());
1591 boost::shared_ptr<AudioSource>
1592 AudioRegion::audio_source (uint32_t n) const
1594 // Guaranteed to succeed (use a static cast for speed?)
1595 return boost::dynamic_pointer_cast<AudioSource>(source(n));
1599 AudioRegion::get_related_audio_file_channel_count () const
1601 uint32_t chan_count = 0;
1602 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1604 boost::shared_ptr<SndFileSource> sndf = boost::dynamic_pointer_cast<SndFileSource>(*i);
1607 if (sndf->channel_count() > chan_count) {
1608 chan_count = sndf->channel_count();
1611 #ifdef HAVE_COREAUDIO
1613 boost::shared_ptr<CoreAudioSource> cauf = boost::dynamic_pointer_cast<CoreAudioSource>(*i);
1615 if (cauf->channel_count() > chan_count) {
1616 chan_count = cauf->channel_count();
1620 #endif // HAVE_COREAUDIO
1627 AudioRegion::clear_transients () // yet unused
1629 _user_transients.clear ();
1630 _valid_transients = false;
1631 send_change (PropertyChange (Properties::valid_transients));
1635 AudioRegion::add_transient (framepos_t where)
1637 if (where < first_frame () || where >= last_frame ()) {
1642 if (!_valid_transients) {
1643 _transient_user_start = _start;
1644 _valid_transients = true;
1646 frameoffset_t offset = _transient_user_start - _start;
1648 if (where < offset) {
1652 // region start changed (extend to front), shift points and offset
1653 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1656 _transient_user_start -= offset;
1660 const framepos_t p = where - offset;
1661 _user_transients.push_back(p);
1662 send_change (PropertyChange (Properties::valid_transients));
1666 AudioRegion::update_transient (framepos_t old_position, framepos_t new_position)
1668 bool changed = false;
1669 if (!_onsets.empty ()) {
1670 const framepos_t p = old_position - _position;
1671 AnalysisFeatureList::iterator x = std::find (_onsets.begin (), _onsets.end (), p);
1672 if (x != _transients.end ()) {
1673 (*x) = new_position - _position;
1678 if (_valid_transients) {
1679 const frameoffset_t offset = _position + _transient_user_start - _start;
1680 const framepos_t p = old_position - offset;
1681 AnalysisFeatureList::iterator x = std::find (_user_transients.begin (), _user_transients.end (), p);
1682 if (x != _transients.end ()) {
1683 (*x) = new_position - offset;
1689 send_change (PropertyChange (Properties::valid_transients));
1694 AudioRegion::remove_transient (framepos_t where)
1696 bool changed = false;
1697 if (!_onsets.empty ()) {
1698 const framepos_t p = where - _position;
1699 AnalysisFeatureList::iterator i = std::find (_onsets.begin (), _onsets.end (), p);
1700 if (i != _transients.end ()) {
1706 if (_valid_transients) {
1707 const framepos_t p = where - (_position + _transient_user_start - _start);
1708 AnalysisFeatureList::iterator i = std::find (_user_transients.begin (), _user_transients.end (), p);
1709 if (i != _transients.end ()) {
1710 _transients.erase (i);
1716 send_change (PropertyChange (Properties::valid_transients));
1721 AudioRegion::set_onsets (AnalysisFeatureList& results)
1725 send_change (PropertyChange (Properties::valid_transients));
1729 AudioRegion::build_transients ()
1731 _transients.clear ();
1732 _transient_analysis_start = _transient_analysis_end = 0;
1734 boost::shared_ptr<Playlist> pl = playlist();
1740 /* check analyzed sources first */
1741 SourceList::iterator s;
1742 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1743 if (!(*s)->has_been_analysed()) {
1745 cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
1751 if (s == _sources.end()) {
1752 /* all sources are analyzed, merge data from each one */
1753 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1755 /* find the set of transients within the bounds of this region */
1756 AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
1757 (*s)->transients.end(),
1760 AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
1761 (*s)->transients.end(),
1765 _transients.insert (_transients.end(), low, high);
1768 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1770 /* translate all transients to current position */
1771 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1775 _transient_analysis_start = _start;
1776 _transient_analysis_end = _start + _length;
1780 /* no existing/complete transient info */
1782 static bool analyse_dialog_shown = false; /* global per instance of Ardour */
1784 if (!Config->get_auto_analyse_audio()) {
1785 if (!analyse_dialog_shown) {
1786 pl->session().Dialog (string_compose (_("\
1787 You have requested an operation that requires audio analysis.\n\n\
1788 You currently have \"auto-analyse-audio\" disabled, which means \
1789 that transient data must be generated every time it is required.\n\n\
1790 If you are doing work that will require transient data on a \
1791 regular basis, you should probably enable \"auto-analyse-audio\" \
1792 in Preferences > Audio > Regions, then quit %1 and restart.\n\n\
1793 This dialog will not display again. But you may notice a slight delay \
1794 in this and future transient-detection operations.\n\
1796 analyse_dialog_shown = true;
1801 TransientDetector t (pl->session().frame_rate());
1802 for (uint32_t i = 0; i < n_channels(); ++i) {
1804 AnalysisFeatureList these_results;
1808 /* this produces analysis result relative to current position
1809 * ::read() sample 0 is at _position */
1810 if (t.run ("", this, i, these_results)) {
1815 _transients.insert (_transients.end(), these_results.begin(), these_results.end());
1818 error << string_compose(_("Transient Analysis failed for %1."), _("Audio Region")) << endmsg;
1822 TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
1823 _transient_analysis_start = _start;
1824 _transient_analysis_end = _start + _length;
1827 /* Transient analysis uses ::read() which is relative to _start,
1828 * at the time of analysis and spans _length samples.
1830 * This is true for RhythmFerret::run_analysis and the
1831 * TransientDetector here.
1833 * We store _start and length in _transient_analysis_start,
1834 * _transient_analysis_end in case the region is trimmed or split after analysis.
1836 * Various methods (most notably Playlist::find_next_transient and
1837 * RhythmFerret::do_split_action) span multiple regions and *merge/combine*
1839 * We therefore need to translate the analysis timestamps to absolute session-time
1840 * and include the _position of the region.
1842 * Note: we should special case the AudioRegionView. The region-view itself
1843 * is located at _position (currently ARV subtracts _position again)
1846 AudioRegion::get_transients (AnalysisFeatureList& results)
1848 boost::shared_ptr<Playlist> pl = playlist();
1853 Region::merge_features (results, _user_transients, _position + _transient_user_start - _start);
1855 if (!_onsets.empty ()) {
1856 // onsets are invalidated when start or length changes
1857 merge_features (results, _onsets, _position);
1861 if ((_transient_analysis_start == _transient_analysis_end)
1862 || _transient_analysis_start > _start
1863 || _transient_analysis_end < _start + _length) {
1864 build_transients ();
1867 merge_features (results, _transients, _position + _transient_analysis_start - _start);
1870 /** Find areas of `silence' within a region.
1872 * @param threshold Threshold below which signal is considered silence (as a sample value)
1873 * @param min_length Minimum length of silent period to be reported.
1874 * @return Silent intervals, measured relative to the region start in the source
1878 AudioRegion::find_silence (Sample threshold, framecnt_t min_length, framecnt_t fade_length, InterThreadInfo& itt) const
1880 framecnt_t const block_size = 64 * 1024;
1881 boost::scoped_array<Sample> loudest (new Sample[block_size]);
1882 boost::scoped_array<Sample> buf (new Sample[block_size]);
1884 assert (fade_length >= 0);
1885 assert (min_length > 0);
1887 framepos_t pos = _start;
1888 framepos_t const end = _start + _length;
1890 AudioIntervalResult silent_periods;
1892 bool in_silence = true;
1893 frameoffset_t silence_start = _start;
1895 while (pos < end && !itt.cancel) {
1897 framecnt_t cur_samples = 0;
1898 framecnt_t const to_read = min (end - pos, block_size);
1899 /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
1900 memset (loudest.get(), 0, sizeof (Sample) * block_size);
1902 for (uint32_t n = 0; n < n_channels(); ++n) {
1904 cur_samples = read_raw_internal (buf.get(), pos, to_read, n);
1905 for (framecnt_t i = 0; i < cur_samples; ++i) {
1906 loudest[i] = max (loudest[i], abs (buf[i]));
1910 /* now look for silence */
1911 for (framecnt_t i = 0; i < cur_samples; ++i) {
1912 bool const silence = abs (loudest[i]) < threshold;
1913 if (silence && !in_silence) {
1914 /* non-silence to silence */
1916 silence_start = pos + i + fade_length;
1917 } else if (!silence && in_silence) {
1918 /* silence to non-silence */
1920 frameoffset_t silence_end = pos + i - 1 - fade_length;
1922 if (silence_end - silence_start >= min_length) {
1923 silent_periods.push_back (std::make_pair (silence_start, silence_end));
1929 itt.progress = (end - pos) / (double)_length;
1931 if (cur_samples == 0) {
1932 assert (pos >= end);
1937 if (in_silence && !itt.cancel) {
1938 /* last block was silent, so finish off the last period */
1939 if (end - 1 - silence_start >= min_length + fade_length) {
1940 silent_periods.push_back (std::make_pair (silence_start, end - 1));
1946 return silent_periods;
1949 Evoral::Range<framepos_t>
1950 AudioRegion::body_range () const
1952 return Evoral::Range<framepos_t> (first_frame() + _fade_in->back()->when + 1, last_frame() - _fade_out->back()->when);
1955 boost::shared_ptr<Region>
1956 AudioRegion::get_single_other_xfade_region (bool start) const
1958 boost::shared_ptr<Playlist> pl (playlist());
1961 /* not currently in a playlist - xfade length is unbounded
1964 return boost::shared_ptr<AudioRegion> ();
1967 boost::shared_ptr<RegionList> rl;
1970 rl = pl->regions_at (position());
1972 rl = pl->regions_at (last_frame());
1975 RegionList::iterator i;
1976 boost::shared_ptr<Region> other;
1979 /* count and find the other region in a single pass through the list */
1981 for (i = rl->begin(); i != rl->end(); ++i) {
1982 if ((*i).get() != this) {
1989 /* zero or multiple regions stacked here - don't care about xfades */
1990 return boost::shared_ptr<AudioRegion> ();
1997 AudioRegion::verify_xfade_bounds (framecnt_t len, bool start)
1999 /* this is called from a UI to check on whether a new proposed
2000 length for an xfade is legal or not. it returns the legal
2001 length corresponding to @a len which may be shorter than or
2002 equal to @a len itself.
2005 boost::shared_ptr<Region> other = get_single_other_xfade_region (start);
2009 /* zero or > 2 regions here, don't care about len, but
2010 it can't be longer than the region itself.
2012 return min (length(), len);
2015 /* we overlap a single region. clamp the length of an xfade to
2016 the maximum possible duration of the overlap (if the other
2017 region were trimmed appropriately).
2021 maxlen = other->latest_possible_frame() - position();
2023 maxlen = last_frame() - other->earliest_possible_position();
2026 return min (length(), min (maxlen, len));