verbosity--
[ardour.git] / libs / evoral / src / libsmf / smf_load.c
1 /*-
2  * Copyright (c) 2007, 2008 Edward Tomasz NapieraƂa <trasz@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * ALTHOUGH THIS SOFTWARE IS MADE OF WIN AND SCIENCE, IT IS PROVIDED BY THE
15  * AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
16  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
17  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
18  * THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
20  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
21  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
23  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  */
27
28 /**
29  * \file
30  *
31  * Standard MIDI File format loader.
32  *
33  */
34
35 /* Reference: http://www.borg.com/~jglatt/tech/midifile.htm */
36
37 #include <stdlib.h>
38 #include <string.h>
39 #include <assert.h>
40 #include <math.h>
41 #include <errno.h>
42 #include <ctype.h>
43 #include <arpa/inet.h>
44 #include "smf.h"
45 #include "smf_private.h"
46
47 /**
48  * Returns pointer to the next SMF chunk in smf->buffer, based on length of the previous one.
49  * Returns NULL in case of error.
50  */
51 static struct chunk_header_struct *
52 next_chunk(smf_t *smf)
53 {
54         struct chunk_header_struct *chunk;
55         void *next_chunk_ptr;
56
57         assert(smf->file_buffer != NULL);
58         assert(smf->file_buffer_length > 0);
59         assert(smf->next_chunk_offset >= 0);
60
61         if (smf->next_chunk_offset + sizeof(struct chunk_header_struct) >= smf->file_buffer_length) {
62                 g_critical("SMF warning: no more chunks left.");
63                 return (NULL);
64         }
65
66         next_chunk_ptr = (unsigned char *)smf->file_buffer + smf->next_chunk_offset;
67
68         chunk = (struct chunk_header_struct *)next_chunk_ptr;
69
70         if (!isalpha(chunk->id[0]) || !isalpha(chunk->id[1]) || !isalpha(chunk->id[2]) || !isalpha(chunk->id[3])) {
71                 g_critical("SMF error: chunk signature contains at least one non-alphanumeric byte.");
72                 return (NULL);
73         }
74
75         /*
76          * XXX: On SPARC, after compiling with "-fast" option there will be SIGBUS here.
77          * Please compile with -xmemalign=8i".
78          */
79         smf->next_chunk_offset += sizeof(struct chunk_header_struct) + ntohl(chunk->length);
80
81         if (smf->next_chunk_offset > smf->file_buffer_length) {
82                 g_critical("SMF error: malformed chunk; truncated file?");
83                 return (NULL);
84         }
85
86         return (chunk);
87 }
88
89 /**
90  * Returns 1, iff signature of the "chunk" is the same as string passed as "signature".
91  */
92 static int
93 chunk_signature_matches(const struct chunk_header_struct *chunk, const char *signature)
94 {
95         if (!memcmp(chunk->id, signature, 4))
96                 return (1);
97
98         return (0);
99 }
100
101 /**
102  * Verifies if MThd header looks OK.  Returns 0 iff it does.
103  */
104 static int
105 parse_mthd_header(smf_t *smf)
106 {
107         int len;
108         struct chunk_header_struct *mthd, *tmp_mthd;
109
110         /* Make sure compiler didn't do anything stupid. */
111         assert(sizeof(struct chunk_header_struct) == 8);
112
113         /*
114          * We could just do "mthd = smf->file_buffer;" here, but this way we wouldn't
115          * get useful error messages.
116          */
117         if (smf->file_buffer_length < 6) {
118                 g_critical("SMF error: file is too short, it cannot be a MIDI file.");
119
120                 return (-1);
121         }
122
123         tmp_mthd = smf->file_buffer;
124
125         if (!chunk_signature_matches(tmp_mthd, "MThd")) {
126                 g_critical("SMF error: MThd signature not found, is that a MIDI file?");
127                 
128                 return (-2);
129         }
130
131         /* Ok, now use next_chunk(). */
132         mthd = next_chunk(smf);
133         if (mthd == NULL)
134                 return (-3);
135
136         assert(mthd == tmp_mthd);
137
138         len = ntohl(mthd->length);
139         if (len != 6) {
140                 g_critical("SMF error: MThd chunk length %d, must be 6.", len);
141
142                 return (-4);
143         }
144
145         return (0);
146 }
147
148 /**
149  * Parses MThd chunk, filling "smf" structure with values extracted from it.  Returns 0 iff everything went OK.
150  */
151 static int
152 parse_mthd_chunk(smf_t *smf)
153 {
154         signed char first_byte_of_division, second_byte_of_division;
155
156         struct mthd_chunk_struct *mthd;
157
158         assert(sizeof(struct mthd_chunk_struct) == 14);
159
160         if (parse_mthd_header(smf))
161                 return (1);
162
163         mthd = (struct mthd_chunk_struct *)smf->file_buffer;
164
165         smf->format = ntohs(mthd->format);
166         if (smf->format < 0 || smf->format > 2) {
167                 g_critical("SMF error: bad MThd format field value: %d, valid values are 0-2, inclusive.", smf->format);
168                 return (-1);
169         }
170
171         if (smf->format == 2) {
172                 g_critical("SMF file uses format #2, no support for that yet.");
173                 return (-2);
174         }
175
176         smf->expected_number_of_tracks = ntohs(mthd->number_of_tracks);
177         if (smf->expected_number_of_tracks <= 0) {
178                 g_critical("SMF error: bad number of tracks: %d, must be greater than zero.", smf->expected_number_of_tracks);
179                 return (-3);
180         }
181
182         /* XXX: endianess? */
183         first_byte_of_division = *((signed char *)&(mthd->division));
184         second_byte_of_division = *((signed char *)&(mthd->division) + 1);
185
186         if (first_byte_of_division >= 0) {
187                 smf->ppqn = ntohs(mthd->division);
188                 smf->frames_per_second = 0;
189                 smf->resolution = 0;
190         } else {
191                 smf->ppqn = 0;
192                 smf->frames_per_second = - first_byte_of_division;
193                 smf->resolution = second_byte_of_division;
194         }
195
196         if (smf->ppqn == 0) {
197                 g_critical("SMF file uses FPS timing instead of PPQN, no support for that yet.");
198                 return (-4);
199         }
200         
201         return (0);
202 }
203
204 /**
205  * Interprets Variable Length Quantity pointed at by "buf" and puts its value into "value" and number
206  * of bytes consumed into "len", making sure it does not read past "buf" + "buffer_length".
207  * Explanation of Variable Length Quantities is here: http://www.borg.com/~jglatt/tech/midifile/vari.htm
208  * Returns 0 iff everything went OK, different value in case of error.
209  */
210 static int
211 extract_vlq(const unsigned char *buf, const int buffer_length, int *value, int *len)
212 {
213         int val = 0;
214         const unsigned char *c = buf;
215
216         assert(buffer_length > 0);
217
218         for (;;) {
219                 if (c >= buf + buffer_length) {
220                         g_critical("End of buffer in extract_vlq().");
221                         return (-1);
222                 }
223
224                 val = (val << 7) + (*c & 0x7F);
225
226                 if (*c & 0x80)
227                         c++;
228                 else
229                         break;
230         };
231
232         *value = val;
233         *len = c - buf + 1;
234
235         if (*len > 4) {
236                 g_critical("SMF error: Variable Length Quantities longer than four bytes are not supported yet.");
237                 return (-2);
238         }
239
240         return (0);
241 }
242
243 /**
244  * Returns 1 if the given byte is a valid status byte, 0 otherwise.
245  */
246 int
247 is_status_byte(const unsigned char status)
248 {
249         return (status & 0x80);
250 }
251
252 static int
253 is_sysex_byte(const unsigned char status)
254 {
255         if (status == 0xF0)
256                 return (1);
257
258         return (0);
259 }
260
261 static int
262 is_escape_byte(const unsigned char status)
263 {
264         if (status == 0xF7)
265                 return (1);
266
267         return (0);
268 }
269
270 /**
271  * Just like expected_message_length(), but only for System Exclusive messages.
272  * Note that value returned by this thing here is the length of SysEx "on the wire",
273  * not the number of bytes that this sysex takes in the file - in SMF format sysex
274  * contains VLQ telling how many bytes it takes, "on the wire" format does not have
275  * this.
276  */
277 static int
278 expected_sysex_length(const unsigned char status, const unsigned char *second_byte, const int buffer_length, int *consumed_bytes)
279 {
280         int sysex_length, len;
281
282         assert(status == 0xF0);
283
284         if (buffer_length < 3) {
285                 g_critical("SMF error: end of buffer in expected_sysex_length().");
286                 return (-1);
287         }
288
289         extract_vlq(second_byte, buffer_length, &sysex_length, &len);
290
291         if (consumed_bytes != NULL)
292                 *consumed_bytes = len;
293
294         /* +1, because the length does not include status byte. */
295         return (sysex_length + 1);
296 }
297
298 static int
299 expected_escaped_length(const unsigned char status, const unsigned char *second_byte, const int buffer_length, int *consumed_bytes)
300 {
301         /* -1, because we do not want to account for 0x7F status. */
302         return (expected_sysex_length(status, second_byte, buffer_length, consumed_bytes) - 1);
303 }
304
305 /**
306  * Returns expected length of the midi message (including the status byte), in bytes, for the given status byte.
307  * The "second_byte" points to the expected second byte of the MIDI message.  "buffer_length" is the buffer
308  * length limit, counting from "second_byte".  Returns value < 0 iff there was an error.
309  */
310 static int
311 expected_message_length(unsigned char status, const unsigned char *second_byte, const int buffer_length)
312 {
313         /* Make sure this really is a valid status byte. */
314         assert(is_status_byte(status));
315
316         /* We cannot use this routine for sysexes. */
317         assert(!is_sysex_byte(status));
318
319         /* We cannot use this routine for escaped events. */
320         assert(!is_escape_byte(status));
321
322         /* Buffer length may be zero, for e.g. realtime messages. */
323         assert(buffer_length >= 0);
324
325         /* Is this a metamessage? */
326         if (status == 0xFF) {
327                 if (buffer_length < 2) {
328                         g_critical("SMF error: end of buffer in expected_message_length().");
329                         return (-1);
330                 }
331
332                 /*
333                  * Format of this kind of messages is like this: 0xFF 0xwhatever 0xlength and then "length" bytes.
334                  * Second byte points to this:                        ^^^^^^^^^^
335                  */
336                 return (*(second_byte + 1) + 3);
337         }
338
339         if ((status & 0xF0) == 0xF0) {
340                 switch (status) {
341                         case 0xF2: /* Song Position Pointer. */
342                                 return (3);
343
344                         case 0xF1: /* MTC Quarter Frame. */
345                         case 0xF3: /* Song Select. */
346                                 return (2);
347
348                         case 0xF6: /* Tune Request. */
349                         case 0xF8: /* MIDI Clock. */
350                         case 0xF9: /* Tick. */
351                         case 0xFA: /* MIDI Start. */
352                         case 0xFB: /* MIDI Continue. */
353                         case 0xFC: /* MIDI Stop. */
354                         case 0xFE: /* Active Sense. */
355                                 return (1);
356
357                         default:
358                                 g_critical("SMF error: unknown 0xFx-type status byte '0x%x'.", status);
359                                 return (-2);
360                 }
361         }
362
363         /* Filter out the channel. */
364         status &= 0xF0;
365
366         switch (status) {
367                 case 0x80: /* Note Off. */
368                 case 0x90: /* Note On. */
369                 case 0xA0: /* AfterTouch. */
370                 case 0xB0: /* Control Change. */
371                 case 0xE0: /* Pitch Wheel. */
372                         return (3);     
373
374                 case 0xC0: /* Program Change. */
375                 case 0xD0: /* Channel Pressure. */
376                         return (2);
377
378                 default:
379                         g_critical("SMF error: unknown status byte '0x%x'.", status);
380                         return (-3);
381         }
382 }
383
384 static int
385 extract_sysex_event(const unsigned char *buf, const int buffer_length, smf_event_t *event, int *len, int last_status)
386 {
387         int status, message_length, vlq_length;
388         const unsigned char *c = buf;
389
390         status = *buf;
391
392         assert(is_sysex_byte(status));
393
394         c++;
395
396         message_length = expected_sysex_length(status, c, buffer_length - 1, &vlq_length);
397
398         if (message_length < 0)
399                 return (-3);
400
401         c += vlq_length;
402
403         if (vlq_length + message_length >= buffer_length) {
404                 g_critical("End of buffer in extract_sysex_event().");
405                 return (-5);
406         }
407
408         event->midi_buffer_length = message_length;
409         event->midi_buffer = malloc(event->midi_buffer_length);
410         if (event->midi_buffer == NULL) {
411                 g_critical("Cannot allocate memory in extract_sysex_event(): %s", strerror(errno));
412                 return (-4);
413         }
414
415         event->midi_buffer[0] = status;
416         memcpy(event->midi_buffer + 1, c, message_length - 1);
417
418         *len = vlq_length + message_length;
419
420         return (0);
421 }
422
423 static int
424 extract_escaped_event(const unsigned char *buf, const int buffer_length, smf_event_t *event, int *len, int last_status)
425 {
426         int status, message_length, vlq_length;
427         const unsigned char *c = buf;
428
429         status = *buf;
430
431         assert(is_escape_byte(status));
432
433         c++;
434
435         message_length = expected_escaped_length(status, c, buffer_length - 1, &vlq_length);
436
437         if (message_length < 0)
438                 return (-3);
439
440         c += vlq_length;
441
442         if (vlq_length + message_length >= buffer_length) {
443                 g_critical("End of buffer in extract_escaped_event().");
444                 return (-5);
445         }
446
447         event->midi_buffer_length = message_length;
448         event->midi_buffer = malloc(event->midi_buffer_length);
449         if (event->midi_buffer == NULL) {
450                 g_critical("Cannot allocate memory in extract_escaped_event(): %s", strerror(errno));
451                 return (-4);
452         }
453
454         memcpy(event->midi_buffer, c, message_length);
455
456         if (smf_event_is_valid(event)) {
457                 g_critical("Escaped event is invalid.");
458                 return (-1);
459         }
460
461         if (smf_event_is_system_realtime(event) || smf_event_is_system_common(event)) {
462                 g_warning("Escaped event is not System Realtime nor System Common.");
463         }
464
465         *len = vlq_length + message_length;
466
467         return (0);
468 }
469
470
471 /**
472  * Puts MIDI data extracted from from "buf" into "event" and number of consumed bytes into "len".
473  * In case valid status is not found, it uses "last_status" (so called "running status").
474  * Returns 0 iff everything went OK, value < 0 in case of error.
475  */
476 static int
477 extract_midi_event(const unsigned char *buf, const int buffer_length, smf_event_t *event, int *len, int last_status)
478 {
479         int status, message_length;
480         const unsigned char *c = buf;
481
482         assert(buffer_length > 0);
483
484         /* Is the first byte the status byte? */
485         if (is_status_byte(*c)) {
486                 status = *c;
487                 c++;
488
489         } else {
490                 /* No, we use running status then. */
491                 status = last_status;
492         }
493
494         if (!is_status_byte(status)) {
495                 g_critical("SMF error: bad status byte (MSB is zero).");
496                 return (-1);
497         }
498
499         if (is_sysex_byte(status))
500                 return (extract_sysex_event(buf, buffer_length, event, len, last_status));
501
502         if (is_escape_byte(status))
503                 return (extract_escaped_event(buf, buffer_length, event, len, last_status));
504
505         /* At this point, "c" points to first byte following the status byte. */
506         message_length = expected_message_length(status, c, buffer_length - (c - buf));
507
508         if (message_length < 0)
509                 return (-3);
510
511         if (message_length - 1 > buffer_length - (c - buf)) {
512                 g_critical("End of buffer in extract_midi_event().");
513                 return (-5);
514         }
515
516         event->midi_buffer_length = message_length;
517         event->midi_buffer = malloc(event->midi_buffer_length);
518         if (event->midi_buffer == NULL) {
519                 g_critical("Cannot allocate memory in extract_midi_event(): %s", strerror(errno));
520                 return (-4);
521         }
522
523         event->midi_buffer[0] = status;
524         memcpy(event->midi_buffer + 1, c, message_length - 1);
525
526         *len = c + message_length - 1 - buf;
527
528         return (0);
529 }
530
531 /**
532  * Locates, basing on track->next_event_offset, the next event data in track->buffer,
533  * interprets it, allocates smf_event_t and fills it properly.  Returns smf_event_t
534  * or NULL, if there was an error.  Allocating event means adding it to the track;
535  * see smf_event_new().
536  */
537 static smf_event_t *
538 parse_next_event(smf_track_t *track)
539 {
540         int time = 0, len, buffer_length;
541         unsigned char *c, *start;
542
543         smf_event_t *event = smf_event_new();
544         if (event == NULL)
545                 goto error;
546
547         c = start = (unsigned char *)track->file_buffer + track->next_event_offset;
548
549         assert(track->file_buffer != NULL);
550         assert(track->file_buffer_length > 0);
551         assert(track->next_event_offset > 0);
552
553         buffer_length = track->file_buffer_length - track->next_event_offset;
554         assert(buffer_length > 0);
555
556         /* First, extract time offset from previous event. */
557         if (extract_vlq(c, buffer_length, &time, &len))
558                 goto error;
559
560         c += len;
561         buffer_length -= len;
562
563         if (buffer_length <= 0)
564                 goto error;
565
566         /* Now, extract the actual event. */
567         if (extract_midi_event(c, buffer_length, event, &len, track->last_status))
568                 goto error;
569
570         c += len;
571         buffer_length -= len;
572         track->last_status = event->midi_buffer[0];
573         track->next_event_offset += c - start;
574
575         smf_track_add_event_delta_pulses(track, event, time);
576
577         return (event);
578
579 error:
580         if (event != NULL)
581                 smf_event_delete(event);
582
583         return (NULL);
584 }
585
586 /**
587  * Takes "len" characters starting in "buf", making sure it does not access past the length of the buffer,
588  * and makes ordinary, zero-terminated string from it.  May return NULL if there was any problem.
589  */ 
590 static char *
591 make_string(const unsigned char *buf, const int buffer_length, int len)
592 {
593         char *str;
594
595         assert(buffer_length > 0);
596         assert(len > 0);
597
598         if (len > buffer_length) {
599                 g_critical("End of buffer in make_string().");
600
601                 len = buffer_length;
602         }
603
604         str = malloc(len + 1);
605         if (str == NULL) {
606                 g_critical("Cannot allocate memory in make_string().");
607                 return (NULL);
608         }
609
610         memcpy(str, buf, len);
611         str[len] = '\0';
612
613         return (str);
614 }
615
616 /**
617  * \return 1, if passed a metaevent containing text, that is, Text, Copyright,
618  * Sequence/Track Name, Instrument, Lyric, Marker, Cue Point, Program Name,
619  * or Device Name; 0 otherwise.
620  */
621 int
622 smf_event_is_textual(const smf_event_t *event)
623 {
624         if (!smf_event_is_metadata(event))
625                 return (0);
626
627         if (event->midi_buffer_length < 4)
628                 return (0);
629
630         if (event->midi_buffer[3] < 1 && event->midi_buffer[3] > 9)
631                 return (0);
632
633         return (1);
634 }
635
636 /**
637  * Extracts text from "textual metaevents", such as Text or Lyric.
638  *
639  * \return Zero-terminated string extracted from "text events" or NULL, if there was any problem.
640  */
641 char *
642 smf_event_extract_text(const smf_event_t *event)
643 {
644         int string_length = -1, length_length = -1;
645
646         if (!smf_event_is_textual(event))
647                 return (NULL);
648
649         if (event->midi_buffer_length < 3) {
650                 g_critical("smf_event_extract_text: truncated MIDI message.");
651                 return (NULL);
652         }
653
654         extract_vlq((void *)&(event->midi_buffer[2]), event->midi_buffer_length - 2, &string_length, &length_length);
655
656         if (string_length <= 0) {
657                 g_critical("smf_event_extract_text: truncated MIDI message.");
658                 return (NULL);
659         }
660
661         return (make_string((void *)(&event->midi_buffer[2] + length_length), event->midi_buffer_length - 2 - length_length, string_length));
662 }
663
664 /**
665  * Verify if the next chunk really is MTrk chunk, and if so, initialize some track variables and return 0.
666  * Return different value otherwise.
667  */
668 static int
669 parse_mtrk_header(smf_track_t *track)
670 {
671         struct chunk_header_struct *mtrk;
672
673         /* Make sure compiler didn't do anything stupid. */
674         assert(sizeof(struct chunk_header_struct) == 8);
675         assert(track->smf != NULL);
676
677         mtrk = next_chunk(track->smf);
678
679         if (mtrk == NULL)
680                 return (-1);
681
682         if (!chunk_signature_matches(mtrk, "MTrk")) {
683                 g_warning("SMF warning: Expected MTrk signature, got %c%c%c%c instead; ignoring this chunk.",
684                                 mtrk->id[0], mtrk->id[1], mtrk->id[2], mtrk->id[3]);
685                 
686                 return (-2);
687         }
688
689         track->file_buffer = mtrk;
690         track->file_buffer_length = sizeof(struct chunk_header_struct) + ntohl(mtrk->length);
691         track->next_event_offset = sizeof(struct chunk_header_struct);
692
693         return (0);
694 }
695
696 /**
697  * Return 1 if event is end-of-the-track, 0 otherwise.
698  */
699 static int
700 event_is_end_of_track(const smf_event_t *event)
701 {
702         if (event->midi_buffer[0] == 0xFF && event->midi_buffer[1] == 0x2F)
703                 return (1);
704
705         return (0);
706 }
707
708 /**
709  * \return Nonzero, if event is as long as it should be, from the MIDI specification point of view.
710  * Does not work for SysExes - it doesn't recognize internal structure of SysEx.
711  */
712 int
713 smf_event_length_is_valid(const smf_event_t *event)
714 {
715         assert(event);
716         assert(event->midi_buffer);
717
718         if (event->midi_buffer_length < 1)
719                 return (0);
720
721         /* We cannot use expected_message_length on sysexes. */
722         if (smf_event_is_sysex(event))
723                 return (1);
724
725         if (event->midi_buffer_length != expected_message_length(event->midi_buffer[0],
726                 &(event->midi_buffer[1]), event->midi_buffer_length - 1)) {
727
728                 return (0);
729         }
730
731         return (1);
732 }
733
734 /**
735  * \return Nonzero, if MIDI data in the event is valid, 0 otherwise.  For example,
736  * it checks if event length is correct.
737  */
738 /* XXX: this routine requires some more work to detect more errors. */
739 int
740 smf_event_is_valid(const smf_event_t *event)
741 {
742         assert(event);
743         assert(event->midi_buffer);
744         assert(event->midi_buffer_length >= 1);
745
746         if (!is_status_byte(event->midi_buffer[0])) {
747                 g_critical("First byte of MIDI message is not a valid status byte.");
748
749                 return (0);
750         }
751
752         if (!smf_event_length_is_valid(event))
753                 return (0);
754
755         return (1);
756 }
757
758 /**
759  * Parse events and put it on the track.
760  */
761 static int
762 parse_mtrk_chunk(smf_track_t *track)
763 {
764         smf_event_t *event;
765
766         if (parse_mtrk_header(track))
767                 return (-1);
768
769         for (;;) {
770                 event = parse_next_event(track);
771
772                 /* Couldn't parse an event? */
773                 if (event == NULL)
774                         return (-1);
775
776                 assert(smf_event_is_valid(event));
777
778                 if (event_is_end_of_track(event))
779                         break;
780         }
781
782         track->file_buffer = NULL;
783         track->file_buffer_length = 0;
784         track->next_event_offset = -1;
785
786         return (0);
787 }
788
789 /**
790  * Allocate buffer of proper size and read file contents into it.  Close file afterwards.
791  */
792 static int
793 load_file_into_buffer(void **file_buffer, int *file_buffer_length, const char *file_name)
794 {
795         FILE *stream = fopen(file_name, "r");
796
797         if (stream == NULL) {
798                 g_critical("Cannot open input file: %s", strerror(errno));
799
800                 return (-1);
801         }
802
803         if (fseek(stream, 0, SEEK_END)) {
804                 g_critical("fseek(3) failed: %s", strerror(errno));
805
806                 return (-2);
807         }
808
809         *file_buffer_length = ftell(stream);
810         if (*file_buffer_length == -1) {
811                 g_critical("ftell(3) failed: %s", strerror(errno));
812
813                 return (-3);
814         }
815
816         if (fseek(stream, 0, SEEK_SET)) {
817                 g_critical("fseek(3) failed: %s", strerror(errno));
818
819                 return (-4);
820         }
821
822         *file_buffer = malloc(*file_buffer_length);
823         if (*file_buffer == NULL) {
824                 g_critical("malloc(3) failed: %s", strerror(errno));
825
826                 return (-5);
827         }
828
829         if (fread(*file_buffer, 1, *file_buffer_length, stream) != *file_buffer_length) {
830                 g_critical("fread(3) failed: %s", strerror(errno));
831
832                 return (-6);
833         }
834         
835         if (fclose(stream)) {
836                 g_critical("fclose(3) failed: %s", strerror(errno));
837
838                 return (-7);
839         }
840
841         return (0);
842 }
843
844 /**
845   * Creates new SMF and fills it with data loaded from the given buffer.
846  * \return SMF or NULL, if loading failed.
847   */
848 smf_t *
849 smf_load_from_memory(const void *buffer, const int buffer_length)
850 {
851         int i;
852
853         smf_t *smf = smf_new();
854
855         smf->file_buffer = (void *)buffer;
856         smf->file_buffer_length = buffer_length;
857         smf->next_chunk_offset = 0;
858
859         if (parse_mthd_chunk(smf))
860                 return (NULL);
861
862         for (i = 1; i <= smf->expected_number_of_tracks; i++) {
863                 smf_track_t *track = smf_track_new();
864                 if (track == NULL)
865                         return (NULL);
866
867                 smf_add_track(smf, track);
868
869                 /* Skip unparseable chunks. */
870                 if (parse_mtrk_chunk(track)) {
871                         g_warning("SMF warning: Cannot load track.");
872                         smf_track_delete(track);
873                 }
874
875                 track->file_buffer = NULL;
876                 track->file_buffer_length = 0;
877                 track->next_event_offset = -1;
878         }
879
880         if (smf->expected_number_of_tracks != smf->number_of_tracks) {
881                 g_warning("SMF warning: MThd header declared %d tracks, but only %d found; continuing anyway.",
882                                 smf->expected_number_of_tracks, smf->number_of_tracks);
883
884                 smf->expected_number_of_tracks = smf->number_of_tracks;
885         }
886
887         smf->file_buffer = NULL;
888         smf->file_buffer_length = 0;
889         smf->next_chunk_offset = -1;
890
891         return (smf);
892 }
893
894 /**
895  * Loads SMF file.
896  *
897  * \param file_name Path to the file.
898  * \return SMF or NULL, if loading failed.
899  */
900 smf_t *
901 smf_load(const char *file_name)
902 {
903         int file_buffer_length;
904         void *file_buffer;
905         smf_t *smf;
906
907         if (load_file_into_buffer(&file_buffer, &file_buffer_length, file_name))
908                 return (NULL);
909
910         smf = smf_load_from_memory(file_buffer, file_buffer_length);
911
912         memset(file_buffer, 0, file_buffer_length);
913         free(file_buffer);
914
915         if (smf == NULL)
916                 return (NULL);
917
918         smf_rewind(smf);
919
920         return (smf);
921 }
922