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