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