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>
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.
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.
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.
29 #include <glib/gstdio.h>
31 #include "libsmf/smf.h"
33 #include "evoral/Event.h"
34 #include "evoral/SMF.h"
35 #include "evoral/midi_util.h"
38 extern double round(double x);
58 SMF::num_tracks() const
60 Glib::Threads::Mutex::Lock lm (_smf_lock);
61 return _smf ? _smf->number_of_tracks : 0;
67 Glib::Threads::Mutex::Lock lm (_smf_lock);
71 /** Seek to the specified track (1-based indexing)
72 * \return 0 on success
75 SMF::seek_to_track(int track)
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;
87 /** Attempt to open the SMF file just to see if it is valid.
89 * \return true on success
93 SMF::test(const std::string& path)
95 FILE* f = g_fopen(path.c_str(), "r");
100 smf_t* test_smf = smf_load(f);
107 smf_delete(test_smf);
112 /** Attempt to open the SMF file for reading and/or writing.
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
119 SMF::open(const std::string& path, int track)
121 Glib::Threads::Mutex::Lock lm (_smf_lock);
124 _type0channels.clear ();
131 FILE* f = g_fopen(path.c_str(), "r");
134 } else if ((_smf = smf_load(f)) == 0) {
137 } else if ((_smf_track = smf_get_track_by_number(_smf, track)) == 0) {
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;
147 _smf_track->next_event_number = 1;
154 if (_smf->format == 0 && _smf->number_of_tracks == 1 && !_empty) {
155 // type-0 file: scan file for # of used channels.
157 uint32_t delta_t = 0;
160 event_id_t event_id = 0;
162 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
169 uint8_t type = buf[0] & 0xf0;
170 uint8_t chan = buf[0] & 0x0f;
171 if (type < 0x80 || type > 0xE0) {
174 _type0channels.insert(chan);
183 /** Attempt to create a new SMF file for reading and/or writing.
185 * \return 0 on success
186 * -1 if the file can not be created
187 * -2 if the track can not be created
190 SMF::create(const std::string& path, int track, uint16_t ppqn)
192 Glib::Threads::Mutex::Lock lm (_smf_lock);
205 if (smf_set_ppqn(_smf, ppqn) != 0) {
209 for (int i = 0; i < track; ++i) {
210 _smf_track = smf_track_new();
214 smf_add_track(_smf, _smf_track);
217 _smf_track = smf_get_track_by_number(_smf, track);
221 _smf_track->next_event_number = 0;
224 /* put a stub file on disk */
226 FILE* f = g_fopen (path.c_str(), "w+");
231 if (smf_save (_smf, f)) {
240 _type0channels.clear ();
248 Glib::Threads::Mutex::Lock lm (_smf_lock);
255 _type0channels.clear ();
260 SMF::seek_to_start() const
262 Glib::Threads::Mutex::Lock lm (_smf_lock);
264 _smf_track->next_event_number = std::min(_smf_track->number_of_events, (size_t)1);
266 cerr << "WARNING: SMF seek_to_start() with no track" << endl;
270 /** Read an event from the current position in file.
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).
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.
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.
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).
288 SMF::read_event(uint32_t* delta_t, uint32_t* size, uint8_t** buf, event_id_t* note_id) const
290 Glib::Threads::Mutex::Lock lm (_smf_lock);
299 if ((event = smf_track_get_next_event(_smf_track)) != NULL) {
301 *delta_t = event->delta_time_pulses;
303 if (smf_event_is_metadata(event)) {
304 *note_id = -1; // "no note id in this meta-event */
306 if (event->midi_buffer[1] == 0x7f) { // Sequencer-specific
311 if (smf_extract_vlq (&event->midi_buffer[2], event->midi_buffer_length-2, &evsize, &lenlen) == 0) {
313 if (event->midi_buffer[2+lenlen] == 0x99 && // Evoral
314 event->midi_buffer[3+lenlen] == 0x1) { // Evoral Note ID
319 if (smf_extract_vlq (&event->midi_buffer[4+lenlen], event->midi_buffer_length-(4+lenlen), &id, &idlen) == 0) {
325 return 0; /* this is a meta-event */
328 int event_size = event->midi_buffer_length;
329 assert(event_size > 0);
331 // Make sure we have enough scratch buffer
332 if (*size < (unsigned)event_size) {
333 *buf = (uint8_t*)realloc(*buf, event_size);
336 memcpy(*buf, event->midi_buffer, size_t(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 */
344 if (!midi_event_is_valid(*buf, *size)) {
345 cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
350 /* printf("SMF::read_event @ %u: ", *delta_t);
351 for (size_t i = 0; i < *size; ++i) {
352 printf("%X ", (*buf)[i]);
362 SMF::append_event_delta(uint32_t delta_t, uint32_t size, const uint8_t* buf, event_id_t note_id)
364 Glib::Threads::Mutex::Lock lm (_smf_lock);
370 /* printf("SMF::append_event_delta @ %u:", delta_t);
371 for (size_t i = 0; i < size; ++i) {
372 printf("%X ", buf[i]);
390 /* System Real Time or System Common event: not valid in SMF
395 if (!midi_event_is_valid(buf, size)) {
396 cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
402 /* XXX july 2010: currently only store event ID's for notes, program changes and bank changes
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))
414 if (store_id && note_id >= 0) {
420 event = smf_event_new ();
421 assert(event != NULL);
423 /* generate VLQ representation of note ID */
424 idlen = smf_format_vlq (idbuf, sizeof(idbuf), note_id);
426 /* generate VLQ representation of meta event length,
427 which is the idlen + 2 bytes (Evoral type ID plus Note ID type)
430 lenlen = smf_format_vlq (lenbuf, sizeof(lenbuf), idlen+2);
432 event->midi_buffer_length = 2 + lenlen + 2 + idlen;
433 /* this should be allocated by malloc(3) because libsmf will
436 event->midi_buffer = (uint8_t*) malloc (sizeof(uint8_t) * event->midi_buffer_length);
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);
446 smf_track_add_event_delta_pulses(_smf_track, event, 0);
449 event = smf_event_new_from_pointer(buf, size);
450 assert(event != NULL);
453 smf_track_add_event_delta_pulses(_smf_track, event, delta_t);
460 Glib::Threads::Mutex::Lock lm (_smf_lock);
463 smf_track_delete(_smf_track);
465 _smf_track = smf_track_new();
468 smf_add_track(_smf, _smf_track);
469 assert(_smf->number_of_tracks == 1);
473 SMF::end_write(string const & path)
475 Glib::Threads::Mutex::Lock lm (_smf_lock);
481 FILE* f = g_fopen (path.c_str(), "w+");
483 throw FileError (path);
486 if (smf_save(_smf, f) != 0) {
488 throw FileError (path);
495 SMF::round_to_file_precision (double val) const
499 return round (val * div) / div;
503 SMF::track_names(vector<string>& names) const
511 Glib::Threads::Mutex::Lock lm (_smf_lock);
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);
516 names.push_back (string());
519 names.push_back (trk->name);
521 names.push_back (string());
528 SMF::instrument_names(vector<string>& names) const
536 Glib::Threads::Mutex::Lock lm (_smf_lock);
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);
541 names.push_back (string());
543 if (trk->instrument) {
544 names.push_back (trk->instrument);
546 names.push_back (string());
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)
564 SMF::num_tempos () const
567 return smf_get_tempo_count (_smf);
571 SMF::tempo_at_smf_pulse (size_t smf_pulse) const
573 smf_tempo_t* t = smf_get_tempo_by_seconds (_smf, smf_pulse);
577 return new Tempo (t);
581 SMF::tempo_at_seconds (double seconds) const
583 smf_tempo_t* t = smf_get_tempo_by_seconds (_smf, seconds);
587 return new Tempo (t);
591 SMF::nth_tempo (size_t n) const
595 smf_tempo_t* t = smf_get_tempo_by_number (_smf, n);
600 return new Tempo (t);
603 } // namespace Evoral