Use a shared_ptr for SessionPlaylists so that it can be explicitly destroyed in ...
[ardour.git] / libs / ardour / audioregion.cc
index 8034f3ddacf5963b4517fca7c4407583b62424d2..e46f8ed3fd15607f7c01ea9efd45ae6adc966312 100644 (file)
@@ -1,5 +1,5 @@
 /*
-    Copyright (C) 2000-2006 Paul Davis 
+    Copyright (C) 2000-2006 Paul Davis
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
@@ -20,6 +20,7 @@
 #include <cmath>
 #include <climits>
 #include <cfloat>
+#include <algorithm>
 
 #include <set>
 
 
 #include <glibmm/thread.h>
 
-#include <pbd/basename.h>
-#include <pbd/xml++.h>
-#include <pbd/stacktrace.h>
-#include <pbd/enumwriter.h>
-#include <pbd/convert.h>
-
-#include <ardour/audioregion.h>
-#include <ardour/session.h>
-#include <ardour/gain.h>
-#include <ardour/dB.h>
-#include <ardour/playlist.h>
-#include <ardour/audiofilesource.h>
-#include <ardour/region_factory.h>
-#include <ardour/runtime_functions.h>
+#include "pbd/basename.h"
+#include "pbd/xml++.h"
+#include "pbd/stacktrace.h"
+#include "pbd/enumwriter.h"
+#include "pbd/convert.h"
+
+#include "evoral/Curve.hpp"
+
+#include "ardour/audioregion.h"
+#include "ardour/session.h"
+#include "ardour/gain.h"
+#include "ardour/dB.h"
+#include "ardour/playlist.h"
+#include "ardour/audiofilesource.h"
+#include "ardour/region_factory.h"
+#include "ardour/runtime_functions.h"
+#include "ardour/transient_detector.h"
 
 #include "i18n.h"
 #include <locale.h>
@@ -69,24 +73,28 @@ AudioRegion::init ()
        set_default_envelope ();
 
        listen_to_my_curves ();
+       connect_to_analysis_changed ();
 }
 
-/* constructor for use by derived types only */
+/** Constructor for use by derived types only */
 AudioRegion::AudioRegion (Session& s, nframes_t start, nframes_t length, string name)
        : Region (s, start, length, name, DataType::AUDIO)
-       , _fade_in (new AutomationList(Parameter(FadeInAutomation), 0.0, 2.0, 1.0))
-       , _fade_out (new AutomationList(Parameter(FadeOutAutomation), 0.0, 2.0, 1.0))
-       , _envelope (new AutomationList(Parameter(EnvelopeAutomation), 0.0, 2.0, 1.0))
+       , _automatable(s)
+       , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
+       , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
+       , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
 {
        init ();
+       assert (_sources.size() == _master_sources.size());
 }
 
 /** Basic AudioRegion constructor (one channel) */
 AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, nframes_t start, nframes_t length)
        : Region (src, start, length, PBD::basename_nosuffix(src->name()), DataType::AUDIO, 0,  Region::Flag(Region::DefaultFlags|Region::External))
-       , _fade_in (new AutomationList(Parameter(FadeInAutomation), 0.0, 2.0, 1.0))
-       , _fade_out (new AutomationList(Parameter(FadeOutAutomation), 0.0, 2.0, 1.0))
-       , _envelope (new AutomationList(Parameter(EnvelopeAutomation), 0.0, 2.0, 1.0))
+       , _automatable(src->session())
+       , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
+       , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
+       , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
 {
        boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (src);
        if (afs) {
@@ -94,14 +102,16 @@ AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, nframes_t start, n
        }
 
        init ();
+       assert (_sources.size() == _master_sources.size());
 }
 
 /* Basic AudioRegion constructor (one channel) */
 AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, nframes_t start, nframes_t length, const string& name, layer_t layer, Flag flags)
        : Region (src, start, length, name, DataType::AUDIO, layer, flags)
-       , _fade_in (new AutomationList(Parameter(FadeInAutomation), 0.0, 2.0, 1.0))
-       , _fade_out (new AutomationList(Parameter(FadeOutAutomation), 0.0, 2.0, 1.0))
-       , _envelope (new AutomationList(Parameter(EnvelopeAutomation), 0.0, 2.0, 1.0))
+       , _automatable(src->session())
+       , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
+       , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
+       , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
 {
        boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (src);
        if (afs) {
@@ -109,45 +119,33 @@ AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, nframes_t start, n
        }
 
        init ();
+       assert (_sources.size() == _master_sources.size());
 }
 
-/* Basic AudioRegion constructor (many channels) */
-AudioRegion::AudioRegion (SourceList& srcs, nframes_t start, nframes_t length, const string& name, layer_t layer, Flag flags)
+/** Basic AudioRegion constructor (many channels) */
+AudioRegion::AudioRegion (const SourceList& srcs, nframes_t start, nframes_t length, const string& name, layer_t layer, Flag flags)
        : Region (srcs, start, length, name, DataType::AUDIO, layer, flags)
-       , _fade_in (new AutomationList(Parameter(FadeInAutomation), 0.0, 2.0, 1.0))
-       , _fade_out (new AutomationList(Parameter(FadeOutAutomation), 0.0, 2.0, 1.0))
-       , _envelope (new AutomationList(Parameter(EnvelopeAutomation), 0.0, 2.0, 1.0))
+       , _automatable(srcs[0]->session())
+       , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
+       , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
+       , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
 {
        init ();
+       connect_to_analysis_changed ();
+       assert (_sources.size() == _master_sources.size());
 }
 
-
 /** Create a new AudioRegion, that is part of an existing one */
 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, nframes_t offset, nframes_t length, const string& name, layer_t layer, Flag flags)
        : Region (other, offset, length, name, layer, flags)
-       , _fade_in (new AutomationList(Parameter(FadeInAutomation), 0.0, 2.0, 1.0))
-       , _fade_out (new AutomationList(Parameter(FadeOutAutomation), 0.0, 2.0, 1.0))
-       , _envelope (new AutomationList(Parameter(EnvelopeAutomation), 0.0, 2.0, 1.0))
+       , _automatable(other->session())
+       , _fade_in (new AutomationList(*other->_fade_in))
+       , _fade_out (new AutomationList(*other->_fade_out))
+       , _envelope (new AutomationList(*other->_envelope, offset, offset + length))
 {
-       set<boost::shared_ptr<Source> > unique_srcs;
-
-       for (SourceList::const_iterator i= other->_sources.begin(); i != other->_sources.end(); ++i) {
-               _sources.push_back (*i);
-
-               pair<set<boost::shared_ptr<Source> >::iterator,bool> result;
-
-               result = unique_srcs.insert (*i);
-               
-               if (result.second) {
-                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
-                       if (afs) {
-                               afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
-                       }
-               }
-       }
+       connect_to_header_position_offset_changed ();
 
        /* return to default fades if the existing ones are too long */
-       init ();
 
        if (_flags & LeftOfSplit) {
                if (_fade_in->back()->when >= _length) {
@@ -172,29 +170,64 @@ AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, nframes_t
        _scale_amplitude = other->_scale_amplitude;
 
        assert(_type == DataType::AUDIO);
+
+       listen_to_my_curves ();
+       connect_to_analysis_changed ();
+
+       assert (_sources.size() == _master_sources.size());
 }
 
 AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other)
        : Region (other)
-       , _fade_in (new AutomationList(Parameter(FadeInAutomation), 0.0, 2.0, 1.0))
-       , _fade_out (new AutomationList(Parameter(FadeOutAutomation), 0.0, 2.0, 1.0))
-       , _envelope (new AutomationList(Parameter(EnvelopeAutomation), 0.0, 2.0, 1.0))
+       , _automatable (other->session())
+       , _fade_in (new AutomationList (*other->_fade_in))
+       , _fade_out (new AutomationList (*other->_fade_out))
+       , _envelope (new AutomationList (*other->_envelope))
 {
+       assert(_type == DataType::AUDIO);
        _scale_amplitude = other->_scale_amplitude;
-       _envelope = other->_envelope;
 
-       set_default_fades ();
-       
        listen_to_my_curves ();
+       connect_to_analysis_changed ();
 
-       assert(_type == DataType::AUDIO);
+       assert (_sources.size() == _master_sources.size());
+}
+
+AudioRegion::AudioRegion (boost::shared_ptr<const AudioRegion> other, const SourceList& /*srcs*/,
+                         nframes_t length, const string& name, layer_t layer, Flag flags)
+       : Region (other, length, name, layer, flags)
+       , _automatable (other->session())
+       , _fade_in (new AutomationList (*other->_fade_in))
+       , _fade_out (new AutomationList (*other->_fade_out))
+       , _envelope (new AutomationList (*other->_envelope))
+{
+       /* make-a-sort-of-copy-with-different-sources constructor (used by audio filter) */
+
+       for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
+
+               boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> ((*i));
+               if (afs) {
+                       afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
+               }
+       }
+
+       _scale_amplitude = other->_scale_amplitude;
+
+       _fade_in_disabled = 0;
+       _fade_out_disabled = 0;
+
+       listen_to_my_curves ();
+       connect_to_analysis_changed ();
+
+       assert (_sources.size() == _master_sources.size());
 }
 
 AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, const XMLNode& node)
        : Region (src, node)
-       , _fade_in (new AutomationList(Parameter(FadeInAutomation), 0.0, 2.0, 1.0))
-       , _fade_out (new AutomationList(Parameter(FadeOutAutomation), 0.0, 2.0, 1.0))
-       , _envelope (new AutomationList(Parameter(EnvelopeAutomation), 0.0, 2.0, 1.0))
+       , _automatable(src->session())
+       , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
+       , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
+       , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
 {
        boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (src);
        if (afs) {
@@ -203,26 +236,32 @@ AudioRegion::AudioRegion (boost::shared_ptr<AudioSource> src, const XMLNode& nod
 
        init ();
 
-       if (set_state (node)) {
+       if (set_state (node, Stateful::loading_state_version)) {
                throw failed_constructor();
        }
 
        assert(_type == DataType::AUDIO);
+       connect_to_analysis_changed ();
+
+       assert (_sources.size() == _master_sources.size());
 }
 
 AudioRegion::AudioRegion (SourceList& srcs, const XMLNode& node)
        : Region (srcs, node)
-       , _fade_in (new AutomationList(Parameter(FadeInAutomation), 0.0, 2.0, 1.0))
-       , _fade_out (new AutomationList(Parameter(FadeOutAutomation), 0.0, 2.0, 1.0))
-       , _envelope (new AutomationList(Parameter(EnvelopeAutomation), 0.0, 2.0, 1.0))
+       , _automatable(srcs[0]->session())
+       , _fade_in (new AutomationList(Evoral::Parameter(FadeInAutomation)))
+       , _fade_out (new AutomationList(Evoral::Parameter(FadeOutAutomation)))
+       , _envelope (new AutomationList(Evoral::Parameter(EnvelopeAutomation)))
 {
        init ();
 
-       if (set_state (node)) {
+       if (set_state (node, Stateful::loading_state_version)) {
                throw failed_constructor();
        }
 
        assert(_type == DataType::AUDIO);
+       connect_to_analysis_changed ();
+       assert (_sources.size() == _master_sources.size());
 }
 
 AudioRegion::~AudioRegion ()
@@ -230,59 +269,36 @@ AudioRegion::~AudioRegion ()
 }
 
 void
-AudioRegion::listen_to_my_curves ()
+AudioRegion::connect_to_analysis_changed ()
 {
-       _envelope->StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
-       _fade_in->StateChanged.connect (mem_fun (*this, &AudioRegion::fade_in_changed));
-       _fade_out->StateChanged.connect (mem_fun (*this, &AudioRegion::fade_out_changed));
-}
-
-bool
-AudioRegion::verify_length (nframes_t len)
-{
-       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source());
-
-       if (afs && afs->destructive()) {
-               return true;
-       } else {
-               return Region::verify_length(len);
+       for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
+               (*i)->AnalysisChanged.connect (mem_fun (*this, &AudioRegion::invalidate_transients));
        }
 }
 
-bool
-AudioRegion::verify_start_and_length (nframes_t new_start, nframes_t new_length)
+void
+AudioRegion::connect_to_header_position_offset_changed ()
 {
-       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source());
-
-       if (afs && afs->destructive()) {
-               return true;
-       } else {
-               return Region::verify_start_and_length(new_start, new_length);
-       }
-}
+       set<boost::shared_ptr<Source> > unique_srcs;
 
-bool
-AudioRegion::verify_start (nframes_t pos)
-{
-       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source());
+       for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
 
-       if (afs && afs->destructive()) {
-               return true;
-       } else {
-               return Region::verify_start(pos);
+               if (unique_srcs.find (*i) == unique_srcs.end ()) {
+                       unique_srcs.insert (*i);
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*i);
+                       if (afs) {
+                               afs->HeaderPositionOffsetChanged.connect (mem_fun (*this, &AudioRegion::source_offset_changed));
+                       }
+               }
        }
 }
 
-bool
-AudioRegion::verify_start_mutable (nframes_t& new_start)
+void
+AudioRegion::listen_to_my_curves ()
 {
-       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(source());
-
-       if (afs && afs->destructive()) {
-               return true;
-       } else {
-               return Region::verify_start_mutable(new_start);
-       }
+       _envelope->StateChanged.connect (mem_fun (*this, &AudioRegion::envelope_changed));
+       _fade_in->StateChanged.connect (mem_fun (*this, &AudioRegion::fade_in_changed));
+       _fade_out->StateChanged.connect (mem_fun (*this, &AudioRegion::fade_out_changed));
 }
 
 void
@@ -305,7 +321,7 @@ ARDOUR::nframes_t
 AudioRegion::read_peaks (PeakData *buf, nframes_t npeaks, nframes_t offset, nframes_t cnt, uint32_t chan_n, double samples_per_unit) const
 {
        if (chan_n >= _sources.size()) {
-               return 0; 
+               return 0;
        }
 
        if (audio_source(chan_n)->read_peaks (buf, npeaks, offset, cnt, samples_per_unit)) {
@@ -321,30 +337,54 @@ AudioRegion::read_peaks (PeakData *buf, nframes_t npeaks, nframes_t offset, nfra
        }
 }
 
-ARDOUR::nframes_t
-AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer, nframes_t position, nframes_t cnt, uint32_t chan_n) const
+nframes_t
+AudioRegion::read (Sample* buf, sframes_t timeline_position, nframes_t cnt, int channel) const
 {
-       return _read_at (_sources, buf, mixdown_buffer, gain_buffer, position, cnt, chan_n);
+       /* raw read, no fades, no gain, nada */
+       return _read_at (_sources, _length, buf, 0, 0, _position + timeline_position, cnt, channel, 0, 0, ReadOps (0));
 }
 
-ARDOUR::nframes_t
-AudioRegion::master_read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer, nframes_t position, 
-                            nframes_t cnt, uint32_t chan_n) const
+nframes_t
+AudioRegion::read_with_ops (Sample* buf, sframes_t file_position, nframes_t cnt, int channel, ReadOps rops) const
 {
-       return _read_at (_master_sources, buf, mixdown_buffer, gain_buffer, position, cnt, chan_n);
+       return _read_at (_sources, _length, buf, 0, 0, file_position, cnt, channel, 0, 0, rops);
 }
 
-ARDOUR::nframes_t
-AudioRegion::_read_at (const SourceList& srcs, Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
-                      nframes_t position, nframes_t cnt, uint32_t chan_n) const
+nframes_t
+AudioRegion::read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
+               sframes_t file_position, nframes_t cnt, uint32_t chan_n,
+               nframes_t read_frames, nframes_t skip_frames) const
 {
-       // cerr << _name << "._read_at(" << position << ") - " << _position << endl;
+       /* regular diskstream/butler read complete with fades etc */
+       return _read_at (_sources, _length, buf, mixdown_buffer, gain_buffer,
+                       file_position, cnt, chan_n, read_frames, skip_frames, ReadOps (~0));
+}
 
+nframes_t
+AudioRegion::master_read_at (Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
+               sframes_t position, nframes_t cnt, uint32_t chan_n) const
+{
+       /* do not read gain/scaling/fades and do not count this disk i/o in statistics */
+
+       return _read_at (_master_sources, _master_sources.front()->length(_master_sources.front()->timeline_position()),
+                        buf, mixdown_buffer, gain_buffer, position, cnt, chan_n, 0, 0, ReadOps (0));
+}
+
+nframes_t
+AudioRegion::_read_at (const SourceList& /*srcs*/, nframes_t limit,
+               Sample *buf, Sample *mixdown_buffer, float *gain_buffer,
+               sframes_t position, nframes_t cnt,
+               uint32_t chan_n,
+               nframes_t /*read_frames*/,
+               nframes_t /*skip_frames*/,
+               ReadOps rops) const
+{
        nframes_t internal_offset;
        nframes_t buf_offset;
        nframes_t to_read;
+       bool raw = (rops == ReadOpsNone);
 
-       if (muted()) {
+       if (muted() && !raw) {
                return 0; /* read nothing */
        }
 
@@ -359,117 +399,120 @@ AudioRegion::_read_at (const SourceList& srcs, Sample *buf, Sample *mixdown_buff
                buf_offset = 0;
        }
 
-       if (internal_offset >= _length) {
+       if (internal_offset >= limit) {
                return 0; /* read nothing */
        }
 
-       if ((to_read = min (cnt, _length - internal_offset)) == 0) {
+       if ((to_read = min (cnt, limit - internal_offset)) == 0) {
                return 0; /* read nothing */
        }
 
-       if (opaque()) {
+       if (opaque() || raw) {
                /* overwrite whatever is there */
                mixdown_buffer = buf + buf_offset;
        } else {
                mixdown_buffer += buf_offset;
        }
 
-       _read_data_count = 0;
+       if (rops & ReadOpsCount) {
+               _read_data_count = 0;
+       }
 
        if (chan_n < n_channels()) {
-               
+
                boost::shared_ptr<AudioSource> src = audio_source(chan_n);
                if (src->read (mixdown_buffer, _start + internal_offset, to_read) != to_read) {
-
                        return 0; /* "read nothing" */
                }
 
-               _read_data_count += src->read_data_count();
+               if (rops & ReadOpsCount) {
+                       _read_data_count += src->read_data_count();
+               }
 
        } else {
-               
+
                /* track is N-channel, this region has less channels; silence the ones
                   we don't have.
                */
 
                memset (mixdown_buffer, 0, sizeof (Sample) * cnt);
+       }
 
-               /* no fades required */
+       if (rops & ReadOpsFades) {
 
-               goto merge;
-       }
+               /* fade in */
 
-       /* fade in */
+               if ((_flags & FadeIn) && _session.config.get_use_region_fades()) {
 
-       if (_flags & FadeIn) {
+                       nframes_t fade_in_length = (nframes_t) _fade_in->back()->when;
 
-               nframes_t fade_in_length = (nframes_t) _fade_in->back()->when;
-               
-               /* see if this read is within the fade in */
+                       /* see if this read is within the fade in */
 
-               if (internal_offset < fade_in_length) {
-               
-                       nframes_t limit;
+                       if (internal_offset < fade_in_length) {
 
-                       limit = min (to_read, fade_in_length - internal_offset);
+                               nframes_t fi_limit;
 
-                       _fade_in->curve().get_vector (internal_offset, internal_offset+limit, gain_buffer, limit);
+                               fi_limit = min (to_read, fade_in_length - internal_offset);
 
-                       for (nframes_t n = 0; n < limit; ++n) {
-                               mixdown_buffer[n] *= gain_buffer[n];
+
+                               _fade_in->curve().get_vector (internal_offset, internal_offset+fi_limit, gain_buffer, fi_limit);
+
+                               for (nframes_t n = 0; n < fi_limit; ++n) {
+                                       mixdown_buffer[n] *= gain_buffer[n];
+                               }
                        }
                }
-       }
-       
-       /* fade out */
 
-       if (_flags & FadeOut) {
-       
-               /* see if some part of this read is within the fade out */
+               /* fade out */
+
+               if ((_flags & FadeOut) && _session.config.get_use_region_fades()) {
+
+                       /* see if some part of this read is within the fade out */
 
                /* .................        >|            REGION
-                                           _length
-                                           
+                                            limit
+
                                  {           }            FADE
                                             fade_out_length
-                                 ^                                          
-                               _length - fade_out_length
+                                 ^
+                                 limit - fade_out_length
                         |--------------|
                         ^internal_offset
                                        ^internal_offset + to_read
 
-                  we need the intersection of [internal_offset,internal_offset+to_read] with
-                  [_length - fade_out_length, _length]
+                                      we need the intersection of [internal_offset,internal_offset+to_read] with
+                                      [limit - fade_out_length, limit]
 
                */
 
-       
-               nframes_t fade_out_length = (nframes_t) _fade_out->back()->when;
-               nframes_t fade_interval_start = max(internal_offset, _length-fade_out_length);
-               nframes_t fade_interval_end   = min(internal_offset + to_read, _length);
-
-               if (fade_interval_end > fade_interval_start) {
-                       /* (part of the) the fade out is  in this buffer */
-                       
-                       nframes_t limit = fade_interval_end - fade_interval_start;
-                       nframes_t curve_offset = fade_interval_start - (_length-fade_out_length);
-                       nframes_t fade_offset = fade_interval_start - internal_offset;
-                                                                      
-                       _fade_out->curve().get_vector (curve_offset,curve_offset+limit, gain_buffer, limit);
-
-                       for (nframes_t n = 0, m = fade_offset; n < limit; ++n, ++m) {
-                               mixdown_buffer[m] *= gain_buffer[n];
+
+                       nframes_t fade_out_length = (nframes_t) _fade_out->back()->when;
+                       nframes_t fade_interval_start = max(internal_offset, limit-fade_out_length);
+                       nframes_t fade_interval_end   = min(internal_offset + to_read, limit);
+
+                       if (fade_interval_end > fade_interval_start) {
+                               /* (part of the) the fade out is  in this buffer */
+
+                               nframes_t fo_limit = fade_interval_end - fade_interval_start;
+                               nframes_t curve_offset = fade_interval_start - (limit-fade_out_length);
+                               nframes_t fade_offset = fade_interval_start - internal_offset;
+
+                               _fade_out->curve().get_vector (curve_offset, curve_offset+fo_limit, gain_buffer, fo_limit);
+
+                               for (nframes_t n = 0, m = fade_offset; n < fo_limit; ++n, ++m) {
+                                       mixdown_buffer[m] *= gain_buffer[n];
+                               }
                        }
-               } 
 
+               }
        }
 
-       /* Regular gain curves */
+       /* Regular gain curves and scaling */
 
-       if (envelope_active())  {
+       if ((rops & ReadOpsOwnAutomation) && envelope_active())  {
                _envelope->curve().get_vector (internal_offset, internal_offset + to_read, gain_buffer, to_read);
-               
-               if (_scale_amplitude != 1.0f) {
+
+               if ((rops & ReadOpsOwnScaling) && _scale_amplitude != 1.0f) {
                        for (nframes_t n = 0; n < to_read; ++n) {
                                mixdown_buffer[n] *= gain_buffer[n] * _scale_amplitude;
                        }
@@ -478,11 +521,15 @@ AudioRegion::_read_at (const SourceList& srcs, Sample *buf, Sample *mixdown_buff
                                mixdown_buffer[n] *= gain_buffer[n];
                        }
                }
-       } else if (_scale_amplitude != 1.0f) {
-               apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
-       }
+       } else if ((rops & ReadOpsOwnScaling) && _scale_amplitude != 1.0f) {
+
+               // XXX this should be using what in 2.0 would have been:
+               // Session::apply_gain_to_buffer (mixdown_buffer, to_read, _scale_amplitude);
 
-  merge:
+               for (nframes_t n = 0; n < to_read; ++n) {
+                       mixdown_buffer[n] *= _scale_amplitude;
+               }
+       }
 
        if (!opaque()) {
 
@@ -490,15 +537,15 @@ AudioRegion::_read_at (const SourceList& srcs, Sample *buf, Sample *mixdown_buff
                 */
 
                buf += buf_offset;
-               
+
                for (nframes_t n = 0; n < to_read; ++n) {
                        buf[n] += mixdown_buffer[n];
                }
-       } 
-       
+       }
+
        return to_read;
 }
-       
+
 XMLNode&
 AudioRegion::state (bool full)
 {
@@ -507,7 +554,7 @@ AudioRegion::state (bool full)
        char buf[64];
        char buf2[64];
        LocaleGuard lg (X_("POSIX"));
-       
+
        node.add_property ("flags", enum_2_string (_flags));
 
        snprintf (buf, sizeof(buf), "%.12g", _scale_amplitude);
@@ -531,33 +578,33 @@ AudioRegion::state (bool full)
        node.add_property ("channels", buf);
 
        if (full) {
-       
+
                child = node.add_child (X_("FadeIn"));
-               
+
                if ((_flags & DefaultFadeIn)) {
                        child->add_property (X_("default"), X_("yes"));
                } else {
                        child->add_child_nocopy (_fade_in->get_state ());
                }
 
-               child->add_property (X_("active"), _fade_in_disabled ? X_("no") : X_("yes"));
-               
+               child->add_property (X_("active"), fade_in_active () ? X_("yes") : X_("no"));
+
                child = node.add_child (X_("FadeOut"));
-               
+
                if ((_flags & DefaultFadeOut)) {
                        child->add_property (X_("default"), X_("yes"));
                } else {
                        child->add_child_nocopy (_fade_out->get_state ());
                }
-               
-               child->add_property (X_("active"), _fade_out_disabled ? X_("no") : X_("yes"));
+
+               child->add_property (X_("active"), fade_out_active () ? X_("yes") : X_("no"));
        }
-       
+
        child = node.add_child ("Envelope");
 
        if (full) {
                bool default_env = false;
-               
+
                // If there are only two points, the points are in the start of the region and the end of the region
                // so, if they are both at 1.0f, that means the default region.
 
@@ -567,7 +614,7 @@ AudioRegion::state (bool full)
                        if (_envelope->front()->when == 0 && _envelope->back()->when == _length) {
                                default_env = true;
                        }
-               } 
+               }
 
                if (default_env) {
                        child->add_property ("default", "yes");
@@ -587,16 +634,16 @@ AudioRegion::state (bool full)
 }
 
 int
-AudioRegion::set_live_state (const XMLNode& node, Change& what_changed, bool send)
+AudioRegion::set_live_state (const XMLNode& node, int version, Change& what_changed, bool send)
 {
        const XMLNodeList& nlist = node.children();
        const XMLProperty *prop;
        LocaleGuard lg (X_("POSIX"));
 
-       Region::set_live_state (node, what_changed, false);
+       Region::set_live_state (node, version, what_changed, false);
 
        uint32_t old_flags = _flags;
-               
+
        if ((prop = node.property ("flags")) != 0) {
                _flags = Flag (string_2_enum (prop->value(), _flags));
 
@@ -606,6 +653,14 @@ AudioRegion::set_live_state (const XMLNode& node, Change& what_changed, bool sen
                _flags = Flag (_flags & ~Region::RightOfSplit);
        }
 
+       /* leave this flag setting in place, no matter what */
+
+       if ((old_flags & DoNotSendPropertyChanges)) {
+               _flags = Flag (_flags | DoNotSendPropertyChanges);
+       }
+
+       /* find out if any flags changed that we signal about */
+
        if ((old_flags ^ _flags) & Muted) {
                what_changed = Change (what_changed|MuteChanged);
        }
@@ -622,21 +677,21 @@ AudioRegion::set_live_state (const XMLNode& node, Change& what_changed, bool sen
        } else {
                _scale_amplitude = 1.0;
        }
-       
+
        /* Now find envelope description and other misc child items */
-                               
+
        for (XMLNodeConstIterator niter = nlist.begin(); niter != nlist.end(); ++niter) {
-               
+
                XMLNode *child;
                XMLProperty *prop;
-               
+
                child = (*niter);
-               
+
                if (child->name() == "Envelope") {
 
                        _envelope->clear ();
 
-                       if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child)) {
+                       if ((prop = child->property ("default")) != 0 || _envelope->set_state (*child, version)) {
                                set_default_envelope ();
                        }
 
@@ -644,21 +699,48 @@ AudioRegion::set_live_state (const XMLNode& node, Change& what_changed, bool sen
                        _envelope->truncate_end (_length);
 
                } else if (child->name() == "FadeIn") {
-                       
+
                        _fade_in->clear ();
-                       
-                       if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0 || _fade_in->set_state (*child)) {
+
+                       if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0) {
                                set_default_fade_in ();
-                       } 
+                       } else {
+                               XMLNode* grandchild = child->child ("AutomationList");
+                               if (grandchild) {
+                                       _fade_in->set_state (*grandchild, version);
+                               }
+                       }
+
+                       if ((prop = child->property ("active")) != 0) {
+                               if (string_is_affirmative (prop->value())) {
+                                       set_fade_in_active (true);
+                               } else {
+                                       set_fade_in_active (false);
+                               }
+                       }
 
                } else if (child->name() == "FadeOut") {
-                       
+
                        _fade_out->clear ();
 
-                       if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0 || _fade_out->set_state (*child)) {
+                       if ((prop = child->property ("default")) != 0 || (prop = child->property ("steepness")) != 0) {
                                set_default_fade_out ();
-                       } 
-               } 
+                       } else {
+                               XMLNode* grandchild = child->child ("AutomationList");
+                               if (grandchild) {
+                                       _fade_out->set_state (*grandchild, version);
+                               }
+                       }
+
+                       if ((prop = child->property ("active")) != 0) {
+                               if (string_is_affirmative (prop->value())) {
+                                       set_fade_out_active (true);
+                               } else {
+                                       set_fade_out_active (false);
+                               }
+                       }
+
+               }
        }
 
        if (send) {
@@ -669,14 +751,14 @@ AudioRegion::set_live_state (const XMLNode& node, Change& what_changed, bool sen
 }
 
 int
-AudioRegion::set_state (const XMLNode& node)
+AudioRegion::set_state (const XMLNode& node, int version)
 {
        /* Region::set_state() calls the virtual set_live_state(),
           which will get us back to AudioRegion::set_live_state()
           to handle the relevant stuff.
        */
 
-       return Region::set_state (node);
+       return Region::set_state (node, version);
 }
 
 void
@@ -884,20 +966,20 @@ AudioRegion::fade_out_is_default () const
 void
 AudioRegion::set_default_fade_in ()
 {
+       _fade_in_disabled = 0;
        set_fade_in (Linear, 64);
 }
 
 void
 AudioRegion::set_default_fade_out ()
 {
+       _fade_out_disabled = 0;
        set_fade_out (Linear, 64);
 }
 
 void
 AudioRegion::set_default_fades ()
 {
-       _fade_in_disabled = 0;
-       _fade_out_disabled = 0;
        set_default_fade_in ();
        set_default_fade_out ();
 }
@@ -915,10 +997,10 @@ AudioRegion::set_default_envelope ()
 void
 AudioRegion::recompute_at_end ()
 {
-       /* our length has changed. recompute a new final point by interpolating 
+       /* our length has changed. recompute a new final point by interpolating
           based on the the existing curve.
        */
-       
+
        _envelope->freeze ();
        _envelope->truncate_end (_length);
        _envelope->set_max_xval (_length);
@@ -933,7 +1015,7 @@ AudioRegion::recompute_at_end ()
                _fade_out->extend_to (_length);
                send_change (FadeOutChanged);
        }
-}      
+}
 
 void
 AudioRegion::recompute_at_start ()
@@ -954,20 +1036,17 @@ AudioRegion::recompute_at_start ()
 }
 
 int
-AudioRegion::separate_by_channel (Session& session, vector<boost::shared_ptr<AudioRegion> >& v) const
+AudioRegion::separate_by_channel (Session& /*session*/, vector<boost::shared_ptr<Region> >& v) const
 {
        SourceList srcs;
        string new_name;
-       int n;
+       int n = 0;
 
        if (_sources.size() < 2) {
                return 0;
        }
 
-       n = 0;
-
        for (SourceList::const_iterator i = _sources.begin(); i != _sources.end(); ++i) {
-
                srcs.clear ();
                srcs.push_back (*i);
 
@@ -984,17 +1063,14 @@ AudioRegion::separate_by_channel (Session& session, vector<boost::shared_ptr<Aud
                        new_name += ('0' + n + 1);
                }
 
-               /* create a copy with just one source. prevent if from being thought of as "whole file" even if 
-                  it covers the entire source file(s).
+               /* create a copy with just one source. prevent if from being thought of as
+                  "whole file" even if it covers the entire source file(s).
                 */
 
                Flag f = Flag (_flags & ~WholeFile);
 
-               boost::shared_ptr<Region> r = RegionFactory::create (srcs, _start, _length, new_name, _layer, f);
-               boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (r);
+               v.push_back(RegionFactory::create (srcs, _start, _length, new_name, _layer, f));
 
-               v.push_back (ar);
-               
                ++n;
        }
 
@@ -1002,74 +1078,75 @@ AudioRegion::separate_by_channel (Session& session, vector<boost::shared_ptr<Aud
 }
 
 nframes_t
-AudioRegion::read_raw_internal (Sample* buf, nframes_t pos, nframes_t cnt) const
+AudioRegion::read_raw_internal (Sample* buf, sframes_t pos, nframes_t cnt, int channel) const
 {
-       return audio_source()->read  (buf, pos, cnt);
+       return audio_source()->read (buf, pos, cnt, channel);
 }
 
-
 int
-AudioRegion::exportme (Session& session, AudioExportSpecification& spec)
+AudioRegion::exportme (Session& /*session*/, ARDOUR::ExportSpecification& /*spec*/)
 {
-       const nframes_t blocksize = 4096;
-       nframes_t to_read;
-       int status = -1;
-
-       spec.channels = _sources.size();
-
-       if (spec.prepare (blocksize, session.frame_rate())) {
-               goto out;
-       }
-
-       spec.pos = 0;
-       spec.total_frames = _length;
-
-       while (spec.pos < _length && !spec.stop) {
-               
-               
-               /* step 1: interleave */
-               
-               to_read = min (_length - spec.pos, blocksize);
-               
-               if (spec.channels == 1) {
-
-                       if (read_raw_internal (spec.dataF, _start + spec.pos, to_read) != to_read) {
-                               goto out;
-                       }
-
-               } else {
-
-                       Sample buf[blocksize];
-
-                       for (uint32_t chan = 0; chan < spec.channels; ++chan) {
-                               
-                               if (audio_source(chan)->read (buf, _start + spec.pos, to_read) != to_read) {
-                                       goto out;
-                               }
-                               
-                               for (nframes_t x = 0; x < to_read; ++x) {
-                                       spec.dataF[chan+(x*spec.channels)] = buf[x];
-                               }
-                       }
-               }
-               
-               if (spec.process (to_read)) {
-                       goto out;
-               }
-               
-               spec.pos += to_read;
-               spec.progress = (double) spec.pos /_length;
-               
-       }
-       
-       status = 0;
-
-  out: 
-       spec.running = false;
-       spec.status = status;
-       spec.clear();
-       
-       return status;
+       // TODO EXPORT
+//     const nframes_t blocksize = 4096;
+//     nframes_t to_read;
+//     int status = -1;
+//
+//     spec.channels = _sources.size();
+//
+//     if (spec.prepare (blocksize, session.frame_rate())) {
+//             goto out;
+//     }
+//
+//     spec.pos = 0;
+//     spec.total_frames = _length;
+//
+//     while (spec.pos < _length && !spec.stop) {
+//
+//
+//             /* step 1: interleave */
+//
+//             to_read = min (_length - spec.pos, blocksize);
+//
+//             if (spec.channels == 1) {
+//
+//                     if (read_raw_internal (spec.dataF, _start + spec.pos, to_read) != to_read) {
+//                             goto out;
+//                     }
+//
+//             } else {
+//
+//                     Sample buf[blocksize];
+//
+//                     for (uint32_t chan = 0; chan < spec.channels; ++chan) {
+//
+//                             if (audio_source(chan)->read (buf, _start + spec.pos, to_read) != to_read) {
+//                                     goto out;
+//                             }
+//
+//                             for (nframes_t x = 0; x < to_read; ++x) {
+//                                     spec.dataF[chan+(x*spec.channels)] = buf[x];
+//                             }
+//                     }
+//             }
+//
+//             if (spec.process (to_read)) {
+//                     goto out;
+//             }
+//
+//             spec.pos += to_read;
+//             spec.progress = (double) spec.pos /_length;
+//
+//     }
+//
+//     status = 0;
+//
+//  out:
+//     spec.running = false;
+//     spec.status = status;
+//     spec.clear();
+//
+//     return status;
+       return 0;
 }
 
 void
@@ -1080,7 +1157,7 @@ AudioRegion::set_scale_amplitude (gain_t g)
        _scale_amplitude = g;
 
        /* tell the diskstream we're in */
-       
+
        if (pl) {
                pl->Modified();
        }
@@ -1123,10 +1200,10 @@ AudioRegion::normalize_to (float target_dB)
 
                        /* read it in */
 
-                       if (read_raw_internal (buf, fpos, to_read) != to_read) {
+                       if (read_raw_internal (buf, fpos, to_read, 0) != to_read) {
                                return;
                        }
-                       
+
                        maxamp = compute_peak (buf, to_read, maxamp);
                }
 
@@ -1230,12 +1307,21 @@ AudioRegion::speed_mismatch (float sr) const
 void
 AudioRegion::source_offset_changed ()
 {
+       /* XXX this fixes a crash that should not occur. It does occur
+          becauses regions are not being deleted when a session
+          is unloaded. That bug must be fixed.
+       */
+
+       if (_sources.empty()) {
+               return;
+       }
+
        boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(_sources.front());
 
        if (afs && afs->destructive()) {
                // set_start (source()->natural_position(), this);
                set_position (source()->natural_position(), this);
-       } 
+       }
 }
 
 boost::shared_ptr<AudioSource>
@@ -1245,9 +1331,195 @@ AudioRegion::audio_source (uint32_t n) const
        return boost::dynamic_pointer_cast<AudioSource>(source(n));
 }
 
+int
+AudioRegion::get_transients (AnalysisFeatureList& results, bool force_new)
+{
+       boost::shared_ptr<Playlist> pl = playlist();
+
+       if (!pl) {
+               return -1;
+       }
+
+       if (_valid_transients && !force_new) {
+               results = _transients;
+               return 0;
+       }
+
+       SourceList::iterator s;
+
+       for (s = _sources.begin() ; s != _sources.end(); ++s) {
+               if (!(*s)->has_been_analysed()) {
+                       cerr << "For " << name() << " source " << (*s)->name() << " has not been analyzed\n";
+                       break;
+               }
+       }
+
+       if (s == _sources.end()) {
+               /* all sources are analyzed, merge data from each one */
+
+               for (s = _sources.begin() ; s != _sources.end(); ++s) {
+
+                       /* find the set of transients within the bounds of this region */
+
+                       AnalysisFeatureList::iterator low = lower_bound ((*s)->transients.begin(),
+                                                                        (*s)->transients.end(),
+                                                                        _start);
+
+                       AnalysisFeatureList::iterator high = upper_bound ((*s)->transients.begin(),
+                                                                         (*s)->transients.end(),
+                                                                         _start + _length);
+
+                       /* and add them */
+
+                       results.insert (results.end(), low, high);
+               }
+
+               TransientDetector::cleanup_transients (results, pl->session().frame_rate(), 3.0);
+
+               /* translate all transients to current position */
+
+               for (AnalysisFeatureList::iterator x = results.begin(); x != results.end(); ++x) {
+                       (*x) -= _start;
+                       (*x) += _position;
+               }
+
+               _transients = results;
+               _valid_transients = true;
+
+               return 0;
+       }
+
+       /* no existing/complete transient info */
+
+       if (!Config->get_auto_analyse_audio()) {
+               pl->session().Dialog (_("\
+You have requested an operation that requires audio analysis.\n\n\
+You currently have \"auto-analyse-audio\" disabled, which means\n\
+that transient data must be generated every time it is required.\n\n\
+If you are doing work that will require transient data on a\n\
+regular basis, you should probably enable \"auto-analyse-audio\"\n\
+then quit ardour and restart."));
+       }
+
+       TransientDetector t (pl->session().frame_rate());
+       bool existing_results = !results.empty();
+
+       _transients.clear ();
+       _valid_transients = false;
+
+       for (uint32_t i = 0; i < n_channels(); ++i) {
+
+               AnalysisFeatureList these_results;
+
+               t.reset ();
+
+               if (t.run ("", this, i, these_results)) {
+                       return -1;
+               }
+
+               /* translate all transients to give absolute position */
+
+               for (AnalysisFeatureList::iterator i = these_results.begin(); i != these_results.end(); ++i) {
+                       (*i) += _position;
+               }
+
+               /* merge */
+
+               _transients.insert (_transients.end(), these_results.begin(), these_results.end());
+       }
+
+       if (!results.empty()) {
+               if (existing_results) {
+
+                       /* merge our transients into the existing ones, then clean up
+                          those.
+                       */
+
+                       results.insert (results.end(), _transients.begin(), _transients.end());
+                       TransientDetector::cleanup_transients (results, pl->session().frame_rate(), 3.0);
+               }
+
+               /* make sure ours are clean too */
+
+               TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
+
+       } else {
+
+               TransientDetector::cleanup_transients (_transients, pl->session().frame_rate(), 3.0);
+               results = _transients;
+       }
+
+       _valid_transients = true;
+
+       return 0;
+}
+
+/** Find areas of `silence' within a region.
+ *
+ *  @param threshold Threshold below which signal is considered silence (as a sample value)
+ *  @param min_length Minimum length of silent period to be reported.
+ *  @return Silent periods; first of pair is the offset within the region, second is the length of the period
+ */
+
+std::list<std::pair<nframes_t, nframes_t> >
+AudioRegion::find_silence (Sample threshold, nframes_t min_length) const
+{
+       nframes_t const block_size = 64 * 1024;
+       Sample loudest[block_size];
+       Sample buf[block_size];
+
+       nframes_t pos = _start;
+       nframes_t const end = _start + _length - 1;
+
+       std::list<std::pair<nframes_t, nframes_t> > silent_periods;
+
+       bool in_silence = false;
+       nframes_t silence_start = 0;
+       bool silence;
+
+       while (pos < end) {
+
+               /* fill `loudest' with the loudest absolute sample at each instant, across all channels */
+               memset (loudest, 0, sizeof (Sample) * block_size);
+               for (uint32_t n = 0; n < n_channels(); ++n) {
+
+                       read_raw_internal (buf, pos, block_size, n);
+                       for (nframes_t i = 0; i < block_size; ++i) {
+                               loudest[i] = max (loudest[i], abs (buf[i]));
+                       }
+               }
+
+               /* now look for silence */
+               for (nframes_t i = 0; i < block_size; ++i) {
+                       silence = abs (loudest[i]) < threshold;
+                       if (silence && !in_silence) {
+                               /* non-silence to silence */
+                               in_silence = true;
+                               silence_start = pos + i;
+                       } else if (!silence && in_silence) {
+                               /* silence to non-silence */
+                               in_silence = false;
+                               if (pos + i - 1 - silence_start >= min_length) {
+                                       silent_periods.push_back (std::make_pair (silence_start, pos + i - 1));
+                               }
+                       }
+               }
+
+               pos += block_size;
+       }
+
+       if (in_silence && end - 1 - silence_start >= min_length) {
+               /* last block was silent, so finish off the last period */
+               silent_periods.push_back (std::make_pair (silence_start, end));
+       }
+
+       return silent_periods;
+}
+
+
 extern "C" {
 
-       int region_read_peaks_from_c (void *arg, uint32_t npeaks, uint32_t start, uint32_t cnt, intptr_t data, uint32_t n_chan, double samples_per_unit) 
+       int region_read_peaks_from_c (void *arg, uint32_t npeaks, uint32_t start, uint32_t cnt, intptr_t data, uint32_t n_chan, double samples_per_unit)
 {
        return ((AudioRegion *) arg)->read_peaks ((PeakData *) data, (nframes_t) npeaks, (nframes_t) start, (nframes_t) cnt, n_chan,samples_per_unit);
 }