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