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