]> git.sesse.net Git - vlc/blob - modules/demux/smf.c
skins2: fix stray line in Qt menu used by skins2
[vlc] / modules / demux / smf.c
1 /*****************************************************************************
2  * smf.c : Standard MIDI File (.mid) demux module for vlc
3  *****************************************************************************
4  * Copyright © 2007 Rémi Denis-Courmont
5  * $Id$
6  *
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.
11  *
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.
16  *
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  *****************************************************************************/
21
22 #ifdef HAVE_CONFIG_H
23 # include "config.h"
24 #endif
25
26 #include <vlc_common.h>
27 #include <vlc_plugin.h>
28 #include <vlc_demux.h>
29 #include <vlc_charset.h>
30 #include <limits.h>
31
32 #include <assert.h>
33
34 #define TEMPO_MIN  20
35 #define TEMPO_MAX 250 /* Beats per minute */
36
37 static int  Open  (vlc_object_t *);
38 static void Close (vlc_object_t *);
39
40 vlc_module_begin ()
41     set_description (N_("SMF demuxer"))
42     set_category (CAT_INPUT)
43     set_subcategory (SUBCAT_INPUT_DEMUX)
44     set_capability ("demux", 20)
45     set_callbacks (Open, Close)
46 vlc_module_end ()
47
48 static int Demux   (demux_t *);
49 static int Control (demux_t *, int i_query, va_list args);
50
51 typedef struct smf_track_t
52 {
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 */
57 } mtrk_t;
58
59 static int ReadDeltaTime (stream_t *s, mtrk_t *track);
60
61 struct demux_sys_t
62 {
63     es_out_id_t *es;
64     date_t       pts;
65     uint64_t     pulse; /* Pulses counter */
66
67     unsigned     ppqn;   /* Pulses Per Quarter Note */
68     /* by the way, "quarter note" is "noire" in French */
69
70     unsigned     trackc; /* Number of tracks */
71     mtrk_t       trackv[]; /* Track states */
72 };
73
74 /*****************************************************************************
75  * Open: check file and initializes structures
76  *****************************************************************************/
77 static int Open (vlc_object_t * p_this)
78 {
79     demux_t       *p_demux = (demux_t *)p_this;
80     stream_t      *stream = p_demux->s;
81     demux_sys_t   *p_sys;
82     const uint8_t *peek;
83     unsigned       tracks, ppqn;
84     bool     multitrack;
85
86     /* (Try to) parse the SMF header */
87     /* Header chunk always has 6 bytes payload */
88     if (stream_Peek (stream, &peek, 14) < 14)
89         return VLC_EGENERIC;
90
91     /* Skip RIFF MIDI header if present */
92     if (!memcmp (peek, "RIFF", 4) && !memcmp (peek + 8, "RMID", 4))
93     {
94         uint32_t riff_len = GetDWLE (peek + 4);
95
96         msg_Dbg (p_this, "detected RIFF MIDI file (%u bytes)",
97                  (unsigned)riff_len);
98         if ((stream_Read (stream, NULL, 12) < 12))
99             return VLC_EGENERIC;
100
101         /* Look for the RIFF data chunk */
102         for (;;)
103         {
104             char chnk_hdr[8];
105             uint32_t chnk_len;
106
107             if ((riff_len < 8)
108              || (stream_Read (stream, chnk_hdr, 8) < 8))
109                 return VLC_EGENERIC;
110
111             riff_len -= 8;
112             chnk_len = GetDWLE (chnk_hdr + 4);
113             if (riff_len < chnk_len)
114                 return VLC_EGENERIC;
115             riff_len -= chnk_len;
116
117             if (!memcmp (chnk_hdr, "data", 4))
118                 break; /* found! */
119
120             if (stream_Read (stream, NULL, chnk_len) < (ssize_t)chnk_len)
121                 return VLC_EGENERIC;
122         }
123
124         /* Read real SMF header. Assume RIFF data chunk length is proper. */
125         if (stream_Peek (stream, &peek, 14) < 14)
126             return VLC_EGENERIC;
127     }
128
129     if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
130         return VLC_EGENERIC;
131     peek += 8;
132
133     /* First word: SMF type */
134     switch (GetWBE (peek))
135     {
136         case 0:
137             multitrack = false;
138             break;
139         case 1:
140             multitrack = true;
141             break;
142         default:
143             /* We don't implement SMF2 (as do many) */
144             msg_Err (p_this, "unsupported SMF file type %u", GetWBE (peek));
145             return VLC_EGENERIC;
146     }
147     peek += 2;
148
149     /* Second word: number of tracks */
150     tracks = GetWBE (peek);
151     peek += 2;
152     if (!multitrack && (tracks != 1))
153     {
154         msg_Err (p_this, "invalid SMF type 0 file");
155         return VLC_EGENERIC;
156     }
157
158     msg_Dbg (p_this, "detected Standard MIDI File (type %u) with %u track(s)",
159              multitrack, tracks);
160
161     /* Third/last word: timing */
162     ppqn = GetWBE (peek);
163     if (ppqn & 0x8000)
164     {
165         /* FIXME */
166         msg_Err (p_this, "SMPTE timestamps not implemented");
167         return VLC_EGENERIC;
168     }
169     else
170     {
171         msg_Dbg (p_this, " %u pulses per quarter note", ppqn);
172     }
173
174     p_sys = malloc (sizeof (*p_sys) + (sizeof (mtrk_t) * tracks));
175     if (unlikely(p_sys == NULL))
176         return VLC_ENOMEM;
177
178     /* We've had a valid SMF header - now skip it*/
179     if (stream_Read (stream, NULL, 14) < 14)
180         goto error;
181
182     /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
183     date_Init (&p_sys->pts, ppqn * 2, 1);
184     date_Set (&p_sys->pts, 0);
185     p_sys->pulse        = 0;
186     p_sys->ppqn         = ppqn;
187
188     p_sys->trackc       = tracks;
189     /* Prefetch track offsets */
190     for (unsigned i = 0; i < tracks; i++)
191     {
192         uint8_t head[8];
193
194         if (i > 0)
195         {
196             /* Seeking screws streaming up, but there is no way around this,
197              * as SMF1 tracks are performed simultaneously.
198              * Not a big deal as SMF1 are usually only a few kbytes anyway. */
199             if (stream_Seek (stream, p_sys->trackv[i - 1].end))
200             {
201                 msg_Err (p_this, "cannot build SMF index (corrupted file?)");
202                 goto error;
203             }
204         }
205
206         for (;;)
207         {
208             if (stream_Read (stream, head, 8) < 8)
209             {
210                 /* FIXME: don't give up if we have at least one valid track */
211                 msg_Err (p_this, "incomplete SMF chunk, file is corrupted");
212                 goto error;
213             }
214
215             if (memcmp (head, "MTrk", 4) == 0)
216                 break;
217
218             msg_Dbg (p_this, "skipping unknown SMF chunk");
219             stream_Read (stream, NULL, GetDWBE (head + 4));
220         }
221
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. */
230     }
231
232     es_format_t  fmt;
233     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MIDI);
234     fmt.audio.i_channels = 2;
235     fmt.audio.i_rate = 44100; /* dummy value */
236     p_sys->es = es_out_Add (p_demux->out, &fmt);
237
238     p_demux->pf_demux   = Demux;
239     p_demux->pf_control = Control;
240     p_demux->p_sys      = p_sys;
241     return VLC_SUCCESS;
242
243 error:
244     free (p_sys);
245     return VLC_EGENERIC;
246 }
247
248 /**
249  * Releases allocate resources.
250  */
251 static void Close (vlc_object_t * p_this)
252 {
253     demux_t *p_demux = (demux_t *)p_this;
254     demux_sys_t *p_sys = p_demux->p_sys;
255
256     free (p_sys);
257 }
258
259 /**
260  * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
261  * @return read value, or -1 on EOF/error.
262  */
263 static int32_t ReadVarInt (stream_t *s)
264 {
265     uint32_t val = 0;
266     uint8_t byte;
267
268     for (unsigned i = 0; i < 4; i++)
269     {
270         if (stream_Read (s, &byte, 1) < 1)
271             return -1;
272
273         val = (val << 7) | (byte & 0x7f);
274         if ((byte & 0x80) == 0)
275             return val;
276     }
277
278     return -1;
279 }
280
281
282 /**
283  * Reads (delta) time from the next event of a given track.
284  * @param s stream to read data from (must be positioned at the right offset)
285  */
286 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
287 {
288     int32_t delta_time;
289
290     assert (stream_Tell (s) == track->offset);
291
292     if (track->offset >= track->end)
293     {
294         /* This track is done */
295         track->next = UINT64_MAX;
296         return 0;
297     }
298
299     delta_time = ReadVarInt (s);
300     if (delta_time < 0)
301         return -1;
302
303     track->next += delta_time;
304     track->offset = stream_Tell (s);
305     return 0;
306 }
307
308
309 /**
310  * Non-MIDI Meta events handler
311  */
312 static
313 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
314 {
315     stream_t *s = p_demux->s;
316     demux_sys_t *p_sys = p_demux->p_sys;
317     uint8_t *payload;
318     uint8_t type;
319     int32_t length;
320     int ret = 0;
321
322     if (stream_Read (s, &type, 1) != 1)
323         return -1;
324
325     length = ReadVarInt (s);
326     if (length < 0)
327         return -1;
328
329     payload = malloc (length + 1);
330     if ((payload == NULL)
331      || (stream_Read (s, payload, length) != length))
332     {
333         free (payload);
334         return -1;
335     }
336
337     payload[length] = '\0';
338
339     switch (type)
340     {
341         case 0x00: /* Sequence Number */
342             break;
343
344         case 0x01: /* Text (comment) */
345             EnsureUTF8 ((char *)payload);
346             msg_Info (p_demux, "Text      : %s", (char *)payload);
347             break;
348
349         case 0x02: /* Copyright */
350             EnsureUTF8 ((char *)payload);
351             msg_Info (p_demux, "Copyright : %s", (char *)payload);
352             break;
353
354         case 0x03: /* Track name */
355             EnsureUTF8 ((char *)payload);
356             msg_Info (p_demux, "Track name: %s", (char *)payload);
357             break;
358
359         case 0x04: /* Instrument name */
360             EnsureUTF8 ((char *)payload);
361             msg_Info (p_demux, "Instrument: %s", (char *)payload);
362             break;
363
364         case 0x05: /* Lyric (one syllable) */
365             /*EnsureUTF8 ((char *)payload);*/
366             break;
367
368         case 0x06: /* Marker text */
369             EnsureUTF8 ((char *)payload);
370             msg_Info (p_demux, "Marker    : %s", (char *)payload);
371
372         case 0x07: /* Cue point (WAVE filename) */
373             EnsureUTF8 ((char *)payload);
374             msg_Info (p_demux, "Cue point : %s", (char *)payload);
375             break;
376
377         case 0x08: /* Program/Patch name */
378             EnsureUTF8 ((char *)payload);
379             msg_Info (p_demux, "Patch name: %s", (char *)payload);
380             break;
381
382         case 0x09: /* MIDI port name */
383             EnsureUTF8 ((char *)payload);
384             msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
385             break;
386
387         case 0x2F: /* End of track */
388             if (tr->end != stream_Tell (s))
389             {
390                 msg_Err (p_demux, "misplaced end of track");
391                 ret = -1;
392             }
393             break;
394
395         case 0x51: /* Tempo */
396             if (length == 3)
397             {
398                 uint32_t uspqn = (payload[0] << 16)
399                                | (payload[1] << 8) | payload[2];
400                 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
401                 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
402                          (unsigned)uspqn, tempo);
403
404                 if (tempo < TEMPO_MIN)
405                 {
406                     msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
407                     tempo = TEMPO_MIN;
408                 }
409                 else
410                 if (tempo > TEMPO_MAX)
411                 {
412                     msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
413                     tempo = TEMPO_MAX;
414                 }
415                 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
416             }
417             else
418                 ret = -1;
419             break;
420
421         case 0x54: /* SMPTE offset */
422             if (length == 5)
423                 msg_Warn (p_demux, "SMPTE offset not implemented");
424             else
425                 ret = -1;
426             break;
427
428         case 0x58: /* Time signature */
429             if (length == 4)
430                 ;
431             else
432                 ret = -1;
433             break;
434
435         case 0x59: /* Key signature */
436             if (length == 2)
437                 ;
438             else
439                 ret = -1;
440             break;
441
442         case 0x7f: /* Proprietary event */
443             msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
444                      length);
445             break;
446
447         default:
448             msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
449                       type, length);
450     }
451
452     free (payload);
453     return ret;
454 }
455
456
457
458 static
459 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
460 {
461     stream_t *s = p_demux->s;
462     block_t *block;
463     uint8_t first, event;
464     unsigned datalen;
465
466     if (stream_Seek (s, tr->offset)
467      || (stream_Read (s, &first, 1) != 1))
468         return -1;
469
470     event = (first & 0x80) ? first : tr->running_event;
471
472     switch (event & 0xf0)
473     {
474         case 0xF0: /* System Exclusive */
475             switch (event)
476             {
477                 case 0xF0: /* System Specific start */
478                 case 0xF7: /* System Specific continuation */
479                 {
480                     /* Variable length followed by SysEx event data */
481                     int32_t len = ReadVarInt (s);
482                     if (len == -1)
483                         return -1;
484
485                     block = stream_Block (s, len);
486                     if (block == NULL)
487                         return -1;
488                     block = block_Realloc (block, 1, len);
489                     if (block == NULL)
490                         return -1;
491                     block->p_buffer[0] = event;
492                     goto send;
493                 }
494                 case 0xFF: /* SMF Meta Event */
495                     if (HandleMeta (p_demux, tr))
496                         return -1;
497                     /* We MUST NOT pass this event forward. It would be
498                      * confused as a MIDI Reset real-time event. */
499                     goto skip;
500                 case 0xF1:
501                 case 0xF3:
502                     datalen = 1;
503                     break;
504                 case 0xF2:
505                     datalen = 2;
506                     break;
507                 case 0xF4:
508                 case 0xF5:
509                     /* We cannot handle undefined "common" (non-real-time)
510                      * events inside SMF, as we cannot differentiate a
511                      * one byte delta-time (< 0x80) from event data. */
512                 default:
513                     datalen = 0;
514                     break;
515             }
516             break;
517         case 0xC0:
518         case 0xD0:
519             datalen = 1;
520             break;
521         default:
522             datalen = 2;
523             break;
524     }
525
526     /* FIXME: one message per block is very inefficient */
527     block = block_Alloc (1 + datalen);
528     if (block == NULL)
529         goto skip;
530
531     block->p_buffer[0] = event;
532     if (first & 0x80)
533     {
534         stream_Read (s, block->p_buffer + 1, datalen);
535     }
536     else
537     {
538         if (datalen == 0)
539         {
540             msg_Err (p_demux, "malformatted MIDI event");
541             return -1; /* implicit running status requires non-empty payload */
542         }
543
544         block->p_buffer[1] = first;
545         if (datalen > 1)
546             stream_Read (s, block->p_buffer + 2, datalen - 1);
547     }
548
549 send:
550     block->i_dts = block->i_pts = VLC_TS_0 + date_Get (&p_demux->p_sys->pts);
551     es_out_Send (p_demux->out, p_demux->p_sys->es, block);
552
553 skip:
554     if (event < 0xF8)
555         /* If event is not real-time, update running status */
556         tr->running_event = event;
557
558     tr->offset = stream_Tell (s);
559     return 0;
560 }
561
562 /*****************************************************************************
563  * Demux: read chunks and send them to the synthesizer
564  *****************************************************************************
565  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
566  *****************************************************************************/
567 static int Demux (demux_t *p_demux)
568 {
569     stream_t *s = p_demux->s;
570     demux_sys_t *p_sys = p_demux->p_sys;
571     uint64_t     pulse = p_sys->pulse, next_pulse = UINT64_MAX;
572
573     if (pulse == UINT64_MAX)
574         return 0; /* all tracks are done */
575
576     es_out_Control (p_demux->out, ES_OUT_SET_PCR,
577                     VLC_TS_0 + date_Get (&p_sys->pts));
578
579     for (unsigned i = 0; i < p_sys->trackc; i++)
580     {
581         mtrk_t *track = p_sys->trackv + i;
582
583         while (track->next == pulse)
584         {
585             if (HandleMessage (p_demux, track)
586              || ReadDeltaTime (s, track))
587             {
588                 msg_Err (p_demux, "fatal parsing error");
589                 return VLC_EGENERIC;
590             }
591         }
592
593         if (track->next < next_pulse)
594             next_pulse = track->next;
595     }
596
597     mtime_t cur_tick = (date_Get (&p_sys->pts) + 9999) / 10000, last_tick;
598     if (next_pulse != UINT64_MAX)
599         last_tick = date_Increment (&p_sys->pts, next_pulse - pulse) / 10000;
600     else
601         last_tick = cur_tick + 1;
602
603     /* MIDI Tick emulation (ping the decoder every 10ms) */
604     while (cur_tick < last_tick)
605     {
606         block_t *tick = block_Alloc (1);
607         if (tick == NULL)
608             break;
609
610         tick->p_buffer[0] = 0xF9;
611         tick->i_dts = tick->i_pts = VLC_TS_0 + cur_tick++ * 10000;
612         es_out_Send (p_demux->out, p_sys->es, tick);
613     }
614
615     p_sys->pulse = next_pulse;
616
617     return 1;
618 }
619
620
621 /*****************************************************************************
622  * Control:
623  *****************************************************************************/
624 static int Control (demux_t *p_demux, int i_query, va_list args)
625 {
626     demux_sys_t *p_sys = p_demux->p_sys;
627
628     switch (i_query)
629     {
630         case DEMUX_GET_TIME:
631         {
632             *(va_arg (args, int64_t *)) = date_Get (&p_sys->pts);
633             return 0;
634         }
635 #if 0
636         /* TODO: */
637         case DEMUX_SET_TIME:
638         case DEMUX_GET_POSITION:
639         case DEMUX_SET_POSITION:
640         case DEMUX_GET_LENGTH:
641 #endif
642     }
643     return VLC_EGENERIC;
644 }