utils.c 111 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"
Måns Rullgård's avatar
Måns Rullgård committed
27
#include "audiointerleave.h"
28 29
#include <sys/time.h>
#include <time.h>
30
#include <strings.h>
31 32 33 34
#include <stdarg.h>
#if CONFIG_NETWORK
#include "network.h"
#endif
35

36 37 38
#undef NDEBUG
#include <assert.h>

39 40
/**
 * @file libavformat/utils.c
Diego Biurrun's avatar
Diego Biurrun committed
41
 * various utility functions for use within FFmpeg
42 43
 */

44 45 46 47 48
unsigned avformat_version(void)
{
    return LIBAVFORMAT_VERSION_INT;
}

49
const char *avformat_configuration(void)
50 51 52 53
{
    return FFMPEG_CONFIGURATION;
}

54
const char *avformat_license(void)
55 56 57 58 59
{
#define LICENSE_PREFIX "libavformat license: "
    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
}

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
/* 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;
}
109

Diego Biurrun's avatar
Diego Biurrun committed
110
/** head of registered input format linked list */
111
AVInputFormat *first_iformat = NULL;
Diego Biurrun's avatar
Diego Biurrun committed
112
/** head of registered output format linked list */
113
AVOutputFormat *first_oformat = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
114

115 116 117 118 119 120 121 122 123 124 125 126
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;
}

127
void av_register_input_format(AVInputFormat *format)
Fabrice Bellard's avatar
Fabrice Bellard committed
128
{
129 130 131 132 133 134 135 136 137 138 139
    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
140 141 142 143 144
    while (*p != NULL) p = &(*p)->next;
    *p = format;
    format->next = NULL;
}

145
int av_match_ext(const char *filename, const char *extensions)
Fabrice Bellard's avatar
Fabrice Bellard committed
146 147 148 149
{
    const char *ext, *p;
    char ext1[32], *q;

Michael Niedermayer's avatar
Michael Niedermayer committed
150 151
    if(!filename)
        return 0;
152

Fabrice Bellard's avatar
Fabrice Bellard committed
153 154 155 156 157 158
    ext = strrchr(filename, '.');
    if (ext) {
        ext++;
        p = extensions;
        for(;;) {
            q = ext1;
159
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
Fabrice Bellard's avatar
Fabrice Bellard committed
160 161
                *q++ = *p++;
            *q = '\0';
162
            if (!strcasecmp(ext1, ext))
Fabrice Bellard's avatar
Fabrice Bellard committed
163
                return 1;
164
            if (*p == '\0')
Fabrice Bellard's avatar
Fabrice Bellard committed
165 166 167 168 169 170 171
                break;
            p++;
        }
    }
    return 0;
}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
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);
}

190
#if LIBAVFORMAT_VERSION_MAJOR < 53
191
AVOutputFormat *guess_format(const char *short_name, const char *filename,
192
                             const char *mime_type)
193 194 195 196 197 198 199
{
    return av_guess_format(short_name, filename, mime_type);
}
#endif

AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
                                const char *mime_type)
Fabrice Bellard's avatar
Fabrice Bellard committed
200
{
201
    AVOutputFormat *fmt, *fmt_found;
Fabrice Bellard's avatar
Fabrice Bellard committed
202 203
    int score_max, score;

Fabrice Bellard's avatar
Fabrice Bellard committed
204
    /* specific test for image sequences */
205
#if CONFIG_IMAGE2_MUXER
206
    if (!short_name && filename &&
207
        av_filename_number_test(filename) &&
208
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
209
        return av_guess_format("image2", NULL, NULL);
210
    }
211
#endif
Diego Biurrun's avatar
Diego Biurrun committed
212
    /* Find the proper file type. */
Fabrice Bellard's avatar
Fabrice Bellard committed
213 214
    fmt_found = NULL;
    score_max = 0;
215
    fmt = first_oformat;
Fabrice Bellard's avatar
Fabrice Bellard committed
216 217 218 219 220 221
    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;
222
        if (filename && fmt->extensions &&
223
            av_match_ext(filename, fmt->extensions)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
224 225 226 227 228 229 230 231 232
            score += 5;
        }
        if (score > score_max) {
            score_max = score;
            fmt_found = fmt;
        }
        fmt = fmt->next;
    }
    return fmt_found;
