2 * Copyright (c) 2007, 2008 Edward Tomasz NapieraĆa <trasz@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
31 * Standard MIDI File format loader.
35 /* Reference: http://www.borg.com/~jglatt/tech/midifile.htm */
43 #ifdef PLATFORM_WINDOWS
46 #include <arpa/inet.h>
49 #include "smf_private.h"
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.
55 static struct chunk_header_struct *
56 next_chunk(smf_t *smf)
58 struct chunk_header_struct *chunk;
61 assert(smf->file_buffer != NULL);
62 assert(smf->file_buffer_length > 0);
64 if (smf->next_chunk_offset + sizeof(struct chunk_header_struct) >= smf->file_buffer_length) {
65 g_critical("SMF warning: no more chunks left.");
69 next_chunk_ptr = (unsigned char *)smf->file_buffer + smf->next_chunk_offset;
71 chunk = (struct chunk_header_struct *)next_chunk_ptr;
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.");
79 * XXX: On SPARC, after compiling with "-fast" option there will be SIGBUS here.
80 * Please compile with -xmemalign=8i".
82 smf->next_chunk_offset += sizeof(struct chunk_header_struct) + ntohl(chunk->length);
84 if (smf->next_chunk_offset > smf->file_buffer_length) {
85 g_critical("SMF error: malformed chunk; truncated file?");
93 * Returns 1, iff signature of the "chunk" is the same as string passed as "signature".
96 chunk_signature_matches(const struct chunk_header_struct *chunk, const char *signature)
98 if (!memcmp(chunk->id, signature, 4))
105 * Verifies if MThd header looks OK. Returns 0 iff it does.
108 parse_mthd_header(smf_t *smf)
111 struct chunk_header_struct *mthd, *tmp_mthd;
113 /* Make sure compiler didn't do anything stupid. */
114 assert(sizeof(struct chunk_header_struct) == 8);
117 * We could just do "mthd = smf->file_buffer;" here, but this way we wouldn't
118 * get useful error messages.
120 if (smf->file_buffer_length < 6) {
121 g_critical("SMF error: file is too short, it cannot be a MIDI file.");
126 tmp_mthd = (struct chunk_header_struct*)smf->file_buffer;
128 if (!chunk_signature_matches(tmp_mthd, "MThd")) {
129 g_critical("SMF error: MThd signature not found, is that a MIDI file?");
134 /* Ok, now use next_chunk(). */
135 mthd = next_chunk(smf);
139 assert(mthd == tmp_mthd);
141 len = ntohl(mthd->length);
143 g_critical("SMF error: MThd chunk length %d, must be 6.", len);
152 * Parses MThd chunk, filling "smf" structure with values extracted from it. Returns 0 iff everything went OK.
155 parse_mthd_chunk(smf_t *smf)
157 signed char first_byte_of_division, second_byte_of_division;
159 struct mthd_chunk_struct *mthd;
161 assert(sizeof(struct mthd_chunk_struct) == 14);
163 if (parse_mthd_header(smf))
166 mthd = (struct mthd_chunk_struct *)smf->file_buffer;
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);
174 if (smf->format == 2) {
175 g_critical("SMF file uses format #2, no support for that yet.");
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);
185 /* XXX: endianess? */
186 first_byte_of_division = *((signed char *)&(mthd->division));
187 second_byte_of_division = *((signed char *)&(mthd->division) + 1);
189 if (first_byte_of_division >= 0) {
190 smf->ppqn = ntohs(mthd->division);
191 smf->frames_per_second = 0;
195 smf->frames_per_second = - first_byte_of_division;
196 smf->resolution = second_byte_of_division;
199 if (smf->ppqn == 0) {
200 g_critical("SMF file uses FPS timing instead of PPQN, no support for that yet.");
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.
214 smf_extract_vlq(const unsigned char *buf, const size_t buffer_length, uint32_t *value, uint32_t *len)
217 const unsigned char *c = buf;
220 if (c >= buf + buffer_length) {
221 g_critical("End of buffer in extract_vlq().");
225 val = (val << 7) + (*c & 0x7F);
238 g_critical("SMF error: Variable Length Quantities longer than four bytes are not supported yet.");
246 * Returns 1 if the given byte is a valid status byte, 0 otherwise.
249 is_status_byte(const unsigned char status)
251 return (status & 0x80);
255 is_sysex_byte(const unsigned char status)
264 is_escape_byte(const unsigned char status)
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
280 expected_sysex_length(const unsigned char status, const unsigned char *second_byte, const size_t buffer_length, int32_t *consumed_bytes)
282 uint32_t sysex_length = 0;
285 assert(status == 0xF0);
287 if (buffer_length < 3) {
288 g_critical("SMF error: end of buffer in expected_sysex_length().");
292 smf_extract_vlq(second_byte, buffer_length, &sysex_length, &len);
294 if (consumed_bytes != NULL)
295 *consumed_bytes = len;
297 /* +1, because the length does not include status byte. */
298 return (sysex_length + 1);
302 expected_escaped_length(const unsigned char status, const unsigned char *second_byte, const size_t buffer_length, int32_t *consumed_bytes)
304 /* -1, because we do not want to account for 0x7F status. */
305 return (expected_sysex_length(status, second_byte, buffer_length, consumed_bytes) - 1);
309 * Returns expected length of the midi message (including the status byte), in bytes, for the given status byte.
310 * The "second_byte" points to the expected second byte of the MIDI message. "buffer_length" is the buffer
311 * length limit, counting from "second_byte". Returns value < 0 iff there was an error.
314 expected_message_length(unsigned char status, const unsigned char *second_byte, const size_t buffer_length)
316 /* Make sure this really is a valid status byte. */
317 assert(is_status_byte(status));
319 /* We cannot use this routine for sysexes. */
320 assert(!is_sysex_byte(status));
322 /* We cannot use this routine for escaped events. */
323 assert(!is_escape_byte(status));
325 /* Is this a metamessage? */
326 if (status == 0xFF) {
327 if (buffer_length < 2) {
328 g_critical("SMF error: end of buffer in expected_message_length().");
333 * Format of this kind of messages is like this: 0xFF 0xwhatever 0xlength and then "length" bytes.
334 * Second byte points to this: ^^^^^^^^^^
336 return (*(second_byte + 1) + 3);
339 if ((status & 0xF0) == 0xF0) {
341 case 0xF2: /* Song Position Pointer. */
344 case 0xF1: /* MTC Quarter Frame. */
345 case 0xF3: /* Song Select. */
348 case 0xF6: /* Tune Request. */
349 case 0xF8: /* MIDI Clock. */
350 case 0xF9: /* Tick. */
351 case 0xFA: /* MIDI Start. */
352 case 0xFB: /* MIDI Continue. */
353 case 0xFC: /* MIDI Stop. */
354 case 0xFE: /* Active Sense. */
358 g_critical("SMF error: unknown 0xFx-type status byte '0x%x'.", status);
363 /* Filter out the channel. */
367 case 0x80: /* Note Off. */
368 case 0x90: /* Note On. */
369 case 0xA0: /* AfterTouch. */
370 case 0xB0: /* Control Change. */
371 case 0xE0: /* Pitch Wheel. */
374 case 0xC0: /* Program Change. */
375 case 0xD0: /* Channel Pressure. */
379 g_critical("SMF error: unknown status byte '0x%x'.", status);
385 extract_sysex_event(const unsigned char *buf, const size_t buffer_length, smf_event_t *event, uint32_t *len, int last_status)
390 int32_t vlq_length, message_length;
391 const unsigned char *c = buf;
395 assert(is_sysex_byte(status));
399 message_length = expected_sysex_length(status, c, buffer_length - 1, &vlq_length);
401 if (message_length < 0)
406 if (vlq_length + (size_t)message_length >= buffer_length) {
407 g_critical("End of buffer in extract_sysex_event().");
411 event->midi_buffer_length = message_length;
412 event->midi_buffer = (uint8_t*)malloc(event->midi_buffer_length);
413 if (event->midi_buffer == NULL) {
414 g_critical("Cannot allocate memory in extract_sysex_event(): %s", strerror(errno));
418 event->midi_buffer[0] = status;
419 memcpy(event->midi_buffer + 1, c, message_length - 1);
421 *len = vlq_length + message_length;
427 extract_escaped_event(const unsigned char *buf, const size_t buffer_length, smf_event_t *event, uint32_t *len, int last_status)
432 int32_t message_length = 0;
433 int32_t vlq_length = 0;
434 const unsigned char *c = buf;
438 assert(is_escape_byte(status));
442 message_length = expected_escaped_length(status, c, buffer_length - 1, &vlq_length);
444 if (message_length < 0)
449 if (vlq_length + (size_t)message_length >= buffer_length) {
450 g_critical("End of buffer in extract_escaped_event().");
454 event->midi_buffer_length = message_length;
455 event->midi_buffer = (uint8_t*)malloc(event->midi_buffer_length);
456 if (event->midi_buffer == NULL) {
457 g_critical("Cannot allocate memory in extract_escaped_event(): %s", strerror(errno));
461 memcpy(event->midi_buffer, c, message_length);
463 if (smf_event_is_valid(event)) {
464 g_critical("Escaped event is invalid.");
468 if (smf_event_is_system_realtime(event) || smf_event_is_system_common(event)) {
469 g_warning("Escaped event is not System Realtime nor System Common.");
472 *len = vlq_length + message_length;
479 * Puts MIDI data extracted from from "buf" into "event" and number of consumed bytes into "len".
480 * In case valid status is not found, it uses "last_status" (so called "running status").
481 * Returns 0 iff everything went OK, value < 0 in case of error.
484 extract_midi_event(const unsigned char *buf, const size_t buffer_length, smf_event_t *event, uint32_t *len, int last_status)
487 int32_t message_length;
488 const unsigned char *c = buf;
490 assert(buffer_length > 0);
492 /* Is the first byte the status byte? */
493 if (is_status_byte(*c)) {
498 /* No, we use running status then. */
499 status = last_status;
502 if (!is_status_byte(status)) {
503 g_critical("SMF error: bad status byte (MSB is zero).");
507 if (is_sysex_byte(status))
508 return (extract_sysex_event(buf, buffer_length, event, len, last_status));
510 if (is_escape_byte(status))
511 return (extract_escaped_event(buf, buffer_length, event, len, last_status));
513 /* At this point, "c" points to first byte following the status byte. */
514 message_length = expected_message_length(status, c, buffer_length - (c - buf));
516 if (message_length < 0)
519 if ((size_t)message_length > buffer_length - (c - buf) + 1) {
520 g_critical("End of buffer in extract_midi_event().");
524 event->midi_buffer_length = message_length;
525 event->midi_buffer = (uint8_t*)malloc(event->midi_buffer_length);
526 if (event->midi_buffer == NULL) {
527 g_critical("Cannot allocate memory in extract_midi_event(): %s", strerror(errno));
531 event->midi_buffer[0] = status;
532 memcpy(event->midi_buffer + 1, c, message_length - 1);
534 *len = c + message_length - 1 - buf;
540 * Locates, basing on track->next_event_offset, the next event data in track->buffer,
541 * interprets it, allocates smf_event_t and fills it properly. Returns smf_event_t
542 * or NULL, if there was an error. Allocating event means adding it to the track;
543 * see smf_event_new().
546 parse_next_event(smf_track_t *track)
550 size_t buffer_length;
551 unsigned char *c, *start;
553 smf_event_t *event = smf_event_new();
557 c = start = (unsigned char *)track->file_buffer + track->next_event_offset;
559 assert(track->file_buffer != NULL);
560 assert(track->file_buffer_length > 0);
561 assert(track->next_event_offset > 0);
563 buffer_length = track->file_buffer_length - track->next_event_offset;
564 assert(buffer_length > 0);
566 /* First, extract time offset from previous event. */
567 if (smf_extract_vlq(c, buffer_length, &time, &len))
571 buffer_length -= len;
573 if (buffer_length <= 0)
576 /* Now, extract the actual event. */
577 if (extract_midi_event(c, buffer_length, event, &len, track->last_status))
581 buffer_length -= len;
582 track->last_status = event->midi_buffer[0];
583 track->next_event_offset += c - start;
585 smf_track_add_event_delta_pulses(track, event, time);
591 smf_event_delete(event);
597 * Takes "len" characters starting in "buf", making sure it does not access past the length of the buffer,
598 * and makes ordinary, zero-terminated string from it. May return NULL if there was any problem.
601 make_string(const unsigned char *buf, const size_t buffer_length, uint32_t len)
605 assert(buffer_length > 0);
608 if (len > buffer_length) {
609 g_critical("End of buffer in make_string().");
614 str = (char*)malloc(len + 1);
616 g_critical("Cannot allocate memory in make_string().");
620 memcpy(str, buf, len);
627 * \return 1, if passed a metaevent containing text, that is, Text, Copyright,
628 * Sequence/Track Name, Instrument, Lyric, Marker, Cue Point, Program Name,
629 * or Device Name; 0 otherwise.
632 smf_event_is_textual(const smf_event_t *event)
634 if (!smf_event_is_metadata(event))
637 if (event->midi_buffer_length < 4)
640 if (event->midi_buffer[3] < 1 && event->midi_buffer[3] > 9)
647 * Extracts text from "textual metaevents", such as Text or Lyric.
649 * \return Zero-terminated string extracted from "text events" or NULL, if there was any problem.
652 smf_event_extract_text(const smf_event_t *event)
654 uint32_t string_length = 0;
655 uint32_t length_length = 0;
657 if (!smf_event_is_textual(event))
660 if (event->midi_buffer_length < 3) {
661 g_critical("smf_event_extract_text: truncated MIDI message.");
665 smf_extract_vlq((const unsigned char*)(void *)&(event->midi_buffer[2]), event->midi_buffer_length - 2, &string_length, &length_length);
667 if (string_length <= 0) {
668 g_critical("smf_event_extract_text: truncated MIDI message.");
672 return (make_string((const unsigned char*)(void *)(&event->midi_buffer[2] + length_length), event->midi_buffer_length - 2 - length_length, string_length));
676 * Verify if the next chunk really is MTrk chunk, and if so, initialize some track variables and return 0.
677 * Return different value otherwise.
680 parse_mtrk_header(smf_track_t *track)
682 struct chunk_header_struct *mtrk;
684 /* Make sure compiler didn't do anything stupid. */
685 assert(sizeof(struct chunk_header_struct) == 8);
686 assert(track->smf != NULL);
688 mtrk = next_chunk(track->smf);
693 if (!chunk_signature_matches(mtrk, "MTrk")) {
694 g_warning("SMF warning: Expected MTrk signature, got %c%c%c%c instead; ignoring this chunk.",
695 mtrk->id[0], mtrk->id[1], mtrk->id[2], mtrk->id[3]);
700 track->file_buffer = mtrk;
701 track->file_buffer_length = sizeof(struct chunk_header_struct) + ntohl(mtrk->length);
702 track->next_event_offset = sizeof(struct chunk_header_struct);
708 * Return 1 if event is end-of-the-track, 0 otherwise.
711 event_is_end_of_track(const smf_event_t *event)
713 if (event->midi_buffer[0] == 0xFF && event->midi_buffer[1] == 0x2F)
720 * \return Nonzero, if event is as long as it should be, from the MIDI specification point of view.
721 * Does not work for SysExes - it doesn't recognize internal structure of SysEx.
724 smf_event_length_is_valid(const smf_event_t *event)
727 assert(event->midi_buffer);
731 if (event->midi_buffer_length < 1)
734 /* We cannot use expected_message_length on sysexes. */
735 if (smf_event_is_sysex(event))
739 expected = expected_message_length(event->midi_buffer[0],
740 &(event->midi_buffer[1]), event->midi_buffer_length - 1);
741 if (expected < 0 || event->midi_buffer_length != (size_t)expected) {
749 * \return Nonzero, if MIDI data in the event is valid, 0 otherwise. For example,
750 * it checks if event length is correct.
752 /* XXX: this routine requires some more work to detect more errors. */
754 smf_event_is_valid(const smf_event_t *event)
757 assert(event->midi_buffer);
758 assert(event->midi_buffer_length >= 1);
760 if (!is_status_byte(event->midi_buffer[0])) {
761 g_critical("First byte of MIDI message is not a valid status byte.");
766 if (!smf_event_length_is_valid(event))
773 * Parse events and put it on the track.
776 parse_mtrk_chunk(smf_track_t *track)
780 if (parse_mtrk_header(track))
784 event = parse_next_event(track);
786 /* Couldn't parse an event? */
790 assert(smf_event_is_valid(event));
792 if (event_is_end_of_track(event))
796 track->file_buffer = NULL;
797 track->file_buffer_length = 0;
798 track->next_event_offset = -1;
804 * Allocate buffer of proper size and read file contents into it.
807 load_file_into_buffer(void **file_buffer, size_t *file_buffer_length, FILE* stream)
811 if (stream == NULL) {
812 g_critical("Cannot open input file: %s", strerror(errno));
817 if (fseek(stream, 0, SEEK_END)) {
818 g_critical("fseek(3) failed: %s", strerror(errno));
823 offset = ftell(stream);
825 g_critical("ftell(3) failed: %s", strerror(errno));
829 *file_buffer_length = (size_t)offset;
831 if (fseek(stream, 0, SEEK_SET)) {
832 g_critical("fseek(3) failed: %s", strerror(errno));
837 *file_buffer = malloc(*file_buffer_length);
838 if (*file_buffer == NULL) {
839 g_critical("malloc(3) failed: %s", strerror(errno));
844 if (fread(*file_buffer, 1, *file_buffer_length, stream) != *file_buffer_length) {
845 g_critical("fread(3) failed: %s", strerror(errno));
855 * Creates new SMF and fills it with data loaded from the given buffer.
856 * \return SMF or NULL, if loading failed.
859 smf_load_from_memory(const void *buffer, const size_t buffer_length)
863 smf_t *smf = smf_new();
865 smf->file_buffer = (void *)buffer;
866 smf->file_buffer_length = buffer_length;
867 smf->next_chunk_offset = 0;
869 if (parse_mthd_chunk(smf))
872 for (i = 1; i <= smf->expected_number_of_tracks; i++) {
873 smf_track_t *track = smf_track_new();
877 smf_add_track(smf, track);
879 /* Skip unparseable chunks. */
880 if (parse_mtrk_chunk(track)) {
881 g_warning("SMF warning: Cannot load track.");
882 smf_track_delete(track);
886 track->file_buffer = NULL;
887 track->file_buffer_length = 0;
888 track->next_event_offset = -1;
891 if (smf->expected_number_of_tracks != smf->number_of_tracks) {
892 g_warning("SMF warning: MThd header declared %d tracks, but only %d found; continuing anyway.",
893 smf->expected_number_of_tracks, smf->number_of_tracks);
895 smf->expected_number_of_tracks = smf->number_of_tracks;
898 smf->file_buffer = NULL;
899 smf->file_buffer_length = 0;
900 smf->next_chunk_offset = 0;
908 * \param file Open file.
909 * \return SMF or NULL, if loading failed.
914 size_t file_buffer_length;
918 if (load_file_into_buffer(&file_buffer, &file_buffer_length, file))
921 smf = smf_load_from_memory(file_buffer, file_buffer_length);
923 memset(file_buffer, 0, file_buffer_length);