remove unused API
[ardour.git] / libs / ardour / disk_reader.cc
index 70c35318cb6cde74845f54c7ba9dedd7e933be06..0df940a13b97dcbd099ff44f12f0392988ad49c5 100644 (file)
@@ -1,20 +1,20 @@
 /*
- * Copyright (C) 2009-2018 Paul Davis
- * Copyright (C) 2019 Robin Gareus <robin@gareus.org>
+ * Copyright (C) 2017-2018 Paul Davis <paul@linuxaudiosystems.com>
+ * Copyright (C) 2017-2019 Robin Gareus <robin@gareus.org>
  *
- * 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 the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * 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
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  */
 
 #include <boost/smart_ptr/scoped_array.hpp>
@@ -51,37 +51,32 @@ Sample* DiskReader::_sum_buffer = 0;
 Sample* DiskReader::_mixdown_buffer = 0;
 gain_t* DiskReader::_gain_buffer = 0;
 samplecnt_t DiskReader::midi_readahead = 4096;
-bool DiskReader::_no_disk_output = false;
+gint DiskReader::_no_disk_output (0);
 
 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
        : DiskIOProcessor (s, str, f)
        , overwrite_sample (0)
-       , _pending_overwrite (false)
        , overwrite_queued (false)
+       , run_must_resolve (false)
        , _declick_amp (s.nominal_sample_rate ())
        , _declick_offs (0)
 {
        file_sample[DataType::AUDIO] = 0;
        file_sample[DataType::MIDI] = 0;
+       g_atomic_int_set (&_pending_overwrite, 0);
 }
 
 DiskReader::~DiskReader ()
 {
        DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
-
-       for (uint32_t n = 0; n < DataType::num_types; ++n) {
-               if (_playlists[n]) {
-                       _playlists[n]->release ();
-               }
-       }
 }
 
 void
 DiskReader::ReaderChannelInfo::resize (samplecnt_t bufsize)
 {
        delete rbuf;
-       /* touch memory to lock it */
        rbuf = new PlaybackBuffer<Sample> (bufsize);
+       /* touch memory to lock it */
        memset (rbuf->buffer(), 0, sizeof (Sample) * rbuf->bufsize());
 }
 
@@ -163,6 +158,11 @@ DiskReader::set_state (const XMLNode& node, int version)
 void
 DiskReader::realtime_handle_transport_stopped ()
 {
+       /* can't do the resolve here because we don't have a place to put the
+        * note resolving data. Defer to
+        * MidiTrack::realtime_handle_transport_stopped() which will call
+        * ::resolve_tracker() and put the output in its _immediate_events store.
+        */
 }
 
 void
@@ -204,17 +204,11 @@ DiskReader::adjust_buffering ()
        }
 }
 
