utils.c 124 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
Diego Biurrun's avatar
Diego Biurrun committed
2
 * various utility functions for use within FFmpeg
Fabrice Bellard's avatar
Fabrice Bellard committed
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
Fabrice Bellard's avatar
Fabrice Bellard committed
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Fabrice Bellard's avatar
Fabrice Bellard committed
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
16
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 */
Fabrice Bellard's avatar
Fabrice Bellard committed
21
#include "avformat.h"
22
#include "internal.h"
23
#include "libavcodec/internal.h"
24
#include "libavutil/opt.h"
25
#include "metadata.h"
26
#include "id3v2.h"
27
#include "libavutil/avstring.h"
28
#include "riff.h"
Måns Rullgård's avatar
Måns Rullgård committed
29
#include "audiointerleave.h"
30 31
#include <sys/time.h>
#include <time.h>
32
#include <strings.h>
33 34 35 36
#include <stdarg.h>
#if CONFIG_NETWORK
#include "network.h"
#endif
37

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

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

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

51
const char *avformat_configuration(void)
52 53 54 55
{
    return FFMPEG_CONFIGURATION;
}

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

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
/* 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;
}
111

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

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

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

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

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

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

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

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

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

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

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

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

        if (stream_fmt)
            fmt = stream_fmt;
    }

    return fmt;
}
260
#endif
261

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

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

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

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

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

Michael Niedermayer's avatar
Michael Niedermayer committed
326 327 328 329 330 331 332 333 334 335 336 337 338
int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
{
    int ret= av_new_packet(pkt, size);

    if(ret<0)
        return ret;

    pkt->pos= url_ftell(s);

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

    return ret;
}

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

359

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

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

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

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

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

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

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

438 439
/************************************************************/
/* input media file */
440

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

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

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

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

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

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

492
    if (pb && !ic->data_offset)
493
        ic->data_offset = url_ftell(ic->pb);
494

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

499 500
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

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

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

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

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

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

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

591
    return ret;
592 593
}

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

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

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

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

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

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

Fabrice Bellard's avatar
Fabrice Bellard committed
656 657
}

658 659
/*******************************************************/

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

849 850 851
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
                                      int64_t dts, int64_t pts)
{
852 853 854
    AVStream *st= s->streams[stream_index];
    AVPacketList *pktl= s->packet_buffer;

855
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
856 857 858 859 860 861 862 863 864 865 866 867 868 869
        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;
870 871 872

        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
            st->start_time= pktl->pkt.pts;
873
    }
874 875
    if (st->start_time == AV_NOPTS_VALUE)
        st->start_time = pts;
876 877
}

878 879 880
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
    AVPacketList *pktl= s->packet_buffer;
881 882 883