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 *****************************************************************************/
27 #include <vlc_plugin.h>
28 #include <vlc_demux.h>
30 #include <vlc_codecs.h>
31 #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 (_("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, 1);
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 stream_Read (stream, head, 8);
213 if (memcmp (head, "MTrk", 4) == 0)
216 msg_Dbg (p_this, "skipping unknown SMF chunk");
217 stream_Read (stream, NULL, GetDWBE (head + 4));
220 p_sys->trackv[i].offset = stream_Tell (stream);
221 p_sys->trackv[i].end = p_sys->trackv[i].offset + GetDWBE (head + 4);
222 p_sys->trackv[i].next = 0;
223 ReadDeltaTime (stream, p_sys->trackv + i);
224 p_sys->trackv[i].running_event = 0xF6;
225 /* Why 0xF6 (Tuning Calibration)?
226 * Because it has zero bytes of data, so the parser will detect the
227 * error if the first event uses running status. */
231 es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC('M', 'I', 'D', 'I'));
232 p_sys->es = es_out_Add (p_demux->out, &fmt);
242 * Releases allocate resources.
244 static void Close (vlc_object_t * p_this)
246 demux_t *p_demux = (demux_t *)p_this;
247 demux_sys_t *p_sys = p_demux->p_sys;
253 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
254 * @return read value, or -1 on EOF/error.
256 static int32_t ReadVarInt (stream_t *s)
261 for (unsigned i = 0; i < 4; i++)
263 if (stream_Read (s, &byte, 1) < 1)
266 val = (val << 7) | (byte & 0x7f);
267 if ((byte & 0x80) == 0)
276 * Reads (delta) time from the next event of a given track.
277 * @param s stream to read data from (must be positioned at the right offset)
279 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
283 assert (stream_Tell (s) == track->offset);
285 if (track->offset >= track->end)
287 /* This track is done */
288 track->next = UINT64_MAX;
292 delta_time = ReadVarInt (s);
296 track->next += delta_time;
297 track->offset = stream_Tell (s);
303 * Non-MIDI Meta events handler
306 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
308 stream_t *s = p_demux->s;
309 demux_sys_t *p_sys = p_demux->p_sys;
315 if (stream_Read (s, &type, 1) != 1)
318 length = ReadVarInt (s);
322 payload = malloc (length + 1);
323 if ((payload == NULL)
324 || (stream_Read (s, payload, length) != length))
330 payload[length] = '\0';
334 case 0x00: /* Sequence Number */
337 case 0x01: /* Text (comment) */
338 EnsureUTF8 ((char *)payload);
339 msg_Info (p_demux, "Text : %s", (char *)payload);
342 case 0x02: /* Copyright */
343 EnsureUTF8 ((char *)payload);
344 msg_Info (p_demux, "Copyright : %s", (char *)payload);
347 case 0x03: /* Track name */
348 EnsureUTF8 ((char *)payload);
349 msg_Info (p_demux, "Track name: %s", (char *)payload);
352 case 0x04: /* Instrument name */
353 EnsureUTF8 ((char *)payload);
354 msg_Info (p_demux, "Instrument: %s", (char *)payload);
357 case 0x05: /* Lyric (one syllable) */
358 /*EnsureUTF8 ((char *)payload);*/
361 case 0x06: /* Marker text */
362 EnsureUTF8 ((char *)payload);
363 msg_Info (p_demux, "Marker : %s", (char *)payload);
365 case 0x07: /* Cue point (WAVE filename) */
366 EnsureUTF8 ((char *)payload);
367 msg_Info (p_demux, "Cue point : %s", (char *)payload);
370 case 0x08: /* Program/Patch name */
371 EnsureUTF8 ((char *)payload);
372 msg_Info (p_demux, "Patch name: %s", (char *)payload);
375 case 0x09: /* MIDI port name */
376 EnsureUTF8 ((char *)payload);
377 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
380 case 0x2F: /* End of track */
381 if (tr->end != stream_Tell (s))
383 msg_Err (p_demux, "misplaced end of track");
388 case 0x51: /* Tempo */
391 uint32_t uspqn = (payload[0] << 16)
392 | (payload[1] << 8) | payload[2];
393 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
394 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
395 (unsigned)uspqn, tempo);
397 if (tempo < TEMPO_MIN)
399 msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
403 if (tempo > TEMPO_MAX)
405 msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
408 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
414 case 0x54: /* SMPTE offset */
416 msg_Warn (p_demux, "SMPTE offset not implemented");
421 case 0x58: /* Time signature */
428 case 0x59: /* Key signature */
435 case 0x7f: /* Proprietary event */
436 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
441 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
452 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
454 stream_t *s = p_demux->s;
456 uint8_t first, event;
459 if (stream_Seek (s, tr->offset)
460 || (stream_Read (s, &first, 1) != 1))
463 event = (first & 0x80) ? first : tr->running_event;
465 switch (event & 0xf0)
467 case 0xF0: /* System Exclusive */
470 case 0xF0: /* System Specific */
472 /* TODO: don't skip these */
473 stream_Read (s, NULL, 1); /* Manuf ID */
477 if (stream_Read (s, &c, 1) != 1)
484 case 0xFF: /* SMF Meta Event */
485 if (HandleMeta (p_demux, tr))
487 /* We MUST NOT pass this event forward. It would be
488 * confused as a MIDI Reset real-time event. */
499 /* We cannot handle undefined "common" (non-real-time)
500 * events inside SMF, as we cannot differentiate a
501 * one byte delta-time (< 0x80) from event data. */
502 case 0xF7: /* End of sysex -> should never happen(?) */
503 msg_Err (p_demux, "unknown MIDI event 0x%02X", event);
504 return -1; /* undefined events */
518 /* FIXME: one message per block is very inefficient */
519 block = block_New (p_demux, 1 + datalen);
523 block->p_buffer[0] = event;
526 stream_Read (s, block->p_buffer + 1, datalen);
532 msg_Err (p_demux, "malformatted MIDI event");
533 return -1; /* can't use implicit running status with empty payload! */
536 block->p_buffer[1] = first;
538 stream_Read (s, block->p_buffer + 2, datalen - 1);
541 block->i_dts = block->i_pts = date_Get (&p_demux->p_sys->pts);
542 es_out_Send (p_demux->out, p_demux->p_sys->es, block);
546 /* If event is not real-time, update running status */
547 tr->running_event = event;
549 tr->offset = stream_Tell (s);
553 /*****************************************************************************
554 * Demux: read chunks and send them to the synthetizer
555 *****************************************************************************
556 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
557 *****************************************************************************/
558 static int Demux (demux_t *p_demux)
560 stream_t *s = p_demux->s;
561 demux_sys_t *p_sys = p_demux->p_sys;
562 uint64_t pulse = p_sys->pulse, next_pulse = UINT64_MAX;
564 if (pulse == UINT64_MAX)
565 return 0; /* all tracks are done */
567 es_out_Control (p_demux->out, ES_OUT_SET_PCR, date_Get (&p_sys->pts));
569 for (unsigned i = 0; i < p_sys->trackc; i++)
571 mtrk_t *track = p_sys->trackv + i;
573 while (track->next == pulse)
575 if (HandleMessage (p_demux, track)
576 || ReadDeltaTime (s, track))
578 msg_Err (p_demux, "fatal parsing error");
583 if (track->next < next_pulse)
584 next_pulse = track->next;
587 mtime_t cur_tick = (date_Get (&p_sys->pts) + 9999) / 10000, last_tick;
588 if (next_pulse != UINT64_MAX)
589 last_tick = date_Increment (&p_sys->pts, next_pulse - pulse) / 10000;
591 last_tick = cur_tick + 1;
593 /* MIDI Tick emulation (ping the decoder every 10ms) */
594 while (cur_tick < last_tick)
596 block_t *tick = block_New (p_demux, 1);
600 tick->p_buffer[0] = 0xF9;
601 tick->i_dts = tick->i_pts = cur_tick++ * 10000;
602 es_out_Send (p_demux->out, p_sys->es, tick);
605 p_sys->pulse = next_pulse;
611 /*****************************************************************************
613 *****************************************************************************/
614 static int Control (demux_t *p_demux, int i_query, va_list args)
616 demux_sys_t *p_sys = p_demux->p_sys;
622 *(va_arg (args, int64_t *)) = date_Get (&p_sys->pts);
628 case DEMUX_GET_POSITION:
629 case DEMUX_SET_POSITION:
630 case DEMUX_GET_LENGTH: