utils.c 127 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
2
 * various utility functions for use within Libav
Fabrice Bellard's avatar
Fabrice Bellard committed
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav 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
 * Libav 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 Libav; 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
 */
21 22 23

/* #define DEBUG */

Fabrice Bellard's avatar
Fabrice Bellard committed
24
#include "avformat.h"
25
#include "avio_internal.h"
26
#include "internal.h"
27
#include "libavcodec/internal.h"
28
#include "libavcodec/bytestream.h"
29
#include "libavutil/opt.h"
30
#include "libavutil/dict.h"
31
#include "libavutil/pixdesc.h"
32
#include "metadata.h"
33
#include "id3v2.h"
34
#include "libavutil/avassert.h"
35
#include "libavutil/avstring.h"
36
#include "libavutil/mathematics.h"
37
#include "libavutil/parseutils.h"
38
#include "riff.h"
Måns Rullgård's avatar
Måns Rullgård committed
39
#include "audiointerleave.h"
40
#include "url.h"
41 42
#include <sys/time.h>
#include <time.h>
43 44 45 46
#include <stdarg.h>
#if CONFIG_NETWORK
#include "network.h"
#endif
47

48 49 50
#undef NDEBUG
#include <assert.h>

51
/**
52
 * @file
53
 * various utility functions for use within Libav
54 55
 */

56 57 58 59 60
unsigned avformat_version(void)
{
    return LIBAVFORMAT_VERSION_INT;
}

61
const char *avformat_configuration(void)
62
{
63
    return LIBAV_CONFIGURATION;
64 65
}

66
const char *avformat_license(void)
67 68
{
#define LICENSE_PREFIX "libavformat license: "
69
    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
70 71
}

72 73 74 75 76 77 78 79 80 81 82 83
/* 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
 */
84
static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
{
    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
 */
102
static void frac_add(AVFrac *f, int64_t incr)
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
{
    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;
}
121

Diego Biurrun's avatar
Diego Biurrun committed
122
/** head of registered input format linked list */
123
static AVInputFormat *first_iformat = NULL;
Diego Biurrun's avatar
Diego Biurrun committed
124
/** head of registered output format linked list */
125
static AVOutputFormat *first_oformat = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
126

127 128 129 130 131 132 133 134 135 136 137 138
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;
}

139
void av_register_input_format(AVInputFormat *format)
Fabrice Bellard's avatar
Fabrice Bellard committed
140
{
141 142 143 144 145 146 147 148 149 150 151
    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
152 153 154 155 156
    while (*p != NULL) p = &(*p)->next;
    *p = format;
    format->next = NULL;
}

157
int av_match_ext(const char *filename, const char *extensions)
Fabrice Bellard's avatar
Fabrice Bellard committed
158 159 160 161
{
    const char *ext, *p;
    char ext1[32], *q;

Michael Niedermayer's avatar
Michael Niedermayer committed
162 163
    if(!filename)
        return 0;
164

Fabrice Bellard's avatar
Fabrice Bellard committed
165 166 167 168 169 170
    ext = strrchr(filename, '.');
    if (ext) {
        ext++;
        p = extensions;
        for(;;) {
            q = ext1;
171
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
Fabrice Bellard's avatar
Fabrice Bellard committed
172 173
                *q++ = *p++;
            *q = '\0';
174
            if (!av_strcasecmp(ext1, ext))
Fabrice Bellard's avatar
Fabrice Bellard committed
175
                return 1;
176
            if (*p == '\0')
Fabrice Bellard's avatar
Fabrice Bellard committed
177 178 179 180 181 182 183
                break;
            p++;
        }
    }
    return 0;
}

184 185 186 187 188 189 190 191 192 193 194
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);
195
        if (!av_strncasecmp(name, names, len))
196 197 198
            return 1;
        names = p+1;
    }
199
    return !av_strcasecmp(name, names);
200 201
}

202 203
AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
                                const char *mime_type)
