Sync with http://svn.drobilla.net/lad/trunk/evoral r1891.
[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  * 
5  * Evoral is free software; you can redistribute it and/or modify it under the
6  * terms of the GNU General Public License as published by the Free Software
7  * Foundation; either version 2 of the License, or (at your option) any later
8  * version.
9  * 
10  * Evoral is distributed in the hope that it will be useful, but WITHOUT ANY
11  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
13  * 
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <errno.h>
22 #include <string.h>
23 #include <cassert>
24 #include <iostream>
25 #include <glibmm/miscutils.h>
26 #include "evoral/midi_util.h"
27 #include "evoral/SMF.hpp"
28 #include "evoral/SMFReader.hpp"
29 #include "evoral/Event.hpp"
30
31 using namespace std;
32
33 namespace Evoral {
34
35 SMF::SMF()
36         : _fd(0)
37         , _last_ev_time(0)
38         , _track_size(4) // 4 bytes for the ever-present EOT event
39         , _header_size(22)
40         , _empty(true)
41 {
42 }
43
44 SMF::~SMF()
45 {
46 }
47
48 /** Attempt to open the SMF file for reading and writing.
49  *
50  * Currently SMF is always read/write.
51  *
52  * \return  0 on success
53  *         -1 if the file can not be opened for reading,
54  *         -2 if the file can not be opened for writing
55  */
56 int
57 SMF::open(const std::string& path)
58 {
59         //cerr << "Opening SMF file " << path() << " writeable: " << writable() << endl;
60         _fd = fopen(path.c_str(), "r+");
61
62         // File already exists
63         if (_fd) {
64                 fseek(_fd, _header_size - 4, 0);
65                 uint32_t track_size_be = 0;
66                 fread(&track_size_be, 4, 1, _fd);
67                 _track_size = GUINT32_FROM_BE(track_size_be);
68                 _empty = _track_size > 4;
69                 //cerr << "SMF - read track size " << _track_size << endl;
70
71         // We're making a new file
72         } else {
73                 _fd = fopen(path.c_str(), "w+");
74                 if (_fd == NULL) {
75                         cerr << "ERROR: Can not open SMF file " << path << " for writing: " <<
76                                 strerror(errno) << endl;
77                         return -2;
78                 }
79                 _track_size = 4;
80                 _empty = true;
81
82                 // Write a tentative header just to pad things out so writing happens in the right spot
83                 flush_header();
84                 flush_footer();
85         }
86                 
87         return (_fd == 0) ? -1 : 0;
88 }
89
90 void
91 SMF::close()
92 {
93         if (_fd) {
94                 flush_header();
95                 flush_footer();
96                 fclose(_fd);
97                 _fd = NULL;
98         }
99 }
100
101 void
102 SMF::seek_to_start() const
103 {
104         fseek(_fd, _header_size, SEEK_SET);
105 }
106
107 void
108 SMF::seek_to_footer_position()
109 {
110         uint8_t buffer[4];
111         
112         // Check if there is a track end marker at the end of the data
113         fseek(_fd, -4, SEEK_END);
114         size_t read_bytes = fread(buffer, sizeof(uint8_t), 4, _fd);
115
116         if ((read_bytes == 4)
117                         && buffer[0] == 0x00
118                         && buffer[1] == 0xFF
119                         && buffer[2] == 0x2F
120                         && buffer[3] == 0x00) {
121                 // there is one, so overwrite it
122                 fseek(_fd, -4, SEEK_END);
123         } else {
124                 // there is none, so append
125                 fseek(_fd, 0, SEEK_END);
126         }
127 }
128
129 void
130 SMF::flush()
131 {
132         fflush(_fd);
133 }
134
135 int
136 SMF::flush_header()
137 {
138         // FIXME: write timeline position somehow?
139         
140         //cerr << path() << " SMF Flushing header\n";
141
142         assert(_fd);
143
144         const uint16_t type     = GUINT16_TO_BE(0);     // SMF Type 0 (single track)
145         const uint16_t ntracks  = GUINT16_TO_BE(1);     // Number of tracks (always 1 for Type 0)
146         const uint16_t division = GUINT16_TO_BE(_ppqn); // Pulses per quarter note (beat)
147
148         char data[6];
149         memcpy(data, &type, 2);
150         memcpy(data+2, &ntracks, 2);
151         memcpy(data+4, &division, 2);
152
153         //_fd = freopen(path().c_str(), "r+", _fd);
154         //assert(_fd);
155         fseek(_fd, 0, SEEK_SET);
156         write_chunk("MThd", 6, data);
157         write_chunk_header("MTrk", _track_size); 
158
159         fflush(_fd);
160
161         return 0;
162 }
163
164 int
165 SMF::flush_footer()
166 {
167         //cerr << path() << " SMF Flushing footer\n";
168         seek_to_footer_position();
169         write_footer();
170         seek_to_footer_position();
171
172         return 0;
173 }
174
175 void
176 SMF::write_footer()
177 {
178         write_var_len(0);
179         char eot[3] = { 0xFF, 0x2F, 0x00 }; // end-of-track meta-event
180         fwrite(eot, 1, 3, _fd);
181         fflush(_fd);
182 }
183
184
185 /** Read an event from the current position in file.
186  *
187  * File position MUST be at the beginning of a delta time, or this will die very messily.
188  * ev.buffer must be of size ev.size, and large enough for the event.  The returned event
189  * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
190  * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
191  *
192  * \a size should be the capacity of \a buf.  If it is not large enough, \a buf will
193  * be freed and a new buffer allocated in its place, the size of which will be placed
194  * in size.
195  *
196  * Returns event length (including status byte) on success, 0 if event was
197  * skipped (eg a meta event), or -1 on EOF (or end of track).
198  */
199 int
200 SMF::read_event(uint32_t* delta_t, uint32_t* size, uint8_t** buf) const
201 {
202         if (feof(_fd)) {
203                 return -1;
204         }
205
206         assert(delta_t);
207         assert(size);
208         assert(buf);
209
210         try {
211                 *delta_t = SMFReader::read_var_len(_fd);
212         } catch (...) {
213                 return -1; // Premature EOF
214         }
215         
216         if (feof(_fd)) {
217                 return -1; // Premature EOF
218         }
219
220         const int status = fgetc(_fd);
221
222         if (status == EOF) {
223                 return -1; // Premature EOF
224         }
225
226         //printf("Status @ %X = %X\n", (unsigned)ftell(_fd) - 1, status);
227
228         if (status == 0xFF) {
229                 if (feof(_fd)) {
230                         return -1; // Premature EOF
231                 }
232                 const int type = fgetc(_fd);
233                 if ((unsigned char)type == 0x2F) {
234                         return -1; // hit end of track
235                 } else {
236                         *size = 0;
237                         return 0;
238                 }
239         }
240         
241         const int event_size = midi_event_size((unsigned char)status) + 1;
242         if (event_size <= 0) {
243                 *size = 0;
244                 return 0;
245         }
246         
247         // Make sure we have enough scratch buffer
248         if (*size < (unsigned)event_size)
249                 *buf = (uint8_t*)realloc(*buf, event_size);
250         
251         *size = event_size;
252
253         (*buf)[0] = (unsigned char)status;
254         if (event_size > 1)
255                 fread((*buf) + 1, 1, *size - 1, _fd);
256
257         /*printf("SMF %s read event: delta = %u, size = %u, data = ", _name.c_str(), *delta_t, *size);
258         for (size_t i=0; i < *size; ++i) {
259                 printf("%X ", (*buf)[i]);
260         }
261         printf("\n");*/
262         
263         return (int)*size;
264 }
265
266 void
267 SMF::append_event_unlocked(uint32_t delta_t, const Evoral::Event& ev)
268 {
269         if (ev.size() == 0)
270                 return;
271
272         const size_t stamp_size = write_var_len(delta_t);
273         fwrite(ev.buffer(), 1, ev.size(), _fd);
274
275         _track_size += stamp_size + ev.size();
276         _last_ev_time = ev.time();
277
278         if (ev.size() > 0)
279                 _empty = false;
280 }
281
282 void
283 SMF::begin_write(FrameTime start_frame)
284 {
285         _last_ev_time = 0;
286         fseek(_fd, _header_size, SEEK_SET);
287 }
288
289 void
290 SMF::end_write()
291 {
292         flush_header();
293         flush_footer();
294 }
295
296 void
297 SMF::write_chunk_header(const char id[4], uint32_t length)
298 {
299         const uint32_t length_be = GUINT32_TO_BE(length);
300
301         fwrite(id, 1, 4, _fd);
302         fwrite(&length_be, 4, 1, _fd);
303 }
304
305 void
306 SMF::write_chunk(const char id[4], uint32_t length, void* data)
307 {
308         write_chunk_header(id, length);
309         
310         fwrite(data, 1, length, _fd);
311 }
312
313 /** Returns the size (in bytes) of the value written. */
314 size_t
315 SMF::write_var_len(uint32_t value)
316 {
317         size_t ret = 0;
318
319         uint32_t buffer = value & 0x7F;
320
321         while ( (value >>= 7) ) {
322                 buffer <<= 8;
323                 buffer |= ((value & 0x7F) | 0x80);
324         }
325
326         while (true) {
327                 //printf("Writing var len byte %X\n", (unsigned char)buffer);
328                 ++ret;
329                 fputc(buffer, _fd);
330                 if (buffer & 0x80)
331                         buffer >>= 8;
332                 else
333                         break;
334         }
335
336         return ret;
337 }
338
339 } // namespace Evoral