Clean up.
[ardour.git] / libs / ardour / midi_diskstream.cc
index 27b9ad7942ab5dbbba7d0f8bb6e236e52a7a6e82..f960c170db095fbdbf1c1284ced71b7846613b2c 100644 (file)
 
 #include <ardour/ardour.h>
 #include <ardour/audioengine.h>
-#include <ardour/midi_diskstream.h>
-#include <ardour/utils.h>
 #include <ardour/configuration.h>
-#include <ardour/smf_source.h>
-#include <ardour/send.h>
-#include <ardour/region_factory.h>
-#include <ardour/midi_playlist.h>
-#include <ardour/playlist_factory.h>
 #include <ardour/cycle_timer.h>
-#include <ardour/midi_region.h>
+#include <ardour/io.h>
+#include <ardour/midi_diskstream.h>
+#include <ardour/midi_playlist.h>
 #include <ardour/midi_port.h>
+#include <ardour/midi_region.h>
+#include <ardour/playlist_factory.h>
+#include <ardour/region_factory.h>
+#include <ardour/send.h>
+#include <ardour/session.h>
+#include <ardour/smf_source.h>
+#include <ardour/utils.h>
 
 #include "i18n.h"
 #include <locale.h>
@@ -57,18 +59,17 @@ using namespace std;
 using namespace ARDOUR;
 using namespace PBD;
 
+nframes_t MidiDiskstream::midi_readahead = 4096;
+
 MidiDiskstream::MidiDiskstream (Session &sess, const string &name, Diskstream::Flag flag)
        : Diskstream(sess, name, flag)
        , _playback_buf(0)
        , _capture_buf(0)
-       //, _current_playback_buffer(0)
-       //, _current_capture_buffer(0)
-       //, _playback_wrap_buffer(0)
-       //, _capture_wrap_buffer(0)
        , _source_port(0)
-       , _capture_transition_buf(0)
        , _last_flush_frame(0)
        , _note_mode(Sustained)
