format_ebml.c 32.2 KB
Newer Older
1 2
/* Icecast
 *
3
 * This program is distributed under the GNU General Public License,
4 5 6
 * version 2. A copy of this license is included with this source.
 * At your option, this specific source file can also be distributed
 * under the GNU GPL version 3.
7
 *
8
 * Copyright 2012,      David Richards, Mozilla Foundation,
9
 *                      and others (see AUTHORS for details).
10
 * Copyright 2014,      Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>.
11 12 13 14
 */

/* format_ebml.c
 *
giles's avatar
giles committed
15
 * format plugin for WebM/EBML
16 17 18 19 20 21 22
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

23
#include <stdint.h>
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "refbuf.h"
#include "source.h"
#include "client.h"

#include "stats.h"
#include "format.h"
#include "format_ebml.h"

#define CATMODULE "format-ebml"

#include "logging.h"

40 41 42
/* The size of the header buffer; should be large enough to contain
 * everything before the first Cluster in a reasonable stream
 */
43
#define EBML_HEADER_MAX_SIZE 131072
44 45 46 47 48 49 50

/* The size of the input/staging buffers; this much of a cluster
 * will be buffered before being returned. Should be large enough
 * that the first video block will be encountered before it is full,
 * to allow probing for the keyframe flag while we still have the
 * option to mark the cluster as a sync point.
 */
51 52
#define EBML_SLICE_SIZE 4096

53
/* A value that no EBML var-int is allowed to take. */
54
#define EBML_UNKNOWN ((uint_least64_t) -1)
55

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
/* The magic numbers for each element we are interested in.
 * Defined here:
 * http://www.matroska.org/technical/specs/index.html
 * http://www.webmproject.org/docs/container/
 *
 * Some of the higher-level elements have 4-byte identifiers;
 * The lower-level elements have 1-byte identifiers.
 */
#define UNCOMMON_MAGIC_LEN 4

#define SEGMENT_MAGIC "\x18\x53\x80\x67"
#define CLUSTER_MAGIC "\x1F\x43\xB6\x75"
#define TRACKS_MAGIC "\x16\x54\xAE\x6B"

#define COMMON_MAGIC_LEN 1

#define TRACK_ENTRY_MAGIC "\xAE"
#define TRACK_NUMBER_MAGIC "\xD7"
#define TRACK_TYPE_MAGIC "\x83"
#define SIMPLE_BLOCK_MAGIC "\xA3"

77 78 79 80
/* If support for Tags gets added, it may make sense
 * to convert this into a pair of flags signaling
 * "new headers" and "new tags"
 */
81
typedef enum ebml_read_mode {
82
    /* The header buffer has not been extracted yet */
83
    EBML_STATE_READING_HEADER = 0,
84
    /* The header buffer has been read, begin normal operation */
85 86
    EBML_STATE_READING_CLUSTERS
} ebml_read_mode;
87

Joseph Wallace's avatar
Joseph Wallace committed
88
typedef enum ebml_parsing_state {
89
    /* Examine EBML elements, output to header buffer */
Joseph Wallace's avatar
Joseph Wallace committed
90
    EBML_STATE_PARSING_HEADER = 0,
91 92

    /* Blindly copy a specified number of bytes to the header buffer */
Joseph Wallace's avatar
Joseph Wallace committed
93
    EBML_STATE_COPYING_TO_HEADER,
94 95

    /* Finalize header buffer and wait for previous cluster to flush (as necessary) */
Joseph Wallace's avatar
Joseph Wallace committed
96
    EBML_STATE_START_CLUSTER,
97 98

    /* Examine EBML elements, output to data buffer */
Joseph Wallace's avatar
Joseph Wallace committed
99
    EBML_STATE_PARSING_CLUSTERS,
100 101

    /* Blindly copy a specified number of bytes to the data buffer */
Joseph Wallace's avatar
Joseph Wallace committed
102 103 104
    EBML_STATE_COPYING_TO_DATA
} ebml_parsing_state;

105
typedef enum ebml_chunk_type {
106
    /* This chunk is the header buffer */
107
    EBML_CHUNK_HEADER = 0,
108 109

    /* This chunk starts a cluster that works as a sync point */
110
    EBML_CHUNK_CLUSTER_START,
111 112 113 114

    /* This chunk continues the previous cluster, or
     * else starts a non-sync-point cluster
     */
115 116 117
    EBML_CHUNK_CLUSTER_CONTINUE
} ebml_chunk_type;

118
typedef enum ebml_keyframe_status {
119
    /* Have not found a video track block yet */
120
    EBML_KEYFRAME_UNKNOWN = -1,
121 122

    /* Found the first video track block, it was not a keyframe */
123
    EBML_KEYFRAME_DOES_NOT_START_CLUSTER = 0,
124 125

    /* Found the first video track block, it was a keyframe */
126 127 128
    EBML_KEYFRAME_STARTS_CLUSTER = 1
} ebml_keyframe_status;

129
typedef struct ebml_st {
130

131
    ebml_read_mode output_state;
Joseph Wallace's avatar
Joseph Wallace committed
132
    ebml_parsing_state parse_state;
133
    uint_least64_t copy_len;
134

135
    ssize_t cluster_start;
136
    ebml_keyframe_status cluster_starts_with_keyframe;
137
    int flush_cluster;
138

139
    size_t position;
140
    unsigned char *buffer;
141

142
    size_t input_position;
143
    unsigned char *input_buffer;
144

145 146 147
    size_t header_size;
    size_t header_position;
    size_t header_read_position;
148
    unsigned char *header;
149

150 151
    uint_least64_t keyframe_track_number;
    uint_least64_t parsing_track_number;
152
    int parsing_track_is_video;
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
} ebml_t;

typedef struct ebml_source_state_st {

    ebml_t *ebml;
    refbuf_t *header;
    int file_headers_written;

} ebml_source_state_t;

typedef struct ebml_client_data_st {

    refbuf_t *header;
    size_t header_pos;

} ebml_client_data_t;
169

170 171 172 173 174 175
static void ebml_free_plugin(format_plugin_t *plugin);
static refbuf_t *ebml_get_buffer(source_t *source);
static int ebml_write_buf_to_client(client_t *client);
static void ebml_write_buf_to_file(source_t *source, refbuf_t *refbuf);
static int ebml_create_client_data(source_t *source, client_t *client);
static void ebml_free_client_data(client_t *client);
176 177 178

static ebml_t *ebml_create();
static void ebml_destroy(ebml_t *ebml);
179 180 181 182 183
static size_t ebml_read_space(ebml_t *ebml);
static size_t ebml_read(ebml_t *ebml, char *buffer, size_t len, ebml_chunk_type *chunk_type);
static unsigned char *ebml_get_write_buffer(ebml_t *ebml, size_t *bytes);
static ssize_t ebml_wrote(ebml_t *ebml, size_t len);
static ssize_t ebml_parse_tag(unsigned char      *buffer,
184
                              unsigned char      *buffer_end,
185
                              uint_least64_t *payload_length);
186 187
static ssize_t ebml_parse_var_int(unsigned char      *buffer,
                                  unsigned char      *buffer_end,
188
                                  uint_least64_t *out_value);
189 190 191 192
static ssize_t ebml_parse_sized_int(unsigned char      *buffer,
                                    unsigned char      *buffer_end,
                                    size_t             len,
                                    int                is_signed,
193
                                    uint_least64_t *out_value);
194
static inline void ebml_check_track(ebml_t *ebml);
195

196
int format_ebml_get_plugin(source_t *source)
197 198 199 200 201 202 203 204 205 206 207 208 209
{

    ebml_source_state_t *ebml_source_state = calloc(1, sizeof(ebml_source_state_t));
    format_plugin_t *plugin = calloc(1, sizeof(format_plugin_t));

    plugin->get_buffer = ebml_get_buffer;
    plugin->write_buf_to_client = ebml_write_buf_to_client;
    plugin->create_client_data = ebml_create_client_data;
    plugin->free_plugin = ebml_free_plugin;
    plugin->write_buf_to_file = ebml_write_buf_to_file;
    plugin->set_tag = NULL;
    plugin->apply_settings = NULL;

210
    plugin->contenttype = httpp_getvar(source->parser, "content-type");
211 212

    plugin->_state = ebml_source_state;
213
    vorbis_comment_init(&plugin->vc);
214 215 216
    source->format = plugin;

    ebml_source_state->ebml = ebml_create();
217

218 219 220
    return 0;
}

221
static void ebml_free_plugin(format_plugin_t *plugin)
222 223 224 225
{

    ebml_source_state_t *ebml_source_state = plugin->_state;

226
    refbuf_release(ebml_source_state->header);
227
    ebml_destroy(ebml_source_state->ebml);
228
    free(ebml_source_state);
229
    vorbis_comment_clear(&plugin->vc);
230
    free(plugin);
231 232
}

233 234
/* Write to a client from the header buffer.
 */
235
static int send_ebml_header(client_t *client)
236 237 238
{

    ebml_client_data_t *ebml_client_data = client->format_data;
239
    size_t len = EBML_SLICE_SIZE;
240 241
    int ret;

242
    if (ebml_client_data->header->len - ebml_client_data->header_pos < len)
243 244 245
    {
        len = ebml_client_data->header->len - ebml_client_data->header_pos;
    }
246
    ret = client_send_bytes (client,
247 248 249 250 251 252 253 254 255 256 257 258
                             ebml_client_data->header->data + ebml_client_data->header_pos,
                             len);

    if (ret > 0)
    {
        ebml_client_data->header_pos += ret;
    }

    return ret;

}

259 260
/* Initial write-to-client function.
 */
261 262 263 264 265 266 267 268 269 270 271
static int ebml_write_buf_to_client (client_t *client)
{

    ebml_client_data_t *ebml_client_data = client->format_data;

    if (ebml_client_data->header_pos != ebml_client_data->header->len)
    {
        return send_ebml_header (client);
    }
    else
    {
272 273
        /* Now that the header's sent, short-circuit to the generic
         * write-refbufs function. */
274 275 276 277 278 279
        client->write_to_client = format_generic_write_to_client;
        return client->write_to_client(client);
    }

}

280 281
/* Return a refbuf to add to the queue.
 */
282
static refbuf_t *ebml_get_buffer(source_t *source)
283 284 285 286
{

    ebml_source_state_t *ebml_source_state = source->format->_state;
    format_plugin_t *format = source->format;
287
    unsigned char *write_buffer = NULL;
288 289
    size_t read_bytes = 0;
    size_t write_bytes = 0;
290
    ebml_chunk_type chunk_type;
291
    refbuf_t *refbuf;
292
    size_t ret;
293 294 295

    while (1)
    {
296 297
        read_bytes = ebml_read_space(ebml_source_state->ebml);
        if (read_bytes > 0) {
298
            /* A chunk is available for reading */
299 300
            refbuf = refbuf_new(read_bytes);
            ebml_read(ebml_source_state->ebml, refbuf->data, read_bytes, &chunk_type);
301 302 303

            if (ebml_source_state->header == NULL)
            {
304
                /* Capture header before adding clusters to the queue */
305 306 307 308
                ebml_source_state->header = refbuf;
                continue;
            }

309
/*            ICECAST_LOG_DEBUG("EBML: generated refbuf, size %i : %hhi %hhi %hhi",
310
 *                            read_bytes, refbuf->data[0], refbuf->data[1], refbuf->data[2]);
311
 */
312

313
            if (chunk_type == EBML_CHUNK_CLUSTER_START)
314 315
            {
                refbuf->sync_point = 1;
316
/*                ICECAST_LOG_DEBUG("EBML: ^ was sync point"); */
317 318 319
            }
            return refbuf;

320
        } else if(read_bytes == 0) {
321
            /* Feed more bytes into the parser */
322 323 324
            write_buffer = ebml_get_write_buffer(ebml_source_state->ebml, &write_bytes);
            read_bytes = client_read_bytes (source->client, write_buffer, write_bytes);
            if (read_bytes <= 0) {
325 326 327
                ebml_wrote (ebml_source_state->ebml, 0);
                return NULL;
            }
328 329 330
            format->read_bytes += read_bytes;
            ret = ebml_wrote (ebml_source_state->ebml, read_bytes);
            if (ret != read_bytes) {
331
                ICECAST_LOG_ERROR("Problem processing stream");
332 333 334
                source->running = 0;
                return NULL;
            }
335 336 337 338
        } else {
            ICECAST_LOG_ERROR("Problem processing stream");
            source->running = 0;
            return NULL;
339 340 341 342
        }
    }
}

343 344
/* Initialize client state.
 */
345
static int ebml_create_client_data(source_t *source, client_t *client)
346
{
347
    ebml_client_data_t *ebml_client_data;
348 349
    ebml_source_state_t *ebml_source_state = source->format->_state;

350 351
    if (!ebml_source_state->header)
        return -1;
352

353 354 355
    ebml_client_data = calloc(1, sizeof(ebml_client_data_t));
    if (!ebml_client_data)
        return -1;
356

357 358 359 360 361
    ebml_client_data->header = ebml_source_state->header;
    refbuf_addref(ebml_client_data->header);
    client->format_data = ebml_client_data;
    client->free_client_data = ebml_free_client_data;
    return 0;
362 363 364 365 366 367 368 369 370 371 372 373 374 375
}

static void ebml_free_client_data (client_t *client)
{

    ebml_client_data_t *ebml_client_data = client->format_data;

    refbuf_release (ebml_client_data->header);
    free (client->format_data);
    client->format_data = NULL;
}

static void ebml_write_buf_to_file_fail (source_t *source)
{
376
    ICECAST_LOG_WARN("Write to dump file failed, disabling");
377 378 379 380 381 382 383 384 385 386 387 388
    fclose (source->dumpfile);
    source->dumpfile = NULL;
}

