format_ebml.c 17.8 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 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
 *
 */

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

#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"

#define EBML_HEADER_MAX_SIZE 131072
#define EBML_SLICE_SIZE 4096

42 43 44
/* A value that no EBML var-int is allowed to take. */
#define EBML_UNKNOWN ((unsigned long long) -1)

45 46 47 48
typedef enum ebml_read_mode {
    EBML_STATE_READING_HEADER = 0,
    EBML_STATE_READING_CLUSTERS
} ebml_read_mode;
49

50 51 52 53 54 55
typedef enum ebml_chunk_type {
    EBML_CHUNK_HEADER = 0,
    EBML_CHUNK_CLUSTER_START,
    EBML_CHUNK_CLUSTER_CONTINUE
} ebml_chunk_type;

56 57 58 59 60 61 62 63 64 65 66
typedef struct ebml_client_data_st ebml_client_data_t;

struct ebml_client_data_st {

    refbuf_t *header;
    int header_pos;

};

struct ebml_st {

67 68
    ebml_read_mode output_state;
    
69 70
    char *cluster_id;
    int cluster_start;
71

72 73
    int position;
    unsigned char *buffer;
74 75 76

    int input_position;
    unsigned char *input_buffer;
77
    
78 79 80 81 82 83 84
    int header_size;
    int header_position;
    int header_read_position;
    unsigned char *header;

};

85 86 87 88 89 90
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);
91 92 93 94

static ebml_t *ebml_create();
static void ebml_destroy(ebml_t *ebml);
static int ebml_read_space(ebml_t *ebml);
95
static int ebml_read(ebml_t *ebml, char *buffer, int len, ebml_chunk_type *chunk_type);
96
static unsigned char *ebml_get_write_buffer(ebml_t *ebml, int *bytes);
97
static int ebml_wrote(ebml_t *ebml, int len);
98 99 100 101 102 103
static int ebml_parse_tag(unsigned char      *buffer,
                          unsigned char      *buffer_end,
                          unsigned long long *payload_length);
static int ebml_parse_var_int(unsigned char      *buffer,
                              unsigned char      *buffer_end,
                              unsigned long long *out_value);
104

105
int format_ebml_get_plugin(source_t *source)
106 107 108 109 110 111 112 113 114 115 116 117 118
{

    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;

119
    plugin->contenttype = httpp_getvar(source->parser, "content-type");
120 121

    plugin->_state = ebml_source_state;
122
    vorbis_comment_init(&plugin->vc);
123 124 125
    source->format = plugin;

    ebml_source_state->ebml = ebml_create();
126
    
127 128 129
    return 0;
}

130
static void ebml_free_plugin(format_plugin_t *plugin)
131 132 133 134
{

    ebml_source_state_t *ebml_source_state = plugin->_state;

135
    refbuf_release(ebml_source_state->header);
136
    ebml_destroy(ebml_source_state->ebml);
137
    free(ebml_source_state);
138
    vorbis_comment_clear(&plugin->vc);
139
    free(plugin);
140 141
}

142 143
/* Write to a client from the header buffer.
 */
144
static int send_ebml_header(client_t *client)
145 146 147 148 149 150
{

    ebml_client_data_t *ebml_client_data = client->format_data;
    int len = EBML_SLICE_SIZE;
    int ret;

151
    if (ebml_client_data->header->len - ebml_client_data->header_pos < len)
152 153 154
    {
        len = ebml_client_data->header->len - ebml_client_data->header_pos;
    }
155
    ret = client_send_bytes (client,
156 157 158 159 160 161 162 163 164 165 166 167
                             ebml_client_data->header->data + ebml_client_data->header_pos,
                             len);

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

    return ret;

}

168 169
/* Initial write-to-client function.
 */
