utils.c 156 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
2
 * various utility functions for use within FFmpeg
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
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
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
 *
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
 */
21

22 23 24
#undef NDEBUG
#include <assert.h>
#include <stdarg.h>
25 26
#include <stdint.h>

27 28
#include "config.h"

29
#include "libavutil/avassert.h"
30
#include "libavutil/avstring.h"
31 32
#include "libavutil/dict.h"
#include "libavutil/internal.h"
33
#include "libavutil/mathematics.h"
34
#include "libavutil/opt.h"
35
#include "libavutil/parseutils.h"
36
#include "libavutil/pixdesc.h"
37
#include "libavutil/time.h"
38
#include "libavutil/timestamp.h"
39 40 41

#include "libavcodec/bytestream.h"
#include "libavcodec/internal.h"
42
#include "libavcodec/raw.h"
43

44
#include "audiointerleave.h"
45 46 47 48 49
#include "avformat.h"
#include "avio_internal.h"
#include "id3v2.h"
#include "internal.h"
#include "metadata.h"
50 51 52
#if CONFIG_NETWORK
#include "network.h"
#endif
53 54
#include "riff.h"
#include "url.h"
55

56
/**
57
 * @file
58
 * various utility functions for use within FFmpeg
59 60
 */

61 62
unsigned avformat_version(void)
{
63
    av_assert0(LIBAVFORMAT_VERSION_MICRO >= 100);
64 65 66
    return LIBAVFORMAT_VERSION_INT;
}

67
const char *avformat_configuration(void)
68
{
69
    return FFMPEG_CONFIGURATION;
70 71
}

72
const char *avformat_license(void)
73 74
{
#define LICENSE_PREFIX "libavformat license: "
75
    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
76 77
}

78
#define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
79 80

static int is_relative(int64_t ts) {
81
    return ts > (RELATIVE_TS_BASE - (1LL<<48));
82 83
}

84 85 86 87 88 89 90 91 92
/**
 * Wrap a given time stamp, if there is an indication for an overflow
 *
 * @param st stream
 * @param timestamp the time stamp to wrap
 * @return resulting time stamp
 */
static int64_t wrap_timestamp(AVStream *st, int64_t timestamp)
{
93
    if (st->pts_wrap_behavior != AV_PTS_WRAP_IGNORE &&
94 95 96
        st->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
        if (st->pts_wrap_behavior == AV_PTS_WRAP_ADD_OFFSET &&
            timestamp < st->pts_wrap_reference)
97
            return timestamp + (1ULL << st->pts_wrap_bits);
98 99
        else if (st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
            timestamp >= st->pts_wrap_reference)
100
            return timestamp - (1ULL << st->pts_wrap_bits);
101 102 103 104
    }
    return timestamp;
}

105
MAKE_ACCESSORS(AVStream, stream, AVRational, r_frame_rate)
106 107 108
MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
109
MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
110 111
MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
112

113
static AVCodec *find_decoder(AVFormatContext *s, AVStream *st, enum AVCodecID codec_id)
114 115 116 117
{
    if (st->codec->codec)
        return st->codec->codec;

118
    switch (st->codec->codec_type) {
119
    case AVMEDIA_TYPE_VIDEO:
120
        if (s->video_codec)    return s->video_codec;
121 122
        break;
    case AVMEDIA_TYPE_AUDIO:
123
        if (s->audio_codec)    return s->audio_codec;
124 125
        break;
    case AVMEDIA_TYPE_SUBTITLE:
126
        if (s->subtitle_codec) return s->subtitle_codec;
127 128 129
        break;
    }

130 131 132
    return avcodec_find_decoder(codec_id);
}

133 134 135 136 137
int av_format_get_probe_score(const AVFormatContext *s)
{
    return s->probe_score;
}

138 139
/* an arbitrarily chosen "sane" max packet size -- 50M */
#define SANE_CHUNK_SIZE (50000000)
Fabrice Bellard's avatar
Fabrice Bellard committed
140

141
int ffio_limit(AVIOContext *s, int size)
Michael Niedermayer's avatar
Michael Niedermayer committed
142
{
143
    if (s->maxsize>= 0) {
144
        int64_t remaining= s->maxsize - avio_tell(s);
145 146 147 148
        if (remaining < size) {
            int64_t newsize = avio_size(s);
            if (!s->maxsize || s->maxsize<newsize)
                s->maxsize = newsize - !newsize;
149
            remaining= s->maxsize - avio_tell(s);
150
            remaining= FFMAX(remaining, 0);
151 152
        }

153
        if (s->maxsize>= 0 && remaining+1 < size) {
154
            av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG, "Truncating packet of size %d to %"PRId64"\n", size, remaining+1);
155
            size = remaining+1;
156
        }
157
    }
158 159 160
    return size;
}

161 162
/* Read the data in sane-sized chunks and append to pkt.
 * Return the number of bytes read or an error. */
163
static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
164
{
165
    int64_t orig_pos   = pkt->pos; // av_grow_packet might reset pos
166
    int orig_size      = pkt->size;
167
    int ret;
168 169 170 171 172

    do {
        int prev_size = pkt->size;
        int read_size;

173 174
        /* When the caller requests a lot of data, limit it to the amount
         * left in file or SANE_CHUNK_SIZE when it is not known. */
175 176 177 178 179 180 181
        read_size = size;
        if (read_size > SANE_CHUNK_SIZE/10) {
            read_size = ffio_limit(s, read_size);
            // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
            if (s->maxsize < 0)
                read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
        }
182

183 184 185
        ret = av_grow_packet(pkt, read_size);
        if (ret < 0)
            break;
Michael Niedermayer's avatar
Michael Niedermayer committed
186

187 188 189 190 191
        ret = avio_read(s, pkt->data + prev_size, read_size);
        if (ret != read_size) {
            av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
            break;
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
192

193 194
        size -= read_size;
    } while (size > 0);
195 196
    if (size > 0)
        pkt->flags |= AV_PKT_FLAG_CORRUPT;
Michael Niedermayer's avatar
Michael Niedermayer committed
197

198 199
    pkt->pos = orig_pos;
    if (!pkt->size)
Michael Niedermayer's avatar
Michael Niedermayer committed
200
        av_free_packet(pkt);
201 202 203 204 205 206 207 208 209
    return pkt->size > orig_size ? pkt->size - orig_size : ret;
}

int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
{
    av_init_packet(pkt);
    pkt->data = NULL;
    pkt->size = 0;
    pkt->pos  = avio_tell(s);
Michael Niedermayer's avatar
Michael Niedermayer committed
210

211
    return append_packet_chunked(s, pkt, size);
Michael Niedermayer's avatar
Michael Niedermayer committed
212 213
}

214
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
215 216 217
{
    if (!pkt->size)
        return av_get_packet(s, pkt, size);
218
    return append_packet_chunked(s, pkt, size);
219 220
}

221
int av_filename_number_test(const char *filename)
222 223
{
    char buf[1024];
224 225
    return filename &&
           (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
226 227
}

228 229
AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened,
                                      int *score_ret)
230
{
231
    AVProbeData lpd = *pd;
232
    AVInputFormat *fmt1 = NULL, *fmt;
233
    int score, nodat = 0, score_max = 0;
234 235 236 237
    const static uint8_t zerobuffer[AVPROBE_PADDING_SIZE];

    if (!lpd.buf)
        lpd.buf = zerobuffer;
238

239 240 241
    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) {
242
            lpd.buf      += id3len;
243
            lpd.buf_size -= id3len;
244
        } else
245
            nodat = 1;
246 247
    }

248
    fmt = NULL;
249
    while ((fmt1 = av_iformat_next(fmt1))) {
250
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
251 252
            continue;
        score = 0;
253
        if (fmt1->read_probe) {
254
            score = fmt1->read_probe(&lpd);
255
            if (fmt1->extensions && av_match_ext(lpd.filename, fmt1->extensions))
256
                score = FFMAX(score, nodat ? AVPROBE_SCORE_EXTENSION / 2 - 1 : 1);
257
        } else if (fmt1->extensions) {
258
            if (av_match_ext(lpd.filename, fmt1->extensions))
259
                score = AVPROBE_SCORE_EXTENSION;
260
        }
261 262
        if (score > score_max) {
            score_max = score;
263 264
            fmt       = fmt1;
        } else if (score == score_max)
265
            fmt = NULL;
266
    }
267
    if (nodat)
268
        score_max = FFMIN(AVPROBE_SCORE_EXTENSION / 2 - 1, score_max);
269
    *score_ret = score_max;
270

271 272 273
    return fmt;
}

274 275 276
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
{
    int score_ret;
277 278 279
    AVInputFormat *fmt = av_probe_input_format3(pd, is_opened, &score_ret);
    if (score_ret > *score_max) {
        *score_max = score_ret;
280
        return fmt;
281
    } else
282 283 284
        return NULL;
}

285 286 287
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
{
    int score = 0;
288 289 290
    return av_probe_input_format2(pd, is_opened, &score);
}

291
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
292
                                     AVProbeData *pd)
293
{
294
    static const struct {
295 296 297
        const char *name;
        enum AVCodecID id;
        enum AVMediaType type;
298
    } fmt_id_type[] = {
299 300 301 302 303
        { "aac",       AV_CODEC_ID_AAC,        AVMEDIA_TYPE_AUDIO },
        { "ac3",       AV_CODEC_ID_AC3,        AVMEDIA_TYPE_AUDIO },
        { "dts",       AV_CODEC_ID_DTS,        AVMEDIA_TYPE_AUDIO },
        { "eac3",      AV_CODEC_ID_EAC3,       AVMEDIA_TYPE_AUDIO },
        { "h264",      AV_CODEC_ID_H264,       AVMEDIA_TYPE_VIDEO },
304
        { "hevc",      AV_CODEC_ID_HEVC,       AVMEDIA_TYPE_VIDEO },
305
        { "loas",      AV_CODEC_ID_AAC_LATM,   AVMEDIA_TYPE_AUDIO },
306 307
        { "m4v",       AV_CODEC_ID_MPEG4,      AVMEDIA_TYPE_VIDEO },
        { "mp3",       AV_CODEC_ID_MP3,        AVMEDIA_TYPE_AUDIO },
308
        { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
309 310
        { 0 }
    };
311 312
    int score;
    AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
313

314
    if (fmt && st->request_probe <= score) {
315
        int i;
316 317 318 319
        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);
320 321 322 323 324 325
        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;
            }
326
        }
327
    }
328
    return score;
329 330
}

331 332
/************************************************************/
/* input media file */
333

334
int av_demuxer_open(AVFormatContext *ic) {
335 336 337
    int err;

    if (ic->iformat->read_header) {
338
        err = ic->iformat->read_header(ic);
339 340 341 342 343 344 345 346 347 348 349
        if (err < 0)
            return err;
    }

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

    return 0;
}


350
int av_probe_input_buffer2(AVIOContext *pb, AVInputFormat **fmt,
351 352 353
                          const char *filename, void *logctx,
                          unsigned int offset, unsigned int max_probe_size)
{
354
    AVProbeData pd = { filename ? filename : "" };
355
    uint8_t *buf = NULL;
356
    uint8_t *mime_type;
357
    int ret = 0, probe_size, buf_offset = 0;
358
    int score = 0;
359

360
    if (!max_probe_size)
361
        max_probe_size = PROBE_BUF_MAX;
362
    else if (max_probe_size > PROBE_BUF_MAX)
363
        max_probe_size = PROBE_BUF_MAX;
364
    else if (max_probe_size < PROBE_BUF_MIN) {
365 366
        av_log(logctx, AV_LOG_ERROR,
               "Specified probe size value %u cannot be < %u\n", max_probe_size, PROBE_BUF_MIN);
367 368 369
        return AVERROR(EINVAL);
    }

370
    if (offset >= max_probe_size)
371 372
        return AVERROR(EINVAL);

373
    if (!*fmt && pb->av_class && av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type) >= 0 && mime_type) {
374
        if (!av_strcasecmp(mime_type, "audio/aacp")) {
375 376
            *fmt = av_find_input_format("aac");
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
377
        av_freep(&mime_type);
378 379
    }

380 381 382
    for (probe_size = PROBE_BUF_MIN; probe_size <= max_probe_size && !*fmt;
         probe_size = FFMIN(probe_size << 1,
                            FFMAX(max_probe_size, probe_size + 1))) {
383
        score = probe_size < max_probe_size ? AVPROBE_SCORE_RETRY : 0;
384

385
        /* Read probe data. */
386 387
        if ((ret = av_reallocp(&buf, probe_size + AVPROBE_PADDING_SIZE)) < 0)
            return ret;
388 389
        if ((ret = avio_read(pb, buf + buf_offset,
                             probe_size - buf_offset)) < 0) {
390
            /* Fail if error was not end of file, otherwise, lower score. */
391 392 393 394 395
            if (ret != AVERROR_EOF) {
                av_free(buf);
                return ret;
            }
            score = 0;
396
            ret   = 0;          /* error was end of file, nothing read */
397
        }
398
        buf_offset += ret;
399 400
        if (buf_offset < offset)
            continue;
401
        pd.buf_size = buf_offset - offset;
402 403 404 405
        pd.buf = &buf[offset];

        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);

406
        /* Guess file format. */
407
        *fmt = av_probe_input_format2(&pd, 1, &score);
408 409
        if (*fmt) {
            /* This can only be true in the last iteration. */
410
            if (score <= AVPROBE_SCORE_RETRY) {
411
                av_log(logctx, AV_LOG_WARNING,
412 413
                       "Format %s detected only with low score of %d, "
                       "misdetection possible!\n", (*fmt)->name, score);
414 415
            } else
                av_log(logctx, AV_LOG_DEBUG,
416 417
                       "Format %s probed with size=%d and score=%d\n",
                       (*fmt)->name, probe_size, score);
418 419 420 421 422
#if 0
            FILE *f = fopen("probestat.tmp", "ab");
            fprintf(f, "probe_size:%d format:%s score:%d filename:%s\n", probe_size, (*fmt)->name, score, filename);
            fclose(f);
#endif
423 424 425
        }
    }

426
    if (!*fmt) {
427
        av_free(buf);
428 429 430
        return AVERROR_INVALIDDATA;
    }

431
    /* Rewind. Reuse probe buffer to avoid seeking. */
432
    ret = ffio_rewind_with_probe_data(pb, &buf, buf_offset);
433

434
    return ret < 0 ? ret : score;
435 436
}

437 438 439 440 441 442 443 444
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
                          const char *filename, void *logctx,
                          unsigned int offset, unsigned int max_probe_size)
{
    int ret = av_probe_input_buffer2(pb, fmt, filename, logctx, offset, max_probe_size);
    return ret < 0 ? ret : 0;
}

445 446 447
/* Open input file and probe the format if necessary. */
static int init_input(AVFormatContext *s, const char *filename,
                      AVDictionary **options)
448 449
{
    int ret;
450
    AVProbeData pd = { filename, NULL, 0 };
451
    int score = AVPROBE_SCORE_RETRY;
452 453 454 455

    if (s->pb) {
        s->flags |= AVFMT_FLAG_CUSTOM_IO;
        if (!s->iformat)
456
            return av_probe_input_buffer2(s->pb, &s->iformat, filename,
457
                                         s, 0, s->probesize);
458
        else if (s->iformat->flags & AVFMT_NOFILE)
459 460
            av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
                                      "will be ignored with AVFMT_NOFILE format.\n");
461
        return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
462 463
    }

464
    if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
465
        (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
466
        return score;
467

468
    if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags,
469
                          &s->interrupt_callback, options)) < 0)
470
        return ret;
471 472
    if (s->iformat)
        return 0;
473
    return av_probe_input_buffer2(s->pb, &s->iformat, filename,
474
                                 s, 0, s->probesize);
475 476
}

477
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
478 479
                               AVPacketList **plast_pktl)
{
480 481 482 483 484 485 486 487 488
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
    if (!pktl)
        return NULL;

    if (*packet_buffer)
        (*plast_pktl)->next = pktl;
    else
        *packet_buffer = pktl;

489
    /* Add the packet in the buffered packet list. */
490
    *plast_pktl = pktl;
491
    pktl->pkt   = *pkt;
492 493 494
    return &pktl->pkt;
}

495
int avformat_queue_attached_pictures(AVFormatContext *s)
496 497 498
{
    int i;
    for (i = 0; i < s->nb_streams; i++)
499 500
        if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
            s->streams[i]->discard < AVDISCARD_ALL) {
501
            AVPacket copy = s->streams[i]->attached_pic;
502
            copy.buf = av_buffer_ref(copy.buf);
503 504 505
            if (!copy.buf)
                return AVERROR(ENOMEM);

506 507
            add_to_pktbuf(&s->raw_packet_buffer, &copy,
                          &s->raw_packet_buffer_end);
508
        }
509
    return 0;
510 511
}

512 513
int avformat_open_input(AVFormatContext **ps, const char *filename,
                        AVInputFormat *fmt, AVDictionary **options)
514 515
{
    AVFormatContext *s = *ps;
516
    int ret = 0;
517
    AVDictionary *tmp = NULL;
518
    ID3v2ExtraMeta *id3v2_extra_meta = NULL;
519 520 521

    if (!s && !(s = avformat_alloc_context()))
        return AVERROR(ENOMEM);
522
    if (!s->av_class) {
523
        av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
524 525
        return AVERROR(EINVAL);
    }
526 527 528 529 530 531 532 533 534
    if (fmt)
        s->iformat = fmt;

    if (options)
        av_dict_copy(&tmp, *options, 0);

    if ((ret = av_opt_set_dict(s, &tmp)) < 0)
        goto fail;

535
    if ((ret = init_input(s, filename, &tmp)) < 0)
536
        goto fail;
537
    s->probe_score = ret;
538
    avio_skip(s->pb, s->skip_initial_bytes);
539

540
    /* Check filename in case an image number is expected. */
541 542 543
    if (s->iformat->flags & AVFMT_NEEDNUMBER) {
        if (!av_filename_number_test(filename)) {
            ret = AVERROR(EINVAL);
544
            goto fail;
545
        }
546 547 548
    }

    s->duration = s->start_time = AV_NOPTS_VALUE;
549
    av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
550

551
    /* Allocate private data. */
552 553 554
    if (s->iformat->priv_data_size > 0) {
        if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
            ret = AVERROR(ENOMEM);
555
            goto fail;
556
        }
557
        if (s->iformat->priv_class) {
558
            *(const AVClass **) s->priv_data = s->iformat->priv_class;
559 560 561 562
            av_opt_set_defaults(s->priv_data);
            if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
                goto fail;
        }
563 564
    }

565 566
    /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
    if (s->pb)
567
        ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
568

569
    if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
570
        if ((ret = s->iformat->read_header(s)) < 0)
571
            goto fail;
572

573
    if (id3v2_extra_meta) {
574 575
        if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
            !strcmp(s->iformat->name, "tta")) {
576
            if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
577 578
                goto fail;
        } else
579
            av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
580
    }
581 582
    ff_id3v2_free_extra_meta(&id3v2_extra_meta);

583
    if ((ret = avformat_queue_attached_pictures(s)) < 0)
584
        goto fail;
585

586
    if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)
587 588 589 590 591 592 593
        s->data_offset = avio_tell(s->pb);

    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

    if (options) {
        av_dict_free(options);
        *options = tmp;
594
    }
595
    *ps = s;
596
    return 0;
597

598
fail:
599
    ff_id3v2_free_extra_meta(&id3v2_extra_meta);
600 601 602 603 604 605
    av_dict_free(&tmp);
    if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
        avio_close(s->pb);
    avformat_free_context(s);
    *ps = NULL;
    return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
606 607
}

608 609
/*******************************************************/

610 611
static void force_codec_ids(AVFormatContext *s, AVStream *st)
{
612
    switch (st->codec->codec_type) {
613
    case AVMEDIA_TYPE_VIDEO:
614 615
        if (s->video_codec_id)
            st->codec->codec_id = s->video_codec_id;
616 617
        break;
    case AVMEDIA_TYPE_AUDIO:
618 619
        if (s->audio_codec_id)
            st->codec->codec_id = s->audio_codec_id;
620 621
        break;
    case AVMEDIA_TYPE_SUBTITLE:
622 623
        if (s->subtitle_codec_id)
            st->codec->codec_id = s->subtitle_codec_id;
624 625 626 627
        break;
    }
}

628
static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
629
{
630
    if (st->request_probe>0) {
631
        AVProbeData *pd = &st->probe_data;
632 633
        int end;
        av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
634 635
        --st->probe_packets;

636
        if (pkt) {
637
            uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
638
            if (!new_buf) {
639 640 641
                av_log(s, AV_LOG_WARNING,
                       "Failed to reallocate probe buffer for stream %d\n",
                       st->index);
642
                goto no_packet;
643
            }
644
            pd->buf = new_buf;
645
            memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
646
            pd->buf_size += pkt->size;
647
            memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
648
        } else {
649
no_packet:
650
            st->probe_packets = 0;
651
            if (!pd->buf_size) {
652
                av_log(s, AV_LOG_WARNING,
653
                       "nothing to probe for stream %d\n", st->index);
654
            }
655
        }
656

657
        end=    s->raw_packet_buffer_remaining_size <= 0
658
                || st->probe_packets<= 0;
659

660 661
        if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
            int score = set_codec_from_probe_data(s, st, pd);
662
            if (    (st->codec->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
663
                || end) {
664
                pd->buf_size = 0;
665
                av_freep(&pd->buf);
666 667
                st->request_probe = -1;
                if (st->codec->codec_id != AV_CODEC_ID_NONE) {
668
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
669
                } else
670
                    av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
671
            }
672
            force_codec_ids(s, st);
673 674
        }
    }
675
    return 0;
676 677
}

678 679 680 681 682 683 684 685 686 687 688
static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
{
    int64_t ref = pkt->dts;
    int i, pts_wrap_behavior;
    int64_t pts_wrap_reference;
    AVProgram *first_program;

    if (ref == AV_NOPTS_VALUE)
        ref = pkt->pts;
    if (st->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
        return 0;
689
    ref &= (1LL << st->pts_wrap_bits)-1;
690 691 692 693

    // reference time stamp should be 60 s before first time stamp
    pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
    // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
694 695
    pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
        (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
696 697 698 699 700 701 702
        AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;

    first_program = av_find_program_from_stream(s, NULL, stream_index);

    if (!first_program) {
        int default_stream_index = av_find_default_stream_index(s);
        if (s->streams[default_stream_index]->pts_wrap_reference == AV_NOPTS_VALUE) {
703
            for (i = 0; i < s->nb_streams; i++) {
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
                s->streams[i]->pts_wrap_reference = pts_wrap_reference;
                s->streams[i]->pts_wrap_behavior = pts_wrap_behavior;
            }
        }
        else {
            st->pts_wrap_reference = s->streams[default_stream_index]->pts_wrap_reference;
            st->pts_wrap_behavior = s->streams[default_stream_index]->pts_wrap_behavior;
        }
    }
    else {
        AVProgram *program = first_program;
        while (program) {
            if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
                pts_wrap_reference = program->pts_wrap_reference;
                pts_wrap_behavior = program->pts_wrap_behavior;
                break;
            }
            program = av_find_program_from_stream(s, program, stream_index);
        }

        // update every program with differing pts_wrap_reference
        program = first_program;
726
        while (program) {
727
            if (program->pts_wrap_reference != pts_wrap_reference) {
728
                for (i = 0; i<program->nb_stream_indexes; i++) {
729 730 731 732 733 734 735 736 737 738 739 740 741
                    s->streams[program->stream_index[i]]->pts_wrap_reference = pts_wrap_reference;
                    s->streams[program->stream_index[i]]->pts_wrap_behavior = pts_wrap_behavior;
                }

                program->pts_wrap_reference = pts_wrap_reference;
                program->pts_wrap_behavior = pts_wrap_behavior;
            }
            program = av_find_program_from_stream(s, program, stream_index);
        }
    }
    return 1;
}

742
int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
743
{
744
    int ret, i, err;
745
    AVStream *st;
746

747
    for (;;) {
748 749 750 751
        AVPacketList *pktl = s->raw_packet_buffer;

        if (pktl) {
            *pkt = pktl->pkt;
752
            st   = s->streams[pkt->stream_index];
753
            if (s->raw_packet_buffer_remaining_size <= 0)
754 755
                if ((err = probe_codec(s, st, NULL)) < 0)
                    return err;
756
            if (st->request_probe <= 0) {
757
                s->raw_packet_buffer                 = pktl->next;
758
                s->raw_packet_buffer_remaining_size += pkt->size;
759 760 761 762 763
                av_free(pktl);
                return 0;
            }
        }

764 765
        pkt->data = NULL;
        pkt->size = 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
766
        av_init_packet(pkt);
767
        ret = s->iformat->read_packet(s, pkt);
768 769 770
        if (ret < 0) {
            if (!pktl || ret == AVERROR(EAGAIN))
                return ret;
771 772
            for (i = 0; i < s->nb_streams; i++) {
                st = s->streams[i];
773
                if (st->probe_packets)
774 775
                    if ((err = probe_codec(s, st, NULL)) < 0)
                        return err;
776
                av_assert0(st->request_probe <= 0);
777
            }
778 779
            continue;
        }
780

781 782 783 784 785
        if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
            (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
            av_log(s, AV_LOG_WARNING,
                   "Dropped corrupted packet (stream = %d)\n",
                   pkt->stream_index);
786
            av_free_packet(pkt);
787 788 789
            continue;
        }

790
        if (pkt->stream_index >= (unsigned)s->nb_streams) {
791 792 793 794
            av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);
            continue;
        }

795
        st = s->streams[pkt->stream_index];
796 797 798 799 800 801 802 803 804 805 806

        if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
            // correct first time stamps to negative values
            if (!is_relative(st->first_dts))
                st->first_dts = wrap_timestamp(st, st->first_dts);
            if (!is_relative(st->start_time))
                st->start_time = wrap_timestamp(st, st->start_time);
            if (!is_relative(st->cur_dts))
                st->cur_dts = wrap_timestamp(st, st->cur_dts);
        }

807 808
        pkt->dts = wrap_timestamp(st, pkt->dts);
        pkt->pts = wrap_timestamp(st, pkt->pts);
809

810 811
        force_codec_ids(s, st);

812 813 814
        /* TODO: audio: time filter; video: frame reordering (pts != dts) */
        if (s->use_wallclock_as_timestamps)
            pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
815

816
        if (!pktl && st->request_probe <= 0)
817 818
            return ret;

819
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
820
        s->raw_packet_buffer_remaining_size -= pkt->size;
821

822 823
        if ((err = probe_codec(s, st, pkt)) < 0)
            return err;
824
    }
825 826
}

827 828 829 830 831 832 833 834
#if FF_API_READ_PACKET
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    return ff_read_packet(s, pkt);
}
#endif


835 836
/**********************************************************/

837 838
static int determinable_frame_size(AVCodecContext *avctx)
{
839 840 841 842 843
    if (/*avctx->codec_id == AV_CODEC_ID_AAC ||*/
        avctx->codec_id == AV_CODEC_ID_MP1 ||
        avctx->codec_id == AV_CODEC_ID_MP2 ||
        avctx->codec_id == AV_CODEC_ID_MP3/* ||
        avctx->codec_id == AV_CODEC_ID_CELT*/)
844 845 846 847
        return 1;
    return 0;
}

848
/**
849
 * Get the number of samples of an audio frame. Return -1 on error.
850
 */
851
int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
852 853 854
{
    int frame_size;

855 856 857
    /* give frame_size priority if demuxing */
    if (!mux && enc->frame_size > 1)
        return enc->frame_size;
858

859 860 861
    if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
        return frame_size;

Diego Biurrun's avatar
Diego Biurrun committed
862
    /* Fall back on using frame_size if muxing. */
863 864 865
    if (enc->frame_size > 1)
        return enc->frame_size;

866 867
    //For WMA we currently have no other means to calculate duration thus we
    //do it here by assuming CBR, which is true for all known cases.
868
    if (!mux && enc->bit_rate>0 && size>0 && enc->sample_rate>0 && enc->block_align>1) {
869 870 871 872
        if (enc->codec_id == AV_CODEC_ID_WMAV1 || enc->codec_id == AV_CODEC_ID_WMAV2)
            return  ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
    }

873
    return -1;
874 875
}

876
/**
877
 * Return the frame duration in seconds. Return 0 if not available.
878
 */
879 880
void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
                               AVCodecParserContext *pc, AVPacket *pkt)
881 882 883 884 885
{
    int frame_size;

    *pnum = 0;
    *pden = 0;
886
    switch (st->codec->codec_type) {
887
    case AVMEDIA_TYPE_VIDEO:
888
        if (st->r_frame_rate.num && !pc) {
889 890
            *pnum = st->r_frame_rate.den;
            *pden = st->r_frame_rate.num;
891
        } else if (st->time_base.num * 1000LL > st->time_base.den) {
892 893
            *pnum = st->time_base.num;
            *pden = st->time_base.den;
894
        } else if (st->codec->time_base.num * 1000LL > st->codec->time_base.den) {
895 896
            *pnum = st->codec->time_base.num;
            *pden = st->codec->time_base.den;
897
            if (pc && pc->repeat_pict) {
898 899 900 901
                if (*pnum > INT_MAX / (1 + pc->repeat_pict))
                    *pden /= 1 + pc->repeat_pict;
                else
                    *pnum *= 1 + pc->repeat_pict;
902
            }
903 904 905 906
            /* 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)
907
                *pnum = *pden = 0;
908 909
        }
        break;
910
    case AVMEDIA_TYPE_AUDIO:
911
        frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
912
        if (frame_size <= 0 || st->codec->sample_rate <= 0)
913 914
            break;
        *pnum = frame_size;
915
        *pden = st->codec->sample_rate;
916 917 918 919 920 921
        break;
    default:
        break;
    }
}

922
static int is_intra_only(AVCodecContext *enc) {
923
    const AVCodecDescriptor *desc;
924

925
    if (enc->codec_type != AVMEDIA_TYPE_VIDEO)
926
        return 1;
927 928 929 930 931

    desc = av_codec_get_codec_descriptor(enc);
    if (!desc) {
        desc = avcodec_descriptor_get(enc->codec_id);
        av_codec_set_codec_descriptor(enc, desc);
932
    }
933 934
    if (desc)
        return !!(desc->props & AV_CODEC_PROP_INTRA_ONLY);
935 936 937
    return 0;
}

938 939
static int has_decode_delay_been_guessed(AVStream *st)
{
940 941
    if (st->codec->codec_id != AV_CODEC_ID_H264) return 1;
    if (!st->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
942
        return 1;
943
#if CONFIG_H264_DECODER
944
    if (st->codec->has_b_frames &&
945 946 947
       avpriv_h264_has_num_reorder_frames(st->codec) == st->codec->has_b_frames)
        return 1;
#endif
948
    if (st->codec->has_b_frames<3)
949
        return st->nb_decoded_frames >= 7;
950
    else if (st->codec->has_b_frames<4)
951
        return st->nb_decoded_frames >= 18;
952
    else
953
        return st->nb_decoded_frames >= 20;
954 955
}

956 957 958 959
static AVPacketList *get_next_pkt(AVFormatContext *s, AVStream *st, AVPacketList *pktl)
{
    if (pktl->next)
        return pktl->next;
960 961
    if (pktl == s->packet_buffer_end)
        return s->parse_queue;
962 963 964
    return NULL;
}

965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
    int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
                       st->codec->codec_id != AV_CODEC_ID_HEVC;

    if(!onein_oneout) {
        int delay = st->codec->has_b_frames;
        int i;

        if (dts == AV_NOPTS_VALUE) {
            int64_t best_score = INT64_MAX;
            for (i = 0; i<delay; i++) {
                if (st->pts_reorder_error_count[i]) {
                    int64_t score = st->pts_reorder_error[i] / st->pts_reorder_error_count[i];
                    if (score < best_score) {
                        best_score = score;
                        dts = pts_buffer[i];
                    }
                }
            }
        } else {
            for (i = 0; i<delay; i++) {
                if (pts_buffer[i] != AV_NOPTS_VALUE) {
                    int64_t diff =  FFABS(pts_buffer[i] - dts)
                                    + (uint64_t)st->pts_reorder_error[i];
                    diff = FFMAX(diff, st->pts_reorder_error[i]);
                    st->pts_reorder_error[i] = diff;
                    st->pts_reorder_error_count[i]++;
                    if (st->pts_reorder_error_count[i] > 250) {
                        st->pts_reorder_error[i] >>= 1;
                        st->pts_reorder_error_count[i] >>= 1;
                    }
                }
            }
        }
    }

    if (dts == AV_NOPTS_VALUE)
        dts = pts_buffer[0];

    return dts;
}

1007
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
1008
                                      int64_t dts, int64_t pts, AVPacket *pkt)
1009
{
1010
    AVStream *st       = s->streams[stream_index];
1011
    AVPacketList *pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
1012
    int64_t pts_buffer[MAX_REORDER_DELAY+1];
1013
    int64_t shift;
1014
    int i, delay;
1015

1016 1017
    if (st->first_dts != AV_NOPTS_VALUE ||
        dts           == AV_NOPTS_VALUE ||
1018 1019
        st->cur_dts   == AV_NOPTS_VALUE ||
        is_relative(dts))
1020 1021
        return;

1022 1023
    delay         = st->codec->has_b_frames;
    st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
1024
    st->cur_dts   = dts;
1025
    shift         = st->first_dts - RELATIVE_TS_BASE;
1026

1027
    for (i = 0; i<MAX_REORDER_DELAY+1; i++)
1028 1029
        pts_buffer[i] = AV_NOPTS_VALUE;

1030
    if (is_relative(pts))
1031
        pts += shift;
1032

1033
    for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1034
        if (pktl->pkt.stream_index != stream_index)
1035
            continue;
1036
        if (is_relative(pktl->pkt.pts))
1037
            pktl->pkt.pts += shift;
1038

1039
        if (is_relative(pktl->pkt.dts))
1040
            pktl->pkt.dts += shift;
1041

1042 1043
        if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
            st->start_time = pktl->pkt.pts;
1044

1045 1046 1047 1048
        if (pktl->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
            pts_buffer[0] = pktl->pkt.pts;
            for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
                FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
1049 1050

            pktl->pkt.dts = select_from_pts_buffer(st, pts_buffer, pktl->pkt.dts);
1051
        }
1052
    }
1053

1054 1055
    if (st->start_time == AV_NOPTS_VALUE)
        st->start_time = pts;
1056 1057
}

1058 1059
static void update_initial_durations(AVFormatContext *s, AVStream *st,
                                     int stream_index, int duration)
1060
{
1061 1062
    AVPacketList *pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
    int64_t cur_dts    = RELATIVE_TS_BASE;
1063

1064
    if (st->first_dts != AV_NOPTS_VALUE) {
1065 1066 1067
        if (st->update_initial_durations_done)
            return;
        st->update_initial_durations_done = 1;
1068
        cur_dts = st->first_dts;
1069
        for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1070 1071 1072 1073
            if (pktl->pkt.stream_index == stream_index) {
                if (pktl->pkt.pts != pktl->pkt.dts  ||
                    pktl->pkt.dts != AV_NOPTS_VALUE ||
                    pktl->pkt.duration)
1074
                    break;
1075
                cur_dts -= duration;
1076 1077
            }
        }
1078
        if (pktl && pktl->pkt.dts != st->first_dts) {
1079 1080
            av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %d) in the queue\n",
                   av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
1081 1082
            return;
        }
1083
        if (!pktl) {
1084
            av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
1085 1086
            return;
        }
1087
        pktl          = s->packet_buffer ? s->packet_buffer : s->parse_queue;
1088
        st->first_dts = cur_dts;
1089
    } else if (st->cur_dts != RELATIVE_TS_BASE)
1090
        return;
1091

1092
    for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1093
        if (pktl->pkt.stream_index != stream_index)
1094
            continue;
1095
        if (pktl->pkt.pts == pktl->pkt.dts  &&
1096
            (pktl->pkt.dts == AV_NOPTS_VALUE || pktl->pkt.dts == st->first_dts) &&
1097 1098 1099 1100
            !pktl->pkt.duration) {
            pktl->pkt.dts = cur_dts;
            if (!st->codec->has_b_frames)
                pktl->pkt.pts = cur_dts;
1101
//            if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
1102
                pktl->pkt.duration = duration;
1103
        } else
1104
            break;
1105
        cur_dts = pktl->pkt.dts + pktl->pkt.duration;
1106
    }
1107
    if (!pktl)
1108
        st->cur_dts = cur_dts;
1109 1110
}

1111
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
1112 1113
                               AVCodecParserContext *pc, AVPacket *pkt)
{
1114
    int num, den, presentation_delayed, delay, i;
1115
    int64_t offset;
1116
    AVRational duration;
1117 1118
    int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
                       st->codec->codec_id != AV_CODEC_ID_HEVC;
1119

1120 1121 1122
    if (s->flags & AVFMT_FLAG_NOFILLIN)
        return;

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
        if (pkt->dts == pkt->pts && st->last_dts_for_order_check != AV_NOPTS_VALUE) {
            if (st->last_dts_for_order_check <= pkt->dts) {
                st->dts_ordered++;
            } else {
                av_log(s, st->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
                       "DTS %"PRIi64" < %"PRIi64" out of order\n",
                       pkt->dts,
                       st->last_dts_for_order_check);
                st->dts_misordered++;
            }
            if (st->dts_ordered + st->dts_misordered > 250) {
                st->dts_ordered    >>= 1;
                st->dts_misordered >>= 1;
            }
        }

        st->last_dts_for_order_check = pkt->dts;
        if (st->dts_ordered < 8*st->dts_misordered && pkt->dts == pkt->pts)
            pkt->dts = AV_NOPTS_VALUE;
    }

1145 1146
    if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
        pkt->dts = AV_NOPTS_VALUE;
1147

1148 1149
    if (pc && pc->pict_type == AV_PICTURE_TYPE_B
        && !st->codec->has_b_frames)
1150
        //FIXME Set low_delay = 0 when has_b_frames = 1
1151 1152
        st->codec->has_b_frames = 1;

1153
    /* do we have a video B-frame ? */
1154
    delay = st->codec->has_b_frames;
1155
    presentation_delayed = 0;
1156

1157
    /* XXX: need has_b_frame, but cannot get it if the codec is
1158
     *  not initialized */
1159
    if (delay &&
1160
        pc && pc->pict_type != AV_PICTURE_TYPE_B)
1161 1162
        presentation_delayed = 1;

1163 1164 1165
    if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
        st->pts_wrap_bits < 63 &&
        pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1166 1167
        if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
            pkt->dts -= 1LL << st->pts_wrap_bits;
1168
        } else
1169
            pkt->pts += 1LL << st->pts_wrap_bits;
1170 1171
    }

1172 1173 1174 1175 1176 1177
    /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
     * We take the conservative approach and discard both.
     * Note: If this is misbehaving for an H.264 file, then possibly
     * presentation_delayed is not set correctly. */
    if (delay == 1 && pkt->dts == pkt->pts &&
        pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1178
        av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1179 1180
        if (    strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
             && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1181
            pkt->dts = AV_NOPTS_VALUE;
1182 1183
    }

1184
    duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1185
    if (pkt->duration == 0) {
1186
        ff_compute_frame_duration(&num, &den, st, pc, pkt);
1187
        if (den && num) {
1188 1189 1190
            duration = (AVRational) {num, den};
            pkt->duration = av_rescale_rnd(1,
                                           num * (int64_t) st->time_base.den,
1191 1192
                                           den * (int64_t) st->time_base.num,
                                           AV_ROUND_DOWN);
1193 1194
        }
    }
1195

1196
    if (pkt->duration != 0 && (s->packet_buffer || s->parse_queue))
1197
        update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1198

1199 1200 1201
    /* Correct timestamps with byte offset if demuxers only have timestamps
     * on packet boundaries */
    if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1202 1203
        /* this will estimate bitrate based on this frame's duration and size */
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1204
        if (pkt->pts != AV_NOPTS_VALUE)
1205
            pkt->pts += offset;
1206
        if (pkt->dts != AV_NOPTS_VALUE)
1207 1208 1209
            pkt->dts += offset;
    }

Diego Biurrun's avatar
Diego Biurrun committed
1210
    /* This may be redundant, but it should not hurt. */
1211 1212 1213
    if (pkt->dts != AV_NOPTS_VALUE &&
        pkt->pts != AV_NOPTS_VALUE &&
        pkt->pts > pkt->dts)
Michael Niedermayer's avatar
Michael Niedermayer committed
1214
        presentation_delayed = 1;
1215

1216
    av_dlog(NULL,
1217 1218 1219 1220
            "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%d\n",
            presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
            pkt->stream_index, pc, pkt->duration);
    /* Interpolate PTS and DTS if they are not present. We skip H264
1221 1222
     * currently because delay and has_b_frames are not reliably set. */
    if ((delay == 0 || (delay == 1 && pc)) &&
1223
        onein_oneout) {
Michael Niedermayer's avatar
Michael Niedermayer committed
1224
        if (presentation_delayed) {
1225 1226
            /* DTS = decompression timestamp */
            /* PTS = presentation timestamp */
Michael Niedermayer's avatar
Michael Niedermayer committed
1227
            if (pkt->dts == AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
1228
                pkt->dts = st->last_IP_pts;
1229
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
Michael Niedermayer's avatar
Michael Niedermayer committed
1230 1231 1232
            if (pkt->dts == AV_NOPTS_VALUE)
                pkt->dts = st->cur_dts;

1233 1234
            /* This is tricky: the dts must be incremented by the duration
             * of the frame we are displaying, i.e. the last I- or P-frame. */
Michael Niedermayer's avatar
Michael Niedermayer committed
1235 1236
            if (st->last_IP_duration == 0)
                st->last_IP_duration = pkt->duration;
1237
            if (pkt->dts != AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
1238
                st->cur_dts = pkt->dts + st->last_IP_duration;
1239 1240 1241 1242
            st->last_IP_duration = pkt->duration;
            st->last_IP_pts      = pkt->pts;
            /* Cannot compute PTS if not present (we can compute it only
             * by knowing the future. */
1243 1244
        } else if (pkt->pts != AV_NOPTS_VALUE ||
                   pkt->dts != AV_NOPTS_VALUE ||
1245
                   pkt->duration                ) {
1246

Michael Niedermayer's avatar
Michael Niedermayer committed
1247
            /* presentation is not delayed : PTS and DTS are the same */
1248
            if (pkt->pts == AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
1249
                pkt->pts = pkt->dts;
1250
            update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1251
                                      pkt->pts, pkt);
1252
            if (pkt->pts == AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
1253 1254
                pkt->pts = st->cur_dts;
            pkt->dts = pkt->pts;
1255
            if (pkt->pts != AV_NOPTS_VALUE)
1256
                st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
Michael Niedermayer's avatar
Michael Niedermayer committed
1257
        }
1258
    }
1259

1260
    if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
1261 1262 1263
        st->pts_buffer[0] = pkt->pts;
        for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
1264 1265

        pkt->dts = select_from_pts_buffer(st, st->pts_buffer, pkt->dts);
1266
    }
1267
    // We skipped it above so we try here.
1268
    if (!onein_oneout)
1269 1270 1271
        // This should happen on the first packet
        update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
    if (pkt->dts > st->cur_dts)
1272
        st->cur_dts = pkt->dts;
1273

1274 1275
    av_dlog(NULL, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s\n",
            presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts));
1276

1277
    /* update flags */
1278
    if (is_intra_only(st->codec))
1279
        pkt->flags |= AV_PKT_FLAG_KEY;
1280 1281
    if (pc)
        pkt->convergence_duration = pc->convergence_duration;
1282 1283
}

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
{
    while (*pkt_buf) {
        AVPacketList *pktl = *pkt_buf;
        *pkt_buf = pktl->next;
        av_free_packet(&pktl->pkt);
        av_freep(&pktl);
    }
    *pkt_buf_end = NULL;
}
1294

1295
/**
1296
 * Parse a packet, add all split parts to parse_queue.
1297
 *
1298
 * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
1299 1300
 */
static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1301
{
1302
    AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1303 1304 1305
    AVStream *st = s->streams[stream_index];
    uint8_t *data = pkt ? pkt->data : NULL;
    int size      = pkt ? pkt->size : 0;
1306
    int ret = 0, got_output = 0;
1307

1308 1309
    if (!pkt) {
        av_init_packet(&flush_pkt);
1310
        pkt        = &flush_pkt;
1311
        got_output = 1;
1312 1313 1314
    } else if (!size && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
        // preserve 0-size sync packets
        compute_pkt_fields(s, st, st->parser, pkt);
1315
    }
1316

1317 1318
    while (size > 0 || (pkt == &flush_pkt && got_output)) {
        int len;
1319

1320
        av_init_packet(&out_pkt);
1321
        len = av_parser_parse2(st->parser, st->codec,
1322 1323
                               &out_pkt.data, &out_pkt.size, data, size,
                               pkt->pts, pkt->dts, pkt->pos);
1324

1325
        pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1326
        pkt->pos = -1;
1327 1328 1329 1330 1331 1332 1333 1334 1335
        /* increment read pointer */
        data += len;
        size -= len;

        got_output = !!out_pkt.size;

        if (!out_pkt.size)
            continue;

1336 1337 1338
        if (pkt->side_data) {
            out_pkt.side_data       = pkt->side_data;
            out_pkt.side_data_elems = pkt->side_data_elems;
1339 1340
            pkt->side_data          = NULL;
            pkt->side_data_elems    = 0;
1341 1342
        }

1343 1344 1345 1346
        /* set the duration */
        out_pkt.duration = 0;
        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
            if (st->codec->sample_rate > 0) {
1347 1348 1349 1350 1351
                out_pkt.duration =
                    av_rescale_q_rnd(st->parser->duration,
                                     (AVRational) { 1, st->codec->sample_rate },
                                     st->time_base,
                                     AV_ROUND_DOWN);
1352
            }
1353 1354 1355 1356 1357 1358 1359 1360 1361
        } else if (st->codec->time_base.num != 0 &&
                   st->codec->time_base.den != 0) {
            out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
                                                st->codec->time_base,
                                                st->time_base,
                                                AV_ROUND_DOWN);
        }

        out_pkt.stream_index = st->index;
1362 1363 1364
        out_pkt.pts          = st->parser->pts;
        out_pkt.dts          = st->parser->dts;
        out_pkt.pos          = st->parser->pos;
1365

1366
        if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1367
            out_pkt.pos = st->parser->frame_offset;
1368 1369 1370 1371 1372 1373

        if (st->parser->key_frame == 1 ||
            (st->parser->key_frame == -1 &&
             st->parser->pict_type == AV_PICTURE_TYPE_I))
            out_pkt.flags |= AV_PKT_FLAG_KEY;

1374
        if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1375 1376
            out_pkt.flags |= AV_PKT_FLAG_KEY;

1377 1378 1379
        compute_pkt_fields(s, st, st->parser, &out_pkt);

        if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1380 1381
            out_pkt.buf = pkt->buf;
            pkt->buf    = NULL;
1382
#if FF_API_DESTRUCT_PACKET
1383
FF_DISABLE_DEPRECATION_WARNINGS
1384 1385
            out_pkt.destruct = pkt->destruct;
            pkt->destruct = NULL;
1386
FF_ENABLE_DEPRECATION_WARNINGS
1387
#endif
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
        }
        if ((ret = av_dup_packet(&out_pkt)) < 0)
            goto fail;

        if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
            av_free_packet(&out_pkt);
            ret = AVERROR(ENOMEM);
            goto fail;
        }
    }

    /* end of the stream => close and free the parser */
    if (pkt == &flush_pkt) {
        av_parser_close(st->parser);
        st->parser = NULL;
    }

