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
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 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 General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, 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[0]; /* 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));
178 /* We've had a valid SMF header - now skip it*/
179 if (stream_Read (stream, NULL, 14) < 14)
182 p_demux->pf_demux = Demux;
183 p_demux->pf_control = Control;
184 p_demux->p_sys = p_sys;
186 /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
187 date_Init (&p_sys->pts, ppqn * 2, 1);
188 date_Set (&p_sys->pts, 0);
192 p_sys->trackc = tracks;
193 /* Prefetch track offsets */
194 for (unsigned i = 0; i < tracks; i++)
200 /* Seeking screws streaming up, but there is no way around this,
201 * as SMF1 tracks are performed simultaneously.
202 * Not a big deal as SMF1 are usually only a few kbytes anyway. */
203 if (stream_Seek (stream, p_sys->trackv[i-1].end))
205 msg_Err (p_this, "cannot build SMF index (corrupted file?)");
212 if (stream_Read (stream, head, 8) < 8)
214 /* FIXME: don't give up if we have at least one valid track */
215 msg_Err (p_this, "incomplete SMF chunk, file is corrupted");
219 if (memcmp (head, "MTrk", 4) == 0)
222 msg_Dbg (p_this, "skipping unknown SMF chunk");
223 stream_Read (stream, NULL, GetDWBE (head + 4));
226 p_sys->trackv[i].offset = stream_Tell (stream);
227 p_sys->trackv[i].end = p_sys->trackv[i].offset + GetDWBE (head + 4);
228 p_sys->trackv[i].next = 0;
229 ReadDeltaTime (stream, p_sys->trackv + i);
230 p_sys->trackv[i].running_event = 0xF6;
231 /* Why 0xF6 (Tuning Calibration)?
232 * Because it has zero bytes of data, so the parser will detect the
233 * error if the first event uses running status. */
237 es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MIDI);
238 fmt.audio.i_channels = 2;
239 fmt.audio.i_rate = 44100; /* dummy value */
240 p_sys->es = es_out_Add (p_demux->out, &fmt);
250 * Releases allocate resources.
252 static void Close (vlc_object_t * p_this)
254 demux_t *p_demux = (demux_t *)p_this;
255 demux_sys_t *p_sys = p_demux->p_sys;
261 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
262 * @return read value, or -1 on EOF/error.
264 static int32_t ReadVarInt (stream_t *s)
269 for (unsigned i = 0; i < 4; i++)
271 if (stream_Read (s, &byte, 1) < 1)
274 val = (val << 7) | (byte & 0x7f);
275 if ((byte & 0x80) == 0)
284 * Reads (delta) time from the next event of a given track.
285 * @param s stream to read data from (must be positioned at the right offset)
287 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
291 assert (stream_Tell (s) == track->offset);
293 if (track->offset >= track->end)
295 /* This track is done */
296 track->next = UINT64_MAX;
300 delta_time = ReadVarInt (s);
304 track->next += delta_time;
305 track->offset = stream_Tell (s);
311 * Non-MIDI Meta events handler
314 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
316 stream_t *s = p_demux->s;
317 demux_sys_t *p_sys = p_demux->p_sys;
323 if (stream_Read (s, &type, 1) != 1)
326 length = ReadVarInt (s);
330 payload = malloc (length + 1);
331 if ((payload == NULL)
332 || (stream_Read (s, payload, length) != length))
338 payload[length] = '\0';
342 case 0x00: /* Sequence Number */
345 case 0x01: /* Text (comment) */
346 EnsureUTF8 ((char *)payload);
347 msg_Info (p_demux, "Text : %s", (char *)payload);
350 case 0x02: /* Copyright */
351 EnsureUTF8 ((char *)payload);
352 msg_Info (p_demux, "Copyright : %s", (char *)payload);
355 case 0x03: /* Track name */
356 EnsureUTF8 ((char *)payload);
357 msg_Info (p_demux, "Track name: %s", (char *)payload);
360 case 0x04: /* Instrument name */
361 EnsureUTF8 ((char *)payload);
362 msg_Info (p_demux, "Instrument: %s", (char *)payload);
365 case 0x05: /* Lyric (one syllable) */
366 /*EnsureUTF8 ((char *)payload);*/
369 case 0x06: /* Marker text */
370 EnsureUTF8 ((char *)payload);
371 msg_Info (p_demux, "Marker : %s", (char *)payload);
373 case 0x07: /* Cue point (WAVE filename) */
374 EnsureUTF8 ((char *)payload);
375 msg_Info (p_demux, "Cue point : %s", (char *)payload);
378 case 0x08: /* Program/Patch name */
379 EnsureUTF8 ((char *)payload);
380 msg_Info (p_demux, "Patch name: %s", (char *)payload);
383 case 0x09: /* MIDI port name */
384 EnsureUTF8 ((char *)payload);
385 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
388 case 0x2F: /* End of track */
389 if (tr->end != stream_Tell (s))
391 msg_Err (p_demux, "misplaced end of track");
396 case 0x51: /* Tempo */
399 uint32_t uspqn = (payload[0] << 16)
400 | (payload[1] << 8) | payload[2];
401 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
402 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
403 (unsigned)uspqn, tempo);
405 if (tempo < TEMPO_MIN)
407 msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
411 if (tempo > TEMPO_MAX)
413 msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
416 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
422 case 0x54: /* SMPTE offset */
424 msg_Warn (p_demux, "SMPTE offset not implemented");
429 case 0x58: /* Time signature */
436 case 0x59: /* Key signature */
443 case 0x7f: /* Proprietary event */
444 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
449 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
460 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
462 stream_t *s = p_demux->s;
464 uint8_t first, event;
467 if (stream_Seek (s, tr->offset)
468 || (stream_Read (s, &first, 1) != 1))
471 event = (first & 0x80) ? first : tr->running_event;
473 switch (event & 0xf0)
475 case 0xF0: /* System Exclusive */
478 case 0xF0: /* System Specific start */
479 case 0xF7: /* System Specific continuation */
481 /* Variable length followed by SysEx event data */
482 int32_t len = ReadVarInt (s);
486 block = stream_Block (s, len);
489 block = block_Realloc (block, 1, len);
492 block->p_buffer[0] = event;
495 case 0xFF: /* SMF Meta Event */
496 if (HandleMeta (p_demux, tr))
498 /* We MUST NOT pass this event forward. It would be
499 * confused as a MIDI Reset real-time event. */
510 /* We cannot handle undefined "common" (non-real-time)
511 * events inside SMF, as we cannot differentiate a
512 * one byte delta-time (< 0x80) from event data. */
527 /* FIXME: one message per block is very inefficient */
528 block = block_New (p_demux, 1 + datalen);
532 block->p_buffer[0] = event;
535 stream_Read (s, block->p_buffer + 1, datalen);
541 msg_Err (p_demux, "malformatted MIDI event");
542 return -1; /* can't use implicit running status with empty payload! */
545 block->p_buffer[1] = first;
547 stream_Read (s, block->p_buffer + 2, datalen - 1);
551 block->i_dts = block->i_pts = VLC_TS_0 + date_Get (&p_demux->p_sys->pts);
552 es_out_Send (p_demux->out, p_demux->p_sys->es, block);
556 /* If event is not real-time, update running status */
557 tr->running_event = event;
559 tr->offset = stream_Tell (s);
563 /*****************************************************************************
564 * Demux: read chunks and send them to the synthesizer
565 *****************************************************************************
566 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
567 *****************************************************************************/
568 static int Demux (demux_t *p_demux)
570 stream_t *s = p_demux->s;
571 demux_sys_t *p_sys = p_demux->p_sys;
572 uint64_t pulse = p_sys->pulse, next_pulse = UINT64_MAX;
574 if (pulse == UINT64_MAX)
575 return 0; /* all tracks are done */
577 es_out_Control (p_demux->out, ES_OUT_SET_PCR, 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_New (p_demux, 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: