Fix timestamps and durations if the first packets have no durations nor timestamps,
[libav.git] / libavformat / utils.c
CommitLineData
de6d9b64 1/*
a85736f2 2 * various utility functions for use within FFmpeg
19720f15 3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
de6d9b64 4 *
b78e7197
DB
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg 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 *
b78e7197 12 * FFmpeg 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
b78e7197 18 * License along with FFmpeg; if not, write to the Free Software
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
de6d9b64 20 */
8be1c656 21#include "avformat.h"
4eb72c6b 22#include "opt.h"
75e61b0e 23#include "avstring.h"
45da8124 24#include "riff.h"
82e4ac2c
RP
25#include <sys/time.h>
26#include <time.h>
c5510dd6 27
b754978a
MN
28#undef NDEBUG
29#include <assert.h>
30
e36bdf8b
DK
31/**
32 * @file libavformat/utils.c
a85736f2 33 * various utility functions for use within FFmpeg
e36bdf8b
DK
34 */
35
f3a30e3a
LB
36static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
37static void av_frac_add(AVFrac *f, int64_t incr);
f3a30e3a 38
a85736f2 39/** head of registered input format linked list */
8b69867f 40AVInputFormat *first_iformat = NULL;
a85736f2 41/** head of registered output format linked list */
8b69867f 42AVOutputFormat *first_oformat = NULL;
de6d9b64 43
84be6e72
MN
44AVInputFormat *av_iformat_next(AVInputFormat *f)
45{
46 if(f) return f->next;
47 else return first_iformat;
48}
49
50AVOutputFormat *av_oformat_next(AVOutputFormat *f)
51{
52 if(f) return f->next;
53 else return first_oformat;
54}
55
b9a281db 56void av_register_input_format(AVInputFormat *format)
de6d9b64 57{
b9a281db
FB
58 AVInputFormat **p;
59 p = &first_iformat;
60 while (*p != NULL) p = &(*p)->next;
61 *p = format;
62 format->next = NULL;
63}
64
65void av_register_output_format(AVOutputFormat *format)
66{
67 AVOutputFormat **p;
68 p = &first_oformat;
de6d9b64
FB
69 while (*p != NULL) p = &(*p)->next;
70 *p = format;
71 format->next = NULL;
72}
73
5b25dfa7 74int match_ext(const char *filename, const char *extensions)
de6d9b64
FB
75{
76 const char *ext, *p;
77 char ext1[32], *q;
78
293ed23f
MN
79 if(!filename)
80 return 0;
115329f1 81
de6d9b64
FB
82 ext = strrchr(filename, '.');
83 if (ext) {
84 ext++;
85 p = extensions;
86 for(;;) {
87 q = ext1;
115329f1 88 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
de6d9b64
FB
89 *q++ = *p++;
90 *q = '\0';
115329f1 91 if (!strcasecmp(ext1, ext))
de6d9b64 92 return 1;
115329f1 93 if (*p == '\0')
de6d9b64
FB
94 break;
95 p++;
96 }
97 }
98 return 0;
99}
100
115329f1 101AVOutputFormat *guess_format(const char *short_name, const char *filename,
b9a281db 102 const char *mime_type)
de6d9b64 103{
b9a281db 104 AVOutputFormat *fmt, *fmt_found;
de6d9b64
FB
105 int score_max, score;
106
87a0a681 107 /* specific test for image sequences */
ff70e601 108#ifdef CONFIG_IMAGE2_MUXER
115329f1 109 if (!short_name && filename &&
5c07cf53 110 av_filename_number_test(filename) &&
5b6d5596
MN
111 av_guess_image2_codec(filename) != CODEC_ID_NONE) {
112 return guess_format("image2", NULL, NULL);
113 }
ff70e601 114#endif
a85736f2 115 /* Find the proper file type. */
de6d9b64
FB
116 fmt_found = NULL;
117 score_max = 0;
b9a281db 118 fmt = first_oformat;
de6d9b64
FB
119 while (fmt != NULL) {
120 score = 0;
121 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
122 score += 100;
123 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
124 score += 10;
115329f1 125 if (filename && fmt->extensions &&
de6d9b64
FB
126 match_ext(filename, fmt->extensions)) {
127 score += 5;
128 }
129 if (score > score_max) {
130 score_max = score;
131 fmt_found = fmt;
132 }
133 fmt = fmt->next;
134 }
135 return fmt_found;
115329f1 136}
de6d9b64 137
115329f1 138AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
c5510dd6
PG
139 const char *mime_type)
140{
141 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
142
143 if (fmt) {
144 AVOutputFormat *stream_fmt;
145 char stream_format_name[64];
146
147 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
148 stream_fmt = guess_format(stream_format_name, NULL, NULL);
149
150 if (stream_fmt)
151 fmt = stream_fmt;
152 }
153
154 return fmt;
155}
156
115329f1 157enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
5b6d5596
MN
158 const char *filename, const char *mime_type, enum CodecType type){
159 if(type == CODEC_TYPE_VIDEO){
160 enum CodecID codec_id= CODEC_ID_NONE;
161
ff70e601 162#ifdef CONFIG_IMAGE2_MUXER
ae214ac3 163 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
5b6d5596
MN
164 codec_id= av_guess_image2_codec(filename);
165 }
ff70e601 166#endif
5b6d5596
MN
167 if(codec_id == CODEC_ID_NONE)
168 codec_id= fmt->video_codec;
169 return codec_id;
170 }else if(type == CODEC_TYPE_AUDIO)
171 return fmt->audio_codec;
172 else
173 return CODEC_ID_NONE;
174}
175
b9a281db
FB
176AVInputFormat *av_find_input_format(const char *short_name)
177{
178 AVInputFormat *fmt;
179 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
180 if (!strcmp(fmt->name, short_name))
181 return fmt;
182 }
183 return NULL;
184}
185
de6d9b64
FB
186/* memory handling */
187
90ad92b3 188void av_destruct_packet(AVPacket *pkt)
6fa5a56c
FB
189{
190 av_free(pkt->data);
191 pkt->data = NULL; pkt->size = 0;
192}
193
659596f0
RP
194void av_init_packet(AVPacket *pkt)
195{
196 pkt->pts = AV_NOPTS_VALUE;
197 pkt->dts = AV_NOPTS_VALUE;
198 pkt->pos = -1;
199 pkt->duration = 0;
200 pkt->flags = 0;
201 pkt->stream_index = 0;
202 pkt->destruct= av_destruct_packet_nofree;
203}
204
de6d9b64
FB
205int av_new_packet(AVPacket *pkt, int size)
206{
55bdd34d 207 uint8_t *data;
568e18b1 208 if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
769e10f0 209 return AVERROR(ENOMEM);
568e18b1 210 data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
6fa5a56c 211 if (!data)
769e10f0 212 return AVERROR(ENOMEM);
6fa5a56c 213 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
8cd5be98 214
6fa5a56c 215 av_init_packet(pkt);
115329f1 216 pkt->data = data;
6fa5a56c
FB
217 pkt->size = size;
218 pkt->destruct = av_destruct_packet;
de6d9b64
FB
219 return 0;
220}
221
2692067a
MN
222int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
223{
224 int ret= av_new_packet(pkt, size);
225
226 if(ret<0)
227 return ret;
228
229 pkt->pos= url_ftell(s);
230
231 ret= get_buffer(s, pkt->data, size);
232 if(ret<=0)
233 av_free_packet(pkt);
234 else
235 pkt->size= ret;
236
237 return ret;
238}
239
fb2758c8
FB
240int av_dup_packet(AVPacket *pkt)
241{
242 if (pkt->destruct != av_destruct_packet) {
243 uint8_t *data;
a85736f2 244 /* We duplicate the packet and don't forget to add the padding again. */
568e18b1 245 if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
769e10f0 246 return AVERROR(ENOMEM);
8a56ac7b 247 data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
fb2758c8 248 if (!data) {
769e10f0 249 return AVERROR(ENOMEM);
fb2758c8
FB
250 }
251 memcpy(data, pkt->data, pkt->size);
8a56ac7b 252 memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
fb2758c8
FB
253 pkt->data = data;
254 pkt->destruct = av_destruct_packet;
255 }
256 return 0;
257}
258
5c07cf53 259int av_filename_number_test(const char *filename)
b9a281db
FB
260{
261 char buf[1024];
5c07cf53 262 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
b9a281db
FB
263}
264
79750486 265static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
b9a281db
FB
266{
267 AVInputFormat *fmt1, *fmt;
79750486 268 int score;
b9a281db
FB
269
270 fmt = NULL;
b9a281db 271 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
b8e705ec 272 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
b9a281db
FB
273 continue;
274 score = 0;
a8dbe951
PG
275 if (fmt1->read_probe) {
276 score = fmt1->read_probe(pd);
277 } else if (fmt1->extensions) {
b9a281db
FB
278 if (match_ext(pd->filename, fmt1->extensions)) {
279 score = 50;
280 }
115329f1 281 }
79750486
MN
282 if (score > *score_max) {
283 *score_max = score;
b9a281db
FB
284 fmt = fmt1;
285 }
286 }
287 return fmt;
288}
289
79750486
MN
290AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
291 int score=0;
292 return av_probe_input_format2(pd, is_opened, &score);
293}
294
b9a281db
FB
295/************************************************************/
296/* input media file */
96baaa6a 297
da24c5e3 298/**
e36bdf8b 299 * Open a media file from an IO stream. 'fmt' must be specified.
da24c5e3 300 */
43465395 301static const char* format_to_name(void* ptr)
bc874dae 302{
43465395 303 AVFormatContext* fc = (AVFormatContext*) ptr;
bc874dae
MB
304 if(fc->iformat) return fc->iformat->name;
305 else if(fc->oformat) return fc->oformat->name;
306 else return "NULL";
307}
308
66acccf0 309#define OFFSET(x) offsetof(AVFormatContext,x)
755bfeab 310#define DEFAULT 0 //should be NAN but it does not work as it is not a constant in glibc as required by ANSI/ISO C
4eb72c6b
NS
311//these names are too long to be readable
312#define E AV_OPT_FLAG_ENCODING_PARAM
313#define D AV_OPT_FLAG_DECODING_PARAM
314
315static const AVOption options[]={
8c3dd5dc 316{"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, 32000, 32, INT_MAX, D}, /* 32000 from mpegts.c: 1.0 second at 24Mbit/s */
09a45576 317{"muxrate", "set mux rate", OFFSET(mux_rate), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
4ff8fcef 318{"packetsize", "set packet size", OFFSET(packet_size), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
18de0b81 319{"fflags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, INT_MIN, INT_MAX, D|E, "fflags"},
2c00106c
MN
320{"ignidx", "ignore index", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNIDX, INT_MIN, INT_MAX, D, "fflags"},
321{"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
8c3dd5dc 322{"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
ec1b10f4 323{"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
e19fbbec 324{"analyzeduration", "how many microseconds are analyzed to estimate duration", OFFSET(max_analyze_duration), FF_OPT_TYPE_INT, 3*AV_TIME_BASE, 0, INT_MAX, D},
841f39a7 325{"cryptokey", "decryption key", OFFSET(key), FF_OPT_TYPE_BINARY, 0, 0, 0, D},
3dea63bd 326{"indexmem", "max memory used for timestamp index (per stream)", OFFSET(max_index_size), FF_OPT_TYPE_INT, INT_MAX, 0, INT_MAX, D},
4eb72c6b
NS
327{NULL},
328};
329
5e89b50b
PI
330#undef E
331#undef D
332#undef DEFAULT
333
4eb72c6b
NS
334static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
335
702dfe01
BC
336static void avformat_get_context_defaults(AVFormatContext *s)
337{
4eb72c6b 338 memset(s, 0, sizeof(AVFormatContext));
9e6c9470 339
73a8ceaa
PI
340 s->av_class = &av_format_context_class;
341
342 av_opt_set_defaults(s);
4eb72c6b 343}
bc874dae
MB
344
345AVFormatContext *av_alloc_format_context(void)
346{
347 AVFormatContext *ic;
5894991f 348 ic = av_malloc(sizeof(AVFormatContext));
bc874dae 349 if (!ic) return ic;
4eb72c6b 350 avformat_get_context_defaults(ic);
43465395 351 ic->av_class = &av_format_context_class;
bc874dae
MB
352 return ic;
353}
354
115329f1
DB
355int av_open_input_stream(AVFormatContext **ic_ptr,
356 ByteIOContext *pb, const char *filename,
da24c5e3
FB
357 AVInputFormat *fmt, AVFormatParameters *ap)
358{
359 int err;
360 AVFormatContext *ic;
c04c3282
MN
361 AVFormatParameters default_ap;
362
363 if(!ap){
364 ap=&default_ap;
365 memset(ap, 0, sizeof(default_ap));
366 }
da24c5e3 367
4eb72c6b
NS
368 if(!ap->prealloced_context)
369 ic = av_alloc_format_context();
370 else
371 ic = *ic_ptr;
da24c5e3 372 if (!ic) {
769e10f0 373 err = AVERROR(ENOMEM);
da24c5e3
FB
374 goto fail;
375 }
376 ic->iformat = fmt;
899681cd 377 ic->pb = pb;
da24c5e3
FB
378 ic->duration = AV_NOPTS_VALUE;
379 ic->start_time = AV_NOPTS_VALUE;
75e61b0e 380 av_strlcpy(ic->filename, filename, sizeof(ic->filename));
da24c5e3
FB
381
382 /* allocate private data */
383 if (fmt->priv_data_size > 0) {
384 ic->priv_data = av_mallocz(fmt->priv_data_size);
385 if (!ic->priv_data) {
769e10f0 386 err = AVERROR(ENOMEM);
da24c5e3
FB
387 goto fail;
388 }
389 } else {
390 ic->priv_data = NULL;
391 }
392
da24c5e3
FB
393 err = ic->iformat->read_header(ic, ap);
394 if (err < 0)
395 goto fail;
fb2758c8 396
faf7cbf1 397 if (pb && !ic->data_offset)
899681cd 398 ic->data_offset = url_ftell(ic->pb);
fb2758c8 399
da24c5e3
FB
400 *ic_ptr = ic;
401 return 0;
402 fail:
403 if (ic) {
404 av_freep(&ic->priv_data);
405 }
406 av_free(ic);
407 *ic_ptr = NULL;
408 return err;
409}
410
a85736f2 411/** size of probe buffer, for guessing file type from file contents */
a877eedc 412#define PROBE_BUF_MIN 2048
329b1e75 413#define PROBE_BUF_MAX (1<<20)
b9a281db 414
115329f1 415int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
b9a281db
FB
416 AVInputFormat *fmt,
417 int buf_size,
418 AVFormatParameters *ap)
de6d9b64 419{
17acc63a 420 int err, probe_size;
b9a281db 421 AVProbeData probe_data, *pd = &probe_data;
17acc63a 422 ByteIOContext *pb = NULL;
115329f1 423
da24c5e3
FB
424 pd->filename = "";
425 if (filename)
426 pd->filename = filename;
a877eedc 427 pd->buf = NULL;
b9a281db
FB
428 pd->buf_size = 0;
429
430 if (!fmt) {
a85736f2 431 /* guess format if no file can be opened */
a25e098d 432 fmt = av_probe_input_format(pd, 0);
de6d9b64 433 }
de6d9b64 434
a85736f2 435 /* Do not open file if the format does not need it. XXX: specific
b6892136 436 hack needed to handle RTSP/TCP */
17acc63a 437 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
87a0a681 438 /* if no file needed do not try to open one */
899681cd 439 if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
96baaa6a 440 goto fail;
b9a281db 441 }
96baaa6a 442 if (buf_size > 0) {
da24c5e3 443 url_setbufsize(pb, buf_size);
96baaa6a 444 }
a877eedc
MN
445
446 for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
79750486 447 int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
5b25dfa7 448 /* read probe data */
87e87886 449 pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
a877eedc 450 pd->buf_size = get_buffer(pb, pd->buf, probe_size);
9be51815 451 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
497244a8 452 if (url_fseek(pb, 0, SEEK_SET) < 0) {
53e2f9ca 453 url_fclose(pb);
899681cd 454 if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
17acc63a 455 pb = NULL;
6f3e0b21 456 err = AVERROR(EIO);
53e2f9ca
MN
457 goto fail;
458 }
459 }
a877eedc 460 /* guess file format */
79750486 461 fmt = av_probe_input_format2(pd, 1, &score);
5b25dfa7 462 }
a877eedc 463 av_freep(&pd->buf);
b9a281db
FB
464 }
465
466 /* if still no format found, error */
467 if (!fmt) {
468 err = AVERROR_NOFMT;
da24c5e3 469 goto fail;
de6d9b64 470 }
115329f1 471
a85736f2 472 /* check filename in case an image number is expected */
da24c5e3 473 if (fmt->flags & AVFMT_NEEDNUMBER) {
5c07cf53 474 if (!av_filename_number_test(filename)) {
87a0a681 475 err = AVERROR_NUMEXPECTED;
da24c5e3 476 goto fail;
87a0a681
FB
477 }
478 }
da24c5e3
FB
479 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
480 if (err)
481 goto fail;
b9a281db 482 return 0;
de6d9b64 483 fail:
a877eedc 484 av_freep(&pd->buf);
17acc63a 485 if (pb)
da24c5e3 486 url_fclose(pb);
b9a281db
FB
487 *ic_ptr = NULL;
488 return err;
115329f1 489
de6d9b64
FB
490}
491
da24c5e3
FB
492/*******************************************************/
493
de6d9b64
FB
494int av_read_packet(AVFormatContext *s, AVPacket *pkt)
495{
62600469
MN
496 int ret;
497 AVStream *st;
b237eb80 498 av_init_packet(pkt);
62600469 499 ret= s->iformat->read_packet(s, pkt);
88b00723
RD
500 if (ret < 0)
501 return ret;
62600469
MN
502 st= s->streams[pkt->stream_index];
503
504 switch(st->codec->codec_type){
505 case CODEC_TYPE_VIDEO:
506 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
507 break;
508 case CODEC_TYPE_AUDIO:
509 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
510 break;
511 case CODEC_TYPE_SUBTITLE:
512 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
513 break;
514 }
515
516 return ret;
fb2758c8
FB
517}
518
519/**********************************************************/
520
e36bdf8b 521/**
a85736f2 522 * Get the number of samples of an audio frame. Return -1 on error.
e36bdf8b 523 */
fb2758c8
FB
524static int get_audio_frame_size(AVCodecContext *enc, int size)
525{
526 int frame_size;
527
528 if (enc->frame_size <= 1) {
ac3e1834
BC
529 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
530
531 if (bits_per_sample) {
fb2758c8
FB
532 if (enc->channels == 0)
533 return -1;
f1b163e0 534 frame_size = (size << 3) / (bits_per_sample * enc->channels);
ac3e1834 535 } else {
fb2758c8
FB
536 /* used for example by ADPCM codecs */
537 if (enc->bit_rate == 0)
538 return -1;
539 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
fb2758c8
FB
540 }
541 } else {
542 frame_size = enc->frame_size;
543 }
544 return frame_size;
545}
546
547
e36bdf8b 548/**
a85736f2 549 * Return the frame duration in seconds. Return 0 if not available.
e36bdf8b 550 */
115329f1 551static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
fb2758c8
FB
552 AVCodecParserContext *pc, AVPacket *pkt)
553{
554 int frame_size;
555
556 *pnum = 0;
557 *pden = 0;
01f4895c 558 switch(st->codec->codec_type) {
fb2758c8 559 case CODEC_TYPE_VIDEO:
1677155d 560 if(st->time_base.num*1000LL > st->time_base.den){
c0df9d75
MN
561 *pnum = st->time_base.num;
562 *pden = st->time_base.den;
01f4895c
MN
563 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
564 *pnum = st->codec->time_base.num;
565 *pden = st->codec->time_base.den;
327c4076
MN
566 if (pc && pc->repeat_pict) {
567 *pden *= 2;
568 *pnum = (*pnum) * (2 + pc->repeat_pict);
569 }
fb2758c8
FB
570 }
571 break;
572 case CODEC_TYPE_AUDIO:
01f4895c 573 frame_size = get_audio_frame_size(st->codec, pkt->size);
fb2758c8
FB
574 if (frame_size < 0)
575 break;
576 *pnum = frame_size;
01f4895c 577 *pden = st->codec->sample_rate;
fb2758c8
FB
578 break;
579 default:
580 break;
581 }
582}
583
5ba7c3d7
MN
584static int is_intra_only(AVCodecContext *enc){
585 if(enc->codec_type == CODEC_TYPE_AUDIO){
586 return 1;
587 }else if(enc->codec_type == CODEC_TYPE_VIDEO){
588 switch(enc->codec_id){
589 case CODEC_ID_MJPEG:
590 case CODEC_ID_MJPEGB:
591 case CODEC_ID_LJPEG:
592 case CODEC_ID_RAWVIDEO:
593 case CODEC_ID_DVVIDEO:
594 case CODEC_ID_HUFFYUV:
f37b9768 595 case CODEC_ID_FFVHUFF:
5ba7c3d7
MN
596 case CODEC_ID_ASV1:
597 case CODEC_ID_ASV2:
598 case CODEC_ID_VCR1:
599 return 1;
600 default: break;
601 }
602 }
603 return 0;
604}
605
9fcbcca6
NB
606static void update_initial_timestamps(AVFormatContext *s, int stream_index,
607 int64_t dts, int64_t pts)
608{
82583548
MN
609 AVStream *st= s->streams[stream_index];
610 AVPacketList *pktl= s->packet_buffer;
611
612 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE)
613 return;
614
615 st->first_dts= dts - st->cur_dts;
616 st->cur_dts= dts;
617
618 for(; pktl; pktl= pktl->next){
619 if(pktl->pkt.stream_index != stream_index)
620 continue;
621 //FIXME think more about this check
622 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
623 pktl->pkt.pts += st->first_dts;
624
625 if(pktl->pkt.dts != AV_NOPTS_VALUE)
626 pktl->pkt.dts += st->first_dts;
48a59dfe
MN
627
628 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
629 st->start_time= pktl->pkt.pts;
82583548 630 }
9fcbcca6
NB
631 if (st->start_time == AV_NOPTS_VALUE)
632 st->start_time = pts;
82583548
MN
633}
634
83a9db42
MN
635static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
636{
637 AVPacketList *pktl= s->packet_buffer;
638
639 assert(pkt->duration && !st->cur_dts);
640
641 for(; pktl; pktl= pktl->next){
642 if(pktl->pkt.stream_index != pkt->stream_index)
643 continue;
644 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE){
645 pktl->pkt.pts= pktl->pkt.dts= st->cur_dts;
646 st->cur_dts += pkt->duration;
647 pktl->pkt.duration= pkt->duration;
648 }else
649 break;
650 }
651}
652
115329f1 653static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
fb2758c8
FB
654 AVCodecParserContext *pc, AVPacket *pkt)
655{
d9e1efb7 656 int num, den, presentation_delayed, delay, i;
a74008a4 657 int64_t offset;
115329f1 658
10a7571b
MN
659 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
660 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
661 pkt->dts -= 1LL<<st->pts_wrap_bits;
662 }
663
fb2758c8 664 if (pkt->duration == 0) {
3c895fc0 665 compute_frame_duration(&num, &den, st, pc, pkt);
fb2758c8 666 if (den && num) {
77405fc8 667 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
83a9db42
MN
668
669 if(pkt->dts == AV_NOPTS_VALUE && pkt->pts == AV_NOPTS_VALUE && st->cur_dts == 0)
670 update_initial_durations(s, st, pkt);
fb2758c8
FB
671 }
672 }
673
a85736f2
DB
674 /* correct timestamps with byte offset if demuxers only have timestamps
675 on packet boundaries */
a74008a4
JP
676 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
677 /* this will estimate bitrate based on this frame's duration and size */
678 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
679 if(pkt->pts != AV_NOPTS_VALUE)
680 pkt->pts += offset;
681 if(pkt->dts != AV_NOPTS_VALUE)
682 pkt->dts += offset;
683 }
684
a85736f2 685 /* do we have a video B-frame ? */
befe3b05 686 delay= st->codec->has_b_frames;
fb2758c8 687 presentation_delayed = 0;
7e4baa66
MN
688 /* XXX: need has_b_frame, but cannot get it if the codec is
689 not initialized */
690 if (delay &&
691 pc && pc->pict_type != FF_B_TYPE)
692 presentation_delayed = 1;
755bfeab 693 /* This may be redundant, but it should not hurt. */
7e4baa66
MN
694 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
695 presentation_delayed = 1;
115329f1 696
e928649b 697 if(st->cur_dts == AV_NOPTS_VALUE){
82583548 698 st->cur_dts = 0; //FIXME maybe set it to 0 during init
e928649b 699 }
fb2758c8 700
949b1a13 701// av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
fb2758c8 702 /* interpolate PTS and DTS if they are not present */
7e4baa66
MN
703 if(delay <=1){
704 if (presentation_delayed) {
a85736f2
DB
705 /* DTS = decompression timestamp */
706 /* PTS = presentation timestamp */
7e4baa66
MN
707 if (pkt->dts == AV_NOPTS_VALUE)
708 pkt->dts = st->last_IP_pts;
9fcbcca6 709 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
7e4baa66
MN
710 if (pkt->dts == AV_NOPTS_VALUE)
711 pkt->dts = st->cur_dts;
712
713 /* this is tricky: the dts must be incremented by the duration
a85736f2 714 of the frame we are displaying, i.e. the last I- or P-frame */
7e4baa66
MN
715 if (st->last_IP_duration == 0)
716 st->last_IP_duration = pkt->duration;
717 st->cur_dts = pkt->dts + st->last_IP_duration;
718 st->last_IP_duration = pkt->duration;
719 st->last_IP_pts= pkt->pts;
720 /* cannot compute PTS if not present (we can compute it only
a85736f2 721 by knowing the future */
028d6f3e 722 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
7e4baa66
MN
723 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
724 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
725 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
726 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
727 pkt->pts += pkt->duration;
728 // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
729 }
90bb394d 730 }
115329f1 731
7e4baa66
MN
732 /* presentation is not delayed : PTS and DTS are the same */
733 if(pkt->pts == AV_NOPTS_VALUE)
734 pkt->pts = pkt->dts;
9fcbcca6 735 update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
7e4baa66
MN
736 if(pkt->pts == AV_NOPTS_VALUE)
737 pkt->pts = st->cur_dts;
738 pkt->dts = pkt->pts;
739 st->cur_dts = pkt->pts + pkt->duration;
740 }
fb2758c8 741 }
d9e1efb7
MN
742
743 if(pkt->pts != AV_NOPTS_VALUE){
744 st->pts_buffer[0]= pkt->pts;
745 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
746 st->pts_buffer[i]= (i-delay-1) * pkt->duration;
747 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
748 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
749 if(pkt->dts == AV_NOPTS_VALUE)
750 pkt->dts= st->pts_buffer[0];
82583548 751 if(delay>1){
9fcbcca6 752 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
82583548 753 }
d9e1efb7
MN
754 if(pkt->dts > st->cur_dts)
755 st->cur_dts = pkt->dts;
756 }
757
758// av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
115329f1 759
fb2758c8 760 /* update flags */
3a1d3588
JD
761 if(is_intra_only(st->codec))
762 pkt->flags |= PKT_FLAG_KEY;
763 else if (pc) {
fb2758c8 764 pkt->flags = 0;
a85736f2 765 /* keyframe computation */
fb2758c8
FB
766 if (pc->pict_type == FF_I_TYPE)
767 pkt->flags |= PKT_FLAG_KEY;
fb2758c8 768 }
fb2758c8
FB
769}
770
63dd1377 771void av_destruct_packet_nofree(AVPacket *pkt)
fb2758c8
FB
772{
773 pkt->data = NULL; pkt->size = 0;
774}
775
776static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
777{
778 AVStream *st;
37353960 779 int len, ret, i;
fb2758c8 780
b237eb80
MN
781 av_init_packet(pkt);
782
fb2758c8
FB
783 for(;;) {
784 /* select current input stream component */
785 st = s->cur_st;
786 if (st) {
90ad92b3 787 if (!st->need_parsing || !st->parser) {
fb2758c8
FB
788 /* no parsing needed: we just output the packet as is */
789 /* raw data support */
790 *pkt = s->cur_pkt;
791 compute_pkt_fields(s, st, NULL, pkt);
792 s->cur_st = NULL;
434cab9e 793 break;
f3356e9c 794 } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
115329f1 795 len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
6ec87caa
FB
796 s->cur_ptr, s->cur_len,
797 s->cur_pkt.pts, s->cur_pkt.dts);
798 s->cur_pkt.pts = AV_NOPTS_VALUE;
799 s->cur_pkt.dts = AV_NOPTS_VALUE;
fb2758c8
FB
800 /* increment read pointer */
801 s->cur_ptr += len;
802 s->cur_len -= len;
115329f1 803
fb2758c8
FB
804 /* return packet if any */
805 if (pkt->size) {
37353960 806 got_packet:
711737af 807 pkt->pos = s->cur_pkt.pos; // Isn't quite accurate but close.
fb2758c8
FB
808 pkt->duration = 0;
809 pkt->stream_index = st->index;
6ec87caa
FB
810 pkt->pts = st->parser->pts;
811 pkt->dts = st->parser->dts;
fb2758c8
FB
812 pkt->destruct = av_destruct_packet_nofree;
813 compute_pkt_fields(s, st, st->parser, pkt);
e9b78eeb
MN
814
815 if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
3dea63bd 816 ff_reduce_index(s, st->index);
e9b78eeb
MN
817 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
818 0, 0, AVINDEX_KEYFRAME);
819 }
820
434cab9e 821 break;
fb2758c8
FB
822 }
823 } else {
bcbecff1 824 /* free packet */
115329f1 825 av_free_packet(&s->cur_pkt);
fb2758c8
FB
826 s->cur_st = NULL;
827 }
828 } else {
fb2758c8
FB
829 /* read next packet */
830 ret = av_read_packet(s, &s->cur_pkt);
37353960 831 if (ret < 0) {
8fa36ae0 832 if (ret == AVERROR(EAGAIN))
37353960
FB
833 return ret;
834 /* return the last frames, if any */
835 for(i = 0; i < s->nb_streams; i++) {
836 st = s->streams[i];
90ad92b3 837 if (st->parser && st->need_parsing) {
115329f1
DB
838 av_parser_parse(st->parser, st->codec,
839 &pkt->data, &pkt->size,
840 NULL, 0,
6ec87caa 841 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
37353960
FB
842 if (pkt->size)
843 goto got_packet;
844 }
845 }
a85736f2 846 /* no more packets: really terminate parsing */
fb2758c8 847 return ret;
37353960 848 }
115329f1 849
9ee91c2f 850 st = s->streams[s->cur_pkt.stream_index];
434cab9e 851 if(st->codec->debug & FF_DEBUG_PTS)
ccd3228e 852 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
434cab9e
MN
853 s->cur_pkt.stream_index,
854 s->cur_pkt.pts,
855 s->cur_pkt.dts,
856 s->cur_pkt.size);
fb2758c8 857
fb2758c8
FB
858 s->cur_st = st;
859 s->cur_ptr = s->cur_pkt.data;
860 s->cur_len = s->cur_pkt.size;
861 if (st->need_parsing && !st->parser) {
01f4895c 862 st->parser = av_parser_init(st->codec->codec_id);
fb2758c8 863 if (!st->parser) {
a85736f2 864 /* no parser available: just output the raw packets */
57004ff1
AJ
865 st->need_parsing = AVSTREAM_PARSE_NONE;
866 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
7cbaa7ba 867 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
fb2758c8 868 }
e9b78eeb
MN
869 if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
870 st->parser->last_frame_offset=
871 st->parser->cur_offset= s->cur_pkt.pos;
872 }
fb2758c8
FB
873 }
874 }
875 }
434cab9e 876 if(st->codec->debug & FF_DEBUG_PTS)
ccd3228e 877 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
434cab9e
MN
878 pkt->stream_index,
879 pkt->pts,
880 pkt->dts,
881 pkt->size);
882
883 return 0;
fb2758c8
FB
884}
885
02b15cc8
MN
886static AVPacket *add_to_pktbuf(AVFormatContext *s, AVPacket *pkt){
887 AVPacketList *pktl= s->packet_buffer;
888 AVPacketList **plast_pktl= &s->packet_buffer;
889
890 while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
891
892 pktl = av_mallocz(sizeof(AVPacketList));
893 if (!pktl)
894 return NULL;
895
896 /* add the packet in the buffered packet list */
897 *plast_pktl = pktl;
898 pktl->pkt= *pkt;
899 return &pktl->pkt;
900}
901
fb2758c8
FB
902int av_read_frame(AVFormatContext *s, AVPacket *pkt)
903{
de6d9b64 904 AVPacketList *pktl;
30bc6613
MN
905 int eof=0;
906 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
907
908 for(;;){
909 pktl = s->packet_buffer;
910 if (pktl) {
911 AVPacket *next_pkt= &pktl->pkt;
30bc6613
MN
912
913 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
914 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
115329f1 915 if( pktl->pkt.stream_index == next_pkt->stream_index
30bc6613
MN
916 && next_pkt->dts < pktl->pkt.dts
917 && pktl->pkt.pts != pktl->pkt.dts //not b frame
918 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
919 next_pkt->pts= pktl->pkt.dts;
920 }
921 pktl= pktl->next;
922 }
923 pktl = s->packet_buffer;
924 }
115329f1
DB
925
926 if( next_pkt->pts != AV_NOPTS_VALUE
927 || next_pkt->dts == AV_NOPTS_VALUE
30bc6613
MN
928 || !genpts || eof){
929 /* read packet from packet buffer, if there is data */
930 *pkt = *next_pkt;
931 s->packet_buffer = pktl->next;
932 av_free(pktl);
933 return 0;
934 }
935 }
936 if(genpts){
30bc6613
MN
937 int ret= av_read_frame_internal(s, pkt);
938 if(ret<0){
8fa36ae0 939 if(pktl && ret != AVERROR(EAGAIN)){
30bc6613
MN
940 eof=1;
941 continue;
942 }else
943 return ret;
944 }
115329f1 945
02b15cc8 946 if(av_dup_packet(add_to_pktbuf(s, pkt)) < 0)
769e10f0 947 return AVERROR(ENOMEM);
30bc6613
MN
948 }else{
949 assert(!s->packet_buffer);
950 return av_read_frame_internal(s, pkt);
951 }
fb2758c8
FB
952 }
953}
954
955/* XXX: suppress the packet queue */
956static void flush_packet_queue(AVFormatContext *s)
957{
958 AVPacketList *pktl;
959
960 for(;;) {
961 pktl = s->packet_buffer;
115329f1 962 if (!pktl)
fb2758c8
FB
963 break;
964 s->packet_buffer = pktl->next;
965 av_free_packet(&pktl->pkt);
966 av_free(pktl);
b9a281db
FB
967 }
968}
969
da24c5e3 970/*******************************************************/
fb2758c8
FB
971/* seek support */
972
b754978a
MN
973int av_find_default_stream_index(AVFormatContext *s)
974{
975 int i;
976 AVStream *st;
977
978 if (s->nb_streams <= 0)
979 return -1;
980 for(i = 0; i < s->nb_streams; i++) {
981 st = s->streams[i];
01f4895c 982 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
b754978a
MN
983 return i;
984 }
985 }
986 return 0;
987}
988
e36bdf8b
DK
989/**
990 * Flush the frame reader.
991 */
fb2758c8
FB
992static void av_read_frame_flush(AVFormatContext *s)
993{
994 AVStream *st;
995 int i;
996
997 flush_packet_queue(s);
998
999 /* free previous packet */
1000 if (s->cur_st) {
1001 if (s->cur_st->parser)
1002 av_free_packet(&s->cur_pkt);
1003 s->cur_st = NULL;
1004 }
1005 /* fail safe */
1006 s->cur_ptr = NULL;
1007 s->cur_len = 0;
115329f1 1008
fb2758c8
FB
1009 /* for each stream, reset read state */
1010 for(i = 0; i < s->nb_streams; i++) {
1011 st = s->streams[i];
115329f1 1012
fb2758c8
FB
1013 if (st->parser) {
1014 av_parser_close(st->parser);
1015 st->parser = NULL;
1016 }
77405fc8 1017 st->last_IP_pts = AV_NOPTS_VALUE;
a843d1ff 1018 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
fb2758c8
FB
1019 }
1020}
1021
22ffac70 1022void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
8bcb147f
MN
1023 int i;
1024
1025 for(i = 0; i < s->nb_streams; i++) {
1a1dc611 1026 AVStream *st = s->streams[i];
8bcb147f 1027
115329f1 1028 st->cur_dts = av_rescale(timestamp,
1a1dc611
NK
1029 st->time_base.den * (int64_t)ref_st->time_base.num,
1030 st->time_base.num * (int64_t)ref_st->time_base.den);
8bcb147f
MN
1031 }
1032}
1033
3dea63bd
PK
1034void ff_reduce_index(AVFormatContext *s, int stream_index)
1035{
1036 AVStream *st= s->streams[stream_index];
1037 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1038
1039 if((unsigned)st->nb_index_entries >= max_entries){
1040 int i;
1041 for(i=0; 2*i<st->nb_index_entries; i++)
1042 st->index_entries[i]= st->index_entries[2*i];
1043 st->nb_index_entries= i;
1044 }
1045}
1046
3e9245a9 1047int av_add_index_entry(AVStream *st,
30a43f2d 1048 int64_t pos, int64_t timestamp, int size, int distance, int flags)
fb2758c8
FB
1049{
1050 AVIndexEntry *entries, *ie;
b754978a 1051 int index;
115329f1 1052
568e18b1
MN
1053 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1054 return -1;
115329f1 1055
fb2758c8
FB
1056 entries = av_fast_realloc(st->index_entries,
1057 &st->index_entries_allocated_size,
115329f1 1058 (st->nb_index_entries + 1) *
fb2758c8 1059 sizeof(AVIndexEntry));
568e18b1
MN
1060 if(!entries)
1061 return -1;
1062
b754978a
MN
1063 st->index_entries= entries;
1064
27a5fe5f 1065 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
b754978a 1066
3ba1438d 1067 if(index<0){
3e9245a9
MN
1068 index= st->nb_index_entries++;
1069 ie= &entries[index];
3ba1438d
MN
1070 assert(index==0 || ie[-1].timestamp < timestamp);
1071 }else{
1072 ie= &entries[index];
1073 if(ie->timestamp != timestamp){
528c2c73
MN
1074 if(ie->timestamp <= timestamp)
1075 return -1;
3ba1438d
MN
1076 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1077 st->nb_index_entries++;
755bfeab 1078 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
3ba1438d 1079 distance= ie->min_distance;
3e9245a9 1080 }
3ba1438d 1081
b754978a
MN
1082 ie->pos = pos;
1083 ie->timestamp = timestamp;
3e9245a9 1084 ie->min_distance= distance;
30a43f2d 1085 ie->size= size;
b754978a 1086 ie->flags = flags;
115329f1 1087
3e9245a9 1088 return index;
fb2758c8
FB
1089}
1090
dc56fc38 1091int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
27a5fe5f 1092 int flags)
fb2758c8 1093{
b754978a
MN
1094 AVIndexEntry *entries= st->index_entries;
1095 int nb_entries= st->nb_index_entries;
fb2758c8
FB
1096 int a, b, m;
1097 int64_t timestamp;
1098
3ba1438d
MN
1099 a = - 1;
1100 b = nb_entries;
b754978a 1101
3ba1438d
MN
1102 while (b - a > 1) {
1103 m = (a + b) >> 1;
fb2758c8 1104 timestamp = entries[m].timestamp;
3ba1438d
MN
1105 if(timestamp >= wanted_timestamp)
1106 b = m;
1107 if(timestamp <= wanted_timestamp)
b754978a 1108 a = m;
fb2758c8 1109 }
27a5fe5f 1110 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
115329f1 1111
27a5fe5f
MN
1112 if(!(flags & AVSEEK_FLAG_ANY)){
1113 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1114 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1115 }
1116 }
3ba1438d 1117
115329f1 1118 if(m == nb_entries)
3ba1438d
MN
1119 return -1;
1120 return m;
fb2758c8
FB
1121}
1122
0f652a8e 1123#define DEBUG_SEEK
8d14a25c 1124
3ba1438d 1125int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
8d14a25c
MN
1126 AVInputFormat *avif= s->iformat;
1127 int64_t pos_min, pos_max, pos, pos_limit;
1128 int64_t ts_min, ts_max, ts;
89ddd2a9 1129 int index;
8d14a25c
MN
1130 AVStream *st;
1131
cdd5034f
MN
1132 if (stream_index < 0)
1133 return -1;
115329f1 1134
8d14a25c 1135#ifdef DEBUG_SEEK
4733abcb 1136 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
8d14a25c
MN
1137#endif
1138
1139 ts_max=
1140 ts_min= AV_NOPTS_VALUE;
90b5b51e 1141 pos_limit= -1; //gcc falsely says it may be uninitialized
8d14a25c
MN
1142
1143 st= s->streams[stream_index];
1144 if(st->index_entries){
1145 AVIndexEntry *e;
1146
a85736f2 1147 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 1148 index= FFMAX(index, 0);
8d14a25c
MN
1149 e= &st->index_entries[index];
1150
1151 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1152 pos_min= e->pos;
1153 ts_min= e->timestamp;
1154#ifdef DEBUG_SEEK
115329f1 1155 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
8d14a25c
MN
1156 pos_min,ts_min);
1157#endif
1158 }else{
1159 assert(index==0);
1160 }
115329f1
DB
1161
1162 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
27a5fe5f
MN
1163 assert(index < st->nb_index_entries);
1164 if(index >= 0){
8d14a25c
MN
1165 e= &st->index_entries[index];
1166 assert(e->timestamp >= target_ts);
1167 pos_max= e->pos;
1168 ts_max= e->timestamp;
1169 pos_limit= pos_max - e->min_distance;
1170#ifdef DEBUG_SEEK
115329f1 1171 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
8d14a25c
MN
1172 pos_max,pos_limit, ts_max);
1173#endif
1174 }
1175 }
1176
89ddd2a9
MN
1177 pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1178 if(pos<0)
1179 return -1;
1180
1181 /* do the seek */
899681cd 1182 url_fseek(s->pb, pos, SEEK_SET);
89ddd2a9
MN
1183
1184 av_update_cur_dts(s, st, ts);
1185
1186 return 0;
1187}
1188
89ddd2a9
MN
1189int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
1190 int64_t pos, ts;
1191 int64_t start_pos, filesize;
1192 int no_change;
1193
1194#ifdef DEBUG_SEEK
1195 av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1196#endif
1197
8d14a25c
MN
1198 if(ts_min == AV_NOPTS_VALUE){
1199 pos_min = s->data_offset;
89ddd2a9 1200 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
8d14a25c
MN
1201 if (ts_min == AV_NOPTS_VALUE)
1202 return -1;
1203 }
1204
1205 if(ts_max == AV_NOPTS_VALUE){
1206 int step= 1024;
899681cd 1207 filesize = url_fsize(s->pb);
6fd93ce2 1208 pos_max = filesize - 1;
8d14a25c
MN
1209 do{
1210 pos_max -= step;
89ddd2a9 1211 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
8d14a25c
MN
1212 step += step;
1213 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1214 if (ts_max == AV_NOPTS_VALUE)
1215 return -1;
115329f1 1216
8d14a25c
MN
1217 for(;;){
1218 int64_t tmp_pos= pos_max + 1;
89ddd2a9 1219 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
8d14a25c
MN
1220 if(tmp_ts == AV_NOPTS_VALUE)
1221 break;
1222 ts_max= tmp_ts;
1223 pos_max= tmp_pos;
6fd93ce2
KA
1224 if(tmp_pos >= filesize)
1225 break;
8d14a25c
MN
1226 }
1227 pos_limit= pos_max;
1228 }
1229
53f7c43f
MN
1230 if(ts_min > ts_max){
1231 return -1;
1232 }else if(ts_min == ts_max){
1233 pos_limit= pos_min;
1234 }
1235
8d14a25c
MN
1236 no_change=0;
1237 while (pos_min < pos_limit) {
1238#ifdef DEBUG_SEEK
115329f1 1239 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
8d14a25c
MN
1240 pos_min, pos_max,
1241 ts_min, ts_max);
1242#endif
1243 assert(pos_limit <= pos_max);
1244
1245 if(no_change==0){
1246 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1247 // interpolate position (better than dichotomy)
3ba1438d
MN
1248 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1249 + pos_min - approximate_keyframe_distance;
8d14a25c
MN
1250 }else if(no_change==1){
1251 // bisection, if interpolation failed to change min or max pos last time
1252 pos = (pos_min + pos_limit)>>1;
1253 }else{
a85736f2
DB
1254 /* linear search if bisection failed, can only happen if there
1255 are very few or no keyframes between min/max */
8d14a25c
MN
1256 pos=pos_min;
1257 }
1258 if(pos <= pos_min)
1259 pos= pos_min + 1;
1260 else if(pos > pos_limit)
1261 pos= pos_limit;
1262 start_pos= pos;
1263
89ddd2a9 1264 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
8d14a25c
MN
1265 if(pos == pos_max)
1266 no_change++;
1267 else
1268 no_change=0;
1269#ifdef DEBUG_SEEK
4733abcb 1270av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
8d14a25c 1271#endif
db2a0e22
MN
1272 if(ts == AV_NOPTS_VALUE){
1273 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1274 return -1;
1275 }
8d14a25c 1276 assert(ts != AV_NOPTS_VALUE);
3ba1438d 1277 if (target_ts <= ts) {
8d14a25c
MN
1278 pos_limit = start_pos - 1;
1279 pos_max = pos;
1280 ts_max = ts;
3ba1438d
MN
1281 }
1282 if (target_ts >= ts) {
8d14a25c
MN
1283 pos_min = pos;
1284 ts_min = ts;
8d14a25c
MN
1285 }
1286 }
115329f1 1287
3ba1438d
MN
1288 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1289 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
8d14a25c
MN
1290#ifdef DEBUG_SEEK
1291 pos_min = pos;
89ddd2a9 1292 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
8d14a25c 1293 pos_min++;
89ddd2a9 1294 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
115329f1 1295 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
8d14a25c
MN
1296 pos, ts_min, target_ts, ts_max);
1297#endif
89ddd2a9
MN
1298 *ts_ret= ts;
1299 return pos;
8d14a25c
MN
1300}
1301
3ba1438d 1302static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
3ba1438d
MN
1303 int64_t pos_min, pos_max;
1304#if 0
1305 AVStream *st;
1306
1307 if (stream_index < 0)
1308 return -1;
1309
1310 st= s->streams[stream_index];
1311#endif
1312
1313 pos_min = s->data_offset;
899681cd 1314 pos_max = url_fsize(s->pb) - 1;
3ba1438d
MN
1315
1316 if (pos < pos_min) pos= pos_min;
1317 else if(pos > pos_max) pos= pos_max;
1318
899681cd 1319 url_fseek(s->pb, pos, SEEK_SET);
3ba1438d
MN
1320
1321#if 0
8bcb147f 1322 av_update_cur_dts(s, st, ts);
3ba1438d
MN
1323#endif
1324 return 0;
1325}
1326
115329f1 1327static int av_seek_frame_generic(AVFormatContext *s,
3ba1438d 1328 int stream_index, int64_t timestamp, int flags)
fb2758c8 1329{
8bcb147f 1330 int index;
fb2758c8
FB
1331 AVStream *st;
1332 AVIndexEntry *ie;
1333
fb2758c8 1334 st = s->streams[stream_index];
e9b78eeb 1335
27a5fe5f 1336 index = av_index_search_timestamp(st, timestamp, flags);
e9b78eeb 1337
b5a3541d 1338 if(index < 0 || index==st->nb_index_entries-1){
e9b78eeb
MN
1339 int i;
1340 AVPacket pkt;
1341
1342 if(st->index_entries && st->nb_index_entries){
1343 ie= &st->index_entries[st->nb_index_entries-1];
899681cd 1344 url_fseek(s->pb, ie->pos, SEEK_SET);
e9b78eeb
MN
1345 av_update_cur_dts(s, st, ie->timestamp);
1346 }else
899681cd 1347 url_fseek(s->pb, 0, SEEK_SET);
e9b78eeb
MN
1348
1349 for(i=0;; i++) {
1350 int ret = av_read_frame(s, &pkt);
1351 if(ret<0)
1352 break;
1353 av_free_packet(&pkt);
1354 if(stream_index == pkt.stream_index){
1355 if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)
1356 break;
1357 }
1358 }
1359 index = av_index_search_timestamp(st, timestamp, flags);
1360 }
fb2758c8
FB
1361 if (index < 0)
1362 return -1;
1363
fb2758c8 1364 av_read_frame_flush(s);
e9b78eeb
MN
1365 if (s->iformat->read_seek){
1366 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1367 return 0;
1368 }
1369 ie = &st->index_entries[index];
899681cd 1370 url_fseek(s->pb, ie->pos, SEEK_SET);
3ba1438d 1371
8bcb147f 1372 av_update_cur_dts(s, st, ie->timestamp);
cdd5034f 1373
fb2758c8
FB
1374 return 0;
1375}
1376
3ba1438d 1377int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
fb2758c8
FB
1378{
1379 int ret;
cdd5034f 1380 AVStream *st;
115329f1 1381
fb2758c8 1382 av_read_frame_flush(s);
115329f1 1383
3ba1438d
MN
1384 if(flags & AVSEEK_FLAG_BYTE)
1385 return av_seek_frame_byte(s, stream_index, timestamp, flags);
115329f1 1386
cdd5034f
MN
1387 if(stream_index < 0){
1388 stream_index= av_find_default_stream_index(s);
1389 if(stream_index < 0)
1390 return -1;
115329f1 1391
3ba1438d 1392 st= s->streams[stream_index];
eb497825 1393 /* timestamp for default must be expressed in AV_TIME_BASE units */
3ba1438d 1394 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
cdd5034f
MN
1395 }
1396 st= s->streams[stream_index];
1397
fb2758c8
FB
1398 /* first, we try the format specific seek */
1399 if (s->iformat->read_seek)
3ba1438d 1400 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
fb2758c8
FB
1401 else
1402 ret = -1;
1403 if (ret >= 0) {
1404 return 0;
1405 }
8d14a25c
MN
1406
1407 if(s->iformat->read_timestamp)
3ba1438d 1408 return av_seek_frame_binary(s, stream_index, timestamp, flags);
8d14a25c 1409 else
3ba1438d 1410 return av_seek_frame_generic(s, stream_index, timestamp, flags);
fb2758c8
FB
1411}
1412
1413/*******************************************************/
12f996ed 1414
e36bdf8b 1415/**
c1e8b678 1416 * Returns TRUE if the stream has accurate duration in any stream.
e36bdf8b 1417 *
c1e8b678 1418 * @return TRUE if the stream has accurate duration for at least one component.
e36bdf8b 1419 */
c1e8b678 1420static int av_has_duration(AVFormatContext *ic)
12f996ed
FB
1421{
1422 int i;
1423 AVStream *st;
1424
1425 for(i = 0;i < ic->nb_streams; i++) {
1426 st = ic->streams[i];
c1e8b678 1427 if (st->duration != AV_NOPTS_VALUE)
12f996ed
FB
1428 return 1;
1429 }
1430 return 0;
1431}
1432
e36bdf8b
DK
1433/**
1434 * Estimate the stream timings from the one of each components.
1435 *
1436 * Also computes the global bitrate if possible.
1437 */
12f996ed
FB
1438static void av_update_stream_timings(AVFormatContext *ic)
1439{
c0df9d75 1440 int64_t start_time, start_time1, end_time, end_time1;
c1e8b678 1441 int64_t duration, duration1;
12f996ed
FB
1442 int i;
1443 AVStream *st;
1444
f27a7268
MR
1445 start_time = INT64_MAX;
1446 end_time = INT64_MIN;
c1e8b678 1447 duration = INT64_MIN;
12f996ed
FB
1448 for(i = 0;i < ic->nb_streams; i++) {
1449 st = ic->streams[i];
7f938dd3 1450 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
c0df9d75
MN
1451 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1452 if (start_time1 < start_time)
1453 start_time = start_time1;
12f996ed 1454 if (st->duration != AV_NOPTS_VALUE) {
c0df9d75
MN
1455 end_time1 = start_time1
1456 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
12f996ed
FB
1457 if (end_time1 > end_time)
1458 end_time = end_time1;
1459 }
1460 }
c1e8b678
NB
1461 if (st->duration != AV_NOPTS_VALUE) {
1462 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1463 if (duration1 > duration)
1464 duration = duration1;
1465 }
12f996ed 1466 }
f27a7268 1467 if (start_time != INT64_MAX) {
12f996ed 1468 ic->start_time = start_time;
f27a7268 1469 if (end_time != INT64_MIN) {
c1e8b678
NB
1470 if (end_time - start_time > duration)
1471 duration = end_time - start_time;
1472 }
1473 }
1474 if (duration != INT64_MIN) {
1475 ic->duration = duration;
1476 if (ic->file_size > 0) {
a85736f2 1477 /* compute the bitrate */
c1e8b678
NB
1478 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1479 (double)ic->duration;
12f996ed
FB
1480 }
1481 }
12f996ed
FB
1482}
1483
1484static void fill_all_stream_timings(AVFormatContext *ic)
1485{
1486 int i;
1487 AVStream *st;
1488
1489 av_update_stream_timings(ic);
1490 for(i = 0;i < ic->nb_streams; i++) {
1491 st = ic->streams[i];
1492 if (st->start_time == AV_NOPTS_VALUE) {
c0df9d75
MN
1493 if(ic->start_time != AV_NOPTS_VALUE)
1494 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1495 if(ic->duration != AV_NOPTS_VALUE)
1496 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
12f996ed
FB
1497 }
1498 }
1499}
1500
1501static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1502{
1503 int64_t filesize, duration;
1504 int bit_rate, i;
1505 AVStream *st;
1506
1507 /* if bit_rate is already set, we believe it */
1508 if (ic->bit_rate == 0) {
1509 bit_rate = 0;
1510 for(i=0;i<ic->nb_streams;i++) {
1511 st = ic->streams[i];
01f4895c 1512 bit_rate += st->codec->bit_rate;
12f996ed
FB
1513 }
1514 ic->bit_rate = bit_rate;
1515 }
1516
1517 /* if duration is already set, we believe it */
115329f1
DB
1518 if (ic->duration == AV_NOPTS_VALUE &&
1519 ic->bit_rate != 0 &&
12f996ed
FB
1520 ic->file_size != 0) {
1521 filesize = ic->file_size;
1522 if (filesize > 0) {
12f996ed
FB
1523 for(i = 0; i < ic->nb_streams; i++) {
1524 st = ic->streams[i];
c0df9d75 1525 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
9f32041d 1526 if (st->duration == AV_NOPTS_VALUE)
12f996ed 1527 st->duration = duration;
12f996ed
FB
1528 }
1529 }
1530 }
1531}
1532
12f996ed
FB
1533#define DURATION_MAX_READ_SIZE 250000
1534
1535/* only usable for MPEG-PS streams */
9ecf7fad 1536static void av_estimate_timings_from_pts(AVFormatContext *ic, offset_t old_offset)
12f996ed
FB
1537{
1538 AVPacket pkt1, *pkt = &pkt1;
1539 AVStream *st;
1540 int read_size, i, ret;
bf4e3bd2 1541 int64_t end_time;
12f996ed 1542 int64_t filesize, offset, duration;
115329f1 1543
578688fa
LA
1544 /* free previous packet */
1545 if (ic->cur_st && ic->cur_st->parser)
1546 av_free_packet(&ic->cur_pkt);
1547 ic->cur_st = NULL;
1548
1549 /* flush packet queue */
1550 flush_packet_queue(ic);
1551
1552 for(i=0;i<ic->nb_streams;i++) {
1553 st = ic->streams[i];
1554 if (st->parser) {
1555 av_parser_close(st->parser);
1556 st->parser= NULL;
1557 }
1558 }
115329f1 1559
12f996ed
FB
1560 /* we read the first packets to get the first PTS (not fully
1561 accurate, but it is enough now) */
899681cd 1562 url_fseek(ic->pb, 0, SEEK_SET);
12f996ed
FB
1563 read_size = 0;
1564 for(;;) {
1565 if (read_size >= DURATION_MAX_READ_SIZE)
1566 break;
1567 /* if all info is available, we can stop */
1568 for(i = 0;i < ic->nb_streams; i++) {
1569 st = ic->streams[i];
1570 if (st->start_time == AV_NOPTS_VALUE)
1571 break;
1572 }
1573 if (i == ic->nb_streams)
1574 break;
1575
1576 ret = av_read_packet(ic, pkt);
1577 if (ret != 0)
1578 break;
1579 read_size += pkt->size;
1580 st = ic->streams[pkt->stream_index];
1581 if (pkt->pts != AV_NOPTS_VALUE) {
1582 if (st->start_time == AV_NOPTS_VALUE)
c0df9d75 1583 st->start_time = pkt->pts;
0a5f92a1
MN
1584 }
1585 av_free_packet(pkt);
1586 }
12f996ed 1587
12f996ed
FB
1588 /* estimate the end time (duration) */
1589 /* XXX: may need to support wrapping */
1590 filesize = ic->file_size;
1591 offset = filesize - DURATION_MAX_READ_SIZE;
1592 if (offset < 0)
1593 offset = 0;
1594
899681cd 1595 url_fseek(ic->pb, offset, SEEK_SET);
12f996ed
FB
1596 read_size = 0;
1597 for(;;) {
1598 if (read_size >= DURATION_MAX_READ_SIZE)
1599 break;
115329f1 1600
12f996ed
FB
1601 ret = av_read_packet(ic, pkt);
1602 if (ret != 0)
1603 break;
1604 read_size += pkt->size;
1605 st = ic->streams[pkt->stream_index];
bf494092
NB
1606 if (pkt->pts != AV_NOPTS_VALUE &&
1607 st->start_time != AV_NOPTS_VALUE) {
c0df9d75 1608 end_time = pkt->pts;
12f996ed
FB
1609 duration = end_time - st->start_time;
1610 if (duration > 0) {
1611 if (st->duration == AV_NOPTS_VALUE ||
1612 st->duration < duration)
1613 st->duration = duration;
1614 }
1615 }
1616 av_free_packet(pkt);
1617 }
115329f1 1618
c0df9d75 1619 fill_all_stream_timings(ic);
12f996ed 1620
899681cd 1621 url_fseek(ic->pb, old_offset, SEEK_SET);
df886e7e
MN
1622 for(i=0; i<ic->nb_streams; i++){
1623 st= ic->streams[i];
1624 st->cur_dts= st->first_dts;
cc5297e8 1625 st->last_IP_pts = AV_NOPTS_VALUE;
df886e7e 1626 }
12f996ed
FB
1627}
1628
9ecf7fad 1629static void av_estimate_timings(AVFormatContext *ic, offset_t old_offset)
12f996ed 1630{
12f996ed
FB
1631 int64_t file_size;
1632
1633 /* get the file size, if possible */
1634 if (ic->iformat->flags & AVFMT_NOFILE) {
1635 file_size = 0;
1636 } else {
899681cd 1637 file_size = url_fsize(ic->pb);
12f996ed
FB
1638 if (file_size < 0)
1639 file_size = 0;
1640 }
1641 ic->file_size = file_size;
1642
ff70e601
MR
1643 if ((!strcmp(ic->iformat->name, "mpeg") ||
1644 !strcmp(ic->iformat->name, "mpegts")) &&
ceeacce6 1645 file_size && !url_is_streamed(ic->pb)) {
12f996ed 1646 /* get accurate estimate from the PTSes */
9ecf7fad 1647 av_estimate_timings_from_pts(ic, old_offset);
c1e8b678 1648 } else if (av_has_duration(ic)) {
a85736f2 1649 /* at least one component has timings - we use them for all
12f996ed
FB
1650 the components */
1651 fill_all_stream_timings(ic);
1652 } else {
a85736f2 1653 /* less precise: use bitrate info */
12f996ed
FB
1654 av_estimate_timings_from_bit_rate(ic);
1655 }
1656 av_update_stream_timings(ic);
1657
1658#if 0
1659 {
1660 int i;
1661 AVStream *st;
1662 for(i = 0;i < ic->nb_streams; i++) {
1663 st = ic->streams[i];
115329f1
DB
1664 printf("%d: start_time: %0.3f duration: %0.3f\n",
1665 i, (double)st->start_time / AV_TIME_BASE,
12f996ed
FB
1666 (double)st->duration / AV_TIME_BASE);
1667 }
115329f1
DB
1668 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1669 (double)ic->start_time / AV_TIME_BASE,
12f996ed
FB
1670 (double)ic->duration / AV_TIME_BASE,
1671 ic->bit_rate / 1000);
1672 }
1673#endif
1674}
1675
b9a281db
FB
1676static int has_codec_parameters(AVCodecContext *enc)
1677{
1678 int val;
1679 switch(enc->codec_type) {
1680 case CODEC_TYPE_AUDIO:
1681 val = enc->sample_rate;
1682 break;
1683 case CODEC_TYPE_VIDEO:
644a9262 1684 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
b9a281db
FB
1685 break;
1686 default:
1687 val = 1;
1688 break;
1689 }
3303926c 1690 return (enc->codec_id != CODEC_ID_NONE && val != 0);
b9a281db
FB
1691}
1692
fb2758c8
FB
1693static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1694{
1695 int16_t *samples;
1696 AVCodec *codec;
3fdb6af9 1697 int got_picture, data_size, ret=0;
fb2758c8 1698 AVFrame picture;
115329f1 1699
01f4895c
MN
1700 if(!st->codec->codec){
1701 codec = avcodec_find_decoder(st->codec->codec_id);
fb2758c8
FB
1702 if (!codec)
1703 return -1;
01f4895c 1704 ret = avcodec_open(st->codec, codec);
fb2758c8
FB
1705 if (ret < 0)
1706 return ret;
43c0040a 1707 }
644a9262 1708
01f4895c
MN
1709 if(!has_codec_parameters(st->codec)){
1710 switch(st->codec->codec_type) {
fb2758c8 1711 case CODEC_TYPE_VIDEO:
115329f1 1712 ret = avcodec_decode_video(st->codec, &picture,
dc296223 1713 &got_picture, data, size);
fb2758c8
FB
1714 break;
1715 case CODEC_TYPE_AUDIO:
3fdb6af9
BC
1716 data_size = FFMAX(size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1717 samples = av_malloc(data_size);
fb2758c8
FB
1718 if (!samples)
1719 goto fail;
3fdb6af9 1720 ret = avcodec_decode_audio2(st->codec, samples,
dc296223 1721 &data_size, data, size);
fb2758c8
FB
1722 av_free(samples);
1723 break;
1724 default:
1725 break;
1726 }
644a9262 1727 }
fb2758c8 1728 fail:
fb2758c8
FB
1729 return ret;
1730}
1731
6fea687e
JD
1732static int set_codec_from_probe_data(AVStream *st, AVProbeData *pd, int score)
1733{
1734 AVInputFormat *fmt;
1735 fmt = av_probe_input_format2(pd, 1, &score);
1736
1737 if (fmt) {
1738 if (strncmp(fmt->name, "mp3", 3) == 0)
1739 st->codec->codec_id = CODEC_ID_MP3;
1740 else if (strncmp(fmt->name, "ac3", 3) == 0)
1741 st->codec->codec_id = CODEC_ID_AC3;
1742 }
efd5fc53 1743 return !!fmt;
6fea687e
JD
1744}
1745
45da8124
AJ
1746unsigned int codec_get_tag(const AVCodecTag *tags, int id)
1747{
1748 while (tags->id != CODEC_ID_NONE) {
1749 if (tags->id == id)
1750 return tags->tag;
1751 tags++;
1752 }
1753 return 0;
1754}
1755
1756enum CodecID codec_get_id(const AVCodecTag *tags, unsigned int tag)
1757{
41415d28
MN
1758 int i;
1759 for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
1760 if(tag == tags[i].tag)
1761 return tags[i].id;
1762 }
1763 for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
1764 if( toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
1765 && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
1766 && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
1767 && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
1768 return tags[i].id;
45da8124
AJ
1769 }
1770 return CODEC_ID_NONE;
1771}
1772
1773unsigned int av_codec_get_tag(const AVCodecTag *tags[4], enum CodecID id)
1774{
1775 int i;
1776 for(i=0; tags && tags[i]; i++){
1777 int tag= codec_get_tag(tags[i], id);
1778 if(tag) return tag;
1779 }
1780 return 0;
1781}
1782
1783enum CodecID av_codec_get_id(const AVCodecTag *tags[4], unsigned int tag)
1784{
1785 int i;
1786 for(i=0; tags && tags[i]; i++){
1787 enum CodecID id= codec_get_id(tags[i], tag);
1788 if(id!=CODEC_ID_NONE) return id;
1789 }
1790 return CODEC_ID_NONE;
1791}
1792
fb2758c8
FB
1793/* absolute maximum size we read until we abort */
1794#define MAX_READ_SIZE 5000000
1795
fd97f6a2 1796#define MAX_STD_TIMEBASES (60*12+5)
4d43cbcc
MN
1797static int get_std_framerate(int i){
1798 if(i<60*12) return i*1001;
fd97f6a2 1799 else return ((int[]){24,30,60,12,15})[i-60*12]*1000*12;
4d43cbcc
MN
1800}
1801
945208ca
MN
1802/*
1803 * Is the time base unreliable.
1804 * This is a heuristic to balance between quick acceptance of the values in
1805 * the headers vs. some extra checks.
a85736f2
DB
1806 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
1807 * MPEG-2 commonly misuses field repeat flags to store different framerates.
945208ca
MN
1808 * And there are "variable" fps files this needs to detect as well.
1809 */
1810static int tb_unreliable(AVCodecContext *c){
1811 if( c->time_base.den >= 101L*c->time_base.num
1812 || c->time_base.den < 5L*c->time_base.num
1813/* || c->codec_tag == ff_get_fourcc("DIVX")
1814 || c->codec_tag == ff_get_fourcc("XVID")*/
1815 || c->codec_id == CODEC_ID_MPEG2VIDEO)
1816 return 1;
1817 return 0;
1818}
1819
b9a281db
FB
1820int av_find_stream_info(AVFormatContext *ic)
1821{
9f75260e 1822 int i, count, ret, read_size, j;
b9a281db 1823 AVStream *st;
fb2758c8 1824 AVPacket pkt1, *pkt;
15bc38e5 1825 int64_t last_dts[MAX_STREAMS];
3c150d16 1826 int duration_count[MAX_STREAMS]={0};
0cbff027 1827 double (*duration_error)[MAX_STD_TIMEBASES];
899681cd 1828 offset_t old_offset = url_ftell(ic->pb);
ea486ab3
BC
1829 int64_t codec_info_duration[MAX_STREAMS]={0};
1830 int codec_info_nb_frames[MAX_STREAMS]={0};
6fea687e
JD
1831 AVProbeData probe_data[MAX_STREAMS];
1832 int codec_identified[MAX_STREAMS]={0};
b9a281db 1833
0cbff027 1834 duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
769e10f0 1835 if (!duration_error) return AVERROR(ENOMEM);
0cbff027 1836
c0df9d75
MN
1837 for(i=0;i<ic->nb_streams;i++) {
1838 st = ic->streams[i];
01f4895c 1839 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
c0df9d75
MN
1840/* if(!st->time_base.num)
1841 st->time_base= */
01f4895c
MN
1842 if(!st->codec->time_base.num)
1843 st->codec->time_base= st->time_base;
c0df9d75 1844 }
90ad92b3
MN
1845 //only for the split stuff
1846 if (!st->parser) {
01f4895c 1847 st->parser = av_parser_init(st->codec->codec_id);
57004ff1 1848 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
7cbaa7ba
MN
1849 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1850 }
90ad92b3 1851 }
c0df9d75
MN
1852 }
1853
15bc38e5
MN
1854 for(i=0;i<MAX_STREAMS;i++){
1855 last_dts[i]= AV_NOPTS_VALUE;
15bc38e5 1856 }
115329f1 1857
6fea687e 1858 memset(probe_data, 0, sizeof(probe_data));
b9a281db
FB
1859 count = 0;
1860 read_size = 0;
b9a281db
FB
1861 for(;;) {
1862 /* check if one codec still needs to be handled */
1863 for(i=0;i<ic->nb_streams;i++) {
1864 st = ic->streams[i];
01f4895c 1865 if (!has_codec_parameters(st->codec))
b9a281db 1866 break;
3e76d1b5 1867 /* variable fps and no guess at the real fps */
945208ca 1868 if( tb_unreliable(st->codec)
01f4895c 1869 && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
3e76d1b5 1870 break;
01f4895c 1871 if(st->parser && st->parser->parser->split && !st->codec->extradata)
90ad92b3 1872 break;
82583548
MN
1873 if(st->first_dts == AV_NOPTS_VALUE)
1874 break;
b9a281db
FB
1875 }
1876 if (i == ic->nb_streams) {
1877 /* NOTE: if the format has no header, then we need to read
1878 some packets to get most of the streams, so we cannot
1879 stop here */
fb2758c8 1880 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
b9a281db
FB
1881 /* if we found the info for all the codecs, we can stop */
1882 ret = count;
1883 break;
1884 }
5fb83c38 1885 }
35eab0c0
MN
1886 /* we did not get all the codec info, but we read too much data */
1887 if (read_size >= MAX_READ_SIZE) {
1888 ret = count;
1889 break;
1890 }
b9a281db 1891
fb2758c8
FB
1892 /* NOTE: a new stream can be added there if no header in file
1893 (AVFMTCTX_NOHEADER) */
1894 ret = av_read_frame_internal(ic, &pkt1);
1895 if (ret < 0) {
1896 /* EOF or error */
1897 ret = -1; /* we could not have all the codec parameters before EOF */
e19456e3
MN
1898 for(i=0;i<ic->nb_streams;i++) {
1899 st = ic->streams[i];
305ee50f
MN
1900 if (!has_codec_parameters(st->codec)){
1901 char buf[256];
1902 avcodec_string(buf, sizeof(buf), st->codec, 0);
1903 av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
344a18c3
MR
1904 } else {
1905 ret = 0;
305ee50f 1906 }
e19456e3 1907 }
fb2758c8
FB
1908 break;
1909 }
1910
02b15cc8
MN
1911 pkt= add_to_pktbuf(ic, &pkt1);
1912 if(av_dup_packet(pkt) < 0)
1913 return AVERROR(ENOMEM);
b9a281db 1914
fb2758c8 1915 read_size += pkt->size;
b9a281db
FB
1916
1917 st = ic->streams[pkt->stream_index];
ea486ab3
BC
1918 if(codec_info_nb_frames[st->index]>1)
1919 codec_info_duration[st->index] += pkt->duration;
fb2758c8 1920 if (pkt->duration != 0)
ea486ab3 1921 codec_info_nb_frames[st->index]++;
fb2758c8 1922
cefe0607 1923 {
3c150d16
MN
1924 int index= pkt->stream_index;
1925 int64_t last= last_dts[index];
1926 int64_t duration= pkt->dts - last;
1927
1928 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
4d43cbcc
MN
1929 double dur= duration * av_q2d(st->time_base);
1930
1931// if(st->codec->codec_type == CODEC_TYPE_VIDEO)
1932// av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
1694118b 1933 if(duration_count[index] < 2)
0cbff027 1934 memset(duration_error, 0, MAX_STREAMS * sizeof(*duration_error));
69c262d1
MN
1935 for(i=1; i<MAX_STD_TIMEBASES; i++){
1936 int framerate= get_std_framerate(i);
1937 int ticks= lrintf(dur*framerate/(1001*12));
1938 double error= dur - ticks*1001*12/(double)framerate;
1939 duration_error[index][i] += error*error;
1940 }
4d43cbcc 1941 duration_count[index]++;
15bc38e5 1942 }
fd97f6a2
MN
1943 if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
1944 last_dts[pkt->stream_index]= pkt->dts;
6fea687e
JD
1945
1946 if (st->codec->codec_id == CODEC_ID_NONE) {
1947 AVProbeData *pd = &(probe_data[st->index]);
9be51815 1948 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
6fea687e
JD
1949 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
1950 pd->buf_size += pkt->size;
9be51815 1951 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
6fea687e 1952 }
15bc38e5 1953 }
01f4895c
MN
1954 if(st->parser && st->parser->parser->split && !st->codec->extradata){
1955 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
90ad92b3 1956 if(i){
01f4895c 1957 st->codec->extradata_size= i;
62c52121 1958 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
01f4895c 1959 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
62c52121 1960 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
90ad92b3
MN
1961 }
1962 }
115329f1 1963
fb2758c8
FB
1964 /* if still no information, we try to open the codec and to
1965 decompress the frame. We try to avoid that in most cases as
a85736f2
DB
1966 it takes longer and uses more memory. For MPEG-4, we need to
1967 decompress for QuickTime. */
01f4895c
MN
1968 if (!has_codec_parameters(st->codec) /*&&
1969 (st->codec->codec_id == CODEC_ID_FLV1 ||
1970 st->codec->codec_id == CODEC_ID_H264 ||
1971 st->codec->codec_id == CODEC_ID_H263 ||
1972 st->codec->codec_id == CODEC_ID_H261 ||
1973 st->codec->codec_id == CODEC_ID_VORBIS ||
1974 st->codec->codec_id == CODEC_ID_MJPEG ||
1975 st->codec->codec_id == CODEC_ID_PNG ||
1976 st->codec->codec_id == CODEC_ID_PAM ||
1977 st->codec->codec_id == CODEC_ID_PGM ||
1978 st->codec->codec_id == CODEC_ID_PGMYUV ||
1979 st->codec->codec_id == CODEC_ID_PBM ||
1980 st->codec->codec_id == CODEC_ID_PPM ||
1981 st->codec->codec_id == CODEC_ID_SHORTEN ||
1982 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
fb2758c8 1983 try_decode_frame(st, pkt->data, pkt->size);
115329f1 1984
b3fc0925 1985 if (st->time_base.den > 0 && av_rescale_q(codec_info_duration[st->index], st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
fb2758c8 1986 break;
b9a281db
FB
1987 }
1988 count++;
1989 }
1990
43c0040a
MN
1991 // close codecs which where opened in try_decode_frame()
1992 for(i=0;i<ic->nb_streams;i++) {
1993 st = ic->streams[i];
01f4895c
MN
1994 if(st->codec->codec)
1995 avcodec_close(st->codec);
43c0040a 1996 }
b9a281db
FB
1997 for(i=0;i<ic->nb_streams;i++) {
1998 st = ic->streams[i];
01f4895c
MN
1999 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2000 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2001 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
15bc38e5 2002
1694118b 2003 if(duration_count[i]
945208ca 2004 && tb_unreliable(st->codec) /*&&
a85736f2 2005 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
4d43cbcc
MN
2006 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2007 double best_error= 2*av_q2d(st->time_base);
2008 best_error= best_error*best_error*duration_count[i]*1000*12*30;
2009
2010 for(j=1; j<MAX_STD_TIMEBASES; j++){
2011 double error= duration_error[i][j] * get_std_framerate(j);
2012// if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2013// av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
9f75260e
MN
2014 if(error < best_error){
2015 best_error= error;
4d43cbcc 2016 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, get_std_framerate(j), 12*1001, INT_MAX);
9f75260e 2017 }
3c150d16 2018 }
15bc38e5
MN
2019 }
2020
c0df9d75 2021 if (!st->r_frame_rate.num){
5523d5f4
MN
2022 if( st->codec->time_base.den * (int64_t)st->time_base.num
2023 <= st->codec->time_base.num * (int64_t)st->time_base.den){
2024 st->r_frame_rate.num = st->codec->time_base.den;
2025 st->r_frame_rate.den = st->codec->time_base.num;
2026 }else{
2027 st->r_frame_rate.num = st->time_base.den;
2028 st->r_frame_rate.den = st->time_base.num;
2029 }
14bea432 2030 }
a185f52a 2031 }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {
19ecf882 2032 if (st->codec->codec_id == CODEC_ID_NONE && probe_data[st->index].buf_size > 0) {
e0c850a8 2033 codec_identified[st->index] = set_codec_from_probe_data(st, &(probe_data[st->index]), 1);
6fea687e 2034 if (codec_identified[st->index]) {
57004ff1 2035 st->need_parsing = AVSTREAM_PARSE_FULL;
6fea687e
JD
2036 }
2037 }
a185f52a
MN
2038 if(!st->codec->bits_per_sample)
2039 st->codec->bits_per_sample= av_get_bits_per_sample(st->codec->codec_id);
b9a281db 2040 }
de6d9b64 2041 }
b9a281db 2042
9ecf7fad 2043 av_estimate_timings(ic, old_offset);
6fea687e
JD
2044
2045 for(i=0;i<ic->nb_streams;i++) {
2046 st = ic->streams[i];
c7385375
MN
2047 if (codec_identified[st->index])
2048 break;
2049 }
2050 //FIXME this is a mess
2051 if(i!=ic->nb_streams){
2052 av_read_frame_flush(ic);
2053 for(i=0;i<ic->nb_streams;i++) {
2054 st = ic->streams[i];
2055 if (codec_identified[st->index]) {
2056 av_seek_frame(ic, st->index, 0.0, 0);
2057 }
2058 st->cur_dts= st->first_dts;
6fea687e 2059 }
899681cd 2060 url_fseek(ic->pb, ic->data_offset, SEEK_SET);
6fea687e
JD
2061 }
2062
e928649b 2063#if 0
a85736f2 2064 /* correct DTS for B-frame streams with no timestamps */
e928649b
MN
2065 for(i=0;i<ic->nb_streams;i++) {
2066 st = ic->streams[i];
01f4895c 2067 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
e928649b
MN
2068 if(b-frames){
2069 ppktl = &ic->packet_buffer;
2070 while(ppkt1){
2071 if(ppkt1->stream_index != i)
2072 continue;
2073 if(ppkt1->pkt->dts < 0)
2074 break;
2075 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2076 break;
2077 ppkt1->pkt->dts -= delta;
2078 ppkt1= ppkt1->next;
2079 }
2080 if(ppkt1)
2081 continue;
2082 st->cur_dts -= delta;
2083 }
2084 }
2085 }
2086#endif
0cbff027
KA
2087
2088 av_free(duration_error);
6fea687e
JD
2089 for(i=0;i<MAX_STREAMS;i++){
2090 av_freep(&(probe_data[i].buf));
2091 }
0cbff027 2092
b9a281db 2093 return ret;
de6d9b64
FB
2094}
2095
fb2758c8
FB
2096/*******************************************************/
2097
fb2758c8
FB
2098int av_read_play(AVFormatContext *s)
2099{
fa13095a
BA
2100 if (s->iformat->read_play)
2101 return s->iformat->read_play(s);
fd2982a0 2102 if (s->pb)
502bdf68 2103 return av_url_read_fpause(s->pb, 0);
fa13095a 2104 return AVERROR(ENOSYS);
fb2758c8
FB
2105}
2106
fb2758c8
FB
2107int av_read_pause(AVFormatContext *s)
2108{
fa13095a
BA
2109 if (s->iformat->read_pause)
2110 return s->iformat->read_pause(s);
fd2982a0 2111 if (s->pb)
502bdf68 2112 return av_url_read_fpause(s->pb, 1);
fa13095a 2113 return AVERROR(ENOSYS);
fb2758c8
FB
2114}
2115
2506fd54 2116void av_close_input_stream(AVFormatContext *s)
de6d9b64 2117{
ca75a923 2118 int i;
da24c5e3 2119 AVStream *st;
de6d9b64 2120
fb2758c8
FB
2121 /* free previous packet */
2122 if (s->cur_st && s->cur_st->parser)
115329f1 2123 av_free_packet(&s->cur_pkt);
fb2758c8 2124
b9a281db
FB
2125 if (s->iformat->read_close)
2126 s->iformat->read_close(s);
de6d9b64 2127 for(i=0;i<s->nb_streams;i++) {
da24c5e3
FB
2128 /* free all data in a stream component */
2129 st = s->streams[i];
fb2758c8
FB
2130 if (st->parser) {
2131 av_parser_close(st->parser);
de6d9b64 2132 }
fb2758c8 2133 av_free(st->index_entries);
a5e9102b 2134 av_free(st->codec->extradata);
01f4895c 2135 av_free(st->codec);
f8d7c9d3 2136 av_free(st->filename);
fb2758c8 2137 av_free(st);
de6d9b64 2138 }
15afa396
NS
2139 for(i=s->nb_programs-1; i>=0; i--) {
2140 av_freep(&s->programs[i]->provider_name);
2141 av_freep(&s->programs[i]->name);
526efa10 2142 av_freep(&s->programs[i]->stream_index);
15afa396
NS
2143 av_freep(&s->programs[i]);
2144 }
fb2758c8 2145 flush_packet_queue(s);
a8dbe951 2146 av_freep(&s->priv_data);
1ea4f593 2147 av_free(s);
de6d9b64
FB
2148}
2149
2506fd54
RD
2150void av_close_input_file(AVFormatContext *s)
2151{
2152 ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2153 av_close_input_stream(s);
2154 if (pb)
2155 url_fclose(pb);
2156}
2157
b9a281db
FB
2158AVStream *av_new_stream(AVFormatContext *s, int id)
2159{
2160 AVStream *st;
504ee036 2161 int i;
b9a281db
FB
2162
2163 if (s->nb_streams >= MAX_STREAMS)
2164 return NULL;
2165
2166 st = av_mallocz(sizeof(AVStream));
2167 if (!st)
2168 return NULL;
115329f1 2169
01f4895c 2170 st->codec= avcodec_alloc_context();
48091512
FB
2171 if (s->iformat) {
2172 /* no default bitrate if decoding */
01f4895c 2173 st->codec->bit_rate = 0;
48091512 2174 }
b9a281db
FB
2175 st->index = s->nb_streams;
2176 st->id = id;
12f996ed
FB
2177 st->start_time = AV_NOPTS_VALUE;
2178 st->duration = AV_NOPTS_VALUE;
e928649b 2179 st->cur_dts = AV_NOPTS_VALUE;
82583548 2180 st->first_dts = AV_NOPTS_VALUE;
9ee91c2f 2181
a85736f2 2182 /* default pts setting is MPEG-like */
9ee91c2f 2183 av_set_pts_info(st, 33, 1, 90000);
77405fc8 2184 st->last_IP_pts = AV_NOPTS_VALUE;
504ee036
MN
2185 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2186 st->pts_buffer[i]= AV_NOPTS_VALUE;
9ee91c2f 2187
b9a281db
FB
2188 s->streams[s->nb_streams++] = st;
2189 return st;
2190}
2191
15afa396
NS
2192AVProgram *av_new_program(AVFormatContext *ac, int id)
2193{
2194 AVProgram *program=NULL;
2195 int i;
2196
2197#ifdef DEBUG_SI
2198 av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2199#endif
2200
2201 for(i=0; i<ac->nb_programs; i++)
2202 if(ac->programs[i]->id == id)
2203 program = ac->programs[i];
2204
2205 if(!program){
2206 program = av_mallocz(sizeof(AVProgram));
2207 if (!program)
2208 return NULL;
2209 dynarray_add(&ac->programs, &ac->nb_programs, program);
2210 program->discard = AVDISCARD_NONE;
2211 }
2212 program->id = id;
2213
2214 return program;
2215}
2216
2217void av_set_program_name(AVProgram *program, char *provider_name, char *name)
2218{
2219 assert(!provider_name == !name);
2220 if(name){
2221 av_free(program->provider_name);
2222 av_free(program-> name);
2223 program->provider_name = av_strdup(provider_name);
2224 program-> name = av_strdup( name);
2225 }
2226}
2227
2228
b9a281db
FB
2229/************************************************************/
2230/* output media file */
de6d9b64 2231
87a0a681
FB
2232int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2233{
2234 int ret;
115329f1 2235
98486a6b
RS
2236 if (s->oformat->priv_data_size > 0) {
2237 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2238 if (!s->priv_data)
769e10f0 2239 return AVERROR(ENOMEM);
98486a6b
RS
2240 } else
2241 s->priv_data = NULL;
115329f1 2242
87a0a681
FB
2243 if (s->oformat->set_parameters) {
2244 ret = s->oformat->set_parameters(s, ap);
2245 if (ret < 0)
2246 return ret;
2247 }
2248 return 0;
2249}
2250
b9a281db
FB
2251int av_write_header(AVFormatContext *s)
2252{
1e51d801
FB
2253 int ret, i;
2254 AVStream *st;
2255
9450118b
MN
2256 // some sanity checks
2257 for(i=0;i<s->nb_streams;i++) {
2258 st = s->streams[i];
2259
2260 switch (st->codec->codec_type) {
2261 case CODEC_TYPE_AUDIO:
2262 if(st->codec->sample_rate<=0){
2263 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2264 return -1;
2265 }
2266 break;
2267 case CODEC_TYPE_VIDEO:
2268 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2269 av_log(s, AV_LOG_ERROR, "time base not set\n");
2270 return -1;
2271 }
2272 if(st->codec->width<=0 || st->codec->height<=0){
2273 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2274 return -1;
2275 }
2276 break;
2277 }
5ecfa9f5
MN
2278
2279 if(s->oformat->codec_tag){
2280 if(st->codec->codec_tag){
2281 //FIXME
2282 //check that tag + id is in the table
a85736f2 2283 //if neither is in the table -> OK
5ecfa9f5
MN
2284 //if tag is in the table with another id -> FAIL
2285 //if id is in the table with another tag -> FAIL unless strict < ?
2286 }else
2287 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2288 }
9450118b
MN
2289 }
2290
8fae2df5 2291 if (!s->priv_data && s->oformat->priv_data_size > 0) {
c6efa4b5
BC
2292 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2293 if (!s->priv_data)
769e10f0 2294 return AVERROR(ENOMEM);
8fae2df5 2295 }
c6efa4b5 2296
31e11451
MN
2297 if(s->oformat->write_header){
2298 ret = s->oformat->write_header(s);
2299 if (ret < 0)
2300 return ret;
2301 }
1e51d801
FB
2302
2303 /* init PTS generation */
2304 for(i=0;i<s->nb_streams;i++) {
f0ff20a1 2305 int64_t den = AV_NOPTS_VALUE;
1e51d801
FB
2306 st = s->streams[i];
2307
01f4895c 2308 switch (st->codec->codec_type) {
1e51d801 2309 case CODEC_TYPE_AUDIO:
f0ff20a1 2310 den = (int64_t)st->time_base.num * st->codec->sample_rate;
1e51d801
FB
2311 break;
2312 case CODEC_TYPE_VIDEO:
f0ff20a1 2313 den = (int64_t)st->time_base.num * st->codec->time_base.den;
1e51d801
FB
2314 break;
2315 default:
2316 break;
2317 }
f0ff20a1
WG
2318 if (den != AV_NOPTS_VALUE) {
2319 if (den <= 0)
2320 return AVERROR_INVALIDDATA;
2321 av_frac_init(&st->pts, 0, 0, den);
2322 }
1e51d801
FB
2323 }
2324 return 0;
b9a281db
FB
2325}
2326
3c895fc0 2327//FIXME merge with compute_pkt_fields
5edea431 2328static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
504ee036
MN
2329 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2330 int num, den, frame_size, i;
b0c7f5a9 2331
949b1a13 2332// av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
115329f1 2333
e928649b
MN
2334/* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2335 return -1;*/
115329f1 2336
e928649b 2337 /* duration field */
3c895fc0
MN
2338 if (pkt->duration == 0) {
2339 compute_frame_duration(&num, &den, st, NULL, pkt);
2340 if (den && num) {
2341 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2342 }
2343 }
e928649b
MN
2344
2345 //XXX/FIXME this is a temporary hack until all encoders output pts
504ee036 2346 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
e928649b
MN
2347 pkt->dts=
2348// pkt->pts= st->cur_dts;
2349 pkt->pts= st->pts.val;
2350 }
2351
115329f1 2352 //calculate dts from pts
e928649b 2353 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
504ee036
MN
2354 st->pts_buffer[0]= pkt->pts;
2355 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2356 st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2357 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
1345f4ed 2358 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
504ee036
MN
2359
2360 pkt->dts= st->pts_buffer[0];
e928649b 2361 }
115329f1 2362
5edea431 2363 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
578688fa 2364 av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
5edea431
MN
2365 return -1;
2366 }
2367 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
578688fa 2368 av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
5edea431
MN
2369 return -1;
2370 }
2371
949b1a13 2372// av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
e928649b
MN
2373 st->cur_dts= pkt->dts;
2374 st->pts.val= pkt->dts;
2375
1e51d801 2376 /* update pts */
01f4895c 2377 switch (st->codec->codec_type) {
1e51d801 2378 case CODEC_TYPE_AUDIO:
01f4895c 2379 frame_size = get_audio_frame_size(st->codec, pkt->size);
6d8f985e 2380
a85736f2
DB
2381 /* HACK/FIXME, we skip the initial 0 size packets as they are most
2382 likely equal to the encoder delay, but it would be better if we
2383 had the real timestamps from the encoder */
e928649b 2384 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
9ee91c2f 2385 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
7feb950a 2386 }
1e51d801
FB
2387 break;
2388 case CODEC_TYPE_VIDEO:
01f4895c 2389 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
1e51d801
FB
2390 break;
2391 default:
2392 break;
2393 }
5edea431 2394 return 0;
3c895fc0
MN
2395}
2396
2397static void truncate_ts(AVStream *st, AVPacket *pkt){
2398 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
115329f1 2399
e0c91bc2 2400// if(pkt->dts < 0)
a85736f2 2401// pkt->dts= 0; //this happens for low_delay=0 and B-frames, FIXME, needs further investigation about what we should do here
115329f1 2402
68a432cf 2403 if (pkt->pts != AV_NOPTS_VALUE)
8533284d 2404 pkt->pts &= pts_mask;
68a432cf 2405 if (pkt->dts != AV_NOPTS_VALUE)
8533284d 2406 pkt->dts &= pts_mask;
3c895fc0
MN
2407}
2408
3c895fc0
MN
2409int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2410{
576ae256
MN
2411 int ret;
2412
5edea431 2413 ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
494bbf58 2414 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
5edea431 2415 return ret;
115329f1 2416
3c895fc0
MN
2417 truncate_ts(s->streams[pkt->stream_index], pkt);
2418
576ae256
MN
2419 ret= s->oformat->write_packet(s, pkt);
2420 if(!ret)
899681cd 2421 ret= url_ferror(s->pb);
576ae256 2422 return ret;
3c895fc0
MN
2423}
2424
f21c0b4c 2425int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
fe2d6fe2
MN
2426 AVPacketList *pktl, **next_point, *this_pktl;
2427 int stream_count=0;
2428 int streams[MAX_STREAMS];
2429
2430 if(pkt){
2431 AVStream *st= s->streams[ pkt->stream_index];
2432
2577897d 2433// assert(pkt->destruct != av_destruct_packet); //FIXME
fe2d6fe2
MN
2434
2435 this_pktl = av_mallocz(sizeof(AVPacketList));
2436 this_pktl->pkt= *pkt;
2577897d 2437 if(pkt->destruct == av_destruct_packet)
a85736f2 2438 pkt->destruct= NULL; // not shared -> must keep original from being freed
2577897d
MN
2439 else
2440 av_dup_packet(&this_pktl->pkt); //shared -> must dup
fe2d6fe2
MN
2441
2442 next_point = &s->packet_buffer;
2443 while(*next_point){
2444 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2445 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2446 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2447 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2448 break;
2449 next_point= &(*next_point)->next;
2450 }
2451 this_pktl->next= *next_point;
2452 *next_point= this_pktl;
2453 }
115329f1 2454
fe2d6fe2
MN
2455 memset(streams, 0, sizeof(streams));
2456 pktl= s->packet_buffer;
2457 while(pktl){
949b1a13 2458//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%"PRId64"\n", pktl->pkt.stream_index, pktl->pkt.dts);
fe2d6fe2
MN
2459 if(streams[ pktl->pkt.stream_index ] == 0)
2460 stream_count++;
2461 streams[ pktl->pkt.stream_index ]++;
2462 pktl= pktl->next;
2463 }
115329f1 2464
fe2d6fe2
MN
2465 if(s->nb_streams == stream_count || (flush && stream_count)){
2466 pktl= s->packet_buffer;
2467 *out= pktl->pkt;
115329f1
DB
2468
2469 s->packet_buffer= pktl->next;
fe2d6fe2
MN
2470 av_freep(&pktl);
2471 return 1;
2472 }else{
2473 av_init_packet(out);
2474 return 0;
2475 }
2476}
2477
2478/**
a85736f2 2479 * Interleaves an AVPacket correctly so it can be muxed.
fe2d6fe2
MN
2480 * @param out the interleaved packet will be output here
2481 * @param in the input packet
2482 * @param flush 1 if no further packets are available as input and all
2483 * remaining packets should be output
115329f1 2484 * @return 1 if a packet was output, 0 if no packet could be output,
fe2d6fe2
MN
2485 * < 0 if an error occured
2486 */
2487static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2488 if(s->oformat->interleave_packet)
2489 return s->oformat->interleave_packet(s, out, in, flush);
2490 else
2491 return av_interleave_packet_per_dts(s, out, in, flush);
2492}
2493
3c895fc0 2494int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
3c895fc0
MN
2495 AVStream *st= s->streams[ pkt->stream_index];
2496
6f824977 2497 //FIXME/XXX/HACK drop zero sized packets
01f4895c 2498 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
6f824977 2499 return 0;
3ce16b30 2500
949b1a13 2501//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
494bbf58 2502 if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3ce16b30 2503 return -1;
115329f1 2504
3c895fc0
MN
2505 if(pkt->dts == AV_NOPTS_VALUE)
2506 return -1;
3c895fc0 2507
fe2d6fe2
MN
2508 for(;;){
2509 AVPacket opkt;
2510 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2511 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2512 return ret;
115329f1 2513
fe2d6fe2
MN
2514 truncate_ts(s->streams[opkt.stream_index], &opkt);
2515 ret= s->oformat->write_packet(s, &opkt);
115329f1 2516
fe2d6fe2
MN
2517 av_free_packet(&opkt);
2518 pkt= NULL;
115329f1 2519
3c895fc0
MN
2520 if(ret<0)
2521 return ret;
899681cd
BA
2522 if(url_ferror(s->pb))
2523 return url_ferror(s->pb);
3c895fc0 2524 }
b9a281db
FB
2525}
2526
b9a281db
FB
2527int av_write_trailer(AVFormatContext *s)
2528{
c40a3a42 2529 int ret, i;
115329f1 2530
fe2d6fe2
MN
2531 for(;;){
2532 AVPacket pkt;
2533 ret= av_interleave_packet(s, &pkt, NULL, 1);
2534 if(ret<0) //FIXME cleanup needed for ret<0 ?
c40a3a42 2535 goto fail;
fe2d6fe2
MN
2536 if(!ret)
2537 break;
115329f1 2538
fe2d6fe2
MN
2539 truncate_ts(s->streams[pkt.stream_index], &pkt);
2540 ret= s->oformat->write_packet(s, &pkt);
115329f1 2541
fe2d6fe2 2542 av_free_packet(&pkt);
115329f1 2543
3c895fc0 2544 if(ret<0)
c40a3a42 2545 goto fail;
899681cd 2546 if(url_ferror(s->pb))
576ae256 2547 goto fail;
3c895fc0
MN
2548 }
2549
31e11451
MN
2550 if(s->oformat->write_trailer)
2551 ret = s->oformat->write_trailer(s);
c40a3a42 2552fail:
576ae256 2553 if(ret == 0)
899681cd 2554 ret=url_ferror(s->pb);
c40a3a42
MN
2555 for(i=0;i<s->nb_streams;i++)
2556 av_freep(&s->streams[i]->priv_data);
b9a281db
FB
2557 av_freep(&s->priv_data);
2558 return ret;
de6d9b64
FB
2559}
2560
526efa10
NS
2561void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2562{
2563 int i, j;
2564 AVProgram *program=NULL;
2565 void *tmp;
2566
2567 for(i=0; i<ac->nb_programs; i++){
2568 if(ac->programs[i]->id != progid)
2569 continue;
2570 program = ac->programs[i];
2571 for(j=0; j<program->nb_stream_indexes; j++)
2572 if(program->stream_index[j] == idx)
2573 return;
2574
2575 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2576 if(!tmp)
2577 return;
2578 program->stream_index = tmp;
2579 program->stream_index[program->nb_stream_indexes++] = idx;
2580 return;
2581 }
2582}
2583
de6d9b64 2584/* "user interface" functions */
4e745a3b 2585static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
fad0e030 2586{
4e745a3b 2587 char buf[256];
fad0e030
NS
2588 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2589 AVStream *st = ic->streams[i];
2590 int g = ff_gcd(st->time_base.num, st->time_base.den);
2591 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2592 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2593 /* the pid is an important information, so we display it */
2594 /* XXX: add a generic system */
2595 if (flags & AVFMT_SHOW_IDS)
2596 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2597 if (strlen(st->language) > 0)
2598 av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2599 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2600 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2601 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2602 if(st->r_frame_rate.den && st->r_frame_rate.num)
5fba300d 2603 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(r)", av_q2d(st->r_frame_rate));
fad0e030 2604/* else if(st->time_base.den && st->time_base.num)
5fba300d 2605 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(m)", 1/av_q2d(st->time_base));*/
fad0e030 2606 else
5fba300d 2607 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(c)", 1/av_q2d(st->codec->time_base));
fad0e030
NS
2608 }
2609 av_log(NULL, AV_LOG_INFO, "\n");
2610}
de6d9b64
FB
2611
2612void dump_format(AVFormatContext *ic,
115329f1 2613 int index,
de6d9b64
FB
2614 const char *url,
2615 int is_output)
2616{
63bb42fb 2617 int i;
de6d9b64 2618
115329f1 2619 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
de6d9b64 2620 is_output ? "Output" : "Input",
115329f1
DB
2621 index,
2622 is_output ? ic->oformat->name : ic->iformat->name,
de6d9b64 2623 is_output ? "to" : "from", url);
12f996ed 2624 if (!is_output) {
2143116d 2625 av_log(NULL, AV_LOG_INFO, " Duration: ");
12f996ed
FB
2626 if (ic->duration != AV_NOPTS_VALUE) {
2627 int hours, mins, secs, us;
2628 secs = ic->duration / AV_TIME_BASE;
2629 us = ic->duration % AV_TIME_BASE;
2630 mins = secs / 60;
2631 secs %= 60;
2632 hours = mins / 60;
2633 mins %= 60;
115329f1 2634 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
12f996ed
FB
2635 (10 * us) / AV_TIME_BASE);
2636 } else {
2143116d 2637 av_log(NULL, AV_LOG_INFO, "N/A");
12f996ed 2638 }
d0f3f159
WG
2639 if (ic->start_time != AV_NOPTS_VALUE) {
2640 int secs, us;
2143116d 2641 av_log(NULL, AV_LOG_INFO, ", start: ");
d0f3f159
WG
2642 secs = ic->start_time / AV_TIME_BASE;
2643 us = ic->start_time % AV_TIME_BASE;
2143116d 2644 av_log(NULL, AV_LOG_INFO, "%d.%06d",
d0f3f159
WG
2645 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2646 }
2143116d 2647 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
12f996ed 2648 if (ic->bit_rate) {
2143116d 2649 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
12f996ed 2650 } else {
2143116d 2651 av_log(NULL, AV_LOG_INFO, "N/A");
12f996ed 2652 }
2143116d 2653 av_log(NULL, AV_LOG_INFO, "\n");
12f996ed 2654 }
526efa10
NS
2655 if(ic->nb_programs) {
2656 int j, k;
2657 for(j=0; j<ic->nb_programs; j++) {
f473666f
NS
2658 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2659 ic->programs[j]->name ? ic->programs[j]->name : "");
526efa10 2660 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++)
4e745a3b 2661 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
526efa10
NS
2662 }
2663 } else
fad0e030 2664 for(i=0;i<ic->nb_streams;i++)
4e745a3b 2665 dump_stream_format(ic, i, index, is_output);
de6d9b64
FB
2666}
2667
de6d9b64
FB
2668int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2669{
26ef3220 2670 return av_parse_video_frame_size(width_ptr, height_ptr, str);
de6d9b64
FB
2671}
2672
26ef3220 2673int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
445f1b83 2674{
26ef3220
SS
2675 AVRational frame_rate;
2676 int ret = av_parse_video_frame_rate(&frame_rate, arg);
2677 *frame_rate_num= frame_rate.num;
2678 *frame_rate_den= frame_rate.den;
2679 return ret;
445f1b83
RS
2680}
2681
82e4ac2c 2682/**
a85736f2 2683 * Gets the current time in microseconds.
82e4ac2c
RP
2684 */
2685int64_t av_gettime(void)
2686{
2687 struct timeval tv;
2688 gettimeofday(&tv,NULL);
2689 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
2690}
2691
0c1a9eda 2692int64_t parse_date(const char *datestr, int duration)
de6d9b64
FB
2693{
2694 const char *p;
0c1a9eda 2695 int64_t t;
2dbceb9f 2696 struct tm dt;
c5510dd6
PG
2697 int i;
2698 static const char *date_fmt[] = {
2699 "%Y-%m-%d",
2700 "%Y%m%d",
2701 };
2702 static const char *time_fmt[] = {
2703 "%H:%M:%S",
2704 "%H%M%S",
2705 };
2706 const char *q;
916c80e9 2707 int is_utc, len;
c5510dd6 2708 char lastch;
a6a92a9a 2709 int negative = 0;
6d8f985e
MN
2710
2711#undef time
c5510dd6
PG
2712 time_t now = time(0);
2713
916c80e9
FB
2714 len = strlen(datestr);
2715 if (len > 0)
2716 lastch = datestr[len - 1];
2717 else
2718 lastch = '\0';
c5510dd6 2719 is_utc = (lastch == 'z' || lastch == 'Z');
2dbceb9f
PG
2720
2721 memset(&dt, 0, sizeof(dt));
de6d9b64
FB
2722
2723 p = datestr;
916c80e9 2724 q = NULL;
de6d9b64 2725 if (!duration) {
a8f70d72 2726 /* parse the year-month-day part */
c5510dd6 2727 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
f71869a4 2728 q = small_strptime(p, date_fmt[i], &dt);
c5510dd6
PG
2729 if (q) {
2730 break;
2731 }
2732 }
2733
a8f70d72
SS
2734 /* if the year-month-day part is missing, then take the
2735 * current year-month-day time */
c5510dd6
PG
2736 if (!q) {
2737 if (is_utc) {
2738 dt = *gmtime(&now);
2739 } else {
2740 dt = *localtime(&now);
2741 }
2742 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
de6d9b64 2743 } else {
c5510dd6 2744 p = q;
de6d9b64 2745 }
c5510dd6
PG
2746
2747 if (*p == 'T' || *p == 't' || *p == ' ')
2748 p++;
c5510dd6 2749
a8f70d72 2750 /* parse the hour-minute-second part */
916c80e9 2751 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
f71869a4 2752 q = small_strptime(p, time_fmt[i], &dt);
916c80e9
FB
2753 if (q) {
2754 break;
2755 }
2756 }
2757 } else {
a8f70d72 2758 /* parse datestr as a duration */
bb270c08
DB
2759 if (p[0] == '-') {
2760 negative = 1;
2761 ++p;
2762 }
a8f70d72 2763 /* parse datestr as HH:MM:SS */
f71869a4 2764 q = small_strptime(p, time_fmt[0], &dt);
916c80e9 2765 if (!q) {
a8f70d72 2766 /* parse datestr as S+ */
916c80e9 2767 dt.tm_sec = strtol(p, (char **)&q, 10);
f9436161
SS
2768 if (q == p)
2769 /* the parsing didn't succeed */
2770 return INT64_MIN;
916c80e9
FB
2771 dt.tm_min = 0;
2772 dt.tm_hour = 0;
c5510dd6
PG
2773 }
2774 }
2775
2776 /* Now we have all the fields that we can get */
2777 if (!q) {
f9436161 2778 return INT64_MIN;
de6d9b64 2779 }
2dbceb9f
PG
2780
2781 if (duration) {
c5510dd6 2782 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2dbceb9f 2783 } else {
c5510dd6
PG
2784 dt.tm_isdst = -1; /* unknown */
2785 if (is_utc) {
2786 t = mktimegm(&dt);
2787 } else {
2788 t = mktime(&dt);
2789 }
de6d9b64 2790 }
2dbceb9f 2791
c5510dd6
PG
2792 t *= 1000000;
2793
a8f70d72 2794 /* parse the .m... part */
c5510dd6 2795 if (*q == '.') {
de6d9b64 2796 int val, n;
c5510dd6
PG
2797 q++;
2798 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
115329f1 2799 if (!isdigit(*q))
c5510dd6
PG
2800 break;
2801 val += n * (*q - '0');
de6d9b64
FB
2802 }
2803 t += val;
2804 }
a6a92a9a 2805 return negative ? -t : t;
de6d9b64
FB
2806}
2807
de6d9b64
FB
2808int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2809{
2810 const char *p;
2811 char tag[128], *q;
2812
2813 p = info;
2814 if (*p == '?')
2815 p++;
2816 for(;;) {
2817 q = tag;
2818 while (*p != '\0' && *p != '=' && *p != '&') {
2819 if ((q - tag) < sizeof(tag) - 1)
2820 *q++ = *p;
2821 p++;
2822 }
2823 *q = '\0';
2824 q = arg;
2825 if (*p == '=') {
2826 p++;
2827 while (*p != '&' && *p != '\0') {
2dbceb9f
PG
2828 if ((q - arg) < arg_size - 1) {
2829 if (*p == '+')
2830 *q++ = ' ';
2831 else
2832 *q++ = *p;
2833 }
de6d9b64
FB
2834 p++;
2835 }
2836 *q = '\0';
2837 }
115329f1 2838 if (!strcmp(tag, tag1))
de6d9b64
FB
2839 return 1;
2840 if (*p != '&')
2841 break;
8d1335ea 2842 p++;
de6d9b64
FB
2843 }
2844 return 0;
2845}
2846
5c07cf53
MB
2847int av_get_frame_filename(char *buf, int buf_size,
2848 const char *path, int number)
9150f42e
FB
2849{
2850 const char *p;
0bf92f79
PI
2851 char *q, buf1[20], c;
2852 int nd, len, percentd_found;
9150f42e
FB
2853
2854 q = buf;
2855 p = path;
2856 percentd_found = 0;
2857 for(;;) {
2858 c = *p++;
2859 if (c == '\0')
2860 break;
2861 if (c == '%') {
c9646fda
PG
2862 do {
2863 nd = 0;
2864 while (isdigit(*p)) {
2865 nd = nd * 10 + *p++ - '0';
2866 }
2867 c = *p++;
c9646fda
PG
2868 } while (isdigit(c));
2869
9150f42e
FB
2870 switch(c) {
2871 case '%':
2872 goto addchar;
2873 case 'd':
2874 if (percentd_found)
2875 goto fail;
2876 percentd_found = 1;
2877 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2878 len = strlen(buf1);
2879 if ((q - buf + len) > buf_size - 1)
2880 goto fail;
2881 memcpy(q, buf1, len);
2882 q += len;
2883 break;
2884 default:
2885 goto fail;
2886 }
2887 } else {
2888 addchar:
2889 if ((q - buf) < buf_size - 1)
2890 *q++ = c;
2891 }
2892 }
2893 if (!percentd_found)
2894 goto fail;
2895 *q = '\0';
2896 return 0;
2897 fail:
2898 *q = '\0';
2899 return -1;
2900}
2901
750f0e1f 2902static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
b9a281db
FB
2903{
2904 int len, i, j, c;
750f0e1f 2905#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
b9a281db
FB
2906
2907 for(i=0;i<size;i+=16) {
2908 len = size - i;
2909 if (len > 16)
2910 len = 16;
750f0e1f 2911 PRINT("%08x ", i);
b9a281db
FB
2912 for(j=0;j<16;j++) {
2913 if (j < len)
750f0e1f 2914 PRINT(" %02x", buf[i+j]);
b9a281db 2915 else
750f0e1f 2916 PRINT(" ");
b9a281db 2917 }
750f0e1f 2918 PRINT(" ");
b9a281db
FB
2919 for(j=0;j<len;j++) {
2920 c = buf[i+j];
2921 if (c < ' ' || c > '~')
2922 c = '.';
750f0e1f 2923 PRINT("%c", c);
b9a281db 2924 }
750f0e1f 2925 PRINT("\n");
b9a281db 2926 }
750f0e1f
PI
2927#undef PRINT
2928}
2929
2930void av_hex_dump(FILE *f, uint8_t *buf, int size)
2931{
2932 hex_dump_internal(NULL, f, 0, buf, size);
2933}
2934
2935void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
2936{
2937 hex_dump_internal(avcl, NULL, level, buf, size);
b9a281db
FB
2938}
2939
c0df9d75 2940 //FIXME needs to know the time_base
750f0e1f 2941static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
fb2758c8 2942{
750f0e1f
PI
2943#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2944 PRINT("stream #%d:\n", pkt->stream_index);
2945 PRINT(" keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
2946 PRINT(" duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
37353960 2947 /* DTS is _always_ valid after av_read_frame() */
750f0e1f 2948 PRINT(" dts=");
37353960 2949 if (pkt->dts == AV_NOPTS_VALUE)
750f0e1f 2950 PRINT("N/A");
37353960 2951 else
750f0e1f 2952 PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
a85736f2 2953 /* PTS may not be known if B-frames are present. */
750f0e1f 2954 PRINT(" pts=");
fb2758c8 2955 if (pkt->pts == AV_NOPTS_VALUE)
750f0e1f 2956 PRINT("N/A");
fb2758c8 2957 else
750f0e1f
PI
2958 PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
2959 PRINT("\n");
2960 PRINT(" size=%d\n", pkt->size);
2961#undef PRINT
fb2758c8
FB
2962 if (dump_payload)
2963 av_hex_dump(f, pkt->data, pkt->size);
2964}
2965
750f0e1f
PI
2966void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
2967{
2968 pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
2969}
2970
2971void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
2972{
2973 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
2974}
2975
a9a721da 2976void url_split(char *proto, int proto_size,
6ba5cbc6 2977 char *authorization, int authorization_size,
a9a721da
FB
2978 char *hostname, int hostname_size,
2979 int *port_ptr,
2980 char *path, int path_size,
2981 const char *url)
2982{
7ef55085 2983 const char *p, *ls, *at, *col, *brk;
7e1e297e
RB
2984
2985 if (port_ptr) *port_ptr = -1;
2986 if (proto_size > 0) proto[0] = 0;
2987 if (authorization_size > 0) authorization[0] = 0;
2988 if (hostname_size > 0) hostname[0] = 0;
2989 if (path_size > 0) path[0] = 0;
2990
2991 /* parse protocol */
2992 if ((p = strchr(url, ':'))) {
2993 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
2994 p++; /* skip ':' */
2995 if (*p == '/') p++;
2996 if (*p == '/') p++;
a9a721da 2997 } else {
7e1e297e
RB
2998 /* no protocol means plain filename */
2999 av_strlcpy(path, url, path_size);
3000 return;
3001 }
6ba5cbc6 3002
7e1e297e 3003 /* separate path from hostname */
7ef55085
MN
3004 ls = strchr(p, '/');
3005 if(!ls)
3006 ls = strchr(p, '?');
3007 if(ls)
5cc9253f 3008 av_strlcpy(path, ls, path_size);
7ef55085 3009 else
7e1e297e
RB
3010 ls = &p[strlen(p)]; // XXX
3011
3012 /* the rest is hostname, use that to parse auth/port */
3013 if (ls != p) {
3014 /* authorization (user[:pass]@hostname) */
3015 if ((at = strchr(p, '@')) && at < ls) {
3016 av_strlcpy(authorization, p,
3017 FFMIN(authorization_size, at + 1 - p));
3018 p = at + 1; /* skip '@' */
a9a721da 3019 }
7e1e297e 3020
f8f88a42
RB
3021 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3022 /* [host]:port */
3023 av_strlcpy(hostname, p + 1,
3024 FFMIN(hostname_size, brk - p));
3025 if (brk[1] == ':' && port_ptr)
3026 *port_ptr = atoi(brk + 2);
3027 } else if ((col = strchr(p, ':')) && col < ls) {
3028 av_strlcpy(hostname, p,
3029 FFMIN(col + 1 - p, hostname_size));
3030 if (port_ptr) *port_ptr = atoi(col + 1);
3031 } else
3032 av_strlcpy(hostname, p,
3033 FFMIN(ls + 1 - p, hostname_size));
a9a721da 3034 }
a9a721da
FB
3035}
3036
9ee91c2f 3037void av_set_pts_info(AVStream *s, int pts_wrap_bits,
916c80e9
FB
3038 int pts_num, int pts_den)
3039{
3040 s->pts_wrap_bits = pts_wrap_bits;
9ee91c2f
MN
3041 s->time_base.num = pts_num;
3042 s->time_base.den = pts_den;
916c80e9
FB
3043}
3044
3045/* fraction handling */
3046
3047/**
e36bdf8b
DK
3048 * f = val + (num / den) + 0.5.
3049 *
3050 * 'num' is normalized so that it is such as 0 <= num < den.
916c80e9
FB
3051 *
3052 * @param f fractional number
3053 * @param val integer value
3054 * @param num must be >= 0
115329f1 3055 * @param den must be >= 1
916c80e9 3056 */
f3a30e3a 3057static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
916c80e9
FB
3058{
3059 num += (den >> 1);
3060 if (num >= den) {
3061 val += num / den;
3062 num = num % den;
3063 }
3064 f->val = val;
3065 f->num = num;
3066 f->den = den;
3067}
3068
e36bdf8b 3069/**
a85736f2 3070 * Fractional addition to f: f = f + (incr / f->den).
916c80e9
FB
3071 *
3072 * @param f fractional number
3073 * @param incr increment, can be positive or negative
3074 */
f3a30e3a 3075static void av_frac_add(AVFrac *f, int64_t incr)
916c80e9 3076{
0c1a9eda 3077 int64_t num, den;
916c80e9
FB
3078
3079 num = f->num + incr;
3080 den = f->den;
3081 if (num < 0) {
3082 f->val += num / den;
3083 num = num % den;
3084 if (num < 0) {
3085 num += den;
3086 f->val--;
3087 }
3088 } else if (num >= den) {
3089 f->val += num / den;
3090 num = num % den;
3091 }
3092 f->num = num;
3093}