static void ebml_write_buf_to_file (source_t *source, refbuf_t *refbuf)
{

    ebml_source_state_t *ebml_source_state = source->format->_state;

    if (ebml_source_state->file_headers_written == 0)
    {
        if (fwrite (ebml_source_state->header->data, 1,
389
                    ebml_source_state->header->len,
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
                    source->dumpfile) != ebml_source_state->header->len)
            ebml_write_buf_to_file_fail(source);
        else
            ebml_source_state->file_headers_written = 1;
    }

    if (fwrite (refbuf->data, 1, refbuf->len, source->dumpfile) != refbuf->len)
    {
        ebml_write_buf_to_file_fail(source);
    }

}

/* internal ebml parsing */

static void ebml_destroy(ebml_t *ebml)
{

    free(ebml->header);
    free(ebml->input_buffer);
    free(ebml->buffer);
    free(ebml);

}

static ebml_t *ebml_create()
{

    ebml_t *ebml = calloc(1, sizeof(ebml_t));

420 421
    ebml->output_state = EBML_STATE_READING_HEADER;

422
    ebml->header = calloc(1, EBML_HEADER_MAX_SIZE);
Joseph Wallace's avatar
Joseph Wallace committed
423
    ebml->buffer = calloc(1, EBML_SLICE_SIZE);
424 425
    ebml->input_buffer = calloc(1, EBML_SLICE_SIZE);

426
    ebml->cluster_start = -1;
427

428 429 430
    ebml->keyframe_track_number = EBML_UNKNOWN;
    ebml->parsing_track_number = EBML_UNKNOWN;
    ebml->parsing_track_is_video = 0;
431 432 433 434 435

    return ebml;

}

436 437 438
/* Return the size of a buffer needed to store the next
 * chunk that ebml_read can yield.
 */
439
static size_t ebml_read_space(ebml_t *ebml)
440 441
{

442
    size_t read_space;
443

444 445
    switch (ebml->output_state) {
        case EBML_STATE_READING_HEADER:
446

447 448 449 450 451 452 453 454
            if (ebml->header_size != 0) {
                /* The header can be read */
                return ebml->header_size;
            } else {
                /* The header's not ready yet */
                return 0;
            }
            break;
455

456
        case EBML_STATE_READING_CLUSTERS:
457

458 459 460 461
            if (ebml->cluster_start > 0) {
                /* return up until just before a new cluster starts */
                read_space = ebml->cluster_start;
            } else {
462

463 464 465 466
                if (ebml->position == EBML_SLICE_SIZE) {
                    /* The current cluster fills the buffer,
                     * we have no choice but to start flushing it.
                     */
467

468 469
                    ebml->flush_cluster = 1;
                }
470

471 472 473 474 475 476 477 478 479
                if (ebml->flush_cluster) {
                    /* return what we have */
                    read_space = ebml->position;
                } else {
                    /* wait until we've read more, so the parser has
                     * time to gather metadata
                     */
                    read_space = 0;
                }
480
            }
481

482
            return read_space;
483
    }
484

485 486
    ICECAST_LOG_ERROR("EBML: Invalid parser read state");
    return 0;
487 488
}

489
/* Return a chunk of the EBML/MKV/WebM stream.
490
 * The header will be buffered until it can be returned as one chunk.
491
 * A cluster element's opening tag will always start a new chunk.
492 493 494
 * 
 * chunk_type will be set to indicate if the chunk is the header,
 * the start of a cluster, or continuing the current cluster.
495
 */
496
static size_t ebml_read(ebml_t *ebml, char *buffer, size_t len, ebml_chunk_type *chunk_type)
497 498
{

499 500
    size_t read_space;
    size_t to_read;
501

502
    *chunk_type = EBML_CHUNK_HEADER;
503

504
    if (len < 1) {
505
        return 0;
506
    }
507

508 509
    switch (ebml->output_state) {
        case EBML_STATE_READING_HEADER:
510

511 512 513 514
            if (ebml->header_size != 0)
            {
                /* Can read a chunk of the header */
                read_space = ebml->header_size - ebml->header_read_position;
515

516 517 518 519 520
                if (read_space >= len) {
                    to_read = len;
                } else {
                    to_read = read_space;
                }
521

522 523
                memcpy(buffer, ebml->header, to_read);
                ebml->header_read_position += to_read;
524

525
                *chunk_type = EBML_CHUNK_HEADER;
526

527 528 529 530 531 532 533
                if (ebml->header_read_position == ebml->header_size) {
                    ebml->output_state = EBML_STATE_READING_CLUSTERS;
                }
            } else {
                /* The header's not ready yet */
                return 0;
            }
534

535
            break;
536

537
        case EBML_STATE_READING_CLUSTERS:
538

539 540
            *chunk_type = EBML_CHUNK_CLUSTER_CONTINUE;
            read_space = ebml->position;
541

542 543
            if (ebml->cluster_start == 0) {
                /* new cluster is starting now */
544

545 546 547 548 549 550 551
                if (ebml->cluster_starts_with_keyframe != EBML_KEYFRAME_DOES_NOT_START_CLUSTER) {
                    /* If we positively identified the first video frame as a non-keyframe,
                     * don't use this cluster as a sync point. Since some files lack
                     * video tracks completely, or we may have failed to probe
                     * the first video frame, it's better to be pass through
                     * ambiguous cases to avoid blocking the stream forever.
                     */
552 553
                    *chunk_type = EBML_CHUNK_CLUSTER_START;
                }
554

555 556 557
                /* mark end of cluster */
                ebml->cluster_start = -1;
            } else if (ebml->cluster_start > 0) {
558 559 560
                /* return up until just before a new cluster starts */
                read_space = ebml->cluster_start;
            }
561

562 563 564
            if (read_space < 1) {
                return 0;
            }
565

566
            if (read_space >= len ) {
567
                to_read = len;
568
            } else {
569
                to_read = read_space;
570
            }
571

572
            memcpy(buffer, ebml->buffer, to_read);
573

574 575 576
            /* Shift unread data down to the start of the buffer */
            memmove(ebml->buffer, ebml->buffer + to_read, ebml->position - to_read);
            ebml->position -= to_read;
577

578 579
            if (ebml->cluster_start > 0) {
                ebml->cluster_start -= to_read;
580
            }
581

582
            break;
583 584 585 586 587 588
    }

    return to_read;

}

