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