Fix a tiny memory-leak when calling vfork
[ardour.git] / libs / ardour / audioregion.cc
1 /*
2     Copyright (C) 2000-2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <cmath>
21 #include <climits>
22 #include <cfloat>
23 #include <algorithm>
24
25 #include <set>
26
27 #include <boost/scoped_array.hpp>
28 #include <boost/shared_ptr.hpp>
29
30 #include <glibmm/threads.h>
31
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"
37
38 #include "evoral/Curve.hpp"
39
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"
52
53 #include "ardour/sndfilesource.h"
54 #ifdef HAVE_COREAUDIO
55 #include "ardour/coreaudiosource.h"
56 #endif // HAVE_COREAUDIO
57
58 #include "pbd/i18n.h"
59 #include <locale.h>
60
61 using namespace std;
62 using namespace ARDOUR;
63 using namespace PBD;
64
65 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;
78         }
79 }
80
81 /* Curve manipulations */
82
83 static void
84 reverse_curve (boost::shared_ptr<Evoral::ControlList> dst, boost::shared_ptr<const Evoral::ControlList> src)
85 {
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);
89         }
90 }
91
92 static void
93 generate_inverse_power_curve (boost::shared_ptr<Evoral::ControlList> dst, boost::shared_ptr<const Evoral::ControlList> src)
94 {
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);
99                 value = sqrtf(value);
100                 dst->fast_simple_add ( (*it)->when, value );
101         }
102 }
103
104 static void
105 generate_db_fade (boost::shared_ptr<Evoral::ControlList> dst, double len, int num_steps, float dB_drop)
106 {
107         dst->clear ();
108         dst->fast_simple_add (0, 1);
109
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++) {
114                 coeff *= fade_speed;
115                 dst->fast_simple_add (len*(double)i/(double)num_steps, coeff);
116         }
117
118         dst->fast_simple_add (len, GAIN_COEFF_SMALL);
119 }
120
121 static void
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)
125 {
126         Evoral::ControlList::EventList::size_type size = curve1->size();
127
128         //curve lengths must match for now
129         if (size != curve2->size()) {
130                 return;
131         }
132
133         Evoral::ControlList::const_iterator c1 = curve1->begin();
134         int count = 0;
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);
138
139                 double interp = v1 * ( 1.0-( (double)count / (double)size) );
140                 interp += v2 * ( (double)count / (double)size );
141
142                 interp = dB_to_coefficient(interp);
143                 dst->fast_simple_add ( (*c1)->when, interp );
144                 c1++;
145                 count++;
146         }
147 }
148
149 void
150 AudioRegion::make_property_quarks ()
151 {
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));
174 }
175
176 void
177 AudioRegion::register_properties ()
178 {
179         /* no need to register parent class properties */
180
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);
192 }
193
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))))
205
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() */
218
219 void
220 AudioRegion::init ()
221 {
222         register_properties ();
223
224         suspend_property_changes();
225         set_default_fades ();
226         set_default_envelope ();
227         resume_property_changes();
228
229         listen_to_my_curves ();
230         connect_to_analysis_changed ();
231         connect_to_header_position_offset_changed ();
232 }
233
234 /** Constructor for use by derived types only */
235 AudioRegion::AudioRegion (Session& s, samplepos_t start, samplecnt_t len, std::string name)
236         : Region (s, start, len, name, DataType::AUDIO)
237         , AUDIOREGION_STATE_DEFAULT
238         , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (Evoral::Parameter(EnvelopeAutomation))))
239         , _automatable (s)
240         , _fade_in_suspended (0)
241         , _fade_out_suspended (0)
242 {
243         init ();
244         assert (_sources.size() == _master_sources.size());
245 }
246
247 /** Basic AudioRegion constructor */
248 AudioRegion::AudioRegion (const SourceList& srcs)
249         : Region (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)
255 {
256         init ();
257         assert (_sources.size() == _master_sources.size());
258 }
259
260 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other)
261         : Region (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.
265           */
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)
270 {
271         /* don't use init here, because we got fade in/out from the other region
272         */
273         register_properties ();
274         listen_to_my_curves ();
275         connect_to_analysis_changed ();
276         connect_to_header_position_offset_changed ();
277
278         assert(_type == DataType::AUDIO);
279         assert (_sources.size() == _master_sources.size());
280 }
281
282 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, MusicSample offset)
283         : Region (other, offset)
284         , AUDIOREGION_COPY_STATE (other)
285           /* As far as I can see, the _envelope's times are relative to region position, and have nothing
286              to do with sources (and hence _start).  So when we copy the envelope, we just use the supplied offset.
287           */
288         , _envelope (Properties::envelope, boost::shared_ptr<AutomationList> (new AutomationList (*other->_envelope.val(), offset.sample, other->_length)))
289         , _automatable (other->session())
290         , _fade_in_suspended (0)
291         , _fade_out_suspended (0)
292 {
293         /* don't use init here, because we got fade in/out from the other region
294         */
295         register_properties ();
296         listen_to_my_curves ();
297         connect_to_analysis_changed ();
298         connect_to_header_position_offset_changed ();
299
300         assert(_type == DataType::AUDIO);
301         assert (_sources.size() == _master_sources.size());
302 }
303
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)
311 {
312         /* make-a-sort-of-copy-with-different-sources constructor (used by audio filter) */
313
314         register_properties ();
315
316         listen_to_my_curves ();
317         connect_to_analysis_changed ();
318         connect_to_header_position_offset_changed ();
319
320         assert (_sources.size() == _master_sources.size());
321 }
322
323 AudioRegion::AudioRegion (SourceList& srcs)
324         : Region (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)
330 {
331         init ();
332
333         assert(_type == DataType::AUDIO);
334         assert (_sources.size() == _master_sources.size());
335 }
336
337 AudioRegion::~AudioRegion ()
338 {
339 }
340
341 void
342 AudioRegion::post_set (const PropertyChange& /*ignored*/)
343 {
344         if (!_sync_marked) {
345                 _sync_position = _start;
346         }
347
348         /* return to default fades if the existing ones are too long */
349
350         if (_left_of_split) {
351                 if (_fade_in->back()->when >= _length) {
352                         set_default_fade_in ();
353                 }
354                 set_default_fade_out ();
355                 _left_of_split = false;
356         }
357
358         if (_right_of_split) {
359                 if (_fade_out->back()->when >= _length) {
360                         set_default_fade_out ();
361                 }
362
363                 set_default_fade_in ();
364                 _right_of_split = false;
365         }
366
367         /* If _length changed, adjust our gain envelope accordingly */
368         _envelope->truncate_end (_length);
369 }
370
371 void
372 AudioRegion::connect_to_analysis_changed ()
373 {
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));
376         }
377 }
378
379 void
380 AudioRegion::connect_to_header_position_offset_changed ()
381 {
382         set<boost::shared_ptr<Source> > unique_srcs;
383
384         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
385
386                 /* connect only once to HeaderPositionOffsetChanged, even if sources are replicated
387                  */
388
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);
392                         if (afs) {
393                                 afs->HeaderPositionOffsetChanged.connect_same_thread (*this, boost::bind (&AudioRegion::source_offset_changed, this));
394                         }
395                 }
396         }
397 }
398
399 void
400 AudioRegion::listen_to_my_curves ()
401 {
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));
405 }
406
407 void
408 AudioRegion::set_envelope_active (bool yn)
409 {
410         if (envelope_active() != yn) {
411                 _envelope_active = yn;
412                 send_change (PropertyChange (Properties::envelope_active));
413         }
414 }
415
416 /** @param buf Buffer to put peak data in.
417  *  @param npeaks Number of peaks to read (ie the number of PeakDatas in buf)
418  *  @param offset Start position, as an offset from the start of this region's source.
419  *  @param cnt Number of samples to read.
420  *  @param chan_n Channel.
421  *  @param samples_per_pixel Number of samples to use to generate one peak value.
422  */
423
424 ARDOUR::samplecnt_t
425 AudioRegion::read_peaks (PeakData *buf, samplecnt_t npeaks, samplecnt_t offset, samplecnt_t cnt, uint32_t chan_n, double samples_per_pixel) const
426 {
427         if (chan_n >= _sources.size()) {
428                 return 0;
429         }
430
431         if (audio_source(chan_n)->read_peaks (buf, npeaks, offset, cnt, samples_per_pixel)) {
432                 return 0;
433         }
434
435         if (_scale_amplitude != 1.0f) {
436                 for (samplecnt_t n = 0; n < npeaks; ++n) {
437                         buf[n].max *= _scale_amplitude;
438                         buf[n].min *= _scale_amplitude;
439                 }
440         }
441
442         return npeaks;
443 }
444
445 /** @param buf Buffer to write data to (existing data will be overwritten).
446  *  @param pos Position to read from as an offset from the region position.
447  *  @param cnt Number of samples to read.
448  *  @param channel Channel to read from.
449  */
450 samplecnt_t
451 AudioRegion::read (Sample* buf, samplepos_t pos, samplecnt_t cnt, int channel) const
452 {
453         /* raw read, no fades, no gain, nada */
454         return read_from_sources (_sources, _length, buf, _position + pos, cnt, channel);
455 }
456
457 samplecnt_t
458 AudioRegion::master_read_at (Sample *buf, Sample* /*mixdown_buffer*/, float* /*gain_buffer*/,
459                              samplepos_t position, samplecnt_t cnt, uint32_t chan_n) const
460 {
461         /* do not read gain/scaling/fades and do not count this disk i/o in statistics */
462
463         assert (cnt >= 0);
464         return read_from_sources (
465                 _master_sources, _master_sources.front()->length (_master_sources.front()->timeline_position()),
466                 buf, position, cnt, chan_n
467                 );
468 }
469
470 /** @param buf Buffer to mix data into.
471  *  @param mixdown_buffer Scratch buffer for audio data.
472  *  @param gain_buffer Scratch buffer for gain data.
473  *  @param position Position within the session to read from.
474  *  @param cnt Number of samples to read.
475  *  @param chan_n Channel number to read.
476  */
477 samplecnt_t
478 AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
479                       samplepos_t position,
480                       samplecnt_t cnt,
481                       uint32_t chan_n) const
482 {
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.
485         */
486
487         /* See doc/region_read.svg for a drawing which might help to explain
488            what is going on.
489         */
490
491         assert (cnt >= 0);
492
493         if (n_channels() == 0) {
494                 return 0;
495         }
496
497         /* WORK OUT WHERE TO GET DATA FROM */
498
499         samplecnt_t to_read;
500
501         assert (position >= _position);
502         sampleoffset_t const internal_offset = position - _position;
503
504         if (internal_offset >= _length) {
505                 return 0; /* read nothing */
506         }
507
508         if ((to_read = min (cnt, _length - internal_offset)) == 0) {
509                 return 0; /* read nothing */
510         }
511
512         boost::shared_ptr<Playlist> pl (playlist());
513         if (!pl){
514                 return 0;
515         }
516         
517         /* COMPUTE DETAILS OF ANY FADES INVOLVED IN THIS READ */
518
519         /* Amount (length) of fade in that we are dealing with in this read */
520         samplecnt_t fade_in_limit = 0;
521
522         /* Offset from buf / mixdown_buffer of the start
523            of any fade out that we are dealing with
524         */
525         sampleoffset_t fade_out_offset = 0;
526
527         /* Amount (length) of fade out that we are dealing with in this read */
528         samplecnt_t fade_out_limit = 0;
529
530         samplecnt_t fade_interval_start = 0;
531
532         /* Fade in */
533
534         if (_fade_in_active && _session.config.get_use_region_fades()) {
535
536                 samplecnt_t fade_in_length = (samplecnt_t) _fade_in->back()->when;
537
538                 /* see if this read is within the fade in */
539
540                 if (internal_offset < fade_in_length) {
541                         fade_in_limit = min (to_read, fade_in_length - internal_offset);
542                 }
543         }
544
545         /* Fade out */
546
547         if (_fade_out_active && _session.config.get_use_region_fades()) {
548
549                 /* see if some part of this read is within the fade out */
550
551                 /* .................        >|            REGION
552                  *                           _length
553                  *
554                  *               {           }            FADE
555                  *                           fade_out_length
556                  *               ^
557                  *               _length - fade_out_length
558                  *
559                  *      |--------------|
560                  *      ^internal_offset
561                  *                     ^internal_offset + to_read
562                  *
563                  *                     we need the intersection of [internal_offset,internal_offset+to_read] with
564                  *                     [_length - fade_out_length, _length]
565                  *
566                  */
567
568                 fade_interval_start = max (internal_offset, _length - samplecnt_t (_fade_out->back()->when));
569                 samplecnt_t fade_interval_end = min(internal_offset + to_read, _length.val());
570
571                 if (fade_interval_end > fade_interval_start) {
572                         /* (part of the) the fade out is in this buffer */
573                         fade_out_limit = fade_interval_end - fade_interval_start;
574                         fade_out_offset = fade_interval_start - internal_offset;
575                 }
576         }
577
578         /* READ DATA FROM THE SOURCE INTO mixdown_buffer.
579            We can never read directly into buf, since it may contain data
580            from a region `below' this one in the stack, and our fades (if they exist)
581            may need to mix with the existing data.
582         */
583
584         if (read_from_sources (_sources, _length, mixdown_buffer, position, to_read, chan_n) != to_read) {
585                 return 0;
586         }
587
588         /* APPLY REGULAR GAIN CURVES AND SCALING TO mixdown_buffer */
589
590         if (envelope_active())  {
591                 _envelope->curve().get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
592
593                 if (_scale_amplitude != 1.0f) {
594                         for (samplecnt_t n = 0; n < to_read; ++n) {
595                                 mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
596                         }
597                 } else {
598                         for (samplecnt_t n = 0; n < to_read; ++n) {
599                                 mixdown_buffer[n] *= gain_buffer[n];
600                         }
601                 }
602         } else if (_scale_amplitude != 1.0f) {
603                 apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
604         }
605
606         /* APPLY FADES TO THE DATA IN mixdown_buffer AND MIX THE RESULTS INTO
607          * buf. The key things to realize here: (1) the fade being applied is
608          * (as of April 26th 2012) just the inverse of the fade in curve (2)
609          * "buf" contains data from lower regions already. So this operation
610          * fades out the existing material.
611          */
612  
613         bool is_opaque = opaque();
614
615         if (fade_in_limit != 0) {
616
617                 if (is_opaque) {
618                         if (_inverse_fade_in) {
619
620                                 /* explicit inverse fade in curve (e.g. for constant
621                                  * power), so we have to fetch it.
622                                  */
623
624                                 _inverse_fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
625
626                                 /* Fade the data from lower layers out */
627                                 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
628                                         buf[n] *= gain_buffer[n];
629                                 }
630
631                                 /* refill gain buffer with the fade in */
632
633                                 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
634
635                         } else {
636
637                                 /* no explicit inverse fade in, so just use (1 - fade
638                                  * in) for the fade out of lower layers
639                                  */
640
641                                 _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
642
643                                 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
644                                         buf[n] *= 1 - gain_buffer[n];
645                                 }
646                         }
647                 } else {
648                         _fade_in->curve().get_vector (internal_offset, internal_offset + fade_in_limit, gain_buffer, fade_in_limit);
649                 }
650
651                 /* Mix our newly-read data in, with the fade */
652                 for (samplecnt_t n = 0; n < fade_in_limit; ++n) {
653                         buf[n] += mixdown_buffer[n] * gain_buffer[n];
654                 }
655         }
656
657         if (fade_out_limit != 0) {
658
659                 samplecnt_t const curve_offset = fade_interval_start - (_length - _fade_out->back()->when);
660
661                 if (is_opaque) {
662                         if (_inverse_fade_out) {
663
664                                 _inverse_fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
665
666                                 /* Fade the data from lower levels in */
667                                 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
668                                         buf[m] *= gain_buffer[n];
669                                 }
670
671                                 /* fetch the actual fade out */
672
673                                 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
674
675                         } else {
676
677                                 /* no explicit inverse fade out (which is
678                                  * actually a fade in), so just use (1 - fade
679                                  * out) for the fade in of lower layers
680                                  */
681
682                                 _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
683
684                                 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
685                                         buf[m] *= 1 - gain_buffer[n];
686                                 }
687                         }
688                 } else {
689                         _fade_out->curve().get_vector (curve_offset, curve_offset + fade_out_limit, gain_buffer, fade_out_limit);
690                 }
691
692                 /* Mix our newly-read data with whatever was already there,
693                    with the fade out applied to our data.
694                 */
695                 for (samplecnt_t n = 0, m = fade_out_offset; n < fade_out_limit; ++n, ++m) {
696                         buf[m] += mixdown_buffer[m] * gain_buffer[n];
697                 }
698         }
699
700         /* MIX OR COPY THE REGION BODY FROM mixdown_buffer INTO buf */
701
702         samplecnt_t const N = to_read - fade_in_limit - fade_out_limit;
703         if (N > 0) {
704                 if (is_opaque) {
705                         DEBUG_TRACE (DEBUG::AudioPlayback, string_compose ("Region %1 memcpy into buf @ %2 + %3, from mixdown buffer @ %4 + %5, len = %6 cnt was %7\n",
706                                                                            name(), buf, fade_in_limit, mixdown_buffer, fade_in_limit, N, cnt));
707                         memcpy (buf + fade_in_limit, mixdown_buffer + fade_in_limit, N * sizeof (Sample));
708                 } else {
709                         mix_buffers_no_gain (buf + fade_in_limit, mixdown_buffer + fade_in_limit, N);
710                 }
711         }
712
713         return to_read;
714 }
715
716 /** Read data directly from one of our sources, accounting for the situation when the track has a different channel
717  *  count to the region.
718  *
719  *  @param srcs Source list to get our source from.
720  *  @param limit Furthest that we should read, as an offset from the region position.
721  *  @param buf Buffer to write data into (existing contents of the buffer will be overwritten)
722  *  @param position Position to read from, in session samples.
723  *  @param cnt Number of samples to read.
724  *  @param chan_n Channel to read from.
725  *  @return Number of samples read.
726  */
727
728 samplecnt_t
729 AudioRegion::read_from_sources (SourceList const & srcs, samplecnt_t limit, Sample* buf, samplepos_t position, samplecnt_t cnt, uint32_t chan_n) const
730 {
731         sampleoffset_t const internal_offset = position - _position;
732         if (internal_offset >= limit) {
733                 return 0;
734         }
735
736         samplecnt_t const to_read = min (cnt, limit - internal_offset);
737         if (to_read == 0) {
738                 return 0;
739         }
740
741         if (chan_n < n_channels()) {
742
743                 boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[chan_n]);
744                 if (src->read (buf, _start + internal_offset, to_read) != to_read) {
745                         return 0; /* "read nothing" */
746                 }
747
748         } else {
749
750                 /* track is N-channel, this region has fewer channels; silence the ones
751                    we don't have.
752                 */
753
754                 if (Config->get_replicate_missing_region_channels()) {
755
756                         /* copy an existing channel's data in for this non-existant one */
757
758                         uint32_t channel = chan_n % n_channels();
759                         boost::shared_ptr<AudioSource> src = boost::dynamic_pointer_cast<AudioSource> (srcs[channel]);
760
761                         if (src->read (buf, _start + internal_offset, to_read) != to_read) {
762                                 return 0; /* "read nothing" */
763                         }
764
765                 } else {
766
767                         /* use silence */
768                         memset (buf, 0, sizeof (Sample) * to_read);
769                 }
770         }
771
772         return to_read;
773 }
774
775 XMLNode&
776 AudioRegion::get_basic_state ()
777 {
778         XMLNode& node (Region::state ());
779
780         node.set_property ("channels", (uint32_t)_sources.size());
781
782         return node;
783 }
784
785 XMLNode&
786 AudioRegion::state ()
787 {
788         XMLNode& node (get_basic_state());
789         XMLNode *child;
790
791         child = node.add_child ("Envelope");
792
793         bool default_env = false;
794
795         // If there are only two points, the points are in the start of the region and the end of the region
796         // so, if they are both at 1.0f, that means the default region.
797
798         if (_envelope->size() == 2 &&
799             _envelope->front()->value == GAIN_COEFF_UNITY &&
800             _envelope->back()->value==GAIN_COEFF_UNITY) {
801                 if (_envelope->front()->when == 0 && _envelope->back()->when == _length) {
802                         default_env = true;
803                 }
804         }
805
806         if (default_env) {
807                 child->set_property ("default", "yes");
808         } else {
809                 child->add_child_nocopy (_envelope->get_state ());
810         }
811
812         child = node.add_child (X_("FadeIn"));
813
814         if (_default_fade_in) {
815                 child->set_property ("default", "yes");
816         } else {
817                 child->add_child_nocopy (_fade_in->get_state ());
818         }
819
820         if (_inverse_fade_in) {
821                 child = node.add_child (X_("InverseFadeIn"));
822                 child->add_child_nocopy (_inverse_fade_in->get_state ());
823         }
824
825         child = node.add_child (X_("FadeOut"));
826
827         if (_default_fade_out) {
828                 child->set_property ("default", "yes");
829         } else {
830                 child->add_child_nocopy (_fade_out->get_state ());
831         }
832
833         if (_inverse_fade_out) {
834                 child = node.add_child (X_("InverseFadeOut"));
835                 child->add_child_nocopy (_inverse_fade_out->get_state ());
836         }
837
838         return node;
839 }
840
841 int
842 AudioRegion::_set_state (const XMLNode& node, int version, PropertyChange& what_changed, bool send)
843 {
844         const XMLNodeList& nlist = node.children();
845         boost::shared_ptr<Playlist> the_playlist (_playlist.lock());
846
847         suspend_property_changes ();
848
849         if (the_playlist) {
850                 the_playlist->freeze ();
851         }
852
853
854         /* this will set all our State members and stuff controlled by the Region.
855            It should NOT send any changed signals - that is our responsibility.
856         */
857
858         Region::_set_state (node, version, what_changed, false);
859
860         float val;
861         if (node.get_property ("scale-gain", val)) {
862                 if (val != _scale_amplitude) {
863                         _scale_amplitude = val;
864                         what_changed.add (Properties::scale_amplitude);
865                 }
866         }
867
868         /* Now find envelope description and other related child items */
869
870         _envelope->freeze ();
871
872         for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
873                 XMLNode *child;
874                 XMLProperty const * prop;
875
876                 child = (*niter);
877
878                 if (child->name() == "Envelope") {
879
880                         _envelope->clear ();
881
882                         if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child, version)) {
883                                 set_default_envelope ();
884                         }
885
886                         _envelope->truncate_end (_length);
887
888
889                 } else if (child->name() == "FadeIn") {
890
891                         _fade_in->clear ();
892
893                         bool is_default;
894                         if ((child->get_property ("default", is_default) && is_default) || (prop = child->property ("steepness")) != 0) {
895                                 set_default_fade_in ();
896                         } else {
897                                 XMLNode* grandchild = child->child ("AutomationList");
898                                 if (grandchild) {
899                                         _fade_in->set_state (*grandchild, version);
900                                 }
901                         }
902
903                         bool is_active;
904                         if (child->get_property ("active", is_active)) {
905                                 set_fade_in_active (is_active);
906                         }
907
908                 } else if (child->name() == "FadeOut") {
909
910                         _fade_out->clear ();
911
912                         bool is_default;
913                         if ((child->get_property ("default", is_default) && is_default) || (prop = child->property ("steepness")) != 0) {
914                                 set_default_fade_out ();
915                         } else {
916                                 XMLNode* grandchild = child->child ("AutomationList");
917                                 if (grandchild) {
918                                         _fade_out->set_state (*grandchild, version);
919                                 }
920                         }
921
922                         bool is_active;
923                         if (child->get_property ("active", is_active)) {
924                                 set_fade_out_active (is_active);
925                         }
926
927                 } else if ( (child->name() == "InverseFadeIn") || (child->name() == "InvFadeIn")  ) {
928                         XMLNode* grandchild = child->child ("AutomationList");
929                         if (grandchild) {
930                                 _inverse_fade_in->set_state (*grandchild, version);
931                         }
932                 } else if ( (child->name() == "InverseFadeOut") || (child->name() == "InvFadeOut") ) {
933                         XMLNode* grandchild = child->child ("AutomationList");
934                         if (grandchild) {
935                                 _inverse_fade_out->set_state (*grandchild, version);
936                         }
937                 }
938         }
939
940         _envelope->thaw ();
941         resume_property_changes ();
942
943         if (send) {
944                 send_change (what_changed);
945         }
946
947         if (the_playlist) {
948                 the_playlist->thaw ();
949         }
950
951         return 0;
952 }
953
954 int
955 AudioRegion::set_state (const XMLNode& node, int version)
956 {
957         PropertyChange what_changed;
958         return _set_state (node, version, what_changed, true);
959 }
960
961 void
962 AudioRegion::fade_range (samplepos_t start, samplepos_t end)
963 {
964         samplepos_t s, e;
965
966         switch (coverage (start, end)) {
967         case Evoral::OverlapStart:
968                 trim_front(start);
969                 s = _position;
970                 e = end;
971                 set_fade_in (FadeConstantPower, e - s);
972                 break;
973         case Evoral::OverlapEnd:
974                 trim_end(end);
975                 s = start;
976                 e = _position + _length;
977                 set_fade_out (FadeConstantPower, e - s);
978                 break;
979         case Evoral::OverlapInternal:
980                 /* needs addressing, perhaps. Difficult to do if we can't
981                  * control one edge of the fade relative to the relevant edge
982                  * of the region, which we cannot - fades are currently assumed
983                  * to start/end at the start/end of the region
984                  */
985                 break;
986         default:
987                 return;
988         }
989 }
990
991 void
992 AudioRegion::set_fade_in_shape (FadeShape shape)
993 {
994         set_fade_in (shape, (samplecnt_t) _fade_in->back()->when);
995 }
996
997 void
998 AudioRegion::set_fade_out_shape (FadeShape shape)
999 {
1000         set_fade_out (shape, (samplecnt_t) _fade_out->back()->when);
1001 }
1002
1003 void
1004 AudioRegion::set_fade_in (boost::shared_ptr<AutomationList> f)
1005 {
1006         _fade_in->freeze ();
1007         *(_fade_in.val()) = *f;
1008         _fade_in->thaw ();
1009         _default_fade_in = false;
1010
1011         send_change (PropertyChange (Properties::fade_in));
1012 }
1013
1014 void
1015 AudioRegion::set_fade_in (FadeShape shape, samplecnt_t len)
1016 {
1017         const ARDOUR::ParameterDescriptor desc(FadeInAutomation);
1018         boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeInAutomation, desc));
1019         boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeInAutomation, desc));
1020         boost::shared_ptr<Evoral::ControlList> c3 (new Evoral::ControlList (FadeInAutomation, desc));
1021
1022         _fade_in->freeze ();
1023         _fade_in->clear ();
1024         _inverse_fade_in->clear ();
1025
1026         const int num_steps = 32;
1027
1028         switch (shape) {
1029         case FadeLinear:
1030                 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1031                 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1032                 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1033                 break;
1034
1035         case FadeFast:
1036                 generate_db_fade (_fade_in.val(), len, num_steps, -60);
1037                 reverse_curve (c1, _fade_in.val());
1038                 _fade_in->copy_events (*c1);
1039                 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1040                 break;
1041
1042         case FadeSlow:
1043                 generate_db_fade (c1, len, num_steps, -1);  // start off with a slow fade
1044                 generate_db_fade (c2, len, num_steps, -80); // end with a fast fade
1045                 merge_curves (_fade_in.val(), c1, c2);
1046                 reverse_curve (c3, _fade_in.val());
1047                 _fade_in->copy_events (*c3);
1048                 generate_inverse_power_curve (_inverse_fade_in.val(), _fade_in.val());
1049                 break;
1050
1051         case FadeConstantPower:
1052                 _fade_in->fast_simple_add (0.0, GAIN_COEFF_SMALL);
1053                 for (int i = 1; i < num_steps; ++i) {
1054                         const float dist = i / (num_steps + 1.f);
1055                         _fade_in->fast_simple_add (len * dist, sin (dist * M_PI / 2.0));
1056                 }
1057                 _fade_in->fast_simple_add (len, GAIN_COEFF_UNITY);
1058                 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1059                 break;
1060
1061         case FadeSymmetric:
1062                 //start with a nearly linear cuve
1063                 _fade_in->fast_simple_add (0, 1);
1064                 _fade_in->fast_simple_add (0.5 * len, 0.6);
1065                 //now generate a fade-out curve by successively applying a gain drop
1066                 const double breakpoint = 0.7;  //linear for first 70%
1067                 for (int i = 2; i < 9; ++i) {
1068                         const float coeff = (1.f - breakpoint) * powf (0.5, i);
1069                         _fade_in->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1070                 }
1071                 _fade_in->fast_simple_add (len, GAIN_COEFF_SMALL);
1072                 reverse_curve (c3, _fade_in.val());
1073                 _fade_in->copy_events (*c3);
1074                 reverse_curve (_inverse_fade_in.val(), _fade_in.val());
1075                 break;
1076         }
1077
1078         _fade_in->set_interpolation(Evoral::ControlList::Curved);
1079         _inverse_fade_in->set_interpolation(Evoral::ControlList::Curved);
1080
1081         _default_fade_in = false;
1082         _fade_in->thaw ();
1083         send_change (PropertyChange (Properties::fade_in));
1084 }
1085
1086 void
1087 AudioRegion::set_fade_out (boost::shared_ptr<AutomationList> f)
1088 {
1089         _fade_out->freeze ();
1090         *(_fade_out.val()) = *f;
1091         _fade_out->thaw ();
1092         _default_fade_out = false;
1093
1094         send_change (PropertyChange (Properties::fade_out));
1095 }
1096
1097 void
1098 AudioRegion::set_fade_out (FadeShape shape, samplecnt_t len)
1099 {
1100         const ARDOUR::ParameterDescriptor desc(FadeOutAutomation);
1101         boost::shared_ptr<Evoral::ControlList> c1 (new Evoral::ControlList (FadeOutAutomation, desc));
1102         boost::shared_ptr<Evoral::ControlList> c2 (new Evoral::ControlList (FadeOutAutomation, desc));
1103
1104         _fade_out->freeze ();
1105         _fade_out->clear ();
1106         _inverse_fade_out->clear ();
1107
1108         const int num_steps = 32;
1109
1110         switch (shape) {
1111         case FadeLinear:
1112                 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1113                 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1114                 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1115                 break;
1116
1117         case FadeFast:
1118                 generate_db_fade (_fade_out.val(), len, num_steps, -60);
1119                 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1120                 break;
1121
1122         case FadeSlow:
1123                 generate_db_fade (c1, len, num_steps, -1);  //start off with a slow fade
1124                 generate_db_fade (c2, len, num_steps, -80);  //end with a fast fade
1125                 merge_curves (_fade_out.val(), c1, c2);
1126                 generate_inverse_power_curve (_inverse_fade_out.val(), _fade_out.val());
1127                 break;
1128
1129         case FadeConstantPower:
1130                 //constant-power fades use a sin/cos relationship
1131                 //the cutoff is abrupt but it has the benefit of being symmetrical
1132                 _fade_out->fast_simple_add (0.0, GAIN_COEFF_UNITY);
1133                 for (int i = 1; i < num_steps; ++i) {
1134                         const float dist = i / (num_steps + 1.f);
1135                         _fade_out->fast_simple_add (len * dist, cos (dist * M_PI / 2.0));
1136                 }
1137                 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1138                 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1139                 break;
1140
1141         case FadeSymmetric:
1142                 //start with a nearly linear cuve
1143                 _fade_out->fast_simple_add (0, 1);
1144                 _fade_out->fast_simple_add (0.5 * len, 0.6);
1145                 //now generate a fade-out curve by successively applying a gain drop
1146                 const double breakpoint = 0.7;  //linear for first 70%
1147                 for (int i = 2; i < 9; ++i) {
1148                         const float coeff = (1.f - breakpoint) * powf (0.5, i);
1149                         _fade_out->fast_simple_add (len * (breakpoint + ((GAIN_COEFF_UNITY - breakpoint) * (double)i / 9.0)), coeff);
1150                 }
1151                 _fade_out->fast_simple_add (len, GAIN_COEFF_SMALL);
1152                 reverse_curve (_inverse_fade_out.val(), _fade_out.val());
1153                 break;
1154         }
1155
1156         _fade_out->set_interpolation(Evoral::ControlList::Curved);
1157         _inverse_fade_out->set_interpolation(Evoral::ControlList::Curved);
1158
1159         _default_fade_out = false;
1160         _fade_out->thaw ();
1161         send_change (PropertyChange (Properties::fade_out));
1162 }
1163
1164 void
1165 AudioRegion::set_fade_in_length (samplecnt_t len)
1166 {
1167         if (len > _length) {
1168                 len = _length - 1;
1169         }
1170
1171         if (len < 64) {
1172                 len = 64;
1173         }
1174
1175         bool changed = _fade_in->extend_to (len);
1176
1177         if (changed) {
1178                 if (_inverse_fade_in) {
1179                         _inverse_fade_in->extend_to (len);
1180                 }
1181
1182                 _default_fade_in = false;
1183                 send_change (PropertyChange (Properties::fade_in));
1184         }
1185 }
1186
1187 void
1188 AudioRegion::set_fade_out_length (samplecnt_t len)
1189 {
1190         if (len > _length) {
1191                 len = _length - 1;
1192         }
1193
1194         if (len < 64) {
1195                 len = 64;
1196         }
1197
1198         bool changed =  _fade_out->extend_to (len);
1199
1200         if (changed) {
1201
1202                 if (_inverse_fade_out) {
1203                         _inverse_fade_out->extend_to (len);
1204                 }
1205                 _default_fade_out = false;
1206
1207                 send_change (PropertyChange (Properties::fade_out));
1208         }
1209 }
1210
1211 void
1212 AudioRegion::set_fade_in_active (bool yn)
1213 {
1214         if (yn == _fade_in_active) {
1215                 return;
1216         }
1217
1218         _fade_in_active = yn;
1219         send_change (PropertyChange (Properties::fade_in_active));
1220 }
1221
1222 void
1223 AudioRegion::set_fade_out_active (bool yn)
1224 {
1225         if (yn == _fade_out_active) {
1226                 return;
1227         }
1228         _fade_out_active = yn;
1229         send_change (PropertyChange (Properties::fade_out_active));
1230 }
1231
1232 bool
1233 AudioRegion::fade_in_is_default () const
1234 {
1235         return _fade_in->size() == 2 && _fade_in->front()->when == 0 && _fade_in->back()->when == 64;
1236 }
1237
1238 bool
1239 AudioRegion::fade_out_is_default () const
1240 {
1241         return _fade_out->size() == 2 && _fade_out->front()->when == 0 && _fade_out->back()->when == 64;
1242 }
1243
1244 void
1245 AudioRegion::set_default_fade_in ()
1246 {
1247         _fade_in_suspended = 0;
1248         set_fade_in (Config->get_default_fade_shape(), 64);
1249 }
1250
1251 void
1252 AudioRegion::set_default_fade_out ()
1253 {
1254         _fade_out_suspended = 0;
1255         set_fade_out (Config->get_default_fade_shape(), 64);
1256 }
1257
1258 void
1259 AudioRegion::set_default_fades ()
1260 {
1261         set_default_fade_in ();
1262         set_default_fade_out ();
1263 }
1264
1265 void
1266 AudioRegion::set_default_envelope ()
1267 {
1268         _envelope->freeze ();
1269         _envelope->clear ();
1270         _envelope->fast_simple_add (0, GAIN_COEFF_UNITY);
1271         _envelope->fast_simple_add (_length, GAIN_COEFF_UNITY);
1272         _envelope->thaw ();
1273 }
1274
1275 void
1276 AudioRegion::recompute_at_end ()
1277 {
1278         /* our length has changed. recompute a new final point by interpolating
1279            based on the the existing curve.
1280         */
1281
1282         _envelope->freeze ();
1283         _envelope->truncate_end (_length);
1284         _envelope->thaw ();
1285
1286         suspend_property_changes();
1287
1288         if (_left_of_split) {
1289                 set_default_fade_out ();
1290                 _left_of_split = false;
1291         } else if (_fade_out->back()->when > _length) {
1292                 _fade_out->extend_to (_length);
1293                 send_change (PropertyChange (Properties::fade_out));
1294         }
1295
1296         if (_fade_in->back()->when > _length) {
1297                 _fade_in->extend_to (_length);
1298                 send_change (PropertyChange (Properties::fade_in));
1299         }
1300
1301         resume_property_changes();
1302 }
1303
1304 void
1305 AudioRegion::recompute_at_start ()
1306 {
1307         /* as above, but the shift was from the front */
1308
1309         _envelope->truncate_start (_length);
1310
1311         suspend_property_changes();
1312
1313         if (_right_of_split) {
1314                 set_default_fade_in ();
1315                 _right_of_split = false;
1316         } else if (_fade_in->back()->when > _length) {
1317                 _fade_in->extend_to (_length);
1318                 send_change (PropertyChange (Properties::fade_in));
1319         }
1320
1321         if (_fade_out->back()->when > _length) {
1322                 _fade_out->extend_to (_length);
1323                 send_change (PropertyChange (Properties::fade_out));
1324         }
1325
1326         resume_property_changes();
1327 }
1328
1329 int
1330 AudioRegion::separate_by_channel (vector<boost::shared_ptr<Region> >& v) const
1331 {
1332         SourceList srcs;
1333         string new_name;
1334         int n = 0;
1335
1336         if (_sources.size() < 2) {
1337                 return 0;
1338         }
1339
1340         for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1341                 srcs.clear ();
1342                 srcs.push_back (*i);
1343
1344                 new_name = _name;
1345
1346                 if (_sources.size() == 2) {
1347                         if (n == 0) {
1348                                 new_name += "-L";
1349                         } else {
1350                                 new_name += "-R";
1351                         }
1352                 } else {
1353                         new_name += '-';
1354                         new_name += ('0' + n + 1);
1355                 }
1356
1357                 /* create a copy with just one source. prevent if from being thought of as
1358                    "whole file" even if it covers the entire source file(s).
1359                  */
1360
1361                 PropertyList plist;
1362
1363                 plist.add (Properties::start, _start.val());
1364                 plist.add (Properties::length, _length.val());
1365                 plist.add (Properties::name, new_name);
1366                 plist.add (Properties::layer, layer ());
1367
1368                 v.push_back(RegionFactory::create (srcs, plist));
1369                 v.back()->set_whole_file (false);
1370
1371                 ++n;
1372         }
1373
1374         return 0;
1375 }
1376
1377 samplecnt_t
1378 AudioRegion::read_raw_internal (Sample* buf, samplepos_t pos, samplecnt_t cnt, int channel) const
1379 {
1380         return audio_source(channel)->read (buf, pos, cnt);
1381 }
1382
1383 void
1384 AudioRegion::set_scale_amplitude (gain_t g)
1385 {
1386         boost::shared_ptr<Playlist> pl (playlist());
1387
1388         _scale_amplitude = g;
1389
1390         /* tell the diskstream we're in */
1391
1392         if (pl) {
1393                 pl->ContentsChanged();
1394         }
1395
1396         /* tell everybody else */
1397
1398         send_change (PropertyChange (Properties::scale_amplitude));
1399 }
1400
1401 double
1402 AudioRegion::maximum_amplitude (Progress* p) const
1403 {
1404         samplepos_t fpos = _start;
1405         samplepos_t const fend = _start + _length;
1406         double maxamp = 0;
1407
1408         samplecnt_t const blocksize = 64 * 1024;
1409         Sample buf[blocksize];
1410
1411         while (fpos < fend) {
1412
1413                 uint32_t n;
1414
1415                 samplecnt_t const to_read = min (fend - fpos, blocksize);
1416
1417                 for (n = 0; n < n_channels(); ++n) {
1418
1419                         /* read it in */
1420
1421                         if (read_raw_internal (buf, fpos, to_read, n) != to_read) {
1422                                 return 0;
1423                         }
1424
1425                         maxamp = compute_peak (buf, to_read, maxamp);
1426                 }
1427
1428                 fpos += to_read;
1429                 if (p) {
1430                         p->set_progress (float (fpos - _start) / _length);
1431                         if (p->cancelled ()) {
1432                                 return -1;
1433                         }
1434                 }
1435         }
1436
1437         return maxamp;
1438 }
1439
1440 double
1441 AudioRegion::rms (Progress* p) const
1442 {
1443         samplepos_t fpos = _start;
1444         samplepos_t const fend = _start + _length;
1445         uint32_t const n_chan = n_channels ();
1446         double rms = 0;
1447
1448         samplecnt_t const blocksize = 64 * 1024;
1449         Sample buf[blocksize];
1450
1451         samplecnt_t total = 0;
1452
1453         if (n_chan == 0 || fend == fpos) {
1454                 return 0;
1455         }
1456
1457         while (fpos < fend) {
1458                 samplecnt_t const to_read = min (fend - fpos, blocksize);
1459                 for (uint32_t c = 0; c < n_chan; ++c) {
1460                         if (read_raw_internal (buf, fpos, to_read, c) != to_read) {
1461                                 return 0;
1462                         }
1463                         for (samplepos_t i = 0; i < to_read; ++i) {
1464                                 rms += buf[i] * buf[i];
1465                         }
1466                 }
1467                 total += to_read;
1468                 fpos += to_read;
1469                 if (p) {
1470                         p->set_progress (float (fpos - _start) / _length);
1471                         if (p->cancelled ()) {
1472                                 return -1;
1473                         }
1474                 }
1475         }
1476         return sqrt (2. * rms / (double)(total * n_chan));
1477 }
1478
1479 /** Normalize using a given maximum amplitude and target, so that region
1480  *  _scale_amplitude becomes target / max_amplitude.
1481  */
1482 void
1483 AudioRegion::normalize (float max_amplitude, float target_dB)
1484 {
1485         gain_t target = dB_to_coefficient (target_dB);
1486
1487         if (target == GAIN_COEFF_UNITY) {
1488                 /* do not normalize to precisely 1.0 (0 dBFS), to avoid making it appear
1489                    that we may have clipped.
1490                 */
1491                 target -= FLT_EPSILON;
1492         }
1493
1494         if (max_amplitude < GAIN_COEFF_SMALL) {
1495                 /* don't even try */
1496                 return;
1497         }
1498
1499         if (max_amplitude == target) {
1500                 /* we can't do anything useful */
1501                 return;
1502         }
1503
1504         set_scale_amplitude (target / max_amplitude);
1505 }
1506
1507 void
1508 AudioRegion::fade_in_changed ()
1509 {
1510         send_change (PropertyChange (Properties::fade_in));
1511 }
1512
1513 void
1514 AudioRegion::fade_out_changed ()
1515 {
1516         send_change (PropertyChange (Properties::fade_out));
1517 }
1518
1519 void
1520 AudioRegion::envelope_changed ()
1521 {
1522         send_change (PropertyChange (Properties::envelope));
1523 }
1524
1525 void
1526 AudioRegion::suspend_fade_in ()
1527 {
1528         if (++_fade_in_suspended == 1) {
1529                 if (fade_in_is_default()) {
1530                         set_fade_in_active (false);
1531                 }
1532         }
1533 }
1534
1535 void
1536 AudioRegion::resume_fade_in ()
1537 {
1538         if (--_fade_in_suspended == 0 && _fade_in_suspended) {
1539                 set_fade_in_active (true);
1540         }
1541 }
1542
1543 void
1544 AudioRegion::suspend_fade_out ()
1545 {
1546         if (++_fade_out_suspended == 1) {
1547                 if (fade_out_is_default()) {
1548                         set_fade_out_active (false);
1549                 }
1550         }
1551 }
1552
1553 void
1554 AudioRegion::resume_fade_out ()
1555 {
1556         if (--_fade_out_suspended == 0 &&_fade_out_suspended) {
1557                 set_fade_out_active (true);
1558         }
1559 }
1560
1561 bool
1562 AudioRegion::speed_mismatch (float sr) const
1563 {
1564         if (_sources.empty()) {
1565                 /* impossible, but ... */
1566                 return false;
1567         }
1568
1569         float fsr = audio_source()->sample_rate();
1570
1571         return fsr != sr;
1572 }
1573
1574 void
1575 AudioRegion::source_offset_changed ()
1576 {
1577         /* XXX this fixes a crash that should not occur. It does occur
1578            becauses regions are not being deleted when a session
1579            is unloaded. That bug must be fixed.
1580         */
1581
1582         if (_sources.empty()) {
1583                 return;
1584         }
1585
1586         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
1587
1588         if (afs && afs->destructive()) {
1589                 // set_start (source()->natural_position(), this);
1590                 set_position (source()->natural_position());
1591         }
1592 }
1593
1594 boost::shared_ptr<AudioSource>
1595 AudioRegion::audio_source (uint32_t n) const
1596 {
1597         // Guaranteed to succeed (use a static cast for speed?)
1598         return boost::dynamic_pointer_cast<AudioSource>(source(n));
1599 }
1600
1601 uint32_t
1602 AudioRegion::get_related_audio_file_channel_count () const
1603 {
1604     uint32_t chan_count = 0;
1605     for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
1606
1607         boost::shared_ptr<SndFileSource> sndf = boost::dynamic_pointer_cast<SndFileSource>(*i);
1608         if (sndf ) {
1609
1610             if (sndf->channel_count() > chan_count) {
1611                 chan_count = sndf->channel_count();
1612             }
1613         }
1614 #ifdef HAVE_COREAUDIO
1615         else {
1616             boost::shared_ptr<CoreAudioSource> cauf = boost::dynamic_pointer_cast<CoreAudioSource>(*i);
1617             if (cauf) {
1618                 if (cauf->channel_count() > chan_count) {
1619                     chan_count = cauf->channel_count();
1620                 }
1621             }
1622         }
1623 #endif // HAVE_COREAUDIO
1624     }
1625
1626     return chan_count;
1627 }
1628
1629 void
1630 AudioRegion::clear_transients () // yet unused
1631 {
1632         _user_transients.clear ();
1633         _valid_transients = false;
1634         send_change (PropertyChange (Properties::valid_transients));
1635 }
1636
1637 void
1638 AudioRegion::add_transient (samplepos_t where)
1639 {
1640         if (where < first_sample () || where >= last_sample ()) {
1641                 return;
1642         }
1643         where -= _position;
1644
1645         if (!_valid_transients) {
1646                 _transient_user_start = _start;
1647                 _valid_transients = true;
1648         }
1649         sampleoffset_t offset = _transient_user_start - _start;
1650
1651         if (where < offset) {
1652                 if (offset <= 0) {
1653                         return;
1654                 }
1655                 // region start changed (extend to front), shift points and offset
1656                 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1657                         (*x) += offset;
1658                 }
1659                 _transient_user_start -= offset;
1660                 offset = 0;
1661         }
1662
1663         const samplepos_t p = where - offset;
1664         _user_transients.push_back(p);
1665         send_change (PropertyChange (Properties::valid_transients));
1666 }
1667
1668 void
1669 AudioRegion::update_transient (samplepos_t old_position, samplepos_t new_position)
1670 {
1671         bool changed = false;
1672         if (!_onsets.empty ()) {
1673                 const samplepos_t p = old_position - _position;
1674                 AnalysisFeatureList::iterator x = std::find (_onsets.begin (), _onsets.end (), p);
1675                 if (x != _transients.end ()) {
1676                         (*x) = new_position - _position;
1677                         changed = true;
1678                 }
1679         }
1680
1681         if (_valid_transients) {
1682                 const sampleoffset_t offset = _position + _transient_user_start - _start;
1683                 const samplepos_t p = old_position - offset;
1684                 AnalysisFeatureList::iterator x = std::find (_user_transients.begin (), _user_transients.end (), p);
1685                 if (x != _transients.end ()) {
1686                         (*x) = new_position - offset;
1687                         changed = true;
1688                 }
1689         }
1690
1691         if (changed) {
1692                 send_change (PropertyChange (Properties::valid_transients));
1693         }
1694 }
1695
1696 void
1697 AudioRegion::remove_transient (samplepos_t where)
1698 {
1699         bool changed = false;
1700         if (!_onsets.empty ()) {
1701                 const samplepos_t p = where - _position;
1702                 AnalysisFeatureList::iterator i = std::find (_onsets.begin (), _onsets.end (), p);
1703                 if (i != _transients.end ()) {
1704                         _onsets.erase (i);
1705                         changed = true;
1706                 }
1707         }
1708
1709         if (_valid_transients) {
1710                 const samplepos_t p = where - (_position + _transient_user_start - _start);
1711                 AnalysisFeatureList::iterator i = std::find (_user_transients.begin (), _user_transients.end (), p);
1712                 if (i != _transients.end ()) {
1713                         _transients.erase (i);
1714                         changed = true;
1715                 }
1716         }
1717
1718         if (changed) {
1719                 send_change (PropertyChange (Properties::valid_transients));
1720         }
1721 }
1722
1723 void
1724 AudioRegion::set_onsets (AnalysisFeatureList& results)
1725 {
1726         _onsets.clear();
1727         _onsets = results;
1728         send_change (PropertyChange (Properties::valid_transients));
1729 }
1730
1731 void
1732 AudioRegion::build_transients ()
1733 {
1734         _transients.clear ();
1735         _transient_analysis_start = _transient_analysis_end = 0;
1736
1737         boost::shared_ptr<Playlist> pl = playlist();
1738
1739         if (!pl) {
1740                 return;
1741         }
1742
1743         /* check analyzed sources first */
1744         SourceList::iterator s;
1745         for (s = _sources.begin() ; s != _sources.end(); ++s) {
1746                 if (!(*s)->has_been_analysed()) {
1747 #ifndef NDEBUG
1748                         cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
1749 #endif
1750                         break;
1751                 }
1752         }
1753
1754         if (s == _sources.end()) {
1755                 /* all sources are analyzed, merge data from each one */
1756                 for (s = _sources.begin() ; s != _sources.end(); ++s) {
1757
1758                         /* find the set of transients within the bounds of this region */
1759                         AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
1760                                                                          (*s)->transients.end(),
1761                                                                          _start);
1762
1763                         AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
1764                                                                           (*s)->transients.end(),
1765                                                                           _start + _length);
1766
1767                         /* and add them */
1768                         _transients.insert (_transients.end(), low, high);
1769                 }
1770
1771                 TransientDetector::cleanup_transients (_transients, pl->session().sample_rate(), 3.0);
1772
1773                 /* translate all transients to current position */
1774                 for (AnalysisFeatureList::iterator x = _transients.begin(); x != _transients.end(); ++x) {
1775                         (*x) -= _start;
1776                 }
1777
1778                 _transient_analysis_start = _start;
1779                 _transient_analysis_end = _start + _length;
1780                 return;
1781         }
1782
1783         /* no existing/complete transient info */
1784
1785         static bool analyse_dialog_shown = false; /* global per instance of Ardour */
1786
1787         if (!Config->get_auto_analyse_audio()) {
1788                 if (!analyse_dialog_shown) {
1789                         pl->session().Dialog (string_compose (_("\
1790 You have requested an operation that requires audio analysis.\n\n\
1791 You currently have \"auto-analyse-audio\" disabled, which means \
1792 that transient data must be generated every time it is required.\n\n\
1793 If you are doing work that will require transient data on a \
1794 regular basis, you should probably enable \"auto-analyse-audio\" \
1795 in Preferences > Audio > Regions, then quit %1 and restart.\n\n\
1796 This dialog will not display again.  But you may notice a slight delay \
1797 in this and future transient-detection operations.\n\
1798 "), PROGRAM_NAME));
1799                         analyse_dialog_shown = true;
1800                 }
1801         }
1802
1803         try {
1804                 TransientDetector t (pl->session().sample_rate());
1805                 for (uint32_t i = 0; i < n_channels(); ++i) {
1806
1807                         AnalysisFeatureList these_results;
1808
1809                         t.reset ();
1810
1811                         /* this produces analysis result relative to current position
1812                          * ::read() sample 0 is at _position */
1813                         if (t.run ("", this, i, these_results)) {
1814                                 return;
1815                         }
1816
1817                         /* merge */
1818                         _transients.insert (_transients.end(), these_results.begin(), these_results.end());
1819                 }
1820         } catch (...) {
1821                 error << string_compose(_("Transient Analysis failed for %1."), _("Audio Region")) << endmsg;
1822                 return;
1823         }
1824
1825         TransientDetector::cleanup_transients (_transients, pl->session().sample_rate(), 3.0);
1826         _transient_analysis_start = _start;
1827         _transient_analysis_end = _start + _length;
1828 }
1829
1830 /* Transient analysis uses ::read() which is relative to _start,
1831  * at the time of analysis and spans _length samples.
1832  *
1833  * This is true for RhythmFerret::run_analysis and the
1834  * TransientDetector here.
1835  *
1836  * We store _start and length in _transient_analysis_start,
1837  * _transient_analysis_end in case the region is trimmed or split after analysis.
1838  *
1839  * Various methods (most notably Playlist::find_next_transient and
1840  * RhythmFerret::do_split_action) span multiple regions and *merge/combine*
1841  * Analysis results.
1842  * We therefore need to translate the analysis timestamps to absolute session-time
1843  * and include the _position of the region.
1844  *
1845  * Note: we should special case the AudioRegionView. The region-view itself
1846  * is located at _position (currently ARV subtracts _position again)
1847  */
1848 void
1849 AudioRegion::get_transients (AnalysisFeatureList& results)
1850 {
1851         boost::shared_ptr<Playlist> pl = playlist();
1852         if (!playlist ()) {
1853                 return;
1854         }
1855
1856         Region::merge_features (results, _user_transients, _position + _transient_user_start - _start);
1857
1858         if (!_onsets.empty ()) {
1859                 // onsets are invalidated when start or length changes
1860                 merge_features (results, _onsets, _position);
1861                 return;
1862         }
1863
1864         if ((_transient_analysis_start == _transient_analysis_end)
1865                         || _transient_analysis_start > _start
1866                         || _transient_analysis_end < _start + _length) {
1867                 build_transients ();
1868         }
1869
1870         merge_features (results, _transients, _position + _transient_analysis_start - _start);
1871 }
1872
1873 /** Find areas of `silence' within a region.
1874  *
1875  *  @param threshold Threshold below which signal is considered silence (as a sample value)
1876  *  @param min_length Minimum length of silent period to be reported.
1877  *  @return Silent intervals, measured relative to the region start in the source
1878  */
1879
1880 AudioIntervalResult
1881 AudioRegion::find_silence (Sample threshold, samplecnt_t min_length, samplecnt_t fade_length, InterThreadInfo& itt) const
1882 {
1883         samplecnt_t const block_size = 64 * 1024;
1884         boost::scoped_array<Sample> loudest (new Sample[block_size]);
1885         boost::scoped_array<Sample> buf (new Sample[block_size]);
1886
1887         assert (fade_length >= 0);
1888         assert (min_length > 0);
1889
1890         samplepos_t pos = _start;
1891         samplepos_t const end = _start + _length;
1892
1893         AudioIntervalResult silent_periods;
1894
1895         bool in_silence = true;
1896         sampleoffset_t silence_start = _start;
1897
1898         while (pos < end && !itt.cancel) {
1899
1900                 samplecnt_t cur_samples = 0;
1901                 samplecnt_t const to_read = min (end - pos, block_size);
1902                 /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
1903                 memset (loudest.get(), 0, sizeof (Sample) * block_size);
1904
1905                 for (uint32_t n = 0; n < n_channels(); ++n) {
1906
1907                         cur_samples = read_raw_internal (buf.get(), pos, to_read, n);
1908                         for (samplecnt_t i = 0; i < cur_samples; ++i) {
1909                                 loudest[i] = max (loudest[i], abs (buf[i]));
1910                         }
1911                 }
1912
1913                 /* now look for silence */
1914                 for (samplecnt_t i = 0; i < cur_samples; ++i) {
1915                         bool const silence = abs (loudest[i]) < threshold;
1916                         if (silence && !in_silence) {
1917                                 /* non-silence to silence */
1918                                 in_silence = true;
1919                                 silence_start = pos + i + fade_length;
1920                         } else if (!silence && in_silence) {
1921                                 /* silence to non-silence */
1922                                 in_silence = false;
1923                                 sampleoffset_t silence_end = pos + i - 1 - fade_length;
1924
1925                                 if (silence_end - silence_start >= min_length) {
1926                                         silent_periods.push_back (std::make_pair (silence_start, silence_end));
1927                                 }
1928                         }
1929                 }
1930
1931                 pos += cur_samples;
1932                 itt.progress = (end - pos) / (double)_length;
1933
1934                 if (cur_samples == 0) {
1935                         assert (pos >= end);
1936                         break;
1937                 }
1938         }
1939
1940         if (in_silence && !itt.cancel) {
1941                 /* last block was silent, so finish off the last period */
1942                 if (end - 1 - silence_start >= min_length + fade_length) {
1943                         silent_periods.push_back (std::make_pair (silence_start, end - 1));
1944                 }
1945         }
1946
1947         itt.done = true;
1948
1949         return silent_periods;
1950 }
1951
1952 Evoral::Range<samplepos_t>
1953 AudioRegion::body_range () const
1954 {
1955         return Evoral::Range<samplepos_t> (first_sample() + _fade_in->back()->when + 1, last_sample() - _fade_out->back()->when);
1956 }
1957
1958 boost::shared_ptr<Region>
1959 AudioRegion::get_single_other_xfade_region (bool start) const
1960 {
1961         boost::shared_ptr<Playlist> pl (playlist());
1962
1963         if (!pl) {
1964                 /* not currently in a playlist - xfade length is unbounded
1965                    (and irrelevant)
1966                 */
1967                 return boost::shared_ptr<AudioRegion> ();
1968         }
1969
1970         boost::shared_ptr<RegionList> rl;
1971
1972         if (start) {
1973                 rl = pl->regions_at (position());
1974         } else {
1975                 rl = pl->regions_at (last_sample());
1976         }
1977
1978         RegionList::iterator i;
1979         boost::shared_ptr<Region> other;
1980         uint32_t n = 0;
1981
1982         /* count and find the other region in a single pass through the list */
1983
1984         for (i = rl->begin(); i != rl->end(); ++i) {
1985                 if ((*i).get() != this) {
1986                         other = *i;
1987                 }
1988                 ++n;
1989         }
1990
1991         if (n != 2) {
1992                 /* zero or multiple regions stacked here - don't care about xfades */
1993                 return boost::shared_ptr<AudioRegion> ();
1994         }
1995
1996         return other;
1997 }
1998
1999 samplecnt_t
2000 AudioRegion::verify_xfade_bounds (samplecnt_t len, bool start)
2001 {
2002         /* this is called from a UI to check on whether a new proposed
2003            length for an xfade is legal or not. it returns the legal
2004            length corresponding to @a len which may be shorter than or
2005            equal to @a len itself.
2006         */
2007
2008         boost::shared_ptr<Region> other = get_single_other_xfade_region (start);
2009         samplecnt_t maxlen;
2010
2011         if (!other) {
2012                 /* zero or > 2 regions here, don't care about len, but
2013                    it can't be longer than the region itself.
2014                  */
2015                 return min (length(), len);
2016         }
2017
2018         /* we overlap a single region. clamp the length of an xfade to
2019            the maximum possible duration of the overlap (if the other
2020            region were trimmed appropriately).
2021         */
2022
2023         if (start) {
2024                 maxlen = other->latest_possible_sample() - position();
2025         } else {
2026                 maxlen = last_sample() - other->earliest_possible_position();
2027         }
2028
2029         return min (length(), min (maxlen, len));
2030
2031 }
2032