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