589 590 591 592 593
/* Get pointer & length of the buffer able to accept input.
 * 
 * Returns the start of the writable space;
 * Sets bytes to the amount of space available.
 */
594
static unsigned char *ebml_get_write_buffer(ebml_t *ebml, size_t *bytes)
595
{
596 597
    *bytes = EBML_SLICE_SIZE - ebml->input_position;
    return ebml->input_buffer + ebml->input_position;
598 599
}

600 601
/* Process data that has been written to the EBML parser's input buffer.
 */
602
static ssize_t ebml_wrote(ebml_t *ebml, size_t len)
603
{
Joseph Wallace's avatar
Joseph Wallace committed
604
    int processing = 1;
605 606
    size_t cursor = 0;
    size_t to_copy;
Joseph Wallace's avatar
Joseph Wallace committed
607
    unsigned char *end_of_buffer;
608

609 610 611
    ssize_t tag_length;
    ssize_t value_length;
    ssize_t track_number_length;
612 613 614
    uint_least64_t payload_length;
    uint_least64_t data_value;
    uint_least64_t track_number;
615
    unsigned char flags;
616
    ebml_parsing_state copy_state;
617

Joseph Wallace's avatar
Joseph Wallace committed
618 619
    ebml->input_position += len;
    end_of_buffer = ebml->input_buffer + ebml->input_position;
620

Joseph Wallace's avatar
Joseph Wallace committed
621
    while (processing) {
622

Joseph Wallace's avatar
Joseph Wallace committed
623
        /*ICECAST_LOG_DEBUG("Parse State: %i", ebml->parse_state);*/
624

Joseph Wallace's avatar
Joseph Wallace committed
625
        switch (ebml->parse_state) {
626

Joseph Wallace's avatar
Joseph Wallace committed
627 628
            case EBML_STATE_PARSING_HEADER:
            case EBML_STATE_PARSING_CLUSTERS:
629

Joseph Wallace's avatar
Joseph Wallace committed
630 631 632 633 634
                if (ebml->parse_state == EBML_STATE_PARSING_HEADER) {
                    copy_state = EBML_STATE_COPYING_TO_HEADER;
                } else {
                    copy_state = EBML_STATE_COPYING_TO_DATA;
                }
635

Joseph Wallace's avatar
Joseph Wallace committed
636 637
                tag_length = ebml_parse_tag(ebml->input_buffer + cursor,
                                            end_of_buffer, &payload_length);
638

Joseph Wallace's avatar
Joseph Wallace committed
639
                if (tag_length > 0) {
640

Joseph Wallace's avatar
Joseph Wallace committed
641 642 643 644
                    if (payload_length == EBML_UNKNOWN) {
                        /* Parse all children for tags we can't skip */
                        payload_length = 0;
                    }
645

646
                    /* Recognize tags of interest */
647 648
                    if (tag_length > UNCOMMON_MAGIC_LEN) {
                        if (!memcmp(ebml->input_buffer + cursor, CLUSTER_MAGIC, UNCOMMON_MAGIC_LEN)) {
649 650 651
                            /* Found a Cluster */
                            ebml->parse_state = EBML_STATE_START_CLUSTER;
                            break;
652
                        } else if (!memcmp(ebml->input_buffer + cursor, SEGMENT_MAGIC, UNCOMMON_MAGIC_LEN)) {
653 654
                            /* Parse all Segment children */
                            payload_length = 0;
655

656
                        } else if (!memcmp(ebml->input_buffer + cursor, TRACKS_MAGIC, UNCOMMON_MAGIC_LEN)) {
657 658
                            /* Parse all Tracks children */
                            payload_length = 0;
659

660
                        }
661

662
                    }
663

664 665
                    if (tag_length > COMMON_MAGIC_LEN) {
                        if (!memcmp(ebml->input_buffer + cursor, SIMPLE_BLOCK_MAGIC, COMMON_MAGIC_LEN)) {
666 667 668 669
                            /* Probe SimpleBlock header for the keyframe status */
                            if (ebml->cluster_starts_with_keyframe == EBML_KEYFRAME_UNKNOWN) {
                                track_number_length = ebml_parse_var_int(ebml->input_buffer + cursor + tag_length,
                                                                  end_of_buffer, &track_number);
670

671 672 673 674 675 676 677
                                if (track_number_length == 0) {
                                    /* Wait for more data */
                                    processing = 0;
                                } else if (track_number_length < 0) {
                                    return -1;
                                } else if (track_number == ebml->keyframe_track_number) {
                                    /* this block belongs to the video track */
678

679 680 681 682 683 684
                                    /* skip the 16-bit timecode for now, read the flags byte */
                                    if (cursor + tag_length + track_number_length + 2 >= ebml->input_position) {
                                        /* Wait for more data */
                                        processing = 0;
                                    } else {
                                        flags = ebml->input_buffer[cursor + tag_length + track_number_length + 2];
685

686 687 688 689 690 691 692 693 694
                                        if (flags & 0x80) {
                                            /* "keyframe" flag is set */
                                            ebml->cluster_starts_with_keyframe = EBML_KEYFRAME_STARTS_CLUSTER;
                                            /* ICECAST_LOG_DEBUG("Found keyframe in track %hhu", track_number); */
                                        } else {
                                            ebml->cluster_starts_with_keyframe = EBML_KEYFRAME_DOES_NOT_START_CLUSTER;
                                            /* ICECAST_LOG_DEBUG("Found non-keyframe in track %hhu", track_number); */
                                        }
                                    }
695

696
                                }
697

698
                            }
699

700
                        } else if (!memcmp(ebml->input_buffer + cursor, TRACK_ENTRY_MAGIC, COMMON_MAGIC_LEN)) {
701 702 703 704
                            /* Parse all TrackEntry children; reset the state */
                            payload_length = 0;
                            ebml->parsing_track_number = EBML_UNKNOWN;
                            ebml->parsing_track_is_video = 0;
705

706
                        } else if (!memcmp(ebml->input_buffer + cursor, TRACK_NUMBER_MAGIC, COMMON_MAGIC_LEN)) {
707 708 709
                            /* Probe TrackNumber for value */
                            value_length = ebml_parse_sized_int(ebml->input_buffer + cursor + tag_length,
                                                                end_of_buffer, payload_length, 0, &data_value);
710

711 712 713 714 715 716 717 718 719
                            if (value_length == 0) {
                                /* Wait for more data */
                                processing = 0;
                            } else if (value_length < 0) {
                                return -1;
                            } else {
                                ebml->parsing_track_number = data_value;
                                ebml_check_track(ebml);
                            }
720

721
                        } else if (!memcmp(ebml->input_buffer + cursor, TRACK_TYPE_MAGIC, COMMON_MAGIC_LEN)) {
722 723 724
                            /* Probe TrackType for a video flag */
                            value_length = ebml_parse_sized_int(ebml->input_buffer + cursor + tag_length,
                                                                end_of_buffer, payload_length, 0, &data_value);
725

726 727 728 729 730 731 732 733 734 735 736 737
                            if (value_length == 0) {
                                /* Wait for more data */
                                processing = 0;
                            } else if (value_length < 0) {
                                return -1;
                            } else {
                                if (data_value & 0x01) {
                                    /* This is a video track (0x01 flag = video) */
                                    ebml->parsing_track_is_video = 1;
                                    ebml_check_track(ebml);
                                }
                            }
738

739 740
                        }
                    }
741

742
                    if (processing) {
743
                        /* Moving to next element, copy current to buffer */
Joseph Wallace's avatar
Joseph Wallace committed
744 745 746 747 748 749 750 751 752 753 754 755 756 757
                        ebml->copy_len = tag_length + payload_length;
                        ebml->parse_state = copy_state;
                    }

                } else if (tag_length == 0) {
                    /* Wait for more data */
                    /* ICECAST_LOG_DEBUG("Wait"); */
                    processing = 0;
                } else if (tag_length < 0) {
                    /* Parse error */
                    /* ICECAST_LOG_DEBUG("Stop"); */
                    return -1;
                }
                break;
758

Joseph Wallace's avatar
Joseph Wallace committed
759 760 761 762 763 764 765
            case EBML_STATE_START_CLUSTER:
                /* found a cluster; wait to process it until
                 * any previous cluster tag has been flushed
                 * from the read buffer, so as to not lose the
                 * sync point.
                 */
                if (ebml->cluster_start >= 0) {
766 767
                    /* Allow the cluster in the read buffer to flush. */
                    ebml->flush_cluster = 1;
Joseph Wallace's avatar
Joseph Wallace committed
768 769
                    processing = 0;
                } else {
770

Joseph Wallace's avatar
Joseph Wallace committed
771 772
                    tag_length = ebml_parse_tag(ebml->input_buffer + cursor,
                                                end_of_buffer, &payload_length);
773

Joseph Wallace's avatar
Joseph Wallace committed
774 775
                    /* The header has been fully read by now, publish its size. */
                    ebml->header_size = ebml->header_position;
776

777
                    /* Mark this potential sync point, prepare probe */
Joseph Wallace's avatar
Joseph Wallace committed
778
                    ebml->cluster_start = ebml->position;
779
                    ebml->cluster_starts_with_keyframe = EBML_KEYFRAME_UNKNOWN;
780

781 782
                    /* Buffer data to give us time to probe for keyframes, etc. */
                    ebml->flush_cluster = 0;
783

Joseph Wallace's avatar
Joseph Wallace committed
784 785 786 787 788
                    /* Copy cluster tag to read buffer */
                    ebml->copy_len = tag_length;
                    ebml->parse_state = EBML_STATE_COPYING_TO_DATA;
                }
                break;
789

Joseph Wallace's avatar
Joseph Wallace committed
790 791 792 793 794 795
            case EBML_STATE_COPYING_TO_HEADER:
            case EBML_STATE_COPYING_TO_DATA:
                to_copy = ebml->input_position - cursor;
                if (to_copy > ebml->copy_len) {
                    to_copy = ebml->copy_len;
                }
796

Joseph Wallace's avatar
Joseph Wallace committed
797 798 799 800 801
                if (ebml->parse_state == EBML_STATE_COPYING_TO_HEADER) {
                    if ((ebml->header_position + to_copy) > EBML_HEADER_MAX_SIZE) {
                        ICECAST_LOG_ERROR("EBML Header too large, failing");
                        return -1;
                    }
802

Joseph Wallace's avatar
Joseph Wallace committed
803 804
                    memcpy(ebml->header + ebml->header_position, ebml->input_buffer + cursor, to_copy);
                    ebml->header_position += to_copy;
805

Joseph Wallace's avatar
Joseph Wallace committed
806 807 808 809
                } else if (ebml->parse_state == EBML_STATE_COPYING_TO_DATA) {
                    if ((ebml->position + to_copy) > EBML_SLICE_SIZE) {
                        to_copy = EBML_SLICE_SIZE - ebml->position;
                    }
810

Joseph Wallace's avatar
Joseph Wallace committed
811 812 813 814
                    memcpy(ebml->buffer + ebml->position, ebml->input_buffer + cursor, to_copy);
                    ebml->position += to_copy;
                }
                /* ICECAST_LOG_DEBUG("Copied %i of %hhu", to_copy, ebml->copy_len); */
815

Joseph Wallace's avatar
Joseph Wallace committed
816 817
                cursor += to_copy;
                ebml->copy_len -= to_copy;
818

Joseph Wallace's avatar
Joseph Wallace committed
819 820 821 822 823 824 825 826 827 828 829
                if (ebml->copy_len == 0) {
                    /* resume parsing */
                    if (ebml->parse_state == EBML_STATE_COPYING_TO_HEADER) {
                        ebml->parse_state = EBML_STATE_PARSING_HEADER;
                    } else {
                        ebml->parse_state = EBML_STATE_PARSING_CLUSTERS;
                    }
                } else {
                    /* wait for more data */
                    processing = 0;
                }
830

Joseph Wallace's avatar
Joseph Wallace committed
831
                break;
832

Joseph Wallace's avatar
Joseph Wallace committed
833 834
            default:
                processing = 0;
835

836
        }
837

838
    }
839

Joseph Wallace's avatar
Joseph Wallace committed
840 841 842
    /* Shift unprocessed data down to the start of the buffer */
    memmove(ebml->input_buffer, ebml->input_buffer + cursor, ebml->input_position - cursor);
    ebml->input_position -= cursor;
843

844
    return len;
845

846
}
847

