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