Right fix for older zlib version
[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;
37353960 661 int len, ret, i;
fb2758c8
FB
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) {
fb2758c8 675 len = av_parser_parse(st->parser, &st->codec, &pkt->data, &pkt->size,
6ec87caa
FB
676 s->cur_ptr, s->cur_len,
677 s->cur_pkt.pts, s->cur_pkt.dts);
678 s->cur_pkt.pts = AV_NOPTS_VALUE;
679 s->cur_pkt.dts = AV_NOPTS_VALUE;
fb2758c8
FB
680 /* increment read pointer */
681 s->cur_ptr += len;
682 s->cur_len -= len;
683
684 /* return packet if any */
685 if (pkt->size) {
37353960 686 got_packet:
fb2758c8
FB
687 pkt->duration = 0;
688 pkt->stream_index = st->index;
6ec87caa
FB
689 pkt->pts = st->parser->pts;
690 pkt->dts = st->parser->dts;
fb2758c8
FB
691 pkt->destruct = av_destruct_packet_nofree;
692 compute_pkt_fields(s, st, st->parser, pkt);
fb2758c8
FB
693 return 0;
694 }
695 } else {
bcbecff1
FB
696 /* free packet */
697 av_free_packet(&s->cur_pkt);
fb2758c8
FB
698 s->cur_st = NULL;
699 }
700 } else {
fb2758c8
FB
701 /* read next packet */
702 ret = av_read_packet(s, &s->cur_pkt);
37353960
FB
703 if (ret < 0) {
704 if (ret == -EAGAIN)
705 return ret;
706 /* return the last frames, if any */
707 for(i = 0; i < s->nb_streams; i++) {
708 st = s->streams[i];
709 if (st->parser) {
710 av_parser_parse(st->parser, &st->codec,
711 &pkt->data, &pkt->size,
6ec87caa
FB
712 NULL, 0,
713 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
37353960
FB
714 if (pkt->size)
715 goto got_packet;
716 }
717 }
718 /* no more packets: really terminates parsing */
fb2758c8 719 return ret;
37353960 720 }
fb2758c8
FB
721
722 /* convert the packet time stamp units and handle wrapping */
723 s->cur_pkt.pts = convert_timestamp_units(s,
724 &s->last_pkt_pts, &s->last_pkt_pts_frac,
725 &s->last_pkt_stream_pts,
726 s->cur_pkt.pts);
727 s->cur_pkt.dts = convert_timestamp_units(s,
728 &s->last_pkt_dts, &s->last_pkt_dts_frac,
729 &s->last_pkt_stream_dts,
730 s->cur_pkt.dts);
731#if 0
6ec87caa 732 if (s->cur_pkt.stream_index == 0) {
fb2758c8
FB
733 if (s->cur_pkt.pts != AV_NOPTS_VALUE)
734 printf("PACKET pts=%0.3f\n",
735 (double)s->cur_pkt.pts / AV_TIME_BASE);
736 if (s->cur_pkt.dts != AV_NOPTS_VALUE)
737 printf("PACKET dts=%0.3f\n",
738 (double)s->cur_pkt.dts / AV_TIME_BASE);
739 }
740#endif
741
742 /* duration field */
743 if (s->cur_pkt.duration != 0) {
744 s->cur_pkt.duration = ((int64_t)s->cur_pkt.duration * AV_TIME_BASE * s->pts_num) /
745 s->pts_den;
746 }
747
748 st = s->streams[s->cur_pkt.stream_index];
749 s->cur_st = st;
750 s->cur_ptr = s->cur_pkt.data;
751 s->cur_len = s->cur_pkt.size;
752 if (st->need_parsing && !st->parser) {
753 st->parser = av_parser_init(st->codec.codec_id);
754 if (!st->parser) {
755 /* no parser available : just output the raw packets */
756 st->need_parsing = 0;
757 }
758 }
759 }
760 }
761}
762
763/**
764 * Return the next frame of a stream. The returned packet is valid
765 * until the next av_read_frame() or until av_close_input_file() and
766 * must be freed with av_free_packet. For video, the packet contains
767 * exactly one frame. For audio, it contains an integer number of
768 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
769 * data). If the audio frames have a variable size (e.g. MPEG audio),
770 * then it contains one frame.
771 *
772 * pkt->pts, pkt->dts and pkt->duration are always set to correct
773 * values in AV_TIME_BASE unit (and guessed if the format cannot
774 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
775 * has B frames, so it is better to rely on pkt->dts if you do not
776 * decompress the payload.
777 *
778 * Return 0 if OK, < 0 if error or end of file.
779 */
780int av_read_frame(AVFormatContext *s, AVPacket *pkt)
781{
de6d9b64
FB
782 AVPacketList *pktl;
783
784 pktl = s->packet_buffer;
785 if (pktl) {
786 /* read packet from packet buffer, if there is data */
787 *pkt = pktl->pkt;
788 s->packet_buffer = pktl->next;
1ea4f593 789 av_free(pktl);
de6d9b64
FB
790 return 0;
791 } else {
fb2758c8
FB
792 return av_read_frame_internal(s, pkt);
793 }
794}
795
796/* XXX: suppress the packet queue */
797static void flush_packet_queue(AVFormatContext *s)
798{
799 AVPacketList *pktl;
800
801 for(;;) {
802 pktl = s->packet_buffer;
803 if (!pktl)
804 break;
805 s->packet_buffer = pktl->next;
806 av_free_packet(&pktl->pkt);
807 av_free(pktl);
b9a281db
FB
808 }
809}
810
da24c5e3 811/*******************************************************/
fb2758c8
FB
812/* seek support */
813
814/* flush the frame reader */
815static void av_read_frame_flush(AVFormatContext *s)
816{
817 AVStream *st;
818 int i;
819
820 flush_packet_queue(s);
821
822 /* free previous packet */
823 if (s->cur_st) {
824 if (s->cur_st->parser)
825 av_free_packet(&s->cur_pkt);
826 s->cur_st = NULL;
827 }
828 /* fail safe */
829 s->cur_ptr = NULL;
830 s->cur_len = 0;
831
832 /* for each stream, reset read state */
833 for(i = 0; i < s->nb_streams; i++) {
834 st = s->streams[i];
835
836 if (st->parser) {
837 av_parser_close(st->parser);
838 st->parser = NULL;
839 }
fb2758c8
FB
840 st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
841 }
842}
843
844static void add_index_entry(AVStream *st,
845 int64_t pos, int64_t timestamp, int flags)
846{
847 AVIndexEntry *entries, *ie;
848
849 entries = av_fast_realloc(st->index_entries,
850 &st->index_entries_allocated_size,
851 (st->nb_index_entries + 1) *
852 sizeof(AVIndexEntry));
853 if (entries) {
854 st->index_entries = entries;
855 ie = &entries[st->nb_index_entries++];
856 ie->pos = pos;
857 ie->timestamp = timestamp;
858 ie->flags = flags;
859 }
860}
861
862/* build an index for raw streams using a parser */
863static void av_build_index_raw(AVFormatContext *s)
864{
865 AVPacket pkt1, *pkt = &pkt1;
866 int ret;
867 AVStream *st;
868
869 st = s->streams[0];
870 av_read_frame_flush(s);
871 url_fseek(&s->pb, s->data_offset, SEEK_SET);
872
873 for(;;) {
874 ret = av_read_frame(s, pkt);
875 if (ret < 0)
876 break;
877 if (pkt->stream_index == 0 && st->parser &&
878 (pkt->flags & PKT_FLAG_KEY)) {
879 add_index_entry(st, st->parser->frame_offset, pkt->dts,
880 AVINDEX_KEYFRAME);
881 }
882 av_free_packet(pkt);
883 }
884}
885
886/* return TRUE if we deal with a raw stream (raw codec data and
887 parsing needed) */
888static int is_raw_stream(AVFormatContext *s)
889{
890 AVStream *st;
891
892 if (s->nb_streams != 1)
893 return 0;
894 st = s->streams[0];
895 if (!st->need_parsing)
896 return 0;
897 return 1;
898}
899
900/* return the largest index entry whose timestamp is <=
901 wanted_timestamp */
902static int index_search_timestamp(AVIndexEntry *entries,
903 int nb_entries, int wanted_timestamp)
904{
905 int a, b, m;
906 int64_t timestamp;
907
908 if (nb_entries <= 0)
909 return -1;
910
911 a = 0;
912 b = nb_entries - 1;
913 while (a <= b) {
914 m = (a + b) >> 1;
915 timestamp = entries[m].timestamp;
916 if (timestamp == wanted_timestamp)
917 goto found;
918 else if (timestamp > wanted_timestamp) {
919 b = m - 1;
920 } else {
921 a = m + 1;
922 }
923 }
924 m = a;
925 if (m > 0)
926 m--;
927 found:
928 return m;
929}
930
931static int av_seek_frame_generic(AVFormatContext *s,
932 int stream_index, int64_t timestamp)
933{
934 int index;
935 AVStream *st;
936 AVIndexEntry *ie;
937
938 if (!s->index_built) {
939 if (is_raw_stream(s)) {
940 av_build_index_raw(s);
941 } else {
942 return -1;
943 }
944 s->index_built = 1;
945 }
946
947 if (stream_index < 0)
948 stream_index = 0;
949 st = s->streams[stream_index];
950 index = index_search_timestamp(st->index_entries, st->nb_index_entries,
951 timestamp);
952 if (index < 0)
953 return -1;
954
955 /* now we have found the index, we can seek */
956 ie = &st->index_entries[index];
957 av_read_frame_flush(s);
958 url_fseek(&s->pb, ie->pos, SEEK_SET);
959 st->cur_dts = ie->timestamp;
960 return 0;
961}
962
963/**
964 * Seek to the key frame just before the frame at timestamp
965 * 'timestamp' in 'stream_index'. If stream_index is (-1), a default
966 * stream is selected
967 */
968int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp)
969{
970 int ret;
971
972 av_read_frame_flush(s);
973
974 /* first, we try the format specific seek */
975 if (s->iformat->read_seek)
976 ret = s->iformat->read_seek(s, stream_index, timestamp);
977 else
978 ret = -1;
979 if (ret >= 0) {
980 return 0;
981 }
982
983 return av_seek_frame_generic(s, stream_index, timestamp);
984}
985
986/*******************************************************/
12f996ed
FB
987
988/* return TRUE if the stream has accurate timings for at least one component */
989static int av_has_timings(AVFormatContext *ic)
990{
991 int i;
992 AVStream *st;
993
994 for(i = 0;i < ic->nb_streams; i++) {
995 st = ic->streams[i];
996 if (st->start_time != AV_NOPTS_VALUE &&
997 st->duration != AV_NOPTS_VALUE)
998 return 1;
999 }
1000 return 0;
1001}
1002
1003/* estimate the stream timings from the one of each components. Also
1004 compute the global bitrate if possible */
1005static void av_update_stream_timings(AVFormatContext *ic)
1006{
1007 int64_t start_time, end_time, end_time1;
1008 int i;
1009 AVStream *st;
1010
1011 start_time = MAXINT64;
1012 end_time = MININT64;
1013 for(i = 0;i < ic->nb_streams; i++) {
1014 st = ic->streams[i];
1015 if (st->start_time != AV_NOPTS_VALUE) {
1016 if (st->start_time < start_time)
1017 start_time = st->start_time;
1018 if (st->duration != AV_NOPTS_VALUE) {
1019 end_time1 = st->start_time + st->duration;
1020 if (end_time1 > end_time)
1021 end_time = end_time1;
1022 }
1023 }
1024 }
1025 if (start_time != MAXINT64) {
1026 ic->start_time = start_time;
1027 if (end_time != MAXINT64) {
1028 ic->duration = end_time - start_time;
1029 if (ic->file_size > 0) {
1030 /* compute the bit rate */
1031 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1032 (double)ic->duration;
1033 }
1034 }
1035 }
1036
1037}
1038
1039static void fill_all_stream_timings(AVFormatContext *ic)
1040{
1041 int i;
1042 AVStream *st;
1043
1044 av_update_stream_timings(ic);
1045 for(i = 0;i < ic->nb_streams; i++) {
1046 st = ic->streams[i];
1047 if (st->start_time == AV_NOPTS_VALUE) {
1048 st->start_time = ic->start_time;
1049 st->duration = ic->duration;
1050 }
1051 }
1052}
1053
1054static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1055{
1056 int64_t filesize, duration;
1057 int bit_rate, i;
1058 AVStream *st;
1059
1060 /* if bit_rate is already set, we believe it */
1061 if (ic->bit_rate == 0) {
1062 bit_rate = 0;
1063 for(i=0;i<ic->nb_streams;i++) {
1064 st = ic->streams[i];
1065 bit_rate += st->codec.bit_rate;
1066 }
1067 ic->bit_rate = bit_rate;
1068 }
1069
1070 /* if duration is already set, we believe it */
1071 if (ic->duration == AV_NOPTS_VALUE &&
1072 ic->bit_rate != 0 &&
1073 ic->file_size != 0) {
1074 filesize = ic->file_size;
1075 if (filesize > 0) {
1076 duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
1077 for(i = 0; i < ic->nb_streams; i++) {
1078 st = ic->streams[i];
1079 if (st->start_time == AV_NOPTS_VALUE ||
1080 st->duration == AV_NOPTS_VALUE) {
1081 st->start_time = 0;
1082 st->duration = duration;
1083 }
1084 }
1085 }
1086 }
1087}
1088
12f996ed
FB
1089#define DURATION_MAX_READ_SIZE 250000
1090
1091/* only usable for MPEG-PS streams */
1092static void av_estimate_timings_from_pts(AVFormatContext *ic)
1093{
1094 AVPacket pkt1, *pkt = &pkt1;
1095 AVStream *st;
1096 int read_size, i, ret;
1097 int64_t start_time, end_time, end_time1;
1098 int64_t filesize, offset, duration;
1099
fb2758c8
FB
1100 /* free previous packet */
1101 if (ic->cur_st && ic->cur_st->parser)
1102 av_free_packet(&ic->cur_pkt);
1103 ic->cur_st = NULL;
1104
1105 /* flush packet queue */
1106 flush_packet_queue(ic);
1107
1108
12f996ed
FB
1109 /* we read the first packets to get the first PTS (not fully
1110 accurate, but it is enough now) */
1111 url_fseek(&ic->pb, 0, SEEK_SET);
1112 read_size = 0;
1113 for(;;) {
1114 if (read_size >= DURATION_MAX_READ_SIZE)
1115 break;
1116 /* if all info is available, we can stop */
1117 for(i = 0;i < ic->nb_streams; i++) {
1118 st = ic->streams[i];
1119 if (st->start_time == AV_NOPTS_VALUE)
1120 break;
1121 }
1122 if (i == ic->nb_streams)
1123 break;
1124
1125 ret = av_read_packet(ic, pkt);
1126 if (ret != 0)
1127 break;
1128 read_size += pkt->size;
1129 st = ic->streams[pkt->stream_index];
1130 if (pkt->pts != AV_NOPTS_VALUE) {
1131 if (st->start_time == AV_NOPTS_VALUE)
1132 st->start_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
0a5f92a1
MN
1133 }
1134 av_free_packet(pkt);
1135 }
12f996ed
FB
1136
1137 /* we compute the minimum start_time and use it as default */
1138 start_time = MAXINT64;
1139 for(i = 0; i < ic->nb_streams; i++) {
1140 st = ic->streams[i];
1141 if (st->start_time != AV_NOPTS_VALUE &&
1142 st->start_time < start_time)
1143 start_time = st->start_time;
1144 }
12f996ed
FB
1145 if (start_time != MAXINT64)
1146 ic->start_time = start_time;
1147
1148 /* estimate the end time (duration) */
1149 /* XXX: may need to support wrapping */
1150 filesize = ic->file_size;
1151 offset = filesize - DURATION_MAX_READ_SIZE;
1152 if (offset < 0)
1153 offset = 0;
1154
12f996ed
FB
1155 url_fseek(&ic->pb, offset, SEEK_SET);
1156 read_size = 0;
1157 for(;;) {
1158 if (read_size >= DURATION_MAX_READ_SIZE)
1159 break;
1160 /* if all info is available, we can stop */
1161 for(i = 0;i < ic->nb_streams; i++) {
1162 st = ic->streams[i];
1163 if (st->duration == AV_NOPTS_VALUE)
1164 break;
1165 }
1166 if (i == ic->nb_streams)
1167 break;
1168
1169 ret = av_read_packet(ic, pkt);
1170 if (ret != 0)
1171 break;
1172 read_size += pkt->size;
1173 st = ic->streams[pkt->stream_index];
1174 if (pkt->pts != AV_NOPTS_VALUE) {
1175 end_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
1176 duration = end_time - st->start_time;
1177 if (duration > 0) {
1178 if (st->duration == AV_NOPTS_VALUE ||
1179 st->duration < duration)
1180 st->duration = duration;
1181 }
1182 }
1183 av_free_packet(pkt);
1184 }
1185
1186 /* estimate total duration */
1187 end_time = MININT64;
1188 for(i = 0;i < ic->nb_streams; i++) {
1189 st = ic->streams[i];
1190 if (st->duration != AV_NOPTS_VALUE) {
1191 end_time1 = st->start_time + st->duration;
1192 if (end_time1 > end_time)
1193 end_time = end_time1;
1194 }
1195 }
1196
1197 /* update start_time (new stream may have been created, so we do
1198 it at the end */
1199 if (ic->start_time != AV_NOPTS_VALUE) {
1200 for(i = 0; i < ic->nb_streams; i++) {
1201 st = ic->streams[i];
1202 if (st->start_time == AV_NOPTS_VALUE)
1203 st->start_time = ic->start_time;
1204 }
1205 }
1206
1207 if (end_time != MININT64) {
1208 /* put dummy values for duration if needed */
1209 for(i = 0;i < ic->nb_streams; i++) {
1210 st = ic->streams[i];
1211 if (st->duration == AV_NOPTS_VALUE &&
1212 st->start_time != AV_NOPTS_VALUE)
1213 st->duration = end_time - st->start_time;
1214 }
1215 ic->duration = end_time - ic->start_time;
1216 }
1217
1218 url_fseek(&ic->pb, 0, SEEK_SET);
1219}
1220
1221static void av_estimate_timings(AVFormatContext *ic)
1222{
1223 URLContext *h;
1224 int64_t file_size;
1225
1226 /* get the file size, if possible */
1227 if (ic->iformat->flags & AVFMT_NOFILE) {
1228 file_size = 0;
1229 } else {
1230 h = url_fileno(&ic->pb);
1231 file_size = url_filesize(h);
1232 if (file_size < 0)
1233 file_size = 0;
1234 }
1235 ic->file_size = file_size;
1236
1237 if (ic->iformat == &mpegps_demux) {
1238 /* get accurate estimate from the PTSes */
1239 av_estimate_timings_from_pts(ic);
1240 } else if (av_has_timings(ic)) {
1241 /* at least one components has timings - we use them for all
1242 the components */
1243 fill_all_stream_timings(ic);
1244 } else {
1245 /* less precise: use bit rate info */
1246 av_estimate_timings_from_bit_rate(ic);
1247 }
1248 av_update_stream_timings(ic);
1249
1250#if 0
1251 {
1252 int i;
1253 AVStream *st;
1254 for(i = 0;i < ic->nb_streams; i++) {
1255 st = ic->streams[i];
1256 printf("%d: start_time: %0.3f duration: %0.3f\n",
1257 i, (double)st->start_time / AV_TIME_BASE,
1258 (double)st->duration / AV_TIME_BASE);
1259 }
1260 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1261 (double)ic->start_time / AV_TIME_BASE,
1262 (double)ic->duration / AV_TIME_BASE,
1263 ic->bit_rate / 1000);
1264 }
1265#endif
1266}
1267
b9a281db
FB
1268static int has_codec_parameters(AVCodecContext *enc)
1269{
1270 int val;
1271 switch(enc->codec_type) {
1272 case CODEC_TYPE_AUDIO:
1273 val = enc->sample_rate;
1274 break;
1275 case CODEC_TYPE_VIDEO:
1276 val = enc->width;
1277 break;
1278 default:
1279 val = 1;
1280 break;
1281 }
1282 return (val != 0);
1283}
1284
fb2758c8
FB
1285static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1286{
1287 int16_t *samples;
1288 AVCodec *codec;
1289 int got_picture, ret;
1290 AVFrame picture;
1291
1292 codec = avcodec_find_decoder(st->codec.codec_id);
1293 if (!codec)
1294 return -1;
1295 ret = avcodec_open(&st->codec, codec);
1296 if (ret < 0)
1297 return ret;
1298 switch(st->codec.codec_type) {
1299 case CODEC_TYPE_VIDEO:
1300 ret = avcodec_decode_video(&st->codec, &picture,
1301 &got_picture, (uint8_t *)data, size);
1302 break;
1303 case CODEC_TYPE_AUDIO:
1304 samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1305 if (!samples)
1306 goto fail;
1307 ret = avcodec_decode_audio(&st->codec, samples,
1308 &got_picture, (uint8_t *)data, size);
1309 av_free(samples);
1310 break;
1311 default:
1312 break;
1313 }
1314 fail:
1315 avcodec_close(&st->codec);
1316 return ret;
1317}
1318
1319/* absolute maximum size we read until we abort */
1320#define MAX_READ_SIZE 5000000
1321
1322/* maximum duration until we stop analysing the stream */
1323#define MAX_STREAM_DURATION ((int)(AV_TIME_BASE * 1.0))
1324
b9a281db
FB
1325/**
1326 * Read the beginning of a media file to get stream information. This
1327 * is useful for file formats with no headers such as MPEG. This
1328 * function also compute the real frame rate in case of mpeg2 repeat
1329 * frame mode.
1330 *
1331 * @param ic media file handle
1332 * @return >=0 if OK. AVERROR_xxx if error.
1333 */
1334int av_find_stream_info(AVFormatContext *ic)
1335{
fb2758c8 1336 int i, count, ret, read_size;
b9a281db 1337 AVStream *st;
fb2758c8 1338 AVPacket pkt1, *pkt;
b9a281db 1339 AVPacketList *pktl=NULL, **ppktl;
b9a281db
FB
1340
1341 count = 0;
1342 read_size = 0;
1343 ppktl = &ic->packet_buffer;
1344 for(;;) {
1345 /* check if one codec still needs to be handled */
1346 for(i=0;i<ic->nb_streams;i++) {
1347 st = ic->streams[i];
fb2758c8 1348 if (!has_codec_parameters(&st->codec))
b9a281db
FB
1349 break;
1350 }
1351 if (i == ic->nb_streams) {
1352 /* NOTE: if the format has no header, then we need to read
1353 some packets to get most of the streams, so we cannot
1354 stop here */
fb2758c8 1355 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
b9a281db
FB
1356 /* if we found the info for all the codecs, we can stop */
1357 ret = count;
1358 break;
1359 }
1360 } else {
1361 /* we did not get all the codec info, but we read too much data */
fb2758c8 1362 if (read_size >= MAX_READ_SIZE) {
b9a281db
FB
1363 ret = count;
1364 break;
1365 }
1366 }
1367
fb2758c8
FB
1368 /* NOTE: a new stream can be added there if no header in file
1369 (AVFMTCTX_NOHEADER) */
1370 ret = av_read_frame_internal(ic, &pkt1);
1371 if (ret < 0) {
1372 /* EOF or error */
1373 ret = -1; /* we could not have all the codec parameters before EOF */
1374 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
1375 i == ic->nb_streams)
1376 ret = 0;
1377 break;
1378 }
1379
b9a281db
FB
1380 pktl = av_mallocz(sizeof(AVPacketList));
1381 if (!pktl) {
1382 ret = AVERROR_NOMEM;
1383 break;
1384 }
1385
1386 /* add the packet in the buffered packet list */
1387 *ppktl = pktl;
1388 ppktl = &pktl->next;
1389
b9a281db 1390 pkt = &pktl->pkt;
fb2758c8
FB
1391 *pkt = pkt1;
1392
1393 /* duplicate the packet */
1394 if (av_dup_packet(pkt) < 0) {
1395 ret = AVERROR_NOMEM;
1396 break;
b9a281db 1397 }
b9a281db 1398
fb2758c8 1399 read_size += pkt->size;
b9a281db
FB
1400
1401 st = ic->streams[pkt->stream_index];
fb2758c8
FB
1402 st->codec_info_duration += pkt->duration;
1403 if (pkt->duration != 0)
1404 st->codec_info_nb_frames++;
1405
1406 /* if still no information, we try to open the codec and to
1407 decompress the frame. We try to avoid that in most cases as
1408 it takes longer and uses more memory. For MPEG4, we need to
1409 decompress for Quicktime. */
1410 if (!has_codec_parameters(&st->codec) &&
1411 (st->codec.codec_id == CODEC_ID_FLV1 ||
1412 st->codec.codec_id == CODEC_ID_H264 ||
1413 st->codec.codec_id == CODEC_ID_H263 ||
1414 (st->codec.codec_id == CODEC_ID_MPEG4 && !st->need_parsing)))
1415 try_decode_frame(st, pkt->data, pkt->size);
1416
1417 if (st->codec_info_duration >= MAX_STREAM_DURATION) {
1418 break;
b9a281db
FB
1419 }
1420 count++;
1421 }
1422
b9a281db
FB
1423 /* set real frame rate info */
1424 for(i=0;i<ic->nb_streams;i++) {
1425 st = ic->streams[i];
1426 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
fb2758c8
FB
1427 /* compute the real frame rate for telecine */
1428 if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
1429 st->codec.codec_id == CODEC_ID_MPEG2VIDEO) &&
1430 st->codec.sub_id == 2) {
1431 if (st->codec_info_nb_frames >= 20) {
1432 float coded_frame_rate, est_frame_rate;
1433 est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
1434 (double)st->codec_info_duration ;
1435 coded_frame_rate = (double)st->codec.frame_rate /
1436 (double)st->codec.frame_rate_base;
1437#if 0
1438 printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
1439 coded_frame_rate, est_frame_rate);
1440#endif
1441 /* if we detect that it could be a telecine, we
1442 signal it. It would be better to do it at a
1443 higher level as it can change in a film */
1444 if (coded_frame_rate >= 24.97 &&
1445 (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
1446 st->r_frame_rate = 24024;
1447 st->r_frame_rate_base = 1001;
1448 }
1449 }
1450 }
1451 /* if no real frame rate, use the codec one */
14bea432
MN
1452 if (!st->r_frame_rate){
1453 st->r_frame_rate = st->codec.frame_rate;
1454 st->r_frame_rate_base = st->codec.frame_rate_base;
1455 }
b9a281db 1456 }
de6d9b64 1457 }
b9a281db 1458
12f996ed 1459 av_estimate_timings(ic);
b9a281db 1460 return ret;
de6d9b64
FB
1461}
1462
fb2758c8
FB
1463/*******************************************************/
1464
1465/**
1466 * start playing a network based stream (e.g. RTSP stream) at the
1467 * current position
1468 */
1469int av_read_play(AVFormatContext *s)
1470{
1471 if (!s->iformat->read_play)
1472 return AVERROR_NOTSUPP;
1473 return s->iformat->read_play(s);
1474}
1475
1476/**
1477 * pause a network based stream (e.g. RTSP stream). Use av_read_play()
1478 * to resume it.
1479 */
1480int av_read_pause(AVFormatContext *s)
1481{
1482 if (!s->iformat->read_pause)
1483 return AVERROR_NOTSUPP;
1484 return s->iformat->read_pause(s);
1485}
1486
b9a281db
FB
1487/**
1488 * Close a media file (but not its codecs)
1489 *
1490 * @param s media file handle
1491 */
de6d9b64
FB
1492void av_close_input_file(AVFormatContext *s)
1493{
b6892136 1494 int i, must_open_file;
da24c5e3 1495 AVStream *st;
de6d9b64 1496
fb2758c8
FB
1497 /* free previous packet */
1498 if (s->cur_st && s->cur_st->parser)
1499 av_free_packet(&s->cur_pkt);
1500
b9a281db
FB
1501 if (s->iformat->read_close)
1502 s->iformat->read_close(s);
de6d9b64 1503 for(i=0;i<s->nb_streams;i++) {
da24c5e3
FB
1504 /* free all data in a stream component */
1505 st = s->streams[i];
fb2758c8
FB
1506 if (st->parser) {
1507 av_parser_close(st->parser);
de6d9b64 1508 }
fb2758c8
FB
1509 av_free(st->index_entries);
1510 av_free(st);
de6d9b64 1511 }
fb2758c8 1512 flush_packet_queue(s);
b6892136 1513 must_open_file = 1;
da24c5e3 1514 if (s->iformat->flags & AVFMT_NOFILE) {
b6892136
FB
1515 must_open_file = 0;
1516 }
1517 if (must_open_file) {
96baaa6a
FB
1518 url_fclose(&s->pb);
1519 }
a8dbe951 1520 av_freep(&s->priv_data);
1ea4f593 1521 av_free(s);
de6d9b64
FB
1522}
1523
b9a281db
FB
1524/**
1525 * Add a new stream to a media file. Can only be called in the
da24c5e3
FB
1526 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
1527 * format context, then new streams can be added in read_packet too.
b9a281db
FB
1528 *
1529 *
1530 * @param s media file handle
da24c5e3 1531 * @param id file format dependent stream id
b9a281db
FB
1532 */
1533AVStream *av_new_stream(AVFormatContext *s, int id)
1534{
1535 AVStream *st;
1536
1537 if (s->nb_streams >= MAX_STREAMS)
1538 return NULL;
1539
1540 st = av_mallocz(sizeof(AVStream));
1541 if (!st)
1542 return NULL;
1e491e29 1543 avcodec_get_context_defaults(&st->codec);
48091512
FB
1544 if (s->iformat) {
1545 /* no default bitrate if decoding */
1546 st->codec.bit_rate = 0;
1547 }
b9a281db
FB
1548 st->index = s->nb_streams;
1549 st->id = id;
12f996ed
FB
1550 st->start_time = AV_NOPTS_VALUE;
1551 st->duration = AV_NOPTS_VALUE;
b9a281db
FB
1552 s->streams[s->nb_streams++] = st;
1553 return st;
1554}
1555
1556/************************************************************/
1557/* output media file */
de6d9b64 1558
87a0a681
FB
1559int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1560{
1561 int ret;
98486a6b
RS
1562
1563 if (s->oformat->priv_data_size > 0) {
1564 s->priv_data = av_mallocz(s->oformat->priv_data_size);
1565 if (!s->priv_data)
1566 return AVERROR_NOMEM;
1567 } else
1568 s->priv_data = NULL;
1569
87a0a681
FB
1570 if (s->oformat->set_parameters) {
1571 ret = s->oformat->set_parameters(s, ap);
1572 if (ret < 0)
1573 return ret;
1574 }
1575 return 0;
1576}
1577
b9a281db
FB
1578/**
1579 * allocate the stream private data and write the stream header to an
1580 * output media file
1581 *
1582 * @param s media file handle
1583 * @return 0 if OK. AVERROR_xxx if error.
1584 */
1585int av_write_header(AVFormatContext *s)
1586{
1e51d801
FB
1587 int ret, i;
1588 AVStream *st;
1589
916c80e9
FB
1590 /* default pts settings is MPEG like */
1591 av_set_pts_info(s, 33, 1, 90000);
1e51d801
FB
1592 ret = s->oformat->write_header(s);
1593 if (ret < 0)
1594 return ret;
1595
1596 /* init PTS generation */
1597 for(i=0;i<s->nb_streams;i++) {
1598 st = s->streams[i];
1599
1600 switch (st->codec.codec_type) {
1601 case CODEC_TYPE_AUDIO:
1602 av_frac_init(&st->pts, 0, 0,
0c1a9eda 1603 (int64_t)s->pts_num * st->codec.sample_rate);
1e51d801
FB
1604 break;
1605 case CODEC_TYPE_VIDEO:
1606 av_frac_init(&st->pts, 0, 0,
0c1a9eda 1607 (int64_t)s->pts_num * st->codec.frame_rate);
1e51d801
FB
1608 break;
1609 default:
1610 break;
1611 }
1612 }
1613 return 0;
b9a281db
FB
1614}
1615
1616/**
1e51d801
FB
1617 * Write a packet to an output media file. The packet shall contain
1618 * one audio or video frame.
b9a281db
FB
1619 *
1620 * @param s media file handle
1e51d801
FB
1621 * @param stream_index stream index
1622 * @param buf buffer containing the frame data
1623 * @param size size of buffer
d4c0ff91 1624 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
b9a281db 1625 */
1e51d801
FB
1626int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf,
1627 int size)
de6d9b64 1628{
1e51d801 1629 AVStream *st;
0c1a9eda 1630 int64_t pts_mask;
7feb950a 1631 int ret, frame_size;
1e51d801
FB
1632
1633 st = s->streams[stream_index];
1634 pts_mask = (1LL << s->pts_wrap_bits) - 1;
fb2758c8 1635 ret = s->oformat->write_packet(s, stream_index, buf, size,
1e51d801
FB
1636 st->pts.val & pts_mask);
1637 if (ret < 0)
1638 return ret;
1639
1640 /* update pts */
1641 switch (st->codec.codec_type) {
1642 case CODEC_TYPE_AUDIO:
fb2758c8
FB
1643 frame_size = get_audio_frame_size(&st->codec, size);
1644 if (frame_size >= 0) {
1645 av_frac_add(&st->pts,
1646 (int64_t)s->pts_den * frame_size);
7feb950a 1647 }
1e51d801
FB
1648 break;
1649 case CODEC_TYPE_VIDEO:
1650 av_frac_add(&st->pts,
14bea432 1651 (int64_t)s->pts_den * st->codec.frame_rate_base);
1e51d801
FB
1652 break;
1653 default:
1654 break;
1655 }
d4c0ff91 1656 return ret;
b9a281db
FB
1657}
1658
1659/**
1660 * write the stream trailer to an output media file and and free the
1661 * file private data.
1662 *
1663 * @param s media file handle
1664 * @return 0 if OK. AVERROR_xxx if error. */
1665int av_write_trailer(AVFormatContext *s)
1666{
1667 int ret;
1668 ret = s->oformat->write_trailer(s);
1669 av_freep(&s->priv_data);
1670 return ret;
de6d9b64
FB
1671}
1672
1673/* "user interface" functions */
1674
1675void dump_format(AVFormatContext *ic,
1676 int index,
1677 const char *url,
1678 int is_output)
1679{
b9a281db 1680 int i, flags;
de6d9b64
FB
1681 char buf[256];
1682
1683 fprintf(stderr, "%s #%d, %s, %s '%s':\n",
1684 is_output ? "Output" : "Input",
b9a281db
FB
1685 index,
1686 is_output ? ic->oformat->name : ic->iformat->name,
de6d9b64 1687 is_output ? "to" : "from", url);
12f996ed 1688 if (!is_output) {
c9245417 1689 fprintf(stderr, " Duration: ");
12f996ed
FB
1690 if (ic->duration != AV_NOPTS_VALUE) {
1691 int hours, mins, secs, us;
1692 secs = ic->duration / AV_TIME_BASE;
1693 us = ic->duration % AV_TIME_BASE;
1694 mins = secs / 60;
1695 secs %= 60;
1696 hours = mins / 60;
1697 mins %= 60;
c9245417 1698 fprintf(stderr, "%02d:%02d:%02d.%01d", hours, mins, secs,
12f996ed
FB
1699 (10 * us) / AV_TIME_BASE);
1700 } else {
c9245417 1701 fprintf(stderr, "N/A");
12f996ed 1702 }
c9245417 1703 fprintf(stderr, ", bitrate: ");
12f996ed 1704 if (ic->bit_rate) {
c9245417 1705 fprintf(stderr,"%d kb/s", ic->bit_rate / 1000);
12f996ed 1706 } else {
c9245417 1707 fprintf(stderr, "N/A");
12f996ed 1708 }
c9245417 1709 fprintf(stderr, "\n");
12f996ed 1710 }
de6d9b64
FB
1711 for(i=0;i<ic->nb_streams;i++) {
1712 AVStream *st = ic->streams[i];
1713 avcodec_string(buf, sizeof(buf), &st->codec, is_output);
b9a281db
FB
1714 fprintf(stderr, " Stream #%d.%d", index, i);
1715 /* the pid is an important information, so we display it */
1716 /* XXX: add a generic system */
1717 if (is_output)
1718 flags = ic->oformat->flags;
1719 else
1720 flags = ic->iformat->flags;
1721 if (flags & AVFMT_SHOW_IDS) {
1722 fprintf(stderr, "[0x%x]", st->id);
1723 }
1724 fprintf(stderr, ": %s\n", buf);
de6d9b64
FB
1725 }
1726}
1727
1728typedef struct {
445f1b83 1729 const char *abv;
de6d9b64 1730 int width, height;
445f1b83
RS
1731 int frame_rate, frame_rate_base;
1732} AbvEntry;
1733
1734static AbvEntry frame_abvs[] = {
ba2a8cb4
RS
1735 { "ntsc", 720, 480, 30000, 1001 },
1736 { "pal", 720, 576, 25, 1 },
1737 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
1738 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
904736b5
RS
1739 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
1740 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
445f1b83
RS
1741 { "film", 352, 240, 24, 1 },
1742 { "ntsc-film", 352, 240, 24000, 1001 },
1743 { "sqcif", 128, 96, 0, 0 },
1744 { "qcif", 176, 144, 0, 0 },
1745 { "cif", 352, 288, 0, 0 },
1746 { "4cif", 704, 576, 0, 0 },
de6d9b64 1747};
445f1b83 1748
de6d9b64
FB
1749int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
1750{
1751 int i;
445f1b83 1752 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
de6d9b64
FB
1753 const char *p;
1754 int frame_width = 0, frame_height = 0;
1755
1756 for(i=0;i<n;i++) {
445f1b83
RS
1757 if (!strcmp(frame_abvs[i].abv, str)) {
1758 frame_width = frame_abvs[i].width;
1759 frame_height = frame_abvs[i].height;
de6d9b64
FB
1760 break;
1761 }
1762 }
1763 if (i == n) {
1764 p = str;
1765 frame_width = strtol(p, (char **)&p, 10);
1766 if (*p)
1767 p++;
1768 frame_height = strtol(p, (char **)&p, 10);
1769 }
1770 if (frame_width <= 0 || frame_height <= 0)
1771 return -1;
1772 *width_ptr = frame_width;
1773 *height_ptr = frame_height;
1774 return 0;
1775}
1776
445f1b83
RS
1777int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
1778{
1779 int i;
1780 char* cp;
1781
1782 /* First, we check our abbreviation table */
1783 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
1784 if (!strcmp(frame_abvs[i].abv, arg)) {
1785 *frame_rate = frame_abvs[i].frame_rate;
1786 *frame_rate_base = frame_abvs[i].frame_rate_base;
1787 return 0;
1788 }
1789
1790 /* Then, we try to parse it as fraction */
1791 cp = strchr(arg, '/');
1792 if (cp) {
1793 char* cpp;
1794 *frame_rate = strtol(arg, &cpp, 10);
1795 if (cpp != arg || cpp == cp)
1796 *frame_rate_base = strtol(cp+1, &cpp, 10);
1797 else
1798 *frame_rate = 0;
1799 }
1800 else {
1801 /* Finally we give up and parse it as double */
1802 *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
1803 *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
1804 }
1805 if (!*frame_rate || !*frame_rate_base)
1806 return -1;
1807 else
1808 return 0;
1809}
1810
916c80e9
FB
1811/* Syntax:
1812 * - If not a duration:
1813 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
c5510dd6 1814 * Time is localtime unless Z is suffixed to the end. In this case GMT
916c80e9
FB
1815 * Return the date in micro seconds since 1970
1816 * - If duration:
1817 * HH[:MM[:SS[.m...]]]
1818 * S+[.m...]
1819 */
0c1a9eda 1820int64_t parse_date(const char *datestr, int duration)
de6d9b64
FB
1821{
1822 const char *p;
0c1a9eda 1823 int64_t t;
2dbceb9f 1824 struct tm dt;
c5510dd6
PG
1825 int i;
1826 static const char *date_fmt[] = {
1827 "%Y-%m-%d",
1828 "%Y%m%d",
1829 };
1830 static const char *time_fmt[] = {
1831 "%H:%M:%S",
1832 "%H%M%S",
1833 };
1834 const char *q;
916c80e9 1835 int is_utc, len;
c5510dd6
PG
1836 char lastch;
1837 time_t now = time(0);
1838
916c80e9
FB
1839 len = strlen(datestr);
1840 if (len > 0)
1841 lastch = datestr[len - 1];
1842 else
1843 lastch = '\0';
c5510dd6 1844 is_utc = (lastch == 'z' || lastch == 'Z');
2dbceb9f
PG
1845
1846 memset(&dt, 0, sizeof(dt));
de6d9b64
FB
1847
1848 p = datestr;
916c80e9 1849 q = NULL;
de6d9b64 1850 if (!duration) {
c5510dd6 1851 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
f71869a4 1852 q = small_strptime(p, date_fmt[i], &dt);
c5510dd6
PG
1853 if (q) {
1854 break;
1855 }
1856 }
1857
1858 if (!q) {
1859 if (is_utc) {
1860 dt = *gmtime(&now);
1861 } else {
1862 dt = *localtime(&now);
1863 }
1864 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
de6d9b64 1865 } else {
c5510dd6 1866 p = q;
de6d9b64 1867 }
c5510dd6
PG
1868
1869 if (*p == 'T' || *p == 't' || *p == ' ')
1870 p++;
c5510dd6 1871
916c80e9 1872 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
f71869a4 1873 q = small_strptime(p, time_fmt[i], &dt);
916c80e9
FB
1874 if (q) {
1875 break;
1876 }
1877 }
1878 } else {
f71869a4 1879 q = small_strptime(p, time_fmt[0], &dt);
916c80e9
FB
1880 if (!q) {
1881 dt.tm_sec = strtol(p, (char **)&q, 10);
1882 dt.tm_min = 0;
1883 dt.tm_hour = 0;
c5510dd6
PG
1884 }
1885 }
1886
1887 /* Now we have all the fields that we can get */
1888 if (!q) {
1889 if (duration)
1890 return 0;
1891 else
0c1a9eda 1892 return now * int64_t_C(1000000);
de6d9b64 1893 }
2dbceb9f
PG
1894
1895 if (duration) {
c5510dd6 1896 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2dbceb9f 1897 } else {
c5510dd6
PG
1898 dt.tm_isdst = -1; /* unknown */
1899 if (is_utc) {
1900 t = mktimegm(&dt);
1901 } else {
1902 t = mktime(&dt);
1903 }
de6d9b64 1904 }
2dbceb9f 1905
c5510dd6
PG
1906 t *= 1000000;
1907
1908 if (*q == '.') {
de6d9b64 1909 int val, n;
c5510dd6
PG
1910 q++;
1911 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1912 if (!isdigit(*q))
1913 break;
1914 val += n * (*q - '0');
de6d9b64
FB
1915 }
1916 t += val;
1917 }
1918 return t;
1919}
1920
2dbceb9f 1921/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
de6d9b64
FB
1922 1 if found */
1923int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1924{
1925 const char *p;
1926 char tag[128], *q;
1927
1928 p = info;
1929 if (*p == '?')
1930 p++;
1931 for(;;) {
1932 q = tag;
1933 while (*p != '\0' && *p != '=' && *p != '&') {
1934 if ((q - tag) < sizeof(tag) - 1)
1935 *q++ = *p;
1936 p++;
1937 }
1938 *q = '\0';
1939 q = arg;
1940 if (*p == '=') {
1941 p++;
1942 while (*p != '&' && *p != '\0') {
2dbceb9f
PG
1943 if ((q - arg) < arg_size - 1) {
1944 if (*p == '+')
1945 *q++ = ' ';
1946 else
1947 *q++ = *p;
1948 }
de6d9b64
FB
1949 p++;
1950 }
1951 *q = '\0';
1952 }
1953 if (!strcmp(tag, tag1))
1954 return 1;
1955 if (*p != '&')
1956 break;
8d1335ea 1957 p++;
de6d9b64
FB
1958 }
1959 return 0;
1960}
1961
9150f42e
FB
1962/* Return in 'buf' the path with '%d' replaced by number. Also handles
1963 the '%0nd' format where 'n' is the total number of digits and
1964 '%%'. Return 0 if OK, and -1 if format error */
1965int get_frame_filename(char *buf, int buf_size,
1966 const char *path, int number)
1967{
1968 const char *p;
0bf92f79
PI
1969 char *q, buf1[20], c;
1970 int nd, len, percentd_found;
9150f42e
FB
1971
1972 q = buf;
1973 p = path;
1974 percentd_found = 0;
1975 for(;;) {
1976 c = *p++;
1977 if (c == '\0')
1978 break;
1979 if (c == '%') {
c9646fda
PG
1980 do {
1981 nd = 0;
1982 while (isdigit(*p)) {
1983 nd = nd * 10 + *p++ - '0';
1984 }
1985 c = *p++;
c9646fda
PG
1986 } while (isdigit(c));
1987
9150f42e
FB
1988 switch(c) {
1989 case '%':
1990 goto addchar;
1991 case 'd':
1992 if (percentd_found)
1993 goto fail;
1994 percentd_found = 1;
1995 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1996 len = strlen(buf1);
1997 if ((q - buf + len) > buf_size - 1)
1998 goto fail;
1999 memcpy(q, buf1, len);
2000 q += len;
2001 break;
2002 default:
2003 goto fail;
2004 }
2005 } else {
2006 addchar:
2007 if ((q - buf) < buf_size - 1)
2008 *q++ = c;
2009 }
2010 }
2011 if (!percentd_found)
2012 goto fail;
2013 *q = '\0';
2014 return 0;
2015 fail:
2016 *q = '\0';
2017 return -1;
2018}
2019
b9a281db 2020/**
fb2758c8
FB
2021 * Print nice hexa dump of a buffer
2022 * @param f stream for output
b9a281db
FB
2023 * @param buf buffer
2024 * @param size buffer size
2025 */
fb2758c8 2026void av_hex_dump(FILE *f, uint8_t *buf, int size)
b9a281db
FB
2027{
2028 int len, i, j, c;
2029
2030 for(i=0;i<size;i+=16) {
2031 len = size - i;
2032 if (len > 16)
2033 len = 16;
fb2758c8 2034 fprintf(f, "%08x ", i);
b9a281db
FB
2035 for(j=0;j<16;j++) {
2036 if (j < len)
fb2758c8 2037 fprintf(f, " %02x", buf[i+j]);
b9a281db 2038 else
fb2758c8 2039 fprintf(f, " ");
b9a281db 2040 }
fb2758c8 2041 fprintf(f, " ");
b9a281db
FB
2042 for(j=0;j<len;j++) {
2043 c = buf[i+j];
2044 if (c < ' ' || c > '~')
2045 c = '.';
fb2758c8 2046 fprintf(f, "%c", c);
b9a281db 2047 }
fb2758c8 2048 fprintf(f, "\n");
b9a281db
FB
2049 }
2050}
2051
fb2758c8
FB
2052/**
2053 * Print on 'f' a nice dump of a packet
2054 * @param f stream for output
2055 * @param pkt packet to dump
2056 * @param dump_payload true if the payload must be displayed too
2057 */
2058void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
2059{
2060 fprintf(f, "stream #%d:\n", pkt->stream_index);
2061 fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
2062 fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
37353960
FB
2063 /* DTS is _always_ valid after av_read_frame() */
2064 fprintf(f, " dts=");
2065 if (pkt->dts == AV_NOPTS_VALUE)
2066 fprintf(f, "N/A");
2067 else
2068 fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
fb2758c8
FB
2069 /* PTS may be not known if B frames are present */
2070 fprintf(f, " pts=");
2071 if (pkt->pts == AV_NOPTS_VALUE)
2072 fprintf(f, "N/A");
2073 else
2074 fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
2075 fprintf(f, "\n");
2076 fprintf(f, " size=%d\n", pkt->size);
2077 if (dump_payload)
2078 av_hex_dump(f, pkt->data, pkt->size);
2079}
2080
a9a721da
FB
2081void url_split(char *proto, int proto_size,
2082 char *hostname, int hostname_size,
2083 int *port_ptr,
2084 char *path, int path_size,
2085 const char *url)
2086{
2087 const char *p;
2088 char *q;
2089 int port;
2090
2091 port = -1;
2092
2093 p = url;
2094 q = proto;
2095 while (*p != ':' && *p != '\0') {
2096 if ((q - proto) < proto_size - 1)
2097 *q++ = *p;
2098 p++;
2099 }
2100 if (proto_size > 0)
2101 *q = '\0';
2102 if (*p == '\0') {
2103 if (proto_size > 0)
2104 proto[0] = '\0';
2105 if (hostname_size > 0)
2106 hostname[0] = '\0';
2107 p = url;
2108 } else {
2109 p++;
2110 if (*p == '/')
2111 p++;
2112 if (*p == '/')
2113 p++;
2114 q = hostname;
2115 while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
2116 if ((q - hostname) < hostname_size - 1)
2117 *q++ = *p;
2118 p++;
2119 }
2120 if (hostname_size > 0)
2121 *q = '\0';
2122 if (*p == ':') {
2123 p++;
2124 port = strtoul(p, (char **)&p, 10);
2125 }
2126 }
2127 if (port_ptr)
2128 *port_ptr = port;
2129 pstrcpy(path, path_size, p);
2130}
2131
916c80e9
FB
2132/**
2133 * Set the pts for a given stream
2134 * @param s stream
2135 * @param pts_wrap_bits number of bits effectively used by the pts
2136 * (used for wrap control, 33 is the value for MPEG)
2137 * @param pts_num numerator to convert to seconds (MPEG: 1)
2138 * @param pts_den denominator to convert to seconds (MPEG: 90000)
2139 */
2140void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
2141 int pts_num, int pts_den)
2142{
2143 s->pts_wrap_bits = pts_wrap_bits;
2144 s->pts_num = pts_num;
2145 s->pts_den = pts_den;
2146}
2147
2148/* fraction handling */
2149
2150/**
2151 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
2152 * as 0 <= num < den.
2153 *
2154 * @param f fractional number
2155 * @param val integer value
2156 * @param num must be >= 0
2157 * @param den must be >= 1
2158 */
0c1a9eda 2159void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
916c80e9
FB
2160{
2161 num += (den >> 1);
2162 if (num >= den) {
2163 val += num / den;
2164 num = num % den;
2165 }
2166 f->val = val;
2167 f->num = num;
2168 f->den = den;
2169}
2170
2171/* set f to (val + 0.5) */
0c1a9eda 2172void av_frac_set(AVFrac *f, int64_t val)
916c80e9
FB
2173{
2174 f->val = val;
2175 f->num = f->den >> 1;
2176}
2177
2178/**
2179 * Fractionnal addition to f: f = f + (incr / f->den)
2180 *
2181 * @param f fractional number
2182 * @param incr increment, can be positive or negative
2183 */
0c1a9eda 2184void av_frac_add(AVFrac *f, int64_t incr)
916c80e9 2185{
0c1a9eda 2186 int64_t num, den;
916c80e9
FB
2187
2188 num = f->num + incr;
2189 den = f->den;
2190 if (num < 0) {
2191 f->val += num / den;
2192 num = num % den;
2193 if (num < 0) {
2194 num += den;
2195 f->val--;
2196 }
2197 } else if (num >= den) {
2198 f->val += num / den;
2199 num = num % den;
2200 }
2201 f->num = num;
2202}
87a0a681
FB
2203
2204/**
2205 * register a new image format
2206 * @param img_fmt Image format descriptor
2207 */
2208void av_register_image_format(AVImageFormat *img_fmt)
2209{
2210 AVImageFormat **p;
2211
2212 p = &first_image_format;
2213 while (*p != NULL) p = &(*p)->next;
2214 *p = img_fmt;
2215 img_fmt->next = NULL;
2216}
2217
2218/* guess image format */
2219AVImageFormat *av_probe_image_format(AVProbeData *pd)
2220{
2221 AVImageFormat *fmt1, *fmt;
2222 int score, score_max;
2223
2224 fmt = NULL;
2225 score_max = 0;
2226 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2227 if (fmt1->img_probe) {
2228 score = fmt1->img_probe(pd);
2229 if (score > score_max) {
2230 score_max = score;
2231 fmt = fmt1;
2232 }
2233 }
2234 }
2235 return fmt;
2236}
2237
2238AVImageFormat *guess_image_format(const char *filename)
2239{
2240 AVImageFormat *fmt1;
2241
2242 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2243 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
2244 return fmt1;
2245 }
2246 return NULL;
2247}
2248
2249/**
2250 * Read an image from a stream.
2251 * @param gb byte stream containing the image
2252 * @param fmt image format, NULL if probing is required
2253 */
2254int av_read_image(ByteIOContext *pb, const char *filename,
2255 AVImageFormat *fmt,
2256 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
2257{
2258 char buf[PROBE_BUF_SIZE];
2259 AVProbeData probe_data, *pd = &probe_data;
2260 offset_t pos;
2261 int ret;
2262
2263 if (!fmt) {
5c91a675 2264 pd->filename = filename;
87a0a681
FB
2265 pd->buf = buf;
2266 pos = url_ftell(pb);
2267 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
2268 url_fseek(pb, pos, SEEK_SET);
2269 fmt = av_probe_image_format(pd);
2270 }
2271 if (!fmt)
2272 return AVERROR_NOFMT;
2273 ret = fmt->img_read(pb, alloc_cb, opaque);
2274 return ret;
2275}
2276
2277/**
2278 * Write an image to a stream.
2279 * @param pb byte stream for the image output
2280 * @param fmt image format
2281 * @param img image data and informations
2282 */
2283int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
2284{
2285 return fmt->img_write(pb, img);
2286}
2287