utils.c 104 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
Diego Biurrun's avatar
Diego Biurrun committed
2
 * various utility functions for use within FFmpeg
Fabrice Bellard's avatar
Fabrice Bellard committed
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
Fabrice Bellard's avatar
Fabrice Bellard committed
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Fabrice Bellard's avatar
Fabrice Bellard committed
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
16
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 */
Fabrice Bellard's avatar
Fabrice Bellard committed
21
#include "avformat.h"
22
#include "internal.h"
23
#include "libavcodec/opt.h"
24
#include "metadata.h"
25
#include "libavutil/avstring.h"
26
#include "riff.h"
27 28
#include <sys/time.h>
#include <time.h>
29
#include <strings.h>
30

31 32 33
#undef NDEBUG
#include <assert.h>

34 35
/**
 * @file libavformat/utils.c
Diego Biurrun's avatar
Diego Biurrun committed
36
 * various utility functions for use within FFmpeg
37 38
 */

39 40 41 42 43
unsigned avformat_version(void)
{
    return LIBAVFORMAT_VERSION_INT;
}

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
/* fraction handling */

/**
 * f = val + (num / den) + 0.5.
 *
 * 'num' is normalized so that it is such as 0 <= num < den.
 *
 * @param f fractional number
 * @param val integer value
 * @param num must be >= 0
 * @param den must be >= 1
 */
static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
{
    num += (den >> 1);
    if (num >= den) {
        val += num / den;
        num = num % den;
    }
    f->val = val;
    f->num = num;
    f->den = den;
}

/**
 * Fractional addition to f: f = f + (incr / f->den).
 *
 * @param f fractional number
 * @param incr increment, can be positive or negative
 */
static void av_frac_add(AVFrac *f, int64_t incr)
{
    int64_t num, den;

    num = f->num + incr;
    den = f->den;
    if (num < 0) {
        f->val += num / den;
        num = num % den;
        if (num < 0) {
            num += den;
            f->val--;
        }
    } else if (num >= den) {
        f->val += num / den;
        num = num % den;
    }
    f->num = num;
}
93

Diego Biurrun's avatar
Diego Biurrun committed
94
/** head of registered input format linked list */
95
AVInputFormat *first_iformat = NULL;
Diego Biurrun's avatar
Diego Biurrun committed
96
/** head of registered output format linked list */
97
AVOutputFormat *first_oformat = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
98

99 100 101 102 103 104 105 106 107 108 109 110
AVInputFormat  *av_iformat_next(AVInputFormat  *f)
{
    if(f) return f->next;
    else  return first_iformat;
}

AVOutputFormat *av_oformat_next(AVOutputFormat *f)
{
    if(f) return f->next;
    else  return first_oformat;
}

111
void av_register_input_format(AVInputFormat *format)
Fabrice Bellard's avatar
Fabrice Bellard committed
112
{
113 114 115 116 117 118 119 120 121 122 123
    AVInputFormat **p;
    p = &first_iformat;
    while (*p != NULL) p = &(*p)->next;
    *p = format;
    format->next = NULL;
}

void av_register_output_format(AVOutputFormat *format)
{
    AVOutputFormat **p;
    p = &first_oformat;
Fabrice Bellard's avatar
Fabrice Bellard committed
124 125 126 127 128
    while (*p != NULL) p = &(*p)->next;
    *p = format;
    format->next = NULL;
}

