smf.c 16.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*****************************************************************************
 * smf.c : Standard MIDI File (.mid) demux module for vlc
 *****************************************************************************
 * Copyright © 2007 Rémi Denis-Courmont
 * $Id$
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

22
23
24
25
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

26
27
28
29
#include <vlc/vlc.h>
#include <vlc_demux.h>
#include <vlc_aout.h>
#include <vlc_codecs.h>
30
#include <vlc_charset.h>
31
32
#include <limits.h>

33
34
35
#define TEMPO_MIN  20
#define TEMPO_MAX 250 /* Beats per minute */

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
static int  Open  (vlc_object_t *);
static void Close (vlc_object_t *);

vlc_module_begin ();
    set_description (_("SMF demuxer"));
    set_category (CAT_INPUT);
    set_subcategory (SUBCAT_INPUT_DEMUX);
    set_capability ("demux2", 20);
    set_callbacks (Open, Close);
vlc_module_end ();

static int Demux   (demux_t *);
static int Control (demux_t *, int i_query, va_list args);

typedef struct smf_track_t
{
    int64_t  offset; /* Read offset in the file (stream_Tell) */
    int64_t  end;    /* End offset in the file */
    uint64_t next;   /* Time of next message (in term of pulses) */
    uint8_t  running_event; /* Running (previous) event */
} mtrk_t;

static int ReadDeltaTime (stream_t *s, mtrk_t *track);

struct demux_sys_t
{
    es_out_id_t *es;
    date_t       pts;
    uint64_t     pulse; /* Pulses counter */

    unsigned     ppqn;   /* Pulses Per Quarter Note */
    /* by the way, "quarter note" is "noire" in French */

    unsigned     trackc; /* Number of tracks */
    mtrk_t       trackv[0]; /* Track states */
};

/*****************************************************************************
 * Open: check file and initializes structures
 *****************************************************************************/
static int Open (vlc_object_t * p_this)
{
    demux_t       *p_demux = (demux_t *)p_this;
    stream_t      *stream = p_demux->s;
    demux_sys_t   *p_sys;
    const uint8_t *peek;
    unsigned       tracks, ppqn;
    vlc_bool_t     multitrack;

    /* (Try to) parse the SMF header */
    /* Header chunk always has 6 bytes payload */
    if (stream_Peek (stream, &peek, 14) < 14)
        return VLC_EGENERIC;

    if (memcmp (peek, "MThd\x00\x00\x00\x06", 8))
        return VLC_EGENERIC;
    peek += 8;

    /* First word: SMF type */
    switch (GetWBE (peek))
    {
        case 0:
            multitrack = VLC_FALSE;
            break;
        case 1:
            multitrack = VLC_TRUE;
            break;
        default:
            /* We don't implement SMF2 (as do many) */
            msg_Err (p_this, "unsupported SMF file type %u", GetWBE (peek));
            return VLC_EGENERIC;
    }
    peek += 2;

    /* Second word: number of tracks */
    tracks = GetWBE (peek);
    peek += 2;
    if (!multitrack && (tracks != 1))
    {
        msg_Err (p_this, "invalid SMF type 0 file");
        return VLC_EGENERIC;
    }

    msg_Dbg (p_this, "detected Standard MIDI File (type %u) with %u track(s)",
             multitrack, tracks);

    /* Third/last word: timing */
    ppqn = GetWBE (peek);
    if (ppqn & 0x8000)
    {
        /* FIXME */
        msg_Err (p_this, "SMPTE timestamps not implemented");
        return VLC_EGENERIC;
    }
    else
    {
        msg_Dbg (p_this, " %u pulses per quarter note", ppqn);
    }

    p_sys = malloc (sizeof (*p_sys) + (sizeof (mtrk_t) * tracks));
    if (p_sys == NULL)
        return VLC_ENOMEM;

    /* We've had a valid SMF header - now skip it*/
    if (stream_Read (stream, NULL, 14) < 14)
        goto error;

    p_demux->pf_demux   = Demux;
    p_demux->pf_control = Control;
    p_demux->p_sys      = p_sys;

147
148
    /* Default SMF tempo is 120BPM, i.e. half a second per quarter note */
    date_Init (&p_sys->pts, ppqn * 2, 1);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
149
    date_Set (&p_sys->pts, 1);
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    p_sys->pulse        = 0;
    p_sys->ppqn         = ppqn;

    p_sys->trackc       = tracks;
    /* Prefetch track offsets */
    for (unsigned i = 0; i < tracks; i++)
    {
        uint8_t head[8];

        if (i > 0)
        {
            /* Seeking screws streaming up, but there is no way around this,
             * as SMF1 tracks are performed simultaneously.
             * Not a big deal as SMF1 are usually only a few kbytes anyway. */
            if (stream_Seek (stream,  p_sys->trackv[i-1].end))
            {
                msg_Err (p_this, "cannot build SMF index (corrupted file?)");
                goto error;
            }
        }

        for (;;)
        {
            stream_Read (stream, head, 8);
            if (memcmp (head, "MTrk", 4) == 0)
                break;

            msg_Dbg (p_this, "skipping unknown SMF chunk");
            stream_Read (stream, NULL, GetDWBE (head + 4));
        }

        p_sys->trackv[i].offset = stream_Tell (stream);
        p_sys->trackv[i].end = p_sys->trackv[i].offset + GetDWBE (head + 4);
        p_sys->trackv[i].next = 0;
        ReadDeltaTime (stream, p_sys->trackv + i);
        p_sys->trackv[i].running_event = 0xF6;
        /* Why 0xF6 (Tuning Calibration)?
         * Because it has zero bytes of data, so the parser will detect the
         * error if the first event uses running status. */
    }

191
192
193
194
    es_format_t  fmt;
    es_format_Init (&fmt, AUDIO_ES, VLC_FOURCC('M', 'I', 'D', 'I'));
    p_sys->es = es_out_Add (p_demux->out, &fmt);

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    return VLC_SUCCESS;

error:
    free (p_sys);
    return VLC_EGENERIC;
}

