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