utils.c 121 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 "avio_internal.h"
23
#include "internal.h"
24
#include "libavcodec/internal.h"
25
#include "libavutil/opt.h"
26
#include "metadata.h"
27
#include "id3v2.h"
28
#include "libavutil/avstring.h"
29
#include "riff.h"
Måns Rullgård's avatar
Måns Rullgård committed
30
#include "audiointerleave.h"
31 32
#include <sys/time.h>
#include <time.h>
33
#include <strings.h>
34 35 36 37
#include <stdarg.h>
#if CONFIG_NETWORK
#include "network.h"
#endif
38

39 40 41
#undef NDEBUG
#include <assert.h>

42
/**
43
 * @file
Diego Biurrun's avatar
Diego Biurrun committed
44
 * various utility functions for use within FFmpeg
45 46
 */

47 48 49 50 51
unsigned avformat_version(void)
{
    return LIBAVFORMAT_VERSION_INT;
}

52
const char *avformat_configuration(void)
53
{
54
    return LIBAV_CONFIGURATION;
55 56
}

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

Diego Biurrun's avatar
Diego Biurrun committed
113
/** head of registered input format linked list */
114 115 116
#if !FF_API_FIRST_FORMAT
static
#endif
117
AVInputFormat *first_iformat = NULL;
Diego Biurrun's avatar
Diego Biurrun committed
118
/** head of registered output format linked list */
119 120 121
#if !FF_API_FIRST_FORMAT
static
#endif
122
AVOutputFormat *first_oformat = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
123

124 125 126 127 128 129 130 131 132 133 134 135
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;
}

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

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

Michael Niedermayer's avatar
Michael Niedermayer committed
159 160
    if(!filename)
        return 0;
161

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

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
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);
}

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

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

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

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

        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
253
        stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
254 255 256 257 258 259 260

        if (stream_fmt)
            fmt = stream_fmt;
    }

    return fmt;
}
261
#endif
262

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

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

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

294
#if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
295 296 297 298 299 300 301 302 303
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
304

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
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
326

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

    if(ret<0)
        return ret;

334
    pkt->pos= avio_tell(s);
Michael Niedermayer's avatar
Michael Niedermayer committed
335

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

    return ret;
}

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

360

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

367
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
368
{
369
    AVProbeData lpd = *pd;
370
    AVInputFormat *fmt1 = NULL, *fmt;
371
    int score;
372

373 374 375 376 377 378 379 380
    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;
        }
    }

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

402 403 404 405 406
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
    int score=0;
    return av_probe_input_format2(pd, is_opened, &score);
}

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

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

439 440
/************************************************************/
/* input media file */
441

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

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

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

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

483
    // e.g. AVFMT_NOFILE formats will not have a AVIOContext
484 485 486
    if (ic->pb)
        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);

487
    if (ic->iformat->read_header) {
488 489 490
        err = ic->iformat->read_header(ic, ap);
        if (err < 0)
            goto fail;
491
    }
492

493
    if (pb && !ic->data_offset)
494
        ic->data_offset = avio_tell(ic->pb);
495

496
#if FF_API_OLD_METADATA
497 498 499
    ff_metadata_demux_compat(ic);
#endif

500 501
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

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

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

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

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

583
    if (!*fmt) {
584
        av_free(buf);
585 586 587
        return AVERROR_INVALIDDATA;
    }

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

592
    return ret;
593 594
}

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

605 606 607
    pd->filename = "";
    if (filename)
        pd->filename = filename;
608
    pd->buf = NULL;
609 610 611
    pd->buf_size = 0;

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

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

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

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

Fabrice Bellard's avatar
Fabrice Bellard committed
657 658
}

659 660
/*******************************************************/

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

667 668 669 670 671
    if (*packet_buffer)
        (*plast_pktl)->next = pktl;
    else
        *packet_buffer = pktl;

672 673 674 675 676 677
    /* add the packet in the buffered packet list */
    *plast_pktl = pktl;
    pktl->pkt= *pkt;
    return &pktl->pkt;
}

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

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

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

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

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

724 725
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
                     !st->probe_packets))
726 727
            return ret;

728
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
729
        s->raw_packet_buffer_remaining_size -= pkt->size;
730

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

736 737 738 739 740
            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);

741
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
742 743
                //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
744 745 746
                if(st->codec->codec_id != CODEC_ID_PROBE){
                    pd->buf_size=0;
                    av_freep(&pd->buf);
747
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
748
                }
749
            }
750 751
        }
    }
752 753 754 755
}

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

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

763 764 765
    if(enc->codec_id == CODEC_ID_VORBIS)
        return -1;

766
    if (enc->frame_size <= 1) {
767 768 769
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);

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


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

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

826
static int is_intra_only(AVCodecContext *enc){
827
    if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
828
        return 1;
829
    }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
830 831 832 833 834 835 836
        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
837
        case CODEC_ID_FFVHUFF:
838 839 840
        case CODEC_ID_ASV1:
        case CODEC_ID_ASV2:
        case CODEC_ID_VCR1:
Baptiste Coudurier's avatar
Baptiste Coudurier committed
841
        case CODEC_ID_DNXHD:
842
        case CODEC_ID_JPEG2000: