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