]> git.sesse.net Git - ffmpeg/blob - libavformat/utils.c
flash video (flv) support patch by (Garrick Meeker <gmeeker at theoryllc dot com>)
[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;
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     pstrcpy(ic->filename, sizeof(ic->filename), filename);
325     pd->filename = ic->filename;
326     pd->buf = buf;
327     pd->buf_size = 0;
328
329     if (!fmt) {
330         /* guess format if no file can be opened  */
331         fmt = av_probe_input_format(pd, 0);
332     }
333
334     if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
335         /* if no file needed do not try to open one */
336         if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
337             err = AVERROR_IO;
338             goto fail;
339         }
340         if (buf_size > 0) {
341             url_setbufsize(&ic->pb, buf_size);
342         }
343         if (!fmt) {
344             /* read probe data */
345             pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
346             url_fseek(&ic->pb, 0, SEEK_SET);
347         }
348     }
349     
350     /* guess file format */
351     if (!fmt) {
352         fmt = av_probe_input_format(pd, 1);
353     }
354
355     /* if still no format found, error */
356     if (!fmt) {
357         err = AVERROR_NOFMT;
358         goto fail1;
359     }
360         
361     /* XXX: suppress this hack for redirectors */
362 #ifdef CONFIG_NETWORK
363     if (fmt == &redir_demux) {
364         err = redir_open(ic_ptr, &ic->pb);
365         url_fclose(&ic->pb);
366         av_free(ic);
367         return err;
368     }
369 #endif
370
371     ic->iformat = fmt;
372
373     /* check filename in case of an image number is expected */
374     if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
375         if (filename_number_test(ic->filename) < 0) { 
376             err = AVERROR_NUMEXPECTED;
377             goto fail1;
378         }
379     }
380     
381     /* allocate private data */
382     if (fmt->priv_data_size > 0) {
383         ic->priv_data = av_mallocz(fmt->priv_data_size);
384         if (!ic->priv_data) {
385             err = AVERROR_NOMEM;
386         goto fail1;
387         }
388     } else
389         ic->priv_data = NULL;
390
391     /* default pts settings is MPEG like */
392     av_set_pts_info(ic, 33, 1, 90000);
393
394     err = ic->iformat->read_header(ic, ap);
395     if (err < 0)
396         goto fail1;
397     *ic_ptr = ic;
398     return 0;
399  fail1:
400     if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
401         url_fclose(&ic->pb);
402     }
403  fail:
404     if (ic) {
405         av_freep(&ic->priv_data);
406     }
407     av_free(ic);
408     *ic_ptr = NULL;
409     return err;
410 }
411
412 /**
413  * Read a packet from a media file
414  * @param s media file handle
415  * @param pkt is filled 
416  * @return 0 if OK. AVERROR_xxx if error.
417  */
418 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
419 {
420     AVPacketList *pktl;
421
422     pktl = s->packet_buffer;
423     if (pktl) {
424         /* read packet from packet buffer, if there is data */
425         *pkt = pktl->pkt;
426         s->packet_buffer = pktl->next;
427         av_free(pktl);
428         return 0;
429     } else {
430         return s->iformat->read_packet(s, pkt);
431     }
432 }
433
434 /* state for codec information */
435 #define CSTATE_NOTFOUND    0
436 #define CSTATE_DECODING    1
437 #define CSTATE_FOUND       2
438
439 static int has_codec_parameters(AVCodecContext *enc)
440 {
441     int val;
442     switch(enc->codec_type) {
443     case CODEC_TYPE_AUDIO:
444         val = enc->sample_rate;
445         break;
446     case CODEC_TYPE_VIDEO:
447         val = enc->width;
448         break;
449     default:
450         val = 1;
451         break;
452     }
453     return (val != 0);
454 }
455
456 /**
457  * Read the beginning of a media file to get stream information. This
458  * is useful for file formats with no headers such as MPEG. This
459  * function also compute the real frame rate in case of mpeg2 repeat
460  * frame mode.
461  *
462  * @param ic media file handle
463  * @return >=0 if OK. AVERROR_xxx if error.  
464  */
465 int av_find_stream_info(AVFormatContext *ic)
466 {
467     int i, count, ret, got_picture, size, read_size;
468     AVCodec *codec;
469     AVStream *st;
470     AVPacket *pkt;
471     AVFrame picture;
472     AVPacketList *pktl=NULL, **ppktl;
473     short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
474     uint8_t *ptr;
475     int min_read_size, max_read_size;
476
477     /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
478        Mbits. We read at most 0.2 second of file to find all streams */
479
480     /* XXX: base it on stream bitrate when possible */
481     if (ic->iformat == &mpegts_demux) {
482         /* maximum number of bytes we accept to read to find all the streams
483            in a file */
484         min_read_size = 6000000;
485     } else {
486         min_read_size = 250000;
487     }
488     /* max read size is 2 seconds of video max */
489     max_read_size = min_read_size * 10;
490
491     /* set initial codec state */
492     for(i=0;i<ic->nb_streams;i++) {
493         st = ic->streams[i];
494         if (has_codec_parameters(&st->codec))
495             st->codec_info_state = CSTATE_FOUND;
496         else
497             st->codec_info_state = CSTATE_NOTFOUND;
498         st->codec_info_nb_repeat_frames = 0;
499         st->codec_info_nb_real_frames = 0;
500     }
501
502     count = 0;
503     read_size = 0;
504     ppktl = &ic->packet_buffer;
505     for(;;) {
506         /* check if one codec still needs to be handled */
507         for(i=0;i<ic->nb_streams;i++) {
508             st = ic->streams[i];
509             if (st->codec_info_state != CSTATE_FOUND)
510                 break;
511         }
512         if (i == ic->nb_streams) {
513             /* NOTE: if the format has no header, then we need to read
514                some packets to get most of the streams, so we cannot
515                stop here */
516             if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
517                 read_size >= min_read_size) {
518                 /* if we found the info for all the codecs, we can stop */
519                 ret = count;
520                 break;
521             }
522         } else {
523             /* we did not get all the codec info, but we read too much data */
524             if (read_size >= max_read_size) {
525                 ret = count;
526                 break;
527             }
528         }
529
530         pktl = av_mallocz(sizeof(AVPacketList));
531         if (!pktl) {
532             ret = AVERROR_NOMEM;
533             break;
534         }
535
536         /* add the packet in the buffered packet list */
537         *ppktl = pktl;
538         ppktl = &pktl->next;
539
540         /* NOTE: a new stream can be added there if no header in file
541            (AVFMT_NOHEADER) */
542         pkt = &pktl->pkt;
543         if (ic->iformat->read_packet(ic, pkt) < 0) {
544             /* EOF or error */
545             ret = -1; /* we could not have all the codec parameters before EOF */
546             if ((ic->iformat->flags & AVFMT_NOHEADER) &&
547                 i == ic->nb_streams)
548                 ret = 0;
549             break;
550         }
551         read_size += pkt->size;
552
553         /* open new codecs */
554         for(i=0;i<ic->nb_streams;i++) {
555             st = ic->streams[i];
556             if (st->codec_info_state == CSTATE_NOTFOUND) {
557                 /* set to found in case of error */
558                 st->codec_info_state = CSTATE_FOUND; 
559                 codec = avcodec_find_decoder(st->codec.codec_id);
560                 if (codec) {
561                     if(codec->capabilities & CODEC_CAP_TRUNCATED)
562                         st->codec.flags |= CODEC_FLAG_TRUNCATED;
563
564                     ret = avcodec_open(&st->codec, codec);
565                     if (ret >= 0)
566                         st->codec_info_state = CSTATE_DECODING;
567                 }
568             }
569         }
570
571         st = ic->streams[pkt->stream_index];
572         if (st->codec_info_state == CSTATE_DECODING) {
573             /* decode the data and update codec parameters */
574             ptr = pkt->data;
575             size = pkt->size;
576             while (size > 0) {
577                 switch(st->codec.codec_type) {
578                 case CODEC_TYPE_VIDEO:
579                     ret = avcodec_decode_video(&st->codec, &picture, 
580                                                &got_picture, ptr, size);
581                     break;
582                 case CODEC_TYPE_AUDIO:
583                     ret = avcodec_decode_audio(&st->codec, samples, 
584                                                &got_picture, ptr, size);
585                     break;
586                 default:
587                     ret = -1;
588                     break;
589                 }
590                 if (ret < 0) {
591                     /* if error, simply ignore because another packet
592                        may be OK */
593                     break;
594                 }
595                 if (got_picture) {
596                     /* we got the parameters - now we can stop
597                        examining this stream */
598                     /* XXX: add a codec info so that we can decide if
599                        the codec can repeat frames */
600                     if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO && 
601                         ic->iformat != &mpegts_demux &&
602                         st->codec.sub_id == 2) {
603                         /* for mpeg2 video, we want to know the real
604                            frame rate, so we decode 40 frames. In mpeg
605                            TS case we do not do it because it would be
606                            too long */
607                         st->codec_info_nb_real_frames++;
608                         st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
609 #if 0
610                         /* XXX: testing */
611                         if ((st->codec_info_nb_real_frames % 24) == 23) {
612                             st->codec_info_nb_repeat_frames += 2;
613                         }
614 #endif
615                         /* stop after 40 frames */
616                         if (st->codec_info_nb_real_frames >= 40) {
617                             av_reduce(
618                                 &st->r_frame_rate,
619                                 &st->r_frame_rate_base,
620                                 (int64_t)st->codec.frame_rate * st->codec_info_nb_real_frames,
621                                 (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
622                                 1<<30);
623                             goto close_codec;
624                         }
625                     } else {
626                     close_codec:
627                         st->codec_info_state = CSTATE_FOUND;
628                         avcodec_close(&st->codec);
629                         break;
630                     }
631                 }
632                 ptr += ret;
633                 size -= ret;
634             }
635         }
636         count++;
637     }
638
639     /* close each codec if there are opened */
640     for(i=0;i<ic->nb_streams;i++) {
641         st = ic->streams[i];
642         if (st->codec_info_state == CSTATE_DECODING)
643             avcodec_close(&st->codec);
644     }
645
646     /* set real frame rate info */
647     for(i=0;i<ic->nb_streams;i++) {
648         st = ic->streams[i];
649         if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
650             if (!st->r_frame_rate){
651                 st->r_frame_rate      = st->codec.frame_rate;
652                 st->r_frame_rate_base = st->codec.frame_rate_base;
653             }
654         }
655     }
656
657     return ret;
658 }
659
660 /**
661  * Close a media file (but not its codecs)
662  *
663  * @param s media file handle
664  */
665 void av_close_input_file(AVFormatContext *s)
666 {
667     int i;
668
669     if (s->iformat->read_close)
670         s->iformat->read_close(s);
671     for(i=0;i<s->nb_streams;i++) {
672         av_free(s->streams[i]);
673     }
674     if (s->packet_buffer) {
675         AVPacketList *p, *p1;
676         p = s->packet_buffer;
677         while (p != NULL) {
678             p1 = p->next;
679             av_free_packet(&p->pkt);
680             av_free(p);
681             p = p1;
682         }
683         s->packet_buffer = NULL;
684     }
685     if (!(s->iformat->flags & AVFMT_NOFILE)) {
686         url_fclose(&s->pb);
687     }
688     av_freep(&s->priv_data);
689     av_free(s);
690 }
691
692 /**
693  * Add a new stream to a media file. Can only be called in the
694  * read_header function. If the flag AVFMT_NOHEADER is in the format
695  * description, then new streams can be added in read_packet too.
696  *
697  *
698  * @param s media file handle
699  * @param id file format dependent stream id
700  */
701 AVStream *av_new_stream(AVFormatContext *s, int id)
702 {
703     AVStream *st;
704
705     if (s->nb_streams >= MAX_STREAMS)
706         return NULL;
707
708     st = av_mallocz(sizeof(AVStream));
709     if (!st)
710         return NULL;
711     avcodec_get_context_defaults(&st->codec);
712
713     st->index = s->nb_streams;
714     st->id = id;
715     s->streams[s->nb_streams++] = st;
716     return st;
717 }
718
719 /************************************************************/
720 /* output media file */
721
722 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
723 {
724     int ret;
725     
726     if (s->oformat->priv_data_size > 0) {
727         s->priv_data = av_mallocz(s->oformat->priv_data_size);
728         if (!s->priv_data)
729             return AVERROR_NOMEM;
730     } else
731         s->priv_data = NULL;
732         
733     if (s->oformat->set_parameters) {
734         ret = s->oformat->set_parameters(s, ap);
735         if (ret < 0)
736             return ret;
737     }
738     return 0;
739 }
740
741 /**
742  * allocate the stream private data and write the stream header to an
743  * output media file
744  *
745  * @param s media file handle
746  * @return 0 if OK. AVERROR_xxx if error.  
747  */
748 int av_write_header(AVFormatContext *s)
749 {
750     int ret, i;
751     AVStream *st;
752
753     /* default pts settings is MPEG like */
754     av_set_pts_info(s, 33, 1, 90000);
755     ret = s->oformat->write_header(s);
756     if (ret < 0)
757         return ret;
758
759     /* init PTS generation */
760     for(i=0;i<s->nb_streams;i++) {
761         st = s->streams[i];
762
763         switch (st->codec.codec_type) {
764         case CODEC_TYPE_AUDIO:
765             av_frac_init(&st->pts, 0, 0, 
766                          (int64_t)s->pts_num * st->codec.sample_rate);
767             break;
768         case CODEC_TYPE_VIDEO:
769             av_frac_init(&st->pts, 0, 0, 
770                          (int64_t)s->pts_num * st->codec.frame_rate);
771             break;
772         default:
773             break;
774         }
775     }
776     return 0;
777 }
778
779 /**
780  * Write a packet to an output media file. The packet shall contain
781  * one audio or video frame.
782  *
783  * @param s media file handle
784  * @param stream_index stream index
785  * @param buf buffer containing the frame data
786  * @param size size of buffer
787  * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
788  */
789 int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf, 
790                    int size)
791 {
792     AVStream *st;
793     int64_t pts_mask;
794     int ret, frame_size;
795
796     st = s->streams[stream_index];
797     pts_mask = (1LL << s->pts_wrap_bits) - 1;
798     ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size, 
799                                    st->pts.val & pts_mask);
800     if (ret < 0)
801         return ret;
802
803     /* update pts */
804     switch (st->codec.codec_type) {
805     case CODEC_TYPE_AUDIO:
806         if (st->codec.frame_size <= 1) {
807             frame_size = size / st->codec.channels;
808             /* specific hack for pcm codecs because no frame size is provided */
809             switch(st->codec.codec_id) {
810             case CODEC_ID_PCM_S16LE:
811             case CODEC_ID_PCM_S16BE:
812             case CODEC_ID_PCM_U16LE:
813             case CODEC_ID_PCM_U16BE:
814                 frame_size >>= 1;
815                 break;
816             default:
817                 break;
818             }
819         } else {
820             frame_size = st->codec.frame_size;
821         }
822         av_frac_add(&st->pts, 
823                     (int64_t)s->pts_den * frame_size);
824         break;
825     case CODEC_TYPE_VIDEO:
826         av_frac_add(&st->pts, 
827                     (int64_t)s->pts_den * st->codec.frame_rate_base);
828         break;
829     default:
830         break;
831     }
832     return ret;
833 }
834
835 /**
836  * write the stream trailer to an output media file and and free the
837  * file private data.
838  *
839  * @param s media file handle
840  * @return 0 if OK. AVERROR_xxx if error.  */
841 int av_write_trailer(AVFormatContext *s)
842 {
843     int ret;
844     ret = s->oformat->write_trailer(s);
845     av_freep(&s->priv_data);
846     return ret;
847 }
848
849 /* "user interface" functions */
850
851 void dump_format(AVFormatContext *ic,
852                  int index, 
853                  const char *url,
854                  int is_output)
855 {
856     int i, flags;
857     char buf[256];
858
859     fprintf(stderr, "%s #%d, %s, %s '%s':\n", 
860             is_output ? "Output" : "Input",
861             index, 
862             is_output ? ic->oformat->name : ic->iformat->name, 
863             is_output ? "to" : "from", url);
864     for(i=0;i<ic->nb_streams;i++) {
865         AVStream *st = ic->streams[i];
866         avcodec_string(buf, sizeof(buf), &st->codec, is_output);
867         fprintf(stderr, "  Stream #%d.%d", index, i);
868         /* the pid is an important information, so we display it */
869         /* XXX: add a generic system */
870         if (is_output)
871             flags = ic->oformat->flags;
872         else
873             flags = ic->iformat->flags;
874         if (flags & AVFMT_SHOW_IDS) {
875             fprintf(stderr, "[0x%x]", st->id);
876         }
877         fprintf(stderr, ": %s\n", buf);
878     }
879 }
880
881 typedef struct {
882     const char *str;
883     int width, height;
884 } SizeEntry;
885
886 static SizeEntry sizes[] = {
887     { "sqcif", 128, 96 },
888     { "qcif", 176, 144 },
889     { "cif", 352, 288 },
890     { "4cif", 704, 576 },
891 };
892     
893 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
894 {
895     int i;
896     int n = sizeof(sizes) / sizeof(SizeEntry);
897     const char *p;
898     int frame_width = 0, frame_height = 0;
899
900     for(i=0;i<n;i++) {
901         if (!strcmp(sizes[i].str, str)) {
902             frame_width = sizes[i].width;
903             frame_height = sizes[i].height;
904             break;
905         }
906     }
907     if (i == n) {
908         p = str;
909         frame_width = strtol(p, (char **)&p, 10);
910         if (*p)
911             p++;
912         frame_height = strtol(p, (char **)&p, 10);
913     }
914     if (frame_width <= 0 || frame_height <= 0)
915         return -1;
916     *width_ptr = frame_width;
917     *height_ptr = frame_height;
918     return 0;
919 }
920
921 int64_t av_gettime(void)
922 {
923 #ifdef CONFIG_WIN32
924     struct _timeb tb;
925     _ftime(&tb);
926     return ((int64_t)tb.time * int64_t_C(1000) + (int64_t)tb.millitm) * int64_t_C(1000);
927 #else
928     struct timeval tv;
929     gettimeofday(&tv,NULL);
930     return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
931 #endif
932 }
933
934 static time_t mktimegm(struct tm *tm)
935 {
936     time_t t;
937
938     int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
939
940     if (m < 3) {
941         m += 12;
942         y--;
943     }
944
945     t = 86400 * 
946         (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
947
948     t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
949
950     return t;
951 }
952
953 /* Syntax:
954  * - If not a duration:
955  *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
956  * Time is localtime unless Z is suffixed to the end. In this case GMT
957  * Return the date in micro seconds since 1970 
958  * - If duration:
959  *  HH[:MM[:SS[.m...]]]
960  *  S+[.m...]
961  */
962 int64_t parse_date(const char *datestr, int duration)
963 {
964     const char *p;
965     int64_t t;
966     struct tm dt;
967     int i;
968     static const char *date_fmt[] = {
969         "%Y-%m-%d",
970         "%Y%m%d",
971     };
972     static const char *time_fmt[] = {
973         "%H:%M:%S",
974         "%H%M%S",
975     };
976     const char *q;
977     int is_utc, len;
978     char lastch;
979     time_t now = time(0);
980
981     len = strlen(datestr);
982     if (len > 0)
983         lastch = datestr[len - 1];
984     else
985         lastch = '\0';
986     is_utc = (lastch == 'z' || lastch == 'Z');
987
988     memset(&dt, 0, sizeof(dt));
989
990     p = datestr;
991     q = NULL;
992     if (!duration) {
993         for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
994             q = strptime(p, date_fmt[i], &dt);
995             if (q) {
996                 break;
997             }
998         }
999
1000         if (!q) {
1001             if (is_utc) {
1002                 dt = *gmtime(&now);
1003             } else {
1004                 dt = *localtime(&now);
1005             }
1006             dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
1007         } else {
1008             p = q;
1009         }
1010
1011         if (*p == 'T' || *p == 't' || *p == ' ')
1012             p++;
1013
1014         for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
1015             q = strptime(p, time_fmt[i], &dt);
1016             if (q) {
1017                 break;
1018             }
1019         }
1020     } else {
1021         q = strptime(p, time_fmt[0], &dt);
1022         if (!q) {
1023             dt.tm_sec = strtol(p, (char **)&q, 10);
1024             dt.tm_min = 0;
1025             dt.tm_hour = 0;
1026         }
1027     }
1028
1029     /* Now we have all the fields that we can get */
1030     if (!q) {
1031         if (duration)
1032             return 0;
1033         else
1034             return now * int64_t_C(1000000);
1035     }
1036
1037     if (duration) {
1038         t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
1039     } else {
1040         dt.tm_isdst = -1;       /* unknown */
1041         if (is_utc) {
1042             t = mktimegm(&dt);
1043         } else {
1044             t = mktime(&dt);
1045         }
1046     }
1047
1048     t *= 1000000;
1049
1050     if (*q == '.') {
1051         int val, n;
1052         q++;
1053         for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1054             if (!isdigit(*q)) 
1055                 break;
1056             val += n * (*q - '0');
1057         }
1058         t += val;
1059     }
1060     return t;
1061 }
1062
1063 /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
1064    1 if found */
1065 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1066 {
1067     const char *p;
1068     char tag[128], *q;
1069
1070     p = info;
1071     if (*p == '?')
1072         p++;
1073     for(;;) {
1074         q = tag;
1075         while (*p != '\0' && *p != '=' && *p != '&') {
1076             if ((q - tag) < sizeof(tag) - 1)
1077                 *q++ = *p;
1078             p++;
1079         }
1080         *q = '\0';
1081         q = arg;
1082         if (*p == '=') {
1083             p++;
1084             while (*p != '&' && *p != '\0') {
1085                 if ((q - arg) < arg_size - 1) {
1086                     if (*p == '+')
1087                         *q++ = ' ';
1088                     else
1089                         *q++ = *p;
1090                 }
1091                 p++;
1092             }
1093             *q = '\0';
1094         }
1095         if (!strcmp(tag, tag1)) 
1096             return 1;
1097         if (*p != '&')
1098             break;
1099         p++;
1100     }
1101     return 0;
1102 }
1103
1104 /* Return in 'buf' the path with '%d' replaced by number. Also handles
1105    the '%0nd' format where 'n' is the total number of digits and
1106    '%%'. Return 0 if OK, and -1 if format error */
1107 int get_frame_filename(char *buf, int buf_size,
1108                        const char *path, int number)
1109 {
1110     const char *p;
1111     char *q, buf1[20];
1112     int nd, len, c, percentd_found;
1113
1114     q = buf;
1115     p = path;
1116     percentd_found = 0;
1117     for(;;) {
1118         c = *p++;
1119         if (c == '\0')
1120             break;
1121         if (c == '%') {
1122             do {
1123                 nd = 0;
1124                 while (isdigit(*p)) {
1125                     nd = nd * 10 + *p++ - '0';
1126                 }
1127                 c = *p++;
1128                 if (c == '*' && nd > 0) {
1129                     // The nd field is actually the modulus
1130                     number = number % nd;
1131                     c = *p++;
1132                     nd = 0;
1133                 }
1134             } while (isdigit(c));
1135
1136             switch(c) {
1137             case '%':
1138                 goto addchar;
1139             case 'd':
1140                 if (percentd_found)
1141                     goto fail;
1142                 percentd_found = 1;
1143                 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1144                 len = strlen(buf1);
1145                 if ((q - buf + len) > buf_size - 1)
1146                     goto fail;
1147                 memcpy(q, buf1, len);
1148                 q += len;
1149                 break;
1150             default:
1151                 goto fail;
1152             }
1153         } else {
1154         addchar:
1155             if ((q - buf) < buf_size - 1)
1156                 *q++ = c;
1157         }
1158     }
1159     if (!percentd_found)
1160         goto fail;
1161     *q = '\0';
1162     return 0;
1163  fail:
1164     *q = '\0';
1165     return -1;
1166 }
1167
1168 /**
1169  *
1170  * Print on stdout a nice hexa dump of a buffer
1171  * @param buf buffer
1172  * @param size buffer size
1173  */
1174 void av_hex_dump(uint8_t *buf, int size)
1175 {
1176     int len, i, j, c;
1177
1178     for(i=0;i<size;i+=16) {
1179         len = size - i;
1180         if (len > 16)
1181             len = 16;
1182         printf("%08x ", i);
1183         for(j=0;j<16;j++) {
1184             if (j < len)
1185                 printf(" %02x", buf[i+j]);
1186             else
1187                 printf("   ");
1188         }
1189         printf(" ");
1190         for(j=0;j<len;j++) {
1191             c = buf[i+j];
1192             if (c < ' ' || c > '~')
1193                 c = '.';
1194             printf("%c", c);
1195         }
1196         printf("\n");
1197     }
1198 }
1199
1200 void url_split(char *proto, int proto_size,
1201                char *hostname, int hostname_size,
1202                int *port_ptr,
1203                char *path, int path_size,
1204                const char *url)
1205 {
1206     const char *p;
1207     char *q;
1208     int port;
1209
1210     port = -1;
1211
1212     p = url;
1213     q = proto;
1214     while (*p != ':' && *p != '\0') {
1215         if ((q - proto) < proto_size - 1)
1216             *q++ = *p;
1217         p++;
1218     }
1219     if (proto_size > 0)
1220         *q = '\0';
1221     if (*p == '\0') {
1222         if (proto_size > 0)
1223             proto[0] = '\0';
1224         if (hostname_size > 0)
1225             hostname[0] = '\0';
1226         p = url;
1227     } else {
1228         p++;
1229         if (*p == '/')
1230             p++;
1231         if (*p == '/')
1232             p++;
1233         q = hostname;
1234         while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1235             if ((q - hostname) < hostname_size - 1)
1236                 *q++ = *p;
1237             p++;
1238         }
1239         if (hostname_size > 0)
1240             *q = '\0';
1241         if (*p == ':') {
1242             p++;
1243             port = strtoul(p, (char **)&p, 10);
1244         }
1245     }
1246     if (port_ptr)
1247         *port_ptr = port;
1248     pstrcpy(path, path_size, p);
1249 }
1250
1251 /**
1252  * Set the pts for a given stream
1253  * @param s stream 
1254  * @param pts_wrap_bits number of bits effectively used by the pts
1255  *        (used for wrap control, 33 is the value for MPEG) 
1256  * @param pts_num numerator to convert to seconds (MPEG: 1) 
1257  * @param pts_den denominator to convert to seconds (MPEG: 90000)
1258  */
1259 void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1260                      int pts_num, int pts_den)
1261 {
1262     s->pts_wrap_bits = pts_wrap_bits;
1263     s->pts_num = pts_num;
1264     s->pts_den = pts_den;
1265 }
1266
1267 /* fraction handling */
1268
1269 /**
1270  * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1271  * as 0 <= num < den.
1272  *
1273  * @param f fractional number
1274  * @param val integer value
1275  * @param num must be >= 0
1276  * @param den must be >= 1 
1277  */
1278 void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
1279 {
1280     num += (den >> 1);
1281     if (num >= den) {
1282         val += num / den;
1283         num = num % den;
1284     }
1285     f->val = val;
1286     f->num = num;
1287     f->den = den;
1288 }
1289
1290 /* set f to (val + 0.5) */
1291 void av_frac_set(AVFrac *f, int64_t val)
1292 {
1293     f->val = val;
1294     f->num = f->den >> 1;
1295 }
1296
1297 /**
1298  * Fractionnal addition to f: f = f + (incr / f->den)
1299  *
1300  * @param f fractional number
1301  * @param incr increment, can be positive or negative
1302  */
1303 void av_frac_add(AVFrac *f, int64_t incr)
1304 {
1305     int64_t num, den;
1306
1307     num = f->num + incr;
1308     den = f->den;
1309     if (num < 0) {
1310         f->val += num / den;
1311         num = num % den;
1312         if (num < 0) {
1313             num += den;
1314             f->val--;
1315         }
1316     } else if (num >= den) {
1317         f->val += num / den;
1318         num = num % den;
1319     }
1320     f->num = num;
1321 }
1322
1323 /**
1324  * register a new image format
1325  * @param img_fmt Image format descriptor
1326  */
1327 void av_register_image_format(AVImageFormat *img_fmt)
1328 {
1329     AVImageFormat **p;
1330
1331     p = &first_image_format;
1332     while (*p != NULL) p = &(*p)->next;
1333     *p = img_fmt;
1334     img_fmt->next = NULL;
1335 }
1336
1337 /* guess image format */
1338 AVImageFormat *av_probe_image_format(AVProbeData *pd)
1339 {
1340     AVImageFormat *fmt1, *fmt;
1341     int score, score_max;
1342
1343     fmt = NULL;
1344     score_max = 0;
1345     for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1346         if (fmt1->img_probe) {
1347             score = fmt1->img_probe(pd);
1348             if (score > score_max) {
1349                 score_max = score;
1350                 fmt = fmt1;
1351             }
1352         }
1353     }
1354     return fmt;
1355 }
1356
1357 AVImageFormat *guess_image_format(const char *filename)
1358 {
1359     AVImageFormat *fmt1;
1360
1361     for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1362         if (fmt1->extensions && match_ext(filename, fmt1->extensions))
1363             return fmt1;
1364     }
1365     return NULL;
1366 }
1367
1368 /**
1369  * Read an image from a stream. 
1370  * @param gb byte stream containing the image
1371  * @param fmt image format, NULL if probing is required
1372  */
1373 int av_read_image(ByteIOContext *pb, const char *filename,
1374                   AVImageFormat *fmt,
1375                   int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
1376 {
1377     char buf[PROBE_BUF_SIZE];
1378     AVProbeData probe_data, *pd = &probe_data;
1379     offset_t pos;
1380     int ret;
1381
1382     if (!fmt) {
1383         pd->filename = filename;
1384         pd->buf = buf;
1385         pos = url_ftell(pb);
1386         pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
1387         url_fseek(pb, pos, SEEK_SET);
1388         fmt = av_probe_image_format(pd);
1389     }
1390     if (!fmt)
1391         return AVERROR_NOFMT;
1392     ret = fmt->img_read(pb, alloc_cb, opaque);
1393     return ret;
1394 }
1395
1396 /**
1397  * Write an image to a stream.
1398  * @param pb byte stream for the image output
1399  * @param fmt image format
1400  * @param img image data and informations
1401  */
1402 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
1403 {
1404     return fmt->img_write(pb, img);
1405 }
1406