Fabrice Bellard's avatar
Fabrice Bellard committed
204
{
205
    AVOutputFormat *fmt = NULL, *fmt_found;
Fabrice Bellard's avatar
Fabrice Bellard committed
206 207
    int score_max, score;

Fabrice Bellard's avatar
Fabrice Bellard committed
208
    /* specific test for image sequences */
209
#if CONFIG_IMAGE2_MUXER
210
    if (!short_name && filename &&
211
        av_filename_number_test(filename) &&
212
        ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
213
        return av_guess_format("image2", NULL, NULL);
214
    }
215
#endif
Diego Biurrun's avatar
Diego Biurrun committed
216
    /* Find the proper file type. */
Fabrice Bellard's avatar
Fabrice Bellard committed
217 218
    fmt_found = NULL;
    score_max = 0;
219
    while ((fmt = av_oformat_next(fmt))) {
Fabrice Bellard's avatar
Fabrice Bellard committed
220
        score = 0;
221
        if (fmt->name && short_name && !av_strcasecmp(fmt->name, short_name))
Fabrice Bellard's avatar
Fabrice Bellard committed
222 223 224
            score += 100;
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
            score += 10;
225
        if (filename && fmt->extensions &&
226
            av_match_ext(filename, fmt->extensions)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
227 228 229 230 231 232 233 234
            score += 5;
        }
        if (score > score_max) {
            score_max = score;
            fmt_found = fmt;
        }
    }
    return fmt_found;
235
}
Fabrice Bellard's avatar
Fabrice Bellard committed
236

237
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
238 239
                            const char *filename, const char *mime_type, enum AVMediaType type){
    if(type == AVMEDIA_TYPE_VIDEO){
240 241
        enum CodecID codec_id= CODEC_ID_NONE;

242
#if CONFIG_IMAGE2_MUXER
243
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
244
            codec_id= ff_guess_image2_codec(filename);
245
        }
246
#endif
247 248 249
        if(codec_id == CODEC_ID_NONE)
            codec_id= fmt->video_codec;
        return codec_id;
250
    }else if(type == AVMEDIA_TYPE_AUDIO)
251
        return fmt->audio_codec;
252 253
    else if (type == AVMEDIA_TYPE_SUBTITLE)
        return fmt->subtitle_codec;
254 255 256 257
    else
        return CODEC_ID_NONE;
}

258 259
AVInputFormat *av_find_input_format(const char *short_name)
{
260 261
    AVInputFormat *fmt = NULL;
    while ((fmt = av_iformat_next(fmt))) {
262
        if (match_format(short_name, fmt->name))
263 264 265 266 267
            return fmt;
    }
    return NULL;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
268

269
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Michael Niedermayer's avatar
Michael Niedermayer committed
270 271 272 273 274 275
{
    int ret= av_new_packet(pkt, size);

    if(ret<0)
        return ret;

276
    pkt->pos= avio_tell(s);
Michael Niedermayer's avatar
Michael Niedermayer committed
277

278
    ret= avio_read(s, pkt->data, size);
Michael Niedermayer's avatar
Michael Niedermayer committed
279 280 281
    if(ret<=0)
        av_free_packet(pkt);
    else
282
        av_shrink_packet(pkt, ret);
Michael Niedermayer's avatar
Michael Niedermayer committed
283 284 285 286

    return ret;
}

287
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
288 289 290 291 292 293 294 295 296
{
    int ret;
    int old_size;
    if (!pkt->size)
        return av_get_packet(s, pkt, size);
    old_size = pkt->size;
    ret = av_grow_packet(pkt, size);
    if (ret < 0)
        return ret;
297
    ret = avio_read(s, pkt->data + old_size, size);
298 299 300 301
    av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
    return ret;
}

302

303
int av_filename_number_test(const char *filename)
304 305
{
    char buf[1024];
306
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
307 308
}

309
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
310
{
311
    AVProbeData lpd = *pd;
312
    AVInputFormat *fmt1 = NULL, *fmt;
313
    int score, id3 = 0;
314

315 316 317 318 319 320
    if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
        int id3len = ff_id3v2_tag_len(lpd.buf);
        if (lpd.buf_size > id3len + 16) {
            lpd.buf += id3len;
            lpd.buf_size -= id3len;
        }
321
        id3 = 1;
322 323
    }

324
    fmt = NULL;
325
    while ((fmt1 = av_iformat_next(fmt1))) {
326
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
327 328
            continue;
        score = 0;
329
        if (fmt1->read_probe) {
330
            score = fmt1->read_probe(&lpd);
331
        } else if (fmt1->extensions) {
332
            if (av_match_ext(lpd.filename, fmt1->extensions)) {
333 334
                score = 50;
            }
335
        }
336 337
        if (score > *score_max) {
            *score_max = score;
338
            fmt = fmt1;
339 340
        }else if (score == *score_max)
            fmt = NULL;
341
    }
342 343

    /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
344
    if (!fmt && is_opened && *score_max < AVPROBE_SCORE_MAX/4) {
345 346 347 348 349 350 351
        while ((fmt = av_iformat_next(fmt)))
            if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
                *score_max = AVPROBE_SCORE_MAX/4;
                break;
            }
    }