848 849 850 851 852
static inline void ebml_check_track(ebml_t *ebml)
{
    if (ebml->keyframe_track_number == EBML_UNKNOWN
        && ebml->parsing_track_is_video
        && ebml->parsing_track_number != EBML_UNKNOWN) {
853

854 855 856 857 858
        ebml->keyframe_track_number = ebml->parsing_track_number;
        ICECAST_LOG_DEBUG("Identified track #%ffu as the video track", ebml->keyframe_track_number);
    }
}

859 860 861 862 863 864 865 866 867 868 869 870
/* Try to parse an EBML tag at the given location, returning the
 * length of the tag & the length of the associated payload.
 * 
 * Returns the length of the tag on success, and writes the payload
 * size to *payload_length.
 * 
 * Return 0 if it would be necessary to read past the
 * given end-of-buffer address to read a complete tag.
 * 
 * Returns -1 if the tag is corrupt.
 */

871 872
static ssize_t ebml_parse_tag(unsigned char *buffer,
                             unsigned char *buffer_end,
873
                             uint_least64_t *payload_length)
874
{
875 876
    size_t type_length;
    size_t size_length;
877
    uint_least64_t value;
878

879
    *payload_length = 0;
880

881 882
    /* read past the type tag */
    type_length = ebml_parse_var_int(buffer, buffer_end, &value);
883

884 885 886
    if (type_length <= 0) {
        return type_length;
    }
887

888 889
    /* read the length tag */
    size_length = ebml_parse_var_int(buffer + type_length, buffer_end, payload_length);
890

891 892 893
    if (size_length <= 0) {
        return size_length;
    }
894

895 896 897 898 899 900 901 902 903
    return type_length + size_length;
}

