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