-void
-DiskReader::playlist_changed (const PropertyChange&)
-{
-       playlist_modified ();
-}
-
 void
 DiskReader::playlist_modified ()
 {
-       if (!i_am_the_modifier && !overwrite_queued) {
-               _session.request_overwrite_buffer (_route);
+       if (!overwrite_queued) {
+               _session.request_overwrite_buffer (_track);
                overwrite_queued = true;
        }
 }
@@ -237,8 +231,10 @@ DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
           take care of the buffer refill.
        */
 
+        cerr << "DR " << _track->name() << " using playlist, loading ? " << _session.loading() << endl;
+
         if (!overwrite_queued && (prior_playlist || _session.loading())) {
-               _session.request_overwrite_buffer (_route);
+               _session.request_overwrite_buffer (_track);
                overwrite_queued = true;
        }
 
@@ -253,7 +249,15 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
        boost::shared_ptr<ChannelList> c = channels.reader();
        ChannelList::iterator chan;
        sampleoffset_t disk_samples_to_consume;
-       MonitorState ms = _route->monitoring_state ();
+       MonitorState ms = _track->monitoring_state ();
+
+       if (run_must_resolve) {
+               boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (_track);
+               if (mt) {
+                       resolve_tracker (mt->immediate_events(), start_sample);
+               }
+               run_must_resolve = false;
+       }
 
        if (_active) {
                if (!_pending_active) {
@@ -268,7 +272,14 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
                }
        }
 
-       if ((speed == 0.0) && (ms == MonitoringDisk)) {
+       const bool declick_out = _session.declick_in_progress();
+       const gain_t target_gain = (declick_out || (speed == 0.0) || ((ms & MonitoringDisk) == 0)) ? 0.0 : 1.0;
+
+       if (!_session.cfg ()->get_use_transport_fades ()) {
+               _declick_amp.set_gain (target_gain);
+       }
+
+       if (declick_out && (ms == MonitoringDisk) && _declick_amp.gain () == target_gain) {
                /* no channels, or stopped. Don't accidentally pass any data
                 * from disk into our outputs (e.g. via interpolation)
                 */
@@ -276,12 +287,7 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
        }
 
        BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
-       const bool still_locating = _session.global_locate_pending();
-
-       if (c->empty()) {
-               /* do nothing with audio */
-               goto midi;
-       }
+       const bool still_locating = _session.global_locate_pending() || pending_overwrite ();
 
        assert (speed == -1 || speed == 0 || speed == 1);
 
@@ -291,6 +297,24 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
                disk_samples_to_consume = nframes;
        }
 
+       if (c->empty()) {
+               /* do nothing with audio */
+               goto midi;
+       }
+
+       if (_declick_amp.gain () != target_gain && target_gain == 0) {
+               /* fade-out */
+#if 0
+               printf ("DR fade-out speed=%.1f gain=%.3f off=%ld start=%ld playpos=%ld (%s)\n",
+                               speed, _declick_amp.gain (), _declick_offs, start_sample, playback_sample, owner()->name().c_str());
+#endif
+               ms = MonitorState (ms | MonitoringDisk);
+               assert (result_required);
+               result_required = true;
+       } else {
+               _declick_offs = 0;
+       }
+
        if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating || _no_disk_output) {
 
                /* no need for actual disk data, just advance read pointer and return */
@@ -324,41 +348,41 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
                for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
 
                        ChannelInfo* chaninfo (*chan);
-                       AudioBuffer& output (bufs.get_audio (n%n_buffers));
+                       AudioBuffer& output (bufs.get_audio (n % n_buffers));
 
                        AudioBuffer& disk_buf ((ms & MonitoringInput) ? scratch_bufs.get_audio(n) : output);
 
-                       if (start_sample != playback_sample) {
-                               cerr << owner()->name() << " playback @ " << start_sample << " not aligned with " << playback_sample << " jump " << (start_sample - playback_sample) << endl;
-
+                       if (start_sample != playback_sample && target_gain != 0) {
                                if (can_internal_playback_seek (start_sample - playback_sample)) {
                                        internal_playback_seek (start_sample - playback_sample);
                                } else {
-                                       cerr << owner()->name() << " playback not possible: ss = " << start_sample << " ps = " << playback_sample << endl;
-                                       abort (); // XXX -- now what?
-                                       goto midi;
+                                       disk_samples_to_consume = 0; /* will force an underrun below */
                                }
                        }
 
-                       if (speed != 0.0) {
+                       if (!declick_out) {
                                const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), disk_samples_to_consume);
                                if (disk_samples_to_consume > total) {
-                                       cerr << _name << " Need " << disk_samples_to_consume << " total = " << total << endl;
+                                       cerr << _name << " Need " << total << " have only " << disk_samples_to_consume << endl;
                                        cerr << "underrun for " << _name << endl;
                                        DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
                                                                                    DEBUG_THREAD_SELF, name(), total));
                                        Underrun ();
                                        return;
                                }
+                       } else if (_declick_amp.gain () != target_gain) {
+                               assert (target_gain == 0);
+                               const samplecnt_t total = chaninfo->rbuf->read (disk_buf.data(), nframes, false, _declick_offs);
+                               _declick_offs += total;
                        }
 
-                       if (scaling != 1.0f && speed != 0.0) {
-                               Amp::apply_simple_gain (disk_buf, disk_samples_to_consume, scaling);
-                       }
+                       _declick_amp.apply_gain (disk_buf, nframes, target_gain);
+
+                       Amp::apply_simple_gain (disk_buf, nframes, scaling);
 
                        if (ms & MonitoringInput) {
                                /* mix the disk signal into the input signal (already in bufs) */
-                               mix_buffers_no_gain (output.data(), disk_buf.data(), disk_samples_to_consume);
+                               mix_buffers_no_gain (output.data(), disk_buf.data(), nframes);
                        }
                }
        }
@@ -366,7 +390,7 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
        /* MIDI data handling */
 
   midi:
-       if (/*!_session.declick_out_pending() && */ bufs.count().n_midi() && _midi_buf) {
+       if (!declick_in_progress() && bufs.count().n_midi()) {
                MidiBuffer* dst;
 
                if (_no_disk_output) {
@@ -375,7 +399,7 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
                        dst = &bufs.get_midi (0);
                }
 
-               if ((ms & MonitoringDisk) && !still_locating) {
+               if ((ms & MonitoringDisk) && !still_locating && speed) {
                        get_midi_playback (*dst, start_sample, end_sample, ms, scratch_bufs, speed, disk_samples_to_consume);
                }
        }
@@ -390,6 +414,12 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
                        playback_sample += disk_samples_to_consume;
                }
 
+               Location* loc = _loop_location;
+               if (loc) {
+                       Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
+                       playback_sample = loop_range.squish (playback_sample);
+               }
+
                if (_playlists[DataType::AUDIO]) {
                        if (!c->empty()) {
                                if (_slaved) {
@@ -407,55 +437,9 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
                        }
                }
 
-               if (_playlists[DataType::MIDI]) {
-                       /* MIDI butler needed part */
-
-                       uint32_t samples_read = g_atomic_int_get(const_cast<gint*>(&_samples_read_from_ringbuffer));
-                       uint32_t samples_written = g_atomic_int_get(const_cast<gint*>(&_samples_written_to_ringbuffer));
-
-                       /*
-                         cerr << name() << " MDS written: " << samples_written << " - read: " << samples_read <<
-                         " = " << samples_written - samples_read
-                         << " + " << disk_samples_to_consume << " < " << midi_readahead << " = " << need_butler << ")" << endl;
-                       */
-
-                       /* samples_read will generally be less than samples_written, but
-                        * immediately after an overwrite, we can end up having read some data
-                        * before we've written any. we don't need to trip an assert() on this,
-                        * but we do need to check so that the decision on whether or not we
-                        * need the butler is done correctly.
-                        */
-
-                       /* furthermore..
-                        *
-                        * Doing heavy GUI operations[1] can stall also the butler.
-                        * The RT-thread meanwhile will happily continue and
-                        * ‘samples_read’ (from buffer to output) will become larger
-                        * than ‘samples_written’ (from disk to buffer).
-                        *
-                        * The disk-stream is now behind..
-                        *
-                        * In those cases the butler needs to be summed to refill the buffer (done now)
-                        * AND we need to skip (samples_read - samples_written). ie remove old events
-                        * before playback_sample from the rinbuffer.
-                        *
-                        * [1] one way to do so is described at #6170.
-                        * For me just popping up the context-menu on a MIDI-track header
-                        * of a track with a large (think beethoven :) midi-region also did the
-                        * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
-                        *
-                        * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
-                        * and can stall
-                        */
-                       if (samples_read <= samples_written) {
-                               if ((samples_written - samples_read) + disk_samples_to_consume < midi_readahead) {
-                                       butler_required = true;
-                               }
-                       } else {
-                               butler_required = true;
-                       }
-
-               }
+               /* All of MIDI is in RAM, no need to call the butler unless we
+                * have to overwrite buffers because of a playlist change.
+                */
 
                _need_butler = butler_required;
        }
@@ -463,31 +447,44 @@ DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_samp
        // DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
 }
 
+bool
+DiskReader::declick_in_progress () const
+{
+       return _declick_amp.gain() != 0; // declick-out
+}
+
+bool
+DiskReader::pending_overwrite () const {
+       return g_atomic_int_get (&_pending_overwrite) != 0;
+}
+
 void
 DiskReader::set_pending_overwrite ()
 {
        /* called from audio thread, so we can use the read ptr and playback sample as we wish */
 
-       assert (!_pending_overwrite);
-
-       _pending_overwrite = true;
+       assert (!pending_overwrite ());
        overwrite_sample = playback_sample;
 
        boost::shared_ptr<ChannelList> c = channels.reader ();
        for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
                (*chan)->rbuf->read_flush ();
        }