/**
 * Releases allocate resources.
 */
static void Close (vlc_object_t * p_this)
{
    demux_t *p_demux = (demux_t *)p_this;
    demux_sys_t *p_sys = p_demux->p_sys;

    free (p_sys);
}

/**
 * Reads MIDI variable length (7, 14, 21 or 28 bits) integer.
 * @return read value, or -1 on EOF/error.
 */
static int32_t ReadVarInt (stream_t *s)
{
    uint32_t val = 0;
    uint8_t byte;

    for (unsigned i = 0; i < 4; i++)
    {
        if (stream_Read (s, &byte, 1) < 1)
            return -1;

        val = (val << 7) | (byte & 0x7f);
        if ((byte & 0x80) == 0)
            return val;
    }

    return -1;
}


/**
 * Reads (delta) time from the next event of a given track.
 * @param s stream to read data from (must be positioned at the right offset)
 */
static int ReadDeltaTime (stream_t *s, mtrk_t *track)
{
    int32_t delta_time;

    assert (stream_Tell (s) == track->offset);

    if (track->offset >= track->end)
    {
        /* This track is done */
        track->next = UINT64_MAX;
        return 0;
    }

    delta_time = ReadVarInt (s);
    if (delta_time < 0)
        return -1;

    track->next += delta_time;
    track->offset = stream_Tell (s);
    return 0;
}


263
264
265
266
267
268
269
/**
 * Non-MIDI Meta events handler
 */