352 353 354 355 356 357 358 359
    if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4-1) {
        while ((fmt = av_iformat_next(fmt)))
            if (fmt->extensions && av_match_ext("mp3", fmt->extensions)) {
                *score_max = AVPROBE_SCORE_MAX/4-1;
                break;
            }
    }

360 361 362
    return fmt;
}

363 364 365 366 367
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
    int score=0;
    return av_probe_input_format2(pd, is_opened, &score);
}

368
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
369
{
370 371 372 373 374 375 376 377 378 379 380 381 382 383
    static const struct {
        const char *name; enum CodecID id; enum AVMediaType type;
    } fmt_id_type[] = {
        { "aac"      , CODEC_ID_AAC       , AVMEDIA_TYPE_AUDIO },
        { "ac3"      , CODEC_ID_AC3       , AVMEDIA_TYPE_AUDIO },
        { "dts"      , CODEC_ID_DTS       , AVMEDIA_TYPE_AUDIO },
        { "eac3"     , CODEC_ID_EAC3      , AVMEDIA_TYPE_AUDIO },
        { "h264"     , CODEC_ID_H264      , AVMEDIA_TYPE_VIDEO },
        { "m4v"      , CODEC_ID_MPEG4     , AVMEDIA_TYPE_VIDEO },
        { "mp3"      , CODEC_ID_MP3       , AVMEDIA_TYPE_AUDIO },
        { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
        { 0 }
    };
    AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
384 385

    if (fmt) {
386
        int i;
387 388
        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);
389 390 391 392 393 394
        for (i = 0; fmt_id_type[i].name; i++) {
            if (!strcmp(fmt->name, fmt_id_type[i].name)) {
                st->codec->codec_id   = fmt_id_type[i].id;
                st->codec->codec_type = fmt_id_type[i].type;
                break;
            }
395
        }
396 397 398 399
    }
    return !!fmt;
}

400 401
/************************************************************/
/* input media file */
402

Diego Biurrun's avatar
Diego Biurrun committed
403
/** size of probe buffer, for guessing file type from file contents */
404
#define PROBE_BUF_MIN 2048
405
#define PROBE_BUF_MAX (1<<20)
406

407
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
                          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);
    }

427
    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
428
        probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
429
        int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
430 431 432 433 434 435 436 437
        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);
438
        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
439 440 441 442 443 444
            /* fail if error was not end of file, otherwise, lower score */
            if (ret != AVERROR_EOF) {
                av_free(buf);
                return ret;
            }
            score = 0;
445
            ret = 0;            /* error was end of file, nothing read */
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        }
        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);
        }
    }