170 171 172 173 174 175 176 177 178 179 180
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
    {
181 182
        /* Now that the header's sent, short-circuit to the generic
         * write-refbufs function. */
183 184 185 186 187 188
        client->write_to_client = format_generic_write_to_client;
        return client->write_to_client(client);
    }

}

189 190
/* Return a refbuf to add to the queue.
 */
191
static refbuf_t *ebml_get_buffer(source_t *source)
192 193 194 195
{

    ebml_source_state_t *ebml_source_state = source->format->_state;
    format_plugin_t *format = source->format;
196 197 198
    unsigned char *write_buffer = NULL;
    int read_bytes = 0;
    int write_bytes = 0;
199
    ebml_chunk_type chunk_type;
200 201 202 203 204
    refbuf_t *refbuf;
    int ret;

    while (1)
    {
205 206
        read_bytes = ebml_read_space(ebml_source_state->ebml);
        if (read_bytes > 0) {
207
            /* A chunk is available for reading */
208 209
            refbuf = refbuf_new(read_bytes);
            ebml_read(ebml_source_state->ebml, refbuf->data, read_bytes, &chunk_type);
210 211 212

            if (ebml_source_state->header == NULL)
            {
213
                /* Capture header before adding clusters to the queue */
214 215 216 217
                ebml_source_state->header = refbuf;
                continue;
            }

218
/*            ICECAST_LOG_DEBUG("EBML: generated refbuf, size %i : %hhi %hhi %hhi",
219
 *                            read_bytes, refbuf->data[0], refbuf->data[1], refbuf->data[2]);
220 221 222
 */
                              
            if (chunk_type == EBML_CHUNK_CLUSTER_START)
223 224
            {
                refbuf->sync_point = 1;
225
/*                ICECAST_LOG_DEBUG("EBML: ^ was sync point"); */
226 227 228
            }
            return refbuf;

229
        } else if(read_bytes == 0) {
230
            /* Feed more bytes into the parser */
231 232 233
            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) {
234 235 236
                ebml_wrote (ebml_source_state->ebml, 0);
                return NULL;
            }
237 238 239
            format->read_bytes += read_bytes;
            ret = ebml_wrote (ebml_source_state->ebml, read_bytes);
            if (ret != read_bytes) {
240
                ICECAST_LOG_ERROR("Problem processing stream");
241 242 243
                source->running = 0;
                return NULL;
            }
244 245 246 247
        } else {
            ICECAST_LOG_ERROR("Problem processing stream");
            source->running = 0;
            return NULL;
248 249 250 251
        }
    }
}

252 253
/* Initialize client state.
 */
254
static int ebml_create_client_data(source_t *source, client_t *client)
255
{
256
    ebml_client_data_t *ebml_client_data;
257 258
    ebml_source_state_t *ebml_source_state = source->format->_state;

259 260
    if (!ebml_source_state->header)
        return -1;
261

262 263 264
    ebml_client_data = calloc(1, sizeof(ebml_client_data_t));
    if (!ebml_client_data)
        return -1;
265

266 267 268 269 270
    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;
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
}


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)
{
287
    ICECAST_LOG_WARN("Write to dump file failed, disabling");
288 289 290 291 292 293 294 295 296 297 298 299 300
    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,
301
                    ebml_source_state->header->len,
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
                    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));

333 334
    ebml->output_state = EBML_STATE_READING_HEADER;

335 336 337 338 339 340
    ebml->header = calloc(1, EBML_HEADER_MAX_SIZE);
    ebml->buffer = calloc(1, EBML_SLICE_SIZE * 4);
    ebml->input_buffer = calloc(1, EBML_SLICE_SIZE);

    ebml->cluster_id = "\x1F\x43\xB6\x75";

341
    ebml->cluster_start = -1;
342 343 344 345 346

    return ebml;

}

347 348 349
/* Return the size of a buffer needed to store the next
 * chunk that ebml_read can yield.
 */