static
int HandleMeta (demux_t *p_demux, mtrk_t *tr)
{
    stream_t *s = p_demux->s;
270
    demux_sys_t *p_sys = p_demux->p_sys;
271
272
273
    uint8_t *payload;
    uint8_t type;
    int32_t length;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
274
    int ret = 0;
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298

    if (stream_Read (s, &type, 1) != 1)
        return -1;

    length = ReadVarInt (s);
    if (length < 0)
        return -1;

    payload = malloc (length + 1);
    if ((payload == NULL)
     || (stream_Read (s, payload, length) != length))
    {
        free (payload);
        return -1;
    }

    payload[length] = '\0';

    switch (type)
    {
        case 0x00: /* Sequence Number */
            break;

        case 0x01: /* Test (comment) */
299
            EnsureUTF8 ((char *)payload);
300
301
302
303
            msg_Info (p_demux, "Text      : %s", (char *)payload);
            break;

        case 0x02: /* Copyright */
304
            EnsureUTF8 ((char *)payload);
305
306
307
308
            msg_Info (p_demux, "Copyright : %s", (char *)payload);
            break;

        case 0x03: /* Track name */
309
            EnsureUTF8 ((char *)payload);
310
311
312
313
            msg_Info (p_demux, "Track name: %s", (char *)payload);
            break;

        case 0x04: /* Instrument name */
314
            EnsureUTF8 ((char *)payload);
315
316
317
318
            msg_Info (p_demux, "Instrument: %s", (char *)payload);
            break;

        case 0x05: /* Lyric (one syllable) */
319
            /*EnsureUTF8 ((char *)payload);*/
320
321
322
            break;

        case 0x06: /* Marker text */
323
            EnsureUTF8 ((char *)payload);
324
325
326
            msg_Info (p_demux, "Marker    : %s", (char *)payload);

        case 0x07: /* Cue point (WAVE filename) */
327
            EnsureUTF8 ((char *)payload);
328
329
330
331
            msg_Info (p_demux, "Cue point : %s", (char *)payload);
            break;

        case 0x08: /* Program/Patch name */
332
            EnsureUTF8 ((char *)payload);
333
334
335
336
            msg_Info (p_demux, "Patch name: %s", (char *)payload);
            break;

        case 0x09: /* MIDI port name */
337
            EnsureUTF8 ((char *)payload);
338
339
340
341
342
343
344
            msg_Dbg (p_demux, "MIDI port : %s", (char *)payload);
            break;

        case 0x2F: /* End of track */
            if (tr->end != stream_Tell (s))
            {
                msg_Err (p_demux, "misplaced end of track");
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
345
                ret = -1;
346
347
348
349
            }
            break;

        case 0x51: /* Tempo */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
350
351
            if (length == 3)
            {
352
                uint32_t uspqn = (payload[0] << 16)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
353
                               | (payload[1] << 8) | payload[2];
354
355
356
357
                unsigned tempo = 60 * 1000000 / (uspqn ? uspqn : 1);
                msg_Dbg (p_demux, "tempo: %uus/qn -> %u BPM",
                         (unsigned)uspqn, tempo);

358
                if (tempo < TEMPO_MIN)
359
                {
360
361
                    msg_Warn (p_demux, "tempo too slow -> %u BPM", TEMPO_MIN);
                    tempo = TEMPO_MIN;
362
363
                }
                else
364
                if (tempo > TEMPO_MAX)
365
                {
366
367
                    msg_Warn (p_demux, "tempo too fast -> %u BPM", TEMPO_MAX);
                    tempo = TEMPO_MAX;
368
369
                }
                date_Change (&p_sys->pts, p_sys->ppqn * tempo, 60);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
370
371
372
            }
            else
                ret = -1;
373
374
375
            break;

        case 0x54: /* SMPTE offset */
376
377
378
379
380
381
            if (length == 5)
                msg_Warn (p_demux, "SMPTE offset not implemented");
            else
                ret = -1;
            break;

382
        case 0x58: /* Time signature */
383
384
385
386
387
388
            if (length == 4)
                ;
            else
                ret = -1;
            break;

389
        case 0x59: /* Key signature */
390
391
392
393
            if (length == 2)
                ;
            else
                ret = -1;
394
395
396
            break;

        case 0x7f: /* Proprietary event */
397
398
            msg_Dbg (p_demux, "ignored proprietary SMF Meta Event (%d bytes)",
                     length);
399
400
401
402
403
404
405
406
407
408
409
410
411
            break;

        default:
            msg_Warn (p_demux, "unknown SMF Meta Event type 0x%02X (%d bytes)",
                      type, length);
    }

    free (payload);
    return 0;
}



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
static
int HandleMessage (demux_t *p_demux, mtrk_t *tr)
{
    stream_t *s = p_demux->s;
    block_t *block;
    uint8_t first, event;
    unsigned datalen;

    if (stream_Seek (s, tr->offset)
     || (stream_Read (s, &first, 1) != 1))
        return -1;

    event = (first & 0x80) ? first : tr->running_event;

    switch (event & 0xf0)
    {
        case 0xF0: /* System Exclusive */
            switch (event)
            {
                case 0xF0: /* System Specific */
                {
                    /* TODO: don't skip these */
                    stream_Read (s, NULL, 1); /* Manuf ID */
                    for (;;)
                    {
                        uint8_t c;
                        if (stream_Read (s, &c, 1) != 1)
                            return -1;
                        if (c == 0xF7)
                            goto skip;
                    }
                }
                case 0xFF: /* SMF Meta Event */
445
                    if (HandleMeta (p_demux, tr))
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
                        return -1;
                    /* We MUST NOT pass this event to forward. It would be
                     * confused as a MIDI Reset real-time event. */
                    goto skip;
                case 0xF1:
                case 0xF3:
                    datalen = 1;
                    break;
                case 0xF2:
                    datalen = 2;
                    break;
                case 0xF4:
                case 0xF5:
                    /* We cannot handle undefined "common" (non-real-time)
                     * events inside SMF, as we cannot differentiate a
                     * one byte delta-time (< 0x80) from event data. */
                case 0xF7: /* End of sysex -> should never happen(?) */
                    msg_Err (p_demux, "unknown MIDI event 0x%02X", event);
                    return -1; /* undefined events */
                default:
                    datalen = 0;
                    break;
            }
        case 0xC0:
        case 0xD0:
            datalen = 1;
            break;
        default:
            datalen = 2;
            break;
    }

    /* FIXME: one message per block is very inefficient */
    block = block_New (p_demux, 1 + datalen);
    if (block == NULL)
        goto skip;

    block->p_buffer[0] = event;
    if (first & 0x80)
    {
        stream_Read (s, block->p_buffer + 1, datalen);
    }
    else
    {
        if (datalen == 0)
        {
            msg_Err (p_demux, "malformatted MIDI event");
            return -1; /* can't use implicit running status with empty payload! */
        }

        block->p_buffer[1] = first;
        if (datalen > 1)
            stream_Read (s, block->p_buffer + 2, datalen - 1);
    }

501
    block->i_dts = block->i_pts = date_Get (&p_demux->p_sys->pts);
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
    es_out_Send (p_demux->out, p_demux->p_sys->es, block);

skip:
    if (event < 0xF8)
        /* If event is not real-time, update running status */
        tr->running_event = event;

    tr->offset = stream_Tell (s);
    return 0;
}

