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