debug instrumentation for locate time
[ardour.git] / libs / ardour / disk_reader.cc
index 10cf428c822c202b821abfc36ca8ae10b1477c42..918761e5371cb6812a3456d256bca5d838f7fc88 100644 (file)
@@ -17,6 +17,7 @@
 
 */
 
+#include "pbd/enumwriter.h"
 #include "pbd/i18n.h"
 #include "pbd/memento_command.h"
 
@@ -28,6 +29,7 @@
 #include "ardour/disk_reader.h"
 #include "ardour/midi_ring_buffer.h"
 #include "ardour/midi_playlist.h"
+#include "ardour/pannable.h"
 #include "ardour/playlist.h"
 #include "ardour/playlist_factory.h"
 #include "ardour/session.h"
@@ -38,29 +40,25 @@ using namespace PBD;
 using namespace std;
 
 ARDOUR::framecnt_t DiskReader::_chunk_frames = default_chunk_frames ();
+PBD::Signal0<void> DiskReader::Underrun;
+Sample* DiskReader::_mixdown_buffer = 0;
+gain_t* DiskReader::_gain_buffer = 0;
+framecnt_t DiskReader::midi_readahead = 4096;
 
 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
        : DiskIOProcessor (s, str, f)
        , _roll_delay (0)
-       , loop_location (0)
        , overwrite_frame (0)
         , overwrite_offset (0)
         , _pending_overwrite (false)
         , overwrite_queued (false)
-        , file_frame (0)
-        , playback_sample (0)
-       , _monitoring_choice (MonitorDisk)
-       , _need_butler (false)
        , _gui_feed_buffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
