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