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);
97 uint64_t pulse; /* Pulses counter */
99 unsigned ppqn; /* Pulses Per Quarter Note */
100 /* by the way, "quarter note" is "noire" in French */
102 unsigned trackc; /* Number of tracks */
103 mtrk_t trackv[]; /* Track states */
107 * Non-MIDI Meta events handler
110 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
112 stream_t *s = p_demux->s;
113 demux_sys_t *p_sys = p_demux->p_sys;
119 if (stream_Read (s, &type, 1) != 1)
122 length = ReadVarInt (s);
126 payload = malloc (length + 1);
127 if ((payload == NULL)
128 || (stream_Read (s, payload, length) != length))
134 payload[length] = '\0';
138 case 0x00: /* Sequence Number */
141 case 0x01: /* Text (comment) */
142 EnsureUTF8 ((char *)payload);
143 msg_Info (p_demux, "Text : %s", (char *)payload);
146 case 0x02: /* Copyright */
147 EnsureUTF8 ((char *)payload);
148 msg_Info (p_demux, "Copyright : %s", (char *)payload);
151 case 0x03: /* Track name */
152 EnsureUTF8 ((char *)payload);
153 msg_Info (p_demux, "Track name: %s", (char *)payload);
156 case 0x04: /* Instrument name */
157 EnsureUTF8 ((char *)payload);
158 msg_Info (p_demux, "Instrument: %s", (char *)payload);
161 case 0x05: /* Lyric (one syllable) */
162 /*EnsureUTF8 ((char *)payload);*/
165 case 0x06: /* Marker text */
166 EnsureUTF8 ((char *)payload);
167 msg_Info (p_demux, "Marker : %s", (char *)payload);
169 case 0x07: /* Cue point (WAVE filename) */
170 EnsureUTF8 ((char *)payload);
171 msg_Info (p_demux, "Cue point : %s", (char *)payload);
174 case 0x08: /* Program/Patch name */
175 EnsureUTF8 ((char *)payload);
176 msg_Info (p_demux, "Patch name: %s", (char *)payload);
179 case 0x09: /* MIDI port name */
180 EnsureUTF8 ((char *)payload);
181 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
184 case 0x2F: /* End of track */
185 if (tr->end != stream_Tell (s))
187 msg_Err (p_demux, "misplaced end of track");
192 case 0x51: /* Tempo */
195 uint32_t uspqn = (payload[0] << 16)
196 | (payload[1] << 8) | payload[2];
197 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
198 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
199 (unsigned)uspqn, tempo);
201 if (tempo < TEMPO_MIN)
203 msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
207 if (tempo > TEMPO_MAX)
209 msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
212 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
218 case 0x54: /* SMPTE offset */
220 msg_Warn (p_demux, "SMPTE offset not implemented");
225 case 0x58: /* Time signature */
232 case 0x59: /* Key signature */
239 case 0x7f: /* Proprietary event */
240 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
245 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
254 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
256 stream_t *s = p_demux->s;
258 uint8_t first, event;
261 if (stream_Seek (s, tr->offset)
262 || (stream_Read (s, &first, 1) != 1))
265 event = (first & 0x80) ? first : tr->running_event;
267 switch (event & 0xf0)
269 case 0xF0: /* System Exclusive */
272 case 0xF0: /* System Specific start */
273 case 0xF7: /* System Specific continuation */
275 /* Variable length followed by SysEx event data */
276 int32_t len = ReadVarInt (s);
280 block = stream_Block (s, len);
283 block = block_Realloc (block, 1, len);
286 block->p_buffer[0] = event;
289 case 0xFF: /* SMF Meta Event */
290 if (HandleMeta (p_demux, tr))
292 /* We MUST NOT pass this event forward. It would be
293 * confused as a MIDI Reset real-time event. */
304 /* We cannot handle undefined "common" (non-real-time)
305 * events inside SMF, as we cannot differentiate a
306 * one byte delta-time (< 0x80) from event data. */
321 /* FIXME: one message per block is very inefficient */
322 block = block_Alloc (1 + datalen);
326 block->p_buffer[0] = event;
329 stream_Read (s, block->p_buffer + 1, datalen);
335 msg_Err (p_demux, "malformatted MIDI event");
336 return -1; /* implicit running status requires non-empty payload */
339 block->p_buffer[1] = first;
341 stream_Read (s, block->p_buffer + 2, datalen - 1);
345 block->i_dts = block->i_pts = VLC_TS_0 + date_Get (&p_demux->p_sys->pts);
346 es_out_Send (p_demux->out, p_demux->p_sys->es, block);
350 /* If event is not real-time, update running status */
351 tr->running_event = event;
353 tr->offset = stream_Tell (s);
357 /*****************************************************************************
358 * Demux: read chunks and send them to the synthesizer
359 *****************************************************************************
360 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
361 *****************************************************************************/
362 static int Demux (demux_t *p_demux)
364 stream_t *s = p_demux->s;
365 demux_sys_t *p_sys = p_demux->p_sys;
366 uint64_t pulse = p_sys->pulse, next_pulse = UINT64_MAX;
368 if (pulse == UINT64_MAX)
369 return 0; /* all tracks are done */
371 es_out_Control (p_demux->out, ES_OUT_SET_PCR,
372 VLC_TS_0 + date_Get (&p_sys->pts));
374 for (unsigned i = 0; i < p_sys->trackc; i++)
376 mtrk_t *track = p_sys->trackv + i;
378 while (track->next == pulse)
380 if (HandleMessage (p_demux, track)
381 || ReadDeltaTime (s, track))
383 msg_Err (p_demux, "fatal parsing error");
388 if (track->next < next_pulse)
389 next_pulse = track->next;
392 mtime_t cur_tick = (date_Get (&p_sys->pts) + 9999) / 10000, last_tick;
393 if (next_pulse != UINT64_MAX)
394 last_tick = date_Increment (&p_sys->pts, next_pulse - pulse) / 10000;
396 last_tick = cur_tick + 1;
398 /* MIDI Tick emulation (ping the decoder every 10ms) */
399 while (cur_tick < last_tick)
401 block_t *tick = block_Alloc (1);
405 tick->p_buffer[0] = 0xF9;
406 tick->i_dts = tick->i_pts = VLC_TS_0 + cur_tick++ * 10000;
407 es_out_Send (p_demux->out, p_sys->es, tick);
410 p_sys->pulse = next_pulse;
415 /*****************************************************************************
417 *****************************************************************************/
418 static int Control (demux_t *p_demux, int i_query, va_list args)
420 demux_sys_t *p_sys = p_demux->p_sys;
426 *(va_arg (args, int64_t *)) = date_Get (&p_sys->pts);
432 case DEMUX_GET_POSITION:
433 case DEMUX_SET_POSITION:
434 case DEMUX_GET_LENGTH:
441 * Probes file format and starts demuxing.
443 static int Open (vlc_object_t *obj)
445 demux_t *demux = (demux_t *)obj;
446 stream_t *stream = demux->s;
450 /* (Try to) parse the SMF header */
451 /* Header chunk always has 6 bytes payload */
452 if (stream_Peek (stream, &peek, 14) < 14)
455 /* Skip RIFF MIDI header if present */
456 if (!memcmp (peek, "RIFF", 4) && !memcmp (peek + 8, "RMID", 4))
458 uint32_t riff_len = GetDWLE (peek + 4);
460 msg_Dbg (demux, "detected RIFF MIDI file (%"PRIu32" bytes)", riff_len);
461 if ((stream_Read (stream, NULL, 12) < 12))
464 /* Look for the RIFF data chunk */
471 || (stream_Read (stream, chnk_hdr, 8) < 8))
475 chnk_len = GetDWLE (chnk_hdr + 4);
476 if (riff_len < chnk_len)
478 riff_len -= chnk_len;
480 if (!memcmp (chnk_hdr, "data", 4))
483 if (stream_Read (stream, NULL, chnk_len) < (ssize_t)chnk_len)
487 /* Read real SMF header. Assume RIFF data chunk length is proper. */
488 if (stream_Peek (stream, &peek, 14) < 14)
492 if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
496 /* First word: SMF type */
497 switch (GetWBE (peek))
506 /* We don't implement SMF2 (as do many) */
507 msg_Err (demux, "unsupported SMF file type %u", GetWBE (peek));
512 /* Second word: number of tracks */
513 unsigned tracks = GetWBE (peek);
515 if (!multitrack && (tracks != 1))
517 msg_Err (demux, "invalid SMF type 0 file");
521 msg_Dbg (demux, "detected Standard MIDI File (type %u) with %u track(s)",
524 /* Third/last word: timing */
525 unsigned ppqn = GetWBE (peek);
528 msg_Err (demux, "SMPTE timestamps not implemented");
533 msg_Dbg (demux, " %u pulses per quarter note", ppqn);
536 demux_sys_t *sys = malloc (sizeof (*sys) + (sizeof (mtrk_t) * tracks));
537 if (unlikely(sys == NULL))
540 /* We've had a valid SMF header - now skip it*/
541 if (stream_Read (stream, NULL, 14) < 14)
544 /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
545 date_Init (&sys->pts, ppqn * 2, 1);
546 date_Set (&sys->pts, 0);
550 sys->trackc = tracks;
551 /* Prefetch track offsets */
552 for (unsigned i = 0; i < tracks; i++)
558 /* Seeking screws streaming up, but there is no way around this,
559 * as SMF1 tracks are performed simultaneously.
560 * Not a big deal as SMF1 are usually only a few kbytes anyway. */
561 if (stream_Seek (stream, sys->trackv[i - 1].end))
563 msg_Err (demux, "cannot build SMF index (corrupted file?)");
570 if (stream_Read (stream, head, 8) < 8)
572 /* FIXME: don't give up if we have at least one valid track */
573 msg_Err (demux, "incomplete SMF chunk, file is corrupted");
577 if (memcmp (head, "MTrk", 4) == 0)
580 msg_Dbg (demux, "skipping unknown SMF chunk");
581 stream_Read (stream, NULL, GetDWBE (head + 4));
584 sys->trackv[i].offset = stream_Tell (stream);
585 sys->trackv[i].end = sys->trackv[i].offset + GetDWBE (head + 4);
586 sys->trackv[i].next = 0;
587 ReadDeltaTime (stream, sys->trackv + i);
588 sys->trackv[i].running_event = 0xF6;
589 /* Why 0xF6 (Tuning Calibration)?
590 * Because it has zero bytes of data, so the parser will detect the
591 * error if the first event uses running status. */
595 es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MIDI);
596 fmt.audio.i_channels = 2;
597 fmt.audio.i_rate = 44100; /* dummy value */
598 sys->es = es_out_Add (demux->out, &fmt);
600 demux->pf_demux = Demux;
601 demux->pf_control = Control;
611 * Releases allocate resources.
613 static void Close (vlc_object_t * p_this)
615 demux_t *p_demux = (demux_t *)p_this;
616 demux_sys_t *p_sys = p_demux->p_sys;
622 set_description (N_("SMF demuxer"))
623 set_category (CAT_INPUT)
624 set_subcategory (SUBCAT_INPUT_DEMUX)
625 set_capability ("demux", 20)
626 set_callbacks (Open, Close)