+
+       g_atomic_int_set (&_pending_overwrite, 1);
+       run_must_resolve = true;
 }
 
 bool
 DiskReader::overwrite_existing_buffers ()
 {
-       boost::shared_ptr<ChannelList> c = channels.reader();
-
+       /* called from butler thread */
+       assert (pending_overwrite ());
        overwrite_queued = false;
 
        DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2\n", overwrite_sample));
 
+       boost::shared_ptr<ChannelList> c = channels.reader();
        if (!c->empty ()) {
                /* AUDIO */
 
@@ -495,6 +492,7 @@ DiskReader::overwrite_existing_buffers ()
 
                /* assume all are the same size */
                samplecnt_t size = c->front()->rbuf->write_space ();
+               assert (size > 0);
 
                boost::scoped_array<Sample> sum_buffer (new Sample[size]);
                boost::scoped_array<Sample> mixdown_buffer (new Sample[size]);
@@ -512,8 +510,6 @@ DiskReader::overwrite_existing_buffers ()
                        samplepos_t start = overwrite_sample;
                        samplecnt_t to_read = size;
 
-                       cerr << owner()->name() << " over-read: " << to_read << endl;
-
                        if (audio_read ((*chan)->rbuf, sum_buffer.get(), mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
                                error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"), id(), size, overwrite_sample) << endmsg;
                                goto midi;
@@ -523,29 +519,18 @@ DiskReader::overwrite_existing_buffers ()
 
   midi:
 
-       if (_midi_buf && _playlists[DataType::MIDI]) {
-
-               /* Clear the playback buffer contents.  This is safe as long as the butler
-                  thread is suspended, which it should be.
-               */
-               _midi_buf->reset ();
-               _midi_buf->reset_tracker ();
-
-               g_atomic_int_set (&_samples_read_from_ringbuffer, 0);
-               g_atomic_int_set (&_samples_written_to_ringbuffer, 0);
+       RTMidiBuffer* mbuf = rt_midibuffer ();
 
-               /* Resolve all currently active notes in the playlist.  This is more
-                  aggressive than it needs to be: ideally we would only resolve what is
-                  absolutely necessary, but this seems difficult and/or impossible without
-                  having the old data or knowing what change caused the overwrite.
-               */
-               midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_sample);
-
-               midi_read (overwrite_sample, _chunk_samples, false);
-               file_sample[DataType::MIDI] = overwrite_sample; // overwrite_sample was adjusted by ::midi_read() to the new position
+       if (mbuf) {
+               PBD::Timing minsert;
+               minsert.start();
+               midi_playlist()->render (0);
+               minsert.update();
+               assert (midi_playlist()->rendered());
+               // cerr << "Reading " << name()  << " took " << minsert.elapsed() << " microseconds, final size = " << midi_playlist()->rendered()->size() << endl;
        }
 
-       _pending_overwrite = false;
+       g_atomic_int_set (&_pending_overwrite, 0);
 
        return true;
 }
@@ -553,30 +538,38 @@ DiskReader::overwrite_existing_buffers ()
 int
 DiskReader::seek (samplepos_t sample, bool complete_refill)
 {
+       /* called via non_realtime_locate() from butler thread */
+
        uint32_t n;
        int ret = -1;
        ChannelList::iterator chan;
        boost::shared_ptr<ChannelList> c = channels.reader();
 
-       //sample = std::max ((samplecnt_t)0, sample -_session.worst_output_latency ());
-
-       for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
-               (*chan)->rbuf->reset ();
+#ifndef NDEBUG
+       if (_declick_amp.gain() != 0) {
+               /* this should not happen. new transport should postponse seeking
+                * until de-click is complete */
+               printf ("LOCATE WITHOUT DECLICK (gain=%f) at %ld seek-to %ld\n", _declick_amp.gain (), playback_sample, sample);
+               //return -1;
        }
+       if (sample == playback_sample && !complete_refill) {
+               return 0; // XXX double-check this
+       }
+#endif
 
-       if (g_atomic_int_get (&_samples_read_from_ringbuffer) == 0) {
-               /* we haven't read anything since the last seek,
-                  so flush all note trackers to prevent
-                  wierdness
-               */
-               reset_tracker ();
+       g_atomic_int_set (&_pending_overwrite, 0);
+
+       DEBUG_TRACE (DEBUG::DiskIO, string_compose ("DiskReader::seek %s %ld -> %ld refill=%d\n", owner()->name().c_str(), playback_sample, sample, complete_refill));
+
+       const samplecnt_t distance = sample - playback_sample;
+       if (!complete_refill && can_internal_playback_seek (distance)) {
+               internal_playback_seek (distance);
+               return 0;
        }
 
-       if (_midi_buf) {
-               _midi_buf->reset();
+       for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
+               (*chan)->rbuf->reset ();
        }
-       g_atomic_int_set(&_samples_read_from_ringbuffer, 0);
-       g_atomic_int_set(&_samples_written_to_ringbuffer, 0);
 
        playback_sample = sample;
        file_sample[DataType::AUDIO] = sample;
@@ -594,7 +587,6 @@ DiskReader::seek (samplepos_t sample, bool complete_refill)
                ret = do_refill_with_alloc (true);
        }
 
-
        return ret;
 }
 
@@ -612,16 +604,9 @@ DiskReader::can_internal_playback_seek (sampleoffset_t distance)
                }
        }
 
-       if (distance < 0) {
-               return true; // XXX TODO un-seek MIDI
-       }
-
-       /* 2. MIDI */
-
-       uint32_t samples_read    = g_atomic_int_get(&_samples_read_from_ringbuffer);
-       uint32_t samples_written = g_atomic_int_get(&_samples_written_to_ringbuffer);
+       /* 2. MIDI can always seek any distance */
 
-       return ((samples_written - samples_read) < distance);
+       return true;
 }
 
 void
@@ -637,7 +622,7 @@ DiskReader::internal_playback_seek (sampleoffset_t distance)
        boost::shared_ptr<ChannelList> c = channels.reader();
        for (chan = c->begin(); chan != c->end(); ++chan) {
                if (distance < 0) {
-                       off = 0 - (sampleoffset_t) (*chan)->rbuf->decrement_read_ptr (llabs (distance));
+                       off = 0 - (sampleoffset_t) (*chan)->rbuf->decrement_read_ptr (::llabs (distance));
                } else {
                        off = (*chan)->rbuf->increment_read_ptr (distance);
                }
@@ -997,7 +982,7 @@ DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const
                return;
        }
 
-       if (!_route || Config->get_automation_follows_regions () == false) {
+       if (!_track || Config->get_automation_follows_regions () == false) {
                return;
        }
 
@@ -1011,7 +996,7 @@ DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const
        }
 
        /* move panner automation */
-       boost::shared_ptr<Pannable> pannable = _route->pannable();
+       boost::shared_ptr<Pannable> pannable = _track->pannable();
         Evoral::ControlSet::Controls& c (pannable->controls());
 
         for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
@@ -1031,7 +1016,7 @@ DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const
                 }
         }
        /* move processor automation */
-        _route->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_samples));
+        _track->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_samples));
 }
 
 void
@@ -1069,29 +1054,13 @@ DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evora
 void
 DiskReader::reset_tracker ()
 {
-       if (_midi_buf) {
-               _midi_buf->reset_tracker ();
-       }
-
-       boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
-
-       if (mp) {
-               mp->reset_note_trackers ();
-       }
+       _tracker.reset ();
 }
 
 void
 DiskReader::resolve_tracker (Evoral::EventSink<samplepos_t>& buffer, samplepos_t time)
 {
-       if (_midi_buf) {
-               _midi_buf->resolve_tracker(buffer, time);
-       }
-
-       boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
-
-       if (mp) {
-               mp->reset_note_trackers ();
-       }
+       _tracker.resolve_notes (buffer, time);
 }
 
 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
