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);
59 assert(smf
->next_chunk_offset
>= 0);
61 if (smf
->next_chunk_offset
+ sizeof(struct chunk_header_struct
) >= smf
->file_buffer_length
) {
62 g_critical("SMF warning: no more chunks left.");
66 next_chunk_ptr
= (unsigned char *)smf
->file_buffer
+ smf
->next_chunk_offset
;
68 chunk
= (struct chunk_header_struct
*)next_chunk_ptr
;
70 if (!isalpha(chunk
->id
[0]) || !isalpha(chunk
->id
[1]) || !isalpha(chunk
->id
[2]) || !isalpha(chunk
->id
[3])) {
71 g_critical("SMF error: chunk signature contains at least one non-alphanumeric byte.");
76 * XXX: On SPARC, after compiling with "-fast" option there will be SIGBUS here.
77 * Please compile with -xmemalign=8i".
79 smf
->next_chunk_offset
+= sizeof(struct chunk_header_struct
) + ntohl(chunk
->length
);
81 if (smf
->next_chunk_offset
> smf
->file_buffer_length
) {
82 g_critical("SMF error: malformed chunk; truncated file?");
90 * Returns 1, iff signature of the "chunk" is the same as string passed as "signature".
93 chunk_signature_matches(const struct chunk_header_struct
*chunk
, const char *signature
)
95 if (!memcmp(chunk
->id
, signature
, 4))
102 * Verifies if MThd header looks OK. Returns 0 iff it does.
105 parse_mthd_header(smf_t
*smf
)
108 struct chunk_header_struct
*mthd
, *tmp_mthd
;
110 /* Make sure compiler didn't do anything stupid. */
111 assert(sizeof(struct chunk_header_struct
) == 8);
114 * We could just do "mthd = smf->file_buffer;" here, but this way we wouldn't
115 * get useful error messages.
117 if (smf
->file_buffer_length
< 6) {
118 g_critical("SMF error: file is too short, it cannot be a MIDI file.");
123 tmp_mthd
= smf
->file_buffer
;
125 if (!chunk_signature_matches(tmp_mthd
, "MThd")) {
126 g_critical("SMF error: MThd signature not found, is that a MIDI file?");
131 /* Ok, now use next_chunk(). */
132 mthd
= next_chunk(smf
);
136 assert(mthd
== tmp_mthd
);
138 len
= ntohl(mthd
->length
);
140 g_critical("SMF error: MThd chunk length %d, must be 6.", len
);
149 * Parses MThd chunk, filling "smf" structure with values extracted from it. Returns 0 iff everything went OK.
152 parse_mthd_chunk(smf_t
*smf
)
154 signed char first_byte_of_division
, second_byte_of_division
;
156 struct mthd_chunk_struct
*mthd
;
158 assert(sizeof(struct mthd_chunk_struct
) == 14);
160 if (parse_mthd_header(smf
))
163 mthd
= (struct mthd_chunk_struct
*)smf
->file_buffer
;
165 smf
->format
= ntohs(mthd
->format
);
166 if (smf
->format
< 0 || smf
->format
> 2) {
167 g_critical("SMF error: bad MThd format field value: %d, valid values are 0-2, inclusive.", smf
->format
);
171 if (smf
->format
== 2) {
172 g_critical("SMF file uses format #2, no support for that yet.");
176 smf
->expected_number_of_tracks
= ntohs(mthd
->number_of_tracks
);
177 if (smf
->expected_number_of_tracks
<= 0) {
178 g_critical("SMF error: bad number of tracks: %d, must be greater than zero.", smf
->expected_number_of_tracks
);
182 /* XXX: endianess? */
183 first_byte_of_division
= *((signed char *)&(mthd
->division
));
184 second_byte_of_division
= *((signed char *)&(mthd
->division
) + 1);
186 if (first_byte_of_division
>= 0) {
187 smf
->ppqn
= ntohs(mthd
->division
);
188 smf
->frames_per_second
= 0;
192 smf
->frames_per_second
= - first_byte_of_division
;
193 smf
->resolution
= second_byte_of_division
;
196 if (smf
->ppqn
== 0) {
197 g_critical("SMF file uses FPS timing instead of PPQN, no support for that yet.");
205 * Interprets Variable Length Quantity pointed at by "buf" and puts its value into "value" and number
206 * of bytes consumed into "len", making sure it does not read past "buf" + "buffer_length".
207 * Explanation of Variable Length Quantities is here: http://www.borg.com/~jglatt/tech/midifile/vari.htm
208 * Returns 0 iff everything went OK, different value in case of error.
211 extract_vlq(const unsigned char *buf
, const int buffer_length
, int *value
, int *len
)
214 const unsigned char *c
= buf
;
216 assert(buffer_length
> 0);
219 if (c
>= buf
+ buffer_length
) {
220 g_critical("End of buffer in extract_vlq().");
224 val
= (val
<< 7) + (*c
& 0x7F);
236 g_critical("SMF error: Variable Length Quantities longer than four bytes are not supported yet.");
244 * Returns 1 if the given byte is a valid status byte, 0 otherwise.
247 is_status_byte(const unsigned char status
)
249 return (status
& 0x80);
253 is_sysex_byte(const unsigned char status
)
262 is_escape_byte(const unsigned char status
)
271 * Just like expected_message_length(), but only for System Exclusive messages.
272 * Note that value returned by this thing here is the length of SysEx "on the wire",
273 * not the number of bytes that this sysex takes in the file - in SMF format sysex
274 * contains VLQ telling how many bytes it takes, "on the wire" format does not have
278 expected_sysex_length(const unsigned char status
, const unsigned char *second_byte
, const int buffer_length
, int *consumed_bytes
)
280 int sysex_length
, len
;
282 assert(status
== 0xF0);
284 if (buffer_length
< 3) {
285 g_critical("SMF error: end of buffer in expected_sysex_length().");
289 extract_vlq(second_byte
, buffer_length
, &sysex_length
, &len
);
291 if (consumed_bytes
!= NULL
)
292 *consumed_bytes
= len
;
294 /* +1, because the length does not include status byte. */
295 return (sysex_length
+ 1);
299 expected_escaped_length(const unsigned char status
, const unsigned char *second_byte
, const int buffer_length
, int *consumed_bytes
)
301 /* -1, because we do not want to account for 0x7F status. */
302 return (expected_sysex_length(status
, second_byte
, buffer_length
, consumed_bytes
) - 1);
306 * Returns expected length of the midi message (including the status byte), in bytes, for the given status byte.
307 * The "second_byte" points to the expected second byte of the MIDI message. "buffer_length" is the buffer
308 * length limit, counting from "second_byte". Returns value < 0 iff there was an error.
311 expected_message_length(unsigned char status
, const unsigned char *second_byte
, const int buffer_length
)
313 /* Make sure this really is a valid status byte. */
314 assert(is_status_byte(status
));
316 /* We cannot use this routine for sysexes. */
317 assert(!is_sysex_byte(status
));
319 /* We cannot use this routine for escaped events. */
320 assert(!is_escape_byte(status
));
322 /* Buffer length may be zero, for e.g. realtime messages. */
323 assert(buffer_length
>= 0);
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 int buffer_length
, smf_event_t
*event
, int *len
, int last_status
)
387 int status
, message_length
, vlq_length
;
388 const unsigned char *c
= buf
;
392 assert(is_sysex_byte(status
));
396 message_length
= expected_sysex_length(status
, c
, buffer_length
- 1, &vlq_length
);
398 if (message_length
< 0)
403 if (vlq_length
+ message_length
>= buffer_length
) {
404 g_critical("End of buffer in extract_sysex_event().");
408 event
->midi_buffer_length
= message_length
;
409 event
->midi_buffer
= malloc(event
->midi_buffer_length
);
410 if (event
->midi_buffer
== NULL
) {
411 g_critical("Cannot allocate memory in extract_sysex_event(): %s", strerror(errno
));
415 event
->midi_buffer
[0] = status
;
416 memcpy(event
->midi_buffer
+ 1, c
, message_length
- 1);
418 *len
= vlq_length
+ message_length
;
424 extract_escaped_event(const unsigned char *buf
, const int buffer_length
, smf_event_t
*event
, int *len
, int last_status
)
426 int status
, message_length
, vlq_length
;
427 const unsigned char *c
= buf
;
431 assert(is_escape_byte(status
));
435 message_length
= expected_escaped_length(status
, c
, buffer_length
- 1, &vlq_length
);
437 if (message_length
< 0)
442 if (vlq_length
+ message_length
>= buffer_length
) {
443 g_critical("End of buffer in extract_escaped_event().");
447 event
->midi_buffer_length
= message_length
;
448 event
->midi_buffer
= malloc(event
->midi_buffer_length
);
449 if (event
->midi_buffer
== NULL
) {
450 g_critical("Cannot allocate memory in extract_escaped_event(): %s", strerror(errno
));
454 memcpy(event
->midi_buffer
, c
, message_length
);
456 if (smf_event_is_valid(event
)) {
457 g_critical("Escaped event is invalid.");
461 if (smf_event_is_system_realtime(event
) || smf_event_is_system_common(event
)) {
462 g_warning("Escaped event is not System Realtime nor System Common.");
465 *len
= vlq_length
+ message_length
;
472 * Puts MIDI data extracted from from "buf" into "event" and number of consumed bytes into "len".
473 * In case valid status is not found, it uses "last_status" (so called "running status").
474 * Returns 0 iff everything went OK, value < 0 in case of error.
477 extract_midi_event(const unsigned char *buf
, const int buffer_length
, smf_event_t
*event
, int *len
, int last_status
)
479 int status
, message_length
;
480 const unsigned char *c
= buf
;
482 assert(buffer_length
> 0);
484 /* Is the first byte the status byte? */
485 if (is_status_byte(*c
)) {
490 /* No, we use running status then. */
491 status
= last_status
;
494 if (!is_status_byte(status
)) {
495 g_critical("SMF error: bad status byte (MSB is zero).");
499 if (is_sysex_byte(status
))
500 return (extract_sysex_event(buf
, buffer_length
, event
, len
, last_status
));
502 if (is_escape_byte(status
))
503 return (extract_escaped_event(buf
, buffer_length
, event
, len
, last_status
));
505 /* At this point, "c" points to first byte following the status byte. */
506 message_length
= expected_message_length(status
, c
, buffer_length
- (c
- buf
));
508 if (message_length
< 0)
511 if (message_length
- 1 > buffer_length
- (c
- buf
)) {
512 g_critical("End of buffer in extract_midi_event().");
516 event
->midi_buffer_length
= message_length
;
517 event
->midi_buffer
= malloc(event
->midi_buffer_length
);
518 if (event
->midi_buffer
== NULL
) {
519 g_critical("Cannot allocate memory in extract_midi_event(): %s", strerror(errno
));
523 event
->midi_buffer
[0] = status
;
524 memcpy(event
->midi_buffer
+ 1, c
, message_length
- 1);
526 *len
= c
+ message_length
- 1 - buf
;
532 * Locates, basing on track->next_event_offset, the next event data in track->buffer,
533 * interprets it, allocates smf_event_t and fills it properly. Returns smf_event_t
534 * or NULL, if there was an error. Allocating event means adding it to the track;
535 * see smf_event_new().
538 parse_next_event(smf_track_t
*track
)
540 int time
= 0, len
, buffer_length
;
541 unsigned char *c
, *start
;
543 smf_event_t
*event
= smf_event_new();
547 c
= start
= (unsigned char *)track
->file_buffer
+ track
->next_event_offset
;
549 assert(track
->file_buffer
!= NULL
);
550 assert(track
->file_buffer_length
> 0);
551 assert(track
->next_event_offset
> 0);
553 buffer_length
= track
->file_buffer_length
- track
->next_event_offset
;
554 assert(buffer_length
> 0);
556 /* First, extract time offset from previous event. */
557 if (extract_vlq(c
, buffer_length
, &time
, &len
))
561 buffer_length
-= len
;
563 if (buffer_length
<= 0)
566 /* Now, extract the actual event. */
567 if (extract_midi_event(c
, buffer_length
, event
, &len
, track
->last_status
))
571 buffer_length
-= len
;
572 track
->last_status
= event
->midi_buffer
[0];
573 track
->next_event_offset
+= c
- start
;
575 smf_track_add_event_delta_pulses(track
, event
, time
);
581 smf_event_delete(event
);
587 * Takes "len" characters starting in "buf", making sure it does not access past the length of the buffer,
588 * and makes ordinary, zero-terminated string from it. May return NULL if there was any problem.
591 make_string(const unsigned char *buf
, const int buffer_length
, int len
)
595 assert(buffer_length
> 0);
598 if (len
> buffer_length
) {
599 g_critical("End of buffer in make_string().");
604 str
= malloc(len
+ 1);
606 g_critical("Cannot allocate memory in make_string().");
610 memcpy(str
, buf
, len
);
617 * \return 1, if passed a metaevent containing text, that is, Text, Copyright,
618 * Sequence/Track Name, Instrument, Lyric, Marker, Cue Point, Program Name,
619 * or Device Name; 0 otherwise.
622 smf_event_is_textual(const smf_event_t
*event
)
624 if (!smf_event_is_metadata(event
))
627 if (event
->midi_buffer_length
< 4)
630 if (event
->midi_buffer
[3] < 1 && event
->midi_buffer
[3] > 9)
637 * Extracts text from "textual metaevents", such as Text or Lyric.
639 * \return Zero-terminated string extracted from "text events" or NULL, if there was any problem.
642 smf_event_extract_text(const smf_event_t
*event
)
644 int string_length
= -1, length_length
= -1;
646 if (!smf_event_is_textual(event
))
649 if (event
->midi_buffer_length
< 3) {
650 g_critical("smf_event_extract_text: truncated MIDI message.");
654 extract_vlq((void *)&(event
->midi_buffer
[2]), event
->midi_buffer_length
- 2, &string_length
, &length_length
);
656 if (string_length
<= 0) {
657 g_critical("smf_event_extract_text: truncated MIDI message.");
661 return (make_string((void *)(&event
->midi_buffer
[2] + length_length
), event
->midi_buffer_length
- 2 - length_length
, string_length
));
665 * Verify if the next chunk really is MTrk chunk, and if so, initialize some track variables and return 0.
666 * Return different value otherwise.
669 parse_mtrk_header(smf_track_t
*track
)
671 struct chunk_header_struct
*mtrk
;
673 /* Make sure compiler didn't do anything stupid. */
674 assert(sizeof(struct chunk_header_struct
) == 8);
675 assert(track
->smf
!= NULL
);
677 mtrk
= next_chunk(track
->smf
);
682 if (!chunk_signature_matches(mtrk
, "MTrk")) {
683 g_warning("SMF warning: Expected MTrk signature, got %c%c%c%c instead; ignoring this chunk.",
684 mtrk
->id
[0], mtrk
->id
[1], mtrk
->id
[2], mtrk
->id
[3]);
689 track
->file_buffer
= mtrk
;
690 track
->file_buffer_length
= sizeof(struct chunk_header_struct
) + ntohl(mtrk
->length
);
691 track
->next_event_offset
= sizeof(struct chunk_header_struct
);
697 * Return 1 if event is end-of-the-track, 0 otherwise.
700 event_is_end_of_track(const smf_event_t
*event
)
702 if (event
->midi_buffer
[0] == 0xFF && event
->midi_buffer
[1] == 0x2F)
709 * \return Nonzero, if event is as long as it should be, from the MIDI specification point of view.
710 * Does not work for SysExes - it doesn't recognize internal structure of SysEx.
713 smf_event_length_is_valid(const smf_event_t
*event
)
716 assert(event
->midi_buffer
);
718 if (event
->midi_buffer_length
< 1)
721 /* We cannot use expected_message_length on sysexes. */
722 if (smf_event_is_sysex(event
))
725 if (event
->midi_buffer_length
!= expected_message_length(event
->midi_buffer
[0],
726 &(event
->midi_buffer
[1]), event
->midi_buffer_length
- 1)) {
735 * \return Nonzero, if MIDI data in the event is valid, 0 otherwise. For example,
736 * it checks if event length is correct.
738 /* XXX: this routine requires some more work to detect more errors. */
740 smf_event_is_valid(const smf_event_t
*event
)
743 assert(event
->midi_buffer
);
744 assert(event
->midi_buffer_length
>= 1);
746 if (!is_status_byte(event
->midi_buffer
[0])) {
747 g_critical("First byte of MIDI message is not a valid status byte.");
752 if (!smf_event_length_is_valid(event
))
759 * Parse events and put it on the track.
762 parse_mtrk_chunk(smf_track_t
*track
)
766 if (parse_mtrk_header(track
))
770 event
= parse_next_event(track
);
772 /* Couldn't parse an event? */
776 assert(smf_event_is_valid(event
));
778 if (event_is_end_of_track(event
))
782 track
->file_buffer
= NULL
;
783 track
->file_buffer_length
= 0;
784 track
->next_event_offset
= -1;
790 * Allocate buffer of proper size and read file contents into it. Close file afterwards.
793 load_file_into_buffer(void **file_buffer
, int *file_buffer_length
, const char *file_name
)
795 FILE *stream
= fopen(file_name
, "r");
797 if (stream
== NULL
) {
798 g_critical("Cannot open input file: %s", strerror(errno
));
803 if (fseek(stream
, 0, SEEK_END
)) {
804 g_critical("fseek(3) failed: %s", strerror(errno
));
809 *file_buffer_length
= ftell(stream
);
810 if (*file_buffer_length
== -1) {
811 g_critical("ftell(3) failed: %s", strerror(errno
));
816 if (fseek(stream
, 0, SEEK_SET
)) {
817 g_critical("fseek(3) failed: %s", strerror(errno
));
822 *file_buffer
= malloc(*file_buffer_length
);
823 if (*file_buffer
== NULL
) {
824 g_critical("malloc(3) failed: %s", strerror(errno
));
829 if (fread(*file_buffer
, 1, *file_buffer_length
, stream
) != *file_buffer_length
) {
830 g_critical("fread(3) failed: %s", strerror(errno
));
835 if (fclose(stream
)) {
836 g_critical("fclose(3) failed: %s", strerror(errno
));
845 * Creates new SMF and fills it with data loaded from the given buffer.
846 * \return SMF or NULL, if loading failed.
849 smf_load_from_memory(const void *buffer
, const int buffer_length
)
853 smf_t
*smf
= smf_new();
855 smf
->file_buffer
= (void *)buffer
;
856 smf
->file_buffer_length
= buffer_length
;
857 smf
->next_chunk_offset
= 0;
859 if (parse_mthd_chunk(smf
))
862 for (i
= 1; i
<= smf
->expected_number_of_tracks
; i
++) {
863 smf_track_t
*track
= smf_track_new();
867 smf_add_track(smf
, track
);
869 /* Skip unparseable chunks. */
870 if (parse_mtrk_chunk(track
)) {
871 g_warning("SMF warning: Cannot load track.");
872 smf_track_delete(track
);
875 track
->file_buffer
= NULL
;
876 track
->file_buffer_length
= 0;
877 track
->next_event_offset
= -1;
880 if (smf
->expected_number_of_tracks
!= smf
->number_of_tracks
) {
881 g_warning("SMF warning: MThd header declared %d tracks, but only %d found; continuing anyway.",
882 smf
->expected_number_of_tracks
, smf
->number_of_tracks
);
884 smf
->expected_number_of_tracks
= smf
->number_of_tracks
;
887 smf
->file_buffer
= NULL
;
888 smf
->file_buffer_length
= 0;
889 smf
->next_chunk_offset
= -1;
897 * \param file_name Path to the file.
898 * \return SMF or NULL, if loading failed.
901 smf_load(const char *file_name
)
903 int file_buffer_length
;
907 if (load_file_into_buffer(&file_buffer
, &file_buffer_length
, file_name
))
910 smf
= smf_load_from_memory(file_buffer
, file_buffer_length
);
912 memset(file_buffer
, 0, file_buffer_length
);