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