utils.c 123 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 "libavutil/opt.h"
29
#include "metadata.h"
30
#include "id3v2.h"
31
#include "libavutil/avstring.h"
32
#include "riff.h"
Måns Rullgård's avatar
Måns Rullgård committed
33
#include "audiointerleave.h"
34 35
#include <sys/time.h>
#include <time.h>
36
#include <strings.h>
37 38 39 40
#include <stdarg.h>
#if CONFIG_NETWORK
#include "network.h"
#endif
41

42 43 44
#undef NDEBUG
#include <assert.h>

45
/**
46
 * @file
47
 * various utility functions for use within Libav
48 49
 */

50 51 52 53 54
unsigned avformat_version(void)
{
    return LIBAVFORMAT_VERSION_INT;
}

55
const char *avformat_configuration(void)
56
{
57
    return LIBAV_CONFIGURATION;
58 59
}

60
const char *avformat_license(void)
61 62
{
#define LICENSE_PREFIX "libavformat license: "
63
    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
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 109 110 111 112 113 114
/* 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;
}
115

Diego Biurrun's avatar
Diego Biurrun committed
116
/** head of registered input format linked list */
117 118 119
#if !FF_API_FIRST_FORMAT
static
#endif
120
AVInputFormat *first_iformat = NULL;
Diego Biurrun's avatar
Diego Biurrun committed
121
/** head of registered output format linked list */
122 123 124
#if !FF_API_FIRST_FORMAT
static
#endif
125
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 (!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 195 196 197 198 199 200 201
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);
}

202
#if FF_API_GUESS_FORMAT
203
AVOutputFormat *guess_format(const char *short_name, const char *filename,
204
                             const char *mime_type)
205 206 207 208 209 210 211
{
    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
212
{
213
    AVOutputFormat *fmt = NULL, *fmt_found;
Fabrice Bellard's avatar
Fabrice Bellard committed
214 215
    int score_max, score;

Fabrice Bellard's avatar
Fabrice Bellard committed
216
    /* specific test for image sequences */
217
#if CONFIG_IMAGE2_MUXER
218
    if (!short_name && filename &&
219
        av_filename_number_test(filename) &&
220
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
221
        return av_guess_format("image2", NULL, NULL);
222
    }
223
#endif
Diego Biurrun's avatar
Diego Biurrun committed
224
    /* Find the proper file type. */
Fabrice Bellard's avatar
Fabrice Bellard committed
225 226
    fmt_found = NULL;
    score_max = 0;
227
    while ((fmt = av_oformat_next(fmt))) {
Fabrice Bellard's avatar
Fabrice Bellard committed
228 229 230 231 232
        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;
233
        if (filename && fmt->extensions &&
234
            av_match_ext(filename, fmt->extensions)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
235 236 237 238 239 240 241 242
            score += 5;
        }
        if (score > score_max) {
            score_max = score;
            fmt_found = fmt;
        }
    }
    return fmt_found;
243
}
Fabrice Bellard's avatar
Fabrice Bellard committed
244

245
#if FF_API_GUESS_FORMAT
246
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
247 248
                             const char *mime_type)
{
249
    AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
250 251 252 253 254 255

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

        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
256
        stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
257 258 259 260 261 262 263

        if (stream_fmt)
            fmt = stream_fmt;
    }

    return fmt;
}
264
#endif
265

266
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
267 268
                            const char *filename, const char *mime_type, enum AVMediaType type){
    if(type == AVMEDIA_TYPE_VIDEO){
269 270
        enum CodecID codec_id= CODEC_ID_NONE;

271
#if CONFIG_IMAGE2_MUXER
272
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
273 274
            codec_id= av_guess_image2_codec(filename);
        }
275
#endif
276 277 278
        if(codec_id == CODEC_ID_NONE)
            codec_id= fmt->video_codec;
        return codec_id;
279
    }else if(type == AVMEDIA_TYPE_AUDIO)
280
        return fmt->audio_codec;
281 282
    else if (type == AVMEDIA_TYPE_SUBTITLE)
        return fmt->subtitle_codec;
283 284 285 286
    else
        return CODEC_ID_NONE;
}

