2 * Copyright (C) 2006-2014 David Robillard <d@drobilla.net>
3 * Copyright (C) 2006-2017 Paul Davis <paul@linuxaudiosystems.com>
4 * Copyright (C) 2007-2012 Carl Hetherington <carl@carlh.net>
5 * Copyright (C) 2012-2019 Robin Gareus <robin@gareus.org>
6 * Copyright (C) 2015-2018 Ben Loftis <ben@harrisonconsoles.com>
7 * Copyright (C) 2016-2017 Nick Mainsbridge <mainsbridge@gmail.com>
8 * Copyright (C) 2016 Tim Mayberry <mojofunk@gmail.com>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
32 #include <boost/scoped_array.hpp>
33 #include <boost/shared_ptr.hpp>
35 #include <glibmm/threads.h>
37 #include "pbd/basename.h"
38 #include "pbd/xml++.h"
39 #include "pbd/stacktrace.h"
40 #include "pbd/enumwriter.h"
41 #include "pbd/convert.h"
43 #include "evoral/Curve.hpp"
45 #include "ardour/audioregion.h"
46 #include "ardour/session.h"
47 #include "ardour/dB.h"
48 #include "ardour/debug.h"
49 #include "ardour/event_type_map.h"
50 #include "ardour/playlist.h"
51 #include "ardour/audiofilesource.h"
52 #include "ardour/region_factory.h"
53 #include "ardour/runtime_functions.h"
54 #include "ardour/transient_detector.h"
55 #include "ardour/parameter_descriptor.h"
56 #include "ardour/progress.h"
58 #include "ardour/sndfilesource.h"
60 #include "ardour/coreaudiosource.h"
61 #endif // HAVE_COREAUDIO
67 using namespace ARDOUR;
71 namespace Properties {
72 PBD::PropertyDescriptor<bool> envelope_active;
73 PBD::PropertyDescriptor<bool> default_fade_in;
74 PBD::PropertyDescriptor<bool> default_fade_out;
75 PBD::PropertyDescriptor<bool> fade_in_active;
76 PBD::PropertyDescriptor<bool> fade_out_active;
77 PBD::PropertyDescriptor<float> scale_amplitude;
78 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > fade_in;
79 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > inverse_fade_in;
80 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > fade_out;
81 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > inverse_fade_out;
82 PBD::PropertyDescriptor<boost::shared_ptr<AutomationList> > envelope;
86 /* Curve manipulations */
89 reverse_curve (boost::shared_ptr<Evoral::ControlList> dst, boost::shared_ptr<const Evoral::ControlList> src)
91 size_t len = src->when(false);
92 // TODO read-lock of src (!)
93 for (Evoral::ControlList::const_reverse_iterator it = src->rbegin(); it!=src->rend(); it++) {
94 dst->fast_simple_add (len - (*it)->when, (*it)->value);
99 generate_inverse_power_curve (boost::shared_ptr<Evoral::ControlList> dst, boost::shared_ptr<const Evoral::ControlList> src)
101 // calc inverse curve using sum of squares
102 for (Evoral::ControlList::const_iterator it = src->begin(); it!=src->end(); ++it ) {
103 float value = (*it)->value;
104 value = 1 - powf(value,2);
105 value = sqrtf(value);
106 dst->fast_simple_add ( (*it)->when, value );
111 generate_db_fade (boost::shared_ptr<Evoral::ControlList> dst, double len, int num_steps, float dB_drop)
114 dst->fast_simple_add (0, 1);
116 //generate a fade-out curve by successively applying a gain drop
117 float fade_speed = dB_to_coefficient(dB_drop / (float) num_steps);
118 float coeff = GAIN_COEFF_UNITY;
119 for (int i = 1; i < (num_steps-1); i++) {
121 dst->fast_simple_add (len*(double)i/(double)num_steps, coeff);
124 dst->fast_simple_add (len, GAIN_COEFF_SMALL);
128 merge_curves (boost::shared_ptr<Evoral::ControlList> dst,
129 boost::shared_ptr<const Evoral::ControlList> curve1,
130 boost::shared_ptr<const Evoral::ControlList> curve2)
132 Evoral::ControlList::EventList::size_type size = curve1->size();
134 //curve lengths must match for now
135 if (size != curve2->size()) {
139 Evoral::ControlList::const_iterator c1 = curve1->begin();
141 for (Evoral::ControlList::const_iterator c2 = curve2->begin(); c2!=curve2->end(); c2++ ) {
142 float v1 = accurate_coefficient_to_dB((*c1)->value);
143 float v2 = accurate_coefficient_to_dB((*c2)->value);
145 double interp = v1 * ( 1.0-( (double)count / (double)size) );
146 interp += v2 * ( (double)count / (double)size );
148 interp = dB_to_coefficient(interp);
149 dst->fast_simple_add ( (*c1)->when, interp );
156 AudioRegion::make_property_quarks ()
158 Properties::envelope_active.property_id = g_quark_from_static_string (X_("envelope-active"));
159 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for envelope-active = %1\n", Properties::envelope_active.property_id));
160 Properties::default_fade_in.property_id = g_quark_from_static_string (X_("default-fade-in"));
161 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for default-fade-in = %1\n", Properties::default_fade_in.property_id));
162 Properties::default_fade_out.property_id = g_quark_from_static_string (X_("default-fade-out"));
163 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for default-fade-out = %1\n", Properties::default_fade_out.property_id));
164 Properties::fade_in_active.property_id = g_quark_from_static_string (X_("fade-in-active"));
165 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-in-active = %1\n", Properties::fade_in_active.property_id));
166 Properties::fade_out_active.property_id = g_quark_from_static_string (X_("fade-out-active"));
167 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for fade-out-active = %1\n", Properties::fade_out_active.property_id));
168 Properties::scale_amplitude.property_id = g_quark_from_static_string (X_("scale-amplitude"));
169 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for scale-amplitude = %1\n", Properties::scale_amplitude.property_id));
170 Properties::fade_in.property_id = g_quark_from_static_string (X_("FadeIn"));
171 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for FadeIn = %1\n", Properties::fade_in.property_id));
172 Properties::inverse_fade_in.property_id = g_quark_from_static_string (X_("InverseFadeIn"));
173 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for InverseFadeIn = %1\n", Properties::inverse_fade_in.property_id));
174 Properties::fade_out.property_id = g_quark_from_static_string (X_("FadeOut"));
175 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for FadeOut = %1\n", Properties::fade_out.property_id));
176 Properties::inverse_fade_out.property_id = g_quark_from_static_string (X_("InverseFadeOut"));
177 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for InverseFadeOut = %1\n", Properties::inverse_fade_out.property_id));
178 Properties::envelope.property_id = g_quark_from_static_string (X_("Envelope"));
179 DEBUG_TRACE (DEBUG::Properties, string_compose ("quark for Envelope = %1\n", Properties::envelope.property_id));
183 AudioRegion::register_properties ()
185 /* no need to register parent class properties */
187 add_property (_envelope_active);
188 add_property (_default_fade_in);
189 add_property (_default_fade_out);
190 add_property (_fade_in_active);
191 add_property (_fade_out_active);
192 add_property (_scale_amplitude);
193 add_property (_fade_in);
194 add_property (_inverse_fade_in);
195 add_property (_fade_out);
196 add_property (_inverse_fade_out);
197 add_property (_envelope);
200 #define AUDIOREGION_STATE_DEFAULT \
201 _envelope_active (Properties::envelope_active, false) \
202 , _default_fade_in (Properties::default_fade_in, true) \
203 , _default_fade_out (Properties::default_fade_out, true) \
204 , _fade_in_active (Properties::fade_in_active, true) \
205 , _fade_out_active (Properties::fade_out_active, true) \
206 , _scale_amplitude (Properties::scale_amplitude, 1.0) \
207 , _fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeInAutomation)))) \
208 , _inverse_fade_in (Properties::inverse_fade_in, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeInAutomation)))) \
209 , _fade_out (Properties::fade_out, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeOutAutomation)))) \
210 , _inverse_fade_out (Properties::inverse_fade_out, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter (FadeOutAutomation))))
212 #define AUDIOREGION_COPY_STATE(other) \
213 _envelope_active (Properties::envelope_active, other->_envelope_active) \
214 , _default_fade_in (Properties::default_fade_in, other->_default_fade_in) \
215 , _default_fade_out (Properties::default_fade_out, other->_default_fade_out) \
216 , _fade_in_active (Properties::fade_in_active, other->_fade_in_active) \
217 , _fade_out_active (Properties::fade_out_active, other->_fade_out_active) \
218 , _scale_amplitude (Properties::scale_amplitude, other->_scale_amplitude) \
219 , _fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_fade_in.val()))) \
220 , _inverse_fade_in (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_inverse_fade_in.val()))) \
221 , _fade_out (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_fade_out.val()))) \
222 , _inverse_fade_out (Properties::fade_in, boost::shared_ptr<AutomationList> (new AutomationList (*other->_inverse_fade_out.val()))) \
223 /* a Session will reset these to its chosen defaults by calling AudioRegion::set_default_fade() */
228 register_properties ();
230 suspend_property_changes();
231 set_default_fades ();
232 set_default_envelope ();
233 resume_property_changes();
235 listen_to_my_curves ();
236 connect_to_analysis_changed ();
237 connect_to_header_position_offset_changed ();
240 /** Constructor for use by derived types only */
241 AudioRegion::AudioRegion (Session& s, samplepos_t start, samplecnt_t len, std::string name)
242 : Region (s, start, len, name, DataType::AUDIO)
243 , AUDIOREGION_STATE_DEFAULT
244 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter(EnvelopeAutomation))))
246 , _fade_in_suspended (0)
247 , _fade_out_suspended (0)
250 assert (_sources.size() == _master_sources.size());
253 /** Basic AudioRegion constructor */
254 AudioRegion::AudioRegion (const SourceList& srcs)
256 , AUDIOREGION_STATE_DEFAULT
257 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter(EnvelopeAutomation))))
258 , _automatable(srcs[0]->session())
259 , _fade_in_suspended (0)
260 , _fade_out_suspended (0)
263 assert (_sources.size() == _master_sources.size());
266 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other)
268 , AUDIOREGION_COPY_STATE (other)
269 /* As far as I can see, the _envelope's times are relative to region position, and have nothing
270 * to do with sources (and hence _start). So when we copy the envelope, we just use the supplied offset.
272 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val(), 0, other->_length)))
273 , _automatable (other->session())
274 , _fade_in_suspended (0)
275 , _fade_out_suspended (0)
277 /* don't use init here, because we got fade in/out from the other region
279 register_properties ();
280 listen_to_my_curves ();
281 connect_to_analysis_changed ();
282 connect_to_header_position_offset_changed ();
284 assert(_type == DataType::AUDIO);
285 assert (_sources.size() == _master_sources.size());
288 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, MusicSample offset)
289 : Region (other, offset)
290 , AUDIOREGION_COPY_STATE (other)
291 /* As far as I can see, the _envelope's times are relative to region position, and have nothing
292 to do with sources (and hence _start). So when we copy the envelope, we just use the supplied offset.
294 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val(), offset.sample, other->_length)))
295 , _automatable (other->session())
296 , _fade_in_suspended (0)
297 , _fade_out_suspended (0)
299 /* don't use init here, because we got fade in/out from the other region
301 register_properties ();
302 listen_to_my_curves ();
303 connect_to_analysis_changed ();
304 connect_to_header_position_offset_changed ();
306 assert(_type == DataType::AUDIO);
307 assert (_sources.size() == _master_sources.size());
310 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, const SourceList& srcs)
311 : Region (boost::static_pointer_cast<const Region>(other), srcs)
312 , AUDIOREGION_COPY_STATE (other)
313 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val())))
314 , _automatable (other->session())
315 , _fade_in_suspended (0)
316 , _fade_out_suspended (0)
318 /* make-a-sort-of-copy-with-different-sources constructor (used by audio filter) */
320 register_properties ();
322 listen_to_my_curves ();
323 connect_to_analysis_changed ();
324 connect_to_header_position_offset_changed ();
326 assert (_sources.size() == _master_sources.size());
329 AudioRegion::AudioRegion (SourceList& srcs)
331 , AUDIOREGION_STATE_DEFAULT
332 , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList(Evoral::Parameter(EnvelopeAutomation))))
333 , _automatable(srcs[0]->session())
334 , _fade_in_suspended (0)
335 , _fade_out_suspended (0)
339 assert(_type == DataType::AUDIO);
340 assert (_sources.size() == _master_sources.size());
343 AudioRegion::~AudioRegion ()
348 AudioRegion::post_set (const PropertyChange& /*ignored*/)
351 _sync_position = _start;
354 /* return to default fades if the existing ones are too long */
356 if (_left_of_split) {
357 if (_fade_in->when(false) >= _length) {
358 set_default_fade_in ();
360 set_default_fade_out ();
361 _left_of_split = false;
364 if (_right_of_split) {
365 if (_fade_out->when(false) >= _length) {
366 set_default_fade_out ();
369 set_default_fade_in ();
370 _right_of_split = false;
373 /* If _length changed, adjust our gain envelope accordingly */
374 _envelope->truncate_end (_length);
378 AudioRegion::connect_to_analysis_changed ()
380 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
381 (*i)->AnalysisChanged.connect_same_thread (*this, boost::bind (&AudioRegion::maybe_invalidate_transients, this));
386 AudioRegion::connect_to_header_position_offset_changed ()
388 set<boost::shared_ptr<Source> > unique_srcs;
390 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
392 /* connect only once to HeaderPositionOffsetChanged, even if sources are replicated
395 if (unique_srcs.find (*i) == unique_srcs.end ()) {
396 unique_srcs.insert (*i);
397 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
399 afs->HeaderPositionOffsetChanged.connect_same_thread (*this, boost::bind (&AudioRegion::source_offset_changed, this));
406 AudioRegion::listen_to_my_curves ()
408 _envelope->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::envelope_changed, this));
409 _fade_in->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::fade_in_changed, this));
410 _fade_out->StateChanged.connect_same_thread (*this, boost::bind (&AudioRegion::fade_out_changed, this));
414 AudioRegion::set_envelope_active (bool yn)
416 if (envelope_active() != yn) {
417 _envelope_active = yn;
418 send_change (PropertyChange (Properties::envelope_active));
422 /** @param buf Buffer to put peak data in.
423 * @param npeaks Number of peaks to read (ie the number of PeakDatas in buf)
424 * @param offset Start position, as an offset from the start of this region's source.
425 * @param cnt Number of samples to read.
426 * @param chan_n Channel.
427 * @param samples_per_pixel Number of samples to use to generate one peak value.
431 AudioRegion::read_peaks (PeakData *buf, samplecnt_t npeaks, samplecnt_t offset, samplecnt_t cnt, uint32_t chan_n, double samples_per_pixel) const
433 if (chan_n >= _sources.size()) {
437 if (audio_source(chan_n)->read_peaks (buf, npeaks, offset, cnt, samples_per_pixel)) {
441 if (_scale_amplitude != 1.0f) {
442 for (samplecnt_t n = 0; n < npeaks; ++n) {
443 buf[n].max *= _scale_amplitude;
444 buf[n].min *= _scale_amplitude;
451 /** @param buf Buffer to write data to (existing data will be overwritten).
452 * @param pos Position to read from as an offset from the region position.
453 * @param cnt Number of samples to read.
454 * @param channel Channel to read from.
457 AudioRegion::read (Sample* buf, samplepos_t pos, samplecnt_t cnt, int channel) const
459 /* raw read, no fades, no gain, nada */
460 return read_from_sources (_sources, _length, buf, _position + pos, cnt, channel);
464 AudioRegion::master_read_at (Sample *buf, Sample* /*mixdown_buffer*/, float* /*gain_buffer*/,
465 samplepos_t position, samplecnt_t cnt, uint32_t chan_n) const
467 /* do not read gain/scaling/fades and do not count this disk i/o in statistics */
470 return read_from_sources (
471 _master_sources, _master_sources.front()->length (_master_sources.front()->natural_position()),
472 buf, position, cnt, chan_n
476 /** @param buf Buffer to mix data into.
477 * @param mixdown_buffer Scratch buffer for audio data.
478 * @param gain_buffer Scratch buffer for gain data.
479 * @param position Position within the session to read from.
480 * @param cnt Number of samples to read.
481 * @param chan_n Channel number to read.
484 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
485 samplepos_t position,
487 uint32_t chan_n) const
489 /* We are reading data from this region into buf (possibly via mixdown_buffer).
490 The caller has verified that we cover the desired section.
493 /* See doc/region_read.svg for a drawing which might help to explain
499 if (n_channels() == 0) {
503 /* WORK OUT WHERE TO GET DATA FROM */
507 assert (position >= _position);
508 sampleoffset_t const internal_offset = position - _position;
510 if (internal_offset >= _length) {
511 return 0; /* read nothing */
514 if ((to_read = min (cnt, _length - internal_offset)) == 0) {
515 return 0; /* read nothing */
518 boost::shared_ptr<Playlist> pl (playlist());
523 /* COMPUTE DETAILS OF ANY FADES INVOLVED IN THIS READ */
525 /* Amount (length) of fade in that we are dealing with in this read */
526 samplecnt_t fade_in_limit = 0;
528 /* Offset from buf / mixdown_buffer of the start
529 of any fade out that we are dealing with
531 sampleoffset_t fade_out_offset = 0;
533 /* Amount (length) of fade out that we are dealing with in this read */
534 samplecnt_t fade_out_limit = 0;
536 samplecnt_t fade_interval_start = 0;
540 if (_fade_in_active && _session.config.get_use_region_fades()) {
542 samplecnt_t fade_in_length = (samplecnt_t) _fade_in->when(false);
544 /* see if this read is within the fade in */
546 if (internal_offset < fade_in_length) {
547 fade_in_limit = min (to_read, fade_in_length - internal_offset);
553 if (_fade_out_active && _session.config.get_use_region_fades()) {
555 /* see if some part of this read is within the fade out */
557 /* ................. >| REGION
563 * _length - fade_out_length
567 * ^internal_offset + to_read
569 * we need the intersection of [internal_offset,internal_offset+to_read] with
570 * [_length - fade_out_length, _length]
574 fade_interval_start = max (internal_offset, _length - samplecnt_t (_fade_out->when(false)));
575 samplecnt_t fade_interval_end = min(internal_offset + to_read, _length.val());
577 if (fade_interval_end > fade_interval_start) {
578 /* (part of the) the fade out is in this buffer */
579 fade_out_limit = fade_interval_end - fade_interval_start;
580 fade_out_offset = fade_interval_start - internal_offset;
584 /* READ DATA FROM THE SOURCE INTO mixdown_buffer.
585 We can never read directly into buf, since it may contain data
586 from a region `below' this one in the stack, and our fades (if they exist)
587 may need to mix with the existing data.
590 if (read_from_sources (_sources, _length, mixdown_buffer, position, to_read, chan_n) != to_read) {
594 /* APPLY REGULAR GAIN CURVES AND SCALING TO mixdown_buffer */
596 if (envelope_active()) {
597 _envelope->curve().get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
599 if (_scale_amplitude != 1.0f) {
600 for (samplecnt_t n = 0; n < to_read; ++n) {
601 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
604 for (samplecnt_t n = 0; n < to_read; ++n) {
605 mixdown_buffer[n] *= gain_buffer[n];
608 } else if (_scale_amplitude != 1.0f) {
609 apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
612 /* APPLY FADES TO THE DATA IN mixdown_buffer AND MIX THE RESULTS INTO
613 * buf. The key things to realize here: (1) the fade being applied is
614 * (as of April 26th 2012) just the inverse of the fade in curve (2)
615 * "buf" contains data from lower regions already. So this operation
616 * fades out the existing material.
619 bool is_opaque = opaque();
621 if (fade_in_limit != 0) {
624 if (_inverse_fade_in) {
626 /* explicit inverse fade in curve (e.g. for constant
627 * power), so we have to fetch it.
630 _inverse_fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
632 /* Fade the data from lower layers out */
633 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
634 buf[n] *= gain_buffer[n];
637 /* refill gain buffer with the fade in */
639 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
643 /* no explicit inverse fade in, so just use (1 - fade
644 * in) for the fade out of lower layers
647 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
649 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
650 buf[n] *= 1 - gain_buffer[n];
654 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
657 /* Mix our newly-read data in, with the fade */
658 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
659 buf[n] += mixdown_buffer[n] * gain_buffer[n];
663 if (fade_out_limit != 0) {
665 samplecnt_t const curve_offset = fade_interval_start - (_length - _fade_out->when(false));
668 if (_inverse_fade_out) {
670 _inverse_fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
672 /* Fade the data from lower levels in */
673 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
674 buf[m] *= gain_buffer[n];
677 /* fetch the actual fade out */
679 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
683 /* no explicit inverse fade out (which is
684 * actually a fade in), so just use (1 - fade
685 * out) for the fade in of lower layers
688 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
690 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
691 buf[m] *= 1 - gain_buffer[n];
695 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
698 /* Mix our newly-read data with whatever was already there,
699 with the fade out applied to our data.
701 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
702 buf[m] += mixdown_buffer[m] * gain_buffer[n];
706 /* MIX OR COPY THE REGION BODY FROM mixdown_buffer INTO buf */
708 samplecnt_t const N = to_read - fade_in_limit - fade_out_limit;
711 DEBUG_TRACE (DEBUG::AudioPlayback, string_compose ("Region %1 memcpy into buf @ %2 + %3, from mixdown buffer @ %4 + %5, len = %6 cnt was %7\n",
712 name(), buf, fade_in_limit, mixdown_buffer, fade_in_limit, N, cnt));
713 memcpy (buf + fade_in_limit, mixdown_buffer + fade_in_limit, N * sizeof (Sample));
715 mix_buffers_no_gain (buf + fade_in_limit, mixdown_buffer + fade_in_limit, N);
722 /** Read data directly from one of our sources, accounting for the situation when the track has a different channel
723 * count to the region.
725 * @param srcs Source list to get our source from.
726 * @param limit Furthest that we should read, as an offset from the region position.
727 * @param buf Buffer to write data into (existing contents of the buffer will be overwritten)
728 * @param position Position to read from, in session samples.
729 * @param cnt Number of samples to read.
730 * @param chan_n Channel to read from.
731 * @return Number of samples read.
735 AudioRegion::read_from_sources (SourceList const & srcs, samplecnt_t limit, Sample* buf, samplepos_t position, samplecnt_t cnt, uint32_t chan_n) const
737 sampleoffset_t const internal_offset = position - _position;
738 if (internal_offset >= limit) {
742 samplecnt_t const to_read = min (cnt, limit - internal_offset);
747 if (chan_n < n_channels()) {
749 boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[chan_n]);
750 if (src->read (buf, _start + internal_offset, to_read) != to_read) {
751 return 0; /* "read nothing" */
756 /* track is N-channel, this region has fewer channels; silence the ones
760 if (Config->get_replicate_missing_region_channels()) {
762 /* copy an existing channel's data in for this non-existant one */
764 uint32_t channel = chan_n % n_channels();
765 boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[channel]);
767 if (src->read (buf, _start + internal_offset, to_read) != to_read) {
768 return 0; /* "read nothing" */
774 memset (buf, 0, sizeof (Sample) * to_read);
782 AudioRegion::get_basic_state ()
784 XMLNode& node (Region::state ());
786 node.set_property ("channels", (uint32_t)_sources.size());
792 AudioRegion::state ()
794 XMLNode& node (get_basic_state());
797 child = node.add_child ("Envelope");
799 bool default_env = false;
801 // If there are only two points, the points are in the start of the region and the end of the region
802 // so, if they are both at 1.0f, that means the default region.
804 if (_envelope->size() == 2 &&
805 _envelope->front()->value == GAIN_COEFF_UNITY &&
806 _envelope->back()->value==GAIN_COEFF_UNITY) {
807 if (_envelope->front()->when == 0 && _envelope->back()->when == _length) {
813 child->set_property ("default", "yes");
815 child->add_child_nocopy (_envelope->get_state ());
818 child = node.add_child (X_("FadeIn"));
820 if (_default_fade_in) {
821 child->set_property ("default", "yes");
823 child->add_child_nocopy (_fade_in->get_state ());
826 if (_inverse_fade_in) {
827 child = node.add_child (X_("InverseFadeIn"));
828 child->add_child_nocopy (_inverse_fade_in->get_state ());
831 child = node.add_child (X_("FadeOut"));
833 if (_default_fade_out) {
834 child->set_property ("default", "yes");
836 child->add_child_nocopy (_fade_out->get_state ());
839 if (_inverse_fade_out) {
840 child = node.add_child (X_("InverseFadeOut"));
841 child->add_child_nocopy (_inverse_fade_out->get_state ());
848 AudioRegion::_set_state (const XMLNode& node, int version, PropertyChange& what_changed, bool send)
850 const XMLNodeList& nlist = node.children();
851 boost::shared_ptr<Playlist> the_playlist (_playlist.lock());
853 suspend_property_changes ();
856 the_playlist->freeze ();
860 /* this will set all our State members and stuff controlled by the Region.
861 It should NOT send any changed signals - that is our responsibility.
864 Region::_set_state (node, version, what_changed, false);
867 if (node.get_property ("scale-gain", val)) {
868 if (val != _scale_amplitude) {
869 _scale_amplitude = val;
870 what_changed.add (Properties::scale_amplitude);
874 /* Now find envelope description and other related child items */
876 _envelope->freeze ();
878 for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
880 XMLProperty const * prop;
884 if (child->name() == "Envelope") {
888 if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child, version)) {
889 set_default_envelope ();
892 _envelope->truncate_end (_length);
895 } else if (child->name() == "FadeIn") {
900 if ((child->get_property ("default", is_default) && is_default) || (prop = child->property ("steepness")) != 0) {
901 set_default_fade_in ();
903 XMLNode* grandchild = child->child ("AutomationList");
905 _fade_in->set_state (*grandchild, version);
910 if (child->get_property ("active", is_active)) {
911 set_fade_in_active (is_active);
914 } else if (child->name() == "FadeOut") {
919 if ((child->get_property ("default", is_default) && is_default) || (prop = child->property ("steepness")) != 0) {
920 set_default_fade_out ();
922 XMLNode* grandchild = child->child ("AutomationList");
924 _fade_out->set_state (*grandchild, version);
929 if (child->get_property ("active", is_active)) {
930 set_fade_out_active (is_active);
933 } else if ( (child->name() == "InverseFadeIn") || (child->name() == "InvFadeIn") ) {
934 XMLNode* grandchild = child->child ("AutomationList");
936 _inverse_fade_in->set_state (*grandchild, version);
938 } else if ( (child->name() == "InverseFadeOut") || (child->name() == "InvFadeOut") ) {
939 XMLNode* grandchild = child->child ("AutomationList");
941 _inverse_fade_out->set_state (*grandchild, version);
947 resume_property_changes ();
950 send_change (what_changed);
954 the_playlist->thaw ();
961 AudioRegion::set_state (const XMLNode& node, int version)
963 PropertyChange what_changed;
964 return _set_state (node, version, what_changed, true);
968 AudioRegion::fade_range (samplepos_t start, samplepos_t end)
972 switch (coverage (start, end)) {
973 case Evoral::OverlapStart:
977 set_fade_in (FadeConstantPower, e - s);
979 case Evoral::OverlapEnd:
982 e = _position + _length;
983 set_fade_out (FadeConstantPower, e - s);
985 case Evoral::OverlapInternal:
986 /* needs addressing, perhaps. Difficult to do if we can't
987 * control one edge of the fade relative to the relevant edge
988 * of the region, which we cannot - fades are currently assumed
989 * to start/end at the start/end of the region
998 AudioRegion::set_fade_in_shape (FadeShape shape)
1000 set_fade_in (shape, (samplecnt_t) _fade_in->when(false));
1004 AudioRegion::set_fade_out_shape (FadeShape shape)
1006 set_fade_out (shape, (samplecnt_t) _fade_out->when(false));
1010 AudioRegion::set_fade_in (boost::shared_ptr<AutomationList> f)
1012 _fade_in->freeze ();
1013 *(_fade_in.val()) = *f;
1015 _default_fade_in = false;
1017 send_change (PropertyChange (Properties::fade_in));
1021 AudioRegion::set_fade_in (FadeShape shape, samplecnt_t len)
1023 const ARDOUR::ParameterDescriptor desc(FadeInAutomation);
1024 boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeInAutomation, desc));
1025 boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeInAutomation, desc));
1026 boost::shared_ptr<Evoral::ControlList> c3 (new Evoral::ControlList (FadeInAutomation, desc));
1028 _fade_in->freeze ();
1030 _inverse_fade_in->clear ();
1032 const int num_steps = 32;
1036 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1037 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1038 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1042 generate_db_fade (_fade_in.val(), len, num_steps, -60);
1043 reverse_curve (c1, _fade_in.val());
1044 _fade_in->copy_events (*c1);
1045 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1049 generate_db_fade (c1, len, num_steps, -1); // start off with a slow fade
1050 generate_db_fade (c2, len, num_steps, -80); // end with a fast fade
1051 merge_curves (_fade_in.val(), c1, c2);
1052 reverse_curve (c3, _fade_in.val());
1053 _fade_in->copy_events (*c3);
1054 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1057 case FadeConstantPower:
1058 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1059 for (int i = 1; i < num_steps; ++i) {
1060 const float dist = i / (num_steps + 1.f);
1061 _fade_in->fast_simple_add (len * dist, sin (dist * M_PI / 2.0));
1063 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1064 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1068 //start with a nearly linear cuve
1069 _fade_in->fast_simple_add (0, 1);
1070 _fade_in->fast_simple_add (0.5 * len, 0.6);
1071 //now generate a fade-out curve by successively applying a gain drop
1072 const double breakpoint = 0.7; //linear for first 70%
1073 for (int i = 2; i < 9; ++i) {
1074 const float coeff = (1.f - breakpoint) * powf (0.5, i);
1075 _fade_in->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1077 _fade_in->fast_simple_add (len, GAIN_COEFF_SMALL);
1078 reverse_curve (c3, _fade_in.val());
1079 _fade_in->copy_events (*c3);
1080 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1084 _fade_in->set_interpolation(Evoral::ControlList::Curved);
1085 _inverse_fade_in->set_interpolation(Evoral::ControlList::Curved);
1087 _default_fade_in = false;
1089 send_change (PropertyChange (Properties::fade_in));
1093 AudioRegion::set_fade_out (boost::shared_ptr<AutomationList> f)
1095 _fade_out->freeze ();
1096 *(_fade_out.val()) = *f;
1098 _default_fade_out = false;
1100 send_change (PropertyChange (Properties::fade_out));
1104 AudioRegion::set_fade_out (FadeShape shape, samplecnt_t len)
1106 const ARDOUR::ParameterDescriptor desc(FadeOutAutomation);
1107 boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeOutAutomation, desc));
1108 boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeOutAutomation, desc));
1110 _fade_out->freeze ();
1111 _fade_out->clear ();
1112 _inverse_fade_out->clear ();
1114 const int num_steps = 32;
1118 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1119 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1120 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1124 generate_db_fade (_fade_out.val(), len, num_steps, -60);
1125 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1129 generate_db_fade (c1, len, num_steps, -1); //start off with a slow fade
1130 generate_db_fade (c2, len, num_steps, -80); //end with a fast fade
1131 merge_curves (_fade_out.val(), c1, c2);
1132 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1135 case FadeConstantPower:
1136 //constant-power fades use a sin/cos relationship
1137 //the cutoff is abrupt but it has the benefit of being symmetrical
1138 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1139 for (int i = 1; i < num_steps; ++i) {
1140 const float dist = i / (num_steps + 1.f);
1141 _fade_out->fast_simple_add (len * dist, cos (dist * M_PI / 2.0));
1143 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1144 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1148 //start with a nearly linear cuve
1149 _fade_out->fast_simple_add (0, 1);
1150 _fade_out->fast_simple_add (0.5 * len, 0.6);
1151 //now generate a fade-out curve by successively applying a gain drop
1152 const double breakpoint = 0.7; //linear for first 70%
1153 for (int i = 2; i < 9; ++i) {
1154 const float coeff = (1.f - breakpoint) * powf (0.5, i);
1155 _fade_out->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1157 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1158 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1162 _fade_out->set_interpolation(Evoral::ControlList::Curved);
1163 _inverse_fade_out->set_interpolation(Evoral::ControlList::Curved);
1165 _default_fade_out = false;
1167 send_change (PropertyChange (Properties::fade_out));
1171 AudioRegion::set_fade_in_length (samplecnt_t len)
1173 if (len > _length) {
1181 bool changed = _fade_in->extend_to (len);
1184 if (_inverse_fade_in) {
1185 _inverse_fade_in->extend_to (len);
1188 _default_fade_in = false;
1189 send_change (PropertyChange (Properties::fade_in));
1194 AudioRegion::set_fade_out_length (samplecnt_t len)
1196 if (len > _length) {
1204 bool changed = _fade_out->extend_to (len);
1208 if (_inverse_fade_out) {
1209 _inverse_fade_out->extend_to (len);
1211 _default_fade_out = false;
1213 send_change (PropertyChange (Properties::fade_out));
1218 AudioRegion::set_fade_in_active (bool yn)
1220 if (yn == _fade_in_active) {
1224 _fade_in_active = yn;
1225 send_change (PropertyChange (Properties::fade_in_active));
1229 AudioRegion::set_fade_out_active (bool yn)
1231 if (yn == _fade_out_active) {
1234 _fade_out_active = yn;
1235 send_change (PropertyChange (Properties::fade_out_active));
1239 AudioRegion::fade_in_is_default () const
1241 return _fade_in->size() == 2 && _fade_in->when(true) == 0 && _fade_in->when(false) == 64;
1245 AudioRegion::fade_out_is_default () const
1247 return _fade_out->size() == 2 && _fade_out->when(true) == 0 && _fade_out->when(false) == 64;
1251 AudioRegion::set_default_fade_in ()
1253 _fade_in_suspended = 0;
1254 set_fade_in (Config->get_default_fade_shape(), 64);
1258 AudioRegion::set_default_fade_out ()
1260 _fade_out_suspended = 0;
1261 set_fade_out (Config->get_default_fade_shape(), 64);
1265 AudioRegion::set_default_fades ()
1267 set_default_fade_in ();
1268 set_default_fade_out ();
1272 AudioRegion::set_default_envelope ()
1274 _envelope->freeze ();
1275 _envelope->clear ();
1276 _envelope->fast_simple_add (0, GAIN_COEFF_UNITY);
1277 _envelope->fast_simple_add (_length, GAIN_COEFF_UNITY);
1282 AudioRegion::recompute_at_end ()
1284 /* our length has changed. recompute a new final point by interpolating
1285 based on the the existing curve.
1288 _envelope->freeze ();
1289 _envelope->truncate_end (_length);
1292 suspend_property_changes();
1294 if (_left_of_split) {
1295 set_default_fade_out ();
1296 _left_of_split = false;
1297 } else if (_fade_out->when(false) > _length) {
1298 _fade_out->extend_to (_length);
1299 send_change (PropertyChange (Properties::fade_out));
1302 if (_fade_in->when(false) > _length) {
1303 _fade_in->extend_to (_length);
1304 send_change (PropertyChange (Properties::fade_in));
1307 resume_property_changes();
1311 AudioRegion::recompute_at_start ()
1313 /* as above, but the shift was from the front */
1315 _envelope->truncate_start (_length);
1317 suspend_property_changes();
1319 if (_right_of_split) {
1320 set_default_fade_in ();
1321 _right_of_split = false;
1322 } else if (_fade_in->when(false) > _length) {
1323 _fade_in->extend_to (_length);
1324 send_change (PropertyChange (Properties::fade_in));
1327 if (_fade_out->when(false) > _length) {
1328 _fade_out->extend_to (_length);
1329 send_change (PropertyChange (Properties::fade_out));
1332 resume_property_changes();
1336 AudioRegion::separate_by_channel (vector<boost::shared_ptr<Region> >& v) const
1342 if (_sources.size() < 2) {
1346 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1348 srcs.push_back (*i);
1352 if (_sources.size() == 2) {
1360 new_name += ('0' + n + 1);
1363 /* create a copy with just one source. prevent if from being thought of as
1364 "whole file" even if it covers the entire source file(s).
1369 plist.add (Properties::start, _start.val());
1370 plist.add (Properties::length, _length.val());
1371 plist.add (Properties::name, new_name);
1372 plist.add (Properties::layer, layer ());
1374 v.push_back(RegionFactory::create (srcs, plist));
1375 v.back()->set_whole_file (false);
1384 AudioRegion::read_raw_internal (Sample* buf, samplepos_t pos, samplecnt_t cnt, int channel) const
1386 return audio_source(channel)->read (buf, pos, cnt);
1390 AudioRegion::set_scale_amplitude (gain_t g)
1392 boost::shared_ptr<Playlist> pl (playlist());
1394 _scale_amplitude = g;
1396 /* tell the diskstream we're in */
1399 pl->ContentsChanged();
1402 /* tell everybody else */
1404 send_change (PropertyChange (Properties::scale_amplitude));
1408 AudioRegion::maximum_amplitude (Progress* p) const
1410 samplepos_t fpos = _start;
1411 samplepos_t const fend = _start + _length;
1414 samplecnt_t const blocksize = 64 * 1024;
1415 Sample buf[blocksize];
1417 while (fpos < fend) {
1421 samplecnt_t const to_read = min (fend - fpos, blocksize);
1423 for (n = 0; n < n_channels(); ++n) {
1427 if (read_raw_internal (buf, fpos, to_read, n) != to_read) {
1431 maxamp = compute_peak (buf, to_read, maxamp);
1436 p->set_progress (float (fpos - _start) / _length);
1437 if (p->cancelled ()) {
1447 AudioRegion::rms (Progress* p) const
1449 samplepos_t fpos = _start;
1450 samplepos_t const fend = _start + _length;
1451 uint32_t const n_chan = n_channels ();
1454 samplecnt_t const blocksize = 64 * 1024;
1455 Sample buf[blocksize];
1457 samplecnt_t total = 0;
1459 if (n_chan == 0 || fend == fpos) {
1463 while (fpos < fend) {
1464 samplecnt_t const to_read = min (fend - fpos, blocksize);
1465 for (uint32_t c = 0; c < n_chan; ++c) {
1466 if (read_raw_internal (buf, fpos, to_read, c) != to_read) {
1469 for (samplepos_t i = 0; i < to_read; ++i) {
1470 rms += buf[i] * buf[i];
1476 p->set_progress (float (fpos - _start) / _length);
1477 if (p->cancelled ()) {
1482 return sqrt (2. * rms / (double)(total * n_chan));
1485 /** Normalize using a given maximum amplitude and target, so that region
1486 * _scale_amplitude becomes target / max_amplitude.
1489 AudioRegion::normalize (float max_amplitude, float target_dB)
1491 gain_t target = dB_to_coefficient (target_dB);
1493 if (target == GAIN_COEFF_UNITY) {
1494 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1495 that we may have clipped.
1497 target -= FLT_EPSILON;
1500 if (max_amplitude < GAIN_COEFF_SMALL) {
1501 /* don't even try */
1505 if (max_amplitude == target) {
1506 /* we can't do anything useful */
1510 set_scale_amplitude (target / max_amplitude);
1514 AudioRegion::fade_in_changed ()
1516 send_change (PropertyChange (Properties::fade_in));
1520 AudioRegion::fade_out_changed ()
1522 send_change (PropertyChange (Properties::fade_out));
1526 AudioRegion::envelope_changed ()
1528 send_change (PropertyChange (Properties::envelope));
1532 AudioRegion::suspend_fade_in ()
1534 if (++_fade_in_suspended == 1) {
1535 if (fade_in_is_default()) {
1536 set_fade_in_active (false);
1542 AudioRegion::resume_fade_in ()
1544 if (--_fade_in_suspended == 0 && _fade_in_suspended) {
1545 set_fade_in_active (true);
1550 AudioRegion::suspend_fade_out ()
1552 if (++_fade_out_suspended == 1) {
1553 if (fade_out_is_default()) {
1554 set_fade_out_active (false);
1560 AudioRegion::resume_fade_out ()
1562 if (--_fade_out_suspended == 0 &&_fade_out_suspended) {
1563 set_fade_out_active (true);
1568 AudioRegion::speed_mismatch (float sr) const
1570 if (_sources.empty()) {
1571 /* impossible, but ... */
1575 float fsr = audio_source()->sample_rate();
1581 AudioRegion::source_offset_changed ()
1583 /* XXX this fixes a crash that should not occur. It does occur
1584 becauses regions are not being deleted when a session
1585 is unloaded. That bug must be fixed.
1588 if (_sources.empty()) {
1592 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1594 if (afs && afs->destructive()) {
1595 // set_start (source()->natural_position(), this);
1596 set_position (source()->natural_position());
1600 boost::shared_ptr<AudioSource>
1601 AudioRegion::audio_source (uint32_t n) const
1603 // Guaranteed to succeed (use a static cast for speed?)
1604 return boost::dynamic_pointer_cast<AudioSource>(source(n));
1608 AudioRegion::get_related_audio_file_channel_count () const
1610 uint32_t chan_count = 0;
1611 for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1613 boost::shared_ptr<SndFileSource> sndf = boost::dynamic_pointer_cast<SndFileSource>(*i);
1616 if (sndf->channel_count() > chan_count) {
1617 chan_count = sndf->channel_count();
1620 #ifdef HAVE_COREAUDIO
1622 boost::shared_ptr<CoreAudioSource> cauf = boost::dynamic_pointer_cast<CoreAudioSource>(*i);
1624 if (cauf->channel_count() > chan_count) {
1625 chan_count = cauf->channel_count();
1629 #endif // HAVE_COREAUDIO
1636 AudioRegion::clear_transients () // yet unused
1638 _user_transients.clear ();
1639 _valid_transients = false;
1640 send_change (PropertyChange (Properties::valid_transients));
1644 AudioRegion::add_transient (samplepos_t where)
1646 if (where < first_sample () || where >= last_sample ()) {
1651 if (!_valid_transients) {
1652 _transient_user_start = _start;
1653 _valid_transients = true;
1655 sampleoffset_t offset = _transient_user_start - _start;
1657 if (where < offset) {
1661 // region start changed (extend to front), shift points and offset
1662 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1665 _transient_user_start -= offset;
1669 const samplepos_t p = where - offset;
1670 _user_transients.push_back(p);
1671 send_change (PropertyChange (Properties::valid_transients));
1675 AudioRegion::update_transient (samplepos_t old_position, samplepos_t new_position)
1677 bool changed = false;
1678 if (!_onsets.empty ()) {
1679 const samplepos_t p = old_position - _position;
1680 AnalysisFeatureList::iterator x = std::find (_onsets.begin (), _onsets.end (), p);
1681 if (x != _transients.end ()) {
1682 (*x) = new_position - _position;
1687 if (_valid_transients) {
1688 const sampleoffset_t offset = _position + _transient_user_start - _start;
1689 const samplepos_t p = old_position - offset;
1690 AnalysisFeatureList::iterator x = std::find (_user_transients.begin (), _user_transients.end (), p);
1691 if (x != _transients.end ()) {
1692 (*x) = new_position - offset;
1698 send_change (PropertyChange (Properties::valid_transients));
1703 AudioRegion::remove_transient (samplepos_t where)
1705 bool changed = false;
1706 if (!_onsets.empty ()) {
1707 const samplepos_t p = where - _position;
1708 AnalysisFeatureList::iterator i = std::find (_onsets.begin (), _onsets.end (), p);
1709 if (i != _transients.end ()) {
1715 if (_valid_transients) {
1716 const samplepos_t p = where - (_position + _transient_user_start - _start);
1717 AnalysisFeatureList::iterator i = std::find (_user_transients.begin (), _user_transients.end (), p);
1718 if (i != _user_transients.end ()) {
1719 _user_transients.erase (i);
1725 send_change (PropertyChange (Properties::valid_transients));
1730 AudioRegion::set_onsets (AnalysisFeatureList& results)
1734 send_change (PropertyChange (Properties::valid_transients));
1738 AudioRegion::build_transients ()
1740 _transients.clear ();
1741 _transient_analysis_start = _transient_analysis_end = 0;
1743 boost::shared_ptr<Playlist> pl = playlist();
1749 /* check analyzed sources first */
1750 SourceList::iterator s;
1751 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1752 if (!(*s)->has_been_analysed()) {
1754 cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
1760 if (s == _sources.end()) {
1761 /* all sources are analyzed, merge data from each one */
1762 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1764 /* find the set of transients within the bounds of this region */
1765 AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
1766 (*s)->transients.end(),
1769 AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
1770 (*s)->transients.end(),
1774 _transients.insert (_transients.end(), low, high);
1777 TransientDetector::cleanup_transients (_transients, pl->session().sample_rate(), 3.0);
1779 /* translate all transients to current position */
1780 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1784 _transient_analysis_start = _start;
1785 _transient_analysis_end = _start + _length;
1789 /* no existing/complete transient info */
1791 static bool analyse_dialog_shown = false; /* global per instance of Ardour */
1793 if (!Config->get_auto_analyse_audio()) {
1794 if (!analyse_dialog_shown) {
1795 pl->session().Dialog (string_compose (_("\
1796 You have requested an operation that requires audio analysis.\n\n\
1797 You currently have \"auto-analyse-audio\" disabled, which means \
1798 that transient data must be generated every time it is required.\n\n\
1799 If you are doing work that will require transient data on a \
1800 regular basis, you should probably enable \"auto-analyse-audio\" \
1801 in Preferences > Audio > Regions, then quit %1 and restart.\n\n\
1802 This dialog will not display again. But you may notice a slight delay \
1803 in this and future transient-detection operations.\n\
1805 analyse_dialog_shown = true;
1810 TransientDetector t (pl->session().sample_rate());
1811 for (uint32_t i = 0; i < n_channels(); ++i) {
1813 AnalysisFeatureList these_results;
1817 /* this produces analysis result relative to current position
1818 * ::read() sample 0 is at _position */
1819 if (t.run ("", this, i, these_results)) {
1824 _transients.insert (_transients.end(), these_results.begin(), these_results.end());
1827 error << string_compose(_("Transient Analysis failed for %1."), _("Audio Region")) << endmsg;
1831 TransientDetector::cleanup_transients (_transients, pl->session().sample_rate(), 3.0);
1832 _transient_analysis_start = _start;
1833 _transient_analysis_end = _start + _length;
1836 /* Transient analysis uses ::read() which is relative to _start,
1837 * at the time of analysis and spans _length samples.
1839 * This is true for RhythmFerret::run_analysis and the
1840 * TransientDetector here.
1842 * We store _start and length in _transient_analysis_start,
1843 * _transient_analysis_end in case the region is trimmed or split after analysis.
1845 * Various methods (most notably Playlist::find_next_transient and
1846 * RhythmFerret::do_split_action) span multiple regions and *merge/combine*
1848 * We therefore need to translate the analysis timestamps to absolute session-time
1849 * and include the _position of the region.
1851 * Note: we should special case the AudioRegionView. The region-view itself
1852 * is located at _position (currently ARV subtracts _position again)
1855 AudioRegion::get_transients (AnalysisFeatureList& results)
1857 boost::shared_ptr<Playlist> pl = playlist();
1862 Region::merge_features (results, _user_transients, _position + _transient_user_start - _start);
1864 if (!_onsets.empty ()) {
1865 // onsets are invalidated when start or length changes
1866 merge_features (results, _onsets, _position);
1870 if ((_transient_analysis_start == _transient_analysis_end)
1871 || _transient_analysis_start > _start
1872 || _transient_analysis_end < _start + _length) {
1873 build_transients ();
1876 merge_features (results, _transients, _position + _transient_analysis_start - _start);
1879 /** Find areas of `silence' within a region.
1881 * @param threshold Threshold below which signal is considered silence (as a sample value)
1882 * @param min_length Minimum length of silent period to be reported.
1883 * @return Silent intervals, measured relative to the region start in the source
1887 AudioRegion::find_silence (Sample threshold, samplecnt_t min_length, samplecnt_t fade_length, InterThreadInfo& itt) const
1889 samplecnt_t const block_size = 64 * 1024;
1890 boost::scoped_array<Sample> loudest (new Sample[block_size]);
1891 boost::scoped_array<Sample> buf (new Sample[block_size]);
1893 assert (fade_length >= 0);
1894 assert (min_length > 0);
1896 samplepos_t pos = _start;
1897 samplepos_t const end = _start + _length;
1899 AudioIntervalResult silent_periods;
1901 bool in_silence = true;
1902 sampleoffset_t silence_start = _start;
1904 while (pos < end && !itt.cancel) {
1906 samplecnt_t cur_samples = 0;
1907 samplecnt_t const to_read = min (end - pos, block_size);
1908 /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
1909 memset (loudest.get(), 0, sizeof (Sample) * block_size);
1911 for (uint32_t n = 0; n < n_channels(); ++n) {
1913 cur_samples = read_raw_internal (buf.get(), pos, to_read, n);
1914 for (samplecnt_t i = 0; i < cur_samples; ++i) {
1915 loudest[i] = max (loudest[i], abs (buf[i]));
1919 /* now look for silence */
1920 for (samplecnt_t i = 0; i < cur_samples; ++i) {
1921 bool const silence = abs (loudest[i]) < threshold;
1922 if (silence && !in_silence) {
1923 /* non-silence to silence */
1925 silence_start = pos + i + fade_length;
1926 } else if (!silence && in_silence) {
1927 /* silence to non-silence */
1929 sampleoffset_t silence_end = pos + i - 1 - fade_length;
1931 if (silence_end - silence_start >= min_length) {
1932 silent_periods.push_back (std::make_pair (silence_start, silence_end));
1938 itt.progress = (end - pos) / (double)_length;
1940 if (cur_samples == 0) {
1941 assert (pos >= end);
1946 if (in_silence && !itt.cancel) {
1947 /* last block was silent, so finish off the last period */
1948 if (end - 1 - silence_start >= min_length + fade_length) {
1949 silent_periods.push_back (std::make_pair (silence_start, end - 1));
1955 return silent_periods;
1958 Evoral::Range<samplepos_t>
1959 AudioRegion::body_range () const
1961 return Evoral::Range<samplepos_t> (first_sample() + _fade_in->when(false) + 1, last_sample() - _fade_out->when(false));
1964 boost::shared_ptr<Region>
1965 AudioRegion::get_single_other_xfade_region (bool start) const
1967 boost::shared_ptr<Playlist> pl (playlist());
1970 /* not currently in a playlist - xfade length is unbounded
1973 return boost::shared_ptr<AudioRegion> ();
1976 boost::shared_ptr<RegionList> rl;
1979 rl = pl->regions_at (position());
1981 rl = pl->regions_at (last_sample());
1984 RegionList::iterator i;
1985 boost::shared_ptr<Region> other;
1988 /* count and find the other region in a single pass through the list */
1990 for (i = rl->begin(); i != rl->end(); ++i) {
1991 if ((*i).get() != this) {
1998 /* zero or multiple regions stacked here - don't care about xfades */
1999 return boost::shared_ptr<AudioRegion> ();
2006 AudioRegion::verify_xfade_bounds (samplecnt_t len, bool start)
2008 /* this is called from a UI to check on whether a new proposed
2009 length for an xfade is legal or not. it returns the legal
2010 length corresponding to @a len which may be shorter than or
2011 equal to @a len itself.
2014 boost::shared_ptr<Region> other = get_single_other_xfade_region (start);
2018 /* zero or > 2 regions here, don't care about len, but
2019 it can't be longer than the region itself.
2021 return min (length(), len);
2024 /* we overlap a single region. clamp the length of an xfade to
2025 the maximum possible duration of the overlap (if the other
2026 region were trimmed appropriately).
2030 maxlen = other->latest_possible_sample() - position();
2032 maxlen = last_sample() - other->earliest_possible_position();
2035 return min (length(), min (maxlen, len));