utils.c 121 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
static AVInputFormat *first_iformat = NULL;
Diego Biurrun's avatar
Diego Biurrun committed
119
/** head of registered output format linked list */
120
static AVOutputFormat *first_oformat = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
121

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

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

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

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

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

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

197 198
AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
                                const char *mime_type)
Fabrice Bellard's avatar
Fabrice Bellard committed
199
{
200
    AVOutputFormat *fmt = NULL, *fmt_found;
Fabrice Bellard's avatar
Fabrice Bellard committed
201 202
    int score_max, score;

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

232
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
233 234
                            const char *filename, const char *mime_type, enum AVMediaType type){
    if(type == AVMEDIA_TYPE_VIDEO){
235 236
        enum CodecID codec_id= CODEC_ID_NONE;

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

253 254
AVInputFormat *av_find_input_format(const char *short_name)
{
255 256
    AVInputFormat *fmt = NULL;
    while ((fmt = av_iformat_next(fmt))) {
257
        if (match_format(short_name, fmt->name))
258 259 260 261 262
            return fmt;
    }
    return NULL;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
263

264
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Michael Niedermayer's avatar
Michael Niedermayer committed
265 266 267 268 269 270
{
    int ret= av_new_packet(pkt, size);

    if(ret<0)
        return ret;

271
    pkt->pos= avio_tell(s);
Michael Niedermayer's avatar
Michael Niedermayer committed
272

273
    ret= avio_read(s, pkt->data, size);
Michael Niedermayer's avatar
Michael Niedermayer committed
274 275 276
    if(ret<=0)
        av_free_packet(pkt);
    else
277
        av_shrink_packet(pkt, ret);
Michael Niedermayer's avatar
Michael Niedermayer committed
278 279 280 281

    return ret;
}

282
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
283 284 285 286 287 288 289 290 291
{
    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;
292
    ret = avio_read(s, pkt->data + old_size, size);
293 294 295 296
    av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
    return ret;
}

297

298
int av_filename_number_test(const char *filename)
299 300
{
    char buf[1024];
301
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
302 303
}

304
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
305
{
306
    AVProbeData lpd = *pd;
307
    AVInputFormat *fmt1 = NULL, *fmt;
308
    int score, id3 = 0;
309

310 311 312 313 314 315
    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;
        }
316
        id3 = 1;
317 318
    }

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

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

347 348 349
    return fmt;
}

350 351 352 353 354
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
    int score=0;
    return av_probe_input_format2(pd, is_opened, &score);
}

355
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
356
{
357 358 359 360 361 362 363 364 365 366 367 368 369 370
    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);
371 372

    if (fmt) {
373
        int i;
374 375
        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);
376 377 378 379 380 381
        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;
            }
382
        }
383 384 385 386
    }
    return !!fmt;
}

387 388
/************************************************************/
/* input media file */
389

390
/**
391
 * Open a media file from an IO stream. 'fmt' must be specified.
392
 */
393
int av_open_input_stream(AVFormatContext **ic_ptr,
394
                         AVIOContext *pb, const char *filename,
395 396 397 398
                         AVInputFormat *fmt, AVFormatParameters *ap)
{
    int err;
    AVFormatContext *ic;
399 400 401 402 403 404
    AVFormatParameters default_ap;

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

406
    if(!ap->prealloced_context)
407
        ic = avformat_alloc_context();
408 409
    else
        ic = *ic_ptr;
410
    if (!ic) {
411
        err = AVERROR(ENOMEM);
412 413 414
        goto fail;
    }
    ic->iformat = fmt;
415
    ic->pb = pb;
416 417
    ic->duration = AV_NOPTS_VALUE;
    ic->start_time = AV_NOPTS_VALUE;
Måns Rullgård's avatar
Måns Rullgård committed
418
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
419 420 421 422 423

    /* allocate private data */
    if (fmt->priv_data_size > 0) {
        ic->priv_data = av_mallocz(fmt->priv_data_size);
        if (!ic->priv_data) {
424
            err = AVERROR(ENOMEM);
425 426 427 428 429 430
            goto fail;
        }
    } else {
        ic->priv_data = NULL;
    }

431
    // e.g. AVFMT_NOFILE formats will not have a AVIOContext
432 433 434
    if (ic->pb)
        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);