/* Try to parse an EBML variable-length integer.
 * Returns 0 if there's not enough space to read the number;
 * Returns -1 if the number is malformed.
 * Else, returns the length of the number in bytes and writes the
 * value to *out_value.
 */
904 905
static ssize_t ebml_parse_var_int(unsigned char *buffer,
                                 unsigned char *buffer_end,
906
                                 uint_least64_t *out_value)
907
{
908 909
    size_t size = 1;
    size_t i;
910
    unsigned char mask = 0x80;
911 912
    uint_least64_t value;
    uint_least64_t unknown_marker;
913

914 915 916
    if (buffer >= buffer_end) {
        return 0;
    }
917

918 919
    /* find the length marker bit in the first byte */
    value = buffer[0];
920

921 922 923 924 925 926 927 928 929
    while (mask) {
        if (value & mask) {
            value = value & ~mask;
            unknown_marker = mask - 1;
            break;
        }
        size++;
        mask = mask >> 1;
    }
930

931 932 933 934 935
    /* catch malformed number (no prefix) */
    if (mask == 0) {
        ICECAST_LOG_DEBUG("Corrupt var-int");
        return -1;
    }
936

937 938 939 940
    /* catch number bigger than parsing buffer */
    if (buffer + size - 1 >= buffer_end) {
        return 0;
    }
941

942 943 944 945 946
    /* read remaining bytes of (big-endian) number */
    for (i = 1; i < size; i++) {
        value = (value << 8) + buffer[i];
        unknown_marker = (unknown_marker << 8) + 0xFF;
    }
947

948
    /* catch special "unknown" length */
949

950 951 952 953 954 955 956 957 958
    if (value == unknown_marker) {
        *out_value = EBML_UNKNOWN;
    } else {
        *out_value = value;
    }

/*
    ICECAST_LOG_DEBUG("Varint: value %lli, unknown %llu, mask %hhu, size %i", value, unknown_marker, mask, size);
*/
959

960 961
    return size;
}
962

