new ffserver options patch by (D Richard Felker III <dalias at aerifal dot cx>)
[libav.git] / libav / 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"
af469427 20#include "tick.h"
c5510dd6 21#include <ctype.h>
8be1c656 22#ifndef CONFIG_WIN32
de6d9b64
FB
23#include <unistd.h>
24#include <fcntl.h>
de6d9b64 25#include <sys/time.h>
8be1c656
FB
26#else
27#define strcasecmp _stricmp
28#include <sys/types.h>
29#include <sys/timeb.h>
30#endif
9235088f 31#include <time.h>
de6d9b64 32
c5510dd6
PG
33#ifndef HAVE_STRPTIME
34#include "strptime.h"
35#endif
36
b9a281db
FB
37AVInputFormat *first_iformat;
38AVOutputFormat *first_oformat;
de6d9b64 39
b9a281db 40void av_register_input_format(AVInputFormat *format)
de6d9b64 41{
b9a281db
FB
42 AVInputFormat **p;
43 p = &first_iformat;
44 while (*p != NULL) p = &(*p)->next;
45 *p = format;
46 format->next = NULL;
47}
48
49void av_register_output_format(AVOutputFormat *format)
50{
51 AVOutputFormat **p;
52 p = &first_oformat;
de6d9b64
FB
53 while (*p != NULL) p = &(*p)->next;
54 *p = format;
55 format->next = NULL;
56}
57
58int match_ext(const char *filename, const char *extensions)
59{
60 const char *ext, *p;
61 char ext1[32], *q;
62
63 ext = strrchr(filename, '.');
64 if (ext) {
65 ext++;
66 p = extensions;
67 for(;;) {
68 q = ext1;
69 while (*p != '\0' && *p != ',')
70 *q++ = *p++;
71 *q = '\0';
72 if (!strcasecmp(ext1, ext))
73 return 1;
74 if (*p == '\0')
75 break;
76 p++;
77 }
78 }
79 return 0;
80}
81
b9a281db
FB
82AVOutputFormat *guess_format(const char *short_name, const char *filename,
83 const char *mime_type)
de6d9b64 84{
b9a281db 85 AVOutputFormat *fmt, *fmt_found;
de6d9b64
FB
86 int score_max, score;
87
88 /* find the proper file type */
89 fmt_found = NULL;
90 score_max = 0;
b9a281db 91 fmt = first_oformat;
de6d9b64
FB
92 while (fmt != NULL) {
93 score = 0;
94 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
95 score += 100;
96 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
97 score += 10;
98 if (filename && fmt->extensions &&
99 match_ext(filename, fmt->extensions)) {
100 score += 5;
101 }
102 if (score > score_max) {
103 score_max = score;
104 fmt_found = fmt;
105 }
106 fmt = fmt->next;
107 }
108 return fmt_found;
109}
110
c5510dd6
PG
111AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
112 const char *mime_type)
113{
114 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
115
116 if (fmt) {
117 AVOutputFormat *stream_fmt;
118 char stream_format_name[64];
119
120 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
121 stream_fmt = guess_format(stream_format_name, NULL, NULL);
122
123 if (stream_fmt)
124 fmt = stream_fmt;
125 }
126
127 return fmt;
128}
129
b9a281db
FB
130AVInputFormat *av_find_input_format(const char *short_name)
131{
132 AVInputFormat *fmt;
133 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
134 if (!strcmp(fmt->name, short_name))
135 return fmt;
136 }
137 return NULL;
138}
139
de6d9b64
FB
140/* memory handling */
141
b9a281db
FB
142/**
143 * Allocate the payload of a packet and intialized its fields to default values.
144 *
145 * @param pkt packet
146 * @param size wanted payload size
147 * @return 0 if OK. AVERROR_xxx otherwise.
148 */
de6d9b64
FB
149int av_new_packet(AVPacket *pkt, int size)
150{
1ea4f593 151 pkt->data = av_malloc(size);
de6d9b64 152 if (!pkt->data)
b9a281db 153 return AVERROR_NOMEM;
de6d9b64
FB
154 pkt->size = size;
155 /* sane state */
916c80e9 156 pkt->pts = AV_NOPTS_VALUE;
de6d9b64
FB
157 pkt->stream_index = 0;
158 pkt->flags = 0;
159 return 0;
160}
161
b9a281db
FB
162/**
163 * Free a packet
164 *
165 * @param pkt packet to free
166 */
de6d9b64
FB
167void av_free_packet(AVPacket *pkt)
168{
1ea4f593 169 av_freep(&pkt->data);
de6d9b64 170 /* fail safe */
de6d9b64
FB
171 pkt->size = 0;
172}
173
174/* fifo handling */
175
176int fifo_init(FifoBuffer *f, int size)
177{
1ea4f593 178 f->buffer = av_malloc(size);
de6d9b64
FB
179 if (!f->buffer)
180 return -1;
181 f->end = f->buffer + size;
182 f->wptr = f->rptr = f->buffer;
183 return 0;
184}
185
186void fifo_free(FifoBuffer *f)
187{
1ea4f593 188 av_free(f->buffer);
de6d9b64
FB
189}
190
191int fifo_size(FifoBuffer *f, UINT8 *rptr)
192{
193 int size;
194
195 if (f->wptr >= rptr) {
196 size = f->wptr - rptr;
197 } else {
198 size = (f->end - rptr) + (f->wptr - f->buffer);
199 }
200 return size;
201}
202
203/* get data from the fifo (return -1 if not enough data) */
204int fifo_read(FifoBuffer *f, UINT8 *buf, int buf_size, UINT8 **rptr_ptr)
205{
206 UINT8 *rptr = *rptr_ptr;
207 int size, len;
208
209 if (f->wptr >= rptr) {
210 size = f->wptr - rptr;
211 } else {
212 size = (f->end - rptr) + (f->wptr - f->buffer);
213 }
214
215 if (size < buf_size)
216 return -1;
217 while (buf_size > 0) {
218 len = f->end - rptr;
219 if (len > buf_size)
220 len = buf_size;
221 memcpy(buf, rptr, len);
222 buf += len;
223 rptr += len;
224 if (rptr >= f->end)
225 rptr = f->buffer;
226 buf_size -= len;
227 }
228 *rptr_ptr = rptr;
229 return 0;
230}
231
232void fifo_write(FifoBuffer *f, UINT8 *buf, int size, UINT8 **wptr_ptr)
233{
234 int len;
235 UINT8 *wptr;
236 wptr = *wptr_ptr;
237 while (size > 0) {
238 len = f->end - wptr;
239 if (len > size)
240 len = size;
241 memcpy(wptr, buf, len);
242 wptr += len;
243 if (wptr >= f->end)
244 wptr = f->buffer;
245 buf += len;
246 size -= len;
247 }
248 *wptr_ptr = wptr;
249}
250
b9a281db
FB
251int filename_number_test(const char *filename)
252{
253 char buf[1024];
254 return get_frame_filename(buf, sizeof(buf), filename, 1);
255}
256
257/* guess file format */
a25e098d 258AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
b9a281db
FB
259{
260 AVInputFormat *fmt1, *fmt;
261 int score, score_max;
262
263 fmt = NULL;
264 score_max = 0;
265 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
266 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
267 continue;
268 score = 0;
a8dbe951
PG
269 if (fmt1->read_probe) {
270 score = fmt1->read_probe(pd);
271 } else if (fmt1->extensions) {
b9a281db
FB
272 if (match_ext(pd->filename, fmt1->extensions)) {
273 score = 50;
274 }
a8dbe951 275 }
b9a281db
FB
276 if (score > score_max) {
277 score_max = score;
278 fmt = fmt1;
279 }
280 }
281 return fmt;
282}
283
284/************************************************************/
285/* input media file */
96baaa6a 286
b9a281db
FB
287#define PROBE_BUF_SIZE 2048
288
289/**
290 * Open a media file as input. The codec are not opened. Only the file
291 * header (if present) is read.
292 *
293 * @param ic_ptr the opened media file handle is put here
294 * @param filename filename to open.
295 * @param fmt if non NULL, force the file format to use
296 * @param buf_size optional buffer size (zero if default is OK)
297 * @param ap additionnal parameters needed when opening the file (NULL if default)
298 * @return 0 if OK. AVERROR_xxx otherwise.
299 */
300int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
301 AVInputFormat *fmt,
302 int buf_size,
303 AVFormatParameters *ap)
de6d9b64 304{
de6d9b64 305 AVFormatContext *ic = NULL;
de6d9b64 306 int err;
b9a281db
FB
307 char buf[PROBE_BUF_SIZE];
308 AVProbeData probe_data, *pd = &probe_data;
de6d9b64
FB
309
310 ic = av_mallocz(sizeof(AVFormatContext));
b9a281db
FB
311 if (!ic) {
312 err = AVERROR_NOMEM;
de6d9b64 313 goto fail;
de6d9b64 314 }
b9a281db
FB
315 pstrcpy(ic->filename, sizeof(ic->filename), filename);
316 pd->filename = ic->filename;
317 pd->buf = buf;
318 pd->buf_size = 0;
319
320 if (!fmt) {
321 /* guess format if no file can be opened */
a25e098d 322 fmt = av_probe_input_format(pd, 0);
de6d9b64 323 }
de6d9b64 324
96baaa6a 325 /* if no file needed do not try to open one */
b9a281db
FB
326 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
327 if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
328 err = AVERROR_IO;
96baaa6a 329 goto fail;
b9a281db 330 }
96baaa6a
FB
331 if (buf_size > 0) {
332 url_setbufsize(&ic->pb, buf_size);
333 }
b9a281db
FB
334 /* read probe data */
335 pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
336 url_fseek(&ic->pb, 0, SEEK_SET);
96baaa6a
FB
337 }
338
b9a281db
FB
339 /* guess file format */
340 if (!fmt) {
a25e098d 341 fmt = av_probe_input_format(pd, 1);
b9a281db
FB
342 }
343
344 /* if still no format found, error */
345 if (!fmt) {
346 err = AVERROR_NOFMT;
de6d9b64
FB
347 goto fail;
348 }
b9a281db
FB
349
350 ic->iformat = fmt;
de6d9b64 351
b9a281db
FB
352 /* allocate private data */
353 ic->priv_data = av_mallocz(fmt->priv_data_size);
354 if (!ic->priv_data) {
355 err = AVERROR_NOMEM;
356 goto fail;
357 }
358
916c80e9
FB
359 /* default pts settings is MPEG like */
360 av_set_pts_info(ic, 33, 1, 90000);
361
b9a281db
FB
362 /* check filename in case of an image number is expected */
363 if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
364 if (filename_number_test(ic->filename) < 0) {
365 err = AVERROR_NUMEXPECTED;
366 goto fail1;
367 }
368 }
369
370 err = ic->iformat->read_header(ic, ap);
371 if (err < 0)
372 goto fail1;
373 *ic_ptr = ic;
374 return 0;
375 fail1:
376 if (!(fmt->flags & AVFMT_NOFILE)) {
377 url_fclose(&ic->pb);
378 }
de6d9b64 379 fail:
b9a281db 380 if (ic) {
a8dbe951 381 av_freep(&ic->priv_data);
b9a281db 382 }
1ea4f593 383 av_free(ic);
b9a281db
FB
384 *ic_ptr = NULL;
385 return err;
de6d9b64
FB
386}
387
b9a281db
FB
388/**
389 * Read a packet from a media file
390 * @param s media file handle
391 * @param pkt is filled
392 * @return 0 if OK. AVERROR_xxx if error.
393 */
de6d9b64
FB
394int av_read_packet(AVFormatContext *s, AVPacket *pkt)
395{
396 AVPacketList *pktl;
397
398 pktl = s->packet_buffer;
399 if (pktl) {
400 /* read packet from packet buffer, if there is data */
401 *pkt = pktl->pkt;
402 s->packet_buffer = pktl->next;
1ea4f593 403 av_free(pktl);
de6d9b64
FB
404 return 0;
405 } else {
b9a281db
FB
406 return s->iformat->read_packet(s, pkt);
407 }
408}
409
410/* state for codec information */
411#define CSTATE_NOTFOUND 0
412#define CSTATE_DECODING 1
413#define CSTATE_FOUND 2
414
415static int has_codec_parameters(AVCodecContext *enc)
416{
417 int val;
418 switch(enc->codec_type) {
419 case CODEC_TYPE_AUDIO:
420 val = enc->sample_rate;
421 break;
422 case CODEC_TYPE_VIDEO:
423 val = enc->width;
424 break;
425 default:
426 val = 1;
427 break;
428 }
429 return (val != 0);
430}
431
432/**
433 * Read the beginning of a media file to get stream information. This
434 * is useful for file formats with no headers such as MPEG. This
435 * function also compute the real frame rate in case of mpeg2 repeat
436 * frame mode.
437 *
438 * @param ic media file handle
439 * @return >=0 if OK. AVERROR_xxx if error.
440 */
441int av_find_stream_info(AVFormatContext *ic)
442{
443 int i, count, ret, got_picture, size, read_size;
444 AVCodec *codec;
445 AVStream *st;
446 AVPacket *pkt;
447 AVPicture picture;
448 AVPacketList *pktl=NULL, **ppktl;
449 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
450 UINT8 *ptr;
451 int min_read_size, max_read_size;
452
453 /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
454 Mbits. We read at most 0.1 second of file to find all streams */
455
456 /* XXX: base it on stream bitrate when possible */
457 if (ic->iformat == &mpegts_demux) {
458 /* maximum number of bytes we accept to read to find all the streams
459 in a file */
460 min_read_size = 3000000;
461 } else {
462 min_read_size = 125000;
463 }
464 /* max read size is 2 seconds of video max */
465 max_read_size = min_read_size * 20;
466
467 /* set initial codec state */
468 for(i=0;i<ic->nb_streams;i++) {
469 st = ic->streams[i];
470 if (has_codec_parameters(&st->codec))
471 st->codec_info_state = CSTATE_FOUND;
472 else
473 st->codec_info_state = CSTATE_NOTFOUND;
474 st->codec_info_nb_repeat_frames = 0;
475 st->codec_info_nb_real_frames = 0;
476 }
477
478 count = 0;
479 read_size = 0;
480 ppktl = &ic->packet_buffer;
481 for(;;) {
482 /* check if one codec still needs to be handled */
483 for(i=0;i<ic->nb_streams;i++) {
484 st = ic->streams[i];
485 if (st->codec_info_state != CSTATE_FOUND)
486 break;
487 }
488 if (i == ic->nb_streams) {
489 /* NOTE: if the format has no header, then we need to read
490 some packets to get most of the streams, so we cannot
491 stop here */
492 if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
493 read_size >= min_read_size) {
494 /* if we found the info for all the codecs, we can stop */
495 ret = count;
496 break;
497 }
498 } else {
499 /* we did not get all the codec info, but we read too much data */
500 if (read_size >= max_read_size) {
501 ret = count;
502 break;
503 }
504 }
505
506 pktl = av_mallocz(sizeof(AVPacketList));
507 if (!pktl) {
508 ret = AVERROR_NOMEM;
509 break;
510 }
511
512 /* add the packet in the buffered packet list */
513 *ppktl = pktl;
514 ppktl = &pktl->next;
515
516 /* NOTE: a new stream can be added there if no header in file
517 (AVFMT_NOHEADER) */
518 pkt = &pktl->pkt;
519 if (ic->iformat->read_packet(ic, pkt) < 0) {
520 /* EOF or error */
521 ret = -1; /* we could not have all the codec parameters before EOF */
522 if ((ic->iformat->flags & AVFMT_NOHEADER) &&
523 i == ic->nb_streams)
524 ret = 0;
525 break;
526 }
527 read_size += pkt->size;
528
529 /* open new codecs */
530 for(i=0;i<ic->nb_streams;i++) {
531 st = ic->streams[i];
532 if (st->codec_info_state == CSTATE_NOTFOUND) {
533 /* set to found in case of error */
534 st->codec_info_state = CSTATE_FOUND;
535 codec = avcodec_find_decoder(st->codec.codec_id);
536 if (codec) {
537 ret = avcodec_open(&st->codec, codec);
538 if (ret >= 0)
539 st->codec_info_state = CSTATE_DECODING;
540 }
541 }
542 }
543
544 st = ic->streams[pkt->stream_index];
545 if (st->codec_info_state == CSTATE_DECODING) {
546 /* decode the data and update codec parameters */
547 ptr = pkt->data;
548 size = pkt->size;
549 while (size > 0) {
550 switch(st->codec.codec_type) {
551 case CODEC_TYPE_VIDEO:
552 ret = avcodec_decode_video(&st->codec, &picture,
553 &got_picture, ptr, size);
554 break;
555 case CODEC_TYPE_AUDIO:
556 ret = avcodec_decode_audio(&st->codec, samples,
557 &got_picture, ptr, size);
558 break;
559 default:
560 ret = -1;
561 break;
562 }
563 if (ret < 0) {
564 /* if error, simply ignore because another packet
565 may be OK */
566 break;
567 }
568 if (got_picture) {
569 /* we got the parameters - now we can stop
570 examining this stream */
571 /* XXX: add a codec info so that we can decide if
572 the codec can repeat frames */
573 if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO &&
574 ic->iformat != &mpegts_demux &&
575 st->codec.sub_id == 2) {
576 /* for mpeg2 video, we want to know the real
577 frame rate, so we decode 40 frames. In mpeg
578 TS case we do not do it because it would be
579 too long */
580 st->codec_info_nb_real_frames++;
581 st->codec_info_nb_repeat_frames += st->codec.repeat_pict;
582#if 0
583 /* XXX: testing */
584 if ((st->codec_info_nb_real_frames % 24) == 23) {
585 st->codec_info_nb_repeat_frames += 2;
586 }
587#endif
588 /* stop after 40 frames */
589 if (st->codec_info_nb_real_frames >= 40) {
590 st->r_frame_rate = (st->codec.frame_rate *
591 st->codec_info_nb_real_frames) /
592 (st->codec_info_nb_real_frames +
593 (st->codec_info_nb_repeat_frames >> 1));
594 goto close_codec;
595 }
596 } else {
597 close_codec:
598 st->codec_info_state = CSTATE_FOUND;
599 avcodec_close(&st->codec);
24f9709b 600 break;
b9a281db 601 }
b9a281db
FB
602 }
603 ptr += ret;
604 size -= ret;
605 }
606 }
607 count++;
608 }
609
610 /* close each codec if there are opened */
611 for(i=0;i<ic->nb_streams;i++) {
612 st = ic->streams[i];
613 if (st->codec_info_state == CSTATE_DECODING)
614 avcodec_close(&st->codec);
615 }
616
617 /* set real frame rate info */
618 for(i=0;i<ic->nb_streams;i++) {
619 st = ic->streams[i];
620 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
621 if (!st->r_frame_rate)
622 st->r_frame_rate = st->codec.frame_rate;
623 }
de6d9b64 624 }
b9a281db
FB
625
626 return ret;
de6d9b64
FB
627}
628
b9a281db
FB
629/**
630 * Close a media file (but not its codecs)
631 *
632 * @param s media file handle
633 */
de6d9b64
FB
634void av_close_input_file(AVFormatContext *s)
635{
636 int i;
637
b9a281db
FB
638 if (s->iformat->read_close)
639 s->iformat->read_close(s);
de6d9b64 640 for(i=0;i<s->nb_streams;i++) {
1ea4f593 641 av_free(s->streams[i]);
de6d9b64
FB
642 }
643 if (s->packet_buffer) {
644 AVPacketList *p, *p1;
645 p = s->packet_buffer;
646 while (p != NULL) {
647 p1 = p->next;
648 av_free_packet(&p->pkt);
1ea4f593 649 av_free(p);
de6d9b64
FB
650 p = p1;
651 }
652 s->packet_buffer = NULL;
653 }
b9a281db 654 if (!(s->iformat->flags & AVFMT_NOFILE)) {
96baaa6a
FB
655 url_fclose(&s->pb);
656 }
a8dbe951 657 av_freep(&s->priv_data);
1ea4f593 658 av_free(s);
de6d9b64
FB
659}
660
b9a281db
FB
661/**
662 * Add a new stream to a media file. Can only be called in the
663 * read_header function. If the flag AVFMT_NOHEADER is in the format
664 * description, then new streams can be added in read_packet too.
665 *
666 *
667 * @param s media file handle
668 * @param id file format dependent stream id
669 */
670AVStream *av_new_stream(AVFormatContext *s, int id)
671{
672 AVStream *st;
673
674 if (s->nb_streams >= MAX_STREAMS)
675 return NULL;
676
677 st = av_mallocz(sizeof(AVStream));
678 if (!st)
679 return NULL;
680 st->index = s->nb_streams;
681 st->id = id;
682 s->streams[s->nb_streams++] = st;
683 return st;
684}
685
686/************************************************************/
687/* output media file */
de6d9b64 688
b9a281db
FB
689/**
690 * allocate the stream private data and write the stream header to an
691 * output media file
692 *
693 * @param s media file handle
694 * @return 0 if OK. AVERROR_xxx if error.
695 */
696int av_write_header(AVFormatContext *s)
697{
698 s->priv_data = av_mallocz(s->oformat->priv_data_size);
699 if (!s->priv_data)
700 return AVERROR_NOMEM;
916c80e9
FB
701 /* default pts settings is MPEG like */
702 av_set_pts_info(s, 33, 1, 90000);
b9a281db
FB
703 return s->oformat->write_header(s);
704}
705
706/**
707 * write a packet to an output media file
708 *
709 * @param s media file handle
710 * @param pkt packet to write
711 * @param force_pts XXX: need to suppress that
712 */
10bb7023 713int av_write_packet(AVFormatContext *s, AVPacket *pkt, int force_pts)
de6d9b64
FB
714{
715 /* XXX: currently, an emulation because internal API must change */
b9a281db
FB
716 return s->oformat->write_packet(s, pkt->stream_index, pkt->data, pkt->size, force_pts);
717}
718
719/**
720 * write the stream trailer to an output media file and and free the
721 * file private data.
722 *
723 * @param s media file handle
724 * @return 0 if OK. AVERROR_xxx if error. */
725int av_write_trailer(AVFormatContext *s)
726{
727 int ret;
728 ret = s->oformat->write_trailer(s);
729 av_freep(&s->priv_data);
730 return ret;
de6d9b64
FB
731}
732
733/* "user interface" functions */
734
735void dump_format(AVFormatContext *ic,
736 int index,
737 const char *url,
738 int is_output)
739{
b9a281db 740 int i, flags;
de6d9b64
FB
741 char buf[256];
742
743 fprintf(stderr, "%s #%d, %s, %s '%s':\n",
744 is_output ? "Output" : "Input",
b9a281db
FB
745 index,
746 is_output ? ic->oformat->name : ic->iformat->name,
de6d9b64
FB
747 is_output ? "to" : "from", url);
748 for(i=0;i<ic->nb_streams;i++) {
749 AVStream *st = ic->streams[i];
750 avcodec_string(buf, sizeof(buf), &st->codec, is_output);
b9a281db
FB
751 fprintf(stderr, " Stream #%d.%d", index, i);
752 /* the pid is an important information, so we display it */
753 /* XXX: add a generic system */
754 if (is_output)
755 flags = ic->oformat->flags;
756 else
757 flags = ic->iformat->flags;
758 if (flags & AVFMT_SHOW_IDS) {
759 fprintf(stderr, "[0x%x]", st->id);
760 }
761 fprintf(stderr, ": %s\n", buf);
de6d9b64
FB
762 }
763}
764
765typedef struct {
766 const char *str;
767 int width, height;
768} SizeEntry;
769
770static SizeEntry sizes[] = {
771 { "sqcif", 128, 96 },
772 { "qcif", 176, 144 },
773 { "cif", 352, 288 },
774 { "4cif", 704, 576 },
775};
776
777int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
778{
779 int i;
780 int n = sizeof(sizes) / sizeof(SizeEntry);
781 const char *p;
782 int frame_width = 0, frame_height = 0;
783
784 for(i=0;i<n;i++) {
785 if (!strcmp(sizes[i].str, str)) {
786 frame_width = sizes[i].width;
787 frame_height = sizes[i].height;
788 break;
789 }
790 }
791 if (i == n) {
792 p = str;
793 frame_width = strtol(p, (char **)&p, 10);
794 if (*p)
795 p++;
796 frame_height = strtol(p, (char **)&p, 10);
797 }
798 if (frame_width <= 0 || frame_height <= 0)
799 return -1;
800 *width_ptr = frame_width;
801 *height_ptr = frame_height;
802 return 0;
803}
804
a25e098d 805INT64 av_gettime(void)
de6d9b64 806{
8be1c656
FB
807#ifdef CONFIG_WIN32
808 struct _timeb tb;
809 _ftime(&tb);
810 return ((INT64)tb.time * INT64_C(1000) + (INT64)tb.millitm) * INT64_C(1000);
811#else
de6d9b64
FB
812 struct timeval tv;
813 gettimeofday(&tv,NULL);
814 return (INT64)tv.tv_sec * 1000000 + tv.tv_usec;
8be1c656 815#endif
de6d9b64
FB
816}
817
c5510dd6
PG
818static time_t mktimegm(struct tm *tm)
819{
820 time_t t;
821
822 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
823
824 if (m < 3) {
825 m += 12;
826 y--;
827 }
828
829 t = 86400 *
830 (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
831
832 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
833
834 return t;
835}
836
916c80e9
FB
837/* Syntax:
838 * - If not a duration:
839 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
c5510dd6 840 * Time is localtime unless Z is suffixed to the end. In this case GMT
916c80e9
FB
841 * Return the date in micro seconds since 1970
842 * - If duration:
843 * HH[:MM[:SS[.m...]]]
844 * S+[.m...]
845 */
de6d9b64
FB
846INT64 parse_date(const char *datestr, int duration)
847{
848 const char *p;
849 INT64 t;
2dbceb9f 850 struct tm dt;
c5510dd6
PG
851 int i;
852 static const char *date_fmt[] = {
853 "%Y-%m-%d",
854 "%Y%m%d",
855 };
856 static const char *time_fmt[] = {
857 "%H:%M:%S",
858 "%H%M%S",
859 };
860 const char *q;
916c80e9 861 int is_utc, len;
c5510dd6
PG
862 char lastch;
863 time_t now = time(0);
864
916c80e9
FB
865 len = strlen(datestr);
866 if (len > 0)
867 lastch = datestr[len - 1];
868 else
869 lastch = '\0';
c5510dd6 870 is_utc = (lastch == 'z' || lastch == 'Z');
2dbceb9f
PG
871
872 memset(&dt, 0, sizeof(dt));
de6d9b64
FB
873
874 p = datestr;
916c80e9 875 q = NULL;
de6d9b64 876 if (!duration) {
c5510dd6
PG
877 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
878 q = strptime(p, date_fmt[i], &dt);
879 if (q) {
880 break;
881 }
882 }
883
884 if (!q) {
885 if (is_utc) {
886 dt = *gmtime(&now);
887 } else {
888 dt = *localtime(&now);
889 }
890 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
de6d9b64 891 } else {
c5510dd6 892 p = q;
de6d9b64 893 }
c5510dd6
PG
894
895 if (*p == 'T' || *p == 't' || *p == ' ')
896 p++;
c5510dd6 897
916c80e9
FB
898 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
899 q = strptime(p, time_fmt[i], &dt);
900 if (q) {
901 break;
902 }
903 }
904 } else {
905 q = strptime(p, time_fmt[0], &dt);
906 if (!q) {
907 dt.tm_sec = strtol(p, (char **)&q, 10);
908 dt.tm_min = 0;
909 dt.tm_hour = 0;
c5510dd6
PG
910 }
911 }
912
913 /* Now we have all the fields that we can get */
914 if (!q) {
915 if (duration)
916 return 0;
917 else
918 return now * INT64_C(1000000);
de6d9b64 919 }
2dbceb9f
PG
920
921 if (duration) {
c5510dd6 922 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2dbceb9f 923 } else {
c5510dd6
PG
924 dt.tm_isdst = -1; /* unknown */
925 if (is_utc) {
926 t = mktimegm(&dt);
927 } else {
928 t = mktime(&dt);
929 }
de6d9b64 930 }
2dbceb9f 931
c5510dd6
PG
932 t *= 1000000;
933
934 if (*q == '.') {
de6d9b64 935 int val, n;
c5510dd6
PG
936 q++;
937 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
938 if (!isdigit(*q))
939 break;
940 val += n * (*q - '0');
de6d9b64
FB
941 }
942 t += val;
943 }
944 return t;
945}
946
2dbceb9f 947/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
de6d9b64
FB
948 1 if found */
949int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
950{
951 const char *p;
952 char tag[128], *q;
953
954 p = info;
955 if (*p == '?')
956 p++;
957 for(;;) {
958 q = tag;
959 while (*p != '\0' && *p != '=' && *p != '&') {
960 if ((q - tag) < sizeof(tag) - 1)
961 *q++ = *p;
962 p++;
963 }
964 *q = '\0';
965 q = arg;
966 if (*p == '=') {
967 p++;
968 while (*p != '&' && *p != '\0') {
2dbceb9f
PG
969 if ((q - arg) < arg_size - 1) {
970 if (*p == '+')
971 *q++ = ' ';
972 else
973 *q++ = *p;
974 }
de6d9b64
FB
975 p++;
976 }
977 *q = '\0';
978 }
979 if (!strcmp(tag, tag1))
980 return 1;
981 if (*p != '&')
982 break;
8d1335ea 983 p++;
de6d9b64
FB
984 }
985 return 0;
986}
987
9150f42e
FB
988/* Return in 'buf' the path with '%d' replaced by number. Also handles
989 the '%0nd' format where 'n' is the total number of digits and
990 '%%'. Return 0 if OK, and -1 if format error */
991int get_frame_filename(char *buf, int buf_size,
992 const char *path, int number)
993{
994 const char *p;
995 char *q, buf1[20];
996 int nd, len, c, percentd_found;
997
998 q = buf;
999 p = path;
1000 percentd_found = 0;
1001 for(;;) {
1002 c = *p++;
1003 if (c == '\0')
1004 break;
1005 if (c == '%') {
1006 nd = 0;
1007 while (*p >= '0' && *p <= '9') {
1008 nd = nd * 10 + *p++ - '0';
1009 }
1010 c = *p++;
1011 switch(c) {
1012 case '%':
1013 goto addchar;
1014 case 'd':
1015 if (percentd_found)
1016 goto fail;
1017 percentd_found = 1;
1018 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1019 len = strlen(buf1);
1020 if ((q - buf + len) > buf_size - 1)
1021 goto fail;
1022 memcpy(q, buf1, len);
1023 q += len;
1024 break;
1025 default:
1026 goto fail;
1027 }
1028 } else {
1029 addchar:
1030 if ((q - buf) < buf_size - 1)
1031 *q++ = c;
1032 }
1033 }
1034 if (!percentd_found)
1035 goto fail;
1036 *q = '\0';
1037 return 0;
1038 fail:
1039 *q = '\0';
1040 return -1;
1041}
1042
b9a281db
FB
1043/**
1044 *
1045 * Print on stdout a nice hexa dump of a buffer
1046 * @param buf buffer
1047 * @param size buffer size
1048 */
1049void av_hex_dump(UINT8 *buf, int size)
1050{
1051 int len, i, j, c;
1052
1053 for(i=0;i<size;i+=16) {
1054 len = size - i;
1055 if (len > 16)
1056 len = 16;
1057 printf("%08x ", i);
1058 for(j=0;j<16;j++) {
1059 if (j < len)
1060 printf(" %02x", buf[i+j]);
1061 else
1062 printf(" ");
1063 }
1064 printf(" ");
1065 for(j=0;j<len;j++) {
1066 c = buf[i+j];
1067 if (c < ' ' || c > '~')
1068 c = '.';
1069 printf("%c", c);
1070 }
1071 printf("\n");
1072 }
1073}
1074
a9a721da
FB
1075void url_split(char *proto, int proto_size,
1076 char *hostname, int hostname_size,
1077 int *port_ptr,
1078 char *path, int path_size,
1079 const char *url)
1080{
1081 const char *p;
1082 char *q;
1083 int port;
1084
1085 port = -1;
1086
1087 p = url;
1088 q = proto;
1089 while (*p != ':' && *p != '\0') {
1090 if ((q - proto) < proto_size - 1)
1091 *q++ = *p;
1092 p++;
1093 }
1094 if (proto_size > 0)
1095 *q = '\0';
1096 if (*p == '\0') {
1097 if (proto_size > 0)
1098 proto[0] = '\0';
1099 if (hostname_size > 0)
1100 hostname[0] = '\0';
1101 p = url;
1102 } else {
1103 p++;
1104 if (*p == '/')
1105 p++;
1106 if (*p == '/')
1107 p++;
1108 q = hostname;
1109 while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1110 if ((q - hostname) < hostname_size - 1)
1111 *q++ = *p;
1112 p++;
1113 }
1114 if (hostname_size > 0)
1115 *q = '\0';
1116 if (*p == ':') {
1117 p++;
1118 port = strtoul(p, (char **)&p, 10);
1119 }
1120 }
1121 if (port_ptr)
1122 *port_ptr = port;
1123 pstrcpy(path, path_size, p);
1124}
1125
916c80e9
FB
1126/**
1127 * Set the pts for a given stream
1128 * @param s stream
1129 * @param pts_wrap_bits number of bits effectively used by the pts
1130 * (used for wrap control, 33 is the value for MPEG)
1131 * @param pts_num numerator to convert to seconds (MPEG: 1)
1132 * @param pts_den denominator to convert to seconds (MPEG: 90000)
1133 */
1134void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1135 int pts_num, int pts_den)
1136{
1137 s->pts_wrap_bits = pts_wrap_bits;
1138 s->pts_num = pts_num;
1139 s->pts_den = pts_den;
1140}
1141
1142/* fraction handling */
1143
1144/**
1145 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1146 * as 0 <= num < den.
1147 *
1148 * @param f fractional number
1149 * @param val integer value
1150 * @param num must be >= 0
1151 * @param den must be >= 1
1152 */
1153void av_frac_init(AVFrac *f, INT64 val, INT64 num, INT64 den)
1154{
1155 num += (den >> 1);
1156 if (num >= den) {
1157 val += num / den;
1158 num = num % den;
1159 }
1160 f->val = val;
1161 f->num = num;
1162 f->den = den;
1163}
1164
1165/* set f to (val + 0.5) */
1166void av_frac_set(AVFrac *f, INT64 val)
1167{
1168 f->val = val;
1169 f->num = f->den >> 1;
1170}
1171
1172/**
1173 * Fractionnal addition to f: f = f + (incr / f->den)
1174 *
1175 * @param f fractional number
1176 * @param incr increment, can be positive or negative
1177 */
1178void av_frac_add(AVFrac *f, INT64 incr)
1179{
1180 INT64 num, den;
1181
1182 num = f->num + incr;
1183 den = f->den;
1184 if (num < 0) {
1185 f->val += num / den;
1186 num = num % den;
1187 if (num < 0) {
1188 num += den;
1189 f->val--;
1190 }
1191 } else if (num >= den) {
1192 f->val += num / den;
1193 num = num % den;
1194 }
1195 f->num = num;
1196}