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