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