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