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 *****************************************************************************/
23 #include <vlc_demux.h>
25 #include <vlc_codecs.h>
26 #include <vlc_charset.h>
29 static int Open (vlc_object_t *);
30 static void Close (vlc_object_t *);
33 set_description (_("SMF demuxer"));
34 set_category (CAT_INPUT);
35 set_subcategory (SUBCAT_INPUT_DEMUX);
36 set_capability ("demux2", 20);
37 set_callbacks (Open, Close);
40 static int Demux (demux_t *);
41 static int Control (demux_t *, int i_query, va_list args);
43 typedef struct smf_track_t
45 int64_t offset; /* Read offset in the file (stream_Tell) */
46 int64_t end; /* End offset in the file */
47 uint64_t next; /* Time of next message (in term of pulses) */
48 uint8_t running_event; /* Running (previous) event */
51 static int ReadDeltaTime (stream_t *s, mtrk_t *track);
57 uint64_t pulse; /* Pulses counter */
59 unsigned ppqn; /* Pulses Per Quarter Note */
60 /* by the way, "quarter note" is "noire" in French */
62 unsigned trackc; /* Number of tracks */
63 mtrk_t trackv[0]; /* Track states */
66 /*****************************************************************************
67 * Open: check file and initializes structures
68 *****************************************************************************/
69 static int Open (vlc_object_t * p_this)
71 demux_t *p_demux = (demux_t *)p_this;
72 stream_t *stream = p_demux->s;
75 unsigned tracks, ppqn;
76 vlc_bool_t multitrack;
78 /* (Try to) parse the SMF header */
79 /* Header chunk always has 6 bytes payload */
80 if (stream_Peek (stream, &peek, 14) < 14)
83 if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
87 /* First word: SMF type */
88 switch (GetWBE (peek))
91 multitrack = VLC_FALSE;
94 multitrack = VLC_TRUE;
97 /* We don't implement SMF2 (as do many) */
98 msg_Err (p_this, "unsupported SMF file type %u", GetWBE (peek));
103 /* Second word: number of tracks */
104 tracks = GetWBE (peek);
106 if (!multitrack && (tracks != 1))
108 msg_Err (p_this, "invalid SMF type 0 file");
112 msg_Dbg (p_this, "detected Standard MIDI File (type %u) with %u track(s)",
115 /* Third/last word: timing */
116 ppqn = GetWBE (peek);
120 msg_Err (p_this, "SMPTE timestamps not implemented");
125 msg_Dbg (p_this, " %u pulses per quarter note", ppqn);
128 p_sys = malloc (sizeof (*p_sys) + (sizeof (mtrk_t) * tracks));
132 /* We've had a valid SMF header - now skip it*/
133 if (stream_Read (stream, NULL, 14) < 14)
136 p_demux->pf_demux = Demux;
137 p_demux->pf_control = Control;
138 p_demux->p_sys = p_sys;
140 /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
141 date_Init (&p_sys->pts, ppqn * 2, 1);
142 date_Set (&p_sys->pts, 1);
146 p_sys->trackc = tracks;
147 /* Prefetch track offsets */
148 for (unsigned i = 0; i < tracks; i++)
154 /* Seeking screws streaming up, but there is no way around this,
155 * as SMF1 tracks are performed simultaneously.
156 * Not a big deal as SMF1 are usually only a few kbytes anyway. */
157 if (stream_Seek (stream, p_sys->trackv[i-1].end))
159 msg_Err (p_this, "cannot build SMF index (corrupted file?)");
166 stream_Read (stream, head, 8);
167 if (memcmp (head, "MTrk", 4) == 0)
170 msg_Dbg (p_this, "skipping unknown SMF chunk");
171 stream_Read (stream, NULL, GetDWBE (head + 4));
174 p_sys->trackv[i].offset = stream_Tell (stream);
175 p_sys->trackv[i].end = p_sys->trackv[i].offset + GetDWBE (head + 4);
176 p_sys->trackv[i].next = 0;
177 ReadDeltaTime (stream, p_sys->trackv + i);
178 p_sys->trackv[i].running_event = 0xF6;
179 /* Why 0xF6 (Tuning Calibration)?
180 * Because it has zero bytes of data, so the parser will detect the
181 * error if the first event uses running status. */
185 es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC('M', 'I', 'D', 'I'));
186 p_sys->es = es_out_Add (p_demux->out, &fmt);
196 * Releases allocate resources.
198 static void Close (vlc_object_t * p_this)
200 demux_t *p_demux = (demux_t *)p_this;
201 demux_sys_t *p_sys = p_demux->p_sys;
207 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
208 * @return read value, or -1 on EOF/error.
210 static int32_t ReadVarInt (stream_t *s)
215 for (unsigned i = 0; i < 4; i++)
217 if (stream_Read (s, &byte, 1) < 1)
220 val = (val << 7) | (byte & 0x7f);
221 if ((byte & 0x80) == 0)
230 * Reads (delta) time from the next event of a given track.
231 * @param s stream to read data from (must be positioned at the right offset)
233 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
237 assert (stream_Tell (s) == track->offset);
239 if (track->offset >= track->end)
241 /* This track is done */
242 track->next = UINT64_MAX;
246 delta_time = ReadVarInt (s);
250 track->next += delta_time;
251 track->offset = stream_Tell (s);
257 * Non-MIDI Meta events handler
260 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
262 stream_t *s = p_demux->s;
263 demux_sys_t *p_sys = p_demux->p_sys;
269 if (stream_Read (s, &type, 1) != 1)
272 length = ReadVarInt (s);
276 payload = malloc (length + 1);
277 if ((payload == NULL)
278 || (stream_Read (s, payload, length) != length))
284 payload[length] = '\0';
288 case 0x00: /* Sequence Number */
291 case 0x01: /* Test (comment) */
292 EnsureUTF8 ((char *)payload);
293 msg_Info (p_demux, "Text : %s", (char *)payload);
296 case 0x02: /* Copyright */
297 EnsureUTF8 ((char *)payload);
298 msg_Info (p_demux, "Copyright : %s", (char *)payload);
301 case 0x03: /* Track name */
302 EnsureUTF8 ((char *)payload);
303 msg_Info (p_demux, "Track name: %s", (char *)payload);
306 case 0x04: /* Instrument name */
307 EnsureUTF8 ((char *)payload);
308 msg_Info (p_demux, "Instrument: %s", (char *)payload);
311 case 0x05: /* Lyric (one syllable) */
312 /*EnsureUTF8 ((char *)payload);*/
315 case 0x06: /* Marker text */
316 EnsureUTF8 ((char *)payload);
317 msg_Info (p_demux, "Marker : %s", (char *)payload);
319 case 0x07: /* Cue point (WAVE filename) */
320 EnsureUTF8 ((char *)payload);
321 msg_Info (p_demux, "Cue point : %s", (char *)payload);
324 case 0x08: /* Program/Patch name */
325 EnsureUTF8 ((char *)payload);
326 msg_Info (p_demux, "Patch name: %s", (char *)payload);
329 case 0x09: /* MIDI port name */
330 EnsureUTF8 ((char *)payload);
331 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
334 case 0x2F: /* End of track */
335 if (tr->end != stream_Tell (s))
337 msg_Err (p_demux, "misplaced end of track");
342 case 0x51: /* Tempo */
345 uint32_t uspqn = (payload[0] << 16)
346 | (payload[1] << 8) | payload[2];
347 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
348 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
349 (unsigned)uspqn, tempo);
353 msg_Warn (p_demux, "tempo too slow -> 20 BPM");
359 msg_Warn (p_demux, "tempo too fast -> 240 BPM");
362 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
368 case 0x54: /* SMPTE offset */
370 msg_Warn (p_demux, "SMPTE offset not implemented");
375 case 0x58: /* Time signature */
382 case 0x59: /* Key signature */
389 case 0x7f: /* Proprietary event */
390 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
395 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
406 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
408 stream_t *s = p_demux->s;
410 uint8_t first, event;
413 if (stream_Seek (s, tr->offset)
414 || (stream_Read (s, &first, 1) != 1))
417 event = (first & 0x80) ? first : tr->running_event;
419 switch (event & 0xf0)
421 case 0xF0: /* System Exclusive */
424 case 0xF0: /* System Specific */
426 /* TODO: don't skip these */
427 stream_Read (s, NULL, 1); /* Manuf ID */
431 if (stream_Read (s, &c, 1) != 1)
437 case 0xFF: /* SMF Meta Event */
438 if (HandleMeta (p_demux, tr))
440 /* We MUST NOT pass this event to forward. It would be
441 * confused as a MIDI Reset real-time event. */
452 /* We cannot handle undefined "common" (non-real-time)
453 * events inside SMF, as we cannot differentiate a
454 * one byte delta-time (< 0x80) from event data. */
455 case 0xF7: /* End of sysex -> should never happen(?) */
456 msg_Err (p_demux, "unknown MIDI event 0x%02X", event);
457 return -1; /* undefined events */
471 /* FIXME: one message per block is very inefficient */
472 block = block_New (p_demux, 1 + datalen);
476 block->p_buffer[0] = event;
479 stream_Read (s, block->p_buffer + 1, datalen);
485 msg_Err (p_demux, "malformatted MIDI event");
486 return -1; /* can't use implicit running status with empty payload! */
489 block->p_buffer[1] = first;
491 stream_Read (s, block->p_buffer + 2, datalen - 1);
494 block->i_dts = block->i_pts = date_Get (&p_demux->p_sys->pts);
495 es_out_Send (p_demux->out, p_demux->p_sys->es, block);
499 /* If event is not real-time, update running status */
500 tr->running_event = event;
502 tr->offset = stream_Tell (s);
506 /*****************************************************************************
507 * Demux: read chunks and send them to the synthetizer
508 *****************************************************************************
509 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
510 *****************************************************************************/
511 static int Demux (demux_t *p_demux)
513 stream_t *s = p_demux->s;
514 demux_sys_t *p_sys = p_demux->p_sys;
515 uint64_t pulse = p_sys->pulse, next_pulse = UINT64_MAX;
517 if (pulse == UINT64_MAX)
518 return 0; /* all tracks are done */
520 es_out_Control (p_demux->out, ES_OUT_SET_PCR, date_Get (&p_sys->pts));
522 for (unsigned i = 0; i < p_sys->trackc; i++)
524 mtrk_t *track = p_sys->trackv + i;
526 while (track->next == pulse)
528 if (HandleMessage (p_demux, track)
529 || ReadDeltaTime (s, track))
531 msg_Err (p_demux, "fatal parsing error");
536 if (track->next < next_pulse)
537 next_pulse = track->next;
540 if (next_pulse != UINT64_MAX)
541 date_Increment (&p_sys->pts, next_pulse - pulse);
542 p_sys->pulse = next_pulse;
548 /*****************************************************************************
550 *****************************************************************************/
551 static int Control (demux_t *p_demux, int i_query, va_list args)
553 return demux2_vaControlHelper (p_demux->s, 0, -1, 0, 1, i_query, args);