129
int match_ext(const char *filename, const char *extensions)
Fabrice Bellard's avatar
Fabrice Bellard committed
130 131 132 133
{
    const char *ext, *p;
    char ext1[32], *q;

Michael Niedermayer's avatar
Michael Niedermayer committed
134 135
    if(!filename)
        return 0;
136

Fabrice Bellard's avatar
Fabrice Bellard committed
137 138 139 140 141 142
    ext = strrchr(filename, '.');
    if (ext) {
        ext++;
        p = extensions;
        for(;;) {
            q = ext1;
143
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
Fabrice Bellard's avatar
Fabrice Bellard committed
144 145
                *q++ = *p++;
            *q = '\0';
146
            if (!strcasecmp(ext1, ext))
Fabrice Bellard's avatar
Fabrice Bellard committed
147
                return 1;
148
            if (*p == '\0')
Fabrice Bellard's avatar
Fabrice Bellard committed
149 150 151 152 153 154 155
                break;
            p++;
        }
    }
    return 0;
}

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
static int match_format(const char *name, const char *names)
{
    const char *p;
    int len, namelen;

    if (!name || !names)
        return 0;

    namelen = strlen(name);
    while ((p = strchr(names, ','))) {
        len = FFMAX(p - names, namelen);
        if (!strncasecmp(name, names, len))
            return 1;
        names = p+1;
    }
    return !strcasecmp(name, names);
}

174
AVOutputFormat *guess_format(const char *short_name, const char *filename,
175
                             const char *mime_type)
Fabrice Bellard's avatar
Fabrice Bellard committed
176
{
177
    AVOutputFormat *fmt, *fmt_found;
Fabrice Bellard's avatar
Fabrice Bellard committed
178 179
    int score_max, score;

Fabrice Bellard's avatar
Fabrice Bellard committed
180
    /* specific test for image sequences */
181
#if CONFIG_IMAGE2_MUXER
182
    if (!short_name && filename &&
183
        av_filename_number_test(filename) &&
184 185 186
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
        return guess_format("image2", NULL, NULL);
    }
187
#endif
Diego Biurrun's avatar
Diego Biurrun committed
188
    /* Find the proper file type. */
Fabrice Bellard's avatar
Fabrice Bellard committed
189 190
    fmt_found = NULL;
    score_max = 0;
191
    fmt = first_oformat;
Fabrice Bellard's avatar
Fabrice Bellard committed
192 193 194 195 196 197
    while (fmt != NULL) {
        score = 0;
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
            score += 100;
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
            score += 10;
198
        if (filename && fmt->extensions &&
Fabrice Bellard's avatar
Fabrice Bellard committed
199 200 201 202 203 204 205 206 207 208
            match_ext(filename, fmt->extensions)) {
            score += 5;
        }
        if (score > score_max) {
            score_max = score;
            fmt_found = fmt;
        }
        fmt = fmt->next;
    }
    return fmt_found;
209
}
Fabrice Bellard's avatar
Fabrice Bellard committed
210

211
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
                             const char *mime_type)
{
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);

    if (fmt) {
        AVOutputFormat *stream_fmt;
        char stream_format_name[64];

        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
        stream_fmt = guess_format(stream_format_name, NULL, NULL);

        if (stream_fmt)
            fmt = stream_fmt;
    }

    return fmt;
}

230
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
231 232 233 234
                            const char *filename, const char *mime_type, enum CodecType type){
    if(type == CODEC_TYPE_VIDEO){
        enum CodecID codec_id= CODEC_ID_NONE;

235
#if CONFIG_IMAGE2_MUXER
236
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
237 238
            codec_id= av_guess_image2_codec(filename);
        }
239
#endif
240 241 242 243 244 245 246 247 248
        if(codec_id == CODEC_ID_NONE)
            codec_id= fmt->video_codec;
        return codec_id;
    }else if(type == CODEC_TYPE_AUDIO)
        return fmt->audio_codec;
    else
        return CODEC_ID_NONE;
}

249 250 251 252
AVInputFormat *av_find_input_format(const char *short_name)
{
    AVInputFormat *fmt;
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
253
        if (match_format(short_name, fmt->name))
254 255 256 257 258
            return fmt;
    }
    return NULL;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
259 260 261
/* memory handling */


Michael Niedermayer's avatar
Michael Niedermayer committed
262 263 264 265 266 267 268 269 270 271 272 273 274
int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
{
    int ret= av_new_packet(pkt, size);

    if(ret<0)
        return ret;

    pkt->pos= url_ftell(s);

    ret= get_buffer(s, pkt->data, size);
    if(ret<=0)
        av_free_packet(pkt);
    else
275
        av_shrink_packet(pkt, ret);
Michael Niedermayer's avatar
Michael Niedermayer committed
276 277 278 279

    return ret;
}

280

281
int av_filename_number_test(const char *filename)
282 283
{
    char buf[1024];
284
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
285 286
}

287
static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
288 289
{
    AVInputFormat *fmt1, *fmt;
290
    int score;
291 292 293

    fmt = NULL;
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
294
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
295 296
            continue;
        score = 0;
297 298 299
        if (fmt1->read_probe) {
            score = fmt1->read_probe(pd);
        } else if (fmt1->extensions) {
300 301 302
            if (match_ext(pd->filename, fmt1->extensions)) {
                score = 50;
            }
303
        }
304 305
        if (score > *score_max) {
            *score_max = score;
306
            fmt = fmt1;
307 308
        }else if (score == *score_max)
            fmt = NULL;
309 310 311 312
    }
    return fmt;
}

313 314 315 316 317
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
    int score=0;
    return av_probe_input_format2(pd, is_opened, &score);
}

318 319 320 321 322 323
static int set_codec_from_probe_data(AVStream *st, AVProbeData *pd, int score)
{
    AVInputFormat *fmt;
    fmt = av_probe_input_format2(pd, 1, &score);

    if (fmt) {
324
        if (!strcmp(fmt->name, "mp3")) {
325
            st->codec->codec_id = CODEC_ID_MP3;
326 327
            st->codec->codec_type = CODEC_TYPE_AUDIO;
        } else if (!strcmp(fmt->name, "ac3")) {
328
            st->codec->codec_id = CODEC_ID_AC3;
329 330
            st->codec->codec_type = CODEC_TYPE_AUDIO;
        } else if (!strcmp(fmt->name, "mpegvideo")) {
331
            st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
332
            st->codec->codec_type = CODEC_TYPE_VIDEO;
333 334 335
        } else if (!strcmp(fmt->name, "m4v")) {
            st->codec->codec_id = CODEC_ID_MPEG4;
            st->codec->codec_type = CODEC_TYPE_VIDEO;
336
        } else if (!strcmp(fmt->name, "h264")) {
337
            st->codec->codec_id = CODEC_ID_H264;
338
            st->codec->codec_type = CODEC_TYPE_VIDEO;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
339 340 341
        } else if (!strcmp(fmt->name, "dts")) {
            st->codec->codec_id = CODEC_ID_DTS;
            st->codec->codec_type = CODEC_TYPE_AUDIO;
342
        }
343 344 345 346
    }
    return !!fmt;
}

347 348
/************************************************************/
/* input media file */
349

350
/**
351
 * Open a media file from an IO stream. 'fmt' must be specified.
352
 */
353 354
int av_open_input_stream(AVFormatContext **ic_ptr,
                         ByteIOContext *pb, const char *filename,
355 356 357 358
                         AVInputFormat *fmt, AVFormatParameters *ap)
{
    int err;
    AVFormatContext *ic;
359 360 361 362 363 364
    AVFormatParameters default_ap;

    if(!ap){
        ap=&default_ap;
        memset(ap, 0, sizeof(default_ap));
    }
365

366
    if(!ap->prealloced_context)
367
        ic = avformat_alloc_context();
368 369
    else
        ic = *ic_ptr;
370
    if (!ic) {
371
        err = AVERROR(ENOMEM);
372 373 374
        goto fail;
    }
    ic->iformat = fmt;
375
    ic->pb = pb;
376 377
    ic->duration = AV_NOPTS_VALUE;
    ic->start_time = AV_NOPTS_VALUE;
Måns Rullgård's avatar
Måns Rullgård committed
378
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
379 380 381 382 383

    /* allocate private data */
    if (fmt->priv_data_size > 0) {
        ic->priv_data = av_mallocz(fmt->priv_data_size);
        if (!ic->priv_data) {
384
            err = AVERROR(ENOMEM);
385 386 387 388 389 390
            goto fail;
        }
    } else {
        ic->priv_data = NULL;
    }

391
    if (ic->iformat->read_header) {
392 393 394
        err = ic->iformat->read_header(ic, ap);
        if (err < 0)
            goto fail;
395
    }
396

397
    if (pb && !ic->data_offset)
398
        ic->data_offset = url_ftell(ic->pb);
399

400 401 402 403
#if LIBAVFORMAT_VERSION_MAJOR < 53
    ff_metadata_demux_compat(ic);
#endif

404 405
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

406 407 408 409
    *ic_ptr = ic;
    return 0;
 fail:
    if (ic) {
410
        int i;
411
        av_freep(&ic->priv_data);
412 413 414 415 416 417 418 419
        for(i=0;i<ic->nb_streams;i++) {
            AVStream *st = ic->streams[i];
            if (st) {
                av_free(st->priv_data);
                av_free(st->codec->extradata);
            }
            av_free(st);
        }
420 421 422 423 424 425
    }
    av_free(ic);
    *ic_ptr = NULL;
    return err;
}