fail:
    av_free_packet(pkt);
    return ret;
}

1410 1411 1412 1413 1414 1415
static int read_from_packet_buffer(AVPacketList **pkt_buffer,
                                   AVPacketList **pkt_buffer_end,
                                   AVPacket      *pkt)
{
    AVPacketList *pktl;
    av_assert0(*pkt_buffer);
1416 1417
    pktl        = *pkt_buffer;
    *pkt        = pktl->pkt;
1418 1419 1420 1421 1422 1423 1424
    *pkt_buffer = pktl->next;
    if (!pktl->next)
        *pkt_buffer_end = NULL;
    av_freep(&pktl);
    return 0;
}

1425
static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1426
{
1427
    int ret = 0, i, got_packet = 0;
1428

1429 1430
    av_init_packet(pkt);

1431 1432 1433
    while (!got_packet && !s->parse_queue) {
        AVStream *st;
        AVPacket cur_pkt;
1434

1435
        /* read next packet */
1436
        ret = ff_read_packet(s, &cur_pkt);
1437 1438
        if (ret < 0) {
            if (ret == AVERROR(EAGAIN))
1439
                return ret;
1440
            /* flush the parsers */
1441
            for (i = 0; i < s->nb_streams; i++) {
1442 1443 1444
                st = s->streams[i];
                if (st->parser && st->need_parsing)
                    parse_packet(s, NULL, st->index);
1445
            }
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
            /* all remaining packets are now in parse_queue =>
             * really terminate parsing */
            break;
        }
        ret = 0;
        st  = s->streams[cur_pkt.stream_index];

        if (cur_pkt.pts != AV_NOPTS_VALUE &&
            cur_pkt.dts != AV_NOPTS_VALUE &&
            cur_pkt.pts < cur_pkt.dts) {
1456
            av_log(s, AV_LOG_WARNING,
1457
                   "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1458
                   cur_pkt.stream_index,
1459 1460
                   av_ts2str(cur_pkt.pts),
                   av_ts2str(cur_pkt.dts),
1461 1462 1463
                   cur_pkt.size);
        }
        if (s->debug & FF_FDEBUG_TS)
1464
            av_log(s, AV_LOG_DEBUG,
1465
                   "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%d, flags=%d\n",
1466
                   cur_pkt.stream_index,
1467 1468
                   av_ts2str(cur_pkt.pts),
                   av_ts2str(cur_pkt.dts),
1469
                   cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
1470 1471 1472 1473

        if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
            st->parser = av_parser_init(st->codec->codec_id);
            if (!st->parser) {
1474 1475 1476
                av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
                       "%s, packets or times may be invalid.\n",
                       avcodec_get_name(st->codec->codec_id));
1477 1478
                /* no parser available: just output the raw packets */
                st->need_parsing = AVSTREAM_PARSE_NONE;
1479
            } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1480
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1481
            else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1482
                st->parser->flags |= PARSER_FLAG_ONCE;
1483
            else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1484
                st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1485
        }
1486

1487 1488 1489 1490 1491 1492 1493
        if (!st->need_parsing || !st->parser) {
            /* no parsing needed: we just output the packet as is */
            *pkt = cur_pkt;
            compute_pkt_fields(s, st, NULL, pkt);
            if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
                (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
                ff_reduce_index(s, st->index);
1494 1495
                av_add_index_entry(st, pkt->pos, pkt->dts,
                                   0, 0, AVINDEX_KEYFRAME);
1496
            }
1497 1498 1499 1500 1501 1502 1503
            got_packet = 1;
        } else if (st->discard < AVDISCARD_ALL) {
            if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
                return ret;
        } else {
            /* free packet */
            av_free_packet(&cur_pkt);
1504
        }
1505 1506 1507 1508
        if (pkt->flags & AV_PKT_FLAG_KEY)
            st->skip_to_keyframe = 0;
        if (st->skip_to_keyframe) {
            av_free_packet(&cur_pkt);
1509 1510 1511
            if (got_packet) {
                *pkt = cur_pkt;
            }
1512 1513
            got_packet = 0;
        }
1514
    }
1515 1516 1517 1518

    if (!got_packet && s->parse_queue)
        ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    if (ret >= 0) {
        AVStream *st = s->streams[pkt->stream_index];
        if (st->skip_samples) {
            uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
            if (p) {
                AV_WL32(p, st->skip_samples);
                av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d\n", st->skip_samples);
            }
            st->skip_samples = 0;
        }
    }

1531
    if (ret >= 0 && !(s->flags & AVFMT_FLAG_KEEP_SIDE_DATA))
1532 1533
        av_packet_merge_side_data(pkt);

1534 1535
    if (s->debug & FF_FDEBUG_TS)
        av_log(s, AV_LOG_DEBUG,
1536
               "read_frame_internal stream=%d, pts=%s, dts=%s, "
1537
               "size=%d, duration=%d, flags=%d\n",
1538 1539 1540
               pkt->stream_index,
               av_ts2str(pkt->pts),
               av_ts2str(pkt->dts),
1541
               pkt->size, pkt->duration, pkt->flags);
1542

1543
    return ret;
1544 1545
}

1546
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Fabrice Bellard's avatar
Fabrice Bellard committed
1547
{
1548
    const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1549
    int eof = 0;
1550
    int ret;
1551
    AVStream *st;
1552

1553
    if (!genpts) {
1554 1555 1556 1557
        ret = s->packet_buffer
              ? read_from_packet_buffer(&s->packet_buffer,
                                        &s->packet_buffer_end, pkt)
              : read_frame_internal(s, pkt);
1558 1559 1560
        if (ret < 0)
            return ret;
        goto return_packet;
1561
    }
1562

1563 1564
    for (;;) {
        AVPacketList *pktl = s->packet_buffer;
1565 1566

        if (pktl) {
1567
            AVPacket *next_pkt = &pktl->pkt;
1568

1569
            if (next_pkt->dts != AV_NOPTS_VALUE) {
1570
                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1571 1572 1573
                // last dts seen for this stream. if any of packets following
                // current one had no dts, we will set this to AV_NOPTS_VALUE.
                int64_t last_dts = next_pkt->dts;
1574 1575
                while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
                    if (pktl->pkt.stream_index == next_pkt->stream_index &&
1576
                        (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0)) {
1577 1578
                        if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {
                            // not B-frame
1579 1580 1581 1582 1583 1584
                            next_pkt->pts = pktl->pkt.dts;
                        }
                        if (last_dts != AV_NOPTS_VALUE) {
                            // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
                            last_dts = pktl->pkt.dts;
                        }
1585
                    }
1586
                    pktl = pktl->next;
1587
                }
1588 1589 1590 1591 1592 1593 1594 1595
                if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
                    // Fixing the last reference frame had none pts issue (For MXF etc).
                    // We only do this when
                    // 1. eof.
                    // 2. we are not able to resolve a pts value for current packet.
                    // 3. the packets for this stream at the end of the files had valid dts.
                    next_pkt->pts = last_dts + next_pkt->duration;
                }
1596 1597
                pktl = s->packet_buffer;
            }
1598

1599 1600
            /* read packet from packet buffer, if there is data */
            if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1601 1602
                  next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
                ret = read_from_packet_buffer(&s->packet_buffer,
1603
                                               &s->packet_buffer_end, pkt);
1604 1605
                goto return_packet;
            }
1606
        }
1607

1608 1609 1610 1611 1612 1613 1614
        ret = read_frame_internal(s, pkt);
        if (ret < 0) {
            if (pktl && ret != AVERROR(EAGAIN)) {
                eof = 1;
                continue;
            } else
                return ret;
1615
        }
1616 1617

        if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1618
                                        &s->packet_buffer_end)) < 0)
1619
            return AVERROR(ENOMEM);
1620
    }
1621 1622

return_packet:
1623

1624
    st = s->streams[pkt->stream_index];
1625 1626 1627 1628 1629
    if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
        ff_reduce_index(s, st->index);
        av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
    }

1630 1631 1632 1633
    if (is_relative(pkt->dts))
        pkt->dts -= RELATIVE_TS_BASE;
    if (is_relative(pkt->pts))
        pkt->pts -= RELATIVE_TS_BASE;
1634

1635
    return ret;
1636 1637 1638 1639 1640
}

/* XXX: suppress the packet queue */
static void flush_packet_queue(AVFormatContext *s)
{
1641
    free_packet_buffer(&s->parse_queue,       &s->parse_queue_end);
1642 1643
    free_packet_buffer(&s->packet_buffer,     &s->packet_buffer_end);
    free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1644

1645
    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1646 1647
}

1648 1649 1650
/*******************************************************/
/* seek support */

1651 1652
int av_find_default_stream_index(AVFormatContext *s)
{
1653
    int first_audio_index = -1;
1654 1655 1656 1657 1658
    int i;
    AVStream *st;

    if (s->nb_streams <= 0)
        return -1;
1659
    for (i = 0; i < s->nb_streams; i++) {
1660
        st = s->streams[i];
1661 1662
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
            !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1663 1664
            return i;
        }
1665 1666
        if (first_audio_index < 0 &&
            st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1667
            first_audio_index = i;
1668
    }
1669
    return first_audio_index >= 0 ? first_audio_index : 0;
1670 1671
}

1672
/** Flush the frame reader. */
1673
void ff_read_frame_flush(AVFormatContext *s)
1674 1675
{
    AVStream *st;
1676
    int i, j;
1677 1678 1679

    flush_packet_queue(s);

1680 1681
    /* Reset read state for each stream. */
    for (i = 0; i < s->nb_streams; i++) {
1682
        st = s->streams[i];
1683

1684 1685 1686 1687
        if (st->parser) {
            av_parser_close(st->parser);
            st->parser = NULL;
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
1688
        st->last_IP_pts = AV_NOPTS_VALUE;
1689
        st->last_dts_for_order_check = AV_NOPTS_VALUE;
1690 1691 1692 1693 1694
        if (st->first_dts == AV_NOPTS_VALUE)
            st->cur_dts = RELATIVE_TS_BASE;
        else
            /* We set the current DTS to an unspecified origin. */
            st->cur_dts = AV_NOPTS_VALUE;
1695 1696

        st->probe_packets = MAX_PROBE_PACKETS;
1697

1698 1699
        for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
            st->pts_buffer[j] = AV_NOPTS_VALUE;
1700 1701 1702
    }
}

1703 1704
void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
{
1705 1706
    int i;

1707
    for (i = 0; i < s->nb_streams; i++) {
1708
        AVStream *st = s->streams[i];
1709

1710 1711 1712 1713
        st->cur_dts =
            av_rescale(timestamp,
                       st->time_base.den * (int64_t) ref_st->time_base.num,
                       st->time_base.num * (int64_t) ref_st->time_base.den);
1714 1715 1716
    }
}

1717 1718
void ff_reduce_index(AVFormatContext *s, int stream_index)
{
1719 1720
    AVStream *st             = s->streams[stream_index];
    unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1721

1722
    if ((unsigned) st->nb_index_entries >= max_entries) {
1723
        int i;
1724 1725 1726
        for (i = 0; 2 * i < st->nb_index_entries; i++)
            st->index_entries[i] = st->index_entries[2 * i];
        st->nb_index_entries = i;
1727 1728 1729
    }
}

1730 1731 1732
int ff_add_index_entry(AVIndexEntry **index_entries,
                       int *nb_index_entries,
                       unsigned int *index_entries_allocated_size,
1733 1734
                       int64_t pos, int64_t timestamp,
                       int size, int distance, int flags)
1735 1736
{
    AVIndexEntry *entries, *ie;
1737
    int index;
1738

1739
    if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1740
        return -1;
1741

1742
    if (timestamp == AV_NOPTS_VALUE)
1743 1744
        return AVERROR(EINVAL);

1745 1746 1747
    if (size < 0 || size > 0x3FFFFFFF)
        return AVERROR(EINVAL);

1748 1749 1750
    if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
        timestamp -= RELATIVE_TS_BASE;

1751 1752 1753
    entries = av_fast_realloc(*index_entries,
                              index_entries_allocated_size,
                              (*nb_index_entries + 1) *
1754
                              sizeof(AVIndexEntry));
1755
    if (!entries)
1756 1757
        return -1;

1758
    *index_entries = entries;
1759

1760 1761
    index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
                                      timestamp, AVSEEK_FLAG_ANY);
1762

1763 1764 1765
    if (index < 0) {
        index = (*nb_index_entries)++;
        ie    = &entries[index];
1766
        av_assert0(index == 0 || ie[-1].timestamp < timestamp);
1767 1768 1769 1770
    } else {
        ie = &entries[index];
        if (ie->timestamp != timestamp) {
            if (ie->timestamp <= timestamp)
1771
                return -1;
1772 1773
            memmove(entries + index + 1, entries + index,
                    sizeof(AVIndexEntry) * (*nb_index_entries - index));
1774
            (*nb_index_entries)++;
1775 1776 1777
        } else if (ie->pos == pos && distance < ie->min_distance)
            // do not reduce the distance
            distance = ie->min_distance;
1778
    }
1779

1780 1781 1782 1783 1784
    ie->pos          = pos;
    ie->timestamp    = timestamp;
    ie->min_distance = distance;
    ie->size         = size;
    ie->flags        = flags;
1785

1786
    return index;
1787 1788
}

