export low_delay for encoding too
[libav.git] / libavformat / utils.c
CommitLineData
de6d9b64
FB
1/*
2 * Various utilities for ffmpeg system
19720f15 3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
de6d9b64 4 *
19720f15
FB
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
de6d9b64 9 *
19720f15 10 * This library is distributed in the hope that it will be useful,
de6d9b64 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
FB
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
de6d9b64 14 *
19720f15
FB
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
de6d9b64 18 */
8be1c656 19#include "avformat.h"
c5510dd6 20
b754978a
MN
21#undef NDEBUG
22#include <assert.h>
23
b9a281db
FB
24AVInputFormat *first_iformat;
25AVOutputFormat *first_oformat;
87a0a681 26AVImageFormat *first_image_format;
de6d9b64 27
b9a281db 28void av_register_input_format(AVInputFormat *format)
de6d9b64 29{
b9a281db
FB
30 AVInputFormat **p;
31 p = &first_iformat;
32 while (*p != NULL) p = &(*p)->next;
33 *p = format;
34 format->next = NULL;
35}
36
37void av_register_output_format(AVOutputFormat *format)
38{
39 AVOutputFormat **p;
40 p = &first_oformat;
de6d9b64
FB
41 while (*p != NULL) p = &(*p)->next;
42 *p = format;
43 format->next = NULL;
44}
45
5b25dfa7 46int match_ext(const char *filename, const char *extensions)
de6d9b64
FB
47{
48 const char *ext, *p;
49 char ext1[32], *q;
50
293ed23f
MN
51 if(!filename)
52 return 0;
53
de6d9b64
FB
54 ext = strrchr(filename, '.');
55 if (ext) {
56 ext++;
57 p = extensions;
58 for(;;) {
59 q = ext1;
60 while (*p != '\0' && *p != ',')
61 *q++ = *p++;
62 *q = '\0';
63 if (!strcasecmp(ext1, ext))
64 return 1;
65 if (*p == '\0')
66 break;
67 p++;
68 }
69 }
70 return 0;
71}
72
b9a281db
FB
73AVOutputFormat *guess_format(const char *short_name, const char *filename,
74 const char *mime_type)
de6d9b64 75{
b9a281db 76 AVOutputFormat *fmt, *fmt_found;
de6d9b64
FB
77 int score_max, score;
78
87a0a681 79 /* specific test for image sequences */
94d883e8
FB
80 if (!short_name && filename &&
81 filename_number_test(filename) >= 0 &&
82 guess_image_format(filename)) {
87a0a681
FB
83 return guess_format("image", NULL, NULL);
84 }
85
de6d9b64
FB
86 /* find the proper file type */
87 fmt_found = NULL;
88 score_max = 0;
b9a281db 89 fmt = first_oformat;
de6d9b64
FB
90 while (fmt != NULL) {
91 score = 0;
92 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
93 score += 100;
94 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
95 score += 10;
96 if (filename && fmt->extensions &&
97 match_ext(filename, fmt->extensions)) {
98 score += 5;
99 }
100 if (score > score_max) {
101 score_max = score;
102 fmt_found = fmt;
103 }
104 fmt = fmt->next;
105 }
106 return fmt_found;
107}
108
c5510dd6
PG
109AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
110 const char *mime_type)
111{
112 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
113
114 if (fmt) {
115 AVOutputFormat *stream_fmt;
116 char stream_format_name[64];
117
118 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
119 stream_fmt = guess_format(stream_format_name, NULL, NULL);
120
121 if (stream_fmt)
122 fmt = stream_fmt;
123 }
124
125 return fmt;
126}
127
b9a281db
FB
128AVInputFormat *av_find_input_format(const char *short_name)
129{
130 AVInputFormat *fmt;
131 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
132 if (!strcmp(fmt->name, short_name))
133 return fmt;
134 }
135 return NULL;
136}
137
de6d9b64
FB
138/* memory handling */
139
b9a281db 140/**
6fa5a56c
FB
141 * Default packet destructor
142 */
143static void av_destruct_packet(AVPacket *pkt)
144{
145 av_free(pkt->data);
146 pkt->data = NULL; pkt->size = 0;
147}
148
149/**
b9a281db
FB
150 * Allocate the payload of a packet and intialized its fields to default values.
151 *
152 * @param pkt packet
153 * @param size wanted payload size
154 * @return 0 if OK. AVERROR_xxx otherwise.
155 */
de6d9b64
FB
156int av_new_packet(AVPacket *pkt, int size)
157{
6fa5a56c
FB
158 void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
159 if (!data)
b9a281db 160 return AVERROR_NOMEM;
6fa5a56c 161 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
8cd5be98 162
6fa5a56c
FB
163 av_init_packet(pkt);
164 pkt->data = data;
165 pkt->size = size;
166 pkt->destruct = av_destruct_packet;
de6d9b64
FB
167 return 0;
168}
169
fb2758c8
FB
170/* This is a hack - the packet memory allocation stuff is broken. The
171 packet is allocated if it was not really allocated */
172int av_dup_packet(AVPacket *pkt)
173{
174 if (pkt->destruct != av_destruct_packet) {
175 uint8_t *data;
8a56ac7b
FB
176 /* we duplicate the packet and don't forget to put the padding
177 again */
178 data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
fb2758c8
FB
179 if (!data) {
180 return AVERROR_NOMEM;
181 }
182 memcpy(data, pkt->data, pkt->size);
8a56ac7b 183 memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
fb2758c8
FB
184 pkt->data = data;
185 pkt->destruct = av_destruct_packet;
186 }
187 return 0;
188}
189
de6d9b64
FB
190/* fifo handling */
191
192int fifo_init(FifoBuffer *f, int size)
193{
1ea4f593 194 f->buffer = av_malloc(size);
de6d9b64
FB
195 if (!f->buffer)
196 return -1;
197 f->end = f->buffer + size;
198 f->wptr = f->rptr = f->buffer;
199 return 0;
200}
201
202void fifo_free(FifoBuffer *f)
203{
1ea4f593 204 av_free(f->buffer);
de6d9b64
FB
205}
206
0c1a9eda 207int fifo_size(FifoBuffer *f, uint8_t *rptr)
de6d9b64
FB
208{
209 int size;
210
211 if (f->wptr >= rptr) {
212 size = f->wptr - rptr;
213 } else {
214 size = (f->end - rptr) + (f->wptr - f->buffer);
215 }
216 return size;
217}
218
219/* get data from the fifo (return -1 if not enough data) */
0c1a9eda 220int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
de6d9b64 221{
0c1a9eda 222 uint8_t *rptr = *rptr_ptr;
de6d9b64
FB
223 int size, len;
224
225 if (f->wptr >= rptr) {
226 size = f->wptr - rptr;
227 } else {
228 size = (f->end - rptr) + (f->wptr - f->buffer);
229 }
230
231 if (size < buf_size)
232 return -1;
233 while (buf_size > 0) {
234 len = f->end - rptr;
235 if (len > buf_size)
236 len = buf_size;
237 memcpy(buf, rptr, len);
238 buf += len;
239 rptr += len;
240 if (rptr >= f->end)
241 rptr = f->buffer;
242 buf_size -= len;
243 }
244 *rptr_ptr = rptr;
245 return 0;
246}
247
0c1a9eda 248void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
de6d9b64
FB
249{
250 int len;
0c1a9eda 251 uint8_t *wptr;
de6d9b64
FB
252 wptr = *wptr_ptr;
253 while (size > 0) {
254 len = f->end - wptr;
255 if (len > size)
256 len = size;
257 memcpy(wptr, buf, len);
258 wptr += len;
259 if (wptr >= f->end)
260 wptr = f->buffer;
261 buf += len;
262 size -= len;
263 }
264 *wptr_ptr = wptr;
265}
266
b9a281db
FB
267int filename_number_test(const char *filename)
268{
269 char buf[1024];
293ed23f
MN
270 if(!filename)
271 return -1;
b9a281db
FB
272 return get_frame_filename(buf, sizeof(buf), filename, 1);
273}
274
275/* guess file format */
a25e098d 276AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
b9a281db
FB
277{
278 AVInputFormat *fmt1, *fmt;
279 int score, score_max;
280
281 fmt = NULL;
282 score_max = 0;
283 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
284 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
285 continue;
286 score = 0;
a8dbe951
PG
287 if (fmt1->read_probe) {
288 score = fmt1->read_probe(pd);
289 } else if (fmt1->extensions) {
b9a281db
FB
290 if (match_ext(pd->filename, fmt1->extensions)) {
291 score = 50;
292 }
a8dbe951 293 }
b9a281db
FB
294 if (score > score_max) {
295 score_max = score;
296 fmt = fmt1;
297 }
298 }
299 return fmt;
300}
301
302/************************************************************/
303/* input media file */
96baaa6a 304
da24c5e3
FB
305/**
306 * open a media file from an IO stream. 'fmt' must be specified.
307 */
bc874dae 308
43465395 309static const char* format_to_name(void* ptr)
bc874dae 310{
43465395 311 AVFormatContext* fc = (AVFormatContext*) ptr;
bc874dae
MB
312 if(fc->iformat) return fc->iformat->name;
313 else if(fc->oformat) return fc->oformat->name;
314 else return "NULL";
315}
316
317static const AVClass av_format_context_class = { "AVFormatContext", format_to_name };
318
319AVFormatContext *av_alloc_format_context(void)
320{
321 AVFormatContext *ic;
322 ic = av_mallocz(sizeof(AVFormatContext));
323 if (!ic) return ic;
43465395 324 ic->av_class = &av_format_context_class;
bc874dae
MB
325 return ic;
326}
327
da24c5e3
FB
328int av_open_input_stream(AVFormatContext **ic_ptr,
329 ByteIOContext *pb, const char *filename,
330 AVInputFormat *fmt, AVFormatParameters *ap)
331{
332 int err;
333 AVFormatContext *ic;
334
bc874dae 335 ic = av_alloc_format_context();
da24c5e3
FB
336 if (!ic) {
337 err = AVERROR_NOMEM;
338 goto fail;
339 }
340 ic->iformat = fmt;
341 if (pb)
342 ic->pb = *pb;
343 ic->duration = AV_NOPTS_VALUE;
344 ic->start_time = AV_NOPTS_VALUE;
345 pstrcpy(ic->filename, sizeof(ic->filename), filename);
346
347 /* allocate private data */
348 if (fmt->priv_data_size > 0) {
349 ic->priv_data = av_mallocz(fmt->priv_data_size);
350 if (!ic->priv_data) {
351 err = AVERROR_NOMEM;
352 goto fail;
353 }
354 } else {
355 ic->priv_data = NULL;
356 }
357
da24c5e3
FB
358 err = ic->iformat->read_header(ic, ap);
359 if (err < 0)
360 goto fail;
fb2758c8
FB
361
362 if (pb)
363 ic->data_offset = url_ftell(&ic->pb);
364
da24c5e3
FB
365 *ic_ptr = ic;
366 return 0;
367 fail:
368 if (ic) {
369 av_freep(&ic->priv_data);
370 }
371 av_free(ic);
372 *ic_ptr = NULL;
373 return err;
374}
375
b9a281db
FB
376#define PROBE_BUF_SIZE 2048
377
378/**
379 * Open a media file as input. The codec are not opened. Only the file
380 * header (if present) is read.
381 *
382 * @param ic_ptr the opened media file handle is put here
383 * @param filename filename to open.
384 * @param fmt if non NULL, force the file format to use
385 * @param buf_size optional buffer size (zero if default is OK)
386 * @param ap additionnal parameters needed when opening the file (NULL if default)
387 * @return 0 if OK. AVERROR_xxx otherwise.
388 */
389int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
390 AVInputFormat *fmt,
391 int buf_size,
392 AVFormatParameters *ap)
de6d9b64 393{
da24c5e3
FB
394 int err, must_open_file, file_opened;
395 uint8_t buf[PROBE_BUF_SIZE];
b9a281db 396 AVProbeData probe_data, *pd = &probe_data;
da24c5e3
FB
397 ByteIOContext pb1, *pb = &pb1;
398
399 file_opened = 0;
400 pd->filename = "";
401 if (filename)
402 pd->filename = filename;
b9a281db
FB
403 pd->buf = buf;
404 pd->buf_size = 0;
405
406 if (!fmt) {
407 /* guess format if no file can be opened */
a25e098d 408 fmt = av_probe_input_format(pd, 0);
de6d9b64 409 }
de6d9b64 410
b6892136
FB
411 /* do not open file if the format does not need it. XXX: specific
412 hack needed to handle RTSP/TCP */
413 must_open_file = 1;
da24c5e3 414 if (fmt && (fmt->flags & AVFMT_NOFILE)) {
b6892136
FB
415 must_open_file = 0;
416 }
417
418 if (!fmt || must_open_file) {
87a0a681 419 /* if no file needed do not try to open one */
da24c5e3 420 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
b9a281db 421 err = AVERROR_IO;
96baaa6a 422 goto fail;
b9a281db 423 }
da24c5e3 424 file_opened = 1;
96baaa6a 425 if (buf_size > 0) {
da24c5e3 426 url_setbufsize(pb, buf_size);
96baaa6a 427 }
5b25dfa7
FB
428 if (!fmt) {
429 /* read probe data */
da24c5e3
FB
430 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
431 url_fseek(pb, 0, SEEK_SET);
5b25dfa7 432 }
96baaa6a
FB
433 }
434
b9a281db
FB
435 /* guess file format */
436 if (!fmt) {
a25e098d 437 fmt = av_probe_input_format(pd, 1);
b9a281db
FB
438 }
439
440 /* if still no format found, error */
441 if (!fmt) {
442 err = AVERROR_NOFMT;
da24c5e3 443 goto fail;
de6d9b64 444 }
b9a281db 445
67d06418 446 /* XXX: suppress this hack for redirectors */
f3ec2d46 447#ifdef CONFIG_NETWORK
67d06418 448 if (fmt == &redir_demux) {
da24c5e3
FB
449 err = redir_open(ic_ptr, pb);
450 url_fclose(pb);
67d06418
FB
451 return err;
452 }
9b2e001f 453#endif
67d06418 454
87a0a681 455 /* check filename in case of an image number is expected */
da24c5e3
FB
456 if (fmt->flags & AVFMT_NEEDNUMBER) {
457 if (filename_number_test(filename) < 0) {
87a0a681 458 err = AVERROR_NUMEXPECTED;
da24c5e3 459 goto fail;
87a0a681
FB
460 }
461 }
da24c5e3
FB
462 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
463 if (err)
464 goto fail;
b9a281db 465 return 0;
de6d9b64 466 fail:
da24c5e3
FB
467 if (file_opened)
468 url_fclose(pb);
b9a281db
FB
469 *ic_ptr = NULL;
470 return err;
da24c5e3 471
de6d9b64
FB
472}
473
da24c5e3
FB
474/*******************************************************/
475
b9a281db 476/**
fb2758c8
FB
477 * Read a transport packet from a media file. This function is
478 * absolete and should never be used. Use av_read_frame() instead.
da24c5e3 479 *
b9a281db
FB
480 * @param s media file handle
481 * @param pkt is filled
da24c5e3 482 * @return 0 if OK. AVERROR_xxx if error.
b9a281db 483 */
de6d9b64
FB
484int av_read_packet(AVFormatContext *s, AVPacket *pkt)
485{
fb2758c8
FB
486 return s->iformat->read_packet(s, pkt);
487}
488
489/**********************************************************/
490
fb2758c8
FB
491/* get the number of samples of an audio frame. Return (-1) if error */
492static int get_audio_frame_size(AVCodecContext *enc, int size)
493{
494 int frame_size;
495
496 if (enc->frame_size <= 1) {
497 /* specific hack for pcm codecs because no frame size is
498 provided */
499 switch(enc->codec_id) {
500 case CODEC_ID_PCM_S16LE:
501 case CODEC_ID_PCM_S16BE:
502 case CODEC_ID_PCM_U16LE:
503 case CODEC_ID_PCM_U16BE:
504 if (enc->channels == 0)
505 return -1;
506 frame_size = size / (2 * enc->channels);
507 break;
508 case CODEC_ID_PCM_S8:
509 case CODEC_ID_PCM_U8:
510 case CODEC_ID_PCM_MULAW:
511 case CODEC_ID_PCM_ALAW:
512 if (enc->channels == 0)
513 return -1;
514 frame_size = size / (enc->channels);
515 break;
516 default:
517 /* used for example by ADPCM codecs */
518 if (enc->bit_rate == 0)
519 return -1;
520 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
521 break;
522 }
523 } else {
524 frame_size = enc->frame_size;
525 }
526 return frame_size;
527}
528
529
530/* return the frame duration in seconds, return 0 if not available */
531static void compute_frame_duration(int *pnum, int *pden,
532 AVFormatContext *s, AVStream *st,
533 AVCodecParserContext *pc, AVPacket *pkt)
534{
535 int frame_size;
536
537 *pnum = 0;
538 *pden = 0;
539 switch(st->codec.codec_type) {
540 case CODEC_TYPE_VIDEO:
541 *pnum = st->codec.frame_rate_base;
542 *pden = st->codec.frame_rate;
543 if (pc && pc->repeat_pict) {
544 *pden *= 2;
545 *pnum = (*pnum) * (2 + pc->repeat_pict);
546 }
547 break;
548 case CODEC_TYPE_AUDIO:
549 frame_size = get_audio_frame_size(&st->codec, pkt->size);
550 if (frame_size < 0)
551 break;
552 *pnum = frame_size;
553 *pden = st->codec.sample_rate;
554 break;
555 default:
556 break;
557 }
558}
559
77405fc8 560static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
4fc2c644 561 int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
77405fc8
MN
562 int64_t delta= last_ts - mask/2;
563 return ((lsb - delta)&mask) + delta;
564}
565
fb2758c8
FB
566static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
567 AVCodecParserContext *pc, AVPacket *pkt)
568{
569 int num, den, presentation_delayed;
570
77405fc8 571 /* handle wrapping */
e928649b
MN
572 if(st->cur_dts != AV_NOPTS_VALUE){
573 if(pkt->pts != AV_NOPTS_VALUE)
574 pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
575 if(pkt->dts != AV_NOPTS_VALUE)
576 pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
577 }
77405fc8 578
fb2758c8
FB
579 if (pkt->duration == 0) {
580 compute_frame_duration(&num, &den, s, st, pc, pkt);
581 if (den && num) {
77405fc8 582 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
fb2758c8
FB
583 }
584 }
585
586 /* do we have a video B frame ? */
587 presentation_delayed = 0;
588 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
589 /* XXX: need has_b_frame, but cannot get it if the codec is
590 not initialized */
591 if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
592 st->codec.codec_id == CODEC_ID_MPEG2VIDEO ||
593 st->codec.codec_id == CODEC_ID_MPEG4 ||
594 st->codec.codec_id == CODEC_ID_H264) &&
595 pc && pc->pict_type != FF_B_TYPE)
596 presentation_delayed = 1;
77405fc8
MN
597 /* this may be redundant, but it shouldnt hurt */
598 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
599 presentation_delayed = 1;
fb2758c8 600 }
e928649b
MN
601
602 if(st->cur_dts == AV_NOPTS_VALUE){
603 if(presentation_delayed) st->cur_dts = -pkt->duration;
604 else st->cur_dts = 0;
605 }
fb2758c8 606
e928649b 607// av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
fb2758c8
FB
608 /* interpolate PTS and DTS if they are not present */
609 if (presentation_delayed) {
610 /* DTS = decompression time stamp */
611 /* PTS = presentation time stamp */
612 if (pkt->dts == AV_NOPTS_VALUE) {
77405fc8
MN
613 /* if we know the last pts, use it */
614 if(st->last_IP_pts != AV_NOPTS_VALUE)
615 st->cur_dts = pkt->dts = st->last_IP_pts;
616 else
617 pkt->dts = st->cur_dts;
fb2758c8
FB
618 } else {
619 st->cur_dts = pkt->dts;
620 }
621 /* this is tricky: the dts must be incremented by the duration
622 of the frame we are displaying, i.e. the last I or P frame */
623 if (st->last_IP_duration == 0)
624 st->cur_dts += pkt->duration;
625 else
626 st->cur_dts += st->last_IP_duration;
627 st->last_IP_duration = pkt->duration;
77405fc8 628 st->last_IP_pts= pkt->pts;
fb2758c8
FB
629 /* cannot compute PTS if not present (we can compute it only
630 by knowing the futur */
631 } else {
632 /* presentation is not delayed : PTS and DTS are the same */
633 if (pkt->pts == AV_NOPTS_VALUE) {
2092bd75
GB
634 if (pkt->dts == AV_NOPTS_VALUE) {
635 pkt->pts = st->cur_dts;
636 pkt->dts = st->cur_dts;
637 }
638 else {
639 st->cur_dts = pkt->dts;
640 pkt->pts = pkt->dts;
641 }
fb2758c8
FB
642 } else {
643 st->cur_dts = pkt->pts;
644 pkt->dts = pkt->pts;
645 }
646 st->cur_dts += pkt->duration;
647 }
e928649b 648// av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
fb2758c8
FB
649
650 /* update flags */
651 if (pc) {
652 pkt->flags = 0;
653 /* key frame computation */
654 switch(st->codec.codec_type) {
655 case CODEC_TYPE_VIDEO:
656 if (pc->pict_type == FF_I_TYPE)
657 pkt->flags |= PKT_FLAG_KEY;
658 break;
659 case CODEC_TYPE_AUDIO:
660 pkt->flags |= PKT_FLAG_KEY;
661 break;
662 default:
663 break;
664 }
665 }
666
77405fc8
MN
667 /* convert the packet time stamp units */
668 if(pkt->pts != AV_NOPTS_VALUE)
669 pkt->pts = av_rescale(pkt->pts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
670 if(pkt->dts != AV_NOPTS_VALUE)
671 pkt->dts = av_rescale(pkt->dts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
672
673 /* duration field */
674 pkt->duration = av_rescale(pkt->duration, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
fb2758c8
FB
675}
676
677static void av_destruct_packet_nofree(AVPacket *pkt)
678{
679 pkt->data = NULL; pkt->size = 0;
680}
681
682static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
683{
684 AVStream *st;
37353960 685 int len, ret, i;
fb2758c8
FB
686
687 for(;;) {
688 /* select current input stream component */
689 st = s->cur_st;
690 if (st) {
691 if (!st->parser) {
692 /* no parsing needed: we just output the packet as is */
693 /* raw data support */
694 *pkt = s->cur_pkt;
695 compute_pkt_fields(s, st, NULL, pkt);
696 s->cur_st = NULL;
697 return 0;
698 } else if (s->cur_len > 0) {
fb2758c8 699 len = av_parser_parse(st->parser, &st->codec, &pkt->data, &pkt->size,
6ec87caa
FB
700 s->cur_ptr, s->cur_len,
701 s->cur_pkt.pts, s->cur_pkt.dts);
702 s->cur_pkt.pts = AV_NOPTS_VALUE;
703 s->cur_pkt.dts = AV_NOPTS_VALUE;
fb2758c8
FB
704 /* increment read pointer */
705 s->cur_ptr += len;
706 s->cur_len -= len;
707
708 /* return packet if any */
709 if (pkt->size) {
37353960 710 got_packet:
fb2758c8
FB
711 pkt->duration = 0;
712 pkt->stream_index = st->index;
6ec87caa
FB
713 pkt->pts = st->parser->pts;
714 pkt->dts = st->parser->dts;
fb2758c8
FB
715 pkt->destruct = av_destruct_packet_nofree;
716 compute_pkt_fields(s, st, st->parser, pkt);
fb2758c8
FB
717 return 0;
718 }
719 } else {
bcbecff1
FB
720 /* free packet */
721 av_free_packet(&s->cur_pkt);
fb2758c8
FB
722 s->cur_st = NULL;
723 }
724 } else {
fb2758c8
FB
725 /* read next packet */
726 ret = av_read_packet(s, &s->cur_pkt);
37353960
FB
727 if (ret < 0) {
728 if (ret == -EAGAIN)
729 return ret;
730 /* return the last frames, if any */
731 for(i = 0; i < s->nb_streams; i++) {
732 st = s->streams[i];
733 if (st->parser) {
734 av_parser_parse(st->parser, &st->codec,
735 &pkt->data, &pkt->size,
6ec87caa
FB
736 NULL, 0,
737 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
37353960
FB
738 if (pkt->size)
739 goto got_packet;
740 }
741 }
742 /* no more packets: really terminates parsing */
fb2758c8 743 return ret;
37353960 744 }
9ee91c2f
MN
745
746 st = s->streams[s->cur_pkt.stream_index];
fb2758c8 747
fb2758c8
FB
748 s->cur_st = st;
749 s->cur_ptr = s->cur_pkt.data;
750 s->cur_len = s->cur_pkt.size;
751 if (st->need_parsing && !st->parser) {
752 st->parser = av_parser_init(st->codec.codec_id);
753 if (!st->parser) {
754 /* no parser available : just output the raw packets */
755 st->need_parsing = 0;
756 }
757 }
758 }
759 }
760}
761
762/**
763 * Return the next frame of a stream. The returned packet is valid
764 * until the next av_read_frame() or until av_close_input_file() and
765 * must be freed with av_free_packet. For video, the packet contains
766 * exactly one frame. For audio, it contains an integer number of
767 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
768 * data). If the audio frames have a variable size (e.g. MPEG audio),
769 * then it contains one frame.
770 *
771 * pkt->pts, pkt->dts and pkt->duration are always set to correct
772 * values in AV_TIME_BASE unit (and guessed if the format cannot
773 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
774 * has B frames, so it is better to rely on pkt->dts if you do not
775 * decompress the payload.
776 *
777 * Return 0 if OK, < 0 if error or end of file.
778 */
779int av_read_frame(AVFormatContext *s, AVPacket *pkt)
780{
de6d9b64
FB
781 AVPacketList *pktl;
782
783 pktl = s->packet_buffer;
784 if (pktl) {
785 /* read packet from packet buffer, if there is data */
786 *pkt = pktl->pkt;
787 s->packet_buffer = pktl->next;
1ea4f593 788 av_free(pktl);
de6d9b64
FB
789 return 0;
790 } else {
fb2758c8
FB
791 return av_read_frame_internal(s, pkt);
792 }
793}
794
795/* XXX: suppress the packet queue */
796static void flush_packet_queue(AVFormatContext *s)
797{
798 AVPacketList *pktl;
799
800 for(;;) {
801 pktl = s->packet_buffer;
802 if (!pktl)
803 break;
804 s->packet_buffer = pktl->next;
805 av_free_packet(&pktl->pkt);
806 av_free(pktl);
b9a281db
FB
807 }
808}
809
da24c5e3 810/*******************************************************/
fb2758c8
FB
811/* seek support */
812
b754978a
MN
813int av_find_default_stream_index(AVFormatContext *s)
814{
815 int i;
816 AVStream *st;
817
818 if (s->nb_streams <= 0)
819 return -1;
820 for(i = 0; i < s->nb_streams; i++) {
821 st = s->streams[i];
822 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
823 return i;
824 }
825 }
826 return 0;
827}
828
fb2758c8
FB
829/* flush the frame reader */
830static void av_read_frame_flush(AVFormatContext *s)
831{
832 AVStream *st;
833 int i;
834
835 flush_packet_queue(s);
836
837 /* free previous packet */
838 if (s->cur_st) {
839 if (s->cur_st->parser)
840 av_free_packet(&s->cur_pkt);
841 s->cur_st = NULL;
842 }
843 /* fail safe */
844 s->cur_ptr = NULL;
845 s->cur_len = 0;
846
847 /* for each stream, reset read state */
848 for(i = 0; i < s->nb_streams; i++) {
849 st = s->streams[i];
850
851 if (st->parser) {
852 av_parser_close(st->parser);
853 st->parser = NULL;
854 }
77405fc8 855 st->last_IP_pts = AV_NOPTS_VALUE;
fb2758c8
FB
856 st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
857 }
858}
859
cdd5034f
MN
860/**
861 * add a index entry into a sorted list updateing if it is already there.
862 * @param timestamp timestamp in the timebase of the given stream
863 */
3e9245a9
MN
864int av_add_index_entry(AVStream *st,
865 int64_t pos, int64_t timestamp, int distance, int flags)
fb2758c8
FB
866{
867 AVIndexEntry *entries, *ie;
b754978a 868 int index;
fb2758c8
FB
869
870 entries = av_fast_realloc(st->index_entries,
871 &st->index_entries_allocated_size,
872 (st->nb_index_entries + 1) *
873 sizeof(AVIndexEntry));
b754978a
MN
874 st->index_entries= entries;
875
876 if(st->nb_index_entries){
877 index= av_index_search_timestamp(st, timestamp);
878 ie= &entries[index];
879
880 if(ie->timestamp != timestamp){
881 if(ie->timestamp < timestamp){
882 index++; //index points to next instead of previous entry, maybe nonexistant
883 ie= &st->index_entries[index];
884 }else
885 assert(index==0);
886
887 if(index != st->nb_index_entries){
888 assert(index < st->nb_index_entries);
889 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
890 }
891 st->nb_index_entries++;
c9247fc3
MN
892 }else{
893 if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
894 distance= ie->min_distance;
b754978a 895 }
3e9245a9
MN
896 }else{
897 index= st->nb_index_entries++;
898 ie= &entries[index];
899 }
b754978a
MN
900
901 ie->pos = pos;
902 ie->timestamp = timestamp;
3e9245a9 903 ie->min_distance= distance;
b754978a 904 ie->flags = flags;
3e9245a9
MN
905
906 return index;
fb2758c8
FB
907}
908
909/* build an index for raw streams using a parser */
910static void av_build_index_raw(AVFormatContext *s)
911{
912 AVPacket pkt1, *pkt = &pkt1;
913 int ret;
914 AVStream *st;
915
916 st = s->streams[0];
917 av_read_frame_flush(s);
918 url_fseek(&s->pb, s->data_offset, SEEK_SET);
919
920 for(;;) {
921 ret = av_read_frame(s, pkt);
922 if (ret < 0)
923 break;
924 if (pkt->stream_index == 0 && st->parser &&
925 (pkt->flags & PKT_FLAG_KEY)) {
cdd5034f
MN
926 int64_t dts= av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
927 av_add_index_entry(st, st->parser->frame_offset, dts,
3e9245a9 928 0, AVINDEX_KEYFRAME);
fb2758c8
FB
929 }
930 av_free_packet(pkt);
931 }
932}
933
934/* return TRUE if we deal with a raw stream (raw codec data and
935 parsing needed) */
936static int is_raw_stream(AVFormatContext *s)
937{
938 AVStream *st;
939
940 if (s->nb_streams != 1)
941 return 0;
942 st = s->streams[0];
943 if (!st->need_parsing)
944 return 0;
945 return 1;
946}
947
948/* return the largest index entry whose timestamp is <=
949 wanted_timestamp */
b754978a 950int av_index_search_timestamp(AVStream *st, int wanted_timestamp)
fb2758c8 951{
b754978a
MN
952 AVIndexEntry *entries= st->index_entries;
953 int nb_entries= st->nb_index_entries;
fb2758c8
FB
954 int a, b, m;
955 int64_t timestamp;
956
957 if (nb_entries <= 0)
958 return -1;
959
960 a = 0;
961 b = nb_entries - 1;
b754978a
MN
962
963 while (a < b) {
964 m = (a + b + 1) >> 1;
fb2758c8 965 timestamp = entries[m].timestamp;
b754978a 966 if (timestamp > wanted_timestamp) {
fb2758c8
FB
967 b = m - 1;
968 } else {
b754978a 969 a = m;
fb2758c8
FB
970 }
971 }
b754978a 972 return a;
fb2758c8
FB
973}
974
8d14a25c
MN
975#define DEBUG_SEEK
976
cdd5034f
MN
977/**
978 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
979 * this isnt supposed to be called directly by a user application, but by demuxers
980 * @param target_ts target timestamp in the time base of the given stream
981 * @param stream_index stream number
982 */
8d14a25c
MN
983int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts){
984 AVInputFormat *avif= s->iformat;
985 int64_t pos_min, pos_max, pos, pos_limit;
986 int64_t ts_min, ts_max, ts;
987 int64_t start_pos;
cdd5034f 988 int index, no_change, i;
8d14a25c
MN
989 AVStream *st;
990
cdd5034f
MN
991 if (stream_index < 0)
992 return -1;
993
8d14a25c
MN
994#ifdef DEBUG_SEEK
995 av_log(s, AV_LOG_DEBUG, "read_seek: %d %lld\n", stream_index, target_ts);
996#endif
997
998 ts_max=
999 ts_min= AV_NOPTS_VALUE;
1000 pos_limit= -1; //gcc falsely says it may be uninitalized
1001
1002 st= s->streams[stream_index];
1003 if(st->index_entries){
1004 AVIndexEntry *e;
1005
1006 index= av_index_search_timestamp(st, target_ts);
1007 e= &st->index_entries[index];
1008
1009 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1010 pos_min= e->pos;
1011 ts_min= e->timestamp;
1012#ifdef DEBUG_SEEK
1013 av_log(s, AV_LOG_DEBUG, "unsing cached pos_min=0x%llx dts_min=%lld\n",
1014 pos_min,ts_min);
1015#endif
1016 }else{
1017 assert(index==0);
1018 }
1019 index++;
1020 if(index < st->nb_index_entries){
1021 e= &st->index_entries[index];
1022 assert(e->timestamp >= target_ts);
1023 pos_max= e->pos;
1024 ts_max= e->timestamp;
1025 pos_limit= pos_max - e->min_distance;
1026#ifdef DEBUG_SEEK
1027 av_log(s, AV_LOG_DEBUG, "unsing cached pos_max=0x%llx pos_limit=0x%llx dts_max=%lld\n",
1028 pos_max,pos_limit, ts_max);
1029#endif
1030 }
1031 }
1032
1033 if(ts_min == AV_NOPTS_VALUE){
1034 pos_min = s->data_offset;
1035 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1036 if (ts_min == AV_NOPTS_VALUE)
1037 return -1;
1038 }
1039
1040 if(ts_max == AV_NOPTS_VALUE){
1041 int step= 1024;
1042 pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1043 do{
1044 pos_max -= step;
1045 ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1046 step += step;
1047 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1048 if (ts_max == AV_NOPTS_VALUE)
1049 return -1;
1050
1051 for(;;){
1052 int64_t tmp_pos= pos_max + 1;
1053 int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1054 if(tmp_ts == AV_NOPTS_VALUE)
1055 break;
1056 ts_max= tmp_ts;
1057 pos_max= tmp_pos;
1058 }
1059 pos_limit= pos_max;
1060 }
1061
1062 no_change=0;
1063 while (pos_min < pos_limit) {
1064#ifdef DEBUG_SEEK
1065 av_log(s, AV_LOG_DEBUG, "pos_min=0x%llx pos_max=0x%llx dts_min=%lld dts_max=%lld\n",
1066 pos_min, pos_max,
1067 ts_min, ts_max);
1068#endif
1069 assert(pos_limit <= pos_max);
1070
1071 if(no_change==0){
1072 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1073 // interpolate position (better than dichotomy)
1074 pos = (int64_t)((double)(pos_max - pos_min) *
1075 (double)(target_ts - ts_min) /
1076 (double)(ts_max - ts_min)) + pos_min - approximate_keyframe_distance;
1077 }else if(no_change==1){
1078 // bisection, if interpolation failed to change min or max pos last time
1079 pos = (pos_min + pos_limit)>>1;
1080 }else{
1081 // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1082 pos=pos_min;
1083 }
1084 if(pos <= pos_min)
1085 pos= pos_min + 1;
1086 else if(pos > pos_limit)
1087 pos= pos_limit;
1088 start_pos= pos;
1089
1090 ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1091 if(pos == pos_max)
1092 no_change++;
1093 else
1094 no_change=0;
1095#ifdef DEBUG_SEEK
1096av_log(s, AV_LOG_DEBUG, "%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1097#endif
1098 assert(ts != AV_NOPTS_VALUE);
1099 if (target_ts < ts) {
1100 pos_limit = start_pos - 1;
1101 pos_max = pos;
1102 ts_max = ts;
1103 } else {
1104 pos_min = pos;
1105 ts_min = ts;
1106 /* check if we are lucky */
1107 if (target_ts == ts)
1108 break;
1109 }
1110 }
1111
1112 pos = pos_min;
1113#ifdef DEBUG_SEEK
1114 pos_min = pos;
1115 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1116 pos_min++;
1117 ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1118 av_log(s, AV_LOG_DEBUG, "pos=0x%llx %lld<=%lld<=%lld\n",
1119 pos, ts_min, target_ts, ts_max);
1120#endif
1121 /* do the seek */
1122 url_fseek(&s->pb, pos, SEEK_SET);
cdd5034f
MN
1123
1124 ts= av_rescale(ts_min, AV_TIME_BASE*(int64_t)st->time_base.num, st->time_base.den);
1125 for(i = 0; i < s->nb_streams; i++) {
1126 st = s->streams[i];
1127
77405fc8 1128 st->cur_dts = av_rescale(ts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
cdd5034f 1129 }
8d14a25c
MN
1130
1131 return 0;
1132}
1133
fb2758c8
FB
1134static int av_seek_frame_generic(AVFormatContext *s,
1135 int stream_index, int64_t timestamp)
1136{
cdd5034f 1137 int index, i;
fb2758c8
FB
1138 AVStream *st;
1139 AVIndexEntry *ie;
1140
1141 if (!s->index_built) {
1142 if (is_raw_stream(s)) {
1143 av_build_index_raw(s);
1144 } else {
1145 return -1;
1146 }
1147 s->index_built = 1;
1148 }
1149
fb2758c8 1150 st = s->streams[stream_index];
b754978a 1151 index = av_index_search_timestamp(st, timestamp);
fb2758c8
FB
1152 if (index < 0)
1153 return -1;
1154
1155 /* now we have found the index, we can seek */
1156 ie = &st->index_entries[index];
1157 av_read_frame_flush(s);
1158 url_fseek(&s->pb, ie->pos, SEEK_SET);
cdd5034f
MN
1159
1160 timestamp= av_rescale(ie->timestamp, AV_TIME_BASE*(int64_t)st->time_base.num, st->time_base.den);
1161 for(i = 0; i < s->nb_streams; i++) {
1162 st = s->streams[i];
1163
77405fc8 1164 st->cur_dts = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
cdd5034f
MN
1165 }
1166
fb2758c8
FB
1167 return 0;
1168}
1169
1170/**
1171 * Seek to the key frame just before the frame at timestamp
cdd5034f
MN
1172 * 'timestamp' in 'stream_index'.
1173 * @param stream_index If stream_index is (-1), a default
1174 * stream is selected
1175 * @param timestamp timestamp in AV_TIME_BASE units
1176 * @return >= 0 on success
fb2758c8
FB
1177 */
1178int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp)
1179{
1180 int ret;
cdd5034f 1181 AVStream *st;
fb2758c8
FB
1182
1183 av_read_frame_flush(s);
cdd5034f
MN
1184
1185 if(stream_index < 0){
1186 stream_index= av_find_default_stream_index(s);
1187 if(stream_index < 0)
1188 return -1;
1189 }
1190 st= s->streams[stream_index];
1191
1192 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
fb2758c8
FB
1193
1194 /* first, we try the format specific seek */
1195 if (s->iformat->read_seek)
1196 ret = s->iformat->read_seek(s, stream_index, timestamp);
1197 else
1198 ret = -1;
1199 if (ret >= 0) {
1200 return 0;
1201 }
8d14a25c
MN
1202
1203 if(s->iformat->read_timestamp)
1204 return av_seek_frame_binary(s, stream_index, timestamp);
1205 else
1206 return av_seek_frame_generic(s, stream_index, timestamp);
fb2758c8
FB
1207}
1208
1209/*******************************************************/
12f996ed
FB
1210
1211/* return TRUE if the stream has accurate timings for at least one component */
1212static int av_has_timings(AVFormatContext *ic)
1213{
1214 int i;
1215 AVStream *st;
1216
1217 for(i = 0;i < ic->nb_streams; i++) {
1218 st = ic->streams[i];
1219 if (st->start_time != AV_NOPTS_VALUE &&
1220 st->duration != AV_NOPTS_VALUE)
1221 return 1;
1222 }
1223 return 0;
1224}
1225
1226/* estimate the stream timings from the one of each components. Also
1227 compute the global bitrate if possible */
1228static void av_update_stream_timings(AVFormatContext *ic)
1229{
1230 int64_t start_time, end_time, end_time1;
1231 int i;
1232 AVStream *st;
1233
1234 start_time = MAXINT64;
1235 end_time = MININT64;
1236 for(i = 0;i < ic->nb_streams; i++) {
1237 st = ic->streams[i];
1238 if (st->start_time != AV_NOPTS_VALUE) {
1239 if (st->start_time < start_time)
1240 start_time = st->start_time;
1241 if (st->duration != AV_NOPTS_VALUE) {
1242 end_time1 = st->start_time + st->duration;
1243 if (end_time1 > end_time)
1244 end_time = end_time1;
1245 }
1246 }
1247 }
1248 if (start_time != MAXINT64) {
1249 ic->start_time = start_time;
1250 if (end_time != MAXINT64) {
1251 ic->duration = end_time - start_time;
1252 if (ic->file_size > 0) {
1253 /* compute the bit rate */
1254 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1255 (double)ic->duration;
1256 }
1257 }
1258 }
1259
1260}
1261
1262static void fill_all_stream_timings(AVFormatContext *ic)
1263{
1264 int i;
1265 AVStream *st;
1266
1267 av_update_stream_timings(ic);
1268 for(i = 0;i < ic->nb_streams; i++) {
1269 st = ic->streams[i];
1270 if (st->start_time == AV_NOPTS_VALUE) {
1271 st->start_time = ic->start_time;
1272 st->duration = ic->duration;
1273 }
1274 }
1275}
1276
1277static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1278{
1279 int64_t filesize, duration;
1280 int bit_rate, i;
1281 AVStream *st;
1282
1283 /* if bit_rate is already set, we believe it */
1284 if (ic->bit_rate == 0) {
1285 bit_rate = 0;
1286 for(i=0;i<ic->nb_streams;i++) {
1287 st = ic->streams[i];
1288 bit_rate += st->codec.bit_rate;
1289 }
1290 ic->bit_rate = bit_rate;
1291 }
1292
1293 /* if duration is already set, we believe it */
1294 if (ic->duration == AV_NOPTS_VALUE &&
1295 ic->bit_rate != 0 &&
1296 ic->file_size != 0) {
1297 filesize = ic->file_size;
1298 if (filesize > 0) {
1299 duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
1300 for(i = 0; i < ic->nb_streams; i++) {
1301 st = ic->streams[i];
1302 if (st->start_time == AV_NOPTS_VALUE ||
1303 st->duration == AV_NOPTS_VALUE) {
1304 st->start_time = 0;
1305 st->duration = duration;
1306 }
1307 }
1308 }
1309 }
1310}
1311
12f996ed
FB
1312#define DURATION_MAX_READ_SIZE 250000
1313
1314/* only usable for MPEG-PS streams */
1315static void av_estimate_timings_from_pts(AVFormatContext *ic)
1316{
1317 AVPacket pkt1, *pkt = &pkt1;
1318 AVStream *st;
1319 int read_size, i, ret;
1320 int64_t start_time, end_time, end_time1;
1321 int64_t filesize, offset, duration;
1322
fb2758c8
FB
1323 /* free previous packet */
1324 if (ic->cur_st && ic->cur_st->parser)
1325 av_free_packet(&ic->cur_pkt);
1326 ic->cur_st = NULL;
1327
1328 /* flush packet queue */
1329 flush_packet_queue(ic);
1330
1331
12f996ed
FB
1332 /* we read the first packets to get the first PTS (not fully
1333 accurate, but it is enough now) */
1334 url_fseek(&ic->pb, 0, SEEK_SET);
1335 read_size = 0;
1336 for(;;) {
1337 if (read_size >= DURATION_MAX_READ_SIZE)
1338 break;
1339 /* if all info is available, we can stop */
1340 for(i = 0;i < ic->nb_streams; i++) {
1341 st = ic->streams[i];
1342 if (st->start_time == AV_NOPTS_VALUE)
1343 break;
1344 }
1345 if (i == ic->nb_streams)
1346 break;
1347
1348 ret = av_read_packet(ic, pkt);
1349 if (ret != 0)
1350 break;
1351 read_size += pkt->size;
1352 st = ic->streams[pkt->stream_index];
1353 if (pkt->pts != AV_NOPTS_VALUE) {
1354 if (st->start_time == AV_NOPTS_VALUE)
9ee91c2f 1355 st->start_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
0a5f92a1
MN
1356 }
1357 av_free_packet(pkt);
1358 }
12f996ed
FB
1359
1360 /* we compute the minimum start_time and use it as default */
1361 start_time = MAXINT64;
1362 for(i = 0; i < ic->nb_streams; i++) {
1363 st = ic->streams[i];
1364 if (st->start_time != AV_NOPTS_VALUE &&
1365 st->start_time < start_time)
1366 start_time = st->start_time;
1367 }
12f996ed
FB
1368 if (start_time != MAXINT64)
1369 ic->start_time = start_time;
1370
1371 /* estimate the end time (duration) */
1372 /* XXX: may need to support wrapping */
1373 filesize = ic->file_size;
1374 offset = filesize - DURATION_MAX_READ_SIZE;
1375 if (offset < 0)
1376 offset = 0;
1377
12f996ed
FB
1378 url_fseek(&ic->pb, offset, SEEK_SET);
1379 read_size = 0;
1380 for(;;) {
1381 if (read_size >= DURATION_MAX_READ_SIZE)
1382 break;
1383 /* if all info is available, we can stop */
1384 for(i = 0;i < ic->nb_streams; i++) {
1385 st = ic->streams[i];
1386 if (st->duration == AV_NOPTS_VALUE)
1387 break;
1388 }
1389 if (i == ic->nb_streams)
1390 break;
1391
1392 ret = av_read_packet(ic, pkt);
1393 if (ret != 0)
1394 break;
1395 read_size += pkt->size;
1396 st = ic->streams[pkt->stream_index];
1397 if (pkt->pts != AV_NOPTS_VALUE) {
9ee91c2f 1398 end_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
12f996ed
FB
1399 duration = end_time - st->start_time;
1400 if (duration > 0) {
1401 if (st->duration == AV_NOPTS_VALUE ||
1402 st->duration < duration)
1403 st->duration = duration;
1404 }
1405 }
1406 av_free_packet(pkt);
1407 }
1408
1409 /* estimate total duration */
1410 end_time = MININT64;
1411 for(i = 0;i < ic->nb_streams; i++) {
1412 st = ic->streams[i];
1413 if (st->duration != AV_NOPTS_VALUE) {
1414 end_time1 = st->start_time + st->duration;
1415 if (end_time1 > end_time)
1416 end_time = end_time1;
1417 }
1418 }
1419
1420 /* update start_time (new stream may have been created, so we do
1421 it at the end */
1422 if (ic->start_time != AV_NOPTS_VALUE) {
1423 for(i = 0; i < ic->nb_streams; i++) {
1424 st = ic->streams[i];
1425 if (st->start_time == AV_NOPTS_VALUE)
1426 st->start_time = ic->start_time;
1427 }
1428 }
1429
1430 if (end_time != MININT64) {
1431 /* put dummy values for duration if needed */
1432 for(i = 0;i < ic->nb_streams; i++) {
1433 st = ic->streams[i];
1434 if (st->duration == AV_NOPTS_VALUE &&
1435 st->start_time != AV_NOPTS_VALUE)
1436 st->duration = end_time - st->start_time;
1437 }
1438 ic->duration = end_time - ic->start_time;
1439 }
1440
1441 url_fseek(&ic->pb, 0, SEEK_SET);
1442}
1443
1444static void av_estimate_timings(AVFormatContext *ic)
1445{
1446 URLContext *h;
1447 int64_t file_size;
1448
1449 /* get the file size, if possible */
1450 if (ic->iformat->flags & AVFMT_NOFILE) {
1451 file_size = 0;
1452 } else {
1453 h = url_fileno(&ic->pb);
1454 file_size = url_filesize(h);
1455 if (file_size < 0)
1456 file_size = 0;
1457 }
1458 ic->file_size = file_size;
1459
1460 if (ic->iformat == &mpegps_demux) {
1461 /* get accurate estimate from the PTSes */
1462 av_estimate_timings_from_pts(ic);
1463 } else if (av_has_timings(ic)) {
1464 /* at least one components has timings - we use them for all
1465 the components */
1466 fill_all_stream_timings(ic);
1467 } else {
1468 /* less precise: use bit rate info */
1469 av_estimate_timings_from_bit_rate(ic);
1470 }
1471 av_update_stream_timings(ic);
1472
1473#if 0
1474 {
1475 int i;
1476 AVStream *st;
1477 for(i = 0;i < ic->nb_streams; i++) {
1478 st = ic->streams[i];
1479 printf("%d: start_time: %0.3f duration: %0.3f\n",
1480 i, (double)st->start_time / AV_TIME_BASE,
1481 (double)st->duration / AV_TIME_BASE);
1482 }
1483 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1484 (double)ic->start_time / AV_TIME_BASE,
1485 (double)ic->duration / AV_TIME_BASE,
1486 ic->bit_rate / 1000);
1487 }
1488#endif
1489}
1490
b9a281db
FB
1491static int has_codec_parameters(AVCodecContext *enc)
1492{
1493 int val;
1494 switch(enc->codec_type) {
1495 case CODEC_TYPE_AUDIO:
1496 val = enc->sample_rate;
1497 break;
1498 case CODEC_TYPE_VIDEO:
1499 val = enc->width;
1500 break;
1501 default:
1502 val = 1;
1503 break;
1504 }
1505 return (val != 0);
1506}
1507
fb2758c8
FB
1508static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1509{
1510 int16_t *samples;
1511 AVCodec *codec;
1512 int got_picture, ret;
1513 AVFrame picture;
1514
1515 codec = avcodec_find_decoder(st->codec.codec_id);
1516 if (!codec)
1517 return -1;
1518 ret = avcodec_open(&st->codec, codec);
1519 if (ret < 0)
1520 return ret;
1521 switch(st->codec.codec_type) {
1522 case CODEC_TYPE_VIDEO:
1523 ret = avcodec_decode_video(&st->codec, &picture,
1524 &got_picture, (uint8_t *)data, size);
1525 break;
1526 case CODEC_TYPE_AUDIO:
1527 samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1528 if (!samples)
1529 goto fail;
1530 ret = avcodec_decode_audio(&st->codec, samples,
1531 &got_picture, (uint8_t *)data, size);
1532 av_free(samples);
1533 break;
1534 default:
1535 break;
1536 }
1537 fail:
1538 avcodec_close(&st->codec);
1539 return ret;
1540}
1541
1542/* absolute maximum size we read until we abort */
1543#define MAX_READ_SIZE 5000000
1544
1545/* maximum duration until we stop analysing the stream */
1546#define MAX_STREAM_DURATION ((int)(AV_TIME_BASE * 1.0))
1547
b9a281db
FB
1548/**
1549 * Read the beginning of a media file to get stream information. This
1550 * is useful for file formats with no headers such as MPEG. This
1551 * function also compute the real frame rate in case of mpeg2 repeat
1552 * frame mode.
1553 *
1554 * @param ic media file handle
1555 * @return >=0 if OK. AVERROR_xxx if error.
1556 */
1557int av_find_stream_info(AVFormatContext *ic)
1558{
fb2758c8 1559 int i, count, ret, read_size;
b9a281db 1560 AVStream *st;
fb2758c8 1561 AVPacket pkt1, *pkt;
b9a281db 1562 AVPacketList *pktl=NULL, **ppktl;
b9a281db
FB
1563
1564 count = 0;
1565 read_size = 0;
1566 ppktl = &ic->packet_buffer;
1567 for(;;) {
1568 /* check if one codec still needs to be handled */
1569 for(i=0;i<ic->nb_streams;i++) {
1570 st = ic->streams[i];
fb2758c8 1571 if (!has_codec_parameters(&st->codec))
b9a281db
FB
1572 break;
1573 }
1574 if (i == ic->nb_streams) {
1575 /* NOTE: if the format has no header, then we need to read
1576 some packets to get most of the streams, so we cannot
1577 stop here */
fb2758c8 1578 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
b9a281db
FB
1579 /* if we found the info for all the codecs, we can stop */
1580 ret = count;
1581 break;
1582 }
1583 } else {
1584 /* we did not get all the codec info, but we read too much data */
fb2758c8 1585 if (read_size >= MAX_READ_SIZE) {
b9a281db
FB
1586 ret = count;
1587 break;
1588 }
1589 }
1590
fb2758c8
FB
1591 /* NOTE: a new stream can be added there if no header in file
1592 (AVFMTCTX_NOHEADER) */
1593 ret = av_read_frame_internal(ic, &pkt1);
1594 if (ret < 0) {
1595 /* EOF or error */
1596 ret = -1; /* we could not have all the codec parameters before EOF */
1597 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
1598 i == ic->nb_streams)
1599 ret = 0;
1600 break;
1601 }
1602
b9a281db
FB
1603 pktl = av_mallocz(sizeof(AVPacketList));
1604 if (!pktl) {
1605 ret = AVERROR_NOMEM;
1606 break;
1607 }
1608
1609 /* add the packet in the buffered packet list */
1610 *ppktl = pktl;
1611 ppktl = &pktl->next;
1612
b9a281db 1613 pkt = &pktl->pkt;
fb2758c8
FB
1614 *pkt = pkt1;
1615
1616 /* duplicate the packet */
1617 if (av_dup_packet(pkt) < 0) {
1618 ret = AVERROR_NOMEM;
1619 break;
b9a281db 1620 }
b9a281db 1621
fb2758c8 1622 read_size += pkt->size;
b9a281db
FB
1623
1624 st = ic->streams[pkt->stream_index];
fb2758c8
FB
1625 st->codec_info_duration += pkt->duration;
1626 if (pkt->duration != 0)
1627 st->codec_info_nb_frames++;
1628
1629 /* if still no information, we try to open the codec and to
1630 decompress the frame. We try to avoid that in most cases as
1631 it takes longer and uses more memory. For MPEG4, we need to
1632 decompress for Quicktime. */
1633 if (!has_codec_parameters(&st->codec) &&
1634 (st->codec.codec_id == CODEC_ID_FLV1 ||
1635 st->codec.codec_id == CODEC_ID_H264 ||
1636 st->codec.codec_id == CODEC_ID_H263 ||
8bfed902 1637 st->codec.codec_id == CODEC_ID_VORBIS ||
fb2758c8
FB
1638 (st->codec.codec_id == CODEC_ID_MPEG4 && !st->need_parsing)))
1639 try_decode_frame(st, pkt->data, pkt->size);
1640
1641 if (st->codec_info_duration >= MAX_STREAM_DURATION) {
1642 break;
b9a281db
FB
1643 }
1644 count++;
1645 }
1646
b9a281db
FB
1647 /* set real frame rate info */
1648 for(i=0;i<ic->nb_streams;i++) {
1649 st = ic->streams[i];
1650 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
fb2758c8
FB
1651 /* compute the real frame rate for telecine */
1652 if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
1653 st->codec.codec_id == CODEC_ID_MPEG2VIDEO) &&
1654 st->codec.sub_id == 2) {
1655 if (st->codec_info_nb_frames >= 20) {
1656 float coded_frame_rate, est_frame_rate;
1657 est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
1658 (double)st->codec_info_duration ;
1659 coded_frame_rate = (double)st->codec.frame_rate /
1660 (double)st->codec.frame_rate_base;
1661#if 0
1662 printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
1663 coded_frame_rate, est_frame_rate);
1664#endif
1665 /* if we detect that it could be a telecine, we
1666 signal it. It would be better to do it at a
1667 higher level as it can change in a film */
1668 if (coded_frame_rate >= 24.97 &&
1669 (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
1670 st->r_frame_rate = 24024;
1671 st->r_frame_rate_base = 1001;
1672 }
1673 }
1674 }
1675 /* if no real frame rate, use the codec one */
14bea432
MN
1676 if (!st->r_frame_rate){
1677 st->r_frame_rate = st->codec.frame_rate;
1678 st->r_frame_rate_base = st->codec.frame_rate_base;
1679 }
b9a281db 1680 }
de6d9b64 1681 }
b9a281db 1682
12f996ed 1683 av_estimate_timings(ic);
e928649b
MN
1684#if 0
1685 /* correct DTS for b frame streams with no timestamps */
1686 for(i=0;i<ic->nb_streams;i++) {
1687 st = ic->streams[i];
1688 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1689 if(b-frames){
1690 ppktl = &ic->packet_buffer;
1691 while(ppkt1){
1692 if(ppkt1->stream_index != i)
1693 continue;
1694 if(ppkt1->pkt->dts < 0)
1695 break;
1696 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
1697 break;
1698 ppkt1->pkt->dts -= delta;
1699 ppkt1= ppkt1->next;
1700 }
1701 if(ppkt1)
1702 continue;
1703 st->cur_dts -= delta;
1704 }
1705 }
1706 }
1707#endif
b9a281db 1708 return ret;
de6d9b64
FB
1709}
1710
fb2758c8
FB
1711/*******************************************************/
1712
1713/**
1714 * start playing a network based stream (e.g. RTSP stream) at the
1715 * current position
1716 */
1717int av_read_play(AVFormatContext *s)
1718{
1719 if (!s->iformat->read_play)
1720 return AVERROR_NOTSUPP;
1721 return s->iformat->read_play(s);
1722}
1723
1724/**
1725 * pause a network based stream (e.g. RTSP stream). Use av_read_play()
1726 * to resume it.
1727 */
1728int av_read_pause(AVFormatContext *s)
1729{
1730 if (!s->iformat->read_pause)
1731 return AVERROR_NOTSUPP;
1732 return s->iformat->read_pause(s);
1733}
1734
b9a281db
FB
1735/**
1736 * Close a media file (but not its codecs)
1737 *
1738 * @param s media file handle
1739 */
de6d9b64
FB
1740void av_close_input_file(AVFormatContext *s)
1741{
b6892136 1742 int i, must_open_file;
da24c5e3 1743 AVStream *st;
de6d9b64 1744
fb2758c8
FB
1745 /* free previous packet */
1746 if (s->cur_st && s->cur_st->parser)
1747 av_free_packet(&s->cur_pkt);
1748
b9a281db
FB
1749 if (s->iformat->read_close)
1750 s->iformat->read_close(s);
de6d9b64 1751 for(i=0;i<s->nb_streams;i++) {
da24c5e3
FB
1752 /* free all data in a stream component */
1753 st = s->streams[i];
fb2758c8
FB
1754 if (st->parser) {
1755 av_parser_close(st->parser);
de6d9b64 1756 }
fb2758c8
FB
1757 av_free(st->index_entries);
1758 av_free(st);
de6d9b64 1759 }
fb2758c8 1760 flush_packet_queue(s);
b6892136 1761 must_open_file = 1;
da24c5e3 1762 if (s->iformat->flags & AVFMT_NOFILE) {
b6892136
FB
1763 must_open_file = 0;
1764 }
1765 if (must_open_file) {
96baaa6a
FB
1766 url_fclose(&s->pb);
1767 }
a8dbe951 1768 av_freep(&s->priv_data);
1ea4f593 1769 av_free(s);
de6d9b64
FB
1770}
1771
b9a281db
FB
1772/**
1773 * Add a new stream to a media file. Can only be called in the
da24c5e3
FB
1774 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
1775 * format context, then new streams can be added in read_packet too.
b9a281db
FB
1776 *
1777 *
1778 * @param s media file handle
da24c5e3 1779 * @param id file format dependent stream id
b9a281db
FB
1780 */
1781AVStream *av_new_stream(AVFormatContext *s, int id)
1782{
1783 AVStream *st;
1784
1785 if (s->nb_streams >= MAX_STREAMS)
1786 return NULL;
1787
1788 st = av_mallocz(sizeof(AVStream));
1789 if (!st)
1790 return NULL;
1e491e29 1791 avcodec_get_context_defaults(&st->codec);
48091512
FB
1792 if (s->iformat) {
1793 /* no default bitrate if decoding */
1794 st->codec.bit_rate = 0;
1795 }
b9a281db
FB
1796 st->index = s->nb_streams;
1797 st->id = id;
12f996ed
FB
1798 st->start_time = AV_NOPTS_VALUE;
1799 st->duration = AV_NOPTS_VALUE;
e928649b 1800 st->cur_dts = AV_NOPTS_VALUE;
9ee91c2f
MN
1801
1802 /* default pts settings is MPEG like */
1803 av_set_pts_info(st, 33, 1, 90000);
77405fc8 1804 st->last_IP_pts = AV_NOPTS_VALUE;
9ee91c2f 1805
b9a281db
FB
1806 s->streams[s->nb_streams++] = st;
1807 return st;
1808}
1809
1810/************************************************************/
1811/* output media file */
de6d9b64 1812
87a0a681
FB
1813int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1814{
1815 int ret;
98486a6b
RS
1816
1817 if (s->oformat->priv_data_size > 0) {
1818 s->priv_data = av_mallocz(s->oformat->priv_data_size);
1819 if (!s->priv_data)
1820 return AVERROR_NOMEM;
1821 } else
1822 s->priv_data = NULL;
1823
87a0a681
FB
1824 if (s->oformat->set_parameters) {
1825 ret = s->oformat->set_parameters(s, ap);
1826 if (ret < 0)
1827 return ret;
1828 }
1829 return 0;
1830}
1831
b9a281db
FB
1832/**
1833 * allocate the stream private data and write the stream header to an
1834 * output media file
1835 *
1836 * @param s media file handle
1837 * @return 0 if OK. AVERROR_xxx if error.
1838 */
1839int av_write_header(AVFormatContext *s)
1840{
1e51d801
FB
1841 int ret, i;
1842 AVStream *st;
1843
1e51d801
FB
1844 ret = s->oformat->write_header(s);
1845 if (ret < 0)
1846 return ret;
1847
1848 /* init PTS generation */
1849 for(i=0;i<s->nb_streams;i++) {
1850 st = s->streams[i];
1851
1852 switch (st->codec.codec_type) {
1853 case CODEC_TYPE_AUDIO:
1854 av_frac_init(&st->pts, 0, 0,
9ee91c2f 1855 (int64_t)st->time_base.num * st->codec.sample_rate);
1e51d801
FB
1856 break;
1857 case CODEC_TYPE_VIDEO:
1858 av_frac_init(&st->pts, 0, 0,
9ee91c2f 1859 (int64_t)st->time_base.num * st->codec.frame_rate);
1e51d801
FB
1860 break;
1861 default:
1862 break;
1863 }
1864 }
1865 return 0;
b9a281db
FB
1866}
1867
1868/**
1e51d801
FB
1869 * Write a packet to an output media file. The packet shall contain
1870 * one audio or video frame.
b9a281db
FB
1871 *
1872 * @param s media file handle
e928649b 1873 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
d4c0ff91 1874 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
b9a281db 1875 */
e928649b 1876int av_write_frame(AVFormatContext *s, AVPacket *pkt)
de6d9b64 1877{
1e51d801 1878 AVStream *st;
0c1a9eda 1879 int64_t pts_mask;
7feb950a 1880 int ret, frame_size;
e928649b 1881 int b_frames;
1e51d801 1882
e928649b
MN
1883 if(pkt->stream_index<0)
1884 return -1;
1885 st = s->streams[pkt->stream_index];
b0c7f5a9 1886
e928649b
MN
1887 b_frames = FFMAX(st->codec.has_b_frames, st->codec.max_b_frames);
1888
1889 // av_log(s, AV_LOG_DEBUG, "av_write_frame: pts:%lld dts:%lld cur_dts:%lld b:%d size:%d\n", pkt->pts, pkt->dts, st->cur_dts, b_frames, pkt->size);
1890
1891/* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
1892 return -1;*/
1893
1894 if(pkt->pts != AV_NOPTS_VALUE)
1895 pkt->pts = av_rescale(pkt->pts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1896 if(pkt->dts != AV_NOPTS_VALUE)
1897 pkt->dts = av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1898
1899 /* duration field */
1900 pkt->duration = av_rescale(pkt->duration, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1901
1902 //XXX/FIXME this is a temporary hack until all encoders output pts
1903 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
1904 pkt->dts=
1905// pkt->pts= st->cur_dts;
1906 pkt->pts= st->pts.val;
1907 }
1908
1909 //calculate dts from pts
1910 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
1911 if(b_frames){
1912 if(st->last_IP_pts == AV_NOPTS_VALUE){
1913 st->last_IP_pts= -av_rescale(1,
1914 st->codec.frame_rate_base*(int64_t)st->time_base.den,
1915 st->codec.frame_rate *(int64_t)st->time_base.num);
1916 }
1917 if(st->last_IP_pts < pkt->pts){
1918 pkt->dts= st->last_IP_pts;
1919 st->last_IP_pts= pkt->pts;
1920 }else
1921 pkt->dts= pkt->pts;
1922 }else
1923 pkt->dts= pkt->pts;
1924 }
1925
1926// av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
1927 st->cur_dts= pkt->dts;
1928 st->pts.val= pkt->dts;
1929
1930 pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
1931 pkt->pts &= pts_mask;
1932 pkt->dts &= pts_mask;
1933
1934 ret = s->oformat->write_packet(s, pkt);
b0c7f5a9 1935
1e51d801
FB
1936 if (ret < 0)
1937 return ret;
1938
1939 /* update pts */
1940 switch (st->codec.codec_type) {
1941 case CODEC_TYPE_AUDIO:
e928649b 1942 frame_size = get_audio_frame_size(&st->codec, pkt->size);
6d8f985e 1943
b0c7f5a9 1944 /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
6d8f985e 1945 but it would be better if we had the real timestamps from the encoder */
e928649b 1946 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
9ee91c2f 1947 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
7feb950a 1948 }
1e51d801
FB
1949 break;
1950 case CODEC_TYPE_VIDEO:
9ee91c2f 1951 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec.frame_rate_base);
1e51d801
FB
1952 break;
1953 default:
1954 break;
1955 }
d4c0ff91 1956 return ret;
b9a281db
FB
1957}
1958
1959/**
1960 * write the stream trailer to an output media file and and free the
1961 * file private data.
1962 *
1963 * @param s media file handle
1964 * @return 0 if OK. AVERROR_xxx if error. */
1965int av_write_trailer(AVFormatContext *s)
1966{
1967 int ret;
1968 ret = s->oformat->write_trailer(s);
1969 av_freep(&s->priv_data);
1970 return ret;
de6d9b64
FB
1971}
1972
1973/* "user interface" functions */
1974
1975void dump_format(AVFormatContext *ic,
1976 int index,
1977 const char *url,
1978 int is_output)
1979{
b9a281db 1980 int i, flags;
de6d9b64
FB
1981 char buf[256];
1982
43465395 1983 av_log(NULL, AV_LOG_DEBUG, "%s #%d, %s, %s '%s':\n",
de6d9b64 1984 is_output ? "Output" : "Input",
b9a281db
FB
1985 index,
1986 is_output ? ic->oformat->name : ic->iformat->name,
de6d9b64 1987 is_output ? "to" : "from", url);
12f996ed 1988 if (!is_output) {
43465395 1989 av_log(NULL, AV_LOG_DEBUG, " Duration: ");
12f996ed
FB
1990 if (ic->duration != AV_NOPTS_VALUE) {
1991 int hours, mins, secs, us;
1992 secs = ic->duration / AV_TIME_BASE;
1993 us = ic->duration % AV_TIME_BASE;
1994 mins = secs / 60;
1995 secs %= 60;
1996 hours = mins / 60;
1997 mins %= 60;
43465395 1998 av_log(NULL, AV_LOG_DEBUG, "%02d:%02d:%02d.%01d", hours, mins, secs,
12f996ed
FB
1999 (10 * us) / AV_TIME_BASE);
2000 } else {
43465395 2001 av_log(NULL, AV_LOG_DEBUG, "N/A");
12f996ed 2002 }
43465395 2003 av_log(NULL, AV_LOG_DEBUG, ", bitrate: ");
12f996ed 2004 if (ic->bit_rate) {
43465395 2005 av_log(NULL, AV_LOG_DEBUG,"%d kb/s", ic->bit_rate / 1000);
12f996ed 2006 } else {
43465395 2007 av_log(NULL, AV_LOG_DEBUG, "N/A");
12f996ed 2008 }
43465395 2009 av_log(NULL, AV_LOG_DEBUG, "\n");
12f996ed 2010 }
de6d9b64
FB
2011 for(i=0;i<ic->nb_streams;i++) {
2012 AVStream *st = ic->streams[i];
2013 avcodec_string(buf, sizeof(buf), &st->codec, is_output);
43465395 2014 av_log(NULL, AV_LOG_DEBUG, " Stream #%d.%d", index, i);
b9a281db
FB
2015 /* the pid is an important information, so we display it */
2016 /* XXX: add a generic system */
2017 if (is_output)
2018 flags = ic->oformat->flags;
2019 else
2020 flags = ic->iformat->flags;
2021 if (flags & AVFMT_SHOW_IDS) {
43465395 2022 av_log(NULL, AV_LOG_DEBUG, "[0x%x]", st->id);
b9a281db 2023 }
43465395 2024 av_log(NULL, AV_LOG_DEBUG, ": %s\n", buf);
de6d9b64
FB
2025 }
2026}
2027
2028typedef struct {
445f1b83 2029 const char *abv;
de6d9b64 2030 int width, height;
445f1b83
RS
2031 int frame_rate, frame_rate_base;
2032} AbvEntry;
2033
2034static AbvEntry frame_abvs[] = {
ba2a8cb4
RS
2035 { "ntsc", 720, 480, 30000, 1001 },
2036 { "pal", 720, 576, 25, 1 },
2037 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2038 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
904736b5
RS
2039 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
2040 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
445f1b83
RS
2041 { "film", 352, 240, 24, 1 },
2042 { "ntsc-film", 352, 240, 24000, 1001 },
2043 { "sqcif", 128, 96, 0, 0 },
2044 { "qcif", 176, 144, 0, 0 },
2045 { "cif", 352, 288, 0, 0 },
2046 { "4cif", 704, 576, 0, 0 },
de6d9b64 2047};
445f1b83 2048
de6d9b64
FB
2049int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2050{
2051 int i;
445f1b83 2052 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
de6d9b64
FB
2053 const char *p;
2054 int frame_width = 0, frame_height = 0;
2055
2056 for(i=0;i<n;i++) {
445f1b83
RS
2057 if (!strcmp(frame_abvs[i].abv, str)) {
2058 frame_width = frame_abvs[i].width;
2059 frame_height = frame_abvs[i].height;
de6d9b64
FB
2060 break;
2061 }
2062 }
2063 if (i == n) {
2064 p = str;
2065 frame_width = strtol(p, (char **)&p, 10);
2066 if (*p)
2067 p++;
2068 frame_height = strtol(p, (char **)&p, 10);
2069 }
2070 if (frame_width <= 0 || frame_height <= 0)
2071 return -1;
2072 *width_ptr = frame_width;
2073 *height_ptr = frame_height;
2074 return 0;
2075}
2076
445f1b83
RS
2077int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2078{
2079 int i;
2080 char* cp;
2081
2082 /* First, we check our abbreviation table */
2083 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2084 if (!strcmp(frame_abvs[i].abv, arg)) {
2085 *frame_rate = frame_abvs[i].frame_rate;
2086 *frame_rate_base = frame_abvs[i].frame_rate_base;
2087 return 0;
2088 }
2089
2090 /* Then, we try to parse it as fraction */
2091 cp = strchr(arg, '/');
2092 if (cp) {
2093 char* cpp;
2094 *frame_rate = strtol(arg, &cpp, 10);
2095 if (cpp != arg || cpp == cp)
2096 *frame_rate_base = strtol(cp+1, &cpp, 10);
2097 else
2098 *frame_rate = 0;
2099 }
2100 else {
2101 /* Finally we give up and parse it as double */
8bfed902 2102 *frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME use av_d2q()
445f1b83
RS
2103 *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
2104 }
2105 if (!*frame_rate || !*frame_rate_base)
2106 return -1;
2107 else
2108 return 0;
2109}
2110
916c80e9
FB
2111/* Syntax:
2112 * - If not a duration:
2113 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
c5510dd6 2114 * Time is localtime unless Z is suffixed to the end. In this case GMT
916c80e9
FB
2115 * Return the date in micro seconds since 1970
2116 * - If duration:
2117 * HH[:MM[:SS[.m...]]]
2118 * S+[.m...]
2119 */
0c1a9eda 2120int64_t parse_date(const char *datestr, int duration)
de6d9b64
FB
2121{
2122 const char *p;
0c1a9eda 2123 int64_t t;
2dbceb9f 2124 struct tm dt;
c5510dd6
PG
2125 int i;
2126 static const char *date_fmt[] = {
2127 "%Y-%m-%d",
2128 "%Y%m%d",
2129 };
2130 static const char *time_fmt[] = {
2131 "%H:%M:%S",
2132 "%H%M%S",
2133 };
2134 const char *q;
916c80e9 2135 int is_utc, len;
c5510dd6 2136 char lastch;
6d8f985e
MN
2137
2138#undef time
c5510dd6
PG
2139 time_t now = time(0);
2140
916c80e9
FB
2141 len = strlen(datestr);
2142 if (len > 0)
2143 lastch = datestr[len - 1];
2144 else
2145 lastch = '\0';
c5510dd6 2146 is_utc = (lastch == 'z' || lastch == 'Z');
2dbceb9f
PG
2147
2148 memset(&dt, 0, sizeof(dt));
de6d9b64
FB
2149
2150 p = datestr;
916c80e9 2151 q = NULL;
de6d9b64 2152 if (!duration) {
c5510dd6 2153 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
f71869a4 2154 q = small_strptime(p, date_fmt[i], &dt);
c5510dd6
PG
2155 if (q) {
2156 break;
2157 }
2158 }
2159
2160 if (!q) {
2161 if (is_utc) {
2162 dt = *gmtime(&now);
2163 } else {
2164 dt = *localtime(&now);
2165 }
2166 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
de6d9b64 2167 } else {
c5510dd6 2168 p = q;
de6d9b64 2169 }
c5510dd6
PG
2170
2171 if (*p == 'T' || *p == 't' || *p == ' ')
2172 p++;
c5510dd6 2173
916c80e9 2174 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
f71869a4 2175 q = small_strptime(p, time_fmt[i], &dt);
916c80e9
FB
2176 if (q) {
2177 break;
2178 }
2179 }
2180 } else {
f71869a4 2181 q = small_strptime(p, time_fmt[0], &dt);
916c80e9
FB
2182 if (!q) {
2183 dt.tm_sec = strtol(p, (char **)&q, 10);
2184 dt.tm_min = 0;
2185 dt.tm_hour = 0;
c5510dd6
PG
2186 }
2187 }
2188
2189 /* Now we have all the fields that we can get */
2190 if (!q) {
2191 if (duration)
2192 return 0;
2193 else
0c1a9eda 2194 return now * int64_t_C(1000000);
de6d9b64 2195 }
2dbceb9f
PG
2196
2197 if (duration) {
c5510dd6 2198 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2dbceb9f 2199 } else {
c5510dd6
PG
2200 dt.tm_isdst = -1; /* unknown */
2201 if (is_utc) {
2202 t = mktimegm(&dt);
2203 } else {
2204 t = mktime(&dt);
2205 }
de6d9b64 2206 }
2dbceb9f 2207
c5510dd6
PG
2208 t *= 1000000;
2209
2210 if (*q == '.') {
de6d9b64 2211 int val, n;
c5510dd6
PG
2212 q++;
2213 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2214 if (!isdigit(*q))
2215 break;
2216 val += n * (*q - '0');
de6d9b64
FB
2217 }
2218 t += val;
2219 }
2220 return t;
2221}
2222
2dbceb9f 2223/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
de6d9b64
FB
2224 1 if found */
2225int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2226{
2227 const char *p;
2228 char tag[128], *q;
2229
2230 p = info;
2231 if (*p == '?')
2232 p++;
2233 for(;;) {
2234 q = tag;
2235 while (*p != '\0' && *p != '=' && *p != '&') {
2236 if ((q - tag) < sizeof(tag) - 1)
2237 *q++ = *p;
2238 p++;
2239 }
2240 *q = '\0';
2241 q = arg;
2242 if (*p == '=') {
2243 p++;
2244 while (*p != '&' && *p != '\0') {
2dbceb9f
PG
2245 if ((q - arg) < arg_size - 1) {
2246 if (*p == '+')
2247 *q++ = ' ';
2248 else
2249 *q++ = *p;
2250 }
de6d9b64
FB
2251 p++;
2252 }
2253 *q = '\0';
2254 }
2255 if (!strcmp(tag, tag1))
2256 return 1;
2257 if (*p != '&')
2258 break;
8d1335ea 2259 p++;
de6d9b64
FB
2260 }
2261 return 0;
2262}
2263
9150f42e
FB
2264/* Return in 'buf' the path with '%d' replaced by number. Also handles
2265 the '%0nd' format where 'n' is the total number of digits and
2266 '%%'. Return 0 if OK, and -1 if format error */
2267int get_frame_filename(char *buf, int buf_size,
2268 const char *path, int number)
2269{
2270 const char *p;
0bf92f79
PI
2271 char *q, buf1[20], c;
2272 int nd, len, percentd_found;
9150f42e
FB
2273
2274 q = buf;
2275 p = path;
2276 percentd_found = 0;
2277 for(;;) {
2278 c = *p++;
2279 if (c == '\0')
2280 break;
2281 if (c == '%') {
c9646fda
PG
2282 do {
2283 nd = 0;
2284 while (isdigit(*p)) {
2285 nd = nd * 10 + *p++ - '0';
2286 }
2287 c = *p++;
c9646fda
PG
2288 } while (isdigit(c));
2289
9150f42e
FB
2290 switch(c) {
2291 case '%':
2292 goto addchar;
2293 case 'd':
2294 if (percentd_found)
2295 goto fail;
2296 percentd_found = 1;
2297 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2298 len = strlen(buf1);
2299 if ((q - buf + len) > buf_size - 1)
2300 goto fail;
2301 memcpy(q, buf1, len);
2302 q += len;
2303 break;
2304 default:
2305 goto fail;
2306 }
2307 } else {
2308 addchar:
2309 if ((q - buf) < buf_size - 1)
2310 *q++ = c;
2311 }
2312 }
2313 if (!percentd_found)
2314 goto fail;
2315 *q = '\0';
2316 return 0;
2317 fail:
2318 *q = '\0';
2319 return -1;
2320}
2321
b9a281db 2322/**
fb2758c8
FB
2323 * Print nice hexa dump of a buffer
2324 * @param f stream for output
b9a281db
FB
2325 * @param buf buffer
2326 * @param size buffer size
2327 */
fb2758c8 2328void av_hex_dump(FILE *f, uint8_t *buf, int size)
b9a281db
FB
2329{
2330 int len, i, j, c;
2331
2332 for(i=0;i<size;i+=16) {
2333 len = size - i;
2334 if (len > 16)
2335 len = 16;
fb2758c8 2336 fprintf(f, "%08x ", i);
b9a281db
FB
2337 for(j=0;j<16;j++) {
2338 if (j < len)
fb2758c8 2339 fprintf(f, " %02x", buf[i+j]);
b9a281db 2340 else
fb2758c8 2341 fprintf(f, " ");
b9a281db 2342 }
fb2758c8 2343 fprintf(f, " ");
b9a281db
FB
2344 for(j=0;j<len;j++) {
2345 c = buf[i+j];
2346 if (c < ' ' || c > '~')
2347 c = '.';
fb2758c8 2348 fprintf(f, "%c", c);
b9a281db 2349 }
fb2758c8 2350 fprintf(f, "\n");
b9a281db
FB
2351 }
2352}
2353
fb2758c8
FB
2354/**
2355 * Print on 'f' a nice dump of a packet
2356 * @param f stream for output
2357 * @param pkt packet to dump
2358 * @param dump_payload true if the payload must be displayed too
2359 */
2360void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
2361{
2362 fprintf(f, "stream #%d:\n", pkt->stream_index);
2363 fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
2364 fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
37353960
FB
2365 /* DTS is _always_ valid after av_read_frame() */
2366 fprintf(f, " dts=");
2367 if (pkt->dts == AV_NOPTS_VALUE)
2368 fprintf(f, "N/A");
2369 else
2370 fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
fb2758c8
FB
2371 /* PTS may be not known if B frames are present */
2372 fprintf(f, " pts=");
2373 if (pkt->pts == AV_NOPTS_VALUE)
2374 fprintf(f, "N/A");
2375 else
2376 fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
2377 fprintf(f, "\n");
2378 fprintf(f, " size=%d\n", pkt->size);
2379 if (dump_payload)
2380 av_hex_dump(f, pkt->data, pkt->size);
2381}
2382
a9a721da
FB
2383void url_split(char *proto, int proto_size,
2384 char *hostname, int hostname_size,
2385 int *port_ptr,
2386 char *path, int path_size,
2387 const char *url)
2388{
2389 const char *p;
2390 char *q;
2391 int port;
2392
2393 port = -1;
2394
2395 p = url;
2396 q = proto;
2397 while (*p != ':' && *p != '\0') {
2398 if ((q - proto) < proto_size - 1)
2399 *q++ = *p;
2400 p++;
2401 }
2402 if (proto_size > 0)
2403 *q = '\0';
2404 if (*p == '\0') {
2405 if (proto_size > 0)
2406 proto[0] = '\0';
2407 if (hostname_size > 0)
2408 hostname[0] = '\0';
2409 p = url;
2410 } else {
2411 p++;
2412 if (*p == '/')
2413 p++;
2414 if (*p == '/')
2415 p++;
2416 q = hostname;
2417 while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
2418 if ((q - hostname) < hostname_size - 1)
2419 *q++ = *p;
2420 p++;
2421 }
2422 if (hostname_size > 0)
2423 *q = '\0';
2424 if (*p == ':') {
2425 p++;
2426 port = strtoul(p, (char **)&p, 10);
2427 }
2428 }
2429 if (port_ptr)
2430 *port_ptr = port;
2431 pstrcpy(path, path_size, p);
2432}
2433
916c80e9
FB
2434/**
2435 * Set the pts for a given stream
2436 * @param s stream
2437 * @param pts_wrap_bits number of bits effectively used by the pts
2438 * (used for wrap control, 33 is the value for MPEG)
2439 * @param pts_num numerator to convert to seconds (MPEG: 1)
2440 * @param pts_den denominator to convert to seconds (MPEG: 90000)
2441 */
9ee91c2f 2442void av_set_pts_info(AVStream *s, int pts_wrap_bits,
916c80e9
FB
2443 int pts_num, int pts_den)
2444{
2445 s->pts_wrap_bits = pts_wrap_bits;
9ee91c2f
MN
2446 s->time_base.num = pts_num;
2447 s->time_base.den = pts_den;
916c80e9
FB
2448}
2449
2450/* fraction handling */
2451
2452/**
2453 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
2454 * as 0 <= num < den.
2455 *
2456 * @param f fractional number
2457 * @param val integer value
2458 * @param num must be >= 0
2459 * @param den must be >= 1
2460 */
0c1a9eda 2461void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
916c80e9
FB
2462{
2463 num += (den >> 1);
2464 if (num >= den) {
2465 val += num / den;
2466 num = num % den;
2467 }
2468 f->val = val;
2469 f->num = num;
2470 f->den = den;
2471}
2472
2473/* set f to (val + 0.5) */
0c1a9eda 2474void av_frac_set(AVFrac *f, int64_t val)
916c80e9
FB
2475{
2476 f->val = val;
2477 f->num = f->den >> 1;
2478}
2479
2480/**
2481 * Fractionnal addition to f: f = f + (incr / f->den)
2482 *
2483 * @param f fractional number
2484 * @param incr increment, can be positive or negative
2485 */
0c1a9eda 2486void av_frac_add(AVFrac *f, int64_t incr)
916c80e9 2487{
0c1a9eda 2488 int64_t num, den;
916c80e9
FB
2489
2490 num = f->num + incr;
2491 den = f->den;
2492 if (num < 0) {
2493 f->val += num / den;
2494 num = num % den;
2495 if (num < 0) {
2496 num += den;
2497 f->val--;
2498 }
2499 } else if (num >= den) {
2500 f->val += num / den;
2501 num = num % den;
2502 }
2503 f->num = num;
2504}
87a0a681
FB
2505
2506/**
2507 * register a new image format
2508 * @param img_fmt Image format descriptor
2509 */
2510void av_register_image_format(AVImageFormat *img_fmt)
2511{
2512 AVImageFormat **p;
2513
2514 p = &first_image_format;
2515 while (*p != NULL) p = &(*p)->next;
2516 *p = img_fmt;
2517 img_fmt->next = NULL;
2518}
2519
2520/* guess image format */
2521AVImageFormat *av_probe_image_format(AVProbeData *pd)
2522{
2523 AVImageFormat *fmt1, *fmt;
2524 int score, score_max;
2525
2526 fmt = NULL;
2527 score_max = 0;
2528 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2529 if (fmt1->img_probe) {
2530 score = fmt1->img_probe(pd);
2531 if (score > score_max) {
2532 score_max = score;
2533 fmt = fmt1;
2534 }
2535 }
2536 }
2537 return fmt;
2538}
2539
2540AVImageFormat *guess_image_format(const char *filename)
2541{
2542 AVImageFormat *fmt1;
2543
2544 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2545 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
2546 return fmt1;
2547 }
2548 return NULL;
2549}
2550
2551/**
2552 * Read an image from a stream.
2553 * @param gb byte stream containing the image
2554 * @param fmt image format, NULL if probing is required
2555 */
2556int av_read_image(ByteIOContext *pb, const char *filename,
2557 AVImageFormat *fmt,
2558 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
2559{
2560 char buf[PROBE_BUF_SIZE];
2561 AVProbeData probe_data, *pd = &probe_data;
2562 offset_t pos;
2563 int ret;
2564
2565 if (!fmt) {
5c91a675 2566 pd->filename = filename;
87a0a681
FB
2567 pd->buf = buf;
2568 pos = url_ftell(pb);
2569 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
2570 url_fseek(pb, pos, SEEK_SET);
2571 fmt = av_probe_image_format(pd);
2572 }
2573 if (!fmt)
2574 return AVERROR_NOFMT;
2575 ret = fmt->img_read(pb, alloc_cb, opaque);
2576 return ret;
2577}
2578
2579/**
2580 * Write an image to a stream.
2581 * @param pb byte stream for the image output
2582 * @param fmt image format
2583 * @param img image data and informations
2584 */
2585int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
2586{
2587 return fmt->img_write(pb, img);
2588}
2589