233
}
Fabrice Bellard's avatar
Fabrice Bellard committed
234

235
#if LIBAVFORMAT_VERSION_MAJOR < 53
236
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
237 238
                             const char *mime_type)
{
239
    AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
240 241 242 243 244 245

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

        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
246
        stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
247 248 249 250 251 252 253

        if (stream_fmt)
            fmt = stream_fmt;
    }

    return fmt;
}
254
#endif
255

256
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
257 258 259 260
                            const char *filename, const char *mime_type, enum CodecType type){
    if(type == CODEC_TYPE_VIDEO){
        enum CodecID codec_id= CODEC_ID_NONE;

261
#if CONFIG_IMAGE2_MUXER
262
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
263 264
            codec_id= av_guess_image2_codec(filename);
        }
265
#endif
266 267 268 269 270 271 272 273 274
        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;
}

275 276 277 278
AVInputFormat *av_find_input_format(const char *short_name)
{
    AVInputFormat *fmt;
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
279
        if (match_format(short_name, fmt->name))
280 281 282 283 284
            return fmt;
    }
    return NULL;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
285 286 287
/* memory handling */


Michael Niedermayer's avatar
Michael Niedermayer committed
288 289 290 291 292 293 294 295 296 297 298 299 300
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
301
        av_shrink_packet(pkt, ret);
Michael Niedermayer's avatar
Michael Niedermayer committed
302 303 304 305

    return ret;
}

306

307
int av_filename_number_test(const char *filename)
308 309
{
    char buf[1024];
310
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
311 312
}

313
static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
314 315
{
    AVInputFormat *fmt1, *fmt;
316
    int score;
317 318 319

    fmt = NULL;
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
320
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
321 322
            continue;
        score = 0;
323 324 325
        if (fmt1->read_probe) {
            score = fmt1->read_probe(pd);
        } else if (fmt1->extensions) {
326
            if (av_match_ext(pd->filename, fmt1->extensions)) {
327 328
                score = 50;
            }
329
        }
330 331
        if (score > *score_max) {
            *score_max = score;
332
            fmt = fmt1;
333 334
        }else if (score == *score_max)
            fmt = NULL;
335 336 337 338
    }
    return fmt;
}

339 340 341 342 343
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
    int score=0;
    return av_probe_input_format2(pd, is_opened, &score);
}

344
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
345 346 347 348 349
{
    AVInputFormat *fmt;
    fmt = av_probe_input_format2(pd, 1, &score);

    if (fmt) {
350 351
        av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
               pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
352
        if (!strcmp(fmt->name, "mp3")) {
353
            st->codec->codec_id = CODEC_ID_MP3;
354 355
            st->codec->codec_type = CODEC_TYPE_AUDIO;
        } else if (!strcmp(fmt->name, "ac3")) {
356
            st->codec->codec_id = CODEC_ID_AC3;
357
            st->codec->codec_type = CODEC_TYPE_AUDIO;
358 359 360
        } else if (!strcmp(fmt->name, "eac3")) {
            st->codec->codec_id = CODEC_ID_EAC3;
            st->codec->codec_type = CODEC_TYPE_AUDIO;
361
        } else if (!strcmp(fmt->name, "mpegvideo")) {
362
            st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
363
            st->codec->codec_type = CODEC_TYPE_VIDEO;
364 365 366
        } else if (!strcmp(fmt->name, "m4v")) {
            st->codec->codec_id = CODEC_ID_MPEG4;
            st->codec->codec_type = CODEC_TYPE_VIDEO;
367
        } else if (!strcmp(fmt->name, "h264")) {
368
            st->codec->codec_id = CODEC_ID_H264;
369
            st->codec->codec_type = CODEC_TYPE_VIDEO;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
370 371 372
        } else if (!strcmp(fmt->name, "dts")) {
            st->codec->codec_id = CODEC_ID_DTS;
            st->codec->codec_type = CODEC_TYPE_AUDIO;
373
        }
374 375 376 377
    }
    return !!fmt;
}

378 379
/************************************************************/
/* input media file */
380

381
/**
382
 * Open a media file from an IO stream. 'fmt' must be specified.
383
 */