350 351 352 353 354
static int ebml_read_space(ebml_t *ebml)
{

    int read_space;

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    switch (ebml->output_state) {
        case EBML_STATE_READING_HEADER:
        
            if (ebml->header_size != 0) {
                /* The header can be read */
                return ebml->header_size;
            } else {
                /* The header's not ready yet */
                return 0;
            }
            break;
            
        case EBML_STATE_READING_CLUSTERS:
            
            if (ebml->cluster_start > 0) {
                /* return up until just before a new cluster starts */
                read_space = ebml->cluster_start;
            } else {
373 374
                /* return what we have */
                read_space = ebml->position;
375
            }
376

377
            return read_space;
378
    }
379 380 381
    
    ICECAST_LOG_ERROR("EBML: Invalid parser read state");
    return 0;
382 383
}

384
/* Return a chunk of the EBML/MKV/WebM stream.
385
 * The header will be buffered until it can be returned as one chunk.
386
 * A cluster element's opening tag will always start a new chunk.
387 388 389
 * 
 * chunk_type will be set to indicate if the chunk is the header,
 * the start of a cluster, or continuing the current cluster.
390
 */
391
static int ebml_read(ebml_t *ebml, char *buffer, int len, ebml_chunk_type *chunk_type)
392 393 394 395
{

    int read_space;
    int to_read;
396 397
    
    *chunk_type = EBML_CHUNK_HEADER;
398

399
    if (len < 1) {
400
        return 0;
401
    }
402

403 404 405 406 407 408 409
    switch (ebml->output_state) {
        case EBML_STATE_READING_HEADER:
        
            if (ebml->header_size != 0)
            {
                /* Can read a chunk of the header */
                read_space = ebml->header_size - ebml->header_read_position;
410

411 412 413 414 415
                if (read_space >= len) {
                    to_read = len;
                } else {
                    to_read = read_space;
                }
416

417 418
                memcpy(buffer, ebml->header, to_read);
                ebml->header_read_position += to_read;
419 420 421
                
                *chunk_type = EBML_CHUNK_HEADER;
                
422 423 424 425 426 427 428 429 430 431 432
                if (ebml->header_read_position == ebml->header_size) {
                    ebml->output_state = EBML_STATE_READING_CLUSTERS;
                }
            } else {
                /* The header's not ready yet */
                return 0;
            }
        
            break;
            
        case EBML_STATE_READING_CLUSTERS:
433
        
434 435 436 437 438 439 440 441 442 443
            *chunk_type = EBML_CHUNK_CLUSTER_CONTINUE;
            read_space = ebml->position;
            
            if (ebml->cluster_start == 0) {
                /* new cluster is starting now */
                *chunk_type = EBML_CHUNK_CLUSTER_START;
                
                /* mark end of cluster */
                ebml->cluster_start = -1;
            } else if (ebml->cluster_start > 0) {
444 445 446
                /* return up until just before a new cluster starts */
                read_space = ebml->cluster_start;
            }
447

448 449 450
            if (read_space < 1) {
                return 0;
            }
451

452
            if (read_space >= len ) {
453
                to_read = len;
454
            } else {
455
                to_read = read_space;
456
            }
457

458 459 460 461 462
            memcpy(buffer, ebml->buffer, to_read);
            
            /* 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;
463

464 465
            if (ebml->cluster_start > 0) {
                ebml->cluster_start -= to_read;
466
            }
467 468
        
            break;
469 470 471 472 473 474
    }

    return to_read;

}

475 476 477 478 479 480
/* 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.
 */
static unsigned char *ebml_get_write_buffer(ebml_t *ebml, int *bytes)
481
{
482 483
    *bytes = EBML_SLICE_SIZE - ebml->input_position;
    return ebml->input_buffer + ebml->input_position;
484 485
}

486 487
/* Process data that has been written to the EBML parser's input buffer.
 */
488 489 490 491 492
static int ebml_wrote(ebml_t *ebml, int len)
{

    int b;

493 494 495
    if (ebml->header_size == 0) {
        /* Still reading header */
        if ((ebml->header_position + len) > EBML_HEADER_MAX_SIZE) {
496
            ICECAST_LOG_ERROR("EBML Header too large, failing");
497 498
            return -1;
        }
499

500 501
/*
        ICECAST_LOG_DEBUG("EBML: Adding to header, ofset is %d size is %d adding %d",
502 503
                          ebml->header_size, ebml->header_position, len);
*/
504

505 506
        memcpy(ebml->header + ebml->header_position, ebml->input_buffer, len);
        ebml->header_position += len;
507 508
    } else {
        /* Header's already been determined, read into data buffer */
509 510
        memcpy(ebml->buffer + ebml->position, ebml->input_buffer, len);
    }
511

512
    for (b = 0; b <= len - 4; b++)
513
    {
514 515 516 517 518 519
        /* Scan for cluster start marker.
         * False positives are possible, but unlikely, and only
         * permanently corrupt a stream if they occur while scanning
         * the initial header. Else, a client can reconnect in a few
         * seconds and get a real sync point.
         */
520 521
        if (!memcmp(ebml->input_buffer + b, ebml->cluster_id, 4))
        {
522 523 524
/*
            ICECAST_LOG_DEBUG("EBML: found cluster");
*/
525

526 527
            if (ebml->header_size == 0)
            {
528
                /* We were looking for the header end; now we've found it */
529
                ebml->header_size = ebml->header_position - len + b;
530 531
                
                /* Shift data after the header into the data buffer */
532 533
                memcpy(ebml->buffer, ebml->input_buffer + b, len - b);
                ebml->position = len - b;
534 535
                
                /* Mark the start of the data as the first sync point */
536
                ebml->cluster_start = 0;
537
                return len;
538 539
            } else {
                /* We've located a sync point in the data stream */
540 541 542 543
                ebml->cluster_start = ebml->position + b;
            }
        }
    }
544

545 546 547 548 549
    ebml->position += len;

    return len;

}
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653

/* 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.
 */

static int ebml_parse_tag(unsigned char *buffer,
                          unsigned char *buffer_end,
                          unsigned long long *payload_length)
{
    int type_length;
    int size_length;
    unsigned long long value;
    
    *payload_length = 0;
    
    /* read past the type tag */
    type_length = ebml_parse_var_int(buffer, buffer_end, &value);
    
    if (type_length <= 0) {
        return type_length;
    }
    
    /* read the length tag */
    size_length = ebml_parse_var_int(buffer + type_length, buffer_end, payload_length);
    
    if (size_length <= 0) {
        return size_length;
    }
    
    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.
 */
static int ebml_parse_var_int(unsigned char *buffer,
                              unsigned char *buffer_end,
                              unsigned long long *out_value)
{
    int size = 1;
    int i;
    unsigned char mask = 0x80;
    unsigned long long value;
    unsigned long long unknown_marker;
    
    if (buffer >= buffer_end) {
        return 0;
    }
    
    /* find the length marker bit in the first byte */
    value = buffer[0];
    
    while (mask) {
        if (value & mask) {
            value = value & ~mask;
            unknown_marker = mask - 1;
            break;
        }
        size++;
        mask = mask >> 1;
    }
    
    /* catch malformed number (no prefix) */
    if (mask == 0) {
        ICECAST_LOG_DEBUG("Corrupt var-int");
        return -1;
    }
    
    /* catch number bigger than parsing buffer */
    if (buffer + size - 1 >= buffer_end) {
        return 0;
    }
    
    /* read remaining bytes of (big-endian) number */
    for (i = 1; i < size; i++) {
        value = (value << 8) + buffer[i];
        unknown_marker = (unknown_marker << 8) + 0xFF;
    }
    
    /* catch special "unknown" length */
    
    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);
*/
    
    return size;
}