take all tracks inside a midi-file into account when loading model
[ardour.git] / libs / ardour / smf_source.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3     Author: David Robillard
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <vector>
22
23 #include <sys/time.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <regex.h>
28
29 #include "pbd/pathscanner.h"
30 #include "pbd/stl_delete.h"
31 #include "pbd/strsplit.h"
32
33 #include <glibmm/miscutils.h>
34
35 #include "evoral/Control.hpp"
36
37 #include "ardour/event_type_map.h"
38 #include "ardour/midi_model.h"
39 #include "ardour/midi_ring_buffer.h"
40 #include "ardour/midi_state_tracker.h"
41 #include "ardour/session.h"
42 #include "ardour/smf_source.h"
43 #include "ardour/debug.h"
44
45 #include "i18n.h"
46
47 using namespace ARDOUR;
48 using namespace Glib;
49 using namespace PBD;
50
51 /** Constructor used for new internal-to-session files.  File cannot exist. */
52 SMFSource::SMFSource (Session& s, const string& path, Source::Flag flags)
53         : Source(s, DataType::MIDI, path, flags)
54         , MidiSource(s, path, flags)
55         , FileSource(s, DataType::MIDI, path, string(), flags)
56         , Evoral::SMF()
57         , _last_ev_time_beats(0.0)
58         , _last_ev_time_frames(0)
59         , _smf_last_read_end (0)
60         , _smf_last_read_time (0)
61 {
62         /* note that origin remains empty */
63
64         if (init(_path, false)) {
65                 throw failed_constructor ();
66         }
67
68         /* file is not opened until write */
69
70         if (flags & Writable) {
71                 return;
72         }
73
74         if (open(_path)) {
75                 throw failed_constructor ();
76         }
77         _open = true;
78 }
79
80 /** Constructor used for existing internal-to-session files. */
81 SMFSource::SMFSource (Session& s, const XMLNode& node, bool must_exist)
82         : Source(s, node)
83         , MidiSource(s, node)
84         , FileSource(s, node, must_exist)
85         , _last_ev_time_beats(0.0)
86         , _last_ev_time_frames(0)
87         , _smf_last_read_end (0)
88         , _smf_last_read_time (0)
89 {
90         if (set_state(node, Stateful::loading_state_version)) {
91                 throw failed_constructor ();
92         }
93
94         if (init(_path, true)) {
95                 throw failed_constructor ();
96         }
97
98         if (open(_path)) {
99                 throw failed_constructor ();
100         }
101
102         _open = true;
103 }
104
105 SMFSource::~SMFSource ()
106 {
107         if (removable()) {
108                 unlink (_path.c_str());
109         }
110 }
111
112 int
113 SMFSource::open_for_write ()
114 {
115         if (create (_path)) {
116                 return -1;
117         }
118         _open = true;
119         return 0;
120 }
121
122 /** All stamps in audio frames */
123 framecnt_t
124 SMFSource::read_unlocked (Evoral::EventSink<framepos_t>& destination,
125                           framepos_t const               source_start,
126                           framepos_t                     start,
127                           framecnt_t                     duration,
128                           MidiStateTracker*              tracker) const
129 {
130         int      ret  = 0;
131         uint64_t time = 0; // in SMF ticks, 1 tick per _ppqn
132
133         if (writable() && !_open) {
134                 /* nothing to read since nothing has ben written */
135                 return duration;
136         }
137
138         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start %1 duration %2\n", start, duration));
139
140         // Output parameters for read_event (which will allocate scratch in buffer as needed)
141         uint32_t ev_delta_t = 0;
142         uint32_t ev_type    = 0;
143         uint32_t ev_size    = 0;
144         uint8_t* ev_buffer  = 0;
145
146         size_t scratch_size = 0; // keep track of scratch to minimize reallocs
147
148         BeatsFramesConverter converter(_session.tempo_map(), source_start);
149
150         const uint64_t start_ticks = (uint64_t)(converter.from(start) * ppqn());
151         DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: start in ticks %1\n", start_ticks));
152
153         if (_smf_last_read_end == 0 || start != _smf_last_read_end) {
154                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: seek to %1\n", start));
155                 Evoral::SMF::seek_to_start();
156                 while (time < start_ticks) {
157                         gint ignored;
158
159                         ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
160                         if (ret == -1) { // EOF
161                                 _smf_last_read_end = start + duration;
162                                 return duration;
163                         }
164                         time += ev_delta_t; // accumulate delta time
165                 }
166         } else {
167                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked: set time to %1\n", _smf_last_read_time));
168                 time = _smf_last_read_time;
169         }
170
171         _smf_last_read_end = start + duration;
172
173         while (true) {
174                 gint ignored; /* XXX don't ignore note id's ??*/
175
176                 ret = read_event(&ev_delta_t, &ev_size, &ev_buffer, &ignored);
177                 if (ret == -1) { // EOF
178                         break;
179                 }
180
181                 time += ev_delta_t; // accumulate delta time
182                 _smf_last_read_time = time;
183
184                 if (ret == 0) { // meta-event (skipped, just accumulate time)
185                         continue;
186                 }
187
188                 ev_type = EventTypeMap::instance().midi_event_type(ev_buffer[0]);
189
190                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF read_unlocked delta %1, time %2, buf[0] %3, type %4\n",
191                                                                   ev_delta_t, time, ev_buffer[0], ev_type));
192
193                 assert(time >= start_ticks);
194
195                 /* Note that we add on the source start time (in session frames) here so that ev_frame_time
196                    is in session frames.
197                 */
198                 const framepos_t ev_frame_time = converter.to(time / (double)ppqn()) + source_start;
199
200                 if (ev_frame_time < start + duration) {
201                         destination.write (ev_frame_time, ev_type, ev_size, ev_buffer);
202
203                         if (tracker) {
204                                 if (ev_buffer[0] & MIDI_CMD_NOTE_ON) {
205                                         tracker->add (ev_buffer[1], ev_buffer[0] & 0xf);
206                                 } else if (ev_buffer[0] & MIDI_CMD_NOTE_OFF) {
207                                         tracker->remove (ev_buffer[1], ev_buffer[0] & 0xf);
208                                 }
209                         }
210                 } else {
211                         break;
212                 }
213
214                 if (ev_size > scratch_size) {
215                         scratch_size = ev_size;
216                 }
217                 ev_size = scratch_size; // ensure read_event only allocates if necessary
218         }
219
220         return duration;
221 }
222
223 framecnt_t
224 SMFSource::write_unlocked (MidiRingBuffer<framepos_t>& source,
225                            framepos_t                  position,
226                            framecnt_t                  cnt)
227 {
228         if (!_writing) {
229                 mark_streaming_write_started ();
230         }
231
232         framepos_t        time;
233         Evoral::EventType type;
234         uint32_t          size;
235
236         size_t   buf_capacity = 4;
237         uint8_t* buf          = (uint8_t*)malloc(buf_capacity);
238
239         if (_model && !_model->writing()) {
240                 _model->start_write();
241         }
242
243         Evoral::MIDIEvent<framepos_t> ev;
244         while (true) {
245                 /* Get the event time, in frames since session start but ignoring looping. */
246                 bool ret;
247                 if (!(ret = source.peek ((uint8_t*)&time, sizeof (time)))) {
248                         /* Ring is empty, no more events. */
249                         break;
250                 }
251
252                 if ((cnt != max_framecnt) &&
253                     (time > position + _capture_length + cnt)) {
254                         /* The diskstream doesn't want us to write everything, and this
255                            event is past the end of this block, so we're done for now. */
256                         break;
257                 }
258
259                 /* Read the time, type, and size of the event. */
260                 if (!(ret = source.read_prefix (&time, &type, &size))) {
261                         error << _("Unable to read event prefix, corrupt MIDI ring") << endmsg;
262                         break;
263                 }
264
265                 /* Enlarge body buffer if necessary now that we know the size. */
266                 if (size > buf_capacity) {
267                         buf_capacity = size;
268                         buf = (uint8_t*)realloc(buf, size);
269                 }
270
271                 /* Read the event body into buffer. */
272                 ret = source.read_contents(size, buf);
273                 if (!ret) {
274                         error << _("Event has time and size but no body, corrupt MIDI ring") << endmsg;
275                         break;
276                 }
277
278                 /* Convert event time from absolute to source relative. */
279                 if (time < position) {
280                         error << _("Event time is before MIDI source position") << endmsg;
281                         break;
282                 }
283                 time -= position;
284                         
285                 ev.set(buf, size, time);
286                 ev.set_event_type(EventTypeMap::instance().midi_event_type(ev.buffer()[0]));
287                 ev.set_id(Evoral::next_event_id());
288
289                 if (!(ev.is_channel_event() || ev.is_smf_meta_event() || ev.is_sysex())) {
290                         continue;
291                 }
292
293                 append_event_unlocked_frames(ev, position);
294         }
295
296         Evoral::SMF::flush ();
297         free (buf);
298
299         return cnt;
300 }
301
302 /** Append an event with a timestamp in beats (double) */
303 void
304 SMFSource::append_event_unlocked_beats (const Evoral::Event<double>& ev)
305 {
306         if (!_writing || ev.size() == 0)  {
307                 return;
308         }
309
310         /*printf("SMFSource: %s - append_event_unlocked_beats ID = %d time = %lf, size = %u, data = ",
311                name().c_str(), ev.id(), ev.time(), ev.size());
312                for (size_t i = 0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");*/
313
314         if (ev.time() < _last_ev_time_beats) {
315                 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
316                         << endmsg;
317                 return;
318         }
319
320         Evoral::event_id_t event_id;
321
322         if (ev.id() < 0) {
323                 event_id  = Evoral::next_event_id();
324         } else {
325                 event_id = ev.id();
326         }
327
328         if (_model) {
329                 _model->append (ev, event_id);
330         }
331
332         _length_beats = max(_length_beats, ev.time());
333
334         const double delta_time_beats   = ev.time() - _last_ev_time_beats;
335         const uint32_t delta_time_ticks = (uint32_t)lrint(delta_time_beats * (double)ppqn());
336
337         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
338         _last_ev_time_beats = ev.time();
339 }
340
341 /** Append an event with a timestamp in frames (framepos_t) */
342 void
343 SMFSource::append_event_unlocked_frames (const Evoral::Event<framepos_t>& ev, framepos_t position)
344 {
345         if (!_writing || ev.size() == 0)  {
346                 return;
347         }
348
349         // printf("SMFSource: %s - append_event_unlocked_frames ID = %d time = %u, size = %u, data = ",
350         // name().c_str(), ev.id(), ev.time(), ev.size());
351         // for (size_t i=0; i < ev.size(); ++i) printf("%X ", ev.buffer()[i]); printf("\n");
352
353         if (ev.time() < _last_ev_time_frames) {
354                 warning << string_compose(_("Skipping event with unordered time %1"), ev.time())
355                         << endmsg;
356                 return;
357         }
358
359         BeatsFramesConverter converter(_session.tempo_map(), position);
360         const double ev_time_beats = converter.from(ev.time());
361         Evoral::event_id_t event_id;
362
363         if (ev.id() < 0) {
364                 event_id  = Evoral::next_event_id();
365         } else {
366                 event_id = ev.id();
367         }
368
369         if (_model) {
370                 const Evoral::Event<double> beat_ev (ev.event_type(),
371                                                      ev_time_beats,
372                                                      ev.size(),
373                                                      const_cast<uint8_t*>(ev.buffer()));
374                 _model->append (beat_ev, event_id);
375         }
376
377         _length_beats = max(_length_beats, ev_time_beats);
378
379         const Evoral::MusicalTime last_time_beats  = converter.from (_last_ev_time_frames);
380         const Evoral::MusicalTime delta_time_beats = ev_time_beats - last_time_beats;
381         const uint32_t            delta_time_ticks = (uint32_t)(lrint(delta_time_beats * (double)ppqn()));
382
383         Evoral::SMF::append_event_delta(delta_time_ticks, ev.size(), ev.buffer(), event_id);
384         _last_ev_time_frames = ev.time();
385 }
386
387 XMLNode&
388 SMFSource::get_state ()
389 {
390         XMLNode& node = MidiSource::get_state();
391         node.add_property (X_("origin"), _origin);
392         return node;
393 }
394
395 int
396 SMFSource::set_state (const XMLNode& node, int version)
397 {
398         if (Source::set_state (node, version)) {
399                 return -1;
400         }
401
402         if (MidiSource::set_state (node, version)) {
403                 return -1;
404         }
405
406         if (FileSource::set_state (node, version)) {
407                 return -1;
408         }
409
410         return 0;
411 }
412
413 void
414 SMFSource::mark_streaming_midi_write_started (NoteMode mode)
415 {
416         /* CALLER MUST HOLD LOCK */
417
418         if (!_open && open_for_write()) {
419                 error << string_compose (_("cannot open MIDI file %1 for write"), _path) << endmsg;
420                 /* XXX should probably throw or return something */
421                 return;
422         }
423
424         MidiSource::mark_streaming_midi_write_started (mode);
425         Evoral::SMF::begin_write ();
426         _last_ev_time_beats = 0.0;
427         _last_ev_time_frames = 0;
428 }
429
430 void
431 SMFSource::mark_streaming_write_completed ()
432 {
433         mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::DeleteStuckNotes);
434 }
435
436 void
437 SMFSource::mark_midi_streaming_write_completed (Evoral::Sequence<Evoral::MusicalTime>::StuckNoteOption stuck_notes_option, Evoral::MusicalTime when)
438 {
439         Glib::Threads::Mutex::Lock lm (_lock);
440         MidiSource::mark_midi_streaming_write_completed (stuck_notes_option, when);
441
442         if (!writable()) {
443                 warning << string_compose ("attempt to write to unwritable SMF file %1", _path) << endmsg;
444                 return;
445         }
446
447         if (_model) {
448                 _model->set_edited(false);
449         }
450
451         Evoral::SMF::end_write ();
452
453         /* data in the file now, not removable */
454
455         mark_nonremovable ();
456 }
457
458 bool
459 SMFSource::safe_midi_file_extension (const string& file)
460 {
461         static regex_t compiled_pattern;
462         static bool compile = true;
463         const int nmatches = 2;
464         regmatch_t matches[nmatches];
465         
466         if (compile && regcomp (&compiled_pattern, "[mM][iI][dD][iI]?$", REG_EXTENDED)) {
467                 return false;
468         } else {
469                 compile = false;
470         }
471         
472         if (regexec (&compiled_pattern, file.c_str(), nmatches, matches, 0)) {
473                 return false;
474         }
475
476         return true;
477 }
478
479 static bool compare_eventlist (
480                 const std::pair< Evoral::Event<double>*, gint >& a,
481                 const std::pair< Evoral::Event<double>*, gint >& b) {
482         return ( a.first->time() < b.first->time() );
483 }
484
485 void
486 SMFSource::load_model (bool lock, bool force_reload)
487 {
488         if (_writing) {
489                 return;
490         }
491
492         boost::shared_ptr<Glib::Threads::Mutex::Lock> lm;
493         if (lock)
494                 lm = boost::shared_ptr<Glib::Threads::Mutex::Lock>(new Glib::Threads::Mutex::Lock(_lock));
495
496         if (_model && !force_reload) {
497                 return;
498         }
499
500         if (!_model) {
501                 _model = boost::shared_ptr<MidiModel> (new MidiModel (shared_from_this ()));
502         } else {
503                 _model->clear();
504         }
505
506         if (writable() && !_open) {
507                 return;
508         }
509
510         _model->start_write();
511         Evoral::SMF::seek_to_start();
512
513         uint64_t time = 0; /* in SMF ticks */
514         Evoral::Event<double> ev;
515
516         uint32_t scratch_size = 0; // keep track of scratch and minimize reallocs
517
518         uint32_t delta_t = 0;
519         uint32_t size    = 0;
520         uint8_t* buf     = NULL;
521         int ret;
522         gint event_id;
523         bool have_event_id;
524
525         // TODO simplify event allocation
526         std::list< std::pair< Evoral::Event<double>*, gint > > eventlist;
527
528         for (unsigned i = 1; i <= num_tracks(); ++i) {
529                 if (seek_to_track(i)) continue;
530
531                 time = 0;
532                 have_event_id = false;
533
534                 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
535
536                         time += delta_t;
537
538                         if (ret == 0) {
539                                 /* meta-event : did we get an event ID ?  */
540                                 if (event_id >= 0) {
541                                         have_event_id = true;
542                                 }
543                                 continue;
544                         }
545
546                         if (ret > 0) {
547                                 /* not a meta-event */
548
549                                 if (!have_event_id) {
550                                         event_id = Evoral::next_event_id();
551                                 }
552                                 uint32_t event_type = EventTypeMap::instance().midi_event_type(buf[0]);
553                                 double   event_time = time / (double) ppqn();
554 #ifndef NDEBUG
555                                 std::string ss;
556
557                                 for (uint32_t xx = 0; xx < size; ++xx) {
558                                         char b[8];
559                                         snprintf (b, sizeof (b), "0x%x ", buf[xx]);
560                                         ss += b;
561                                 }
562
563                                 DEBUG_TRACE (DEBUG::MidiSourceIO, string_compose ("SMF %6 load model delta %1, time %2, size %3 buf %4, type %5\n",
564                                                         delta_t, time, size, ss , event_type, name()));
565 #endif
566
567                                 eventlist.push_back(make_pair (
568                                                         new Evoral::Event<double> (
569                                                                 event_type, event_time,
570                                                                 size, buf, true)
571                                                         , event_id));
572
573                                 // Set size to max capacity to minimize allocs in read_event
574                                 scratch_size = std::max(size, scratch_size);
575                                 size = scratch_size;
576
577                                 _length_beats = max(_length_beats, event_time);
578                         }
579
580                         /* event ID's must immediately precede the event they are for */
581                         have_event_id = false;
582                 }
583         }
584
585         eventlist.sort(compare_eventlist);
586
587         std::list< std::pair< Evoral::Event<double>*, gint > >::iterator it;
588         for (it=eventlist.begin(); it!=eventlist.end(); ++it) {
589                 _model->append (*it->first, it->second);
590                 delete it->first;
591         }
592
593         _model->end_write (Evoral::Sequence<Evoral::MusicalTime>::ResolveStuckNotes, _length_beats);
594         _model->set_edited (false);
595
596         _model_iter = _model->begin();
597
598         free(buf);
599 }
600
601 void
602 SMFSource::destroy_model ()
603 {
604         //cerr << _name << " destroying model " << _model.get() << endl;
605         _model.reset();
606 }
607
608 void
609 SMFSource::flush_midi ()
610 {
611         if (!writable() || (writable() && !_open)) {
612                 return;
613         }
614
615         Evoral::SMF::end_write ();
616         /* data in the file means its no longer removable */
617         mark_nonremovable ();
618 }
619
620 void
621 SMFSource::set_path (const string& p)
622 {
623         FileSource::set_path (p);
624         SMF::set_path (_path);
625 }
626
627 /** Ensure that this source has some file on disk, even if it's just a SMF header */
628 void
629 SMFSource::ensure_disk_file ()
630 {
631         if (_model) {
632                 /* We have a model, so write it to disk; see MidiSource::session_saved
633                    for an explanation of what we are doing here.
634                 */
635                 boost::shared_ptr<MidiModel> mm = _model;
636                 _model.reset ();
637                 mm->sync_to_source ();
638                 _model = mm;
639         } else {
640                 /* No model; if it's not already open, it's an empty source, so create
641                    and open it for writing.
642                 */
643                 if (!_open) {
644                         open_for_write ();
645                 }
646
647                 /* Flush, which will definitely put something on disk */
648                 flush_midi ();
649         }
650 }
651