lavf: use new decode API
[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")) &&
8978feda 1830 file_size && ic->pb->seekable) {
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
a67c061e
AK
2092int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2093{
9f75260e 2094 int i, count, ret, read_size, j;
b9a281db 2095 AVStream *st;
9200514a 2096 AVCodecContext *avctx;
fb2758c8 2097 AVPacket pkt1, *pkt;
50ecf157
DB
2098 int64_t old_offset = avio_tell(ic->pb);
2099 // new streams might appear, no options for those
2100 int orig_nb_streams = ic->nb_streams;
0cbff027 2101
50ecf157 2102 for (i = 0; i < ic->nb_streams; i++) {
edb5238c 2103 const AVCodec *codec;
59297ad6 2104 AVDictionary *thread_opt = NULL;
c0df9d75 2105 st = ic->streams[i];
9200514a 2106 avctx = st->internal->avctx;
dafaef2f 2107
50ecf157 2108 // only for the split stuff
fe8344a2 2109 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
9200514a 2110 st->parser = av_parser_init(st->codecpar->codec_id);
50ecf157 2111 if (st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser)
7cbaa7ba 2112 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
90ad92b3 2113 }
9200514a
AK
2114
2115 /* check if the caller has overridden the codec id */
2116#if FF_API_LAVF_AVCTX
2117FF_DISABLE_DEPRECATION_WARNINGS
2118 if (st->codec->codec_id != st->internal->orig_codec_id) {
2119 st->codecpar->codec_id = st->codec->codec_id;
2120 st->codecpar->codec_type = st->codec->codec_type;
2121 st->internal->orig_codec_id = st->codec->codec_id;
2122 }
2123FF_ENABLE_DEPRECATION_WARNINGS
2124#endif
2125 if (st->codecpar->codec_id != st->internal->orig_codec_id)
2126 st->internal->orig_codec_id = st->codecpar->codec_id;
2127
2128 ret = avcodec_parameters_to_context(avctx, st->codecpar);
2129 if (ret < 0)
2130 goto find_stream_info_err;
2131 if (st->codecpar->codec_id != AV_CODEC_ID_PROBE &&
2132 st->codecpar->codec_id != AV_CODEC_ID_NONE)
2133 st->internal->avctx_inited = 1;
2134
2135#if FF_API_LAVF_AVCTX
2136FF_DISABLE_DEPRECATION_WARNINGS
50ecf157 2137 codec = st->codec->codec ? st->codec->codec
9200514a
AK
2138 : avcodec_find_decoder(st->codecpar->codec_id);
2139FF_ENABLE_DEPRECATION_WARNINGS
2140#else
2141 codec = avcodec_find_decoder(st->codecpar->codec_id);
2142#endif
62784e37 2143
50ecf157
DB
2144 /* Force thread count to 1 since the H.264 decoder will not extract
2145 * SPS and PPS to extradata during multi-threaded decoding. */
59297ad6
JG
2146 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2147
cb2c971d 2148 /* Ensure that subtitle_header is properly set. */
9200514a
AK
2149 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE
2150 && codec && !avctx->codec)
2151 avcodec_open2(avctx, codec,
50ecf157 2152 options ? &options[i] : &thread_opt);
cb2c971d 2153
50ecf157 2154 // Try to just open decoders, in case this is enough to get parameters.
8c1d6ac6 2155 if (!has_codec_parameters(st)) {
9200514a
AK
2156 if (codec && !avctx->codec)
2157 avcodec_open2(avctx, codec,
50ecf157 2158 options ? &options[i] : &thread_opt);
43e4d57f 2159 }
59297ad6
JG
2160 if (!options)
2161 av_dict_free(&thread_opt);
c0df9d75
MN
2162 }
2163
50ecf157 2164 for (i = 0; i < ic->nb_streams; i++) {
fe1c1198
AK
2165 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2166 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
15bc38e5 2167 }
115329f1 2168
50ecf157 2169 count = 0;
b9a281db 2170 read_size = 0;
50ecf157
DB
2171 for (;;) {
2172 if (ff_check_interrupt(&ic->interrupt_callback)) {
2173 ret = AVERROR_EXIT;
71ee6515 2174 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
1d14361d
MN
2175 break;
2176 }
2177
b9a281db 2178 /* check if one codec still needs to be handled */
50ecf157 2179 for (i = 0; i < ic->nb_streams; i++) {
7c152a45
AH
2180 int fps_analyze_framecount = 20;
2181
b9a281db 2182 st = ic->streams[i];
8c1d6ac6 2183 if (!has_codec_parameters(st))
b9a281db 2184 break;
50ecf157
DB
2185 /* If the timebase is coarse (like the usual millisecond precision
2186 * of mkv), we need to analyze more frames to reliably arrive at
2187 * the correct fps. */
7c152a45
AH
2188 if (av_q2d(st->time_base) > 0.0005)
2189 fps_analyze_framecount *= 2;
30315a8d
AC
2190 if (ic->fps_probe_size >= 0)
2191 fps_analyze_framecount = ic->fps_probe_size;
3e76d1b5 2192 /* variable fps and no guess at the real fps */
1eb57e1d 2193 if (!st->avg_frame_rate.num &&
50ecf157 2194 st->codec_info_nb_frames < fps_analyze_framecount &&
9200514a 2195 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
3e76d1b5 2196 break;
50ecf157 2197 if (st->parser && st->parser->parser->split &&
9200514a 2198 !st->codecpar->extradata)
90ad92b3 2199 break;
ba24f129 2200 if (st->first_dts == AV_NOPTS_VALUE &&
b263f8ff 2201 st->codec_info_nb_frames < ic->max_ts_probe &&
9200514a
AK
2202 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
2203 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
82583548 2204 break;
b9a281db
FB
2205 }
2206 if (i == ic->nb_streams) {
50ecf157
DB
2207 /* NOTE: If the format has no header, then we need to read some
2208 * packets to get most of the streams, so we cannot stop here. */
fb2758c8 2209 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
50ecf157 2210 /* If we found the info for all the codecs, we can stop. */
b9a281db 2211 ret = count;
71ee6515 2212 av_log(ic, AV_LOG_DEBUG, "All info found\n");
b9a281db
FB
2213 break;
2214 }
5fb83c38 2215 }
50ecf157 2216 /* We did not get all the codec info, but we read too much data. */
57011a13 2217 if (read_size >= ic->probesize) {
35eab0c0 2218 ret = count;
50ecf157
DB
2219 av_log(ic, AV_LOG_DEBUG,
2220 "Probe buffer size limit %d reached\n", ic->probesize);
35eab0c0
MN
2221 break;
2222 }
b9a281db 2223
50ecf157
DB
2224 /* NOTE: A new stream can be added there if no header in file
2225 * (AVFMTCTX_NOHEADER). */
d3bb7191 2226 ret = read_frame_internal(ic, &pkt1);
59ca3955
AF
2227 if (ret == AVERROR(EAGAIN))
2228 continue;
2229
2230 if (ret < 0) {
212fd3a1
AK
2231 /* EOF or error*/
2232 AVPacket empty_pkt = { 0 };
8c1d6ac6 2233 int err = 0;
212fd3a1
AK
2234 av_init_packet(&empty_pkt);
2235
50ecf157
DB
2236 /* We could not have all the codec parameters before EOF. */
2237 ret = -1;
2238 for (i = 0; i < ic->nb_streams; i++) {
e19456e3 2239 st = ic->streams[i];
212fd3a1
AK
2240
2241 /* flush the decoders */
8c1d6ac6 2242 if (st->info->found_decoder == 1) {
94cf64b8 2243 do {
9200514a 2244 err = try_decode_frame(ic, st, &empty_pkt,
50ecf157
DB
2245 (options && i < orig_nb_streams)
2246 ? &options[i] : NULL);
94cf64b8 2247 } while (err > 0 && !has_codec_parameters(st));
8c1d6ac6 2248 }
b3461c29
JG
2249
2250 if (err < 0) {
2251 av_log(ic, AV_LOG_WARNING,
2252 "decoding for stream %d failed\n", st->index);
8c1d6ac6 2253 } else if (!has_codec_parameters(st)) {
305ee50f 2254 char buf[256];
9200514a 2255 avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
b3461c29
JG
2256 av_log(ic, AV_LOG_WARNING,
2257 "Could not find codec parameters (%s)\n", buf);
344a18c3
MR
2258 } else {
2259 ret = 0;
305ee50f 2260 }
e19456e3 2261 }
fb2758c8
FB
2262 break;
2263 }
2264
d584533c
LB
2265 pkt = &pkt1;
2266
2267 if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
2268 ret = add_to_pktbuf(&ic->internal->packet_buffer, pkt,
2269 &ic->internal->packet_buffer_end, 0);
2270 if (ret < 0)
681ed000
LB
2271 goto find_stream_info_err;
2272 }
b9a281db 2273
fb2758c8 2274 read_size += pkt->size;
b9a281db
FB
2275
2276 st = ic->streams[pkt->stream_index];
9200514a
AK
2277 avctx = st->internal->avctx;
2278 if (!st->internal->avctx_inited) {
2279 ret = avcodec_parameters_to_context(avctx, st->codecpar);
2280 if (ret < 0)
2281 goto find_stream_info_err;
2282 st->internal->avctx_inited = 1;
2283 }
2284
fe1c1198
AK
2285 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2286 /* check for non-increasing dts */
2287 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2288 st->info->fps_last_dts >= pkt->dts) {
50ecf157
DB
2289 av_log(ic, AV_LOG_WARNING,
2290 "Non-increasing DTS in stream %d: packet %d with DTS "
2291 "%"PRId64", packet %d with DTS %"PRId64"\n",
2292 st->index, st->info->fps_last_dts_idx,
2293 st->info->fps_last_dts, st->codec_info_nb_frames,
2294 pkt->dts);
2295 st->info->fps_first_dts =
2296 st->info->fps_last_dts = AV_NOPTS_VALUE;
fe1c1198 2297 }
50ecf157
DB
2298 /* Check for a discontinuity in dts. If the difference in dts
2299 * is more than 1000 times the average packet duration in the
2300 * sequence, we treat it as a discontinuity. */
bdefe22b
MS
2301 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2302 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2303 (pkt->dts - st->info->fps_last_dts) / 1000 >
50ecf157
DB
2304 (st->info->fps_last_dts - st->info->fps_first_dts) /
2305 (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2306 av_log(ic, AV_LOG_WARNING,
2307 "DTS discontinuity in stream %d: packet %d with DTS "
2308 "%"PRId64", packet %d with DTS %"PRId64"\n",
2309 st->index, st->info->fps_last_dts_idx,
2310 st->info->fps_last_dts, st->codec_info_nb_frames,
2311 pkt->dts);
2312 st->info->fps_first_dts =
2313 st->info->fps_last_dts = AV_NOPTS_VALUE;
bdefe22b 2314 }
fe1c1198
AK
2315
2316 /* update stored dts values */
2317 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2318 st->info->fps_first_dts = pkt->dts;
2319 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2320 }
50ecf157 2321 st->info->fps_last_dts = pkt->dts;
fe1c1198
AK
2322 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2323
2324 /* check max_analyze_duration */
2325 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2326 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
db9d39b4
LB
2327 av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached\n",
2328 ic->max_analyze_duration);
19133e96
JR
2329 if (ic->flags & AVFMT_FLAG_NOBUFFER)
2330 av_packet_unref(pkt);
3a560188 2331 break;
71ee6515 2332 }
3a560188 2333 }
9200514a
AK
2334 if (st->parser && st->parser->parser->split && !avctx->extradata) {
2335 int i = st->parser->parser->split(avctx, pkt->data, pkt->size);
4df30f71 2336 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
9200514a
AK
2337 avctx->extradata_size = i;
2338 avctx->extradata = av_mallocz(avctx->extradata_size +
2339 AV_INPUT_BUFFER_PADDING_SIZE);
2340 if (!avctx->extradata)
4df30f71 2341 return AVERROR(ENOMEM);
9200514a
AK
2342 memcpy(avctx->extradata, pkt->data,
2343 avctx->extradata_size);
90ad92b3
MN
2344 }
2345 }
115329f1 2346
50ecf157
DB
2347 /* If still no information, we try to open the codec and to
2348 * decompress the frame. We try to avoid that in most cases as
2349 * it takes longer and uses more memory. For MPEG-4, we need to
2350 * decompress for QuickTime.
2351 *
def97856 2352 * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
50ecf157
DB
2353 * least one frame of codec data, this makes sure the codec initializes
2354 * the channel configuration and does not only trust the values from
2355 * the container. */
9200514a 2356 try_decode_frame(ic, st, pkt,
50ecf157 2357 (options && i < orig_nb_streams) ? &options[i] : NULL);
115329f1 2358
19133e96
JR
2359 if (ic->flags & AVFMT_FLAG_NOBUFFER)
2360 av_packet_unref(pkt);
2361
9d3fdf20 2362 st->codec_info_nb_frames++;
b9a281db
FB
2363 count++;
2364 }
2365
bd107136 2366 // close codecs which were opened in try_decode_frame()
50ecf157 2367 for (i = 0; i < ic->nb_streams; i++) {
43c0040a 2368 st = ic->streams[i];
9200514a 2369 avcodec_close(st->internal->avctx);
43c0040a 2370 }
50ecf157 2371 for (i = 0; i < ic->nb_streams; i++) {
b9a281db 2372 st = ic->streams[i];
9200514a
AK
2373 avctx = st->internal->avctx;
2374 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
fe1c1198 2375 /* estimate average framerate if not set by demuxer */
50ecf157
DB
2376 if (!st->avg_frame_rate.num &&
2377 st->info->fps_last_dts != st->info->fps_first_dts) {
2378 int64_t delta_dts = st->info->fps_last_dts -
2379 st->info->fps_first_dts;
2380 int delta_packets = st->info->fps_last_dts_idx -
2381 st->info->fps_first_dts_idx;
2382 int best_fps = 0;
f66eeff1 2383 double best_error = 0.01;
fe1c1198 2384
e740929a 2385 if (delta_dts >= INT64_MAX / st->time_base.num ||
ce67f442
MS
2386 delta_packets >= INT64_MAX / st->time_base.den ||
2387 delta_dts < 0)
e740929a 2388 continue;
f35f8eeb 2389 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
50ecf157
DB
2390 delta_packets * (int64_t) st->time_base.den,
2391 delta_dts * (int64_t) st->time_base.num, 60000);
f66eeff1 2392
50ecf157
DB
2393 /* Round guessed framerate to a "standard" framerate if it's
2394 * within 1% of the original estimate. */
78987a88 2395 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
50ecf157
DB
2396 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
2397 double error = fabs(av_q2d(st->avg_frame_rate) /
2398 av_q2d(std_fps) - 1);
f66eeff1
AK
2399
2400 if (error < best_error) {
2401 best_error = error;
2402 best_fps = std_fps.num;
2403 }
2404 }
50ecf157 2405 if (best_fps)
f66eeff1 2406 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
50ecf157 2407 best_fps, 12 * 1001, INT_MAX);
fe1c1198 2408 }
9200514a
AK
2409 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
2410 if (!avctx->bits_per_coded_sample)
2411 avctx->bits_per_coded_sample =
2412 av_get_bits_per_sample(avctx->codec_id);
c70a6a41 2413 // set stream disposition based on audio service type
9200514a 2414 switch (avctx->audio_service_type) {
c70a6a41 2415 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
50ecf157
DB
2416 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
2417 break;
c70a6a41 2418 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
50ecf157
DB
2419 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
2420 break;
c70a6a41 2421 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
50ecf157
DB
2422 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
2423 break;
c70a6a41 2424 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
50ecf157
DB
2425 st->disposition = AV_DISPOSITION_COMMENT;
2426 break;
c70a6a41 2427 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
50ecf157
DB
2428 st->disposition = AV_DISPOSITION_KARAOKE;
2429 break;
c70a6a41 2430 }
b9a281db 2431 }
de6d9b64 2432 }
b9a281db 2433
c2c3dedf
AJ
2434 compute_chapters_end(ic);
2435
9200514a
AK
2436 /* update the stream parameters from the internal codec contexts */
2437 for (i = 0; i < ic->nb_streams; i++) {
2438 st = ic->streams[i];
2439 if (!st->internal->avctx_inited)
2440 continue;
2441
2442 ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
2443 if (ret < 0)
2444 goto find_stream_info_err;
2445
2446#if FF_API_LAVF_AVCTX
2447FF_DISABLE_DEPRECATION_WARNINGS
2448 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
2449 if (ret < 0)
2450 goto find_stream_info_err;
2451
2452 if (st->internal->avctx->subtitle_header) {
2453 st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
2454 if (!st->codec->subtitle_header)
2455 goto find_stream_info_err;
2456 st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
2457 memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
2458 st->codec->subtitle_header_size);
2459 }
2460FF_ENABLE_DEPRECATION_WARNINGS
2461#endif
2462
2463 st->internal->avctx_inited = 0;
2464 }
2465
1ceb07eb
AK
2466 estimate_timings(ic, old_offset);
2467
50ecf157
DB
2468find_stream_info_err:
2469 for (i = 0; i < ic->nb_streams; i++) {
fd0368e7 2470 av_freep(&ic->streams[i]->info);
e4e30256 2471 }
b9a281db 2472 return ret;
de6d9b64
FB
2473}
2474
9128ae08
NG
2475static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2476{
2477 int i, j;
2478
2479 for (i = 0; i < ic->nb_programs; i++)
2480 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2481 if (ic->programs[i]->stream_index[j] == s)
2482 return ic->programs[i];
2483 return NULL;
2484}
2485
50ecf157
DB
2486int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
2487 int wanted_stream_nb, int related_stream,
2488 AVCodec **decoder_ret, int flags)
9128ae08 2489{
2c715816 2490 int i, nb_streams = ic->nb_streams;
9128ae08
NG
2491 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2492 unsigned *program = NULL;
2493 AVCodec *decoder = NULL, *best_decoder = NULL;
2494
2495 if (related_stream >= 0 && wanted_stream_nb < 0) {
2496 AVProgram *p = find_program_from_stream(ic, related_stream);
2497 if (p) {
50ecf157 2498 program = p->stream_index;
9128ae08
NG
2499 nb_streams = p->nb_stream_indexes;
2500 }
2501 }
2502 for (i = 0; i < nb_streams; i++) {
2c715816 2503 int real_stream_index = program ? program[i] : i;
50ecf157 2504 AVStream *st = ic->streams[real_stream_index];
9200514a
AK
2505 AVCodecParameters *par = st->codecpar;
2506 if (par->codec_type != type)
9128ae08 2507 continue;
2c715816 2508 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
9128ae08 2509 continue;
50ecf157
DB
2510 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |
2511 AV_DISPOSITION_VISUAL_IMPAIRED))
52091491 2512 continue;
9128ae08 2513 if (decoder_ret) {
9200514a 2514 decoder = avcodec_find_decoder(par->codec_id);
9128ae08
NG
2515 if (!decoder) {
2516 if (ret < 0)
2517 ret = AVERROR_DECODER_NOT_FOUND;
2518 continue;
2519 }
2520 }
2521 if (best_count >= st->codec_info_nb_frames)
2522 continue;
50ecf157
DB
2523 best_count = st->codec_info_nb_frames;
2524 ret = real_stream_index;
9128ae08
NG
2525 best_decoder = decoder;
2526 if (program && i == nb_streams - 1 && ret < 0) {
50ecf157 2527 program = NULL;
9128ae08 2528 nb_streams = ic->nb_streams;
50ecf157
DB
2529 /* no related stream found, try again with everything */
2530 i = 0;
9128ae08
NG
2531 }
2532 }
2533 if (decoder_ret)
2534 *decoder_ret = best_decoder;
2535 return ret;
2536}
2537
fb2758c8
FB
2538/*******************************************************/
2539
fb2758c8
FB
2540int av_read_play(AVFormatContext *s)
2541{
fa13095a
BA
2542 if (s->iformat->read_play)
2543 return s->iformat->read_play(s);
fd2982a0 2544 if (s->pb)
ff1ec0c3 2545 return avio_pause(s->pb, 0);
fa13095a 2546 return AVERROR(ENOSYS);
fb2758c8
FB
2547}
2548
fb2758c8
FB
2549int av_read_pause(AVFormatContext *s)
2550{
fa13095a
BA
2551 if (s->iformat->read_pause)
2552 return s->iformat->read_pause(s);
fd2982a0 2553 if (s->pb)
ff1ec0c3 2554 return avio_pause(s->pb, 1);
fa13095a 2555 return AVERROR(ENOSYS);
fb2758c8
FB
2556}
2557
aeda1121
AK
2558static void free_stream(AVStream **pst)
2559{
2560 AVStream *st = *pst;
2561 int i;
2562
2563 if (!st)
2564 return;
2565
2566 for (i = 0; i < st->nb_side_data; i++)
2567 av_freep(&st->side_data[i].data);
2568 av_freep(&st->side_data);
2569
2570 if (st->parser)
2571 av_parser_close(st->parser);
2572
2573 if (st->attached_pic.data)
2574 av_packet_unref(&st->attached_pic);
2575
9200514a
AK
2576 if (st->internal) {
2577 avcodec_free_context(&st->internal->avctx);
2578 }
8de1ee9f
AK
2579 av_freep(&st->internal);
2580
aeda1121 2581 av_dict_free(&st->metadata);
9200514a 2582 avcodec_parameters_free(&st->codecpar);
aeda1121
AK
2583 av_freep(&st->probe_data.buf);
2584 av_free(st->index_entries);
9200514a
AK
2585#if FF_API_LAVF_AVCTX
2586FF_DISABLE_DEPRECATION_WARNINGS
aeda1121
AK
2587 av_free(st->codec->extradata);
2588 av_free(st->codec->subtitle_header);
2589 av_free(st->codec);
9200514a
AK
2590FF_ENABLE_DEPRECATION_WARNINGS
2591#endif
aeda1121
AK
2592 av_free(st->priv_data);
2593 av_free(st->info);
2594
2595 av_freep(pst);
2596}
2597
f124b087
MS
2598void avformat_free_context(AVFormatContext *s)
2599{
aeda1121 2600 int i;
f124b087 2601
0db6bbb2
LB
2602 if (!s)
2603 return;
2604
36773283 2605 av_opt_free(s);
dbaba52e 2606 if (s->iformat && s->iformat->priv_class && s->priv_data)
36773283
AK
2607 av_opt_free(s->priv_data);
2608
aeda1121
AK
2609 for (i = 0; i < s->nb_streams; i++)
2610 free_stream(&s->streams[i]);
25b32586 2611
50ecf157 2612 for (i = s->nb_programs - 1; i >= 0; i--) {
d2d67e42 2613 av_dict_free(&s->programs[i]->metadata);
526efa10 2614 av_freep(&s->programs[i]->stream_index);
15afa396
NS
2615 av_freep(&s->programs[i]);
2616 }
ceedda75 2617 av_freep(&s->programs);
a8dbe951 2618 av_freep(&s->priv_data);
50ecf157 2619 while (s->nb_chapters--) {
d2d67e42 2620 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
7c8202cc 2621 av_free(s->chapters[s->nb_chapters]);
79d7836a
AK
2622 }
2623 av_freep(&s->chapters);
d2d67e42 2624 av_dict_free(&s->metadata);
7bbb67d5 2625 av_freep(&s->streams);
33c859c1 2626 av_freep(&s->internal);
1ea4f593 2627 av_free(s);
de6d9b64
FB
2628}
2629
52660454
AK
2630void avformat_close_input(AVFormatContext **ps)
2631{
2632 AVFormatContext *s = *ps;
50ecf157 2633 AVIOContext *pb = s->pb;
44272c1c 2634
3f7fd59d 2635 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
44272c1c
LB
2636 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2637 pb = NULL;
2638
3a7f7678 2639 flush_packet_queue(s);
44272c1c 2640
50ecf157 2641 if (s->iformat)
44272c1c
LB
2642 if (s->iformat->read_close)
2643 s->iformat->read_close(s);
44272c1c 2644
3a7f7678 2645 avformat_free_context(s);
44272c1c 2646
52660454 2647 *ps = NULL;
4d1f443c
LB
2648
2649 avio_close(pb);
2506fd54
RD
2650}
2651
3d90f27a 2652AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
569129a6 2653{
b9a281db 2654 AVStream *st;
504ee036 2655 int i;
b9a281db 2656
50ecf157
DB
2657 if (av_reallocp_array(&s->streams, s->nb_streams + 1,
2658 sizeof(*s->streams)) < 0) {
f369b935 2659 s->nb_streams = 0;
38aab35f 2660 return NULL;
f369b935 2661 }
b9a281db
FB
2662
2663 st = av_mallocz(sizeof(AVStream));
2664 if (!st)
2665 return NULL;
fd0368e7
AJ
2666 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2667 av_free(st);
2668 return NULL;
2669 }
115329f1 2670
9200514a
AK
2671#if FF_API_LAVF_AVCTX
2672FF_DISABLE_DEPRECATION_WARNINGS
569129a6 2673 st->codec = avcodec_alloc_context3(c);
9f810a9b
MS
2674 if (!st->codec) {
2675 av_free(st->info);
2676 av_free(st);
2677 return NULL;
2678 }
9200514a
AK
2679FF_ENABLE_DEPRECATION_WARNINGS
2680#endif
8de1ee9f
AK
2681
2682 st->internal = av_mallocz(sizeof(*st->internal));
2683 if (!st->internal)
2684 goto fail;
2685
194be1f4 2686 if (s->iformat) {
9200514a
AK
2687#if FF_API_LAVF_AVCTX
2688FF_DISABLE_DEPRECATION_WARNINGS
48091512 2689 /* no default bitrate if decoding */
01f4895c 2690 st->codec->bit_rate = 0;
9200514a
AK
2691FF_ENABLE_DEPRECATION_WARNINGS
2692#endif
194be1f4
AK
2693
2694 /* default pts setting is MPEG-like */
2695 avpriv_set_pts_info(st, 33, 1, 90000);
a0c71a57
AK
2696 /* we set the current DTS to 0 so that formats without any timestamps
2697 * but durations get some timestamps, formats with some unknown
2698 * timestamps have their first few packets buffered and the
2699 * timestamps corrected before they are returned to the user */
2700 st->cur_dts = 0;
2701 } else {
2702 st->cur_dts = AV_NOPTS_VALUE;
194be1f4
AK
2703 }
2704
9200514a
AK
2705 st->codecpar = avcodec_parameters_alloc();
2706 if (!st->codecpar)
2707 goto fail;
2708
2709 st->internal->avctx = avcodec_alloc_context3(NULL);
2710 if (!st->internal->avctx)
2711 goto fail;
2712
50ecf157 2713 st->index = s->nb_streams;
12f996ed 2714 st->start_time = AV_NOPTS_VALUE;
50ecf157 2715 st->duration = AV_NOPTS_VALUE;
50ecf157 2716 st->first_dts = AV_NOPTS_VALUE;
86cb7e33 2717 st->probe_packets = MAX_PROBE_PACKETS;
9ee91c2f 2718
635fbcb1 2719 st->last_IP_pts = AV_NOPTS_VALUE;
50ecf157
DB
2720 for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
2721 st->pts_buffer[i] = AV_NOPTS_VALUE;
9ee91c2f 2722
50ecf157 2723 st->sample_aspect_ratio = (AVRational) { 0, 1 };
c30a4489 2724
30c26c24
MS
2725 st->info->fps_first_dts = AV_NOPTS_VALUE;
2726 st->info->fps_last_dts = AV_NOPTS_VALUE;
2727
9200514a
AK
2728#if FF_API_LAVF_AVCTX
2729 st->internal->need_codec_update = 1;
2730#endif
2731
b9a281db
FB
2732 s->streams[s->nb_streams++] = st;
2733 return st;
8de1ee9f
AK
2734fail:
2735 free_stream(&st);
2736 return NULL;
b9a281db
FB
2737}
2738
15afa396
NS
2739AVProgram *av_new_program(AVFormatContext *ac, int id)
2740{
50ecf157 2741 AVProgram *program = NULL;
15afa396
NS
2742 int i;
2743
1a3eb042 2744 av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
15afa396 2745
50ecf157
DB
2746 for (i = 0; i < ac->nb_programs; i++)
2747 if (ac->programs[i]->id == id)
15afa396
NS
2748 program = ac->programs[i];
2749
50ecf157 2750 if (!program) {
15afa396
NS
2751 program = av_mallocz(sizeof(AVProgram));
2752 if (!program)
2753 return NULL;
2754 dynarray_add(&ac->programs, &ac->nb_programs, program);
2755 program->discard = AVDISCARD_NONE;
2756 }
2757 program->id = id;
2758
2759 return program;
2760}
2761
50ecf157
DB
2762AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
2763 int64_t start, int64_t end, const char *title)
79d7836a 2764{
7a2a3e8e
MN
2765 AVChapter *chapter = NULL;
2766 int i;
2767
50ecf157
DB
2768 for (i = 0; i < s->nb_chapters; i++)
2769 if (s->chapters[i]->id == id)
7a2a3e8e
MN
2770 chapter = s->chapters[i];
2771
50ecf157
DB
2772 if (!chapter) {
2773 chapter = av_mallocz(sizeof(AVChapter));
2774 if (!chapter)
5c37f43a 2775 return NULL;
7c8202cc 2776 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
7a2a3e8e 2777 }
d2d67e42 2778 av_dict_set(&chapter->metadata, "title", title, 0);
50ecf157
DB
2779 chapter->id = id;
2780 chapter->time_base = time_base;
2781 chapter->start = start;
2782 chapter->end = end;
79d7836a 2783
5c37f43a 2784 return chapter;
79d7836a 2785}
15afa396 2786
50ecf157 2787void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
526efa10
NS
2788{
2789 int i, j;
50ecf157 2790 AVProgram *program = NULL;
526efa10 2791
72017ea1
BC
2792 if (idx >= ac->nb_streams) {
2793 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2794 return;
2795 }
2796
50ecf157
DB
2797 for (i = 0; i < ac->nb_programs; i++) {
2798 if (ac->programs[i]->id != progid)
526efa10
NS
2799 continue;
2800 program = ac->programs[i];
50ecf157
DB
2801 for (j = 0; j < program->nb_stream_indexes; j++)
2802 if (program->stream_index[j] == idx)
526efa10
NS
2803 return;
2804
f369b935
AK
2805 if (av_reallocp_array(&program->stream_index,
2806 program->nb_stream_indexes + 1,
2807 sizeof(*program->stream_index)) < 0) {
2808 program->nb_stream_indexes = 0;
526efa10 2809 return;
f369b935 2810 }
526efa10
NS
2811 program->stream_index[program->nb_stream_indexes++] = idx;
2812 return;
2813 }
2814}
2815
594a9aeb
MS
2816uint64_t ff_ntp_time(void)
2817{
50ecf157 2818 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
594a9aeb
MS
2819}
2820
50ecf157 2821int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
9150f42e
FB
2822{
2823 const char *p;
0bf92f79
PI
2824 char *q, buf1[20], c;
2825 int nd, len, percentd_found;
9150f42e
FB
2826
2827 q = buf;
2828 p = path;
2829 percentd_found = 0;
50ecf157 2830 for (;;) {
9150f42e
FB
2831 c = *p++;
2832 if (c == '\0')
2833 break;
2834 if (c == '%') {
c9646fda
PG
2835 do {
2836 nd = 0;
50ecf157 2837 while (av_isdigit(*p))
c9646fda 2838 nd = nd * 10 + *p++ - '0';
c9646fda 2839 c = *p++;
efa7f420 2840 } while (av_isdigit(c));
c9646fda 2841
50ecf157 2842 switch (c) {
9150f42e
FB
2843 case '%':
2844 goto addchar;
2845 case 'd':
2846 if (percentd_found)
2847 goto fail;
2848 percentd_found = 1;
2849 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2850 len = strlen(buf1);
2851 if ((q - buf + len) > buf_size - 1)
2852 goto fail;
2853 memcpy(q, buf1, len);
2854 q += len;
2855 break;
2856 default:
2857 goto fail;
2858 }
2859 } else {
50ecf157 2860addchar:
9150f42e
FB
2861 if ((q - buf) < buf_size - 1)
2862 *q++ = c;
2863 }
2864 }
2865 if (!percentd_found)
2866 goto fail;
2867 *q = '\0';
2868 return 0;
50ecf157 2869fail:
9150f42e
FB
2870 *q = '\0';
2871 return -1;
2872}
2873
f3bfe388
MR
2874void av_url_split(char *proto, int proto_size,
2875 char *authorization, int authorization_size,
2876 char *hostname, int hostname_size,
50ecf157 2877 int *port_ptr, char *path, int path_size, const char *url)
f3bfe388 2878{
7ef55085 2879 const char *p, *ls, *at, *col, *brk;
7e1e297e 2880
50ecf157
DB
2881 if (port_ptr)
2882 *port_ptr = -1;
2883 if (proto_size > 0)
2884 proto[0] = 0;
2885 if (authorization_size > 0)
2886 authorization[0] = 0;
2887 if (hostname_size > 0)
2888 hostname[0] = 0;
2889 if (path_size > 0)
2890 path[0] = 0;
7e1e297e
RB
2891
2892 /* parse protocol */
2893 if ((p = strchr(url, ':'))) {
2894 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
2895 p++; /* skip ':' */
50ecf157
DB
2896 if (*p == '/')
2897 p++;
2898 if (*p == '/')
2899 p++;
a9a721da 2900 } else {
7e1e297e
RB
2901 /* no protocol means plain filename */
2902 av_strlcpy(path, url, path_size);
2903 return;
2904 }
6ba5cbc6 2905
7e1e297e 2906 /* separate path from hostname */
7ef55085 2907 ls = strchr(p, '/');
50ecf157 2908 if (!ls)
7ef55085 2909 ls = strchr(p, '?');
50ecf157 2910 if (ls)
5cc9253f 2911 av_strlcpy(path, ls, path_size);
7ef55085 2912 else
50ecf157 2913 ls = &p[strlen(p)]; // XXX
7e1e297e
RB
2914
2915 /* the rest is hostname, use that to parse auth/port */
2916 if (ls != p) {
2917 /* authorization (user[:pass]@hostname) */
2918 if ((at = strchr(p, '@')) && at < ls) {
2919 av_strlcpy(authorization, p,
2920 FFMIN(authorization_size, at + 1 - p));
2921 p = at + 1; /* skip '@' */
a9a721da 2922 }
7e1e297e 2923
f8f88a42
RB
2924 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
2925 /* [host]:port */
2926 av_strlcpy(hostname, p + 1,
2927 FFMIN(hostname_size, brk - p));
2928 if (brk[1] == ':' && port_ptr)
2929 *port_ptr = atoi(brk + 2);
2930 } else if ((col = strchr(p, ':')) && col < ls) {
2931 av_strlcpy(hostname, p,
2932 FFMIN(col + 1 - p, hostname_size));
50ecf157
DB
2933 if (port_ptr)
2934 *port_ptr = atoi(col + 1);
f8f88a42
RB
2935 } else
2936 av_strlcpy(hostname, p,
2937 FFMIN(ls + 1 - p, hostname_size));
a9a721da 2938 }
a9a721da
FB
2939}
2940
ddbeb954 2941char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
f1c80e35
RB
2942{
2943 int i;
ddbeb954 2944 static const char hex_table_uc[16] = { '0', '1', '2', '3',
d8f92957
MS
2945 '4', '5', '6', '7',
2946 '8', '9', 'A', 'B',
2947 'C', 'D', 'E', 'F' };
ddbeb954
MS
2948 static const char hex_table_lc[16] = { '0', '1', '2', '3',
2949 '4', '5', '6', '7',
2950 '8', '9', 'a', 'b',
2951 'c', 'd', 'e', 'f' };
2952 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
f1c80e35 2953
50ecf157 2954 for (i = 0; i < s; i++) {
452d3edb
RB
2955 buff[i * 2] = hex_table[src[i] >> 4];
2956 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
f1c80e35
RB
2957 }
2958
2959 return buff;
2960}
2961
311baee7
MS
2962int ff_hex_to_data(uint8_t *data, const char *p)
2963{
2964 int c, len, v;
2965
2966 len = 0;
50ecf157 2967 v = 1;
311baee7
MS
2968 for (;;) {
2969 p += strspn(p, SPACE_CHARS);
2970 if (*p == '\0')
2971 break;
efa7f420 2972 c = av_toupper((unsigned char) *p++);
311baee7
MS
2973 if (c >= '0' && c <= '9')
2974 c = c - '0';
2975 else if (c >= 'A' && c <= 'F')
2976 c = c - 'A' + 10;
2977 else
2978 break;
2979 v = (v << 4) | c;
2980 if (v & 0x100) {
2981 if (data)
2982 data[len] = v;
2983 len++;
2984 v = 1;
2985 }
2986 }
2987 return len;
2988}
2989
c3f9ebf7
AK
2990void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
2991 unsigned int pts_num, unsigned int pts_den)
2992{
b3190529 2993 AVRational new_tb;
50ecf157
DB
2994 if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
2995 if (new_tb.num != pts_num)
2996 av_log(NULL, AV_LOG_DEBUG,
2997 "st:%d removing common factor %d from timebase\n",
2998 s->index, pts_num / new_tb.num);
2999 } else
3000 av_log(NULL, AV_LOG_WARNING,
3001 "st:%d has too large timebase, reducing\n", s->index);
3002
3003 if (new_tb.num <= 0 || new_tb.den <= 0) {
3004 av_log(NULL, AV_LOG_ERROR,
3005 "Ignoring attempt to set invalid timebase for st:%d\n",
3006 s->index);
b3190529
RD
3007 return;
3008 }
50ecf157 3009 s->time_base = new_tb;
b3190529 3010 s->pts_wrap_bits = pts_wrap_bits;
916c80e9 3011}
780d7897 3012
f9c399c4
MS
3013void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3014 void *context)
3015{
3016 const char *ptr = str;
3017
3018 /* Parse key=value pairs. */
3019 for (;;) {
3020 const char *key;
3021 char *dest = NULL, *dest_end;
3022 int key_len, dest_len = 0;
3023
3024 /* Skip whitespace and potential commas. */
efa7f420 3025 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
f9c399c4
MS
3026 ptr++;
3027 if (!*ptr)
3028 break;
3029
3030 key = ptr;
3031
3032 if (!(ptr = strchr(key, '=')))
3033 break;
3034 ptr++;
3035 key_len = ptr - key;
3036
3037 callback_get_buf(context, key, key_len, &dest, &dest_len);
3038 dest_end = dest + dest_len - 1;
3039
3040 if (*ptr == '\"') {
3041 ptr++;
3042 while (*ptr && *ptr != '\"') {
3043 if (*ptr == '\\') {
3044 if (!ptr[1])
3045 break;
3046 if (dest && dest < dest_end)
3047 *dest++ = ptr[1];
3048 ptr += 2;
3049 } else {
3050 if (dest && dest < dest_end)
3051 *dest++ = *ptr;
3052 ptr++;
3053 }
3054 }
3055 if (*ptr == '\"')
3056 ptr++;
3057 } else {
efa7f420 3058 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
f9c399c4
MS
3059 if (dest && dest < dest_end)
3060 *dest++ = *ptr;
3061 }
3062 if (dest)
3063 *dest = 0;
3064 }
3065}
3066
141de5a9
PR
3067int ff_find_stream_index(AVFormatContext *s, int id)
3068{
3069 int i;
50ecf157 3070 for (i = 0; i < s->nb_streams; i++)
141de5a9
PR
3071 if (s->streams[i]->id == id)
3072 return i;
141de5a9
PR
3073 return -1;
3074}
f1f60f52 3075
001d668d
AK
3076int64_t ff_iso8601_to_unix_time(const char *datestr)
3077{
50ecf157 3078 struct tm time1 = { 0 }, time2 = { 0 };
98cab397 3079 const char *ret1, *ret2;
27f27462
LB
3080 ret1 = av_small_strptime(datestr, "%Y - %m - %d %T", &time1);
3081 ret2 = av_small_strptime(datestr, "%Y - %m - %dT%T", &time2);
18579f08
MS
3082 if (ret2 && !ret1)
3083 return av_timegm(&time2);
3084 else
3085 return av_timegm(&time1);
001d668d 3086}
48f9e457 3087
7215fcf8 3088int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
50ecf157 3089 int std_compliance)
48f9e457
AK