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