384 385
int av_open_input_stream(AVFormatContext **ic_ptr,
                         ByteIOContext *pb, const char *filename,
386 387 388 389
                         AVInputFormat *fmt, AVFormatParameters *ap)
{
    int err;
    AVFormatContext *ic;
390 391 392 393 394 395
    AVFormatParameters default_ap;

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

397
    if(!ap->prealloced_context)
398
        ic = avformat_alloc_context();
399 400
    else
        ic = *ic_ptr;
401
    if (!ic) {
402
        err = AVERROR(ENOMEM);
403 404 405
        goto fail;
    }
    ic->iformat = fmt;
406
    ic->pb = pb;
407 408
    ic->duration = AV_NOPTS_VALUE;
    ic->start_time = AV_NOPTS_VALUE;
Måns Rullgård's avatar
Måns Rullgård committed
409
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
410 411 412 413 414

    /* allocate private data */
    if (fmt->priv_data_size > 0) {
        ic->priv_data = av_mallocz(fmt->priv_data_size);
        if (!ic->priv_data) {
415
            err = AVERROR(ENOMEM);
416 417 418 419 420 421
            goto fail;
        }
    } else {
        ic->priv_data = NULL;
    }

422
    if (ic->iformat->read_header) {
423 424 425
        err = ic->iformat->read_header(ic, ap);
        if (err < 0)
            goto fail;
426
    }
427

428
    if (pb && !ic->data_offset)
429
        ic->data_offset = url_ftell(ic->pb);
430

431 432 433 434
#if LIBAVFORMAT_VERSION_MAJOR < 53
    ff_metadata_demux_compat(ic);
#endif

435 436
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

437 438 439 440
    *ic_ptr = ic;
    return 0;
 fail:
    if (ic) {
441
        int i;
442
        av_freep(&ic->priv_data);
443 444 445 446 447 448 449 450
        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);
        }
451 452 453 454 455 456
    }
    av_free(ic);
    *ic_ptr = NULL;
    return err;
}

Diego Biurrun's avatar
Diego Biurrun committed
457
/** size of probe buffer, for guessing file type from file contents */
458
#define PROBE_BUF_MIN 2048
459
#define PROBE_BUF_MAX (1<<20)
460

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
int ff_probe_input_buffer(ByteIOContext **pb, AVInputFormat **fmt,
                          const char *filename, void *logctx,
                          unsigned int offset, unsigned int max_probe_size)
{
    AVProbeData pd = { filename ? filename : "", NULL, -offset };
    unsigned char *buf = NULL;
    int ret = 0, probe_size;

    if (!max_probe_size) {
        max_probe_size = PROBE_BUF_MAX;
    } else if (max_probe_size > PROBE_BUF_MAX) {
        max_probe_size = PROBE_BUF_MAX;
    } else if (max_probe_size < PROBE_BUF_MIN) {
        return AVERROR(EINVAL);
    }

    if (offset >= max_probe_size) {
        return AVERROR(EINVAL);
    }

    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0; probe_size<<=1){
        int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
        int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;

        if (probe_size < offset) {
            continue;
        }

        /* read probe data */
        buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
        if ((ret = get_buffer(*pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
            /* fail if error was not end of file, otherwise, lower score */
            if (ret != AVERROR_EOF) {
                av_free(buf);
                return ret;
            }
            score = 0;
        }
        pd.buf_size += ret;
        pd.buf = &buf[offset];

        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);

        /* guess file format */
        *fmt = av_probe_input_format2(&pd, 1, &score);
        if(*fmt){
            if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
                av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
            }else
                av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
        }
    }

    av_free(buf);
    if (url_fseek(*pb, 0, SEEK_SET) < 0) {
        url_fclose(*pb);
        if (url_fopen(pb, filename, URL_RDONLY) < 0)
            return AVERROR(EIO);
    }

    return 0;
}

524
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
525 526 527
                       AVInputFormat *fmt,
                       int buf_size,
                       AVFormatParameters *ap)
Fabrice Bellard's avatar
Fabrice Bellard committed
528
{
529
    int err;
530
    AVProbeData probe_data, *pd = &probe_data;
531
    ByteIOContext *pb = NULL;
532
    void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
533

534 535 536
    pd->filename = "";
    if (filename)
        pd->filename = filename;
537
    pd->buf = NULL;
538 539 540
    pd->buf_size = 0;

    if (!fmt) {
Diego Biurrun's avatar
Diego Biurrun committed
541
        /* guess format if no file can be opened */
542
        fmt = av_probe_input_format(pd, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
543 544
    }

Diego Biurrun's avatar
Diego Biurrun committed
545
    /* Do not open file if the format does not need it. XXX: specific
Fabrice Bellard's avatar
Fabrice Bellard committed
546
       hack needed to handle RTSP/TCP */
547
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
548
        /* if no file needed do not try to open one */
549
        if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
550
            goto fail;
551
        }
552
        if (buf_size > 0) {
553
            url_setbufsize(pb, buf_size);
554
        }
555 556
        if ((err = ff_probe_input_buffer(&pb, &fmt, filename, logctx, 0, 0)) < 0) {
            goto fail;
557
        }
558 559 560 561 562
    }

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

Diego Biurrun's avatar
Diego Biurrun committed
566
    /* check filename in case an image number is expected */
567
    if (fmt->flags & AVFMT_NEEDNUMBER) {
568
        if (!av_filename_number_test(filename)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
569
            err = AVERROR_NUMEXPECTED;
570
            goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
571 572
        }
    }
573 574 575
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
    if (err)
        goto fail;
576
    return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
577
 fail:
578
    av_freep(&pd->buf);
579
    if (pb)
580
        url_fclose(pb);
581 582 583
    if (ap && ap->prealloced_context)
        av_free(*ic_ptr);
    *ic_ptr = NULL;
584
    return err;
585

Fabrice Bellard's avatar
Fabrice Bellard committed
586 587
}

588 589
/*******************************************************/

590 591 592
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
                               AVPacketList **plast_pktl){
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
593 594 595
    if (!pktl)
        return NULL;

596 597 598 599 600
    if (*packet_buffer)
        (*plast_pktl)->next = pktl;
    else
        *packet_buffer = pktl;

601 602 603 604 605 606
    /* add the packet in the buffered packet list */
    *plast_pktl = pktl;
    pktl->pkt= *pkt;
    return &pktl->pkt;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
607
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
608
{
609
    int ret, i;
610
    AVStream *st;
611 612 613 614 615 616

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

        if (pktl) {
            *pkt = pktl->pkt;
617
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
618 619 620 621 622
               !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;
623
                s->raw_packet_buffer = pktl->next;
624
                s->raw_packet_buffer_remaining_size += pkt->size;
625 626 627 628 629
                av_free(pktl);
                return 0;
            }
        }

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
630 631
        av_init_packet(pkt);
        ret= s->iformat->read_packet(s, pkt);
632 633 634 635 636 637 638
        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
639
        st= s->streams[pkt->stream_index];
640

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
641 642 643 644 645 646 647 648 649 650 651
        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;
        }
652

653 654
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
                     !st->probe_packets))
655 656
            return ret;

657
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
658
        s->raw_packet_buffer_remaining_size -= pkt->size;
659

660 661
        if(st->codec->codec_id == CODEC_ID_PROBE){
            AVProbeData *pd = &st->probe_data;
662
            av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
663 664
            --st->probe_packets;

665 666 667 668 669
            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);

670
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
671
                set_codec_from_probe_data(s, st, pd, 1);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
672 673 674
                if(st->codec->codec_id != CODEC_ID_PROBE){
                    pd->buf_size=0;
                    av_freep(&pd->buf);
675
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
676
                }
677
            }
678 679
        }
    }
680 681 682 683
}

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

684
/**
Diego Biurrun's avatar
Diego Biurrun committed
685
 * Get the number of samples of an audio frame. Return -1 on error.
686
 */
687 688 689 690
static int get_audio_frame_size(AVCodecContext *enc, int size)
{
    int frame_size;

691 692 693
    if(enc->codec_id == CODEC_ID_VORBIS)
        return -1;

694
    if (enc->frame_size <= 1) {
695 696 697
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);

        if (bits_per_sample) {
698 699
            if (enc->channels == 0)
                return -1;
700
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
701
        } else {
702 703 704
            /* used for example by ADPCM codecs */
            if (enc->bit_rate == 0)
                return -1;
705
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
706 707 708 709 710 711 712 713
        }
    } else {
        frame_size = enc->frame_size;
    }
    return frame_size;
}


