also parse extradata for MPEG4
[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
de6d9b64
FB
164/* fifo handling */
165
166int fifo_init(FifoBuffer *f, int size)
167{
1ea4f593 168 f->buffer = av_malloc(size);
de6d9b64
FB
169 if (!f->buffer)
170 return -1;
171 f->end = f->buffer + size;
172 f->wptr = f->rptr = f->buffer;
173 return 0;
174}
175
176void fifo_free(FifoBuffer *f)
177{
1ea4f593 178 av_free(f->buffer);
de6d9b64
FB
179}
180
0c1a9eda 181int fifo_size(FifoBuffer *f, uint8_t *rptr)
de6d9b64
FB
182{
183 int size;
184
185 if (f->wptr >= rptr) {
186 size = f->wptr - rptr;
187 } else {
188 size = (f->end - rptr) + (f->wptr - f->buffer);
189 }
190 return size;
191}
192
193/* get data from the fifo (return -1 if not enough data) */
0c1a9eda 194int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
de6d9b64 195{
0c1a9eda 196 uint8_t *rptr = *rptr_ptr;
de6d9b64
FB
197 int size, len;
198
199 if (f->wptr >= rptr) {
200 size = f->wptr - rptr;
201 } else {
202 size = (f->end - rptr) + (f->wptr - f->buffer);
203 }
204
205 if (size < buf_size)
206 return -1;
207 while (buf_size > 0) {
208 len = f->end - rptr;
209 if (len > buf_size)
210 len = buf_size;
211 memcpy(buf, rptr, len);
212 buf += len;
213 rptr += len;
214 if (rptr >= f->end)
215 rptr = f->buffer;
216 buf_size -= len;
217 }
218 *rptr_ptr = rptr;
219 return 0;
220}
221
0c1a9eda 222void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
de6d9b64
FB
223{
224 int len;
0c1a9eda 225 uint8_t *wptr;
de6d9b64
FB
226 wptr = *wptr_ptr;
227 while (size > 0) {
228 len = f->end - wptr;
229 if (len > size)
230 len = size;
231 memcpy(wptr, buf, len);
232 wptr += len;
233 if (wptr >= f->end)
234 wptr = f->buffer;
235 buf += len;
236 size -= len;
237 }
238 *wptr_ptr = wptr;
239}
240
b9a281db
FB
241int filename_number_test(const char *filename)
242{
243 char buf[1024];
244 return get_frame_filename(buf, sizeof(buf), filename, 1);
245}
246
247/* guess file format */
a25e098d 248AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
b9a281db
FB
249{
250 AVInputFormat *fmt1, *fmt;
251 int score, score_max;
252
253 fmt = NULL;
254 score_max = 0;
255 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
256 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
257 continue;
258 score = 0;
a8dbe951
PG
259 if (fmt1->read_probe) {
260 score = fmt1->read_probe(pd);
261 } else if (fmt1->extensions) {
b9a281db
FB
262 if (match_ext(pd->filename, fmt1->extensions)) {
263 score = 50;
264 }
a8dbe951 265 }
b9a281db
FB
266 if (score > score_max) {
267 score_max = score;
268 fmt = fmt1;
269 }
270 }
271 return fmt;
272}
273
274/************************************************************/
275/* input media file */
96baaa6a 276
da24c5e3
FB
277/**
278 * open a media file from an IO stream. 'fmt' must be specified.
279 */
280int av_open_input_stream(AVFormatContext **ic_ptr,
281 ByteIOContext *pb, const char *filename,
282 AVInputFormat *fmt, AVFormatParameters *ap)
283{
284 int err;
285 AVFormatContext *ic;
286
287 ic = av_mallocz(sizeof(AVFormatContext));
288 if (!ic) {
289 err = AVERROR_NOMEM;
290 goto fail;
291 }
292 ic->iformat = fmt;
293 if (pb)
294 ic->pb = *pb;
295 ic->duration = AV_NOPTS_VALUE;
296 ic->start_time = AV_NOPTS_VALUE;
297 pstrcpy(ic->filename, sizeof(ic->filename), filename);
298
299 /* allocate private data */
300 if (fmt->priv_data_size > 0) {
301 ic->priv_data = av_mallocz(fmt->priv_data_size);
302 if (!ic->priv_data) {
303 err = AVERROR_NOMEM;
304 goto fail;
305 }
306 } else {
307 ic->priv_data = NULL;
308 }
309
310 /* default pts settings is MPEG like */
311 av_set_pts_info(ic, 33, 1, 90000);
312
313 err = ic->iformat->read_header(ic, ap);
314 if (err < 0)
315 goto fail;
316 *ic_ptr = ic;
317 return 0;
318 fail:
319 if (ic) {
320 av_freep(&ic->priv_data);
321 }
322 av_free(ic);
323 *ic_ptr = NULL;
324 return err;
325}
326
b9a281db
FB
327#define PROBE_BUF_SIZE 2048
328
329/**
330 * Open a media file as input. The codec are not opened. Only the file
331 * header (if present) is read.
332 *
333 * @param ic_ptr the opened media file handle is put here
334 * @param filename filename to open.
335 * @param fmt if non NULL, force the file format to use
336 * @param buf_size optional buffer size (zero if default is OK)
337 * @param ap additionnal parameters needed when opening the file (NULL if default)
338 * @return 0 if OK. AVERROR_xxx otherwise.
339 */
340int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
341 AVInputFormat *fmt,
342 int buf_size,
343 AVFormatParameters *ap)
de6d9b64 344{
da24c5e3
FB
345 int err, must_open_file, file_opened;
346 uint8_t buf[PROBE_BUF_SIZE];
b9a281db 347 AVProbeData probe_data, *pd = &probe_data;
da24c5e3
FB
348 ByteIOContext pb1, *pb = &pb1;
349
350 file_opened = 0;
351 pd->filename = "";
352 if (filename)
353 pd->filename = filename;
b9a281db
FB
354 pd->buf = buf;
355 pd->buf_size = 0;
356
357 if (!fmt) {
358 /* guess format if no file can be opened */
a25e098d 359 fmt = av_probe_input_format(pd, 0);
de6d9b64 360 }
de6d9b64 361
b6892136
FB
362 /* do not open file if the format does not need it. XXX: specific
363 hack needed to handle RTSP/TCP */
364 must_open_file = 1;
da24c5e3 365 if (fmt && (fmt->flags & AVFMT_NOFILE)) {
b6892136
FB
366 must_open_file = 0;
367 }
368
369 if (!fmt || must_open_file) {
87a0a681 370 /* if no file needed do not try to open one */
da24c5e3 371 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
b9a281db 372 err = AVERROR_IO;
96baaa6a 373 goto fail;
b9a281db 374 }
da24c5e3 375 file_opened = 1;
96baaa6a 376 if (buf_size > 0) {
da24c5e3 377 url_setbufsize(pb, buf_size);
96baaa6a 378 }
5b25dfa7
FB
379 if (!fmt) {
380 /* read probe data */
da24c5e3
FB
381 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
382 url_fseek(pb, 0, SEEK_SET);
5b25dfa7 383 }
96baaa6a
FB
384 }
385
b9a281db
FB
386 /* guess file format */
387 if (!fmt) {
a25e098d 388 fmt = av_probe_input_format(pd, 1);
b9a281db
FB
389 }
390
391 /* if still no format found, error */
392 if (!fmt) {
393 err = AVERROR_NOFMT;
da24c5e3 394 goto fail;
de6d9b64 395 }
b9a281db 396
67d06418 397 /* XXX: suppress this hack for redirectors */
f3ec2d46 398#ifdef CONFIG_NETWORK
67d06418 399 if (fmt == &redir_demux) {
da24c5e3
FB
400 err = redir_open(ic_ptr, pb);
401 url_fclose(pb);
67d06418
FB
402 return err;
403 }
9b2e001f 404#endif
67d06418 405
87a0a681 406 /* check filename in case of an image number is expected */
da24c5e3
FB
407 if (fmt->flags & AVFMT_NEEDNUMBER) {
408 if (filename_number_test(filename) < 0) {
87a0a681 409 err = AVERROR_NUMEXPECTED;
da24c5e3 410 goto fail;
87a0a681
FB
411 }
412 }
da24c5e3
FB
413 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
414 if (err)
415 goto fail;
b9a281db 416 return 0;
de6d9b64 417 fail:
da24c5e3
FB
418 if (file_opened)
419 url_fclose(pb);
b9a281db
FB
420 *ic_ptr = NULL;
421 return err;
da24c5e3 422
de6d9b64
FB
423}
424
da24c5e3
FB
425/*******************************************************/
426
b9a281db 427/**
da24c5e3
FB
428 * Read a packet from a media file. Use it only for low level file
429 * reading. It is almost always better to use av_read_frame().
430 *
b9a281db
FB
431 * @param s media file handle
432 * @param pkt is filled
da24c5e3 433 * @return 0 if OK. AVERROR_xxx if error.
b9a281db 434 */
de6d9b64
FB
435int av_read_packet(AVFormatContext *s, AVPacket *pkt)
436{
437 AVPacketList *pktl;
438
439 pktl = s->packet_buffer;
440 if (pktl) {
441 /* read packet from packet buffer, if there is data */
442 *pkt = pktl->pkt;
443 s->packet_buffer = pktl->next;
1ea4f593 444 av_free(pktl);
de6d9b64
FB
445 return 0;
446 } else {
b9a281db
FB
447 return s->iformat->read_packet(s, pkt);
448 }
449}
450
da24c5e3 451/*******************************************************/
12f996ed
FB
452
453/* return TRUE if the stream has accurate timings for at least one component */
454static int av_has_timings(AVFormatContext *ic)
455{
456 int i;
457 AVStream *st;
458
459 for(i = 0;i < ic->nb_streams; i++) {
460 st = ic->streams[i];
461 if (st->start_time != AV_NOPTS_VALUE &&
462 st->duration != AV_NOPTS_VALUE)
463 return 1;
464 }
465 return 0;
466}
467
468/* estimate the stream timings from the one of each components. Also
469 compute the global bitrate if possible */
470static void av_update_stream_timings(AVFormatContext *ic)
471{
472 int64_t start_time, end_time, end_time1;
473 int i;
474 AVStream *st;
475
476 start_time = MAXINT64;
477 end_time = MININT64;
478 for(i = 0;i < ic->nb_streams; i++) {
479 st = ic->streams[i];
480 if (st->start_time != AV_NOPTS_VALUE) {
481 if (st->start_time < start_time)
482 start_time = st->start_time;
483 if (st->duration != AV_NOPTS_VALUE) {
484 end_time1 = st->start_time + st->duration;
485 if (end_time1 > end_time)
486 end_time = end_time1;
487 }
488 }
489 }
490 if (start_time != MAXINT64) {
491 ic->start_time = start_time;
492 if (end_time != MAXINT64) {
493 ic->duration = end_time - start_time;
494 if (ic->file_size > 0) {
495 /* compute the bit rate */
496 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
497 (double)ic->duration;
498 }
499 }
500 }
501
502}
503
504static void fill_all_stream_timings(AVFormatContext *ic)
505{
506 int i;
507 AVStream *st;
508
509 av_update_stream_timings(ic);
510 for(i = 0;i < ic->nb_streams; i++) {
511 st = ic->streams[i];
512 if (st->start_time == AV_NOPTS_VALUE) {
513 st->start_time = ic->start_time;
514 st->duration = ic->duration;
515 }
516 }
517}
518
519static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
520{
521 int64_t filesize, duration;
522 int bit_rate, i;
523 AVStream *st;
524
525 /* if bit_rate is already set, we believe it */
526 if (ic->bit_rate == 0) {
527 bit_rate = 0;
528 for(i=0;i<ic->nb_streams;i++) {
529 st = ic->streams[i];
530 bit_rate += st->codec.bit_rate;
531 }
532 ic->bit_rate = bit_rate;
533 }
534
535 /* if duration is already set, we believe it */
536 if (ic->duration == AV_NOPTS_VALUE &&
537 ic->bit_rate != 0 &&
538 ic->file_size != 0) {
539 filesize = ic->file_size;
540 if (filesize > 0) {
541 duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
542 for(i = 0; i < ic->nb_streams; i++) {
543 st = ic->streams[i];
544 if (st->start_time == AV_NOPTS_VALUE ||
545 st->duration == AV_NOPTS_VALUE) {
546 st->start_time = 0;
547 st->duration = duration;
548 }
549 }
550 }
551 }
552}
553
554static void flush_packet_queue(AVFormatContext *s)
555{
556 AVPacketList *pktl;
557
558 for(;;) {
559 pktl = s->packet_buffer;
560 if (!pktl)
561 break;
562 s->packet_buffer = pktl->next;
0a5f92a1 563 av_free_packet(&pktl->pkt);
12f996ed
FB
564 av_free(pktl);
565 }
566}
567
568#define DURATION_MAX_READ_SIZE 250000
569
570/* only usable for MPEG-PS streams */
571static void av_estimate_timings_from_pts(AVFormatContext *ic)
572{
573 AVPacket pkt1, *pkt = &pkt1;
574 AVStream *st;
575 int read_size, i, ret;
576 int64_t start_time, end_time, end_time1;
577 int64_t filesize, offset, duration;
578
579 /* we read the first packets to get the first PTS (not fully
580 accurate, but it is enough now) */
581 url_fseek(&ic->pb, 0, SEEK_SET);
582 read_size = 0;
583 for(;;) {
584 if (read_size >= DURATION_MAX_READ_SIZE)
585 break;
586 /* if all info is available, we can stop */
587 for(i = 0;i < ic->nb_streams; i++) {
588 st = ic->streams[i];
589 if (st->start_time == AV_NOPTS_VALUE)
590 break;
591 }
592 if (i == ic->nb_streams)
593 break;
594
595 ret = av_read_packet(ic, pkt);
596 if (ret != 0)
597 break;
598 read_size += pkt->size;
599 st = ic->streams[pkt->stream_index];
600 if (pkt->pts != AV_NOPTS_VALUE) {
601 if (st->start_time == AV_NOPTS_VALUE)
602 st->start_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
0a5f92a1
MN
603 }
604 av_free_packet(pkt);
605 }
12f996ed
FB
606
607 /* we compute the minimum start_time and use it as default */
608 start_time = MAXINT64;
609 for(i = 0; i < ic->nb_streams; i++) {
610 st = ic->streams[i];
611 if (st->start_time != AV_NOPTS_VALUE &&
612 st->start_time < start_time)
613 start_time = st->start_time;
614 }
12f996ed
FB
615 if (start_time != MAXINT64)
616 ic->start_time = start_time;
617
618 /* estimate the end time (duration) */
619 /* XXX: may need to support wrapping */
620 filesize = ic->file_size;
621 offset = filesize - DURATION_MAX_READ_SIZE;
622 if (offset < 0)
623 offset = 0;
624
625 /* flush packet queue */
626 flush_packet_queue(ic);
627
628 url_fseek(&ic->pb, offset, SEEK_SET);
629 read_size = 0;
630 for(;;) {
631 if (read_size >= DURATION_MAX_READ_SIZE)
632 break;
633 /* if all info is available, we can stop */
634 for(i = 0;i < ic->nb_streams; i++) {
635 st = ic->streams[i];
636 if (st->duration == AV_NOPTS_VALUE)
637 break;
638 }
639 if (i == ic->nb_streams)
640 break;
641
642 ret = av_read_packet(ic, pkt);
643 if (ret != 0)
644 break;
645 read_size += pkt->size;
646 st = ic->streams[pkt->stream_index];
647 if (pkt->pts != AV_NOPTS_VALUE) {
648 end_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
649 duration = end_time - st->start_time;
650 if (duration > 0) {
651 if (st->duration == AV_NOPTS_VALUE ||
652 st->duration < duration)
653 st->duration = duration;
654 }
655 }
656 av_free_packet(pkt);
657 }
658
659 /* estimate total duration */
660 end_time = MININT64;
661 for(i = 0;i < ic->nb_streams; i++) {
662 st = ic->streams[i];
663 if (st->duration != AV_NOPTS_VALUE) {
664 end_time1 = st->start_time + st->duration;
665 if (end_time1 > end_time)
666 end_time = end_time1;
667 }
668 }
669
670 /* update start_time (new stream may have been created, so we do
671 it at the end */
672 if (ic->start_time != AV_NOPTS_VALUE) {
673 for(i = 0; i < ic->nb_streams; i++) {
674 st = ic->streams[i];
675 if (st->start_time == AV_NOPTS_VALUE)
676 st->start_time = ic->start_time;
677 }
678 }
679
680 if (end_time != MININT64) {
681 /* put dummy values for duration if needed */
682 for(i = 0;i < ic->nb_streams; i++) {
683 st = ic->streams[i];
684 if (st->duration == AV_NOPTS_VALUE &&
685 st->start_time != AV_NOPTS_VALUE)
686 st->duration = end_time - st->start_time;
687 }
688 ic->duration = end_time - ic->start_time;
689 }
690
691 url_fseek(&ic->pb, 0, SEEK_SET);
692}
693
694static void av_estimate_timings(AVFormatContext *ic)
695{
696 URLContext *h;
697 int64_t file_size;
698
699 /* get the file size, if possible */
700 if (ic->iformat->flags & AVFMT_NOFILE) {
701 file_size = 0;
702 } else {
703 h = url_fileno(&ic->pb);
704 file_size = url_filesize(h);
705 if (file_size < 0)
706 file_size = 0;
707 }
708 ic->file_size = file_size;
709
710 if (ic->iformat == &mpegps_demux) {
711 /* get accurate estimate from the PTSes */
712 av_estimate_timings_from_pts(ic);
713 } else if (av_has_timings(ic)) {
714 /* at least one components has timings - we use them for all
715 the components */
716 fill_all_stream_timings(ic);
717 } else {
718 /* less precise: use bit rate info */
719 av_estimate_timings_from_bit_rate(ic);
720 }
721 av_update_stream_timings(ic);
722
723#if 0
724 {
725 int i;
726 AVStream *st;
727 for(i = 0;i < ic->nb_streams; i++) {
728 st = ic->streams[i];
729 printf("%d: start_time: %0.3f duration: %0.3f\n",
730 i, (double)st->start_time / AV_TIME_BASE,
731 (double)st->duration / AV_TIME_BASE);
732 }
733 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
734 (double)ic->start_time / AV_TIME_BASE,
735 (double)ic->duration / AV_TIME_BASE,
736 ic->bit_rate / 1000);
737 }
738#endif
739}
740
b9a281db
FB
741/* state for codec information */
742#define CSTATE_NOTFOUND 0
743#define CSTATE_DECODING 1
744#define CSTATE_FOUND 2
745
746static int has_codec_parameters(AVCodecContext *enc)
747{
748 int val;
749 switch(enc->codec_type) {
750 case CODEC_TYPE_AUDIO:
751 val = enc->sample_rate;
752 break;
753 case CODEC_TYPE_VIDEO:
754 val = enc->width;
755 break;
756 default:
757 val = 1;
758 break;
759 }
760 return (val != 0);
761}
762
763/**
764 * Read the beginning of a media file to get stream information. This
765 * is useful for file formats with no headers such as MPEG. This
766 * function also compute the real frame rate in case of mpeg2 repeat
767 * frame mode.
768 *
769 * @param ic media file handle
770 * @return >=0 if OK. AVERROR_xxx if error.
771 */
772int av_find_stream_info(AVFormatContext *ic)
773{
774 int i, count, ret, got_picture, size, read_size;
775 AVCodec *codec;
776 AVStream *st;
777 AVPacket *pkt;
492cd3a9 778 AVFrame picture;
b9a281db
FB
779 AVPacketList *pktl=NULL, **ppktl;
780 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
0c1a9eda 781 uint8_t *ptr;
b9a281db
FB
782 int min_read_size, max_read_size;
783
784 /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
b530f842 785 Mbits. We read at most 0.2 second of file to find all streams */
b9a281db
FB
786
787 /* XXX: base it on stream bitrate when possible */
788 if (ic->iformat == &mpegts_demux) {
789 /* maximum number of bytes we accept to read to find all the streams
790 in a file */
b530f842 791 min_read_size = 6000000;
b9a281db 792 } else {
b530f842 793 min_read_size = 250000;
b9a281db
FB
794 }
795 /* max read size is 2 seconds of video max */
b530f842 796 max_read_size = min_read_size * 10;
b9a281db
FB
797
798 /* set initial codec state */
799 for(i=0;i<ic->nb_streams;i++) {
800 st = ic->streams[i];
801 if (has_codec_parameters(&st->codec))
802 st->codec_info_state = CSTATE_FOUND;
803 else
804 st->codec_info_state = CSTATE_NOTFOUND;
805 st->codec_info_nb_repeat_frames = 0;
806 st->codec_info_nb_real_frames = 0;
807 }
808
809 count = 0;
810 read_size = 0;
811 ppktl = &ic->packet_buffer;
812 for(;;) {
813 /* check if one codec still needs to be handled */
814 for(i=0;i<ic->nb_streams;i++) {
815 st = ic->streams[i];
816 if (st->codec_info_state != CSTATE_FOUND)
817 break;
818 }
819 if (i == ic->nb_streams) {
820 /* NOTE: if the format has no header, then we need to read
821 some packets to get most of the streams, so we cannot
822 stop here */
da24c5e3 823 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER) ||
b9a281db
FB
824 read_size >= min_read_size) {
825 /* if we found the info for all the codecs, we can stop */
826 ret = count;
827 break;
828 }
829 } else {
830 /* we did not get all the codec info, but we read too much data */
831 if (read_size >= max_read_size) {
832 ret = count;
833 break;
834 }
835 }
836
837 pktl = av_mallocz(sizeof(AVPacketList));
838 if (!pktl) {
839 ret = AVERROR_NOMEM;
840 break;
841 }
842
843 /* add the packet in the buffered packet list */
844 *ppktl = pktl;
845 ppktl = &pktl->next;
846
847 /* NOTE: a new stream can be added there if no header in file
da24c5e3 848 (AVFMTCTX_NOHEADER) */
b9a281db
FB
849 pkt = &pktl->pkt;
850 if (ic->iformat->read_packet(ic, pkt) < 0) {
851 /* EOF or error */
852 ret = -1; /* we could not have all the codec parameters before EOF */
da24c5e3 853 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
b9a281db
FB
854 i == ic->nb_streams)
855 ret = 0;
856 break;
857 }
858 read_size += pkt->size;
859
860 /* open new codecs */
861 for(i=0;i<ic->nb_streams;i++) {
862 st = ic->streams[i];
863 if (st->codec_info_state == CSTATE_NOTFOUND) {
864 /* set to found in case of error */
865 st->codec_info_state = CSTATE_FOUND;
866 codec = avcodec_find_decoder(st->codec.codec_id);
867 if (codec) {
d7425f59
MN
868 if(codec->capabilities & CODEC_CAP_TRUNCATED)
869 st->codec.flags |= CODEC_FLAG_TRUNCATED;
870
b9a281db
FB
871 ret = avcodec_open(&st->codec, codec);
872 if (ret >= 0)
873 st->codec_info_state = CSTATE_DECODING;
874 }
875 }
876 }
877
878 st = ic->streams[pkt->stream_index];
879 if (st->codec_info_state == CSTATE_DECODING) {
880 /* decode the data and update codec parameters */
881 ptr = pkt->data;
882 size = pkt->size;
883 while (size > 0) {
884 switch(st->codec.codec_type) {
885 case CODEC_TYPE_VIDEO:
886 ret = avcodec_decode_video(&st->codec, &picture,
887 &got_picture, ptr, size);
888 break;
889 case CODEC_TYPE_AUDIO:
890 ret = avcodec_decode_audio(&st->codec, samples,
891 &got_picture, ptr, size);
892 break;
893 default:
894 ret = -1;
895 break;
896 }
897 if (ret < 0) {
898 /* if error, simply ignore because another packet
899 may be OK */
900 break;
901 }
902 if (got_picture) {
903 /* we got the parameters - now we can stop
904 examining this stream */
905 /* XXX: add a codec info so that we can decide if
906 the codec can repeat frames */
907 if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO &&
908 ic->iformat != &mpegts_demux &&
909 st->codec.sub_id == 2) {
910 /* for mpeg2 video, we want to know the real
911 frame rate, so we decode 40 frames. In mpeg
912 TS case we do not do it because it would be
913 too long */
914 st->codec_info_nb_real_frames++;
2ec23b6d 915 st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
b9a281db
FB
916#if 0
917 /* XXX: testing */
918 if ((st->codec_info_nb_real_frames % 24) == 23) {
919 st->codec_info_nb_repeat_frames += 2;
920 }
921#endif
922 /* stop after 40 frames */
923 if (st->codec_info_nb_real_frames >= 40) {
14bea432
MN
924 av_reduce(
925 &st->r_frame_rate,
926 &st->r_frame_rate_base,
927 (int64_t)st->codec.frame_rate * st->codec_info_nb_real_frames,
e71ea8b2 928 (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
14bea432 929 1<<30);
b9a281db
FB
930 goto close_codec;
931 }
932 } else {
933 close_codec:
934 st->codec_info_state = CSTATE_FOUND;
935 avcodec_close(&st->codec);
24f9709b 936 break;
b9a281db 937 }
b9a281db
FB
938 }
939 ptr += ret;
940 size -= ret;
941 }
942 }
943 count++;
944 }
945
946 /* close each codec if there are opened */
947 for(i=0;i<ic->nb_streams;i++) {
948 st = ic->streams[i];
949 if (st->codec_info_state == CSTATE_DECODING)
950 avcodec_close(&st->codec);
951 }
952
953 /* set real frame rate info */
954 for(i=0;i<ic->nb_streams;i++) {
955 st = ic->streams[i];
956 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
14bea432
MN
957 if (!st->r_frame_rate){
958 st->r_frame_rate = st->codec.frame_rate;
959 st->r_frame_rate_base = st->codec.frame_rate_base;
960 }
b9a281db 961 }
de6d9b64 962 }
b9a281db 963
12f996ed
FB
964
965 av_estimate_timings(ic);
b9a281db 966 return ret;
de6d9b64
FB
967}
968
b9a281db
FB
969/**
970 * Close a media file (but not its codecs)
971 *
972 * @param s media file handle
973 */
de6d9b64
FB
974void av_close_input_file(AVFormatContext *s)
975{
b6892136 976 int i, must_open_file;
da24c5e3 977 AVStream *st;
de6d9b64 978
b9a281db
FB
979 if (s->iformat->read_close)
980 s->iformat->read_close(s);
de6d9b64 981 for(i=0;i<s->nb_streams;i++) {
da24c5e3
FB
982 /* free all data in a stream component */
983 st = s->streams[i];
984 av_free(st);
de6d9b64
FB
985 }
986 if (s->packet_buffer) {
987 AVPacketList *p, *p1;
988 p = s->packet_buffer;
989 while (p != NULL) {
990 p1 = p->next;
991 av_free_packet(&p->pkt);
1ea4f593 992 av_free(p);
de6d9b64
FB
993 p = p1;
994 }
995 s->packet_buffer = NULL;
996 }
b6892136 997 must_open_file = 1;
da24c5e3 998 if (s->iformat->flags & AVFMT_NOFILE) {
b6892136
FB
999 must_open_file = 0;
1000 }
1001 if (must_open_file) {
96baaa6a
FB
1002 url_fclose(&s->pb);
1003 }
a8dbe951 1004 av_freep(&s->priv_data);
1ea4f593 1005 av_free(s);
de6d9b64
FB
1006}
1007
b9a281db
FB
1008/**
1009 * Add a new stream to a media file. Can only be called in the
da24c5e3
FB
1010 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
1011 * format context, then new streams can be added in read_packet too.
b9a281db
FB
1012 *
1013 *
1014 * @param s media file handle
da24c5e3 1015 * @param id file format dependent stream id
b9a281db
FB
1016 */
1017AVStream *av_new_stream(AVFormatContext *s, int id)
1018{
1019 AVStream *st;
1020
1021 if (s->nb_streams >= MAX_STREAMS)
1022 return NULL;
1023
1024 st = av_mallocz(sizeof(AVStream));
1025 if (!st)
1026 return NULL;
1e491e29 1027 avcodec_get_context_defaults(&st->codec);
48091512
FB
1028 if (s->iformat) {
1029 /* no default bitrate if decoding */
1030 st->codec.bit_rate = 0;
1031 }
b9a281db
FB
1032 st->index = s->nb_streams;
1033 st->id = id;
12f996ed
FB
1034 st->start_time = AV_NOPTS_VALUE;
1035 st->duration = AV_NOPTS_VALUE;
b9a281db
FB
1036 s->streams[s->nb_streams++] = st;
1037 return st;
1038}
1039
1040/************************************************************/
1041/* output media file */
de6d9b64 1042
87a0a681
FB
1043int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1044{
1045 int ret;
98486a6b
RS
1046
1047 if (s->oformat->priv_data_size > 0) {
1048 s->priv_data = av_mallocz(s->oformat->priv_data_size);
1049 if (!s->priv_data)
1050 return AVERROR_NOMEM;
1051 } else
1052 s->priv_data = NULL;
1053
87a0a681
FB
1054 if (s->oformat->set_parameters) {
1055 ret = s->oformat->set_parameters(s, ap);
1056 if (ret < 0)
1057 return ret;
1058 }
1059 return 0;
1060}
1061
b9a281db
FB
1062/**
1063 * allocate the stream private data and write the stream header to an
1064 * output media file
1065 *
1066 * @param s media file handle
1067 * @return 0 if OK. AVERROR_xxx if error.
1068 */
1069int av_write_header(AVFormatContext *s)
1070{
1e51d801
FB
1071 int ret, i;
1072 AVStream *st;
1073
916c80e9
FB
1074 /* default pts settings is MPEG like */
1075 av_set_pts_info(s, 33, 1, 90000);
1e51d801
FB
1076 ret = s->oformat->write_header(s);
1077 if (ret < 0)
1078 return ret;
1079
1080 /* init PTS generation */
1081 for(i=0;i<s->nb_streams;i++) {
1082 st = s->streams[i];
1083
1084 switch (st->codec.codec_type) {
1085 case CODEC_TYPE_AUDIO:
1086 av_frac_init(&st->pts, 0, 0,
0c1a9eda 1087 (int64_t)s->pts_num * st->codec.sample_rate);
1e51d801
FB
1088 break;
1089 case CODEC_TYPE_VIDEO:
1090 av_frac_init(&st->pts, 0, 0,
0c1a9eda 1091 (int64_t)s->pts_num * st->codec.frame_rate);
1e51d801
FB
1092 break;
1093 default:
1094 break;
1095 }
1096 }
1097 return 0;
b9a281db
FB
1098}
1099
1100/**
1e51d801
FB
1101 * Write a packet to an output media file. The packet shall contain
1102 * one audio or video frame.
b9a281db
FB
1103 *
1104 * @param s media file handle
1e51d801
FB
1105 * @param stream_index stream index
1106 * @param buf buffer containing the frame data
1107 * @param size size of buffer
d4c0ff91 1108 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
b9a281db 1109 */
1e51d801
FB
1110int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf,
1111 int size)
de6d9b64 1112{
1e51d801 1113 AVStream *st;
0c1a9eda 1114 int64_t pts_mask;
7feb950a 1115 int ret, frame_size;
1e51d801
FB
1116
1117 st = s->streams[stream_index];
1118 pts_mask = (1LL << s->pts_wrap_bits) - 1;
1119 ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size,
1120 st->pts.val & pts_mask);
1121 if (ret < 0)
1122 return ret;
1123
1124 /* update pts */
1125 switch (st->codec.codec_type) {
1126 case CODEC_TYPE_AUDIO:
7feb950a
FB
1127 if (st->codec.frame_size <= 1) {
1128 frame_size = size / st->codec.channels;
1129 /* specific hack for pcm codecs because no frame size is provided */
50d5d129 1130 switch(st->codec.codec_id) {
7feb950a
FB
1131 case CODEC_ID_PCM_S16LE:
1132 case CODEC_ID_PCM_S16BE:
1133 case CODEC_ID_PCM_U16LE:
1134 case CODEC_ID_PCM_U16BE:
1135 frame_size >>= 1;
1136 break;
1137 default:
1138 break;
1139 }
1140 } else {
1141 frame_size = st->codec.frame_size;
1142 }
1e51d801 1143 av_frac_add(&st->pts,
0c1a9eda 1144 (int64_t)s->pts_den * frame_size);
1e51d801
FB
1145 break;
1146 case CODEC_TYPE_VIDEO:
1147 av_frac_add(&st->pts,
14bea432 1148 (int64_t)s->pts_den * st->codec.frame_rate_base);
1e51d801
FB
1149 break;
1150 default:
1151 break;
1152 }
d4c0ff91 1153 return ret;
b9a281db
FB
1154}
1155
1156/**
1157 * write the stream trailer to an output media file and and free the
1158 * file private data.
1159 *
1160 * @param s media file handle
1161 * @return 0 if OK. AVERROR_xxx if error. */
1162int av_write_trailer(AVFormatContext *s)
1163{
1164 int ret;
1165 ret = s->oformat->write_trailer(s);
1166 av_freep(&s->priv_data);
1167 return ret;
de6d9b64
FB
1168}
1169
1170/* "user interface" functions */
1171
1172void dump_format(AVFormatContext *ic,
1173 int index,
1174 const char *url,
1175 int is_output)
1176{
b9a281db 1177 int i, flags;
de6d9b64
FB
1178 char buf[256];
1179
1180 fprintf(stderr, "%s #%d, %s, %s '%s':\n",
1181 is_output ? "Output" : "Input",
b9a281db
FB
1182 index,
1183 is_output ? ic->oformat->name : ic->iformat->name,
de6d9b64 1184 is_output ? "to" : "from", url);
12f996ed 1185 if (!is_output) {
c9245417 1186 fprintf(stderr, " Duration: ");
12f996ed
FB
1187 if (ic->duration != AV_NOPTS_VALUE) {
1188 int hours, mins, secs, us;
1189 secs = ic->duration / AV_TIME_BASE;
1190 us = ic->duration % AV_TIME_BASE;
1191 mins = secs / 60;
1192 secs %= 60;
1193 hours = mins / 60;
1194 mins %= 60;
c9245417 1195 fprintf(stderr, "%02d:%02d:%02d.%01d", hours, mins, secs,
12f996ed
FB
1196 (10 * us) / AV_TIME_BASE);
1197 } else {
c9245417 1198 fprintf(stderr, "N/A");
12f996ed 1199 }
c9245417 1200 fprintf(stderr, ", bitrate: ");
12f996ed 1201 if (ic->bit_rate) {
c9245417 1202 fprintf(stderr,"%d kb/s", ic->bit_rate / 1000);
12f996ed 1203 } else {
c9245417 1204 fprintf(stderr, "N/A");
12f996ed 1205 }
c9245417 1206 fprintf(stderr, "\n");
12f996ed 1207 }
de6d9b64
FB
1208 for(i=0;i<ic->nb_streams;i++) {
1209 AVStream *st = ic->streams[i];
1210 avcodec_string(buf, sizeof(buf), &st->codec, is_output);
b9a281db
FB
1211 fprintf(stderr, " Stream #%d.%d", index, i);
1212 /* the pid is an important information, so we display it */
1213 /* XXX: add a generic system */
1214 if (is_output)
1215 flags = ic->oformat->flags;
1216 else
1217 flags = ic->iformat->flags;
1218 if (flags & AVFMT_SHOW_IDS) {
1219 fprintf(stderr, "[0x%x]", st->id);
1220 }
1221 fprintf(stderr, ": %s\n", buf);
de6d9b64
FB
1222 }
1223}
1224
1225typedef struct {
445f1b83 1226 const char *abv;
de6d9b64 1227 int width, height;
445f1b83
RS
1228 int frame_rate, frame_rate_base;
1229} AbvEntry;
1230
1231static AbvEntry frame_abvs[] = {
ba2a8cb4
RS
1232 { "ntsc", 720, 480, 30000, 1001 },
1233 { "pal", 720, 576, 25, 1 },
1234 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
1235 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
904736b5
RS
1236 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
1237 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
445f1b83
RS
1238 { "film", 352, 240, 24, 1 },
1239 { "ntsc-film", 352, 240, 24000, 1001 },
1240 { "sqcif", 128, 96, 0, 0 },
1241 { "qcif", 176, 144, 0, 0 },
1242 { "cif", 352, 288, 0, 0 },
1243 { "4cif", 704, 576, 0, 0 },
de6d9b64 1244};
445f1b83 1245
de6d9b64
FB
1246int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
1247{
1248 int i;
445f1b83 1249 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
de6d9b64
FB
1250 const char *p;
1251 int frame_width = 0, frame_height = 0;
1252
1253 for(i=0;i<n;i++) {
445f1b83
RS
1254 if (!strcmp(frame_abvs[i].abv, str)) {
1255 frame_width = frame_abvs[i].width;
1256 frame_height = frame_abvs[i].height;
de6d9b64
FB
1257 break;
1258 }
1259 }
1260 if (i == n) {
1261 p = str;
1262 frame_width = strtol(p, (char **)&p, 10);
1263 if (*p)
1264 p++;
1265 frame_height = strtol(p, (char **)&p, 10);
1266 }
1267 if (frame_width <= 0 || frame_height <= 0)
1268 return -1;
1269 *width_ptr = frame_width;
1270 *height_ptr = frame_height;
1271 return 0;
1272}
1273
445f1b83
RS
1274int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
1275{
1276 int i;
1277 char* cp;
1278
1279 /* First, we check our abbreviation table */
1280 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
1281 if (!strcmp(frame_abvs[i].abv, arg)) {
1282 *frame_rate = frame_abvs[i].frame_rate;
1283 *frame_rate_base = frame_abvs[i].frame_rate_base;
1284 return 0;
1285 }
1286
1287 /* Then, we try to parse it as fraction */
1288 cp = strchr(arg, '/');
1289 if (cp) {
1290 char* cpp;
1291 *frame_rate = strtol(arg, &cpp, 10);
1292 if (cpp != arg || cpp == cp)
1293 *frame_rate_base = strtol(cp+1, &cpp, 10);
1294 else
1295 *frame_rate = 0;
1296 }
1297 else {
1298 /* Finally we give up and parse it as double */
1299 *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
1300 *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
1301 }
1302 if (!*frame_rate || !*frame_rate_base)
1303 return -1;
1304 else
1305 return 0;
1306}
1307
916c80e9
FB
1308/* Syntax:
1309 * - If not a duration:
1310 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
c5510dd6 1311 * Time is localtime unless Z is suffixed to the end. In this case GMT
916c80e9
FB
1312 * Return the date in micro seconds since 1970
1313 * - If duration:
1314 * HH[:MM[:SS[.m...]]]
1315 * S+[.m...]
1316 */
0c1a9eda 1317int64_t parse_date(const char *datestr, int duration)
de6d9b64
FB
1318{
1319 const char *p;
0c1a9eda 1320 int64_t t;
2dbceb9f 1321 struct tm dt;
c5510dd6
PG
1322 int i;
1323 static const char *date_fmt[] = {
1324 "%Y-%m-%d",
1325 "%Y%m%d",
1326 };
1327 static const char *time_fmt[] = {
1328 "%H:%M:%S",
1329 "%H%M%S",
1330 };
1331 const char *q;
916c80e9 1332 int is_utc, len;
c5510dd6
PG
1333 char lastch;
1334 time_t now = time(0);
1335
916c80e9
FB
1336 len = strlen(datestr);
1337 if (len > 0)
1338 lastch = datestr[len - 1];
1339 else
1340 lastch = '\0';
c5510dd6 1341 is_utc = (lastch == 'z' || lastch == 'Z');
2dbceb9f
PG
1342
1343 memset(&dt, 0, sizeof(dt));
de6d9b64
FB
1344
1345 p = datestr;
916c80e9 1346 q = NULL;
de6d9b64 1347 if (!duration) {
c5510dd6 1348 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
f71869a4 1349 q = small_strptime(p, date_fmt[i], &dt);
c5510dd6
PG
1350 if (q) {
1351 break;
1352 }
1353 }
1354
1355 if (!q) {
1356 if (is_utc) {
1357 dt = *gmtime(&now);
1358 } else {
1359 dt = *localtime(&now);
1360 }
1361 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
de6d9b64 1362 } else {
c5510dd6 1363 p = q;
de6d9b64 1364 }
c5510dd6
PG
1365
1366 if (*p == 'T' || *p == 't' || *p == ' ')
1367 p++;
c5510dd6 1368
916c80e9 1369 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
f71869a4 1370 q = small_strptime(p, time_fmt[i], &dt);
916c80e9
FB
1371 if (q) {
1372 break;
1373 }
1374 }
1375 } else {
f71869a4 1376 q = small_strptime(p, time_fmt[0], &dt);
916c80e9
FB
1377 if (!q) {
1378 dt.tm_sec = strtol(p, (char **)&q, 10);
1379 dt.tm_min = 0;
1380 dt.tm_hour = 0;
c5510dd6
PG
1381 }
1382 }
1383
1384 /* Now we have all the fields that we can get */
1385 if (!q) {
1386 if (duration)
1387 return 0;
1388 else
0c1a9eda 1389 return now * int64_t_C(1000000);
de6d9b64 1390 }
2dbceb9f
PG
1391
1392 if (duration) {
c5510dd6 1393 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2dbceb9f 1394 } else {
c5510dd6
PG
1395 dt.tm_isdst = -1; /* unknown */
1396 if (is_utc) {
1397 t = mktimegm(&dt);
1398 } else {
1399 t = mktime(&dt);
1400 }
de6d9b64 1401 }
2dbceb9f 1402
c5510dd6
PG
1403 t *= 1000000;
1404
1405 if (*q == '.') {
de6d9b64 1406 int val, n;
c5510dd6
PG
1407 q++;
1408 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1409 if (!isdigit(*q))
1410 break;
1411 val += n * (*q - '0');
de6d9b64
FB
1412 }
1413 t += val;
1414 }
1415 return t;
1416}
1417
2dbceb9f 1418/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
de6d9b64
FB
1419 1 if found */
1420int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1421{
1422 const char *p;
1423 char tag[128], *q;
1424
1425 p = info;
1426 if (*p == '?')
1427 p++;
1428 for(;;) {
1429 q = tag;
1430 while (*p != '\0' && *p != '=' && *p != '&') {
1431 if ((q - tag) < sizeof(tag) - 1)
1432 *q++ = *p;
1433 p++;
1434 }
1435 *q = '\0';
1436 q = arg;
1437 if (*p == '=') {
1438 p++;
1439 while (*p != '&' && *p != '\0') {
2dbceb9f
PG
1440 if ((q - arg) < arg_size - 1) {
1441 if (*p == '+')
1442 *q++ = ' ';
1443 else
1444 *q++ = *p;
1445 }
de6d9b64
FB
1446 p++;
1447 }
1448 *q = '\0';
1449 }
1450 if (!strcmp(tag, tag1))
1451 return 1;
1452 if (*p != '&')
1453 break;
8d1335ea 1454 p++;
de6d9b64
FB
1455 }
1456 return 0;
1457}
1458
9150f42e
FB
1459/* Return in 'buf' the path with '%d' replaced by number. Also handles
1460 the '%0nd' format where 'n' is the total number of digits and
1461 '%%'. Return 0 if OK, and -1 if format error */
1462int get_frame_filename(char *buf, int buf_size,
1463 const char *path, int number)
1464{
1465 const char *p;
0bf92f79
PI
1466 char *q, buf1[20], c;
1467 int nd, len, percentd_found;
9150f42e
FB
1468
1469 q = buf;
1470 p = path;
1471 percentd_found = 0;
1472 for(;;) {
1473 c = *p++;
1474 if (c == '\0')
1475 break;
1476 if (c == '%') {
c9646fda
PG
1477 do {
1478 nd = 0;
1479 while (isdigit(*p)) {
1480 nd = nd * 10 + *p++ - '0';
1481 }
1482 c = *p++;
c9646fda
PG
1483 } while (isdigit(c));
1484
9150f42e
FB
1485 switch(c) {
1486 case '%':
1487 goto addchar;
1488 case 'd':
1489 if (percentd_found)
1490 goto fail;
1491 percentd_found = 1;
1492 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1493 len = strlen(buf1);
1494 if ((q - buf + len) > buf_size - 1)
1495 goto fail;
1496 memcpy(q, buf1, len);
1497 q += len;
1498 break;
1499 default:
1500 goto fail;
1501 }
1502 } else {
1503 addchar:
1504 if ((q - buf) < buf_size - 1)
1505 *q++ = c;
1506 }
1507 }
1508 if (!percentd_found)
1509 goto fail;
1510 *q = '\0';
1511 return 0;
1512 fail:
1513 *q = '\0';
1514 return -1;
1515}
1516
b9a281db
FB
1517/**
1518 *
1519 * Print on stdout a nice hexa dump of a buffer
1520 * @param buf buffer
1521 * @param size buffer size
1522 */
0c1a9eda 1523void av_hex_dump(uint8_t *buf, int size)
b9a281db
FB
1524{
1525 int len, i, j, c;
1526
1527 for(i=0;i<size;i+=16) {
1528 len = size - i;
1529 if (len > 16)
1530 len = 16;
1531 printf("%08x ", i);
1532 for(j=0;j<16;j++) {
1533 if (j < len)
1534 printf(" %02x", buf[i+j]);
1535 else
1536 printf(" ");
1537 }
1538 printf(" ");
1539 for(j=0;j<len;j++) {
1540 c = buf[i+j];
1541 if (c < ' ' || c > '~')
1542 c = '.';
1543 printf("%c", c);
1544 }
1545 printf("\n");
1546 }
1547}
1548
a9a721da
FB
1549void url_split(char *proto, int proto_size,
1550 char *hostname, int hostname_size,
1551 int *port_ptr,
1552 char *path, int path_size,
1553 const char *url)
1554{
1555 const char *p;
1556 char *q;
1557 int port;
1558
1559 port = -1;
1560
1561 p = url;
1562 q = proto;
1563 while (*p != ':' && *p != '\0') {
1564 if ((q - proto) < proto_size - 1)
1565 *q++ = *p;
1566 p++;
1567 }
1568 if (proto_size > 0)
1569 *q = '\0';
1570 if (*p == '\0') {
1571 if (proto_size > 0)
1572 proto[0] = '\0';
1573 if (hostname_size > 0)
1574 hostname[0] = '\0';
1575 p = url;
1576 } else {
1577 p++;
1578 if (*p == '/')
1579 p++;
1580 if (*p == '/')
1581 p++;
1582 q = hostname;
1583 while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1584 if ((q - hostname) < hostname_size - 1)
1585 *q++ = *p;
1586 p++;
1587 }
1588 if (hostname_size > 0)
1589 *q = '\0';
1590 if (*p == ':') {
1591 p++;
1592 port = strtoul(p, (char **)&p, 10);
1593 }
1594 }
1595 if (port_ptr)
1596 *port_ptr = port;
1597 pstrcpy(path, path_size, p);
1598}
1599
916c80e9
FB
1600/**
1601 * Set the pts for a given stream
1602 * @param s stream
1603 * @param pts_wrap_bits number of bits effectively used by the pts
1604 * (used for wrap control, 33 is the value for MPEG)
1605 * @param pts_num numerator to convert to seconds (MPEG: 1)
1606 * @param pts_den denominator to convert to seconds (MPEG: 90000)
1607 */
1608void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1609 int pts_num, int pts_den)
1610{
1611 s->pts_wrap_bits = pts_wrap_bits;
1612 s->pts_num = pts_num;
1613 s->pts_den = pts_den;
1614}
1615
1616/* fraction handling */
1617
1618/**
1619 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1620 * as 0 <= num < den.
1621 *
1622 * @param f fractional number
1623 * @param val integer value
1624 * @param num must be >= 0
1625 * @param den must be >= 1
1626 */
0c1a9eda 1627void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
916c80e9
FB
1628{
1629 num += (den >> 1);
1630 if (num >= den) {
1631 val += num / den;
1632 num = num % den;
1633 }
1634 f->val = val;
1635 f->num = num;
1636 f->den = den;
1637}
1638
1639/* set f to (val + 0.5) */
0c1a9eda 1640void av_frac_set(AVFrac *f, int64_t val)
916c80e9
FB
1641{
1642 f->val = val;
1643 f->num = f->den >> 1;
1644}
1645
1646/**
1647 * Fractionnal addition to f: f = f + (incr / f->den)
1648 *
1649 * @param f fractional number
1650 * @param incr increment, can be positive or negative
1651 */
0c1a9eda 1652void av_frac_add(AVFrac *f, int64_t incr)
916c80e9 1653{
0c1a9eda 1654 int64_t num, den;
916c80e9
FB
1655
1656 num = f->num + incr;
1657 den = f->den;
1658 if (num < 0) {
1659 f->val += num / den;
1660 num = num % den;
1661 if (num < 0) {
1662 num += den;
1663 f->val--;
1664 }
1665 } else if (num >= den) {
1666 f->val += num / den;
1667 num = num % den;
1668 }
1669 f->num = num;
1670}
87a0a681
FB
1671
1672/**
1673 * register a new image format
1674 * @param img_fmt Image format descriptor
1675 */
1676void av_register_image_format(AVImageFormat *img_fmt)
1677{
1678 AVImageFormat **p;
1679
1680 p = &first_image_format;
1681 while (*p != NULL) p = &(*p)->next;
1682 *p = img_fmt;
1683 img_fmt->next = NULL;
1684}
1685
1686/* guess image format */
1687AVImageFormat *av_probe_image_format(AVProbeData *pd)
1688{
1689 AVImageFormat *fmt1, *fmt;
1690 int score, score_max;
1691
1692 fmt = NULL;
1693 score_max = 0;
1694 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1695 if (fmt1->img_probe) {
1696 score = fmt1->img_probe(pd);
1697 if (score > score_max) {
1698 score_max = score;
1699 fmt = fmt1;
1700 }
1701 }
1702 }
1703 return fmt;
1704}
1705
1706AVImageFormat *guess_image_format(const char *filename)
1707{
1708 AVImageFormat *fmt1;
1709
1710 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1711 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
1712 return fmt1;
1713 }
1714 return NULL;
1715}
1716
1717/**
1718 * Read an image from a stream.
1719 * @param gb byte stream containing the image
1720 * @param fmt image format, NULL if probing is required
1721 */
1722int av_read_image(ByteIOContext *pb, const char *filename,
1723 AVImageFormat *fmt,
1724 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
1725{
1726 char buf[PROBE_BUF_SIZE];
1727 AVProbeData probe_data, *pd = &probe_data;
1728 offset_t pos;
1729 int ret;
1730
1731 if (!fmt) {
5c91a675 1732 pd->filename = filename;
87a0a681
FB
1733 pd->buf = buf;
1734 pos = url_ftell(pb);
1735 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
1736 url_fseek(pb, pos, SEEK_SET);
1737 fmt = av_probe_image_format(pd);
1738 }
1739 if (!fmt)
1740 return AVERROR_NOFMT;
1741 ret = fmt->img_read(pb, alloc_cb, opaque);
1742 return ret;
1743}
1744
1745/**
1746 * Write an image to a stream.
1747 * @param pb byte stream for the image output
1748 * @param fmt image format
1749 * @param img image data and informations
1750 */
1751int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
1752{
1753 return fmt->img_write(pb, img);
1754}
1755