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