+       , _frames_written_to_ringbuffer(0)
+       , _frames_read_from_ringbuffer(0)
 {
        /* prevent any write sources from being created */
 
@@ -86,14 +87,11 @@ MidiDiskstream::MidiDiskstream (Session& sess, const XMLNode& node)
        : Diskstream(sess, node)
        , _playback_buf(0)
        , _capture_buf(0)
-       //, _current_playback_buffer(0)
-       //, _current_capture_buffer(0)
-       //, _playback_wrap_buffer(0)
-       //, _capture_wrap_buffer(0)
        , _source_port(0)
-       , _capture_transition_buf(0)
        , _last_flush_frame(0)
        , _note_mode(Sustained)
+       , _frames_written_to_ringbuffer(0)
+       , _frames_read_from_ringbuffer(0)
 {
        in_set_state = true;
        init (Recordable);
@@ -123,9 +121,9 @@ MidiDiskstream::init (Diskstream::Flag f)
        set_block_size (_session.get_block_size());
        allocate_temporary_buffers ();
 
-       _playback_buf = new MidiRingBuffer (_session.diskstream_buffer_size());
-       _capture_buf = new MidiRingBuffer (_session.diskstream_buffer_size());
-       _capture_transition_buf = new RingBufferNPT<CaptureTransition> (128);
+       const size_t size = _session.midi_diskstream_buffer_size();
+       _playback_buf = new MidiRingBuffer<nframes_t>(size);
+       _capture_buf = new MidiRingBuffer<nframes_t>(size);
        
        _n_channels = ChanCount(DataType::MIDI, 1);
 
@@ -141,10 +139,9 @@ MidiDiskstream::~MidiDiskstream ()
 void
 MidiDiskstream::non_realtime_locate (nframes_t position)
 {
-       //cerr << "MDS: non_realtime_locate: " << position << endl;
        assert(_write_source);
        _write_source->set_timeline_position (position);
-       seek(position, true); // correct?
+       seek(position, false);
 }
 
 
@@ -304,7 +301,6 @@ MidiDiskstream::set_destructive (bool yn)
 void
 MidiDiskstream::set_note_mode (NoteMode m)
 {
-       cout << "MDS: SET NOTE MODE: " << m << endl;
        _note_mode = m;
        midi_playlist()->set_note_mode(m);
        if (_write_source && _write_source->model())
@@ -403,21 +399,6 @@ MidiDiskstream::check_record_status (nframes_t transport_frame, nframes_t nframe
                        
                }
 
-               if (_flags & Recordable) {
-                       RingBufferNPT<CaptureTransition>::rw_vector transvec;
-                       _capture_transition_buf->get_write_vector(&transvec);
-
-                       if (transvec.len[0] > 0) {
-                               transvec.buf[0]->type = CaptureStart;
-                               transvec.buf[0]->capture_val = capture_start_frame;
-                               _capture_transition_buf->increment_write_ptr(1);
-                       } else {
-                               // bad!
-                               fatal << X_("programming error: capture_transition_buf is full on rec start!  inconceivable!") 
-                                       << endmsg;
-                       }
-               }
-
        } else if (!record_enabled() || !can_record) {
                
                /* stop recording */
@@ -468,7 +449,7 @@ MidiDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t
                return 0;
        }
 
-       /* This lock is held until the end of AudioDiskstream::commit, so these two functions
+       /* This lock is held until the end of ::commit, so these two functions
           must always be called as a pair. The only exception is if this function
           returns a non-zero value, in which case, ::commit should not be called.
           */
@@ -538,20 +519,12 @@ MidiDiskstream::process (nframes_t transport_frame, nframes_t nframes, nframes_t
 
        if (nominally_recording || rec_nframes) {
 
-               assert(_source_port);
-
                // Pump entire port buffer into the ring buffer (FIXME: split cycles?)
-               //_capture_buf->write(_source_port->get_midi_buffer(), transport_frame);
-               size_t num_events = _source_port->get_midi_buffer().size();
-               size_t to_write = std::min(_capture_buf->write_space(), num_events);
-
-               MidiBuffer::iterator port_iter = _source_port->get_midi_buffer().begin();
-
-               for (size_t i=0; i < to_write; ++i) {
-                       const MIDI::Event& ev = *port_iter;
+               MidiBuffer& buf = _source_port->get_midi_buffer(nframes, offset);
+               for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
+                       const Evoral::MIDIEvent<MidiBuffer::TimeType> ev(*i, false);
                        assert(ev.buffer());
-                       _capture_buf->write(ev.time() + transport_frame, ev.size(), ev.buffer());
-                       ++port_iter;
+                       _capture_buf->write(ev.time() + transport_frame, ev.type(), ev.size(), ev.buffer());
                }
        
        } else {
@@ -642,12 +615,20 @@ MidiDiskstream::commit (nframes_t nframes)
                adjust_capture_position = 0;
        }
 
+       /* what audio does:
+        * can't do this with midi: write space is in bytes, chunk_frames is in frames
        if (_slaved) {
                need_butler = _playback_buf->write_space() >= _playback_buf->capacity() / 2;
        } else {
                need_butler = _playback_buf->write_space() >= disk_io_chunk_frames
                        || _capture_buf->read_space() >= disk_io_chunk_frames;
-       }
+       }*/
+       
+       // Use The Counters To calculate how much time the Ringbuffer holds.
+       uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
+       uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
+       if ((frames_written - frames_read) <= midi_readahead)
+               need_butler = true;
        
        if (commit_should_unlock) {
                state_lock.unlock();
@@ -664,15 +645,17 @@ MidiDiskstream::set_pending_overwrite (bool yn)
        /* called from audio thread, so we can use the read ptr and playback sample as we wish */
        
        pending_overwrite = yn;
-
+       
        overwrite_frame = playback_sample;
-       //overwrite_offset = channels.front().playback_buf->get_read_ptr();
 }
 
 int
 MidiDiskstream::overwrite_existing_buffers ()
 {
-       //cerr << "MDS: overwrite_existing_buffers() (does nothing)" << endl;
+       //read(overwrite_frame, disk_io_chunk_frames, false);
+       overwrite_queued = false;
+       pending_overwrite = false;
+
        return 0;
 }
 
@@ -682,10 +665,10 @@ MidiDiskstream::seek (nframes_t frame, bool complete_refill)
        Glib::Mutex::Lock lm (state_lock);
        int ret = -1;
        
-       //cerr << "MDS: seek: " << frame << endl;
-
        _playback_buf->reset();
        _capture_buf->reset();
+       g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
+       g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
 
        playback_sample = frame;
        file_frame = frame;
@@ -702,7 +685,9 @@ MidiDiskstream::seek (nframes_t frame, bool complete_refill)
 int
 MidiDiskstream::can_internal_playback_seek (nframes_t distance)
 {
-       if (_playback_buf->read_space() < distance) {
+       uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
+       uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
+       if ((frames_written-frames_read) < distance) {
                return false;
        } else {
                return true;
@@ -750,7 +735,7 @@ MidiDiskstream::read (nframes_t& start, nframes_t dur, bool reversed)
                   position within the loop.
                */
                
-               if (loc && start >= loop_end) {
+               if (loc && (start >= loop_end)) {
                        //cerr << "start adjusted from " << start;
                        start = loop_start + ((start - loop_start) % loop_length);
                        //cerr << "to " << start << endl;
@@ -782,6 +767,8 @@ MidiDiskstream::read (nframes_t& start, nframes_t dur, bool reversed)
                                         start) << endmsg;
                        return -1;
                }
+               //cout << "this write " << this_read << "start= " << start << endl;
+               g_atomic_int_add(&_frames_written_to_ringbuffer, this_read);
 
                _read_data_count = _playlist->read_data_count();
                
@@ -796,6 +783,12 @@ MidiDiskstream::read (nframes_t& start, nframes_t dur, bool reversed)
                        /* if we read to the end of the loop, go back to the beginning */
                        
                        if (reloop) {
+                               // Synthesize LoopEvent here, because the next events
+                               // written will have non-monotonic timestamps.
+                               _playback_buf->write(loop_end - 1, LoopEventType, 0, 0);
+                               //cout << "Pushing LoopEvent ts=" << loop_end-1 
+                               //     << " start+this_read " << start+this_read << endl;
+
                                start = loop_start;
                        } else {
                                start += this_read;
@@ -818,47 +811,20 @@ MidiDiskstream::do_refill_with_alloc ()
 int
 MidiDiskstream::do_refill ()
 {
-       int32_t        ret = 0;
-       size_t         write_space = _playback_buf->write_space();
-
-       bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
+       int     ret         = 0;
+       size_t  write_space = _playback_buf->write_space();
+       bool    reversed    = (_visible_speed * _session.transport_speed()) < 0.0f;
 
        if (write_space == 0) {
                return 0;
        }
-
-       /* if we're running close to normal speed and there isn't enough 
-          space to do disk_io_chunk_frames of I/O, then don't bother.  
-
-          at higher speeds, just do it because the sync between butler
-          and audio thread may not be good enough.
-          */
-
-       if ((write_space < disk_io_chunk_frames) && fabs (_actual_speed) < 2.0f) {
-               //cerr << "No refill 1\n";
-               return 0;
-       }
-
-       /* when slaved, don't try to get too close to the read pointer. this
-          leaves space for the buffer reversal to have something useful to
-          work with.
-          */
-
-       if (_slaved && write_space < (_playback_buf->capacity() / 2)) {
-               //cerr << "No refill 2\n";
-               return 0;
-       }
-
+       
        if (reversed) {
-               //cerr << "No refill 3 (reverse)\n";
                return 0;
        }
 
+       /* at end: nothing to do */
        if (file_frame == max_frames) {
-               //cerr << "No refill 4 (EOF)\n";
-
-               /* at end: nothing to do */
-
                return 0;
        }
 
@@ -866,19 +832,25 @@ MidiDiskstream::do_refill ()
        assert(_playback_buf->write_space() > 0); // ... have something to write to, and
        assert(file_frame <= max_frames); // ... something to write
 
-       nframes_t file_frame_tmp = file_frame;
-       nframes_t to_read = min(disk_io_chunk_frames, (max_frames - file_frame));
-       
-       // FIXME: read count?
-       if (read (file_frame_tmp, to_read, reversed)) {
-               ret = -1;
-               goto out;
+       // now calculate how much time is in the ringbuffer.
+       // and lets write as much as we need to get this to be midi_readahead;
+       uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
+       uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
+       if ((frames_written-frames_read) >= midi_readahead) {
+               //cout << "Nothing to do. all fine" << endl;
+               return 0;
        }
 
-       file_frame = file_frame_tmp;
+       nframes_t to_read = midi_readahead - (frames_written - frames_read);
 
-out:
+       //cout << "read for midi_readahead " << to_read << "  rb_contains: " << frames_written-frames_read << endl;
 
+       to_read = min(to_read, (max_frames - file_frame));
+       
+       if (read (file_frame, to_read, reversed)) {
+               ret = -1;
+       }
+               
        return ret;
 }
 
@@ -893,12 +865,10 @@ out:
  * written at all unless @a force_flush is true.
  */
 int
-MidiDiskstream::do_flush (Session::RunContext context, bool force_flush)
+MidiDiskstream::do_flush (RunContext context, bool force_flush)
 {
        uint32_t to_write;
        int32_t ret = 0;
-       // FIXME: I'd be lying if I said I knew what this thing was
-       //RingBufferNPT<CaptureTransition>::rw_vector transvec;
        nframes_t total;
 
        _write_data_count = 0;
@@ -929,7 +899,6 @@ MidiDiskstream::do_flush (Session::RunContext context, bool force_flush)
                ret = 1;
        } 
 
-       //to_write = min (disk_io_chunk_frames, (nframes_t) vector.len[0]);
        to_write = disk_io_chunk_frames;
 
        assert(!destructive());
@@ -944,8 +913,7 @@ MidiDiskstream::do_flush (Session::RunContext context, bool force_flush)
        }
 
 out:
-       //return ret;
-       return 0; // FIXME: everything's fine!  always!  honest!
+       return ret;
 }
 
 void
@@ -968,7 +936,7 @@ MidiDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_cap
           */
 
        while (more_work && !err) {
-               switch (do_flush (Session::TransportContext, true)) {
+               switch (do_flush (TransportContext, true)) {
                        case 0:
                                more_work = false;
                                break;
@@ -1022,9 +990,9 @@ MidiDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_cap
                   */
 
                try {
-                       boost::shared_ptr<Region> rx (RegionFactory::create (srcs, _write_source->last_capture_start_frame(), total_capture, 
-                                                                            whole_file_region_name, 
-                                                                            0, Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
+                       boost::shared_ptr<Region> rx (RegionFactory::create (srcs, 0,
+                                       total_capture, whole_file_region_name, 0,
+                                       Region::Flag (Region::DefaultFlags|Region::Automatic|Region::WholeFile)));
 
                        region = boost::dynamic_pointer_cast<MidiRegion> (rx);
                        region->special_set_position (capture_info.front()->start);
@@ -1043,7 +1011,7 @@ MidiDiskstream::transport_stopped (struct tm& when, time_t twhen, bool abort_cap
                XMLNode &before = _playlist->get_state();
                _playlist->freeze ();
 
-               for (buffer_position = _write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
+               for (buffer_position = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
 
                        string region_name;
 
@@ -1495,7 +1463,6 @@ MidiDiskstream::capture_buffer_load () const
                        (double) _capture_buf->capacity());
 }
 
-
 int
 MidiDiskstream::use_pending_capture_data (XMLNode& node)
 {
@@ -1506,16 +1473,38 @@ MidiDiskstream::use_pending_capture_data (XMLNode& node)
  * so that an event at \a start has time = 0
  */
 void
-MidiDiskstream::get_playback(MidiBuffer& dst, nframes_t start, nframes_t end)
+MidiDiskstream::get_playback(MidiBuffer& dst, nframes_t start, nframes_t end, nframes_t offset)
 {
-       dst.clear();
-       assert(dst.size() == 0);
+       if (offset == 0) {
+               dst.clear();
+               assert(dst.size() == 0);
+       }
        
        // Reverse.  ... We just don't do reverse, ok?  Back off.
        if (end <= start) {
                return;
        }
 
-       // Translates stamps to be relative to start
-       _playback_buf->read(dst, start, end);
+       // Check only events added this offset cycle
+       MidiBuffer::iterator this_cycle_start = dst.end();
+       
+       // Translates stamps to be relative to start, but add offset.
+       #if 1
+               _playback_buf->read(dst, start, end, offset);
+       #else   
+               const size_t events_read = _playback_buf->read(dst, start, end, offset);
+               cout << "frames read = " << frames_read << " events read = " << events_read
+               << " end = " << end << " start = " << start << " offset = " << offset
+               << " readspace " << _playback_buf->read_space()
+               << " writespace " << _playback_buf->write_space() << endl;
+       #endif
+       
+       gint32 frames_read = end - start;
+       g_atomic_int_add(&_frames_read_from_ringbuffer, frames_read);
+       
+       // Feed the data through the MidiStateTracker
+       // If it detects a LoopEvent it will add necessary note offs
+       if (_midi_state_tracker.track(this_cycle_start, dst.end())) {
+               _midi_state_tracker.resolve_notes(dst, end-start - 1 + offset);
+       }
 }