963
/* Parse a big-endian int that may be from 1-8 bytes long.
964 965 966 967
 * Returns 0 if there's not enough space to read the number;
 * Returns -1 if the number is mis-sized.
 * Else, returns the length of the number in bytes and writes the
 * value to *out_value.
968 969
 * If is_signed is true, then the int is assumed to be two's complement
 * signed, negative values will be correctly promoted, and the returned
970
 * unsigned number can be safely cast to a signed number on systems using
971
 * two's complement arithmatic.
972
 */
973
static ssize_t ebml_parse_sized_int(unsigned char       *buffer,
974 975 976
                                    unsigned char       *buffer_end,
                                    size_t              len,
                                    int                 is_signed,
977
                                    uint_least64_t  *out_value)
978
{
979
    uint_least64_t value;
980
    size_t i;
981

982 983 984 985
    if (len < 1 || len > 8) {
        ICECAST_LOG_DEBUG("Sized int of %i bytes", len);
        return -1;
    }
986

987 988 989
    if (buffer + len >= buffer_end) {
        return 0;
    }
990

991 992 993 994 995
    if (is_signed && ((signed char) buffer[0]) < 0) {
        value = -1;
    } else {
        value = 0;
    }
996

997 998 999
    for (i = 0; i < len; i++) {
        value = (value << 8) + ((unsigned char) buffer[i]);
    }
1000

1001
    *out_value = value;
1002

1003 1004
    return len;
}