462
    if (!*fmt) {
463
        av_free(buf);
464 465 466
        return AVERROR_INVALIDDATA;
    }

467
    /* rewind. reuse probe buffer to avoid seeking */
468
    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
469
        av_free(buf);
470

471
    return ret;
472 473
}

474
/* open input file and probe the format if necessary */
475
static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
476 477 478 479 480 481 482
{
    int ret;
    AVProbeData pd = {filename, NULL, 0};

    if (s->pb) {
        s->flags |= AVFMT_FLAG_CUSTOM_IO;
        if (!s->iformat)
483
            return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
484 485 486 487 488 489 490 491 492
        else if (s->iformat->flags & AVFMT_NOFILE)
            return AVERROR(EINVAL);
        return 0;
    }

    if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
        (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
        return 0;

493
    if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
494
                          &s->interrupt_callback, options)) < 0)
495
        return ret;
496 497
    if (s->iformat)
        return 0;
498
    return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
499 500
}

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
                               AVPacketList **plast_pktl){
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
    if (!pktl)
        return NULL;

    if (*packet_buffer)
        (*plast_pktl)->next = pktl;
    else
        *packet_buffer = pktl;

    /* add the packet in the buffered packet list */
    *plast_pktl = pktl;
    pktl->pkt= *pkt;
    return &pktl->pkt;
}

518 519 520 521
static void queue_attached_pictures(AVFormatContext *s)
{
    int i;
    for (i = 0; i < s->nb_streams; i++)
522 523
        if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
            s->streams[i]->discard < AVDISCARD_ALL) {
524 525 526 527 528 529
            AVPacket copy = s->streams[i]->attached_pic;
            copy.destruct = NULL;
            add_to_pktbuf(&s->raw_packet_buffer, &copy, &s->raw_packet_buffer_end);
        }
}

530 531 532
int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
{
    AVFormatContext *s = *ps;
533
    int ret = 0;
534
    AVDictionary *tmp = NULL;
535
    ID3v2ExtraMeta *id3v2_extra_meta = NULL;
536 537 538 539 540 541 542 543 544 545 546 547

    if (!s && !(s = avformat_alloc_context()))
        return AVERROR(ENOMEM);
    if (fmt)
        s->iformat = fmt;

    if (options)
        av_dict_copy(&tmp, *options, 0);

    if ((ret = av_opt_set_dict(s, &tmp)) < 0)
        goto fail;

548
    if ((ret = init_input(s, filename, &tmp)) < 0)
549 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
        goto fail;

    /* check filename in case an image number is expected */
    if (s->iformat->flags & AVFMT_NEEDNUMBER) {
        if (!av_filename_number_test(filename)) {
            ret = AVERROR(EINVAL);
            goto fail;
        }
    }

    s->duration = s->start_time = AV_NOPTS_VALUE;
    av_strlcpy(s->filename, filename, sizeof(s->filename));

    /* allocate private data */
    if (s->iformat->priv_data_size > 0) {
        if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
        if (s->iformat->priv_class) {
            *(const AVClass**)s->priv_data = s->iformat->priv_class;
            av_opt_set_defaults(s->priv_data);
            if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
                goto fail;
        }
    }

    /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
    if (s->pb)
578
        ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
579 580

    if (s->iformat->read_header)
581
        if ((ret = s->iformat->read_header(s)) < 0)
582 583
            goto fail;

584 585 586 587 588
    if (id3v2_extra_meta &&
        (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
        goto fail;
    ff_id3v2_free_extra_meta(&id3v2_extra_meta);

589
    queue_attached_pictures(s);
590

591 592 593 594 595 596 597 598 599 600 601 602 603
    if (s->pb && !s->data_offset)
        s->data_offset = avio_tell(s->pb);

    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

    if (options) {
        av_dict_free(options);
        *options = tmp;
    }
    *ps = s;
    return 0;

fail:
604
    ff_id3v2_free_extra_meta(&id3v2_extra_meta);
605 606 607 608 609 610 611 612
    av_dict_free(&tmp);
    if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
        avio_close(s->pb);
    avformat_free_context(s);
    *ps = NULL;
    return ret;
}

613 614
/*******************************************************/

615
int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
616
{
617
    int ret, i;
618
    AVStream *st;
619 620 621 622 623 624

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

        if (pktl) {
            *pkt = pktl->pkt;
625
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
626 627 628 629 630
               !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;
631
                s->raw_packet_buffer = pktl->next;
632
                s->raw_packet_buffer_remaining_size += pkt->size;
633 634 635 636 637
                av_free(pktl);
                return 0;
            }
        }

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
638 639
        av_init_packet(pkt);
        ret= s->iformat->read_packet(s, pkt);
640 641 642 643 644 645 646
        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;
        }
647 648 649 650 651 652

        if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
            (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
            av_log(s, AV_LOG_WARNING,
                   "Dropped corrupted packet (stream = %d)\n",
                   pkt->stream_index);
653
            av_free_packet(pkt);
654 655 656
            continue;
        }

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
657
        st= s->streams[pkt->stream_index];
658

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
659
        switch(st->codec->codec_type){
660
        case AVMEDIA_TYPE_VIDEO:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
661 662
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
            break;
663
        case AVMEDIA_TYPE_AUDIO:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
664 665
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
            break;
666
        case AVMEDIA_TYPE_SUBTITLE:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
667 668 669
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
            break;
        }
670

671 672
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
                     !st->probe_packets))