Diego Biurrun's avatar
Diego Biurrun committed
426
/** size of probe buffer, for guessing file type from file contents */
427
#define PROBE_BUF_MIN 2048
428
#define PROBE_BUF_MAX (1<<20)
429

430
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
431 432 433
                       AVInputFormat *fmt,
                       int buf_size,
                       AVFormatParameters *ap)
Fabrice Bellard's avatar
Fabrice Bellard committed
434
{
435
    int err, probe_size;
436
    AVProbeData probe_data, *pd = &probe_data;
437
    ByteIOContext *pb = NULL;
438

439 440 441
    pd->filename = "";
    if (filename)
        pd->filename = filename;
442
    pd->buf = NULL;
443 444 445
    pd->buf_size = 0;

    if (!fmt) {
Diego Biurrun's avatar
Diego Biurrun committed
446
        /* guess format if no file can be opened */
447
        fmt = av_probe_input_format(pd, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
448 449
    }

Diego Biurrun's avatar
Diego Biurrun committed
450
    /* Do not open file if the format does not need it. XXX: specific
Fabrice Bellard's avatar
Fabrice Bellard committed
451
       hack needed to handle RTSP/TCP */
452
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
453
        /* if no file needed do not try to open one */
454
        if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
455
            goto fail;
456
        }
457
        if (buf_size > 0) {
458
            url_setbufsize(pb, buf_size);
459
        }
460 461

        for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
462
            int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
463
            /* read probe data */
464
            pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
465
            pd->buf_size = get_buffer(pb, pd->buf, probe_size);
466
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
467
            if (url_fseek(pb, 0, SEEK_SET) < 0) {
468
                url_fclose(pb);
469
                if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
470
                    pb = NULL;
471
                    err = AVERROR(EIO);
472 473 474
                    goto fail;
                }
            }
475
            /* guess file format */
476
            fmt = av_probe_input_format2(pd, 1, &score);
477 478
            if(fmt)
                av_log(*ic_ptr, AV_LOG_DEBUG, "Probe with size=%d detected %s with score=%d\n", probe_size, fmt->name, score);
479
        }
480
        av_freep(&pd->buf);
481 482 483 484 485
    }

    /* if still no format found, error */
    if (!fmt) {
        err = AVERROR_NOFMT;
486
        goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
487
    }
488

Diego Biurrun's avatar
Diego Biurrun committed
489
    /* check filename in case an image number is expected */
490
    if (fmt->flags & AVFMT_NEEDNUMBER) {
491
        if (!av_filename_number_test(filename)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
492
            err = AVERROR_NUMEXPECTED;
493
            goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
494 495
        }
    }
496 497 498
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
    if (err)
        goto fail;
499
    return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
500
 fail:
501
    av_freep(&pd->buf);
502
    if (pb)
503
        url_fclose(pb);
504 505 506
    if (ap && ap->prealloced_context)
        av_free(*ic_ptr);
    *ic_ptr = NULL;
507
    return err;
508

Fabrice Bellard's avatar
Fabrice Bellard committed
509 510
}

511 512
/*******************************************************/