-       , _frames_written_to_ringbuffer (0)
-       , _frames_read_from_ringbuffer (0)
 {
 }
 
 DiskReader::~DiskReader ()
 {
-       DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 deleted\n", _name));
-       Glib::Threads::Mutex::Lock lm (state_lock);
+       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]) {
@@ -114,13 +112,11 @@ DiskReader::default_chunk_frames()
 bool
 DiskReader::set_name (string const & str)
 {
-       if (_name != str) {
-               for (uint32_t n = 0; n < DataType::num_types; ++n) {
-                       if (_playlists[n]) {
-                               _playlists[n]->set_name (str);
-                       }
-               }
-               SessionObject::set_name(str);
+       string my_name = X_("playback:");
+       my_name += str;
+
+       if (_name != my_name) {
+               SessionObject::set_name (my_name);
        }
 
        return true;
@@ -132,82 +128,28 @@ DiskReader::set_roll_delay (ARDOUR::framecnt_t nframes)
        _roll_delay = nframes;
 }
 
+XMLNode&
+DiskReader::state (bool full)
+{
+       XMLNode& node (DiskIOProcessor::state (full));
+       node.set_property(X_("type"), X_("diskreader"));
+       return node;
+}
+
 int
 DiskReader::set_state (const XMLNode& node, int version)
 {
-       XMLProperty const * prop;
-
        if (DiskIOProcessor::set_state (node, version)) {
                return -1;
        }
 
-       if ((prop = node.property ("audio-playlist")) == 0) {
-               return -1;
-       }
-
-       if (find_and_use_playlist (DataType::AUDIO, prop->value())) {
-               return -1;
-       }
-
-       if ((prop = node.property ("midi-playlist")) == 0) {
-               return -1;
-       }
-
-       if (find_and_use_playlist (DataType::MIDI, prop->value())) {
-               return -1;
-       }
-
        return 0;
 }
 
-/* Processor interface */
-
-bool
-DiskReader::configure_io (ChanCount in, ChanCount out)
-{
-       Glib::Threads::Mutex::Lock lm (state_lock);
-
-       RCUWriter<ChannelList> writer (channels);
-       boost::shared_ptr<ChannelList> c = writer.get_copy();
-
-       uint32_t n_audio = in.n_audio();
-
-       if (n_audio > c->size()) {
-               add_channel_to (c, n_audio - c->size());
-       } else if (n_audio < c->size()) {
-               remove_channel_from (c, c->size() - n_audio);
-       }
-
-       if (in.n_midi() > 0 && !_midi_buf) {
-               const size_t size = _session.butler()->midi_diskstream_buffer_size();
-               _midi_buf = new MidiRingBuffer<framepos_t>(size);
-               midi_interpolation.add_channel_to (0,0);
-       }
-
-       Processor::configure_io (in, out);
-
-       return true;
-}
-
-bool
-DiskReader::can_support_io_configuration (const ChanCount& in, ChanCount& out)
-{
-       if (in.n_midi() != 0 && in.n_midi() != 1) {
-               /* we only support zero or 1 MIDI stream */
-               return false;
-       }
-
-       if (in != out) {
-               /* currently no way to deliver different channels that we receive */
-               return false;
-       }
-
-       return true;
-}
-
 void
 DiskReader::realtime_handle_transport_stopped ()
 {
+       realtime_speed_change ();
 }
 
 void
@@ -215,22 +157,6 @@ DiskReader::realtime_locate ()
 {
 }
 
-int
-DiskReader::set_loop (Location *location)
-{
-       if (location) {
-               if (location->start() >= location->end()) {
-                       error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
-                       return -1;
-               }
-       }
-
-       loop_location = location;
-
-       LoopSet (location); /* EMIT SIGNAL */
-       return 0;
-}
-
 float
 DiskReader::buffer_load () const
 {
@@ -265,87 +191,6 @@ DiskReader::adjust_buffering ()
        }
 }
 
-DiskReader::ChannelInfo::ChannelInfo (framecnt_t bufsize, framecnt_t speed_size, framecnt_t wrap_size)
-{
-       current_buffer = 0;
-
-       speed_buffer = new Sample[speed_size];
-       wrap_buffer = new Sample[wrap_size];
-
-       buf = new RingBufferNPT<Sample> (bufsize);
-
-       /* touch the ringbuffer buffer, which will cause
-          them to be mapped into locked physical RAM if
-          we're running with mlockall(). this doesn't do
-          much if we're not.
-       */
-
-       memset (buf->buffer(), 0, sizeof (Sample) * buf->bufsize());
-}
-
-void
-DiskReader::ChannelInfo::resize (framecnt_t bufsize)
-{
-       delete buf;
-       buf = new RingBufferNPT<Sample> (bufsize);
-       memset (buf->buffer(), 0, sizeof (Sample) * buf->bufsize());
-}
-
-DiskReader::ChannelInfo::~ChannelInfo ()
-{
-       delete [] speed_buffer;
-       speed_buffer = 0;
-
-       delete [] wrap_buffer;
-       wrap_buffer = 0;
-
-       delete buf;
-       buf = 0;
-}
-
-int
-DiskReader::set_block_size (pframes_t /*nframes*/)
-{
-       if (_session.get_block_size() > speed_buffer_size) {
-               speed_buffer_size = _session.get_block_size();
-               boost::shared_ptr<ChannelList> c = channels.reader();
-
-               for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
-                       delete [] (*chan)->speed_buffer;
-                       (*chan)->speed_buffer = new Sample[speed_buffer_size];
-               }
-       }
-       allocate_temporary_buffers ();
-       return 0;
-}
-
-void
-DiskReader::allocate_temporary_buffers ()
-{
-       /* make sure the wrap buffer is at least large enough to deal
-          with the speeds up to 1.2, to allow for micro-variation
-          when slaving to MTC, Timecode etc.
-       */
-
-       double const sp = max (fabs (_actual_speed), 1.2);
-       framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
-
-       if (required_wrap_size > wrap_buffer_size) {
-
-               boost::shared_ptr<ChannelList> c = channels.reader();
-
-               for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
-                       if ((*chan)->wrap_buffer) {
-                               delete [] (*chan)->wrap_buffer;
-                       }
-                       (*chan)->wrap_buffer = new Sample[required_wrap_size];
-               }
-
-               wrap_buffer_size = required_wrap_size;
-       }
-}
-
-
 void
 DiskReader::playlist_changed (const PropertyChange&)
 {
@@ -356,75 +201,22 @@ void
 DiskReader::playlist_modified ()
 {
        if (!i_am_the_modifier && !overwrite_queued) {
-               // !!!! _session.request_overwrite_buffer (this);
+               _session.request_overwrite_buffer (_route);
                overwrite_queued = true;
        }
 }
 
-void
-DiskReader::playlist_deleted (boost::weak_ptr<Playlist> wpl)
-{
-       boost::shared_ptr<Playlist> pl (wpl.lock());
-
-       if (!pl) {
-               return;
-       }
-
-       for (uint32_t n = 0; n < DataType::num_types; ++n) {
-               if (pl == _playlists[n]) {
-
-                       /* this catches an ordering issue with session destruction. playlists
-                          are destroyed before disk readers. we have to invalidate any handles
-                          we have to the playlist.
-                       */
-                       _playlists[n].reset ();
-                       break;
-               }
-       }
-}
-
-boost::shared_ptr<AudioPlaylist>
-DiskReader::audio_playlist () const
-{
-       return boost::dynamic_pointer_cast<AudioPlaylist> (_playlists[DataType::AUDIO]);
-}
-
-boost::shared_ptr<MidiPlaylist>
-DiskReader::midi_playlist () const
-{
-       return boost::dynamic_pointer_cast<MidiPlaylist> (_playlists[DataType::MIDI]);
-}
-
 int
 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
 {
-        if (!playlist) {
-                return 0;
-        }
-
         bool prior_playlist = false;
 
-       {
-               Glib::Threads::Mutex::Lock lm (state_lock);
-
-               if (playlist == _playlists[dt]) {
-                       return 0;
-               }
-
-               playlist_connections.drop_connections ();
-
-               if (_playlists[dt]) {
-                       _playlists[dt]->release();
-                        prior_playlist = true;
-               }
-
-               _playlists[dt] = playlist;
-               playlist->use();
+        if (_playlists[dt]) {
+               prior_playlist = true;
+        }
 
-               playlist->ContentsChanged.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_modified, this));
-               playlist->LayeringChanged.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_modified, this));
-               playlist->DropReferences.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_deleted, this, boost::weak_ptr<Playlist>(playlist)));
-               playlist->RangesMoved.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_ranges_moved, this, _1, _2));
+        if (DiskIOProcessor::use_playlist (dt, playlist)) {
+               return -1;
        }
 
        /* don't do this if we've already asked for it *or* if we are setting up
@@ -432,88 +224,14 @@ DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
           take care of the buffer refill.
        */
 