673 674
            return ret;

675
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
676
        s->raw_packet_buffer_remaining_size -= pkt->size;
677

678 679
        if(st->codec->codec_id == CODEC_ID_PROBE){
            AVProbeData *pd = &st->probe_data;
680
            av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
681 682
            --st->probe_packets;

683 684 685 686 687
            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);

688
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
Diego Biurrun's avatar
Diego Biurrun committed
689
                //FIXME we do not reduce score to 0 for the case of running out of buffer space in bytes
690
                set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
691 692 693
                if(st->codec->codec_id != CODEC_ID_PROBE){
                    pd->buf_size=0;
                    av_freep(&pd->buf);
694
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
695
                }
696
            }
697 698
        }
    }
699 700
}

701 702 703 704 705 706 707 708
#if FF_API_READ_PACKET
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    return ff_read_packet(s, pkt);
}
#endif


709 710
/**********************************************************/

711
/**
Diego Biurrun's avatar
Diego Biurrun committed
712
 * Get the number of samples of an audio frame. Return -1 on error.
713
 */
714
static int get_audio_frame_size(AVCodecContext *enc, int size, int mux)
715 716 717
{
    int frame_size;

718 719 720
    /* give frame_size priority if demuxing */
    if (!mux && enc->frame_size > 1)
        return enc->frame_size;
721

722 723 724 725 726 727 728 729
    if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
        return frame_size;

    /* fallback to using frame_size if muxing */
    if (enc->frame_size > 1)
        return enc->frame_size;

    return -1;
730 731 732
}


733
/**
Diego Biurrun's avatar
Diego Biurrun committed
734
 * Return the frame duration in seconds. Return 0 if not available.
735
 */
736
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
737 738 739 740 741 742
                                   AVCodecParserContext *pc, AVPacket *pkt)
{
    int frame_size;

    *pnum = 0;
    *pden = 0;
743
    switch(st->codec->codec_type) {
744
    case AVMEDIA_TYPE_VIDEO:
745 746 747 748
        if (st->r_frame_rate.num) {
            *pnum = st->r_frame_rate.den;
            *pden = st->r_frame_rate.num;
        } else if(st->time_base.num*1000LL > st->time_base.den) {
749 750
            *pnum = st->time_base.num;
            *pden = st->time_base.den;
751 752 753
        }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;
754
            if (pc && pc->repeat_pict) {
755
                *pnum = (*pnum) * (1 + pc->repeat_pict);
756
            }
757 758 759 760 761
            //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
            //Thus if we have no parser in such case leave duration undefined.
            if(st->codec->ticks_per_frame>1 && !pc){
                *pnum = *pden = 0;
            }
762 763
        }
        break;
764
    case AVMEDIA_TYPE_AUDIO:
765
        frame_size = get_audio_frame_size(st->codec, pkt->size, 0);
766
        if (frame_size <= 0 || st->codec->sample_rate <= 0)
767 768
            break;
        *pnum = frame_size;
769
        *pden = st->codec->sample_rate;
770 771 772 773 774 775
        break;
    default:
        break;
    }
}

