ogg2.c 15.5 KB
Newer Older
1 2 3 4
/*
 * Ogg bitstream support
 * Luca Barbato <lu_zero@gentoo.org>
 * Based on tcvp implementation
5
 *
6 7 8 9 10 11 12 13 14 15 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
 */

/**
    Copyright (C) 2005  Michael Ahlberg, Måns Rullgård

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use, copy,
    modify, merge, publish, distribute, sublicense, and/or sell copies
    of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
**/


#include <stdio.h>
#include "ogg2.h"
#include "avformat.h"

#define MAX_PAGE_SIZE 65307
#define DECODER_BUFFER_SIZE MAX_PAGE_SIZE

static ogg_codec_t *ogg_codecs[] = {
    &vorbis_codec,
42
    &theora_codec,
Måns Rullgård's avatar
Måns Rullgård committed
43
    &flac_codec,
Måns Rullgård's avatar
Måns Rullgård committed
44 45 46
    &ogm_video_codec,
    &ogm_audio_codec,
    &ogm_old_codec,
47 48 49
    NULL
};

50
#if 0                           // CONFIG_MUXERS
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
static int
ogg_write_header (AVFormatContext * avfcontext)
{
}

static int
ogg_write_packet (AVFormatContext * avfcontext, AVPacket * pkt)
{
}


static int
ogg_write_trailer (AVFormatContext * avfcontext)
{
}


68
AVOutputFormat ogg_muxer = {
69
    "ogg",
Diego Biurrun's avatar
Diego Biurrun committed
70 71
    "Ogg format",
    "application/ogg",
72 73 74 75 76 77 78 79
    "ogg",
    sizeof (OggContext),
    CODEC_ID_VORBIS,
    0,
    ogg_write_header,
    ogg_write_packet,
    ogg_write_trailer,
};
80
#endif //CONFIG_MUXERS
81 82 83 84 85 86 87

//FIXME We could avoid some structure duplication
static int
ogg_save (AVFormatContext * s)
{
    ogg_t *ogg = s->priv_data;
    ogg_state_t *ost =
Måns Rullgård's avatar
Måns Rullgård committed
88
        av_malloc(sizeof (*ost) + (ogg->nstreams-1) * sizeof (*ogg->streams));
89 90 91 92
    int i;
    ost->pos = url_ftell (&s->pb);;
    ost->curidx = ogg->curidx;
    ost->next = ogg->state;
93
    ost->nstreams = ogg->nstreams;
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
    memcpy(ost->streams, ogg->streams, ogg->nstreams * sizeof(*ogg->streams));

    for (i = 0; i < ogg->nstreams; i++){
        ogg_stream_t *os = ogg->streams + i;
        os->buf = av_malloc (os->bufsize);
        memset (os->buf, 0, os->bufsize);
        memcpy (os->buf, ost->streams[i].buf, os->bufpos);
    }

    ogg->state = ost;

    return 0;
}

static int
ogg_restore (AVFormatContext * s, int discard)
{
    ogg_t *ogg = s->priv_data;
    ByteIOContext *bc = &s->pb;
    ogg_state_t *ost = ogg->state;
    int i;

    if (!ost)
        return 0;

    ogg->state = ost->next;

    if (!discard){
        for (i = 0; i < ogg->nstreams; i++)
            av_free (ogg->streams[i].buf);

        url_fseek (bc, ost->pos, SEEK_SET);
        ogg->curidx = ost->curidx;
127 128 129
        ogg->nstreams = ost->nstreams;
        memcpy(ogg->streams, ost->streams,
               ost->nstreams * sizeof(*ogg->streams));
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    }

    av_free (ost);

    return 0;
}

static int
ogg_reset (ogg_t * ogg)
{
    int i;

    for (i = 0; i < ogg->nstreams; i++){
        ogg_stream_t *os = ogg->streams + i;
        os->bufpos = 0;
        os->pstart = 0;
        os->psize = 0;
        os->granule = -1;
        os->lastgp = -1;
        os->nsegs = 0;
        os->segp = 0;
    }

    ogg->curidx = -1;

    return 0;
}

