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