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