static ogg_codec_t *
Måns Rullgård's avatar
Måns Rullgård committed
159
ogg_find_codec (uint8_t * buf, int size)
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 191 192 193 194 195 196 197
{
    int i;

    for (i = 0; ogg_codecs[i]; i++)
        if (size >= ogg_codecs[i]->magicsize &&
            !memcmp (buf, ogg_codecs[i]->magic, ogg_codecs[i]->magicsize))
            return ogg_codecs[i];

    return NULL;
}

static int
ogg_find_stream (ogg_t * ogg, int serial)
{
    int i;

    for (i = 0; i < ogg->nstreams; i++)
        if (ogg->streams[i].serial == serial)
            return i;

    return -1;
}

static int
ogg_new_stream (AVFormatContext * s, uint32_t serial)
{

    ogg_t *ogg = s->priv_data;
    int idx = ogg->nstreams++;
    AVStream *st;
    ogg_stream_t *os;

    ogg->streams = av_realloc (ogg->streams,
                               ogg->nstreams * sizeof (*ogg->streams));
    memset (ogg->streams + idx, 0, sizeof (*ogg->streams));
    os = ogg->streams + idx;
    os->serial = serial;
    os->bufsize = DECODER_BUFFER_SIZE;
198
    os->buf = av_malloc(os->bufsize);
199 200 201 202 203 204 205 206 207 208 209
    os->header = -1;

    st = av_new_stream (s, idx);
    if (!st)
        return AVERROR_NOMEM;

    av_set_pts_info(st, 64, 1, 1000000);

    return idx;
}

210 211 212 213
static int
ogg_new_buf(ogg_t *ogg, int idx)
{
    ogg_stream_t *os = ogg->streams + idx;
214
    uint8_t *nb = av_malloc(os->bufsize);
215 216 217 218 219 220 221 222 223 224 225 226
    int size = os->bufpos - os->pstart;
    if(os->buf){
        memcpy(nb, os->buf + os->pstart, size);
        av_free(os->buf);
    }
    os->buf = nb;
    os->bufpos = size;
    os->pstart = 0;

    return 0;
}

227 228 229 230 231 232 233 234 235 236 237 238 239
static int
ogg_read_page (AVFormatContext * s, int *str)
{
    ByteIOContext *bc = &s->pb;
    ogg_t *ogg = s->priv_data;
    ogg_stream_t *os;
    int i = 0;
    int flags, nsegs;
    uint64_t gp;
    uint32_t serial;
    uint32_t seq;
    uint32_t crc;
    int size, idx;
240
    uint8_t sync[4];
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    int sp = 0;

    if (get_buffer (bc, sync, 4) < 4)
        return -1;

    do{
        int c;

        if (sync[sp & 3] == 'O' &&
            sync[(sp + 1) & 3] == 'g' &&
            sync[(sp + 2) & 3] == 'g' && sync[(sp + 3) & 3] == 'S')
            break;

        c = url_fgetc (bc);
        if (c < 0)
            return -1;
        sync[sp++ & 3] = c;
    }while (i++ < MAX_PAGE_SIZE);

    if (i >= MAX_PAGE_SIZE){
        av_log (s, AV_LOG_INFO, "ogg, can't find sync word\n");
        return -1;
    }

    if (url_fgetc (bc) != 0)      /* version */
        return -1;

    flags = url_fgetc (bc);
    gp = get_le64 (bc);
    serial = get_le32 (bc);
    seq = get_le32 (bc);
    crc = get_le32 (bc);
    nsegs = url_fgetc (bc);

    idx = ogg_find_stream (ogg, serial);
    if (idx < 0){
        idx = ogg_new_stream (s, serial);
        if (idx < 0)
            return -1;
    }

    os = ogg->streams + idx;

284
    if(os->psize > 0)
285 286
        ogg_new_buf(ogg, idx);

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    if (get_buffer (bc, os->segments, nsegs) < nsegs)
        return -1;

    os->nsegs = nsegs;
    os->segp = 0;

    size = 0;
    for (i = 0; i < nsegs; i++)
        size += os->segments[i];

    if (flags & OGG_FLAG_CONT){
        if (!os->psize){
            while (os->segp < os->nsegs){
                int seg = os->segments[os->segp++];
                os->pstart += seg;
                if (seg < 255)
                  break;
            }
        }
    }else{
      os->psize = 0;
    }

    if (os->bufsize - os->bufpos < size){
Måns Rullgård's avatar
Måns Rullgård committed
311
        uint8_t *nb = av_malloc (os->bufsize *= 2);
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        memcpy (nb, os->buf, os->bufpos);
        av_free (os->buf);
        os->buf = nb;
    }

    if (get_buffer (bc, os->buf + os->bufpos, size) < size)
        return -1;

    os->lastgp = os->granule;
    os->bufpos += size;
    os->granule = gp;
    os->flags = flags;

    if (str)
        *str = idx;

    return 0;
}