513 514 515
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
                               AVPacketList **plast_pktl){
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
516 517 518
    if (!pktl)
        return NULL;

519 520 521 522 523
    if (*packet_buffer)
        (*plast_pktl)->next = pktl;
    else
        *packet_buffer = pktl;

524 525 526 527 528 529
    /* add the packet in the buffered packet list */
    *plast_pktl = pktl;
    pktl->pkt= *pkt;
    return &pktl->pkt;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
530
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
531
{
532
    int ret, i;
533
    AVStream *st;
534 535 536 537 538 539

    for(;;){
        AVPacketList *pktl = s->raw_packet_buffer;

        if (pktl) {
            *pkt = pktl->pkt;
540
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
541 542 543 544 545
               !s->streams[pkt->stream_index]->probe_packets ||
               s->raw_packet_buffer_remaining_size < pkt->size){
                AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
                av_freep(&pd->buf);
                pd->buf_size = 0;
546
                s->raw_packet_buffer = pktl->next;
547
                s->raw_packet_buffer_remaining_size += pkt->size;
548 549 550 551 552
                av_free(pktl);
                return 0;
            }
        }

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
553 554
        av_init_packet(pkt);
        ret= s->iformat->read_packet(s, pkt);
555 556 557 558 559 560 561
        if (ret < 0) {
            if (!pktl || ret == AVERROR(EAGAIN))
                return ret;
            for (i = 0; i < s->nb_streams; i++)
                s->streams[i]->probe_packets = 0;
            continue;
        }
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
562
        st= s->streams[pkt->stream_index];
563

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
564 565 566 567 568 569 570 571 572 573 574
        switch(st->codec->codec_type){
        case CODEC_TYPE_VIDEO:
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
            break;
        case CODEC_TYPE_AUDIO:
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
            break;
        case CODEC_TYPE_SUBTITLE:
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
            break;
        }
575

576 577
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
                     !st->probe_packets))
578 579
            return ret;

580
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
581
        s->raw_packet_buffer_remaining_size -= pkt->size;
582

583 584 585
        if(st->codec->codec_id == CODEC_ID_PROBE){
            AVProbeData *pd = &st->probe_data;

586 587
            --st->probe_packets;

588 589 590 591 592
            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
            pd->buf_size += pkt->size;
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);

593
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
594 595 596 597 598
                set_codec_from_probe_data(st, pd, 1);
                if(st->codec->codec_id != CODEC_ID_PROBE){
                    pd->buf_size=0;
                    av_freep(&pd->buf);
                }
599
            }
600 601
        }
    }
602 603 604 605
}

/**********************************************************/

606
/**
Diego Biurrun's avatar
Diego Biurrun committed
607
 * Get the number of samples of an audio frame. Return -1 on error.
608
 */
609 610 611 612
static int get_audio_frame_size(AVCodecContext *enc, int size)
{
    int frame_size;

613 614 615
    if(enc->codec_id == CODEC_ID_VORBIS)
        return -1;

616
    if (enc->frame_size <= 1) {
617 618 619
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);

        if (bits_per_sample) {
620 621
            if (enc->channels == 0)
                return -1;
622
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
623
        } else {
624 625 626
            /* used for example by ADPCM codecs */
            if (enc->bit_rate == 0)
                return -1;
627
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
628 629 630 631 632 633 634 635
        }
    } else {
        frame_size = enc->frame_size;
    }
    return frame_size;
}


636
/**
Diego Biurrun's avatar
Diego Biurrun committed
637
 * Return the frame duration in seconds. Return 0 if not available.
638
 */
