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