demux: libavi: remove useless member
[vlc.git] / modules / demux / smf.c
blob37b16d6ac5f8cbebe0ac98052b6e397708743957
1 /*****************************************************************************
2 * smf.c : Standard MIDI File (.mid) demux module for vlc
3 *****************************************************************************
4 * Copyright © 2007 Rémi Denis-Courmont
5 * $Id$
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as published by
9 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
20 *****************************************************************************/
22 #ifdef HAVE_CONFIG_H
23 # include "config.h"
24 #endif
26 #include <vlc_common.h>
27 #include <vlc_plugin.h>
28 #include <vlc_demux.h>
29 #include <vlc_charset.h>
30 #include <limits.h>
32 #include <assert.h>
34 #define TEMPO_MIN 20
35 #define TEMPO_MAX 250 /* Beats per minute */
37 /**
38 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
39 * @return read value, or -1 on EOF/error.
41 static int32_t ReadVarInt (stream_t *s)
43 uint32_t val = 0;
44 uint8_t byte;
46 for (unsigned i = 0; i < 4; i++)
48 if (vlc_stream_Read (s, &byte, 1) < 1)
49 return -1;
51 val = (val << 7) | (byte & 0x7f);
52 if ((byte & 0x80) == 0)
53 return val;
56 return -1;
59 typedef struct smf_track_t
61 uint64_t next; /*< Time of next message (in term of pulses) */
62 uint64_t start; /*< Start offset in the file */
63 uint32_t length; /*< Bytes length */
64 uint32_t offset; /*< Read offset relative to the start offset */
65 uint8_t running_event; /*< Running (previous) event */
66 } mtrk_t;
68 /**
69 * Reads (delta) time from the next event of a given track.
70 * @param s stream to read data from (must be positioned at the right offset)
72 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
74 int32_t delta_time;
76 assert (vlc_stream_Tell (s) == track->start + track->offset);
78 if (track->offset >= track->length)
80 /* This track is done */
81 track->next = UINT64_MAX;
82 return 0;
85 delta_time = ReadVarInt (s);
86 if (delta_time < 0)
87 return -1;
89 track->next += delta_time;
90 track->offset = vlc_stream_Tell (s) - track->start;
91 return 0;
94 struct demux_sys_t
96 es_out_id_t *es;
97 date_t pts; /*< Play timestamp */
98 uint64_t pulse; /*< Pulses counter */
99 mtime_t tick; /*< Last tick timestamp */
101 mtime_t duration; /*< Total duration */
102 unsigned ppqn; /*< Pulses Per Quarter Note */
103 /* by the way, "quarter note" is "noire" in French */
105 unsigned trackc; /*< Number of tracks */
106 mtrk_t trackv[]; /*< Track states */
110 * Non-MIDI Meta events handler
112 static
113 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
115 stream_t *s = p_demux->s;
116 demux_sys_t *p_sys = p_demux->p_sys;
117 uint8_t *payload;
118 uint8_t type;
119 int32_t length;
120 int ret = 0;
122 if (vlc_stream_Read (s, &type, 1) != 1)
123 return -1;
125 length = ReadVarInt (s);
126 if (length < 0)
127 return -1;
129 payload = malloc (length + 1);
130 if ((payload == NULL)
131 || (vlc_stream_Read (s, payload, length) != length))
133 free (payload);
134 return -1;
137 payload[length] = '\0';
139 switch (type)
141 case 0x00: /* Sequence Number */
142 break;
144 case 0x01: /* Text (comment) */
145 EnsureUTF8 ((char *)payload);
146 msg_Info (p_demux, "Text : %s", (char *)payload);
147 break;
149 case 0x02: /* Copyright */
150 EnsureUTF8 ((char *)payload);
151 msg_Info (p_demux, "Copyright : %s", (char *)payload);
152 break;
154 case 0x03: /* Track name */
155 EnsureUTF8 ((char *)payload);
156 msg_Info (p_demux, "Track name: %s", (char *)payload);
157 break;
159 case 0x04: /* Instrument name */
160 EnsureUTF8 ((char *)payload);
161 msg_Info (p_demux, "Instrument: %s", (char *)payload);
162 break;
164 case 0x05: /* Lyric (one syllable) */
165 /*EnsureUTF8 ((char *)payload);*/
166 break;
168 case 0x06: /* Marker text */
169 EnsureUTF8 ((char *)payload);
170 msg_Info (p_demux, "Marker : %s", (char *)payload);
171 break;
173 case 0x07: /* Cue point (WAVE filename) */
174 EnsureUTF8 ((char *)payload);
175 msg_Info (p_demux, "Cue point : %s", (char *)payload);
176 break;
178 case 0x08: /* Program/Patch name */
179 EnsureUTF8 ((char *)payload);
180 msg_Info (p_demux, "Patch name: %s", (char *)payload);
181 break;
183 case 0x09: /* MIDI port name */
184 EnsureUTF8 ((char *)payload);
185 msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
186 break;
188 case 0x2F: /* End of track */
189 if (tr->start + tr->length != vlc_stream_Tell (s))
191 msg_Err (p_demux, "misplaced end of track");
192 ret = -1;
194 break;
196 case 0x51: /* Tempo */
197 if (length == 3)
199 uint32_t uspqn = (payload[0] << 16)
200 | (payload[1] << 8) | payload[2];
201 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
202 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
203 (unsigned)uspqn, tempo);
205 if (tempo < TEMPO_MIN)
207 msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
208 tempo = TEMPO_MIN;
210 else
211 if (tempo > TEMPO_MAX)
213 msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
214 tempo = TEMPO_MAX;
216 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
218 else
219 ret = -1;
220 break;
222 case 0x54: /* SMPTE offset */
223 if (length == 5)
224 msg_Warn (p_demux, "SMPTE offset not implemented");
225 else
226 ret = -1;
227 break;
229 case 0x58: /* Time signature */
230 if (length == 4)
232 else
233 ret = -1;
234 break;
236 case 0x59: /* Key signature */
237 if (length == 2)
239 else
240 ret = -1;
241 break;
243 case 0x7f: /* Proprietary event */
244 msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
245 length);
246 break;
248 default:
249 msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
250 type, length);
253 free (payload);
254 return ret;
257 static
258 int HandleMessage (demux_t *p_demux, mtrk_t *tr, es_out_t *out)
260 stream_t *s = p_demux->s;
261 block_t *block;
262 uint8_t first, event;
263 unsigned datalen;
265 if (vlc_stream_Seek (s, tr->start + tr->offset)
266 || (vlc_stream_Read (s, &first, 1) != 1))
267 return -1;
269 event = (first & 0x80) ? first : tr->running_event;
271 switch (event & 0xf0)
273 case 0xF0: /* System Exclusive */
274 switch (event)
276 case 0xF0: /* System Specific start */
277 case 0xF7: /* System Specific continuation */
279 /* Variable length followed by SysEx event data */
280 int32_t len = ReadVarInt (s);
281 if (len == -1)
282 return -1;
284 block = vlc_stream_Block (s, len);
285 if (block == NULL)
286 return -1;
287 block = block_Realloc (block, 1, len);
288 if (block == NULL)
289 return -1;
290 block->p_buffer[0] = event;
291 goto send;
293 case 0xFF: /* SMF Meta Event */
294 if (HandleMeta (p_demux, tr))
295 return -1;
296 /* We MUST NOT pass this event forward. It would be
297 * confused as a MIDI Reset real-time event. */
298 goto skip;
299 case 0xF1:
300 case 0xF3:
301 datalen = 1;
302 break;
303 case 0xF2:
304 datalen = 2;
305 break;
306 case 0xF4:
307 case 0xF5:
308 /* We cannot handle undefined "common" (non-real-time)
309 * events inside SMF, as we cannot differentiate a
310 * one byte delta-time (< 0x80) from event data. */
311 default:
312 datalen = 0;
313 break;
315 break;
316 case 0xC0:
317 case 0xD0:
318 datalen = 1;
319 break;
320 default:
321 datalen = 2;
322 break;
325 /* FIXME: one message per block is very inefficient */
326 block = block_Alloc (1 + datalen);
327 if (block == NULL)
328 goto skip;
330 block->p_buffer[0] = event;
331 if (first & 0x80)
333 if (vlc_stream_Read(s, block->p_buffer + 1, datalen) < datalen)
334 goto error;
336 else
338 if (datalen == 0)
339 { /* implicit running status requires non-empty payload */
340 msg_Err (p_demux, "malformatted MIDI event");
341 goto error;
344 block->p_buffer[1] = first;
345 if (datalen > 1
346 && vlc_stream_Read(s, block->p_buffer + 2, datalen - 1) < datalen - 1)
347 goto error;
350 send:
351 block->i_dts = block->i_pts = date_Get (&p_demux->p_sys->pts);
352 if (out != NULL)
353 es_out_Send (out, p_demux->p_sys->es, block);
354 else
355 block_Release (block);
357 skip:
358 if (event < 0xF8)
359 /* If event is not real-time, update running status */
360 tr->running_event = event;
362 tr->offset = vlc_stream_Tell (s) - tr->start;
363 return 0;
365 error:
366 block_Release(block);
367 return -1;
370 static int SeekSet0 (demux_t *demux)
372 stream_t *stream = demux->s;
373 demux_sys_t *sys = demux->p_sys;
375 /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
376 date_Init (&sys->pts, sys->ppqn * 2, 1);
377 date_Set (&sys->pts, VLC_TS_0);
378 sys->pulse = 0;
379 sys->tick = VLC_TS_0;
381 for (unsigned i = 0; i < sys->trackc; i++)
383 mtrk_t *tr = sys->trackv + i;
385 tr->offset = 0;
386 tr->next = 0;
387 /* Why 0xF6 (Tuning Calibration)?
388 * Because it has zero bytes of data, so the parser will detect the
389 * error if the first event uses running status. */
390 tr->running_event = 0xF6;
392 if (vlc_stream_Seek (stream, tr->start)
393 || ReadDeltaTime (stream, tr))
395 msg_Err (demux, "fatal parsing error");
396 return -1;
400 return 0;
403 static int ReadEvents (demux_t *demux, uint64_t *restrict pulse,
404 es_out_t *out)
406 uint64_t cur_pulse = *pulse, next_pulse = UINT64_MAX;
407 demux_sys_t *sys = demux->p_sys;
409 for (unsigned i = 0; i < sys->trackc; i++)
411 mtrk_t *track = sys->trackv + i;
413 while (track->next <= cur_pulse)
415 if (HandleMessage (demux, track, out)
416 || ReadDeltaTime (demux->s, track))
418 msg_Err (demux, "fatal parsing error");
419 return -1;
423 if (next_pulse > track->next)
424 next_pulse = track->next;
427 if (next_pulse != UINT64_MAX)
428 date_Increment (&sys->pts, next_pulse - cur_pulse);
429 *pulse = next_pulse;
430 return 0;
433 #define TICK (CLOCK_FREQ / 100)
435 /*****************************************************************************
436 * Demux: read chunks and send them to the synthesizer
437 *****************************************************************************
438 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
439 *****************************************************************************/
440 static int Demux (demux_t *demux)
442 demux_sys_t *sys = demux->p_sys;
444 /* MIDI Tick emulation (ping the decoder every 10ms) */
445 if (sys->tick <= date_Get (&sys->pts))
447 block_t *tick = block_Alloc (1);
448 if (unlikely(tick == NULL))
449 return VLC_ENOMEM;
451 tick->p_buffer[0] = 0xF9;
452 tick->i_dts = tick->i_pts = sys->tick;
454 es_out_Send (demux->out, sys->es, tick);
455 es_out_SetPCR (demux->out, sys->tick);
457 sys->tick += TICK;
458 return 1;
461 /* MIDI events in chronological order across all tracks */
462 uint64_t pulse = sys->pulse;
464 if (ReadEvents (demux, &pulse, demux->out))
465 return VLC_EGENERIC;
467 if (pulse == UINT64_MAX)
468 return 0; /* all tracks are done */
470 sys->pulse = pulse;
471 return 1;
474 static int Seek (demux_t *demux, mtime_t pts)
476 demux_sys_t *sys = demux->p_sys;
478 /* Rewind if needed */
479 if (pts < date_Get (&sys->pts) && SeekSet0 (demux))
480 return VLC_EGENERIC;
482 /* Fast forward */
483 uint64_t pulse = sys->pulse;
485 while (pts > date_Get (&sys->pts))
487 if (pulse == UINT64_MAX)
488 return VLC_SUCCESS; /* premature end */
489 if (ReadEvents (demux, &pulse, NULL))
490 return VLC_EGENERIC;
493 sys->pulse = pulse;
494 sys->tick = ((date_Get (&sys->pts) - VLC_TS_0) / TICK) * TICK + VLC_TS_0;
495 return VLC_SUCCESS;
498 /*****************************************************************************
499 * Control:
500 *****************************************************************************/
501 static int Control (demux_t *demux, int i_query, va_list args)
503 demux_sys_t *sys = demux->p_sys;
505 switch (i_query)
507 case DEMUX_CAN_SEEK:
508 *va_arg (args, bool *) = true;
509 break;
510 case DEMUX_GET_POSITION:
511 if (!sys->duration)
512 return VLC_EGENERIC;
513 *va_arg (args, double *) = (sys->tick - (double)VLC_TS_0)
514 / sys->duration;
515 break;
516 case DEMUX_SET_POSITION:
517 return Seek (demux, va_arg (args, double) * sys->duration);
518 case DEMUX_GET_LENGTH:
519 *va_arg (args, int64_t *) = sys->duration;
520 break;
521 case DEMUX_GET_TIME:
522 *va_arg (args, int64_t *) = sys->tick - VLC_TS_0;
523 break;
524 case DEMUX_SET_TIME:
525 return Seek (demux, va_arg (args, int64_t));
526 default:
527 return VLC_EGENERIC;
529 return VLC_SUCCESS;
533 * Probes file format and starts demuxing.
535 static int Open (vlc_object_t *obj)
537 demux_t *demux = (demux_t *)obj;
538 stream_t *stream = demux->s;
539 const uint8_t *peek;
540 bool multitrack;
542 /* (Try to) parse the SMF header */
543 /* Header chunk always has 6 bytes payload */
544 if (vlc_stream_Peek (stream, &peek, 14) < 14)
545 return VLC_EGENERIC;
547 /* Skip RIFF MIDI header if present */
548 if (!memcmp (peek, "RIFF", 4) && !memcmp (peek + 8, "RMID", 4))
550 uint32_t riff_len = GetDWLE (peek + 4);
552 msg_Dbg (demux, "detected RIFF MIDI file (%"PRIu32" bytes)", riff_len);
553 if ((vlc_stream_Read (stream, NULL, 12) < 12))
554 return VLC_EGENERIC;
556 /* Look for the RIFF data chunk */
557 for (;;)
559 char chnk_hdr[8];
560 uint32_t chnk_len;
562 if ((riff_len < 8)
563 || (vlc_stream_Read (stream, chnk_hdr, 8) < 8))
564 return VLC_EGENERIC;
566 riff_len -= 8;
567 chnk_len = GetDWLE (chnk_hdr + 4);
568 if (riff_len < chnk_len)
569 return VLC_EGENERIC;
570 riff_len -= chnk_len;
572 if (!memcmp (chnk_hdr, "data", 4))
573 break; /* found! */
575 if (vlc_stream_Read (stream, NULL, chnk_len) < (ssize_t)chnk_len)
576 return VLC_EGENERIC;
579 /* Read real SMF header. Assume RIFF data chunk length is proper. */
580 if (vlc_stream_Peek (stream, &peek, 14) < 14)
581 return VLC_EGENERIC;
584 if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
585 return VLC_EGENERIC;
586 peek += 8;
588 /* First word: SMF type */
589 switch (GetWBE (peek))
591 case 0:
592 multitrack = false;
593 break;
594 case 1:
595 multitrack = true;
596 break;
597 default:
598 /* We don't implement SMF2 (as do many) */
599 msg_Err (demux, "unsupported SMF file type %u", GetWBE (peek));
600 return VLC_EGENERIC;
602 peek += 2;
604 /* Second word: number of tracks */
605 unsigned tracks = GetWBE (peek);
606 peek += 2;
607 if (!multitrack && (tracks != 1))
609 msg_Err (demux, "invalid SMF type 0 file");
610 return VLC_EGENERIC;
613 msg_Dbg (demux, "detected Standard MIDI File (type %u) with %u track(s)",
614 multitrack, tracks);
616 /* Third/last word: timing */
617 unsigned ppqn = GetWBE (peek);
618 if (ppqn & 0x8000)
619 { /* FIXME */
620 msg_Err (demux, "SMPTE timestamps not implemented");
621 return VLC_EGENERIC;
623 else
625 if (ppqn == 0)
627 msg_Err(demux, "invalid SMF file PPQN: %u", ppqn);
628 return VLC_EGENERIC;
630 msg_Dbg (demux, " %u pulses per quarter note", ppqn);
633 demux_sys_t *sys = malloc (sizeof (*sys) + (sizeof (mtrk_t) * tracks));
634 if (unlikely(sys == NULL))
635 return VLC_ENOMEM;
637 /* We've had a valid SMF header - now skip it*/
638 if (vlc_stream_Read (stream, NULL, 14) < 14)
639 goto error;
641 demux->p_sys = sys;
642 sys->duration = 0;
643 sys->ppqn = ppqn;
644 sys->trackc = tracks;
646 /* Prefetch track offsets */
647 for (unsigned i = 0; i < tracks; i++)
649 mtrk_t *tr = sys->trackv + i;
650 uint8_t head[8];
652 /* Seeking screws streaming up, but there is no way around this, as
653 * SMF1 tracks are performed simultaneously.
654 * Not a big deal as SMF1 are usually only a few kbytes anyway. */
655 if (i > 0 && vlc_stream_Seek (stream, tr[-1].start + tr[-1].length))
657 msg_Err (demux, "cannot build SMF index (corrupted file?)");
658 goto error;
661 for (;;)
663 if (vlc_stream_Read (stream, head, 8) < 8)
665 /* FIXME: don't give up if we have at least one valid track */
666 msg_Err (demux, "incomplete SMF chunk, file is corrupted");
667 goto error;
670 if (memcmp (head, "MTrk", 4) == 0)
671 break;
673 uint_fast32_t chunk_len = GetDWBE(head + 4);
674 msg_Dbg(demux, "skipping unknown SMF chunk (%"PRIuFAST32" bytes)",
675 chunk_len);
676 if (vlc_stream_Seek(stream, vlc_stream_Tell(stream) + chunk_len))
677 goto error;
680 tr->start = vlc_stream_Tell (stream);
681 tr->length = GetDWBE (head + 4);
684 bool b;
685 if (vlc_stream_Control (stream, STREAM_CAN_FASTSEEK, &b) == 0 && b)
687 if (SeekSet0 (demux))
688 goto error;
690 for (uint64_t pulse = 0; pulse != UINT64_MAX;)
691 if (ReadEvents (demux, &pulse, NULL))
692 break;
694 sys->duration = date_Get (&sys->pts);
697 if (SeekSet0 (demux))
698 goto error;
700 es_format_t fmt;
701 es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MIDI);
702 fmt.audio.i_channels = 2;
703 fmt.audio.i_rate = 44100; /* dummy value */
704 sys->es = es_out_Add (demux->out, &fmt);
706 demux->pf_demux = Demux;
707 demux->pf_control = Control;
708 return VLC_SUCCESS;
710 error:
711 free (sys);
712 return VLC_EGENERIC;
716 * Releases allocate resources.
718 static void Close (vlc_object_t * p_this)
720 demux_t *p_demux = (demux_t *)p_this;
721 demux_sys_t *p_sys = p_demux->p_sys;
723 free (p_sys);
726 vlc_module_begin ()
727 set_description (N_("SMF demuxer"))
728 set_category (CAT_INPUT)
729 set_subcategory (SUBCAT_INPUT_DEMUX)
730 set_capability ("demux", 20)
731 set_callbacks (Open, Close)
732 vlc_module_end ()