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