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