1789 1790
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
                       int size, int distance, int flags)
1791
{
1792
    timestamp = wrap_timestamp(st, timestamp);
1793 1794 1795 1796 1797 1798 1799
    return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
                              &st->index_entries_allocated_size, pos,
                              timestamp, size, distance, flags);
}

int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
                              int64_t wanted_timestamp, int flags)
1800 1801 1802 1803
{
    int a, b, m;
    int64_t timestamp;

1804
    a = -1;
1805
    b = nb_entries;
1806

1807 1808 1809
    // Optimize appending index entries at the end.
    if (b && entries[b - 1].timestamp < wanted_timestamp)
        a = b - 1;
1810

1811
    while (b - a > 1) {
1812
        m         = (a + b) >> 1;
1813
        timestamp = entries[m].timestamp;
1814
        if (timestamp >= wanted_timestamp)
1815
            b = m;
1816
        if (timestamp <= wanted_timestamp)
1817
            a = m;
1818
    }
1819
    m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1820

1821 1822 1823
    if (!(flags & AVSEEK_FLAG_ANY))
        while (m >= 0 && m < nb_entries &&
               !(entries[m].flags & AVINDEX_KEYFRAME))
1824
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1825

1826
    if (m == nb_entries)
1827
        return -1;
1828
    return m;
1829 1830
}

1831
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
1832 1833 1834 1835 1836
{
    return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
                                     wanted_timestamp, flags);
}

1837 1838 1839
static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
                                 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
{
1840 1841 1842 1843
    int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
    if (stream_index >= 0)
        ts = wrap_timestamp(s->streams[stream_index], ts);
    return ts;
1844 1845
}

1846 1847
int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
                         int64_t target_ts, int flags)
1848
{
1849
    AVInputFormat *avif = s->iformat;
1850
    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1851
    int64_t ts_min, ts_max, ts;
1852
    int index;
1853
    int64_t ret;
1854 1855
    AVStream *st;

1856 1857
    if (stream_index < 0)
        return -1;
1858

1859
    av_dlog(s, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1860

1861 1862 1863
    ts_max =
    ts_min = AV_NOPTS_VALUE;
    pos_limit = -1; // GCC falsely says it may be uninitialized.
1864

1865 1866
    st = s->streams[stream_index];
    if (st->index_entries) {
1867 1868
        AVIndexEntry *e;

1869 1870 1871 1872 1873 1874
        /* FIXME: Whole function must be checked for non-keyframe entries in
         * index case, especially read_timestamp(). */
        index = av_index_search_timestamp(st, target_ts,
                                          flags | AVSEEK_FLAG_BACKWARD);
        index = FFMAX(index, 0);
        e     = &st->index_entries[index];
1875

1876 1877 1878
        if (e->timestamp <= target_ts || e->pos == e->min_distance) {
            pos_min = e->pos;
            ts_min  = e->timestamp;
1879 1880
            av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
                    pos_min, av_ts2str(ts_min));
1881
        } else {
1882
            av_assert1(index == 0);
1883
        }
1884

1885 1886
        index = av_index_search_timestamp(st, target_ts,
                                          flags & ~AVSEEK_FLAG_BACKWARD);
1887
        av_assert0(index < st->nb_index_entries);
1888 1889
        if (index >= 0) {
            e = &st->index_entries[index];
1890
            av_assert1(e->timestamp >= target_ts);
1891 1892 1893 1894
            pos_max   = e->pos;
            ts_max    = e->timestamp;
            pos_limit = pos_max - e->min_distance;
            av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
1895
                    " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
1896 1897 1898
        }
    }

1899 1900 1901
    pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
                        ts_min, ts_max, flags, &ts, avif->read_timestamp);
    if (pos < 0)
1902 1903 1904
        return -1;

    /* do the seek */
1905
    if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1906
        return ret;
1907

1908
    ff_read_frame_flush(s);
1909
    ff_update_cur_dts(s, st, ts);
1910 1911 1912 1913

    return 0;
}

1914 1915 1916
int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
                    int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
{
1917
    int64_t step = 1024;
1918 1919
    int64_t limit, ts_max;
    int64_t filesize = avio_size(s->pb);
1920 1921
    int64_t pos_max  = filesize - 1;
    do {
1922 1923
        limit = pos_max;
        pos_max = FFMAX(0, (pos_max) - step);
1924 1925 1926 1927
        ts_max  = ff_read_timestamp(s, stream_index,
                                    &pos_max, limit, read_timestamp);
        step   += step;
    } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
1928 1929 1930
    if (ts_max == AV_NOPTS_VALUE)
        return -1;

1931
    for (;;) {
1932
        int64_t tmp_pos = pos_max + 1;
1933 1934 1935
        int64_t tmp_ts  = ff_read_timestamp(s, stream_index,
                                            &tmp_pos, INT64_MAX, read_timestamp);
        if (tmp_ts == AV_NOPTS_VALUE)
1936
            break;
1937
        av_assert0(tmp_pos > pos_max);
1938 1939
        ts_max  = tmp_ts;
        pos_max = tmp_pos;
1940
        if (tmp_pos >= filesize)
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
            break;
    }

    if (ts)
        *ts = ts_max;
    if (pos)
        *pos = pos_max;

    return 0;
}

1952 1953
int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
                      int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1954 1955 1956 1957
                      int64_t ts_min, int64_t ts_max,
                      int flags, int64_t *ts_ret,
                      int64_t (*read_timestamp)(struct AVFormatContext *, int,
                                                int64_t *, int64_t))
1958
{
1959
    int64_t pos, ts;
1960
    int64_t start_pos;
1961
    int no_change;
1962
    int ret;
1963

1964
    av_dlog(s, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1965

1966
    if (ts_min == AV_NOPTS_VALUE) {
1967
        pos_min = s->data_offset;
1968
        ts_min  = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
1969 1970 1971 1972
        if (ts_min == AV_NOPTS_VALUE)
            return -1;
    }

1973 1974
    if (ts_min >= target_ts) {
        *ts_ret = ts_min;
1975 1976 1977
        return pos_min;
    }

1978
    if (ts_max == AV_NOPTS_VALUE) {
1979 1980
        if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
            return ret;
1981
        pos_limit = pos_max;
1982 1983
    }

1984 1985
    if (ts_max <= target_ts) {
        *ts_ret = ts_max;
1986 1987 1988
        return pos_max;
    }

1989
    if (ts_min > ts_max)
1990
        return -1;
1991 1992
    else if (ts_min == ts_max)
        pos_limit = pos_min;
1993

1994
    no_change = 0;
1995
    while (pos_min < pos_limit) {
1996 1997
        av_dlog(s,
                "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
1998
                pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
1999 2000
        assert(pos_limit <= pos_max);

2001 2002
        if (no_change == 0) {
            int64_t approximate_keyframe_distance = pos_max - pos_limit;
2003
            // interpolate position (better than dichotomy)
2004 2005 2006 2007 2008 2009 2010
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
                             ts_max - ts_min) +
                  pos_min - approximate_keyframe_distance;
        } else if (no_change == 1) {
            // bisection if interpolation did not change min / max pos last time
            pos = (pos_min + pos_limit) >> 1;
        } else {
2011
            /* linear search if bisection failed, can only happen if there
2012 2013
             * are very few or no keyframes between min/max */
            pos = pos_min;
2014
        }
2015 2016 2017 2018 2019 2020 2021
        if (pos <= pos_min)
            pos = pos_min + 1;
        else if (pos > pos_limit)
            pos = pos_limit;
        start_pos = pos;

        // May pass pos_limit instead of -1.
2022
        ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2023
        if (pos == pos_max)
2024 2025
            no_change++;
        else
2026
            no_change = 0;
2027 2028
        av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
                " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2029 2030
                pos_min, pos, pos_max,
                av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2031
                pos_limit, start_pos, no_change);
2032
        if (ts == AV_NOPTS_VALUE) {
2033 2034 2035
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
            return -1;
        }
2036
        assert(ts != AV_NOPTS_VALUE);
2037
        if (target_ts <= ts) {
2038
            pos_limit = start_pos - 1;
2039 2040
            pos_max   = pos;
            ts_max    = ts;
2041 2042
        }
        if (target_ts >= ts) {
2043
            pos_min = pos;
2044
            ts_min  = ts;
2045 2046
        }
    }
2047

2048 2049
    pos     = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
    ts      = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min  : ts_max;
2050
#if 0
2051
    pos_min = pos;
2052
    ts_min  = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2053
    pos_min++;
2054
    ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2055 2056
    av_dlog(s, "pos=0x%"PRIx64" %s<=%s<=%s\n",
            pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2057
#endif
2058
    *ts_ret = ts;
2059
    return pos;
2060 2061
}

2062 2063 2064
static int seek_frame_byte(AVFormatContext *s, int stream_index,
                           int64_t pos, int flags)
{
2065 2066 2067
    int64_t pos_min, pos_max;

    pos_min = s->data_offset;
2068
    pos_max = avio_size(s->pb) - 1;
2069

2070 2071 2072 2073
    if (pos < pos_min)
        pos = pos_min;
    else if (pos > pos_max)
        pos = pos_max;
2074

2075
    avio_seek(s->pb, pos, SEEK_SET);
2076

2077 2078
    s->io_repositioned = 1;

2079 2080 2081
    return 0;
}

2082 2083
static int seek_frame_generic(AVFormatContext *s, int stream_index,
                              int64_t timestamp, int flags)
2084
{
2085 2086
    int index;
    int64_t ret;
2087 2088 2089 2090
    AVStream *st;
    AVIndexEntry *ie;

    st = s->streams[stream_index];
2091

2092
    index = av_index_search_timestamp(st, timestamp, flags);
2093

2094 2095
    if (index < 0 && st->nb_index_entries &&
        timestamp < st->index_entries[0].timestamp)
2096 2097
        return -1;

2098
    if (index < 0 || index == st->nb_index_entries - 1) {
2099
        AVPacket pkt;
2100
        int nonkey = 0;
2101

2102
        if (st->nb_index_entries) {
2103
            av_assert0(st->index_entries);
2104
            ie = &st->index_entries[st->nb_index_entries - 1];
2105
            if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2106
                return ret;
2107
            ff_update_cur_dts(s, st, ie->timestamp);
2108
        } else {
2109
            if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
2110 2111
                return ret;
        }
2112
        for (;;) {
2113
            int read_status;
2114
            do {
2115 2116 2117
                read_status = av_read_frame(s, &pkt);
            } while (read_status == AVERROR(EAGAIN));
            if (read_status < 0)
2118 2119
                break;
            av_free_packet(&pkt);
2120 2121
            if (stream_index == pkt.stream_index && pkt.dts > timestamp) {
                if (pkt.flags & AV_PKT_FLAG_KEY)
2122
                    break;
2123
                if (nonkey++ > 1000 && st->codec->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2124 2125 2126
                    av_log(s, AV_LOG_ERROR,"seek_frame_generic failed as this stream seems to contain no keyframes after the target timestamp, %d non keyframes found\n", nonkey);
                    break;
                }
2127 2128 2129 2130
            }
        }
        index = av_index_search_timestamp(st, timestamp, flags);
    }
2131 2132 2133
    if (index < 0)
        return -1;

2134
    ff_read_frame_flush(s);
2135 2136
    if (s->iformat->read_seek)
        if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2137 2138
            return 0;
    ie = &st->index_entries[index];
2139
    if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2140
        return ret;
2141
    ff_update_cur_dts(s, st, ie->timestamp);
2142

2143 2144 2145
    return 0;
}

2146 2147
static int seek_frame_internal(AVFormatContext *s, int stream_index,
                               int64_t timestamp, int flags)
2148 2149
{
    int ret;
2150
    AVStream *st;
2151

2152
    if (flags & AVSEEK_FLAG_BYTE) {
2153 2154
        if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
            return -1;
2155
        ff_read_frame_flush(s);
2156
        return seek_frame_byte(s, stream_index, timestamp, flags);
2157
    }
2158

2159 2160 2161
    if (stream_index < 0) {
        stream_index = av_find_default_stream_index(s);
        if (stream_index < 0)
2162
            return -1;
2163

2164
        st = s->streams[stream_index];
2165
        /* timestamp for default must be expressed in AV_TIME_BASE units */
2166 2167
        timestamp = av_rescale(timestamp, st->time_base.den,
                               AV_TIME_BASE * (int64_t) st->time_base.num);
2168 2169
    }

2170
    /* first, we try the format specific seek */
2171 2172
    if (s->iformat->read_seek) {
        ff_read_frame_flush(s);
2173
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2174
    } else
2175
        ret = -1;
2176
    if (ret >= 0)
2177
        return 0;
2178

2179 2180
    if (s->iformat->read_timestamp &&
        !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2181
        ff_read_frame_flush(s);
2182
        return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2183 2184
    } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
        ff_read_frame_flush(s);
2185
        return seek_frame_generic(s, stream_index, timestamp, flags);
2186
    } else
2187
        return -1;
2188 2189
}

2190 2191
int av_seek_frame(AVFormatContext *s, int stream_index,
                  int64_t timestamp, int flags)
2192
{
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
    int ret;

    if (s->iformat->read_seek2 && !s->iformat->read_seek) {
        int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
        if ((flags & AVSEEK_FLAG_BACKWARD))
            max_ts = timestamp;
        else
            min_ts = timestamp;
        return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
                                  flags & ~AVSEEK_FLAG_BACKWARD);
    }
2204

2205
    ret = seek_frame_internal(s, stream_index, timestamp, flags);
2206 2207

    if (ret >= 0)
2208
        ret = avformat_queue_attached_pictures(s);
2209 2210 2211 2212

    return ret;
}

2213 2214
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
                       int64_t ts, int64_t max_ts, int flags)
2215
{
2216
    if (min_ts > ts || max_ts < ts)
2217
        return -1;
2218 2219
    if (stream_index < -1 || stream_index >= (int)s->nb_streams)
        return AVERROR(EINVAL);
2220

2221
    if (s->seek2any>0)
2222
        flags |= AVSEEK_FLAG_ANY;
2223
    flags &= ~AVSEEK_FLAG_BACKWARD;
2224

2225
    if (s->iformat->read_seek2) {
2226
        int ret;
2227
        ff_read_frame_flush(s);
2228 2229 2230 2231 2232 2233

        if (stream_index == -1 && s->nb_streams == 1) {
            AVRational time_base = s->streams[0]->time_base;
            ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
            min_ts = av_rescale_rnd(min_ts, time_base.den,
                                    time_base.num * (int64_t)AV_TIME_BASE,
2234
                                    AV_ROUND_UP   | AV_ROUND_PASS_MINMAX);
2235 2236
            max_ts = av_rescale_rnd(max_ts, time_base.den,
                                    time_base.num * (int64_t)AV_TIME_BASE,
2237
                                    AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2238 2239
        }

2240 2241
        ret = s->iformat->read_seek2(s, stream_index, min_ts,
                                     ts, max_ts, flags);
2242 2243

        if (ret >= 0)
2244
            ret = avformat_queue_attached_pictures(s);
2245
        return ret;
2246
    }
2247

2248 2249
    if (s->iformat->read_timestamp) {
        // try to seek via read_timestamp()
2250 2251
    }

Diego Biurrun's avatar
Diego Biurrun committed
2252 2253
    // Fall back on old API if new is not implemented but old is.
    // Note the old API has somewhat different semantics.
2254
    if (s->iformat->read_seek || 1) {
2255
        int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2256 2257 2258 2259 2260 2261 2262 2263
        int ret = av_seek_frame(s, stream_index, ts, flags | dir);
        if (ret<0 && ts != min_ts && max_ts != ts) {
            ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
            if (ret >= 0)
                ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
        }
        return ret;
    }
2264

2265
    // try some generic seek like seek_frame_generic() but with new ts semantics
2266
    return -1; //unreachable
2267 2268
}

2269
/*******************************************************/
2270

2271
/**
2272
 * Return TRUE if the stream has accurate duration in any stream.
2273
 *
2274
 * @return TRUE if the stream has accurate duration for at least one component.
2275
 */
2276
static int has_duration(AVFormatContext *ic)
2277 2278 2279 2280
{
    int i;
    AVStream *st;

2281
    for (i = 0; i < ic->nb_streams; i++) {
2282
        st = ic->streams[i];
2283
        if (st->duration != AV_NOPTS_VALUE)
2284 2285
            return 1;
    }
2286
    if (ic->duration != AV_NOPTS_VALUE)
2287
        return 1;
2288 2289 2290
    return 0;
}

2291 2292 2293 2294 2295
/**
 * Estimate the stream timings from the one of each components.
 *
 * Also computes the global bitrate if possible.
 */
2296
static void update_stream_timings(AVFormatContext *ic)
2297
{
2298
    int64_t start_time, start_time1, start_time_text, end_time, end_time1;
2299
    int64_t duration, duration1, filesize;
2300 2301
    int i;
    AVStream *st;
2302
    AVProgram *p;
2303

2304
    start_time = INT64_MAX;
2305
    start_time_text = INT64_MAX;
2306 2307 2308
    end_time   = INT64_MIN;
    duration   = INT64_MIN;
    for (i = 0; i < ic->nb_streams; i++) {
2309
        st = ic->streams[i];
2310
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2311 2312
            start_time1 = av_rescale_q(st->start_time, st->time_base,
                                       AV_TIME_BASE_Q);
2313
            if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codec->codec_type == AVMEDIA_TYPE_DATA) {
2314 2315 2316
                if (start_time1 < start_time_text)
                    start_time_text = start_time1;
            } else
2317
                start_time = FFMIN(start_time, start_time1);
2318
            end_time1   = AV_NOPTS_VALUE;
2319
            if (st->duration != AV_NOPTS_VALUE) {
2320 2321 2322
                end_time1 = start_time1 +
                            av_rescale_q(st->duration, st->time_base,
                                         AV_TIME_BASE_Q);
2323
                end_time = FFMAX(end_time, end_time1);
2324
            }
2325 2326
            for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
                if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2327
                    p->start_time = start_time1;
2328
                if (p->end_time < end_time1)
2329 2330
                    p->end_time = end_time1;
            }
2331
        }
2332
        if (st->duration != AV_NOPTS_VALUE) {
2333 2334 2335
            duration1 = av_rescale_q(st->duration, st->time_base,
                                     AV_TIME_BASE_Q);
            duration  = FFMAX(duration, duration1);
2336
        }
2337
    }
2338 2339
    if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
        start_time = start_time_text;
2340
    else if (start_time > start_time_text)
2341 2342
        av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);

2343
    if (start_time != INT64_MAX) {
2344
        ic->start_time = start_time;
2345 2346
        if (end_time != INT64_MIN) {
            if (ic->nb_programs) {
2347
                for (i = 0; i < ic->nb_programs; i++) {
2348
                    p = ic->programs[i];
2349
                    if (p->start_time != AV_NOPTS_VALUE && p->end_time > p->start_time)
2350 2351 2352 2353 2354
                        duration = FFMAX(duration, p->end_time - p->start_time);
                }
            } else
                duration = FFMAX(duration, end_time - start_time);
        }
2355
    }
2356
    if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2357
        ic->duration = duration;
2358
    }
2359 2360 2361 2362 2363 2364
    if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration != AV_NOPTS_VALUE) {
        /* compute the bitrate */
        double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
                         (double) ic->duration;
        if (bitrate >= 0 && bitrate <= INT_MAX)
            ic->bit_rate = bitrate;
2365 2366 2367 2368 2369 2370 2371 2372
    }
}

static void fill_all_stream_timings(AVFormatContext *ic)
{
    int i;
    AVStream *st;

2373
    update_stream_timings(ic);
2374
    for (i = 0; i < ic->nb_streams; i++) {
2375 2376
        st = ic->streams[i];
        if (st->start_time == AV_NOPTS_VALUE) {
2377 2378 2379 2380 2381 2382
            if (ic->start_time != AV_NOPTS_VALUE)
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
                                              st->time_base);
            if (ic->duration != AV_NOPTS_VALUE)
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
                                            st->time_base);
2383 2384 2385 2386
        }
    }
}

2387
static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2388 2389
{
    int64_t filesize, duration;
2390
    int i, show_warning = 0;
2391 2392 2393
    AVStream *st;

    /* if bit_rate is already set, we believe it */
2394
    if (ic->bit_rate <= 0) {
2395
        int bit_rate = 0;
2396
        for (i = 0; i < ic->nb_streams; i++) {
2397
            st = ic->streams[i];
2398
            if (st->codec->bit_rate > 0) {
2399
                if (INT_MAX - st->codec->bit_rate < bit_rate) {
2400 2401 2402 2403 2404
                    bit_rate = 0;
                    break;
                }
                bit_rate += st->codec->bit_rate;
            }
2405 2406 2407 2408 2409
        }
        ic->bit_rate = bit_rate;
    }

    /* if duration is already set, we believe it */
2410
    if (ic->duration == AV_NOPTS_VALUE &&
2411 2412
        ic->bit_rate != 0) {
        filesize = ic->pb ? avio_size(ic->pb) : 0;
2413
        if (filesize > 0) {
2414
            for (i = 0; i < ic->nb_streams; i++) {
2415
                st      = ic->streams[i];
2416 2417
                if (   st->time_base.num <= INT64_MAX / ic->bit_rate
                    && st->duration == AV_NOPTS_VALUE) {
2418 2419 2420
                    duration = av_rescale(8 * filesize, st->time_base.den,
                                          ic->bit_rate *
                                          (int64_t) st->time_base.num);
2421
                    st->duration = duration;
2422
                    show_warning = 1;
2423
                }
2424 2425 2426
            }
        }
    }
2427
    if (show_warning)
2428 2429
        av_log(ic, AV_LOG_WARNING,
               "Estimating duration from bitrate, this may be inaccurate\n");
2430 2431
}

2432
#define DURATION_MAX_READ_SIZE 250000LL
2433
#define DURATION_MAX_RETRY 4
2434 2435

/* only usable for MPEG-PS streams */
2436
static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2437 2438 2439 2440
{
    AVPacket pkt1, *pkt = &pkt1;
    AVStream *st;
    int read_size, i, ret;
2441
    int64_t end_time;
2442
    int64_t filesize, offset, duration;
2443
    int retry = 0;
2444

2445 2446 2447
    /* flush packet queue */
    flush_packet_queue(ic);

2448
    for (i = 0; i < ic->nb_streams; i++) {
2449
        st = ic->streams[i];
2450 2451 2452
        if (st->start_time == AV_NOPTS_VALUE &&
            st->first_dts == AV_NOPTS_VALUE &&
            st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN)
2453 2454
            av_log(st->codec, AV_LOG_WARNING,
                   "start time is not set in estimate_timings_from_pts\n");
2455

2456 2457
        if (st->parser) {
            av_parser_close(st->parser);
2458
            st->parser = NULL;
2459 2460
        }
    }
2461

2462 2463
    /* estimate the end time (duration) */
    /* XXX: may need to support wrapping */
2464
    filesize = ic->pb ? avio_size(ic->pb) : 0;
2465
    end_time = AV_NOPTS_VALUE;
2466 2467
    do {
        offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2468 2469
        if (offset < 0)
            offset = 0;
2470

2471 2472
        avio_seek(ic->pb, offset, SEEK_SET);
        read_size = 0;
2473 2474
        for (;;) {
            if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2475
                break;
2476

2477
            do {
2478
                ret = ff_read_packet(ic, pkt);
2479
            } while (ret == AVERROR(EAGAIN));
2480 2481 2482
            if (ret != 0)
                break;
            read_size += pkt->size;
2483
            st         = ic->streams[pkt->stream_index];
2484 2485 2486 2487 2488 2489 2490 2491 2492
            if (pkt->pts != AV_NOPTS_VALUE &&
                (st->start_time != AV_NOPTS_VALUE ||
                 st->first_dts  != AV_NOPTS_VALUE)) {
                duration = end_time = pkt->pts;
                if (st->start_time != AV_NOPTS_VALUE)
                    duration -= st->start_time;
                else
                    duration -= st->first_dts;
                if (duration > 0) {
2493
                    if (st->duration == AV_NOPTS_VALUE || st->info->last_duration<= 0 ||
2494
                        (st->duration < duration && FFABS(duration - st->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2495
                        st->duration = duration;
2496
                    st->info->last_duration = duration;
2497
                }
2498
            }
2499
            av_free_packet(pkt);
2500
        }
2501 2502 2503
    } while (end_time == AV_NOPTS_VALUE &&
             filesize > (DURATION_MAX_READ_SIZE << retry) &&
             ++retry <= DURATION_MAX_RETRY);
2504

2505
    fill_all_stream_timings(ic);
2506

2507
    avio_seek(ic->pb, old_offset, SEEK_SET);
2508
    for (i = 0; i < ic->nb_streams; i++) {
2509 2510
        int j;

2511 2512
        st              = ic->streams[i];
        st->cur_dts     = st->first_dts;
Michael Niedermayer's avatar
Michael Niedermayer committed
2513
        st->last_IP_pts = AV_NOPTS_VALUE;
2514
        st->last_dts_for_order_check = AV_NOPTS_VALUE;
2515 2516
        for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
            st->pts_buffer[j] = AV_NOPTS_VALUE;
2517
    }
2518 2519
}

2520
static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2521 2522 2523 2524 2525 2526 2527
{
    int64_t file_size;

    /* get the file size, if possible */
    if (ic->iformat->flags & AVFMT_NOFILE) {
        file_size = 0;
    } else {
2528
        file_size = avio_size(ic->pb);
2529
        file_size = FFMAX(0, file_size);
2530 2531
    }

2532 2533
    if ((!strcmp(ic->iformat->name, "mpeg") ||
         !strcmp(ic->iformat->name, "mpegts")) &&
2534
        file_size && ic->pb->seekable) {
2535
        /* get accurate estimate from the PTSes */
2536
        estimate_timings_from_pts(ic, old_offset);
2537
        ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2538
    } else if (has_duration(ic)) {
2539
        /* at least one component has timings - we use them for all
2540
         * the components */
2541
        fill_all_stream_timings(ic);
2542
        ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2543
    } else {
2544
        /* less precise: use bitrate info */
2545
        estimate_timings_from_bit_rate(ic);
2546
        ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2547
    }
2548
    update_stream_timings(ic);
2549 2550 2551

    {
        int i;
2552
        AVStream av_unused *st;
2553
        for (i = 0; i < ic->nb_streams; i++) {
2554
            st = ic->streams[i];
2555 2556 2557
            av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
                    (double) st->start_time / AV_TIME_BASE,
                    (double) st->duration   / AV_TIME_BASE);
2558
        }
2559 2560
        av_dlog(ic,
                "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2561 2562 2563
                (double) ic->start_time / AV_TIME_BASE,
                (double) ic->duration   / AV_TIME_BASE,
                ic->bit_rate / 1000);
2564 2565 2566
    }
}

2567
static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
2568
{
2569
    AVCodecContext *avctx = st->codec;
2570 2571 2572 2573 2574 2575 2576

#define FAIL(errmsg) do {                                         \
        if (errmsg_ptr)                                           \
            *errmsg_ptr = errmsg;                                 \
        return 0;                                                 \
    } while (0)

2577
    switch (avctx->codec_type) {
2578
    case AVMEDIA_TYPE_AUDIO:
2579
        if (!avctx->frame_size && determinable_frame_size(avctx))
2580
            FAIL("unspecified frame size");
2581 2582
        if (st->info->found_decoder >= 0 &&
            avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2583 2584 2585 2586 2587
            FAIL("unspecified sample format");
        if (!avctx->sample_rate)
            FAIL("unspecified sample rate");
        if (!avctx->channels)
            FAIL("unspecified number of channels");
2588 2589
        if (st->info->found_decoder >= 0 && !st->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
            FAIL("no decodable DTS frames");
2590
        break;
2591
    case AVMEDIA_TYPE_VIDEO:
2592 2593
        if (!avctx->width)
            FAIL("unspecified size");
2594
        if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2595
            FAIL("unspecified pixel format");
2596 2597 2598
        if (st->codec->codec_id == AV_CODEC_ID_RV30 || st->codec->codec_id == AV_CODEC_ID_RV40)
            if (!st->sample_aspect_ratio.num && !st->codec->sample_aspect_ratio.num && !st->codec_info_nb_frames)
                FAIL("no frame in rv30/40 and no sar");
2599
        break;
2600 2601 2602 2603
    case AVMEDIA_TYPE_SUBTITLE:
        if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
            FAIL("unspecified size");
        break;
2604
    case AVMEDIA_TYPE_DATA:
2605
        if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
2606
    }
2607

2608
    if (avctx->codec_id == AV_CODEC_ID_NONE)
2609 2610
        FAIL("unknown codec");
    return 1;
2611 2612
}

2613
/* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2614
static int try_decode_frame(AVFormatContext *s, AVStream *st, AVPacket *avpkt,
2615
                            AVDictionary **options)
2616
{
2617
    const AVCodec *codec;
2618
    int got_picture = 1, ret = 0;
2619
    AVFrame *frame = av_frame_alloc();
2620
    AVSubtitle subtitle;
2621
    AVPacket pkt = *avpkt;
2622

2623 2624 2625
    if (!frame)
        return AVERROR(ENOMEM);

2626
    if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
2627 2628
        AVDictionary *thread_opt = NULL;

2629
        codec = find_decoder(s, st, st->codec->codec_id);
2630

2631 2632
        if (!codec) {
            st->info->found_decoder = -1;
2633
            ret                     = -1;
2634
            goto fail;
2635
        }
2636

2637 2638
        /* Force thread count to 1 since the H.264 decoder will not extract
         * SPS and PPS to extradata during multi-threaded decoding. */
2639 2640 2641 2642
        av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
        ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
        if (!options)
            av_dict_free(&thread_opt);
2643 2644
        if (ret < 0) {
            st->info->found_decoder = -1;
2645
            goto fail;
2646 2647 2648 2649 2650
        }
        st->info->found_decoder = 1;
    } else if (!st->info->found_decoder)
        st->info->found_decoder = 1;

2651 2652 2653 2654
    if (st->info->found_decoder < 0) {
        ret = -1;
        goto fail;
    }
2655

2656 2657
    while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
           ret >= 0 &&
2658
           (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
2659 2660
            (!st->codec_info_nb_frames &&
             st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2661
        got_picture = 0;
2662
        switch (st->codec->codec_type) {
2663
        case AVMEDIA_TYPE_VIDEO:
2664
            ret = avcodec_decode_video2(st->codec, frame,
2665
                                        &got_picture, &pkt);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
2666
            break;
2667
        case AVMEDIA_TYPE_AUDIO:
2668
            ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
2669
            break;
2670 2671 2672 2673 2674
        case AVMEDIA_TYPE_SUBTITLE:
            ret = avcodec_decode_subtitle2(st->codec, &subtitle,
                                           &got_picture, &pkt);
            ret = pkt.size;
            break;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
2675 2676 2677
        default:
            break;
        }
2678 2679
        if (ret >= 0) {
            if (got_picture)
2680
                st->nb_decoded_frames++;
2681 2682
            pkt.data += ret;
            pkt.size -= ret;
2683
            ret       = got_picture;
2684
        }
2685
    }
2686

2687
    if (!pkt.data && !got_picture)
2688 2689
        ret = -1;

2690
fail:
2691
    av_frame_free(&frame);
2692 2693 2694
    return ret;
}

2695
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2696
{
2697
    while (tags->id != AV_CODEC_ID_NONE) {
2698 2699 2700 2701 2702 2703 2704
        if (tags->id == id)
            return tags->tag;
        tags++;
    }
    return 0;
}

2705
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2706
{
2707
    int i;
2708 2709
    for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
        if (tag == tags[i].tag)
2710
            return tags[i].id;
2711
    for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2712
        if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2713
            return tags[i].id;
2714
    return AV_CODEC_ID_NONE;
2715 2716
}

2717 2718 2719 2720
enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
{
    if (flt) {
        switch (bps) {
2721 2722 2723 2724 2725 2726
        case 32:
            return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
        case 64:
            return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
        default:
            return AV_CODEC_ID_NONE;
2727 2728
        }
    } else {
2729
        bps  += 7;
2730 2731 2732
        bps >>= 3;
        if (sflags & (1 << (bps - 1))) {
            switch (bps) {
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
            case 1:
                return AV_CODEC_ID_PCM_S8;
            case 2:
                return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
            case 3:
                return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
            case 4:
                return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
            default:
                return AV_CODEC_ID_NONE;
2743 2744 2745
            }
        } else {
            switch (bps) {
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
            case 1:
                return AV_CODEC_ID_PCM_U8;
            case 2:
                return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
            case 3:
                return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
            case 4:
                return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
            default:
                return AV_CODEC_ID_NONE;
2756 2757 2758 2759 2760
            }
        }
    }
}

2761
unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
2762 2763 2764 2765 2766 2767 2768 2769 2770
{
    unsigned int tag;
    if (!av_codec_get_tag2(tags, id, &tag))
        return 0;
    return tag;
}

int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
                      unsigned int *tag)
2771 2772
{
    int i;
2773
    for (i = 0; tags && tags[i]; i++) {
2774 2775 2776 2777 2778 2779 2780 2781
        const AVCodecTag *codec_tags = tags[i];
        while (codec_tags->id != AV_CODEC_ID_NONE) {
            if (codec_tags->id == id) {
                *tag = codec_tags->tag;
                return 1;
            }
            codec_tags++;
        }
2782 2783 2784 2785
    }
    return 0;
}

2786
enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
2787 2788
{
    int i;
2789 2790 2791 2792
    for (i = 0; tags && tags[i]; i++) {
        enum AVCodecID id = ff_codec_get_id(tags[i], tag);
        if (id != AV_CODEC_ID_NONE)
            return id;
2793
    }
2794
    return AV_CODEC_ID_NONE;
2795 2796
}

2797 2798
static void compute_chapters_end(AVFormatContext *s)
{
2799
    unsigned int i, j;
2800 2801
    int64_t max_time = s->duration +
                       ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2802

2803
    for (i = 0; i < s->nb_chapters; i++)
2804
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2805
            AVChapter *ch = s->chapters[i];
2806 2807 2808
            int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
                                                  ch->time_base)
                                   : INT64_MAX;
2809 2810

            for (j = 0; j < s->nb_chapters; j++) {
2811 2812 2813
                AVChapter *ch1     = s->chapters[j];
                int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
                                                  ch->time_base);
2814 2815 2816 2817
                if (j != i && next_start > ch->start && next_start < end)
                    end = next_start;
            }
            ch->end = (end == INT64_MAX) ? ch->start : end;
2818 2819 2820
        }
}

2821 2822 2823
static int get_std_framerate(int i)
{
    if (i < 60 * 12)
2824
        return (i + 1) * 1001;
2825
    else
2826
        return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i - 60 * 12] * 1000 * 12;
2827 2828
}

2829
/* Is the time base unreliable?
2830 2831
 * This is a heuristic to balance between quick acceptance of the values in
 * the headers vs. some extra checks.
2832 2833
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2834 2835 2836 2837 2838 2839 2840
 * And there are "variable" fps files this needs to detect as well. */
static int tb_unreliable(AVCodecContext *c)
{
    if (c->time_base.den >= 101L * c->time_base.num ||
        c->time_base.den <    5L * c->time_base.num ||
        // c->codec_tag == AV_RL32("DIVX") ||
        // c->codec_tag == AV_RL32("XVID") ||
2841
        c->codec_tag == AV_RL32("mp4v") ||
2842 2843
        c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
        c->codec_id == AV_CODEC_ID_H264)
2844 2845 2846 2847
        return 1;
    return 0;
}

2848 2849 2850 2851 2852 2853 2854
#if FF_API_FORMAT_PARAMETERS
int av_find_stream_info(AVFormatContext *ic)
{
    return avformat_find_stream_info(ic, NULL);
}
#endif

