]> git.sesse.net Git - vlc/blob - modules/demux/smf.c
SMF: avoid a DOS if the SMF header is invalid
[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_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[0]; /* 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 (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     p_demux->pf_demux   = Demux;
183     p_demux->pf_control = Control;
184     p_demux->p_sys      = p_sys;
185
186     /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
187     date_Init (&p_sys->pts, ppqn * 2, 1);
188     date_Set (&p_sys->pts, 0);
189     p_sys->pulse        = 0;
190     p_sys->ppqn         = ppqn;
191
192     p_sys->trackc       = tracks;
193     /* Prefetch track offsets */
194     for (unsigned i = 0; i < tracks; i++)
195     {
196         uint8_t head[8];
197
198         if (i > 0)
199         {
200             /* Seeking screws streaming up, but there is no way around this,
201              * as SMF1 tracks are performed simultaneously.
202              * Not a big deal as SMF1 are usually only a few kbytes anyway. */
203             if (stream_Seek (stream,  p_sys->trackv[i-1].end))
204             {
205                 msg_Err (p_this, "cannot build SMF index (corrupted file?)");
206                 goto error;
207             }
208         }
209
210         for (;;)
211         {
212             if (stream_Read (stream, head, 8) < 8)
213             {
214                 /* FIXME: don't give up if we have at least one valid track */
215                 msg_Err (p_this, "incomplete SMF chunk, file is corrupted");
216                 goto error;
217             }
218
219             if (memcmp (head, "MTrk", 4) == 0)
220                 break;
221
222             msg_Dbg (p_this, "skipping unknown SMF chunk");
223             stream_Read (stream, NULL, GetDWBE (head + 4));
224         }
225
226         p_sys->trackv[i].offset = stream_Tell (stream);
227         p_sys->trackv[i].end = p_sys->trackv[i].offset + GetDWBE (head + 4);
228         p_sys->trackv[i].next = 0;
229         ReadDeltaTime (stream, p_sys->trackv + i);
230         p_sys->trackv[i].running_event = 0xF6;
231         /* Why 0xF6 (Tuning Calibration)?
232          * Because it has zero bytes of data, so the parser will detect the
233          * error if the first event uses running status. */
234     }
235
236     es_format_t  fmt;
237     es_format_Init (&fmt, AUDIO_ES, VLC_CODEC_MIDI);
238     fmt.audio.i_channels = 2;
239     fmt.audio.i_rate = 44100; /* dummy value */
240     p_sys->es = es_out_Add (p_demux->out, &fmt);
241
242     return VLC_SUCCESS;
243
244 error:
245     free (p_sys);
246     return VLC_EGENERIC;
247 }
248
249 /**
250  * Releases allocate resources.
251  */
252 static void Close (vlc_object_t * p_this)
253 {
254     demux_t *p_demux = (demux_t *)p_this;
255     demux_sys_t *p_sys = p_demux->p_sys;
256
257     free (p_sys);
258 }
259
260 /**
261  * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
262  * @return read value, or -1 on EOF/error.
263  */
264 static int32_t ReadVarInt (stream_t *s)
265 {
266     uint32_t val = 0;
267     uint8_t byte;
268
269     for (unsigned i = 0; i < 4; i++)
270     {
271         if (stream_Read (s, &byte, 1) < 1)
272             return -1;
273
274         val = (val << 7) | (byte & 0x7f);
275         if ((byte & 0x80) == 0)
276             return val;
277     }
278
279     return -1;
280 }
281
282
283 /**
284  * Reads (delta) time from the next event of a given track.
285  * @param s stream to read data from (must be positioned at the right offset)
286  */
287 static int ReadDeltaTime (stream_t *s, mtrk_t *track)
288 {
289     int32_t delta_time;
290
291     assert (stream_Tell (s) == track->offset);
292
293     if (track->offset >= track->end)
294     {
295         /* This track is done */
296         track->next = UINT64_MAX;
297         return 0;
298     }
299
300     delta_time = ReadVarInt (s);
301     if (delta_time < 0)
302         return -1;
303
304     track->next += delta_time;
305     track->offset = stream_Tell (s);
306     return 0;
307 }
308
309
310 /**
311  * Non-MIDI Meta events handler
312  */
313 static
314 int HandleMeta (demux_t *p_demux, mtrk_t *tr)
315 {
316     stream_t *s = p_demux->s;
317     demux_sys_t *p_sys = p_demux->p_sys;
318     uint8_t *payload;
319     uint8_t type;
320     int32_t length;
321     int ret = 0;
322
323     if (stream_Read (s, &type, 1) != 1)
324         return -1;
325
326     length = ReadVarInt (s);
327     if (length < 0)
328         return -1;
329
330     payload = malloc (length + 1);
331     if ((payload == NULL)
332      || (stream_Read (s, payload, length) != length))
333     {
334         free (payload);
335         return -1;
336     }
337
338     payload[length] = '\0';
339
340     switch (type)
341     {
342         case 0x00: /* Sequence Number */
343             break;
344
345         case 0x01: /* Text (comment) */
346             EnsureUTF8 ((char *)payload);
347             msg_Info (p_demux, "Text      : %s", (char *)payload);
348             break;
349
350         case 0x02: /* Copyright */
351             EnsureUTF8 ((char *)payload);
352             msg_Info (p_demux, "Copyright : %s", (char *)payload);
353             break;
354
355         case 0x03: /* Track name */
356             EnsureUTF8 ((char *)payload);
357             msg_Info (p_demux, "Track name: %s", (char *)payload);
358             break;
359
360         case 0x04: /* Instrument name */
361             EnsureUTF8 ((char *)payload);
362             msg_Info (p_demux, "Instrument: %s", (char *)payload);
363             break;
364
365         case 0x05: /* Lyric (one syllable) */
366             /*EnsureUTF8 ((char *)payload);*/
367             break;
368
369         case 0x06: /* Marker text */
370             EnsureUTF8 ((char *)payload);
371             msg_Info (p_demux, "Marker    : %s", (char *)payload);
372
373         case 0x07: /* Cue point (WAVE filename) */
374             EnsureUTF8 ((char *)payload);
375             msg_Info (p_demux, "Cue point : %s", (char *)payload);
376             break;
377
378         case 0x08: /* Program/Patch name */
379             EnsureUTF8 ((char *)payload);
380             msg_Info (p_demux, "Patch name: %s", (char *)payload);
381             break;
382
383         case 0x09: /* MIDI port name */
384             EnsureUTF8 ((char *)payload);
385             msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
386             break;
387
388         case 0x2F: /* End of track */
389             if (tr->end != stream_Tell (s))
390             {
391                 msg_Err (p_demux, "misplaced end of track");
392                 ret = -1;
393             }
394             break;
395
396         case 0x51: /* Tempo */
397             if (length == 3)
398             {
399                 uint32_t uspqn = (payload[0] << 16)
400                                | (payload[1] << 8) | payload[2];
401                 unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
402                 msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
403                          (unsigned)uspqn, tempo);
404
405                 if (tempo < TEMPO_MIN)
406                 {
407                     msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
408                     tempo = TEMPO_MIN;
409                 }
410                 else
411                 if (tempo > TEMPO_MAX)
412                 {
413                     msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
414                     tempo = TEMPO_MAX;
415                 }
416                 date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
417             }
418             else
419                 ret = -1;
420             break;
421
422         case 0x54: /* SMPTE offset */
423             if (length == 5)
424                 msg_Warn (p_demux, "SMPTE offset not implemented");
425             else
426                 ret = -1;
427             break;
428
429         case 0x58: /* Time signature */
430             if (length == 4)
431                 ;
432             else
433                 ret = -1;
434             break;
435
436         case 0x59: /* Key signature */
437             if (length == 2)
438                 ;
439             else
440                 ret = -1;
441             break;
442
443         case 0x7f: /* Proprietary event */
444             msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
445                      length);
446             break;
447
448         default:
449             msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
450                       type, length);
451     }
452
453     free (payload);
454     return ret;
455 }
456
457
458
459 static
460 int HandleMessage (demux_t *p_demux, mtrk_t *tr)
461 {
462     stream_t *s = p_demux->s;
463     block_t *block;
464     uint8_t first, event;
465     unsigned datalen;
466
467     if (stream_Seek (s, tr->offset)
468      || (stream_Read (s, &first, 1) != 1))
469         return -1;
470
471     event = (first & 0x80) ? first : tr->running_event;
472
473     switch (event & 0xf0)
474     {
475         case 0xF0: /* System Exclusive */
476             switch (event)
477             {
478                 case 0xF0: /* System Specific start */
479                 case 0xF7: /* System Specific continuation */
480                 {
481                     /* Variable length followed by SysEx event data */
482                     int32_t len = ReadVarInt (s);
483                     if (len == -1)
484                         return -1;
485
486                     block = stream_Block (s, len);
487                     if (block == NULL)
488                         return -1;
489                     block = block_Realloc (block, 1, len);
490                     if (block == NULL)
491                         return -1;
492                     block->p_buffer[0] = event;
493                     goto send;
494                 }
495                 case 0xFF: /* SMF Meta Event */
496                     if (HandleMeta (p_demux, tr))
497                         return -1;
498                     /* We MUST NOT pass this event forward. It would be
499                      * confused as a MIDI Reset real-time event. */
500                     goto skip;
501                 case 0xF1:
502                 case 0xF3:
503                     datalen = 1;
504                     break;
505                 case 0xF2:
506                     datalen = 2;
507                     break;
508                 case 0xF4:
509                 case 0xF5:
510                     /* We cannot handle undefined "common" (non-real-time)
511                      * events inside SMF, as we cannot differentiate a
512                      * one byte delta-time (< 0x80) from event data. */
513                 default:
514                     datalen = 0;
515                     break;
516             }
517             break;
518         case 0xC0:
519         case 0xD0:
520             datalen = 1;
521             break;
522         default:
523             datalen = 2;
524             break;
525     }
526
527     /* FIXME: one message per block is very inefficient */
528     block = block_New (p_demux, 1 + datalen);
529     if (block == NULL)
530         goto skip;
531
532     block->p_buffer[0] = event;
533     if (first & 0x80)
534     {
535         stream_Read (s, block->p_buffer + 1, datalen);
536     }
537     else
538     {
539         if (datalen == 0)
540         {
541             msg_Err (p_demux, "malformatted MIDI event");
542             return -1; /* can't use implicit running status with empty payload! */
543         }
544
545         block->p_buffer[1] = first;
546         if (datalen > 1)
547             stream_Read (s, block->p_buffer + 2, datalen - 1);
548     }
549
550 send:
551     block->i_dts = block->i_pts = VLC_TS_0 + date_Get (&p_demux->p_sys->pts);
552     es_out_Send (p_demux->out, p_demux->p_sys->es, block);
553
554 skip:
555     if (event < 0xF8)
556         /* If event is not real-time, update running status */
557         tr->running_event = event;
558
559     tr->offset = stream_Tell (s);
560     return 0;
561 }
562
563 /*****************************************************************************
564  * Demux: read chunks and send them to the synthesizer
565  *****************************************************************************
566  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
567  *****************************************************************************/
568 static int Demux (demux_t *p_demux)
569 {
570     stream_t *s = p_demux->s;
571     demux_sys_t *p_sys = p_demux->p_sys;
572     uint64_t     pulse = p_sys->pulse, next_pulse = UINT64_MAX;
573
574     if (pulse == UINT64_MAX)
575         return 0; /* all tracks are done */
576
577     es_out_Control (p_demux->out, ES_OUT_SET_PCR, 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_New (p_demux, 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 }