287 288
AVInputFormat *av_find_input_format(const char *short_name)
{
289 290
    AVInputFormat *fmt = NULL;
    while ((fmt = av_iformat_next(fmt))) {
291
        if (match_format(short_name, fmt->name))
292 293 294 295 296
            return fmt;
    }
    return NULL;
}

297
#if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
298 299 300 301 302 303 304 305 306
FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
{
    av_destruct_packet_nofree(pkt);
}

FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
{
    av_destruct_packet(pkt);
}
Fabrice Bellard's avatar
Fabrice Bellard committed
307

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
{
    return av_new_packet(pkt, size);
}

FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
{
    return av_dup_packet(pkt);
}

FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
{
    av_free_packet(pkt);
}

FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
{
    av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
    av_init_packet(pkt);
}
#endif
Fabrice Bellard's avatar
Fabrice Bellard committed
329

330
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Michael Niedermayer's avatar
Michael Niedermayer committed
331 332 333 334 335 336
{
    int ret= av_new_packet(pkt, size);

    if(ret<0)
        return ret;

337
    pkt->pos= avio_tell(s);
Michael Niedermayer's avatar
Michael Niedermayer committed
338

339
    ret= avio_read(s, pkt->data, size);
Michael Niedermayer's avatar
Michael Niedermayer committed
340 341 342
    if(ret<=0)
        av_free_packet(pkt);
    else
343
        av_shrink_packet(pkt, ret);
Michael Niedermayer's avatar
Michael Niedermayer committed
344 345 346 347

    return ret;
}

348
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
349 350 351 352 353 354 355 356 357
{
    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;
358
    ret = avio_read(s, pkt->data + old_size, size);
359 360 361 362
    av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
    return ret;
}

363

364
int av_filename_number_test(const char *filename)
365 366
{
    char buf[1024];
367
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
368 369
}

370
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
371
{
372
    AVProbeData lpd = *pd;
373
    AVInputFormat *fmt1 = NULL, *fmt;
374
    int score;
375

376 377 378 379 380 381 382 383
    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;
        }
    }

384
    fmt = NULL;
385
    while ((fmt1 = av_iformat_next(fmt1))) {
386
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
387 388
            continue;
        score = 0;
389
        if (fmt1->read_probe) {
390
            score = fmt1->read_probe(&lpd);
391
        } else if (fmt1->extensions) {
392
            if (av_match_ext(lpd.filename, fmt1->extensions)) {
393 394
                score = 50;
            }
395
        }
396 397
        if (score > *score_max) {
            *score_max = score;
398
            fmt = fmt1;
399 400
        }else if (score == *score_max)
            fmt = NULL;
401 402 403 404
    }
    return fmt;
}

405 406 407 408 409
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
    int score=0;
    return av_probe_input_format2(pd, is_opened, &score);
}

410
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
411
{
412 413 414 415 416 417 418 419 420 421 422 423 424 425
    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);
426 427

    if (fmt) {
428
        int i;
429 430
        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);
431 432 433 434 435 436
        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;
            }
437
        }
438 439 440 441
    }
    return !!fmt;
}

442 443
/************************************************************/
/* input media file */
444

445
/**
446
 * Open a media file from an IO stream. 'fmt' must be specified.
447
 */
448
int av_open_input_stream(AVFormatContext **ic_ptr,
449
                         AVIOContext *pb, const char *filename,
450 451 452 453
                         AVInputFormat *fmt, AVFormatParameters *ap)
{
    int err;
    AVFormatContext *ic;
454 455 456 457 458 459
    AVFormatParameters default_ap;

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

461
    if(!ap->prealloced_context)
462
        ic = avformat_alloc_context();
463 464
    else
        ic = *ic_ptr;
465
    if (!ic) {
466
        err = AVERROR(ENOMEM);
467 468 469
        goto fail;
    }
    ic->iformat = fmt;
470
    ic->pb = pb;
471 472
    ic->duration = AV_NOPTS_VALUE;
    ic->start_time = AV_NOPTS_VALUE;
Måns Rullgård's avatar
Måns Rullgård committed
473
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
474 475 476 477 478

    /* allocate private data */
    if (fmt->priv_data_size > 0) {
        ic->priv_data = av_mallocz(fmt->priv_data_size);
        if (!ic->priv_data) {
479
            err = AVERROR(ENOMEM);
480 481 482 483 484 485
            goto fail;
        }
    } else {
        ic->priv_data = NULL;
    }

486
    // e.g. AVFMT_NOFILE formats will not have a AVIOContext
487 488 489
    if (ic->pb)
        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);