2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
int ff_alloc_extradata(AVCodecContext *avctx, int size)
{
    int ret;

    if (size < 0 || size >= INT32_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
        avctx->extradata_size = 0;
        return AVERROR(EINVAL);
    }
    avctx->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
    if (avctx->extradata) {
        memset(avctx->extradata + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
        avctx->extradata_size = size;
        ret = 0;
    } else {
        avctx->extradata_size = 0;
        ret = AVERROR(ENOMEM);
    }
    return ret;
}

2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
int ff_get_extradata(AVCodecContext *avctx, AVIOContext *pb, int size)
{
    int ret = ff_alloc_extradata(avctx, size);
    if (ret < 0)
        return ret;
    ret = avio_read(pb, avctx->extradata, size);
    if (ret != size) {
        av_freep(&avctx->extradata);
        avctx->extradata_size = 0;
        av_log(avctx, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
        return ret < 0 ? ret : AVERROR_INVALIDDATA;
    }

    return ret;
}

2891 2892 2893 2894 2895
int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
{
    int i, j;
    int64_t last = st->info->last_dts;

2896 2897 2898 2899
    if (   ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
       && ts - (uint64_t)last < INT64_MAX) {
        double dts = (is_relative(ts) ?  ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
        int64_t duration = ts - last;
2900 2901 2902 2903 2904 2905

        if (!st->info->duration_error)
            st->info->duration_error = av_mallocz(sizeof(st->info->duration_error[0])*2);
        if (!st->info->duration_error)
            return AVERROR(ENOMEM);

2906
//         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2907
//             av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
2908
        for (i = 0; i<MAX_STD_TIMEBASES; i++) {
2909
            if (st->info->duration_error[0][1][i] < 1e10) {
2910 2911 2912 2913
                int framerate = get_std_framerate(i);
                double sdts = dts*framerate/(1001*12);
                for (j= 0; j<2; j++) {
                    int64_t ticks = llrint(sdts+j*0.5);
2914 2915 2916 2917
                    double error= sdts - ticks + j*0.5;
                    st->info->duration_error[j][0][i] += error;
                    st->info->duration_error[j][1][i] += error*error;
                }
2918 2919 2920
            }
        }
        st->info->duration_count++;
2921
        st->info->rfps_duration_sum += duration;
2922 2923 2924

        if (st->info->duration_count % 10 == 0) {
            int n = st->info->duration_count;
2925
            for (i = 0; i<MAX_STD_TIMEBASES; i++) {
2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
                if (st->info->duration_error[0][1][i] < 1e10) {
                    double a0     = st->info->duration_error[0][0][i] / n;
                    double error0 = st->info->duration_error[0][1][i] / n - a0*a0;
                    double a1     = st->info->duration_error[1][0][i] / n;
                    double error1 = st->info->duration_error[1][1][i] / n - a1*a1;
                    if (error0 > 0.04 && error1 > 0.04) {
                        st->info->duration_error[0][1][i] = 2e10;
                        st->info->duration_error[1][1][i] = 2e10;
                    }
                }
            }
        }

2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952
        // ignore the first 4 values, they might have some random jitter
        if (st->info->duration_count > 3 && is_relative(ts) == is_relative(last))
            st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
    }
    if (ts != AV_NOPTS_VALUE)
        st->info->last_dts = ts;

    return 0;
}

void ff_rfps_calculate(AVFormatContext *ic)
{
    int i, j;

2953
    for (i = 0; i < ic->nb_streams; i++) {
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
        AVStream *st = ic->streams[i];

        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
            continue;
        // the check for tb_unreliable() is not completely correct, since this is not about handling
        // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
        // ipmovie.c produces.
        if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)
            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
        if (st->info->duration_count>1 && !st->r_frame_rate.num
            && tb_unreliable(st->codec)) {
            int num = 0;
            double best_error= 0.01;

2968
            for (j= 0; j<MAX_STD_TIMEBASES; j++) {
2969 2970
                int k;

2971
                if (st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))
2972
                    continue;
2973
                if (!st->info->codec_info_duration && 1.0 < (1001*12.0)/get_std_framerate(j))
2974
                    continue;
2975 2976 2977 2978

                if (av_q2d(st->time_base) * st->info->rfps_duration_sum / st->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
                    continue;

2979 2980
                for (k= 0; k<2; k++) {
                    int n = st->info->duration_count;
2981 2982 2983
                    double a= st->info->duration_error[k][0][j] / n;
                    double error= st->info->duration_error[k][1][j]/n - a*a;

2984
                    if (error < best_error && best_error> 0.000000001) {
2985 2986 2987
                        best_error= error;
                        num = get_std_framerate(j);
                    }
2988
                    if (error < 0.02)
2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999
                        av_log(NULL, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
                }
            }
            // do not increase frame rate by more than 1 % in order to match a standard rate.
            if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
        }

        av_freep(&st->info->duration_error);
        st->info->last_dts = AV_NOPTS_VALUE;
        st->info->duration_count = 0;
3000
        st->info->rfps_duration_sum = 0;
3001 3002 3003
    }
}

3004
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3005
{
3006
    int i, count, ret = 0, j;
3007
    int64_t read_size;
3008
    AVStream *st;
3009
    AVPacket pkt1, *pkt;
3010 3011 3012
    int64_t old_offset  = avio_tell(ic->pb);
    // new streams might appear, no options for those
    int orig_nb_streams = ic->nb_streams;
3013
    int flush_codecs    = ic->probesize > 0;
3014

3015
    if (ic->pb)
3016 3017
        av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d\n",
               avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count);
3018

3019
    for (i = 0; i < ic->nb_streams; i++) {
3020
        const AVCodec *codec;
3021
        AVDictionary *thread_opt = NULL;
3022
        st = ic->streams[i];
3023

3024 3025
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
            st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3026 3027 3028 3029
/*            if (!st->time_base.num)
                st->time_base = */
            if (!st->codec->time_base.num)
                st->codec->time_base = st->time_base;
3030
        }
3031
        // only for the split stuff
3032
        if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
3033
            st->parser = av_parser_init(st->codec->codec_id);
3034 3035
            if (st->parser) {
                if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3036
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3037
                } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3038 3039
                    st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
                }
3040 3041 3042 3043
            } else if (st->need_parsing) {
                av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
                       "%s, packets or times may be invalid.\n",
                       avcodec_get_name(st->codec->codec_id));
3044
            }
3045
        }
3046
        codec = find_decoder(ic, st, st->codec->codec_id);
3047

3048 3049
        /* Force thread count to 1 since the H.264 decoder will not extract
         * SPS and PPS to extradata during multi-threaded decoding. */
3050
        av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3051

3052 3053
        /* Ensure that subtitle_header is properly set. */
        if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
3054 3055
            && codec && !st->codec->codec) {
            if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3056 3057
                av_log(ic, AV_LOG_WARNING,
                       "Failed to open codec in av_find_stream_info\n");
3058
        }
3059

3060
        // Try to just open decoders, in case this is enough to get parameters.
3061
        if (!has_codec_parameters(st, NULL) && st->request_probe <= 0) {
3062
            if (codec && !st->codec->codec)
3063
                if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3064 3065
                    av_log(ic, AV_LOG_WARNING,
                           "Failed to open codec in av_find_stream_info\n");
3066
        }
3067 3068
        if (!options)
            av_dict_free(&thread_opt);
3069 3070
    }

3071
    for (i = 0; i < ic->nb_streams; i++) {
3072
#if FF_API_R_FRAME_RATE
3073
        ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
3074
#endif
3075 3076
        ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
        ic->streams[i]->info->fps_last_dts  = AV_NOPTS_VALUE;
3077
    }
3078

3079
    count     = 0;
3080
    read_size = 0;
3081 3082 3083
    for (;;) {
        if (ff_check_interrupt(&ic->interrupt_callback)) {
            ret = AVERROR_EXIT;
3084
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3085 3086 3087
            break;
        }

3088
        /* check if one codec still needs to be handled */
3089
        for (i = 0; i < ic->nb_streams; i++) {
3090 3091
            int fps_analyze_framecount = 20;

3092
            st = ic->streams[i];
3093
            if (!has_codec_parameters(st, NULL))
3094
                break;
3095 3096 3097
            /* If the timebase is coarse (like the usual millisecond precision
             * of mkv), we need to analyze more frames to reliably arrive at
             * the correct fps. */
3098 3099
            if (av_q2d(st->time_base) > 0.0005)
                fps_analyze_framecount *= 2;
3100 3101
            if (ic->fps_probe_size >= 0)
                fps_analyze_framecount = ic->fps_probe_size;
3102 3103
            if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
                fps_analyze_framecount = 0;
3104
            /* variable fps and no guess at the real fps */
3105 3106 3107
            if (tb_unreliable(st->codec) &&
                !(st->r_frame_rate.num && st->avg_frame_rate.num) &&
                st->info->duration_count < fps_analyze_framecount &&
3108
                st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3109
                break;
3110 3111
            if (st->parser && st->parser->parser->split &&
                !st->codec->extradata)
3112
                break;
3113 3114 3115
            if (st->first_dts == AV_NOPTS_VALUE &&
                (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
3116
                break;
3117 3118
        }
        if (i == ic->nb_streams) {
3119 3120
            /* NOTE: If the format has no header, then we need to read some
             * packets to get most of the streams, so we cannot stop here. */
3121
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3122
                /* If we found the info for all the codecs, we can stop. */
3123
                ret = count;
3124
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
3125
                flush_codecs = 0;
3126 3127
                break;
            }
3128
        }
3129
        /* We did not get all the codec info, but we read too much data. */
3130
        if (read_size >= ic->probesize) {
Michael Niedermayer's avatar
Michael Niedermayer committed
3131
            ret = count;
3132
            av_log(ic, AV_LOG_DEBUG,
3133
                   "Probe buffer size limit of %d bytes reached\n", ic->probesize);
3134 3135
            for (i = 0; i < ic->nb_streams; i++)
                if (!ic->streams[i]->r_frame_rate.num &&
3136
                    ic->streams[i]->info->duration_count <= 1 &&
3137
                    ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3138
                    strcmp(ic->iformat->name, "image2"))
3139 3140 3141
                    av_log(ic, AV_LOG_WARNING,
                           "Stream #%d: not enough frames to estimate rate; "
                           "consider increasing probesize\n", i);
Michael Niedermayer's avatar
Michael Niedermayer committed
3142 3143
            break;
        }
3144

3145 3146
        /* NOTE: A new stream can be added there if no header in file
         * (AVFMTCTX_NOHEADER). */
3147
        ret = read_frame_internal(ic, &pkt1);
3148 3149 3150 3151
        if (ret == AVERROR(EAGAIN))
            continue;

        if (ret < 0) {
3152
            /* EOF or error*/
3153 3154 3155
            break;
        }

3156 3157 3158
        if (ic->flags & AVFMT_FLAG_NOBUFFER)
            free_packet_buffer(&ic->packet_buffer, &ic->packet_buffer_end);
        {
3159 3160
            pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
                                &ic->packet_buffer_end);
3161 3162
            if (!pkt) {
                ret = AVERROR(ENOMEM);
3163
                goto find_stream_info_err;
3164
            }
3165 3166 3167
            if ((ret = av_dup_packet(pkt)) < 0)
                goto find_stream_info_err;
        }
3168 3169

        st = ic->streams[pkt->stream_index];
3170 3171 3172
        if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
            read_size += pkt->size;

3173 3174 3175 3176
        if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
            /* check for non-increasing dts */
            if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
                st->info->fps_last_dts >= pkt->dts) {
3177
                av_log(ic, AV_LOG_DEBUG,
3178 3179 3180 3181 3182 3183 3184
                       "Non-increasing DTS in stream %d: packet %d with DTS "
                       "%"PRId64", packet %d with DTS %"PRId64"\n",
                       st->index, st->info->fps_last_dts_idx,
                       st->info->fps_last_dts, st->codec_info_nb_frames,
                       pkt->dts);
                st->info->fps_first_dts =
                st->info->fps_last_dts  = AV_NOPTS_VALUE;
3185
            }
3186 3187 3188
            /* Check for a discontinuity in dts. If the difference in dts
             * is more than 1000 times the average packet duration in the
             * sequence, we treat it as a discontinuity. */
3189 3190 3191
            if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
                st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
                (pkt->dts - st->info->fps_last_dts) / 1000 >
3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
                (st->info->fps_last_dts     - st->info->fps_first_dts) /
                (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
                av_log(ic, AV_LOG_WARNING,
                       "DTS discontinuity in stream %d: packet %d with DTS "
                       "%"PRId64", packet %d with DTS %"PRId64"\n",
                       st->index, st->info->fps_last_dts_idx,
                       st->info->fps_last_dts, st->codec_info_nb_frames,
                       pkt->dts);
                st->info->fps_first_dts =
                st->info->fps_last_dts  = AV_NOPTS_VALUE;
3202
            }
3203 3204 3205 3206 3207 3208

            /* update stored dts values */
            if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
                st->info->fps_first_dts     = pkt->dts;
                st->info->fps_first_dts_idx = st->codec_info_nb_frames;
            }
3209
            st->info->fps_last_dts     = pkt->dts;
3210
            st->info->fps_last_dts_idx = st->codec_info_nb_frames;
3211
        }
3212
        if (st->codec_info_nb_frames>1) {
3213
            int64_t t = 0;
3214 3215 3216
            if (st->time_base.den > 0)
                t = av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
            if (st->avg_frame_rate.num > 0)
3217
                t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3218

3219
            if (   t == 0
3220
                && st->codec_info_nb_frames>30
3221 3222 3223 3224
                && st->info->fps_first_dts != AV_NOPTS_VALUE
                && st->info->fps_last_dts  != AV_NOPTS_VALUE)
                t = FFMAX(t, av_rescale_q(st->info->fps_last_dts - st->info->fps_first_dts, st->time_base, AV_TIME_BASE_Q));

3225
            if (t >= ic->max_analyze_duration) {
3226
                av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %d reached at %"PRId64" microseconds\n", ic->max_analyze_duration, t);
3227
                break;
3228
            }
3229 3230
            if (pkt->duration) {
                st->info->codec_info_duration        += pkt->duration;
3231
                st->info->codec_info_duration_fields += st->parser && st->need_parsing && st->codec->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3232
            }
3233
        }
3234
#if FF_API_R_FRAME_RATE
3235
        ff_rfps_add_frame(ic, st, pkt->dts);
3236
#endif
3237 3238
        if (st->parser && st->parser->parser->split && !st->codec->extradata) {
            int i = st->parser->parser->split(st->codec, pkt->data, pkt->size);
3239
            if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
3240
                if (ff_alloc_extradata(st->codec, i))
3241
                    return AVERROR(ENOMEM);
3242 3243
                memcpy(st->codec->extradata, pkt->data,
                       st->codec->extradata_size);
3244 3245
            }
        }
3246

3247 3248 3249 3250 3251 3252 3253 3254 3255
        /* If still no information, we try to open the codec and to
         * decompress the frame. We try to avoid that in most cases as
         * it takes longer and uses more memory. For MPEG-4, we need to
         * decompress for QuickTime.
         *
         * If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
         * least one frame of codec data, this makes sure the codec initializes
         * the channel configuration and does not only trust the values from
         * the container. */
3256
        try_decode_frame(ic, st, pkt,
3257
                         (options && i < orig_nb_streams) ? &options[i] : NULL);
3258

3259
        st->codec_info_nb_frames++;
3260 3261 3262
        count++;
    }

3263 3264
    if (flush_codecs) {
        AVPacket empty_pkt = { 0 };
3265
        int err = 0;
3266 3267
        av_init_packet(&empty_pkt);

3268
        for (i = 0; i < ic->nb_streams; i++) {
3269

3270 3271 3272
            st = ic->streams[i];

            /* flush the decoders */
3273 3274
            if (st->info->found_decoder == 1) {
                do {
3275
                    err = try_decode_frame(ic, st, &empty_pkt,
3276 3277
                                            (options && i < orig_nb_streams)
                                            ? &options[i] : NULL);
3278
                } while (err > 0 && !has_codec_parameters(st, NULL));
3279 3280 3281 3282 3283

                if (err < 0) {
                    av_log(ic, AV_LOG_INFO,
                        "decoding for stream %d failed\n", st->index);
                }
3284
            }
3285 3286 3287
        }
    }

Diego Biurrun's avatar
Diego Biurrun committed
3288
    // close codecs which were opened in try_decode_frame()
3289
    for (i = 0; i < ic->nb_streams; i++) {
3290
        st = ic->streams[i];
3291
        avcodec_close(st->codec);
3292
    }
3293 3294 3295

    ff_rfps_calculate(ic);

3296
    for (i = 0; i < ic->nb_streams; i++) {
3297
        st = ic->streams[i];
3298
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3299
            if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample) {
3300
                uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
3301
                if (avpriv_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)
3302 3303
                    st->codec->codec_tag= tag;
            }
3304

3305
            /* estimate average framerate if not set by demuxer */
3306 3307 3308
            if (st->info->codec_info_duration_fields &&
                !st->avg_frame_rate.num &&
                st->info->codec_info_duration) {
3309
                int best_fps      = 0;
3310
                double best_error = 0.01;
3311

3312
                if (st->info->codec_info_duration        >= INT64_MAX / st->time_base.num / 2||
3313 3314
                    st->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
                    st->info->codec_info_duration        < 0)
3315
                    continue;
3316
                av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3317 3318
                          st->info->codec_info_duration_fields * (int64_t) st->time_base.den,
                          st->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3319

3320 3321
                /* Round guessed framerate to a "standard" framerate if it's
                 * within 1% of the original estimate. */
3322
                for (j = 0; j < MAX_STD_TIMEBASES; j++) {
3323 3324 3325
                    AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
                    double error       = fabs(av_q2d(st->avg_frame_rate) /
                                              av_q2d(std_fps) - 1);
3326 3327 3328 3329 3330 3331

                    if (error < best_error) {
                        best_error = error;
                        best_fps   = std_fps.num;
                    }
                }
3332
                if (best_fps)
3333
                    av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3334
                              best_fps, 12 * 1001, INT_MAX);
3335
            }
3336

3337 3338 3339
            if (!st->r_frame_rate.num) {
                if (    st->codec->time_base.den * (int64_t) st->time_base.num
                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t) st->time_base.den) {
3340
                    st->r_frame_rate.num = st->codec->time_base.den;
3341
                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
3342
                } else {
3343 3344 3345
                    st->r_frame_rate.num = st->time_base.den;
                    st->r_frame_rate.den = st->time_base.num;
                }
3346
            }
3347 3348 3349 3350
        } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
            if (!st->codec->bits_per_coded_sample)
                st->codec->bits_per_coded_sample =
                    av_get_bits_per_sample(st->codec->codec_id);
3351 3352 3353
            // set stream disposition based on audio service type
            switch (st->codec->audio_service_type) {
            case AV_AUDIO_SERVICE_TYPE_EFFECTS:
3354 3355
                st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
                break;
3356
            case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
3357 3358
                st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
                break;
3359
            case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
3360 3361
                st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
                break;
3362
            case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
3363 3364
                st->disposition = AV_DISPOSITION_COMMENT;
                break;
3365
            case AV_AUDIO_SERVICE_TYPE_KARAOKE:
3366 3367
                st->disposition = AV_DISPOSITION_KARAOKE;
                break;
3368
            }
3369
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
3370
    }
3371

3372
    if (ic->probesize)
3373
    estimate_timings(ic, old_offset);
John Donaghy's avatar
John Donaghy committed
3374

3375
    if (ret >= 0 && ic->nb_streams)
3376 3377 3378
        /* We could not have all the codec parameters before EOF. */
        ret = -1;
    for (i = 0; i < ic->nb_streams; i++) {
3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392
        const char *errmsg;
        st = ic->streams[i];
        if (!has_codec_parameters(st, &errmsg)) {
            char buf[256];
            avcodec_string(buf, sizeof(buf), st->codec, 0);
            av_log(ic, AV_LOG_WARNING,
                   "Could not find codec parameters for stream %d (%s): %s\n"
                   "Consider increasing the value for the 'analyzeduration' and 'probesize' options\n",
                   i, buf, errmsg);
        } else {
            ret = 0;
        }
    }

3393 3394
    compute_chapters_end(ic);

3395 3396
find_stream_info_err:
    for (i = 0; i < ic->nb_streams; i++) {
3397
        st = ic->streams[i];
3398
        if (ic->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
3399
            ic->streams[i]->codec->thread_count = 0;
3400 3401
        if (st->info)
            av_freep(&st->info->duration_error);
3402
        av_freep(&ic->streams[i]->info);
3403
    }
3404
    if (ic->pb)
3405 3406
        av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
               avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
3407
    return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
3408 3409
}

3410
AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
3411 3412 3413
{
    int i, j;

3414 3415 3416 3417 3418 3419 3420 3421 3422 3423
    for (i = 0; i < ic->nb_programs; i++) {
        if (ic->programs[i] == last) {
            last = NULL;
        } else {
            if (!last)
                for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
                    if (ic->programs[i]->stream_index[j] == s)
                        return ic->programs[i];
        }
    }
3424 3425 3426
    return NULL;
}

3427 3428 3429
int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
                        int wanted_stream_nb, int related_stream,
                        AVCodec **decoder_ret, int flags)
3430
{
3431
    int i, nb_streams = ic->nb_streams;
3432
    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1, best_bitrate = -1, best_multiframe = -1, count, bitrate, multiframe;
3433 3434 3435 3436
    unsigned *program = NULL;
    AVCodec *decoder = NULL, *best_decoder = NULL;

    if (related_stream >= 0 && wanted_stream_nb < 0) {
3437
        AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
3438
        if (p) {
3439
            program    = p->stream_index;
3440 3441 3442 3443
            nb_streams = p->nb_stream_indexes;
        }
    }
    for (i = 0; i < nb_streams; i++) {
3444
        int real_stream_index = program ? program[i] : i;
3445
        AVStream *st          = ic->streams[real_stream_index];
3446 3447 3448
        AVCodecContext *avctx = st->codec;
        if (avctx->codec_type != type)
            continue;
3449
        if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
3450
            continue;
3451 3452
        if (wanted_stream_nb != real_stream_index &&
            st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |
3453
                               AV_DISPOSITION_VISUAL_IMPAIRED))
3454
            continue;
3455 3456
        if (type == AVMEDIA_TYPE_AUDIO && !avctx->channels)
            continue;
3457
        if (decoder_ret) {
3458
            decoder = find_decoder(ic, st, st->codec->codec_id);
3459 3460 3461 3462 3463 3464
            if (!decoder) {
                if (ret < 0)
                    ret = AVERROR_DECODER_NOT_FOUND;
                continue;
            }
        }
3465 3466 3467 3468 3469 3470
        count = st->codec_info_nb_frames;
        bitrate = avctx->bit_rate;
        multiframe = FFMIN(5, count);
        if ((best_multiframe >  multiframe) ||
            (best_multiframe == multiframe && best_bitrate >  bitrate) ||
            (best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
3471
            continue;
3472
        best_count   = count;
3473 3474
        best_bitrate = bitrate;
        best_multiframe = multiframe;
3475
        ret          = real_stream_index;
3476 3477
        best_decoder = decoder;
        if (program && i == nb_streams - 1 && ret < 0) {
3478
            program    = NULL;
3479
            nb_streams = ic->nb_streams;
3480 3481
            /* no related stream found, try again with everything */
            i = 0;
3482 3483 3484 3485 3486 3487 3488
        }
    }
    if (decoder_ret)
        *decoder_ret = best_decoder;
    return ret;
}

3489 3490 3491 3492
/*******************************************************/

int av_read_play(AVFormatContext *s)
{
3493 3494
    if (s->iformat->read_play)
        return s->iformat->read_play(s);
3495
    if (s->pb)
3496
        return avio_pause(s->pb, 0);
3497
    return AVERROR(ENOSYS);
3498 3499 3500 3501
}

int av_read_pause(AVFormatContext *s)
{
3502 3503
    if (s->iformat->read_pause)
        return s->iformat->read_pause(s);
3504
    if (s->pb)
3505
        return avio_pause(s->pb, 1);
3506
    return AVERROR(ENOSYS);
3507 3508
}

3509
void ff_free_stream(AVFormatContext *s, AVStream *st) {
3510
    av_assert0(s->nb_streams>0);
3511
    av_assert0(s->streams[ s->nb_streams - 1 ] == st);
3512 3513 3514 3515 3516 3517 3518

    if (st->parser) {
        av_parser_close(st->parser);
    }
    if (st->attached_pic.data)
        av_free_packet(&st->attached_pic);
    av_dict_free(&st->metadata);
3519
    av_freep(&st->probe_data.buf);
3520 3521 3522 3523 3524
    av_freep(&st->index_entries);
    av_freep(&st->codec->extradata);
    av_freep(&st->codec->subtitle_header);
    av_freep(&st->codec);
    av_freep(&st->priv_data);
3525 3526
    if (st->info)
        av_freep(&st->info->duration_error);
3527 3528 3529 3530
    av_freep(&st->info);
    av_freep(&s->streams[ --s->nb_streams ]);
}

3531 3532 3533 3534
void avformat_free_context(AVFormatContext *s)
{
    int i;

3535 3536 3537
    if (!s)
        return;

3538
    av_opt_free(s);
3539
    if (s->iformat && s->iformat->priv_class && s->priv_data)
3540 3541
        av_opt_free(s->priv_data);

3542
    for (i = s->nb_streams - 1; i >= 0; i--) {
3543
        ff_free_stream(s, s->streams[i]);
Fabrice Bellard's avatar
Fabrice Bellard committed
3544
    }
3545
    for (i = s->nb_programs - 1; i >= 0; i--) {
3546
        av_dict_free(&s->programs[i]->metadata);
3547
        av_freep(&s->programs[i]->stream_index);
3548 3549
        av_freep(&s->programs[i]);
    }
Michael Niedermayer's avatar
Michael Niedermayer committed
3550
    av_freep(&s->programs);
3551
    av_freep(&s->priv_data);
3552
    while (s->nb_chapters--) {
3553
        av_dict_free(&s->chapters[s->nb_chapters]->metadata);
3554
        av_freep(&s->chapters[s->nb_chapters]);
3555 3556
    }
    av_freep(&s->chapters);
3557
    av_dict_free(&s->metadata);
3558
    av_freep(&s->streams);
3559
    av_freep(&s->internal);
3560
    av_free(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
3561 3562
}

3563
#if FF_API_CLOSE_INPUT_FILE
3564 3565
void av_close_input_file(AVFormatContext *s)
{
3566 3567 3568 3569 3570 3571
    avformat_close_input(&s);
}
#endif

void avformat_close_input(AVFormatContext **ps)
{
3572 3573 3574 3575 3576 3577
    AVFormatContext *s;
    AVIOContext *pb;

    if (!ps || !*ps)
        return;

3578
    s  = *ps;
3579
    pb = s->pb;
3580

3581
    if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
3582 3583 3584
        (s->flags & AVFMT_FLAG_CUSTOM_IO))
        pb = NULL;

3585
    flush_packet_queue(s);
3586

3587
    if (s->iformat)
3588 3589 3590
        if (s->iformat->read_close)
            s->iformat->read_close(s);

3591
    avformat_free_context(s);
3592

3593
    *ps = NULL;
3594 3595

    avio_close(pb);
3596 3597
}

3598 3599 3600 3601 3602 3603 3604 3605 3606 3607
#if FF_API_NEW_STREAM
AVStream *av_new_stream(AVFormatContext *s, int id)
{
    AVStream *st = avformat_new_stream(s, NULL);
    if (st)
        st->id = id;
    return st;
}
#endif

3608
AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
3609 3610
{
    AVStream *st;
3611
    int i;
3612
    AVStream **streams;
3613

3614
    if (s->nb_streams >= INT_MAX/sizeof(*streams))
3615
        return NULL;
3616
    streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
3617 3618 3619
    if (!streams)
        return NULL;
    s->streams = streams;
3620 3621 3622 3623

    st = av_mallocz(sizeof(AVStream));
    if (!st)
        return NULL;
3624 3625 3626 3627
    if (!(st->info = av_mallocz(sizeof(*st->info)))) {
        av_free(st);
        return NULL;
    }
3628
    st->info->last_dts = AV_NOPTS_VALUE;
3629

3630
    st->codec = avcodec_alloc_context3(c);
3631
    if (s->iformat)
3632
        /* no default bitrate if decoding */
3633
        st->codec->bit_rate = 0;
3634
    st->index      = s->nb_streams;
3635
    st->start_time = AV_NOPTS_VALUE;
3636 3637 3638 3639 3640
    st->duration   = AV_NOPTS_VALUE;
    /* we set the current DTS to 0 so that formats without any timestamps
     * but durations get some timestamps, formats with some unknown
     * timestamps have their first few packets buffered and the
     * timestamps corrected before they are returned to the user */
3641
    st->cur_dts       = s->iformat ? RELATIVE_TS_BASE : 0;
3642
    st->first_dts     = AV_NOPTS_VALUE;
3643
    st->probe_packets = MAX_PROBE_PACKETS;
3644 3645
    st->pts_wrap_reference = AV_NOPTS_VALUE;
    st->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
3646

3647
    /* default pts setting is MPEG-like */
3648
    avpriv_set_pts_info(st, 33, 1, 90000);
Michael Niedermayer's avatar
Michael Niedermayer committed
3649
    st->last_IP_pts = AV_NOPTS_VALUE;
3650
    st->last_dts_for_order_check = AV_NOPTS_VALUE;
3651 3652
    for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
        st->pts_buffer[i] = AV_NOPTS_VALUE;
3653

3654
    st->sample_aspect_ratio = (AVRational) { 0, 1 };
3655

3656 3657 3658 3659 3660 3661
#if FF_API_R_FRAME_RATE
    st->info->last_dts      = AV_NOPTS_VALUE;
#endif
    st->info->fps_first_dts = AV_NOPTS_VALUE;
    st->info->fps_last_dts  = AV_NOPTS_VALUE;

3662 3663 3664 3665
    s->streams[s->nb_streams++] = st;
    return st;
}

3666 3667
AVProgram *av_new_program(AVFormatContext *ac, int id)
{
3668
    AVProgram *program = NULL;
3669 3670
    int i;

3671
    av_dlog(ac, "new_program: id=0x%04x\n", id);
3672

3673 3674
    for (i = 0; i < ac->nb_programs; i++)
        if (ac->programs[i]->id == id)
3675 3676
            program = ac->programs[i];

3677
    if (!program) {
3678 3679 3680 3681 3682 3683 3684
        program = av_mallocz(sizeof(AVProgram));
        if (!program)
            return NULL;
        dynarray_add(&ac->programs, &ac->nb_programs, program);
        program->discard = AVDISCARD_NONE;
    }
    program->id = id;
3685 3686
    program->pts_wrap_reference = AV_NOPTS_VALUE;
    program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
3687

3688 3689 3690
    program->start_time =
    program->end_time   = AV_NOPTS_VALUE;

3691 3692 3693
    return program;
}

3694 3695
AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
                              int64_t start, int64_t end, const char *title)
3696
{
3697 3698 3699
    AVChapter *chapter = NULL;
    int i;

3700 3701
    for (i = 0; i < s->nb_chapters; i++)
        if (s->chapters[i]->id == id)
3702 3703
            chapter = s->chapters[i];

3704 3705 3706
    if (!chapter) {
        chapter = av_mallocz(sizeof(AVChapter));
        if (!chapter)
3707
            return NULL;
3708
        dynarray_add(&s->chapters, &s->nb_chapters, chapter);
3709
    }
3710
    av_dict_set(&chapter->metadata, "title", title, 0);
3711 3712 3713 3714
    chapter->id        = id;
    chapter->time_base = time_base;
    chapter->start     = start;
    chapter->end       = end;
3715

3716
    return chapter;
3717
}
3718

3719
void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
3720 3721
{
    int i, j;
3722
    AVProgram *program = NULL;
3723
    void *tmp;
3724

3725 3726 3727 3728 3729
    if (idx >= ac->nb_streams) {
        av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
        return;
    }

3730 3731
    for (i = 0; i < ac->nb_programs; i++) {
        if (ac->programs[i]->id != progid)
3732 3733
            continue;
        program = ac->programs[i];
3734 3735
        for (j = 0; j < program->nb_stream_indexes; j++)
            if (program->stream_index[j] == idx)
3736 3737
                return;

3738
        tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
3739
        if (!tmp)
3740
            return;
3741
        program->stream_index = tmp;
3742 3743 3744 3745 3746
        program->stream_index[program->nb_stream_indexes++] = idx;
        return;
    }
}

3747 3748 3749 3750 3751 3752 3753 3754 3755
static void print_fps(double d, const char *postfix)
{
    uint64_t v = lrintf(d * 100);
    if (v % 100)
        av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
    else if (v % (100 * 1000))
        av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
    else
        av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d / 1000, postfix);
3756 3757
}

3758
static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
3759
{
3760 3761
    if (m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))) {
        AVDictionaryEntry *tag = NULL;
3762 3763

        av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
3764
        while ((tag = av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX)))
3765
            if (strcmp("language", tag->key)) {
3766
                const char *p = tag->value;
3767
                av_log(ctx, AV_LOG_INFO,
3768 3769
                       "%s  %-16s: ", indent, tag->key);
                while (*p) {
3770
                    char tmp[256];
3771
                    size_t len = strcspn(p, "\x8\xa\xb\xc\xd");
3772 3773 3774 3775 3776 3777 3778 3779
                    av_strlcpy(tmp, p, FFMIN(sizeof(tmp), len+1));
                    av_log(ctx, AV_LOG_INFO, "%s", tmp);
                    p += len;
                    if (*p == 0xd) av_log(ctx, AV_LOG_INFO, " ");
                    if (*p == 0xa) av_log(ctx, AV_LOG_INFO, "\n%s  %-16s: ", indent, "");
                    if (*p) p++;
                }
                av_log(ctx, AV_LOG_INFO, "\n");
3780
            }
3781 3782 3783
    }
}

Fabrice Bellard's avatar
Fabrice Bellard committed
3784
/* "user interface" functions */
3785 3786
static void dump_stream_format(AVFormatContext *ic, int i,
                               int index, int is_output)
3787
{
3788
    char buf[256];
3789 3790
    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
    AVStream *st = ic->streams[i];
3791
    int g = av_gcd(st->time_base.num, st->time_base.den);
3792
    AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
3793
    avcodec_string(buf, sizeof(buf), st->codec, is_output);
3794
    av_log(NULL, AV_LOG_INFO, "    Stream #%d:%d", index, i);
3795 3796 3797 3798
    /* the pid is an important information, so we display it */
    /* XXX: add a generic system */
    if (flags & AVFMT_SHOW_IDS)
        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
3799 3800
    if (lang)
        av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
3801 3802
    av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames,
           st->time_base.num / g, st->time_base.den / g);
3803
    av_log(NULL, AV_LOG_INFO, ": %s", buf);
3804 3805 3806 3807
    if (st->sample_aspect_ratio.num && // default
        av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
        AVRational display_aspect_ratio;
        av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3808 3809 3810
                  st->codec->width  * st->sample_aspect_ratio.num,
                  st->codec->height * st->sample_aspect_ratio.den,
                  1024 * 1024);
3811
        av_log(NULL, AV_LOG_INFO, ", SAR %d:%d DAR %d:%d",
3812 3813
               st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
               display_aspect_ratio.num, display_aspect_ratio.den);
3814
    }
3815 3816
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
        if (st->avg_frame_rate.den && st->avg_frame_rate.num)
3817
            print_fps(av_q2d(st->avg_frame_rate), "fps");
3818
#if FF_API_R_FRAME_RATE
3819
        if (st->r_frame_rate.den && st->r_frame_rate.num)
3820
            print_fps(av_q2d(st->r_frame_rate), "tbr");
3821
#endif
3822 3823 3824 3825
        if (st->time_base.den && st->time_base.num)
            print_fps(1 / av_q2d(st->time_base), "tbn");
        if (st->codec->time_base.den && st->codec->time_base.num)
            print_fps(1 / av_q2d(st->codec->time_base), "tbc");
3826
    }
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844
    if (st->disposition & AV_DISPOSITION_DEFAULT)
        av_log(NULL, AV_LOG_INFO, " (default)");
    if (st->disposition & AV_DISPOSITION_DUB)
        av_log(NULL, AV_LOG_INFO, " (dub)");
    if (st->disposition & AV_DISPOSITION_ORIGINAL)
        av_log(NULL, AV_LOG_INFO, " (original)");
    if (st->disposition & AV_DISPOSITION_COMMENT)
        av_log(NULL, AV_LOG_INFO, " (comment)");
    if (st->disposition & AV_DISPOSITION_LYRICS)
        av_log(NULL, AV_LOG_INFO, " (lyrics)");
    if (st->disposition & AV_DISPOSITION_KARAOKE)
        av_log(NULL, AV_LOG_INFO, " (karaoke)");
    if (st->disposition & AV_DISPOSITION_FORCED)
        av_log(NULL, AV_LOG_INFO, " (forced)");
    if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
        av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
    if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
        av_log(NULL, AV_LOG_INFO, " (visual impaired)");
3845 3846
    if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
        av_log(NULL, AV_LOG_INFO, " (clean effects)");
3847
    av_log(NULL, AV_LOG_INFO, "\n");
3848
    dump_metadata(NULL, st->metadata, "    ");
3849
}
Fabrice Bellard's avatar
Fabrice Bellard committed
3850

3851 3852
void av_dump_format(AVFormatContext *ic, int index,
                    const char *url, int is_output)
Fabrice Bellard's avatar
Fabrice Bellard committed
3853
{
3854
    int i;
3855
    uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
3856 3857
    if (ic->nb_streams && !printed)
        return;
Fabrice Bellard's avatar
Fabrice Bellard committed
3858

3859
    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
3860 3861 3862 3863
           is_output ? "Output" : "Input",
           index,
           is_output ? ic->oformat->name : ic->iformat->name,
           is_output ? "to" : "from", url);
3864
    dump_metadata(NULL, ic->metadata, "  ");
3865
    if (!is_output) {
3866
        av_log(NULL, AV_LOG_INFO, "  Duration: ");
3867 3868
        if (ic->duration != AV_NOPTS_VALUE) {
            int hours, mins, secs, us;
3869
            int64_t duration = ic->duration + 5000;
3870 3871
            secs  = duration / AV_TIME_BASE;
            us    = duration % AV_TIME_BASE;
3872
            mins  = secs / 60;
3873 3874 3875
            secs %= 60;
            hours = mins / 60;
            mins %= 60;
3876 3877
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
                   (100 * us) / AV_TIME_BASE);
3878
        } else {
3879
            av_log(NULL, AV_LOG_INFO, "N/A");
3880
        }
3881 3882
        if (ic->start_time != AV_NOPTS_VALUE) {
            int secs, us;
3883
            av_log(NULL, AV_LOG_INFO, ", start: ");
3884
            secs = ic->start_time / AV_TIME_BASE;
3885
            us   = abs(ic->start_time % AV_TIME_BASE);
3886
            av_log(NULL, AV_LOG_INFO, "%d.%06d",
3887
                   secs, (int) av_rescale(us, 1000000, AV_TIME_BASE));
3888
        }
3889
        av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3890 3891 3892
        if (ic->bit_rate)
            av_log(NULL, AV_LOG_INFO, "%d kb/s", ic->bit_rate / 1000);
        else
3893 3894
            av_log(NULL, AV_LOG_INFO, "N/A");
        av_log(NULL, AV_LOG_INFO, "\n");
3895
    }
3896 3897 3898
    for (i = 0; i < ic->nb_chapters; i++) {
        AVChapter *ch = ic->chapters[i];
        av_log(NULL, AV_LOG_INFO, "    Chapter #%d.%d: ", index, i);
3899 3900 3901 3902
        av_log(NULL, AV_LOG_INFO,
               "start %f, ", ch->start * av_q2d(ch->time_base));
        av_log(NULL, AV_LOG_INFO,
               "end %f\n", ch->end * av_q2d(ch->time_base));
3903 3904 3905

        dump_metadata(NULL, ch->metadata, "    ");
    }
3906
    if (ic->nb_programs) {
3907
        int j, k, total = 0;
3908
        for (j = 0; j < ic->nb_programs; j++) {
3909
            AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
3910
                                                  "name", NULL, 0);
3911
            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,
3912
                   name ? name->value : "");
3913
            dump_metadata(NULL, ic->programs[j]->metadata, "    ");
3914 3915 3916
            for (k = 0; k < ic->programs[j]->nb_stream_indexes; k++) {
                dump_stream_format(ic, ic->programs[j]->stream_index[k],
                                   index, is_output);
3917 3918 3919 3920 3921 3922 3923
                printed[ic->programs[j]->stream_index[k]] = 1;
            }
            total += ic->programs[j]->nb_stream_indexes;
        }
        if (total < ic->nb_streams)
            av_log(NULL, AV_LOG_INFO, "  No Program\n");
    }
3924
    for (i = 0; i < ic->nb_streams; i++)
3925
        if (!printed[i])
3926
            dump_stream_format(ic, i, index, is_output);
