Coverage Report

Created: 2026-03-12 07:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavformat/demux.c
Line
Count
Source
1
/*
2
 * Core demuxing component
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
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
20
 */
21
22
#include <stdint.h>
23
24
#include "config_components.h"
25
26
#include "libavutil/avassert.h"
27
#include "libavutil/avstring.h"
28
#include "libavutil/dict.h"
29
#include "libavutil/internal.h"
30
#include "libavutil/intreadwrite.h"
31
#include "libavutil/mathematics.h"
32
#include "libavutil/mem.h"
33
#include "libavutil/opt.h"
34
#include "libavutil/pixfmt.h"
35
#include "libavutil/time.h"
36
#include "libavutil/timestamp.h"
37
38
#include "libavcodec/avcodec.h"
39
#include "libavcodec/bsf.h"
40
#include "libavcodec/codec_desc.h"
41
#include "libavcodec/internal.h"
42
#include "libavcodec/packet_internal.h"
43
#include "libavcodec/raw.h"
44
45
#include "avformat.h"
46
#include "avformat_internal.h"
47
#include "avio_internal.h"
48
#include "demux.h"
49
#include "id3v2.h"
50
#include "internal.h"
51
#include "url.h"
52
53
static int64_t wrap_timestamp(const AVStream *st, int64_t timestamp)
54
0
{
55
0
    const FFStream *const sti = cffstream(st);
56
0
    if (sti->pts_wrap_behavior != AV_PTS_WRAP_IGNORE && st->pts_wrap_bits < 64 &&
57
0
        sti->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
58
0
        if (sti->pts_wrap_behavior == AV_PTS_WRAP_ADD_OFFSET &&
59
0
            timestamp < sti->pts_wrap_reference)
60
0
            return timestamp + (1ULL << st->pts_wrap_bits);
61
0
        else if (sti->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
62
0
            timestamp >= sti->pts_wrap_reference)
63
0
            return timestamp - (1ULL << st->pts_wrap_bits);
64
0
    }
65
0
    return timestamp;
66
0
}
67
68
int64_t ff_wrap_timestamp(const AVStream *st, int64_t timestamp)
69
0
{
70
0
    return wrap_timestamp(st, timestamp);
71
0
}
72
73
static const AVCodec *find_probe_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
74
0
{
75
0
    const AVCodec *codec;
76
77
#if CONFIG_H264_DECODER
78
    /* Other parts of the code assume this decoder to be used for h264,
79
     * so force it if possible. */
80
    if (codec_id == AV_CODEC_ID_H264)
81
        return avcodec_find_decoder_by_name("h264");
82
#endif
83
84
0
    codec = ff_find_decoder(s, st, codec_id);
85
0
    if (!codec)
86
0
        return NULL;
87
88
0
    if (codec->capabilities & AV_CODEC_CAP_AVOID_PROBING) {
89
0
        const AVCodec *probe_codec = NULL;
90
0
        void *iter = NULL;
91
0
        while ((probe_codec = av_codec_iterate(&iter))) {
92
0
            if (probe_codec->id == codec->id &&
93
0
                    av_codec_is_decoder(probe_codec) &&
94
0
                    !(probe_codec->capabilities & (AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_EXPERIMENTAL))) {
95
0
                return probe_codec;
96
0
            }
97
0
        }
98
0
    }
99
100
0
    return codec;
101
0
}
102
103
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
104
                                     AVProbeData *pd)
105
0
{
106
0
    static const struct {
107
0
        const char *name;
108
0
        enum AVCodecID id;
109
0
        enum AVMediaType type;
110
0
    } fmt_id_type[] = {
111
0
        { "aac",        AV_CODEC_ID_AAC,          AVMEDIA_TYPE_AUDIO    },
112
0
        { "ac3",        AV_CODEC_ID_AC3,          AVMEDIA_TYPE_AUDIO    },
113
0
        { "aptx",       AV_CODEC_ID_APTX,         AVMEDIA_TYPE_AUDIO    },
114
0
        { "av1",        AV_CODEC_ID_AV1,          AVMEDIA_TYPE_VIDEO    },
115
0
        { "dts",        AV_CODEC_ID_DTS,          AVMEDIA_TYPE_AUDIO    },
116
0
        { "dvbsub",     AV_CODEC_ID_DVB_SUBTITLE, AVMEDIA_TYPE_SUBTITLE },
117
0
        { "dvbtxt",     AV_CODEC_ID_DVB_TELETEXT, AVMEDIA_TYPE_SUBTITLE },
118
0
        { "eac3",       AV_CODEC_ID_EAC3,         AVMEDIA_TYPE_AUDIO    },
119
0
        { "h264",       AV_CODEC_ID_H264,         AVMEDIA_TYPE_VIDEO    },
120
0
        { "hevc",       AV_CODEC_ID_HEVC,         AVMEDIA_TYPE_VIDEO    },
121
0
        { "loas",       AV_CODEC_ID_AAC_LATM,     AVMEDIA_TYPE_AUDIO    },
122
0
        { "m4v",        AV_CODEC_ID_MPEG4,        AVMEDIA_TYPE_VIDEO    },
123
0
        { "mjpeg_2000", AV_CODEC_ID_JPEG2000,     AVMEDIA_TYPE_VIDEO    },
124
0
        { "mp3",        AV_CODEC_ID_MP3,          AVMEDIA_TYPE_AUDIO    },
125
0
        { "mpegvideo",  AV_CODEC_ID_MPEG2VIDEO,   AVMEDIA_TYPE_VIDEO    },
126
0
        { "truehd",     AV_CODEC_ID_TRUEHD,       AVMEDIA_TYPE_AUDIO    },
127
0
        { "evc",        AV_CODEC_ID_EVC,          AVMEDIA_TYPE_VIDEO    },
128
0
        { "vvc",        AV_CODEC_ID_VVC,          AVMEDIA_TYPE_VIDEO    },
129
0
        { 0 }
130
0
    };
131
0
    int score;
132
0
    const AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
133
0
    FFStream *const sti = ffstream(st);
134
135
0
    if (fmt) {
136
0
        av_log(s, AV_LOG_DEBUG,
137
0
               "Probe with size=%d, packets=%d detected %s with score=%d\n",
138
0
               pd->buf_size, s->max_probe_packets - sti->probe_packets,
139
0
               fmt->name, score);
140
0
        for (int i = 0; fmt_id_type[i].name; i++) {
141
0
            if (!strcmp(fmt->name, fmt_id_type[i].name)) {
142
0
                if (fmt_id_type[i].type != AVMEDIA_TYPE_AUDIO &&
143
0
                    st->codecpar->sample_rate)
144
0
                    continue;
145
0
                if (sti->request_probe > score &&
146
0
                    st->codecpar->codec_id != fmt_id_type[i].id)
147
0
                    continue;
148
0
                st->codecpar->codec_id   = fmt_id_type[i].id;
149
0
                st->codecpar->codec_type = fmt_id_type[i].type;
150
0
                sti->need_context_update = 1;
151
0
                return score;
152
0
            }
153
0
        }
154
0
    }
155
0
    return 0;
156
0
}
157
158
static int init_input(AVFormatContext *s, const char *filename,
159
                      AVDictionary **options)
160
1.38k
{
161
1.38k
    int ret;
162
1.38k
    AVProbeData pd = { filename, NULL, 0 };
163
1.38k
    int score = AVPROBE_SCORE_RETRY;
164
165
1.38k
    if (s->pb) {
166
0
        s->flags |= AVFMT_FLAG_CUSTOM_IO;
167
0
        if (!s->iformat)
168
0
            return av_probe_input_buffer2(s->pb, &s->iformat, filename,
169
0
                                          s, 0, s->format_probesize);
170
0
        else if (s->iformat->flags & AVFMT_NOFILE)
171
0
            av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
172
0
                                      "will be ignored with AVFMT_NOFILE format.\n");
173
0
        return 0;
174
0
    }
175
176
1.38k
    if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
177
1.38k
        (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
178
0
        return score;
179
180
1.38k
    if ((ret = s->io_open(s, &s->pb, filename, AVIO_FLAG_READ | s->avio_flags, options)) < 0)
181
1.38k
        return ret;
182
183
0
    if (s->iformat)
184
0
        return 0;
185
0
    return av_probe_input_buffer2(s->pb, &s->iformat, filename,
186
0
                                  s, 0, s->format_probesize);
187
0
}
188
189
static int codec_close(FFStream *sti);
190
191
static int update_stream_avctx(AVFormatContext *s)
192
0
{
193
0
    int ret;
194
0
    for (unsigned i = 0; i < s->nb_streams; i++) {
195
0
        AVStream *const st  = s->streams[i];
196
0
        FFStream *const sti = ffstream(st);
197
198
0
        if (!sti->need_context_update)
199
0
            continue;
200
201
0
        if (avcodec_is_open(sti->avctx)) {
202
0
            av_log(s, AV_LOG_DEBUG, "Demuxer context update while decoder is open, closing and trying to re-open\n");
203
0
            ret = codec_close(sti);
204
0
            sti->info->found_decoder = 0;
205
0
            if (ret < 0)
206
0
                return ret;
207
0
        }
208
209
        /* close parser, because it depends on the codec */
210
0
        if (sti->parser && sti->avctx->codec_id != st->codecpar->codec_id) {
211
0
            av_parser_close(sti->parser);
212
0
            sti->parser = NULL;
213
0
        }
214
215
        /* update internal codec context, for the parser */
216
0
        ret = avcodec_parameters_to_context(sti->avctx, st->codecpar);
217
0
        if (ret < 0)
218
0
            return ret;
219
220
0
        sti->codec_desc = avcodec_descriptor_get(sti->avctx->codec_id);
221
222
0
        sti->need_context_update = 0;
223
0
    }
224
0
    return 0;
225
0
}
226
227
0
static av_always_inline int is_id3v2_format(const AVInputFormat *fmt) {
228
0
    return ffifmt(fmt)->flags_internal & FF_INFMT_FLAG_ID3V2_AUTO;
229
0
}
230
231
int avformat_open_input(AVFormatContext **ps, const char *filename,
232
                        const AVInputFormat *fmt, AVDictionary **options)
233
1.38k
{
234
1.38k
    FormatContextInternal *fci;
235
1.38k
    AVFormatContext *s = *ps;
236
1.38k
    FFFormatContext *si;
237
1.38k
    AVDictionary *tmp = NULL;
238
1.38k
    ID3v2ExtraMeta *id3v2_extra_meta = NULL;
239
1.38k
    int ret = 0;
240
241
1.38k
    if (!s && !(s = avformat_alloc_context()))
242
0
        return AVERROR(ENOMEM);
243
1.38k
    fci = ff_fc_internal(s);
244
1.38k
    si = &fci->fc;
245
1.38k
    if (!s->av_class) {
246
0
        av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
247
0
        return AVERROR(EINVAL);
248
0
    }
249
1.38k
    if (fmt)
250
0
        s->iformat = fmt;
251
252
1.38k
    if (options)
253
0
        av_dict_copy(&tmp, *options, 0);
254
255
1.38k
    if (s->pb) // must be before any goto fail
256
0
        s->flags |= AVFMT_FLAG_CUSTOM_IO;
257
258
1.38k
    if ((ret = av_opt_set_dict(s, &tmp)) < 0)
259
0
        goto fail;
260
261
1.38k
    if (!(s->url = av_strdup(filename ? filename : ""))) {
262
0
        ret = AVERROR(ENOMEM);
263
0
        goto fail;
264
0
    }
265
266
1.38k
    if ((ret = init_input(s, filename, &tmp)) < 0)
267
1.38k
        goto fail;
268
0
    s->probe_score = ret;
269
270
0
    if (!s->protocol_whitelist && s->pb && s->pb->protocol_whitelist) {
271
0
        s->protocol_whitelist = av_strdup(s->pb->protocol_whitelist);
272
0
        if (!s->protocol_whitelist) {
273
0
            ret = AVERROR(ENOMEM);
274
0
            goto fail;
275
0
        }
276
0
    }
277
278
0
    if (!s->protocol_blacklist && s->pb && s->pb->protocol_blacklist) {
279
0
        s->protocol_blacklist = av_strdup(s->pb->protocol_blacklist);
280
0
        if (!s->protocol_blacklist) {
281
0
            ret = AVERROR(ENOMEM);
282
0
            goto fail;
283
0
        }
284
0
    }
285
286
0
    if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
287
0
        av_log(s, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", s->format_whitelist);
288
0
        ret = AVERROR(EINVAL);
289
0
        goto fail;
290
0
    }
291
292
0
    avio_skip(s->pb, s->skip_initial_bytes);
293
294
    /* Check filename in case an image number is expected. */
295
0
    if (s->iformat->flags & AVFMT_NEEDNUMBER) {
296
0
        if (!av_filename_number_test(filename)) {
297
0
            ret = AVERROR(EINVAL);
298
0
            goto fail;
299
0
        }
300
0
    }
301
302
0
    s->duration = s->start_time = AV_NOPTS_VALUE;
303
304
    /* Allocate private data. */
305
0
    if (ffifmt(s->iformat)->priv_data_size > 0) {
306
0
        if (!(s->priv_data = av_mallocz(ffifmt(s->iformat)->priv_data_size))) {
307
0
            ret = AVERROR(ENOMEM);
308
0
            goto fail;
309
0
        }
310
0
        if (s->iformat->priv_class) {
311
0
            *(const AVClass **) s->priv_data = s->iformat->priv_class;
312
0
            av_opt_set_defaults(s->priv_data);
313
0
            if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
314
0
                goto fail;
315
0
        }
316
0
    }
317
318
    /* e.g. AVFMT_NOFILE formats will not have an AVIOContext */
319
0
    if (s->pb && is_id3v2_format(s->iformat))
320
0
        ff_id3v2_read_dict(s->pb, &si->id3v2_meta, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
321
322
0
    if (ffifmt(s->iformat)->read_header)
323
0
        if ((ret = ffifmt(s->iformat)->read_header(s)) < 0) {
324
0
            if (ffifmt(s->iformat)->flags_internal & FF_INFMT_FLAG_INIT_CLEANUP)
325
0
                goto close;
326
0
            goto fail;
327
0
        }
328
329
0
    if (!s->metadata) {
330
0
        s->metadata    = si->id3v2_meta;
331
0
        si->id3v2_meta = NULL;
332
0
    } else if (si->id3v2_meta) {
333
0
        av_log(s, AV_LOG_WARNING, "Discarding ID3 tags because more suitable tags were found.\n");
334
0
        av_dict_free(&si->id3v2_meta);
335
0
    }
336
337
0
    if (id3v2_extra_meta) {
338
0
        if ((ret = ff_id3v2_parse_apic(s, id3v2_extra_meta)) < 0)
339
0
            goto close;
340
0
        if ((ret = ff_id3v2_parse_chapters(s, id3v2_extra_meta)) < 0)
341
0
            goto close;
342
0
        if ((ret = ff_id3v2_parse_priv(s, id3v2_extra_meta)) < 0)
343
0
            goto close;
344
0
        ff_id3v2_free_extra_meta(&id3v2_extra_meta);
345
0
    }
346
347
0
    if ((ret = avformat_queue_attached_pictures(s)) < 0)
348
0
        goto close;
349
350
0
    if (s->pb && !si->data_offset)
351
0
        si->data_offset = avio_tell(s->pb);
352
353
0
    fci->raw_packet_buffer_size = 0;
354
355
0
    update_stream_avctx(s);
356
357
0
    if (options) {
358
0
        av_dict_free(options);
359
0
        *options = tmp;
360
0
    }
361
0
    *ps = s;
362
0
    return 0;
363
364
0
close:
365
0
    if (ffifmt(s->iformat)->read_close)
366
0
        ffifmt(s->iformat)->read_close(s);
367
1.38k
fail:
368
1.38k
    ff_id3v2_free_extra_meta(&id3v2_extra_meta);
369
1.38k
    av_dict_free(&tmp);
370
1.38k
    if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
371
0
        avio_closep(&s->pb);
372
1.38k
    avformat_free_context(s);
373
1.38k
    *ps = NULL;
374
1.38k
    return ret;
375
0
}
376
377
void avformat_close_input(AVFormatContext **ps)
378
692
{
379
692
    AVFormatContext *s;
380
692
    AVIOContext *pb;
381
382
692
    if (!ps || !*ps)
383
692
        return;
384
385
0
    s  = *ps;
386
0
    pb = s->pb;
387
388
0
    if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
389
0
        (s->flags & AVFMT_FLAG_CUSTOM_IO))
390
0
        pb = NULL;
391
392
0
    if (s->iformat)
393
0
        if (ffifmt(s->iformat)->read_close)
394
0
            ffifmt(s->iformat)->read_close(s);
395
396
0
    ff_format_io_close(s, &pb);
397
0
    avformat_free_context(s);
398
399
0
    *ps = NULL;
400
0
}
401
402
static void force_codec_ids(AVFormatContext *s, AVStream *st)
403
0
{
404
0
    switch (st->codecpar->codec_type) {
405
0
    case AVMEDIA_TYPE_VIDEO:
406
0
        if (s->video_codec_id)
407
0
            st->codecpar->codec_id = s->video_codec_id;
408
0
        break;
409
0
    case AVMEDIA_TYPE_AUDIO:
410
0
        if (s->audio_codec_id)
411
0
            st->codecpar->codec_id = s->audio_codec_id;
412
0
        break;
413
0
    case AVMEDIA_TYPE_SUBTITLE:
414
0
        if (s->subtitle_codec_id)
415
0
            st->codecpar->codec_id = s->subtitle_codec_id;
416
0
        break;
417
0
    case AVMEDIA_TYPE_DATA:
418
0
        if (s->data_codec_id)
419
0
            st->codecpar->codec_id = s->data_codec_id;
420
0
        break;
421
0
    }
422
0
}
423
424
static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
425
0
{
426
0
    FormatContextInternal *const fci = ff_fc_internal(s);
427
0
    FFStream *const sti = ffstream(st);
428
429
0
    if (sti->request_probe > 0) {
430
0
        AVProbeData *const pd = &sti->probe_data;
431
0
        int end;
432
0
        av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, sti->probe_packets);
433
0
        --sti->probe_packets;
434
435
0
        if (pkt) {
436
0
            uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
437
0
            if (!new_buf) {
438
0
                av_log(s, AV_LOG_WARNING,
439
0
                       "Failed to reallocate probe buffer for stream %d\n",
440
0
                       st->index);
441
0
                goto no_packet;
442
0
            }
443
0
            pd->buf = new_buf;
444
0
            memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
445
0
            pd->buf_size += pkt->size;
446
0
            memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
447
0
        } else {
448
0
no_packet:
449
0
            sti->probe_packets = 0;
450
0
            if (!pd->buf_size) {
451
0
                av_log(s, AV_LOG_WARNING,
452
0
                       "nothing to probe for stream %d\n", st->index);
453
0
            }
454
0
        }
455
456
0
        end = fci->raw_packet_buffer_size >= s->probesize ||
457
0
              sti->probe_packets <= 0;
458
459
0
        if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
460
0
            int score = set_codec_from_probe_data(s, st, pd);
461
0
            if (    (st->codecpar->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
462
0
                || end) {
463
0
                pd->buf_size = 0;
464
0
                av_freep(&pd->buf);
465
0
                sti->request_probe = -1;
466
0
                if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
467
0
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
468
0
                } else
469
0
                    av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
470
0
            }
471
0
            force_codec_ids(s, st);
472
0
        }