-       if (!overwrite_queued && prior_playlist) {
-               // !!! _session.request_overwrite_buffer (this);
+        if (!overwrite_queued && (prior_playlist || _session.loading())) {
+               _session.request_overwrite_buffer (_route);
                overwrite_queued = true;
        }
 
-       PlaylistChanged (dt); /* EMIT SIGNAL */
-       _session.set_dirty ();
-
        return 0;
 }
 
-int
-DiskReader::find_and_use_playlist (DataType dt, const string& name)
-{
-       boost::shared_ptr<Playlist> playlist;
-
-       if ((playlist = _session.playlists->by_name (name)) == 0) {
-               playlist = PlaylistFactory::create (dt, _session, name);
-       }
-
-       if (!playlist) {
-               error << string_compose(_("DiskReader: \"%1\" isn't an playlist"), name) << endmsg;
-               return -1;
-       }
-
-       return use_playlist (dt, playlist);
-}
-
-int
-DiskReader::use_new_playlist (DataType dt)
-{
-       string newname;
-       boost::shared_ptr<Playlist> playlist = _playlists[dt];
-
-       if (playlist) {
-               newname = Playlist::bump_name (playlist->name(), _session);
-       } else {
-               newname = Playlist::bump_name (_name, _session);
-       }
-
-       playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (dt, _session, newname, hidden()));
-
-       if (!playlist) {
-               return -1;
-       }
-
-       return use_playlist (dt, playlist);
-}
-
-int
-DiskReader::use_copy_playlist (DataType dt)
-{
-       assert (_playlists[dt]);
-
-       if (_playlists[dt] == 0) {
-               error << string_compose(_("DiskReader %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
-               return -1;
-       }
-
-       string newname;
-       boost::shared_ptr<Playlist> playlist;
-
-       newname = Playlist::bump_name (_playlists[dt]->name(), _session);
-
-       if ((playlist = PlaylistFactory::create (_playlists[dt], newname)) == 0) {
-               return -1;
-       }
-
-       playlist->reset_shares();
-
-       return use_playlist (dt, playlist);
-}
-
-
-/** Do some record stuff [not described in this comment!]
- *
- *  Also:
- *    - Setup playback_distance with the nframes, or nframes adjusted
- *      for current varispeed, if appropriate.
- *    - Setup current_buffer in each ChannelInfo to point to data
- *      that someone can read playback_distance worth of data from.
- */
 void
 DiskReader::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
                  double speed, pframes_t nframes, bool result_required)
@@ -521,277 +239,240 @@ DiskReader::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
        uint32_t n;
        boost::shared_ptr<ChannelList> c = channels.reader();
        ChannelList::iterator chan;
-       framecnt_t playback_distance = 0;
-
-       Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
-
-       if (!sm.locked()) {
-               return;
-       }
-
-       for (chan = c->begin(); chan != c->end(); ++chan) {
-               (*chan)->current_buffer = 0;
-       }
-
-       const bool need_disk_signal = result_required || _monitoring_choice == MonitorDisk || _monitoring_choice == MonitorCue;
-
-       if (need_disk_signal) {
+       frameoffset_t playback_distance;
+       MonitorState ms = _route->monitoring_state ();
 
-               /* we're doing playback */
-
-               framecnt_t necessary_samples;
-
-               if (_actual_speed != 1.0) {
-                       necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
-               } else {
-                       necessary_samples = nframes;
+       if (_active) {
+               if (!_pending_active) {
+                       _active = false;
+                       return;
                }
-
-               for (chan = c->begin(); chan != c->end(); ++chan) {
-                       (*chan)->buf->get_read_vector (&(*chan)->read_vector);
+       } else {
+               if (_pending_active) {
+                       _active = true;
+               } else {
+                       return;
                }
+       }
 
-               n = 0;
-
-               /* Setup current_buffer in each ChannelInfo to point to data that someone
-                  can read necessary_samples (== nframes at a transport speed of 1) worth of data
-                  from right now.
-               */
-
-               for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
-
-                       ChannelInfo* chaninfo (*chan);
-
-                       if (necessary_samples <= (framecnt_t) chaninfo->read_vector.len[0]) {
-                               /* There are enough samples in the first part of the ringbuffer */
-                               chaninfo->current_buffer = chaninfo->read_vector.buf[0];
-
-                       } else {
-                               framecnt_t total = chaninfo->read_vector.len[0] + chaninfo->read_vector.len[1];
-
-                               if (necessary_samples > total) {
-                                       cerr << _name << " Need " << necessary_samples << " total = " << total << 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;
+       _need_butler = false;
 
-                               } else {
+       if (speed == 0.0 && (ms == MonitoringDisk)) {
+               /* stopped. Don't accidentally pass any data from disk
+                * into our outputs (e.g. via interpolation)
+                */
+               bufs.silence (nframes, 0);
+               return;
+       }
 
-                                       /* We have enough samples, but not in one lump.  Coalesce the two parts
-                                          into one in wrap_buffer in our ChannelInfo, and specify that
-                                          as our current_buffer.
-                                       */
+       if (speed != 1.0f && speed != -1.0f) {
+               interpolation.set_speed (speed);
+               midi_interpolation.set_speed (speed);
+               playback_distance = midi_interpolation.distance (nframes);
+               if (speed < 0.0) {
+                       playback_distance = -playback_distance;
+               }
+       } else {
+               playback_distance = nframes;
+       }
 
-                                       assert(wrap_buffer_size >= necessary_samples);
+       BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
+       const bool still_locating = _session.global_locate_pending();
 
-                                       /* Copy buf[0] from buf */
-                                       memcpy ((char *) chaninfo->wrap_buffer,
-                                                       chaninfo->read_vector.buf[0],
-                                                       chaninfo->read_vector.len[0] * sizeof (Sample));
+       if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating) {
 
-                                       /* Copy buf[1] from buf */
-                                       memcpy (chaninfo->wrap_buffer + chaninfo->read_vector.len[0],
-                                                       chaninfo->read_vector.buf[1],
-                                                       (necessary_samples - chaninfo->read_vector.len[0])
-                                                                       * sizeof (Sample));
+               /* no need for actual disk data, just advance read pointer and return */
 
-                                       chaninfo->current_buffer = chaninfo->wrap_buffer;
-                               }
+               if (!still_locating) {
+                       for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
+                               (*chan)->buf->increment_read_ptr (playback_distance);
                        }
                }
 
-               if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
-
-                       interpolation.set_speed (_target_speed);
-
-                       int channel = 0;
-                       for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
-                               ChannelInfo* chaninfo (*chan);
-
-                               playback_distance = interpolation.interpolate (
-                                       channel, nframes, chaninfo->current_buffer, chaninfo->speed_buffer);
+               /* if monitoring disk but locating, put silence in the buffers */
 
-                               chaninfo->current_buffer = chaninfo->speed_buffer;
-                       }
-
-               } else {
-                       playback_distance = nframes;
+               if (still_locating && (ms == MonitoringDisk)) {
+                       bufs.silence (playback_distance, 0);
                }
 
-               _speed = _target_speed;
-       }
-
-       if (need_disk_signal) {
+       } else {
 
-               /* copy data over to buffer set */
+               /* we need audio data from disk */
 
                size_t n_buffers = bufs.count().n_audio();
                size_t n_chans = c->size();
-               gain_t scaling = 1.0f;
+               gain_t scaling;
 
                if (n_chans > n_buffers) {
                        scaling = ((float) n_buffers)/n_chans;
+               } else {
+                       scaling = 1.0;
                }
 
                for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
 
-                       AudioBuffer& buf (bufs.get_audio (n%n_buffers));
                        ChannelInfo* chaninfo (*chan);
+                       AudioBuffer& output (bufs.get_audio (n%n_buffers));
+                       Sample* disk_signal = 0; /* assignment not really needed but it keeps the compiler quiet and helps track bugs */
 
-                       if (n < n_chans) {
-                               if (scaling != 1.0f) {
-                                       buf.read_from_with_gain (chaninfo->current_buffer, nframes, scaling);
-                               } else {
-                                       buf.read_from (chaninfo->current_buffer, nframes);
-                               }
+                       if (ms & MonitoringInput) {
+                               /* put disk stream in scratch buffer, blend at end */
+                               disk_signal = scratch_bufs.get_audio(n).data ();
                        } else {
-                               if (scaling != 1.0f) {
-                                       buf.accumulate_with_gain_from (chaninfo->current_buffer, nframes, scaling);
-                               } else {
-                                       buf.accumulate_from (chaninfo->current_buffer, nframes);
-                               }
+                               /* no input stream needed, just overwrite buffers */
+                               disk_signal = output.data ();
                        }
-               }
-
-               /* extra buffers will already be silent, so leave them alone */
-       }
-
-       _need_butler = false;
 
-       if (_actual_speed < 0.0) {
-               playback_sample -= playback_distance;
-       } else {
-               playback_sample += playback_distance;
-       }
-
-       for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
-               (*chan)->buf->increment_read_ptr (playback_distance);
-       }
-
-       if (!c->empty()) {
-               if (_slaved) {
-                       if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
-                               _need_butler = true;
-                       }
-               } else {
-                       if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
-                               _need_butler = true;
-                       }
-               }
-       }
+                       chaninfo->buf->get_read_vector (&(*chan)->rw_vector);
 
