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