@@ -1101,9 +1070,14 @@ void
 DiskReader::get_midi_playback (MidiBuffer& dst, samplepos_t start_sample, samplepos_t end_sample, MonitorState ms, BufferSet& scratch_bufs, double speed, samplecnt_t disk_samples_to_consume)
 {
        MidiBuffer* target;
-       samplepos_t nframes = llabs (end_sample - start_sample);
+       samplepos_t nframes = ::llabs (end_sample - start_sample);
 
-       assert (_midi_buf);
+       RTMidiBuffer* rtmb = rt_midibuffer();
+
+       if (!rtmb || (rtmb->size() == 0)) {
+               /* no data to read, so do nothing */
+               return;
+       }
 
        if ((ms & MonitoringInput) == 0) {
                /* Route::process_output_buffers() clears the buffer as-needed */
@@ -1112,21 +1086,13 @@ DiskReader::get_midi_playback (MidiBuffer& dst, samplepos_t start_sample, sample
                target = &scratch_bufs.get_midi (0);
        }
 
-       if (ms & MonitoringDisk) {
-               /* disk data needed */
-
-               Location* loc = _loop_location;
+       size_t events_read = 0;
 
-               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
-                                    "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
-                                    _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), start_sample, end_sample,
-                                    (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
+       if (!pending_overwrite() && (ms & MonitoringDisk)) {
 
-               //cerr << "======== PRE ========\n";
-               //_midi_buf->dump (cerr);
-               //cerr << "----------------\n";
+               /* disk data needed */
 
-               size_t events_read = 0;
+               Location* loc = _loop_location;
 
                if (loc) {
                        samplepos_t effective_start;
@@ -1134,14 +1100,14 @@ DiskReader::get_midi_playback (MidiBuffer& dst, samplepos_t start_sample, sample
                        Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
                        effective_start = loop_range.squish (start_sample);
 
-                       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
+                       DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
 
                        if (effective_start == loc->start()) {
                                /* We need to turn off notes that may extend
                                   beyond the loop end.
                                */
 
-                               _midi_buf->resolve_tracker (*target, 0);
+                               _tracker.resolve_notes (*target, 0);
                        }
 
                        /* for split-cycles we need to offset the events */
@@ -1158,45 +1124,36 @@ DiskReader::get_midi_playback (MidiBuffer& dst, samplepos_t start_sample, sample
                                first = loc->end() - effective_start;
                                second = nframes - first;
 
-                               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
+                               DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
                                                                                      effective_start, loc->end(), first, second));
 
                                if (first) {
-                                       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
+                                       DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("loop read #1, from %1 for %2\n",
                                                                                              effective_start, first));
-                                       events_read = _midi_buf->read (*target, effective_start, first);
+                                       events_read = rtmb->read (*target, effective_start, effective_start + first, _tracker);
                                }
 
                                if (second) {
-                                       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
+                                       DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("loop read #2, from %1 for %2\n",
                                                                                              loc->start(), second));
-                                       events_read += _midi_buf->read (*target, loc->start(), second);
+                                       events_read += rtmb->read (*target, loc->start(), loc->start() + second, _tracker);
                                }
 
                        } else {
-                               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
-                                                                                     effective_start, nframes));
-                               events_read = _midi_buf->read (*target, effective_start, effective_start + nframes);
+                               DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
+                                                                               effective_start, nframes));
+                               events_read = rtmb->read (*target, effective_start, effective_start + nframes, _tracker);
                        }
                } else {
-                       const size_t n_skipped = _midi_buf->skip_to (start_sample);
-                       if (n_skipped > 0) {
-                               warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
-                       }
-                       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", start_sample, end_sample, nframes));
-                       events_read = _midi_buf->read (*target, start_sample, end_sample, Port::port_offset ());
+                       DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("playback buffer read, from %1 to %2 (%3)", start_sample, end_sample, nframes));
+                       events_read = rtmb->read (*target, start_sample, end_sample, _tracker, Port::port_offset ());
                }
 
-               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
-                                    "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
-                                    _name, events_read, playback_sample, playback_sample + nframes,
-                                    _midi_buf->read_space(), _midi_buf->write_space(),
-                                    _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
+               DEBUG_TRACE (DEBUG::MidiDiskIO, string_compose ("%1 MDS events read %2 range %3 .. %4\n", _name, events_read, playback_sample, playback_sample + nframes));
        }
 
