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