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 */
37 static int Open (vlc_object_t *);
38 static void Close (vlc_object_t *);
41 set_description (N_("SMF demuxer"))
42 set_category (CAT_INPUT)
43 set_subcategory (SUBCAT_INPUT_DEMUX)
44 set_capability ("demux", 20)
45 set_callbacks (Open, Close)
48 static int Demux (demux_t *);
49 static int Control (demux_t *, int i_query, va_list args);
51 typedef struct smf_track_t
53 int64_t offset; /* Read offset in the file (stream_Tell) */
54 int64_t end; /* End offset in the file */
55 uint64_t next; /* Time of next message (in term of pulses) */
56 uint8_t running_event; /* Running (previous) event */
59 static int ReadDeltaTime (stream_t *s, mtrk_t *track);
65 uint64_t pulse; /* Pulses counter */
67 unsigned ppqn; /* Pulses Per Quarter Note */
68 /* by the way, "quarter note" is "noire" in French */
70 unsigned trackc; /* Number of tracks */
71 mtrk_t trackv[]; /* Track states */
74 /*****************************************************************************
75 * Open: check file and initializes structures
76 *****************************************************************************/
77 static int Open (vlc_object_t * p_this)
79 demux_t *p_demux = (demux_t *)p_this;
80 stream_t *stream = p_demux->s;
83 unsigned tracks, ppqn;
86 /* (Try to) parse the SMF header */
87 /* Header chunk always has 6 bytes payload */
88 if (stream_Peek (stream, &peek, 14) < 14)
91 /* Skip RIFF MIDI header if present */
92 if (!memcmp (peek, "RIFF", 4) && !memcmp (peek + 8, "RMID", 4))
94 uint32_t riff_len = GetDWLE (peek + 4);
96 msg_Dbg (p_this, "detected RIFF MIDI file (%u bytes)",
98 if ((stream_Read (stream, NULL, 12) < 12))
101 /* Look for the RIFF data chunk */
108 || (stream_Read (stream, chnk_hdr, 8) < 8))
112 chnk_len = GetDWLE (chnk_hdr + 4);
113 if (riff_len < chnk_len)
115 riff_len -= chnk_len;
117 if (!memcmp (chnk_hdr, "data", 4))
120 if (stream_Read (stream, NULL, chnk_len) < (ssize_t)chnk_len)
124 /* Read real SMF header. Assume RIFF data chunk length is proper. */
125 if (stream_Peek (stream, &peek, 14) < 14)
129 if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
133 /* First word: SMF type */
134 switch (GetWBE (peek))
143 /* We don't implement SMF2 (as do many) */
144 msg_Err (p_this, "unsupported SMF file type %u", GetWBE (peek));
149 /* Second word: number of tracks */
150 tracks = GetWBE (peek);
152 if (!multitrack && (tracks != 1))
154 msg_Err (p_this, "invalid SMF type 0 file");
158 msg_Dbg (p_this, "detected Standard MIDI File (type %u) with %u track(s)",
161 /* Third/last word: timing */
162 ppqn = GetWBE (peek);
166 msg_Err (p_this, "SMPTE timestamps not implemented");
171 msg_Dbg (p_this, " %u pulses per quarter note", ppqn);
174 p_sys = malloc (sizeof (*p_sys) + (sizeof (mtrk_t) * tracks));
175 if (unlikely(p_sys == NULL))
178 /* We've had a valid SMF header - now skip it*/
179 if (stream_Read (stream, NULL, 14) < 14)
182 /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
183 date_Init (&p_sys->pts, ppqn * 2, 1);
184 date_Set (&p_sys->pts, 0);
188 p_sys->trackc = tracks;
189 /* Prefetch track offsets */
190 for (unsigned i = 0; i < tracks; i++)
196 /* Seeking screws streaming up, but there is no way around this,
197 * as SMF1 tracks are performed simultaneously.
198 * Not a big deal as SMF1 are usually only a few kbytes anyway. */
199 if (stream_Seek (stream, p_sys->trackv[i - 1].end))
201 msg_Err (p_this, "cannot build SMF index (corrupted file?)");
208 if (stream_Read (stream, head, 8) < 8)
210 /* FIXME: don't give up if we have at least one valid track */
211 msg_Err (p_this, "incomplete SMF chunk, file is corrupted");
215 if (memcmp (head, "MTrk", 4) == 0)
218 msg_Dbg (p_this, "skipping unknown SMF chunk");
219 stream_Read (stream, NULL, GetDWBE (head + 4));
222 p_sys->trackv[i].offset = stream_Tell (stream);
223 p_sys->trackv[i].end = p_sys->trackv[i].offset + GetDWBE (head + 4);
224 p_sys->trackv[i].next = 0;
225 ReadDeltaTime (stream, p_sys->trackv + i);
226 p_sys->trackv[i].running_event = 0xF6;
227 /* Why 0xF6 (Tuning Calibration)?
228 * Because it has zero bytes of data, so the parser will detect the
229 * error if the first event uses running status. */
233 es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MIDI);
234 fmt.audio.i_channels = 2;
235 fmt.audio.i_rate = 44100; /* dummy value */
236 p_sys->es = es_out_Add (p_demux->out, &fmt);
238 p_demux->pf_demux = Demux;
239 p_demux->pf_control = Control;
240 p_demux->p_sys = p_sys;
249 * Releases allocate resources.
251 static void Close (vlc_object_t * p_this)
253 demux_t *p_demux = (demux_t *)p_this;
254 demux_sys_t *p_sys = p_demux->p_sys;
260 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
261 * @return read value, or -1 on EOF/error.
263 static int32_t ReadVarInt (stream_t *s)
268 for (unsigned i = 0; i < 4; i++)
270 if (stream_Read (s, &byte, 1) < 1)
273 val = (val << 7) | (byte & 0x7f);
274 if ((byte & 0x80) == 0)
283 * Reads (delta) time from the next event of a given track.
284 * @param s stream to read data from (must be positioned at the right offset)
286 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
290 assert (stream_Tell (s) == track->offset);
292 if (track->offset >= track->end)
294 /* This track is done */
295 track->next = UINT64_MAX;
299 delta_time = ReadVarInt (s);
303 track->next += delta_time;
304 track->offset = stream_Tell (s);
310 * Non-MIDI Meta events handler
313 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
315 stream_t *s = p_demux->s;
316 demux_sys_t *p_sys = p_demux->p_sys;
322 if (stream_Read (s, &type, 1) != 1)
325 length = ReadVarInt (s);
329 payload = malloc (length + 1);
330 if ((payload == NULL)
331 || (stream_Read (s, payload, length) != length))
337 payload[length] = '\0';
341 case 0x00: /* Sequence Number */
344 case 0x01: /* Text (comment) */
345 EnsureUTF8 ((char *)payload);
346 msg_Info (p_demux, "Text : %s", (char *)payload);
349 case 0x02: /* Copyright */
350 EnsureUTF8 ((char *)payload);
351 msg_Info (p_demux, "Copyright : %s", (char *)payload);
354 case 0x03: /* Track name */
355 EnsureUTF8 ((char *)payload);
356 msg_Info (p_demux, "Track name: %s", (char *)payload);
359 case 0x04: /* Instrument name */
360 EnsureUTF8 ((char *)payload);
361 msg_Info (p_demux, "Instrument: %s", (char *)payload);
364 case 0x05: /* Lyric (one syllable) */
365 /*EnsureUTF8 ((char *)payload);*/
368 case 0x06: /* Marker text */
369 EnsureUTF8 ((char *)payload);
370 msg_Info (p_demux, "Marker : %s", (char *)payload);
372 case 0x07: /* Cue point (WAVE filename) */
373 EnsureUTF8 ((char *)payload);
374 msg_Info (p_demux, "Cue point : %s", (char *)payload);
377 case 0x08: /* Program/Patch name */
378 EnsureUTF8 ((char *)payload);
379 msg_Info (p_demux, "Patch name: %s", (char *)payload);
382 case 0x09: /* MIDI port name */
383 EnsureUTF8 ((char *)payload);
384 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
387 case 0x2F: /* End of track */
388 if (tr->end != stream_Tell (s))
390 msg_Err (p_demux, "misplaced end of track");
395 case 0x51: /* Tempo */
398 uint32_t uspqn = (payload[0] << 16)
399 | (payload[1] << 8) | payload[2];
400 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
401 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
402 (unsigned)uspqn, tempo);
404 if (tempo < TEMPO_MIN)
406 msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
410 if (tempo > TEMPO_MAX)
412 msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
415 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
421 case 0x54: /* SMPTE offset */
423 msg_Warn (p_demux, "SMPTE offset not implemented");
428 case 0x58: /* Time signature */
435 case 0x59: /* Key signature */
442 case 0x7f: /* Proprietary event */
443 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
448 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
459 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
461 stream_t *s = p_demux->s;
463 uint8_t first, event;
466 if (stream_Seek (s, tr->offset)
467 || (stream_Read (s, &first, 1) != 1))
470 event = (first & 0x80) ? first : tr->running_event;
472 switch (event & 0xf0)
474 case 0xF0: /* System Exclusive */
477 case 0xF0: /* System Specific start */
478 case 0xF7: /* System Specific continuation */
480 /* Variable length followed by SysEx event data */
481 int32_t len = ReadVarInt (s);
485 block = stream_Block (s, len);
488 block = block_Realloc (block, 1, len);
491 block->p_buffer[0] = event;
494 case 0xFF: /* SMF Meta Event */
495 if (HandleMeta (p_demux, tr))
497 /* We MUST NOT pass this event forward. It would be
498 * confused as a MIDI Reset real-time event. */
509 /* We cannot handle undefined "common" (non-real-time)
510 * events inside SMF, as we cannot differentiate a
511 * one byte delta-time (< 0x80) from event data. */
526 /* FIXME: one message per block is very inefficient */
527 block = block_Alloc (1 + datalen);
531 block->p_buffer[0] = event;
534 stream_Read (s, block->p_buffer + 1, datalen);
540 msg_Err (p_demux, "malformatted MIDI event");
541 return -1; /* implicit running status requires non-empty payload */
544 block->p_buffer[1] = first;
546 stream_Read (s, block->p_buffer + 2, datalen - 1);
550 block->i_dts = block->i_pts = VLC_TS_0 + date_Get (&p_demux->p_sys->pts);
551 es_out_Send (p_demux->out, p_demux->p_sys->es, block);
555 /* If event is not real-time, update running status */
556 tr->running_event = event;
558 tr->offset = stream_Tell (s);
562 /*****************************************************************************
563 * Demux: read chunks and send them to the synthesizer
564 *****************************************************************************
565 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
566 *****************************************************************************/
567 static int Demux (demux_t *p_demux)
569 stream_t *s = p_demux->s;
570 demux_sys_t *p_sys = p_demux->p_sys;
571 uint64_t pulse = p_sys->pulse, next_pulse = UINT64_MAX;
573 if (pulse == UINT64_MAX)
574 return 0; /* all tracks are done */
576 es_out_Control (p_demux->out, ES_OUT_SET_PCR,
577 VLC_TS_0 + date_Get (&p_sys->pts));
579 for (unsigned i = 0; i < p_sys->trackc; i++)
581 mtrk_t *track = p_sys->trackv + i;
583 while (track->next == pulse)
585 if (HandleMessage (p_demux, track)
586 || ReadDeltaTime (s, track))
588 msg_Err (p_demux, "fatal parsing error");
593 if (track->next < next_pulse)
594 next_pulse = track->next;
597 mtime_t cur_tick = (date_Get (&p_sys->pts) + 9999) / 10000, last_tick;
598 if (next_pulse != UINT64_MAX)
599 last_tick = date_Increment (&p_sys->pts, next_pulse - pulse) / 10000;
601 last_tick = cur_tick + 1;
603 /* MIDI Tick emulation (ping the decoder every 10ms) */
604 while (cur_tick < last_tick)
606 block_t *tick = block_Alloc (1);
610 tick->p_buffer[0] = 0xF9;
611 tick->i_dts = tick->i_pts = VLC_TS_0 + cur_tick++ * 10000;
612 es_out_Send (p_demux->out, p_sys->es, tick);
615 p_sys->pulse = next_pulse;
621 /*****************************************************************************
623 *****************************************************************************/
624 static int Control (demux_t *p_demux, int i_query, va_list args)
626 demux_sys_t *p_sys = p_demux->p_sys;
632 *(va_arg (args, int64_t *)) = date_Get (&p_sys->pts);
638 case DEMUX_GET_POSITION:
639 case DEMUX_SET_POSITION:
640 case DEMUX_GET_LENGTH: