improved/new DEBUG_TRACE output
[ardour.git] / libs / evoral / SMF.cc
1 /*
2  * Copyright (C) 2008-2015 David Robillard <d@drobilla.net>
3  * Copyright (C) 2009-2018 Paul Davis <paul@linuxaudiosystems.com>
4  * Copyright (C) 2009 Hans Baier <hansfbaier@googlemail.com>
5  * Copyright (C) 2010-2012 Carl Hetherington <carl@carlh.net>
6  * Copyright (C) 2014-2018 Robin Gareus <robin@gareus.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <algorithm>
24 #include <cassert>
25 #include <cmath>
26 #include <iostream>
27 #include <stdint.h>
28
29 #include <glib/gstdio.h>
30
31 #include "libsmf/smf.h"
32
33 #include "evoral/Event.h"
34 #include "evoral/SMF.h"
35 #include "evoral/midi_util.h"
36
37 #ifdef COMPILER_MSVC
38 extern double round(double x);
39 #endif
40
41 using namespace std;
42
43 namespace Evoral {
44
45 SMF::SMF()
46         : _smf (0)
47         , _smf_track (0)
48         , _empty (true)
49         , _type0 (false)
50         {};
51
52 SMF::~SMF()
53 {
54         close ();
55 }
56
57 uint16_t
58 SMF::num_tracks() const
59 {
60         Glib::Threads::Mutex::Lock lm (_smf_lock);
61         return _smf ? _smf->number_of_tracks : 0;
62 }
63
64 uint16_t
65 SMF::ppqn() const
66 {
67         Glib::Threads::Mutex::Lock lm (_smf_lock);
68         return _smf->ppqn;
69 }
70
71 /** Seek to the specified track (1-based indexing)
72  * \return 0 on success
73  */
74 int
75 SMF::seek_to_track(int track)
76 {
77         Glib::Threads::Mutex::Lock lm (_smf_lock);
78         _smf_track = smf_get_track_by_number(_smf, track);
79         if (_smf_track != NULL) {
80                 _smf_track->next_event_number = (_smf_track->number_of_events == 0) ? 0 : 1;
81                 return 0;
82         } else {
83                 return -1;
84         }
85 }
86
87 /** Attempt to open the SMF file just to see if it is valid.
88  *
89  * \return  true on success
90  *          false on failure
91  */
92 bool
93 SMF::test(const std::string& path)
94 {
95         FILE* f = g_fopen(path.c_str(), "r");
96         if (f == 0) {
97                 return false;
98         }
99
100         smf_t* test_smf = smf_load(f);
101         fclose(f);
102
103         if (!test_smf) {
104                 return false;
105         }
106         if (test_smf) {
107                 smf_delete(test_smf);
108         }
109         return true;
110 }
111
112 /** Attempt to open the SMF file for reading and/or writing.
113  *
114  * \return  0 on success
115  *         -1 if the file can not be opened or created
116  *         -2 if the file exists but specified track does not exist
117  */
118 int
119 SMF::open(const std::string& path, int track)
120 {
121         Glib::Threads::Mutex::Lock lm (_smf_lock);
122
123         _type0 = false;
124         _type0channels.clear ();
125
126         assert(track >= 1);
127         if (_smf) {
128                 smf_delete(_smf);
129         }
130
131         FILE* f = g_fopen(path.c_str(), "r");
132         if (f == 0) {
133                 return -1;
134         } else if ((_smf = smf_load(f)) == 0) {
135                 fclose(f);
136                 return -1;
137         } else if ((_smf_track = smf_get_track_by_number(_smf, track)) == 0) {
138                 fclose(f);
139                 return -2;
140         }
141
142         //cerr << "Track " << track << " # events: " << _smf_track->number_of_events << endl;
143         if (_smf_track->number_of_events == 0) {
144                 _smf_track->next_event_number = 0;
145                 _empty = true;
146         } else {
147                 _smf_track->next_event_number = 1;
148                 _empty = false;
149         }
150
151         fclose(f);
152
153         lm.release ();
154         if (_smf->format == 0 && _smf->number_of_tracks == 1 && !_empty) {
155                 // type-0 file: scan file for # of used channels.
156                 int ret;
157                 uint32_t delta_t = 0;
158                 uint32_t size    = 0;
159                 uint8_t* buf     = NULL;
160                 event_id_t event_id = 0;
161                 seek_to_start();
162                 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
163                         if (ret == 0) {
164                                 continue;
165                         }
166                         if (size == 0) {
167                                 break;
168                         }
169                         uint8_t type = buf[0] & 0xf0;
170                         uint8_t chan = buf[0] & 0x0f;
171                         if (type < 0x80 || type > 0xE0) {
172                                 continue;
173                         }
174                         _type0channels.insert(chan);
175                 }
176                 _type0 = true;
177                 seek_to_start();
178         }
179         return 0;
180 }
181
182
183 /** Attempt to create a new SMF file for reading and/or writing.
184  *
185  * \return  0 on success
186  *         -1 if the file can not be created
187  *         -2 if the track can not be created
188  */
189 int
190 SMF::create(const std::string& path, int track, uint16_t ppqn)
191 {
192         Glib::Threads::Mutex::Lock lm (_smf_lock);
193
194         assert(track >= 1);
195         if (_smf) {
196                 smf_delete(_smf);
197         }
198
199         _smf = smf_new();
200
201         if (_smf == NULL) {
202                 return -1;
203         }
204
205         if (smf_set_ppqn(_smf, ppqn) != 0) {
206                 return -1;
207         }
208
209         for (int i = 0; i < track; ++i) {
210                 _smf_track = smf_track_new();
211                 if (!_smf_track) {
212                         return -2;
213                 }
214                 smf_add_track(_smf, _smf_track);
215         }
216
217         _smf_track = smf_get_track_by_number(_smf, track);
218         if (!_smf_track)
219                 return -2;
220
221         _smf_track->next_event_number = 0;
222
223         {
224                 /* put a stub file on disk */
225
226                 FILE* f = g_fopen (path.c_str(), "w+");
227                 if (f == 0) {
228                         return -1;
229                 }
230
231                 if (smf_save (_smf, f)) {
232                         fclose (f);
233                         return -1;
234                 }
235                 fclose (f);
236         }
237
238         _empty = true;
239         _type0 = false;
240         _type0channels.clear ();
241
242         return 0;
243 }
244
245 void
246 SMF::close()
247 {
248         Glib::Threads::Mutex::Lock lm (_smf_lock);
249
250         if (_smf) {
251                 smf_delete(_smf);
252                 _smf = 0;
253                 _smf_track = 0;
254                 _type0 = false;
255                 _type0channels.clear ();
256         }
257 }
258
259 void
260 SMF::seek_to_start() const
261 {
262         Glib::Threads::Mutex::Lock lm (_smf_lock);
263         if (_smf_track) {
264                 _smf_track->next_event_number = std::min(_smf_track->number_of_events, (size_t)1);
265         } else {
266                 cerr << "WARNING: SMF seek_to_start() with no track" << endl;
267         }
268 }
269
270 /** Read an event from the current position in file.
271  *
272  * File position MUST be at the beginning of a delta time, or this will die very messily.
273  * ev.buffer must be of size ev.size, and large enough for the event.  The returned event
274  * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
275  * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
276  *
277  * \a buf must be a pointer to a buffer allocated with malloc, or a pointer to NULL.
278  * \a size must be the capacity of \a buf.  If it is not large enough, \a buf will
279  * be reallocated and *size will be set to the new size of buf.
280  *
281  * if the event is a meta-event and is an Evoral Note ID, then \a note_id will be set
282  * to the value of the NoteID; otherwise, meta-events will set \a note_id to -1.
283  *
284  * \return event length (including status byte) on success, 0 if event was
285  * a meta event, or -1 on EOF (or end of track).
286  */
287 int
288 SMF::read_event(uint32_t* delta_t, uint32_t* size, uint8_t** buf, event_id_t* note_id) const
289 {
290         Glib::Threads::Mutex::Lock lm (_smf_lock);
291
292         smf_event_t* event;
293
294         assert(delta_t);
295         assert(size);
296         assert(buf);
297         assert(note_id);
298
299         if ((event = smf_track_get_next_event(_smf_track)) != NULL) {
300
301                 *delta_t = event->delta_time_pulses;
302
303                 if (smf_event_is_metadata(event)) {
304                         *note_id = -1; // "no note id in this meta-event */
305
306                         if (event->midi_buffer[1] == 0x7f) { // Sequencer-specific
307
308                                 uint32_t evsize;
309                                 uint32_t lenlen;
310
311                                 if (smf_extract_vlq (&event->midi_buffer[2], event->midi_buffer_length-2, &evsize, &lenlen) == 0) {
312
313                                         if (event->midi_buffer[2+lenlen] == 0x99 &&  // Evoral
314                                             event->midi_buffer[3+lenlen] == 0x1) { // Evoral Note ID
315
316                                                 uint32_t id;
317                                                 uint32_t idlen;
318
319                                                 if (smf_extract_vlq (&event->midi_buffer[4+lenlen], event->midi_buffer_length-(4+lenlen), &id, &idlen) == 0) {
320                                                         *note_id = id;
321                                                 }
322                                         }
323                                 }
324                         }
325                         return 0; /* this is a meta-event */
326                 }
327
328                 int event_size = event->midi_buffer_length;
329                 assert(event_size > 0);
330
331                 // Make sure we have enough scratch buffer
332                 if (*size < (unsigned)event_size) {
333                         *buf = (uint8_t*)realloc(*buf, event_size);
334                 }
335                 assert (*buf);
336                 memcpy(*buf, event->midi_buffer, size_t(event_size));
337                 *size = event_size;
338                 if (((*buf)[0] & 0xF0) == 0x90 && (*buf)[2] == 0) {
339                         /* normalize note on with velocity 0 to proper note off */
340                         (*buf)[0] = 0x80 | ((*buf)[0] & 0x0F);  /* note off */
341                         (*buf)[2] = 0x40;  /* default velocity */
342                 }
343
344                 if (!midi_event_is_valid(*buf, *size)) {
345                         cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
346                         *size = 0;
347                         return -1;
348                 }
349
350                 /* printf("SMF::read_event @ %u: ", *delta_t);
351                    for (size_t i = 0; i < *size; ++i) {
352                    printf("%X ", (*buf)[i]);
353                    } printf("\n") */
354
355                 return event_size;
356         } else {
357                 return -1;
358         }
359 }
360
361 void
362 SMF::append_event_delta(uint32_t delta_t, uint32_t size, const uint8_t* buf, event_id_t note_id)
363 {
364         Glib::Threads::Mutex::Lock lm (_smf_lock);
365
366         if (size == 0) {
367                 return;
368         }
369
370         /* printf("SMF::append_event_delta @ %u:", delta_t);
371            for (size_t i = 0; i < size; ++i) {
372            printf("%X ", buf[i]);
373            } printf("\n"); */
374
375         switch (buf[0]) {
376         case 0xf1:
377         case 0xf2:
378         case 0xf3:
379         case 0xf4:
380         case 0xf5:
381         case 0xf6:
382         case 0xf8:
383         case 0xf9:
384         case 0xfa:
385         case 0xfb:
386         case 0xfc:
387         case 0xfd:
388         case 0xfe:
389         case 0xff:
390                 /* System Real Time or System Common event: not valid in SMF
391                  */
392                 return;
393         }
394
395         if (!midi_event_is_valid(buf, size)) {
396                 cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
397                 return;
398         }
399
400         smf_event_t* event;
401
402         /* XXX july 2010: currently only store event ID's for notes, program changes and bank changes
403          */
404
405         uint8_t const c = buf[0] & 0xf0;
406         bool const store_id = (
407                 c == MIDI_CMD_NOTE_ON ||
408                 c == MIDI_CMD_NOTE_OFF ||
409                 c == MIDI_CMD_NOTE_PRESSURE ||
410                 c == MIDI_CMD_PGM_CHANGE ||
411                 (c == MIDI_CMD_CONTROL && (buf[1] == MIDI_CTL_MSB_BANK || buf[1] == MIDI_CTL_LSB_BANK))
412                                );
413
414         if (store_id && note_id >= 0) {
415                 int idlen;
416                 int lenlen;
417                 uint8_t idbuf[16];
418                 uint8_t lenbuf[16];
419
420                 event = smf_event_new ();
421                 assert(event != NULL);
422
423                 /* generate VLQ representation of note ID */
424                 idlen = smf_format_vlq (idbuf, sizeof(idbuf), note_id);
425
426                 /* generate VLQ representation of meta event length,
427                    which is the idlen + 2 bytes (Evoral type ID plus Note ID type)
428                 */
429
430                 lenlen = smf_format_vlq (lenbuf, sizeof(lenbuf), idlen+2);
431
432                 event->midi_buffer_length = 2 + lenlen + 2 + idlen;
433                 /* this should be allocated by malloc(3) because libsmf will
434                    call free(3) on it
435                 */
436                 event->midi_buffer = (uint8_t*) malloc (sizeof(uint8_t) * event->midi_buffer_length);
437
438                 event->midi_buffer[0] = 0xff; // Meta-event
439                 event->midi_buffer[1] = 0x7f; // Sequencer-specific
440                 memcpy (&event->midi_buffer[2], lenbuf, lenlen);
441                 event->midi_buffer[2+lenlen] = 0x99; // Evoral type ID
442                 event->midi_buffer[3+lenlen] = 0x1;  // Evoral type Note ID
443                 memcpy (&event->midi_buffer[4+lenlen], idbuf, idlen);
444
445                 assert(_smf_track);
446                 smf_track_add_event_delta_pulses(_smf_track, event, 0);
447         }
448
449         event = smf_event_new_from_pointer(buf, size);
450         assert(event != NULL);
451
452         assert(_smf_track);
453         smf_track_add_event_delta_pulses(_smf_track, event, delta_t);
454         _empty = false;
455 }
456
457 void
458 SMF::begin_write()
459 {
460         Glib::Threads::Mutex::Lock lm (_smf_lock);
461
462         assert(_smf_track);
463         smf_track_delete(_smf_track);
464
465         _smf_track = smf_track_new();
466         assert(_smf_track);
467
468         smf_add_track(_smf, _smf_track);
469         assert(_smf->number_of_tracks == 1);
470 }
471
472 void
473 SMF::end_write(string const & path)
474 {
475         Glib::Threads::Mutex::Lock lm (_smf_lock);
476
477         if (!_smf) {
478                 return;
479         }
480
481         FILE* f = g_fopen (path.c_str(), "w+");
482         if (f == 0) {
483                 throw FileError (path);
484         }
485
486         if (smf_save(_smf, f) != 0) {
487                 fclose(f);
488                 throw FileError (path);
489         }
490
491         fclose(f);
492 }
493
494 double
495 SMF::round_to_file_precision (double val) const
496 {
497         double div = ppqn();
498
499         return round (val * div) / div;
500 }
501
502 void
503 SMF::track_names(vector<string>& names) const
504 {
505         if (!_smf) {
506                 return;
507         }
508
509         names.clear ();
510
511         Glib::Threads::Mutex::Lock lm (_smf_lock);
512
513         for (uint16_t n = 0; n < _smf->number_of_tracks; ++n) {
514                 smf_track_t* trk = smf_get_track_by_number (_smf, n+1);
515                 if (!trk) {
516                         names.push_back (string());
517                 } else {
518                         if (trk->name) {
519                                 names.push_back (trk->name);
520                         } else {
521                                 names.push_back (string());
522                         }
523                 }
524         }
525 }
526
527 void
528 SMF::instrument_names(vector<string>& names) const
529 {
530         if (!_smf) {
531                 return;
532         }
533
534         names.clear ();
535
536         Glib::Threads::Mutex::Lock lm (_smf_lock);
537
538         for (uint16_t n = 0; n < _smf->number_of_tracks; ++n) {
539                 smf_track_t* trk = smf_get_track_by_number (_smf, n+1);
540                 if (!trk) {
541                         names.push_back (string());
542                 } else {
543                         if (trk->instrument) {
544                                 names.push_back (trk->instrument);
545                         } else {
546                                 names.push_back (string());
547                         }
548                 }
549         }
550 }
551
552 SMF::Tempo::Tempo (smf_tempo_t* smft)
553         : time_pulses (smft->time_pulses)
554         , time_seconds (smft->time_seconds)
555         , microseconds_per_quarter_note (smft->microseconds_per_quarter_note)
556         , numerator (smft->numerator)
557         , denominator (smft->denominator)
558         , clocks_per_click (smft->clocks_per_click)
559         , notes_per_note (smft->notes_per_note)
560 {
561 }
562
563 int
564 SMF::num_tempos () const
565 {
566         assert (_smf);
567         return smf_get_tempo_count (_smf);
568 }
569
570 SMF::Tempo*
571 SMF::tempo_at_smf_pulse (size_t smf_pulse) const
572 {
573         smf_tempo_t* t = smf_get_tempo_by_seconds (_smf, smf_pulse);
574         if (!t) {
575                 return 0;
576         }
577         return new Tempo (t);
578 }
579
580 SMF::Tempo*
581 SMF::tempo_at_seconds (double seconds) const
582 {
583         smf_tempo_t* t = smf_get_tempo_by_seconds (_smf, seconds);
584         if (!t) {
585                 return 0;
586         }
587         return new Tempo (t);
588 }
589
590 SMF::Tempo*
591 SMF::nth_tempo (size_t n) const
592 {
593         assert (_smf);
594
595         smf_tempo_t* t = smf_get_tempo_by_number (_smf, n);
596         if (!t) {
597                 return 0;
598         }
599
600         return new Tempo (t);
601 }
602
603 } // namespace Evoral