776
static int is_intra_only(AVCodecContext *enc){
777
    if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
778
        return 1;
779
    }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
780 781 782 783
        switch(enc->codec_id){
        case CODEC_ID_MJPEG:
        case CODEC_ID_MJPEGB:
        case CODEC_ID_LJPEG:
784
        case CODEC_ID_PRORES:
785 786 787
        case CODEC_ID_RAWVIDEO:
        case CODEC_ID_DVVIDEO:
        case CODEC_ID_HUFFYUV:
Loren Merritt's avatar
Loren Merritt committed
788
        case CODEC_ID_FFVHUFF:
789 790 791
        case CODEC_ID_ASV1:
        case CODEC_ID_ASV2:
        case CODEC_ID_VCR1:
Baptiste Coudurier's avatar
Baptiste Coudurier committed
792
        case CODEC_ID_DNXHD:
793
        case CODEC_ID_JPEG2000:
794
        case CODEC_ID_MDEC:
795 796 797 798 799 800 801
            return 1;
        default: break;
        }
    }
    return 0;
}

802 803 804
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
                                      int64_t dts, int64_t pts)
{
805 806 807
    AVStream *st= s->streams[stream_index];
    AVPacketList *pktl= s->packet_buffer;

808
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
809 810 811 812 813 814 815 816 817 818 819 820 821 822
        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;
823 824 825

        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
            st->start_time= pktl->pkt.pts;
826
    }
827 828
    if (st->start_time == AV_NOPTS_VALUE)
        st->start_time = pts;
829 830
}

831 832
static void update_initial_durations(AVFormatContext *s, AVStream *st,
                                     int stream_index, int duration)
833 834
{
    AVPacketList *pktl= s->packet_buffer;
835 836 837 838 839
    int64_t cur_dts= 0;

    if(st->first_dts != AV_NOPTS_VALUE){
        cur_dts= st->first_dts;
        for(; pktl; pktl= pktl->next){
840
            if(pktl->pkt.stream_index == stream_index){
841 842
                if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
                    break;
843
                cur_dts -= duration;
844 845 846 847 848 849
            }
        }
        pktl= s->packet_buffer;
        st->first_dts = cur_dts;
    }else if(st->cur_dts)
        return;
850 851

    for(; pktl; pktl= pktl->next){
852
        if(pktl->pkt.stream_index != stream_index)
853
            continue;
854 855
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
           && !pktl->pkt.duration){
856
            pktl->pkt.dts= cur_dts;
857
            if(!st->codec->has_b_frames)
858
                pktl->pkt.pts= cur_dts;
859 860 861
            cur_dts += duration;
            if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
                pktl->pkt.duration = duration;
862 863 864
        }else
            break;
    }
865 866
    if(st->first_dts == AV_NOPTS_VALUE)
        st->cur_dts= cur_dts;
867 868
}

869
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
870 871
                               AVCodecParserContext *pc, AVPacket *pkt)
{
872
    int num, den, presentation_delayed, delay, i;
873
    int64_t offset;
874

875 876 877
    if (s->flags & AVFMT_FLAG_NOFILLIN)
        return;

878 879 880
    if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
        pkt->dts= AV_NOPTS_VALUE;

881 882 883
    /* do we have a video B-frame ? */
    delay= st->codec->has_b_frames;
    presentation_delayed = 0;