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