utils.c 201 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
#include <stdarg.h>
23 24
#include <stdint.h>

25 26
#include "config.h"

27
#include "libavutil/avassert.h"
28
#include "libavutil/avstring.h"
29 30
#include "libavutil/dict.h"
#include "libavutil/internal.h"
31
#include "libavutil/mathematics.h"
32
#include "libavutil/opt.h"
33
#include "libavutil/parseutils.h"
34
#include "libavutil/pixdesc.h"
35
#include "libavutil/thread.h"
36
#include "libavutil/time.h"
37
#include "libavutil/time_internal.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 58
#include "libavutil/ffversion.h"
const char av_format_ffversion[] = "FFmpeg version " FFMPEG_VERSION;

59 60
static AVMutex avformat_mutex = AV_MUTEX_INITIALIZER;

61
/**
62
 * @file
63
 * various utility functions for use within FFmpeg
64 65
 */

66 67
unsigned avformat_version(void)
{
68
    av_assert0(LIBAVFORMAT_VERSION_MICRO >= 100);
69 70 71
    return LIBAVFORMAT_VERSION_INT;
}

72
const char *avformat_configuration(void)
73
{
74
    return FFMPEG_CONFIGURATION;
75 76
}

77
const char *avformat_license(void)
78 79
{
#define LICENSE_PREFIX "libavformat license: "
80
    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
81 82
}

83 84 85 86 87 88 89 90 91 92
int ff_lock_avformat(void)
{
    return ff_mutex_lock(&avformat_mutex) ? -1 : 0;
}

int ff_unlock_avformat(void)
{
    return ff_mutex_unlock(&avformat_mutex) ? -1 : 0;
}

93
#define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
94 95

static int is_relative(int64_t ts) {
96
    return ts > (RELATIVE_TS_BASE - (1LL<<48));
97 98
}

99 100 101 102 103 104 105
/**
 * 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
 */
106
static int64_t wrap_timestamp(const AVStream *st, int64_t timestamp)
107
{
108
    if (st->pts_wrap_behavior != AV_PTS_WRAP_IGNORE &&
109 110 111
        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)
112
            return timestamp + (1ULL << st->pts_wrap_bits);
113 114
        else if (st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
            timestamp >= st->pts_wrap_reference)
115
            return timestamp - (1ULL << st->pts_wrap_bits);
116 117 118 119
    }
    return timestamp;
}

120
#if FF_API_FORMAT_GET_SET
121
MAKE_ACCESSORS(AVStream, stream, AVRational, r_frame_rate)
122 123
#if FF_API_LAVF_FFSERVER
FF_DISABLE_DEPRECATION_WARNINGS
124
MAKE_ACCESSORS(AVStream, stream, char *, recommended_encoder_configuration)
125 126
FF_ENABLE_DEPRECATION_WARNINGS
#endif
127 128 129
MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
130
MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, data_codec)
131
MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
132 133
MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
134 135
#if FF_API_OLD_OPEN_CALLBACKS
FF_DISABLE_DEPRECATION_WARNINGS
136
MAKE_ACCESSORS(AVFormatContext, format, AVOpenCallback, open_cb)
137 138
FF_ENABLE_DEPRECATION_WARNINGS
#endif
139
#endif
140

141 142
int64_t av_stream_get_end_pts(const AVStream *st)
{
143 144
    if (st->internal->priv_pts) {
        return st->internal->priv_pts->val;
145 146
    } else
        return AV_NOPTS_VALUE;
147 148
}

149 150 151 152 153
struct AVCodecParserContext *av_stream_get_parser(const AVStream *st)
{
    return st->parser;
}

154 155 156 157 158 159 160 161 162 163
void av_format_inject_global_side_data(AVFormatContext *s)
{
    int i;
    s->internal->inject_global_side_data = 1;
    for (i = 0; i < s->nb_streams; i++) {
        AVStream *st = s->streams[i];
        st->inject_global_side_data = 1;
    }
}

164
int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
165
{
166 167
    av_assert0(!dst->codec_whitelist &&
               !dst->format_whitelist &&
168 169
               !dst->protocol_whitelist &&
               !dst->protocol_blacklist);
170 171
    dst-> codec_whitelist = av_strdup(src->codec_whitelist);
    dst->format_whitelist = av_strdup(src->format_whitelist);
172
    dst->protocol_whitelist = av_strdup(src->protocol_whitelist);
173
    dst->protocol_blacklist = av_strdup(src->protocol_blacklist);
174
    if (   (src-> codec_whitelist && !dst-> codec_whitelist)
175
        || (src->  format_whitelist && !dst->  format_whitelist)
176 177 178
        || (src->protocol_whitelist && !dst->protocol_whitelist)
        || (src->protocol_blacklist && !dst->protocol_blacklist)) {
        av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
179 180 181 182 183
        return AVERROR(ENOMEM);
    }
    return 0;
}

184
static const AVCodec *find_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
185
{
186 187
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
188 189
    if (st->codec->codec)
        return st->codec->codec;
190 191
FF_ENABLE_DEPRECATION_WARNINGS
#endif
192

193
    switch (st->codecpar->codec_type) {
194
    case AVMEDIA_TYPE_VIDEO:
195
        if (s->video_codec)    return s->video_codec;
196 197
        break;
    case AVMEDIA_TYPE_AUDIO:
198
        if (s->audio_codec)    return s->audio_codec;
199 200
        break;
    case AVMEDIA_TYPE_SUBTITLE:
201
        if (s->subtitle_codec) return s->subtitle_codec;
202 203 204
        break;
    }

205 206 207
    return avcodec_find_decoder(codec_id);
}

208 209
static const AVCodec *find_probe_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
{
210 211
    const AVCodec *codec;

212 213 214 215 216 217 218
#if CONFIG_H264_DECODER
    /* Other parts of the code assume this decoder to be used for h264,
     * so force it if possible. */
    if (codec_id == AV_CODEC_ID_H264)
        return avcodec_find_decoder_by_name("h264");
#endif

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    codec = find_decoder(s, st, codec_id);
    if (!codec)
        return NULL;

    if (codec->capabilities & AV_CODEC_CAP_AVOID_PROBING) {
        const AVCodec *probe_codec = NULL;
        while (probe_codec = av_codec_next(probe_codec)) {
            if (probe_codec->id == codec_id &&
                    av_codec_is_decoder(probe_codec) &&
                    !(probe_codec->capabilities & (AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_EXPERIMENTAL))) {
                return probe_codec;
            }
        }
    }

    return codec;
235 236
}

237
#if FF_API_FORMAT_GET_SET
238 239 240 241
int av_format_get_probe_score(const AVFormatContext *s)
{
    return s->probe_score;
}
242
#endif
243

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

247
int ffio_limit(AVIOContext *s, int size)
Michael Niedermayer's avatar
Michael Niedermayer committed
248
{
249
    if (s->maxsize>= 0) {
250
        int64_t remaining= s->maxsize - avio_tell(s);
251 252 253 254
        if (remaining < size) {
            int64_t newsize = avio_size(s);
            if (!s->maxsize || s->maxsize<newsize)
                s->maxsize = newsize - !newsize;
255
            remaining= s->maxsize - avio_tell(s);
256
            remaining= FFMAX(remaining, 0);
257 258
        }

259
        if (s->maxsize>= 0 && remaining+1 < size) {
260
            av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG, "Truncating packet of size %d to %"PRId64"\n", size, remaining+1);
261
            size = remaining+1;
262
        }
263
    }
264 265 266
    return size;
}

267 268
/* Read the data in sane-sized chunks and append to pkt.
 * Return the number of bytes read or an error. */
269
static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
270
{
271
    int64_t orig_pos   = pkt->pos; // av_grow_packet might reset pos
272
    int orig_size      = pkt->size;
273
    int ret;
274 275 276 277 278

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

279 280
        /* 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. */
281 282 283 284 285 286 287
        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);
        }
288

289 290 291
        ret = av_grow_packet(pkt, read_size);
        if (ret < 0)
            break;
Michael Niedermayer's avatar
Michael Niedermayer committed
292

293 294 295 296 297
        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
298

299 300
        size -= read_size;
    } while (size > 0);
301 302
    if (size > 0)
        pkt->flags |= AV_PKT_FLAG_CORRUPT;
Michael Niedermayer's avatar
Michael Niedermayer committed
303

304 305
    pkt->pos = orig_pos;
    if (!pkt->size)
306
        av_packet_unref(pkt);
307 308 309 310 311 312 313 314 315
    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
316

317
    return append_packet_chunked(s, pkt, size);
Michael Niedermayer's avatar
Michael Niedermayer committed
318 319
}

320
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
321 322 323
{
    if (!pkt->size)
        return av_get_packet(s, pkt, size);
324
    return append_packet_chunked(s, pkt, size);
325 326
}

327
int av_filename_number_test(const char *filename)
328 329
{
    char buf[1024];
330 331
    return filename &&
           (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
332 333
}

334
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
335
                                     AVProbeData *pd)
336
{
337
    static const struct {
338 339 340
        const char *name;
        enum AVCodecID id;
        enum AVMediaType type;
341
    } fmt_id_type[] = {
342 343
        { "aac",       AV_CODEC_ID_AAC,        AVMEDIA_TYPE_AUDIO },
        { "ac3",       AV_CODEC_ID_AC3,        AVMEDIA_TYPE_AUDIO },
344
        { "aptx",      AV_CODEC_ID_APTX,       AVMEDIA_TYPE_AUDIO },
345
        { "dts",       AV_CODEC_ID_DTS,        AVMEDIA_TYPE_AUDIO },
346
        { "dvbsub",    AV_CODEC_ID_DVB_SUBTITLE,AVMEDIA_TYPE_SUBTITLE },
347
        { "dvbtxt",    AV_CODEC_ID_DVB_TELETEXT,AVMEDIA_TYPE_SUBTITLE },
348 349
        { "eac3",      AV_CODEC_ID_EAC3,       AVMEDIA_TYPE_AUDIO },
        { "h264",      AV_CODEC_ID_H264,       AVMEDIA_TYPE_VIDEO },
350
        { "hevc",      AV_CODEC_ID_HEVC,       AVMEDIA_TYPE_VIDEO },
351
        { "loas",      AV_CODEC_ID_AAC_LATM,   AVMEDIA_TYPE_AUDIO },
352
        { "m4v",       AV_CODEC_ID_MPEG4,      AVMEDIA_TYPE_VIDEO },
353
        { "mjpeg_2000",AV_CODEC_ID_JPEG2000,   AVMEDIA_TYPE_VIDEO },
354
        { "mp3",       AV_CODEC_ID_MP3,        AVMEDIA_TYPE_AUDIO },
355
        { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
Rodger Combs's avatar
Rodger Combs committed
356
        { "truehd",    AV_CODEC_ID_TRUEHD,     AVMEDIA_TYPE_AUDIO },
357 358
        { 0 }
    };
359 360
    int score;
    AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
361

362
    if (fmt) {
363
        int i;
364 365 366 367
        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);
368 369
        for (i = 0; fmt_id_type[i].name; i++) {
            if (!strcmp(fmt->name, fmt_id_type[i].name)) {
370 371 372
                if (fmt_id_type[i].type != AVMEDIA_TYPE_AUDIO &&
                    st->codecpar->sample_rate)
                    continue;
373 374 375
                if (st->request_probe > score &&
                    st->codecpar->codec_id != fmt_id_type[i].id)
                    continue;
376 377
                st->codecpar->codec_id   = fmt_id_type[i].id;
                st->codecpar->codec_type = fmt_id_type[i].type;
378
                st->internal->need_context_update = 1;
379 380 381 382 383 384
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
                st->codec->codec_type = st->codecpar->codec_type;
                st->codec->codec_id   = st->codecpar->codec_id;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
385
                return score;
386
            }
387
        }
388
    }
389
    return 0;
390 391
}

392 393
/************************************************************/
/* input media file */
394

395
int av_demuxer_open(AVFormatContext *ic) {
396 397
    int err;

398
    if (ic->format_whitelist && av_match_list(ic->iformat->name, ic->format_whitelist, ',') <= 0) {
399
        av_log(ic, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", ic->format_whitelist);
400 401 402
        return AVERROR(EINVAL);
    }

403
    if (ic->iformat->read_header) {
404
        err = ic->iformat->read_header(ic);
405 406 407 408
        if (err < 0)
            return err;
    }

409 410
    if (ic->pb && !ic->internal->data_offset)
        ic->internal->data_offset = avio_tell(ic->pb);
411 412 413 414

    return 0;
}

415 416 417
/* Open input file and probe the format if necessary. */
static int init_input(AVFormatContext *s, const char *filename,
                      AVDictionary **options)
418 419
{
    int ret;
420
    AVProbeData pd = { filename, NULL, 0 };
421
    int score = AVPROBE_SCORE_RETRY;
422 423 424 425

    if (s->pb) {
        s->flags |= AVFMT_FLAG_CUSTOM_IO;
        if (!s->iformat)
426
            return av_probe_input_buffer2(s->pb, &s->iformat, filename,
427
                                         s, 0, s->format_probesize);
428
        else if (s->iformat->flags & AVFMT_NOFILE)
429 430
            av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
                                      "will be ignored with AVFMT_NOFILE format.\n");
431
        return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
432 433
    }

434
    if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
435
        (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
436
        return score;
437

438
    if ((ret = s->io_open(s, &s->pb, filename, AVIO_FLAG_READ | s->avio_flags, options)) < 0)
439
        return ret;
440

441 442
    if (s->iformat)
        return 0;
443
    return av_probe_input_buffer2(s->pb, &s->iformat, filename,
444
                                 s, 0, s->format_probesize);
445 446
}

447 448 449
int ff_packet_list_put(AVPacketList **packet_buffer,
                       AVPacketList **plast_pktl,
                       AVPacket      *pkt, int flags)
450
{
451
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
452 453
    int ret;

454
    if (!pktl)
455 456
        return AVERROR(ENOMEM);

457
    if (flags & FF_PACKETLIST_FLAG_REF_PACKET) {
458 459 460 461 462
        if ((ret = av_packet_ref(&pktl->pkt, pkt)) < 0) {
            av_free(pktl);
            return ret;
        }
    } else {
463 464 465
        // TODO: Adapt callers in this file so the line below can use
        //       av_packet_move_ref() to effectively move the reference
        //       to the list.
466 467
        pktl->pkt = *pkt;
    }
468 469 470 471 472 473

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

474
    /* Add the packet in the buffered packet list. */
475
    *plast_pktl = pktl;
476
    return 0;
477 478
}

479
int avformat_queue_attached_pictures(AVFormatContext *s)
480
{
481
    int i, ret;
482
    for (i = 0; i < s->nb_streams; i++)
483 484
        if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
            s->streams[i]->discard < AVDISCARD_ALL) {
485
            if (s->streams[i]->attached_pic.size <= 0) {
486 487 488 489 490
                av_log(s, AV_LOG_WARNING,
                    "Attached picture on stream %d has invalid size, "
                    "ignoring\n", i);
                continue;
            }
491

492 493 494 495
            ret = ff_packet_list_put(&s->internal->raw_packet_buffer,
                                     &s->internal->raw_packet_buffer_end,
                                     &s->streams[i]->attached_pic,
                                     FF_PACKETLIST_FLAG_REF_PACKET);
496 497
            if (ret < 0)
                return ret;
498
        }
499
    return 0;
500 501
}

502 503 504 505 506 507
static int update_stream_avctx(AVFormatContext *s)
{
    int i, ret;
    for (i = 0; i < s->nb_streams; i++) {
        AVStream *st = s->streams[i];

508
        if (!st->internal->need_context_update)
509 510
            continue;

511 512 513 514 515 516
        /* close parser, because it depends on the codec */
        if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
            av_parser_close(st->parser);
            st->parser = NULL;
        }

517 518 519 520 521 522 523 524
        /* update internal codec context, for the parser */
        ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
        if (ret < 0)
            return ret;

#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
        /* update deprecated public codec context */
525 526 527
        ret = avcodec_parameters_to_context(st->codec, st->codecpar);
        if (ret < 0)
            return ret;
528 529
FF_ENABLE_DEPRECATION_WARNINGS
#endif
530

531
        st->internal->need_context_update = 0;
532 533 534
    }
    return 0;
}
535

536

537 538
int avformat_open_input(AVFormatContext **ps, const char *filename,
                        AVInputFormat *fmt, AVDictionary **options)
539 540
{
    AVFormatContext *s = *ps;
541
    int i, ret = 0;
542
    AVDictionary *tmp = NULL;
543
    ID3v2ExtraMeta *id3v2_extra_meta = NULL;
544 545 546

    if (!s && !(s = avformat_alloc_context()))
        return AVERROR(ENOMEM);
547
    if (!s->av_class) {
548
        av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
549 550
        return AVERROR(EINVAL);
    }
551 552 553 554 555 556
    if (fmt)
        s->iformat = fmt;

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

557 558 559
    if (s->pb) // must be before any goto fail
        s->flags |= AVFMT_FLAG_CUSTOM_IO;

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

563 564 565 566 567
    if (!(s->url = av_strdup(filename ? filename : ""))) {
        ret = AVERROR(ENOMEM);
        goto fail;
    }

568 569
#if FF_API_FORMAT_FILENAME
FF_DISABLE_DEPRECATION_WARNINGS
570
    av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
571 572
FF_ENABLE_DEPRECATION_WARNINGS
#endif
573
    if ((ret = init_input(s, filename, &tmp)) < 0)
574
        goto fail;
575
    s->probe_score = ret;
576

577 578 579 580 581 582 583 584
    if (!s->protocol_whitelist && s->pb && s->pb->protocol_whitelist) {
        s->protocol_whitelist = av_strdup(s->pb->protocol_whitelist);
        if (!s->protocol_whitelist) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
    }

585 586 587 588 589 590 591 592
    if (!s->protocol_blacklist && s->pb && s->pb->protocol_blacklist) {
        s->protocol_blacklist = av_strdup(s->pb->protocol_blacklist);
        if (!s->protocol_blacklist) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
    }

593
    if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
594
        av_log(s, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", s->format_whitelist);
595 596 597 598
        ret = AVERROR(EINVAL);
        goto fail;
    }

599
    avio_skip(s->pb, s->skip_initial_bytes);
600

601
    /* Check filename in case an image number is expected. */
602 603 604
    if (s->iformat->flags & AVFMT_NEEDNUMBER) {
        if (!av_filename_number_test(filename)) {
            ret = AVERROR(EINVAL);
605
            goto fail;
606
        }
607 608 609 610
    }

    s->duration = s->start_time = AV_NOPTS_VALUE;

611
    /* Allocate private data. */
612 613 614
    if (s->iformat->priv_data_size > 0) {
        if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
            ret = AVERROR(ENOMEM);
615
            goto fail;
616
        }
617
        if (s->iformat->priv_class) {
618
            *(const AVClass **) s->priv_data = s->iformat->priv_class;
619 620 621 622
            av_opt_set_defaults(s->priv_data);
            if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
                goto fail;
        }
623 624
    }

625 626
    /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
    if (s->pb)
627 628
        ff_id3v2_read_dict(s->pb, &s->internal->id3v2_meta, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);

629

630
    if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
631
        if ((ret = s->iformat->read_header(s)) < 0)
632
            goto fail;
633

634 635 636 637 638 639 640 641 642 643 644 645 646
    if (!s->metadata) {
        s->metadata = s->internal->id3v2_meta;
        s->internal->id3v2_meta = NULL;
    } else if (s->internal->id3v2_meta) {
        int level = AV_LOG_WARNING;
        if (s->error_recognition & AV_EF_COMPLIANT)
            level = AV_LOG_ERROR;
        av_log(s, level, "Discarding ID3 tags because more suitable tags were found.\n");
        av_dict_free(&s->internal->id3v2_meta);
        if (s->error_recognition & AV_EF_EXPLODE)
            return AVERROR_INVALIDDATA;
    }

647
    if (id3v2_extra_meta) {
648
        if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
649
            !strcmp(s->iformat->name, "tta") || !strcmp(s->iformat->name, "wav")) {
650
            if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
651
                goto fail;
652 653
            if ((ret = ff_id3v2_parse_chapters(s, &id3v2_extra_meta)) < 0)
                goto fail;
654 655
            if ((ret = ff_id3v2_parse_priv(s, &id3v2_extra_meta)) < 0)
                goto fail;
656
        } else
657
            av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
658
    }
659 660
    ff_id3v2_free_extra_meta(&id3v2_extra_meta);

661
    if ((ret = avformat_queue_attached_pictures(s)) < 0)
662
        goto fail;
663

664
    if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->internal->data_offset)
665
        s->internal->data_offset = avio_tell(s->pb);
666

667
    s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
668

669 670 671 672 673
    update_stream_avctx(s);

    for (i = 0; i < s->nb_streams; i++)
        s->streams[i]->internal->orig_codec_id = s->streams[i]->codecpar->codec_id;

674 675 676
    if (options) {
        av_dict_free(options);
        *options = tmp;
677
    }
678
    *ps = s;
679
    return 0;
680

681
fail:
682
    ff_id3v2_free_extra_meta(&id3v2_extra_meta);
683 684
    av_dict_free(&tmp);
    if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
685
        avio_closep(&s->pb);
686 687 688
    avformat_free_context(s);
    *ps = NULL;
    return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
689 690
}

691 692
/*******************************************************/

693 694
static void force_codec_ids(AVFormatContext *s, AVStream *st)
{
695
    switch (st->codecpar->codec_type) {
696
    case AVMEDIA_TYPE_VIDEO:
697
        if (s->video_codec_id)
698
            st->codecpar->codec_id = s->video_codec_id;
699 700
        break;
    case AVMEDIA_TYPE_AUDIO:
701
        if (s->audio_codec_id)
702
            st->codecpar->codec_id = s->audio_codec_id;
703 704
        break;
    case AVMEDIA_TYPE_SUBTITLE:
705
        if (s->subtitle_codec_id)
706
            st->codecpar->codec_id = s->subtitle_codec_id;
707
        break;
708 709
    case AVMEDIA_TYPE_DATA:
        if (s->data_codec_id)
710
            st->codecpar->codec_id = s->data_codec_id;
711
        break;
712 713 714
    }
}

715
static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
716
{
717
    if (st->request_probe>0) {
718
        AVProbeData *pd = &st->probe_data;
719 720
        int end;
        av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
721 722
        --st->probe_packets;

723
        if (pkt) {
724
            uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
725
            if (!new_buf) {
726 727 728
                av_log(s, AV_LOG_WARNING,
                       "Failed to reallocate probe buffer for stream %d\n",
                       st->index);
729
                goto no_packet;
730
            }
731
            pd->buf = new_buf;
732
            memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
733
            pd->buf_size += pkt->size;
734
            memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
735
        } else {
736
no_packet:
737
            st->probe_packets = 0;
738
            if (!pd->buf_size) {
739
                av_log(s, AV_LOG_WARNING,
740
                       "nothing to probe for stream %d\n", st->index);
741
            }
742
        }
743

744
        end=    s->internal->raw_packet_buffer_remaining_size <= 0
745
                || st->probe_packets<= 0;
746

747 748
        if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
            int score = set_codec_from_probe_data(s, st, pd);
749
            if (    (st->codecpar->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
750
                || end) {
751
                pd->buf_size = 0;
752
                av_freep(&pd->buf);
753
                st->request_probe = -1;
754
                if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
755
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
756
                } else
757
                    av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
758
            }
759
            force_codec_ids(s, st);
760 761
        }
    }
762
    return 0;
763 764
}

765 766 767 768 769 770 771 772 773 774 775
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;
776
    ref &= (1LL << st->pts_wrap_bits)-1;
777 778 779 780

    // 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
781 782
    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)) ?
783 784 785 786 787 788 789
        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) {
790
            for (i = 0; i < s->nb_streams; i++) {
791 792
                if (av_find_program_from_stream(s, NULL, i))
                    continue;
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
                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;
815
        while (program) {
816
            if (program->pts_wrap_reference != pts_wrap_reference) {
817
                for (i = 0; i<program->nb_stream_indexes; i++) {
818 819 820 821 822 823 824 825 826 827 828 829 830
                    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;
}

831
int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
832
{
833
    int ret, i, err;
834
    AVStream *st;
835

836
    for (;;) {
837
        AVPacketList *pktl = s->internal->raw_packet_buffer;
838 839 840

        if (pktl) {
            *pkt = pktl->pkt;
841
            st   = s->streams[pkt->stream_index];
842
            if (s->internal->raw_packet_buffer_remaining_size <= 0)
843 844
                if ((err = probe_codec(s, st, NULL)) < 0)
                    return err;
845
            if (st->request_probe <= 0) {
846 847
                s->internal->raw_packet_buffer                 = pktl->next;
                s->internal->raw_packet_buffer_remaining_size += pkt->size;
848 849 850 851 852
                av_free(pktl);
                return 0;
            }
        }

853 854
        pkt->data = NULL;
        pkt->size = 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
855
        av_init_packet(pkt);
856
        ret = s->iformat->read_packet(s, pkt);
857
        if (ret < 0) {
858 859 860 861 862
            /* Some demuxers return FFERROR_REDO when they consume
               data and discard it (ignored streams, junk, extradata).
               We must re-call the demuxer to get the real packet. */
            if (ret == FFERROR_REDO)
                continue;
863 864
            if (!pktl || ret == AVERROR(EAGAIN))
                return ret;
865 866
            for (i = 0; i < s->nb_streams; i++) {
                st = s->streams[i];
867
                if (st->probe_packets || st->request_probe > 0)
868 869
                    if ((err = probe_codec(s, st, NULL)) < 0)
                        return err;
870
                av_assert0(st->request_probe <= 0);
871
            }
872 873
            continue;
        }
874

875 876 877
        err = av_packet_make_refcounted(pkt);
        if (err < 0)
            return err;
878

879 880 881 882 883
        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);
884
            av_packet_unref(pkt);
885 886 887
            continue;
        }

888
        if (pkt->stream_index >= (unsigned)s->nb_streams) {
889 890 891 892
            av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);
            continue;
        }

893
        st = s->streams[pkt->stream_index];
894 895 896 897 898 899 900 901 902 903 904

        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);
        }

905 906
        pkt->dts = wrap_timestamp(st, pkt->dts);
        pkt->pts = wrap_timestamp(st, pkt->pts);
907

908 909
        force_codec_ids(s, st);

910 911 912
        /* 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);
913

914
        if (!pktl && st->request_probe <= 0)
915 916
            return ret;

917 918 919
        err = ff_packet_list_put(&s->internal->raw_packet_buffer,
                                 &s->internal->raw_packet_buffer_end,
                                 pkt, 0);
920 921
        if (err)
            return err;
922
        s->internal->raw_packet_buffer_remaining_size -= pkt->size;
923

924 925
        if ((err = probe_codec(s, st, pkt)) < 0)
            return err;
926
    }
927 928
}

929

930 931
/**********************************************************/

932 933
static int determinable_frame_size(AVCodecContext *avctx)
{
934 935 936 937
    switch(avctx->codec_id) {
    case AV_CODEC_ID_MP1:
    case AV_CODEC_ID_MP2:
    case AV_CODEC_ID_MP3:
938
    case AV_CODEC_ID_CODEC2:
939
        return 1;
940 941
    }

942 943 944
    return 0;
}

945
/**
946
 * Return the frame duration in seconds. Return 0 if not available.
947
 */
948
void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
949
                               AVCodecParserContext *pc, AVPacket *pkt)
950
{
951
    AVRational codec_framerate = s->iformat ? st->internal->avctx->framerate :
952 953 954 955 956 957 958 959 960
                                              av_mul_q(av_inv_q(st->internal->avctx->time_base), (AVRational){1, st->internal->avctx->ticks_per_frame});
    int frame_size, sample_rate;

#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
    if ((!codec_framerate.den || !codec_framerate.num) && st->codec->time_base.den && st->codec->time_base.num)
        codec_framerate = av_mul_q(av_inv_q(st->codec->time_base), (AVRational){1, st->codec->ticks_per_frame});
FF_ENABLE_DEPRECATION_WARNINGS
#endif
961 962 963

    *pnum = 0;
    *pden = 0;
964
    switch (st->codecpar->codec_type) {
965
    case AVMEDIA_TYPE_VIDEO:
966
        if (st->r_frame_rate.num && !pc && s->iformat) {
967 968
            *pnum = st->r_frame_rate.den;
            *pden = st->r_frame_rate.num;
969
        } else if (st->time_base.num * 1000LL > st->time_base.den) {
970 971
            *pnum = st->time_base.num;
            *pden = st->time_base.den;
972
        } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
973
            av_assert0(st->internal->avctx->ticks_per_frame);
974 975
            av_reduce(pnum, pden,
                      codec_framerate.den,
976
                      codec_framerate.num * (int64_t)st->internal->avctx->ticks_per_frame,
977 978
                      INT_MAX);

979
            if (pc && pc->repeat_pict) {
980
                av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
981 982 983 984
                av_reduce(pnum, pden,
                          (*pnum) * (1LL + pc->repeat_pict),
                          (*pden),
                          INT_MAX);
985
            }
986 987 988
            /* 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. */
989
            if (st->internal->avctx->ticks_per_frame > 1 && !pc)
990
                *pnum = *pden = 0;
991 992
        }
        break;
993
    case AVMEDIA_TYPE_AUDIO:
994 995 996 997 998 999 1000 1001
        if (st->internal->avctx_inited) {
            frame_size = av_get_audio_frame_duration(st->internal->avctx, pkt->size);
            sample_rate = st->internal->avctx->sample_rate;
        } else {
            frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
            sample_rate = st->codecpar->sample_rate;
        }
        if (frame_size <= 0 || sample_rate <= 0)
1002 1003
            break;
        *pnum = frame_size;
1004
        *pden = sample_rate;
1005 1006 1007 1008 1009 1010
        break;
    default:
        break;
    }
}

1011 1012 1013 1014 1015 1016 1017 1018
static int is_intra_only(enum AVCodecID id)
{
    const AVCodecDescriptor *d = avcodec_descriptor_get(id);
    if (!d)
        return 0;
    if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
        return 0;
    return 1;
1019 1020
}

1021 1022
static int has_decode_delay_been_guessed(AVStream *st)
{
1023
    if (st->codecpar->codec_id != AV_CODEC_ID_H264) return 1;
1024
    if (!st->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
1025
        return 1;
1026
#if CONFIG_H264_DECODER
1027 1028
    if (st->internal->avctx->has_b_frames &&
       avpriv_h264_has_num_reorder_frames(st->internal->avctx) == st->internal->avctx->has_b_frames)
1029 1030
        return 1;
#endif
1031
    if (st->internal->avctx->has_b_frames<3)
1032
        return st->nb_decoded_frames >= 7;
1033
    else if (st->internal->avctx->has_b_frames<4)
1034
        return st->nb_decoded_frames >= 18;
1035
    else
1036
        return st->nb_decoded_frames >= 20;
1037 1038
}

1039 1040 1041 1042
static AVPacketList *get_next_pkt(AVFormatContext *s, AVStream *st, AVPacketList *pktl)
{
    if (pktl->next)
        return pktl->next;
1043 1044
    if (pktl == s->internal->packet_buffer_end)
        return s->internal->parse_queue;
1045 1046 1047
    return NULL;
}

1048
static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
1049 1050
    int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
                       st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1051 1052

    if(!onein_oneout) {
1053
        int delay = st->internal->avctx->has_b_frames;
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
        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;
}

1090 1091 1092 1093 1094 1095 1096 1097
/**
 * Updates the dts of packets of a stream in pkt_buffer, by re-ordering the pts
 * of the packets in a window.
 */
static void update_dts_from_pts(AVFormatContext *s, int stream_index,
                                AVPacketList *pkt_buffer)
{
    AVStream *st       = s->streams[stream_index];
1098
    int delay          = st->internal->avctx->has_b_frames;
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
    int i;

    int64_t pts_buffer[MAX_REORDER_DELAY+1];

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

    for (; pkt_buffer; pkt_buffer = get_next_pkt(s, st, pkt_buffer)) {
        if (pkt_buffer->pkt.stream_index != stream_index)
            continue;

        if (pkt_buffer->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
            pts_buffer[0] = pkt_buffer->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]);

            pkt_buffer->pkt.dts = select_from_pts_buffer(st, pts_buffer, pkt_buffer->pkt.dts);
        }
    }
}

1120
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
1121
                                      int64_t dts, int64_t pts, AVPacket *pkt)
1122
{
1123
    AVStream *st       = s->streams[stream_index];
1124
    AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1125 1126
    AVPacketList *pktl_it;

1127
    uint64_t shift;
1128

1129 1130
    if (st->first_dts != AV_NOPTS_VALUE ||
        dts           == AV_NOPTS_VALUE ||
1131
        st->cur_dts   == AV_NOPTS_VALUE ||
1132
        st->cur_dts < INT_MIN + RELATIVE_TS_BASE ||
1133
        is_relative(dts))
1134 1135
        return;

1136
    st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
1137
    st->cur_dts   = dts;
1138
    shift         = (uint64_t)st->first_dts - RELATIVE_TS_BASE;
1139

1140
    if (is_relative(pts))
1141
        pts += shift;
1142

1143 1144
    for (pktl_it = pktl; pktl_it; pktl_it = get_next_pkt(s, st, pktl_it)) {
        if (pktl_it->pkt.stream_index != stream_index)
1145
            continue;
1146 1147
        if (is_relative(pktl_it->pkt.pts))
            pktl_it->pkt.pts += shift;
1148

1149 1150
        if (is_relative(pktl_it->pkt.dts))
            pktl_it->pkt.dts += shift;
1151

1152
        if (st->start_time == AV_NOPTS_VALUE && pktl_it->pkt.pts != AV_NOPTS_VALUE) {
1153
            st->start_time = pktl_it->pkt.pts;
1154 1155
            if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
                st->start_time += av_rescale_q(st->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base);
1156
        }
1157
    }
1158

1159 1160
    if (has_decode_delay_been_guessed(st)) {
        update_dts_from_pts(s, stream_index, pktl);
1161
    }
1162

1163
    if (st->start_time == AV_NOPTS_VALUE) {
1164 1165 1166
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || !(pkt->flags & AV_PKT_FLAG_DISCARD)) {
            st->start_time = pts;
        }
1167 1168
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
            st->start_time += av_rescale_q(st->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base);
1169
    }
1170 1171
}

1172 1173
static void update_initial_durations(AVFormatContext *s, AVStream *st,
                                     int stream_index, int duration)
1174
{
1175
    AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1176
    int64_t cur_dts    = RELATIVE_TS_BASE;
1177

1178
    if (st->first_dts != AV_NOPTS_VALUE) {
1179 1180 1181
        if (st->update_initial_durations_done)
            return;
        st->update_initial_durations_done = 1;
1182
        cur_dts = st->first_dts;
1183
        for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1184 1185 1186 1187
            if (pktl->pkt.stream_index == stream_index) {
                if (pktl->pkt.pts != pktl->pkt.dts  ||
                    pktl->pkt.dts != AV_NOPTS_VALUE ||
                    pktl->pkt.duration)
1188
                    break;
1189
                cur_dts -= duration;
1190 1191
            }
        }
1192
        if (pktl && pktl->pkt.dts != st->first_dts) {
1193
            av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
1194
                   av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
1195 1196
            return;
        }
1197
        if (!pktl) {
1198
            av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
1199 1200
            return;
        }
1201
        pktl          = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1202
        st->first_dts = cur_dts;
1203
    } else if (st->cur_dts != RELATIVE_TS_BASE)
1204
        return;
1205

1206
    for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1207
        if (pktl->pkt.stream_index != stream_index)
1208
            continue;
1209 1210 1211 1212 1213
        if ((pktl->pkt.pts == pktl->pkt.dts ||
             pktl->pkt.pts == AV_NOPTS_VALUE) &&
            (pktl->pkt.dts == AV_NOPTS_VALUE ||
             pktl->pkt.dts == st->first_dts ||
             pktl->pkt.dts == RELATIVE_TS_BASE) &&
1214 1215
            !pktl->pkt.duration) {
            pktl->pkt.dts = cur_dts;
1216
            if (!st->internal->avctx->has_b_frames)
1217
                pktl->pkt.pts = cur_dts;
1218
//            if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1219
                pktl->pkt.duration = duration;
1220
        } else
1221
            break;
1222
        cur_dts = pktl->pkt.dts + pktl->pkt.duration;
1223
    }
1224
    if (!pktl)
1225
        st->cur_dts = cur_dts;
1226 1227
}

1228
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
1229 1230
                               AVCodecParserContext *pc, AVPacket *pkt,
                               int64_t next_dts, int64_t next_pts)
1231
{
1232
    int num, den, presentation_delayed, delay, i;
1233
    int64_t offset;
1234
    AVRational duration;
1235 1236
    int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
                       st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1237

1238 1239 1240
    if (s->flags & AVFMT_FLAG_NOFILLIN)
        return;

1241
    if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        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;
    }

1263 1264
    if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
        pkt->dts = AV_NOPTS_VALUE;
1265

1266
    if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1267
        && !st->internal->avctx->has_b_frames)
1268
        //FIXME Set low_delay = 0 when has_b_frames = 1
1269
        st->internal->avctx->has_b_frames = 1;
1270

1271
    /* do we have a video B-frame ? */
1272
    delay = st->internal->avctx->has_b_frames;
1273
    presentation_delayed = 0;
1274

1275
    /* XXX: need has_b_frame, but cannot get it if the codec is
1276
     *  not initialized */
1277
    if (delay &&
1278
        pc && pc->pict_type != AV_PICTURE_TYPE_B)
1279 1280
        presentation_delayed = 1;

1281 1282 1283
    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) {
1284 1285
        if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
            pkt->dts -= 1LL << st->pts_wrap_bits;
1286
        } else
1287
            pkt->pts += 1LL << st->pts_wrap_bits;
1288 1289
    }

1290 1291 1292 1293 1294 1295
    /* 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) {
1296
        av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1297 1298
        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
1299
            pkt->dts = AV_NOPTS_VALUE;
1300 1301
    }

1302
    duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1303
    if (pkt->duration == 0) {
1304
        ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1305
        if (den && num) {
1306 1307 1308
            duration = (AVRational) {num, den};
            pkt->duration = av_rescale_rnd(1,
                                           num * (int64_t) st->time_base.den,
1309 1310
                                           den * (int64_t) st->time_base.num,
                                           AV_ROUND_DOWN);
1311 1312
        }
    }
1313

1314
    if (pkt->duration != 0 && (s->internal->packet_buffer || s->internal->parse_queue))
1315
        update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1316

1317 1318 1319
    /* Correct timestamps with byte offset if demuxers only have timestamps
     * on packet boundaries */
    if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1320 1321
        /* this will estimate bitrate based on this frame's duration and size */
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1322
        if (pkt->pts != AV_NOPTS_VALUE)
1323
            pkt->pts += offset;
1324
        if (pkt->dts != AV_NOPTS_VALUE)
1325 1326 1327
            pkt->dts += offset;
    }

Diego Biurrun's avatar
Diego Biurrun committed
1328
    /* This may be redundant, but it should not hurt. */
1329 1330 1331
    if (pkt->dts != AV_NOPTS_VALUE &&
        pkt->pts != AV_NOPTS_VALUE &&
        pkt->pts > pkt->dts)
Michael Niedermayer's avatar
Michael Niedermayer committed
1332
        presentation_delayed = 1;
1333

1334
    if (s->debug & FF_FDEBUG_TS)
1335
        av_log(s, AV_LOG_DEBUG,
1336
            "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%"PRId64" delay:%d onein_oneout:%d\n",
1337
            presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1338
            pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1339

1340
    /* Interpolate PTS and DTS if they are not present. We skip H264
1341 1342
     * currently because delay and has_b_frames are not reliably set. */
    if ((delay == 0 || (delay == 1 && pc)) &&
1343
        onein_oneout) {
Michael Niedermayer's avatar
Michael Niedermayer committed
1344
        if (presentation_delayed) {
1345 1346
            /* DTS = decompression timestamp */
            /* PTS = presentation timestamp */
Michael Niedermayer's avatar
Michael Niedermayer committed
1347
            if (pkt->dts == AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
1348
                pkt->dts = st->last_IP_pts;
1349
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
Michael Niedermayer's avatar
Michael Niedermayer committed
1350 1351 1352
            if (pkt->dts == AV_NOPTS_VALUE)
                pkt->dts = st->cur_dts;

1353 1354
            /* 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. */
1355
            if (st->last_IP_duration == 0 && (uint64_t)pkt->duration <= INT32_MAX)
Michael Niedermayer's avatar
Michael Niedermayer committed
1356
                st->last_IP_duration = pkt->duration;
1357
            if (pkt->dts != AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
1358
                st->cur_dts = pkt->dts + st->last_IP_duration;
1359 1360 1361
            if (pkt->dts != AV_NOPTS_VALUE &&
                pkt->pts == AV_NOPTS_VALUE &&
                st->last_IP_duration > 0 &&
1362
                ((uint64_t)st->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1363 1364 1365 1366
                next_dts != next_pts &&
                next_pts != AV_NOPTS_VALUE)
                pkt->pts = next_dts;

1367 1368
            if ((uint64_t)pkt->duration <= INT32_MAX)
                st->last_IP_duration = pkt->duration;
1369 1370 1371
            st->last_IP_pts      = pkt->pts;
            /* Cannot compute PTS if not present (we can compute it only
             * by knowing the future. */
1372 1373
        } else if (pkt->pts != AV_NOPTS_VALUE ||
                   pkt->dts != AV_NOPTS_VALUE ||
1374
                   pkt->duration                ) {
1375

Michael Niedermayer's avatar
Michael Niedermayer committed
1376
            /* presentation is not delayed : PTS and DTS are the same */
1377
            if (pkt->pts == AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
1378
                pkt->pts = pkt->dts;
1379
            update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1380
                                      pkt->pts, pkt);
1381
            if (pkt->pts == AV_NOPTS_VALUE)
Michael Niedermayer's avatar
Michael Niedermayer committed
1382 1383
                pkt->pts = st->cur_dts;
            pkt->dts = pkt->pts;
1384
            if (pkt->pts != AV_NOPTS_VALUE)
1385
                st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
Michael Niedermayer's avatar
Michael Niedermayer committed
1386
        }
1387
    }
1388

1389
    if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1390 1391 1392
        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]);
1393

1394 1395
        if(has_decode_delay_been_guessed(st))
            pkt->dts = select_from_pts_buffer(st, st->pts_buffer, pkt->dts);
1396
    }
1397
    // We skipped it above so we try here.
1398
    if (!onein_oneout)
1399 1400 1401
        // 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)
1402
        st->cur_dts = pkt->dts;
1403

1404
    if (s->debug & FF_FDEBUG_TS)
1405
        av_log(s, AV_LOG_DEBUG, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s\n",
1406
            presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts));
1407

1408
    /* update flags */
1409
    if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || is_intra_only(st->codecpar->codec_id))
1410
        pkt->flags |= AV_PKT_FLAG_KEY;
1411 1412
#if FF_API_CONVERGENCE_DURATION
FF_DISABLE_DEPRECATION_WARNINGS
1413 1414
    if (pc)
        pkt->convergence_duration = pc->convergence_duration;
1415 1416
FF_ENABLE_DEPRECATION_WARNINGS
#endif
1417 1418
}

1419
void ff_packet_list_free(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
1420
{
1421 1422 1423 1424 1425
    AVPacketList *tmp = *pkt_buf;

    while (tmp) {
        AVPacketList *pktl = tmp;
        tmp = pktl->next;
1426
        av_packet_unref(&pktl->pkt);
1427 1428
        av_freep(&pktl);
    }
1429
    *pkt_buf     = NULL;
1430 1431
    *pkt_buf_end = NULL;
}
1432

1433
/**
1434
 * Parse a packet, add all split parts to parse_queue.
1435
 *
1436
 * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
1437 1438
 */
static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1439
{
1440
    AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1441 1442 1443
    AVStream *st = s->streams[stream_index];
    uint8_t *data = pkt ? pkt->data : NULL;
    int size      = pkt ? pkt->size : 0;
1444
    int ret = 0, got_output = 0;
1445

1446 1447
    if (!pkt) {
        av_init_packet(&flush_pkt);
1448
        pkt        = &flush_pkt;
1449
        got_output = 1;
1450 1451
    } else if (!size && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
        // preserve 0-size sync packets
1452
        compute_pkt_fields(s, st, st->parser, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1453
    }
1454

1455 1456
    while (size > 0 || (pkt == &flush_pkt && got_output)) {
        int len;
1457 1458
        int64_t next_pts = pkt->pts;
        int64_t next_dts = pkt->dts;
1459

1460
        av_init_packet(&out_pkt);
1461
        len = av_parser_parse2(st->parser, st->internal->avctx,
1462 1463
                               &out_pkt.data, &out_pkt.size, data, size,
                               pkt->pts, pkt->dts, pkt->pos);
1464

1465
        pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1466
        pkt->pos = -1;
1467 1468 1469 1470 1471 1472 1473 1474 1475
        /* increment read pointer */
        data += len;
        size -= len;

        got_output = !!out_pkt.size;

        if (!out_pkt.size)
            continue;

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
        if (pkt->buf && out_pkt.data == pkt->data) {
            /* reference pkt->buf only when out_pkt.data is guaranteed to point
             * to data in it and not in the parser's internal buffer. */
            /* XXX: Ensure this is the case with all parsers when st->parser->flags
             * is PARSER_FLAG_COMPLETE_FRAMES and check for that instead? */
            out_pkt.buf = av_buffer_ref(pkt->buf);
            if (!out_pkt.buf) {
                ret = AVERROR(ENOMEM);
                goto fail;
            }
        } else {
            ret = av_packet_make_refcounted(&out_pkt);
            if (ret < 0)
                goto fail;
        }

1492 1493 1494
        if (pkt->side_data) {
            out_pkt.side_data       = pkt->side_data;
            out_pkt.side_data_elems = pkt->side_data_elems;
1495 1496
            pkt->side_data          = NULL;
            pkt->side_data_elems    = 0;
1497 1498
        }

1499
        /* set the duration */
1500
        out_pkt.duration = (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;
1501 1502
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            if (st->internal->avctx->sample_rate > 0) {
1503 1504
                out_pkt.duration =
                    av_rescale_q_rnd(st->parser->duration,
1505
                                     (AVRational) { 1, st->internal->avctx->sample_rate },
1506 1507
                                     st->time_base,
                                     AV_ROUND_DOWN);
1508
            }
1509 1510 1511
        }

        out_pkt.stream_index = st->index;
1512 1513 1514
        out_pkt.pts          = st->parser->pts;
        out_pkt.dts          = st->parser->dts;
        out_pkt.pos          = st->parser->pos;
1515
        out_pkt.flags       |= pkt->flags & AV_PKT_FLAG_DISCARD;
1516

1517
        if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1518
            out_pkt.pos = st->parser->frame_offset;
1519 1520 1521 1522 1523 1524

        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;

1525
        if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1526 1527
            out_pkt.flags |= AV_PKT_FLAG_KEY;

1528
        compute_pkt_fields(s, st, st->parser, &out_pkt, next_dts, next_pts);
1529

1530 1531
        ret = ff_packet_list_put(&s->internal->parse_queue,
                                 &s->internal->parse_queue_end,
1532 1533 1534
                                 &out_pkt, 0);
        if (ret < 0) {
            av_packet_unref(&out_pkt);
1535
            goto fail;
1536
        }
1537 1538 1539 1540 1541 1542 1543 1544 1545
    }

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

fail:
1546
    av_packet_unref(pkt);
1547 1548 1549
    return ret;
}

1550 1551 1552
int ff_packet_list_get(AVPacketList **pkt_buffer,
                       AVPacketList **pkt_buffer_end,
                       AVPacket      *pkt)
1553 1554 1555
{
    AVPacketList *pktl;
    av_assert0(*pkt_buffer);
1556 1557
    pktl        = *pkt_buffer;
    *pkt        = pktl->pkt;
1558 1559 1560 1561 1562 1563 1564
    *pkt_buffer = pktl->next;
    if (!pktl->next)
        *pkt_buffer_end = NULL;
    av_freep(&pktl);
    return 0;
}

1565 1566
static int64_t ts_to_samples(AVStream *st, int64_t ts)
{
1567
    return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
1568 1569
}

1570
static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1571
{
1572
    int ret = 0, i, got_packet = 0;
1573
    AVDictionary *metadata = NULL;
1574

1575 1576
    av_init_packet(pkt);

1577
    while (!got_packet && !s->internal->parse_queue) {
1578 1579
        AVStream *st;
        AVPacket cur_pkt;
1580

1581
        /* read next packet */
1582
        ret = ff_read_packet(s, &cur_pkt);
1583 1584
        if (ret < 0) {
            if (ret == AVERROR(EAGAIN))
1585
                return ret;
1586
            /* flush the parsers */
1587
            for (i = 0; i < s->nb_streams; i++) {
1588 1589 1590
                st = s->streams[i];
                if (st->parser && st->need_parsing)
                    parse_packet(s, NULL, st->index);
1591
            }
1592 1593 1594 1595 1596 1597 1598
            /* all remaining packets are now in parse_queue =>
             * really terminate parsing */
            break;
        }
        ret = 0;
        st  = s->streams[cur_pkt.stream_index];

1599 1600 1601 1602 1603 1604 1605 1606
        /* update context if required */
        if (st->internal->need_context_update) {
            if (avcodec_is_open(st->internal->avctx)) {
                av_log(s, AV_LOG_DEBUG, "Demuxer context update while decoder is open, closing and trying to re-open\n");
                avcodec_close(st->internal->avctx);
                st->info->found_decoder = 0;
            }

1607 1608 1609 1610 1611 1612
            /* close parser, because it depends on the codec */
            if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
                av_parser_close(st->parser);
                st->parser = NULL;
            }

1613 1614 1615 1616
            ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
            if (ret < 0)
                return ret;

1617 1618 1619 1620 1621 1622 1623 1624 1625
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
            /* update deprecated public codec context */
            ret = avcodec_parameters_to_context(st->codec, st->codecpar);
            if (ret < 0)
                return ret;
FF_ENABLE_DEPRECATION_WARNINGS
#endif

1626 1627 1628
            st->internal->need_context_update = 0;
        }

1629 1630 1631
        if (cur_pkt.pts != AV_NOPTS_VALUE &&
            cur_pkt.dts != AV_NOPTS_VALUE &&
            cur_pkt.pts < cur_pkt.dts) {
1632
            av_log(s, AV_LOG_WARNING,
1633
                   "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1634
                   cur_pkt.stream_index,
1635 1636
                   av_ts2str(cur_pkt.pts),
                   av_ts2str(cur_pkt.dts),
1637 1638 1639
                   cur_pkt.size);
        }
        if (s->debug & FF_FDEBUG_TS)
1640
            av_log(s, AV_LOG_DEBUG,
1641
                   "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%"PRId64", flags=%d\n",
1642
                   cur_pkt.stream_index,
1643 1644
                   av_ts2str(cur_pkt.pts),
                   av_ts2str(cur_pkt.dts),
1645
                   cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
1646 1647

        if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1648
            st->parser = av_parser_init(st->codecpar->codec_id);
1649
            if (!st->parser) {
1650 1651
                av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
                       "%s, packets or times may be invalid.\n",
1652
                       avcodec_get_name(st->codecpar->codec_id));
1653 1654
                /* no parser available: just output the raw packets */
                st->need_parsing = AVSTREAM_PARSE_NONE;
1655
            } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1656
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1657
            else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1658
                st->parser->flags |= PARSER_FLAG_ONCE;
1659
            else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1660
                st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1661
        }
1662

1663 1664 1665
        if (!st->need_parsing || !st->parser) {
            /* no parsing needed: we just output the packet as is */
            *pkt = cur_pkt;
1666
            compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1667 1668 1669
            if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
                (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
                ff_reduce_index(s, st->index);
1670 1671
                av_add_index_entry(st, pkt->pos, pkt->dts,
                                   0, 0, AVINDEX_KEYFRAME);
1672
            }
1673 1674 1675 1676
            got_packet = 1;
        } else if (st->discard < AVDISCARD_ALL) {
            if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
                return ret;
1677 1678 1679 1680 1681
            st->codecpar->sample_rate = st->internal->avctx->sample_rate;
            st->codecpar->bit_rate = st->internal->avctx->bit_rate;
            st->codecpar->channels = st->internal->avctx->channels;
            st->codecpar->channel_layout = st->internal->avctx->channel_layout;
            st->codecpar->codec_id = st->internal->avctx->codec_id;
1682 1683
        } else {
            /* free packet */
1684
            av_packet_unref(&cur_pkt);
1685
        }
1686 1687 1688
        if (pkt->flags & AV_PKT_FLAG_KEY)
            st->skip_to_keyframe = 0;
        if (st->skip_to_keyframe) {
1689
            av_packet_unref(&cur_pkt);
1690 1691 1692
            if (got_packet) {
                *pkt = cur_pkt;
            }
1693 1694
            got_packet = 0;
        }
1695
    }
1696

1697
    if (!got_packet && s->internal->parse_queue)
1698
        ret = ff_packet_list_get(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
1699

1700 1701
    if (ret >= 0) {
        AVStream *st = s->streams[pkt->stream_index];
1702
        int discard_padding = 0;
1703
        if (st->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1704 1705 1706 1707
            int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
            int64_t sample = ts_to_samples(st, pts);
            int duration = ts_to_samples(st, pkt->duration);
            int64_t end_sample = sample + duration;
1708 1709 1710
            if (duration > 0 && end_sample >= st->first_discard_sample &&
                sample < st->last_discard_sample)
                discard_padding = FFMIN(end_sample - st->first_discard_sample, duration);
1711
        }
1712 1713
        if (st->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
            st->skip_samples = st->start_skip_samples;
1714
        if (st->skip_samples || discard_padding) {
1715 1716 1717
            uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
            if (p) {
                AV_WL32(p, st->skip_samples);
1718
                AV_WL32(p + 4, discard_padding);
1719
                av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d / discard %d\n", st->skip_samples, discard_padding);
1720 1721 1722
            }
            st->skip_samples = 0;
        }
1723

1724
        if (st->inject_global_side_data) {
1725 1726 1727 1728 1729 1730 1731 1732 1733
            for (i = 0; i < st->nb_side_data; i++) {
                AVPacketSideData *src_sd = &st->side_data[i];
                uint8_t *dst_data;

                if (av_packet_get_side_data(pkt, src_sd->type, NULL))
                    continue;

                dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
                if (!dst_data) {
1734
                    av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1735 1736 1737 1738 1739
                    continue;
                }

                memcpy(dst_data, src_sd->data, src_sd->size);
            }
1740
            st->inject_global_side_data = 0;
1741
        }
1742
    }
1743

1744 1745 1746 1747 1748 1749 1750 1751
    av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
    if (metadata) {
        s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
        av_dict_copy(&s->metadata, metadata, 0);
        av_dict_free(&metadata);
        av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
    }

1752 1753 1754 1755
#if FF_API_LAVF_AVCTX
    update_stream_avctx(s);
#endif

1756 1757
    if (s->debug & FF_FDEBUG_TS)
        av_log(s, AV_LOG_DEBUG,
1758
               "read_frame_internal stream=%d, pts=%s, dts=%s, "
1759
               "size=%d, duration=%"PRId64", flags=%d\n",
1760 1761 1762
               pkt->stream_index,
               av_ts2str(pkt->pts),
               av_ts2str(pkt->dts),
1763
               pkt->size, pkt->duration, pkt->flags);
1764

1765
    return ret;
1766 1767
}

1768
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Fabrice Bellard's avatar
Fabrice Bellard committed
1769
{
1770
    const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1771
    int eof = 0;
1772
    int ret;
1773
    AVStream *st;
1774

1775
    if (!genpts) {
1776
        ret = s->internal->packet_buffer
1777
              ? ff_packet_list_get(&s->internal->packet_buffer,
1778
                                        &s->internal->packet_buffer_end, pkt)
1779
              : read_frame_internal(s, pkt);
1780 1781 1782
        if (ret < 0)
            return ret;
        goto return_packet;
1783
    }
1784

1785
    for (;;) {
1786
        AVPacketList *pktl = s->internal->packet_buffer;
1787 1788

        if (pktl) {
1789
            AVPacket *next_pkt = &pktl->pkt;
1790

1791
            if (next_pkt->dts != AV_NOPTS_VALUE) {
1792
                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1793 1794 1795
                // 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;
1796
                av_assert2(wrap_bits <= 64);
1797 1798
                while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
                    if (pktl->pkt.stream_index == next_pkt->stream_index &&
1799 1800
                        av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) {
                        if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) {
1801
                            // not B-frame
1802 1803 1804 1805 1806 1807
                            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;
                        }
1808
                    }
1809
                    pktl = pktl->next;
1810
                }
1811 1812 1813 1814 1815 1816 1817 1818
                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;
                }
1819
                pktl = s->internal->packet_buffer;
1820
            }
1821

1822
            /* read packet from packet buffer, if there is data */
1823 1824
            st = s->streams[next_pkt->stream_index];
            if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1825
                  next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1826
                ret = ff_packet_list_get(&s->internal->packet_buffer,
1827
                                               &s->internal->packet_buffer_end, pkt);
1828 1829
                goto return_packet;
            }
1830
        }
1831

1832 1833 1834 1835 1836 1837 1838
        ret = read_frame_internal(s, pkt);
        if (ret < 0) {
            if (pktl && ret != AVERROR(EAGAIN)) {
                eof = 1;
                continue;
            } else
                return ret;
1839
        }
1840

1841 1842 1843
        ret = ff_packet_list_put(&s->internal->packet_buffer,
                                 &s->internal->packet_buffer_end,
                                 pkt, FF_PACKETLIST_FLAG_REF_PACKET);
1844
        av_packet_unref(pkt);
1845 1846
        if (ret < 0)
            return ret;
1847
    }
1848 1849

return_packet:
1850

1851
    st = s->streams[pkt->stream_index];
1852 1853 1854 1855 1856
    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);
    }

1857 1858 1859 1860
    if (is_relative(pkt->dts))
        pkt->dts -= RELATIVE_TS_BASE;
    if (is_relative(pkt->pts))
        pkt->pts -= RELATIVE_TS_BASE;
1861

1862
    return ret;
1863 1864 1865 1866 1867
}

/* XXX: suppress the packet queue */
static void flush_packet_queue(AVFormatContext *s)
{
1868 1869
    if (!s->internal)
        return;
1870 1871 1872
    ff_packet_list_free(&s->internal->parse_queue,       &s->internal->parse_queue_end);
    ff_packet_list_free(&s->internal->packet_buffer,     &s->internal->packet_buffer_end);
    ff_packet_list_free(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
1873

1874
    s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1875 1876
}

1877 1878 1879
/*******************************************************/
/* seek support */

1880 1881 1882 1883
int av_find_default_stream_index(AVFormatContext *s)
{
    int i;
    AVStream *st;
1884
    int best_stream = 0;
1885
    int best_score = INT_MIN;
1886 1887 1888

    if (s->nb_streams <= 0)
        return -1;
1889
    for (i = 0; i < s->nb_streams; i++) {
1890
        int score = 0;
1891
        st = s->streams[i];
1892
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1893 1894
            if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
                score -= 400;
1895
            if (st->codecpar->width && st->codecpar->height)
1896 1897
                score += 50;
            score+= 25;
1898
        }
1899 1900
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            if (st->codecpar->sample_rate)
1901 1902
                score += 50;
        }
1903 1904
        if (st->codec_info_nb_frames)
            score += 12;
1905

1906 1907 1908
        if (st->discard != AVDISCARD_ALL)
            score += 200;

1909 1910 1911
        if (score > best_score) {
            best_score = score;
            best_stream = i;
1912 1913
        }
    }
1914
    return best_stream;
1915 1916
}

1917
/** Flush the frame reader. */
1918
void ff_read_frame_flush(AVFormatContext *s)
1919 1920
{
    AVStream *st;
1921
    int i, j;
1922 1923 1924

    flush_packet_queue(s);

1925 1926
    /* Reset read state for each stream. */
    for (i = 0; i < s->nb_streams; i++) {
1927
        st = s->streams[i];
1928

1929 1930 1931 1932
        if (st->parser) {
            av_parser_close(st->parser);
            st->parser = NULL;
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
1933
        st->last_IP_pts = AV_NOPTS_VALUE;
1934
        st->last_dts_for_order_check = AV_NOPTS_VALUE;
1935 1936 1937 1938 1939
        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;
1940 1941

        st->probe_packets = MAX_PROBE_PACKETS;
1942

1943 1944
        for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
            st->pts_buffer[j] = AV_NOPTS_VALUE;
1945

1946 1947
        if (s->internal->inject_global_side_data)
            st->inject_global_side_data = 1;
1948 1949

        st->skip_samples = 0;
1950 1951 1952
    }
}

1953 1954
void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
{
1955 1956
    int i;

1957
    for (i = 0; i < s->nb_streams; i++) {
1958
        AVStream *st = s->streams[i];
1959

1960 1961 1962 1963
        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);
1964 1965 1966
    }
}

1967 1968
void ff_reduce_index(AVFormatContext *s, int stream_index)
{
1969 1970
    AVStream *st             = s->streams[stream_index];
    unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1971

1972
    if ((unsigned) st->nb_index_entries >= max_entries) {
1973
        int i;
1974 1975 1976
        for (i = 0; 2 * i < st->nb_index_entries; i++)
            st->index_entries[i] = st->index_entries[2 * i];
        st->nb_index_entries = i;
1977 1978 1979
    }
}

1980 1981 1982
int ff_add_index_entry(AVIndexEntry **index_entries,
                       int *nb_index_entries,
                       unsigned int *index_entries_allocated_size,
1983 1984
                       int64_t pos, int64_t timestamp,
                       int size, int distance, int flags)
1985 1986
{
    AVIndexEntry *entries, *ie;
1987
    int index;
1988

1989
    if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1990
        return -1;
1991

1992
    if (timestamp == AV_NOPTS_VALUE)
1993 1994
        return AVERROR(EINVAL);

1995 1996 1997
    if (size < 0 || size > 0x3FFFFFFF)
        return AVERROR(EINVAL);

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

2001 2002 2003
    entries = av_fast_realloc(*index_entries,
                              index_entries_allocated_size,
                              (*nb_index_entries + 1) *
2004
                              sizeof(AVIndexEntry));
2005
    if (!entries)
2006 2007
        return -1;

2008
    *index_entries = entries;
2009

2010 2011
    index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
                                      timestamp, AVSEEK_FLAG_ANY);
2012

2013 2014 2015
    if (index < 0) {
        index = (*nb_index_entries)++;
        ie    = &entries[index];
2016
        av_assert0(index == 0 || ie[-1].timestamp < timestamp);
2017 2018 2019 2020
    } else {
        ie = &entries[index];
        if (ie->timestamp != timestamp) {
            if (ie->timestamp <= timestamp)
2021
                return -1;
2022 2023
            memmove(entries + index + 1, entries + index,
                    sizeof(AVIndexEntry) * (*nb_index_entries - index));
2024
            (*nb_index_entries)++;
2025 2026 2027
        } else if (ie->pos == pos && distance < ie->min_distance)
            // do not reduce the distance
            distance = ie->min_distance;
2028
    }
2029

2030 2031 2032 2033 2034
    ie->pos          = pos;
    ie->timestamp    = timestamp;
    ie->min_distance = distance;
    ie->size         = size;
    ie->flags        = flags;
2035

2036
    return index;
2037 2038
}

2039 2040
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
                       int size, int distance, int flags)
2041
{
2042
    timestamp = wrap_timestamp(st, timestamp);
2043 2044 2045 2046 2047 2048 2049
    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)
2050 2051 2052 2053
{
    int a, b, m;
    int64_t timestamp;

2054
    a = -1;
2055
    b = nb_entries;
2056

2057 2058 2059
    // Optimize appending index entries at the end.
    if (b && entries[b - 1].timestamp < wanted_timestamp)
        a = b - 1;
2060

2061
    while (b - a > 1) {
2062
        m         = (a + b) >> 1;
2063 2064

        // Search for the next non-discarded packet.
2065
        while ((entries[m].flags & AVINDEX_DISCARD_FRAME) && m < b && m < nb_entries - 1) {
2066 2067 2068 2069 2070 2071 2072
            m++;
            if (m == b && entries[m].timestamp >= wanted_timestamp) {
                m = b - 1;
                break;
            }
        }

2073
        timestamp = entries[m].timestamp;
2074
        if (timestamp >= wanted_timestamp)
2075
            b = m;
2076
        if (timestamp <= wanted_timestamp)
2077
            a = m;
2078
    }
2079
    m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
2080

2081 2082 2083
    if (!(flags & AVSEEK_FLAG_ANY))
        while (m >= 0 && m < nb_entries &&
               !(entries[m].flags & AVINDEX_KEYFRAME))
2084
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
2085

2086
    if (m == nb_entries)
2087
        return -1;
2088
    return m;
2089 2090
}

2091 2092 2093 2094
void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
{
    int ist1, ist2;
    int64_t pos_delta = 0;
2095
    int64_t skip = 0;
2096
    //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable
2097
    const char *proto = avio_find_protocol_name(s->url);
2098

2099 2100 2101 2102 2103 2104 2105
    if (!proto) {
        av_log(s, AV_LOG_INFO,
               "Protocol name not provided, cannot determine if input is local or "
               "a network protocol, buffers and access patterns cannot be configured "
               "optimally without knowing the protocol\n");
    }

2106
    if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))
2107
        return;
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121

    for (ist1 = 0; ist1 < s->nb_streams; ist1++) {
        AVStream *st1 = s->streams[ist1];
        for (ist2 = 0; ist2 < s->nb_streams; ist2++) {
            AVStream *st2 = s->streams[ist2];
            int i1, i2;

            if (ist1 == ist2)
                continue;

            for (i1 = i2 = 0; i1 < st1->nb_index_entries; i1++) {
                AVIndexEntry *e1 = &st1->index_entries[i1];
                int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);

2122
                skip = FFMAX(skip, e1->size);
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
                for (; i2 < st2->nb_index_entries; i2++) {
                    AVIndexEntry *e2 = &st2->index_entries[i2];
                    int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);
                    if (e2_pts - e1_pts < time_tolerance)
                        continue;
                    pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);
                    break;
                }
            }
        }
    }

    pos_delta *= 2;
    /* XXX This could be adjusted depending on protocol*/
    if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {
        av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);
        ffio_set_buf_size(s->pb, pos_delta);
        s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);
    }
2142 2143 2144 2145

    if (skip < (1<<23)) {
        s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, skip);
    }
2146 2147
}

2148
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
2149 2150 2151 2152 2153
{
    return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
                                     wanted_timestamp, flags);
}

2154 2155 2156
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 ))
{
2157 2158 2159 2160
    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;
2161 2162
}

2163 2164
int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
                         int64_t target_ts, int flags)
2165
{
2166
    AVInputFormat *avif = s->iformat;
2167
    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
2168
    int64_t ts_min, ts_max, ts;
2169
    int index;
2170
    int64_t ret;
2171 2172
    AVStream *st;

2173 2174
    if (stream_index < 0)
        return -1;
2175

2176
    av_log(s, AV_LOG_TRACE, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2177

2178 2179 2180
    ts_max =
    ts_min = AV_NOPTS_VALUE;
    pos_limit = -1; // GCC falsely says it may be uninitialized.
2181

2182 2183
    st = s->streams[stream_index];
    if (st->index_entries) {
2184 2185
        AVIndexEntry *e;

2186 2187 2188 2189 2190 2191
        /* 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];
2192

2193 2194 2195
        if (e->timestamp <= target_ts || e->pos == e->min_distance) {
            pos_min = e->pos;
            ts_min  = e->timestamp;
2196
            av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
2197
                    pos_min, av_ts2str(ts_min));
2198
        } else {
2199
            av_assert1(index == 0);
2200
        }
2201

2202 2203
        index = av_index_search_timestamp(st, target_ts,
                                          flags & ~AVSEEK_FLAG_BACKWARD);
2204
        av_assert0(index < st->nb_index_entries);
2205 2206
        if (index >= 0) {
            e = &st->index_entries[index];
2207
            av_assert1(e->timestamp >= target_ts);
2208 2209 2210
            pos_max   = e->pos;
            ts_max    = e->timestamp;
            pos_limit = pos_max - e->min_distance;
2211
            av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
2212
                    " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
2213 2214 2215
        }
    }

2216 2217 2218
    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)
2219 2220 2221
        return -1;

    /* do the seek */
2222
    if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
2223
        return ret;
2224

2225
    ff_read_frame_flush(s);
2226
    ff_update_cur_dts(s, st, ts);
2227 2228 2229 2230

    return 0;
}

2231 2232 2233
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 ))
{
2234
    int64_t step = 1024;
2235 2236
    int64_t limit, ts_max;
    int64_t filesize = avio_size(s->pb);
2237 2238
    int64_t pos_max  = filesize - 1;
    do {
2239 2240
        limit = pos_max;
        pos_max = FFMAX(0, (pos_max) - step);
2241 2242 2243 2244
        ts_max  = ff_read_timestamp(s, stream_index,
                                    &pos_max, limit, read_timestamp);
        step   += step;
    } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
2245 2246 2247
    if (ts_max == AV_NOPTS_VALUE)
        return -1;

2248
    for (;;) {
2249
        int64_t tmp_pos = pos_max + 1;
2250 2251 2252
        int64_t tmp_ts  = ff_read_timestamp(s, stream_index,
                                            &tmp_pos, INT64_MAX, read_timestamp);
        if (tmp_ts == AV_NOPTS_VALUE)
2253
            break;
2254
        av_assert0(tmp_pos > pos_max);
2255 2256
        ts_max  = tmp_ts;
        pos_max = tmp_pos;
2257
        if (tmp_pos >= filesize)
2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
            break;
    }

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

    return 0;
}

2269 2270
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,
2271 2272 2273 2274
                      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))
2275
{
2276
    int64_t pos, ts;
2277
    int64_t start_pos;
2278
    int no_change;
2279
    int ret;
2280

2281
    av_log(s, AV_LOG_TRACE, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2282

2283
    if (ts_min == AV_NOPTS_VALUE) {
2284
        pos_min = s->internal->data_offset;
2285
        ts_min  = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2286 2287 2288 2289
        if (ts_min == AV_NOPTS_VALUE)
            return -1;
    }

2290 2291
    if (ts_min >= target_ts) {
        *ts_ret = ts_min;
2292 2293 2294
        return pos_min;
    }

2295
    if (ts_max == AV_NOPTS_VALUE) {
2296 2297
        if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
            return ret;
2298
        pos_limit = pos_max;
2299 2300
    }

2301 2302
    if (ts_max <= target_ts) {
        *ts_ret = ts_max;
2303 2304 2305
        return pos_max;
    }

2306
    av_assert0(ts_min < ts_max);
2307

2308
    no_change = 0;
2309
    while (pos_min < pos_limit) {
2310
        av_log(s, AV_LOG_TRACE,
2311
                "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2312
                pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2313
        av_assert0(pos_limit <= pos_max);
2314

2315 2316
        if (no_change == 0) {
            int64_t approximate_keyframe_distance = pos_max - pos_limit;
2317
            // interpolate position (better than dichotomy)
2318 2319 2320 2321 2322 2323 2324
            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 {
2325
            /* linear search if bisection failed, can only happen if there
2326 2327
             * are very few or no keyframes between min/max */
            pos = pos_min;
2328
        }
2329 2330 2331 2332 2333 2334 2335
        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.
2336
        ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2337
        if (pos == pos_max)
2338 2339
            no_change++;
        else
2340
            no_change = 0;
2341
        av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2342
                " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2343 2344
                pos_min, pos, pos_max,
                av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2345
                pos_limit, start_pos, no_change);
2346
        if (ts == AV_NOPTS_VALUE) {
2347 2348 2349
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
            return -1;
        }
2350
        if (target_ts <= ts) {
2351
            pos_limit = start_pos - 1;
2352 2353
            pos_max   = pos;
            ts_max    = ts;
2354 2355
        }
        if (target_ts >= ts) {
2356
            pos_min = pos;
2357
            ts_min  = ts;
2358 2359
        }
    }
2360

2361 2362
    pos     = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
    ts      = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min  : ts_max;
2363
#if 0
2364
    pos_min = pos;
2365
    ts_min  = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2366
    pos_min++;
2367
    ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2368
    av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2369
            pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2370
#endif
2371
    *ts_ret = ts;
2372
    return pos;
2373 2374
}

2375 2376 2377
static int seek_frame_byte(AVFormatContext *s, int stream_index,
                           int64_t pos, int flags)
{
2378 2379
    int64_t pos_min, pos_max;

2380
    pos_min = s->internal->data_offset;
2381
    pos_max = avio_size(s->pb) - 1;
2382

2383 2384 2385 2386
    if (pos < pos_min)
        pos = pos_min;
    else if (pos > pos_max)
        pos = pos_max;
2387

2388
    avio_seek(s->pb, pos, SEEK_SET);
2389

2390 2391
    s->io_repositioned = 1;

2392 2393 2394
    return 0;
}

2395 2396
static int seek_frame_generic(AVFormatContext *s, int stream_index,
                              int64_t timestamp, int flags)
2397
{
2398 2399
    int index;
    int64_t ret;
2400 2401 2402 2403
    AVStream *st;
    AVIndexEntry *ie;

    st = s->streams[stream_index];
2404

2405
    index = av_index_search_timestamp(st, timestamp, flags);
2406

2407 2408
    if (index < 0 && st->nb_index_entries &&
        timestamp < st->index_entries[0].timestamp)
2409 2410
        return -1;

2411
    if (index < 0 || index == st->nb_index_entries - 1) {
2412
        AVPacket pkt;
2413
        int nonkey = 0;
2414

2415
        if (st->nb_index_entries) {
2416
            av_assert0(st->index_entries);
2417
            ie = &st->index_entries[st->nb_index_entries - 1];
2418
            if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2419
                return ret;
2420
            ff_update_cur_dts(s, st, ie->timestamp);
2421
        } else {
2422
            if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
2423 2424
                return ret;
        }
2425
        for (;;) {
2426
            int read_status;
2427
            do {
2428 2429 2430
                read_status = av_read_frame(s, &pkt);
            } while (read_status == AVERROR(EAGAIN));
            if (read_status < 0)
2431
                break;
2432
            if (stream_index == pkt.stream_index && pkt.dts > timestamp) {
2433 2434
                if (pkt.flags & AV_PKT_FLAG_KEY) {
                    av_packet_unref(&pkt);
2435
                    break;
2436
                }
2437
                if (nonkey++ > 1000 && st->codecpar->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2438
                    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);
2439
                    av_packet_unref(&pkt);
2440 2441
                    break;
                }
2442
            }
2443
            av_packet_unref(&pkt);
2444 2445 2446
        }
        index = av_index_search_timestamp(st, timestamp, flags);
    }
2447 2448 2449
    if (index < 0)
        return -1;

2450
    ff_read_frame_flush(s);
2451 2452
    if (s->iformat->read_seek)
        if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2453 2454
            return 0;
    ie = &st->index_entries[index];
2455
    if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2456
        return ret;
2457
    ff_update_cur_dts(s, st, ie->timestamp);
2458

2459 2460 2461
    return 0;
}

2462 2463
static int seek_frame_internal(AVFormatContext *s, int stream_index,
                               int64_t timestamp, int flags)
2464 2465
{
    int ret;
2466
    AVStream *st;
2467

2468
    if (flags & AVSEEK_FLAG_BYTE) {
2469 2470
        if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
            return -1;
2471
        ff_read_frame_flush(s);
2472
        return seek_frame_byte(s, stream_index, timestamp, flags);
2473
    }
2474

2475 2476 2477
    if (stream_index < 0) {
        stream_index = av_find_default_stream_index(s);
        if (stream_index < 0)
2478
            return -1;
2479

2480
        st = s->streams[stream_index];
2481
        /* timestamp for default must be expressed in AV_TIME_BASE units */
2482 2483
        timestamp = av_rescale(timestamp, st->time_base.den,
                               AV_TIME_BASE * (int64_t) st->time_base.num);
2484 2485
    }

2486
    /* first, we try the format specific seek */
2487 2488
    if (s->iformat->read_seek) {
        ff_read_frame_flush(s);
2489
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2490
    } else
2491
        ret = -1;
2492
    if (ret >= 0)
2493
        return 0;
2494

2495 2496
    if (s->iformat->read_timestamp &&
        !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2497
        ff_read_frame_flush(s);
2498
        return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2499 2500
    } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
        ff_read_frame_flush(s);
2501
        return seek_frame_generic(s, stream_index, timestamp, flags);
2502
    } else
2503
        return -1;
2504 2505
}

2506 2507
int av_seek_frame(AVFormatContext *s, int stream_index,
                  int64_t timestamp, int flags)
2508
{
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
    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);
    }
2520

2521
    ret = seek_frame_internal(s, stream_index, timestamp, flags);
2522 2523

    if (ret >= 0)
2524
        ret = avformat_queue_attached_pictures(s);
2525 2526 2527 2528

    return ret;
}

2529 2530
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
                       int64_t ts, int64_t max_ts, int flags)
2531
{
2532
    if (min_ts > ts || max_ts < ts)
2533
        return -1;
2534 2535
    if (stream_index < -1 || stream_index >= (int)s->nb_streams)
        return AVERROR(EINVAL);
2536

2537
    if (s->seek2any>0)
2538
        flags |= AVSEEK_FLAG_ANY;
2539
    flags &= ~AVSEEK_FLAG_BACKWARD;
2540

2541
    if (s->iformat->read_seek2) {
2542
        int ret;
2543
        ff_read_frame_flush(s);
2544 2545 2546 2547 2548 2549

        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,
2550
                                    AV_ROUND_UP   | AV_ROUND_PASS_MINMAX);
2551 2552
            max_ts = av_rescale_rnd(max_ts, time_base.den,
                                    time_base.num * (int64_t)AV_TIME_BASE,
2553
                                    AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2554
            stream_index = 0;
2555 2556
        }

2557 2558
        ret = s->iformat->read_seek2(s, stream_index, min_ts,
                                     ts, max_ts, flags);
2559 2560

        if (ret >= 0)
2561
            ret = avformat_queue_attached_pictures(s);
2562
        return ret;
2563
    }
2564

2565 2566
    if (s->iformat->read_timestamp) {
        // try to seek via read_timestamp()
2567 2568
    }

Diego Biurrun's avatar
Diego Biurrun committed
2569 2570
    // Fall back on old API if new is not implemented but old is.
    // Note the old API has somewhat different semantics.
2571
    if (s->iformat->read_seek || 1) {
2572
        int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2573 2574 2575 2576 2577 2578 2579 2580
        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;
    }
2581

2582
    // try some generic seek like seek_frame_generic() but with new ts semantics
2583
    return -1; //unreachable
2584 2585
}

wm4's avatar
wm4 committed
2586 2587 2588 2589 2590 2591
int avformat_flush(AVFormatContext *s)
{
    ff_read_frame_flush(s);
    return 0;
}

2592
/*******************************************************/
2593

2594
/**
2595
 * Return TRUE if the stream has accurate duration in any stream.
2596
 *
2597
 * @return TRUE if the stream has accurate duration for at least one component.
2598
 */
2599
static int has_duration(AVFormatContext *ic)
2600 2601 2602 2603
{
    int i;
    AVStream *st;

2604
    for (i = 0; i < ic->nb_streams; i++) {
2605
        st = ic->streams[i];
2606
        if (st->duration != AV_NOPTS_VALUE)
2607 2608
            return 1;
    }
2609
    if (ic->duration != AV_NOPTS_VALUE)
2610
        return 1;
2611 2612 2613
    return 0;
}

2614 2615 2616 2617 2618
/**
 * Estimate the stream timings from the one of each components.
 *
 * Also computes the global bitrate if possible.
 */
2619
static void update_stream_timings(AVFormatContext *ic)
2620
{
2621
    int64_t start_time, start_time1, start_time_text, end_time, end_time1, end_time_text;
2622
    int64_t duration, duration1, duration_text, filesize;
2623
    int i;
2624
    AVProgram *p;
2625

2626
    start_time = INT64_MAX;
2627
    start_time_text = INT64_MAX;
2628
    end_time   = INT64_MIN;
2629
    end_time_text   = INT64_MIN;
2630
    duration   = INT64_MIN;
2631 2632
    duration_text = INT64_MIN;

2633
    for (i = 0; i < ic->nb_streams; i++) {
2634 2635 2636
        AVStream *st = ic->streams[i];
        int is_text = st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ||
                      st->codecpar->codec_type == AVMEDIA_TYPE_DATA;
2637
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2638 2639
            start_time1 = av_rescale_q(st->start_time, st->time_base,
                                       AV_TIME_BASE_Q);
2640 2641 2642
            if (is_text)
                start_time_text = FFMIN(start_time_text, start_time1);
            else
2643
                start_time = FFMIN(start_time, start_time1);
2644 2645 2646
            end_time1 = av_rescale_q_rnd(st->duration, st->time_base,
                                         AV_TIME_BASE_Q,
                                         AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
2647
            if (end_time1 != AV_NOPTS_VALUE && (end_time1 > 0 ? start_time1 <= INT64_MAX - end_time1 : start_time1 >= INT64_MIN - end_time1)) {
2648
                end_time1 += start_time1;
2649
                if (is_text)
2650 2651 2652
                    end_time_text = FFMAX(end_time_text, end_time1);
                else
                    end_time = FFMAX(end_time, end_time1);
2653
            }
2654 2655
            for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
                if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2656
                    p->start_time = start_time1;
2657
                if (p->end_time < end_time1)
2658 2659
                    p->end_time = end_time1;
            }
2660
        }
2661
        if (st->duration != AV_NOPTS_VALUE) {
2662 2663
            duration1 = av_rescale_q(st->duration, st->time_base,
                                     AV_TIME_BASE_Q);
2664
            if (is_text)
2665 2666 2667
                duration_text = FFMAX(duration_text, duration1);
            else
                duration = FFMAX(duration, duration1);
2668
        }
2669
    }
2670
    if (start_time == INT64_MAX || (start_time > start_time_text && start_time - (uint64_t)start_time_text < AV_TIME_BASE))
2671
        start_time = start_time_text;
2672
    else if (start_time > start_time_text)
2673 2674
        av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);

2675
    if (end_time == INT64_MIN || (end_time < end_time_text && end_time_text - (uint64_t)end_time < AV_TIME_BASE))
2676
        end_time = end_time_text;
2677
    else if (end_time < end_time_text)
2678 2679
        av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream endtime %f\n", end_time_text / (float)AV_TIME_BASE);

2680 2681 2682 2683 2684
     if (duration == INT64_MIN || (duration < duration_text && duration_text - duration < AV_TIME_BASE))
         duration = duration_text;
     else if (duration < duration_text)
         av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream duration %f\n", duration_text / (float)AV_TIME_BASE);

2685
    if (start_time != INT64_MAX) {
2686
        ic->start_time = start_time;
2687
        if (end_time != INT64_MIN) {
2688
            if (ic->nb_programs > 1) {
2689
                for (i = 0; i < ic->nb_programs; i++) {
2690
                    p = ic->programs[i];
2691 2692 2693
                    if (p->start_time != AV_NOPTS_VALUE &&
                        p->end_time > p->start_time &&
                        p->end_time - (uint64_t)p->start_time <= INT64_MAX)
2694 2695
                        duration = FFMAX(duration, p->end_time - p->start_time);
                }
2696
            } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) {
2697
                duration = FFMAX(duration, end_time - start_time);
2698
            }
2699
        }
2700
    }
2701
    if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2702
        ic->duration = duration;
2703
    }
2704
    if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) {
2705 2706 2707
        /* compute the bitrate */
        double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
                         (double) ic->duration;
2708
        if (bitrate >= 0 && bitrate <= INT64_MAX)
2709
            ic->bit_rate = bitrate;
2710 2711 2712 2713 2714 2715 2716 2717
    }
}

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

2718
    update_stream_timings(ic);
2719
    for (i = 0; i < ic->nb_streams; i++) {
2720 2721
        st = ic->streams[i];
        if (st->start_time == AV_NOPTS_VALUE) {
2722 2723 2724 2725 2726 2727
            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);
2728 2729 2730 2731
        }
    }
}

2732
static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2733 2734
{
    int64_t filesize, duration;
2735
    int i, show_warning = 0;
2736 2737 2738
    AVStream *st;

    /* if bit_rate is already set, we believe it */
2739
    if (ic->bit_rate <= 0) {
2740
        int64_t bit_rate = 0;
2741
        for (i = 0; i < ic->nb_streams; i++) {
2742
            st = ic->streams[i];
2743 2744
            if (st->codecpar->bit_rate <= 0 && st->internal->avctx->bit_rate > 0)
                st->codecpar->bit_rate = st->internal->avctx->bit_rate;
2745
            if (st->codecpar->bit_rate > 0) {
2746
                if (INT64_MAX - st->codecpar->bit_rate < bit_rate) {
2747 2748 2749
                    bit_rate = 0;
                    break;
                }
2750
                bit_rate += st->codecpar->bit_rate;
2751
            } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 1) {
2752
                // If we have a videostream with packets but without a bitrate
Michael Niedermayer's avatar
Michael Niedermayer committed
2753
                // then consider the sum not known
2754 2755
                bit_rate = 0;
                break;
2756
            }
2757 2758 2759 2760 2761
        }
        ic->bit_rate = bit_rate;
    }

    /* if duration is already set, we believe it */
2762
    if (ic->duration == AV_NOPTS_VALUE &&
2763 2764
        ic->bit_rate != 0) {
        filesize = ic->pb ? avio_size(ic->pb) : 0;
2765 2766
        if (filesize > ic->internal->data_offset) {
            filesize -= ic->internal->data_offset;
2767
            for (i = 0; i < ic->nb_streams; i++) {
2768
                st      = ic->streams[i];
2769 2770
                if (   st->time_base.num <= INT64_MAX / ic->bit_rate
                    && st->duration == AV_NOPTS_VALUE) {
2771 2772 2773
                    duration = av_rescale(8 * filesize, st->time_base.den,
                                          ic->bit_rate *
                                          (int64_t) st->time_base.num);
2774
                    st->duration = duration;
2775
                    show_warning = 1;
2776
                }
2777 2778 2779
            }
        }
    }
2780
    if (show_warning)
2781 2782
        av_log(ic, AV_LOG_WARNING,
               "Estimating duration from bitrate, this may be inaccurate\n");
2783 2784
}

2785
#define DURATION_MAX_READ_SIZE 250000LL
2786
#define DURATION_MAX_RETRY 6
2787 2788

/* only usable for MPEG-PS streams */
2789
static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2790 2791 2792
{
    AVPacket pkt1, *pkt = &pkt1;
    AVStream *st;
2793
    int num, den, read_size, i, ret;
2794 2795
    int found_duration = 0;
    int is_end;
2796
    int64_t filesize, offset, duration;
2797
    int retry = 0;
2798

2799 2800 2801
    /* flush packet queue */
    flush_packet_queue(ic);

2802
    for (i = 0; i < ic->nb_streams; i++) {
2803
        st = ic->streams[i];
2804 2805
        if (st->start_time == AV_NOPTS_VALUE &&
            st->first_dts == AV_NOPTS_VALUE &&
2806
            st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN)
2807
            av_log(ic, AV_LOG_WARNING,
2808
                   "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2809

2810 2811
        if (st->parser) {
            av_parser_close(st->parser);
2812
            st->parser = NULL;
2813 2814
        }
    }
2815

2816 2817 2818 2819 2820
    if (ic->skip_estimate_duration_from_pts) {
        av_log(ic, AV_LOG_INFO, "Skipping duration calculation in estimate_timings_from_pts\n");
        goto skip_duration_calc;
    }

2821
    av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2822 2823
    /* estimate the end time (duration) */
    /* XXX: may need to support wrapping */
2824
    filesize = ic->pb ? avio_size(ic->pb) : 0;
2825
    do {
2826
        is_end = found_duration;
2827
        offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2828 2829
        if (offset < 0)
            offset = 0;
2830

2831 2832
        avio_seek(ic->pb, offset, SEEK_SET);
        read_size = 0;
2833 2834
        for (;;) {
            if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2835
                break;
2836

2837
            do {
2838
                ret = ff_read_packet(ic, pkt);
2839
            } while (ret == AVERROR(EAGAIN));
2840 2841 2842
            if (ret != 0)
                break;
            read_size += pkt->size;
2843
            st         = ic->streams[pkt->stream_index];
2844 2845 2846
            if (pkt->pts != AV_NOPTS_VALUE &&
                (st->start_time != AV_NOPTS_VALUE ||
                 st->first_dts  != AV_NOPTS_VALUE)) {
2847
                if (pkt->duration == 0) {
2848
                    ff_compute_frame_duration(ic, &num, &den, st, st->parser, pkt);
2849 2850 2851 2852 2853 2854 2855
                    if (den && num) {
                        pkt->duration = av_rescale_rnd(1,
                                           num * (int64_t) st->time_base.den,
                                           den * (int64_t) st->time_base.num,
                                           AV_ROUND_DOWN);
                    }
                }
2856
                duration = pkt->pts + pkt->duration;
2857
                found_duration = 1;
2858 2859 2860 2861 2862
                if (st->start_time != AV_NOPTS_VALUE)
                    duration -= st->start_time;
                else
                    duration -= st->first_dts;
                if (duration > 0) {
2863
                    if (st->duration == AV_NOPTS_VALUE || st->info->last_duration<= 0 ||
2864
                        (st->duration < duration && FFABS(duration - st->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2865
                        st->duration = duration;
2866
                    st->info->last_duration = duration;
2867
                }
2868
            }
2869
            av_packet_unref(pkt);
2870
        }
2871 2872

        /* check if all audio/video streams have valid duration */
2873 2874 2875 2876
        if (!is_end) {
            is_end = 1;
            for (i = 0; i < ic->nb_streams; i++) {
                st = ic->streams[i];
2877
                switch (st->codecpar->codec_type) {
2878 2879 2880 2881 2882
                    case AVMEDIA_TYPE_VIDEO:
                    case AVMEDIA_TYPE_AUDIO:
                        if (st->duration == AV_NOPTS_VALUE)
                            is_end = 0;
                }
2883 2884
            }
        }
2885
    } while (!is_end &&
2886
             offset &&
2887
             ++retry <= DURATION_MAX_RETRY);
2888

2889 2890
    av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);

2891 2892 2893 2894
    /* warn about audio/video streams which duration could not be estimated */
    for (i = 0; i < ic->nb_streams; i++) {
        st = ic->streams[i];
        if (st->duration == AV_NOPTS_VALUE) {
2895
            switch (st->codecpar->codec_type) {
2896 2897 2898 2899 2900 2901 2902 2903 2904
            case AVMEDIA_TYPE_VIDEO:
            case AVMEDIA_TYPE_AUDIO:
                if (st->start_time != AV_NOPTS_VALUE || st->first_dts  != AV_NOPTS_VALUE) {
                    av_log(ic, AV_LOG_DEBUG, "stream %d : no PTS found at end of file, duration not set\n", i);
                } else
                    av_log(ic, AV_LOG_DEBUG, "stream %d : no TS found at start of file, duration not set\n", i);
            }
        }
    }
2905
skip_duration_calc:
2906
    fill_all_stream_timings(ic);
2907

2908
    avio_seek(ic->pb, old_offset, SEEK_SET);
2909
    for (i = 0; i < ic->nb_streams; i++) {
2910 2911
        int j;

2912 2913
        st              = ic->streams[i];
        st->cur_dts     = st->first_dts;
Michael Niedermayer's avatar
Michael Niedermayer committed
2914
        st->last_IP_pts = AV_NOPTS_VALUE;
2915
        st->last_dts_for_order_check = AV_NOPTS_VALUE;
2916 2917
        for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
            st->pts_buffer[j] = AV_NOPTS_VALUE;
2918
    }
2919 2920
}

2921
static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2922 2923 2924 2925 2926 2927 2928
{
    int64_t file_size;

    /* get the file size, if possible */
    if (ic->iformat->flags & AVFMT_NOFILE) {
        file_size = 0;
    } else {
2929
        file_size = avio_size(ic->pb);
2930
        file_size = FFMAX(0, file_size);
2931 2932
    }

2933 2934
    if ((!strcmp(ic->iformat->name, "mpeg") ||
         !strcmp(ic->iformat->name, "mpegts")) &&
2935
        file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
2936
        /* get accurate estimate from the PTSes */
2937
        estimate_timings_from_pts(ic, old_offset);
2938
        ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2939
    } else if (has_duration(ic)) {
2940
        /* at least one component has timings - we use them for all
2941
         * the components */
2942
        fill_all_stream_timings(ic);
2943
        ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2944
    } else {
2945
        /* less precise: use bitrate info */
2946
        estimate_timings_from_bit_rate(ic);
2947
        ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2948
    }
2949
    update_stream_timings(ic);
2950 2951 2952

    {
        int i;
2953
        AVStream av_unused *st;
2954
        for (i = 0; i < ic->nb_streams; i++) {
2955
            st = ic->streams[i];
2956 2957 2958
            av_log(ic, AV_LOG_TRACE, "stream %d: start_time: %0.3f duration: %0.3f\n", i,
                   (double) st->start_time * av_q2d(st->time_base),
                   (double) st->duration   * av_q2d(st->time_base));
2959
        }
2960
        av_log(ic, AV_LOG_TRACE,
2961
                "format: start_time: %0.3f duration: %0.3f bitrate=%"PRId64" kb/s\n",
2962 2963
                (double) ic->start_time / AV_TIME_BASE,
                (double) ic->duration   / AV_TIME_BASE,
2964
                (int64_t)ic->bit_rate / 1000);
2965 2966 2967
    }
}

2968
static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
2969
{
2970
    AVCodecContext *avctx = st->internal->avctx;
2971 2972 2973 2974 2975 2976 2977

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

2978 2979 2980
    if (   avctx->codec_id == AV_CODEC_ID_NONE
        && avctx->codec_type != AVMEDIA_TYPE_DATA)
        FAIL("unknown codec");
2981
    switch (avctx->codec_type) {
2982
    case AVMEDIA_TYPE_AUDIO:
2983
        if (!avctx->frame_size && determinable_frame_size(avctx))
2984
            FAIL("unspecified frame size");
2985 2986
        if (st->info->found_decoder >= 0 &&
            avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2987 2988 2989 2990 2991
            FAIL("unspecified sample format");
        if (!avctx->sample_rate)
            FAIL("unspecified sample rate");
        if (!avctx->channels)
            FAIL("unspecified number of channels");
2992 2993
        if (st->info->found_decoder >= 0 && !st->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
            FAIL("no decodable DTS frames");
2994
        break;
2995
    case AVMEDIA_TYPE_VIDEO:
2996 2997
        if (!avctx->width)
            FAIL("unspecified size");
2998
        if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2999
            FAIL("unspecified pixel format");
3000 3001
        if (st->codecpar->codec_id == AV_CODEC_ID_RV30 || st->codecpar->codec_id == AV_CODEC_ID_RV40)
            if (!st->sample_aspect_ratio.num && !st->codecpar->sample_aspect_ratio.num && !st->codec_info_nb_frames)
3002
                FAIL("no frame in rv30/40 and no sar");
3003
        break;
3004 3005 3006 3007
    case AVMEDIA_TYPE_SUBTITLE:
        if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
            FAIL("unspecified size");
        break;
3008
    case AVMEDIA_TYPE_DATA:
3009
        if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
3010
    }
3011 3012

    return 1;
3013 3014
}

3015
/* returns 1 or 0 if or if not decoded data was returned, or a negative error */
3016
static int try_decode_frame(AVFormatContext *s, AVStream *st, AVPacket *avpkt,
3017
                            AVDictionary **options)
3018
{
3019
    AVCodecContext *avctx = st->internal->avctx;
3020
    const AVCodec *codec;
3021
    int got_picture = 1, ret = 0;
3022
    AVFrame *frame = av_frame_alloc();
3023
    AVSubtitle subtitle;
3024
    AVPacket pkt = *avpkt;
3025 3026
    int do_skip_frame = 0;
    enum AVDiscard skip_frame;
3027

3028 3029 3030
    if (!frame)
        return AVERROR(ENOMEM);

3031
    if (!avcodec_is_open(avctx) &&
3032
        st->info->found_decoder <= 0 &&
3033
        (st->codecpar->codec_id != -st->info->found_decoder || !st->codecpar->codec_id)) {
3034 3035
        AVDictionary *thread_opt = NULL;

3036
        codec = find_probe_decoder(s, st, st->codecpar->codec_id);
3037

3038
        if (!codec) {
3039
            st->info->found_decoder = -st->codecpar->codec_id;
3040
            ret                     = -1;
3041
            goto fail;
3042
        }
3043

3044 3045
        /* Force thread count to 1 since the H.264 decoder will not extract
         * SPS and PPS to extradata during multi-threaded decoding. */
3046
        av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
3047 3048
        if (s->codec_whitelist)
            av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
3049
        ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
3050 3051
        if (!options)
            av_dict_free(&thread_opt);
3052
        if (ret < 0) {
3053
            st->info->found_decoder = -avctx->codec_id;
3054
            goto fail;
3055 3056 3057 3058 3059
        }
        st->info->found_decoder = 1;
    } else if (!st->info->found_decoder)
        st->info->found_decoder = 1;

3060 3061 3062 3063
    if (st->info->found_decoder < 0) {
        ret = -1;
        goto fail;
    }
3064

3065
    if (avpriv_codec_get_cap_skip_frame_fill_param(avctx->codec)) {
3066
        do_skip_frame = 1;
3067 3068
        skip_frame = avctx->skip_frame;
        avctx->skip_frame = AVDISCARD_ALL;
3069 3070
    }

3071 3072
    while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
           ret >= 0 &&
3073
           (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
3074
            (!st->codec_info_nb_frames &&
3075
             (avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
3076
        got_picture = 0;
wm4's avatar
wm4 committed
3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
            avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
            ret = avcodec_send_packet(avctx, &pkt);
            if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
                break;
            if (ret >= 0)
                pkt.size = 0;
            ret = avcodec_receive_frame(avctx, frame);
            if (ret >= 0)
                got_picture = 1;
            if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                ret = 0;
        } else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3090
            ret = avcodec_decode_subtitle2(avctx, &subtitle,
3091
                                           &got_picture, &pkt);
wm4's avatar
wm4 committed
3092 3093
            if (ret >= 0)
                pkt.size = 0;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
3094
        }
3095 3096
        if (ret >= 0) {
            if (got_picture)
3097
                st->nb_decoded_frames++;
3098
            ret       = got_picture;
3099
        }
3100
    }
3101

3102
    if (!pkt.data && !got_picture)
3103 3104
        ret = -1;

3105
fail:
3106
    if (do_skip_frame) {
3107
        avctx->skip_frame = skip_frame;
3108 3109
    }

3110
    av_frame_free(&frame);
3111 3112 3113
    return ret;
}

3114
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
3115
{
3116
    while (tags->id != AV_CODEC_ID_NONE) {
3117 3118 3119 3120 3121 3122 3123
        if (tags->id == id)
            return tags->tag;
        tags++;
    }
    return 0;
}

3124
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
3125
{
3126
    int i;
3127 3128
    for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
        if (tag == tags[i].tag)
3129
            return tags[i].id;
3130
    for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3131
        if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
3132
            return tags[i].id;
3133
    return AV_CODEC_ID_NONE;
3134 3135
}

3136 3137
enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
{
3138
    if (bps <= 0 || bps > 64)
3139 3140
        return AV_CODEC_ID_NONE;

3141 3142
    if (flt) {
        switch (bps) {
3143 3144 3145 3146 3147 3148
        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;
3149 3150
        }
    } else {
3151
        bps  += 7;
3152 3153 3154
        bps >>= 3;
        if (sflags & (1 << (bps - 1))) {
            switch (bps) {
3155 3156 3157 3158 3159 3160 3161 3162
            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;
3163 3164
            case 8:
                return be ? AV_CODEC_ID_PCM_S64BE : AV_CODEC_ID_PCM_S64LE;
3165 3166
            default:
                return AV_CODEC_ID_NONE;
3167 3168 3169
            }
        } else {
            switch (bps) {
3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
            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;
3180 3181 3182 3183 3184
            }
        }
    }
}

3185
unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
3186 3187 3188 3189 3190 3191 3192 3193 3194
{
    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)
3195 3196
{
    int i;
3197
    for (i = 0; tags && tags[i]; i++) {
3198 3199 3200 3201 3202 3203 3204 3205
        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++;
        }
3206 3207 3208 3209
    }
    return 0;
}

3210
enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
3211 3212
{
    int i;
3213 3214 3215 3216
    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;
3217
    }
3218
    return AV_CODEC_ID_NONE;
3219 3220
}

3221 3222
static void compute_chapters_end(AVFormatContext *s)
{
3223
    unsigned int i, j;
3224 3225
    int64_t max_time = 0;

3226
    if (s->duration > 0 && s->start_time < INT64_MAX - s->duration)
3227
        max_time = s->duration +
3228
                       ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
3229

3230
    for (i = 0; i < s->nb_chapters; i++)
3231
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
3232
            AVChapter *ch = s->chapters[i];
3233 3234 3235
            int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
                                                  ch->time_base)
                                   : INT64_MAX;
3236 3237

            for (j = 0; j < s->nb_chapters; j++) {
3238 3239 3240
                AVChapter *ch1     = s->chapters[j];
                int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
                                                  ch->time_base);
3241 3242 3243
                if (j != i && next_start > ch->start && next_start < end)
                    end = next_start;
            }
3244
            ch->end = (end == INT64_MAX || end < ch->start) ? ch->start : end;
3245 3246 3247
        }
}

3248 3249
static int get_std_framerate(int i)
{
3250
    if (i < 30*12)
3251
        return (i + 1) * 1001;
3252 3253
    i -= 30*12;

3254 3255 3256
    if (i < 30)
        return (i + 31) * 1001 * 12;
    i -= 30;
3257

3258 3259 3260 3261
    if (i < 3)
        return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;

    i -= 3;
3262 3263

    return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
3264 3265
}

3266
/* Is the time base unreliable?
3267 3268
 * This is a heuristic to balance between quick acceptance of the values in
 * the headers vs. some extra checks.
3269 3270
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
3271 3272 3273
 * And there are "variable" fps files this needs to detect as well. */
static int tb_unreliable(AVCodecContext *c)
{
3274 3275
    if (c->time_base.den >= 101LL * c->time_base.num ||
        c->time_base.den <    5LL * c->time_base.num ||
3276 3277
        // c->codec_tag == AV_RL32("DIVX") ||
        // c->codec_tag == AV_RL32("XVID") ||
3278
        c->codec_tag == AV_RL32("mp4v") ||
3279
        c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
3280
        c->codec_id == AV_CODEC_ID_GIF ||
3281
        c->codec_id == AV_CODEC_ID_HEVC ||
3282
        c->codec_id == AV_CODEC_ID_H264)
3283 3284 3285 3286
        return 1;
    return 0;
}

3287
int ff_alloc_extradata(AVCodecParameters *par, int size)
3288
{
3289
    av_freep(&par->extradata);
3290 3291 3292
    par->extradata_size = 0;

    if (size < 0 || size >= INT32_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
3293
        return AVERROR(EINVAL);
3294

3295
    par->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
3296 3297 3298 3299 3300 3301 3302
    if (!par->extradata)
        return AVERROR(ENOMEM);

    memset(par->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
    par->extradata_size = size;

    return 0;
3303 3304
}

3305
int ff_get_extradata(AVFormatContext *s, AVCodecParameters *par, AVIOContext *pb, int size)
3306
{
3307
    int ret = ff_alloc_extradata(par, size);
3308 3309
    if (ret < 0)
        return ret;
3310
    ret = avio_read(pb, par->extradata, size);
3311
    if (ret != size) {
3312 3313
        av_freep(&par->extradata);
        par->extradata_size = 0;
3314
        av_log(s, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
3315 3316 3317 3318 3319 3320
        return ret < 0 ? ret : AVERROR_INVALIDDATA;
    }

    return ret;
}

3321 3322 3323 3324 3325
int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
{
    int i, j;
    int64_t last = st->info->last_dts;

3326 3327 3328 3329
    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;
3330 3331 3332 3333 3334 3335

        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);

3336
//         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3337
//             av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
3338
        for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3339
            if (st->info->duration_error[0][1][i] < 1e10) {
3340 3341 3342 3343
                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);
3344 3345 3346 3347
                    double error= sdts - ticks + j*0.5;
                    st->info->duration_error[j][0][i] += error;
                    st->info->duration_error[j][1][i] += error*error;
                }
3348 3349 3350
            }
        }
        st->info->duration_count++;
3351
        st->info->rfps_duration_sum += duration;
3352 3353 3354

        if (st->info->duration_count % 10 == 0) {
            int n = st->info->duration_count;
3355
            for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368
                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;
                    }
                }
            }
        }

3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382
        // 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;

3383
    for (i = 0; i < ic->nb_streams; i++) {
3384 3385
        AVStream *st = ic->streams[i];

3386
        if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
3387 3388
            continue;
        // the check for tb_unreliable() is not completely correct, since this is not about handling
Lou Logan's avatar
Lou Logan committed
3389
        // an unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3390
        // ipmovie.c produces.
3391
        if (tb_unreliable(st->internal->avctx) && 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)
3392 3393
            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
3394
            && tb_unreliable(st->internal->avctx)) {
3395 3396
            int num = 0;
            double best_error= 0.01;
3397
            AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3398

3399
            for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3400 3401
                int k;

3402 3403
                if (st->info->codec_info_duration &&
                    st->info->codec_info_duration*av_q2d(st->time_base) < (1001*11.5)/get_std_framerate(j))
3404
                    continue;
3405
                if (!st->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3406
                    continue;
3407 3408 3409 3410

                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;

3411 3412
                for (k= 0; k<2; k++) {
                    int n = st->info->duration_count;
3413 3414 3415
                    double a= st->info->duration_error[k][0][j] / n;
                    double error= st->info->duration_error[k][1][j]/n - a*a;

3416
                    if (error < best_error && best_error> 0.000000001) {
3417 3418 3419
                        best_error= error;
                        num = get_std_framerate(j);
                    }
3420
                    if (error < 0.02)
3421
                        av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3422 3423 3424
                }
            }
            // do not increase frame rate by more than 1 % in order to match a standard rate.
3425
            if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3426 3427
                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
        }
3428 3429 3430 3431 3432 3433 3434 3435 3436
        if (   !st->avg_frame_rate.num
            && st->r_frame_rate.num && st->info->rfps_duration_sum
            && st->info->codec_info_duration <= 0
            && st->info->duration_count > 2
            && fabs(1.0 / (av_q2d(st->r_frame_rate) * av_q2d(st->time_base)) - st->info->rfps_duration_sum / (double)st->info->duration_count) <= 1.0
            ) {
            av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
            st->avg_frame_rate = st->r_frame_rate;
        }
3437 3438 3439 3440

        av_freep(&st->info->duration_error);
        st->info->last_dts = AV_NOPTS_VALUE;
        st->info->duration_count = 0;
3441
        st->info->rfps_duration_sum = 0;
3442 3443 3444
    }
}

3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
static int extract_extradata_check(AVStream *st)
{
    const AVBitStreamFilter *f;

    f = av_bsf_get_by_name("extract_extradata");
    if (!f)
        return 0;

    if (f->codec_ids) {
        const enum AVCodecID *ids;
        for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
            if (*ids == st->codecpar->codec_id)
                return 1;
    }

    return 0;
}

static int extract_extradata_init(AVStream *st)
{
3465
    AVStreamInternal *sti = st->internal;
3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
    const AVBitStreamFilter *f;
    int ret;

    f = av_bsf_get_by_name("extract_extradata");
    if (!f)
        goto finish;

    /* check that the codec id is supported */
    ret = extract_extradata_check(st);
    if (!ret)
        goto finish;

3478 3479
    sti->extract_extradata.pkt = av_packet_alloc();
    if (!sti->extract_extradata.pkt)
3480 3481
        return AVERROR(ENOMEM);

3482
    ret = av_bsf_alloc(f, &sti->extract_extradata.bsf);
3483 3484 3485
    if (ret < 0)
        goto fail;

3486
    ret = avcodec_parameters_copy(sti->extract_extradata.bsf->par_in,
3487 3488 3489 3490
                                  st->codecpar);
    if (ret < 0)
        goto fail;

3491
    sti->extract_extradata.bsf->time_base_in = st->time_base;
3492

3493
    ret = av_bsf_init(sti->extract_extradata.bsf);
3494 3495
    if (ret < 0)
        goto fail;
3496 3497

finish:
3498
    sti->extract_extradata.inited = 1;
3499 3500 3501

    return 0;
fail:
3502 3503
    av_bsf_free(&sti->extract_extradata.bsf);
    av_packet_free(&sti->extract_extradata.pkt);
3504 3505 3506 3507 3508
    return ret;
}

static int extract_extradata(AVStream *st, AVPacket *pkt)
{
3509
    AVStreamInternal *sti = st->internal;
3510 3511 3512
    AVPacket *pkt_ref;
    int ret;

3513
    if (!sti->extract_extradata.inited) {
3514 3515 3516 3517 3518
        ret = extract_extradata_init(st);
        if (ret < 0)
            return ret;
    }

3519
    if (sti->extract_extradata.inited && !sti->extract_extradata.bsf)
3520 3521
        return 0;

3522
    pkt_ref = sti->extract_extradata.pkt;
3523 3524 3525 3526
    ret = av_packet_ref(pkt_ref, pkt);
    if (ret < 0)
        return ret;

3527
    ret = av_bsf_send_packet(sti->extract_extradata.bsf, pkt_ref);
3528 3529 3530 3531 3532
    if (ret < 0) {
        av_packet_unref(pkt_ref);
        return ret;
    }

3533
    while (ret >= 0 && !sti->avctx->extradata) {
3534 3535 3536
        int extradata_size;
        uint8_t *extradata;

3537
        ret = av_bsf_receive_packet(sti->extract_extradata.bsf, pkt_ref);
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
        if (ret < 0) {
            if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
                return ret;
            continue;
        }

        extradata = av_packet_get_side_data(pkt_ref, AV_PKT_DATA_NEW_EXTRADATA,
                                            &extradata_size);

        if (extradata) {
3548 3549 3550
            av_assert0(!sti->avctx->extradata);
            if ((unsigned)extradata_size < FF_MAX_EXTRADATA_SIZE)
                sti->avctx->extradata = av_mallocz(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
3551
            if (!sti->avctx->extradata) {
3552 3553 3554
                av_packet_unref(pkt_ref);
                return AVERROR(ENOMEM);
            }
3555 3556
            memcpy(sti->avctx->extradata, extradata, extradata_size);
            sti->avctx->extradata_size = extradata_size;
3557 3558 3559 3560 3561 3562 3563
        }
        av_packet_unref(pkt_ref);
    }

    return 0;
}

3564
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3565
{
3566
    int i, count = 0, ret = 0, j;
3567
    int64_t read_size;
3568
    AVStream *st;
3569
    AVCodecContext *avctx;
3570
    AVPacket pkt1, *pkt;
3571 3572 3573
    int64_t old_offset  = avio_tell(ic->pb);
    // new streams might appear, no options for those
    int orig_nb_streams = ic->nb_streams;
3574
    int flush_codecs;
3575
    int64_t max_analyze_duration = ic->max_analyze_duration;
3576
    int64_t max_stream_analyze_duration;
3577
    int64_t max_subtitle_analyze_duration;
3578
    int64_t probesize = ic->probesize;
3579
    int eof_reached = 0;
3580
    int *missing_streams = av_opt_ptr(ic->iformat->priv_class, ic->priv_data, "missing_streams");
3581 3582

    flush_codecs = probesize > 0;
3583

3584 3585
    av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);

3586
    max_stream_analyze_duration = max_analyze_duration;
3587
    max_subtitle_analyze_duration = max_analyze_duration;
3588
    if (!max_analyze_duration) {
3589 3590
        max_stream_analyze_duration =
        max_analyze_duration        = 5*AV_TIME_BASE;
3591
        max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3592
        if (!strcmp(ic->iformat->name, "flv"))
3593
            max_stream_analyze_duration = 90*AV_TIME_BASE;
3594 3595
        if (!strcmp(ic->iformat->name, "mpeg") || !strcmp(ic->iformat->name, "mpegts"))
            max_stream_analyze_duration = 7*AV_TIME_BASE;
3596
    }
3597

3598
    if (ic->pb)
3599 3600
        av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
               avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, ic->nb_streams);
3601

3602
    for (i = 0; i < ic->nb_streams; i++) {
3603
        const AVCodec *codec;
3604
        AVDictionary *thread_opt = NULL;
3605
        st = ic->streams[i];
3606
        avctx = st->internal->avctx;
3607

3608 3609
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
            st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3610 3611
/*            if (!st->time_base.num)
                st->time_base = */
3612 3613
            if (!avctx->time_base.num)
                avctx->time_base = st->time_base;
3614
        }
3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625

        /* check if the caller has overridden the codec id */
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
        if (st->codec->codec_id != st->internal->orig_codec_id) {
            st->codecpar->codec_id   = st->codec->codec_id;
            st->codecpar->codec_type = st->codec->codec_type;
            st->internal->orig_codec_id = st->codec->codec_id;
        }
FF_ENABLE_DEPRECATION_WARNINGS
#endif
3626
        // only for the split stuff
3627
        if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && st->request_probe <= 0) {
3628
            st->parser = av_parser_init(st->codecpar->codec_id);
3629 3630
            if (st->parser) {
                if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3631
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3632
                } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3633 3634
                    st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
                }
3635 3636 3637
            } else if (st->need_parsing) {
                av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
                       "%s, packets or times may be invalid.\n",
3638
                       avcodec_get_name(st->codecpar->codec_id));
3639
            }
3640
        }
3641 3642 3643 3644 3645 3646 3647

        if (st->codecpar->codec_id != st->internal->orig_codec_id)
            st->internal->orig_codec_id = st->codecpar->codec_id;

        ret = avcodec_parameters_to_context(avctx, st->codecpar);
        if (ret < 0)
            goto find_stream_info_err;
3648
        if (st->request_probe <= 0)
3649 3650
            st->internal->avctx_inited = 1;

3651
        codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3652

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

3657 3658 3659
        if (ic->codec_whitelist)
            av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);

3660
        /* Ensure that subtitle_header is properly set. */
3661
        if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE
3662 3663
            && codec && !avctx->codec) {
            if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3664
                av_log(ic, AV_LOG_WARNING,
3665
                       "Failed to open codec in %s\n",__FUNCTION__);
3666
        }
3667

3668
        // Try to just open decoders, in case this is enough to get parameters.
3669
        if (!has_codec_parameters(st, NULL) && st->request_probe <= 0) {
3670
            if (codec && !avctx->codec)
3671
                if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3672
                    av_log(ic, AV_LOG_WARNING,
3673
                           "Failed to open codec in %s\n",__FUNCTION__);
3674
        }
3675 3676
        if (!options)
            av_dict_free(&thread_opt);
3677 3678
    }

3679
    for (i = 0; i < ic->nb_streams; i++) {
3680
#if FF_API_R_FRAME_RATE
3681
        ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
3682
#endif
3683 3684
        ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
        ic->streams[i]->info->fps_last_dts  = AV_NOPTS_VALUE;
3685
    }
3686

3687
    read_size = 0;
3688
    for (;;) {
3689
        int analyzed_all_streams;
3690 3691
        if (ff_check_interrupt(&ic->interrupt_callback)) {
            ret = AVERROR_EXIT;
3692
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3693 3694 3695
            break;
        }

3696
        /* check if one codec still needs to be handled */
3697
        for (i = 0; i < ic->nb_streams; i++) {
3698
            int fps_analyze_framecount = 20;
3699
            int count;
3700

3701
            st = ic->streams[i];
3702
            if (!has_codec_parameters(st, NULL))
3703
                break;
3704 3705 3706
            /* 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. */
3707 3708
            if (av_q2d(st->time_base) > 0.0005)
                fps_analyze_framecount *= 2;
3709
            if (!tb_unreliable(st->internal->avctx))
3710
                fps_analyze_framecount = 0;
3711 3712
            if (ic->fps_probe_size >= 0)
                fps_analyze_framecount = ic->fps_probe_size;
3713 3714
            if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
                fps_analyze_framecount = 0;
3715
            /* variable fps and no guess at the real fps */
3716 3717 3718
            count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
                       st->info->codec_info_duration_fields/2 :
                       st->info->duration_count;
3719
            if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3720
                st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3721 3722 3723
                if (count < fps_analyze_framecount)
                    break;
            }
3724 3725 3726 3727
            // Look at the first 3 frames if there is evidence of frame delay
            // but the decoder delay is not set.
            if (st->info->frame_delay_evidence && count < 2 && st->internal->avctx->has_b_frames == 0)
                break;
3728 3729 3730 3731
            if (!st->internal->avctx->extradata &&
                (!st->internal->extract_extradata.inited ||
                 st->internal->extract_extradata.bsf) &&
                extract_extradata_check(st))
3732
                break;
3733
            if (st->first_dts == AV_NOPTS_VALUE &&
3734
                !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3735
                st->codec_info_nb_frames < ((st->disposition & AV_DISPOSITION_ATTACHED_PIC) ? 1 : ic->max_ts_probe) &&
3736 3737
                (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
                 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
3738
                break;
3739
        }
3740
        analyzed_all_streams = 0;
3741
        if (!missing_streams || !*missing_streams)
3742
        if (i == ic->nb_streams) {
3743
            analyzed_all_streams = 1;
3744 3745
            /* 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. */
3746
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3747
                /* If we found the info for all the codecs, we can stop. */
3748
                ret = count;
3749
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
3750
                flush_codecs = 0;
3751 3752
                break;
            }
3753
        }
3754
        /* We did not get all the codec info, but we read too much data. */
3755
        if (read_size >= probesize) {
Michael Niedermayer's avatar
Michael Niedermayer committed
3756
            ret = count;
3757
            av_log(ic, AV_LOG_DEBUG,
3758
                   "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3759 3760
            for (i = 0; i < ic->nb_streams; i++)
                if (!ic->streams[i]->r_frame_rate.num &&
3761
                    ic->streams[i]->info->duration_count <= 1 &&
3762
                    ic->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
3763
                    strcmp(ic->iformat->name, "image2"))
3764 3765 3766
                    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
3767 3768
            break;
        }
3769

3770 3771
        /* NOTE: A new stream can be added there if no header in file
         * (AVFMTCTX_NOHEADER). */
3772
        ret = read_frame_internal(ic, &pkt1);
3773 3774 3775 3776
        if (ret == AVERROR(EAGAIN))
            continue;

        if (ret < 0) {
3777
            /* EOF or error*/
3778
            eof_reached = 1;
3779 3780 3781
            break;
        }

3782 3783 3784
        pkt = &pkt1;

        if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
3785 3786 3787
            ret = ff_packet_list_put(&ic->internal->packet_buffer,
                                     &ic->internal->packet_buffer_end,
                                     pkt, 0);
3788
            if (ret < 0)
3789 3790
                goto find_stream_info_err;
        }
3791 3792

        st = ic->streams[pkt->stream_index];
3793 3794 3795
        if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
            read_size += pkt->size;

3796 3797 3798 3799 3800 3801 3802 3803
        avctx = st->internal->avctx;
        if (!st->internal->avctx_inited) {
            ret = avcodec_parameters_to_context(avctx, st->codecpar);
            if (ret < 0)
                goto find_stream_info_err;
            st->internal->avctx_inited = 1;
        }

3804 3805 3806 3807
        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) {
3808
                av_log(ic, AV_LOG_DEBUG,
3809 3810 3811 3812 3813 3814 3815
                       "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;
3816
            }
3817 3818 3819
            /* 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. */
3820 3821
            if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
                st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
3822
                (pkt->dts - (uint64_t)st->info->fps_last_dts) / 1000 >
3823
                (st->info->fps_last_dts     - (uint64_t)st->info->fps_first_dts) /
3824 3825 3826 3827 3828 3829 3830 3831 3832
                (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;
3833
            }
3834 3835 3836 3837 3838 3839

            /* 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;
            }
3840
            st->info->fps_last_dts     = pkt->dts;
3841
            st->info->fps_last_dts_idx = st->codec_info_nb_frames;
3842
        }
3843
        if (st->codec_info_nb_frames>1) {
3844
            int64_t t = 0;
3845
            int64_t limit;
3846

3847 3848 3849
            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)
3850
                t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3851

3852
            if (   t == 0
3853
                && st->codec_info_nb_frames>30
3854 3855 3856 3857
                && 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));

3858
            if (analyzed_all_streams)                                limit = max_analyze_duration;
3859
            else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3860 3861 3862
            else                                                     limit = max_stream_analyze_duration;

            if (t >= limit) {
3863
                av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3864
                       limit,
3865
                       t, pkt->stream_index);
3866 3867
                if (ic->flags & AVFMT_FLAG_NOBUFFER)
                    av_packet_unref(pkt);
3868
                break;
3869
            }
3870
            if (pkt->duration) {
3871
                if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE && pkt->pts != AV_NOPTS_VALUE && st->start_time != AV_NOPTS_VALUE && pkt->pts >= st->start_time) {
3872 3873 3874
                    st->info->codec_info_duration = FFMIN(pkt->pts - st->start_time, st->info->codec_info_duration + pkt->duration);
                } else
                    st->info->codec_info_duration += pkt->duration;
3875
                st->info->codec_info_duration_fields += st->parser && st->need_parsing && avctx->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3876
            }
3877
        }
3878
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3879
#if FF_API_R_FRAME_RATE
3880
            ff_rfps_add_frame(ic, st, pkt->dts);
3881
#endif
3882 3883 3884
            if (pkt->dts != pkt->pts && pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
                st->info->frame_delay_evidence = 1;
        }
3885 3886 3887 3888
        if (!st->internal->avctx->extradata) {
            ret = extract_extradata(st, pkt);
            if (ret < 0)
                goto find_stream_info_err;
3889
        }
3890

3891 3892 3893 3894 3895
        /* 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.
         *
3896
         * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3897 3898 3899
         * 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. */
3900
        try_decode_frame(ic, st, pkt,
3901
                         (options && i < orig_nb_streams) ? &options[i] : NULL);
3902

3903 3904 3905
        if (ic->flags & AVFMT_FLAG_NOBUFFER)
            av_packet_unref(pkt);

3906
        st->codec_info_nb_frames++;
3907 3908 3909
        count++;
    }

3910
    if (eof_reached) {
3911 3912
        int stream_index;
        for (stream_index = 0; stream_index < ic->nb_streams; stream_index++) {
3913
            st = ic->streams[stream_index];
3914 3915
            avctx = st->internal->avctx;
            if (!has_codec_parameters(st, NULL)) {
3916
                const AVCodec *codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3917
                if (codec && !avctx->codec) {
3918 3919 3920 3921
                    AVDictionary *opts = NULL;
                    if (ic->codec_whitelist)
                        av_dict_set(&opts, "codec_whitelist", ic->codec_whitelist, 0);
                    if (avcodec_open2(avctx, codec, (options && stream_index < orig_nb_streams) ? &options[stream_index] : &opts) < 0)
3922
                        av_log(ic, AV_LOG_WARNING,
3923
                               "Failed to open codec in %s\n",__FUNCTION__);
3924
                    av_dict_free(&opts);
3925 3926
                }
            }
3927

3928 3929
            // EOF already reached while reading the stream above.
            // So continue with reoordering DTS with whatever delay we have.
3930
            if (ic->internal->packet_buffer && !has_decode_delay_been_guessed(st)) {
3931 3932 3933 3934 3935
                update_dts_from_pts(ic, stream_index, ic->internal->packet_buffer);
            }
        }
    }

3936 3937
    if (flush_codecs) {
        AVPacket empty_pkt = { 0 };
3938
        int err = 0;
3939 3940
        av_init_packet(&empty_pkt);

3941
        for (i = 0; i < ic->nb_streams; i++) {
3942

3943 3944 3945
            st = ic->streams[i];

            /* flush the decoders */
3946 3947
            if (st->info->found_decoder == 1) {
                do {
3948
                    err = try_decode_frame(ic, st, &empty_pkt,
3949 3950
                                            (options && i < orig_nb_streams)
                                            ? &options[i] : NULL);
3951
                } while (err > 0 && !has_codec_parameters(st, NULL));
3952 3953 3954 3955 3956

                if (err < 0) {
                    av_log(ic, AV_LOG_INFO,
                        "decoding for stream %d failed\n", st->index);
                }
3957
            }
3958 3959 3960
        }
    }

3961 3962
    ff_rfps_calculate(ic);

3963
    for (i = 0; i < ic->nb_streams; i++) {
3964
        st = ic->streams[i];
3965 3966
        avctx = st->internal->avctx;
        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3967 3968 3969 3970
            if (avctx->codec_id == AV_CODEC_ID_RAWVIDEO && !avctx->codec_tag && !avctx->bits_per_coded_sample) {
                uint32_t tag= avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
                if (avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), tag) == avctx->pix_fmt)
                    avctx->codec_tag= tag;
3971
            }
3972

3973
            /* estimate average framerate if not set by demuxer */
3974 3975 3976
            if (st->info->codec_info_duration_fields &&
                !st->avg_frame_rate.num &&
                st->info->codec_info_duration) {
3977
                int best_fps      = 0;
3978
                double best_error = 0.01;
3979
                AVRational codec_frame_rate = avctx->framerate;
3980

3981
                if (st->info->codec_info_duration        >= INT64_MAX / st->time_base.num / 2||
3982 3983
                    st->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
                    st->info->codec_info_duration        < 0)
3984
                    continue;
3985
                av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3986 3987
                          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);
3988

3989 3990
                /* Round guessed framerate to a "standard" framerate if it's
                 * within 1% of the original estimate. */
3991
                for (j = 0; j < MAX_STD_TIMEBASES; j++) {
3992 3993 3994
                    AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
                    double error       = fabs(av_q2d(st->avg_frame_rate) /
                                              av_q2d(std_fps) - 1);
3995 3996 3997 3998 3999

                    if (error < best_error) {
                        best_error = error;
                        best_fps   = std_fps.num;
                    }
4000 4001 4002 4003 4004 4005 4006 4007 4008

                    if (ic->internal->prefer_codec_framerate && codec_frame_rate.num > 0 && codec_frame_rate.den > 0) {
                        error       = fabs(av_q2d(codec_frame_rate) /
                                           av_q2d(std_fps) - 1);
                        if (error < best_error) {
                            best_error = error;
                            best_fps   = std_fps.num;
                        }
                    }
4009
                }
4010
                if (best_fps)
4011
                    av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4012
                              best_fps, 12 * 1001, INT_MAX);
4013
            }
4014

4015
            if (!st->r_frame_rate.num) {
4016 4017
                if (    avctx->time_base.den * (int64_t) st->time_base.num
                    <= avctx->time_base.num * avctx->ticks_per_frame * (int64_t) st->time_base.den) {
4018 4019
                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
                              avctx->time_base.den, (int64_t)avctx->time_base.num * avctx->ticks_per_frame, INT_MAX);
4020
                } else {
4021 4022 4023
                    st->r_frame_rate.num = st->time_base.den;
                    st->r_frame_rate.den = st->time_base.num;
                }
4024
            }
4025
            if (st->display_aspect_ratio.num && st->display_aspect_ratio.den) {
4026
                AVRational hw_ratio = { avctx->height, avctx->width };
4027 4028 4029
                st->sample_aspect_ratio = av_mul_q(st->display_aspect_ratio,
                                                   hw_ratio);
            }
4030 4031 4032 4033
        } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
            if (!avctx->bits_per_coded_sample)
                avctx->bits_per_coded_sample =
                    av_get_bits_per_sample(avctx->codec_id);
4034
            // set stream disposition based on audio service type
4035
            switch (avctx->audio_service_type) {
4036
            case AV_AUDIO_SERVICE_TYPE_EFFECTS:
4037 4038
                st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
                break;
4039
            case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
4040 4041
                st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
                break;
4042
            case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
4043 4044
                st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
                break;
4045
            case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
4046 4047
                st->disposition = AV_DISPOSITION_COMMENT;
                break;
4048
            case AV_AUDIO_SERVICE_TYPE_KARAOKE:
4049 4050
                st->disposition = AV_DISPOSITION_KARAOKE;
                break;
4051
            }
4052
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
4053
    }
4054

4055 4056 4057
    if (probesize)
        estimate_timings(ic, old_offset);

4058 4059
    av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);

4060
    if (ret >= 0 && ic->nb_streams)
4061 4062 4063
        /* We could not have all the codec parameters before EOF. */
        ret = -1;
    for (i = 0; i < ic->nb_streams; i++) {
4064 4065
        const char *errmsg;
        st = ic->streams[i];
4066 4067 4068

        /* if no packet was ever seen, update context now for has_codec_parameters */
        if (!st->internal->avctx_inited) {
4069 4070 4071
            if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
                st->codecpar->format == AV_SAMPLE_FMT_NONE)
                st->codecpar->format = st->internal->avctx->sample_fmt;
4072 4073 4074 4075
            ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
            if (ret < 0)
                goto find_stream_info_err;
        }
4076 4077
        if (!has_codec_parameters(st, &errmsg)) {
            char buf[256];
4078
            avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
4079 4080 4081 4082 4083 4084 4085 4086 4087
            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;
        }
    }

4088 4089
    compute_chapters_end(ic);

4090 4091 4092 4093
    /* update the stream parameters from the internal codec contexts */
    for (i = 0; i < ic->nb_streams; i++) {
        st = ic->streams[i];

4094 4095 4096 4097 4098 4099
        if (st->internal->avctx_inited) {
            int orig_w = st->codecpar->width;
            int orig_h = st->codecpar->height;
            ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
            if (ret < 0)
                goto find_stream_info_err;
4100
#if FF_API_LOWRES
4101
            // The decoder might reduce the video size by the lowres factor.
4102
            if (st->internal->avctx->lowres && orig_w) {
4103 4104 4105
                st->codecpar->width = orig_w;
                st->codecpar->height = orig_h;
            }
4106
#endif
4107
        }
4108 4109 4110 4111 4112 4113 4114

#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
        ret = avcodec_parameters_to_context(st->codec, st->codecpar);
        if (ret < 0)
            goto find_stream_info_err;

4115
#if FF_API_LOWRES
4116 4117
        // The old API (AVStream.codec) "requires" the resolution to be adjusted
        // by the lowres factor.
4118 4119
        if (st->internal->avctx->lowres && st->internal->avctx->width) {
            st->codec->lowres = st->internal->avctx->lowres;
4120 4121 4122
            st->codec->width = st->internal->avctx->width;
            st->codec->height = st->internal->avctx->height;
        }
4123
#endif
4124

4125
        if (st->codec->codec_tag != MKTAG('t','m','c','d')) {
4126
            st->codec->time_base = st->internal->avctx->time_base;
4127 4128
            st->codec->ticks_per_frame = st->internal->avctx->ticks_per_frame;
        }
4129 4130
        st->codec->framerate = st->avg_frame_rate;

4131 4132 4133 4134 4135 4136 4137 4138
        if (st->internal->avctx->subtitle_header) {
            st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
            if (!st->codec->subtitle_header)
                goto find_stream_info_err;
            st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
            memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
                   st->codec->subtitle_header_size);
        }
4139 4140

        // Fields unavailable in AVCodecParameters
4141 4142
        st->codec->coded_width = st->internal->avctx->coded_width;
        st->codec->coded_height = st->internal->avctx->coded_height;
4143
        st->codec->properties = st->internal->avctx->properties;
4144 4145 4146 4147 4148 4149
FF_ENABLE_DEPRECATION_WARNINGS
#endif

        st->internal->avctx_inited = 0;
    }

4150 4151
find_stream_info_err:
    for (i = 0; i < ic->nb_streams; i++) {
4152 4153 4154
        st = ic->streams[i];
        if (st->info)
            av_freep(&st->info->duration_error);
4155
        avcodec_close(ic->streams[i]->internal->avctx);
4156
        av_freep(&ic->streams[i]->info);
4157 4158
        av_bsf_free(&ic->streams[i]->internal->extract_extradata.bsf);
        av_packet_free(&ic->streams[i]->internal->extract_extradata.pkt);
4159
    }
4160
    if (ic->pb)
4161 4162
        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);
4163
    return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
4164 4165
}

4166
AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
4167 4168 4169
{
    int i, j;

4170 4171 4172 4173 4174 4175 4176 4177 4178 4179
    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];
        }
    }
4180 4181 4182
    return NULL;
}

4183 4184 4185
int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
                        int wanted_stream_nb, int related_stream,
                        AVCodec **decoder_ret, int flags)
4186
{
4187
    int i, nb_streams = ic->nb_streams;
4188
    int ret = AVERROR_STREAM_NOT_FOUND;
4189 4190 4191 4192
    int best_count = -1, best_multiframe = -1, best_disposition = -1;
    int count, multiframe, disposition;
    int64_t best_bitrate = -1;
    int64_t bitrate;
4193
    unsigned *program = NULL;
4194
    const AVCodec *decoder = NULL, *best_decoder = NULL;
4195 4196

    if (related_stream >= 0 && wanted_stream_nb < 0) {
4197
        AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
4198
        if (p) {
4199
            program    = p->stream_index;
4200 4201 4202 4203
            nb_streams = p->nb_stream_indexes;
        }
    }
    for (i = 0; i < nb_streams; i++) {
4204
        int real_stream_index = program ? program[i] : i;
4205
        AVStream *st          = ic->streams[real_stream_index];
4206 4207
        AVCodecParameters *par = st->codecpar;
        if (par->codec_type != type)
4208
            continue;
4209
        if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
4210
            continue;
4211
        if (type == AVMEDIA_TYPE_AUDIO && !(par->channels && par->sample_rate))
4212
            continue;
4213
        if (decoder_ret) {
4214
            decoder = find_decoder(ic, st, par->codec_id);
4215 4216 4217 4218 4219 4220
            if (!decoder) {
                if (ret < 0)
                    ret = AVERROR_DECODER_NOT_FOUND;
                continue;
            }
        }
4221
        disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED));
4222
        count = st->codec_info_nb_frames;
4223
        bitrate = par->bit_rate;
4224
        multiframe = FFMIN(5, count);
4225 4226 4227 4228
        if ((best_disposition >  disposition) ||
            (best_disposition == disposition && best_multiframe >  multiframe) ||
            (best_disposition == disposition && best_multiframe == multiframe && best_bitrate >  bitrate) ||
            (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
4229
            continue;
4230
        best_disposition = disposition;
4231
        best_count   = count;
4232 4233
        best_bitrate = bitrate;
        best_multiframe = multiframe;
4234
        ret          = real_stream_index;
4235 4236
        best_decoder = decoder;
        if (program && i == nb_streams - 1 && ret < 0) {
4237
            program    = NULL;
4238
            nb_streams = ic->nb_streams;
4239 4240
            /* no related stream found, try again with everything */
            i = 0;
4241 4242 4243
        }
    }
    if (decoder_ret)
4244
        *decoder_ret = (AVCodec*)best_decoder;
4245 4246 4247
    return ret;
}

4248 4249 4250 4251
/*******************************************************/

int av_read_play(AVFormatContext *s)
{
4252 4253
    if (s->iformat->read_play)
        return s->iformat->read_play(s);
4254
    if (s->pb)
4255
        return avio_pause(s->pb, 0);
4256
    return AVERROR(ENOSYS);
4257 4258 4259 4260
}

int av_read_pause(AVFormatContext *s)
{
4261 4262
    if (s->iformat->read_pause)
        return s->iformat->read_pause(s);
4263
    if (s->pb)
4264
        return avio_pause(s->pb, 1);
4265
    return AVERROR(ENOSYS);
4266 4267
}

4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313
int ff_stream_encode_params_copy(AVStream *dst, const AVStream *src)
{
    int ret, i;

    dst->id                  = src->id;
    dst->time_base           = src->time_base;
    dst->nb_frames           = src->nb_frames;
    dst->disposition         = src->disposition;
    dst->sample_aspect_ratio = src->sample_aspect_ratio;
    dst->avg_frame_rate      = src->avg_frame_rate;
    dst->r_frame_rate        = src->r_frame_rate;

    av_dict_free(&dst->metadata);
    ret = av_dict_copy(&dst->metadata, src->metadata, 0);
    if (ret < 0)
        return ret;

    ret = avcodec_parameters_copy(dst->codecpar, src->codecpar);
    if (ret < 0)
        return ret;

    /* Free existing side data*/
    for (i = 0; i < dst->nb_side_data; i++)
        av_free(dst->side_data[i].data);
    av_freep(&dst->side_data);
    dst->nb_side_data = 0;

    /* Copy side data if present */
    if (src->nb_side_data) {
        dst->side_data = av_mallocz_array(src->nb_side_data,
                                          sizeof(AVPacketSideData));
        if (!dst->side_data)
            return AVERROR(ENOMEM);
        dst->nb_side_data = src->nb_side_data;

        for (i = 0; i < src->nb_side_data; i++) {
            uint8_t *data = av_memdup(src->side_data[i].data,
                                      src->side_data[i].size);
            if (!data)
                return AVERROR(ENOMEM);
            dst->side_data[i].type = src->side_data[i].type;
            dst->side_data[i].size = src->side_data[i].size;
            dst->side_data[i].data = data;
        }
    }

4314 4315
#if FF_API_LAVF_FFSERVER
FF_DISABLE_DEPRECATION_WARNINGS
4316 4317 4318 4319 4320 4321 4322
    av_freep(&dst->recommended_encoder_configuration);
    if (src->recommended_encoder_configuration) {
        const char *conf_str = src->recommended_encoder_configuration;
        dst->recommended_encoder_configuration = av_strdup(conf_str);
        if (!dst->recommended_encoder_configuration)
            return AVERROR(ENOMEM);
    }
4323 4324
FF_ENABLE_DEPRECATION_WARNINGS
#endif
4325 4326 4327 4328

    return 0;
}

4329 4330 4331 4332
static void free_stream(AVStream **pst)
{
    AVStream *st = *pst;
    int i;
4333

4334 4335 4336 4337 4338
    if (!st)
        return;

    for (i = 0; i < st->nb_side_data; i++)
        av_freep(&st->side_data[i].data);
4339
    av_freep(&st->side_data);
4340

4341
    if (st->parser)
4342
        av_parser_close(st->parser);
4343

4344
    if (st->attached_pic.data)
4345
        av_packet_unref(&st->attached_pic);
4346

4347 4348
    if (st->internal) {
        avcodec_free_context(&st->internal->avctx);
4349 4350 4351 4352
        for (i = 0; i < st->internal->nb_bsfcs; i++) {
            av_bsf_free(&st->internal->bsfcs[i]);
            av_freep(&st->internal->bsfcs);
        }
4353
        av_freep(&st->internal->priv_pts);
4354 4355
        av_bsf_free(&st->internal->extract_extradata.bsf);
        av_packet_free(&st->internal->extract_extradata.pkt);
4356
    }
4357 4358
    av_freep(&st->internal);

4359
    av_dict_free(&st->metadata);
4360
    avcodec_parameters_free(&st->codecpar);
4361
    av_freep(&st->probe_data.buf);
4362
    av_freep(&st->index_entries);
4363 4364
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
4365
    avcodec_free_context(&st->codec);
4366 4367
FF_ENABLE_DEPRECATION_WARNINGS
#endif
4368
    av_freep(&st->priv_data);
4369 4370
    if (st->info)
        av_freep(&st->info->duration_error);
4371
    av_freep(&st->info);
4372 4373
#if FF_API_LAVF_FFSERVER
FF_DISABLE_DEPRECATION_WARNINGS
4374
    av_freep(&st->recommended_encoder_configuration);
4375 4376
FF_ENABLE_DEPRECATION_WARNINGS
#endif
4377 4378 4379 4380 4381 4382 4383 4384 4385 4386

    av_freep(pst);
}

void ff_free_stream(AVFormatContext *s, AVStream *st)
{
    av_assert0(s->nb_streams>0);
    av_assert0(s->streams[ s->nb_streams - 1 ] == st);

    free_stream(&s->streams[ --s->nb_streams ]);
4387 4388
}

4389 4390 4391 4392
void avformat_free_context(AVFormatContext *s)
{
    int i;

4393 4394 4395
    if (!s)
        return;

4396
    av_opt_free(s);
4397
    if (s->iformat && s->iformat->priv_class && s->priv_data)
4398
        av_opt_free(s->priv_data);
Lukasz Marek's avatar
Lukasz Marek committed
4399 4400
    if (s->oformat && s->oformat->priv_class && s->priv_data)
        av_opt_free(s->priv_data);
4401

4402
    for (i = s->nb_streams - 1; i >= 0; i--)
4403
        ff_free_stream(s, s->streams[i]);
4404

4405

4406
    for (i = s->nb_programs - 1; i >= 0; i--) {
4407
        av_dict_free(&s->programs[i]->metadata);
4408
        av_freep(&s->programs[i]->stream_index);
4409 4410
        av_freep(&s->programs[i]);
    }
Michael Niedermayer's avatar
Michael Niedermayer committed
4411
    av_freep(&s->programs);
4412
    av_freep(&s->priv_data);
4413
    while (s->nb_chapters--) {
4414
        av_dict_free(&s->chapters[s->nb_chapters]->metadata);
4415
        av_freep(&s->chapters[s->nb_chapters]);
4416 4417
    }
    av_freep(&s->chapters);
4418
    av_dict_free(&s->metadata);
4419
    av_dict_free(&s->internal->id3v2_meta);
4420
    av_freep(&s->streams);
4421
    flush_packet_queue(s);
4422
    av_freep(&s->internal);
4423
    av_freep(&s->url);
4424
    av_free(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
4425 4426
}

4427 4428
void avformat_close_input(AVFormatContext **ps)
{
4429 4430 4431 4432 4433 4434
    AVFormatContext *s;
    AVIOContext *pb;

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

4435
    s  = *ps;
4436
    pb = s->pb;
4437

4438
    if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
4439 4440 4441
        (s->flags & AVFMT_FLAG_CUSTOM_IO))
        pb = NULL;

4442
    flush_packet_queue(s);
4443

4444
    if (s->iformat)
4445 4446 4447
        if (s->iformat->read_close)
            s->iformat->read_close(s);

4448
    avformat_free_context(s);
4449

4450
    *ps = NULL;
4451 4452

    avio_close(pb);
4453 4454
}

4455
AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
4456 4457
{
    AVStream *st;
4458
    int i;
4459
    AVStream **streams;
4460

4461 4462 4463
    if (s->nb_streams >= FFMIN(s->max_streams, INT_MAX/sizeof(*streams))) {
        if (s->max_streams < INT_MAX/sizeof(*streams))
            av_log(s, AV_LOG_ERROR, "Number of streams exceeds max_streams parameter (%d), see the documentation if you wish to increase it\n", s->max_streams);
4464
        return NULL;
4465
    }
4466
    streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
4467 4468 4469
    if (!streams)
        return NULL;
    s->streams = streams;
4470 4471 4472 4473

    st = av_mallocz(sizeof(AVStream));
    if (!st)
        return NULL;
4474 4475 4476 4477
    if (!(st->info = av_mallocz(sizeof(*st->info)))) {
        av_free(st);
        return NULL;
    }
4478
    st->info->last_dts = AV_NOPTS_VALUE;
4479

4480 4481
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
4482
    st->codec = avcodec_alloc_context3(c);
4483 4484 4485 4486 4487
    if (!st->codec) {
        av_free(st->info);
        av_free(st);
        return NULL;
    }
4488 4489
FF_ENABLE_DEPRECATION_WARNINGS
#endif
4490 4491 4492 4493 4494

    st->internal = av_mallocz(sizeof(*st->internal));
    if (!st->internal)
        goto fail;

4495 4496 4497 4498 4499 4500 4501 4502
    st->codecpar = avcodec_parameters_alloc();
    if (!st->codecpar)
        goto fail;

    st->internal->avctx = avcodec_alloc_context3(NULL);
    if (!st->internal->avctx)
        goto fail;

4503
    if (s->iformat) {
4504 4505
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
4506
        /* no default bitrate if decoding */
4507
        st->codec->bit_rate = 0;
4508 4509
FF_ENABLE_DEPRECATION_WARNINGS
#endif
4510 4511 4512

        /* default pts setting is MPEG-like */
        avpriv_set_pts_info(st, 33, 1, 90000);
4513 4514 4515 4516
        /* 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 */
4517
        st->cur_dts = RELATIVE_TS_BASE;
4518 4519
    } else {
        st->cur_dts = AV_NOPTS_VALUE;
4520 4521
    }

4522
    st->index      = s->nb_streams;
4523
    st->start_time = AV_NOPTS_VALUE;
4524 4525
    st->duration   = AV_NOPTS_VALUE;
    st->first_dts     = AV_NOPTS_VALUE;
4526
    st->probe_packets = MAX_PROBE_PACKETS;
4527 4528
    st->pts_wrap_reference = AV_NOPTS_VALUE;
    st->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4529

Michael Niedermayer's avatar
Michael Niedermayer committed
4530
    st->last_IP_pts = AV_NOPTS_VALUE;
4531
    st->last_dts_for_order_check = AV_NOPTS_VALUE;
4532 4533
    for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
        st->pts_buffer[i] = AV_NOPTS_VALUE;
4534

4535
    st->sample_aspect_ratio = (AVRational) { 0, 1 };
4536

4537 4538 4539 4540 4541 4542
#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;

4543 4544
    st->inject_global_side_data = s->internal->inject_global_side_data;

4545
    st->internal->need_context_update = 1;
4546

4547 4548
    s->streams[s->nb_streams++] = st;
    return st;
4549 4550 4551
fail:
    free_stream(&st);
    return NULL;
4552 4553
}

4554 4555
AVProgram *av_new_program(AVFormatContext *ac, int id)
{
4556
    AVProgram *program = NULL;
4557 4558
    int i;

4559
    av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
4560

4561 4562
    for (i = 0; i < ac->nb_programs; i++)
        if (ac->programs[i]->id == id)
4563 4564
            program = ac->programs[i];

4565
    if (!program) {
4566 4567 4568 4569 4570
        program = av_mallocz(sizeof(AVProgram));
        if (!program)
            return NULL;
        dynarray_add(&ac->programs, &ac->nb_programs, program);
        program->discard = AVDISCARD_NONE;
4571
        program->pmt_version = -1;
4572 4573
    }
    program->id = id;
4574 4575
    program->pts_wrap_reference = AV_NOPTS_VALUE;
    program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4576

4577 4578 4579
    program->start_time =
    program->end_time   = AV_NOPTS_VALUE;

4580 4581 4582
    return program;
}

4583 4584
AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
                              int64_t start, int64_t end, const char *title)
4585
{
4586 4587 4588
    AVChapter *chapter = NULL;
    int i;

4589 4590 4591 4592 4593
    if (end != AV_NOPTS_VALUE && start > end) {
        av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
        return NULL;
    }

4594 4595
    for (i = 0; i < s->nb_chapters; i++)
        if (s->chapters[i]->id == id)
4596 4597
            chapter = s->chapters[i];

4598 4599 4600
    if (!chapter) {
        chapter = av_mallocz(sizeof(AVChapter));
        if (!chapter)
4601
            return NULL;
4602
        dynarray_add(&s->chapters, &s->nb_chapters, chapter);
4603
    }
4604
    av_dict_set(&chapter->metadata, "title", title, 0);
4605 4606 4607 4608
    chapter->id        = id;
    chapter->time_base = time_base;
    chapter->start     = start;
    chapter->end       = end;
4609

4610
    return chapter;
4611
}
4612

4613
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
4614 4615
{
    int i, j;
4616
    AVProgram *program = NULL;
4617
    void *tmp;
4618

4619 4620 4621 4622 4623
    if (idx >= ac->nb_streams) {
        av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
        return;
    }

4624 4625
    for (i = 0; i < ac->nb_programs; i++) {
        if (ac->programs[i]->id != progid)
4626 4627
            continue;
        program = ac->programs[i];
4628 4629
        for (j = 0; j < program->nb_stream_indexes; j++)
            if (program->stream_index[j] == idx)
4630 4631
                return;

4632
        tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
4633
        if (!tmp)
4634
            return;
4635
        program->stream_index = tmp;
4636 4637 4638 4639 4640
        program->stream_index[program->nb_stream_indexes++] = idx;
        return;
    }
}

4641 4642
uint64_t ff_ntp_time(void)
{
4643
    return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
4644 4645
}

4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667
uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us)
{
    uint64_t ntp_ts, frac_part, sec;
    uint32_t usec;

    //current ntp time in seconds and micro seconds
    sec = ntp_time_us / 1000000;
    usec = ntp_time_us % 1000000;

    //encoding in ntp timestamp format
    frac_part = usec * 0xFFFFFFFFULL;
    frac_part /= 1000000;

    if (sec > 0xFFFFFFFFULL)
        av_log(NULL, AV_LOG_WARNING, "NTP time format roll over detected\n");

    ntp_ts = sec << 32;
    ntp_ts |= frac_part;

    return ntp_ts;
}

4668
int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number, int flags)
4669 4670
{
    const char *p;
4671
    char *q, buf1[20], c;
4672
    int nd, len, percentd_found;
4673 4674 4675 4676

    q = buf;
    p = path;
    percentd_found = 0;
4677
    for (;;) {
4678 4679 4680 4681
        c = *p++;
        if (c == '\0')
            break;
        if (c == '%') {
4682 4683
            do {
                nd = 0;
4684
                while (av_isdigit(*p))
4685 4686
                    nd = nd * 10 + *p++ - '0';
                c = *p++;
4687
            } while (av_isdigit(c));
4688

4689
            switch (c) {
4690 4691 4692
            case '%':
                goto addchar;
            case 'd':
4693
                if (!(flags & AV_FRAME_FILENAME_FLAGS_MULTIPLE) && percentd_found)
4694 4695
                    goto fail;
                percentd_found = 1;
4696
                if (number < 0)
4697
                    nd += 1;
4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708
                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 {
4709
addchar:
4710 4711 4712 4713
            if ((q - buf) < buf_size - 1)
                *q++ = c;
        }
    }
4714
    if (!percentd_found)
4715 4716 4717
        goto fail;
    *q = '\0';
    return 0;
4718
fail:
4719 4720 4721 4722
    *q = '\0';
    return -1;
}

4723 4724
int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
{
4725
    return av_get_frame_filename2(buf, buf_size, path, number, 0);
4726 4727
}

4728 4729 4730
void av_url_split(char *proto, int proto_size,
                  char *authorization, int authorization_size,
                  char *hostname, int hostname_size,
4731
                  int *port_ptr, char *path, int path_size, const char *url)
Fabrice Bellard's avatar
Fabrice Bellard committed
4732
{
4733
    const char *p, *ls, *ls2, *at, *at2, *col, *brk;
4734

4735 4736 4737 4738 4739 4740 4741 4742 4743 4744
    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;
4745 4746 4747 4748 4749

    /* parse protocol */
    if ((p = strchr(url, ':'))) {
        av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
        p++; /* skip ':' */
4750 4751 4752 4753
        if (*p == '/')
            p++;
        if (*p == '/')
            p++;
Fabrice Bellard's avatar
Fabrice Bellard committed
4754
    } else {
4755 4756 4757 4758
        /* no protocol means plain filename */
        av_strlcpy(path, url, path_size);
        return;
    }
4759

4760
    /* separate path from hostname */
4761
    ls = strchr(p, '/');
4762
    ls2 = strchr(p, '?');
4763
    if (!ls)
4764 4765 4766
        ls = ls2;
    else if (ls && ls2)
        ls = FFMIN(ls, ls2);
4767
    if (ls)
Michael Niedermayer's avatar
Michael Niedermayer committed
4768
        av_strlcpy(path, ls, path_size);
4769
    else
4770
        ls = &p[strlen(p)];  // XXX
4771 4772 4773 4774

    /* the rest is hostname, use that to parse auth/port */
    if (ls != p) {
        /* authorization (user[:pass]@hostname) */
4775 4776 4777 4778
        at2 = p;
        while ((at = strchr(p, '@')) && at < ls) {
            av_strlcpy(authorization, at2,
                       FFMIN(authorization_size, at + 1 - at2));
4779
            p = at + 1; /* skip '@' */
Fabrice Bellard's avatar
Fabrice Bellard committed
4780
        }
4781

4782 4783 4784 4785 4786 4787 4788 4789 4790
        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));
4791 4792
            if (port_ptr)
                *port_ptr = atoi(col + 1);
4793 4794 4795
        } else
            av_strlcpy(hostname, p,
                       FFMIN(ls + 1 - p, hostname_size));
Fabrice Bellard's avatar
Fabrice Bellard committed
4796 4797 4798
    }
}

4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832
int ff_mkdir_p(const char *path)
{
    int ret = 0;
    char *temp = av_strdup(path);
    char *pos = temp;
    char tmp_ch = '\0';

    if (!path || !temp) {
        return -1;
    }

    if (!av_strncasecmp(temp, "/", 1) || !av_strncasecmp(temp, "\\", 1)) {
        pos++;
    } else if (!av_strncasecmp(temp, "./", 2) || !av_strncasecmp(temp, ".\\", 2)) {
        pos += 2;
    }

    for ( ; *pos != '\0'; ++pos) {
        if (*pos == '/' || *pos == '\\') {
            tmp_ch = *pos;
            *pos = '\0';
            ret = mkdir(temp, 0755);
            *pos = tmp_ch;
        }
    }

    if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
        ret = mkdir(temp, 0755);
    }

    av_free(temp);
    return ret;
}

4833
char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4834 4835
{
    int i;
4836
    static const char hex_table_uc[16] = { '0', '1', '2', '3',
Martin Storsjö's avatar
Martin Storsjö committed
4837 4838 4839
                                           '4', '5', '6', '7',
                                           '8', '9', 'A', 'B',
                                           'C', 'D', 'E', 'F' };
4840 4841 4842 4843 4844
    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;
4845

4846
    for (i = 0; i < s; i++) {
4847 4848
        buff[i * 2]     = hex_table[src[i] >> 4];
        buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4849 4850 4851 4852 4853
    }

    return buff;
}

4854 4855 4856 4857 4858
int ff_hex_to_data(uint8_t *data, const char *p)
{
    int c, len, v;

    len = 0;
4859
    v   = 1;
4860 4861 4862 4863
    for (;;) {
        p += strspn(p, SPACE_CHARS);
        if (*p == '\0')
            break;
4864
        c = av_toupper((unsigned char) *p++);
4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881
        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;
}

4882 4883
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
4884
{
4885
    AVRational new_tb;
4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896
    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,
4897 4898
               "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
               new_tb.num, new_tb.den,
4899
               s->index);
4900 4901
        return;
    }
4902
    s->time_base     = new_tb;
4903 4904
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
4905
    s->codec->pkt_timebase = new_tb;
4906 4907
FF_ENABLE_DEPRECATION_WARNINGS
#endif
4908
    s->internal->avctx->pkt_timebase = new_tb;
4909
    s->pts_wrap_bits = pts_wrap_bits;
Fabrice Bellard's avatar
Fabrice Bellard committed
4910
}
4911

4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923
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. */
4924
        while (*ptr && (av_isspace(*ptr) || *ptr == ','))
4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956
            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 {
4957
            for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
4958 4959 4960 4961 4962 4963 4964 4965
                if (dest && dest < dest_end)
                    *dest++ = *ptr;
        }
        if (dest)
            *dest = 0;
    }
}

Peter Ross's avatar
Peter Ross committed
4966 4967 4968
int ff_find_stream_index(AVFormatContext *s, int id)
{
    int i;
4969
    for (i = 0; i < s->nb_streams; i++)
Peter Ross's avatar
Peter Ross committed
4970 4971 4972 4973
        if (s->streams[i]->id == id)
            return i;
    return -1;
}
4974

4975
int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
4976
                         int std_compliance)
4977 4978
{
    if (ofmt) {
4979
        unsigned int codec_tag;
4980 4981 4982
        if (ofmt->query_codec)
            return ofmt->query_codec(codec_id, std_compliance);
        else if (ofmt->codec_tag)
4983
            return !!av_codec_get_tag2(ofmt->codec_tag, codec_id, &codec_tag);
4984 4985
        else if (codec_id == ofmt->video_codec ||
                 codec_id == ofmt->audio_codec ||
4986 4987
                 codec_id == ofmt->subtitle_codec ||
                 codec_id == ofmt->data_codec)
4988
            return 1;
4989 4990 4991
    }
    return AVERROR_PATCHWELCOME;
}
4992 4993 4994 4995 4996 4997 4998

int avformat_network_init(void)
{
#if CONFIG_NETWORK
    int ret;
    if ((ret = ff_network_init()) < 0)
        return ret;
4999 5000
    if ((ret = ff_tls_init()) < 0)
        return ret;
5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012
#endif
    return 0;
}

int avformat_network_deinit(void)
{
#if CONFIG_NETWORK
    ff_network_close();
    ff_tls_deinit();
#endif
    return 0;
}
5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023

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) {
5024
        size  += 4;
5025 5026 5027
        flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
    }
    if (channel_layout) {
5028
        size  += 8;
5029 5030 5031
        flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
    }
    if (sample_rate) {
5032
        size  += 4;
5033 5034 5035
        flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
    }
    if (width || height) {
5036
        size  += 8;
5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054
        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;
}
5055

5056 5057 5058 5059
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;
5060
    AVRational codec_sample_aspect_ratio  = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
5061
    AVRational frame_sample_aspect_ratio  = frame  ? frame->sample_aspect_ratio  : codec_sample_aspect_ratio;
5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077

    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;
}
5078

5079 5080 5081
AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
{
    AVRational fr = st->r_frame_rate;
5082
    AVRational codec_fr = st->internal->avctx->framerate;
5083 5084 5085 5086 5087 5088 5089
    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;
    }

5090

5091
    if (st->internal->avctx->ticks_per_frame > 1) {
5092 5093
        if (   codec_fr.num > 0 && codec_fr.den > 0 &&
            (fr.num == 0 || av_q2d(codec_fr) < av_q2d(fr)*0.7 && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1))
5094 5095 5096 5097 5098 5099
            fr = codec_fr;
    }

    return fr;
}

5100 5101 5102 5103 5104 5105
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' ||
5106
             *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
5107
        enum AVMediaType type;
5108
        int nopic = 0;
5109 5110 5111 5112 5113 5114 5115

        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;
5116
        case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
5117 5118
        default:  av_assert0(0);
        }
5119 5120 5121 5122 5123 5124 5125 5126
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
        if (type != st->codecpar->codec_type
           && (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN || st->codec->codec_type != type))
            return 0;
FF_ENABLE_DEPRECATION_WARNINGS
#else
        if (type != st->codecpar->codec_type)
5127
            return 0;
5128
#endif
5129 5130
        if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
            return 0;
5131 5132
        if (*spec++ == ':') { /* possibly followed by :index */
            int i, index = strtol(spec, NULL, 0);
5133 5134 5135 5136 5137 5138
            for (i = 0; i < s->nb_streams; i++) {
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
                if ((s->streams[i]->codecpar->codec_type == type
                      || s->streams[i]->codec->codec_type == type
                    ) &&
5139 5140 5141
                    !(nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC)) &&
                    index-- == 0)
                    return i == st->index;
5142 5143 5144 5145 5146 5147 5148 5149
FF_ENABLE_DEPRECATION_WARNINGS
#else
                if ((s->streams[i]->codecpar->codec_type == type) &&
                    !(nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC)) &&
                    index-- == 0)
                    return i == st->index;
#endif
            }
5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161
            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;

5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215
            if (*endptr++ == ':') {  // p:<id>:....
                if ( *endptr == 'a' || *endptr == 'v' ||
                     *endptr == 's' || *endptr == 'd') {  // p:<id>:<st_type>[:<index>]
                    enum AVMediaType type;

                    switch (*endptr++) {
                    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;
                    default:  av_assert0(0);
                    }
                    if (*endptr++ == ':') {  // p:<id>:<st_type>:<index>
                        int stream_idx = strtol(endptr, NULL, 0), type_counter = 0;
                        for (j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
                            int stream_index = s->programs[i]->stream_index[j];
                            if (st->index == s->programs[i]->stream_index[j]) {
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
                                return type_counter == stream_idx &&
                                       (type == st->codecpar->codec_type ||
                                        type == st->codec->codec_type);
FF_ENABLE_DEPRECATION_WARNINGS
#else
                                return type_counter == stream_idx &&
                                       type == st->codecpar->codec_type;
#endif
                             }
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
                            if (type == s->streams[stream_index]->codecpar->codec_type ||
                                type == s->streams[stream_index]->codec->codec_type)
                                type_counter++;
FF_ENABLE_DEPRECATION_WARNINGS
#else
                            if (type == s->streams[stream_index]->codecpar->codec_type)
                                type_counter++;
#endif
                        }
                        return 0;
                    } else {  // p:<id>:<st_type>
                        for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
                            if (st->index == s->programs[i]->stream_index[j]) {
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
                                 return type == st->codecpar->codec_type ||
                                        type == st->codec->codec_type;
FF_ENABLE_DEPRECATION_WARNINGS
#else
                                 return type == st->codecpar->codec_type;
#endif
                            }
                        return 0;
                    }
5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243

                } else if ( *endptr == 'm') { // p:<id>:m:<metadata_spec>
                    AVDictionaryEntry *tag;
                    char *key, *val;
                    int ret = 0;

                    if (*(++endptr) != ':') {
                        av_log(s, AV_LOG_ERROR, "Invalid stream specifier syntax, missing ':' sign after :m.\n");
                        return AVERROR(EINVAL);
                    }

                    val = strchr(++endptr, ':');
                    key = val ? av_strndup(endptr, val - endptr) : av_strdup(endptr);
                    if (!key)
                        return AVERROR(ENOMEM);

                    for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
                        if (st->index == s->programs[i]->stream_index[j]) {
                            tag = av_dict_get(st->metadata, key, NULL, 0);
                            if (tag && (!val || !strcmp(tag->value, val + 1)))
                                ret = 1;

                            break;
                        }

                    av_freep(&key);
                    return ret;

5244 5245 5246 5247 5248 5249
                } else {  // p:<id>:<index>
                    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];
                }
5250 5251 5252 5253 5254 5255 5256
            }

            for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
                if (st->index == s->programs[i]->stream_index[j])
                    return 1;
        }
        return 0;
5257 5258 5259
    } else if (*spec == '#' ||
               (*spec == 'i' && *(spec + 1) == ':')) {
        int stream_id;
5260
        char *endptr;
5261 5262
        spec += 1 + (*spec == 'i');
        stream_id = strtol(spec, &endptr, 0);
5263
        if (!*endptr)
5264
            return stream_id == st->id;
5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287
    } else if (*spec == 'm' && *(spec + 1) == ':') {
        AVDictionaryEntry *tag;
        char *key, *val;
        int ret;

        spec += 2;
        val = strchr(spec, ':');

        key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
        if (!key)
            return AVERROR(ENOMEM);

        tag = av_dict_get(st->metadata, key, NULL, 0);
        if (tag) {
            if (!val || !strcmp(tag->value, val + 1))
                ret = 1;
            else
                ret = 0;
        } else
            ret = 0;

        av_freep(&key);
        return ret;
5288
    } else if (*spec == 'u') {
5289 5290 5291 5292 5293 5294
        AVCodecParameters *par = st->codecpar;
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
        AVCodecContext *codec = st->codec;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
5295
        int val;
5296
        switch (par->codec_type) {
5297
        case AVMEDIA_TYPE_AUDIO:
5298 5299 5300 5301 5302 5303 5304 5305 5306
            val = par->sample_rate && par->channels;
#if FF_API_LAVF_AVCTX
            val = val || (codec->sample_rate && codec->channels);
#endif
            if (par->format == AV_SAMPLE_FMT_NONE
#if FF_API_LAVF_AVCTX
                && codec->sample_fmt == AV_SAMPLE_FMT_NONE
#endif
                )
5307 5308 5309
                return 0;
            break;
        case AVMEDIA_TYPE_VIDEO:
5310 5311 5312 5313 5314 5315 5316 5317 5318
            val = par->width && par->height;
#if FF_API_LAVF_AVCTX
            val = val || (codec->width && codec->height);
#endif
            if (par->format == AV_PIX_FMT_NONE
#if FF_API_LAVF_AVCTX
                && codec->pix_fmt == AV_PIX_FMT_NONE
#endif
                )
5319 5320 5321 5322 5323 5324 5325 5326 5327
                return 0;
            break;
        case AVMEDIA_TYPE_UNKNOWN:
            val = 0;
            break;
        default:
            val = 1;
            break;
        }
5328 5329 5330 5331 5332
#if FF_API_LAVF_AVCTX
        return (par->codec_id != AV_CODEC_ID_NONE || codec->codec_id != AV_CODEC_ID_NONE) && val != 0;
#else
        return par->codec_id != AV_CODEC_ID_NONE && val != 0;
#endif
5333 5334 5335 5336 5337 5338
    } else if (!*spec) /* empty specifier, matches everything */
        return 1;

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

5340
int ff_generate_avci_extradata(AVStream *st)
5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368
{
    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,
5369
        0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
5370 5371 5372 5373
        // PPS
        0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
        0xd0
    };
5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388
    static const uint8_t avci50_1080p_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, 0x6f, 0x37,
        0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
        0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
        0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
        0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
        0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
        // PPS
        0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
        0x11
    };
5389 5390 5391 5392 5393 5394 5395 5396 5397 5398
    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,
5399 5400
        0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
        0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421
        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
    };
5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436
    static const uint8_t avci50_720p_extradata[] = {
        // SPS
        0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
        0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
        0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
        0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
        0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
        0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
        0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
        0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
        0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
        // PPS
        0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
        0x11
    };
5437 5438

    const uint8_t *data = NULL;
5439
    int size            = 0;
5440

5441 5442
    if (st->codecpar->width == 1920) {
        if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5443 5444 5445 5446 5447 5448
            data = avci100_1080p_extradata;
            size = sizeof(avci100_1080p_extradata);
        } else {
            data = avci100_1080i_extradata;
            size = sizeof(avci100_1080i_extradata);
        }
5449
    } else if (st->codecpar->width == 1440) {
5450
        if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5451 5452 5453 5454 5455 5456
            data = avci50_1080p_extradata;
            size = sizeof(avci50_1080p_extradata);
        } else {
            data = avci50_1080i_extradata;
            size = sizeof(avci50_1080i_extradata);
        }
5457
    } else if (st->codecpar->width == 1280) {
5458 5459
        data = avci100_720p_extradata;
        size = sizeof(avci100_720p_extradata);
5460
    } else if (st->codecpar->width == 960) {
5461 5462
        data = avci50_720p_extradata;
        size = sizeof(avci50_720p_extradata);
5463
    }
5464

5465
    if (!size)
5466 5467
        return 0;

5468
    av_freep(&st->codecpar->extradata);
5469
    if (ff_alloc_extradata(st->codecpar, size))
5470
        return AVERROR(ENOMEM);
5471
    memcpy(st->codecpar->extradata, data, size);
5472 5473

    return 0;
5474
}
5475

5476 5477
uint8_t *av_stream_get_side_data(const AVStream *st,
                                 enum AVPacketSideDataType type, int *size)
5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489
{
    int i;

    for (i = 0; i < st->nb_side_data; i++) {
        if (st->side_data[i].type == type) {
            if (size)
                *size = st->side_data[i].size;
            return st->side_data[i].data;
        }
    }
    return NULL;
}
5490

5491 5492
int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
                            uint8_t *data, size_t size)
5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503
{
    AVPacketSideData *sd, *tmp;
    int i;

    for (i = 0; i < st->nb_side_data; i++) {
        sd = &st->side_data[i];

        if (sd->type == type) {
            av_freep(&sd->data);
            sd->data = data;
            sd->size = size;
5504
            return 0;
5505 5506 5507
        }
    }

5508 5509 5510
    if ((unsigned)st->nb_side_data + 1 >= INT_MAX / sizeof(*st->side_data))
        return AVERROR(ERANGE);

5511
    tmp = av_realloc(st->side_data, (st->nb_side_data + 1) * sizeof(*tmp));
5512
    if (!tmp) {
5513
        return AVERROR(ENOMEM);
5514 5515 5516 5517 5518 5519 5520 5521 5522
    }

    st->side_data = tmp;
    st->nb_side_data++;

    sd = &st->side_data[st->nb_side_data - 1];
    sd->type = type;
    sd->data = data;
    sd->size = size;
5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541

    return 0;
}

uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
                                 int size)
{
    int ret;
    uint8_t *data = av_malloc(size);

    if (!data)
        return NULL;

    ret = av_stream_add_side_data(st, type, data, size);
    if (ret < 0) {
        av_freep(&data);
        return NULL;
    }

5542 5543
    return data;
}
5544

5545 5546
int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
{
5547 5548 5549 5550
    int ret;
    const AVBitStreamFilter *bsf;
    AVBSFContext *bsfc;
    AVCodecParameters *in_par;
5551

5552
    if (!(bsf = av_bsf_get_by_name(name))) {
5553
        av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter '%s'\n", name);
5554
        return AVERROR_BSF_NOT_FOUND;
5555
    }
5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593

    if ((ret = av_bsf_alloc(bsf, &bsfc)) < 0)
        return ret;

    if (st->internal->nb_bsfcs) {
        in_par = st->internal->bsfcs[st->internal->nb_bsfcs - 1]->par_out;
        bsfc->time_base_in = st->internal->bsfcs[st->internal->nb_bsfcs - 1]->time_base_out;
    } else {
        in_par = st->codecpar;
        bsfc->time_base_in = st->time_base;
    }

    if ((ret = avcodec_parameters_copy(bsfc->par_in, in_par)) < 0) {
        av_bsf_free(&bsfc);
        return ret;
    }

    if (args && bsfc->filter->priv_class) {
        const AVOption *opt = av_opt_next(bsfc->priv_data, NULL);
        const char * shorthand[2] = {NULL};

        if (opt)
            shorthand[0] = opt->name;

        if ((ret = av_opt_set_from_string(bsfc->priv_data, args, shorthand, "=", ":")) < 0) {
            av_bsf_free(&bsfc);
            return ret;
        }
    }

    if ((ret = av_bsf_init(bsfc)) < 0) {
        av_bsf_free(&bsfc);
        return ret;
    }

    if ((ret = av_dynarray_add_nofree(&st->internal->bsfcs, &st->internal->nb_bsfcs, bsfc))) {
        av_bsf_free(&bsfc);
        return ret;
5594
    }
5595

5596
    av_log(NULL, AV_LOG_VERBOSE,
5597 5598 5599 5600 5601
           "Automatically inserted bitstream filter '%s'; args='%s'\n",
           name, args ? args : "");
    return 1;
}

5602 5603
#if FF_API_OLD_BSF
FF_DISABLE_DEPRECATION_WARNINGS
5604 5605 5606 5607 5608 5609 5610 5611 5612 5613
int av_apply_bitstream_filters(AVCodecContext *codec, AVPacket *pkt,
                               AVBitStreamFilterContext *bsfc)
{
    int ret = 0;
    while (bsfc) {
        AVPacket new_pkt = *pkt;
        int a = av_bitstream_filter_filter(bsfc, codec, NULL,
                                           &new_pkt.data, &new_pkt.size,
                                           pkt->data, pkt->size,
                                           pkt->flags & AV_PKT_FLAG_KEY);
5614 5615 5616 5617 5618
        if (a == 0 && new_pkt.size == 0 && new_pkt.side_data_elems == 0) {
            av_packet_unref(pkt);
            memset(pkt, 0, sizeof(*pkt));
            return 0;
        }
5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656
        if(a == 0 && new_pkt.data != pkt->data) {
            uint8_t *t = av_malloc(new_pkt.size + AV_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
            if (t) {
                memcpy(t, new_pkt.data, new_pkt.size);
                memset(t + new_pkt.size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
                new_pkt.data = t;
                new_pkt.buf = NULL;
                a = 1;
            } else {
                a = AVERROR(ENOMEM);
            }
        }
        if (a > 0) {
            new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
                                           av_buffer_default_free, NULL, 0);
            if (new_pkt.buf) {
                pkt->side_data = NULL;
                pkt->side_data_elems = 0;
                av_packet_unref(pkt);
            } else {
                av_freep(&new_pkt.data);
                a = AVERROR(ENOMEM);
            }
        }
        if (a < 0) {
            av_log(codec, AV_LOG_ERROR,
                   "Failed to open bitstream filter %s for stream %d with codec %s",
                   bsfc->filter->name, pkt->stream_index,
                   codec->codec ? codec->codec->name : "copy");
            ret = a;
            break;
        }
        *pkt = new_pkt;

        bsfc = bsfc->next;
    }
    return ret;
}
5657 5658
FF_ENABLE_DEPRECATION_WARNINGS
#endif
5659

5660 5661 5662 5663 5664 5665 5666 5667 5668 5669
int ff_format_output_open(AVFormatContext *s, const char *url, AVDictionary **options)
{
    if (!s->oformat)
        return AVERROR(EINVAL);

    if (!(s->oformat->flags & AVFMT_NOFILE))
        return s->io_open(s, &s->pb, url, AVIO_FLAG_WRITE, options);
    return 0;
}

5670 5671 5672 5673 5674 5675
void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
{
    if (*pb)
        s->io_close(s, *pb);
    *pb = NULL;
}
5676

5677 5678 5679 5680 5681
int ff_is_http_proto(char *filename) {
    const char *proto = avio_find_protocol_name(filename);
    return proto ? (!av_strcasecmp(proto, "http") || !av_strcasecmp(proto, "https")) : 0;
}

5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697
int ff_parse_creation_time_metadata(AVFormatContext *s, int64_t *timestamp, int return_seconds)
{
    AVDictionaryEntry *entry;
    int64_t parsed_timestamp;
    int ret;
    if ((entry = av_dict_get(s->metadata, "creation_time", NULL, 0))) {
        if ((ret = av_parse_time(&parsed_timestamp, entry->value, 0)) >= 0) {
            *timestamp = return_seconds ? parsed_timestamp / 1000000 : parsed_timestamp;
            return 1;
        } else {
            av_log(s, AV_LOG_WARNING, "Failed to parse creation_time %s\n", entry->value);
            return ret;
        }
    }
    return 0;
}
5698

5699 5700 5701 5702
int ff_standardize_creation_time(AVFormatContext *s)
{
    int64_t timestamp;
    int ret = ff_parse_creation_time_metadata(s, &timestamp, 0);
5703 5704
    if (ret == 1)
        return avpriv_dict_set_timestamp(&s->metadata, "creation_time", timestamp);
5705 5706 5707
    return ret;
}

5708
int ff_get_packet_palette(AVFormatContext *s, AVPacket *pkt, int ret, uint32_t *palette)
5709
{
5710
    uint8_t *side_data;
5711 5712
    int size;

5713 5714 5715 5716 5717 5718 5719 5720
    side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_PALETTE, &size);
    if (side_data) {
        if (size != AVPALETTE_SIZE) {
            av_log(s, AV_LOG_ERROR, "Invalid palette side data\n");
            return AVERROR_INVALIDDATA;
        }
        memcpy(palette, side_data, AVPALETTE_SIZE);
        return 1;
5721 5722
    }

5723 5724 5725 5726 5727 5728
    if (ret == CONTAINS_PAL) {
        int i;
        for (i = 0; i < AVPALETTE_COUNT; i++)
            palette[i] = AV_RL32(pkt->data + pkt->size - AVPALETTE_SIZE + i*4);
        return 1;
    }
5729 5730 5731

    return 0;
}
5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754

int ff_bprint_to_codecpar_extradata(AVCodecParameters *par, struct AVBPrint *buf)
{
    int ret;
    char *str;

    ret = av_bprint_finalize(buf, &str);
    if (ret < 0)
        return ret;
    if (!av_bprint_is_complete(buf)) {
        av_free(str);
        return AVERROR(ENOMEM);
    }

    par->extradata = str;
    /* Note: the string is NUL terminated (so extradata can be read as a
     * string), but the ending character is not accounted in the size (in
     * binary formats you are likely not supposed to mux that character). When
     * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
     * zeros. */
    par->extradata_size = buf->len;
    return 0;
}
5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791

int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
                                                  AVStream *ost, const AVStream *ist,
                                                  enum AVTimebaseSource copy_tb)
{
    //TODO: use [io]st->internal->avctx
    const AVCodecContext *dec_ctx = ist->codec;
    AVCodecContext       *enc_ctx = ost->codec;

    enc_ctx->time_base = ist->time_base;
    /*
     * Avi is a special case here because it supports variable fps but
     * having the fps and timebase differe significantly adds quite some
     * overhead
     */
    if (!strcmp(ofmt->name, "avi")) {
#if FF_API_R_FRAME_RATE
        if (copy_tb == AVFMT_TBCF_AUTO && ist->r_frame_rate.num
            && av_q2d(ist->r_frame_rate) >= av_q2d(ist->avg_frame_rate)
            && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(ist->time_base)
            && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(dec_ctx->time_base)
            && av_q2d(ist->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
            || copy_tb == AVFMT_TBCF_R_FRAMERATE) {
            enc_ctx->time_base.num = ist->r_frame_rate.den;
            enc_ctx->time_base.den = 2*ist->r_frame_rate.num;
            enc_ctx->ticks_per_frame = 2;
        } else
#endif
            if (copy_tb == AVFMT_TBCF_AUTO && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->time_base)
                   && av_q2d(ist->time_base) < 1.0/500
                   || copy_tb == AVFMT_TBCF_DECODER) {
            enc_ctx->time_base = dec_ctx->time_base;
            enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
            enc_ctx->time_base.den *= 2;
            enc_ctx->ticks_per_frame = 2;
        }
    } else if (!(ofmt->flags & AVFMT_VARIABLE_FPS)
5792
               && !av_match_name(ofmt->name, "mov,mp4,3gp,3g2,psp,ipod,ismv,f4v")) {
5793 5794 5795 5796 5797 5798 5799 5800 5801
        if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx->time_base.den
            && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->time_base)
            && av_q2d(ist->time_base) < 1.0/500
            || copy_tb == AVFMT_TBCF_DECODER) {
            enc_ctx->time_base = dec_ctx->time_base;
            enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
        }
    }

5802
    if ((enc_ctx->codec_tag == AV_RL32("tmcd") || ost->codecpar->codec_tag == AV_RL32("tmcd"))
5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816
        && dec_ctx->time_base.num < dec_ctx->time_base.den
        && dec_ctx->time_base.num > 0
        && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
        enc_ctx->time_base = dec_ctx->time_base;
    }

    if (ost->avg_frame_rate.num)
        enc_ctx->time_base = av_inv_q(ost->avg_frame_rate);

    av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
              enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);

    return 0;
}
5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828

AVRational av_stream_get_codec_timebase(const AVStream *st)
{
    // See avformat_transfer_internal_stream_timing_info() TODO.
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
    return st->codec->time_base;
FF_ENABLE_DEPRECATION_WARNINGS
#else
    return st->internal->avctx->time_base;
#endif
}
5829 5830 5831 5832 5833 5834

void ff_format_set_url(AVFormatContext *s, char *url)
{
    av_assert0(url);
    av_freep(&s->url);
    s->url = url;
5835 5836
#if FF_API_FORMAT_FILENAME
FF_DISABLE_DEPRECATION_WARNINGS
5837
    av_strlcpy(s->filename, url, sizeof(s->filename));
5838 5839
FF_ENABLE_DEPRECATION_WARNINGS
#endif
5840
}