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