-       /* MIDI data handling */
+                       if (playback_distance <= (framecnt_t) chaninfo->rw_vector.len[0]) {
 
-       if (_actual_speed != 1.0f && _target_speed > 0) {
+                               if (fabsf (speed) != 1.0f) {
+                                       (void) interpolation.interpolate (
+                                               n, nframes,
+                                               chaninfo->rw_vector.buf[0],
+                                               disk_signal);
+                               } else if (speed != 0.0) {
+                                       memcpy (disk_signal, chaninfo->rw_vector.buf[0], sizeof (Sample) * playback_distance);
+                               }
 
-               interpolation.set_speed (_target_speed);
+                       } else {
 
-               playback_distance = midi_interpolation.distance  (nframes);
+                               const framecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
+
+                               if (playback_distance <= total) {
+
+                                       /* We have enough samples, but not in one lump.
+                                        */
+
+                                       if (fabsf (speed) != 1.0f) {
+                                               interpolation.interpolate (n, chaninfo->rw_vector.len[0],
+                                                                          chaninfo->rw_vector.buf[0],
+                                                                          disk_signal);
+                                               disk_signal += chaninfo->rw_vector.len[0];
+                                               interpolation.interpolate (n, playback_distance - chaninfo->rw_vector.len[0],
+                                                                          chaninfo->rw_vector.buf[1],
+                                                                          disk_signal);
+                                       } else if (speed != 0.0) {
+                                               memcpy (disk_signal,
+                                                       chaninfo->rw_vector.buf[0],
+                                                       chaninfo->rw_vector.len[0] * sizeof (Sample));
+                                               memcpy (disk_signal + chaninfo->rw_vector.len[0],
+                                                       chaninfo->rw_vector.buf[1],
+                                                       (playback_distance - chaninfo->rw_vector.len[0]) * sizeof (Sample));
+                                       }
 
-       } else {
-               playback_distance = nframes;
-       }
+                               } else {
 
-       if (need_disk_signal && !_session.declick_out_pending()) {
+                                       cerr << _name << " Need " << playback_distance << " total = " << total << 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;
 
-               /* copy the diskstream data to all output buffers */
+                               }
+                       }
 
-               MidiBuffer& mbuf (bufs.get_midi (0));
-               get_playback (mbuf, playback_distance);
+                       if (scaling != 1.0f && speed != 0.0) {
+                               apply_gain_to_buffer (disk_signal, nframes, scaling);
+                       }
 
-               /* leave the audio count alone */
-               ChanCount cnt (DataType::MIDI, 1);
-               cnt.set (DataType::AUDIO, bufs.count().n_audio());
-               bufs.set_count (cnt);
+                       chaninfo->buf->increment_read_ptr (playback_distance);
 
-               /* vari-speed */
-               if (_target_speed > 0 && _actual_speed != 1.0f) {
-                       MidiBuffer& mbuf (bufs.get_midi (0));
-                       for (MidiBuffer::iterator i = mbuf.begin(); i != mbuf.end(); ++i) {
-                               MidiBuffer::TimeType *tme = i.timeptr();
-                               *tme = (*tme) * nframes / playback_distance;
+                       if ((speed != 0.0) && (ms & MonitoringInput)) {
+                               /* mix the disk signal into the input signal (already in bufs) */
+                               mix_buffers_no_gain (output.data(), disk_signal, speed == 0.0 ? nframes : playback_distance);
                        }
                }
        }
 
-       /* MIDI butler needed part */
+       /* MIDI data handling */
 
-       uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
-       uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
+       if (!_session.declick_out_pending()) {
+               if (ms & MonitoringDisk && !still_locating) {
+                       get_midi_playback (bufs.get_midi (0), playback_distance, ms, scratch_bufs, speed, playback_distance);
+               }
+       }
 
-       /*
-         cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
-         " = " << frames_written - frames_read
-         << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
-       */
+       if (!still_locating) {
 
-       /* frames_read will generally be less than frames_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.
-        */
+               if (speed < 0.0) {
+                       playback_sample -= playback_distance;
+               } else {
+                       playback_sample += playback_distance;
+               }
 
-       /* furthermore..
-        *
-        * Doing heavy GUI operations[1] can stall also the butler.
-        * The RT-thread meanwhile will happily continue and
-        * â€˜frames_read’ (from buffer to output) will become larger
-        * than â€˜frames_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 (frames_read - frames_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 (frames_read <= frames_written) {
-               if ((frames_written - frames_read) + playback_distance < midi_readahead) {
-                       _need_butler = true;
+               if (_playlists[DataType::AUDIO]) {
+                       if (!c->empty()) {
+                               if (_slaved) {
+                                       if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
+                                               DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: slaved, write space = %2 of %3\n", name(), c->front()->buf->write_space(),
+                                                                                           c->front()->buf->bufsize()));
+                                               _need_butler = true;
+                                       }
+                               } else {
+                                       if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
+                                               DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: write space = %2 of %3\n", name(), c->front()->buf->write_space(),
+                                                                                           _chunk_frames));
+                                               _need_butler = true;
+                                       }
+                               }
+                       }
                }
-       } else {
-               _need_butler = true;
-       }
 
-       /* make sure bufs shows whatever data we had available */
+               if (_playlists[DataType::MIDI]) {
+                       /* MIDI butler needed part */
 
-       ChanCount cnt;
-       cnt.set (DataType::MIDI, 1);
-       cnt.set (DataType::AUDIO, bufs.count().n_audio());
-       bufs.set_count (cnt);
-}
+                       uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
+                       uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
+
+                       /*
+                         cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
+                         " = " << frames_written - frames_read
+                         << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
+                       */
+
+                       /* frames_read will generally be less than frames_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
+                        * â€˜frames_read’ (from buffer to output) will become larger
+                        * than â€˜frames_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 (frames_read - frames_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 (frames_read <= frames_written) {
+                               if ((frames_written - frames_read) + playback_distance < midi_readahead) {
+                                       _need_butler = true;
+                               }
+                       } else {
+                               _need_butler = true;
+                       }
 
-frameoffset_t
-DiskReader::calculate_playback_distance (pframes_t nframes)
-{
-       frameoffset_t playback_distance = nframes;
-
-       if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
-               interpolation.set_speed (_target_speed);
-               boost::shared_ptr<ChannelList> c = channels.reader();
-               int channel = 0;
-               for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
-                       playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
                }
-       } else {
-               playback_distance = nframes;
        }
 
-       if (_actual_speed < 0.0) {
-               return -playback_distance;
-       } else {
-               return playback_distance;
-       }
+       // DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
 }
 
 void
@@ -818,11 +499,13 @@ DiskReader::overwrite_existing_buffers ()
 
        overwrite_queued = false;
 
+       DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2\n", overwrite_frame));
+
        if (!c->empty ()) {
 
                /* AUDIO */
 
-               bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
+               const bool reversed = _session.transport_speed() < 0.0f;
 
                /* assume all are the same size */
                framecnt_t size = c->front()->buf->bufsize();
@@ -908,18 +591,6 @@ DiskReader::overwrite_existing_buffers ()
        return ret;
 }
 
-void
-DiskReader::non_realtime_locate (framepos_t location)
-{
-       /* now refill channel buffers */
-
-       if (speed() != 1.0f || speed() != -1.0f) {
-               seek ((framepos_t) (location * (double) speed()), true);
-       } else {
-               seek (location, true);
-       }
-}
-
 int
 DiskReader::seek (framepos_t frame, bool complete_refill)
 {
@@ -928,8 +599,6 @@ DiskReader::seek (framepos_t frame, bool complete_refill)
        ChannelList::iterator chan;
        boost::shared_ptr<ChannelList> c = channels.reader();
 
-       Glib::Threads::Mutex::Lock lm (state_lock);
-
        for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
                (*chan)->buf->reset ();
        }
@@ -1031,6 +700,11 @@ DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
        framecnt_t offset = 0;
        Location *loc = 0;
 
+       if (!_playlists[DataType::AUDIO]) {
+               memset (buf, 0, sizeof (Sample) * cnt);
+               return 0;
+       }
+
        /* XXX we don't currently play loops in reverse. not sure why */
 
        if (!reversed) {
@@ -1163,14 +837,18 @@ DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_
 int
 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
 {
-       if (_session.state_of_the_state() & Session::Loading) {
+       /* do not read from disk while session is marked as Loading, to avoid
+          useless redundant I/O.
+       */
+
+       if (_session.loading()) {
                return 0;
        }
 
        int32_t ret = 0;
        framecnt_t to_read;
        RingBufferNPT<Sample>::rw_vector vector;
-       bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
+       bool const reversed = _session.transport_speed() < 0.0f;
        framecnt_t total_space;
        framecnt_t zero_fill;
        uint32_t chan_n;
@@ -1178,10 +856,6 @@ DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t
        boost::shared_ptr<ChannelList> c = channels.reader();
        framecnt_t ts;
 
-       /* do not read from disk while session is marked as Loading, to avoid
-          useless redundant I/O.
-       */
-
        if (c->empty()) {
                return 0;
        }
@@ -1197,6 +871,7 @@ DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t
        c->front()->buf->get_write_vector (&vector);
 
        if ((total_space = vector.len[0] + vector.len[1]) == 0) {
+               DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
                /* nowhere to write to */
                return 0;
        }
@@ -1221,7 +896,8 @@ DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t
           the playback buffer is empty.
        */
 
-       if ((total_space < _chunk_frames) && fabs (_actual_speed) < 2.0f) {
+       DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: space to refill %2 vs. chunk %3 (speed = %4)\n", name(), total_space, _chunk_frames, _session.transport_speed()));
+       if ((total_space < _chunk_frames) && fabs (_session.transport_speed()) < 2.0f) {
                return 0;
        }
 
@@ -1231,6 +907,7 @@ DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t
        */
 
        if (_slaved && total_space < (framecnt_t) (c->front()->buf->bufsize() / 2)) {
+               DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: not enough to refill while slaved\n", this));
                return 0;
        }
 
@@ -1317,9 +994,7 @@ DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t
 
        framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
 
-       //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
-       // << c->front()->buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
-       // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->buf->bufsize() << " samples\n";
+       DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
 
        // uint64_t before = g_get_monotonic_time ();
        // uint64_t elapsed;
@@ -1404,7 +1079,7 @@ DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t
        }
 
        // elapsed = g_get_monotonic_time () - before;
-       // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
+       // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
 
        file_frame = file_frame_tmp;
        assert (file_frame >= 0);
@@ -1429,8 +1104,7 @@ DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const &
                return;
        }
 
-#if 0
-       if (!_track || Config->get_automation_follows_regions () == false) {
+       if (!_route || Config->get_automation_follows_regions () == false) {
                return;
        }
 
@@ -1444,7 +1118,7 @@ DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const &
        }
 
        /* move panner automation */
-       boost::shared_ptr<Pannable> pannable = _track->pannable();
+       boost::shared_ptr<Pannable> pannable = _route->pannable();
         Evoral::ControlSet::Controls& c (pannable->controls());
 
         for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
@@ -1464,8 +1138,7 @@ DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const &
                 }
         }
        /* move processor automation */
-       _track->foreach_processor (boost::bind (&Diskstream::move_processor_automation, this, _1, movements_frames));
-#endif
+        _route->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_frames));
 }
 
 void
