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