static int
332
ogg_packet (AVFormatContext * s, int *str, int *dstart, int *dsize)
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 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
{
    ogg_t *ogg = s->priv_data;
    int idx;
    ogg_stream_t *os;
    int complete = 0;
    int segp = 0, psize = 0;

#if 0
    av_log (s, AV_LOG_DEBUG, "ogg_packet: curidx=%i\n", ogg->curidx);
#endif

    do{
        idx = ogg->curidx;

        while (idx < 0){
            if (ogg_read_page (s, &idx) < 0)
                return -1;
        }

        os = ogg->streams + idx;

#if 0
        av_log (s, AV_LOG_DEBUG,
                "ogg_packet: idx=%d pstart=%d psize=%d segp=%d nsegs=%d\n",
                idx, os->pstart, os->psize, os->segp, os->nsegs);
#endif

        if (!os->codec){
            if (os->header < 0){
                os->codec = ogg_find_codec (os->buf, os->bufpos);
                if (!os->codec){
                    os->header = 0;
                    return 0;
                }
            }else{
                return 0;
            }
        }

        segp = os->segp;
        psize = os->psize;

        while (os->segp < os->nsegs){
            int ss = os->segments[os->segp++];
            os->psize += ss;
            if (ss < 255){
                complete = 1;
                break;
            }
        }

        if (!complete && os->segp == os->nsegs){
            ogg->curidx = -1;
        }
    }while (!complete);

#if 0
    av_log (s, AV_LOG_DEBUG,
            "ogg_packet: idx %i, frame size %i, start %i\n",
            idx, os->psize, os->pstart);
#endif

    ogg->curidx = idx;

    if (os->header < 0){
        int hdr = os->codec->header (s, idx);
        if (!hdr){
          os->header = os->seq;
          os->segp = segp;
          os->psize = psize;
          ogg->headers = 1;
        }else{
          os->pstart += os->psize;
          os->psize = 0;
        }
    }

    if (os->header > -1 && os->seq > os->header){
        if (os->codec && os->codec->packet)
            os->codec->packet (s, idx);
        if (str)
            *str = idx;
415 416 417 418 419 420
        if (dstart)
            *dstart = os->pstart;
        if (dsize)
            *dsize = os->psize;
        os->pstart += os->psize;
        os->psize = 0;
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    }

    os->seq++;
    if (os->segp == os->nsegs)
        ogg->curidx = -1;

    return 0;
}

static int
ogg_get_headers (AVFormatContext * s)
{
    ogg_t *ogg = s->priv_data;

    do{
436
        if (ogg_packet (s, NULL, NULL, NULL) < 0)
437 438 439 440 441 442 443 444 445 446 447 448 449
            return -1;
    }while (!ogg->headers);

#if 0
    av_log (s, AV_LOG_DEBUG, "found headers\n");
#endif

    return 0;
}

