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