edf33c23f20bce3a598fd63b31ec602a34065417
[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 #include "libsmf/smf.h"
26 #include "evoral/Event.hpp"
27 #include "evoral/SMF.hpp"
28 #include "evoral/midi_util.h"
29
30 #ifdef COMPILER_MSVC
31 extern double round(double x);
32 #endif
33
34 using namespace std;
35
36 namespace Evoral {
37
38 SMF::~SMF()
39 {
40         close ();
41 }
42
43 uint16_t
44 SMF::num_tracks() const
45 {
46         Glib::Threads::Mutex::Lock lm (_smf_lock);
47         return _smf ? _smf->number_of_tracks : 0;
48 }
49
50 uint16_t
51 SMF::ppqn() const
52 {
53         Glib::Threads::Mutex::Lock lm (_smf_lock);
54         return _smf->ppqn;
55 }
56
57 /** Seek to the specified track (1-based indexing)
58  * \return 0 on success
59  */
60 int
61 SMF::seek_to_track(int track)
62 {
63         Glib::Threads::Mutex::Lock lm (_smf_lock);
64         _smf_track = smf_get_track_by_number(_smf, track);
65         if (_smf_track != NULL) {
66                 _smf_track->next_event_number = (_smf_track->number_of_events == 0) ? 0 : 1;
67                 return 0;
68         } else {
69                 return -1;
70         }
71 }
72
73 /** Attempt to open the SMF file just to see if it is valid.
74  *
75  * \return  true on success
76  *          false on failure
77  */
78 bool
79 SMF::test(const std::string& path)
80 {
81         FILE* f = fopen(path.c_str(), "r");
82         if (f == 0) {
83                 return false;
84         }
85
86         smf_t* test_smf = smf_load(f);
87         fclose(f);
88
89         const bool success = (test_smf != NULL);
90         smf_delete(test_smf);
91
92         return success;
93 }
94
95 /** Attempt to open the SMF file for reading and/or writing.
96  *
97  * \return  0 on success
98  *         -1 if the file can not be opened or created
99  *         -2 if the file exists but specified track does not exist
100  */
101 int
102 SMF::open(const std::string& path, int track) THROW_FILE_ERROR
103 {
104         Glib::Threads::Mutex::Lock lm (_smf_lock);
105
106         assert(track >= 1);
107         if (_smf) {
108                 smf_delete(_smf);
109         }
110
111         _file_path = path;
112
113         FILE* f = fopen(_file_path.c_str(), "r");
114         if (f == 0) {
115                 return -1;
116         } else if ((_smf = smf_load(f)) == 0) {
117                 fclose(f);
118                 return -1;
119         } else if ((_smf_track = smf_get_track_by_number(_smf, track)) == 0) {
120                 fclose(f);
121                 return -2;
122         }
123
124         //cerr << "Track " << track << " # events: " << _smf_track->number_of_events << endl;
125         if (_smf_track->number_of_events == 0) {
126                 _smf_track->next_event_number = 0;
127                 _empty = true;
128         } else {
129                 _smf_track->next_event_number = 1;
130                 _empty = false;
131         }
132
133         fclose(f);
134         return 0;
135 }
136
137
138 /** Attempt to create a new SMF file for reading and/or writing.
139  *
140  * \return  0 on success
141  *         -1 if the file can not be created
142  *         -2 if the track can not be created
143  */
144 int
145 SMF::create(const std::string& path, int track, uint16_t ppqn) THROW_FILE_ERROR
146 {
147         Glib::Threads::Mutex::Lock lm (_smf_lock);
148
149         assert(track >= 1);
150         if (_smf) {
151                 smf_delete(_smf);
152         }
153
154         _file_path = path;
155
156         _smf = smf_new();
157
158         if (_smf == NULL) {
159                 return -1;
160         }
161
162         if (smf_set_ppqn(_smf, ppqn) != 0) {
163                 return -1;
164         }
165
166         for (int i = 0; i < track; ++i) {
167                 _smf_track = smf_track_new();
168                 if (!_smf_track) {
169                         return -2;
170                 }
171                 smf_add_track(_smf, _smf_track);
172         }
173
174         _smf_track = smf_get_track_by_number(_smf, track);
175         if (!_smf_track)
176                 return -2;
177
178         _smf_track->next_event_number = 0;
179
180         {
181                 /* put a stub file on disk */
182
183                 FILE* f = fopen (_file_path.c_str(), "w+");
184                 if (f == 0) {
185                         return -1;
186                 }
187
188                 if (smf_save (_smf, f)) {
189                         fclose (f);
190                         return -1;
191                 }
192                 fclose (f);
193         }
194
195         _empty = true;
196
197         return 0;
198 }
199
200 void
201 SMF::close() THROW_FILE_ERROR
202 {
203         Glib::Threads::Mutex::Lock lm (_smf_lock);
204
205         if (_smf) {
206                 smf_delete(_smf);
207                 _smf = 0;
208                 _smf_track = 0;
209         }
210 }
211
212 void
213 SMF::seek_to_start() const
214 {
215         Glib::Threads::Mutex::Lock lm (_smf_lock);
216         if (_smf_track) {
217                 _smf_track->next_event_number = std::min(_smf_track->number_of_events, (size_t)1);
218         } else {
219                 cerr << "WARNING: SMF seek_to_start() with no track" << endl;
220         }
221 }
222
223 /** Read an event from the current position in file.
224  *
225  * File position MUST be at the beginning of a delta time, or this will die very messily.
226  * ev.buffer must be of size ev.size, and large enough for the event.  The returned event
227  * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
228  * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
229  *
230  * \a buf must be a pointer to a buffer allocated with malloc, or a pointer to NULL.
231  * \a size must be the capacity of \a buf.  If it is not large enough, \a buf will
232  * be reallocated and *size will be set to the new size of buf.
233  *
234  * if the event is a meta-event and is an Evoral Note ID, then \a note_id will be set
235  * to the value of the NoteID; otherwise, meta-events will set \a note_id to -1.
236  *
237  * \return event length (including status byte) on success, 0 if event was
238  * a meta event, or -1 on EOF (or end of track).
239  */
240 int
241 SMF::read_event(uint32_t* delta_t, uint32_t* size, uint8_t** buf, event_id_t* note_id) const
242 {
243         Glib::Threads::Mutex::Lock lm (_smf_lock);
244
245         smf_event_t* event;
246
247         assert(delta_t);
248         assert(size);
249         assert(buf);
250         assert(note_id);
251
252         if ((event = smf_track_get_next_event(_smf_track)) != NULL) {
253
254                 *delta_t = event->delta_time_pulses;
255
256                 if (smf_event_is_metadata(event)) {
257                         *note_id = -1; // "no note id in this meta-event */
258
259                         if (event->midi_buffer[1] == 0x7f) { // Sequencer-specific
260
261                                 uint32_t evsize;
262                                 uint32_t lenlen;
263
264                                 if (smf_extract_vlq (&event->midi_buffer[2], event->midi_buffer_length-2, &evsize, &lenlen) == 0) {
265
266                                         if (event->midi_buffer[2+lenlen] == 0x99 &&  // Evoral
267                                             event->midi_buffer[3+lenlen] == 0x1) { // Evoral Note ID
268
269                                                 uint32_t id;
270                                                 uint32_t idlen;
271
272                                                 if (smf_extract_vlq (&event->midi_buffer[4+lenlen], event->midi_buffer_length-(4+lenlen), &id, &idlen) == 0) {
273                                                         *note_id = id;
274                                                 }
275                                         }
276                                 }
277                         }
278                         return 0; /* this is a meta-event */
279                 }
280
281                 int event_size = event->midi_buffer_length;
282                 assert(event_size > 0);
283
284                 // Make sure we have enough scratch buffer
285                 if (*size < (unsigned)event_size) {
286                         *buf = (uint8_t*)realloc(*buf, event_size);
287                 }
288                 memcpy(*buf, event->midi_buffer, size_t(event_size));
289                 *size = event_size;
290                 if ((*buf)[0] == 0x90 && (*buf)[2] == 0) {
291                         /* normalize note on with velocity 0 to proper note off */
292                         (*buf)[0] = 0x80;  /* note off */
293                         (*buf)[2] = 0x40;  /* default velocity */
294                 }
295
296                 if (!midi_event_is_valid(*buf, *size)) {
297                         cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
298                         *size = 0;
299                         return -1;
300                 }
301
302                 /* printf("SMF::read_event @ %u: ", *delta_t);
303                    for (size_t i = 0; i < *size; ++i) {
304                    printf("%X ", (*buf)[i]);
305                    } printf("\n") */
306
307                 return event_size;
308         } else {
309                 return -1;
310         }
311 }
312
313 void
314 SMF::append_event_delta(uint32_t delta_t, uint32_t size, const uint8_t* buf, event_id_t note_id)
315 {
316         Glib::Threads::Mutex::Lock lm (_smf_lock);
317
318         if (size == 0) {
319                 return;
320         }
321
322         /* printf("SMF::append_event_delta @ %u:", delta_t);
323            for (size_t i = 0; i < size; ++i) {
324            printf("%X ", buf[i]);
325            } printf("\n"); */
326
327         if (!midi_event_is_valid(buf, size)) {
328                 cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
329                 return;
330         }
331
332         smf_event_t* event;
333
334         /* XXX july 2010: currently only store event ID's for notes, program changes and bank changes
335          */
336
337         uint8_t const c = buf[0] & 0xf0;
338         bool const store_id = (
339                 c == MIDI_CMD_NOTE_ON ||
340                 c == MIDI_CMD_NOTE_OFF ||
341                 c == MIDI_CMD_PGM_CHANGE ||
342                 (c == MIDI_CMD_CONTROL && (buf[1] == MIDI_CTL_MSB_BANK || buf[1] == MIDI_CTL_LSB_BANK))
343                                );
344
345         if (store_id && note_id >= 0) {
346                 int idlen;
347                 int lenlen;
348                 uint8_t idbuf[16];
349                 uint8_t lenbuf[16];
350
351                 event = smf_event_new ();
352                 assert(event != NULL);
353
354                 /* generate VLQ representation of note ID */
355                 idlen = smf_format_vlq (idbuf, sizeof(idbuf), note_id);
356
357                 /* generate VLQ representation of meta event length,
358                    which is the idlen + 2 bytes (Evoral type ID plus Note ID type)
359                 */
360
361                 lenlen = smf_format_vlq (lenbuf, sizeof(lenbuf), idlen+2);
362
363                 event->midi_buffer_length = 2 + lenlen + 2 + idlen;
364                 /* this should be allocated by malloc(3) because libsmf will
365                    call free(3) on it
366                 */
367                 event->midi_buffer = (uint8_t*) malloc (sizeof(uint8_t) * event->midi_buffer_length);
368
369                 event->midi_buffer[0] = 0xff; // Meta-event
370                 event->midi_buffer[1] = 0x7f; // Sequencer-specific
371                 memcpy (&event->midi_buffer[2], lenbuf, lenlen);
372                 event->midi_buffer[2+lenlen] = 0x99; // Evoral type ID
373                 event->midi_buffer[3+lenlen] = 0x1;  // Evoral type Note ID
374                 memcpy (&event->midi_buffer[4+lenlen], idbuf, idlen);
375
376                 assert(_smf_track);
377                 smf_track_add_event_delta_pulses(_smf_track, event, 0);
378         }
379
380         event = smf_event_new_from_pointer(buf, size);
381         assert(event != NULL);
382
383         assert(_smf_track);
384         smf_track_add_event_delta_pulses(_smf_track, event, delta_t);
385         _empty = false;
386 }
387
388 void
389 SMF::begin_write()
390 {
391         Glib::Threads::Mutex::Lock lm (_smf_lock);
392
393         assert(_smf_track);
394         smf_track_delete(_smf_track);
395
396         _smf_track = smf_track_new();
397         assert(_smf_track);
398
399         smf_add_track(_smf, _smf_track);
400         assert(_smf->number_of_tracks == 1);
401 }
402
403 void
404 SMF::end_write() THROW_FILE_ERROR
405 {
406         Glib::Threads::Mutex::Lock lm (_smf_lock);
407         FILE* f = fopen (_file_path.c_str(), "w+");
408         if (f == 0) {
409                 throw FileError (_file_path);
410         }
411
412         if (smf_save(_smf, f) != 0) {
413                 fclose(f);
414                 throw FileError (_file_path);
415         }
416
417         fclose(f);
418 }
419
420 double
421 SMF::round_to_file_precision (double val) const
422 {
423         double div = ppqn();
424
425         return round (val * div) / div;
426 }
427
428 void
429 SMF::set_path (const std::string& p)
430 {
431         _file_path = p;
432 }
433
434 } // namespace Evoral