-       g_atomic_int_add (&_samples_read_from_ringbuffer, nframes);
 
-       if (ms & MonitoringInput) {
+       if (!pending_overwrite() && !_no_disk_output && (ms & MonitoringInput)) {
                dst.merge_from (*target, nframes);
        }
 
@@ -1214,176 +1171,39 @@ DiskReader::get_midi_playback (MidiBuffer& dst, samplepos_t start_sample, sample
                cerr << "----------------\n";
        }
 #endif
-#if 0
-       cerr << "======== MIDI Disk Buffer ========\n";
-       _midi_buf->dump (cerr);
-       cerr << "----------------\n";
-#endif
-}
-
-/** @a start is set to the new sample position (TIME) read up to */
-int
-DiskReader::midi_read (samplepos_t& start, samplecnt_t dur, bool reversed)
-{
-       samplecnt_t this_read   = 0;
-       samplepos_t loop_end    = 0;
-       samplepos_t loop_start  = 0;
-       samplecnt_t loop_length = 0;
-       Location*  loc         = _loop_location;
-       samplepos_t effective_start = start;
-       Evoral::Range<samplepos_t>*  loop_range (0);
-
-       assert(_midi_buf);
-
-       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS::midi_read @ %1 cnt %2\n", start, dur));
-
-       boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_route);
-       MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
-       sampleoffset_t loop_offset = 0;
-
-       if (!reversed && loc) {
-               get_location_times (loc, &loop_start, &loop_end, &loop_length);
-       }
-
-       while (dur) {
-
-               /* take any loop into account. we can't read past the end of the loop. */
-
-               if (loc && !reversed) {
-
-                       if (!loop_range) {
-                               loop_range = new Evoral::Range<samplepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
-                       }
-
-                       /* if we are (seamlessly) looping, ensure that the first sample we read is at the correct
-                          position within the loop.
-                       */
-
-                       effective_start = loop_range->squish (effective_start);
-
-                       if ((loop_end - effective_start) <= dur) {
-                               /* too close to end of loop to read "dur", so
-                                  shorten it.
-                               */
-                               this_read = loop_end - effective_start;
-                       } else {
-                               this_read = dur;
-                       }
-
-               } else {
-                       this_read = dur;
-               }
-
-               if (this_read == 0) {
-                       break;
-               }
-
-               this_read = min (dur,this_read);
-
-               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
-
-               if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
-                       error << string_compose(
-                                       _("MidiDiskstream %1: cannot read %2 from playlist at sample %3"),
-                                       id(), this_read, start) << endmsg;
-                       return -1;
-               }
-
-               g_atomic_int_add (&_samples_written_to_ringbuffer, this_read);
-
-               if (reversed) {
-
-                       // Swap note ons with note offs here.  etc?
-                       // Fully reversing MIDI requires look-ahead (well, behind) to find previous
-                       // CC values etc.  hard.
-
-               } else {
-
-                       /* adjust passed-by-reference argument (note: this is
-                          monotonic and does not reflect looping.
-                       */
-                       start += this_read;
-
-                       /* similarly adjust effective_start, but this may be
-                          readjusted for seamless looping as we continue around
-                          the loop.
-                       */
-                       effective_start += this_read;
-               }
-
-               dur -= this_read;
-       }
-
-       return 0;
 }
 
 int
 DiskReader::refill_midi ()
 {
-       if (!_playlists[DataType::MIDI] || !_midi_buf) {
-               return 0;
-       }
-
-       const size_t  write_space = _midi_buf->write_space();
-       const bool reversed    = _session.transport_speed() < 0.0f;
-
-       DEBUG_TRACE (DEBUG::DiskIO, string_compose ("MIDI refill, write space = %1 file sample = %2\n", write_space, file_sample[DataType::MIDI]));
-
-       /* no space to write */
-       if (write_space == 0) {
-               return 0;
-       }
-
-       if (reversed) {
-               return 0;
-       }
-
-       /* at end: nothing to do */
-
-       samplepos_t ffm = file_sample[DataType::MIDI];
-
-       if (ffm == max_samplepos) {
-               return 0;
-       }
-
-       int ret = 0;
-       const uint32_t samples_read = g_atomic_int_get (&_samples_read_from_ringbuffer);
-       const uint32_t samples_written = g_atomic_int_get (&_samples_written_to_ringbuffer);
-
-       if ((samples_read < samples_written) && (samples_written - samples_read) >= midi_readahead) {
-               return 0;
-       }
-
-       samplecnt_t to_read = midi_readahead - ((samplecnt_t)samples_written - (samplecnt_t)samples_read);
-
-       to_read = min (to_read, (samplecnt_t) (max_samplepos - ffm));
-       to_read = min (to_read, (samplecnt_t) write_space);
-
-       if (midi_read (ffm, to_read, reversed)) {
-               ret = -1;
-       }
-
-       file_sample[DataType::MIDI] = ffm;
-
-       return ret;
+       /* nothing to do ... it's all in RAM thanks to overwrite */
+       return 0;
 }
 
 void
