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