Merge with trunk R2978.
[ardour.git] / libs / ardour / smf_source.cc
index e1845a009f779393e63594fe5ff3d6e5e6773d38..29f36cc2cd3be54c2d6d655414f6d847a6762aca 100644 (file)
@@ -36,6 +36,8 @@
 #include <ardour/session.h>
 #include <ardour/midi_ring_buffer.h>
 #include <ardour/midi_util.h>
+#include <ardour/tempo.h>
+#include <ardour/audioengine.h>
 
 #include "i18n.h"
 
@@ -48,12 +50,11 @@ bool                                  SMFSource::header_position_negative;
 uint64_t                              SMFSource::header_position_offset;
 */
 
-SMFSource::SMFSource (std::string path, Flag flags)
-       : MidiSource (region_name_from_path(path))
+SMFSource::SMFSource (Session& s, std::string path, Flag flags)
+       : MidiSource (s, region_name_from_path(path, false))
        , _channel(0)
        , _flags (Flag(flags | Writable)) // FIXME: this needs to be writable for now
        , _allow_remove_if_empty(true)
-       , _timeline_position (0)
        , _fd (0)
        , _last_ev_time(0)
        , _track_size(4) // 4 bytes for the ever-present EOT event
@@ -68,16 +69,17 @@ SMFSource::SMFSource (std::string path, Flag flags)
        if (open()) {
                throw failed_constructor ();
        }
+
+       //cerr << "SMF Source path: " << path << endl;
        
        assert(_name.find("/") == string::npos);
 }
 
-SMFSource::SMFSource (const XMLNode& node)
-       : MidiSource (node)
+SMFSource::SMFSource (Session& s, const XMLNode& node)
+       : MidiSource (s, node)
        , _channel(0)
        , _flags (Flag (Writable|CanRename))
        , _allow_remove_if_empty(true)
-       , _timeline_position (0)
        , _fd (0)
        , _last_ev_time(0)
        , _track_size(4) // 4 bytes for the ever-present EOT event
@@ -97,6 +99,8 @@ SMFSource::SMFSource (const XMLNode& node)
                throw failed_constructor ();
        }
        
+       //cerr << "SMF Source name: " << _name << endl;
+       
        assert(_name.find("/") == string::npos);
 }
 
@@ -111,7 +115,7 @@ bool
 SMFSource::removable () const
 {
        return (_flags & Removable) && ((_flags & RemoveAtDestroy) || 
-                                     ((_flags & RemovableIfEmpty) && is_empty (_path)));
+                                     ((_flags & RemovableIfEmpty) && is_empty()));
 }
 
 int
@@ -135,7 +139,7 @@ SMFSource::init (string pathstr, bool must_exist)
 int
 SMFSource::open()
 {
-       cerr << "Opening SMF file " << path() << " writeable: " << writable() << endl;
+       //cerr << "Opening SMF file " << path() << " writeable: " << writable() << endl;
 
        assert(writable()); // FIXME;
 
@@ -147,26 +151,26 @@ SMFSource::open()
                uint32_t track_size_be = 0;
                fread(&track_size_be, 4, 1, _fd);
                _track_size = GUINT32_FROM_BE(track_size_be);
-               cerr << "SMF - read track size " << _track_size;
+               //cerr << "SMF - read track size " << _track_size << endl;
 
        // We're making a new file
        } else {
                _fd = fopen(path().c_str(), "w+");
-               _track_size = 0;
+               _track_size = 4;
 
-               // write a tentative header just to pad things out so writing happens in the right spot
+               // Write a tentative header just to pad things out so writing happens in the right spot
                flush_header();
-               // FIXME: write the footer here too so it's a valid SMF (screw up writing ATM though)
+               write_footer();
+               seek_to_end();
        }
 
        return (_fd == 0) ? -1 : 0;
 }
 
-int
-SMFSource::update_header (jack_nframes_t when, struct tm&, time_t)
+void
+SMFSource::seek_to_end()
 {
-       _timeline_position = when;
-       return flush_header();
+       fseek(_fd, -4, SEEK_END);
 }
 
 int