-DiskReader::set_no_disk_output (bool yn)
+DiskReader::dec_no_disk_output ()
 {
-       /* this MUST be called as part of the process call tree, before any
-          disk readers are invoked. We use it when the session needs the
-          transport (and thus effective read position for DiskReaders) to keep
-          advancing as part of syncing up with a transport master, but we
-          don't want any actual disk output yet because we are still not
-          synced.
+       /* this is called unconditionally when things happen that ought to end
+          a period of "no disk output". It's OK for that to happen when there
+          was no corresponding call to ::inc_no_disk_output(), but we must
+          stop the value from becoming negative.
        */
-       _no_disk_output = yn;
+
+       do {
+               gint v  = g_atomic_int_get (&_no_disk_output);
+               if (v > 0) {
+                       if (g_atomic_int_compare_and_exchange (&_no_disk_output, v, v - 1)) {
+                               break;
+                       }
+               } else {
+                       break;
+               }
+       } while (true);
 }
 
 DiskReader::DeclickAmp::DeclickAmp (samplecnt_t sample_rate)
 {
-       _a = 2200.f / (gain_t)sample_rate;
+       _a = 4550.f / (gain_t)sample_rate;
        _l = -log1p (_a);
        _g = 0;
 }
@@ -1404,21 +1224,21 @@ DiskReader::DeclickAmp::apply_gain (AudioBuffer& buf, samplecnt_t n_samples, con
        const float a = _a;
        Sample* const buffer = buf.data ();
 
-#define MAX_NPROC 16
+       const int max_nproc = 16;
        uint32_t remain = n_samples;
        uint32_t offset = 0;
        while (remain > 0) {
-               uint32_t n_proc = remain > MAX_NPROC ? MAX_NPROC : remain;
+               uint32_t n_proc = remain > max_nproc ? max_nproc : remain;
                for (uint32_t i = 0; i < n_proc; ++i) {
                        buffer[offset + i] *= g;
                }
 #if 1
                g += a * (target - g);
 #else /* accurate exponential fade */
-               if (n_proc == MAX_NPROC) {
+               if (n_proc == max_nproc) {
                        g += a * (target - g);
                } else {
-                       g = target - (target - g) * expf (_l * n_proc / MAX_NPROC);
+                       g = target - (target - g) * expf (_l * n_proc / max_nproc);
                }
 #endif
                remain -= n_proc;
@@ -1431,3 +1251,22 @@ DiskReader::DeclickAmp::apply_gain (AudioBuffer& buf, samplecnt_t n_samples, con
                _g = g;
        }
 }
+
+RTMidiBuffer*
+DiskReader::rt_midibuffer ()
+{
+       boost::shared_ptr<Playlist> pl = _playlists[DataType::MIDI];
+
+       if (!pl) {
+               return 0;
+       }
+
+       boost::shared_ptr<MidiPlaylist> mpl = boost::dynamic_pointer_cast<MidiPlaylist> (pl);
+
+       if (!mpl) {
+               /* error, but whatever ... */
+               return 0;
+       }
+
+       return mpl->rendered();
+}