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>
30 #include <vlc_codecs.h>
31 #include <vlc_charset.h>
37 #define TEMPO_MAX 250 /* Beats per minute */
39 static int Open (vlc_object_t *);
40 static void Close (vlc_object_t *);
43 set_description (N_("SMF demuxer"))
44 set_category (CAT_INPUT)
45 set_subcategory (SUBCAT_INPUT_DEMUX)
46 set_capability ("demux", 20)
47 set_callbacks (Open, Close)
50 static int Demux (demux_t *);
51 static int Control (demux_t *, int i_query, va_list args);
53 typedef struct smf_track_t
55 int64_t offset; /* Read offset in the file (stream_Tell) */
56 int64_t end; /* End offset in the file */
57 uint64_t next; /* Time of next message (in term of pulses) */
58 uint8_t running_event; /* Running (previous) event */
61 static int ReadDeltaTime (stream_t *s, mtrk_t *track);
67 uint64_t pulse; /* Pulses counter */
69 unsigned ppqn; /* Pulses Per Quarter Note */
70 /* by the way, "quarter note" is "noire" in French */
72 unsigned trackc; /* Number of tracks */
73 mtrk_t trackv[0]; /* Track states */
76 /*****************************************************************************
77 * Open: check file and initializes structures
78 *****************************************************************************/
79 static int Open (vlc_object_t * p_this)
81 demux_t *p_demux = (demux_t *)p_this;
82 stream_t *stream = p_demux->s;
85 unsigned tracks, ppqn;
88 /* (Try to) parse the SMF header */
89 /* Header chunk always has 6 bytes payload */
90 if (stream_Peek (stream, &peek, 14) < 14)
93 /* Skip RIFF MIDI header if present */
94 if (!memcmp (peek, "RIFF", 4) && !memcmp (peek + 8, "RMID", 4))
96 uint32_t riff_len = GetDWLE (peek + 4);
98 msg_Dbg (p_this, "detected RIFF MIDI file (%u bytes)",
100 if ((stream_Read (stream, NULL, 12) < 12))
103 /* Look for the RIFF data chunk */
110 || (stream_Read (stream, chnk_hdr, 8) < 8))
114 chnk_len = GetDWLE (chnk_hdr + 4);
115 if (riff_len < chnk_len)
117 riff_len -= chnk_len;
119 if (!memcmp (chnk_hdr, "data", 4))
122 if (stream_Read (stream, NULL, chnk_len) < (ssize_t)chnk_len)
126 /* Read real SMF header. Assume RIFF data chunk length is proper. */
127 if (stream_Peek (stream, &peek, 14) < 14)
131 if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
135 /* First word: SMF type */
136 switch (GetWBE (peek))
145 /* We don't implement SMF2 (as do many) */
146 msg_Err (p_this, "unsupported SMF file type %u", GetWBE (peek));
151 /* Second word: number of tracks */
152 tracks = GetWBE (peek);
154 if (!multitrack && (tracks != 1))
156 msg_Err (p_this, "invalid SMF type 0 file");
160 msg_Dbg (p_this, "detected Standard MIDI File (type %u) with %u track(s)",
163 /* Third/last word: timing */
164 ppqn = GetWBE (peek);
168 msg_Err (p_this, "SMPTE timestamps not implemented");
173 msg_Dbg (p_this, " %u pulses per quarter note", ppqn);
176 p_sys = malloc (sizeof (*p_sys) + (sizeof (mtrk_t) * tracks));
180 /* We've had a valid SMF header - now skip it*/
181 if (stream_Read (stream, NULL, 14) < 14)
184 p_demux->pf_demux = Demux;
185 p_demux->pf_control = Control;
186 p_demux->p_sys = p_sys;
188 /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
189 date_Init (&p_sys->pts, ppqn * 2, 1);
190 date_Set (&p_sys->pts, 1);
194 p_sys->trackc = tracks;
195 /* Prefetch track offsets */
196 for (unsigned i = 0; i < tracks; i++)
202 /* Seeking screws streaming up, but there is no way around this,
203 * as SMF1 tracks are performed simultaneously.
204 * Not a big deal as SMF1 are usually only a few kbytes anyway. */
205 if (stream_Seek (stream, p_sys->trackv[i-1].end))
207 msg_Err (p_this, "cannot build SMF index (corrupted file?)");
214 stream_Read (stream, head, 8);
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_original_channels = fmt.audio.i_physical_channels =
236 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
237 fmt.audio.i_rate = 44100; /* dummy value */
238 p_sys->es = es_out_Add (p_demux->out, &fmt);
248 * Releases allocate resources.
250 static void Close (vlc_object_t * p_this)
252 demux_t *p_demux = (demux_t *)p_this;
253 demux_sys_t *p_sys = p_demux->p_sys;
259 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
260 * @return read value, or -1 on EOF/error.
262 static int32_t ReadVarInt (stream_t *s)
267 for (unsigned i = 0; i < 4; i++)
269 if (stream_Read (s, &byte, 1) < 1)
272 val = (val << 7) | (byte & 0x7f);
273 if ((byte & 0x80) == 0)
282 * Reads (delta) time from the next event of a given track.
283 * @param s stream to read data from (must be positioned at the right offset)
285 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
289 assert (stream_Tell (s) == track->offset);
291 if (track->offset >= track->end)
293 /* This track is done */
294 track->next = UINT64_MAX;
298 delta_time = ReadVarInt (s);
302 track->next += delta_time;
303 track->offset = stream_Tell (s);
309 * Non-MIDI Meta events handler
312 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
314 stream_t *s = p_demux->s;
315 demux_sys_t *p_sys = p_demux->p_sys;
321 if (stream_Read (s, &type, 1) != 1)
324 length = ReadVarInt (s);
328 payload = malloc (length + 1);
329 if ((payload == NULL)
330 || (stream_Read (s, payload, length) != length))
336 payload[length] = '\0';
340 case 0x00: /* Sequence Number */
343 case 0x01: /* Text (comment) */
344 EnsureUTF8 ((char *)payload);
345 msg_Info (p_demux, "Text : %s", (char *)payload);
348 case 0x02: /* Copyright */
349 EnsureUTF8 ((char *)payload);
350 msg_Info (p_demux, "Copyright : %s", (char *)payload);
353 case 0x03: /* Track name */
354 EnsureUTF8 ((char *)payload);
355 msg_Info (p_demux, "Track name: %s", (char *)payload);
358 case 0x04: /* Instrument name */
359 EnsureUTF8 ((char *)payload);
360 msg_Info (p_demux, "Instrument: %s", (char *)payload);
363 case 0x05: /* Lyric (one syllable) */
364 /*EnsureUTF8 ((char *)payload);*/
367 case 0x06: /* Marker text */
368 EnsureUTF8 ((char *)payload);
369 msg_Info (p_demux, "Marker : %s", (char *)payload);
371 case 0x07: /* Cue point (WAVE filename) */
372 EnsureUTF8 ((char *)payload);
373 msg_Info (p_demux, "Cue point : %s", (char *)payload);
376 case 0x08: /* Program/Patch name */
377 EnsureUTF8 ((char *)payload);
378 msg_Info (p_demux, "Patch name: %s", (char *)payload);
381 case 0x09: /* MIDI port name */
382 EnsureUTF8 ((char *)payload);
383 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
386 case 0x2F: /* End of track */
387 if (tr->end != stream_Tell (s))
389 msg_Err (p_demux, "misplaced end of track");
394 case 0x51: /* Tempo */
397 uint32_t uspqn = (payload[0] << 16)
398 | (payload[1] << 8) | payload[2];
399 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
400 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
401 (unsigned)uspqn, tempo);
403 if (tempo < TEMPO_MIN)
405 msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
409 if (tempo > TEMPO_MAX)
411 msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
414 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
420 case 0x54: /* SMPTE offset */
422 msg_Warn (p_demux, "SMPTE offset not implemented");
427 case 0x58: /* Time signature */
434 case 0x59: /* Key signature */
441 case 0x7f: /* Proprietary event */
442 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
447 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
458 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
460 stream_t *s = p_demux->s;
462 uint8_t first, event;
465 if (stream_Seek (s, tr->offset)
466 || (stream_Read (s, &first, 1) != 1))
469 event = (first & 0x80) ? first : tr->running_event;
471 switch (event & 0xf0)
473 case 0xF0: /* System Exclusive */
476 case 0xF0: /* System Specific */
478 /* TODO: don't skip these */
479 stream_Read (s, NULL, 1); /* Manuf ID */
483 if (stream_Read (s, &c, 1) != 1)
490 case 0xFF: /* SMF Meta Event */
491 if (HandleMeta (p_demux, tr))
493 /* We MUST NOT pass this event forward. It would be
494 * confused as a MIDI Reset real-time event. */
505 /* We cannot handle undefined "common" (non-real-time)
506 * events inside SMF, as we cannot differentiate a
507 * one byte delta-time (< 0x80) from event data. */
508 case 0xF7: /* End of sysex -> should never happen(?) */
509 msg_Err (p_demux, "unknown MIDI event 0x%02X", event);
510 return -1; /* undefined events */
524 /* FIXME: one message per block is very inefficient */
525 block = block_New (p_demux, 1 + datalen);
529 block->p_buffer[0] = event;
532 stream_Read (s, block->p_buffer + 1, datalen);
538 msg_Err (p_demux, "malformatted MIDI event");
539 return -1; /* can't use implicit running status with empty payload! */
542 block->p_buffer[1] = first;
544 stream_Read (s, block->p_buffer + 2, datalen - 1);
547 block->i_dts = block->i_pts = date_Get (&p_demux->p_sys->pts);
548 es_out_Send (p_demux->out, p_demux->p_sys->es, block);
552 /* If event is not real-time, update running status */
553 tr->running_event = event;
555 tr->offset = stream_Tell (s);
559 /*****************************************************************************
560 * Demux: read chunks and send them to the synthetizer
561 *****************************************************************************
562 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
563 *****************************************************************************/
564 static int Demux (demux_t *p_demux)
566 stream_t *s = p_demux->s;
567 demux_sys_t *p_sys = p_demux->p_sys;
568 uint64_t pulse = p_sys->pulse, next_pulse = UINT64_MAX;
570 if (pulse == UINT64_MAX)
571 return 0; /* all tracks are done */
573 es_out_Control (p_demux->out, ES_OUT_SET_PCR, date_Get (&p_sys->pts));
575 for (unsigned i = 0; i < p_sys->trackc; i++)
577 mtrk_t *track = p_sys->trackv + i;
579 while (track->next == pulse)
581 if (HandleMessage (p_demux, track)
582 || ReadDeltaTime (s, track))
584 msg_Err (p_demux, "fatal parsing error");
589 if (track->next < next_pulse)
590 next_pulse = track->next;
593 mtime_t cur_tick = (date_Get (&p_sys->pts) + 9999) / 10000, last_tick;
594 if (next_pulse != UINT64_MAX)
595 last_tick = date_Increment (&p_sys->pts, next_pulse - pulse) / 10000;
597 last_tick = cur_tick + 1;
599 /* MIDI Tick emulation (ping the decoder every 10ms) */
600 while (cur_tick < last_tick)
602 block_t *tick = block_New (p_demux, 1);
606 tick->p_buffer[0] = 0xF9;
607 tick->i_dts = tick->i_pts = cur_tick++ * 10000;
608 es_out_Send (p_demux->out, p_sys->es, tick);
611 p_sys->pulse = next_pulse;
617 /*****************************************************************************
619 *****************************************************************************/
620 static int Control (demux_t *p_demux, int i_query, va_list args)
622 demux_sys_t *p_sys = p_demux->p_sys;
628 *(va_arg (args, int64_t *)) = date_Get (&p_sys->pts);
634 case DEMUX_GET_POSITION:
635 case DEMUX_SET_POSITION:
636 case DEMUX_GET_LENGTH: