avformat: Free the internal codec context at the end
[libav.git] / libavformat / utils.c
CommitLineData
de6d9b64 1/*
2912e87a 2 * various utility functions for use within Libav
19720f15 3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
de6d9b64 4 *
2912e87a 5 * This file is part of Libav.
b78e7197 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
19720f15
FB
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
b78e7197 10 * version 2.1 of the License, or (at your option) any later version.
de6d9b64 11 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
de6d9b64 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
FB
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
de6d9b64 16 *
19720f15 17 * You should have received a copy of the GNU Lesser General Public
2912e87a 18 * License along with Libav; if not, write to the Free Software
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
de6d9b64 20 */
79f43a8c 21
50ecf157
DB
22#undef NDEBUG
23#include <assert.h>
24#include <stdarg.h>
8f8bc923
DB
25#include <stdint.h>
26
50ecf157
DB
27#include "config.h"
28
6450599e 29#include "libavutil/avassert.h"
245976da 30#include "libavutil/avstring.h"
50ecf157
DB
31#include "libavutil/dict.h"
32#include "libavutil/internal.h"
0ebcdf5c 33#include "libavutil/mathematics.h"
50ecf157 34#include "libavutil/opt.h"
4a835416 35#include "libavutil/parseutils.h"
50ecf157 36#include "libavutil/pixdesc.h"
c4ef6a3e 37#include "libavutil/time.h"
50ecf157
DB
38
39#include "libavcodec/bytestream.h"
40#include "libavcodec/internal.h"
41
c26e58e3 42#include "audiointerleave.h"
50ecf157 43#include "avformat.h"
50ecf157
DB
44#include "id3v2.h"
45#include "internal.h"
46#include "metadata.h"
780d7897
MS
47#if CONFIG_NETWORK
48#include "network.h"
49#endif
50ecf157
DB
50#include "riff.h"
51#include "url.h"
b754978a 52
e36bdf8b 53/**
ba87f080 54 * @file
2912e87a 55 * various utility functions for use within Libav
e36bdf8b
DK
56 */
57
c97429e2
SS
58unsigned avformat_version(void)
59{
60 return LIBAVFORMAT_VERSION_INT;
61}
62
41600690 63const char *avformat_configuration(void)
c1736936 64{
29ba0911 65 return LIBAV_CONFIGURATION;
c1736936
DB
66}
67
41600690 68const char *avformat_license(void)
c1736936
DB
69{
70#define LICENSE_PREFIX "libavformat license: "
a03be6e1 71 return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
c1736936
DB
72}
73
aa3c7799
AK
74/* an arbitrarily chosen "sane" max packet size -- 50M */
75#define SANE_CHUNK_SIZE (50000000)
de6d9b64 76
50ecf157
DB
77/* Read the data in sane-sized chunks and append to pkt.
78 * Return the number of bytes read or an error. */
aa3c7799 79static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
2692067a 80{
aa3c7799 81 int64_t chunk_size = size;
d1c229cd 82 int64_t orig_pos = pkt->pos; // av_grow_packet might reset pos
aa3c7799
AK
83 int orig_size = pkt->size;
84 int ret = 0;
85
86 do {
87 int prev_size = pkt->size;
88 int read_size;
89
50ecf157
DB
90 /* When the caller requests a lot of data, limit it to the amount
91 * left in file or SANE_CHUNK_SIZE when it is not known. */
aa3c7799
AK
92 if (size > SANE_CHUNK_SIZE) {
93 int64_t filesize = avio_size(s) - avio_tell(s);
94 chunk_size = FFMAX(filesize, SANE_CHUNK_SIZE);
95 }
96 read_size = FFMIN(size, chunk_size);
97
98 ret = av_grow_packet(pkt, read_size);
99 if (ret < 0)
100 break;
2692067a 101
aa3c7799
AK
102 ret = avio_read(s, pkt->data + prev_size, read_size);
103 if (ret != read_size) {
104 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
105 break;
106 }
2692067a 107
aa3c7799
AK
108 size -= read_size;
109 } while (size > 0);
2692067a 110
aa3c7799
AK
111 pkt->pos = orig_pos;
112 if (!pkt->size)
ce70f28a 113 av_packet_unref(pkt);
aa3c7799
AK
114 return pkt->size > orig_size ? pkt->size - orig_size : ret;
115}
116
117int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
118{
119 av_init_packet(pkt);
120 pkt->data = NULL;
121 pkt->size = 0;
122 pkt->pos = avio_tell(s);
2692067a 123
aa3c7799 124 return append_packet_chunked(s, pkt, size);
2692067a
MN
125}
126
ae628ec1 127int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
6bfc2683 128{
6bfc2683
RD
129 if (!pkt->size)
130 return av_get_packet(s, pkt, size);
aa3c7799 131 return append_packet_chunked(s, pkt, size);
6bfc2683
RD
132}
133
5c07cf53 134int av_filename_number_test(const char *filename)
b9a281db
FB
135{
136 char buf[1024];
50ecf157
DB
137 return filename &&
138 (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
b9a281db
FB
139}
140
50ecf157
DB
141static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
142 AVProbeData *pd, int score)
64cd3108 143{
cf5b33d9 144 static const struct {
50ecf157
DB
145 const char *name;
146 enum AVCodecID id;
147 enum AVMediaType type;
cf5b33d9 148 } fmt_id_type[] = {
50ecf157
DB
149 { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
150 { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
151 { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
152 { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
153 { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
dcbfb780 154 { "latm", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
50ecf157
DB
155 { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
156 { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
36ef5369 157 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
cf5b33d9
SS
158 { 0 }
159 };
160 AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
64cd3108
MN
161
162 if (fmt) {
cf5b33d9 163 int i;
50ecf157
DB
164 av_log(s, AV_LOG_DEBUG,
165 "Probe with size=%d, packets=%d detected %s with score=%d\n",
166 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets,
167 fmt->name, score);
cf5b33d9
SS
168 for (i = 0; fmt_id_type[i].name; i++) {
169 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
9200514a
AK
170 st->codecpar->codec_id = fmt_id_type[i].id;
171 st->codecpar->codec_type = fmt_id_type[i].type;
172#if FF_API_LAVF_AVCTX
173FF_DISABLE_DEPRECATION_WARNINGS
174 st->codec->codec_type = st->codecpar->codec_type;
175 st->codec->codec_id = st->codecpar->codec_id;
176FF_ENABLE_DEPRECATION_WARNINGS
177#endif
cf5b33d9
SS
178 break;
179 }
f1588ed5 180 }
64cd3108
MN
181 }
182 return !!fmt;
183}
184
b9a281db
FB
185/************************************************************/
186/* input media file */
96baaa6a 187
50ecf157
DB
188/* Open input file and probe the format if necessary. */
189static int init_input(AVFormatContext *s, const char *filename,
190 AVDictionary **options)
05e84c95
AK
191{
192 int ret;
50ecf157 193 AVProbeData pd = { filename, NULL, 0 };
05e84c95
AK
194
195 if (s->pb) {
196 s->flags |= AVFMT_FLAG_CUSTOM_IO;
197 if (!s->iformat)
50ecf157
DB
198 return av_probe_input_buffer(s->pb, &s->iformat, filename,
199 s, 0, s->probesize);
05e84c95
AK
200 else if (s->iformat->flags & AVFMT_NOFILE)
201 return AVERROR(EINVAL);
202 return 0;
203 }
204
50ecf157 205 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
05e84c95
AK
206 (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
207 return 0;
208
7fbb3b5b
AK
209 ret = s->io_open(s, &s->pb, filename, AVIO_FLAG_READ, options);
210 if (ret < 0)
7e6029f9 211 return ret;
05e84c95
AK
212 if (s->iformat)
213 return 0;
50ecf157
DB
214 return av_probe_input_buffer(s->pb, &s->iformat, filename,
215 s, 0, s->probesize);
05e84c95
AK
216}
217
d584533c
LB
218static int add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
219 AVPacketList **plast_pktl, int ref)
50ecf157 220{
dd2a4bcf 221 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
d584533c
LB
222 int ret;
223
dd2a4bcf 224 if (!pktl)
d584533c
LB
225 return AVERROR(ENOMEM);
226
227 if (ref) {
228 if ((ret = av_packet_ref(&pktl->pkt, pkt)) < 0) {
229 av_free(pktl);
230 return ret;
231 }
232 } else {
233 pktl->pkt = *pkt;
234 }
dd2a4bcf
AK
235
236 if (*packet_buffer)
237 (*plast_pktl)->next = pktl;
238 else
239 *packet_buffer = pktl;
240
50ecf157 241 /* Add the packet in the buffered packet list. */
dd2a4bcf 242 *plast_pktl = pktl;
d584533c 243 return 0;
dd2a4bcf
AK
244}
245
1afddbe5 246static int queue_attached_pictures(AVFormatContext *s)
01fcc42b 247{
d584533c 248 int i, ret;
01fcc42b 249 for (i = 0; i < s->nb_streams; i++)
40b41be3
AK
250 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
251 s->streams[i]->discard < AVDISCARD_ALL) {
1afddbe5 252
d584533c
LB
253 ret = add_to_pktbuf(&s->internal->raw_packet_buffer,
254 &s->streams[i]->attached_pic,
255 &s->internal->raw_packet_buffer_end, 1);
256 if (ret < 0)
257 return ret;
01fcc42b 258 }
1afddbe5 259 return 0;
01fcc42b
AK
260}
261
9200514a
AK
262#if FF_API_LAVF_AVCTX
263FF_DISABLE_DEPRECATION_WARNINGS
264static int update_stream_avctx(AVFormatContext *s)
265{
266 int i, ret;
267 for (i = 0; i < s->nb_streams; i++) {
268 AVStream *st = s->streams[i];
269
270 if (!st->internal->need_codec_update)
271 continue;
272
273 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
274 if (ret < 0)
275 return ret;
276
277 st->internal->need_codec_update = 0;
278 }
279 return 0;
280}
281FF_ENABLE_DEPRECATION_WARNINGS
282#endif
283
50ecf157
DB
284int avformat_open_input(AVFormatContext **ps, const char *filename,
285 AVInputFormat *fmt, AVDictionary **options)
05e84c95
AK
286{
287 AVFormatContext *s = *ps;
9200514a 288 int i, ret = 0;
05e84c95 289 AVDictionary *tmp = NULL;
079ea6ca 290 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
05e84c95
AK
291
292 if (!s && !(s = avformat_alloc_context()))
293 return AVERROR(ENOMEM);
294 if (fmt)
295 s->iformat = fmt;
296
297 if (options)
298 av_dict_copy(&tmp, *options, 0);
299
300 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
301 goto fail;
302
32caa7b1 303 if ((ret = init_input(s, filename, &tmp)) < 0)
05e84c95
AK
304 goto fail;
305
50ecf157 306 /* Check filename in case an image number is expected. */
05e84c95
AK
307 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
308 if (!av_filename_number_test(filename)) {
309 ret = AVERROR(EINVAL);
310 goto fail;
311 }
312 }
313
314 s->duration = s->start_time = AV_NOPTS_VALUE;
a5db8e4a 315 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
05e84c95 316
50ecf157 317 /* Allocate private data. */
05e84c95
AK
318 if (s->iformat->priv_data_size > 0) {
319 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
320 ret = AVERROR(ENOMEM);
321 goto fail;
322 }
323 if (s->iformat->priv_class) {
50ecf157 324 *(const AVClass **) s->priv_data = s->iformat->priv_class;
05e84c95
AK
325 av_opt_set_defaults(s->priv_data);
326 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
327 goto fail;
328 }
329 }
330
331 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
332 if (s->pb)
393fd0d8 333 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
05e84c95
AK
334
335 if (s->iformat->read_header)
6e9651d1 336 if ((ret = s->iformat->read_header(s)) < 0)
05e84c95
AK
337 goto fail;
338
079ea6ca
AK
339 if (id3v2_extra_meta &&
340 (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
341 goto fail;
342 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
343
1afddbe5
AK
344 if ((ret = queue_attached_pictures(s)) < 0)
345 goto fail;
dd2a4bcf 346
9deaec78 347 if (s->pb && !s->internal->data_offset)
348 s->internal->data_offset = avio_tell(s->pb);
05e84c95 349
9deaec78 350 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
05e84c95 351
9200514a
AK
352#if FF_API_LAVF_AVCTX
353 update_stream_avctx(s);
354#endif
355
356 for (i = 0; i < s->nb_streams; i++)
357 s->streams[i]->internal->orig_codec_id = s->streams[i]->codecpar->codec_id;
358
05e84c95
AK
359 if (options) {
360 av_dict_free(options);
361 *options = tmp;
362 }
363 *ps = s;
364 return 0;
365
366fail:
079ea6ca 367 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
05e84c95
AK
368 av_dict_free(&tmp);
369 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
370 avio_close(s->pb);
371 avformat_free_context(s);
372 *ps = NULL;
373 return ret;
374}
375
da24c5e3
FB
376/*******************************************************/
377
68b46774 378static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
62bebf6e 379{
9200514a 380 if (st->codecpar->codec_id == AV_CODEC_ID_PROBE) {
62bebf6e
AC
381 AVProbeData *pd = &st->probe_data;
382 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
383 --st->probe_packets;
384
f0ff9eb4 385 if (pkt) {
68b46774
AK
386 int err;
387 if ((err = av_reallocp(&pd->buf, pd->buf_size + pkt->size +
388 AVPROBE_PADDING_SIZE)) < 0)
389 return err;
50ecf157 390 memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
f0ff9eb4 391 pd->buf_size += pkt->size;
50ecf157 392 memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
f0ff9eb4
AC
393 } else {
394 st->probe_packets = 0;
6746cd7f 395 if (!pd->buf_size) {
50ecf157
DB
396 av_log(s, AV_LOG_ERROR,
397 "nothing to probe for stream %d\n", st->index);
68b46774 398 return 0;
6746cd7f 399 }
f0ff9eb4 400 }
62bebf6e 401
f0ff9eb4
AC
402 if (!st->probe_packets ||
403 av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
50ecf157
DB
404 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0
405 ? AVPROBE_SCORE_MAX / 4 : 0);
9200514a 406 if (st->codecpar->codec_id != AV_CODEC_ID_PROBE) {
50ecf157 407 pd->buf_size = 0;
62bebf6e
AC
408 av_freep(&pd->buf);
409 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
410 }
411 }
412 }
68b46774 413 return 0;
62bebf6e
AC
414}
415
3c90cc2e 416int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
de6d9b64 417{
68b46774 418 int ret, i, err;
62600469 419 AVStream *st;
0bef08e5 420
50ecf157 421 for (;;) {
9deaec78 422 AVPacketList *pktl = s->internal->raw_packet_buffer;
0bef08e5
MN
423
424 if (pktl) {
425 *pkt = pktl->pkt;
50ecf157 426 st = s->streams[pkt->stream_index];
9200514a 427 if (st->codecpar->codec_id != AV_CODEC_ID_PROBE ||
50ecf157 428 !st->probe_packets ||
9deaec78 429 s->internal->raw_packet_buffer_remaining_size < pkt->size) {
f0ff9eb4 430 AVProbeData *pd;
50ecf157 431 if (st->probe_packets)
68b46774
AK
432 if ((err = probe_codec(s, st, NULL)) < 0)
433 return err;
f0ff9eb4 434 pd = &st->probe_data;
af122d6a
BC
435 av_freep(&pd->buf);
436 pd->buf_size = 0;
9deaec78 437 s->internal->raw_packet_buffer = pktl->next;
438 s->internal->raw_packet_buffer_remaining_size += pkt->size;
0bef08e5
MN
439 av_free(pktl);
440 return 0;
441 }
442 }
443
1cc569dd
AK
444 pkt->data = NULL;
445 pkt->size = 0;
55823964 446 av_init_packet(pkt);
50ecf157 447 ret = s->iformat->read_packet(s, pkt);
86cb7e33
BC
448 if (ret < 0) {
449 if (!pktl || ret == AVERROR(EAGAIN))
450 return ret;
f0ff9eb4
AC
451 for (i = 0; i < s->nb_streams; i++) {
452 st = s->streams[i];
50ecf157 453 if (st->probe_packets)
68b46774
AK
454 if ((err = probe_codec(s, st, NULL)) < 0)
455 return err;
f0ff9eb4 456 }
86cb7e33
BC
457 continue;
458 }
73e8e8db 459
a5d42043
LB
460 if (!pkt->buf) {
461 AVPacket tmp = { 0 };
462 ret = av_packet_ref(&tmp, pkt);
463 if (ret < 0)
464 return ret;
465 *pkt = tmp;
466 }
467
73e8e8db
ZK
468 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
469 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
470 av_log(s, AV_LOG_WARNING,
471 "Dropped corrupted packet (stream = %d)\n",
472 pkt->stream_index);
ce70f28a 473 av_packet_unref(pkt);
73e8e8db
ZK
474 continue;
475 }
476
50ecf157 477 st = s->streams[pkt->stream_index];
62600469 478
9200514a 479 switch (st->codecpar->codec_type) {
72415b2a 480 case AVMEDIA_TYPE_VIDEO:
50ecf157 481 if (s->video_codec_id)
9200514a 482 st->codecpar->codec_id = s->video_codec_id;
55823964 483 break;
72415b2a 484 case AVMEDIA_TYPE_AUDIO:
50ecf157 485 if (s->audio_codec_id)
9200514a 486 st->codecpar->codec_id = s->audio_codec_id;
55823964 487 break;
72415b2a 488 case AVMEDIA_TYPE_SUBTITLE:
50ecf157 489 if (s->subtitle_codec_id)
9200514a 490 st->codecpar->codec_id = s->subtitle_codec_id;
55823964
MN
491 break;
492 }
62600469 493
9200514a 494 if (!pktl && (st->codecpar->codec_id != AV_CODEC_ID_PROBE ||
50ecf157 495 !st->probe_packets))
744b4c02
MN
496 return ret;
497
d584533c
LB
498 err = add_to_pktbuf(&s->internal->raw_packet_buffer, pkt,
499 &s->internal->raw_packet_buffer_end, 0);
500 if (err)
501 return err;
9deaec78 502 s->internal->raw_packet_buffer_remaining_size -= pkt->size;
744b4c02 503
68b46774
AK
504 if ((err = probe_codec(s, st, pkt)) < 0)
505 return err;
0bef08e5 506 }
fb2758c8
FB
507}
508
509/**********************************************************/
510
e36bdf8b 511/**
a85736f2 512 * Return the frame duration in seconds. Return 0 if not available.
e36bdf8b 513 */
2d6e5849 514void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
55f9037f 515 AVCodecParserContext *pc, AVPacket *pkt)
fb2758c8 516{
9200514a
AK
517 AVRational codec_framerate = s->iformat ? st->internal->avctx->framerate :
518 (AVRational){ 0, 1 };
fb2758c8
FB
519 int frame_size;
520
521 *pnum = 0;
522 *pden = 0;
9200514a 523 switch (st->codecpar->codec_type) {
72415b2a 524 case AVMEDIA_TYPE_VIDEO:
aba232cf
AK
525 if (st->avg_frame_rate.num) {
526 *pnum = st->avg_frame_rate.den;
527 *pden = st->avg_frame_rate.num;
50ecf157 528 } else if (st->time_base.num * 1000LL > st->time_base.den) {
c0df9d75
MN
529 *pnum = st->time_base.num;
530 *pden = st->time_base.den;
2d6e5849
AK
531 } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
532 *pnum = codec_framerate.den;
533 *pden = codec_framerate.num;
327c4076 534 if (pc && pc->repeat_pict) {
7709ce02
JG
535 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
536 *pden /= 1 + pc->repeat_pict;
537 else
538 *pnum *= 1 + pc->repeat_pict;
327c4076 539 }
50ecf157
DB
540 /* If this codec can be interlaced or progressive then we need
541 * a parser to compute duration of a packet. Thus if we have
542 * no parser in such case leave duration undefined. */
9200514a 543 if (st->internal->avctx->ticks_per_frame > 1 && !pc)
497431a5 544 *pnum = *pden = 0;
fb2758c8
FB
545 }
546 break;
72415b2a 547 case AVMEDIA_TYPE_AUDIO:
9200514a
AK
548 frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
549 if (frame_size <= 0 || st->codecpar->sample_rate <= 0)
fb2758c8
FB
550 break;
551 *pnum = frame_size;
9200514a 552 *pden = st->codecpar->sample_rate;
fb2758c8
FB
553 break;
554 default:
555 break;
556 }
557}
558
885da7b0
AK
559static int is_intra_only(enum AVCodecID id)
560{
561 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
562 if (!d)
563 return 0;
564 if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
565 return 0;
566 return 1;
5ba7c3d7
MN
567}
568
9fcbcca6
NB
569static void update_initial_timestamps(AVFormatContext *s, int stream_index,
570 int64_t dts, int64_t pts)
571{
50ecf157 572 AVStream *st = s->streams[stream_index];
9deaec78 573 AVPacketList *pktl = s->internal->packet_buffer;
82583548 574
50ecf157
DB
575 if (st->first_dts != AV_NOPTS_VALUE ||
576 dts == AV_NOPTS_VALUE ||
577 st->cur_dts == AV_NOPTS_VALUE)
82583548
MN
578 return;
579
50ecf157
DB
580 st->first_dts = dts - st->cur_dts;
581 st->cur_dts = dts;
82583548 582
50ecf157
DB
583 for (; pktl; pktl = pktl->next) {
584 if (pktl->pkt.stream_index != stream_index)
82583548 585 continue;
50ecf157
DB
586 // FIXME: think more about this check
587 if (pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
82583548
MN
588 pktl->pkt.pts += st->first_dts;
589
50ecf157 590 if (pktl->pkt.dts != AV_NOPTS_VALUE)
82583548 591 pktl->pkt.dts += st->first_dts;
48a59dfe 592
50ecf157
DB
593 if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
594 st->start_time = pktl->pkt.pts;
82583548 595 }
9fcbcca6
NB
596 if (st->start_time == AV_NOPTS_VALUE)
597 st->start_time = pts;
82583548
MN
598}
599
a7fa7568
JR
600static void update_initial_durations(AVFormatContext *s, AVStream *st,
601 int stream_index, int duration)
83a9db42 602{
9deaec78 603 AVPacketList *pktl = s->internal->packet_buffer;
50ecf157 604 int64_t cur_dts = 0;
820ad60c 605
50ecf157
DB
606 if (st->first_dts != AV_NOPTS_VALUE) {
607 cur_dts = st->first_dts;
608 for (; pktl; pktl = pktl->next) {
609 if (pktl->pkt.stream_index == stream_index) {
610 if (pktl->pkt.pts != pktl->pkt.dts ||
611 pktl->pkt.dts != AV_NOPTS_VALUE ||
612 pktl->pkt.duration)
820ad60c 613 break;
a7fa7568 614 cur_dts -= duration;
820ad60c
MN
615 }
616 }
9deaec78 617 pktl = s->internal->packet_buffer;
820ad60c 618 st->first_dts = cur_dts;
50ecf157 619 } else if (st->cur_dts)
820ad60c 620 return;
83a9db42 621
50ecf157
DB
622 for (; pktl; pktl = pktl->next) {
623 if (pktl->pkt.stream_index != stream_index)
83a9db42 624 continue;
50ecf157
DB
625 if (pktl->pkt.pts == pktl->pkt.dts &&
626 pktl->pkt.dts == AV_NOPTS_VALUE &&
627 !pktl->pkt.duration) {
628 pktl->pkt.dts = cur_dts;
9200514a 629 if (!st->internal->avctx->has_b_frames)
50ecf157 630 pktl->pkt.pts = cur_dts;
a7fa7568 631 cur_dts += duration;
9200514a 632 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
a7fa7568 633 pktl->pkt.duration = duration;
50ecf157 634 } else
83a9db42
MN
635 break;
636 }
50ecf157
DB
637 if (st->first_dts == AV_NOPTS_VALUE)
638 st->cur_dts = cur_dts;
83a9db42
MN
639}
640
115329f1 641static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
fb2758c8
FB
642 AVCodecParserContext *pc, AVPacket *pkt)
643{
d9e1efb7 644 int num, den, presentation_delayed, delay, i;
a74008a4 645 int64_t offset;
115329f1 646
fe8344a2
MN
647 if (s->flags & AVFMT_FLAG_NOFILLIN)
648 return;
649
50ecf157
DB
650 if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
651 pkt->dts = AV_NOPTS_VALUE;
c55806e3 652
f781f748 653 /* do we have a video B-frame ? */
9200514a 654 delay = st->internal->avctx->has_b_frames;
f781f748 655 presentation_delayed = 0;
37b00b47 656
f781f748 657 /* XXX: need has_b_frame, but cannot get it if the codec is
50ecf157 658 * not initialized */
f781f748 659 if (delay &&
975a1447 660 pc && pc->pict_type != AV_PICTURE_TYPE_B)
f781f748
MN
661 presentation_delayed = 1;
662
c5b46a06
MN
663 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
664 st->pts_wrap_bits < 63 &&
665 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
50ecf157 666 pkt->dts -= 1LL << st->pts_wrap_bits;
10a7571b
MN
667 }
668
50ecf157
DB
669 /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
670 * We take the conservative approach and discard both.
671 * Note: If this is misbehaving for an H.264 file, then possibly
672 * presentation_delayed is not set correctly. */
673 if (delay == 1 && pkt->dts == pkt->pts &&
674 pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
b0a18c2f 675 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
bd239c9a 676 pkt->dts = AV_NOPTS_VALUE;
9806f846
MN
677 }
678
9200514a 679 if (pkt->duration == 0 && st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
2d6e5849 680 ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
fb2758c8 681 if (den && num) {
50ecf157
DB
682 pkt->duration = av_rescale_rnd(1, num * (int64_t) st->time_base.den,
683 den * (int64_t) st->time_base.num,
684 AV_ROUND_DOWN);
83a9db42 685
9deaec78 686 if (pkt->duration != 0 && s->internal->packet_buffer)
50ecf157
DB
687 update_initial_durations(s, st, pkt->stream_index,
688 pkt->duration);
fb2758c8
FB
689 }
690 }
691
50ecf157
DB
692 /* Correct timestamps with byte offset if demuxers only have timestamps
693 * on packet boundaries */
694 if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
a74008a4
JP
695 /* this will estimate bitrate based on this frame's duration and size */
696 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
50ecf157 697 if (pkt->pts != AV_NOPTS_VALUE)
a74008a4 698 pkt->pts += offset;
50ecf157 699 if (pkt->dts != AV_NOPTS_VALUE)
a74008a4
JP
700 pkt->dts += offset;
701 }
702
755bfeab 703 /* This may be redundant, but it should not hurt. */
50ecf157
DB
704 if (pkt->dts != AV_NOPTS_VALUE &&
705 pkt->pts != AV_NOPTS_VALUE &&
706 pkt->pts > pkt->dts)
7e4baa66 707 presentation_delayed = 1;
115329f1 708
1a3eb042 709 av_log(NULL, AV_LOG_TRACE,
50ecf157
DB
710 "IN delayed:%d pts:%"PRId64", dts:%"PRId64" "
711 "cur_dts:%"PRId64" st:%d pc:%p\n",
72eaba5e
DB
712 presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
713 pkt->stream_index, pc);
50ecf157
DB
714 /* Interpolate PTS and DTS if they are not present. We skip H.264
715 * currently because delay and has_b_frames are not reliably set. */
716 if ((delay == 0 || (delay == 1 && pc)) &&
9200514a 717 st->codecpar->codec_id != AV_CODEC_ID_H264) {
7e4baa66 718 if (presentation_delayed) {
a85736f2
DB
719 /* DTS = decompression timestamp */
720 /* PTS = presentation timestamp */
7e4baa66 721 if (pkt->dts == AV_NOPTS_VALUE)
635fbcb1 722 pkt->dts = st->last_IP_pts;
9fcbcca6 723 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
7e4baa66
MN
724 if (pkt->dts == AV_NOPTS_VALUE)
725 pkt->dts = st->cur_dts;
726
50ecf157
DB
727 /* This is tricky: the dts must be incremented by the duration
728 * of the frame we are displaying, i.e. the last I- or P-frame. */
635fbcb1
MN
729 if (st->last_IP_duration == 0)
730 st->last_IP_duration = pkt->duration;
50ecf157 731 if (pkt->dts != AV_NOPTS_VALUE)
cdb5af79 732 st->cur_dts = pkt->dts + st->last_IP_duration;
50ecf157
DB
733 st->last_IP_duration = pkt->duration;
734 st->last_IP_pts = pkt->pts;
735 /* Cannot compute PTS if not present (we can compute it only
736 * by knowing the future. */
a7fa7568
JR
737 } else if (pkt->pts != AV_NOPTS_VALUE ||
738 pkt->dts != AV_NOPTS_VALUE ||
739 pkt->duration ||
9200514a 740 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
a7fa7568 741 int duration = pkt->duration;
9200514a 742 if (!duration && st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2d6e5849 743 ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
a7fa7568 744 if (den && num) {
50ecf157
DB
745 duration = av_rescale_rnd(1,
746 num * (int64_t) st->time_base.den,
747 den * (int64_t) st->time_base.num,
748 AV_ROUND_DOWN);
9deaec78 749 if (duration != 0 && s->internal->packet_buffer)
a7fa7568
JR
750 update_initial_durations(s, st, pkt->stream_index,
751 duration);
a7fa7568
JR
752 }
753 }
754
8916f1fb
JR
755 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
756 duration) {
e5356ebf
JR
757 /* presentation is not delayed : PTS and DTS are the same */
758 if (pkt->pts == AV_NOPTS_VALUE)
759 pkt->pts = pkt->dts;
760 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
761 pkt->pts);
762 if (pkt->pts == AV_NOPTS_VALUE)
763 pkt->pts = st->cur_dts;
764 pkt->dts = pkt->pts;
765 if (pkt->pts != AV_NOPTS_VALUE)
766 st->cur_dts = pkt->pts + duration;
8916f1fb 767 }
7e4baa66 768 }
fb2758c8 769 }
d9e1efb7 770
50ecf157
DB
771 if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
772 st->pts_buffer[0] = pkt->pts;
773 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
774 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
775 if (pkt->dts == AV_NOPTS_VALUE)
776 pkt->dts = st->pts_buffer[0];
777 // We skipped it above so we try here.
9200514a 778 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
50ecf157
DB
779 // This should happen on the first packet
780 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
781 if (pkt->dts > st->cur_dts)
d9e1efb7
MN
782 st->cur_dts = pkt->dts;
783 }
784
1a3eb042 785 av_log(NULL, AV_LOG_TRACE,
72eaba5e
DB
786 "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
787 presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
115329f1 788
fb2758c8 789 /* update flags */
9200514a 790 if (is_intra_only(st->codecpar->codec_id))
cc947f04 791 pkt->flags |= AV_PKT_FLAG_KEY;
948f3c19 792#if FF_API_CONVERGENCE_DURATION
793FF_DISABLE_DEPRECATION_WARNINGS
b1fa4942
IS
794 if (pc)
795 pkt->convergence_duration = pc->convergence_duration;
948f3c19 796FF_ENABLE_DEPRECATION_WARNINGS
797#endif
fb2758c8
FB
798}
799
52b0943f
AK
800static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
801{
802 while (*pkt_buf) {
803 AVPacketList *pktl = *pkt_buf;
804 *pkt_buf = pktl->next;
ce70f28a 805 av_packet_unref(&pktl->pkt);
52b0943f
AK
806 av_freep(&pktl);
807 }
808 *pkt_buf_end = NULL;
809}
810
27c7ca9c 811/**
50ecf157 812 * Parse a packet, add all split parts to parse_queue.
27c7ca9c 813 *
50ecf157 814 * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
27c7ca9c
AK
815 */
816static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
817{
818 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
50ecf157
DB
819 AVStream *st = s->streams[stream_index];
820 uint8_t *data = pkt ? pkt->data : NULL;
821 int size = pkt ? pkt->size : 0;
27c7ca9c
AK
822 int ret = 0, got_output = 0;
823
824 if (!pkt) {
825 av_init_packet(&flush_pkt);
50ecf157 826 pkt = &flush_pkt;
27c7ca9c
AK
827 got_output = 1;
828 }
829
830 while (size > 0 || (pkt == &flush_pkt && got_output)) {
831 int len;
832
833 av_init_packet(&out_pkt);
9200514a 834 len = av_parser_parse2(st->parser, st->internal->avctx,
27c7ca9c
AK
835 &out_pkt.data, &out_pkt.size, data, size,
836 pkt->pts, pkt->dts, pkt->pos);
837
838 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
839 /* increment read pointer */
840 data += len;
841 size -= len;
842
843 got_output = !!out_pkt.size;
844
845 if (!out_pkt.size)
846 continue;
847
c330eba8
AK
848 if (pkt->side_data) {
849 out_pkt.side_data = pkt->side_data;
850 out_pkt.side_data_elems = pkt->side_data_elems;
50ecf157
DB
851 pkt->side_data = NULL;
852 pkt->side_data_elems = 0;
c330eba8
AK
853 }
854
27c7ca9c
AK
855 /* set the duration */
856 out_pkt.duration = 0;
9200514a
AK
857 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
858 if (st->internal->avctx->sample_rate > 0) {
50ecf157
DB
859 out_pkt.duration =
860 av_rescale_q_rnd(st->parser->duration,
9200514a 861 (AVRational) { 1, st->internal->avctx->sample_rate },
50ecf157
DB
862 st->time_base,
863 AV_ROUND_DOWN);
27c7ca9c 864 }
27c7ca9c
AK
865 }
866
867 out_pkt.stream_index = st->index;
50ecf157
DB
868 out_pkt.pts = st->parser->pts;
869 out_pkt.dts = st->parser->dts;
870 out_pkt.pos = st->parser->pos;
27c7ca9c
AK
871
872 if (st->parser->key_frame == 1 ||
873 (st->parser->key_frame == -1 &&
874 st->parser->pict_type == AV_PICTURE_TYPE_I))
875 out_pkt.flags |= AV_PKT_FLAG_KEY;
876
877 compute_pkt_fields(s, st, st->parser, &out_pkt);
878
879 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
880 out_pkt.flags & AV_PKT_FLAG_KEY) {
881 ff_reduce_index(s, st->index);
882 av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
883 0, 0, AVINDEX_KEYFRAME);
884 }
885
d584533c
LB
886 if ((ret = add_to_pktbuf(&s->internal->parse_queue, &out_pkt,
887 &s->internal->parse_queue_end,
888 1))) {
ce70f28a 889 av_packet_unref(&out_pkt);
27c7ca9c
AK
890 goto fail;
891 }
892 }
893
27c7ca9c
AK
894 /* end of the stream => close and free the parser */
895 if (pkt == &flush_pkt) {
896 av_parser_close(st->parser);
897 st->parser = NULL;
898 }
899
900fail:
ce70f28a 901 av_packet_unref(pkt);
27c7ca9c
AK
902 return ret;
903}
904
dcee8115
AK
905static int read_from_packet_buffer(AVPacketList **pkt_buffer,
906 AVPacketList **pkt_buffer_end,
907 AVPacket *pkt)
908{
909 AVPacketList *pktl;
910 av_assert0(*pkt_buffer);
50ecf157
DB
911 pktl = *pkt_buffer;
912 *pkt = pktl->pkt;
dcee8115
AK
913 *pkt_buffer = pktl->next;
914 if (!pktl->next)
915 *pkt_buffer_end = NULL;
916 av_freep(&pktl);
917 return 0;
918}
919
d3bb7191 920static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
fb2758c8 921{
27c7ca9c 922 int ret = 0, i, got_packet = 0;
019d3fcc 923 AVDictionary *metadata = NULL;
fb2758c8 924
b237eb80
MN
925 av_init_packet(pkt);
926
9deaec78 927 while (!got_packet && !s->internal->parse_queue) {
27c7ca9c
AK
928 AVStream *st;
929 AVPacket cur_pkt;
e9b78eeb 930
27c7ca9c 931 /* read next packet */
3c90cc2e 932 ret = ff_read_packet(s, &cur_pkt);
27c7ca9c
AK
933 if (ret < 0) {
934 if (ret == AVERROR(EAGAIN))
fb2758c8 935 return ret;
27c7ca9c 936 /* flush the parsers */
50ecf157 937 for (i = 0; i < s->nb_streams; i++) {
27c7ca9c
AK
938 st = s->streams[i];
939 if (st->parser && st->need_parsing)
940 parse_packet(s, NULL, st->index);
37353960 941 }
27c7ca9c
AK
942 /* all remaining packets are now in parse_queue =>
943 * really terminate parsing */
944 break;
945 }
946 ret = 0;
947 st = s->streams[cur_pkt.stream_index];
948
949 if (cur_pkt.pts != AV_NOPTS_VALUE &&
950 cur_pkt.dts != AV_NOPTS_VALUE &&
951 cur_pkt.pts < cur_pkt.dts) {
50ecf157
DB
952 av_log(s, AV_LOG_WARNING,
953 "Invalid timestamps stream=%d, pts=%"PRId64", "
954 "dts=%"PRId64", size=%d\n",
955 cur_pkt.stream_index, cur_pkt.pts,
956 cur_pkt.dts, cur_pkt.size);
27c7ca9c
AK
957 }
958 if (s->debug & FF_FDEBUG_TS)
50ecf157
DB
959 av_log(s, AV_LOG_DEBUG,
960 "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", "
948f3c19 961 "size=%d, duration=%"PRId64", flags=%d\n",
50ecf157
DB
962 cur_pkt.stream_index, cur_pkt.pts, cur_pkt.dts,
963 cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
27c7ca9c
AK
964
965 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
9200514a 966 st->parser = av_parser_init(st->codecpar->codec_id);
50ecf157 967 if (!st->parser)
27c7ca9c
AK
968 /* no parser available: just output the raw packets */
969 st->need_parsing = AVSTREAM_PARSE_NONE;
50ecf157 970 else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
27c7ca9c 971 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
50ecf157 972 else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
27c7ca9c 973 st->parser->flags |= PARSER_FLAG_ONCE;
27c7ca9c 974 }
b18a4ab2 975
27c7ca9c
AK
976 if (!st->need_parsing || !st->parser) {
977 /* no parsing needed: we just output the packet as is */
978 *pkt = cur_pkt;
979 compute_pkt_fields(s, st, NULL, pkt);
980 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
981 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
982 ff_reduce_index(s, st->index);
50ecf157
DB
983 av_add_index_entry(st, pkt->pos, pkt->dts,
984 0, 0, AVINDEX_KEYFRAME);
fb2758c8 985 }
27c7ca9c
AK
986 got_packet = 1;
987 } else if (st->discard < AVDISCARD_ALL) {
988 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
989 return ret;
990 } else {
991 /* free packet */
ce70f28a 992 av_packet_unref(&cur_pkt);
fb2758c8
FB
993 }
994 }
27c7ca9c 995
9deaec78 996 if (!got_packet && s->internal->parse_queue)
997 ret = read_from_packet_buffer(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
27c7ca9c 998
019d3fcc
AS
999 av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1000 if (metadata) {
1001 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1002 av_dict_copy(&s->metadata, metadata, 0);
1003 av_dict_free(&metadata);
1004 av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
1005 }
1006
9200514a
AK
1007#if FF_API_LAVF_AVCTX
1008 update_stream_avctx(s);
1009#endif
1010
50ecf157
DB
1011 if (s->debug & FF_FDEBUG_TS)
1012 av_log(s, AV_LOG_DEBUG,
1013 "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", "
948f3c19 1014 "size=%d, duration=%"PRId64", flags=%d\n",
50ecf157
DB
1015 pkt->stream_index, pkt->pts, pkt->dts,
1016 pkt->size, pkt->duration, pkt->flags);
434cab9e 1017
27c7ca9c 1018 return ret;
fb2758c8
FB
1019}
1020
fb2758c8
FB
1021int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1022{
f9b9dd87 1023 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
50ecf157 1024 int eof = 0;
30bc6613 1025
6450599e 1026 if (!genpts)
9deaec78 1027 return s->internal->packet_buffer
1028 ? read_from_packet_buffer(&s->internal->packet_buffer,
1029 &s->internal->packet_buffer_end, pkt)
50ecf157 1030 : read_frame_internal(s, pkt);
6450599e 1031
f9b9dd87 1032 for (;;) {
6450599e 1033 int ret;
9deaec78 1034 AVPacketList *pktl = s->internal->packet_buffer;
6450599e 1035
30bc6613 1036 if (pktl) {
f9b9dd87 1037 AVPacket *next_pkt = &pktl->pkt;
30bc6613 1038
6450599e 1039 if (next_pkt->dts != AV_NOPTS_VALUE) {
5be5d28c 1040 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
f9b9dd87
AK
1041 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1042 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1043 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
50ecf157
DB
1044 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {
1045 // not B-frame
f9b9dd87 1046 next_pkt->pts = pktl->pkt.dts;
30bc6613 1047 }
f9b9dd87 1048 pktl = pktl->next;
30bc6613 1049 }
9deaec78 1050 pktl = s->internal->packet_buffer;
30bc6613 1051 }
115329f1 1052
6450599e
AK
1053 /* read packet from packet buffer, if there is data */
1054 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1055 next_pkt->dts != AV_NOPTS_VALUE && !eof))
9deaec78 1056 return read_from_packet_buffer(&s->internal->packet_buffer,
1057 &s->internal->packet_buffer_end, pkt);
30bc6613 1058 }
115329f1 1059
6450599e
AK
1060 ret = read_frame_internal(s, pkt);
1061 if (ret < 0) {
1062 if (pktl && ret != AVERROR(EAGAIN)) {
1063 eof = 1;
1064 continue;
1065 } else
1066 return ret;
30bc6613 1067 }
6450599e 1068
d584533c
LB
1069 ret = add_to_pktbuf(&s->internal->packet_buffer, pkt,
1070 &s->internal->packet_buffer_end, 1);
1071 if (ret < 0)
1072 return ret;
fb2758c8
FB
1073 }
1074}
1075
1076/* XXX: suppress the packet queue */
1077static void flush_packet_queue(AVFormatContext *s)
1078{
9deaec78 1079 free_packet_buffer(&s->internal->parse_queue, &s->internal->parse_queue_end);
1080 free_packet_buffer(&s->internal->packet_buffer, &s->internal->packet_buffer_end);
1081 free_packet_buffer(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
fb2758c8 1082
9deaec78 1083 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
b9a281db
FB
1084}
1085
da24c5e3 1086/*******************************************************/
fb2758c8
FB
1087/* seek support */
1088
b754978a
MN
1089int av_find_default_stream_index(AVFormatContext *s)
1090{
ca162a50 1091 int first_audio_index = -1;
b754978a
MN
1092 int i;
1093 AVStream *st;
1094
1095 if (s->nb_streams <= 0)
1096 return -1;
50ecf157 1097 for (i = 0; i < s->nb_streams; i++) {
b754978a 1098 st = s->streams[i];
9200514a 1099 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
cd9a3c35 1100 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
b754978a
MN
1101 return i;
1102 }
50ecf157 1103 if (first_audio_index < 0 &&
9200514a 1104 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
ca162a50 1105 first_audio_index = i;
b754978a 1106 }
ca162a50 1107 return first_audio_index >= 0 ? first_audio_index : 0;
b754978a
MN
1108}
1109
50ecf157 1110/** Flush the frame reader. */
972ffe62 1111void ff_read_frame_flush(AVFormatContext *s)
fb2758c8
FB
1112{
1113 AVStream *st;
106fa129 1114 int i, j;
fb2758c8
FB
1115
1116 flush_packet_queue(s);
1117
50ecf157
DB
1118 /* Reset read state for each stream. */
1119 for (i = 0; i < s->nb_streams; i++) {
fb2758c8 1120 st = s->streams[i];
115329f1 1121
fb2758c8
FB
1122 if (st->parser) {
1123 av_parser_close(st->parser);
1124 st->parser = NULL;
1125 }
635fbcb1 1126 st->last_IP_pts = AV_NOPTS_VALUE;
50ecf157
DB
1127 /* We set the current DTS to an unspecified origin. */
1128 st->cur_dts = AV_NOPTS_VALUE;
86cb7e33
BC
1129
1130 st->probe_packets = MAX_PROBE_PACKETS;
106fa129 1131
50ecf157
DB
1132 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1133 st->pts_buffer[j] = AV_NOPTS_VALUE;
fb2758c8
FB
1134 }
1135}
1136
a2faa951
AK
1137void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1138{
8bcb147f
MN
1139 int i;
1140
50ecf157 1141 for (i = 0; i < s->nb_streams; i++) {
1a1dc611 1142 AVStream *st = s->streams[i];
8bcb147f 1143
50ecf157
DB
1144 st->cur_dts =
1145 av_rescale(timestamp,
1146 st->time_base.den * (int64_t) ref_st->time_base.num,
1147 st->time_base.num * (int64_t) ref_st->time_base.den);
8bcb147f
MN
1148 }
1149}
1150
3dea63bd
PK
1151void ff_reduce_index(AVFormatContext *s, int stream_index)
1152{
50ecf157
DB
1153 AVStream *st = s->streams[stream_index];
1154 unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
3dea63bd 1155
50ecf157 1156 if ((unsigned) st->nb_index_entries >= max_entries) {
3dea63bd 1157 int i;
50ecf157
DB
1158 for (i = 0; 2 * i < st->nb_index_entries; i++)
1159 st->index_entries[i] = st->index_entries[2 * i];
1160 st->nb_index_entries = i;
3dea63bd
PK
1161 }
1162}
1163
e6fb5a4f
PR
1164int ff_add_index_entry(AVIndexEntry **index_entries,
1165 int *nb_index_entries,
1166 unsigned int *index_entries_allocated_size,
50ecf157
DB
1167 int64_t pos, int64_t timestamp,
1168 int size, int distance, int flags)
fb2758c8
FB
1169{
1170 AVIndexEntry *entries, *ie;
b754978a 1171 int index;
115329f1 1172
50ecf157 1173 if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
568e18b1 1174 return -1;
115329f1 1175
e6fb5a4f
PR
1176 entries = av_fast_realloc(*index_entries,
1177 index_entries_allocated_size,
1178 (*nb_index_entries + 1) *
fb2758c8 1179 sizeof(AVIndexEntry));
50ecf157 1180 if (!entries)
568e18b1
MN
1181 return -1;
1182
50ecf157 1183 *index_entries = entries;
b754978a 1184
50ecf157
DB
1185 index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
1186 timestamp, AVSEEK_FLAG_ANY);
b754978a 1187
50ecf157
DB
1188 if (index < 0) {
1189 index = (*nb_index_entries)++;
1190 ie = &entries[index];
1191 assert(index == 0 || ie[-1].timestamp < timestamp);
1192 } else {
1193 ie = &entries[index];
1194 if (ie->timestamp != timestamp) {
1195 if (ie->timestamp <= timestamp)
528c2c73 1196 return -1;
50ecf157
DB
1197 memmove(entries + index + 1, entries + index,
1198 sizeof(AVIndexEntry) * (*nb_index_entries - index));
e6fb5a4f 1199 (*nb_index_entries)++;
50ecf157
DB
1200 } else if (ie->pos == pos && distance < ie->min_distance)
1201 // do not reduce the distance
1202 distance = ie->min_distance;
3e9245a9 1203 }
3ba1438d 1204
50ecf157
DB
1205 ie->pos = pos;
1206 ie->timestamp = timestamp;
1207 ie->min_distance = distance;
1208 ie->size = size;
1209 ie->flags = flags;
115329f1 1210
3e9245a9 1211 return index;
fb2758c8
FB
1212}
1213
50ecf157
DB
1214int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
1215 int size, int distance, int flags)
e6fb5a4f
PR
1216{
1217 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1218 &st->index_entries_allocated_size, pos,
1219 timestamp, size, distance, flags);
1220}
1221
1222int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1223 int64_t wanted_timestamp, int flags)
fb2758c8
FB
1224{
1225 int a, b, m;
1226 int64_t timestamp;
1227
50ecf157 1228 a = -1;
3ba1438d 1229 b = nb_entries;
b754978a 1230
50ecf157
DB
1231 // Optimize appending index entries at the end.
1232 if (b && entries[b - 1].timestamp < wanted_timestamp)
1233 a = b - 1;
67c10de7 1234
3ba1438d 1235 while (b - a > 1) {
50ecf157 1236 m = (a + b) >> 1;
fb2758c8 1237 timestamp = entries[m].timestamp;
50ecf157 1238 if (timestamp >= wanted_timestamp)
3ba1438d 1239 b = m;
50ecf157 1240 if (timestamp <= wanted_timestamp)
b754978a 1241 a = m;
fb2758c8 1242 }
50ecf157 1243 m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
115329f1 1244
50ecf157
DB
1245 if (!(flags & AVSEEK_FLAG_ANY))
1246 while (m >= 0 && m < nb_entries &&
1247 !(entries[m].flags & AVINDEX_KEYFRAME))
27a5fe5f 1248 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
3ba1438d 1249
50ecf157 1250 if (m == nb_entries)
3ba1438d 1251 return -1;
50ecf157 1252 return m;
fb2758c8
FB
1253}
1254
50ecf157 1255int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
e6fb5a4f
PR
1256{
1257 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1258 wanted_timestamp, flags);
1259}
1260
50ecf157
DB
1261int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
1262 int64_t target_ts, int flags)
a2faa951 1263{
50ecf157 1264 AVInputFormat *avif = s->iformat;
e6586575 1265 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
8d14a25c 1266 int64_t ts_min, ts_max, ts;
89ddd2a9 1267 int index;
b593f7fd 1268 int64_t ret;
8d14a25c
MN
1269 AVStream *st;
1270
cdd5034f
MN
1271 if (stream_index < 0)
1272 return -1;
115329f1 1273
1a3eb042 1274 av_log(s, AV_LOG_TRACE, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
8d14a25c 1275
50ecf157
DB
1276 ts_max =
1277 ts_min = AV_NOPTS_VALUE;
1278 pos_limit = -1; // GCC falsely says it may be uninitialized.
8d14a25c 1279
50ecf157
DB
1280 st = s->streams[stream_index];
1281 if (st->index_entries) {
8d14a25c
MN
1282 AVIndexEntry *e;
1283
50ecf157
DB
1284 /* FIXME: Whole function must be checked for non-keyframe entries in
1285 * index case, especially read_timestamp(). */
1286 index = av_index_search_timestamp(st, target_ts,
1287 flags | AVSEEK_FLAG_BACKWARD);
1288 index = FFMAX(index, 0);
1289 e = &st->index_entries[index];
8d14a25c 1290
50ecf157
DB
1291 if (e->timestamp <= target_ts || e->pos == e->min_distance) {
1292 pos_min = e->pos;
1293 ts_min = e->timestamp;
1a3eb042 1294 av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
50ecf157
DB
1295 pos_min, ts_min);
1296 } else {
1297 assert(index == 0);
8d14a25c 1298 }
115329f1 1299
50ecf157
DB
1300 index = av_index_search_timestamp(st, target_ts,
1301 flags & ~AVSEEK_FLAG_BACKWARD);
27a5fe5f 1302 assert(index < st->nb_index_entries);
50ecf157
DB
1303 if (index >= 0) {
1304 e = &st->index_entries[index];
8d14a25c 1305 assert(e->timestamp >= target_ts);
50ecf157
DB
1306 pos_max = e->pos;
1307 ts_max = e->timestamp;
1308 pos_limit = pos_max - e->min_distance;
1a3eb042 1309 av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
50ecf157 1310 " dts_max=%"PRId64"\n", pos_max, pos_limit, ts_max);
8d14a25c
MN
1311 }
1312 }
1313
50ecf157
DB
1314 pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
1315 ts_min, ts_max, flags, &ts, avif->read_timestamp);
1316 if (pos < 0)
89ddd2a9
MN
1317 return -1;
1318
1319 /* do the seek */
6b4aa5da 1320 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
b593f7fd 1321 return ret;
89ddd2a9 1322
a2faa951 1323 ff_update_cur_dts(s, st, ts);
89ddd2a9
MN
1324
1325 return 0;
1326}
1327
a2faa951
AK
1328int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1329 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
50ecf157
DB
1330 int64_t ts_min, int64_t ts_max,
1331 int flags, int64_t *ts_ret,
1332 int64_t (*read_timestamp)(struct AVFormatContext *, int,
1333 int64_t *, int64_t))
a2faa951 1334{
89ddd2a9
MN
1335 int64_t pos, ts;
1336 int64_t start_pos, filesize;
1337 int no_change;
1338
1a3eb042 1339 av_log(s, AV_LOG_TRACE, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
89ddd2a9 1340
50ecf157 1341 if (ts_min == AV_NOPTS_VALUE) {
9deaec78 1342 pos_min = s->internal->data_offset;
50ecf157 1343 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
8d14a25c
MN
1344 if (ts_min == AV_NOPTS_VALUE)
1345 return -1;
1346 }
1347
50ecf157
DB
1348 if (ts_max == AV_NOPTS_VALUE) {
1349 int step = 1024;
76aa876e 1350 filesize = avio_size(s->pb);
50ecf157
DB
1351 pos_max = filesize - 1;
1352 do {
8d14a25c 1353 pos_max -= step;
50ecf157
DB
1354 ts_max = read_timestamp(s, stream_index, &pos_max,
1355 pos_max + step);
1356 step += step;
1357 } while (ts_max == AV_NOPTS_VALUE && pos_max >= step);
8d14a25c
MN
1358 if (ts_max == AV_NOPTS_VALUE)
1359 return -1;
115329f1 1360
50ecf157
DB
1361 for (;;) {
1362 int64_t tmp_pos = pos_max + 1;
1363 int64_t tmp_ts = read_timestamp(s, stream_index,
1364 &tmp_pos, INT64_MAX);
1365 if (tmp_ts == AV_NOPTS_VALUE)
8d14a25c 1366 break;
50ecf157
DB
1367 ts_max = tmp_ts;
1368 pos_max = tmp_pos;
1369 if (tmp_pos >= filesize)
6fd93ce2 1370 break;
8d14a25c 1371 }
50ecf157 1372 pos_limit = pos_max;
8d14a25c
MN
1373 }
1374
50ecf157 1375 if (ts_min > ts_max)
53f7c43f 1376 return -1;
50ecf157
DB
1377 else if (ts_min == ts_max)
1378 pos_limit = pos_min;
53f7c43f 1379
50ecf157 1380 no_change = 0;
8d14a25c 1381 while (pos_min < pos_limit) {
1a3eb042 1382 av_log(s, AV_LOG_TRACE, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64
50ecf157 1383 " dts_max=%"PRId64"\n", pos_min, pos_max, ts_min, ts_max);
8d14a25c
MN
1384 assert(pos_limit <= pos_max);
1385
50ecf157
DB
1386 if (no_change == 0) {
1387 int64_t approximate_keyframe_distance = pos_max - pos_limit;
8d14a25c 1388 // interpolate position (better than dichotomy)
50ecf157
DB
1389 pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
1390 ts_max - ts_min) +
1391 pos_min - approximate_keyframe_distance;
1392 } else if (no_change == 1) {
1393 // bisection if interpolation did not change min / max pos last time
1394 pos = (pos_min + pos_limit) >> 1;
1395 } else {
a85736f2 1396 /* linear search if bisection failed, can only happen if there
50ecf157
DB
1397 * are very few or no keyframes between min/max */
1398 pos = pos_min;
1399 }
1400 if (pos <= pos_min)
1401 pos = pos_min + 1;
1402 else if (pos > pos_limit)
1403 pos = pos_limit;
1404 start_pos = pos;
1405
1406 // May pass pos_limit instead of -1.
1407 ts = read_timestamp(s, stream_index, &pos, INT64_MAX);
1408 if (pos == pos_max)
8d14a25c
MN
1409 no_change++;
1410 else
50ecf157 1411 no_change = 0;
1a3eb042 1412 av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64
50ecf157 1413 " target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
919d7a34
DB
1414 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1415 pos_limit, start_pos, no_change);
50ecf157 1416 if (ts == AV_NOPTS_VALUE) {
db2a0e22
MN
1417 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1418 return -1;
1419 }
8d14a25c 1420 assert(ts != AV_NOPTS_VALUE);
3ba1438d 1421 if (target_ts <= ts) {
8d14a25c 1422 pos_limit = start_pos - 1;
50ecf157
DB
1423 pos_max = pos;
1424 ts_max = ts;
3ba1438d
MN
1425 }
1426 if (target_ts >= ts) {
8d14a25c 1427 pos_min = pos;
50ecf157 1428 ts_min = ts;
8d14a25c
MN
1429 }
1430 }
115329f1 1431
50ecf157
DB
1432 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1433 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
8d14a25c 1434 pos_min = pos;
50ecf157 1435 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
8d14a25c 1436 pos_min++;
89ddd2a9 1437 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1a3eb042 1438 av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
919d7a34 1439 pos, ts_min, target_ts, ts_max);
50ecf157 1440 *ts_ret = ts;
89ddd2a9 1441 return pos;
8d14a25c
MN
1442}
1443
50ecf157
DB
1444static int seek_frame_byte(AVFormatContext *s, int stream_index,
1445 int64_t pos, int flags)
1446{
3ba1438d 1447 int64_t pos_min, pos_max;
3ba1438d 1448
9deaec78 1449 pos_min = s->internal->data_offset;
76aa876e 1450 pos_max = avio_size(s->pb) - 1;
3ba1438d 1451
50ecf157
DB
1452 if (pos < pos_min)
1453 pos = pos_min;
1454 else if (pos > pos_max)
1455 pos = pos_max;
3ba1438d 1456
6b4aa5da 1457 avio_seek(s->pb, pos, SEEK_SET);
3ba1438d 1458
3ba1438d
MN
1459 return 0;
1460}
1461
50ecf157
DB
1462static int seek_frame_generic(AVFormatContext *s, int stream_index,
1463 int64_t timestamp, int flags)
fb2758c8 1464{
6659b32a
SS
1465 int index;
1466 int64_t ret;
fb2758c8
FB
1467 AVStream *st;
1468 AVIndexEntry *ie;
1469
fb2758c8 1470 st = s->streams[stream_index];
e9b78eeb 1471
27a5fe5f 1472 index = av_index_search_timestamp(st, timestamp, flags);
e9b78eeb 1473
50ecf157
DB
1474 if (index < 0 && st->nb_index_entries &&
1475 timestamp < st->index_entries[0].timestamp)
8c3b161e
MN
1476 return -1;
1477
50ecf157 1478 if (index < 0 || index == st->nb_index_entries - 1) {
e9b78eeb
MN
1479 AVPacket pkt;
1480
50ecf157 1481 if (st->nb_index_entries) {
5e5c9086 1482 assert(st->index_entries);
50ecf157 1483 ie = &st->index_entries[st->nb_index_entries - 1];
6b4aa5da 1484 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
aaec4e03 1485 return ret;
a2faa951 1486 ff_update_cur_dts(s, st, ie->timestamp);
50ecf157 1487 } else {
9deaec78 1488 if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
aaec4e03
BC
1489 return ret;
1490 }
940173d4 1491 for (;;) {
4439caa4 1492 int read_status;
50ecf157 1493 do {
4439caa4
AC
1494 read_status = av_read_frame(s, &pkt);
1495 } while (read_status == AVERROR(EAGAIN));
1496 if (read_status < 0)
e9b78eeb 1497 break;
ce70f28a 1498 av_packet_unref(&pkt);
50ecf157
DB
1499 if (stream_index == pkt.stream_index)
1500 if ((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
e9b78eeb 1501 break;
e9b78eeb
MN
1502 }
1503 index = av_index_search_timestamp(st, timestamp, flags);
1504 }
fb2758c8
FB
1505 if (index < 0)
1506 return -1;
1507
972ffe62 1508 ff_read_frame_flush(s);
50ecf157
DB
1509 if (s->iformat->read_seek)
1510 if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
e9b78eeb 1511 return 0;
e9b78eeb 1512 ie = &st->index_entries[index];
6b4aa5da 1513 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
aaec4e03 1514 return ret;
a2faa951 1515 ff_update_cur_dts(s, st, ie->timestamp);
cdd5034f 1516
fb2758c8
FB
1517 return 0;
1518}
1519
01fcc42b
AK
1520static int seek_frame_internal(AVFormatContext *s, int stream_index,
1521 int64_t timestamp, int flags)
fb2758c8
FB
1522{
1523 int ret;
cdd5034f 1524 AVStream *st;
115329f1 1525
0041cdba 1526 if (flags & AVSEEK_FLAG_BYTE) {
b631fba9
JR
1527 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1528 return -1;
0041cdba 1529 ff_read_frame_flush(s);
d3bb7191 1530 return seek_frame_byte(s, stream_index, timestamp, flags);
0041cdba 1531 }
115329f1 1532
50ecf157
DB
1533 if (stream_index < 0) {
1534 stream_index = av_find_default_stream_index(s);
1535 if (stream_index < 0)
cdd5034f 1536 return -1;
115329f1 1537
50ecf157 1538 st = s->streams[stream_index];
7e6029f9 1539 /* timestamp for default must be expressed in AV_TIME_BASE units */
50ecf157
DB
1540 timestamp = av_rescale(timestamp, st->time_base.den,
1541 AV_TIME_BASE * (int64_t) st->time_base.num);
cdd5034f 1542 }
cdd5034f 1543
fb2758c8 1544 /* first, we try the format specific seek */
0041cdba
JR
1545 if (s->iformat->read_seek) {
1546 ff_read_frame_flush(s);
3ba1438d 1547 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
0041cdba 1548 } else
fb2758c8 1549 ret = -1;
50ecf157 1550 if (ret >= 0)
fb2758c8 1551 return 0;
8d14a25c 1552
50ecf157
DB
1553 if (s->iformat->read_timestamp &&
1554 !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
0041cdba 1555 ff_read_frame_flush(s);
a2faa951 1556 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
0041cdba
JR
1557 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1558 ff_read_frame_flush(s);
d3bb7191 1559 return seek_frame_generic(s, stream_index, timestamp, flags);
50ecf157 1560 } else
69fa2396 1561 return -1;
fb2758c8
FB
1562}
1563
50ecf157
DB
1564int av_seek_frame(AVFormatContext *s, int stream_index,
1565 int64_t timestamp, int flags)
01fcc42b
AK
1566{
1567 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1568
1569 if (ret >= 0)
1afddbe5 1570 ret = queue_attached_pictures(s);
01fcc42b
AK
1571
1572 return ret;
1573}
1574
50ecf157
DB
1575int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
1576 int64_t ts, int64_t max_ts, int flags)
32d88592 1577{
50ecf157 1578 if (min_ts > ts || max_ts < ts)
32d88592
MN
1579 return -1;
1580
0041cdba 1581 if (s->iformat->read_seek2) {
01fcc42b 1582 int ret;
0041cdba 1583 ff_read_frame_flush(s);
50ecf157
DB
1584 ret = s->iformat->read_seek2(s, stream_index, min_ts,
1585 ts, max_ts, flags);
01fcc42b
AK
1586
1587 if (ret >= 0)
1afddbe5 1588 ret = queue_attached_pictures(s);
01fcc42b 1589 return ret;
0041cdba 1590 }
32d88592 1591
50ecf157
DB
1592 if (s->iformat->read_timestamp) {
1593 // try to seek via read_timestamp()
32d88592
MN
1594 }
1595
a5f88736
DB
1596 // Fall back on old API if new is not implemented but old is.
1597 // Note the old API has somewhat different semantics.
50ecf157
DB
1598 if (s->iformat->read_seek || 1)
1599 return av_seek_frame(s, stream_index, ts,
1600 flags | ((uint64_t) ts - min_ts >
1601 (uint64_t) max_ts - ts
1602 ? AVSEEK_FLAG_BACKWARD : 0));
32d88592 1603
d3bb7191 1604 // try some generic seek like seek_frame_generic() but with new ts semantics
32d88592
MN
1605}
1606
fb2758c8 1607/*******************************************************/
12f996ed 1608
e36bdf8b 1609/**
49bd8e4b 1610 * Return TRUE if the stream has accurate duration in any stream.
e36bdf8b 1611 *
c1e8b678 1612 * @return TRUE if the stream has accurate duration for at least one component.
e36bdf8b 1613 */
d3bb7191 1614static int has_duration(AVFormatContext *ic)
12f996ed
FB
1615{
1616 int i;
1617 AVStream *st;
1618
50ecf157 1619 for (i = 0; i < ic->nb_streams; i++) {
12f996ed 1620 st = ic->streams[i];
c1e8b678 1621 if (st->duration != AV_NOPTS_VALUE)
12f996ed
FB
1622 return 1;
1623 }
8b97ae64 1624 if (ic->duration != AV_NOPTS_VALUE)
cbf767a8 1625 return 1;
12f996ed
FB
1626 return 0;
1627}
1628
e36bdf8b
DK
1629/**
1630 * Estimate the stream timings from the one of each components.
1631 *
1632 * Also computes the global bitrate if possible.
1633 */
d3bb7191 1634static void update_stream_timings(AVFormatContext *ic)
12f996ed 1635{
c0df9d75 1636 int64_t start_time, start_time1, end_time, end_time1;
c10731e7 1637 int64_t duration, duration1, filesize;
12f996ed
FB
1638 int i;
1639 AVStream *st;
1640
f27a7268 1641 start_time = INT64_MAX;
50ecf157
DB
1642 end_time = INT64_MIN;
1643 duration = INT64_MIN;
1644 for (i = 0; i < ic->nb_streams; i++) {
12f996ed 1645 st = ic->streams[i];
7f938dd3 1646 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
50ecf157
DB
1647 start_time1 = av_rescale_q(st->start_time, st->time_base,
1648 AV_TIME_BASE_Q);
1649 start_time = FFMIN(start_time, start_time1);
12f996ed 1650 if (st->duration != AV_NOPTS_VALUE) {
50ecf157
DB
1651 end_time1 = start_time1 +
1652 av_rescale_q(st->duration, st->time_base,
1653 AV_TIME_BASE_Q);
a7503430 1654 end_time = FFMAX(end_time, end_time1);
12f996ed
FB
1655 }
1656 }
c1e8b678 1657 if (st->duration != AV_NOPTS_VALUE) {
50ecf157
DB
1658 duration1 = av_rescale_q(st->duration, st->time_base,
1659 AV_TIME_BASE_Q);
1660 duration = FFMAX(duration, duration1);
c1e8b678 1661 }
12f996ed 1662 }
f27a7268 1663 if (start_time != INT64_MAX) {
12f996ed 1664 ic->start_time = start_time;
a7503430
AK
1665 if (end_time != INT64_MIN)
1666 duration = FFMAX(duration, end_time - start_time);
c1e8b678
NB
1667 }
1668 if (duration != INT64_MIN) {
1669 ic->duration = duration;
50ecf157 1670 if (ic->pb && (filesize = avio_size(ic->pb)) > 0)
a85736f2 1671 /* compute the bitrate */
50ecf157
DB
1672 ic->bit_rate = (double) filesize * 8.0 * AV_TIME_BASE /
1673 (double) ic->duration;
12f996ed 1674 }
12f996ed
FB
1675}
1676
1677static void fill_all_stream_timings(AVFormatContext *ic)
1678{
1679 int i;
1680 AVStream *st;
1681
d3bb7191 1682 update_stream_timings(ic);
50ecf157 1683 for (i = 0; i < ic->nb_streams; i++) {
12f996ed
FB
1684 st = ic->streams[i];
1685 if (st->start_time == AV_NOPTS_VALUE) {
50ecf157
DB
1686 if (ic->start_time != AV_NOPTS_VALUE)
1687 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
1688 st->time_base);
1689 if (ic->duration != AV_NOPTS_VALUE)
1690 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
1691 st->time_base);
12f996ed
FB
1692 }
1693 }
1694}
1695
d3bb7191 1696static void estimate_timings_from_bit_rate(AVFormatContext *ic)
12f996ed
FB
1697{
1698 int64_t filesize, duration;
fab694dd 1699 int i;
12f996ed
FB
1700 AVStream *st;
1701
1702 /* if bit_rate is already set, we believe it */
9100d4d6 1703 if (ic->bit_rate <= 0) {
fab694dd 1704 int bit_rate = 0;
50ecf157 1705 for (i = 0; i < ic->nb_streams; i++) {
12f996ed 1706 st = ic->streams[i];
9200514a
AK
1707 if (st->codecpar->bit_rate > 0) {
1708 if (INT_MAX - st->codecpar->bit_rate < bit_rate) {
df33a58e
AK
1709 bit_rate = 0;
1710 break;
1711 }
9200514a 1712 bit_rate += st->codecpar->bit_rate;
df33a58e 1713 }
12f996ed
FB
1714 }
1715 ic->bit_rate = bit_rate;
1716 }
1717
1718 /* if duration is already set, we believe it */
115329f1 1719 if (ic->duration == AV_NOPTS_VALUE &&
c10731e7
AK
1720 ic->bit_rate != 0) {
1721 filesize = ic->pb ? avio_size(ic->pb) : 0;
12f996ed 1722 if (filesize > 0) {
50ecf157
DB
1723 for (i = 0; i < ic->nb_streams; i++) {
1724 st = ic->streams[i];
1725 duration = av_rescale(8 * filesize, st->time_base.den,
1726 ic->bit_rate *
1727 (int64_t) st->time_base.num);
9f32041d 1728 if (st->duration == AV_NOPTS_VALUE)
12f996ed 1729 st->duration = duration;
12f996ed
FB
1730 }
1731 }
1732 }
1733}
1734
12f996ed 1735#define DURATION_MAX_READ_SIZE 250000
411ff322 1736#define DURATION_MAX_RETRY 3
12f996ed
FB
1737
1738/* only usable for MPEG-PS streams */
d3bb7191 1739static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
12f996ed
FB
1740{
1741 AVPacket pkt1, *pkt = &pkt1;
1742 AVStream *st;
1743 int read_size, i, ret;
3e4318bf 1744 int64_t end_time;
12f996ed 1745 int64_t filesize, offset, duration;
50ecf157 1746 int retry = 0;
115329f1 1747
578688fa
LA
1748 /* flush packet queue */
1749 flush_packet_queue(ic);
1750
50ecf157 1751 for (i = 0; i < ic->nb_streams; i++) {
578688fa 1752 st = ic->streams[i];
3e4318bf 1753 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
9200514a 1754 av_log(ic, AV_LOG_WARNING,
50ecf157 1755 "start time is not set in estimate_timings_from_pts\n");
cc20679a 1756
578688fa
LA
1757 if (st->parser) {
1758 av_parser_close(st->parser);
50ecf157 1759 st->parser = NULL;
578688fa
LA
1760 }
1761 }
115329f1 1762
12f996ed
FB
1763 /* estimate the end time (duration) */
1764 /* XXX: may need to support wrapping */
c10731e7 1765 filesize = ic->pb ? avio_size(ic->pb) : 0;
411ff322 1766 end_time = AV_NOPTS_VALUE;
50ecf157
DB
1767 do {
1768 offset = filesize - (DURATION_MAX_READ_SIZE << retry);
7e6029f9
AC
1769 if (offset < 0)
1770 offset = 0;
12f996ed 1771
7e6029f9
AC
1772 avio_seek(ic->pb, offset, SEEK_SET);
1773 read_size = 0;
50ecf157
DB
1774 for (;;) {
1775 if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
7e6029f9 1776 break;
115329f1 1777
7e6029f9 1778 do {
3c90cc2e 1779 ret = ff_read_packet(ic, pkt);
50ecf157 1780 } while (ret == AVERROR(EAGAIN));
7e6029f9
AC
1781 if (ret != 0)
1782 break;
1783 read_size += pkt->size;
50ecf157 1784 st = ic->streams[pkt->stream_index];
7e6029f9
AC
1785 if (pkt->pts != AV_NOPTS_VALUE &&
1786 (st->start_time != AV_NOPTS_VALUE ||
1787 st->first_dts != AV_NOPTS_VALUE)) {
1788 duration = end_time = pkt->pts;
1789 if (st->start_time != AV_NOPTS_VALUE)
1790 duration -= st->start_time;
1791 else
1792 duration -= st->first_dts;
1793 if (duration < 0)
50ecf157 1794 duration += 1LL << st->pts_wrap_bits;
7e6029f9
AC
1795 if (duration > 0) {
1796 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1797 st->duration = duration;
1798 }
12f996ed 1799 }
ce70f28a 1800 av_packet_unref(pkt);
12f996ed 1801 }
50ecf157
DB
1802 } while (end_time == AV_NOPTS_VALUE &&
1803 filesize > (DURATION_MAX_READ_SIZE << retry) &&
1804 ++retry <= DURATION_MAX_RETRY);
115329f1 1805
c0df9d75 1806 fill_all_stream_timings(ic);
12f996ed 1807
6b4aa5da 1808 avio_seek(ic->pb, old_offset, SEEK_SET);
50ecf157
DB
1809 for (i = 0; i < ic->nb_streams; i++) {
1810 st = ic->streams[i];
1811 st->cur_dts = st->first_dts;
635fbcb1 1812 st->last_IP_pts = AV_NOPTS_VALUE;
df886e7e 1813 }
12f996ed
FB
1814}
1815
d3bb7191 1816static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
12f996ed 1817{
12f996ed
FB
1818 int64_t file_size;
1819
1820 /* get the file size, if possible */
1821 if (ic->iformat->flags & AVFMT_NOFILE) {
1822 file_size = 0;
1823 } else {
76aa876e 1824 file_size = avio_size(ic->pb);
a7503430 1825 file_size = FFMAX(0, file_size);
12f996ed 1826 }
12f996ed 1827
ff70e601
MR
1828 if ((!strcmp(ic->iformat->name, "mpeg") ||
1829 !strcmp(ic->iformat->name, "mpegts")) &&
83548fe8 1830 file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
12f996ed 1831 /* get accurate estimate from the PTSes */
d3bb7191
AK
1832 estimate_timings_from_pts(ic, old_offset);
1833 } else if (has_duration(ic)) {
a85736f2 1834 /* at least one component has timings - we use them for all
50ecf157 1835 * the components */
12f996ed
FB
1836 fill_all_stream_timings(ic);
1837 } else {
50ecf157
DB
1838 av_log(ic, AV_LOG_WARNING,
1839 "Estimating duration from bitrate, this may be inaccurate\n");
a85736f2 1840 /* less precise: use bitrate info */
d3bb7191 1841 estimate_timings_from_bit_rate(ic);
12f996ed 1842 }
d3bb7191 1843 update_stream_timings(ic);
12f996ed 1844
12f996ed
FB
1845 {
1846 int i;
5e1166b3 1847 AVStream av_unused *st;
50ecf157 1848 for (i = 0; i < ic->nb_streams; i++) {
12f996ed 1849 st = ic->streams[i];
1a3eb042 1850 av_log(ic, AV_LOG_TRACE, "%d: start_time: %0.3f duration: %0.3f\n", i,
045dd4b9
DB
1851 (double) st->start_time / AV_TIME_BASE,
1852 (double) st->duration / AV_TIME_BASE);
12f996ed 1853 }
1a3eb042 1854 av_log(ic, AV_LOG_TRACE,
50ecf157 1855 "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
045dd4b9
DB
1856 (double) ic->start_time / AV_TIME_BASE,
1857 (double) ic->duration / AV_TIME_BASE,
1858 ic->bit_rate / 1000);
12f996ed 1859 }
12f996ed
FB
1860}
1861
8c1d6ac6 1862static int has_codec_parameters(AVStream *st)
b9a281db 1863{
9200514a 1864 AVCodecContext *avctx = st->internal->avctx;
b9a281db 1865 int val;
50ecf157 1866
25dfda7f 1867 switch (avctx->codec_type) {
72415b2a 1868 case AVMEDIA_TYPE_AUDIO:
8c1d6ac6 1869 val = avctx->sample_rate && avctx->channels;
50ecf157
DB
1870 if (st->info->found_decoder >= 0 &&
1871 avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
8c1d6ac6 1872 return 0;
b9a281db 1873 break;
72415b2a 1874 case AVMEDIA_TYPE_VIDEO:
8c1d6ac6 1875 val = avctx->width;
716d413c 1876 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
8c1d6ac6 1877 return 0;
b9a281db
FB
1878 break;
1879 default:
1880 val = 1;
1881 break;
1882 }
36ef5369 1883 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
b9a281db
FB
1884}
1885
ae447836
BC
1886static int has_decode_delay_been_guessed(AVStream *st)
1887{
9200514a 1888 return st->internal->avctx->codec_id != AV_CODEC_ID_H264 ||
50ecf157 1889 st->info->nb_decoded_frames >= 6;
ae447836
BC
1890}
1891
b3461c29 1892/* returns 1 or 0 if or if not decoded data was returned, or a negative error */
9200514a 1893static int try_decode_frame(AVFormatContext *s, AVStream *st, AVPacket *avpkt,
50ecf157 1894 AVDictionary **options)
fb2758c8 1895{
9200514a 1896 AVCodecContext *avctx = st->internal->avctx;
edb5238c 1897 const AVCodec *codec;
212fd3a1 1898 int got_picture = 1, ret = 0;
5b9c3b45 1899 AVFrame *frame = av_frame_alloc();
f08e54e8 1900 AVPacket pkt = *avpkt;
115329f1 1901
9eb29657
AK
1902 if (!frame)
1903 return AVERROR(ENOMEM);
1904
9200514a 1905 if (!avcodec_is_open(avctx) && !st->info->found_decoder) {
59297ad6
JG
1906 AVDictionary *thread_opt = NULL;
1907
9200514a
AK
1908#if FF_API_LAVF_AVCTX
1909FF_DISABLE_DEPRECATION_WARNINGS
50ecf157 1910 codec = st->codec->codec ? st->codec->codec
9200514a
AK
1911 : avcodec_find_decoder(st->codecpar->codec_id);
1912FF_ENABLE_DEPRECATION_WARNINGS
1913#else
1914 codec = avcodec_find_decoder(st->codecpar->codec_id);
1915#endif
bc901998 1916
8c1d6ac6
JR
1917 if (!codec) {
1918 st->info->found_decoder = -1;
50ecf157 1919 ret = -1;
9eb29657 1920 goto fail;
8c1d6ac6 1921 }
59297ad6 1922
50ecf157
DB
1923 /* Force thread count to 1 since the H.264 decoder will not extract
1924 * SPS and PPS to extradata during multi-threaded decoding. */
59297ad6 1925 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
9200514a 1926 ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
59297ad6
JG
1927 if (!options)
1928 av_dict_free(&thread_opt);
8c1d6ac6
JR
1929 if (ret < 0) {
1930 st->info->found_decoder = -1;
9eb29657 1931 goto fail;
8c1d6ac6
JR
1932 }
1933 st->info->found_decoder = 1;
1934 } else if (!st->info->found_decoder)
1935 st->info->found_decoder = 1;
1936
9eb29657
AK
1937 if (st->info->found_decoder < 0) {
1938 ret = -1;
1939 goto fail;
1940 }
644a9262 1941
212fd3a1
AK
1942 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
1943 ret >= 0 &&
50ecf157
DB
1944 (!has_codec_parameters(st) || !has_decode_delay_been_guessed(st) ||
1945 (!st->codec_info_nb_frames &&
9200514a 1946 (avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
f08e54e8 1947 got_picture = 0;
8bc4accc 1948 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
1949 avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1950 ret = avcodec_send_packet(avctx, &pkt);
1951 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
1952 break;
1953 if (ret >= 0)
1954 pkt.size = 0;
1955 ret = avcodec_receive_frame(avctx, frame);
1956 if (ret >= 0)
1957 got_picture = 1;
1958 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1959 ret = 0;
e472ea34 1960 }
f08e54e8
JR
1961 if (ret >= 0) {
1962 if (got_picture)
1963 st->info->nb_decoded_frames++;
b3461c29 1964 ret = got_picture;
f08e54e8 1965 }
fb2758c8 1966 }
9eb29657
AK
1967
1968fail:
eb891b31 1969 av_frame_free(&frame);
fb2758c8
FB
1970 return ret;
1971}
1972
36ef5369 1973unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
45da8124 1974{
36ef5369 1975 while (tags->id != AV_CODEC_ID_NONE) {
45da8124
AJ
1976 if (tags->id == id)
1977 return tags->tag;
1978 tags++;
1979 }
1980 return 0;
1981}
1982
36ef5369 1983enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
45da8124 1984{
41415d28 1985 int i;
50ecf157
DB
1986 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
1987 if (tag == tags[i].tag)
41415d28 1988 return tags[i].id;
50ecf157 1989 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
0842d589 1990 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
41415d28 1991 return tags[i].id;
36ef5369 1992 return AV_CODEC_ID_NONE;
45da8124
AJ
1993}
1994
261e9348
JR
1995enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
1996{
1997 if (flt) {
1998 switch (bps) {
50ecf157
DB
1999 case 32:
2000 return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2001 case 64:
2002 return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2003 default:
2004 return AV_CODEC_ID_NONE;
261e9348
JR
2005 }
2006 } else {
2007 bps >>= 3;
2008 if (sflags & (1 << (bps - 1))) {
2009 switch (bps) {
50ecf157
DB
2010 case 1:
2011 return AV_CODEC_ID_PCM_S8;
2012 case 2:
2013 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2014 case 3:
2015 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2016 case 4:
2017 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2018 default:
2019 return AV_CODEC_ID_NONE;
261e9348
JR
2020 }
2021 } else {
2022 switch (bps) {
50ecf157
DB
2023 case 1:
2024 return AV_CODEC_ID_PCM_U8;
2025 case 2:
2026 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2027 case 3:
2028 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2029 case 4:
2030 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2031 default:
2032 return AV_CODEC_ID_NONE;
261e9348
JR
2033 }
2034 }
2035 }
2036}
2037
50ecf157 2038unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
45da8124
AJ
2039{
2040 int i;
50ecf157
DB
2041 for (i = 0; tags && tags[i]; i++) {
2042 int tag = ff_codec_get_tag(tags[i], id);
2043 if (tag)
2044 return tag;
45da8124
AJ
2045 }
2046 return 0;
2047}
2048
50ecf157 2049enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
45da8124
AJ
2050{
2051 int i;
50ecf157
DB
2052 for (i = 0; tags && tags[i]; i++) {
2053 enum AVCodecID id = ff_codec_get_id(tags[i], tag);
2054 if (id != AV_CODEC_ID_NONE)
2055 return id;
45da8124 2056 }
36ef5369 2057 return AV_CODEC_ID_NONE;
45da8124
AJ
2058}
2059
c2c3dedf
AJ
2060static void compute_chapters_end(AVFormatContext *s)
2061{
ab11317c 2062 unsigned int i, j;
50ecf157
DB
2063 int64_t max_time = s->duration +
2064 ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
c2c3dedf 2065
ab11317c 2066 for (i = 0; i < s->nb_chapters; i++)
c2c3dedf 2067 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
ab11317c 2068 AVChapter *ch = s->chapters[i];
50ecf157
DB
2069 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
2070 ch->time_base)
2071 : INT64_MAX;
ab11317c
AK
2072
2073 for (j = 0; j < s->nb_chapters; j++) {
50ecf157
DB
2074 AVChapter *ch1 = s->chapters[j];
2075 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
2076 ch->time_base);
ab11317c
AK
2077 if (j != i && next_start > ch->start && next_start < end)
2078 end = next_start;
2079 }
2080 ch->end = (end == INT64_MAX) ? ch->start : end;
c2c3dedf 2081 }
c2c3dedf
AJ
2082}
2083
50ecf157
DB
2084static int get_std_framerate(int i)
2085{
2086 if (i < 60 * 12)
78987a88 2087 return (i + 1) * 1001;
50ecf157
DB
2088 else
2089 return ((const int[]) { 24, 30, 60, 12, 15 })[i - 60 * 12] * 1000 * 12;
4d43cbcc
MN
2090}
2091
8e2ea691
AK
2092static int extract_extradata_init(AVStream *st)
2093{
2094 AVStreamInternal *i = st->internal;
2095 const AVBitStreamFilter *f;
2096 int ret;
2097
2098 f = av_bsf_get_by_name("extract_extradata");
2099 if (!f)
2100 goto finish;
2101
096a8eff
AK
2102 /* check that the codec id is supported */
2103 if (f->codec_ids) {
2104 const enum AVCodecID *ids;
2105 for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
2106 if (*ids == st->codecpar->codec_id)
2107 break;
2108 if (*ids == AV_CODEC_ID_NONE)
2109 goto finish;
2110 }
2111
8e2ea691
AK
2112 i->extract_extradata.pkt = av_packet_alloc();
2113 if (!i->extract_extradata.pkt)
2114 return AVERROR(ENOMEM);
2115
2116 ret = av_bsf_alloc(f, &i->extract_extradata.bsf);
2117 if (ret < 0)
2118 goto fail;
2119
2120 ret = avcodec_parameters_copy(i->extract_extradata.bsf->par_in,
2121 st->codecpar);
2122 if (ret < 0)
2123 goto fail;
2124
2125 i->extract_extradata.bsf->time_base_in = st->time_base;
2126
2127 /* if init fails here, we assume extracting extradata is just not
2128 * supported for this codec, so we return success */
2129 ret = av_bsf_init(i->extract_extradata.bsf);
2130 if (ret < 0) {
2131 av_bsf_free(&i->extract_extradata.bsf);
2132 ret = 0;
2133 }
2134
2135finish:
2136 i->extract_extradata.inited = 1;
2137
2138 return 0;
2139fail:
2140 av_bsf_free(&i->extract_extradata.bsf);
2141 av_packet_free(&i->extract_extradata.pkt);
2142 return ret;
2143}
2144
2145static int extract_extradata(AVStream *st, AVPacket *pkt)
2146{
2147 AVStreamInternal *i = st->internal;
2148 AVPacket *pkt_ref;
2149 int ret;
2150
2151 if (!i->extract_extradata.inited) {
2152 ret = extract_extradata_init(st);
2153 if (ret < 0)
2154 return ret;
2155 }
2156
2157 if (i->extract_extradata.inited && !i->extract_extradata.bsf)
2158 return 0;
2159
2160 pkt_ref = i->extract_extradata.pkt;
2161 ret = av_packet_ref(pkt_ref, pkt);
2162 if (ret < 0)
2163 return ret;
2164
2165 ret = av_bsf_send_packet(i->extract_extradata.bsf, pkt_ref);
2166 if (ret < 0) {
2167 av_packet_unref(pkt_ref);
2168 return ret;
2169 }
2170
2171 while (ret >= 0 && !i->avctx->extradata) {
2172 int extradata_size;
2173 uint8_t *extradata;
2174
2175 ret = av_bsf_receive_packet(i->extract_extradata.bsf, pkt_ref);
2176 if (ret < 0) {
2177 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
2178 return ret;
2179 continue;
2180 }
2181
2182 extradata = av_packet_get_side_data(pkt_ref, AV_PKT_DATA_NEW_EXTRADATA,
2183 &extradata_size);
2184
2185 if (extradata) {
2186 i->avctx->extradata = av_mallocz(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2187 if (!i->avctx->extradata) {
2188 av_packet_unref(pkt_ref);
2189 return AVERROR(ENOMEM);
2190 }
2191 memcpy(i->avctx->extradata, extradata, extradata_size);
2192 i->avctx->extradata_size = extradata_size;
2193 }
2194 av_packet_unref(pkt_ref);
2195 }
2196
2197 return 0;
2198}
2199
a67c061e
AK
2200int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2201{
9f75260e 2202 int i, count, ret, read_size, j;
b9a281db 2203 AVStream *st;
9200514a 2204 AVCodecContext *avctx;
fb2758c8 2205 AVPacket pkt1, *pkt;
50ecf157
DB
2206 int64_t old_offset = avio_tell(ic->pb);
2207 // new streams might appear, no options for those
2208 int orig_nb_streams = ic->nb_streams;
0cbff027 2209
50ecf157 2210 for (i = 0; i < ic->nb_streams; i++) {
edb5238c 2211 const AVCodec *codec;
59297ad6 2212 AVDictionary *thread_opt = NULL;
c0df9d75 2213 st = ic->streams[i];
9200514a 2214 avctx = st->internal->avctx;
dafaef2f 2215
50ecf157 2216 // only for the split stuff
fe8344a2 2217 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
9200514a 2218 st->parser = av_parser_init(st->codecpar->codec_id);
50ecf157 2219 if (st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser)
7cbaa7ba 2220 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
90ad92b3 2221 }
9200514a
AK
2222
2223 /* check if the caller has overridden the codec id */
2224#if FF_API_LAVF_AVCTX
2225FF_DISABLE_DEPRECATION_WARNINGS
2226 if (st->codec->codec_id != st->internal->orig_codec_id) {
2227 st->codecpar->codec_id = st->codec->codec_id;
2228 st->codecpar->codec_type = st->codec->codec_type;
2229 st->internal->orig_codec_id = st->codec->codec_id;
2230 }
2231FF_ENABLE_DEPRECATION_WARNINGS
2232#endif
2233 if (st->codecpar->codec_id != st->internal->orig_codec_id)
2234 st->internal->orig_codec_id = st->codecpar->codec_id;
2235
2236 ret = avcodec_parameters_to_context(avctx, st->codecpar);
2237 if (ret < 0)
2238 goto find_stream_info_err;
2239 if (st->codecpar->codec_id != AV_CODEC_ID_PROBE &&
2240 st->codecpar->codec_id != AV_CODEC_ID_NONE)
2241 st->internal->avctx_inited = 1;
2242
2243#if FF_API_LAVF_AVCTX
2244FF_DISABLE_DEPRECATION_WARNINGS
50ecf157 2245 codec = st->codec->codec ? st->codec->codec
9200514a
AK
2246 : avcodec_find_decoder(st->codecpar->codec_id);
2247FF_ENABLE_DEPRECATION_WARNINGS
2248#else
2249 codec = avcodec_find_decoder(st->codecpar->codec_id);
2250#endif
62784e37 2251
50ecf157
DB
2252 /* Force thread count to 1 since the H.264 decoder will not extract
2253 * SPS and PPS to extradata during multi-threaded decoding. */
59297ad6
JG
2254 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2255
cb2c971d 2256 /* Ensure that subtitle_header is properly set. */
9200514a
AK
2257 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE
2258 && codec && !avctx->codec)
2259 avcodec_open2(avctx, codec,
50ecf157 2260 options ? &options[i] : &thread_opt);
cb2c971d 2261
50ecf157 2262 // Try to just open decoders, in case this is enough to get parameters.
8c1d6ac6 2263 if (!has_codec_parameters(st)) {
9200514a
AK
2264 if (codec && !avctx->codec)
2265 avcodec_open2(avctx, codec,
50ecf157 2266 options ? &options[i] : &thread_opt);
43e4d57f 2267 }
59297ad6
JG
2268 if (!options)
2269 av_dict_free(&thread_opt);
c0df9d75
MN
2270 }
2271
50ecf157 2272 for (i = 0; i < ic->nb_streams; i++) {
fe1c1198
AK
2273 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2274 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
15bc38e5 2275 }
115329f1 2276
50ecf157 2277 count = 0;
b9a281db 2278 read_size = 0;
50ecf157
DB
2279 for (;;) {
2280 if (ff_check_interrupt(&ic->interrupt_callback)) {
2281 ret = AVERROR_EXIT;
71ee6515 2282 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
1d14361d
MN
2283 break;
2284 }
2285
b9a281db 2286 /* check if one codec still needs to be handled */
50ecf157 2287 for (i = 0; i < ic->nb_streams; i++) {
7c152a45
AH
2288 int fps_analyze_framecount = 20;
2289
b9a281db 2290 st = ic->streams[i];
8c1d6ac6 2291 if (!has_codec_parameters(st))
b9a281db 2292 break;
50ecf157
DB
2293 /* If the timebase is coarse (like the usual millisecond precision
2294 * of mkv), we need to analyze more frames to reliably arrive at
2295 * the correct fps. */
7c152a45
AH
2296 if (av_q2d(st->time_base) > 0.0005)
2297 fps_analyze_framecount *= 2;
30315a8d
AC
2298 if (ic->fps_probe_size >= 0)
2299 fps_analyze_framecount = ic->fps_probe_size;
3e76d1b5 2300 /* variable fps and no guess at the real fps */
1eb57e1d 2301 if (!st->avg_frame_rate.num &&
50ecf157 2302 st->codec_info_nb_frames < fps_analyze_framecount &&
9200514a 2303 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
3e76d1b5 2304 break;
8e2ea691
AK
2305 if (!st->codecpar->extradata &&
2306 !st->internal->avctx->extradata &&
2307 (!st->internal->extract_extradata.inited ||
2308 st->internal->extract_extradata.bsf))
90ad92b3 2309 break;
ba24f129 2310 if (st->first_dts == AV_NOPTS_VALUE &&
b263f8ff 2311 st->codec_info_nb_frames < ic->max_ts_probe &&
9200514a
AK
2312 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
2313 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
82583548 2314 break;
b9a281db
FB
2315 }
2316 if (i == ic->nb_streams) {
50ecf157
DB
2317 /* NOTE: If the format has no header, then we need to read some
2318 * packets to get most of the streams, so we cannot stop here. */
fb2758c8 2319 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
50ecf157 2320 /* If we found the info for all the codecs, we can stop. */
b9a281db 2321 ret = count;
71ee6515 2322 av_log(ic, AV_LOG_DEBUG, "All info found\n");
b9a281db
FB
2323 break;
2324 }
5fb83c38 2325 }
50ecf157 2326 /* We did not get all the codec info, but we read too much data. */
57011a13 2327 if (read_size >= ic->probesize) {
35eab0c0 2328 ret = count;
50ecf157
DB
2329 av_log(ic, AV_LOG_DEBUG,
2330 "Probe buffer size limit %d reached\n", ic->probesize);
35eab0c0
MN
2331 break;
2332 }
b9a281db 2333
50ecf157
DB
2334 /* NOTE: A new stream can be added there if no header in file
2335 * (AVFMTCTX_NOHEADER). */
d3bb7191 2336 ret = read_frame_internal(ic, &pkt1);
59ca3955
AF
2337 if (ret == AVERROR(EAGAIN))
2338 continue;
2339
2340 if (ret < 0) {
212fd3a1
AK
2341 /* EOF or error*/
2342 AVPacket empty_pkt = { 0 };
8c1d6ac6 2343 int err = 0;
212fd3a1
AK
2344 av_init_packet(&empty_pkt);
2345
50ecf157
DB
2346 /* We could not have all the codec parameters before EOF. */
2347 ret = -1;
2348 for (i = 0; i < ic->nb_streams; i++) {
e19456e3 2349 st = ic->streams[i];
212fd3a1
AK
2350
2351 /* flush the decoders */
8c1d6ac6 2352 if (st->info->found_decoder == 1) {
94cf64b8 2353 do {
9200514a 2354 err = try_decode_frame(ic, st, &empty_pkt,
50ecf157
DB
2355 (options && i < orig_nb_streams)
2356 ? &options[i] : NULL);
94cf64b8 2357 } while (err > 0 && !has_codec_parameters(st));
8c1d6ac6 2358 }
b3461c29
JG
2359
2360 if (err < 0) {
2361 av_log(ic, AV_LOG_WARNING,
2362 "decoding for stream %d failed\n", st->index);
8c1d6ac6 2363 } else if (!has_codec_parameters(st)) {
305ee50f 2364 char buf[256];
9200514a 2365 avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
b3461c29
JG
2366 av_log(ic, AV_LOG_WARNING,
2367 "Could not find codec parameters (%s)\n", buf);
344a18c3
MR
2368 } else {
2369 ret = 0;
305ee50f 2370 }
e19456e3 2371 }
fb2758c8
FB
2372 break;
2373 }
2374
d584533c
LB
2375 pkt = &pkt1;
2376
2377 if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
2378 ret = add_to_pktbuf(&ic->internal->packet_buffer, pkt,
2379 &ic->internal->packet_buffer_end, 0);
2380 if (ret < 0)
681ed000
LB
2381 goto find_stream_info_err;
2382 }
b9a281db 2383
fb2758c8 2384 read_size += pkt->size;
b9a281db
FB
2385
2386 st = ic->streams[pkt->stream_index];
9200514a
AK
2387 avctx = st->internal->avctx;
2388 if (!st->internal->avctx_inited) {
2389 ret = avcodec_parameters_to_context(avctx, st->codecpar);
2390 if (ret < 0)
2391 goto find_stream_info_err;
2392 st->internal->avctx_inited = 1;
2393 }
2394
fe1c1198
AK
2395 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2396 /* check for non-increasing dts */
2397 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2398 st->info->fps_last_dts >= pkt->dts) {
50ecf157
DB
2399 av_log(ic, AV_LOG_WARNING,
2400 "Non-increasing DTS in stream %d: packet %d with DTS "
2401 "%"PRId64", packet %d with DTS %"PRId64"\n",
2402 st->index, st->info->fps_last_dts_idx,
2403 st->info->fps_last_dts, st->codec_info_nb_frames,
2404 pkt->dts);
2405 st->info->fps_first_dts =
2406 st->info->fps_last_dts = AV_NOPTS_VALUE;
fe1c1198 2407 }
50ecf157
DB
2408 /* Check for a discontinuity in dts. If the difference in dts
2409 * is more than 1000 times the average packet duration in the
2410 * sequence, we treat it as a discontinuity. */
bdefe22b
MS
2411 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2412 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2413 (pkt->dts - st->info->fps_last_dts) / 1000 >
50ecf157
DB
2414 (st->info->fps_last_dts - st->info->fps_first_dts) /
2415 (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2416 av_log(ic, AV_LOG_WARNING,
2417 "DTS discontinuity in stream %d: packet %d with DTS "
2418 "%"PRId64", packet %d with DTS %"PRId64"\n",
2419 st->index, st->info->fps_last_dts_idx,
2420 st->info->fps_last_dts, st->codec_info_nb_frames,
2421 pkt->dts);
2422 st->info->fps_first_dts =
2423 st->info->fps_last_dts = AV_NOPTS_VALUE;
bdefe22b 2424 }
fe1c1198
AK
2425
2426 /* update stored dts values */
2427 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2428 st->info->fps_first_dts = pkt->dts;
2429 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2430 }
50ecf157 2431 st->info->fps_last_dts = pkt->dts;
fe1c1198
AK
2432 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2433
2434 /* check max_analyze_duration */
2435 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2436 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
db9d39b4
LB
2437 av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached\n",
2438 ic->max_analyze_duration);
19133e96
JR
2439 if (ic->flags & AVFMT_FLAG_NOBUFFER)
2440 av_packet_unref(pkt);
3a560188 2441 break;
71ee6515 2442 }
3a560188 2443 }
8e2ea691
AK
2444 if (!st->internal->avctx->extradata) {
2445 ret = extract_extradata(st, pkt);
2446 if (ret < 0)
2447 goto find_stream_info_err;
90ad92b3 2448 }
115329f1 2449
50ecf157
DB
2450 /* If still no information, we try to open the codec and to
2451 * decompress the frame. We try to avoid that in most cases as
2452 * it takes longer and uses more memory. For MPEG-4, we need to
2453 * decompress for QuickTime.
2454 *
def97856 2455 * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
50ecf157
DB
2456 * least one frame of codec data, this makes sure the codec initializes
2457 * the channel configuration and does not only trust the values from
2458 * the container. */
9200514a 2459 try_decode_frame(ic, st, pkt,
50ecf157 2460 (options && i < orig_nb_streams) ? &options[i] : NULL);
115329f1 2461
19133e96
JR
2462 if (ic->flags & AVFMT_FLAG_NOBUFFER)
2463 av_packet_unref(pkt);
2464
9d3fdf20 2465 st->codec_info_nb_frames++;
b9a281db
FB
2466 count++;
2467 }
2468
50ecf157 2469 for (i = 0; i < ic->nb_streams; i++) {
b9a281db 2470 st = ic->streams[i];
9200514a
AK
2471 avctx = st->internal->avctx;
2472 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
fe1c1198 2473 /* estimate average framerate if not set by demuxer */
50ecf157
DB
2474 if (!st->avg_frame_rate.num &&
2475 st->info->fps_last_dts != st->info->fps_first_dts) {
2476 int64_t delta_dts = st->info->fps_last_dts -
2477 st->info->fps_first_dts;
2478 int delta_packets = st->info->fps_last_dts_idx -
2479 st->info->fps_first_dts_idx;
2480 int best_fps = 0;
f66eeff1 2481 double best_error = 0.01;
fe1c1198 2482
e740929a 2483 if (delta_dts >= INT64_MAX / st->time_base.num ||
ce67f442
MS
2484 delta_packets >= INT64_MAX / st->time_base.den ||
2485 delta_dts < 0)
e740929a 2486 continue;
f35f8eeb 2487 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
50ecf157
DB
2488 delta_packets * (int64_t) st->time_base.den,
2489 delta_dts * (int64_t) st->time_base.num, 60000);
f66eeff1 2490
50ecf157
DB
2491 /* Round guessed framerate to a "standard" framerate if it's
2492 * within 1% of the original estimate. */
78987a88 2493 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
50ecf157
DB
2494 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
2495 double error = fabs(av_q2d(st->avg_frame_rate) /
2496 av_q2d(std_fps) - 1);
f66eeff1
AK
2497
2498 if (error < best_error) {
2499 best_error = error;
2500 best_fps = std_fps.num;
2501 }
2502 }
50ecf157 2503 if (best_fps)
f66eeff1 2504 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
50ecf157 2505 best_fps, 12 * 1001, INT_MAX);
fe1c1198 2506 }
9200514a
AK
2507 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
2508 if (!avctx->bits_per_coded_sample)
2509 avctx->bits_per_coded_sample =
2510 av_get_bits_per_sample(avctx->codec_id);
c70a6a41 2511 // set stream disposition based on audio service type
9200514a 2512 switch (avctx->audio_service_type) {
c70a6a41 2513 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
50ecf157
DB
2514 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
2515 break;
c70a6a41 2516 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
50ecf157
DB
2517 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
2518 break;
c70a6a41 2519 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
50ecf157
DB
2520 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
2521 break;
c70a6a41 2522 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
50ecf157
DB
2523 st->disposition = AV_DISPOSITION_COMMENT;
2524 break;
c70a6a41 2525 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
50ecf157
DB
2526 st->disposition = AV_DISPOSITION_KARAOKE;
2527 break;
c70a6a41 2528 }
b9a281db 2529 }
de6d9b64 2530 }
b9a281db 2531
c2c3dedf
AJ
2532 compute_chapters_end(ic);
2533
9200514a
AK
2534 /* update the stream parameters from the internal codec contexts */
2535 for (i = 0; i < ic->nb_streams; i++) {
2536 st = ic->streams[i];
2537 if (!st->internal->avctx_inited)
2538 continue;
2539
2540 ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
2541 if (ret < 0)
2542 goto find_stream_info_err;
2543
2544#if FF_API_LAVF_AVCTX
2545FF_DISABLE_DEPRECATION_WARNINGS
2546 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
2547 if (ret < 0)
2548 goto find_stream_info_err;
2549
2550 if (st->internal->avctx->subtitle_header) {
2551 st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
2552 if (!st->codec->subtitle_header)
2553 goto find_stream_info_err;
2554 st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
2555 memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
2556 st->codec->subtitle_header_size);
2557 }
2558FF_ENABLE_DEPRECATION_WARNINGS
2559#endif
2560
2561 st->internal->avctx_inited = 0;
2562 }
2563
1ceb07eb
AK
2564 estimate_timings(ic, old_offset);
2565
50ecf157
DB
2566find_stream_info_err:
2567 for (i = 0; i < ic->nb_streams; i++) {
9e4a5eb5 2568 avcodec_close(ic->streams[i]->internal->avctx);
fd0368e7 2569 av_freep(&ic->streams[i]->info);
8e2ea691
AK
2570 av_bsf_free(&ic->streams[i]->internal->extract_extradata.bsf);
2571 av_packet_free(&ic->streams[i]->internal->extract_extradata.pkt);
e4e30256 2572 }
b9a281db 2573 return ret;
de6d9b64
FB
2574}
2575
9128ae08
NG
2576static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2577{
2578 int i, j;
2579
2580 for (i = 0; i < ic->nb_programs; i++)
2581 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2582 if (ic->programs[i]->stream_index[j] == s)
2583 return ic->programs[i];
2584 return NULL;
2585}
2586
50ecf157
DB
2587int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
2588 int wanted_stream_nb, int related_stream,
2589 AVCodec **decoder_ret, int flags)
9128ae08 2590{
2c715816 2591 int i, nb_streams = ic->nb_streams;
9128ae08
NG
2592 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2593 unsigned *program = NULL;
2594 AVCodec *decoder = NULL, *best_decoder = NULL;
2595
2596 if (related_stream >= 0 && wanted_stream_nb < 0) {
2597 AVProgram *p = find_program_from_stream(ic, related_stream);
2598 if (p) {
50ecf157 2599 program = p->stream_index;
9128ae08
NG
2600 nb_streams = p->nb_stream_indexes;
2601 }
2602 }
2603 for (i = 0; i < nb_streams; i++) {
2c715816 2604 int real_stream_index = program ? program[i] : i;
50ecf157 2605 AVStream *st = ic->streams[real_stream_index];
9200514a
AK
2606 AVCodecParameters *par = st->codecpar;
2607 if (par->codec_type != type)
9128ae08 2608 continue;
2c715816 2609 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
9128ae08 2610 continue;
50ecf157
DB
2611 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |
2612 AV_DISPOSITION_VISUAL_IMPAIRED))
52091491 2613 continue;
9128ae08 2614 if (decoder_ret) {
9200514a 2615 decoder = avcodec_find_decoder(par->codec_id);
9128ae08
NG
2616 if (!decoder) {
2617 if (ret < 0)
2618 ret = AVERROR_DECODER_NOT_FOUND;
2619 continue;
2620 }
2621 }
2622 if (best_count >= st->codec_info_nb_frames)
2623 continue;
50ecf157
DB
2624 best_count = st->codec_info_nb_frames;
2625 ret = real_stream_index;
9128ae08
NG
2626 best_decoder = decoder;
2627 if (program && i == nb_streams - 1 && ret < 0) {
50ecf157 2628 program = NULL;
9128ae08 2629 nb_streams = ic->nb_streams;
50ecf157
DB
2630 /* no related stream found, try again with everything */
2631 i = 0;
9128ae08
NG
2632 }
2633 }
2634 if (decoder_ret)
2635 *decoder_ret = best_decoder;
2636 return ret;
2637}
2638
fb2758c8
FB
2639/*******************************************************/
2640
fb2758c8
FB
2641int av_read_play(AVFormatContext *s)
2642{
fa13095a
BA
2643 if (s->iformat->read_play)
2644 return s->iformat->read_play(s);
fd2982a0 2645 if (s->pb)
ff1ec0c3 2646 return avio_pause(s->pb, 0);
fa13095a 2647 return AVERROR(ENOSYS);
fb2758c8
FB
2648}
2649
fb2758c8
FB
2650int av_read_pause(AVFormatContext *s)
2651{
fa13095a
BA
2652 if (s->iformat->read_pause)
2653 return s->iformat->read_pause(s);
fd2982a0 2654 if (s->pb)
ff1ec0c3 2655 return avio_pause(s->pb, 1);
fa13095a 2656 return AVERROR(ENOSYS);
fb2758c8
FB
2657}
2658
aeda1121
AK
2659static void free_stream(AVStream **pst)
2660{
2661 AVStream *st = *pst;
2662 int i;
2663
2664 if (!st)
2665 return;
2666
2667 for (i = 0; i < st->nb_side_data; i++)
2668 av_freep(&st->side_data[i].data);
2669 av_freep(&st->side_data);
2670
2671 if (st->parser)
2672 av_parser_close(st->parser);
2673
2674 if (st->attached_pic.data)
2675 av_packet_unref(&st->attached_pic);
2676
9200514a
AK
2677 if (st->internal) {
2678 avcodec_free_context(&st->internal->avctx);
8e2ea691
AK
2679 av_bsf_free(&st->internal->extract_extradata.bsf);
2680 av_packet_free(&st->internal->extract_extradata.pkt);
9200514a 2681 }
8de1ee9f
AK
2682 av_freep(&st->internal);
2683
aeda1121 2684 av_dict_free(&st->metadata);
9200514a 2685 avcodec_parameters_free(&st->codecpar);
aeda1121
AK
2686 av_freep(&st->probe_data.buf);
2687 av_free(st->index_entries);
9200514a
AK
2688#if FF_API_LAVF_AVCTX
2689FF_DISABLE_DEPRECATION_WARNINGS
aeda1121
AK
2690 av_free(st->codec->extradata);
2691 av_free(st->codec->subtitle_header);
2692 av_free(st->codec);
9200514a
AK
2693FF_ENABLE_DEPRECATION_WARNINGS
2694#endif
aeda1121
AK
2695 av_free(st->priv_data);
2696 av_free(st->info);
2697
2698 av_freep(pst);
2699}
2700
f124b087
MS
2701void avformat_free_context(AVFormatContext *s)
2702{
aeda1121 2703 int i;
f124b087 2704
0db6bbb2
LB
2705 if (!s)
2706 return;
2707
36773283 2708 av_opt_free(s);
dbaba52e 2709 if (s->iformat && s->iformat->priv_class && s->priv_data)
36773283
AK
2710 av_opt_free(s->priv_data);
2711
aeda1121
AK
2712 for (i = 0; i < s->nb_streams; i++)
2713 free_stream(&s->streams[i]);
25b32586 2714
50ecf157 2715 for (i = s->nb_programs - 1; i >= 0; i--) {
d2d67e42 2716 av_dict_free(&s->programs[i]->metadata);
526efa10 2717 av_freep(&s->programs[i]->stream_index);
15afa396
NS
2718 av_freep(&s->programs[i]);
2719 }
ceedda75 2720 av_freep(&s->programs);
a8dbe951 2721 av_freep(&s->priv_data);
50ecf157 2722 while (s->nb_chapters--) {
d2d67e42 2723 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
7c8202cc 2724 av_free(s->chapters[s->nb_chapters]);
79d7836a
AK
2725 }
2726 av_freep(&s->chapters);
d2d67e42 2727 av_dict_free(&s->metadata);
7bbb67d5 2728 av_freep(&s->streams);
33c859c1 2729 av_freep(&s->internal);
1ea4f593 2730 av_free(s);
de6d9b64
FB
2731}
2732
52660454
AK
2733void avformat_close_input(AVFormatContext **ps)
2734{
2735 AVFormatContext *s = *ps;
50ecf157 2736 AVIOContext *pb = s->pb;
44272c1c 2737
3f7fd59d 2738 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
44272c1c
LB
2739 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2740 pb = NULL;
2741
3a7f7678 2742 flush_packet_queue(s);
44272c1c 2743
50ecf157 2744 if (s->iformat)
44272c1c
LB
2745 if (s->iformat->read_close)
2746 s->iformat->read_close(s);
44272c1c 2747
3a7f7678 2748 avformat_free_context(s);
44272c1c 2749
52660454 2750 *ps = NULL;
4d1f443c
LB
2751
2752 avio_close(pb);
2506fd54
RD
2753}
2754
3d90f27a 2755AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
569129a6 2756{
b9a281db 2757 AVStream *st;
504ee036 2758 int i;
b9a281db 2759
50ecf157
DB
2760 if (av_reallocp_array(&s->streams, s->nb_streams + 1,
2761 sizeof(*s->streams)) < 0) {
f369b935 2762 s->nb_streams = 0;
38aab35f 2763 return NULL;
f369b935 2764 }
b9a281db
FB
2765
2766 st = av_mallocz(sizeof(AVStream));
2767 if (!st)
2768 return NULL;
fd0368e7
AJ
2769 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2770 av_free(st);
2771 return NULL;
2772 }
115329f1 2773
9200514a
AK
2774#if FF_API_LAVF_AVCTX
2775FF_DISABLE_DEPRECATION_WARNINGS
569129a6 2776 st->codec = avcodec_alloc_context3(c);
9f810a9b
MS
2777 if (!st->codec) {
2778 av_free(st->info);
2779 av_free(st);
2780 return NULL;
2781 }
9200514a
AK
2782FF_ENABLE_DEPRECATION_WARNINGS
2783#endif
8de1ee9f
AK
2784
2785 st->internal = av_mallocz(sizeof(*st->internal));
2786 if (!st->internal)
2787 goto fail;
2788
194be1f4 2789 if (s->iformat) {
9200514a
AK
2790#if FF_API_LAVF_AVCTX
2791FF_DISABLE_DEPRECATION_WARNINGS
48091512 2792 /* no default bitrate if decoding */
01f4895c 2793 st->codec->bit_rate = 0;
9200514a
AK
2794FF_ENABLE_DEPRECATION_WARNINGS
2795#endif
194be1f4
AK
2796
2797 /* default pts setting is MPEG-like */
2798 avpriv_set_pts_info(st, 33, 1, 90000);
a0c71a57
AK
2799 /* we set the current DTS to 0 so that formats without any timestamps
2800 * but durations get some timestamps, formats with some unknown
2801 * timestamps have their first few packets buffered and the
2802 * timestamps corrected before they are returned to the user */
2803 st->cur_dts = 0;
2804 } else {
2805 st->cur_dts = AV_NOPTS_VALUE;
194be1f4
AK
2806 }
2807
9200514a
AK
2808 st->codecpar = avcodec_parameters_alloc();
2809 if (!st->codecpar)
2810 goto fail;
2811
2812 st->internal->avctx = avcodec_alloc_context3(NULL);
2813 if (!st->internal->avctx)
2814 goto fail;
2815
50ecf157 2816 st->index = s->nb_streams;
12f996ed 2817 st->start_time = AV_NOPTS_VALUE;
50ecf157 2818 st->duration = AV_NOPTS_VALUE;
50ecf157 2819 st->first_dts = AV_NOPTS_VALUE;
86cb7e33 2820 st->probe_packets = MAX_PROBE_PACKETS;
9ee91c2f 2821
635fbcb1 2822 st->last_IP_pts = AV_NOPTS_VALUE;
50ecf157
DB
2823 for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
2824 st->pts_buffer[i] = AV_NOPTS_VALUE;
9ee91c2f 2825
50ecf157 2826 st->sample_aspect_ratio = (AVRational) { 0, 1 };
c30a4489 2827
30c26c24
MS
2828 st->info->fps_first_dts = AV_NOPTS_VALUE;
2829 st->info->fps_last_dts = AV_NOPTS_VALUE;
2830
9200514a
AK
2831#if FF_API_LAVF_AVCTX
2832 st->internal->need_codec_update = 1;
2833#endif
2834
b9a281db
FB
2835 s->streams[s->nb_streams++] = st;
2836 return st;
8de1ee9f
AK
2837fail:
2838 free_stream(&st);
2839 return NULL;
b9a281db
FB
2840}
2841
15afa396
NS
2842AVProgram *av_new_program(AVFormatContext *ac, int id)
2843{
50ecf157 2844 AVProgram *program = NULL;
15afa396
NS
2845 int i;
2846
1a3eb042 2847 av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
15afa396 2848
50ecf157
DB
2849 for (i = 0; i < ac->nb_programs; i++)
2850 if (ac->programs[i]->id == id)
15afa396
NS
2851 program = ac->programs[i];
2852
50ecf157 2853 if (!program) {
15afa396
NS
2854 program = av_mallocz(sizeof(AVProgram));
2855 if (!program)
2856 return NULL;
2857 dynarray_add(&ac->programs, &ac->nb_programs, program);
2858 program->discard = AVDISCARD_NONE;
2859 }
2860 program->id = id;
2861
2862 return program;
2863}
2864
50ecf157
DB
2865AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
2866 int64_t start, int64_t end, const char *title)
79d7836a 2867{
7a2a3e8e
MN
2868 AVChapter *chapter = NULL;
2869 int i;
2870
50ecf157
DB
2871 for (i = 0; i < s->nb_chapters; i++)
2872 if (s->chapters[i]->id == id)
7a2a3e8e
MN
2873 chapter = s->chapters[i];
2874
50ecf157
DB
2875 if (!chapter) {
2876 chapter = av_mallocz(sizeof(AVChapter));
2877 if (!chapter)
5c37f43a 2878 return NULL;
7c8202cc 2879 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
7a2a3e8e 2880 }
d2d67e42 2881 av_dict_set(&chapter->metadata, "title", title, 0);
50ecf157
DB
2882 chapter->id = id;
2883 chapter->time_base = time_base;
2884 chapter->start = start;
2885 chapter->end = end;
79d7836a 2886
5c37f43a 2887 return chapter;
79d7836a 2888}
15afa396 2889
50ecf157 2890void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
526efa10
NS
2891{
2892 int i, j;
50ecf157 2893 AVProgram *program = NULL;
526efa10 2894
72017ea1
BC
2895 if (idx >= ac->nb_streams) {
2896 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2897 return;
2898 }
2899
50ecf157
DB
2900 for (i = 0; i < ac->nb_programs; i++) {
2901 if (ac->programs[i]->id != progid)
526efa10
NS
2902 continue;
2903 program = ac->programs[i];
50ecf157
DB
2904 for (j = 0; j < program->nb_stream_indexes; j++)
2905 if (program->stream_index[j] == idx)
526efa10
NS
2906 return;
2907
f369b935
AK
2908 if (av_reallocp_array(&program->stream_index,
2909 program->nb_stream_indexes + 1,
2910 sizeof(*program->stream_index)) < 0) {
2911 program->nb_stream_indexes = 0;
526efa10 2912 return;
f369b935 2913 }
526efa10
NS
2914 program->stream_index[program->nb_stream_indexes++] = idx;
2915 return;
2916 }
2917}
2918
594a9aeb
MS
2919uint64_t ff_ntp_time(void)
2920{
50ecf157 2921 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
594a9aeb
MS
2922}
2923
50ecf157 2924int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
9150f42e
FB
2925{
2926 const char *p;
0bf92f79
PI
2927 char *q, buf1[20], c;
2928 int nd, len, percentd_found;
9150f42e
FB
2929
2930 q = buf;
2931 p = path;
2932 percentd_found = 0;
50ecf157 2933 for (;;) {
9150f42e
FB
2934 c = *p++;
2935 if (c == '\0')
2936 break;
2937 if (c == '%') {
c9646fda
PG
2938 do {
2939 nd = 0;
50ecf157 2940 while (av_isdigit(*p))
c9646fda 2941 nd = nd * 10 + *p++ - '0';
c9646fda 2942 c = *p++;
efa7f420 2943 } while (av_isdigit(c));
c9646fda 2944
50ecf157 2945 switch (c) {
9150f42e
FB
2946 case '%':
2947 goto addchar;
2948 case 'd':
2949 if (percentd_found)
2950 goto fail;
2951 percentd_found = 1;
2952 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2953 len = strlen(buf1);
2954 if ((q - buf + len) > buf_size - 1)
2955 goto fail;
2956 memcpy(q, buf1, len);
2957 q += len;
2958 break;
2959 default:
2960 goto fail;
2961 }
2962 } else {
50ecf157 2963addchar:
9150f42e
FB
2964 if ((q - buf) < buf_size - 1)
2965 *q++ = c;
2966 }
2967 }
2968 if (!percentd_found)
2969 goto fail;
2970 *q = '\0';
2971 return 0;
50ecf157 2972fail:
9150f42e
FB
2973 *q = '\0';
2974 return -1;
2975}
2976
f3bfe388
MR
2977void av_url_split(char *proto, int proto_size,
2978 char *authorization, int authorization_size,
2979 char *hostname, int hostname_size,
50ecf157 2980 int *port_ptr, char *path, int path_size, const char *url)
f3bfe388 2981{
7ef55085 2982 const char *p, *ls, *at, *col, *brk;
7e1e297e 2983
50ecf157
DB
2984 if (port_ptr)
2985 *port_ptr = -1;
2986 if (proto_size > 0)
2987 proto[0] = 0;
2988 if (authorization_size > 0)
2989 authorization[0] = 0;
2990 if (hostname_size > 0)
2991 hostname[0] = 0;
2992 if (path_size > 0)
2993 path[0] = 0;
7e1e297e
RB
2994
2995 /* parse protocol */
2996 if ((p = strchr(url, ':'))) {
2997 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
2998 p++; /* skip ':' */
50ecf157
DB
2999 if (*p == '/')
3000 p++;
3001 if (*p == '/')
3002 p++;
a9a721da 3003 } else {
7e1e297e
RB
3004 /* no protocol means plain filename */
3005 av_strlcpy(path, url, path_size);
3006 return;
3007 }
6ba5cbc6 3008
7e1e297e 3009 /* separate path from hostname */
7ef55085 3010 ls = strchr(p, '/');
50ecf157 3011 if (!ls)
7ef55085 3012 ls = strchr(p, '?');
50ecf157 3013 if (ls)
5cc9253f 3014 av_strlcpy(path, ls, path_size);
7ef55085 3015 else
50ecf157 3016 ls = &p[strlen(p)]; // XXX
7e1e297e
RB
3017
3018 /* the rest is hostname, use that to parse auth/port */
3019 if (ls != p) {
3020 /* authorization (user[:pass]@hostname) */
3021 if ((at = strchr(p, '@')) && at < ls) {
3022 av_strlcpy(authorization, p,
3023 FFMIN(authorization_size, at + 1 - p));
3024 p = at + 1; /* skip '@' */
a9a721da 3025 }
7e1e297e 3026
f8f88a42
RB
3027 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3028 /* [host]:port */
3029 av_strlcpy(hostname, p + 1,
3030 FFMIN(hostname_size, brk - p));
3031 if (brk[1] == ':' && port_ptr)
3032 *port_ptr = atoi(brk + 2);
3033 } else if ((col = strchr(p, ':')) && col < ls) {
3034 av_strlcpy(hostname, p,
3035 FFMIN(col + 1 - p, hostname_size));
50ecf157
DB
3036 if (port_ptr)
3037 *port_ptr = atoi(col + 1);
f8f88a42
RB
3038 } else
3039 av_strlcpy(hostname, p,
3040 FFMIN(ls + 1 - p, hostname_size));
a9a721da 3041 }
a9a721da
FB
3042}
3043
ddbeb954 3044char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
f1c80e35
RB
3045{
3046 int i;
ddbeb954 3047 static const char hex_table_uc[16] = { '0', '1', '2', '3',
d8f92957
MS
3048 '4', '5', '6', '7',
3049 '8', '9', 'A', 'B',
3050 'C', 'D', 'E', 'F' };
ddbeb954
MS
3051 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3052 '4', '5', '6', '7',
3053 '8', '9', 'a', 'b',
3054 'c', 'd', 'e', 'f' };
3055 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
f1c80e35 3056
50ecf157 3057 for (i = 0; i < s; i++) {
452d3edb
RB
3058 buff[i * 2] = hex_table[src[i] >> 4];
3059 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
f1c80e35
RB
3060 }
3061
3062 return buff;
3063}
3064
311baee7
MS
3065int ff_hex_to_data(uint8_t *data, const char *p)
3066{
3067 int c, len, v;
3068
3069 len = 0;
50ecf157 3070 v = 1;
311baee7
MS
3071 for (;;) {
3072 p += strspn(p, SPACE_CHARS);
3073 if (*p == '\0')
3074 break;
efa7f420 3075 c = av_toupper((unsigned char) *p++);
311baee7
MS
3076 if (c >= '0' && c <= '9')
3077 c = c - '0';
3078 else if (c >= 'A' && c <= 'F')
3079 c = c - 'A' + 10;
3080 else
3081 break;
3082 v = (v << 4) | c;
3083 if (v & 0x100) {
3084 if (data)
3085 data[len] = v;
3086 len++;
3087 v = 1;
3088 }
3089 }
3090 return len;
3091}
3092
c3f9ebf7
AK
3093void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3094 unsigned int pts_num, unsigned int pts_den)
3095{
b3190529 3096 AVRational new_tb;
50ecf157
DB
3097 if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
3098 if (new_tb.num != pts_num)
3099 av_log(NULL, AV_LOG_DEBUG,
3100 "st:%d removing common factor %d from timebase\n",
3101 s->index, pts_num / new_tb.num);
3102 } else
3103 av_log(NULL, AV_LOG_WARNING,
3104 "st:%d has too large timebase, reducing\n", s->index);
3105
3106 if (new_tb.num <= 0 || new_tb.den <= 0) {
3107 av_log(NULL, AV_LOG_ERROR,
3108 "Ignoring attempt to set invalid timebase for st:%d\n",
3109 s->index);
b3190529
RD
3110 return;
3111 }
50ecf157