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