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 #include <arpa/inet.h>
45 #include "smf_private.h"
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.
51 static struct chunk_header_struct *
52 next_chunk(smf_t *smf)
54 struct chunk_header_struct *chunk;
57 assert(smf->file_buffer != NULL);
58 assert(smf->file_buffer_length > 0);
60 if (smf->next_chunk_offset + sizeof(struct chunk_header_struct) >= smf->file_buffer_length) {
61 g_critical("SMF warning: no more chunks left.");
65 next_chunk_ptr = (unsigned char *)smf->file_buffer + smf->next_chunk_offset;
67 chunk = (struct chunk_header_struct *)next_chunk_ptr;
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.");
75 * XXX: On SPARC, after compiling with "-fast" option there will be SIGBUS here.
76 * Please compile with -xmemalign=8i".
78 smf->next_chunk_offset += sizeof(struct chunk_header_struct) + ntohl(chunk->length);
80 if (smf->next_chunk_offset > smf->file_buffer_length) {
81 g_critical("SMF error: malformed chunk; truncated file?");
89 * Returns 1, iff signature of the "chunk" is the same as string passed as "signature".
92 chunk_signature_matches(const struct chunk_header_struct *chunk, const char *signature)
94 if (!memcmp(chunk->id, signature, 4))
101 * Verifies if MThd header looks OK. Returns 0 iff it does.
104 parse_mthd_header(smf_t *smf)
107 struct chunk_header_struct *mthd, *tmp_mthd;
109 /* Make sure compiler didn't do anything stupid. */
110 assert(sizeof(struct chunk_header_struct) == 8);
113 * We could just do "mthd = smf->file_buffer;" here, but this way we wouldn't
114 * get useful error messages.
116 if (smf->file_buffer_length < 6) {
117 g_critical("SMF error: file is too short, it cannot be a MIDI file.");
122 tmp_mthd = smf->file_buffer;
124 if (!chunk_signature_matches(tmp_mthd, "MThd")) {
125 g_critical("SMF error: MThd signature not found, is that a MIDI file?");
130 /* Ok, now use next_chunk(). */
131 mthd = next_chunk(smf);
135 assert(mthd == tmp_mthd);
137 len = ntohl(mthd->length);
139 g_critical("SMF error: MThd chunk length %d, must be 6.", len);
148 * Parses MThd chunk, filling "smf" structure with values extracted from it. Returns 0 iff everything went OK.
151 parse_mthd_chunk(smf_t *smf)
153 signed char first_byte_of_division, second_byte_of_division;
155 struct mthd_chunk_struct *mthd;
157 assert(sizeof(struct mthd_chunk_struct) == 14);
159 if (parse_mthd_header(smf))
162 mthd = (struct mthd_chunk_struct *)smf->file_buffer;
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);
170 if (smf->format == 2) {
171 g_critical("SMF file uses format #2, no support for that yet.");
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);
181 /* XXX: endianess? */
182 first_byte_of_division = *((signed char *)&(mthd->division));
183 second_byte_of_division = *((signed char *)&(mthd->division) + 1);
185 if (first_byte_of_division >= 0) {
186 smf->ppqn = ntohs(mthd->division);
187 smf->frames_per_second = 0;
191 smf->frames_per_second = - first_byte_of_division;
192 smf->resolution = second_byte_of_division;
195 if (smf->ppqn == 0) {
196 g_critical("SMF file uses FPS timing instead of PPQN, no support for that yet.");
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.
210 smf_extract_vlq(const unsigned char *buf, const size_t buffer_length, uint32_t *value, uint32_t *len)
213 const unsigned char *c = buf;
216 if (c >= buf + buffer_length) {
217 g_critical("End of buffer in extract_vlq().");
221 val = (val << 7) + (*c & 0x7F);
234 g_critical("SMF error: Variable Length Quantities longer than four bytes are not supported yet.");
242 * Returns 1 if the given byte is a valid status byte, 0 otherwise.
245 is_status_byte(const unsigned char status)
247 return (status & 0x80);
251 is_sysex_byte(const unsigned char status)
260 is_escape_byte(const unsigned char status)
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
276 expected_sysex_length(const unsigned char status, const unsigned char *second_byte, const size_t buffer_length, int32_t *consumed_bytes)
278 uint32_t sysex_length, len;
280 assert(status == 0xF0);
282 if (buffer_length < 3) {
283 g_critical("SMF error: end of buffer in expected_sysex_length().");
287 smf_extract_vlq(second_byte, buffer_length, &sysex_length, &len);
289 if (consumed_bytes != NULL)
290 *consumed_bytes = len;
292 /* +1, because the length does not include status byte. */
293 return (sysex_length + 1);
297 expected_escaped_length(const unsigned char status, const unsigned char *second_byte, const size_t buffer_length, int32_t *consumed_bytes)
299 /* -1, because we do not want to account for 0x7F status. */
300 return (expected_sysex_length(status, second_byte, buffer_length, consumed_bytes) - 1);
304 * Returns expected length of the midi message (including the status byte), in bytes, for the given status byte.
305 * The "second_byte" points to the expected second byte of the MIDI message. "buffer_length" is the buffer
306 * length limit, counting from "second_byte". Returns value < 0 iff there was an error.
309 expected_message_length(unsigned char status, const unsigned char *second_byte, const size_t buffer_length)
311 /* Make sure this really is a valid status byte. */
312 assert(is_status_byte(status));
314 /* We cannot use this routine for sysexes. */
315 assert(!is_sysex_byte(status));
317 /* We cannot use this routine for escaped events. */
318 assert(!is_escape_byte(status));
320 /* Is this a metamessage? */
321 if (status == 0xFF) {
322 if (buffer_length < 2) {
323 g_critical("SMF error: end of buffer in expected_message_length().");
328 * Format of this kind of messages is like this: 0xFF 0xwhatever 0xlength and then "length" bytes.
329 * Second byte points to this: ^^^^^^^^^^
331 return (*(second_byte + 1) + 3);
334 if ((status & 0xF0) == 0xF0) {
336 case 0xF2: /* Song Position Pointer. */
339 case 0xF1: /* MTC Quarter Frame. */
340 case 0xF3: /* Song Select. */
343 case 0xF6: /* Tune Request. */
344 case 0xF8: /* MIDI Clock. */
345 case 0xF9: /* Tick. */
346 case 0xFA: /* MIDI Start. */
347 case 0xFB: /* MIDI Continue. */
348 case 0xFC: /* MIDI Stop. */
349 case 0xFE: /* Active Sense. */
353 g_critical("SMF error: unknown 0xFx-type status byte '0x%x'.", status);
358 /* Filter out the channel. */
362 case 0x80: /* Note Off. */
363 case 0x90: /* Note On. */
364 case 0xA0: /* AfterTouch. */
365 case 0xB0: /* Control Change. */
366 case 0xE0: /* Pitch Wheel. */
369 case 0xC0: /* Program Change. */
370 case 0xD0: /* Channel Pressure. */
374 g_critical("SMF error: unknown status byte '0x%x'.", status);
380 extract_sysex_event(const unsigned char *buf, const size_t buffer_length, smf_event_t *event, uint32_t *len, int last_status)
385 int32_t vlq_length, message_length;
386 const unsigned char *c = buf;
390 assert(is_sysex_byte(status));
394 message_length = expected_sysex_length(status, c, buffer_length - 1, &vlq_length);
396 if (message_length < 0)
401 if (vlq_length + (size_t)message_length >= buffer_length) {
402 g_critical("End of buffer in extract_sysex_event().");
406 event->midi_buffer_length = message_length;
407 event->midi_buffer = malloc(event->midi_buffer_length);
408 if (event->midi_buffer == NULL) {
409 g_critical("Cannot allocate memory in extract_sysex_event(): %s", strerror(errno));
413 event->midi_buffer[0] = status;
414 memcpy(event->midi_buffer + 1, c, message_length - 1);
416 *len = vlq_length + message_length;
422 extract_escaped_event(const unsigned char *buf, const size_t buffer_length, smf_event_t *event, uint32_t *len, int last_status)
427 int32_t message_length, vlq_length;
428 const unsigned char *c = buf;
432 assert(is_escape_byte(status));
436 message_length = expected_escaped_length(status, c, buffer_length - 1, &vlq_length);
438 if (message_length < 0)
443 if (vlq_length + (size_t)message_length >= buffer_length) {
444 g_critical("End of buffer in extract_escaped_event().");
448 event->midi_buffer_length = message_length;
449 event->midi_buffer = malloc(event->midi_buffer_length);
450 if (event->midi_buffer == NULL) {
451 g_critical("Cannot allocate memory in extract_escaped_event(): %s", strerror(errno));
455 memcpy(event->midi_buffer, c, message_length);
457 if (smf_event_is_valid(event)) {
458 g_critical("Escaped event is invalid.");
462 if (smf_event_is_system_realtime(event) || smf_event_is_system_common(event)) {
463 g_warning("Escaped event is not System Realtime nor System Common.");
466 *len = vlq_length + message_length;
473 * Puts MIDI data extracted from from "buf" into "event" and number of consumed bytes into "len".
474 * In case valid status is not found, it uses "last_status" (so called "running status").
475 * Returns 0 iff everything went OK, value < 0 in case of error.
478 extract_midi_event(const unsigned char *buf, const size_t buffer_length, smf_event_t *event, uint32_t *len, int last_status)
481 int32_t message_length;
482 const unsigned char *c = buf;
484 assert(buffer_length > 0);
486 /* Is the first byte the status byte? */
487 if (is_status_byte(*c)) {
492 /* No, we use running status then. */
493 status = last_status;
496 if (!is_status_byte(status)) {
497 g_critical("SMF error: bad status byte (MSB is zero).");
501 if (is_sysex_byte(status))
502 return (extract_sysex_event(buf, buffer_length, event, len, last_status));
504 if (is_escape_byte(status))
505 return (extract_escaped_event(buf, buffer_length, event, len, last_status));
507 /* At this point, "c" points to first byte following the status byte. */
508 message_length = expected_message_length(status, c, buffer_length - (c - buf));
510 if (message_length < 0)
513 if ((size_t)message_length > buffer_length - (c - buf) + 1) {
514 g_critical("End of buffer in extract_midi_event().");
518 event->midi_buffer_length = message_length;
519 event->midi_buffer = malloc(event->midi_buffer_length);
520 if (event->midi_buffer == NULL) {
521 g_critical("Cannot allocate memory in extract_midi_event(): %s", strerror(errno));
525 event->midi_buffer[0] = status;
526 memcpy(event->midi_buffer + 1, c, message_length - 1);
528 *len = c + message_length - 1 - buf;
534 * Locates, basing on track->next_event_offset, the next event data in track->buffer,
535 * interprets it, allocates smf_event_t and fills it properly. Returns smf_event_t
536 * or NULL, if there was an error. Allocating event means adding it to the track;
537 * see smf_event_new().
540 parse_next_event(smf_track_t *track)
544 size_t buffer_length;
545 unsigned char *c, *start;
547 smf_event_t *event = smf_event_new();
551 c = start = (unsigned char *)track->file_buffer + track->next_event_offset;
553 assert(track->file_buffer != NULL);
554 assert(track->file_buffer_length > 0);
555 assert(track->next_event_offset > 0);
557 buffer_length = track->file_buffer_length - track->next_event_offset;
558 assert(buffer_length > 0);
560 /* First, extract time offset from previous event. */
561 if (smf_extract_vlq(c, buffer_length, &time, &len))
565 buffer_length -= len;
567 if (buffer_length <= 0)
570 /* Now, extract the actual event. */
571 if (extract_midi_event(c, buffer_length, event, &len, track->last_status))
575 buffer_length -= len;
576 track->last_status = event->midi_buffer[0];
577 track->next_event_offset += c - start;
579 smf_track_add_event_delta_pulses(track, event, time);
585 smf_event_delete(event);
591 * Takes "len" characters starting in "buf", making sure it does not access past the length of the buffer,
592 * and makes ordinary, zero-terminated string from it. May return NULL if there was any problem.
595 make_string(const unsigned char *buf, const size_t buffer_length, uint32_t len)
599 assert(buffer_length > 0);
602 if (len > buffer_length) {
603 g_critical("End of buffer in make_string().");
608 str = malloc(len + 1);
610 g_critical("Cannot allocate memory in make_string().");
614 memcpy(str, buf, len);
621 * \return 1, if passed a metaevent containing text, that is, Text, Copyright,
622 * Sequence/Track Name, Instrument, Lyric, Marker, Cue Point, Program Name,
623 * or Device Name; 0 otherwise.
626 smf_event_is_textual(const smf_event_t *event)
628 if (!smf_event_is_metadata(event))
631 if (event->midi_buffer_length < 4)
634 if (event->midi_buffer[3] < 1 && event->midi_buffer[3] > 9)
641 * Extracts text from "textual metaevents", such as Text or Lyric.
643 * \return Zero-terminated string extracted from "text events" or NULL, if there was any problem.
646 smf_event_extract_text(const smf_event_t *event)
648 uint32_t string_length, length_length;
650 if (!smf_event_is_textual(event))
653 if (event->midi_buffer_length < 3) {
654 g_critical("smf_event_extract_text: truncated MIDI message.");
658 smf_extract_vlq((void *)&(event->midi_buffer[2]), event->midi_buffer_length - 2, &string_length, &length_length);
660 if (string_length <= 0) {
661 g_critical("smf_event_extract_text: truncated MIDI message.");
665 return (make_string((void *)(&event->midi_buffer[2] + length_length), event->midi_buffer_length - 2 - length_length, string_length));
669 * Verify if the next chunk really is MTrk chunk, and if so, initialize some track variables and return 0.
670 * Return different value otherwise.
673 parse_mtrk_header(smf_track_t *track)
675 struct chunk_header_struct *mtrk;
677 /* Make sure compiler didn't do anything stupid. */
678 assert(sizeof(struct chunk_header_struct) == 8);
679 assert(track->smf != NULL);
681 mtrk = next_chunk(track->smf);
686 if (!chunk_signature_matches(mtrk, "MTrk")) {
687 g_warning("SMF warning: Expected MTrk signature, got %c%c%c%c instead; ignoring this chunk.",
688 mtrk->id[0], mtrk->id[1], mtrk->id[2], mtrk->id[3]);
693 track->file_buffer = mtrk;
694 track->file_buffer_length = sizeof(struct chunk_header_struct) + ntohl(mtrk->length);
695 track->next_event_offset = sizeof(struct chunk_header_struct);
701 * Return 1 if event is end-of-the-track, 0 otherwise.
704 event_is_end_of_track(const smf_event_t *event)
706 if (event->midi_buffer[0] == 0xFF && event->midi_buffer[1] == 0x2F)
713 * \return Nonzero, if event is as long as it should be, from the MIDI specification point of view.
714 * Does not work for SysExes - it doesn't recognize internal structure of SysEx.
717 smf_event_length_is_valid(const smf_event_t *event)
720 assert(event->midi_buffer);
724 if (event->midi_buffer_length < 1)
727 /* We cannot use expected_message_length on sysexes. */
728 if (smf_event_is_sysex(event))
732 expected = expected_message_length(event->midi_buffer[0],
733 &(event->midi_buffer[1]), event->midi_buffer_length - 1);
734 if (expected < 0 || event->midi_buffer_length != (size_t)expected) {
742 * \return Nonzero, if MIDI data in the event is valid, 0 otherwise. For example,
743 * it checks if event length is correct.
745 /* XXX: this routine requires some more work to detect more errors. */
747 smf_event_is_valid(const smf_event_t *event)
750 assert(event->midi_buffer);
751 assert(event->midi_buffer_length >= 1);
753 if (!is_status_byte(event->midi_buffer[0])) {
754 g_critical("First byte of MIDI message is not a valid status byte.");
759 if (!smf_event_length_is_valid(event))
766 * Parse events and put it on the track.
769 parse_mtrk_chunk(smf_track_t *track)
773 if (parse_mtrk_header(track))
777 event = parse_next_event(track);
779 /* Couldn't parse an event? */
783 assert(smf_event_is_valid(event));
785 if (event_is_end_of_track(event))
789 track->file_buffer = NULL;
790 track->file_buffer_length = 0;
791 track->next_event_offset = -1;
797 * Allocate buffer of proper size and read file contents into it.
800 load_file_into_buffer(void **file_buffer, size_t *file_buffer_length, FILE* stream)
804 if (stream == NULL) {
805 g_critical("Cannot open input file: %s", strerror(errno));
810 if (fseek(stream, 0, SEEK_END)) {
811 g_critical("fseek(3) failed: %s", strerror(errno));
816 offset = ftell(stream);
818 g_critical("ftell(3) failed: %s", strerror(errno));
822 *file_buffer_length = (size_t)offset;
824 if (fseek(stream, 0, SEEK_SET)) {
825 g_critical("fseek(3) failed: %s", strerror(errno));
830 *file_buffer = malloc(*file_buffer_length);
831 if (*file_buffer == NULL) {
832 g_critical("malloc(3) failed: %s", strerror(errno));
837 if (fread(*file_buffer, 1, *file_buffer_length, stream) != *file_buffer_length) {
838 g_critical("fread(3) failed: %s", strerror(errno));
847 * Creates new SMF and fills it with data loaded from the given buffer.
848 * \return SMF or NULL, if loading failed.
851 smf_load_from_memory(const void *buffer, const size_t buffer_length)
855 smf_t *smf = smf_new();
857 smf->file_buffer = (void *)buffer;
858 smf->file_buffer_length = buffer_length;
859 smf->next_chunk_offset = 0;
861 if (parse_mthd_chunk(smf))
864 for (i = 1; i <= smf->expected_number_of_tracks; i++) {
865 smf_track_t *track = smf_track_new();
869 smf_add_track(smf, track);
871 /* Skip unparseable chunks. */
872 if (parse_mtrk_chunk(track)) {
873 g_warning("SMF warning: Cannot load track.");
874 smf_track_delete(track);
877 track->file_buffer = NULL;
878 track->file_buffer_length = 0;
879 track->next_event_offset = -1;
882 if (smf->expected_number_of_tracks != smf->number_of_tracks) {
883 g_warning("SMF warning: MThd header declared %d tracks, but only %d found; continuing anyway.",
884 smf->expected_number_of_tracks, smf->number_of_tracks);
886 smf->expected_number_of_tracks = smf->number_of_tracks;
889 smf->file_buffer = NULL;
890 smf->file_buffer_length = 0;
891 smf->next_chunk_offset = 0;
899 * \param file Open file.
900 * \return SMF or NULL, if loading failed.
905 size_t file_buffer_length;
909 if (load_file_into_buffer(&file_buffer, &file_buffer_length, file))
912 smf = smf_load_from_memory(file_buffer, file_buffer_length);
914 memset(file_buffer, 0, file_buffer_length);