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