@@ -1534,126 +1207,123 @@ DiskReader::resolve_tracker (Evoral::EventSink<framepos_t>& buffer, framepos_t t
        }
 }
 
-void
-DiskReader::flush_playback (framepos_t start, framepos_t end)
-{
-       _midi_buf->flush (start, end);
-       g_atomic_int_add (&_frames_read_from_ringbuffer, end - start);
-}
-
 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
  *  so that an event at playback_sample has time = 0
  */
 void
-DiskReader::get_playback (MidiBuffer& dst, framecnt_t nframes)
+DiskReader::get_midi_playback (MidiBuffer& dst, framecnt_t nframes, MonitorState ms, BufferSet& scratch_bufs, double speed, framecnt_t playback_distance)
 {
-       dst.clear();
+       MidiBuffer* target;
 
-       Location* loc = loop_location;
+       if ((ms & MonitoringInput) == 0) {
+               dst.clear();
+               target = &dst;
+       } else {
+               target = &scratch_bufs.get_midi (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(), playback_sample, playback_sample + nframes,
-                            (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
+       if (ms & MonitoringDisk) {
+               /* no disk data needed */
 
-       //cerr << "======== PRE ========\n";
-       //_midi_buf->dump (cerr);
-       //cerr << "----------------\n";
+               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(), playback_sample, playback_sample + nframes,
+                                    (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
 
-       if (loc) {
-               framepos_t effective_start;
+               //cerr << "======== PRE ========\n";
+               //_midi_buf->dump (cerr);
+               //cerr << "----------------\n";
 
-               Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
-               effective_start = loop_range.squish (playback_sample);
+               size_t events_read = 0;
 
-               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
+               if (loc) {
+                       framepos_t effective_start;
 
-               if (effective_start == loc->start()) {
-                       /* We need to turn off notes that may extend
-                          beyond the loop end.
-                       */
+                       Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
+                       effective_start = loop_range.squish (playback_sample);
 
-                       _midi_buf->resolve_tracker (dst, 0);
-               }
+                       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
 
-               /* for split-cycles we need to offset the events */
+                       if (effective_start == loc->start()) {
+                               /* We need to turn off notes that may extend
+                                  beyond the loop end.
+                               */
 
-               if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
+                               _midi_buf->resolve_tracker (*target, 0);
+                       }
 
-                       /* end of loop is within the range we are reading, so
-                          split the read in two, and lie about the location
-                          for the 2nd read
-                       */
+                       /* for split-cycles we need to offset the events */
 
-                       framecnt_t first, second;
+                       if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
 
-                       first = loc->end() - effective_start;
-                       second = nframes - first;
+                               /* end of loop is within the range we are reading, so
+                                  split the read in two, and lie about the location
+                                  for the 2nd read
+                               */
 
-                       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
-                                                                             effective_start, loc->end(), first, second));
+                               framecnt_t first, second;
 
-                       if (first) {
-                               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
-                                                                                     effective_start, first));
-                               events_read = _midi_buf->read (dst, effective_start, first);
-                       }
+                               first = loc->end() - effective_start;
+                               second = nframes - first;
 
-                       if (second) {
-                               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
-                                                                                     loc->start(), second));
-                               events_read += _midi_buf->read (dst, loc->start(), second);
-                       }
+                               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, 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",
+                                                                                             effective_start, first));
+                                       events_read = _midi_buf->read (*target, effective_start, first);
+                               }
+
+                               if (second) {
+                                       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
+                                                                                             loc->start(), second));
+                                       events_read += _midi_buf->read (*target, loc->start(), second);
+                               }
 
