Coverage Report

Created: 2026-10-14 06:52

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