/*****************************************************************************
 * Demux: read chunks and send them to the synthetizer
 *****************************************************************************
 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
 *****************************************************************************/
static int Demux (demux_t *p_demux)
{
    stream_t *s = p_demux->s;
    demux_sys_t *p_sys = p_demux->p_sys;
    uint64_t     pulse = p_sys->pulse, next_pulse = UINT64_MAX;

    if (pulse == UINT64_MAX)
        return 0; /* all tracks are done */

527
    es_out_Control (p_demux->out, ES_OUT_SET_PCR, date_Get (&p_sys->pts));
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545

    for (unsigned i = 0; i < p_sys->trackc; i++)
    {
        mtrk_t *track = p_sys->trackv + i;

        while (track->next == pulse)
        {
            if (HandleMessage (p_demux, track)
             || ReadDeltaTime (s, track))
            {
                msg_Err (p_demux, "fatal parsing error");
                return VLC_EGENERIC;
            }
        }

        if (track->next < next_pulse)
            next_pulse = track->next;
    }
546

547
    mtime_t cur_tick = (date_Get (&p_sys->pts) + 9999) / 10000, last_tick;
548
    if (next_pulse != UINT64_MAX)
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
        last_tick = date_Increment (&p_sys->pts, next_pulse - pulse) / 10000;
    else
        last_tick = cur_tick + 1;

    /* MIDI Tick emulation (ping the decider every 10ms) */
    while (cur_tick < last_tick)
    {
        block_t *tick = block_New (p_demux, 1);
        if (tick == NULL)
            break;

        tick->p_buffer[0] = 0xF9;
        tick->i_dts = tick->i_pts = cur_tick++ * 10000;
        es_out_Send (p_demux->out, p_sys->es, tick);
    }

565
566
567
568
569
570
571
572
573
574
575
    p_sys->pulse = next_pulse;

    return 1;
}


/*****************************************************************************
 * Control:
 *****************************************************************************/
static int Control (demux_t *p_demux, int i_query, va_list args)
{
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
    demux_sys_t *p_sys = p_demux->p_sys;

    switch (i_query)
    {
        case DEMUX_GET_TIME:
        {
            *(va_arg (args, int64_t *)) = date_Get (&p_sys->pts);
            return 0;
        }
#if 0
        /* TODO: */
        case DEMUX_SET_TIME:
        case DEMUX_GET_POSITION:
        case DEMUX_SET_POSITION:
        case DEMUX_GET_LENGTH:
#endif
    }
    return VLC_EGENERIC;
594
}