ae3c8781a53976c49173f463e4806fb406c57d43
[ardour.git] / libs / evoral / src / SMF.cpp
1 /* This file is part of Evoral.
2  * Copyright (C) 2008 Dave 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 #define __STDC_LIMIT_MACROS 1
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 #include "pbd/file_manager.h"
30
31 using namespace std;
32
33 namespace Evoral {
34
35 SMF::~SMF()
36 {
37         if (_smf) {
38                 smf_delete(_smf);
39                 _smf = 0;
40                 _smf_track = 0;
41         }
42 }
43
44 uint16_t
45 SMF::num_tracks() const
46 {
47         return _smf->number_of_tracks;
48 }
49
50 uint16_t
51 SMF::ppqn() const
52 {
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         _smf_track = smf_get_track_by_number(_smf, track);
63         if (_smf_track != NULL) {
64                 _smf_track->next_event_number = (_smf_track->number_of_events == 0) ? 0 : 1;
65                 return 0;
66         } else {
67                 return -1;
68         }
69 }
70
71 /** Attempt to open the SMF file for reading and/or writing.
72  *
73  * \return  0 on success
74  *         -1 if the file can not be opened or created
75  *         -2 if the file exists but specified track does not exist
76  */
77 int
78 SMF::open(const std::string& path, int track) THROW_FILE_ERROR
79 {
80         assert(track >= 1);
81         if (_smf) {
82                 smf_delete(_smf);
83         }
84
85         _file_path = path;
86
87         PBD::StdioFileDescriptor d (_file_path, "r");
88         FILE* f = d.allocate ();
89         if (f == 0) {
90                 return -1;
91         }
92         
93         if ((_smf = smf_load (f)) == 0) {
94                 return -1;
95         }
96
97         if ((_smf_track = smf_get_track_by_number(_smf, track)) == 0) {
98                 return -2;
99         }
100
101         //cerr << "Track " << track << " # events: " << _smf_track->number_of_events << endl;
102         if (_smf_track->number_of_events == 0) {
103                 _smf_track->next_event_number = 0;
104                 _empty = true;
105         } else {
106                 _smf_track->next_event_number = 1;
107                 _empty = false;
108         }
109
110         return 0;
111 }
112
113
114 /** Attempt to create a new SMF file for reading and/or writing.
115  *
116  * \return  0 on success
117  *         -1 if the file can not be created
118  *         -2 if the track can not be created
119  */
120 int
121 SMF::create(const std::string& path, int track, uint16_t ppqn) THROW_FILE_ERROR
122 {
123         assert(track >= 1);
124         if (_smf) {
125                 smf_delete(_smf);
126         }
127
128         _file_path = path;
129
130         _smf = smf_new();
131         if (smf_set_ppqn(_smf, ppqn) != 0) {
132                 throw FileError();
133         }
134
135         if (_smf == NULL) {
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         _empty = true;
151
152         return 0;
153 }
154
155 void
156 SMF::close() THROW_FILE_ERROR
157 {
158         if (_smf) {
159 #if 0
160                 /* XXX why would we automatically save-on-close? 
161                  */
162
163                 PBD::StdioFileDescriptor d (_file_path, "w+");
164                 FILE* f = d.allocate ();
165                 if (f == 0) {
166                         throw FileError ();
167                 }
168                 
169                 cerr << "CLOSE: Save SMF to " << _file_path << endl;
170
171                 if (smf_save(_smf, f) != 0) {
172                         throw FileError();
173                 }
174 #endif
175                 smf_delete(_smf);
176                 _smf = 0;
177                 _smf_track = 0;
178         }
179 }
180
181 void
182 SMF::seek_to_start() const
183 {
184         _smf_track->next_event_number = 1;
185 }
186
187 static void
188 midify_note_id (event_id_t note_id, uint8_t* buf)
189 {
190         buf[0] = (note_id & 0xfe000000) >> 25;
191         buf[1] = (note_id & 0x01fc0000) >> 18;
192         buf[2] = (note_id & 0x0003f800) >> 11;
193         buf[3] = (note_id & 0x000007f0) >> 4;
194         buf[4] = (note_id & 0x0000000f);
195 }
196
197 static event_id_t
198 unmidify_note_id (uint8_t* buf)
199 {
200         return ((int) buf[0] << 25) | ((int) buf[1] << 18) | ((int) buf[2] << 11) | ((int)buf[3] << 4) | (int) buf[4];
201 }
202
203 /** Read an event from the current position in file.
204  *
205  * File position MUST be at the beginning of a delta time, or this will die very messily.
206  * ev.buffer must be of size ev.size, and large enough for the event.  The returned event
207  * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
208  * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
209  *
210  * \a buf must be a pointer to a buffer allocated with malloc, or a pointer to NULL.
211  * \a size must be the capacity of \a buf.  If it is not large enough, \a buf will
212  * be reallocated and *size will be set to the new size of buf.
213  *
214  * if the event is a meta-event and is an Evoral Note ID, then \a note_id will be set
215  * to the value of the NoteID; otherwise, meta-events will set \a note_id to -1.
216  *
217  * \return event length (including status byte) on success, 0 if event was
218  * a meta event, or -1 on EOF (or end of track).
219  */
220 int
221 SMF::read_event(uint32_t* delta_t, uint32_t* size, uint8_t** buf, event_id_t* note_id) const
222 {
223         smf_event_t* event;
224
225         assert(delta_t);
226         assert(size);
227         assert(buf);
228         assert(note_id);
229
230         if ((event = smf_track_get_next_event(_smf_track)) != NULL) {
231
232                 *delta_t = event->delta_time_pulses;
233
234                 if (smf_event_is_metadata(event)) {
235                         *note_id = -1; // "no note id in this meta-event */
236                         if (event->midi_buffer[1] == 0x99) { // Evoral meta-event
237                                 if (event->midi_buffer[2] == 6) { // 6 bytes following
238                                         if (event->midi_buffer[3] == 0x1) { // Evoral Note ID
239                                                 *note_id = unmidify_note_id  (&event->midi_buffer[4]);
240                                                 cerr << "Loaded Event ID " << *note_id << endl;
241                                         }
242                                 }
243                         }
244                         return 0; /* this is a meta-event */
245                 }
246
247                 int event_size = event->midi_buffer_length;
248                 assert(event_size > 0);
249
250                 // Make sure we have enough scratch buffer
251                 if (*size < (unsigned)event_size) {
252                         *buf = (uint8_t*)realloc(*buf, event_size);
253                 }
254                 memcpy(*buf, event->midi_buffer, size_t(event_size));
255                 *size = event_size;
256
257                 assert(midi_event_is_valid(*buf, *size));
258
259                 /* printf("SMF::read_event @ %u: ", *delta_t);
260                 for (size_t i = 0; i < *size; ++i) {
261                         printf("%X ", (*buf)[i]);
262                 } printf("\n") */
263
264                 return event_size;
265         } else {
266                 return -1;
267         }
268 }
269
270 void
271 SMF::append_event_delta(uint32_t delta_t, uint32_t size, const uint8_t* buf, event_id_t note_id)
272 {
273         if (size == 0) {
274                 return;
275         }
276
277         /* printf("SMF::append_event_delta @ %u:", delta_t);
278         for (size_t i = 0; i < size; ++i) {
279                 printf("%X ", buf[i]);
280         } printf("\n"); */
281
282         if (!midi_event_is_valid(buf, size)) {
283                 cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
284                 return;
285         }
286
287         smf_event_t* event;
288
289         /* XXX july 2010: currently only store event ID's for notes
290          */
291
292         if (((buf[0] & 0xf0) == MIDI_CMD_NOTE_ON || ((buf[0] & 0xf0) == MIDI_CMD_NOTE_OFF)) && note_id >= 0) {
293                 event = smf_event_new ();
294                 assert(event != NULL);
295
296                 event->midi_buffer = new uint8_t[9];
297                 event->midi_buffer_length = 9;
298
299                 event->midi_buffer[0] = 0xff; // Meta-event
300                 event->midi_buffer[1] = 0x99; // Evoral meta-event
301                 event->midi_buffer[2] = 6;    // 6 bytes of data follow */
302                 event->midi_buffer[3] = 0x1;  // Evoral Note ID
303                 midify_note_id (note_id, &event->midi_buffer[4]);
304
305                 assert(_smf_track);
306                 smf_track_add_event_delta_pulses(_smf_track, event, 0);
307         } 
308
309         event = smf_event_new_from_pointer(buf, size);
310         assert(event != NULL);
311
312         assert(_smf_track);
313         smf_track_add_event_delta_pulses(_smf_track, event, delta_t);
314         _empty = false;
315 }
316
317 void
318 SMF::begin_write()
319 {
320         assert(_smf_track);
321         smf_track_delete(_smf_track);
322
323         _smf_track = smf_track_new();
324         assert(_smf_track);
325
326         smf_add_track(_smf, _smf_track);
327         assert(_smf->number_of_tracks == 1);
328 }
329
330 void
331 SMF::end_write() THROW_FILE_ERROR
332 {
333         PBD::StdioFileDescriptor d (_file_path, "w+");
334         FILE* f = d.allocate ();
335         if (f == 0) {
336                 throw FileError ();
337         }
338
339         if (smf_save(_smf, f) != 0) {
340                 throw FileError();
341         }
342 }
343
344 double
345 SMF::round_to_file_precision (double val) const
346 {
347         double div = ppqn();
348
349         return round (val * div) / div;
350 }
351
352 void
353 SMF::set_path (const std::string& p)
354 {
355         _file_path = p;
356 }
357
358 } // namespace Evoral