473
0
    }
474
0
    return 0;
475
0
}
476
477
static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
478
0
{
479
0
    FFStream *const sti = ffstream(st);
480
0
    int64_t ref = pkt->dts;
481
0
    int pts_wrap_behavior;
482
0
    int64_t pts_wrap_reference;
483
0
    AVProgram *first_program;
484
485
0
    if (ref == AV_NOPTS_VALUE)
486
0
        ref = pkt->pts;
487
0
    if (sti->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
488
0
        return 0;
489
0
    ref &= (1LL << st->pts_wrap_bits)-1;
490
491
    // reference time stamp should be 60 s before first time stamp
492
0
    pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
493
    // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
494
0
    pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
495
0
        (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
496
0
        AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;
497
498
0
    first_program = av_find_program_from_stream(s, NULL, stream_index);
499
500
0
    if (!first_program) {
501
0
        int default_stream_index = av_find_default_stream_index(s);
502
0
        FFStream *const default_sti = ffstream(s->streams[default_stream_index]);
503
0
        if (default_sti->pts_wrap_reference == AV_NOPTS_VALUE) {
504
0
            for (unsigned i = 0; i < s->nb_streams; i++) {
505
0
                FFStream *const sti = ffstream(s->streams[i]);
506
0
                if (av_find_program_from_stream(s, NULL, i))
507
0
                    continue;
508
0
                sti->pts_wrap_reference = pts_wrap_reference;
509
0
                sti->pts_wrap_behavior  = pts_wrap_behavior;
510
0
            }
511
0
        } else {
512
0
            sti->pts_wrap_reference = default_sti->pts_wrap_reference;
513
0
            sti->pts_wrap_behavior  = default_sti->pts_wrap_behavior;
514
0
        }
515
0
    } else {
516
0
        AVProgram *program = first_program;
517
0
        while (program) {
518
0
            if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
519
0
                pts_wrap_reference = program->pts_wrap_reference;
520
0
                pts_wrap_behavior = program->pts_wrap_behavior;
521
0
                break;
522
0
            }
523
0
            program = av_find_program_from_stream(s, program, stream_index);
524
0
        }
525
526
        // update every program with differing pts_wrap_reference
527
0
        program = first_program;
528
0
        while (program) {
529
0
            if (program->pts_wrap_reference != pts_wrap_reference) {
530
0
                for (unsigned i = 0; i < program->nb_stream_indexes; i++) {
531
0
                    FFStream *const sti = ffstream(s->streams[program->stream_index[i]]);
532
0
                    sti->pts_wrap_reference = pts_wrap_reference;
533
0
                    sti->pts_wrap_behavior  = pts_wrap_behavior;
534
0
                }
535
536
0
                program->pts_wrap_reference = pts_wrap_reference;
537
0
                program->pts_wrap_behavior = pts_wrap_behavior;
538
0
            }
539
0
            program = av_find_program_from_stream(s, program, stream_index);
540
0
        }
541
0
    }
542
0
    return 1;
543
0
}
544
545
static void update_timestamps(AVFormatContext *s, AVStream *st, AVPacket *pkt)
546
0
{
547
0
    FFStream *const sti = ffstream(st);
548
549
0
    if (update_wrap_reference(s, st, pkt->stream_index, pkt) && sti->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
550
        // correct first time stamps to negative values
551
0
        if (!is_relative(sti->first_dts))
552
0
            sti->first_dts = wrap_timestamp(st, sti->first_dts);
553
0
        if (!is_relative(st->start_time))
554
0
            st->start_time = wrap_timestamp(st, st->start_time);
555
0
        if (!is_relative(sti->cur_dts))
556
0
            sti->cur_dts = wrap_timestamp(st, sti->cur_dts);
557
0
    }
558
559
0
    pkt->dts = wrap_timestamp(st, pkt->dts);
560
0
    pkt->pts = wrap_timestamp(st, pkt->pts);
561
562
0
    force_codec_ids(s, st);
563
564
    /* TODO: audio: time filter; video: frame reordering (pts != dts) */
565
0
    if (s->use_wallclock_as_timestamps)
566
0
        pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
567
0
}
568
569
/**
570
 * Handle a new packet and either return it directly if possible and
571
 * allow_passthrough is true or queue the packet (or drop the packet
572
 * if corrupt).
573
 *
574
 * @return < 0 on error, 0 if the packet was passed through,
575
 *         1 if it was queued or dropped
576
 */
577
static int handle_new_packet(AVFormatContext *s, AVPacket *pkt, int allow_passthrough)
578
0
{
579
0
    FormatContextInternal *const fci = ff_fc_internal(s);
580
0
    AVStream *st;
581
0
    FFStream *sti;
582
0
    int err;
583
584
0
    av_assert0(pkt->stream_index < (unsigned)s->nb_streams &&
585
0
               "Invalid stream index.\n");
586
587
0
    if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
588
0
        av_log(s, AV_LOG_WARNING,
589
0
               "Packet corrupt (stream = %d, dts = %s)%s.\n",
590
0
               pkt->stream_index, av_ts2str(pkt->dts),
591
0
               s->flags & AVFMT_FLAG_DISCARD_CORRUPT ? ", dropping it" : "");
592
0
        if (s->flags & AVFMT_FLAG_DISCARD_CORRUPT) {
593
0
            av_packet_unref(pkt);
594
0
            return 1;
595
0
        }
596
0
    }
597
598
0
    st  = s->streams[pkt->stream_index];
599
0
    sti = ffstream(st);
600
601
0
    update_timestamps(s, st, pkt);
602
603
0
    if (sti->request_probe <= 0 && allow_passthrough && !fci->raw_packet_buffer.head)
604
0
        return 0;
605
606
0
    err = avpriv_packet_list_put(&fci->raw_packet_buffer, pkt, NULL, 0);
607
0
    if (err < 0) {
608
0
        av_packet_unref(pkt);
609
0
        return err;
610
0
    }
611
612
0
    pkt = &fci->raw_packet_buffer.tail->pkt;
613
0
    fci->raw_packet_buffer_size += pkt->size;
614
615
0
    err = probe_codec(s, st, pkt);
616
0
    if (err < 0)
617
0
        return err;
618
619
0
    return 1;
620
0
}
621
622
int ff_buffer_packet(AVFormatContext *s, AVPacket *pkt)
623
0
{
624
0
    int err = handle_new_packet(s, pkt, 0);
625
626
0
    return err < 0 ? err : 0;
627
0
}
628
629
int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
630
0
{
631
0
    FormatContextInternal *const fci = ff_fc_internal(s);
632
0
    int err;
633
634
0
#if FF_API_INIT_PACKET
635
0
FF_DISABLE_DEPRECATION_WARNINGS
636
0
    pkt->data = NULL;
637
0
    pkt->size = 0;
638
0
    av_init_packet(pkt);
639
0
FF_ENABLE_DEPRECATION_WARNINGS
640
#else
641
    av_packet_unref(pkt);
642
#endif
643
644
0
    for (;;) {
645
0
        PacketListEntry *pktl = fci->raw_packet_buffer.head;
646
647
0
        if (pktl) {
648
0
            AVStream *const st = s->streams[pktl->pkt.stream_index];
649
0
            if (fci->raw_packet_buffer_size >= s->probesize)
650
0
                if ((err = probe_codec(s, st, NULL)) < 0)
651
0
                    return err;
652
0
            if (ffstream(st)->request_probe <= 0) {
653
0
                avpriv_packet_list_get(&fci->raw_packet_buffer, pkt);
654
0
                fci->raw_packet_buffer_size -= pkt->size;
655
0
                return 0;
656
0
            }
657
0
        }
658
659
0
        err = ffifmt(s->iformat)->read_packet(s, pkt);
660
0
        if (err < 0) {
661
0
            av_packet_unref(pkt);
662
663
            /* Some demuxers return FFERROR_REDO when they consume
664
               data and discard it (ignored streams, junk, extradata).
665
               We must re-call the demuxer to get the real packet. */
666
0
            if (err == FFERROR_REDO)
667
0
                continue;
668
0
            if (!pktl || err == AVERROR(EAGAIN))
669
0
                return err;
670
0
            for (unsigned i = 0; i < s->nb_streams; i++) {
671
0
                AVStream *const st  = s->streams[i];
672
0
                FFStream *const sti = ffstream(st);
673
0
                if (sti->probe_packets || sti->request_probe > 0)
674
0
                    if ((err = probe_codec(s, st, NULL)) < 0)
675
0
                        return err;
676
0
                av_assert0(sti->request_probe <= 0);
677
0
            }
678
0
            continue;
679
0
        }
680
681
0
        err = av_packet_make_refcounted(pkt);
682
0
        if (err < 0) {
683
0
            av_packet_unref(pkt);
684
0
            return err;
685
0
        }
686
687
0
        err = handle_new_packet(s, pkt, 1);
688
0
        if (err <= 0) /* Error or passthrough */
689
0
            return err;
690
0
    }
691
0
}
692
693
/**
694
 * Return the frame duration in seconds. Return 0 if not available.
695
 */
696
static void compute_frame_duration(AVFormatContext *s, int *pnum, int *pden,
697
                                   AVStream *st, AVCodecParserContext *pc,
698
                                   AVPacket *pkt)
699
0
{
700
0
    FFStream *const sti = ffstream(st);
701
0
    AVRational codec_framerate = sti->avctx->framerate;
702
0
    int frame_size, sample_rate;
703
704
0
    *pnum = 0;
705
0
    *pden = 0;
706
0
    switch (st->codecpar->codec_type) {
707
0
    case AVMEDIA_TYPE_VIDEO:
708
0
        if (st->r_frame_rate.num && (!pc || !codec_framerate.num)) {
709
0
            *pnum = st->r_frame_rate.den;
710
0
            *pden = st->r_frame_rate.num;
711
0
        } else if ((s->iformat->flags & AVFMT_NOTIMESTAMPS) &&
712
0
                   !codec_framerate.num &&
713
0
                   st->avg_frame_rate.num && st->avg_frame_rate.den) {
714
0
            *pnum = st->avg_frame_rate.den;
715
0
            *pden = st->avg_frame_rate.num;
716
0
        } else if (st->time_base.num * 1000LL > st->time_base.den) {
717
0
            *pnum = st->time_base.num;
718
0
            *pden = st->time_base.den;
719
0
        } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
720
0
            int ticks_per_frame = (sti->codec_desc &&
721
0
                                   (sti->codec_desc->props & AV_CODEC_PROP_FIELDS)) ? 2 : 1;
722
0
            av_reduce(pnum, pden,
723
0
                      codec_framerate.den,
724
0
                      codec_framerate.num * (int64_t)ticks_per_frame,
725
0
                      INT_MAX);
726
727
0
            if (pc && pc->repeat_pict) {
728
0
                av_reduce(pnum, pden,
729
0
                          (*pnum) * (1LL + pc->repeat_pict),
730
0
                          (*pden),
731
0
                          INT_MAX);
732
0
            }
733
            /* If this codec can be interlaced or progressive then we need
734
             * a parser to compute duration of a packet. Thus if we have
735
             * no parser in such case leave duration undefined. */
736
0
            if (sti->codec_desc &&
737
0
                (sti->codec_desc->props & AV_CODEC_PROP_FIELDS) && !pc)
738
0
                *pnum = *pden = 0;
739
0
        }
740
0
        break;
741
0
    case AVMEDIA_TYPE_AUDIO:
742
0
        if (sti->avctx_inited) {
743
0
            frame_size  = av_get_audio_frame_duration(sti->avctx, pkt->size);
744
0
            sample_rate = sti->avctx->sample_rate;
745
0
        } else {
746
0
            frame_size  = av_get_audio_frame_duration2(st->codecpar, pkt->size);
747
0
            sample_rate = st->codecpar->sample_rate;
748
0
        }
749
0
        if (frame_size <= 0 || sample_rate <= 0)
750
0
            break;
751
0
        *pnum = frame_size;
752
0
        *pden = sample_rate;
753
0
        break;
754
0
    default:
755
0
        break;
756
0
    }
757
0
}
758
759
static int has_decode_delay_been_guessed(AVStream *st)
760
0
{
761
0
    FFStream *const sti = ffstream(st);
762
0
    if (st->codecpar->codec_id != AV_CODEC_ID_H264) return 1;
763
0
    if (!sti->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
764
0
        return 1;
765
0
    av_assert0(sti->avctx->codec_id == AV_CODEC_ID_H264 || (sti->avctx->codec_id == AV_CODEC_ID_NONE && !avcodec_is_open(sti->avctx)));
766
#if CONFIG_H264_DECODER
767
    if (sti->avctx->has_b_frames && avcodec_is_open(sti->avctx) &&
768
        avpriv_h264_has_num_reorder_frames(sti->avctx) == sti->avctx->has_b_frames)
769
        return 1;
770
#endif
771
0
    if (sti->avctx->has_b_frames < 3)
772
0
        return sti->nb_decoded_frames >= 7;
773
0
    else if (sti->avctx->has_b_frames < 4)
774
0
        return sti->nb_decoded_frames >= 18;
775
0
    else
776
0
        return sti->nb_decoded_frames >= 20;
777
0
}
778
779
static PacketListEntry *get_next_pkt(AVFormatContext *s, AVStream *st,
780
                                     PacketListEntry *pktl)
781
0
{
782
0
    FormatContextInternal *const fci = ff_fc_internal(s);
783
0
    FFFormatContext *const si = &fci->fc;
784
0
    if (pktl->next)
785
0
        return pktl->next;
786
0
    if (pktl == si->packet_buffer.tail)
787
0
        return fci->parse_queue.head;
788
0
    return NULL;
789
0
}
790
791
static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts)
792
0
{
793
0
    FFStream *const sti = ffstream(st);
794
0
    int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
795
0
                       st->codecpar->codec_id != AV_CODEC_ID_HEVC &&
796
0
                       st->codecpar->codec_id != AV_CODEC_ID_VVC;
797
798
0
    if (!onein_oneout) {
799
0
        int delay = sti->avctx->has_b_frames;
800
801
0
        if (dts == AV_NOPTS_VALUE) {
802
0
            int64_t best_score = INT64_MAX;
803
0
            for (int i = 0; i < delay; i++) {
804
0
                if (sti->pts_reorder_error_count[i]) {
805
0
                    int64_t score = sti->pts_reorder_error[i] / sti->pts_reorder_error_count[i];
806
0
                    if (score < best_score) {
807
0
                        best_score = score;
808
0
                        dts = pts_buffer[i];
809
0
                    }
810
0
                }
811
0
            }
812
0
        } else {
813
0
            for (int i = 0; i < delay; i++) {
814
0
                if (pts_buffer[i] != AV_NOPTS_VALUE) {
815
0
#define ABSDIFF(a,b) (((a) < (b)) ? (b) - (uint64_t)(a) : ((a) - (uint64_t)(b)))
816
0
                    uint64_t diff = ABSDIFF(pts_buffer[i], dts);
817
818
0
                    if (diff > INT64_MAX - sti->pts_reorder_error[i]) {
819
0
                        diff = INT64_MAX;
820
0
                    } else
821
0
                        diff += sti->pts_reorder_error[i];
822
823
0
                    sti->pts_reorder_error[i] = diff;
824
0
                    sti->pts_reorder_error_count[i]++;
825
0
                    if (sti->pts_reorder_error_count[i] > 250) {
826
0
                        sti->pts_reorder_error[i] >>= 1;
827
0
                        sti->pts_reorder_error_count[i] >>= 1;
828
0
                    }
829
0
                }
830
0
            }
831
0
        }
832
0
    }
833
834
0
    if (dts == AV_NOPTS_VALUE)
835
0
        dts = pts_buffer[0];
836
837
0
    return dts;
838
0
}
839
840
/**
841
 * Updates the dts of packets of a stream in pkt_buffer, by re-ordering the pts
842
 * of the packets in a window.
843
 */
844
static void update_dts_from_pts(AVFormatContext *s, int stream_index,
845
                                PacketListEntry *pkt_buffer)
846
0
{
847
0
    AVStream *const st = s->streams[stream_index];
848
0
    int delay = ffstream(st)->avctx->has_b_frames;
849
850
0
    int64_t pts_buffer[MAX_REORDER_DELAY+1];
851
852
0
    for (int i = 0; i < MAX_REORDER_DELAY + 1; i++)
853
0
        pts_buffer[i] = AV_NOPTS_VALUE;
854
855
0
    for (; pkt_buffer; pkt_buffer = get_next_pkt(s, st, pkt_buffer)) {
856
0
        if (pkt_buffer->pkt.stream_index != stream_index)
857
0
            continue;
858
859
0
        if (pkt_buffer->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
860
0
            pts_buffer[0] = pkt_buffer->pkt.pts;
861
0
            for (int i = 0; i < delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
862
0
                FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
863
864
0
            pkt_buffer->pkt.dts = select_from_pts_buffer(st, pts_buffer, pkt_buffer->pkt.dts);
865
0
        }
866
0
    }
867
0
}
868
869
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
870
                                      int64_t dts, int64_t pts, AVPacket *pkt)
871
0
{
872
0
    FormatContextInternal *const fci = ff_fc_internal(s);
873
0
    FFFormatContext *const si = &fci->fc;
874
0
    AVStream *const st  = s->streams[stream_index];
875
0
    FFStream *const sti = ffstream(st);
876
0
    PacketListEntry *pktl = si->packet_buffer.head ? si->packet_buffer.head : fci->parse_queue.head;
877
878
0
    uint64_t shift;
879
880
0
    if (sti->first_dts != AV_NOPTS_VALUE ||
881
0
        dts           == AV_NOPTS_VALUE ||
882
0
        sti->cur_dts   == AV_NOPTS_VALUE ||
883
0
        sti->cur_dts < INT_MIN + RELATIVE_TS_BASE ||
884
0
        dts  < INT_MIN + (sti->cur_dts - RELATIVE_TS_BASE) ||
885
0
        is_relative(dts))
886
0
        return;
887
888
0
    sti->first_dts = dts - (sti->cur_dts - RELATIVE_TS_BASE);
889
0
    sti->cur_dts   = dts;
890
0
    shift          = (uint64_t)sti->first_dts - RELATIVE_TS_BASE;
891
892
0
    if (is_relative(pts))
893
0
        pts += shift;
894
895
0
    for (PacketListEntry *pktl_it = pktl; pktl_it; pktl_it = get_next_pkt(s, st, pktl_it)) {
896
0
        if (pktl_it->pkt.stream_index != stream_index)
897
0
            continue;
898
0
        if (is_relative(pktl_it->pkt.pts))
899
0
            pktl_it->pkt.pts += shift;
900
901
0
        if (is_relative(pktl_it->pkt.dts))
902
0
            pktl_it->pkt.dts += shift;
903
904
0
        if (st->start_time == AV_NOPTS_VALUE && pktl_it->pkt.pts != AV_NOPTS_VALUE) {
905
0
            st->start_time = pktl_it->pkt.pts;
906
0
            if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
907
0
                st->start_time = av_sat_add64(st->start_time, av_rescale_q(sti->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base));
908
0
        }
909
0
    }
910
911
0
    if (has_decode_delay_been_guessed(st))
912
0
        update_dts_from_pts(s, stream_index, pktl);
913
914
0
    if (st->start_time == AV_NOPTS_VALUE) {
915
0
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || !(pkt->flags & AV_PKT_FLAG_DISCARD)) {
916
0
            st->start_time = pts;
917
0
        }
918
0
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
919
0
            st->start_time = av_sat_add64(st->start_time, av_rescale_q(sti->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base));
920
0
    }
921
0
}
922
923
static void update_initial_durations(AVFormatContext *s, AVStream *st,
924
                                     int stream_index, int64_t duration)
925
0
{
926
0
    FormatContextInternal *const fci = ff_fc_internal(s);
927
0
    FFFormatContext *const si = &fci->fc;
928
0
    FFStream *const sti = ffstream(st);
929
0
    PacketListEntry *pktl = si->packet_buffer.head ? si->packet_buffer.head : fci->parse_queue.head;
930
0
    int64_t cur_dts = RELATIVE_TS_BASE;
931
932
0
    if (sti->first_dts != AV_NOPTS_VALUE) {
933
0
        if (sti->update_initial_durations_done)
934
0
            return;
935
0
        sti->update_initial_durations_done = 1;
936
0
        cur_dts = sti->first_dts;
937
0
        for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
938
0
            if (pktl->pkt.stream_index == stream_index) {
939
0
                if (pktl->pkt.pts != pktl->pkt.dts  ||
940
0
                    pktl->pkt.dts != AV_NOPTS_VALUE ||
941
0
                    pktl->pkt.duration)
942
0
                    break;
943
0
                cur_dts -= duration;
944
0
            }
945
0
        }
946
0
        if (pktl && pktl->pkt.dts != sti->first_dts) {
947
0
            av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
948
0
                   av_ts2str(sti->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
949
0
            return;
950
0
        }
951
0
        if (!pktl) {
952
0
            av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(sti->first_dts));
953
0
            return;
954
0
        }
955
0
        pktl = si->packet_buffer.head ? si->packet_buffer.head : fci->parse_queue.head;
956
0
        sti->first_dts = cur_dts;
957
0
    } else if (sti->cur_dts != RELATIVE_TS_BASE)
958
0
        return;
959
960
0
    for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
961
0
        if (pktl->pkt.stream_index != stream_index)
962
0
            continue;
963
0
        if ((pktl->pkt.pts == pktl->pkt.dts ||
964
0
             pktl->pkt.pts == AV_NOPTS_VALUE) &&
965
0
            (pktl->pkt.dts == AV_NOPTS_VALUE ||
966
0
             pktl->pkt.dts == sti->first_dts ||
967
0
             pktl->pkt.dts == RELATIVE_TS_BASE) &&
968
0
            !pktl->pkt.duration &&
969
0
            av_sat_add64(cur_dts, duration) == cur_dts + (uint64_t)duration
970
0
        ) {
971
0
            pktl->pkt.dts = cur_dts;
972
0
            if (!sti->avctx->has_b_frames)
973
0
                pktl->pkt.pts = cur_dts;
974
0
            pktl->pkt.duration = duration;
975
0
        } else
976
0
            break;
977
0
        cur_dts = pktl->pkt.dts + pktl->pkt.duration;
978
0
    }
979
0
    if (!pktl)
980
0
        sti->cur_dts = cur_dts;
981
0
}
982
983
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
984
                               AVCodecParserContext *pc, AVPacket *pkt,
985
                               int64_t next_dts, int64_t next_pts)
986
0
{
987
0
    FormatContextInternal *const fci = ff_fc_internal(s);
988
0
    FFFormatContext *const si = &fci->fc;
989
0
    FFStream *const sti = ffstream(st);
990
0
    int num, den, presentation_delayed, delay;
991
0
    int64_t offset;
992
0
    AVRational duration;
993
0
    int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
994
0
                       st->codecpar->codec_id != AV_CODEC_ID_HEVC &&
995
0
                       st->codecpar->codec_id != AV_CODEC_ID_VVC;
996
997
0
    if (s->flags & AVFMT_FLAG_NOFILLIN)
998
0
        return;
999
1000
0
    if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1001
0
        if (pkt->dts == pkt->pts && sti->last_dts_for_order_check != AV_NOPTS_VALUE) {
1002
0
            if (sti->last_dts_for_order_check <= pkt->dts) {
1003
0
                sti->dts_ordered++;
1004
0
            } else {
1005
0
                av_log(s, sti->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
1006
0
                       "DTS %"PRIi64" < %"PRIi64" out of order\n",
1007
0
                       pkt->dts,
1008
0
                       sti->last_dts_for_order_check);
1009
0
                sti->dts_misordered++;
1010
0
            }
1011
0
            if (sti->dts_ordered + sti->dts_misordered > 250) {
1012
0
                sti->dts_ordered    >>= 1;
1013
0
                sti->dts_misordered >>= 1;
1014
0
            }
1015
0
        }
1016
1017
0
        sti->last_dts_for_order_check = pkt->dts;
1018
0
        if (sti->dts_ordered < 8 * sti->dts_misordered && pkt->dts == pkt->pts)
1019
0
            pkt->dts = AV_NOPTS_VALUE;
1020
0
    }
1021
1022
0
    if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1023
0
        pkt->dts = AV_NOPTS_VALUE;
1024
1025
0
    if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1026
0
        && !sti->avctx->has_b_frames)
1027
        //FIXME Set low_delay = 0 when has_b_frames = 1
1028
0
        sti->avctx->has_b_frames = 1;
1029
1030
    /* do we have a video B-frame ? */
1031
0
    delay = sti->avctx->has_b_frames;
1032
0
    presentation_delayed = 0;
1033
1034
    /* XXX: need has_b_frame, but cannot get it if the codec is
1035
     *  not initialized */
1036
0
    if (delay &&
1037
0
        pc && pc->pict_type != AV_PICTURE_TYPE_B)
1038
0
        presentation_delayed = 1;
1039
1040
0
    if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1041
0
        st->pts_wrap_bits < 63 && pkt->dts > INT64_MIN + (1LL << st->pts_wrap_bits) &&
1042
0
        pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1043
0
        if (is_relative(sti->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > sti->cur_dts) {
1044
0
            pkt->dts -= 1LL << st->pts_wrap_bits;
1045
0
        } else
1046
0
            pkt->pts += 1LL << st->pts_wrap_bits;
1047
0
    }
1048
1049
    /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1050
     * We take the conservative approach and discard both.
1051
     * Note: If this is misbehaving for an H.264 file, then possibly
1052
     * presentation_delayed is not set correctly. */
1053
0
    if (delay == 1 && pkt->dts == pkt->pts &&
1054
0
        pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1055
0
        av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1056
0
        if (    strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1057
0
             && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1058
0
            pkt->dts = AV_NOPTS_VALUE;
1059
0
    }
1060
1061
0
    duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1062
0
    if (pkt->duration <= 0) {
1063
0
        compute_frame_duration(s, &num, &den, st, pc, pkt);
1064
0
        if (den && num) {
1065
0
            duration = (AVRational) {num, den};
1066
0
            pkt->duration = av_rescale_rnd(1,
1067
0
                                           num * (int64_t) st->time_base.den,
1068
0
                                           den * (int64_t) st->time_base.num,
1069
0
                                           AV_ROUND_DOWN);
1070
0
        }
1071
0
    }
1072
1073
0
    if (pkt->duration > 0 && (si->packet_buffer.head || fci->parse_queue.head))
1074
0
        update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1075
1076
    /* Correct timestamps with byte offset if demuxers only have timestamps
1077
     * on packet boundaries */
1078
0
    if (pc && sti->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1079
        /* this will estimate bitrate based on this frame's duration and size */
1080
0
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1081
0
        if (pkt->pts != AV_NOPTS_VALUE)
1082
0
            pkt->pts += offset;
1083
0
        if (pkt->dts != AV_NOPTS_VALUE)
1084
0
            pkt->dts += offset;
1085
0
    }
1086
1087
    /* This may be redundant, but it should not hurt. */
1088
0
    if (pkt->dts != AV_NOPTS_VALUE &&
1089
0
        pkt->pts != AV_NOPTS_VALUE &&
1090
0
        pkt->pts > pkt->dts)
1091
0
        presentation_delayed = 1;
1092
1093
0
    if (s->debug & FF_FDEBUG_TS)
1094
0
        av_log(s, AV_LOG_DEBUG,
1095
0
            "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%"PRId64" delay:%d onein_oneout:%d\n",
1096
0
            presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(sti->cur_dts),
1097
0
            pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1098
1099
    /* Interpolate PTS and DTS if they are not present. We skip H264
1100
     * currently because delay and has_b_frames are not reliably set. */
1101
0
    if ((delay == 0 || (delay == 1 && pc)) &&
1102
0
        onein_oneout) {
1103
0
        if (presentation_delayed) {
1104
            /* DTS = decompression timestamp */
1105
            /* PTS = presentation timestamp */
1106
0
            if (pkt->dts == AV_NOPTS_VALUE)
1107
0
                pkt->dts = sti->last_IP_pts;
1108
0
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1109
0
            if (pkt->dts == AV_NOPTS_VALUE)
1110
0
                pkt->dts = sti->cur_dts;
1111
1112
            /* This is tricky: the dts must be incremented by the duration
1113
             * of the frame we are displaying, i.e. the last I- or P-frame. */
1114
0
            if (sti->last_IP_duration == 0 && (uint64_t)pkt->duration <= INT32_MAX)
1115
0
                sti->last_IP_duration = pkt->duration;
1116
0
            if (pkt->dts != AV_NOPTS_VALUE)
1117
0
                sti->cur_dts = av_sat_add64(pkt->dts, sti->last_IP_duration);
1118
0
            if (pkt->dts != AV_NOPTS_VALUE &&
1119
0
                pkt->pts == AV_NOPTS_VALUE &&
1120
0
                sti->last_IP_duration > 0 &&
1121
0
                ((uint64_t)sti->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1122
0
                next_dts != next_pts &&
1123
0
                next_pts != AV_NOPTS_VALUE)
1124
0
                pkt->pts = next_dts;
1125
1126
0
            if ((uint64_t)pkt->duration <= INT32_MAX)
1127
0
                sti->last_IP_duration = pkt->duration;
1128
0
            sti->last_IP_pts      = pkt->pts;
1129
            /* Cannot compute PTS if not present (we can compute it only
1130
             * by knowing the future. */
1131
0
        } else if (pkt->pts != AV_NOPTS_VALUE ||
1132
0
                   pkt->dts != AV_NOPTS_VALUE ||
1133
0
                   pkt->duration > 0             ) {
1134
1135
            /* presentation is not delayed : PTS and DTS are the same */
1136
0
            if (pkt->pts == AV_NOPTS_VALUE)
1137
0
                pkt->pts = pkt->dts;
1138
0
            update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1139
0
                                      pkt->pts, pkt);
1140
0
            if (pkt->pts == AV_NOPTS_VALUE)
1141
0
                pkt->pts = sti->cur_dts;
1142
0
            pkt->dts = pkt->pts;
1143
0
            if (pkt->pts != AV_NOPTS_VALUE && duration.num >= 0)
1144
0
                sti->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1145
0
        }
1146
0
    }
1147
1148
0
    if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1149
0
        sti->pts_buffer[0] = pkt->pts;
1150
0
        for (int i = 0; i < delay && sti->pts_buffer[i] > sti->pts_buffer[i + 1]; i++)
1151
0
            FFSWAP(int64_t, sti->pts_buffer[i], sti->pts_buffer[i + 1]);
1152
1153
0
        if (has_decode_delay_been_guessed(st))
1154
0
            pkt->dts = select_from_pts_buffer(st, sti->pts_buffer, pkt->dts);
1155
0
    }
1156
    // We skipped it above so we try here.
1157
0
    if (!onein_oneout)
1158
        // This should happen on the first packet
1159
0
        update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1160
0
    if (pkt->dts > sti->cur_dts)
1161
0
        sti->cur_dts = pkt->dts;
1162
1163
0
    if (s->debug & FF_FDEBUG_TS)
1164
0
        av_log(s, AV_LOG_DEBUG, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s st:%d (%d)\n",
1165
0
            presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(sti->cur_dts), st->index, st->id);
1166
1167
    /* update flags */
1168
0
    if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || ff_is_intra_only(st->codecpar->codec_id))
1169
0
        pkt->flags |= AV_PKT_FLAG_KEY;
1170
0
}
1171
1172
/**
1173
 * Parse a packet, add all split parts to parse_queue.
1174
 *
1175
 * @param pkt   Packet to parse; must not be NULL.
1176
 * @param flush Indicates whether to flush. If set, pkt must be blank.
1177
 */
1178
static int parse_packet(AVFormatContext *s, AVPacket *pkt,
1179
                        int stream_index, int flush)
1180
0
{
1181
0
    FormatContextInternal *const fci = ff_fc_internal(s);
1182
0
    AVStream *st = s->streams[stream_index];
1183
0
    FFStream *const sti = ffstream(st);
1184
0
    AVPacket *out_pkt = sti->parse_pkt;
1185
0
    const AVPacketSideData *sd = NULL;
1186
0
    const uint8_t *data = pkt->data;
1187
0
    uint8_t *extradata = sti->avctx->extradata;
1188
0
    int extradata_size = sti->avctx->extradata_size;
1189
0
    int size = pkt->size;
1190
0
    int ret = 0, got_output = flush, pkt_side_data_consumed = 0;
1191
1192
0
    if (!size && !flush && sti->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1193
        // preserve 0-size sync packets
1194
0
        compute_pkt_fields(s, st, sti->parser, pkt, pkt->dts, pkt->pts);
1195
1196
        // Theora has valid 0-sized packets that need to be output
1197
0
        if (st->codecpar->codec_id == AV_CODEC_ID_THEORA) {
1198
0
            ret = avpriv_packet_list_put(&fci->parse_queue,
1199
0
                                         pkt, NULL, 0);
1200
0
            if (ret < 0)
1201
0
                goto fail;
1202
0
        }
1203
0
    }
1204
1205
0
    if (pkt->side_data_elems)
1206
0
        sd = av_packet_side_data_get(pkt->side_data, pkt->side_data_elems,
1207
0
                                     AV_PKT_DATA_NEW_EXTRADATA);
1208
0
    if (sd) {
1209
0
        av_assert1(size && !flush);
1210
1211
0
        sti->avctx->extradata      = sd->data;
1212
0
        sti->avctx->extradata_size = sd->size;
1213
0
    }
1214
1215
0
    while (size > 0 || (flush && got_output)) {
1216
0
        int64_t next_pts = pkt->pts;
1217
0
        int64_t next_dts = pkt->dts;
1218
0
        int len;
1219
1220
0
        len = av_parser_parse2(sti->parser, sti->avctx,
1221
0
                               &out_pkt->data, &out_pkt->size, data, size,
1222
0
                               pkt->pts, pkt->dts, pkt->pos);
1223
1224
0
        pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1225
0
        pkt->pos = -1;
1226
        /* increment read pointer */
1227
0
        av_assert1(data || !len);
1228
0
        data  = len ? data + len : data;
1229
0
        size -= len;
1230
1231
0
        got_output = !!out_pkt->size;
1232
1233
0
        if (pkt->side_data && !out_pkt->side_data) {
1234
            /* for the first iteration, side_data are simply moved to output.
1235
             * in case of additional iterations, they are duplicated each time. */
1236
0
            if (!pkt_side_data_consumed) {
1237
0
                pkt_side_data_consumed = 1;
1238
0
                out_pkt->side_data       = pkt->side_data;
1239
0
                out_pkt->side_data_elems = pkt->side_data_elems;
1240
0
            } else for (int i = 0; i < pkt->side_data_elems; i++) {
1241
0
                const AVPacketSideData *const src_sd = &pkt->side_data[i];
1242
0
                uint8_t *dst_data = av_packet_new_side_data(out_pkt, src_sd->type, src_sd->size);
1243
0
                if (!dst_data) {
1244
0
                    ret = AVERROR(ENOMEM);
1245
0
                    goto fail;
1246
0
                }
1247
0
                memcpy(dst_data, src_sd->data, src_sd->size);
1248
0
            }
1249
0
        }
1250
1251
0
        if (!out_pkt->size)
1252
0
            continue;
1253
1254
0
        if (pkt->buf && out_pkt->data == pkt->data) {
1255
            /* reference pkt->buf only when out_pkt->data is guaranteed to point
1256
             * to data in it and not in the parser's internal buffer. */
1257
            /* XXX: Ensure this is the case with all parsers when sti->parser->flags
1258
             * is PARSER_FLAG_COMPLETE_FRAMES and check for that instead? */
1259
0
            out_pkt->buf = av_buffer_ref(pkt->buf);
1260
0
            if (!out_pkt->buf) {
1261
0
                ret = AVERROR(ENOMEM);
1262
0
                goto fail;
1263
0
            }
1264
0
        } else {
1265
0
            ret = av_packet_make_refcounted(out_pkt);
1266
0
            if (ret < 0)
1267
0
                goto fail;
1268
0
        }
1269
1270
        /* set the duration */
1271
0
        out_pkt->duration = (sti->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;
1272
0
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1273
0
            if (sti->avctx->sample_rate > 0 && !out_pkt->duration && sti->parser->duration > 0) {
1274
0
                out_pkt->duration =
1275
0
                    av_rescale_q_rnd(sti->parser->duration,
1276
0
                                     (AVRational) { 1, sti->avctx->sample_rate },
1277
0
                                     st->time_base,
1278
0
                                     AV_ROUND_DOWN);
1279
0
            }
1280
0
        } else if (st->codecpar->codec_id == AV_CODEC_ID_GIF) {
1281
0
            if (st->time_base.num > 0 && st->time_base.den > 0 &&
1282
0
                sti->parser->duration) {
1283
0
                out_pkt->duration = sti->parser->duration;
1284
0
            }
1285
0
        }
1286
1287
0
        out_pkt->stream_index = st->index;
1288
0
        out_pkt->pts          = sti->parser->pts;
1289
0
        out_pkt->dts          = sti->parser->dts;
1290
0
        out_pkt->pos          = sti->parser->pos;
1291
0
        out_pkt->flags       |= pkt->flags & (AV_PKT_FLAG_DISCARD | AV_PKT_FLAG_CORRUPT);
1292
1293
0
        if (sti->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1294
0
            out_pkt->pos = sti->parser->frame_offset;
1295
1296
0
        if (sti->parser->key_frame == 1 ||
1297
0
            (sti->parser->key_frame == -1 &&
1298
0
             sti->parser->pict_type == AV_PICTURE_TYPE_I))
1299
0
            out_pkt->flags |= AV_PKT_FLAG_KEY;
1300
1301
0
        if (sti->parser->key_frame == -1 && sti->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1302
0
            out_pkt->flags |= AV_PKT_FLAG_KEY;
1303
1304
0
        compute_pkt_fields(s, st, sti->parser, out_pkt, next_dts, next_pts);
1305
1306
0
        ret = avpriv_packet_list_put(&fci->parse_queue,
1307
0
                                     out_pkt, NULL, 0);
1308
0
        if (ret < 0)
1309
0
            goto fail;
1310
0
    }
1311
1312
    /* end of the stream => close and free the parser */
1313
0
    if (flush) {
1314
0
        av_parser_close(sti->parser);
1315
0
        sti->parser = NULL;
1316
0
    }
1317
1318
0
fail:
1319
0
    if (sd) {
1320
0
        sti->avctx->extradata      = extradata;
1321
0
        sti->avctx->extradata_size = extradata_size;
1322
0
    }
1323
0
    if (pkt_side_data_consumed) {
1324
0
        pkt->side_data          = NULL;
1325
0
        pkt->side_data_elems    = 0;
1326
0
    }
1327
1328
0
    if (ret < 0)
1329
0
        av_packet_unref(out_pkt);
1330
0
    av_packet_unref(pkt);
1331
0
    return ret;
1332
0
}
1333
1334
static int64_t ts_to_samples(AVStream *st, int64_t ts)
1335
0
{
1336
0
    return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
1337
0
}
1338
1339
static int codec_close(FFStream *sti)
1340
0
{
1341
0
    AVCodecContext *avctx_new = NULL;
1342
0
    AVCodecParameters *par_tmp = NULL;
1343
0
    const AVCodec *new_codec = NULL;
1344
0
    int ret;
1345
1346
0
    new_codec =
1347
0
      (sti->avctx->codec_id != sti->pub.codecpar->codec_id) ?
1348
0
      avcodec_find_decoder(sti->pub.codecpar->codec_id) :
1349
0
      sti->avctx->codec;
1350
1351
0
    avctx_new = avcodec_alloc_context3(new_codec);
1352
0
    if (!avctx_new) {
1353
0
        ret = AVERROR(ENOMEM);
1354
0
        goto fail;
1355
0
    }
1356
1357
0
    par_tmp = avcodec_parameters_alloc();
1358
0
    if (!par_tmp) {
1359
0
        ret = AVERROR(ENOMEM);
1360
0
        goto fail;
1361
0
    }
1362
1363
0
    ret = avcodec_parameters_from_context(par_tmp, sti->avctx);
1364
0
    if (ret < 0)
1365
0
        goto fail;
1366
1367
0
    ret = avcodec_parameters_to_context(avctx_new, par_tmp);
1368
0
    if (ret < 0)
1369
0
        goto fail;
1370
1371
0
    avctx_new->pkt_timebase = sti->avctx->pkt_timebase;
1372
1373
0
    avcodec_free_context(&sti->avctx);
1374
0
    sti->avctx = avctx_new;
1375
1376
0
    avctx_new = NULL;
1377
0
    ret       = 0;
1378
1379
0
fail:
1380
0
    avcodec_free_context(&avctx_new);
1381
0
    avcodec_parameters_free(&par_tmp);
1382
1383
0
    return ret;
1384
0
}
1385
1386
static int extract_extradata(FFFormatContext *si, AVStream *st, const AVPacket *pkt);
1387
1388
static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1389
0
{
1390
0
    FormatContextInternal *const fci = ff_fc_internal(s);
1391
0
    FFFormatContext *const si = &fci->fc;
1392
0
    int ret, got_packet = 0;
1393
0
    AVDictionary *metadata = NULL;
1394
1395
0
    while (!got_packet && !fci->parse_queue.head) {
1396
0
        AVStream *st;
1397
0
        FFStream *sti;
1398
1399
        /* read next packet */
1400
0
        ret = ff_read_packet(s, pkt);
1401
0
        if (ret < 0) {
1402
0
            if (ret == AVERROR(EAGAIN))
1403
0
                return ret;
1404
            /* flush the parsers */
1405
0
            for (unsigned i = 0; i < s->nb_streams; i++) {
1406
0
                AVStream *const st  = s->streams[i];
1407
0
                FFStream *const sti = ffstream(st);
1408
0
                if (sti->parser && sti->need_parsing)
1409
0
                    parse_packet(s, pkt, st->index, 1);
1410
0
            }
1411
            /* all remaining packets are now in parse_queue =>
1412
             * really terminate parsing */
1413
0
            break;
1414
0
        }
1415
0
        ret = 0;
1416
0
        st  = s->streams[pkt->stream_index];
1417
0
        sti = ffstream(st);
1418
1419
0
        st->event_flags |= AVSTREAM_EVENT_FLAG_NEW_PACKETS;
1420
1421
0
        int new_extradata = !!av_packet_side_data_get(pkt->side_data, pkt->side_data_elems,
1422
0
                                                      AV_PKT_DATA_NEW_EXTRADATA);
1423
0
        if (new_extradata)
1424
0
            sti->need_context_update = 1;
1425
1426
        /* update context if required */
1427
0
        if (sti->need_context_update) {
1428
0
            if (avcodec_is_open(sti->avctx)) {
1429
0
                av_log(s, AV_LOG_DEBUG, "Demuxer context update while decoder is open, closing and trying to re-open\n");
1430
0
                ret = codec_close(sti);
1431
0
                sti->info->found_decoder = 0;
1432
0
                if (ret < 0)
1433
0
                    return ret;
1434
0
            }
1435
1436
            /* close parser, because it depends on the codec and extradata */
1437
0
            if (sti->parser &&
1438
0
                (sti->avctx->codec_id != st->codecpar->codec_id || new_extradata)) {
1439
0
                av_parser_close(sti->parser);
1440
0
                sti->parser = NULL;
1441
0
            }
1442
1443
0
            ret = avcodec_parameters_to_context(sti->avctx, st->codecpar);
1444
0
            if (ret < 0) {
1445
0
                av_packet_unref(pkt);
1446
0
                return ret;
1447
0
            }
1448
1449
0
            if (!sti->avctx->extradata) {
1450
0
                sti->extract_extradata.inited = 0;
1451
1452
0
                ret = extract_extradata(si, st, pkt);
1453
0
                if (ret < 0) {
1454
0
                    av_packet_unref(pkt);
1455
0
                    return ret;
1456
0
                }
1457
0
            }
1458
1459
0
            sti->codec_desc = avcodec_descriptor_get(sti->avctx->codec_id);
1460
1461
0
            sti->need_context_update = 0;
1462
0
        }
1463
1464
0
        if (pkt->pts != AV_NOPTS_VALUE &&
1465
0
            pkt->dts != AV_NOPTS_VALUE &&
1466
0
            pkt->pts < pkt->dts) {
1467
0
            av_log(s, AV_LOG_WARNING,
1468
0
                   "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1469
0
                   pkt->stream_index,
1470
0
                   av_ts2str(pkt->pts),
1471
0
                   av_ts2str(pkt->dts),
1472
0
                   pkt->size);
1473
0
        }
1474
0
        if (s->debug & FF_FDEBUG_TS)
1475
0
            av_log(s, AV_LOG_DEBUG,
1476
0
                   "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%"PRId64", flags=%d\n",
1477
0
                   pkt->stream_index,
1478
0
                   av_ts2str(pkt->pts),
1479
0
                   av_ts2str(pkt->dts),
1480
0
                   pkt->size, pkt->duration, pkt->flags);
1481
1482
0
        if (sti->need_parsing && !sti->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1483
0
            sti->parser = av_parser_init(st->codecpar->codec_id);
1484
0
            if (!sti->parser) {
1485
0
                av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1486
0
                       "%s, packets or times may be invalid.\n",
1487
0
                       avcodec_get_name(st->codecpar->codec_id));
1488
                /* no parser available: just output the raw packets */
1489
0
                sti->need_parsing = AVSTREAM_PARSE_NONE;
1490
0
            } else if (sti->need_parsing == AVSTREAM_PARSE_HEADERS)
1491
0
                sti->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1492
0
            else if (sti->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1493
0
                sti->parser->flags |= PARSER_FLAG_ONCE;
1494
0
            else if (sti->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1495
0
                sti->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1496
0
        }
1497
1498
0
        if (!sti->need_parsing || !sti->parser) {
1499
            /* no parsing needed: we just output the packet as is */
1500
0
            compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1501
0
            if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1502
0
                (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1503
0
                ff_reduce_index(s, st->index);
1504
0
                av_add_index_entry(st, pkt->pos, pkt->dts,
1505
0
                                   0, 0, AVINDEX_KEYFRAME);
1506
0
            }
1507
0
            got_packet = 1;
1508
0
        } else if (st->discard < AVDISCARD_ALL) {
1509
0
            if ((ret = parse_packet(s, pkt, pkt->stream_index, 0)) < 0)
1510
0
                return ret;
1511
0
            st->codecpar->sample_rate = sti->avctx->sample_rate;
1512
0
            st->codecpar->bit_rate = sti->avctx->bit_rate;
1513
0
            ret = av_channel_layout_copy(&st->codecpar->ch_layout, &sti->avctx->ch_layout);
1514
0
            if (ret < 0)
1515
0
                return ret;
1516
0
            st->codecpar->codec_id = sti->avctx->codec_id;
1517
0
        } else {
1518
            /* free packet */
1519
0
            av_packet_unref(pkt);
1520
0
        }
1521
0
        if (pkt->flags & AV_PKT_FLAG_KEY)
1522
0
            sti->skip_to_keyframe = 0;
1523
0
        if (sti->skip_to_keyframe) {
1524
0
            av_packet_unref(pkt);
1525
0
            got_packet = 0;
1526
0
        }
1527
0
    }
1528
1529
0
    if (!got_packet && fci->parse_queue.head)
1530
0
        ret = avpriv_packet_list_get(&fci->parse_queue, pkt);
1531
1532
0
    if (ret >= 0) {
1533
0
        AVStream *const st  = s->streams[pkt->stream_index];
1534
0
        FFStream *const sti = ffstream(st);
1535
0
        int discard_padding = 0;
1536
0
        if (sti->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1537
0
            int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1538
0
            int64_t sample = ts_to_samples(st, pts);
1539
0
            int64_t duration = ts_to_samples(st, pkt->duration);
1540
0
            int64_t end_sample = sample + duration;
1541
0
            if (duration > 0 && end_sample >= sti->first_discard_sample &&
1542
0
                sample < sti->last_discard_sample)
1543
0
                discard_padding = FFMIN(end_sample - sti->first_discard_sample, duration);
1544
0
        }
1545
0
        if (sti->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
1546
0
            sti->skip_samples = sti->start_skip_samples;
1547
0
        sti->skip_samples = FFMAX(0, sti->skip_samples);
1548
0
        if (sti->skip_samples || discard_padding) {
1549
0
            uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1550
0
            if (p) {
1551
0
                AV_WL32(p, sti->skip_samples);
1552
0
                AV_WL32(p + 4, discard_padding);
1553
0
                av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %u / discard %u\n",
1554
0
                       (unsigned)sti->skip_samples, (unsigned)discard_padding);
1555
0
            }
1556
0
            sti->skip_samples = 0;
1557
0
        }
1558
0
    }
1559
1560
0
    if (!fci->metafree) {
1561
0
        int metaret = av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1562
0
        if (metadata) {
1563
0
            s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1564
0
            av_dict_copy(&s->metadata, metadata, 0);
1565
0
            av_dict_free(&metadata);
1566
0
            av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
1567
0
        }
1568
0
        fci->metafree = metaret == AVERROR_OPTION_NOT_FOUND;
1569
0
    }
1570
1571
0
    if (s->debug & FF_FDEBUG_TS)
1572
0
        av_log(s, AV_LOG_DEBUG,
1573
0
               "read_frame_internal stream=%d, pts=%s, dts=%s, "
1574
0
               "size=%d, duration=%"PRId64", flags=%d\n",
1575
0
               pkt->stream_index,
1576
0
               av_ts2str(pkt->pts),
1577
0
               av_ts2str(pkt->dts),
1578
0
               pkt->size, pkt->duration, pkt->flags);
1579
1580
    /* A demuxer might have returned EOF because of an IO error, let's
1581
     * propagate this back to the user. */
1582
0
    if (ret == AVERROR_EOF && s->pb && s->pb->error < 0 && s->pb->error != AVERROR(EAGAIN))
1583
0
        ret = s->pb->error;
1584
1585
0
    return ret;
1586
0
}
1587
1588
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1589
0
{
1590
0
    FFFormatContext *const si = ffformatcontext(s);
1591
0
    const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1592
0
    int eof = 0;
1593
0
    int ret;
1594
0
    AVStream *st;
1595
1596
0
    if (!genpts) {
1597
0
        ret = si->packet_buffer.head
1598
0
              ? avpriv_packet_list_get(&si->packet_buffer, pkt)
1599
0
              : read_frame_internal(s, pkt);
1600
0
        if (ret < 0)
1601
0
            return ret;
1602
0
        goto return_packet;
1603
0
    }
1604
1605
0
    for (;;) {
1606
0
        PacketListEntry *pktl = si->packet_buffer.head;
1607
1608
0
        if (pktl) {
1609
0
            AVPacket *next_pkt = &pktl->pkt;
1610
1611
0
            if (next_pkt->dts != AV_NOPTS_VALUE) {
1612
0
                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1613
                // last dts seen for this stream. if any of packets following
1614
                // current one had no dts, we will set this to AV_NOPTS_VALUE.
1615
0
                int64_t last_dts = next_pkt->dts;
1616
0
                av_assert2(wrap_bits <= 64);
1617
0
                while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1618
0
                    if (pktl->pkt.stream_index == next_pkt->stream_index &&
1619
0
                        av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) {
1620
0
                        if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) {
1621
                            // not B-frame
1622
0
                            next_pkt->pts = pktl->pkt.dts;
1623
0
                        }
1624
0
                        if (last_dts != AV_NOPTS_VALUE) {
1625
                            // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1626
0
                            last_dts = pktl->pkt.dts;
1627
0
                        }
1628
0
                    }
1629
0
                    pktl = pktl->next;
1630
0
                }
1631
0
                if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1632
                    // Fixing the last reference frame had none pts issue (For MXF etc).
1633
                    // We only do this when
1634
                    // 1. eof.
1635
                    // 2. we are not able to resolve a pts value for current packet.
1636
                    // 3. the packets for this stream at the end of the files had valid dts.
1637
0
                    next_pkt->pts = last_dts + next_pkt->duration;
1638
0
                }
1639
0
                pktl = si->packet_buffer.head;
1640
0
            }
1641
1642
            /* read packet from packet buffer, if there is data */
1643
0
            st = s->streams[next_pkt->stream_index];
1644
0
            if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1645
0
                  next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1646
0
                ret = avpriv_packet_list_get(&si->packet_buffer, pkt);
1647
0
                goto return_packet;
1648
0
            }
1649
0
        }
1650
1651
0
        ret = read_frame_internal(s, pkt);
1652
0
        if (ret < 0) {
1653
0
            if (pktl && ret != AVERROR(EAGAIN)) {
1654
0
                eof = 1;
1655
0
                continue;
1656
0
            } else
1657
0
                return ret;
1658
0
        }
1659
1660
0
        ret = avpriv_packet_list_put(&si->packet_buffer,
1661
0
                                     pkt, NULL, 0);
1662
0
        if (ret < 0) {
1663
0
            av_packet_unref(pkt);
1664
0
            return ret;
1665
0
        }
1666
0
    }
1667
1668
0
return_packet:
1669
0
    st = s->streams[pkt->stream_index];
1670
0
    if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1671
0
        ff_reduce_index(s, st->index);
1672
0
        av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1673
0
    }
1674
1675
0
    if (is_relative(pkt->dts))
1676
0
        pkt->dts -= RELATIVE_TS_BASE;
1677
0
    if (is_relative(pkt->pts))
1678
0
        pkt->pts -= RELATIVE_TS_BASE;
1679
1680
0
    return ret;
1681
0
}
1682
1683
/**
1684
 * Return TRUE if the stream has accurate duration in any stream.
1685
 *
1686
 * @return TRUE if the stream has accurate duration for at least one component.
1687
 */
1688
static int has_duration(AVFormatContext *ic)
1689
0
{
1690
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
1691
0
        const AVStream *const st = ic->streams[i];
1692
0
        if (st->duration != AV_NOPTS_VALUE)
1693
0
            return 1;
1694
0
    }
1695
0
    if (ic->duration != AV_NOPTS_VALUE)
1696
0
        return 1;
1697
0
    return 0;
1698
0
}
1699
1700
/**
1701
 * Estimate the stream timings from the one of each components.
1702
 *
1703
 * Also computes the global bitrate if possible.
1704
 */
1705
static void update_stream_timings(AVFormatContext *ic)
1706
0
{
1707
0
    int64_t start_time, start_time1, start_time_text, end_time, end_time1, end_time_text;
1708
0
    int64_t duration, duration1, duration_text, filesize;
1709
1710
0
    start_time = INT64_MAX;
1711
0
    start_time_text = INT64_MAX;
1712
0
    end_time   = INT64_MIN;
1713
0
    end_time_text   = INT64_MIN;
1714
0
    duration   = INT64_MIN;
1715
0
    duration_text = INT64_MIN;
1716
1717
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
1718
0
        AVStream *const st = ic->streams[i];
1719
0
        int is_text = st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ||
1720
0
                      st->codecpar->codec_type == AVMEDIA_TYPE_DATA;
1721
1722
0
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1723
0
            start_time1 = av_rescale_q(st->start_time, st->time_base,
1724
0
                                       AV_TIME_BASE_Q);
1725
0
            if (is_text)
1726
0
                start_time_text = FFMIN(start_time_text, start_time1);
1727
0
            else
1728
0
                start_time = FFMIN(start_time, start_time1);
1729
0
            end_time1 = av_rescale_q_rnd(st->duration, st->time_base,
1730
0
                                         AV_TIME_BASE_Q,
1731
0
                                         AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
1732
0
            if (end_time1 != AV_NOPTS_VALUE && (end_time1 > 0 ? start_time1 <= INT64_MAX - end_time1 : start_time1 >= INT64_MIN - end_time1)) {
1733
0
                end_time1 += start_time1;
1734
0
                if (is_text)
1735
0
                    end_time_text = FFMAX(end_time_text, end_time1);
1736
0
                else
1737
0
                    end_time = FFMAX(end_time, end_time1);
1738
0
            }
1739
0
            for (AVProgram *p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
1740
0
                if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
1741
0
                    p->start_time = start_time1;
1742
0
                if (p->end_time < end_time1)
1743
0
                    p->end_time = end_time1;
1744
0
            }
1745
0
        }
1746
0
        if (st->duration != AV_NOPTS_VALUE) {
1747
0
            duration1 = av_rescale_q(st->duration, st->time_base,
1748
0
                                     AV_TIME_BASE_Q);
1749
0
            if (is_text)
1750
0
                duration_text = FFMAX(duration_text, duration1);
1751
0
            else
1752
0
                duration = FFMAX(duration, duration1);
1753
0
        }
1754
0
    }
1755
0
    if (start_time == INT64_MAX || (start_time > start_time_text && start_time - (uint64_t)start_time_text < AV_TIME_BASE))
1756
0
        start_time = start_time_text;
1757
0
    else if (start_time > start_time_text)
1758
0
        av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
1759
1760
0
    if (end_time == INT64_MIN || (end_time < end_time_text && end_time_text - (uint64_t)end_time < AV_TIME_BASE))
1761
0
        end_time = end_time_text;
1762
0
    else if (end_time < end_time_text)
1763
0
        av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream endtime %f\n", end_time_text / (float)AV_TIME_BASE);
1764
1765
0
     if (duration == INT64_MIN || (duration < duration_text && (uint64_t)duration_text - duration < AV_TIME_BASE))
1766
0
         duration = duration_text;
1767
0
     else if (duration < duration_text)
1768
0
         av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream duration %f\n", duration_text / (float)AV_TIME_BASE);
1769
1770
0
    if (start_time != INT64_MAX) {
1771
0
        ic->start_time = start_time;
1772
0
        if (end_time != INT64_MIN) {
1773
0
            if (ic->nb_programs > 1) {
1774
0
                for (unsigned i = 0; i < ic->nb_programs; i++) {
1775
0
                    AVProgram *const p = ic->programs[i];
1776
1777
0
                    if (p->start_time != AV_NOPTS_VALUE &&
1778
0
                        p->end_time > p->start_time &&
1779
0
                        p->end_time - (uint64_t)p->start_time <= INT64_MAX)
1780
0
                        duration = FFMAX(duration, p->end_time - p->start_time);
1781
0
                }
1782
0
            } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) {
1783
0
                duration = FFMAX(duration, end_time - start_time);
1784
0
            }
1785
0
        }
1786
0
    }
1787
0
    if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
1788
0
        ic->duration = duration;
1789
0
    }
1790
0
    if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) {
1791
        /* compute the bitrate */
1792
0
        double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
1793
0
                         (double) ic->duration;
1794
0
        if (bitrate >= 0 && bitrate <= INT64_MAX)
1795
0
            ic->bit_rate = bitrate;
1796
0
    }
1797
0
}
1798
1799
static void fill_all_stream_timings(AVFormatContext *ic)
1800
0
{
1801
0
    update_stream_timings(ic);
1802
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
1803
0
        AVStream *const st = ic->streams[i];
1804
1805
0
        if (st->start_time == AV_NOPTS_VALUE) {
1806
0
            if (ic->start_time != AV_NOPTS_VALUE)
1807
0
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
1808
0
                                              st->time_base);
1809
0
            if (ic->duration != AV_NOPTS_VALUE)
1810
0
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
1811
0
                                            st->time_base);
1812
0
        }
1813
0
    }
1814
0
}
1815
1816
static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1817
0
{
1818
0
    FFFormatContext *const si = ffformatcontext(ic);
1819
0
    int show_warning = 0;
1820
1821
    /* if bit_rate is already set, we believe it */
1822
0
    if (ic->bit_rate <= 0) {
1823
0
        int64_t bit_rate = 0;
1824
0
        for (unsigned i = 0; i < ic->nb_streams; i++) {
1825
0
            const AVStream *const st  = ic->streams[i];
1826
0
            const FFStream *const sti = cffstream(st);
1827
0
            if (st->codecpar->bit_rate <= 0 && sti->avctx->bit_rate > 0)
1828
0
                st->codecpar->bit_rate = sti->avctx->bit_rate;
1829
0
            if (st->codecpar->bit_rate > 0) {
1830
0
                if (INT64_MAX - st->codecpar->bit_rate < bit_rate) {
1831
0
                    bit_rate = 0;
1832
0
                    break;
1833
0
                }
1834
0
                bit_rate += st->codecpar->bit_rate;
1835
0
            } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sti->codec_info_nb_frames > 1) {
1836
                // If we have a videostream with packets but without a bitrate
1837
                // then consider the sum not known
1838
0
                bit_rate = 0;
1839
0
                break;
1840
0
            }
1841
0
        }
1842
0
        ic->bit_rate = bit_rate;
1843
0
    }
1844
1845
    /* if duration is already set, we believe it */
1846
0
    if (ic->duration == AV_NOPTS_VALUE &&
1847
0
        ic->bit_rate != 0) {
1848
0
        int64_t filesize = ic->pb ? avio_size(ic->pb) : 0;
1849
0
        if (filesize > si->data_offset) {
1850
0
            filesize -= si->data_offset;
1851
0
            for (unsigned i = 0; i < ic->nb_streams; i++) {
1852
0
                AVStream *const st = ic->streams[i];
1853
1854
0
                if (   st->time_base.num <= INT64_MAX / ic->bit_rate
1855
0
                    && st->duration == AV_NOPTS_VALUE) {
1856
0
                    st->duration = av_rescale(filesize, 8LL * st->time_base.den,
1857
0
                                          ic->bit_rate *
1858
0
                                          (int64_t) st->time_base.num);
1859
0
                    show_warning = 1;
1860
0
                }
1861
0
            }
1862
0
        }
1863
0
    }
1864
0
    if (show_warning)
1865
0
        av_log(ic, AV_LOG_WARNING,
1866
0
               "Estimating duration from bitrate, this may be inaccurate\n");
1867
0
}
1868
1869
0
#define DURATION_DEFAULT_MAX_READ_SIZE 250000LL
1870
0
#define DURATION_DEFAULT_MAX_RETRY 6
1871
0
#define DURATION_MAX_RETRY 1
1872
1873
/* only usable for MPEG-PS streams */
1874
static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1875
0
{
1876
0
    FFFormatContext *const si = ffformatcontext(ic);
1877
0
    AVPacket *const pkt = si->pkt;
1878
0
    int num, den, read_size, ret;
1879
0
    int64_t duration_max_read_size = ic->duration_probesize ? ic->duration_probesize >> DURATION_MAX_RETRY : DURATION_DEFAULT_MAX_READ_SIZE;
1880
0
    int duration_max_retry = ic->duration_probesize ? DURATION_MAX_RETRY : DURATION_DEFAULT_MAX_RETRY;
1881
0
    int found_duration = 0;
1882
0
    int is_end;
1883
0
    int64_t filesize, offset, duration;
1884
0
    int retry = 0;
1885
1886
    /* flush packet queue */
1887
0
    ff_flush_packet_queue(ic);
1888
1889
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
1890
0
        AVStream *const st  = ic->streams[i];
1891
0
        FFStream *const sti = ffstream(st);
1892
1893
0
        if (st->start_time == AV_NOPTS_VALUE &&
1894
0
            sti->first_dts == AV_NOPTS_VALUE &&
1895
0
            st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN)
1896
0
            av_log(ic, AV_LOG_WARNING,
1897
0
                   "start time for stream %d is not set in estimate_timings_from_pts\n", i);
1898
1899
0
        if (sti->parser) {
1900
0
            av_parser_close(sti->parser);
1901
0
            sti->parser = NULL;
1902
0
        }
1903
0
    }
1904
1905
0
    if (ic->skip_estimate_duration_from_pts) {
1906
0
        av_log(ic, AV_LOG_INFO, "Skipping duration calculation in estimate_timings_from_pts\n");
1907
0
        goto skip_duration_calc;
1908
0
    }
1909
1910
0
    av_opt_set_int(ic, "skip_changes", 1, AV_OPT_SEARCH_CHILDREN);
1911
    /* estimate the end time (duration) */
1912
    /* XXX: may need to support wrapping */
1913
0
    filesize = ic->pb ? avio_size(ic->pb) : 0;
1914
0
    do {
1915
0
        is_end = found_duration;
1916
0
        offset = filesize - (duration_max_read_size << retry);
1917
0
        if (offset < 0)
1918
0
            offset = 0;
1919
1920
0
        avio_seek(ic->pb, offset, SEEK_SET);
1921
0
        read_size = 0;
1922
0
        for (;;) {
1923
0
            AVStream *st;
1924
0
            FFStream *sti;
1925
0
            if (read_size >= duration_max_read_size << (FFMAX(retry - 1, 0)))
1926
0
                break;
1927
1928
0
            do {
1929
0
                ret = ff_read_packet(ic, pkt);
1930
0
            } while (ret == AVERROR(EAGAIN));
1931
0
            if (ret != 0)
1932
0
                break;
1933
0
            read_size += pkt->size;
1934
0
            st         = ic->streams[pkt->stream_index];
1935
0
            sti        = ffstream(st);
1936
0
            if (pkt->pts != AV_NOPTS_VALUE &&
1937
0
                (st->start_time != AV_NOPTS_VALUE ||
1938
0
                 sti->first_dts != AV_NOPTS_VALUE)) {
1939
0
                if (pkt->duration == 0) {
1940
0
                    compute_frame_duration(ic, &num, &den, st, sti->parser, pkt);
1941
0
                    if (den && num) {
1942
0
                        pkt->duration = av_rescale_rnd(1,
1943
0
                                           num * (int64_t) st->time_base.den,
1944
0
                                           den * (int64_t) st->time_base.num,
1945
0
                                           AV_ROUND_DOWN);
1946
0
                    }
1947
0
                }
1948
0
                duration = pkt->pts + pkt->duration;
1949
0
                found_duration = 1;
1950
0
                if (st->start_time != AV_NOPTS_VALUE)
1951
0
                    duration -= st->start_time;
1952
0
                else
1953
0
                    duration -= sti->first_dts;
1954
0
                if (duration > 0) {
1955
0
                    if (st->duration == AV_NOPTS_VALUE || sti->info->last_duration<= 0 ||
1956
0
                        (st->duration < duration && FFABS(duration - sti->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
1957
0
                        st->duration = duration;
1958
0
                    sti->info->last_duration = duration;
1959
0
                }
1960
0
            }
1961
0
            av_packet_unref(pkt);
1962
0
        }
1963
1964
        /* check if all audio/video streams have valid duration */
1965
0
        if (!is_end) {
1966
0
            is_end = 1;
1967
0
            for (unsigned i = 0; i < ic->nb_streams; i++) {
1968
0
                const AVStream *const st = ic->streams[i];
1969
0
                switch (st->codecpar->codec_type) {
1970
0
                    case AVMEDIA_TYPE_VIDEO:
1971
0
                    case AVMEDIA_TYPE_AUDIO:
1972
0
                        if (st->duration == AV_NOPTS_VALUE)
1973
0
                            is_end = 0;
1974
0
                }
1975
0
            }
1976
0
        }
1977
0
    } while (!is_end &&
1978
0
             offset &&
1979
0
             ++retry <= duration_max_retry);
1980
1981
0
    av_opt_set_int(ic, "skip_changes", 0, AV_OPT_SEARCH_CHILDREN);
1982
1983
    /* warn about audio/video streams which duration could not be estimated */
1984
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
1985
0
        const AVStream *const st  = ic->streams[i];
1986
0
        const FFStream *const sti = cffstream(st);
1987
1988
0
        if (st->duration == AV_NOPTS_VALUE) {
1989
0
            switch (st->codecpar->codec_type) {
1990
0
            case AVMEDIA_TYPE_VIDEO:
1991
0
            case AVMEDIA_TYPE_AUDIO:
1992
0
                if (st->start_time != AV_NOPTS_VALUE || sti->first_dts != AV_NOPTS_VALUE) {
1993
0
                    av_log(ic, AV_LOG_WARNING, "stream %d : no PTS found at end of file, duration not set\n", i);
1994
0
                } else
1995
0
                    av_log(ic, AV_LOG_WARNING, "stream %d : no TS found at start of file, duration not set\n", i);
1996
0
            }
1997
0
        }
1998
0
    }
1999
0
skip_duration_calc:
2000
0
    fill_all_stream_timings(ic);
2001
2002
0
    avio_seek(ic->pb, old_offset, SEEK_SET);
2003
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
2004
0
        AVStream *const st  = ic->streams[i];
2005
0
        FFStream *const sti = ffstream(st);
2006
2007
0
        sti->cur_dts     = sti->first_dts;
2008
0
        sti->last_IP_pts = AV_NOPTS_VALUE;
2009
0
        sti->last_dts_for_order_check = AV_NOPTS_VALUE;
2010
0
        for (int j = 0; j < MAX_REORDER_DELAY + 1; j++)
2011
0
            sti->pts_buffer[j] = AV_NOPTS_VALUE;
2012
0
    }
2013
0
}
2014
2015
/* 1:1 map to AVDurationEstimationMethod */
2016
static const char *const duration_name[] = {
2017
    [AVFMT_DURATION_FROM_PTS]     = "pts",
2018
    [AVFMT_DURATION_FROM_STREAM]  = "stream",
2019
    [AVFMT_DURATION_FROM_BITRATE] = "bit rate",
2020
};
2021
2022
static const char *duration_estimate_name(enum AVDurationEstimationMethod method)
2023
0
{
2024
0
    return duration_name[method];
2025
0
}
2026
2027
static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2028
0
{
2029
0
    int64_t file_size;
2030
2031
    /* get the file size, if possible */
2032
0
    if (ic->iformat->flags & AVFMT_NOFILE) {
2033
0
        file_size = 0;
2034
0
    } else {
2035
0
        file_size = avio_size(ic->pb);
2036
0
        file_size = FFMAX(0, file_size);
2037
0
    }
2038
2039
0
    if ((!strcmp(ic->iformat->name, "mpeg") ||
2040
0
         !strcmp(ic->iformat->name, "mpegts")) &&
2041
0
        file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
2042
        /* get accurate estimate from the PTSes */
2043
0
        estimate_timings_from_pts(ic, old_offset);
2044
0
        ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2045
0
    } else if (has_duration(ic)) {
2046
        /* at least one component has timings - we use them for all
2047
         * the components */
2048
0
        fill_all_stream_timings(ic);
2049
        /* nut demuxer estimate the duration from PTS */
2050
0
        if (!strcmp(ic->iformat->name, "nut"))
2051
0
            ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2052
0
        else
2053
0
            ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2054
0
    } else {
2055
        /* less precise: use bitrate info */
2056
0
        estimate_timings_from_bit_rate(ic);
2057
0
        ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2058
0
    }
2059
0
    update_stream_timings(ic);
2060
2061
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
2062
0
        AVStream *const st = ic->streams[i];
2063
0
        if (st->time_base.den)
2064
0
            av_log(ic, AV_LOG_TRACE, "stream %u: start_time: %s duration: %s\n", i,
2065
0
                   av_ts2timestr(st->start_time, &st->time_base),
2066
0
                   av_ts2timestr(st->duration, &st->time_base));
2067
0
    }
2068
0
    av_log(ic, AV_LOG_TRACE,
2069
0
           "format: start_time: %s duration: %s (estimate from %s) bitrate=%"PRId64" kb/s\n",
2070
0
           av_ts2timestr(ic->start_time, &AV_TIME_BASE_Q),
2071
0
           av_ts2timestr(ic->duration, &AV_TIME_BASE_Q),
2072
0
           duration_estimate_name(ic->duration_estimation_method),
2073
0
           (int64_t)ic->bit_rate / 1000);
2074
0
}
2075
2076
static int determinable_frame_size(const AVCodecContext *avctx)
2077
0
{
2078
0
    switch(avctx->codec_id) {
2079
0
    case AV_CODEC_ID_MP1:
2080
0
    case AV_CODEC_ID_MP2:
2081
0
    case AV_CODEC_ID_MP3:
2082
0
    case AV_CODEC_ID_CODEC2:
2083
0
        return 1;
2084
0
    }
2085
2086
0
    return 0;
2087
0
}
2088
2089
static int has_codec_parameters(const AVStream *st, const char **errmsg_ptr)
2090
0
{
2091
0
    const FFStream *const sti = cffstream(st);
2092
0
    const AVCodecContext *const avctx = sti->avctx;
2093
2094
0
#define FAIL(errmsg) do {                                         \
2095
0
        if (errmsg_ptr)                                           \
2096
0
            *errmsg_ptr = errmsg;                                 \
2097
0
        return 0;                                                 \
2098
0
    } while (0)
2099
2100
0
    if (   avctx->codec_id == AV_CODEC_ID_NONE
2101
0
        && avctx->codec_type != AVMEDIA_TYPE_DATA)
2102
0
        FAIL("unknown codec");
2103
0
    switch (avctx->codec_type) {
2104
0
    case AVMEDIA_TYPE_AUDIO:
2105
0
        if (!avctx->frame_size && determinable_frame_size(avctx))
2106
0
            FAIL("unspecified frame size");
2107
0
        if (sti->info->found_decoder >= 0 &&
2108
0
            avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2109
0
            FAIL("unspecified sample format");
2110
0
        if (!avctx->sample_rate)
2111
0
            FAIL("unspecified sample rate");
2112
0
        if (!avctx->ch_layout.nb_channels)
2113
0
            FAIL("unspecified number of channels");
2114
0
        if (sti->info->found_decoder >= 0 && !sti->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
2115
0
            FAIL("no decodable DTS frames");
2116
0
        break;
2117
0
    case AVMEDIA_TYPE_VIDEO:
2118
0
        if (!avctx->width)
2119
0
            FAIL("unspecified size");
2120
0
        if (sti->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2121
0
            FAIL("unspecified pixel format");
2122
0
        if (st->codecpar->codec_id == AV_CODEC_ID_RV30 || st->codecpar->codec_id == AV_CODEC_ID_RV40)
2123
0
            if (!st->sample_aspect_ratio.num && !st->codecpar->sample_aspect_ratio.num && !sti->codec_info_nb_frames)
2124
0
                FAIL("no frame in rv30/40 and no sar");
2125
0
        break;
2126
0
    case AVMEDIA_TYPE_SUBTITLE:
2127
0
        if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
2128
0
            FAIL("unspecified size");
2129
0
        break;
2130
0
    case AVMEDIA_TYPE_DATA:
2131
0
        if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
2132
0
    }
2133
2134
0
    return 1;
2135
0
}
2136
2137
/* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2138
static int try_decode_frame(AVFormatContext *s, AVStream *st,
2139
                            const AVPacket *pkt, AVDictionary **options)
2140
0
{
2141
0
    FFStream *const sti = ffstream(st);
2142
0
    AVCodecContext *const avctx = sti->avctx;
2143
0
    const AVCodec *codec;
2144
0
    int got_picture = 1, ret = 0;
2145
0
    AVFrame *frame = av_frame_alloc();
2146
0
    AVSubtitle subtitle;
2147
0
    int do_skip_frame = 0;
2148
0
    enum AVDiscard skip_frame;
2149
0
    int pkt_to_send = pkt->size > 0;
2150
2151
0
    if (!frame)
2152
0
        return AVERROR(ENOMEM);
2153
2154
0
    if (!avcodec_is_open(avctx) &&
2155
0
        sti->info->found_decoder <= 0 &&
2156
0
        (st->codecpar->codec_id != -sti->info->found_decoder || !st->codecpar->codec_id)) {
2157
0
        AVDictionary *thread_opt = NULL;
2158
2159
0
        codec = find_probe_decoder(s, st, st->codecpar->codec_id);
2160
2161
0
        if (!codec) {
2162
0
            sti->info->found_decoder = -st->codecpar->codec_id;
2163
0
            ret                     = -1;
2164
0
            goto fail;
2165
0
        }
2166
2167
        /* Force thread count to 1 since the H.264 decoder will not extract
2168
         * SPS and PPS to extradata during multi-threaded decoding. */
2169
0
        av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2170
        /* Force lowres to 0. The decoder might reduce the video size by the
2171
         * lowres factor, and we don't want that propagated to the stream's
2172
         * codecpar */
2173
0
        av_dict_set(options ? options : &thread_opt, "lowres", "0", 0);
2174
0
        if (s->codec_whitelist)
2175
0
            av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
2176
0
        ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
2177
0
        if (!options)
2178
0
            av_dict_free(&thread_opt);
2179
0
        if (ret < 0) {
2180
0
            sti->info->found_decoder = -avctx->codec_id;
2181
0
            goto fail;
2182
0
        }
2183
0
        sti->info->found_decoder = 1;
2184
0
    } else if (!sti->info->found_decoder)
2185
0
        sti->info->found_decoder = 1;
2186
2187
0
    if (sti->info->found_decoder < 0) {
2188
0
        ret = -1;
2189
0
        goto fail;
2190
0
    }
2191
2192
0
    if (avpriv_codec_get_cap_skip_frame_fill_param(avctx->codec)) {
2193
0
        do_skip_frame = 1;
2194
0
        skip_frame = avctx->skip_frame;
2195
0
        avctx->skip_frame = AVDISCARD_ALL;
2196
0
    }
2197
2198
0
    while ((pkt_to_send || (!pkt->data && got_picture)) &&
2199
0
           ret >= 0 &&
2200
0
           (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
2201
0
            (!sti->codec_info_nb_frames &&
2202
0
             (avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
2203
0
        got_picture = 0;
2204
0
        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
2205
0
            avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
2206
0
            ret = avcodec_send_packet(avctx, pkt);
2207
0
            if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
2208
0
                break;
2209
0
            if (ret >= 0)
2210
0
                pkt_to_send = 0;
2211
0
            ret = avcodec_receive_frame(avctx, frame);
2212
0
            if (ret >= 0)
2213
0
                got_picture = 1;
2214
0
            if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
2215
0
                ret = 0;
2216
0
        } else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2217
0
            ret = avcodec_decode_subtitle2(avctx, &subtitle,
2218
0
                                           &got_picture, pkt);
2219
0
            if (got_picture)
2220
0
                avsubtitle_free(&subtitle);
2221
0
            if (ret >= 0)
2222
0
                pkt_to_send = 0;
2223
0
        }
2224
0
        if (ret >= 0) {
2225
0
            if (got_picture)
2226
0
                sti->nb_decoded_frames++;
2227
0
            ret       = got_picture;
2228
0
        }
2229
0
    }
2230
2231
0
fail:
2232
0
    if (do_skip_frame) {
2233
0
        avctx->skip_frame = skip_frame;
2234
0
    }
2235
2236
0
    av_frame_free(&frame);
2237
0
    return ret;
2238
0
}
2239
2240
static int chapter_start_cmp(const void *p1, const void *p2)
2241
0
{
2242
0
    const AVChapter *const ch1 = *(AVChapter**)p1;
2243
0
    const AVChapter *const ch2 = *(AVChapter**)p2;
2244
0
    int delta = av_compare_ts(ch1->start, ch1->time_base, ch2->start, ch2->time_base);
2245
0
    if (delta)
2246
0
        return delta;
2247
0
    return FFDIFFSIGN(ch1->id, ch2->id);
2248
0
}
2249
2250
static int compute_chapters_end(AVFormatContext *s)
2251
0
{
2252
0
    int64_t max_time = 0;
2253
0
    AVChapter **timetable;
2254
2255
0
    if (!s->nb_chapters)
2256
0
        return 0;
2257
2258
0
    if (s->duration > 0 && s->start_time < INT64_MAX - s->duration)
2259
0
        max_time = s->duration +
2260
0
                       ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2261
2262
0
    timetable = av_memdup(s->chapters, s->nb_chapters * sizeof(*timetable));
2263
0
    if (!timetable)
2264
0
        return AVERROR(ENOMEM);
2265
0
    qsort(timetable, s->nb_chapters, sizeof(*timetable), chapter_start_cmp);
2266
2267
0
    for (unsigned i = 0; i < s->nb_chapters; i++)
2268
0
        if (timetable[i]->end == AV_NOPTS_VALUE) {
2269
0
            AVChapter *const ch = timetable[i];
2270
0
            int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
2271
0
                                                  ch->time_base)
2272
0
                                   : INT64_MAX;
2273
2274
0
            if (i + 1 < s->nb_chapters) {
2275
0
                const AVChapter *const ch1 = timetable[i + 1];
2276
0
                int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
2277
0
                                                  ch->time_base);
2278
0
                if (next_start > ch->start && next_start < end)
2279
0
                    end = next_start;
2280
0
            }
2281
0
            ch->end = (end == INT64_MAX || end < ch->start) ? ch->start : end;
2282
0
        }
2283
0
    av_free(timetable);
2284
0
    return 0;
2285
0
}
2286
2287
static int get_std_framerate(int i)
2288
0
{
2289
0
    if (i < 30*12)
2290
0
        return (i + 1) * 1001;
2291
0
    i -= 30*12;
2292
2293
0
    if (i < 30)
2294
0
        return (i + 31) * 1001 * 12;
2295
0
    i -= 30;
2296
2297
0
    if (i < 3)
2298
0
        return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;
2299
2300
0
    i -= 3;
2301
2302
0
    return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
2303
0
}
2304
2305
/* Is the time base unreliable?
2306
 * This is a heuristic to balance between quick acceptance of the values in
2307
 * the headers vs. some extra checks.
2308
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2309
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2310
 * And there are "variable" fps files this needs to detect as well. */
2311
static int tb_unreliable(AVFormatContext *ic, AVStream *st)
2312
0
{
2313
0
    FFStream *const sti = ffstream(st);
2314
0
    const AVCodecDescriptor *desc = sti->codec_desc;
2315
0
    AVCodecContext *c = sti->avctx;
2316
0
    AVRational mul = (AVRational){ desc && (desc->props & AV_CODEC_PROP_FIELDS) ? 2 : 1, 1 };
2317
0
    AVRational time_base = c->framerate.num ? av_inv_q(av_mul_q(c->framerate, mul))
2318
                                            /* NOHEADER check added to not break existing behavior */
2319
0
                                            : (((ic->ctx_flags & AVFMTCTX_NOHEADER) ||
2320
0
                                                st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) ? (AVRational){0, 1}
2321
0
                                                                                                : st->time_base);
2322
2323
0
    if (time_base.den >= 101LL * time_base.num ||
2324
0
        time_base.den <    5LL * time_base.num ||
2325
        // c->codec_tag == AV_RL32("DIVX") ||
2326
        // c->codec_tag == AV_RL32("XVID") ||
2327
0
        c->codec_tag == AV_RL32("mp4v") ||
2328
0
        c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
2329
0
        c->codec_id == AV_CODEC_ID_GIF ||
2330
0
        c->codec_id == AV_CODEC_ID_HEVC ||
2331
0
        c->codec_id == AV_CODEC_ID_H264)
2332
0
        return 1;
2333
0
    return 0;
2334
0
}
2335
2336
int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
2337
0
{
2338
0
    FFStream *const sti = ffstream(st);
2339
0
    FFStreamInfo *info = sti->info;
2340
0
    int64_t last = info->last_dts;
2341
2342
0
    if (   ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
2343
0
       && ts - (uint64_t)last < INT64_MAX) {
2344
0
        double dts = (is_relative(ts) ?  ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
2345
0
        int64_t duration = ts - last;
2346
2347
0
        if (!info->duration_error)
2348
0
            info->duration_error = av_mallocz(sizeof(info->duration_error[0])*2);
2349
0
        if (!info->duration_error)
2350
0
            return AVERROR(ENOMEM);
2351
2352
//         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2353
//             av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
2354
0
        for (int i = 0; i < MAX_STD_TIMEBASES; i++) {
2355
0
            if (info->duration_error[0][1][i] < 1e10) {
2356
0
                int framerate = get_std_framerate(i);
2357
0
                double sdts = dts*framerate/(1001*12);
2358
0
                for (int j = 0; j < 2; j++) {
2359
0
                    int64_t ticks = llrint(sdts+j*0.5);
2360
0
                    double error = sdts - ticks + j*0.5;
2361
0
                    info->duration_error[j][0][i] += error;
2362
0
                    info->duration_error[j][1][i] += error*error;
2363
0
                }
2364
0
            }
2365
0
        }
2366
0
        if (info->rfps_duration_sum <= INT64_MAX - duration) {
2367
0
            info->duration_count++;
2368
0
            info->rfps_duration_sum += duration;
2369
0
        }
2370
2371
0
        if (info->duration_count % 10 == 0) {
2372
0
            int n = info->duration_count;
2373
0
            for (int i = 0; i < MAX_STD_TIMEBASES; i++) {
2374
0
                if (info->duration_error[0][1][i] < 1e10) {
2375
0
                    double a0     = info->duration_error[0][0][i] / n;
2376
0
                    double error0 = info->duration_error[0][1][i] / n - a0*a0;
2377
0
                    double a1     = info->duration_error[1][0][i] / n;
2378
0
                    double error1 = info->duration_error[1][1][i] / n - a1*a1;
2379
0
                    if (error0 > 0.04 && error1 > 0.04) {
2380
0
                        info->duration_error[0][1][i] = 2e10;
2381
0
                        info->duration_error[1][1][i] = 2e10;
2382
0
                    }
2383
0
                }
2384
0
            }
2385
0
        }
2386
2387
        // ignore the first 4 values, they might have some random jitter
2388
0
        if (info->duration_count > 3 && is_relative(ts) == is_relative(last))
2389
0
            info->duration_gcd = av_gcd(info->duration_gcd, duration);
2390
0
    }
2391
0
    if (ts != AV_NOPTS_VALUE)
2392
0
        info->last_dts = ts;
2393
2394
0
    return 0;
2395
0
}
2396
2397
void ff_rfps_calculate(AVFormatContext *ic)
2398
0
{
2399
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
2400
0
        AVStream *const st  = ic->streams[i];
2401
0
        FFStream *const sti = ffstream(st);
2402
2403
0
        if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
2404
0
            continue;
2405
        // the check for tb_unreliable() is not completely correct, since this is not about handling
2406
        // an unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2407
        // ipmovie.c produces.
2408
0
        if (tb_unreliable(ic, st) && sti->info->duration_count > 15 && sti->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num &&
2409
0
            sti->info->duration_gcd < INT64_MAX / st->time_base.num)
2410
0
            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * sti->info->duration_gcd, INT_MAX);
2411
0
        if (sti->info->duration_count > 1 && !st->r_frame_rate.num
2412
0
            && tb_unreliable(ic, st)) {
2413
0
            int num = 0;
2414
0
            double best_error = 0.01;
2415
0
            AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
2416
2417
0
            for (int j = 0; j < MAX_STD_TIMEBASES; j++) {
2418
0
                if (sti->info->codec_info_duration &&
2419
0
                    sti->info->codec_info_duration*av_q2d(st->time_base) < (1001*11.5)/get_std_framerate(j))
2420
0
                    continue;
2421
0
                if (!sti->info->codec_info_duration && get_std_framerate(j) < 1001*12)
2422
0
                    continue;
2423
2424
0
                if (av_q2d(st->time_base) * sti->info->rfps_duration_sum / sti->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
2425
0
                    continue;
2426
2427
0
                for (int k = 0; k < 2; k++) {
2428
0
                    int n = sti->info->duration_count;
2429
0
                    double a = sti->info->duration_error[k][0][j] / n;
2430
0
                    double error = sti->info->duration_error[k][1][j]/n - a*a;
2431
2432
0
                    if (error < best_error && best_error> 0.000000001) {
2433
0
                        best_error= error;
2434
0
                        num = get_std_framerate(j);
2435
0
                    }
2436
0
                    if (error < 0.02)
2437
0
                        av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
2438
0
                }
2439
0
            }
2440
            // do not increase frame rate by more than 1 % in order to match a standard rate.
2441
0
            if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
2442
0
                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2443
0
        }
2444
0
        if (   !st->avg_frame_rate.num
2445
0
            && st->r_frame_rate.num && sti->info->rfps_duration_sum
2446
0
            && sti->info->codec_info_duration <= 0
2447
0
            && sti->info->duration_count > 2
2448
0
            && fabs(1.0 / (av_q2d(st->r_frame_rate) * av_q2d(st->time_base)) - sti->info->rfps_duration_sum / (double)sti->info->duration_count) <= 1.0
2449
0
            ) {
2450
0
            av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
2451
0
            st->avg_frame_rate = st->r_frame_rate;
2452
0
        }
2453
2454
0
        av_freep(&sti->info->duration_error);
2455
0
        sti->info->last_dts = AV_NOPTS_VALUE;
2456
0
        sti->info->duration_count = 0;
2457
0
        sti->info->rfps_duration_sum = 0;
2458
0
    }
2459
0
}
2460
2461
static int extract_extradata_check(AVStream *st)
2462
0
{
2463
0
    const AVBitStreamFilter *const f = av_bsf_get_by_name("extract_extradata");
2464
0
    if (!f)
2465
0
        return 0;
2466
2467
0
    if (f->codec_ids) {
2468
0
        const enum AVCodecID *ids;
2469
0
        for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
2470
0
            if (*ids == st->codecpar->codec_id)
2471
0
                return 1;
2472
0
    }
2473
2474
0
    return 0;
2475
0
}
2476
2477
static int extract_extradata_init(AVStream *st)
2478
0
{
2479
0
    FFStream *const sti = ffstream(st);
2480
0
    const AVBitStreamFilter *f;
2481
0
    int ret;
2482
2483
0
    f = av_bsf_get_by_name("extract_extradata");
2484
0
    if (!f)
2485
0
        goto finish;
2486
2487
    /* check that the codec id is supported */
2488
0
    ret = extract_extradata_check(st);
2489
0
    if (!ret)
2490
0
        goto finish;
2491
2492
0
    av_bsf_free(&sti->extract_extradata.bsf);
2493
0
    ret = av_bsf_alloc(f, &sti->extract_extradata.bsf);
2494
0
    if (ret < 0)
2495
0
        return ret;
2496
2497
0
    ret = avcodec_parameters_copy(sti->extract_extradata.bsf->par_in,
2498
0
                                  st->codecpar);
2499
0
    if (ret < 0)
2500
0
        goto fail;
2501
2502
0
    sti->extract_extradata.bsf->time_base_in = st->time_base;
2503
2504
0
    ret = av_bsf_init(sti->extract_extradata.bsf);
2505
0
    if (ret < 0)
2506
0
        goto fail;
2507
2508
0
finish:
2509
0
    sti->extract_extradata.inited = 1;
2510
2511
0
    return 0;
2512
0
fail:
2513
0
    av_bsf_free(&sti->extract_extradata.bsf);
2514
0
    return ret;
2515
0
}
2516
2517
static int extract_extradata(FFFormatContext *si, AVStream *st, const AVPacket *pkt)
2518
0
{
2519
0
    FFStream *const sti = ffstream(st);
2520
0
    AVPacket *const pkt_ref = si->parse_pkt;
2521
0
    int ret;
2522
2523
0
    if (!sti->extract_extradata.inited) {
2524
0
        ret = extract_extradata_init(st);
2525
0
        if (ret < 0)
2526
0
            return ret;
2527
0
    }
2528
2529
0
    if (sti->extract_extradata.inited && !sti->extract_extradata.bsf)
2530
0
        return 0;
2531
2532
0
    ret = av_packet_ref(pkt_ref, pkt);
2533
0
    if (ret < 0)
2534
0
        return ret;
2535
2536
0
    ret = av_bsf_send_packet(sti->extract_extradata.bsf, pkt_ref);
2537
0
    if (ret < 0) {
2538
0
        av_packet_unref(pkt_ref);
2539
0
        return ret;
2540
0
    }
2541
2542
0
    while (ret >= 0 && !sti->avctx->extradata) {
2543
0
        ret = av_bsf_receive_packet(sti->extract_extradata.bsf, pkt_ref);
2544
0
        if (ret < 0) {
2545
0
            if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
2546
0
                return ret;
2547
0
            continue;
2548
0
        }
2549
2550
0
        for (int i = 0; i < pkt_ref->side_data_elems; i++) {
2551
0
            AVPacketSideData *const side_data = &pkt_ref->side_data[i];
2552
0
            if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) {
2553
0
                sti->avctx->extradata      = side_data->data;
2554
0
                sti->avctx->extradata_size = side_data->size;
2555
0
                side_data->data = NULL;
2556
0
                side_data->size = 0;
2557
0
                break;
2558
0
            }
2559
0
        }
2560
0
        av_packet_unref(pkt_ref);
2561
0
    }
2562
2563
0
    return 0;
2564
0
}
2565
2566
static int parameters_from_context(AVFormatContext *ic, AVCodecParameters *par,
2567
                                   const AVCodecContext *avctx)
2568
0
{
2569
0
    AVCodecParameters *par_tmp;
2570
0
    int ret;
2571
2572
0
    par_tmp = avcodec_parameters_alloc();
2573
0
    if (!par_tmp)
2574
0
        return AVERROR(ENOMEM);
2575
2576
0
    ret = avcodec_parameters_copy(par_tmp, par);
2577
0
    if (ret < 0)
2578
0
        goto fail;
2579
2580
0
    ret = avcodec_parameters_from_context(par, avctx);
2581
0
    if (ret < 0)
2582
0
        goto fail;
2583
2584
    /* Restore some values if they are signaled at the container level
2585
     * given they may have been replaced by codec level values as read
2586
     * internally by avformat_find_stream_info().
2587
     */
2588
0
    if (par_tmp->color_range != AVCOL_RANGE_UNSPECIFIED)
2589
0
        par->color_range = par_tmp->color_range;
2590
0
    if (par_tmp->color_primaries != AVCOL_PRI_UNSPECIFIED ||
2591
0
        par_tmp->color_trc != AVCOL_TRC_UNSPECIFIED ||
2592
0
        par_tmp->color_space != AVCOL_SPC_UNSPECIFIED) {
2593
0
        par->color_primaries = par_tmp->color_primaries;
2594
0
        par->color_trc = par_tmp->color_trc;
2595
0
        par->color_space = par_tmp->color_space;
2596
0
    }
2597
0
    if (par_tmp->chroma_location != AVCHROMA_LOC_UNSPECIFIED)
2598
0
        par->chroma_location = par_tmp->chroma_location;
2599
2600
0
    ret = 0;
2601
0
fail:
2602
0
    avcodec_parameters_free(&par_tmp);
2603
2604
0
    return ret;
2605
0
}
2606
2607
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2608
0
{
2609
0
    FFFormatContext *const si = ffformatcontext(ic);
2610
0
    int count = 0, ret = 0, err;
2611
0
    int64_t read_size;
2612
0
    AVPacket *pkt1 = si->pkt;
2613
0
    int64_t old_offset  = avio_tell(ic->pb);
2614
    // new streams might appear, no options for those
2615
0
    int orig_nb_streams = ic->nb_streams;
2616
0
    int flush_codecs;
2617
0
    int64_t max_analyze_duration = ic->max_analyze_duration;
2618
0
    int64_t max_stream_analyze_duration;
2619
0
    int64_t max_subtitle_analyze_duration;
2620
0
    int64_t probesize = ic->probesize;
2621
0
    int eof_reached = 0;
2622
2623
0
    flush_codecs = probesize > 0;
2624
2625
0
    av_opt_set_int(ic, "skip_clear", 1, AV_OPT_SEARCH_CHILDREN);
2626
2627
0
    max_stream_analyze_duration = max_analyze_duration;
2628
0
    max_subtitle_analyze_duration = max_analyze_duration;
2629
0
    if (!max_analyze_duration) {
2630
0
        max_stream_analyze_duration =
2631
0
        max_analyze_duration        = 5*AV_TIME_BASE;
2632
0
        max_subtitle_analyze_duration = 30*AV_TIME_BASE;
2633
0
        if (!strcmp(ic->iformat->name, "flv"))
2634
0
            max_stream_analyze_duration = 90*AV_TIME_BASE;
2635
0
        if (!strcmp(ic->iformat->name, "mpeg") || !strcmp(ic->iformat->name, "mpegts"))
2636
0
            max_stream_analyze_duration = 7*AV_TIME_BASE;
2637
0
    }
2638
2639
0
    if (ic->pb) {
2640
0
        FFIOContext *const ctx = ffiocontext(ic->pb);
2641
0
        av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
2642
0
               avio_tell(ic->pb), ctx->bytes_read, ctx->seek_count, ic->nb_streams);
2643
0
    }
2644
2645
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
2646
0
        const AVCodec *codec;
2647
0
        AVDictionary *thread_opt = NULL;
2648
0
        AVStream *const st  = ic->streams[i];
2649
0
        FFStream *const sti = ffstream(st);
2650
0
        AVCodecContext *const avctx = sti->avctx;
2651
2652
        /* check if the caller has overridden the codec id */
2653
        // only for the split stuff
2654
0
        if (!sti->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && sti->request_probe <= 0) {
2655
0
            sti->parser = av_parser_init(st->codecpar->codec_id);
2656
0
            if (sti->parser) {
2657
0
                if (sti->need_parsing == AVSTREAM_PARSE_HEADERS) {
2658
0
                    sti->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2659
0
                } else if (sti->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
2660
0
                    sti->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
2661
0
                }
2662
0
            } else if (sti->need_parsing) {
2663
0
                av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
2664
0
                       "%s, packets or times may be invalid.\n",
2665
0
                       avcodec_get_name(st->codecpar->codec_id));
2666
0
            }
2667
0
        }
2668
2669
0
        ret = avcodec_parameters_to_context(avctx, st->codecpar);
2670
0
        if (ret < 0)
2671
0
            goto find_stream_info_err;
2672
0
        if (sti->request_probe <= 0)
2673
0
            sti->avctx_inited = 1;
2674
2675
0
        codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
2676
2677
        /* Force thread count to 1 since the H.264 decoder will not extract
2678
         * SPS and PPS to extradata during multi-threaded decoding. */
2679
0
        av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2680
        /* Force lowres to 0. The decoder might reduce the video size by the
2681
         * lowres factor, and we don't want that propagated to the stream's
2682
         * codecpar */
2683
0
        av_dict_set(options ? &options[i] : &thread_opt, "lowres", "0", 0);
2684
2685
0
        if (ic->codec_whitelist)
2686
0
            av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
2687
2688
        // Try to just open decoders, in case this is enough to get parameters.
2689
        // Also ensure that subtitle_header is properly set.
2690
0
        if (!has_codec_parameters(st, NULL) && sti->request_probe <= 0 ||
2691
0
            st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2692
0
            if (codec && !avctx->codec)
2693
0
                if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
2694
0
                    av_log(ic, AV_LOG_WARNING,
2695
0
                           "Failed to open codec in %s\n", __func__);
2696
0
        }
2697
0
        if (!options)
2698
0
            av_dict_free(&thread_opt);
2699
0
    }
2700
2701
0
    read_size = 0;
2702
0
    for (;;) {
2703
0
        const AVPacket *pkt;
2704
0
        AVStream *st;
2705
0
        FFStream *sti;
2706
0
        AVCodecContext *avctx;
2707
0
        int analyzed_all_streams;
2708
0
        unsigned i;
2709
0
        if (ff_check_interrupt(&ic->interrupt_callback)) {
2710
0
            ret = AVERROR_EXIT;
2711
0
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2712
0
            break;
2713
0
        }
2714
2715
        /* read_frame_internal() in a previous iteration of this loop may
2716
         * have made changes to streams without returning a packet for them.
2717
         * Handle that here. */
2718
0
        ret = update_stream_avctx(ic);
2719
0
        if (ret < 0)
2720
0
            goto unref_then_goto_end;
2721
2722
        /* check if one codec still needs to be handled */
2723
0
        for (i = 0; i < ic->nb_streams; i++) {
2724
0
            AVStream *const st  = ic->streams[i];
2725
0
            FFStream *const sti = ffstream(st);
2726
0
            int fps_analyze_framecount = 20;
2727
0
            int count;
2728
2729
0
            if (!has_codec_parameters(st, NULL))
2730
0
                break;
2731
            /* If the timebase is coarse (like the usual millisecond precision
2732
             * of mkv), we need to analyze more frames to reliably arrive at
2733
             * the correct fps. */
2734
0
            if (av_q2d(st->time_base) > 0.0005)
2735
0
                fps_analyze_framecount *= 2;
2736
0
            if (!tb_unreliable(ic, st))
2737
0
                fps_analyze_framecount = 0;
2738
0
            if (ic->fps_probe_size >= 0)
2739
0
                fps_analyze_framecount = ic->fps_probe_size;
2740
0
            if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
2741
0
                fps_analyze_framecount = 0;
2742
            /* variable fps and no guess at the real fps */
2743
0
            count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
2744
0
                       sti->info->codec_info_duration_fields/2 :
2745
0
                       sti->info->duration_count;
2746
0
            if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
2747
0
                st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2748
0
                if (count < fps_analyze_framecount)
2749
0
                    break;
2750
0
            }
2751
            // Look at the first 3 frames if there is evidence of frame delay
2752
            // but the decoder delay is not set.
2753
0
            if (sti->info->frame_delay_evidence && count < 2 && sti->avctx->has_b_frames == 0)
2754
0
                break;
2755
0
            if (!sti->avctx->extradata &&
2756
0
                (!sti->extract_extradata.inited || sti->extract_extradata.bsf) &&
2757
0
                extract_extradata_check(st))
2758
0
                break;
2759
0
            if (sti->first_dts == AV_NOPTS_VALUE &&
2760
0
                (!(ic->iformat->flags & AVFMT_NOTIMESTAMPS) || sti->need_parsing == AVSTREAM_PARSE_FULL_RAW) &&
2761
0
                sti->codec_info_nb_frames < ((st->disposition & AV_DISPOSITION_ATTACHED_PIC) ? 1 : ic->max_ts_probe) &&
2762
0
                (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
2763
0
                 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
2764
0
                break;
2765
0
        }
2766
0
        analyzed_all_streams = 0;
2767
0
        if (i == ic->nb_streams && !si->missing_streams) {
2768
0
            analyzed_all_streams = 1;
2769
            /* NOTE: If the format has no header, then we need to read some
2770
             * packets to get most of the streams, so we cannot stop here. */
2771
0
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2772
                /* If we found the info for all the codecs, we can stop. */
2773
0
                ret = count;
2774
0
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
2775
0
                flush_codecs = 0;
2776
0
                break;
2777
0
            }
2778
0
        }
2779
        /* We did not get all the codec info, but we read too much data. */
2780
0
        if (read_size >= probesize) {
2781
0
            ret = count;
2782
0
            av_log(ic, AV_LOG_DEBUG,
2783
0
                   "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
2784
0
            for (unsigned i = 0; i < ic->nb_streams; i++) {
2785
0
                AVStream *const st  = ic->streams[i];
2786
0
                FFStream *const sti = ffstream(st);
2787
0
                if (!st->r_frame_rate.num &&
2788
0
                    sti->info->duration_count <= 1 &&
2789
0
                    st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
2790
0
                    strcmp(ic->iformat->name, "image2"))
2791
0
                    av_log(ic, AV_LOG_WARNING,
2792
0
                           "Stream #%d: not enough frames to estimate rate; "
2793
0
                           "consider increasing probesize\n", i);
2794
0
            }
2795
0
            break;
2796
0
        }
2797
2798
        /* NOTE: A new stream can be added there if no header in file
2799
         * (AVFMTCTX_NOHEADER). */
2800
0
        ret = read_frame_internal(ic, pkt1);
2801
0
        if (ret == AVERROR(EAGAIN))
2802
0
            continue;
2803
2804
0
        if (ret < 0) {
2805
            /* EOF or error*/
2806
0
            eof_reached = 1;
2807
0
            break;
2808
0
        }
2809
2810
0
        if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
2811
0
            ret = avpriv_packet_list_put(&si->packet_buffer,
2812
0
                                         pkt1, NULL, 0);
2813
0
            if (ret < 0)
2814
0
                goto unref_then_goto_end;
2815
2816
0
            pkt = &si->packet_buffer.tail->pkt;
2817
0
        } else {
2818
0
            pkt = pkt1;
2819
0
        }
2820
2821
0
        st  = ic->streams[pkt->stream_index];
2822
0
        sti = ffstream(st);
2823
0
        if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2824
0
            read_size += pkt->size;
2825
2826
0
        avctx = sti->avctx;
2827
0
        if (!sti->avctx_inited) {
2828
0
            ret = avcodec_parameters_to_context(avctx, st->codecpar);
2829
0
            if (ret < 0)
2830
0
                goto unref_then_goto_end;
2831
0
            sti->avctx_inited = 1;
2832
0
        }
2833
2834
0
        if (pkt->dts != AV_NOPTS_VALUE && sti->codec_info_nb_frames > 1) {
2835
            /* check for non-increasing dts */
2836
0
            if (sti->info->fps_last_dts != AV_NOPTS_VALUE &&
2837
0
                sti->info->fps_last_dts >= pkt->dts) {
2838
0
                av_log(ic, AV_LOG_DEBUG,
2839
0
                       "Non-increasing DTS in stream %d: packet %d with DTS "
2840
0
                       "%"PRId64", packet %d with DTS %"PRId64"\n",
2841
0
                       st->index, sti->info->fps_last_dts_idx,
2842
0
                       sti->info->fps_last_dts, sti->codec_info_nb_frames,
2843
0
                       pkt->dts);
2844
0
                sti->info->fps_first_dts =
2845
0
                sti->info->fps_last_dts  = AV_NOPTS_VALUE;
2846
0
            }
2847
            /* Check for a discontinuity in dts. If the difference in dts
2848
             * is more than 1000 times the average packet duration in the
2849
             * sequence, we treat it as a discontinuity. */
2850
0
            if (sti->info->fps_last_dts != AV_NOPTS_VALUE &&
2851
0
                sti->info->fps_last_dts_idx > sti->info->fps_first_dts_idx &&
2852
0
                (pkt->dts - (uint64_t)sti->info->fps_last_dts) / 1000 >
2853
0
                (sti->info->fps_last_dts     - (uint64_t)sti->info->fps_first_dts) /
2854
0
                (sti->info->fps_last_dts_idx - sti->info->fps_first_dts_idx)) {
2855
0
                av_log(ic, AV_LOG_WARNING,
2856
0
                       "DTS discontinuity in stream %d: packet %d with DTS "
2857
0
                       "%"PRId64", packet %d with DTS %"PRId64"\n",
2858
0
                       st->index, sti->info->fps_last_dts_idx,
2859
0
                       sti->info->fps_last_dts, sti->codec_info_nb_frames,
2860
0
                       pkt->dts);
2861
0
                sti->info->fps_first_dts =
2862
0
                sti->info->fps_last_dts  = AV_NOPTS_VALUE;
2863
0
            }
2864
2865
            /* update stored dts values */
2866
0
            if (sti->info->fps_first_dts == AV_NOPTS_VALUE) {
2867
0
                sti->info->fps_first_dts     = pkt->dts;
2868
0
                sti->info->fps_first_dts_idx = sti->codec_info_nb_frames;
2869
0
            }
2870
0
            sti->info->fps_last_dts     = pkt->dts;
2871
0
            sti->info->fps_last_dts_idx = sti->codec_info_nb_frames;
2872
0
        }
2873
0
        if (sti->codec_info_nb_frames > 1) {
2874
0
            int64_t t = 0;
2875
0
            int64_t limit;
2876
2877
0
            if (st->time_base.den > 0)
2878
0
                t = av_rescale_q(sti->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
2879
0
            if (st->avg_frame_rate.num > 0)
2880
0
                t = FFMAX(t, av_rescale_q(sti->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
2881
2882
0
            if (   t == 0
2883
0
                && sti->codec_info_nb_frames > 30
2884
0
                && sti->info->fps_first_dts != AV_NOPTS_VALUE
2885
0
                && sti->info->fps_last_dts  != AV_NOPTS_VALUE) {
2886
0
                int64_t dur = av_sat_sub64(sti->info->fps_last_dts, sti->info->fps_first_dts);
2887
0
                t = FFMAX(t, av_rescale_q(dur, st->time_base, AV_TIME_BASE_Q));
2888
0
            }
2889
2890
0
            if (analyzed_all_streams)                                limit = max_analyze_duration;
2891
0
            else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
2892
0
            else                                                     limit = max_stream_analyze_duration;
2893
2894
0
            if (t >= limit) {
2895
0
                av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
2896
0
                       limit,
2897
0
                       t, pkt->stream_index);
2898
0
                if (ic->flags & AVFMT_FLAG_NOBUFFER)
2899
0
                    av_packet_unref(pkt1);
2900
0
                break;
2901
0
            }
2902
0
            if (pkt->duration > 0 && pkt->duration < INT64_MAX - sti->info->codec_info_duration) {
2903
0
                const int fields = sti->codec_desc && (sti->codec_desc->props & AV_CODEC_PROP_FIELDS);
2904
0
                if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE && pkt->pts != AV_NOPTS_VALUE && st->start_time != AV_NOPTS_VALUE && pkt->pts >= st->start_time
2905
0
                    && (uint64_t)pkt->pts - st->start_time < INT64_MAX
2906
0
                ) {
2907
0
                    sti->info->codec_info_duration = FFMIN(pkt->pts - st->start_time, sti->info->codec_info_duration + pkt->duration);
2908
0
                } else
2909
0
                    sti->info->codec_info_duration += pkt->duration;
2910
0
                sti->info->codec_info_duration_fields += sti->parser && sti->need_parsing && fields
2911
0
                                                         ? sti->parser->repeat_pict + 1 : 2;
2912
0
            }
2913
0
        }
2914
0
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2915
0
#if FF_API_R_FRAME_RATE
2916
0
            ff_rfps_add_frame(ic, st, pkt->dts);
2917
0
#endif
2918
0
            if (pkt->dts != pkt->pts && pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
2919
0
                sti->info->frame_delay_evidence = 1;
2920
0
        }
2921
0
        if (!sti->avctx->extradata) {
2922
0
            ret = extract_extradata(si, st, pkt);
2923
0
            if (ret < 0)
2924
0
                goto unref_then_goto_end;
2925
0
        }
2926
2927
        /* If still no information, we try to open the codec and to
2928
         * decompress the frame. We try to avoid that in most cases as
2929
         * it takes longer and uses more memory. For MPEG-4, we need to
2930
         * decompress for QuickTime.
2931
         *
2932
         * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2933
         * least one frame of codec data, this makes sure the codec initializes
2934
         * the channel configuration and does not only trust the values from
2935
         * the container. */
2936
0
        try_decode_frame(ic, st, pkt,
2937
0
                         (options && i < orig_nb_streams) ? &options[i] : NULL);
2938
2939
0
        if (ic->flags & AVFMT_FLAG_NOBUFFER)
2940
0
            av_packet_unref(pkt1);
2941
2942
0
        sti->codec_info_nb_frames++;
2943
0
        count++;
2944
0
    }
2945
2946
0
    if (eof_reached) {
2947
0
        for (unsigned stream_index = 0; stream_index < ic->nb_streams; stream_index++) {
2948
0
            AVStream *const st = ic->streams[stream_index];
2949
0
            AVCodecContext *const avctx = ffstream(st)->avctx;
2950
0
            if (!has_codec_parameters(st, NULL)) {
2951
0
                const AVCodec *codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
2952
0
                if (codec && !avctx->codec) {
2953
0
                    AVDictionary *opts = NULL;
2954
0
                    if (ic->codec_whitelist)
2955
0
                        av_dict_set(&opts, "codec_whitelist", ic->codec_whitelist, 0);
2956
0
                    if (avcodec_open2(avctx, codec, (options && stream_index < orig_nb_streams) ? &options[stream_index] : &opts) < 0)
2957
0
                        av_log(ic, AV_LOG_WARNING,
2958
0
                               "Failed to open codec in %s\n", __func__);
2959
0
                    av_dict_free(&opts);
2960
0
                }
2961
0
            }
2962
2963
            // EOF already reached while reading the stream above.
2964
            // So continue with reoordering DTS with whatever delay we have.
2965
0
            if (si->packet_buffer.head && !has_decode_delay_been_guessed(st)) {
2966
0
                update_dts_from_pts(ic, stream_index, si->packet_buffer.head);
2967
0
            }
2968
0
        }
2969
0
    }
2970
2971
0
    if (flush_codecs) {
2972
0
        AVPacket *empty_pkt = si->pkt;
2973
0
        int err = 0;
2974
0
        av_packet_unref(empty_pkt);
2975
2976
0
        for (unsigned i = 0; i < ic->nb_streams; i++) {
2977
0
            AVStream *const st  = ic->streams[i];
2978
0
            FFStream *const sti = ffstream(st);
2979
2980
            /* flush the decoders */
2981
0
            if (sti->info->found_decoder == 1) {
2982
0
                err = try_decode_frame(ic, st, empty_pkt,
2983
0
                                        (options && i < orig_nb_streams)
2984
0
                                        ? &options[i] : NULL);
2985
2986
0
                if (err < 0) {
2987
0
                    av_log(ic, AV_LOG_INFO,
2988
0
                        "decoding for stream %d failed\n", st->index);
2989
0
                }
2990
0
            }
2991
0
        }
2992
0
    }
2993
2994
0
    ff_rfps_calculate(ic);
2995
2996
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
2997
0
        AVStream *const st  = ic->streams[i];
2998
0
        FFStream *const sti = ffstream(st);
2999
0
        AVCodecContext *const avctx = sti->avctx;
3000
3001
0
        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3002
0
            if (avctx->codec_id == AV_CODEC_ID_RAWVIDEO && !avctx->codec_tag && !avctx->bits_per_coded_sample) {
3003
0
                uint32_t tag= avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
3004
0
                if (avpriv_pix_fmt_find(PIX_FMT_LIST_RAW, tag) == avctx->pix_fmt)
3005
0
                    avctx->codec_tag= tag;
3006
0
            }
3007
3008
            /* estimate average framerate if not set by demuxer */
3009
0
            if (sti->info->codec_info_duration_fields &&
3010
0
                !st->avg_frame_rate.num &&
3011
0
                sti->info->codec_info_duration) {
3012
0
                int best_fps      = 0;
3013
0
                double best_error = 0.01;
3014
0
                AVRational codec_frame_rate = avctx->framerate;
3015
3016
0
                if (sti->info->codec_info_duration        >= INT64_MAX / st->time_base.num / 2||
3017
0
                    sti->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
3018
0
                    sti->info->codec_info_duration        < 0)
3019
0
                    continue;
3020
0
                av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3021
0
                          sti->info->codec_info_duration_fields * (int64_t) st->time_base.den,
3022
0
                          sti->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3023
3024
                /* Round guessed framerate to a "standard" framerate if it's
3025
                 * within 1% of the original estimate. */
3026
0
                for (int j = 0; j < MAX_STD_TIMEBASES; j++) {
3027
0
                    AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
3028
0
                    double error       = fabs(av_q2d(st->avg_frame_rate) /
3029
0
                                              av_q2d(std_fps) - 1);
3030
3031
0
                    if (error < best_error) {
3032
0
                        best_error = error;
3033
0
                        best_fps   = std_fps.num;
3034
0
                    }
3035
3036
0
                    if ((ffifmt(ic->iformat)->flags_internal & FF_INFMT_FLAG_PREFER_CODEC_FRAMERATE) &&
3037
0
                        codec_frame_rate.num > 0 && codec_frame_rate.den > 0) {
3038
0
                        error       = fabs(av_q2d(codec_frame_rate) /
3039
0
                                           av_q2d(std_fps) - 1);
3040
0
                        if (error < best_error) {
3041
0
                            best_error = error;
3042
0
                            best_fps   = std_fps.num;
3043
0
                        }
3044
0
                    }
3045
0
                }
3046
0
                if (best_fps)
3047
0
                    av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3048
0
                              best_fps, 12 * 1001, INT_MAX);
3049
0
            }
3050
0
            if (!st->r_frame_rate.num) {
3051
0
                const AVCodecDescriptor *desc = sti->codec_desc;
3052
0
                AVRational mul = (AVRational){ desc && (desc->props & AV_CODEC_PROP_FIELDS) ? 2 : 1, 1 };
3053
0
                AVRational  fr = av_mul_q(avctx->framerate, mul);
3054
3055
0
                if (fr.num && fr.den && av_cmp_q(st->time_base, av_inv_q(fr)) <= 0) {
3056
0
                    st->r_frame_rate = fr;
3057
0
                } else {
3058
0
                    st->r_frame_rate.num = st->time_base.den;
3059
0
                    st->r_frame_rate.den = st->time_base.num;
3060
0
                }
3061
0
            }
3062
0
            st->codecpar->framerate = avctx->framerate;
3063
0
            if (sti->display_aspect_ratio.num && sti->display_aspect_ratio.den) {
3064
0
                AVRational hw_ratio = { avctx->height, avctx->width };
3065
0
                st->sample_aspect_ratio = av_mul_q(sti->display_aspect_ratio,
3066
0
                                                   hw_ratio);
3067
0
            }
3068
0
        } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
3069
0
            if (!avctx->bits_per_coded_sample)
3070
0
                avctx->bits_per_coded_sample =
3071
0
                    av_get_bits_per_sample(avctx->codec_id);
3072
            // set stream disposition based on audio service type
3073
0
            switch (avctx->audio_service_type) {
3074
0
            case AV_AUDIO_SERVICE_TYPE_EFFECTS:
3075
0
                st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
3076
0
                break;
3077
0
            case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
3078
0
                st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
3079
0
                break;
3080
0
            case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
3081
0
                st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
3082
0
                break;
3083
0
            case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
3084
0
                st->disposition = AV_DISPOSITION_COMMENT;
3085
0
                break;
3086
0
            case AV_AUDIO_SERVICE_TYPE_KARAOKE:
3087
0
                st->disposition = AV_DISPOSITION_KARAOKE;
3088
0
                break;
3089
0
            }
3090
0
        }
3091
0
    }
3092
3093
0
    if (probesize)
3094
0
        estimate_timings(ic, old_offset);
3095
3096
0
    av_opt_set_int(ic, "skip_clear", 0, AV_OPT_SEARCH_CHILDREN);
3097
3098
0
    if (ret >= 0 && ic->nb_streams)
3099
        /* We could not have all the codec parameters before EOF. */
3100
0
        ret = -1;
3101
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
3102
0
        AVStream *const st  = ic->streams[i];
3103
0
        FFStream *const sti = ffstream(st);
3104
0
        const char *errmsg;
3105
3106
        /* if no packet was ever seen, update context now for has_codec_parameters */
3107
0
        if (!sti->avctx_inited) {
3108
0
            if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3109
0
                st->codecpar->format == AV_SAMPLE_FMT_NONE)
3110
0
                st->codecpar->format = sti->avctx->sample_fmt;
3111
0
            ret = avcodec_parameters_to_context(sti->avctx, st->codecpar);
3112
0
            if (ret < 0)
3113
0
                goto find_stream_info_err;
3114
0
        }
3115
0
        if (!has_codec_parameters(st, &errmsg)) {
3116
0
            char buf[256];
3117
0
            avcodec_string(buf, sizeof(buf), sti->avctx, 0);
3118
0
            av_log(ic, AV_LOG_WARNING,
3119
0
                   "Could not find codec parameters for stream %d (%s): %s\n"
3120
0
                   "Consider increasing the value for the 'analyzeduration' (%"PRId64") and 'probesize' (%"PRId64") options\n",
3121
0
                   i, buf, errmsg, ic->max_analyze_duration, ic->probesize);
3122
0
        } else {
3123
0
            ret = 0;
3124
0
        }
3125
0
    }
3126
3127
0
    err = compute_chapters_end(ic);
3128
0
    if (err < 0) {
3129
0
        ret = err;
3130
0
        goto find_stream_info_err;
3131
0
    }
3132
3133
    /* update the stream parameters from the internal codec contexts */
3134
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
3135
0
        AVStream *const st  = ic->streams[i];
3136
0
        FFStream *const sti = ffstream(st);
3137
3138
0
        if (sti->avctx_inited) {
3139
0
            ret = parameters_from_context(ic, st->codecpar, sti->avctx);
3140
0
            if (ret < 0)
3141
0
                goto find_stream_info_err;
3142
3143
0
            if (sti->avctx->rc_buffer_size > 0 || sti->avctx->rc_max_rate > 0 ||
3144
0
                sti->avctx->rc_min_rate) {
3145
0
                size_t cpb_size;
3146
0
                AVCPBProperties *props = av_cpb_properties_alloc(&cpb_size);
3147
0
                if (props) {
3148
0
                    if (sti->avctx->rc_buffer_size > 0)
3149
0
                        props->buffer_size = sti->avctx->rc_buffer_size;
3150
0
                    if (sti->avctx->rc_min_rate > 0)
3151
0
                        props->min_bitrate = sti->avctx->rc_min_rate;
3152
0
                    if (sti->avctx->rc_max_rate > 0)
3153
0
                        props->max_bitrate = sti->avctx->rc_max_rate;
3154
0
                    if (!av_packet_side_data_add(&st->codecpar->coded_side_data,
3155
0
                                                 &st->codecpar->nb_coded_side_data,
3156
0
                                                 AV_PKT_DATA_CPB_PROPERTIES,
3157
0
                                                 (uint8_t *)props, cpb_size, 0))
3158
0
                        av_free(props);
3159
0
                }
3160
0
            }
3161
0
        }
3162
3163
0
        sti->avctx_inited = 0;
3164
0
    }
3165
3166
    /* update the stream group parameters from the stream contexts if needed */
3167
0
    for (unsigned i = 0; i < ic->nb_stream_groups; i++) {
3168
0
        AVStreamGroup *const stg  = ic->stream_groups[i];
3169
0
        AVStreamGroupLCEVC *lcevc;
3170
0
        const AVStream *st;
3171
3172
0
        if (stg->type != AV_STREAM_GROUP_PARAMS_LCEVC)
3173
0
            continue;
3174
3175
        /* For LCEVC in mpegts, the parser is needed to get the enhancement layer
3176
         * dimensions */
3177
0
        lcevc = stg->params.lcevc;
3178
0
        if (lcevc->width && lcevc->height)
3179
0
            continue;
3180
0
        st = stg->streams[lcevc->lcevc_index];
3181
0
        lcevc->width  = st->codecpar->width;
3182
0
        lcevc->height = st->codecpar->height;
3183
0
    }
3184
3185
0
find_stream_info_err:
3186
0
    for (unsigned i = 0; i < ic->nb_streams; i++) {
3187
0
        AVStream *const st  = ic->streams[i];
3188
0
        FFStream *const sti = ffstream(st);
3189
0
        int err;
3190
3191
0
        if (sti->info) {
3192
0
            av_freep(&sti->info->duration_error);
3193
0
            av_freep(&sti->info);
3194
0
        }
3195
3196
0
        if (avcodec_is_open(sti->avctx)) {
3197
0
            err = codec_close(sti);
3198
0
            if (err < 0 && ret >= 0)
3199
0
                ret = err;
3200
0
        }
3201
3202
0
        av_bsf_free(&sti->extract_extradata.bsf);
3203
0
    }
3204
0
    if (ic->pb) {
3205
0
        FFIOContext *const ctx = ffiocontext(ic->pb);
3206
0
        av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
3207
0
               avio_tell(ic->pb), ctx->bytes_read, ctx->seek_count, count);
3208
0
    }
3209
0
    return ret;
3210
3211
0
unref_then_goto_end:
3212
0
    av_packet_unref(pkt1);
3213
0
    goto find_stream_info_err;
3214
0
}