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