714
/**
Diego Biurrun's avatar
Diego Biurrun committed
715
 * Return the frame duration in seconds. Return 0 if not available.
716
 */
717
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
718 719 720 721 722 723
                                   AVCodecParserContext *pc, AVPacket *pkt)
{
    int frame_size;

    *pnum = 0;
    *pden = 0;
724
    switch(st->codec->codec_type) {
725
    case CODEC_TYPE_VIDEO:
Michael Niedermayer's avatar
Michael Niedermayer committed
726
        if(st->time_base.num*1000LL > st->time_base.den){
727 728
            *pnum = st->time_base.num;
            *pden = st->time_base.den;
729 730 731
        }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;
732
            if (pc && pc->repeat_pict) {
733
                *pnum = (*pnum) * (1 + pc->repeat_pict);
734
            }
735 736 737
        }
        break;
    case CODEC_TYPE_AUDIO:
738
        frame_size = get_audio_frame_size(st->codec, pkt->size);
739 740 741
        if (frame_size < 0)
            break;
        *pnum = frame_size;
742
        *pden = st->codec->sample_rate;
743 744 745 746 747 748
        break;
    default:
        break;
    }
}

749 750 751 752 753 754 755 756 757 758 759
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
760
        case CODEC_ID_FFVHUFF:
761 762 763
        case CODEC_ID_ASV1:
        case CODEC_ID_ASV2:
        case CODEC_ID_VCR1:
Baptiste Coudurier's avatar
Baptiste Coudurier committed
764
        case CODEC_ID_DNXHD:
765
        case CODEC_ID_JPEG2000:
766 767 768 769 770 771 772
            return 1;
        default: break;
        }
    }
    return 0;
}

773 774 775
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
                                      int64_t dts, int64_t pts)
{
776 777 778
    AVStream *st= s->streams[stream_index];
    AVPacketList *pktl= s->packet_buffer;

779
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
780 781 782 783 784 785 786 787 788 789 790 791 792 793
        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;
794 795 796

        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
            st->start_time= pktl->pkt.pts;
797
    }
798 799
    if (st->start_time == AV_NOPTS_VALUE)
        st->start_time = pts;
800 801
}

802 803 804
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
    AVPacketList *pktl= s->packet_buffer;
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    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;
820 821 822 823

    for(; pktl; pktl= pktl->next){
        if(pktl->pkt.stream_index != pkt->stream_index)
            continue;
824 825
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
           && !pktl->pkt.duration){
826
            pktl->pkt.dts= cur_dts;
827
            if(!st->codec->has_b_frames)
828 829
                pktl->pkt.pts= cur_dts;
            cur_dts += pkt->duration;
830 831 832 833
            pktl->pkt.duration= pkt->duration;
        }else
            break;
    }
834 835
    if(st->first_dts == AV_NOPTS_VALUE)
        st->cur_dts= cur_dts;
836 837
}

838
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
839 840
                               AVCodecParserContext *pc, AVPacket *pkt)
{
841
    int num, den, presentation_delayed, delay, i;
842
    int64_t offset;
843

844 845 846
    if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
        pkt->dts= AV_NOPTS_VALUE;

847
    if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
848
        //FIXME Set low_delay = 0 when has_b_frames = 1
849 850
        st->codec->has_b_frames = 1;

851 852 853 854 855 856 857 858 859
    /* 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;

860 861 862 863 864
    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;
    }

865 866 867 868
    // 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){
869
        av_log(s, AV_LOG_WARNING, "invalid dts/pts combination\n");
870 871 872
        pkt->dts= pkt->pts= AV_NOPTS_VALUE;
    }

873
    if (pkt->duration == 0) {
874
        compute_frame_duration(&num, &den, st, pc, pkt);
875
        if (den && num) {
876
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
877

878
            if(pkt->duration != 0 && s->packet_buffer)
879
                update_initial_durations(s, st, pkt);
880 881 882
        }
    }

Diego Biurrun's avatar
Diego Biurrun committed
883 884
    /* correct timestamps with byte offset if demuxers only have timestamps
       on packet boundaries */
885 886 887 888 889 890 891 892 893
    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;
    }

894