]> git.sesse.net Git - ffmpeg/blob - libavformat/utils.c
fixing CODEC_FLAG_GLOBAL_HEADER
[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 #ifdef CONFIG_NETWORK
341         || (fmt == &rtp_demux && !strcmp(filename, "null"))
342 #endif
343         ) {
344         must_open_file = 0;
345     }
346
347     if (!fmt || must_open_file) {
348         /* if no file needed do not try to open one */
349         if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
350             err = AVERROR_IO;
351             goto fail;
352         }
353         if (buf_size > 0) {
354             url_setbufsize(&ic->pb, buf_size);
355         }
356         if (!fmt) {
357             /* read probe data */
358             pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
359             url_fseek(&ic->pb, 0, SEEK_SET);
360         }
361     }
362     
363     /* guess file format */
364     if (!fmt) {
365         fmt = av_probe_input_format(pd, 1);
366     }
367
368     /* if still no format found, error */
369     if (!fmt) {
370         err = AVERROR_NOFMT;
371         goto fail1;
372     }
373         
374     /* XXX: suppress this hack for redirectors */
375 #ifdef CONFIG_NETWORK
376     if (fmt == &redir_demux) {
377         err = redir_open(ic_ptr, &ic->pb);
378         url_fclose(&ic->pb);
379         av_free(ic);
380         return err;
381     }
382 #endif
383
384     ic->iformat = fmt;
385
386     /* check filename in case of an image number is expected */
387     if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
388         if (filename_number_test(ic->filename) < 0) { 
389             err = AVERROR_NUMEXPECTED;
390             goto fail1;
391         }
392     }
393     
394     /* allocate private data */
395     if (fmt->priv_data_size > 0) {
396         ic->priv_data = av_mallocz(fmt->priv_data_size);
397         if (!ic->priv_data) {
398             err = AVERROR_NOMEM;
399         goto fail1;
400         }
401     } else
402         ic->priv_data = NULL;
403
404     /* default pts settings is MPEG like */
405     av_set_pts_info(ic, 33, 1, 90000);
406
407     err = ic->iformat->read_header(ic, ap);
408     if (err < 0)
409         goto fail1;
410     *ic_ptr = ic;
411     return 0;
412  fail1:
413     if (!fmt || must_open_file) {
414         url_fclose(&ic->pb);
415     }
416  fail:
417     if (ic) {
418         av_freep(&ic->priv_data);
419     }
420     av_free(ic);
421     *ic_ptr = NULL;
422     return err;
423 }
424
425 /**
426  * Read a packet from a media file
427  * @param s media file handle
428  * @param pkt is filled 
429  * @return 0 if OK. AVERROR_xxx if error.
430  */
431 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
432 {
433     AVPacketList *pktl;
434
435     pktl = s->packet_buffer;
436     if (pktl) {
437         /* read packet from packet buffer, if there is data */
438         *pkt = pktl->pkt;
439         s->packet_buffer = pktl->next;
440         av_free(pktl);
441         return 0;
442     } else {
443         return s->iformat->read_packet(s, pkt);
444     }
445 }
446
447
448 /* return TRUE if the stream has accurate timings for at least one component */
449 static int av_has_timings(AVFormatContext *ic)
450 {
451     int i;
452     AVStream *st;
453
454     for(i = 0;i < ic->nb_streams; i++) {
455         st = ic->streams[i];
456         if (st->start_time != AV_NOPTS_VALUE &&
457             st->duration != AV_NOPTS_VALUE)
458             return 1;
459     }
460     return 0;
461 }
462
463 /* estimate the stream timings from the one of each components. Also
464    compute the global bitrate if possible */
465 static void av_update_stream_timings(AVFormatContext *ic)
466 {
467     int64_t start_time, end_time, end_time1;
468     int i;
469     AVStream *st;
470
471     start_time = MAXINT64;
472     end_time = MININT64;
473     for(i = 0;i < ic->nb_streams; i++) {
474         st = ic->streams[i];
475         if (st->start_time != AV_NOPTS_VALUE) {
476             if (st->start_time < start_time)
477                 start_time = st->start_time;
478             if (st->duration != AV_NOPTS_VALUE) {
479                 end_time1 = st->start_time + st->duration;
480                 if (end_time1 > end_time)
481                     end_time = end_time1;
482             }
483         }
484     }
485     if (start_time != MAXINT64) {
486         ic->start_time = start_time;
487         if (end_time != MAXINT64) {
488             ic->duration = end_time - start_time;
489             if (ic->file_size > 0) {
490                 /* compute the bit rate */
491                 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE / 
492                     (double)ic->duration;
493             }
494         }
495     }
496
497 }
498
499 static void fill_all_stream_timings(AVFormatContext *ic)
500 {
501     int i;
502     AVStream *st;
503
504     av_update_stream_timings(ic);
505     for(i = 0;i < ic->nb_streams; i++) {
506         st = ic->streams[i];
507         if (st->start_time == AV_NOPTS_VALUE) {
508             st->start_time = ic->start_time;
509             st->duration = ic->duration;
510         }
511     }
512 }
513
514 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
515 {
516     int64_t filesize, duration;
517     int bit_rate, i;
518     AVStream *st;
519
520     /* if bit_rate is already set, we believe it */
521     if (ic->bit_rate == 0) {
522         bit_rate = 0;
523         for(i=0;i<ic->nb_streams;i++) {
524             st = ic->streams[i];
525             bit_rate += st->codec.bit_rate;
526         }
527         ic->bit_rate = bit_rate;
528     }
529
530     /* if duration is already set, we believe it */
531     if (ic->duration == AV_NOPTS_VALUE && 
532         ic->bit_rate != 0 && 
533         ic->file_size != 0)  {
534         filesize = ic->file_size;
535         if (filesize > 0) {
536             duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
537             for(i = 0; i < ic->nb_streams; i++) {
538                 st = ic->streams[i];
539                 if (st->start_time == AV_NOPTS_VALUE ||
540                     st->duration == AV_NOPTS_VALUE) {
541                     st->start_time = 0;
542                     st->duration = duration;
543                 }
544             }
545         }
546     }
547 }
548
549 static void flush_packet_queue(AVFormatContext *s)
550 {
551     AVPacketList *pktl;
552
553     for(;;) {
554         pktl = s->packet_buffer;
555         if (!pktl) 
556             break;
557         s->packet_buffer = pktl->next;
558         av_free(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",      352, 240, 30000, 1001 },
1228     { "pal",       352, 288,    25,    1 },
1229     { "film",      352, 240,    24,    1 },
1230     { "ntsc-film", 352, 240, 24000, 1001 },
1231     { "sqcif",     128,  96,     0,    0 },
1232     { "qcif",      176, 144,     0,    0 },
1233     { "cif",       352, 288,     0,    0 },
1234     { "4cif",      704, 576,     0,    0 },
1235 };
1236
1237 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
1238 {
1239     int i;
1240     int n = sizeof(frame_abvs) / sizeof(AbvEntry);
1241     const char *p;
1242     int frame_width = 0, frame_height = 0;
1243
1244     for(i=0;i<n;i++) {
1245         if (!strcmp(frame_abvs[i].abv, str)) {
1246             frame_width = frame_abvs[i].width;
1247             frame_height = frame_abvs[i].height;
1248             break;
1249         }
1250     }
1251     if (i == n) {
1252         p = str;
1253         frame_width = strtol(p, (char **)&p, 10);
1254         if (*p)
1255             p++;
1256         frame_height = strtol(p, (char **)&p, 10);
1257     }
1258     if (frame_width <= 0 || frame_height <= 0)
1259         return -1;
1260     *width_ptr = frame_width;
1261     *height_ptr = frame_height;
1262     return 0;
1263 }
1264
1265 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
1266 {
1267     int i;
1268     char* cp;
1269    
1270     /* First, we check our abbreviation table */
1271     for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
1272          if (!strcmp(frame_abvs[i].abv, arg)) {
1273              *frame_rate = frame_abvs[i].frame_rate;
1274              *frame_rate_base = frame_abvs[i].frame_rate_base;
1275              return 0;
1276          }
1277
1278     /* Then, we try to parse it as fraction */
1279     cp = strchr(arg, '/');
1280     if (cp) {
1281         char* cpp;
1282         *frame_rate = strtol(arg, &cpp, 10);
1283         if (cpp != arg || cpp == cp) 
1284             *frame_rate_base = strtol(cp+1, &cpp, 10);
1285         else
1286            *frame_rate = 0;
1287     } 
1288     else {
1289         /* Finally we give up and parse it as double */
1290         *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
1291         *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
1292     }
1293     if (!*frame_rate || !*frame_rate_base)
1294         return -1;
1295     else
1296         return 0;
1297 }
1298
1299 int64_t av_gettime(void)
1300 {
1301 #ifdef CONFIG_WIN32
1302     struct _timeb tb;
1303     _ftime(&tb);
1304     return ((int64_t)tb.time * int64_t_C(1000) + (int64_t)tb.millitm) * int64_t_C(1000);
1305 #else
1306     struct timeval tv;
1307     gettimeofday(&tv,NULL);
1308     return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
1309 #endif
1310 }
1311
1312 static time_t mktimegm(struct tm *tm)
1313 {
1314     time_t t;
1315
1316     int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
1317
1318     if (m < 3) {
1319         m += 12;
1320         y--;
1321     }
1322
1323     t = 86400 * 
1324         (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
1325
1326     t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
1327
1328     return t;
1329 }
1330
1331 /* Syntax:
1332  * - If not a duration:
1333  *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
1334  * Time is localtime unless Z is suffixed to the end. In this case GMT
1335  * Return the date in micro seconds since 1970 
1336  * - If duration:
1337  *  HH[:MM[:SS[.m...]]]
1338  *  S+[.m...]
1339  */
1340 int64_t parse_date(const char *datestr, int duration)
1341 {
1342     const char *p;
1343     int64_t t;
1344     struct tm dt;
1345     int i;
1346     static const char *date_fmt[] = {
1347         "%Y-%m-%d",
1348         "%Y%m%d",
1349     };
1350     static const char *time_fmt[] = {
1351         "%H:%M:%S",
1352         "%H%M%S",
1353     };
1354     const char *q;
1355     int is_utc, len;
1356     char lastch;
1357     time_t now = time(0);
1358
1359     len = strlen(datestr);
1360     if (len > 0)
1361         lastch = datestr[len - 1];
1362     else
1363         lastch = '\0';
1364     is_utc = (lastch == 'z' || lastch == 'Z');
1365
1366     memset(&dt, 0, sizeof(dt));
1367
1368     p = datestr;
1369     q = NULL;
1370     if (!duration) {
1371         for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
1372             q = strptime(p, date_fmt[i], &dt);
1373             if (q) {
1374                 break;
1375             }
1376         }
1377
1378         if (!q) {
1379             if (is_utc) {
1380                 dt = *gmtime(&now);
1381             } else {
1382                 dt = *localtime(&now);
1383             }
1384             dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
1385         } else {
1386             p = q;
1387         }
1388
1389         if (*p == 'T' || *p == 't' || *p == ' ')
1390             p++;
1391
1392         for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
1393             q = strptime(p, time_fmt[i], &dt);
1394             if (q) {
1395                 break;
1396             }
1397         }
1398     } else {
1399         q = strptime(p, time_fmt[0], &dt);
1400         if (!q) {
1401             dt.tm_sec = strtol(p, (char **)&q, 10);
1402             dt.tm_min = 0;
1403             dt.tm_hour = 0;
1404         }
1405     }
1406
1407     /* Now we have all the fields that we can get */
1408     if (!q) {
1409         if (duration)
1410             return 0;
1411         else
1412             return now * int64_t_C(1000000);
1413     }
1414
1415     if (duration) {
1416         t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
1417     } else {
1418         dt.tm_isdst = -1;       /* unknown */
1419         if (is_utc) {
1420             t = mktimegm(&dt);
1421         } else {
1422             t = mktime(&dt);
1423         }
1424     }
1425
1426     t *= 1000000;
1427
1428     if (*q == '.') {
1429         int val, n;
1430         q++;
1431         for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1432             if (!isdigit(*q)) 
1433                 break;
1434             val += n * (*q - '0');
1435         }
1436         t += val;
1437     }
1438     return t;
1439 }
1440
1441 /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
1442    1 if found */
1443 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1444 {
1445     const char *p;
1446     char tag[128], *q;
1447
1448     p = info;
1449     if (*p == '?')
1450         p++;
1451     for(;;) {
1452         q = tag;
1453         while (*p != '\0' && *p != '=' && *p != '&') {
1454             if ((q - tag) < sizeof(tag) - 1)
1455                 *q++ = *p;
1456             p++;
1457         }
1458         *q = '\0';
1459         q = arg;
1460         if (*p == '=') {
1461             p++;
1462             while (*p != '&' && *p != '\0') {
1463                 if ((q - arg) < arg_size - 1) {
1464                     if (*p == '+')
1465                         *q++ = ' ';
1466                     else
1467                         *q++ = *p;
1468                 }
1469                 p++;
1470             }
1471             *q = '\0';
1472         }
1473         if (!strcmp(tag, tag1)) 
1474             return 1;
1475         if (*p != '&')
1476             break;
1477         p++;
1478     }
1479     return 0;
1480 }
1481
1482 /* Return in 'buf' the path with '%d' replaced by number. Also handles
1483    the '%0nd' format where 'n' is the total number of digits and
1484    '%%'. Return 0 if OK, and -1 if format error */
1485 int get_frame_filename(char *buf, int buf_size,
1486                        const char *path, int number)
1487 {
1488     const char *p;
1489     char *q, buf1[20];
1490     int nd, len, c, percentd_found;
1491
1492     q = buf;
1493     p = path;
1494     percentd_found = 0;
1495     for(;;) {
1496         c = *p++;
1497         if (c == '\0')
1498             break;
1499         if (c == '%') {
1500             do {
1501                 nd = 0;
1502                 while (isdigit(*p)) {
1503                     nd = nd * 10 + *p++ - '0';
1504                 }
1505                 c = *p++;
1506             } while (isdigit(c));
1507
1508             switch(c) {
1509             case '%':
1510                 goto addchar;
1511             case 'd':
1512                 if (percentd_found)
1513                     goto fail;
1514                 percentd_found = 1;
1515                 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1516                 len = strlen(buf1);
1517                 if ((q - buf + len) > buf_size - 1)
1518                     goto fail;
1519                 memcpy(q, buf1, len);
1520                 q += len;
1521                 break;
1522             default:
1523                 goto fail;
1524             }
1525         } else {
1526         addchar:
1527             if ((q - buf) < buf_size - 1)
1528                 *q++ = c;
1529         }
1530     }
1531     if (!percentd_found)
1532         goto fail;
1533     *q = '\0';
1534     return 0;
1535  fail:
1536     *q = '\0';
1537     return -1;
1538 }
1539
1540 /**
1541  *
1542  * Print on stdout a nice hexa dump of a buffer
1543  * @param buf buffer
1544  * @param size buffer size
1545  */
1546 void av_hex_dump(uint8_t *buf, int size)
1547 {
1548     int len, i, j, c;
1549
1550     for(i=0;i<size;i+=16) {
1551         len = size - i;
1552         if (len > 16)
1553             len = 16;
1554         printf("%08x ", i);
1555         for(j=0;j<16;j++) {
1556             if (j < len)
1557                 printf(" %02x", buf[i+j]);
1558             else
1559                 printf("   ");
1560         }
1561         printf(" ");
1562         for(j=0;j<len;j++) {
1563             c = buf[i+j];
1564             if (c < ' ' || c > '~')
1565                 c = '.';
1566             printf("%c", c);
1567         }
1568         printf("\n");
1569     }
1570 }
1571
1572 void url_split(char *proto, int proto_size,
1573                char *hostname, int hostname_size,
1574                int *port_ptr,
1575                char *path, int path_size,
1576                const char *url)
1577 {
1578     const char *p;
1579     char *q;
1580     int port;
1581
1582     port = -1;
1583
1584     p = url;
1585     q = proto;
1586     while (*p != ':' && *p != '\0') {
1587         if ((q - proto) < proto_size - 1)
1588             *q++ = *p;
1589         p++;
1590     }
1591     if (proto_size > 0)
1592         *q = '\0';
1593     if (*p == '\0') {
1594         if (proto_size > 0)
1595             proto[0] = '\0';
1596         if (hostname_size > 0)
1597             hostname[0] = '\0';
1598         p = url;
1599     } else {
1600         p++;
1601         if (*p == '/')
1602             p++;
1603         if (*p == '/')
1604             p++;
1605         q = hostname;
1606         while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1607             if ((q - hostname) < hostname_size - 1)
1608                 *q++ = *p;
1609             p++;
1610         }
1611         if (hostname_size > 0)
1612             *q = '\0';
1613         if (*p == ':') {
1614             p++;
1615             port = strtoul(p, (char **)&p, 10);
1616         }
1617     }
1618     if (port_ptr)
1619         *port_ptr = port;
1620     pstrcpy(path, path_size, p);
1621 }
1622
1623 /**
1624  * Set the pts for a given stream
1625  * @param s stream 
1626  * @param pts_wrap_bits number of bits effectively used by the pts
1627  *        (used for wrap control, 33 is the value for MPEG) 
1628  * @param pts_num numerator to convert to seconds (MPEG: 1) 
1629  * @param pts_den denominator to convert to seconds (MPEG: 90000)
1630  */
1631 void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1632                      int pts_num, int pts_den)
1633 {
1634     s->pts_wrap_bits = pts_wrap_bits;
1635     s->pts_num = pts_num;
1636     s->pts_den = pts_den;
1637 }
1638
1639 /* fraction handling */
1640
1641 /**
1642  * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1643  * as 0 <= num < den.
1644  *
1645  * @param f fractional number
1646  * @param val integer value
1647  * @param num must be >= 0
1648  * @param den must be >= 1 
1649  */
1650 void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
1651 {
1652     num += (den >> 1);
1653     if (num >= den) {
1654         val += num / den;
1655         num = num % den;
1656     }
1657     f->val = val;
1658     f->num = num;
1659     f->den = den;
1660 }
1661
1662 /* set f to (val + 0.5) */
1663 void av_frac_set(AVFrac *f, int64_t val)
1664 {
1665     f->val = val;
1666     f->num = f->den >> 1;
1667 }
1668
1669 /**
1670  * Fractionnal addition to f: f = f + (incr / f->den)
1671  *
1672  * @param f fractional number
1673  * @param incr increment, can be positive or negative
1674  */
1675 void av_frac_add(AVFrac *f, int64_t incr)
1676 {
1677     int64_t num, den;
1678
1679     num = f->num + incr;
1680     den = f->den;
1681     if (num < 0) {
1682         f->val += num / den;
1683         num = num % den;
1684         if (num < 0) {
1685             num += den;
1686             f->val--;
1687         }
1688     } else if (num >= den) {
1689         f->val += num / den;
1690         num = num % den;
1691     }
1692     f->num = num;
1693 }
1694
1695 /**
1696  * register a new image format
1697  * @param img_fmt Image format descriptor
1698  */
1699 void av_register_image_format(AVImageFormat *img_fmt)
1700 {
1701     AVImageFormat **p;
1702
1703     p = &first_image_format;
1704     while (*p != NULL) p = &(*p)->next;
1705     *p = img_fmt;
1706     img_fmt->next = NULL;
1707 }
1708
1709 /* guess image format */
1710 AVImageFormat *av_probe_image_format(AVProbeData *pd)
1711 {
1712     AVImageFormat *fmt1, *fmt;
1713     int score, score_max;
1714
1715     fmt = NULL;
1716     score_max = 0;
1717     for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1718         if (fmt1->img_probe) {
1719             score = fmt1->img_probe(pd);
1720             if (score > score_max) {
1721                 score_max = score;
1722                 fmt = fmt1;
1723             }
1724         }
1725     }
1726     return fmt;
1727 }
1728
1729 AVImageFormat *guess_image_format(const char *filename)
1730 {
1731     AVImageFormat *fmt1;
1732
1733     for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1734         if (fmt1->extensions && match_ext(filename, fmt1->extensions))
1735             return fmt1;
1736     }
1737     return NULL;
1738 }
1739
1740 /**
1741  * Read an image from a stream. 
1742  * @param gb byte stream containing the image
1743  * @param fmt image format, NULL if probing is required
1744  */
1745 int av_read_image(ByteIOContext *pb, const char *filename,
1746                   AVImageFormat *fmt,
1747                   int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
1748 {
1749     char buf[PROBE_BUF_SIZE];
1750     AVProbeData probe_data, *pd = &probe_data;
1751     offset_t pos;
1752     int ret;
1753
1754     if (!fmt) {
1755         pd->filename = filename;
1756         pd->buf = buf;
1757         pos = url_ftell(pb);
1758         pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
1759         url_fseek(pb, pos, SEEK_SET);
1760         fmt = av_probe_image_format(pd);
1761     }
1762     if (!fmt)
1763         return AVERROR_NOFMT;
1764     ret = fmt->img_read(pb, alloc_cb, opaque);
1765     return ret;
1766 }
1767
1768 /**
1769  * Write an image to a stream.
1770  * @param pb byte stream for the image output
1771  * @param fmt image format
1772  * @param img image data and informations
1773  */
1774 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
1775 {
1776     return fmt->img_write(pb, img);
1777 }
1778