490
    if (ic->iformat->read_header) {
491 492 493
        err = ic->iformat->read_header(ic, ap);
        if (err < 0)
            goto fail;
494
    }
495

496
    if (pb && !ic->data_offset)
497
        ic->data_offset = avio_tell(ic->pb);
498

499
#if FF_API_OLD_METADATA
500 501 502
    ff_metadata_demux_compat(ic);
#endif

503 504
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

505 506 507 508
    *ic_ptr = ic;
    return 0;
 fail:
    if (ic) {
509
        int i;
510
        av_freep(&ic->priv_data);
511 512 513 514 515
        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);
516
                av_free(st->codec);
517
                av_free(st->info);
518 519 520
            }
            av_free(st);
        }
521 522 523 524 525 526
    }
    av_free(ic);
    *ic_ptr = NULL;
    return err;
}

Diego Biurrun's avatar
Diego Biurrun committed
527
/** size of probe buffer, for guessing file type from file contents */
528
#define PROBE_BUF_MIN 2048
529
#define PROBE_BUF_MAX (1<<20)
530

531
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
                          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);
    }

551 552
    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0;
        probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
553 554 555 556 557 558 559 560 561
        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);
562
        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
563 564 565 566 567 568
            /* fail if error was not end of file, otherwise, lower score */
            if (ret != AVERROR_EOF) {
                av_free(buf);
                return ret;
            }
            score = 0;
569
            ret = 0;            /* error was end of file, nothing read */
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
        }
        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);
        }
    }

586
    if (!*fmt) {
587
        av_free(buf);
588 589 590
        return AVERROR_INVALIDDATA;
    }

591
    /* rewind. reuse probe buffer to avoid seeking */
592
    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
593
        av_free(buf);
594

595
    return ret;
596 597
}

598
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
599 600 601
                       AVInputFormat *fmt,
                       int buf_size,
                       AVFormatParameters *ap)
Fabrice Bellard's avatar
Fabrice Bellard committed
602
{
603
    int err;
604
    AVProbeData probe_data, *pd = &probe_data;
605
    AVIOContext *pb = NULL;
606
    void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
607

608 609 610
    pd->filename = "";
    if (filename)
        pd->filename = filename;
611
    pd->buf = NULL;
612 613 614
    pd->buf_size = 0;

    if (!fmt) {
Diego Biurrun's avatar
Diego Biurrun committed
615
        /* guess format if no file can be opened */
616
        fmt = av_probe_input_format(pd, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
617 618
    }

Diego Biurrun's avatar
Diego Biurrun committed
619
    /* Do not open file if the format does not need it. XXX: specific
Fabrice Bellard's avatar
Fabrice Bellard committed
620
       hack needed to handle RTSP/TCP */
621
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
622
        /* if no file needed do not try to open one */
623
        if ((err=avio_open(&pb, filename, URL_RDONLY)) < 0) {
624
            goto fail;
625
        }
626
        if (buf_size > 0) {
627
            ffio_set_buf_size(pb, buf_size);
628
        }
629
        if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
630
            goto fail;
631
        }
632 633 634 635
    }

    /* if still no format found, error */
    if (!fmt) {
636
        err = AVERROR_INVALIDDATA;
637
        goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
638
    }
639

Diego Biurrun's avatar
Diego Biurrun committed
640
    /* check filename in case an image number is expected */
641
    if (fmt->flags & AVFMT_NEEDNUMBER) {
642
        if (!av_filename_number_test(filename)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
643
            err = AVERROR_NUMEXPECTED;
644
            goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
645 646
        }
    }
647 648 649
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
    if (err)
        goto fail;
650
    return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
651
 fail:
652
    av_freep(&pd->buf);
653
    if (pb)
654
        avio_close(pb);
655 656 657
    if (ap && ap->prealloced_context)
        av_free(*ic_ptr);
    *ic_ptr = NULL;
658
    return err;
659

Fabrice Bellard's avatar
Fabrice Bellard committed
660 661
}

662 663
/*******************************************************/

664 665 666
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
                               AVPacketList **plast_pktl){
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
667 668 669
    if (!pktl)
        return NULL;

670 671 672 673 674
    if (*packet_buffer)
        (*plast_pktl)->next = pktl;
    else
        *packet_buffer = pktl;

675 676 677 678 679 680
    /* add the packet in the buffered packet list */
    *plast_pktl = pktl;
    pktl->pkt= *pkt;
    return &pktl->pkt;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
681
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
682
{
683
    int ret, i;
684
    AVStream *st;
685 686 687 688 689 690

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

        if (pktl) {
            *pkt = pktl->pkt;
691
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
692 693 694 695 696
               !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;
697
                s->raw_packet_buffer = pktl->next;
698
                s->raw_packet_buffer_remaining_size += pkt->size;
699 700 701 702 703
                av_free(pktl);
                return 0;
            }
        }

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
704 705
        av_init_packet(pkt);
        ret= s->iformat->read_packet(s, pkt);
706 707 708 709 710 711 712
        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
713
        st= s->streams[pkt->stream_index];
714

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
715
        switch(st->codec->codec_type){
716
        case AVMEDIA_TYPE_VIDEO:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
717 718
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
            break;
719
        case AVMEDIA_TYPE_AUDIO:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
720 721
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
            break;
722
        case AVMEDIA_TYPE_SUBTITLE:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
723 724 725
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
            break;
        }
726

727 728
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
                     !st->probe_packets))
729 730
            return ret;

731
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
732
        s->raw_packet_buffer_remaining_size -= pkt->size;
733

734 735
        if(st->codec->codec_id == CODEC_ID_PROBE){
            AVProbeData *pd = &st->probe_data;
736
            av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
737 738
            --st->probe_packets;

739 740 741 742 743
            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);

744
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
745 746
                //FIXME we dont reduce score to 0 for the case of running out of buffer space in bytes
                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
747 748 749
                if(st->codec->codec_id != CODEC_ID_PROBE){
                    pd->buf_size=0;
                    av_freep(&pd->buf);
750
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
751
                }
752
            }
753 754
        }
    }
755 756 757 758
}

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

759
/**
Diego Biurrun's avatar
Diego Biurrun committed
760
 * Get the number of samples of an audio frame. Return -1 on error.
761
 */
762 763 764 765
static int get_audio_frame_size(AVCodecContext *enc, int size)
{
    int frame_size;

766 767 768
    if(enc->codec_id == CODEC_ID_VORBIS)
        return -1;

769
    if (enc->frame_size <= 1) {
770 771 772
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);

        if (bits_per_sample) {
773 774
            if (enc->channels == 0)
                return -1;
775
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
776
        } else {
777 778 779
            /* used for example by ADPCM codecs */
            if (enc->bit_rate == 0)
                return -1;
780
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
781 782 783 784 785 786 787 788
        }
    } else {
        frame_size = enc->frame_size;
    }
    return frame_size;
}


789
/**
Diego Biurrun's avatar
Diego Biurrun committed
790
 * Return the frame duration in seconds. Return 0 if not available.
791
 */
792
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
793 794 795 796 797 798
                                   AVCodecParserContext *pc, AVPacket *pkt)
{
    int frame_size;

    *pnum = 0;
    *pden = 0;
799
    switch(st->codec->codec_type) {
800
    case AVMEDIA_TYPE_VIDEO:
Michael Niedermayer's avatar
Michael Niedermayer committed
801
        if(st->time_base.num*1000LL > st->time_base.den){
802 803
            *pnum = st->time_base.num;
            *pden = st->time_base.den;
804 805 806
        }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;
807
            if (pc && pc->repeat_pict) {
808
                *pnum = (*pnum) * (1 + pc->repeat_pict);
809
            }
810 811 812 813 814
            //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;
            }
815 816
        }
        break;
817
    case AVMEDIA_TYPE_AUDIO:
818
        frame_size = get_audio_frame_size(st->codec, pkt->size);
819
        if (frame_size <= 0 || st->codec->sample_rate <= 0)
820 821
            break;
        *pnum = frame_size;
822
        *pden = st->codec->sample_rate;
823 824 825 826 827 828
        break;
    default:
        break;
    }
}

829
static int is_intra_only(AVCodecContext *enc){
830
    if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
831
        return 1;
832
    }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
833 834 835 836 837 838 839
        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
840
        case CODEC_ID_FFVHUFF: