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