@@ -174,13 +178,13 @@ SMFSource::flush_header ()
 {
        // FIXME: write timeline position somehow?
        
-       cerr << "SMF Flushing header\n";
+       //cerr << "SMF Flushing header\n";
 
        assert(_fd);
 
-       const uint16_t type     = GUINT16_TO_BE(0);    // SMF Type 0 (single track)
-       const uint16_t ntracks  = GUINT16_TO_BE(1);    // Number of tracks (always 1 for Type 0)
-       const uint16_t division = GUINT16_TO_BE(1920); // FIXME FIXME FIXME PPQN
+       const uint16_t type     = GUINT16_TO_BE(0);     // SMF Type 0 (single track)
+       const uint16_t ntracks  = GUINT16_TO_BE(1);     // Number of tracks (always 1 for Type 0)
+       const uint16_t division = GUINT16_TO_BE(_ppqn); // Pulses per beat
 
        char data[6];
        memcpy(data, &type, 2);
@@ -203,16 +207,24 @@ SMFSource::flush_header ()
 int
 SMFSource::flush_footer()
 {
-       cerr << "SMF - Writing EOT\n";
+       seek_to_end();
+       write_footer();
+       seek_to_end();
 
-       fseek(_fd, 0, SEEK_END);
-       write_var_len(1); // whatever...
-       char eot[4] = { 0xFF, 0x2F, 0x00 }; // end-of-track meta-event
-       fwrite(eot, 1, 4, _fd);
-       fflush(_fd);
        return 0;
 }
 
+void
+SMFSource::write_footer()
+{
+       //cerr << "SMF " << name() << " writing EOT at byte " << ftell(_fd) << endl;
+       
+       write_var_len(0);
+       char eot[3] = { 0xFF, 0x2F, 0x00 }; // end-of-track meta-event
+       fwrite(eot, 1, 3, _fd);
+       fflush(_fd);
+}
+
 /** Returns the offset of the first event in the file with a time past @a start,
  * relative to the start of the source.
  *
@@ -220,7 +232,7 @@ SMFSource::flush_footer()
  */
 /*
 long
-SMFSource::find_first_event_after(jack_nframes_t start)
+SMFSource::find_first_event_after(nframes_t start)
 {
        // FIXME: obviously this is slooow
        
@@ -241,72 +253,105 @@ SMFSource::find_first_event_after(jack_nframes_t start)
  *
  * File position MUST be at the beginning of a delta time, or this will die very messily.
  * ev.buffer must be of size ev.size, and large enough for the event.  The returned event
- * will have it's time field set to it's delta time (so it's the caller's responsibility
- * to calculate a real time for the event).
+ * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
+ * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
+ *
+ * \a size should be the capacity of \a buf.  If it is not large enough, \a buf will
+ * be freed and a new buffer allocated in its place, the size of which will be placed
+ * in size.
  *
  * Returns event length (including status byte) on success, 0 if event was
  * skipped (eg a meta event), or -1 on EOF (or end of track).
  */
 int
-SMFSource::read_event(MidiEvent& ev) const
+SMFSource::read_event(uint32_t* delta_t, uint32_t* size, Byte** buf) const
 {
-       // - 4 is for the EOT event, which we don't actually want to read
-       //if (feof(_fd) || ftell(_fd) >= _header_size + _track_size - 4) {
        if (feof(_fd)) {
                return -1;
        }
 
-       uint32_t delta_time = read_var_len();
-       int status = fgetc(_fd);
+       assert(delta_t);
+       assert(size);
+       assert(buf);
+
+       *delta_t = read_var_len();
+       assert(!feof(_fd));
+
+       const int status = fgetc(_fd);
        assert(status != EOF); // FIXME die gracefully
+
+       //printf("Status @ %X = %X\n", (unsigned)ftell(_fd) - 1, status);
+
        if (status == 0xFF) {
                assert(!feof(_fd));
-               int type = fgetc(_fd);
+               const int type = fgetc(_fd);
                if ((unsigned char)type == 0x2F) {
-                       cerr << "SMF - hit EOT" << endl;
-                       return -1; // we hit the logical EOF anyway...
+                       //cerr << _name << " hit EOT" << endl;
+                       return -1;
                } else {
-                       ev.size = 0;
-                       ev.time = delta_time; // this is needed regardless
+                       *size = 0;
                        return 0;
                }
        }
+       
+       const int event_size = midi_event_size((unsigned char)status) + 1;
+       if (event_size <= 0) {
+               *size = 0;
+               return 0;
+       }
+       
+       // Make sure we have enough scratch buffer
+       if (*size < (unsigned)event_size)
+               *buf = (Byte*)realloc(*buf, event_size);
+       
+       *size = event_size;
 
-       ev.buffer[0] = (unsigned char)status;
-       ev.size = midi_event_size(ev.buffer[0]) + 1;
-       fread(ev.buffer+1, 1, ev.size - 1, _fd);
-       ev.time = delta_time;
+       /*if (ev.buffer == NULL)
+               ev.buffer = (Byte*)malloc(sizeof(Byte) * ev.size);*/
 
-       /*printf("SMF - read event, delta = %u, size = %zu, data = ",
-               delta_time, ev.size);
-       for (size_t i=0; i < ev.size; ++i) {
-               printf("%X ", ev.buffer[i]);
+       (*buf)[0] = (unsigned char)status;
+       if (event_size > 1)
+               fread((*buf) + 1, 1, *size - 1, _fd);
+
+       /*printf("%s read event: delta = %u, size = %u, data = ", _name.c_str(), *delta_t, *size);
+       for (size_t i=0; i < *size; ++i) {
+               printf("%X ", (*buf)[i]);
        }
        printf("\n");*/
        
-       return ev.size;
+       return (int)*size;
 }
 
-jack_nframes_t
-SMFSource::read_unlocked (MidiRingBuffer& dst, jack_nframes_t start, jack_nframes_t cnt, jack_nframes_t stamp_offset) const
+/** All stamps in audio frames */
+nframes_t
+SMFSource::read_unlocked (MidiRingBuffer& dst, nframes_t start, nframes_t cnt, nframes_t stamp_offset) const
 {
-       //cerr << "SMF - read " << start << " -- " << cnt;
+       //cerr << "SMF " << name() << " read " << start << ", count=" << cnt << ", offset=" << stamp_offset << endl;
 
-       jack_nframes_t time = 0;
+       // 64 bits ought to be enough for anybody
+       uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
 
-       // FIXME: ugh
-       unsigned char ev_buf[MidiBuffer::max_event_size()];
-       MidiEvent ev;
-       ev.time = 0;
-       ev.size = MidiBuffer::max_event_size();
-       ev.buffer = ev_buf;
+       _read_data_count = 0;
 
-       // FIXME: it would be an impressive feat to actually make this any slower :)
-       
+       // Output parameters for read_event (which will allocate scratch in buffer as needed)
+       uint32_t ev_delta_t = 0;
+       uint32_t ev_size = 0;
+       Byte*    ev_buffer = 0;
+
+       size_t scratch_size = 0; // keep track of scratch to minimize reallocs
+
+       // FIXME: don't seek to start and search every read (brutal!)
        fseek(_fd, _header_size, 0);
        
+       // FIXME: assumes tempo never changes after start
+       const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
+                       _session.engine().frame_rate(),
+                       _session.tempo_map().meter_at(_timeline_position));
+       
+       const uint64_t start_ticks = (uint64_t)((start / frames_per_beat) * _ppqn);
+
        while (!feof(_fd)) {
-               int ret = read_event(ev);
+               int ret = read_event(&ev_delta_t, &ev_size, &ev_buffer);
                if (ret == -1) { // EOF
                        //cerr << "SMF - EOF\n";
                        break;
@@ -314,65 +359,119 @@ SMFSource::read_unlocked (MidiRingBuffer& dst, jack_nframes_t start, jack_nframe
 
                if (ret == 0) { // meta-event (skipped)
                        //cerr << "SMF - META\n";
-                       time += ev.time; // just accumulate delta time and ignore event
+                       time += ev_delta_t; // just accumulate delta time and ignore event
                        continue;
                }
 
-               time += ev.time; // accumulate delta time
-               ev.time = time; // set ev.time to actual time (relative to source start)
+               time += ev_delta_t; // accumulate delta time
 
-               if (ev.time >= start) {
-                       if (ev.time > start + cnt) {
+               if (time >= start_ticks) {
+                       const nframes_t ev_frame_time = (nframes_t)(
+                                       ((time / (double)_ppqn) * frames_per_beat)) + stamp_offset;
+
+                       if (ev_frame_time <= start + cnt)
+                               dst.write(ev_frame_time, ev_size, ev_buffer);
+                       else
                                break;
-                       } else {
-                               ev.time += stamp_offset;
-                               dst.write(ev);
-                       }
                }
+
+               _read_data_count += ev_size;
+
+               if (ev_size > scratch_size)
+                       scratch_size = ev_size;
+               else
+                       ev_size = scratch_size; // minimize realloc in read_event
        }
        
        return cnt;
 }
 
-jack_nframes_t
-SMFSource::write_unlocked (MidiRingBuffer& src, jack_nframes_t cnt)
+/** All stamps in audio frames */
+nframes_t
+SMFSource::write_unlocked (MidiRingBuffer& src, nframes_t cnt)
 {
-       //cerr << "SMF WRITE -- " << _length << "--" << cnt << endl;
+       _write_data_count = 0;
+               
+       double time;
+       size_t size;
+
+       size_t buf_capacity = 4;
+       Byte* buf = (Byte*)malloc(buf_capacity);
        
-       MidiBuffer buf(1024); // FIXME: allocation, size?
-       src.read(buf, /*_length*/0, _length + cnt); // FIXME?
+       if (_model && ! _model->writing())
+               _model->start_write();
 
-       fseek(_fd, 0, SEEK_END);
+       while (true) {
+               bool ret = src.full_peek(sizeof(double), (Byte*)&time);
+               if (!ret || time - _timeline_position > _length + cnt)
+                       break;
 
-       // FIXME: start of source time?
-       
-       for (size_t i=0; i < buf.size(); ++i) {
-               const MidiEvent& ev = buf[i];
-               assert(ev.time >= _timeline_position);
-               uint32_t delta_time = (ev.time - _timeline_position) - _last_ev_time;
-               
-               /*printf("SMF - writing event, delta = %u, size = %zu, data = ",
-                       delta_time, ev.size);
-               for (size_t i=0; i < ev.size; ++i) {
-                       printf("%X ", ev.buffer[i]);
+               ret = src.read_prefix(&time, &size);
+               if (!ret)
+                       break;
+
+               if (size > buf_capacity) {
+                       buf_capacity = size;
+                       buf = (Byte*)realloc(buf, size);
                }
-               printf("\n");
-               */
-               size_t stamp_size = write_var_len(delta_time);
-               fwrite(ev.buffer, 1, ev.size, _fd);
-               _last_ev_time += delta_time;
-               _track_size += stamp_size + ev.size;
+
+               ret = src.read_contents(size, buf);
+               if (!ret) {
+                       cerr << "ERROR: Read time/size but not buffer, corrupt MIDI ring buffer" << endl;
+                       break;
+               }
+               
+               assert(time >= _timeline_position);
+               time -= _timeline_position;
+
+               const MidiEvent ev(time, size, buf);
+               append_event_unlocked(ev);
+
+               if (_model)
+                       _model->append(ev);
        }
 
        fflush(_fd);
+       free(buf);
 
-       if (buf.size() > 0) {
-               ViewDataRangeReady (_length, cnt); /* EMIT SIGNAL */
-       }
+       const nframes_t oldlen = _length;
+       update_length(oldlen, cnt);
 
-       update_length(_length, cnt);
+       ViewDataRangeReady (_timeline_position + oldlen, cnt); /* EMIT SIGNAL */
+       
        return cnt;
 }
+               
+
+void
+SMFSource::append_event_unlocked(const MidiEvent& ev)
+{
+       /*printf("SMF - writing event, time = %lf, size = %u, data = ", ev.time(), ev.size());
+       for (size_t i=0; i < ev.size(); ++i) {
+               printf("%X ", ev.buffer()[i]);
+       }
+       printf("\n");*/
+
+       assert(ev.time() >= 0);
+
+       assert(ev.time() >= _last_ev_time);
+       
+       // FIXME: assumes tempo never changes after start
+       const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
+                       _session.engine().frame_rate(),
+                       _session.tempo_map().meter_at(_timeline_position));
+       
+       const uint32_t delta_time = (uint32_t)((ev.time() - _last_ev_time) / frames_per_beat * _ppqn);
+
+       const size_t stamp_size = write_var_len(delta_time);
+       fwrite(ev.buffer(), 1, ev.size(), _fd);
+
+       _track_size += stamp_size + ev.size();
+       _write_data_count += ev.size();
+
+       _last_ev_time = ev.time();
+}
+
 
 XMLNode&
 SMFSource::get_state ()
@@ -419,13 +518,23 @@ SMFSource::mark_for_remove ()
        _flags = Flag (_flags | RemoveAtDestroy);
 }
 
+void
+SMFSource::mark_streaming_midi_write_started (NoteMode mode, nframes_t start_frame)
+{
+       MidiSource::mark_streaming_midi_write_started (mode, start_frame);
+       _last_ev_time = 0;
+}
+
 void
 SMFSource::mark_streaming_write_completed ()
 {
+       MidiSource::mark_streaming_write_completed();
+
        if (!writable()) {
                return;
        }
        
+       flush_header();
        flush_footer();
 
 #if 0
@@ -649,7 +758,7 @@ SMFSource::set_allow_remove_if_empty (bool yn)
 }
 
 int
-SMFSource::set_name (string newname, bool destructive)
+SMFSource::set_source_name (string newname, bool destructive)
 {
        //Glib::Mutex::Lock lm (_lock); FIXME
        string oldpath = _path;
@@ -672,16 +781,18 @@ SMFSource::set_name (string newname, bool destructive)
 }
 
 bool
-SMFSource::is_empty (string path)
+SMFSource::is_empty () const
 {
-       /* XXX fix me */
+       bool ret = (_track_size > 4);
+
+       //cerr << name() << " IS EMPTY: " << ret << endl;
 
-       return false;
+       return ret;
 }
 
 
 void
-SMFSource::write_chunk_header(char id[4], uint32_t length)
+SMFSource::write_chunk_header(const char id[4], uint32_t length)
 {
        const uint32_t length_be = GUINT32_TO_BE(length);
 
@@ -690,7 +801,7 @@ SMFSource::write_chunk_header(char id[4], uint32_t length)
 }
 
 void
-SMFSource::write_chunk(char id[4], uint32_t length, void* data)
+SMFSource::write_chunk(const char id[4], uint32_t length, void* data)
 {
        write_chunk_header(id, length);
        
@@ -728,9 +839,6 @@ SMFSource::read_var_len() const
 {
        assert(!feof(_fd));
 
-       //int offset = ftell(_fd);
-       //cerr << "SMF - reading var len at " << offset << endl;
-
        uint32_t value;
        unsigned char c;
 
@@ -744,3 +852,76 @@ SMFSource::read_var_len() const
 
        return value;
 }
+
+void
+SMFSource::load_model(bool lock, bool force_reload)
+{
+       if (_writing)
+               return;
+
+       if (lock)
+               Glib::Mutex::Lock lm (_lock);
+
+       if (_model && !force_reload && !_model->empty()) {
+               //cerr << _name << " NOT reloading model " << _model.get() << " (" << _model->n_notes()
+               //      << " notes)" << endl;
+               return;
+       } else {
+               cerr << _name << " loading model" << endl;
+       }
+
+       if (! _model) {
+               _model = boost::shared_ptr<MidiModel>(new MidiModel(_session));
+               cerr << _name << " loaded new model " << _model.get() << endl;
+       } else {
+               cerr << _name << " reloading model " << _model.get()
+                       << " (" << _model->n_notes() << " notes)" <<endl;
+               _model->clear();
+       }
+
+       _model->start_write();
+
+       fseek(_fd, _header_size, 0);
+
+       uint64_t time = 0; /* in SMF ticks */
+       MidiEvent ev;
+       
+       size_t scratch_size = 0; // keep track of scratch and minimize reallocs
+       
+       // FIXME: assumes tempo never changes after start
+       const double frames_per_beat = _session.tempo_map().tempo_at(_timeline_position).frames_per_beat(
+                       _session.engine().frame_rate(),
+                       _session.tempo_map().meter_at(_timeline_position));
+       
+       uint32_t delta_t = 0;
+       int ret;
+       while ((ret = read_event(&delta_t, &ev.size(), &ev.buffer())) >= 0) {
+               
+               time += delta_t;
+               
+               if (ret > 0) { // didn't skip (meta) event
+                       // make ev.time absolute time in frames
+                       ev.time() = (double)time * frames_per_beat / (double)_ppqn;
+
+                       _model->append(ev);
+               }
+
+               if (ev.size() > scratch_size)
+                       scratch_size = ev.size();
+               else
+                       ev.size() = scratch_size;
+       }
+       
+       _model->end_write(false);
+
+       free(ev.buffer());
+}
+
+
+void
+SMFSource::destroy_model()
+{
+       //cerr << _name << " destroying model " << _model.get() << endl;
+       _model.reset();
+}
+