utils.c 124 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
#include "url.h"
35 36
#include <sys/time.h>
#include <time.h>
37
#include <strings.h>
38 39 40 41
#include <stdarg.h>
#if CONFIG_NETWORK
#include "network.h"
#endif
42

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

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

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

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

61
const char *avformat_license(void)
62 63
{
#define LICENSE_PREFIX "libavformat license: "
64
    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
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 115
/* 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;
}
116

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

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

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

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

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

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

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
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);
}

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

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

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

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

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

        if (stream_fmt)
            fmt = stream_fmt;
    }

    return fmt;
}
265
#endif
266

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

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

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

298
#if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
299 300 301 302 303 304 305 306 307
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
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
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
330

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

    if(ret<0)
        return ret;

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

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

    return ret;
}

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

364

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

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

377 378 379 380 381 382
    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;
        }
383
        id3 = 1;
384 385
    }

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

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

414 415 416
    return fmt;
}

417 418 419 420 421
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
    int score=0;
    return av_probe_input_format2(pd, is_opened, &score);
}

422
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
423
{
424 425 426 427 428 429 430 431 432 433 434 435 436 437
    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);
438 439

    if (fmt) {
440
        int i;
441 442
        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);
443 444 445 446 447 448
        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;
            }
449
        }
450 451 452 453
    }
    return !!fmt;
}

454 455
/************************************************************/
/* input media file */
456

457
/**
458
 * Open a media file from an IO stream. 'fmt' must be specified.
459
 */
460
int av_open_input_stream(AVFormatContext **ic_ptr,
461
                         AVIOContext *pb, const char *filename,
462 463 464 465
                         AVInputFormat *fmt, AVFormatParameters *ap)
{
    int err;
    AVFormatContext *ic;
466 467 468 469 470 471
    AVFormatParameters default_ap;

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

473
    if(!ap->prealloced_context)
474
        ic = avformat_alloc_context();
475 476
    else
        ic = *ic_ptr;
477
    if (!ic) {
478
        err = AVERROR(ENOMEM);
479 480 481
        goto fail;
    }
    ic->iformat = fmt;
482
    ic->pb = pb;
483 484
    ic->duration = AV_NOPTS_VALUE;
    ic->start_time = AV_NOPTS_VALUE;
Måns Rullgård's avatar
Måns Rullgård committed
485
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
486 487 488 489 490

    /* allocate private data */
    if (fmt->priv_data_size > 0) {
        ic->priv_data = av_mallocz(fmt->priv_data_size);
        if (!ic->priv_data) {
491
            err = AVERROR(ENOMEM);
492 493 494 495 496 497
            goto fail;
        }
    } else {
        ic->priv_data = NULL;
    }

498
    // e.g. AVFMT_NOFILE formats will not have a AVIOContext
499 500 501
    if (ic->pb)
        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);

502
    if (ic->iformat->read_header) {
503 504 505
        err = ic->iformat->read_header(ic, ap);
        if (err < 0)
            goto fail;
506
    }
507

508
    if (pb && !ic->data_offset)
509
        ic->data_offset = avio_tell(ic->pb);
510

511
#if FF_API_OLD_METADATA
512 513 514
    ff_metadata_demux_compat(ic);
#endif

515 516
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

517 518 519 520
    *ic_ptr = ic;
    return 0;
 fail:
    if (ic) {
521
        int i;
522
        av_freep(&ic->priv_data);
523 524 525 526 527
        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);
528
                av_free(st->codec);
529
                av_free(st->info);
530 531 532
            }
            av_free(st);
        }
533 534 535 536 537 538
    }
    av_free(ic);
    *ic_ptr = NULL;
    return err;
}

Diego Biurrun's avatar
Diego Biurrun committed
539
/** size of probe buffer, for guessing file type from file contents */
540
#define PROBE_BUF_MIN 2048
541
#define PROBE_BUF_MAX (1<<20)
542

543
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
                          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);
    }

563 564
    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))) {
565 566 567 568 569 570 571 572 573
        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);
574
        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
575 576 577 578 579 580
            /* fail if error was not end of file, otherwise, lower score */
            if (ret != AVERROR_EOF) {
                av_free(buf);
                return ret;
            }
            score = 0;
581
            ret = 0;            /* error was end of file, nothing read */
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        }
        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);
        }
    }

598
    if (!*fmt) {
599
        av_free(buf);
600 601 602
        return AVERROR_INVALIDDATA;
    }

603
    /* rewind. reuse probe buffer to avoid seeking */
604
    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
605
        av_free(buf);
606

607
    return ret;
608 609
}

610
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
611 612 613
                       AVInputFormat *fmt,
                       int buf_size,
                       AVFormatParameters *ap)
Fabrice Bellard's avatar
Fabrice Bellard committed
614
{
615
    int err;
616
    AVProbeData probe_data, *pd = &probe_data;
617
    AVIOContext *pb = NULL;
618
    void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
619

620 621 622
    pd->filename = "";
    if (filename)
        pd->filename = filename;
623
    pd->buf = NULL;
624 625 626
    pd->buf_size = 0;

    if (!fmt) {
Diego Biurrun's avatar
Diego Biurrun committed
627
        /* guess format if no file can be opened */
628
        fmt = av_probe_input_format(pd, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
629 630
    }

Diego Biurrun's avatar
Diego Biurrun committed
631
    /* Do not open file if the format does not need it. XXX: specific
Fabrice Bellard's avatar
Fabrice Bellard committed
632
       hack needed to handle RTSP/TCP */
633
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
634
        /* if no file needed do not try to open one */
635
        if ((err=avio_open(&pb, filename, AVIO_RDONLY)) < 0) {
636
            goto fail;
637
        }
638
        if (buf_size > 0) {
639
            ffio_set_buf_size(pb, buf_size);
640
        }
641
        if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
642
            goto fail;
643
        }
644 645 646 647
    }

    /* if still no format found, error */
    if (!fmt) {
648
        err = AVERROR_INVALIDDATA;
649
        goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
650
    }
651

Diego Biurrun's avatar
Diego Biurrun committed
652
    /* check filename in case an image number is expected */
653
    if (fmt->flags & AVFMT_NEEDNUMBER) {
654
        if (!av_filename_number_test(filename)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
655
            err = AVERROR_NUMEXPECTED;
656
            goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
657 658
        }
    }
659 660 661
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
    if (err)
        goto fail;
662
    return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
663
 fail:
664
    av_freep(&pd->buf);
665
    if (pb)
666
        avio_close(pb);
667 668 669
    if (ap && ap->prealloced_context)
        av_free(*ic_ptr);
    *ic_ptr = NULL;
670
    return err;
671

Fabrice Bellard's avatar
Fabrice Bellard committed
672 673
}

674 675
/*******************************************************/

676 677 678
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
                               AVPacketList **plast_pktl){
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
679 680 681
    if (!pktl)
        return NULL;

682 683 684 685 686
    if (*packet_buffer)
        (*plast_pktl)->next = pktl;
    else
        *packet_buffer = pktl;

687 688 689 690 691 692
    /* add the packet in the buffered packet list */
    *plast_pktl = pktl;
    pktl->pkt= *pkt;
    return &pktl->pkt;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
693
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
694
{
695
    int ret, i;
696
    AVStream *st;
697 698 699 700 701 702

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

        if (pktl) {
            *pkt = pktl->pkt;
703
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
704 705 706 707 708
               !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;
709
                s->raw_packet_buffer = pktl->next;
710
                s->raw_packet_buffer_remaining_size += pkt->size;
711 712 713 714 715
                av_free(pktl);
                return 0;
            }
        }

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
716 717
        av_init_packet(pkt);
        ret= s->iformat->read_packet(s, pkt);
718 719 720 721 722 723 724
        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
725
        st= s->streams[pkt->stream_index];
726

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
727
        switch(st->codec->codec_type){
728
        case AVMEDIA_TYPE_VIDEO:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
729 730
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
            break;
731
        case AVMEDIA_TYPE_AUDIO:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
732 733
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
            break;
734
        case AVMEDIA_TYPE_SUBTITLE:
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
735 736 737
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
            break;
        }
738

739 740
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
                     !st->probe_packets))
741 742
            return ret;

743
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
744
        s->raw_packet_buffer_remaining_size -= pkt->size;
745

746 747
        if(st->codec->codec_id == CODEC_ID_PROBE){
            AVProbeData *pd = &st->probe_data;
748
            av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
749 750
            --st->probe_packets;

751 752 753 754 755
            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);

756
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
757 758
                //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
759 760 761
                if(st->codec->codec_id != CODEC_ID_PROBE){
                    pd->buf_size=0;
                    av_freep(&pd->buf);
762
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
763
                }
764
            }
765 766
        }
    }
767 768 769 770
}

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

771
/**
Diego Biurrun's avatar
Diego Biurrun committed
772
 * Get the number of samples of an audio frame. Return -1 on error.
773
 */
774 775 776 777
static int get_audio_frame_size(AVCodecContext *enc, int size)
{
    int frame_size;

778 779 780
    if(enc->codec_id == CODEC_ID_VORBIS)
        return -1;

781
    if (enc->frame_size <= 1) {
782 783 784
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);

        if (bits_per_sample) {
785 786
            if (enc->channels == 0)
                return -1;
787
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
788
        } else {
789 790 791
            /* used for example by ADPCM codecs */
            if (enc->bit_rate == 0)
                return -1;
792
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
793 794 795 796 797 798 799 800
        }
    } else {
        frame_size = enc->frame_size;
    }
    return frame_size;
}


801
/**
Diego Biurrun's avatar
Diego Biurrun committed
802
 * Return the frame duration in seconds. Return 0 if not available.
803
 */
804
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
805 806 807 808 809 810
                                   AVCodecParserContext *pc, AVPacket *pkt)
{
    int frame_size;

    *pnum = 0;
    *pden = 0;
811
    switch(st->codec->codec_type) {
812
    case AVMEDIA_TYPE_VIDEO:
Michael Niedermayer's avatar
Michael Niedermayer committed
813
        if(st->time_base.num*1000LL > st->time_base.den){
814 815
            *pnum = st->time_base.num;
            *pden = st->time_base.den;
816 817 818
        }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;
819
            if (pc && pc->repeat_pict) {
820
                *pnum = (*pnum) * (1 + pc->repeat_pict);
821
            }
822 823 824 825 826
            //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;
            }
827 828
        }
        break;
829
    case AVMEDIA_TYPE_AUDIO:
830
        frame_size = get_audio_frame_size(st->codec, pkt->size);
831
        if (frame_size <= 0 || st->codec->sample_rate <= 0)
832 833
            break;
        *pnum = frame_size;
834
        *pden = st->codec->sample_rate;
835 836 837 838 839 840
        break;
    default:
        break;
    }
}