3927 3928

    av_free(printed);
Fabrice Bellard's avatar
Fabrice Bellard committed
3929 3930
}

3931 3932
uint64_t ff_ntp_time(void)
{
3933
    return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3934 3935
}

3936
int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
3937 3938
{
    const char *p;
3939 3940
    char *q, buf1[20], c;
    int nd, len, percentd_found;
3941 3942 3943 3944

    q = buf;
    p = path;
    percentd_found = 0;
3945
    for (;;) {
3946 3947 3948 3949
        c = *p++;
        if (c == '\0')
            break;
        if (c == '%') {
3950 3951
            do {
                nd = 0;
3952
                while (av_isdigit(*p))
3953 3954
                    nd = nd * 10 + *p++ - '0';
                c = *p++;
3955
            } while (av_isdigit(c));
3956

3957
            switch (c) {
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974
            case '%':
                goto addchar;
            case 'd':
                if (percentd_found)
                    goto fail;
                percentd_found = 1;
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
                len = strlen(buf1);
                if ((q - buf + len) > buf_size - 1)
                    goto fail;
                memcpy(q, buf1, len);
                q += len;
                break;
            default:
                goto fail;
            }
        } else {
3975
addchar:
3976 3977 3978 3979 3980 3981 3982 3983
            if ((q - buf) < buf_size - 1)
                *q++ = c;
        }
    }
    if (!percentd_found)
        goto fail;
    *q = '\0';
    return 0;
3984
fail:
3985 3986 3987 3988
    *q = '\0';
    return -1;
}

3989
#define HEXDUMP_PRINT(...)                      \
3990 3991 3992 3993 3994 3995
    do {                                        \
        if (!f)                                 \
            av_log(avcl, level, __VA_ARGS__);   \
        else                                    \
            fprintf(f, __VA_ARGS__);            \
    } while (0)
3996

3997 3998 3999 4000 4001
static void hex_dump_internal(void *avcl, FILE *f, int level,
                              const uint8_t *buf, int size)
{
    int len, i, j, c;

4002
    for (i = 0; i < size; i += 16) {
4003 4004 4005
        len = size - i;
        if (len > 16)
            len = 16;
4006
        HEXDUMP_PRINT("%08x ", i);
4007
        for (j = 0; j < 16; j++) {
4008
            if (j < len)
4009
                HEXDUMP_PRINT(" %02x", buf[i + j]);
4010
            else
4011
                HEXDUMP_PRINT("   ");
4012
        }
4013
        HEXDUMP_PRINT(" ");
4014 4015
        for (j = 0; j < len; j++) {
            c = buf[i + j];
4016 4017
            if (c < ' ' || c > '~')
                c = '.';
4018
            HEXDUMP_PRINT("%c", c);
4019
        }
4020
        HEXDUMP_PRINT("\n");
4021
    }
4022 4023
}

4024
void av_hex_dump(FILE *f, const uint8_t *buf, int size)
4025 4026 4027 4028
{
    hex_dump_internal(NULL, f, 0, buf, size);
}

4029
void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
4030 4031
{
    hex_dump_internal(avcl, NULL, level, buf, size);
4032 4033
}

4034 4035
static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt,
                              int dump_payload, AVRational time_base)
4036
{
4037 4038 4039
    HEXDUMP_PRINT("stream #%d:\n", pkt->stream_index);
    HEXDUMP_PRINT("  keyframe=%d\n", (pkt->flags & AV_PKT_FLAG_KEY) != 0);
    HEXDUMP_PRINT("  duration=%0.3f\n", pkt->duration * av_q2d(time_base));
4040
    /* DTS is _always_ valid after av_read_frame() */
4041
    HEXDUMP_PRINT("  dts=");
4042
    if (pkt->dts == AV_NOPTS_VALUE)
4043
        HEXDUMP_PRINT("N/A");
4044
    else
4045
        HEXDUMP_PRINT("%0.3f", pkt->dts * av_q2d(time_base));
4046
    /* PTS may not be known if B-frames are present. */
4047
    HEXDUMP_PRINT("  pts=");
4048
    if (pkt->pts == AV_NOPTS_VALUE)
4049
        HEXDUMP_PRINT("N/A");
4050
    else
4051 4052 4053
        HEXDUMP_PRINT("%0.3f", pkt->pts * av_q2d(time_base));
    HEXDUMP_PRINT("\n");
    HEXDUMP_PRINT("  size=%d\n", pkt->size);
4054 4055 4056 4057
    if (dump_payload)
        av_hex_dump(f, pkt->data, pkt->size);
}

4058 4059 4060
void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
{
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
4061 4062
}

4063 4064 4065 4066
void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
                      AVStream *st)
{
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
4067 4068
}

4069 4070 4071
void av_url_split(char *proto, int proto_size,
                  char *authorization, int authorization_size,
                  char *hostname, int hostname_size,
4072
                  int *port_ptr, char *path, int path_size, const char *url)
Fabrice Bellard's avatar
Fabrice Bellard committed
4073
{
4074
    const char *p, *ls, *ls2, *at, *at2, *col, *brk;
4075

4076 4077 4078 4079 4080 4081 4082 4083 4084 4085
    if (port_ptr)
        *port_ptr = -1;
    if (proto_size > 0)
        proto[0] = 0;
    if (authorization_size > 0)
        authorization[0] = 0;
    if (hostname_size > 0)
        hostname[0] = 0;
    if (path_size > 0)
        path[0] = 0;
4086 4087 4088 4089 4090

    /* parse protocol */
    if ((p = strchr(url, ':'))) {
        av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
        p++; /* skip ':' */
4091 4092 4093 4094
        if (*p == '/')
            p++;
        if (*p == '/')
            p++;
Fabrice Bellard's avatar
Fabrice Bellard committed
4095
    } else {
4096 4097 4098 4099
        /* no protocol means plain filename */
        av_strlcpy(path, url, path_size);
        return;
    }
4100

4101
    /* separate path from hostname */
4102
    ls = strchr(p, '/');
4103
    ls2 = strchr(p, '?');
4104
    if (!ls)
4105 4106 4107
        ls = ls2;
    else if (ls && ls2)
        ls = FFMIN(ls, ls2);
4108
    if (ls)
Michael Niedermayer's avatar
Michael Niedermayer committed
4109
        av_strlcpy(path, ls, path_size);
4110
    else
4111
        ls = &p[strlen(p)];  // XXX
4112 4113 4114 4115

    /* the rest is hostname, use that to parse auth/port */
    if (ls != p) {
        /* authorization (user[:pass]@hostname) */
4116 4117 4118 4119
        at2 = p;
        while ((at = strchr(p, '@')) && at < ls) {
            av_strlcpy(authorization, at2,
                       FFMIN(authorization_size, at + 1 - at2));
4120
            p = at + 1; /* skip '@' */
Fabrice Bellard's avatar
Fabrice Bellard committed
4121
        }
4122

4123 4124 4125 4126 4127 4128 4129 4130 4131
        if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
            /* [host]:port */
            av_strlcpy(hostname, p + 1,
                       FFMIN(hostname_size, brk - p));
            if (brk[1] == ':' && port_ptr)
                *port_ptr = atoi(brk + 2);
        } else if ((col = strchr(p, ':')) && col < ls) {
            av_strlcpy(hostname, p,
                       FFMIN(col + 1 - p, hostname_size));
4132 4133
            if (port_ptr)
                *port_ptr = atoi(col + 1);
4134 4135 4136
        } else
            av_strlcpy(hostname, p,
                       FFMIN(ls + 1 - p, hostname_size));
Fabrice Bellard's avatar
Fabrice Bellard committed
4137 4138 4139
    }
}

4140
char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4141 4142
{
    int i;
4143
    static const char hex_table_uc[16] = { '0', '1', '2', '3',
Martin Storsjö's avatar
Martin Storsjö committed
4144 4145 4146
                                           '4', '5', '6', '7',
                                           '8', '9', 'A', 'B',
                                           'C', 'D', 'E', 'F' };
4147 4148 4149 4150 4151
    static const char hex_table_lc[16] = { '0', '1', '2', '3',
                                           '4', '5', '6', '7',
                                           '8', '9', 'a', 'b',
                                           'c', 'd', 'e', 'f' };
    const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
4152

4153
    for (i = 0; i < s; i++) {
4154 4155
        buff[i * 2]     = hex_table[src[i] >> 4];
        buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4156 4157 4158 4159 4160
    }

    return buff;
}

4161 4162 4163 4164 4165
int ff_hex_to_data(uint8_t *data, const char *p)
{
    int c, len, v;

    len = 0;
4166
    v   = 1;
4167 4168 4169 4170
    for (;;) {
        p += strspn(p, SPACE_CHARS);
        if (*p == '\0')
            break;
4171
        c = av_toupper((unsigned char) *p++);
4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188
        if (c >= '0' && c <= '9')
            c = c - '0';
        else if (c >= 'A' && c <= 'F')
            c = c - 'A' + 10;
        else
            break;
        v = (v << 4) | c;
        if (v & 0x100) {
            if (data)
                data[len] = v;
            len++;
            v = 1;
        }
    }
    return len;
}

4189
#if FF_API_SET_PTS_INFO
4190
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
4191
                     unsigned int pts_num, unsigned int pts_den)
4192 4193 4194 4195 4196 4197 4198
{
    avpriv_set_pts_info(s, pts_wrap_bits, pts_num, pts_den);
}
#endif

void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
                         unsigned int pts_num, unsigned int pts_den)
Fabrice Bellard's avatar
Fabrice Bellard committed
4199
{
4200
    AVRational new_tb;
4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211
    if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
        if (new_tb.num != pts_num)
            av_log(NULL, AV_LOG_DEBUG,
                   "st:%d removing common factor %d from timebase\n",
                   s->index, pts_num / new_tb.num);
    } else
        av_log(NULL, AV_LOG_WARNING,
               "st:%d has too large timebase, reducing\n", s->index);

    if (new_tb.num <= 0 || new_tb.den <= 0) {
        av_log(NULL, AV_LOG_ERROR,
4212 4213
               "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
               new_tb.num, new_tb.den,
4214
               s->index);
4215 4216
        return;
    }
4217
    s->time_base     = new_tb;
4218
    av_codec_set_pkt_timebase(s->codec, new_tb);
4219
    s->pts_wrap_bits = pts_wrap_bits;
Fabrice Bellard's avatar
Fabrice Bellard committed
4220
}
4221

4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233
void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
                        void *context)
{
    const char *ptr = str;

    /* Parse key=value pairs. */
    for (;;) {
        const char *key;
        char *dest = NULL, *dest_end;
        int key_len, dest_len = 0;

        /* Skip whitespace and potential commas. */
4234
        while (*ptr && (av_isspace(*ptr) || *ptr == ','))
4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266
            ptr++;
        if (!*ptr)
            break;

        key = ptr;

        if (!(ptr = strchr(key, '=')))
            break;
        ptr++;
        key_len = ptr - key;

        callback_get_buf(context, key, key_len, &dest, &dest_len);
        dest_end = dest + dest_len - 1;

        if (*ptr == '\"') {
            ptr++;
            while (*ptr && *ptr != '\"') {
                if (*ptr == '\\') {
                    if (!ptr[1])
                        break;
                    if (dest && dest < dest_end)
                        *dest++ = ptr[1];
                    ptr += 2;
                } else {
                    if (dest && dest < dest_end)
                        *dest++ = *ptr;
                    ptr++;
                }
            }
            if (*ptr == '\"')
                ptr++;
        } else {
4267
            for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
4268 4269 4270 4271 4272 4273 4274 4275
                if (dest && dest < dest_end)
                    *dest++ = *ptr;
        }
        if (dest)
            *dest = 0;
    }
}

Peter Ross's avatar
Peter Ross committed
4276 4277 4278
int ff_find_stream_index(AVFormatContext *s, int id)
{
    int i;
4279
    for (i = 0; i < s->nb_streams; i++)
Peter Ross's avatar
Peter Ross committed
4280 4281 4282 4283
        if (s->streams[i]->id == id)
            return i;
    return -1;
}
4284

4285 4286
int64_t ff_iso8601_to_unix_time(const char *datestr)
{
4287
    struct tm time1 = { 0 }, time2 = { 0 };
4288
    char *ret1, *ret2;
4289 4290
    ret1 = av_small_strptime(datestr, "%Y - %m - %d %H:%M:%S", &time1);
    ret2 = av_small_strptime(datestr, "%Y - %m - %dT%H:%M:%S", &time2);
4291 4292 4293 4294
    if (ret2 && !ret1)
        return av_timegm(&time2);
    else
        return av_timegm(&time1);
4295
}
4296

4297 4298
int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id,
                         int std_compliance)
4299 4300 4301 4302 4303 4304
{
    if (ofmt) {
        if (ofmt->query_codec)
            return ofmt->query_codec(codec_id, std_compliance);
        else if (ofmt->codec_tag)
            return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
4305 4306
        else if (codec_id == ofmt->video_codec ||
                 codec_id == ofmt->audio_codec ||
4307
                 codec_id == ofmt->subtitle_codec)
4308
            return 1;
4309 4310 4311
    }
    return AVERROR_PATCHWELCOME;
}
4312 4313 4314 4315 4316

int avformat_network_init(void)
{
#if CONFIG_NETWORK
    int ret;
4317
    ff_network_inited_globally = 1;
4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
    if ((ret = ff_network_init()) < 0)
        return ret;
    ff_tls_init();
#endif
    return 0;
}

int avformat_network_deinit(void)
{
#if CONFIG_NETWORK
    ff_network_close();
    ff_tls_deinit();
#endif
    return 0;
}
4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343

int ff_add_param_change(AVPacket *pkt, int32_t channels,
                        uint64_t channel_layout, int32_t sample_rate,
                        int32_t width, int32_t height)
{
    uint32_t flags = 0;
    int size = 4;
    uint8_t *data;
    if (!pkt)
        return AVERROR(EINVAL);
    if (channels) {
4344
        size  += 4;
4345 4346 4347
        flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
    }
    if (channel_layout) {
4348
        size  += 8;
4349 4350 4351
        flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
    }
    if (sample_rate) {
4352
        size  += 4;
4353 4354 4355
        flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
    }
    if (width || height) {
4356
        size  += 8;
4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374
        flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
    }
    data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
    if (!data)
        return AVERROR(ENOMEM);
    bytestream_put_le32(&data, flags);
    if (channels)
        bytestream_put_le32(&data, channels);
    if (channel_layout)
        bytestream_put_le64(&data, channel_layout);
    if (sample_rate)
        bytestream_put_le32(&data, sample_rate);
    if (width || height) {
        bytestream_put_le32(&data, width);
        bytestream_put_le32(&data, height);
    }
    return 0;
}
4375

4376 4377 4378 4379
AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
{
    AVRational undef = {0, 1};
    AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
4380 4381
    AVRational codec_sample_aspect_ratio  = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
    AVRational frame_sample_aspect_ratio  = frame  ? frame->sample_aspect_ratio  : codec_sample_aspect_ratio;
4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397

    av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
               stream_sample_aspect_ratio.num,  stream_sample_aspect_ratio.den, INT_MAX);
    if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
        stream_sample_aspect_ratio = undef;

    av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
               frame_sample_aspect_ratio.num,  frame_sample_aspect_ratio.den, INT_MAX);
    if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
        frame_sample_aspect_ratio = undef;

    if (stream_sample_aspect_ratio.num)
        return stream_sample_aspect_ratio;
    else
        return frame_sample_aspect_ratio;
}
4398

4399 4400 4401
AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
{
    AVRational fr = st->r_frame_rate;
4402 4403 4404 4405 4406 4407 4408 4409
    AVRational codec_fr = av_inv_q(st->codec->time_base);
    AVRational   avg_fr = st->avg_frame_rate;

    if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
        av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
        fr = avg_fr;
    }

4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420

    if (st->codec->ticks_per_frame > 1) {
        codec_fr.den *= st->codec->ticks_per_frame;
        if (   codec_fr.num > 0 && codec_fr.den > 0 && av_q2d(codec_fr) < av_q2d(fr)*0.7
            && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1)
            fr = codec_fr;
    }

    return fr;
}

4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
                                    const char *spec)
{
    if (*spec <= '9' && *spec >= '0') /* opt:index */
        return strtol(spec, NULL, 0) == st->index;
    else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
             *spec == 't') { /* opt:[vasdt] */
        enum AVMediaType type;

        switch (*spec++) {
        case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
        case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
        case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
        case 'd': type = AVMEDIA_TYPE_DATA;       break;
        case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
        default:  av_assert0(0);
        }
        if (type != st->codec->codec_type)
            return 0;
        if (*spec++ == ':') { /* possibly followed by :index */
            int i, index = strtol(spec, NULL, 0);
            for (i = 0; i < s->nb_streams; i++)
                if (s->streams[i]->codec->codec_type == type && index-- == 0)
                   return i == st->index;
            return 0;
        }
        return 1;
    } else if (*spec == 'p' && *(spec + 1) == ':') {
        int prog_id, i, j;
        char *endptr;
        spec += 2;
        prog_id = strtol(spec, &endptr, 0);
        for (i = 0; i < s->nb_programs; i++) {
            if (s->programs[i]->id != prog_id)
                continue;

            if (*endptr++ == ':') {
                int stream_idx = strtol(endptr, NULL, 0);
                return stream_idx >= 0 &&
                    stream_idx < s->programs[i]->nb_stream_indexes &&
                    st->index == s->programs[i]->stream_index[stream_idx];
            }

            for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
                if (st->index == s->programs[i]->stream_index[j])
                    return 1;
        }
        return 0;
    } else if (*spec == '#') {
        int sid;
        char *endptr;
        sid = strtol(spec + 1, &endptr, 0);
        if (!*endptr)
            return st->id == sid;
    } else if (!*spec) /* empty specifier, matches everything */
        return 1;

    av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
    return AVERROR(EINVAL);
}
4481

4482
int ff_generate_avci_extradata(AVStream *st)
4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525
{
    static const uint8_t avci100_1080p_extradata[] = {
        // SPS
        0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
        0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
        0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
        0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
        0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
        0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
        0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
        0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
        0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        // PPS
        0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
        0xd0
    };
    static const uint8_t avci100_1080i_extradata[] = {
        // SPS
        0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
        0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
        0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
        0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
        0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
        0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
        0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
        0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
        0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
        0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
        0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x00,
        // PPS
        0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
        0xd0
    };
    static const uint8_t avci50_1080i_extradata[] = {
        // SPS
        0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
        0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
        0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
        0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
        0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
        0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
        0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
        0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
4526 4527
        0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
        0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548
        0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
        // PPS
        0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
        0x11
    };
    static const uint8_t avci100_720p_extradata[] = {
        // SPS
        0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
        0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
        0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
        0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
        0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
        0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
        0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
        0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
        0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
        0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
        // PPS
        0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
        0x11
    };
4549 4550

    const uint8_t *data = NULL;
4551
    int size            = 0;
4552

4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567
    if (st->codec->width == 1920) {
        if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
            data = avci100_1080p_extradata;
            size = sizeof(avci100_1080p_extradata);
        } else {
            data = avci100_1080i_extradata;
            size = sizeof(avci100_1080i_extradata);
        }
    } else if (st->codec->width == 1440) {
        data = avci50_1080i_extradata;
        size = sizeof(avci50_1080i_extradata);
    } else if (st->codec->width == 1280) {
        data = avci100_720p_extradata;
        size = sizeof(avci100_720p_extradata);
    }
4568

4569
    if (!size)
4570 4571
        return 0;

4572
    av_freep(&st->codec->extradata);
4573
    if (ff_alloc_extradata(st->codec, size))
4574
        return AVERROR(ENOMEM);
4575
    memcpy(st->codec->extradata, data, size);
4576 4577

    return 0;
4578
}