435
    if (ic->iformat->read_header) {
436 437 438
        err = ic->iformat->read_header(ic, ap);
        if (err < 0)
            goto fail;
439
    }
440

441
    if (pb && !ic->data_offset)
442
        ic->data_offset = avio_tell(ic->pb);
443

444 445
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

446 447 448 449
    *ic_ptr = ic;
    return 0;
 fail:
    if (ic) {
450
        int i;
451
        av_freep(&ic->priv_data);
452 453 454 455 456
        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);
457
                av_free(st->codec);
458
                av_free(st->info);
459 460 461
            }
            av_free(st);
        }
462 463 464 465 466 467
    }
    av_free(ic);
    *ic_ptr = NULL;
    return err;
}

Diego Biurrun's avatar
Diego Biurrun committed
468
/** size of probe buffer, for guessing file type from file contents */
469
#define PROBE_BUF_MIN 2048
470
#define PROBE_BUF_MAX (1<<20)
471

472
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
                          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);
    }

492 493
    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))) {
494 495 496 497 498 499 500 501 502
        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);
503
        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
504 505 506 507 508 509
            /* fail if error was not end of file, otherwise, lower score */
            if (ret != AVERROR_EOF) {
                av_free(buf);
                return ret;
            }
            score = 0;
510
            ret = 0;            /* error was end of file, nothing read */
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
        }
        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);
        }
    }

527
    if (!*fmt) {
528
        av_free(buf);
529 530 531
        return AVERROR_INVALIDDATA;
    }

532
    /* rewind. reuse probe buffer to avoid seeking */
533
    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
534
        av_free(buf);
535

536
    return ret;
537 538
}

539
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
540 541 542
                       AVInputFormat *fmt,
                       int buf_size,
                       AVFormatParameters *ap)
Fabrice Bellard's avatar
Fabrice Bellard committed
543
{
544
    int err;
545
    AVProbeData probe_data, *pd = &probe_data;
546
    AVIOContext *pb = NULL;
547
    void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
548

549 550 551
    pd->filename = "";
    if (filename)
        pd->filename = filename;
552
    pd->buf = NULL;
553 554 555
    pd->buf_size = 0;

    if (!fmt) {
Diego Biurrun's avatar
Diego Biurrun committed
556
        /* guess format if no file can be opened */
557
        fmt = av_probe_input_format(pd, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
558 559
    }

Diego Biurrun's avatar
Diego Biurrun committed
560
    /* Do not open file if the format does not need it. XXX: specific
Fabrice Bellard's avatar
Fabrice Bellard committed
561
       hack needed to handle RTSP/TCP */
562
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
563
        /* if no file needed do not try to open one */
564
        if ((err=avio_open(&pb, filename, AVIO_FLAG_READ)) < 0) {
565
            goto fail;
566
        }
567
        if (buf_size > 0) {
568
            ffio_set_buf_size(pb, buf_size);
569
        }
570
        if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
571
            goto fail;
572
        }
573 574 575 576
    }

    /* if still no format found, error */
    if (!fmt) {
577
        err = AVERROR_INVALIDDATA;
578
        goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
579
    }
580

Diego Biurrun's avatar
Diego Biurrun committed
581
    /* check filename in case an image number is expected */
582
    if (fmt->flags & AVFMT_NEEDNUMBER) {
583
        if (!av_filename_number_test(filename)) {
584
            err = AVERROR(EINVAL);
585
            goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
586 587
        }
    }
588 589 590
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
    if (err)
        goto fail;
591
    return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
592
 fail:
593
    av_freep(&pd->buf);
594
    if (pb)
595
        avio_close(pb);
596 597 598
    if (ap && ap->prealloced_context)
        av_free(*ic_ptr);
    *ic_ptr = NULL;
599
    return err;
600

Fabrice Bellard's avatar
Fabrice Bellard committed
601 602
}

603 604
/*******************************************************/

605 606 607
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
                               AVPacketList **plast_pktl){
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
608 609 610
    if (!pktl)
        return NULL;

611 612 613 614 615
    if (*packet_buffer)
        (*plast_pktl)->next = pktl;
    else
        *packet_buffer = pktl;

616 617 618 619 620 621
    /* add the packet in the buffered packet list */
    *plast_pktl = pktl;
    pktl->pkt= *pkt;
    return &pktl->pkt;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
622
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
623
{
624
    int ret, i;
625
    AVStream *st;
626 627 628 629 630 631

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

        if (pktl) {
            *pkt = pktl->pkt;
632
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
633 634 635 636 637
               !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;
638
                s->raw_packet_buffer = pktl->next;
639
                s->raw_packet_buffer_remaining_size += pkt->size;
640 641 642 643 644
                av_free(pktl);
                return 0;
            }
        }

Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
645 646
        av_init_packet(pkt);
        ret= s->iformat->read_packet(s, pkt);
647 648 649 650 651 652 653
        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
654
        st= s->streams[pkt->stream_index];
655

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

668 669
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
                     !st->probe_packets))
670 671
            return ret;

672
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
673
        s->raw_packet_buffer_remaining_size -= pkt->size;
674

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

680 681 682 683 684
            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);

685
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
686 687
                //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
688 689 690
                if(st->codec->codec_id != CODEC_ID_PROBE){
                    pd->buf_size=0;
                    av_freep(&pd->buf);
691
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
692
                }
693
            }
694 695
        }
    }
696 697 698 699
}

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

700
/**
Diego Biurrun's avatar
Diego Biurrun committed
701
 * Get the number of samples of an audio frame. Return -1 on error.
702
 */
703 704 705 706
static int get_audio_frame_size(AVCodecContext *enc, int size)
{
    int frame_size;

707 708 709
    if(enc->codec_id == CODEC_ID_VORBIS)
        return -1;

710
    if (enc->frame_size <= 1) {
711 712 713
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);

        if (bits_per_sample) {
714 715
            if (enc->channels == 0)
                return -1;
716
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
717
        } else {
718 719 720
            /* used for example by ADPCM codecs */
            if (enc->bit_rate == 0)
                return -1;
721
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
722 723 724 725 726 727 728 729
        }
    } else {
        frame_size = enc->frame_size;
    }
    return frame_size;
}


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

    *pnum = 0;
    *pden = 0;
740
    switch(st->codec->codec_type) {
741
    case AVMEDIA_TYPE_VIDEO:
Michael Niedermayer's avatar
Michael Niedermayer committed
742
        if(st->time_base.num*1000LL > st->time_base.den){
743 744
            *pnum = st->time_base.num;
            *pden = st->time_base.den;
745 746 747
        }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;
748
            if (pc && pc->repeat_pict) {
749
                *pnum = (*pnum) * (1 + pc->repeat_pict);
750
            }
751 752 753 754 755
            //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;
            }
756 757
        }
        break;
758
    case AVMEDIA_TYPE_AUDIO:
759
        frame_size = get_audio_frame_size(st->codec, pkt->size);
760
        if (frame_size <= 0 || st->codec->sample_rate <= 0)
761 762
            break;
        *pnum = frame_size;
763
        *pden = st->codec->sample_rate;
764 765 766 767 768 769
        break;
    default:
        break;
    }
}

770
static int is_intra_only(AVCodecContext *enc){
771
    if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
772
        return 1;
773
    }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
774 775 776 777 778 779 780
        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
781
        case CODEC_ID_FFVHUFF:
782 783 784
        case CODEC_ID_ASV1:
        case CODEC_ID_ASV2:
        case CODEC_ID_VCR1:
Baptiste Coudurier's avatar
Baptiste Coudurier committed
785
        case CODEC_ID_DNXHD:
786
        case CODEC_ID_JPEG2000:
787 788 789 790 791 792 793
            return 1;
        default: break;
        }
    }
    return 0;
}

794 795 796
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
                                      int64_t dts, int64_t pts)
{
797 798 799
    AVStream *st= s->streams[stream_index];
    AVPacketList *pktl= s->packet_buffer;

800
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
801 802 803 804 805 806 807 808 809 810 811 812 813 814
        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;
815 816 817

        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
            st->start_time= pktl->pkt.pts;
818
    }
819 820
    if (st->start_time == AV_NOPTS_VALUE)
        st->start_time = pts;
821 822
}

823 824 825
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
    AVPacketList *pktl= s->packet_buffer;
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    int64_t cur_dts= 0;

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

    for(; pktl; pktl= pktl->next){
        if(pktl->pkt.stream_index != pkt->stream_index)
            continue;
845 846
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
           && !pktl->pkt.duration){
847
            pktl->pkt.dts= cur_dts;
848
            if(!st->codec->has_b_frames)