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