+                       } 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);
+                       }
                } 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 (dst, effective_start, effective_start + nframes);
-               }
-       } else {
-               const size_t n_skipped = _midi_buf->skip_to (playback_sample);
-               if (n_skipped > 0) {
-                       warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
+                       const size_t n_skipped = _midi_buf->skip_to (playback_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)", playback_sample, playback_sample + nframes, nframes));
+                       events_read = _midi_buf->read (*target, playback_sample, playback_sample + nframes);
                }
-               DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", playback_sample, playback_sample + nframes, nframes));
-               events_read = _midi_buf->read (dst, playback_sample, playback_sample + nframes);
-       }
 
-       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::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()));
+       }
 
        g_atomic_int_add (&_frames_read_from_ringbuffer, nframes);
 
+       /* vari-speed */
+
+       if (speed != 0.0 && fabsf (speed) != 1.0f) {
+               for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
+                       MidiBuffer::TimeType *tme = i.timeptr();
+                       *tme = (*tme) * nframes / playback_distance;
+               }
+       }
+
+       if (ms & MonitoringInput) {
+               dst.merge_from (*target, nframes);
+       }
+
        //cerr << "======== POST ========\n";
        //_midi_buf->dump (cerr);
        //cerr << "----------------\n";
 }
 
-/** Get the start, end, and length of a location "atomically".
- *
- * Note: Locations don't get deleted, so all we care about when I say "atomic"
- * is that we are always pointing to the same one and using start/length values
- * obtained just once.  Use this function to achieve this since location being
- * a parameter achieves this.
- */
-static void
-get_location_times(const Location* location,
-                   framepos_t*     start,
-                   framepos_t*     end,
-                   framepos_t*     length)
-{
-       if (location) {
-               *start  = location->start();
-               *end    = location->end();
-               *length = *end - *start;
-       }
-}
-
 /** @a start is set to the new frame position (TIME) read up to */
 int
 DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
@@ -1752,12 +1422,14 @@ DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
 int
 DiskReader::refill_midi ()
 {
-       int     ret         = 0;
+       if (!_playlists[DataType::MIDI]) {
+               return 0;
+       }
+
        size_t  write_space = _midi_buf->write_space();
-       bool    reversed    = (_visible_speed * _session.transport_speed()) < 0.0f;
+       const bool reversed    = _session.transport_speed() < 0.0f;
 
-       DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS refill, write space = %1 file frame = %2\n",
-                                                             write_space, file_frame));
+       DEBUG_TRACE (DEBUG::DiskIO, string_compose ("MIDI refill, write space = %1 file frame = %2\n", write_space, file_frame));
 
        /* no space to write */
        if (write_space == 0) {
@@ -1769,12 +1441,14 @@ DiskReader::refill_midi ()
        }
 
        /* at end: nothing to do */
+
        if (file_frame == max_framepos) {
                return 0;
        }
 
-       uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
-       uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
+       int ret = 0;
+       const uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
+       const uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
 
        if ((frames_read < frames_written) && (frames_written - frames_read) >= midi_readahead) {
                return 0;