639
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
640 641 642 643 644 645
                                   AVCodecParserContext *pc, AVPacket *pkt)
{
    int frame_size;

    *pnum = 0;
    *pden = 0;
646
    switch(st->codec->codec_type) {
647
    case CODEC_TYPE_VIDEO:
Michael Niedermayer's avatar
Michael Niedermayer committed
648
        if(st->time_base.num*1000LL > st->time_base.den){
649 650
            *pnum = st->time_base.num;
            *pden = st->time_base.den;
651 652 653
        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
            *pnum = st->codec->time_base.num;
            *pden = st->codec->time_base.den;
654
            if (pc && pc->repeat_pict) {
655
                *pnum = (*pnum) * (1 + pc->repeat_pict);
656
            }
657 658 659
        }
        break;
    case CODEC_TYPE_AUDIO:
660
        frame_size = get_audio_frame_size(st->codec, pkt->size);
661 662 663
        if (frame_size < 0)
            break;
        *pnum = frame_size;
664
        *pden = st->codec->sample_rate;
665 666 667 668 669 670
        break;
    default:
        break;
    }
}

671 672 673 674 675 676 677 678 679 680 681
static int is_intra_only(AVCodecContext *enc){
    if(enc->codec_type == CODEC_TYPE_AUDIO){
        return 1;
    }else if(enc->codec_type == CODEC_TYPE_VIDEO){
        switch(enc->codec_id){
        case CODEC_ID_MJPEG:
        case CODEC_ID_MJPEGB:
        case CODEC_ID_LJPEG:
        case CODEC_ID_RAWVIDEO:
        case CODEC_ID_DVVIDEO:
        case CODEC_ID_HUFFYUV:
Loren Merritt's avatar
Loren Merritt committed
682
        case CODEC_ID_FFVHUFF:
683 684 685
        case CODEC_ID_ASV1:
        case CODEC_ID_ASV2:
        case CODEC_ID_VCR1:
Baptiste Coudurier's avatar
Baptiste Coudurier committed
686
        case CODEC_ID_DNXHD:
687
        case CODEC_ID_JPEG2000:
688 689 690 691 692 693 694
            return 1;
        default: break;
        }
    }
    return 0;
}

695 696 697
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
                                      int64_t dts, int64_t pts)
{
698 699 700
    AVStream *st= s->streams[stream_index];
    AVPacketList *pktl= s->packet_buffer;

701
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
702 703 704 705 706 707 708 709 710 711 712 713 714 715
        return;

    st->first_dts= dts - st->cur_dts;
    st->cur_dts= dts;

    for(; pktl; pktl= pktl->next){
        if(pktl->pkt.stream_index != stream_index)
            continue;
        //FIXME think more about this check
        if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
            pktl->pkt.pts += st->first_dts;

        if(pktl->pkt.dts != AV_NOPTS_VALUE)
            pktl->pkt.dts += st->first_dts;
716 717 718

        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
            st->start_time= pktl->pkt.pts;
719
    }
720 721
    if (st->start_time == AV_NOPTS_VALUE)
        st->start_time = pts;
722 723
}

724 725 726
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
    AVPacketList *pktl= s->packet_buffer;
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
    int64_t cur_dts= 0;

    if(st->first_dts != AV_NOPTS_VALUE){
        cur_dts= st->first_dts;
        for(; pktl; pktl= pktl->next){
            if(pktl->pkt.stream_index == pkt->stream_index){
                if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
                    break;
                cur_dts -= pkt->duration;
            }
        }
        pktl= s->packet_buffer;
        st->first_dts = cur_dts;
    }else if(st->cur_dts)
        return;
742 743 744 745

    for(; pktl; pktl= pktl->next){
        if(pktl->pkt.stream_index != pkt->stream_index)
            continue;
746 747
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
           && !pktl->pkt.duration){
748
            pktl->pkt.dts= cur_dts;
749
            if(!st->codec->has_b_frames)
750 751
                pktl->pkt.pts= cur_dts;
            cur_dts += pkt->duration;
752 753 754 755
            pktl->pkt.duration= pkt->duration;
        }else
            break;
    }
756 757
    if(st->first_dts == AV_NOPTS_VALUE)
        st->cur_dts= cur_dts;
758 759
}

760
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
761 762
                               AVCodecParserContext *pc, AVPacket *pkt)
{
763
    int num, den, presentation_delayed, delay, i;
764
    int64_t offset;
765

766 767 768
    if (pc && pc->pict_type == FF_B_TYPE)
        st->codec->has_b_frames = 1;

769 770 771 772 773 774 775 776 777
    /* do we have a video B-frame ? */
    delay= st->codec->has_b_frames;
    presentation_delayed = 0;
    /* XXX: need has_b_frame, but cannot get it if the codec is
        not initialized */
    if (delay &&
        pc && pc->pict_type != FF_B_TYPE)
        presentation_delayed = 1;

778 779 780 781 782
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
        pkt->dts -= 1LL<<st->pts_wrap_bits;
    }

783 784 785 786
    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
    // we take the conservative approach and discard both
    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
787
        av_log(s, AV_LOG_WARNING, "invalid dts/pts combination\n");
788 789 790
        pkt->dts= pkt->pts= AV_NOPTS_VALUE;
    }

791
    if (pkt->duration == 0) {
792
        compute_frame_duration(&num, &den, st, pc, pkt);
793
        if (den && num) {
794
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
795

796
            if(pkt->duration != 0 && s->packet_buffer)
797
                update_initial_durations(s, st, pkt);
798 799 800
        }
    }

Diego Biurrun's avatar
Diego Biurrun committed
801 802
    /* correct timestamps with byte offset if demuxers only have timestamps
       on packet boundaries */
803 804 805 806 807 808 809 810 811
    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
        /* this will estimate bitrate based on this frame's duration and size */
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
        if(pkt->pts != AV_NOPTS_VALUE)
            pkt->pts += offset;
        if(pkt->dts != AV_NOPTS_VALUE)
            pkt->dts += offset;
    }

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    if (pc && pc->dts_sync_point >= 0) {
        // we have synchronization info from the parser
        int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
        if (den > 0) {
            int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
            if (pkt->dts != AV_NOPTS_VALUE) {
                // got DTS from the stream, update reference timestamp
                st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
            } else if (st->reference_dts != AV_NOPTS_VALUE) {
                // compute DTS based on reference timestamp
                pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
            }
            if (pc->dts_sync_point > 0)
                st->reference_dts = pkt->dts; // new reference
        }
    }

Diego Biurrun's avatar
Diego Biurrun committed
831
    /* This may be redundant, but it should not hurt. */
Michael Niedermayer's avatar
Michael Niedermayer committed
832 833
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
        presentation_delayed = 1;
834

835
//    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
836
    /* interpolate PTS and DTS if they are not present */
837 838
    //We skip H264 currently because delay and has_b_frames are not reliably set
    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
Michael Niedermayer's avatar
Michael Niedermayer committed
839
        if (presentation_delayed) {
Diego Biurrun's avatar
Diego Biurrun committed
840 841
            /* DTS = decompression timestamp */
            /* PTS = presentation timestamp */
Michael Niedermayer's avatar
Michael Niedermayer committed
842
            if (pkt->dts == AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
843
                pkt->dts = st->last_IP_pts;
844
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
Michael Niedermayer's avatar
Michael Niedermayer committed
845 846 847 848
            if (pkt->dts == AV_NOPTS_VALUE)
                pkt->dts = st->cur_dts;

            /* this is tricky: the dts must be incremented by the duration
Diego Biurrun's avatar
Diego Biurrun committed
849
            of the frame we are displaying, i.e. the last I- or P-frame */
Michael Niedermayer's avatar
Michael Niedermayer committed
850 851
            if (st->last_IP_duration == 0)
                st->last_IP_duration = pkt->duration;
852
            if(pkt->dts != AV_NOPTS_VALUE)
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
853
                st->cur_dts = pkt->dts + st->last_IP_duration;
Michael Niedermayer's avatar
Michael Niedermayer committed
854 855
            st->last_IP_duration  = pkt->duration;
            st->last_IP_pts= pkt->pts;
Michael Niedermayer's avatar
Michael Niedermayer committed
856
            /* cannot compute PTS if not present (we can compute it only
Diego Biurrun's avatar
Diego Biurrun committed
857
            by knowing the future */
858
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
Michael Niedermayer's avatar
Michael Niedermayer committed
859 860 861 862 863 864 865
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
                    pkt->pts += pkt->duration;
    //                av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
                }
866
            }
867