static uint64_t
ogg_gptopts (AVFormatContext * s, int i, uint64_t gp)
{
450 451
    ogg_t *ogg = s->priv_data;
    ogg_stream_t *os = ogg->streams + i;
452 453
    uint64_t pts = AV_NOPTS_VALUE;

454
    if(os->codec->gptopts){
455
        pts = os->codec->gptopts(s, i, gp);
456
    } else {
457
        pts = gp;
458 459 460 461 462 463 464 465 466 467 468
    }

    return pts;
}


static int
ogg_get_length (AVFormatContext * s)
{
    ogg_t *ogg = s->priv_data;
    int idx = -1, i;
Måns Rullgård's avatar
Måns Rullgård committed
469
    offset_t size, end;
470 471 472

    if(s->pb.is_streamed)
        return 0;
473 474 475 476 477

// already set
    if (s->duration != AV_NOPTS_VALUE)
        return 0;

Måns Rullgård's avatar
Måns Rullgård committed
478 479 480 481 482
    size = url_fsize(&s->pb);
    if(size < 0)
        return 0;
    end = size > MAX_PAGE_SIZE? size - MAX_PAGE_SIZE: size;

483
    ogg_save (s);
Måns Rullgård's avatar
Måns Rullgård committed
484
    url_fseek (&s->pb, end, SEEK_SET);
485 486

    while (!ogg_read_page (s, &i)){
487 488
        if (ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0 &&
            ogg->streams[i].codec)
489 490 491 492 493 494 495 496
            idx = i;
    }

    if (idx != -1){
        s->streams[idx]->duration =
            ogg_gptopts (s, idx, ogg->streams[idx].granule);
    }

Måns Rullgård's avatar
Måns Rullgård committed
497
    ogg->size = size;
498
    ogg_restore (s, 0);
499
    ogg_save (s);
500
    while (!ogg_read_page (s, &i)) {
501 502 503 504 505 506 507 508
        if (i == idx && ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0)
            break;
    }
    if (i == idx) {
        s->streams[idx]->start_time = ogg_gptopts (s, idx, ogg->streams[idx].granule);
        s->streams[idx]->duration -= s->streams[idx]->start_time;
    }
    ogg_restore (s, 0);
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

    return 0;
}


static int
ogg_read_header (AVFormatContext * s, AVFormatParameters * ap)
{
    ogg_t *ogg = s->priv_data;
    ogg->curidx = -1;
    //linear headers seek from start
    if (ogg_get_headers (s) < 0){
      return -1;
    }

    //linear granulepos seek from end
    ogg_get_length (s);

    //fill the extradata in the per codec callbacks
    return 0;
}


static int
ogg_read_packet (AVFormatContext * s, AVPacket * pkt)
{
    ogg_t *ogg;
    ogg_stream_t *os;
    int idx = -1;
538
    int pstart, psize;
539

540
    //Get an ogg packet
541
    do{
542
        if (ogg_packet (s, &idx, &pstart, &psize) < 0)
543 544 545 546 547 548 549
            return AVERROR_IO;
    }while (idx < 0 || !s->streams[idx]);

    ogg = s->priv_data;
    os = ogg->streams + idx;

    //Alloc a pkt
550
    if (av_new_packet (pkt, psize) < 0)
551 552
        return AVERROR_IO;
    pkt->stream_index = idx;
553
    memcpy (pkt->data, os->buf + pstart, psize);
554 555 556 557
    if (os->lastgp != -1LL){
        pkt->pts = ogg_gptopts (s, idx, os->lastgp);
        os->lastgp = -1;
    }
558 559

    return psize;
560 561 562 563 564 565 566 567 568 569 570
}


static int
ogg_read_close (AVFormatContext * s)
{
    ogg_t *ogg = s->priv_data;
    int i;

    for (i = 0; i < ogg->nstreams; i++){
        av_free (ogg->streams[i].buf);
571
        av_free (ogg->streams[i].private);
572 573 574 575 576 577 578 579 580 581
    }
    av_free (ogg->streams);
    return 0;
}


static int
ogg_read_seek (AVFormatContext * s, int stream_index, int64_t target_ts,
               int flags)
{
Måns Rullgård's avatar
Måns Rullgård committed
582
    AVStream *st = s->streams[stream_index];
583 584 585
    ogg_t *ogg = s->priv_data;
    ByteIOContext *bc = &s->pb;
    uint64_t min = 0, max = ogg->size;
586
    uint64_t tmin = st->start_time, tmax = st->start_time + st->duration;
587 588 589 590
    int64_t pts = AV_NOPTS_VALUE;

    ogg_save (s);

591 592 593
    if ((uint64_t)target_ts < tmin || target_ts < 0)
        target_ts = tmin;
    while (min <= max && tmin < tmax){
Måns Rullgård's avatar
Måns Rullgård committed
594
        uint64_t p = min + (max - min) * (target_ts - tmin) / (tmax - tmin);
595 596 597 598 599
        int i = -1;

        url_fseek (bc, p, SEEK_SET);

        while (!ogg_read_page (s, &i)){
Måns Rullgård's avatar
Måns Rullgård committed
600 601
            if (i == stream_index && ogg->streams[i].granule != 0 &&
                ogg->streams[i].granule != -1)
602 603 604 605 606 607 608 609 610
                break;
        }

        if (i == -1)
            break;

        pts = ogg_gptopts (s, i, ogg->streams[i].granule);
        p = url_ftell (bc);

611
        if (FFABS (pts - target_ts) * st->time_base.num < st->time_base.den)
612 613 614
            break;

        if (pts > target_ts){
615 616 617 618 619 620 621 622
            if (max == p && tmax == pts) {
                // probably our tmin is wrong, causing us to always end up too late in the file
                tmin = (target_ts + tmin + 1) / 2;
                if (tmin == target_ts) {
                    url_fseek(bc, min, SEEK_SET);
                    break;
                }
            }
623 624 625
            max = p;
            tmax = pts;
        }else{
626 627 628 629 630 631 632 633
            if (min == p && tmin == pts) {
                // probably our tmax is wrong, causing us to always end up too early in the file
                tmax = (target_ts + tmax) / 2;
                if (tmax == target_ts) {
                    url_fseek(bc, max, SEEK_SET);
                    break;
                }
            }
634 635 636 637 638
            min = p;
            tmin = pts;
        }
    }

639
    if (FFABS (pts - target_ts) * st->time_base.num < st->time_base.den){
640 641 642 643 644 645 646
        ogg_restore (s, 1);
        ogg_reset (ogg);
    }else{
        ogg_restore (s, 0);
        pts = AV_NOPTS_VALUE;
    }

647 648
    av_update_cur_dts(s, st, pts);
    return 0;
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

#if 0
    //later...
    int64_t pos;
    if (av_seek_frame_binary (s, stream_index, target_ts, flags) < 0)
        return -1;
    pos = url_ftell (&s->pb);
    ogg_read_timestamp (s, stream_index, &pos, pos - 1);
#endif

}

#if 0
static int64_t
ogg_read_timestamp (AVFormatContext * s, int stream_index, int64_t * pos_arg,
                    int64_t pos_limit)
{
    ogg_t *ogg = s->priv_data;
    ByteIOContext *bc = &s->pb;
    int64_t pos, pts;

    if (*pos_arg < 0)
        return AV_NOPTS_VALUE;

    pos = *pos_arg;
}
#endif

677 678 679 680 681 682 683 684 685 686
static int ogg_probe(AVProbeData *p)
{
    if (p->buf[0] == 'O' && p->buf[1] == 'g' &&
        p->buf[2] == 'g' && p->buf[3] == 'S' &&
        p->buf[4] == 0x0 && p->buf[5] <= 0x7 )
        return AVPROBE_SCORE_MAX;
    else
        return 0;
}

687
AVInputFormat ogg_demuxer = {
688 689 690
    "ogg",
    "Ogg",
    sizeof (ogg_t),
691
    ogg_probe,
692 693 694 695
    ogg_read_header,
    ogg_read_packet,
    ogg_read_close,
    ogg_read_seek,
696
// ogg_read_timestamp,
697 698
    .extensions = "ogg",
};