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