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_demux.h>
29 #include <vlc_codecs.h>
30 #include <vlc_charset.h>
34 #define TEMPO_MAX 250 /* Beats per minute */
36 static int Open (vlc_object_t *);
37 static void Close (vlc_object_t *);
40 set_description (_("SMF demuxer"));
41 set_category (CAT_INPUT);
42 set_subcategory (SUBCAT_INPUT_DEMUX);
43 set_capability ("demux", 20);
44 set_callbacks (Open, Close);
47 static int Demux (demux_t *);
48 static int Control (demux_t *, int i_query, va_list args);
50 typedef struct smf_track_t
52 int64_t offset; /* Read offset in the file (stream_Tell) */
53 int64_t end; /* End offset in the file */
54 uint64_t next; /* Time of next message (in term of pulses) */
55 uint8_t running_event; /* Running (previous) event */
58 static int ReadDeltaTime (stream_t *s, mtrk_t *track);
64 uint64_t pulse; /* Pulses counter */
66 unsigned ppqn; /* Pulses Per Quarter Note */
67 /* by the way, "quarter note" is "noire" in French */
69 unsigned trackc; /* Number of tracks */
70 mtrk_t trackv[0]; /* Track states */
73 /*****************************************************************************
74 * Open: check file and initializes structures
75 *****************************************************************************/
76 static int Open (vlc_object_t * p_this)
78 demux_t *p_demux = (demux_t *)p_this;
79 stream_t *stream = p_demux->s;
82 unsigned tracks, ppqn;
85 /* (Try to) parse the SMF header */
86 /* Header chunk always has 6 bytes payload */
87 if (stream_Peek (stream, &peek, 14) < 14)
90 if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
94 /* First word: SMF type */
95 switch (GetWBE (peek))
104 /* We don't implement SMF2 (as do many) */
105 msg_Err (p_this, "unsupported SMF file type %u", GetWBE (peek));
110 /* Second word: number of tracks */
111 tracks = GetWBE (peek);
113 if (!multitrack && (tracks != 1))
115 msg_Err (p_this, "invalid SMF type 0 file");
119 msg_Dbg (p_this, "detected Standard MIDI File (type %u) with %u track(s)",
122 /* Third/last word: timing */
123 ppqn = GetWBE (peek);
127 msg_Err (p_this, "SMPTE timestamps not implemented");
132 msg_Dbg (p_this, " %u pulses per quarter note", ppqn);
135 p_sys = malloc (sizeof (*p_sys) + (sizeof (mtrk_t) * tracks));
139 /* We've had a valid SMF header - now skip it*/
140 if (stream_Read (stream, NULL, 14) < 14)
143 p_demux->pf_demux = Demux;
144 p_demux->pf_control = Control;
145 p_demux->p_sys = p_sys;
147 /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
148 date_Init (&p_sys->pts, ppqn * 2, 1);
149 date_Set (&p_sys->pts, 1);
153 p_sys->trackc = tracks;
154 /* Prefetch track offsets */
155 for (unsigned i = 0; i < tracks; i++)
161 /* Seeking screws streaming up, but there is no way around this,
162 * as SMF1 tracks are performed simultaneously.
163 * Not a big deal as SMF1 are usually only a few kbytes anyway. */
164 if (stream_Seek (stream, p_sys->trackv[i-1].end))
166 msg_Err (p_this, "cannot build SMF index (corrupted file?)");
173 stream_Read (stream, head, 8);
174 if (memcmp (head, "MTrk", 4) == 0)
177 msg_Dbg (p_this, "skipping unknown SMF chunk");
178 stream_Read (stream, NULL, GetDWBE (head + 4));
181 p_sys->trackv[i].offset = stream_Tell (stream);
182 p_sys->trackv[i].end = p_sys->trackv[i].offset + GetDWBE (head + 4);
183 p_sys->trackv[i].next = 0;
184 ReadDeltaTime (stream, p_sys->trackv + i);
185 p_sys->trackv[i].running_event = 0xF6;
186 /* Why 0xF6 (Tuning Calibration)?
187 * Because it has zero bytes of data, so the parser will detect the
188 * error if the first event uses running status. */
192 es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC('M', 'I', 'D', 'I'));
193 p_sys->es = es_out_Add (p_demux->out, &fmt);
203 * Releases allocate resources.
205 static void Close (vlc_object_t * p_this)
207 demux_t *p_demux = (demux_t *)p_this;
208 demux_sys_t *p_sys = p_demux->p_sys;
214 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
215 * @return read value, or -1 on EOF/error.
217 static int32_t ReadVarInt (stream_t *s)
222 for (unsigned i = 0; i < 4; i++)
224 if (stream_Read (s, &byte, 1) < 1)
227 val = (val << 7) | (byte & 0x7f);
228 if ((byte & 0x80) == 0)
237 * Reads (delta) time from the next event of a given track.
238 * @param s stream to read data from (must be positioned at the right offset)
240 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
244 assert (stream_Tell (s) == track->offset);
246 if (track->offset >= track->end)
248 /* This track is done */
249 track->next = UINT64_MAX;
253 delta_time = ReadVarInt (s);
257 track->next += delta_time;
258 track->offset = stream_Tell (s);
264 * Non-MIDI Meta events handler
267 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
269 stream_t *s = p_demux->s;
270 demux_sys_t *p_sys = p_demux->p_sys;
276 if (stream_Read (s, &type, 1) != 1)
279 length = ReadVarInt (s);
283 payload = malloc (length + 1);
284 if ((payload == NULL)
285 || (stream_Read (s, payload, length) != length))
291 payload[length] = '\0';
295 case 0x00: /* Sequence Number */
298 case 0x01: /* Test (comment) */
299 EnsureUTF8 ((char *)payload);
300 msg_Info (p_demux, "Text : %s", (char *)payload);
303 case 0x02: /* Copyright */
304 EnsureUTF8 ((char *)payload);
305 msg_Info (p_demux, "Copyright : %s", (char *)payload);
308 case 0x03: /* Track name */
309 EnsureUTF8 ((char *)payload);
310 msg_Info (p_demux, "Track name: %s", (char *)payload);
313 case 0x04: /* Instrument name */
314 EnsureUTF8 ((char *)payload);
315 msg_Info (p_demux, "Instrument: %s", (char *)payload);
318 case 0x05: /* Lyric (one syllable) */
319 /*EnsureUTF8 ((char *)payload);*/
322 case 0x06: /* Marker text */
323 EnsureUTF8 ((char *)payload);
324 msg_Info (p_demux, "Marker : %s", (char *)payload);
326 case 0x07: /* Cue point (WAVE filename) */
327 EnsureUTF8 ((char *)payload);
328 msg_Info (p_demux, "Cue point : %s", (char *)payload);
331 case 0x08: /* Program/Patch name */
332 EnsureUTF8 ((char *)payload);
333 msg_Info (p_demux, "Patch name: %s", (char *)payload);
336 case 0x09: /* MIDI port name */
337 EnsureUTF8 ((char *)payload);
338 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
341 case 0x2F: /* End of track */
342 if (tr->end != stream_Tell (s))
344 msg_Err (p_demux, "misplaced end of track");
349 case 0x51: /* Tempo */
352 uint32_t uspqn = (payload[0] << 16)
353 | (payload[1] << 8) | payload[2];
354 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
355 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
356 (unsigned)uspqn, tempo);
358 if (tempo < TEMPO_MIN)
360 msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
364 if (tempo > TEMPO_MAX)
366 msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
369 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
375 case 0x54: /* SMPTE offset */
377 msg_Warn (p_demux, "SMPTE offset not implemented");
382 case 0x58: /* Time signature */
389 case 0x59: /* Key signature */
396 case 0x7f: /* Proprietary event */
397 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
402 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
413 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
415 stream_t *s = p_demux->s;
417 uint8_t first, event;
420 if (stream_Seek (s, tr->offset)
421 || (stream_Read (s, &first, 1) != 1))
424 event = (first & 0x80) ? first : tr->running_event;
426 switch (event & 0xf0)
428 case 0xF0: /* System Exclusive */
431 case 0xF0: /* System Specific */
433 /* TODO: don't skip these */
434 stream_Read (s, NULL, 1); /* Manuf ID */
438 if (stream_Read (s, &c, 1) != 1)
444 case 0xFF: /* SMF Meta Event */
445 if (HandleMeta (p_demux, tr))
447 /* We MUST NOT pass this event forward. It would be
448 * confused as a MIDI Reset real-time event. */
459 /* We cannot handle undefined "common" (non-real-time)
460 * events inside SMF, as we cannot differentiate a
461 * one byte delta-time (< 0x80) from event data. */
462 case 0xF7: /* End of sysex -> should never happen(?) */
463 msg_Err (p_demux, "unknown MIDI event 0x%02X", event);
464 return -1; /* undefined events */
478 /* FIXME: one message per block is very inefficient */
479 block = block_New (p_demux, 1 + datalen);
483 block->p_buffer[0] = event;
486 stream_Read (s, block->p_buffer + 1, datalen);
492 msg_Err (p_demux, "malformatted MIDI event");
493 return -1; /* can't use implicit running status with empty payload! */
496 block->p_buffer[1] = first;
498 stream_Read (s, block->p_buffer + 2, datalen - 1);
501 block->i_dts = block->i_pts = date_Get (&p_demux->p_sys->pts);
502 es_out_Send (p_demux->out, p_demux->p_sys->es, block);
506 /* If event is not real-time, update running status */
507 tr->running_event = event;
509 tr->offset = stream_Tell (s);
513 /*****************************************************************************
514 * Demux: read chunks and send them to the synthetizer
515 *****************************************************************************
516 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
517 *****************************************************************************/
518 static int Demux (demux_t *p_demux)
520 stream_t *s = p_demux->s;
521 demux_sys_t *p_sys = p_demux->p_sys;
522 uint64_t pulse = p_sys->pulse, next_pulse = UINT64_MAX;
524 if (pulse == UINT64_MAX)
525 return 0; /* all tracks are done */
527 es_out_Control (p_demux->out, ES_OUT_SET_PCR, date_Get (&p_sys->pts));
529 for (unsigned i = 0; i < p_sys->trackc; i++)
531 mtrk_t *track = p_sys->trackv + i;
533 while (track->next == pulse)
535 if (HandleMessage (p_demux, track)
536 || ReadDeltaTime (s, track))
538 msg_Err (p_demux, "fatal parsing error");
543 if (track->next < next_pulse)
544 next_pulse = track->next;
547 mtime_t cur_tick = (date_Get (&p_sys->pts) + 9999) / 10000, last_tick;
548 if (next_pulse != UINT64_MAX)
549 last_tick = date_Increment (&p_sys->pts, next_pulse - pulse) / 10000;
551 last_tick = cur_tick + 1;
553 /* MIDI Tick emulation (ping the decider every 10ms) */
554 while (cur_tick < last_tick)
556 block_t *tick = block_New (p_demux, 1);
560 tick->p_buffer[0] = 0xF9;
561 tick->i_dts = tick->i_pts = cur_tick++ * 10000;
562 es_out_Send (p_demux->out, p_sys->es, tick);
565 p_sys->pulse = next_pulse;
571 /*****************************************************************************
573 *****************************************************************************/
574 static int Control (demux_t *p_demux, int i_query, va_list args)
576 demux_sys_t *p_sys = p_demux->p_sys;
582 *(va_arg (args, int64_t *)) = date_Get (&p_sys->pts);
588 case DEMUX_GET_POSITION:
589 case DEMUX_SET_POSITION:
590 case DEMUX_GET_LENGTH: