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