1 /*****************************************************************************
2 * smf.c : Standard MIDI File (.mid) demux module for vlc
3 *****************************************************************************
4 * Copyright © 2007 Rémi Denis-Courmont
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as published by
9 * the Free Software Foundation; either version 2.1 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
20 *****************************************************************************/
26 #include <vlc_common.h>
27 #include <vlc_plugin.h>
28 #include <vlc_demux.h>
29 #include <vlc_charset.h>
35 #define TEMPO_MAX 250 /* Beats per minute */
38 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
39 * @return read value, or -1 on EOF/error.
41 static int32_t ReadVarInt (stream_t *s)
46 for (unsigned i = 0; i < 4; i++)
48 if (stream_Read (s, &byte, 1) < 1)
51 val = (val << 7) | (byte & 0x7f);
52 if ((byte & 0x80) == 0)
59 typedef struct smf_track_t
61 int64_t offset; /* Read offset in the file (stream_Tell) */
62 int64_t end; /* End offset in the file */
63 uint64_t next; /* Time of next message (in term of pulses) */
64 uint8_t running_event; /* Running (previous) event */
68 * Reads (delta) time from the next event of a given track.
69 * @param s stream to read data from (must be positioned at the right offset)
71 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
75 assert (stream_Tell (s) == track->offset);
77 if (track->offset >= track->end)
79 /* This track is done */
80 track->next = UINT64_MAX;
84 delta_time = ReadVarInt (s);
88 track->next += delta_time;
89 track->offset = stream_Tell (s);
96 date_t pts; /*< Play timestamp */
97 uint64_t pulse; /*< Pulses counter */
98 mtime_t tick; /*< Last tick timestamp */
100 unsigned ppqn; /*< Pulses Per Quarter Note */
101 /* by the way, "quarter note" is "noire" in French */
103 unsigned trackc; /*< Number of tracks */
104 mtrk_t trackv[]; /*< Track states */
108 * Non-MIDI Meta events handler
111 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
113 stream_t *s = p_demux->s;
114 demux_sys_t *p_sys = p_demux->p_sys;
120 if (stream_Read (s, &type, 1) != 1)
123 length = ReadVarInt (s);
127 payload = malloc (length + 1);
128 if ((payload == NULL)
129 || (stream_Read (s, payload, length) != length))
135 payload[length] = '\0';
139 case 0x00: /* Sequence Number */
142 case 0x01: /* Text (comment) */
143 EnsureUTF8 ((char *)payload);
144 msg_Info (p_demux, "Text : %s", (char *)payload);
147 case 0x02: /* Copyright */
148 EnsureUTF8 ((char *)payload);
149 msg_Info (p_demux, "Copyright : %s", (char *)payload);
152 case 0x03: /* Track name */
153 EnsureUTF8 ((char *)payload);
154 msg_Info (p_demux, "Track name: %s", (char *)payload);
157 case 0x04: /* Instrument name */
158 EnsureUTF8 ((char *)payload);
159 msg_Info (p_demux, "Instrument: %s", (char *)payload);
162 case 0x05: /* Lyric (one syllable) */
163 /*EnsureUTF8 ((char *)payload);*/
166 case 0x06: /* Marker text */
167 EnsureUTF8 ((char *)payload);
168 msg_Info (p_demux, "Marker : %s", (char *)payload);
170 case 0x07: /* Cue point (WAVE filename) */
171 EnsureUTF8 ((char *)payload);
172 msg_Info (p_demux, "Cue point : %s", (char *)payload);
175 case 0x08: /* Program/Patch name */
176 EnsureUTF8 ((char *)payload);
177 msg_Info (p_demux, "Patch name: %s", (char *)payload);
180 case 0x09: /* MIDI port name */
181 EnsureUTF8 ((char *)payload);
182 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
185 case 0x2F: /* End of track */
186 if (tr->end != stream_Tell (s))
188 msg_Err (p_demux, "misplaced end of track");
193 case 0x51: /* Tempo */
196 uint32_t uspqn = (payload[0] << 16)
197 | (payload[1] << 8) | payload[2];
198 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
199 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
200 (unsigned)uspqn, tempo);
202 if (tempo < TEMPO_MIN)
204 msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
208 if (tempo > TEMPO_MAX)
210 msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
213 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
219 case 0x54: /* SMPTE offset */
221 msg_Warn (p_demux, "SMPTE offset not implemented");
226 case 0x58: /* Time signature */
233 case 0x59: /* Key signature */
240 case 0x7f: /* Proprietary event */
241 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
246 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
255 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
257 stream_t *s = p_demux->s;
259 uint8_t first, event;
262 if (stream_Seek (s, tr->offset)
263 || (stream_Read (s, &first, 1) != 1))
266 event = (first & 0x80) ? first : tr->running_event;
268 switch (event & 0xf0)
270 case 0xF0: /* System Exclusive */
273 case 0xF0: /* System Specific start */
274 case 0xF7: /* System Specific continuation */
276 /* Variable length followed by SysEx event data */
277 int32_t len = ReadVarInt (s);
281 block = stream_Block (s, len);
284 block = block_Realloc (block, 1, len);
287 block->p_buffer[0] = event;
290 case 0xFF: /* SMF Meta Event */
291 if (HandleMeta (p_demux, tr))
293 /* We MUST NOT pass this event forward. It would be
294 * confused as a MIDI Reset real-time event. */
305 /* We cannot handle undefined "common" (non-real-time)
306 * events inside SMF, as we cannot differentiate a
307 * one byte delta-time (< 0x80) from event data. */
322 /* FIXME: one message per block is very inefficient */
323 block = block_Alloc (1 + datalen);
327 block->p_buffer[0] = event;
330 stream_Read (s, block->p_buffer + 1, datalen);
336 msg_Err (p_demux, "malformatted MIDI event");
337 return -1; /* implicit running status requires non-empty payload */
340 block->p_buffer[1] = first;
342 stream_Read (s, block->p_buffer + 2, datalen - 1);
346 block->i_dts = block->i_pts = date_Get (&p_demux->p_sys->pts);
347 es_out_Send (p_demux->out, p_demux->p_sys->es, block);
351 /* If event is not real-time, update running status */
352 tr->running_event = event;
354 tr->offset = stream_Tell (s);
358 /*****************************************************************************
359 * Demux: read chunks and send them to the synthesizer
360 *****************************************************************************
361 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
362 *****************************************************************************/
363 static int Demux (demux_t *demux)
365 demux_sys_t *sys = demux->p_sys;
367 /* MIDI Tick emulation (ping the decoder every 10ms) */
368 if (sys->tick <= date_Get (&sys->pts))
370 block_t *tick = block_Alloc (1);
371 if (unlikely(tick == NULL))
374 tick->p_buffer[0] = 0xF9;
375 tick->i_dts = tick->i_pts = sys->tick;
377 es_out_Send (demux->out, sys->es, tick);
378 es_out_Control (demux->out, ES_OUT_SET_PCR, sys->tick);
380 sys->tick += CLOCK_FREQ / 100;
384 /* MIDI events in chronological order across all tracks */
385 uint64_t cur_pulse = sys->pulse, next_pulse = UINT64_MAX;
387 for (unsigned i = 0; i < sys->trackc; i++)
389 mtrk_t *track = sys->trackv + i;
391 while (track->next == cur_pulse)
393 if (HandleMessage (demux, track)
394 || ReadDeltaTime (demux->s, track))
396 msg_Err (demux, "fatal parsing error");
401 if (next_pulse > track->next)
402 next_pulse = track->next;
405 if (next_pulse == UINT64_MAX)
406 return 0; /* all tracks are done */
408 date_Increment (&sys->pts, next_pulse - cur_pulse);
409 sys->pulse = next_pulse;
413 /*****************************************************************************
415 *****************************************************************************/
416 static int Control (demux_t *p_demux, int i_query, va_list args)
418 demux_sys_t *sys = p_demux->p_sys;
423 *va_arg (args, int64_t *) = sys->tick - VLC_TS_0;
428 case DEMUX_GET_POSITION:
429 case DEMUX_SET_POSITION:
430 case DEMUX_GET_LENGTH:
437 * Probes file format and starts demuxing.
439 static int Open (vlc_object_t *obj)
441 demux_t *demux = (demux_t *)obj;
442 stream_t *stream = demux->s;
446 /* (Try to) parse the SMF header */
447 /* Header chunk always has 6 bytes payload */
448 if (stream_Peek (stream, &peek, 14) < 14)
451 /* Skip RIFF MIDI header if present */
452 if (!memcmp (peek, "RIFF", 4) && !memcmp (peek + 8, "RMID", 4))
454 uint32_t riff_len = GetDWLE (peek + 4);
456 msg_Dbg (demux, "detected RIFF MIDI file (%"PRIu32" bytes)", riff_len);
457 if ((stream_Read (stream, NULL, 12) < 12))
460 /* Look for the RIFF data chunk */
467 || (stream_Read (stream, chnk_hdr, 8) < 8))
471 chnk_len = GetDWLE (chnk_hdr + 4);
472 if (riff_len < chnk_len)
474 riff_len -= chnk_len;
476 if (!memcmp (chnk_hdr, "data", 4))
479 if (stream_Read (stream, NULL, chnk_len) < (ssize_t)chnk_len)
483 /* Read real SMF header. Assume RIFF data chunk length is proper. */
484 if (stream_Peek (stream, &peek, 14) < 14)
488 if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
492 /* First word: SMF type */
493 switch (GetWBE (peek))
502 /* We don't implement SMF2 (as do many) */
503 msg_Err (demux, "unsupported SMF file type %u", GetWBE (peek));
508 /* Second word: number of tracks */
509 unsigned tracks = GetWBE (peek);
511 if (!multitrack && (tracks != 1))
513 msg_Err (demux, "invalid SMF type 0 file");
517 msg_Dbg (demux, "detected Standard MIDI File (type %u) with %u track(s)",
520 /* Third/last word: timing */
521 unsigned ppqn = GetWBE (peek);
524 msg_Err (demux, "SMPTE timestamps not implemented");
529 msg_Dbg (demux, " %u pulses per quarter note", ppqn);
532 demux_sys_t *sys = malloc (sizeof (*sys) + (sizeof (mtrk_t) * tracks));
533 if (unlikely(sys == NULL))
536 /* We've had a valid SMF header - now skip it*/
537 if (stream_Read (stream, NULL, 14) < 14)
540 /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
541 date_Init (&sys->pts, ppqn * 2, 1);
542 date_Set (&sys->pts, VLC_TS_0);
544 sys->tick = VLC_TS_0;
547 sys->trackc = tracks;
548 /* Prefetch track offsets */
549 for (unsigned i = 0; i < tracks; i++)
555 /* Seeking screws streaming up, but there is no way around this,
556 * as SMF1 tracks are performed simultaneously.
557 * Not a big deal as SMF1 are usually only a few kbytes anyway. */
558 if (stream_Seek (stream, sys->trackv[i - 1].end))
560 msg_Err (demux, "cannot build SMF index (corrupted file?)");
567 if (stream_Read (stream, head, 8) < 8)
569 /* FIXME: don't give up if we have at least one valid track */
570 msg_Err (demux, "incomplete SMF chunk, file is corrupted");
574 if (memcmp (head, "MTrk", 4) == 0)
577 msg_Dbg (demux, "skipping unknown SMF chunk");
578 stream_Read (stream, NULL, GetDWBE (head + 4));
581 sys->trackv[i].offset = stream_Tell (stream);
582 sys->trackv[i].end = sys->trackv[i].offset + GetDWBE (head + 4);
583 sys->trackv[i].next = 0;
584 ReadDeltaTime (stream, sys->trackv + i);
585 sys->trackv[i].running_event = 0xF6;
586 /* Why 0xF6 (Tuning Calibration)?
587 * Because it has zero bytes of data, so the parser will detect the
588 * error if the first event uses running status. */
592 es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MIDI);
593 fmt.audio.i_channels = 2;
594 fmt.audio.i_rate = 44100; /* dummy value */
595 sys->es = es_out_Add (demux->out, &fmt);
597 demux->pf_demux = Demux;
598 demux->pf_control = Control;
608 * Releases allocate resources.
610 static void Close (vlc_object_t * p_this)
612 demux_t *p_demux = (demux_t *)p_this;
613 demux_sys_t *p_sys = p_demux->p_sys;
619 set_description (N_("SMF demuxer"))
620 set_category (CAT_INPUT)
621 set_subcategory (SUBCAT_INPUT_DEMUX)
622 set_capability ("demux", 20)
623 set_callbacks (Open, Close)