]> git.sesse.net Git - ffmpeg/blob - libavformat/utils.c
undefines a few temporary defines which were not undefined after their usage.
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19 #include "avformat.h"
20 #include "allformats.h"
21 #include "opt.h"
22
23 #undef NDEBUG
24 #include <assert.h>
25
26 /**
27  * @file libavformat/utils.c
28  * Various utility functions for using ffmpeg library.
29  */
30
31 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
32 static void av_frac_add(AVFrac *f, int64_t incr);
33 static void av_frac_set(AVFrac *f, int64_t val);
34
35 /** head of registered input format linked list. */
36 AVInputFormat *first_iformat = NULL;
37 /** head of registered output format linked list. */
38 AVOutputFormat *first_oformat = NULL;
39 /** head of registered image format linked list. */
40 AVImageFormat *first_image_format = NULL;
41
42 void av_register_input_format(AVInputFormat *format)
43 {
44     AVInputFormat **p;
45     p = &first_iformat;
46     while (*p != NULL) p = &(*p)->next;
47     *p = format;
48     format->next = NULL;
49 }
50
51 void av_register_output_format(AVOutputFormat *format)
52 {
53     AVOutputFormat **p;
54     p = &first_oformat;
55     while (*p != NULL) p = &(*p)->next;
56     *p = format;
57     format->next = NULL;
58 }
59
60 int match_ext(const char *filename, const char *extensions)
61 {
62     const char *ext, *p;
63     char ext1[32], *q;
64
65     if(!filename)
66         return 0;
67
68     ext = strrchr(filename, '.');
69     if (ext) {
70         ext++;
71         p = extensions;
72         for(;;) {
73             q = ext1;
74             while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
75                 *q++ = *p++;
76             *q = '\0';
77             if (!strcasecmp(ext1, ext))
78                 return 1;
79             if (*p == '\0')
80                 break;
81             p++;
82         }
83     }
84     return 0;
85 }
86
87 AVOutputFormat *guess_format(const char *short_name, const char *filename,
88                              const char *mime_type)
89 {
90     AVOutputFormat *fmt, *fmt_found;
91     int score_max, score;
92
93     /* specific test for image sequences */
94 #ifdef CONFIG_IMAGE2_MUXER
95     if (!short_name && filename &&
96         av_filename_number_test(filename) &&
97         av_guess_image2_codec(filename) != CODEC_ID_NONE) {
98         return guess_format("image2", NULL, NULL);
99     }
100 #endif
101     if (!short_name && filename &&
102         av_filename_number_test(filename) &&
103         guess_image_format(filename)) {
104         return guess_format("image", NULL, NULL);
105     }
106
107     /* find the proper file type */
108     fmt_found = NULL;
109     score_max = 0;
110     fmt = first_oformat;
111     while (fmt != NULL) {
112         score = 0;
113         if (fmt->name && short_name && !strcmp(fmt->name, short_name))
114             score += 100;
115         if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
116             score += 10;
117         if (filename && fmt->extensions &&
118             match_ext(filename, fmt->extensions)) {
119             score += 5;
120         }
121         if (score > score_max) {
122             score_max = score;
123             fmt_found = fmt;
124         }
125         fmt = fmt->next;
126     }
127     return fmt_found;
128 }
129
130 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
131                              const char *mime_type)
132 {
133     AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
134
135     if (fmt) {
136         AVOutputFormat *stream_fmt;
137         char stream_format_name[64];
138
139         snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
140         stream_fmt = guess_format(stream_format_name, NULL, NULL);
141
142         if (stream_fmt)
143             fmt = stream_fmt;
144     }
145
146     return fmt;
147 }
148
149 /**
150  * Guesses the codec id based upon muxer and filename.
151  */
152 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
153                             const char *filename, const char *mime_type, enum CodecType type){
154     if(type == CODEC_TYPE_VIDEO){
155         enum CodecID codec_id= CODEC_ID_NONE;
156
157 #ifdef CONFIG_IMAGE2_MUXER
158         if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
159             codec_id= av_guess_image2_codec(filename);
160         }
161 #endif
162         if(codec_id == CODEC_ID_NONE)
163             codec_id= fmt->video_codec;
164         return codec_id;
165     }else if(type == CODEC_TYPE_AUDIO)
166         return fmt->audio_codec;
167     else
168         return CODEC_ID_NONE;
169 }
170
171 /**
172  * finds AVInputFormat based on input format's short name.
173  */
174 AVInputFormat *av_find_input_format(const char *short_name)
175 {
176     AVInputFormat *fmt;
177     for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
178         if (!strcmp(fmt->name, short_name))
179             return fmt;
180     }
181     return NULL;
182 }
183
184 /* memory handling */
185
186 /**
187  * Default packet destructor.
188  */
189 void av_destruct_packet(AVPacket *pkt)
190 {
191     av_free(pkt->data);
192     pkt->data = NULL; pkt->size = 0;
193 }
194
195 /**
196  * Allocate the payload of a packet and intialized its fields to default values.
197  *
198  * @param pkt packet
199  * @param size wanted payload size
200  * @return 0 if OK. AVERROR_xxx otherwise.
201  */
202 int av_new_packet(AVPacket *pkt, int size)
203 {
204     void *data;
205     if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
206         return AVERROR_NOMEM;
207     data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
208     if (!data)
209         return AVERROR_NOMEM;
210     memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
211
212     av_init_packet(pkt);
213     pkt->data = data;
214     pkt->size = size;
215     pkt->destruct = av_destruct_packet;
216     return 0;
217 }
218
219 /**
220  * Allocate and read the payload of a packet and intialized its fields to default values.
221  *
222  * @param pkt packet
223  * @param size wanted payload size
224  * @return >0 (read size) if OK. AVERROR_xxx otherwise.
225  */
226 int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
227 {
228     int ret= av_new_packet(pkt, size);
229
230     if(ret<0)
231         return ret;
232
233     pkt->pos= url_ftell(s);
234
235     ret= get_buffer(s, pkt->data, size);
236     if(ret<=0)
237         av_free_packet(pkt);
238     else
239         pkt->size= ret;
240
241     return ret;
242 }
243
244 /* This is a hack - the packet memory allocation stuff is broken. The
245    packet is allocated if it was not really allocated */
246 int av_dup_packet(AVPacket *pkt)
247 {
248     if (pkt->destruct != av_destruct_packet) {
249         uint8_t *data;
250         /* we duplicate the packet and don't forget to put the padding
251            again */
252         if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
253             return AVERROR_NOMEM;
254         data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
255         if (!data) {
256             return AVERROR_NOMEM;
257         }
258         memcpy(data, pkt->data, pkt->size);
259         memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
260         pkt->data = data;
261         pkt->destruct = av_destruct_packet;
262     }
263     return 0;
264 }
265
266 /* fifo handling */
267
268 int fifo_init(FifoBuffer *f, int size)
269 {
270     f->buffer = av_malloc(size);
271     if (!f->buffer)
272         return -1;
273     f->end = f->buffer + size;
274     f->wptr = f->rptr = f->buffer;
275     return 0;
276 }
277
278 void fifo_free(FifoBuffer *f)
279 {
280     av_free(f->buffer);
281 }
282
283 int fifo_size(FifoBuffer *f, uint8_t *rptr)
284 {
285     int size;
286
287     if(!rptr)
288         rptr= f->rptr;
289
290     if (f->wptr >= rptr) {
291         size = f->wptr - rptr;
292     } else {
293         size = (f->end - rptr) + (f->wptr - f->buffer);
294     }
295     return size;
296 }
297
298 /**
299  * Get data from the fifo (returns -1 if not enough data).
300  */
301 int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
302 {
303     uint8_t *rptr;
304     int size, len;
305
306     if(!rptr_ptr)
307         rptr_ptr= &f->rptr;
308     rptr = *rptr_ptr;
309
310     if (f->wptr >= rptr) {
311         size = f->wptr - rptr;
312     } else {
313         size = (f->end - rptr) + (f->wptr - f->buffer);
314     }
315
316     if (size < buf_size)
317         return -1;
318     while (buf_size > 0) {
319         len = f->end - rptr;
320         if (len > buf_size)
321             len = buf_size;
322         memcpy(buf, rptr, len);
323         buf += len;
324         rptr += len;
325         if (rptr >= f->end)
326             rptr = f->buffer;
327         buf_size -= len;
328     }
329     *rptr_ptr = rptr;
330     return 0;
331 }
332
333 /**
334  * Resizes a FIFO.
335  */
336 void fifo_realloc(FifoBuffer *f, unsigned int new_size){
337     unsigned int old_size= f->end - f->buffer;
338
339     if(old_size < new_size){
340         uint8_t *old= f->buffer;
341
342         f->buffer= av_realloc(f->buffer, new_size);
343
344         f->rptr += f->buffer - old;
345         f->wptr += f->buffer - old;
346
347         if(f->wptr < f->rptr){
348             memmove(f->rptr + new_size - old_size, f->rptr, f->buffer + old_size - f->rptr);
349             f->rptr += new_size - old_size;
350         }
351         f->end= f->buffer + new_size;
352     }
353 }
354
355 void fifo_write(FifoBuffer *f, const uint8_t *buf, int size, uint8_t **wptr_ptr)
356 {
357     int len;
358     uint8_t *wptr;
359
360     if(!wptr_ptr)
361         wptr_ptr= &f->wptr;
362     wptr = *wptr_ptr;
363
364     while (size > 0) {
365         len = f->end - wptr;
366         if (len > size)
367             len = size;
368         memcpy(wptr, buf, len);
369         wptr += len;
370         if (wptr >= f->end)
371             wptr = f->buffer;
372         buf += len;
373         size -= len;
374     }
375     *wptr_ptr = wptr;
376 }
377
378 /* get data from the fifo (return -1 if not enough data) */
379 int put_fifo(ByteIOContext *pb, FifoBuffer *f, int buf_size, uint8_t **rptr_ptr)
380 {
381     uint8_t *rptr = *rptr_ptr;
382     int size, len;
383
384     if (f->wptr >= rptr) {
385         size = f->wptr - rptr;
386     } else {
387         size = (f->end - rptr) + (f->wptr - f->buffer);
388     }
389
390     if (size < buf_size)
391         return -1;
392     while (buf_size > 0) {
393         len = f->end - rptr;
394         if (len > buf_size)
395             len = buf_size;
396         put_buffer(pb, rptr, len);
397         rptr += len;
398         if (rptr >= f->end)
399             rptr = f->buffer;
400         buf_size -= len;
401     }
402     *rptr_ptr = rptr;
403     return 0;
404 }
405
406 /**
407  * Allocate the payload of a packet and intialized its fields to default values.
408  *
409  * @param filename possible numbered sequence string
410  * @return 1 if a valid numbered sequence string, 0 otherwise.
411  */
412 int av_filename_number_test(const char *filename)
413 {
414     char buf[1024];
415     return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
416 }
417
418 /**
419  * Guess file format.
420  */
421 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
422 {
423     AVInputFormat *fmt1, *fmt;
424     int score, score_max;
425
426     fmt = NULL;
427     score_max = 0;
428     for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
429         if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
430             continue;
431         score = 0;
432         if (fmt1->read_probe) {
433             score = fmt1->read_probe(pd);
434         } else if (fmt1->extensions) {
435             if (match_ext(pd->filename, fmt1->extensions)) {
436                 score = 50;
437             }
438         }
439         if (score > score_max) {
440             score_max = score;
441             fmt = fmt1;
442         }
443     }
444     return fmt;
445 }
446
447 /************************************************************/
448 /* input media file */
449
450 /**
451  * Open a media file from an IO stream. 'fmt' must be specified.
452  */
453 static const char* format_to_name(void* ptr)
454 {
455     AVFormatContext* fc = (AVFormatContext*) ptr;
456     if(fc->iformat) return fc->iformat->name;
457     else if(fc->oformat) return fc->oformat->name;
458     else return "NULL";
459 }
460
461 #define OFFSET(x) (int)&((AVFormatContext*)0)->x
462 #define DEFAULT 0 //should be NAN but it doesnt work as its not a constant in glibc as required by ANSI/ISO C
463 //these names are too long to be readable
464 #define E AV_OPT_FLAG_ENCODING_PARAM
465 #define D AV_OPT_FLAG_DECODING_PARAM
466
467 static const AVOption options[]={
468 {"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, DEFAULT, 32, INT_MAX, D},
469 {"fflags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, INT_MIN, INT_MAX, D, "fflags"},
470 {"ignidx", "ignore index", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNIDX, INT_MIN, INT_MAX, D, "fflags"},
471 {"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
472 {"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 1, INT_MAX, E},
473 {"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
474 {NULL},
475 };
476
477 #undef E
478 #undef D
479 #undef DEFAULT
480
481 static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
482
483 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(0<<8)+0)
484 static
485 #endif
486 void avformat_get_context_defaults(AVFormatContext *s){
487     memset(s, 0, sizeof(AVFormatContext));
488
489     /* from mpegts.c: 1.0 second at 24Mbit/s */
490     s->probesize=32000;
491 }
492
493 AVFormatContext *av_alloc_format_context(void)
494 {
495     AVFormatContext *ic;
496     ic = av_mallocz(sizeof(AVFormatContext));
497     if (!ic) return ic;
498     avformat_get_context_defaults(ic);
499     ic->av_class = &av_format_context_class;
500     return ic;
501 }
502
503 /**
504  * Allocates all the structures needed to read an input stream.
505  *        This does not open the needed codecs for decoding the stream[s].
506  */
507 int av_open_input_stream(AVFormatContext **ic_ptr,
508                          ByteIOContext *pb, const char *filename,
509                          AVInputFormat *fmt, AVFormatParameters *ap)
510 {
511     int err;
512     AVFormatContext *ic;
513     AVFormatParameters default_ap;
514
515     if(!ap){
516         ap=&default_ap;
517         memset(ap, 0, sizeof(default_ap));
518     }
519
520     if(!ap->prealloced_context)
521         ic = av_alloc_format_context();
522     else
523         ic = *ic_ptr;
524     if (!ic) {
525         err = AVERROR_NOMEM;
526         goto fail;
527     }
528     ic->iformat = fmt;
529     if (pb)
530         ic->pb = *pb;
531     ic->duration = AV_NOPTS_VALUE;
532     ic->start_time = AV_NOPTS_VALUE;
533     pstrcpy(ic->filename, sizeof(ic->filename), filename);
534
535     /* allocate private data */
536     if (fmt->priv_data_size > 0) {
537         ic->priv_data = av_mallocz(fmt->priv_data_size);
538         if (!ic->priv_data) {
539             err = AVERROR_NOMEM;
540             goto fail;
541         }
542     } else {
543         ic->priv_data = NULL;
544     }
545
546     err = ic->iformat->read_header(ic, ap);
547     if (err < 0)
548         goto fail;
549
550     if (pb)
551         ic->data_offset = url_ftell(&ic->pb);
552
553     *ic_ptr = ic;
554     return 0;
555  fail:
556     if (ic) {
557         av_freep(&ic->priv_data);
558     }
559     av_free(ic);
560     *ic_ptr = NULL;
561     return err;
562 }
563
564 /** Size of probe buffer, for guessing file type from file contents. */
565 #define PROBE_BUF_MIN 2048
566 #define PROBE_BUF_MAX (1<<20)
567
568 /**
569  * Open a media file as input. The codec are not opened. Only the file
570  * header (if present) is read.
571  *
572  * @param ic_ptr the opened media file handle is put here
573  * @param filename filename to open.
574  * @param fmt if non NULL, force the file format to use
575  * @param buf_size optional buffer size (zero if default is OK)
576  * @param ap additionnal parameters needed when opening the file (NULL if default)
577  * @return 0 if OK. AVERROR_xxx otherwise.
578  */
579 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
580                        AVInputFormat *fmt,
581                        int buf_size,
582                        AVFormatParameters *ap)
583 {
584     int err, must_open_file, file_opened, probe_size;
585     AVProbeData probe_data, *pd = &probe_data;
586     ByteIOContext pb1, *pb = &pb1;
587
588     file_opened = 0;
589     pd->filename = "";
590     if (filename)
591         pd->filename = filename;
592     pd->buf = NULL;
593     pd->buf_size = 0;
594
595     if (!fmt) {
596         /* guess format if no file can be opened  */
597         fmt = av_probe_input_format(pd, 0);
598     }
599
600     /* do not open file if the format does not need it. XXX: specific
601        hack needed to handle RTSP/TCP */
602     must_open_file = 1;
603     if (fmt && (fmt->flags & AVFMT_NOFILE)) {
604         must_open_file = 0;
605         pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
606     }
607
608     if (!fmt || must_open_file) {
609         /* if no file needed do not try to open one */
610         if (url_fopen(pb, filename, URL_RDONLY) < 0) {
611             err = AVERROR_IO;
612             goto fail;
613         }
614         file_opened = 1;
615         if (buf_size > 0) {
616             url_setbufsize(pb, buf_size);
617         }
618
619         for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
620             /* read probe data */
621             pd->buf= av_realloc(pd->buf, probe_size);
622             pd->buf_size = get_buffer(pb, pd->buf, probe_size);
623             if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
624                 url_fclose(pb);
625                 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
626                     file_opened = 0;
627                     err = AVERROR_IO;
628                     goto fail;
629                 }
630             }
631             /* guess file format */
632             fmt = av_probe_input_format(pd, 1);
633         }
634         av_freep(&pd->buf);
635     }
636
637     /* if still no format found, error */
638     if (!fmt) {
639         err = AVERROR_NOFMT;
640         goto fail;
641     }
642
643     /* XXX: suppress this hack for redirectors */
644 #ifdef CONFIG_NETWORK
645     if (fmt == &redir_demuxer) {
646         err = redir_open(ic_ptr, pb);
647         url_fclose(pb);
648         return err;
649     }
650 #endif
651
652     /* check filename in case of an image number is expected */
653     if (fmt->flags & AVFMT_NEEDNUMBER) {
654         if (!av_filename_number_test(filename)) {
655             err = AVERROR_NUMEXPECTED;
656             goto fail;
657         }
658     }
659     err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
660     if (err)
661         goto fail;
662     return 0;
663  fail:
664     av_freep(&pd->buf);
665     if (file_opened)
666         url_fclose(pb);
667     *ic_ptr = NULL;
668     return err;
669
670 }
671
672 /*******************************************************/
673
674 /**
675  * Read a transport packet from a media file.
676  *
677  * This function is absolete and should never be used.
678  * Use av_read_frame() instead.
679  *
680  * @param s media file handle
681  * @param pkt is filled
682  * @return 0 if OK. AVERROR_xxx if error.
683  */
684 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
685 {
686     return s->iformat->read_packet(s, pkt);
687 }
688
689 /**********************************************************/
690
691 /**
692  * Get the number of samples of an audio frame. Return (-1) if error.
693  */
694 static int get_audio_frame_size(AVCodecContext *enc, int size)
695 {
696     int frame_size;
697
698     if (enc->frame_size <= 1) {
699         int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
700
701         if (bits_per_sample) {
702             if (enc->channels == 0)
703                 return -1;
704             frame_size = (size << 3) / (bits_per_sample * enc->channels);
705         } else {
706             /* used for example by ADPCM codecs */
707             if (enc->bit_rate == 0)
708                 return -1;
709             frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
710         }
711     } else {
712         frame_size = enc->frame_size;
713     }
714     return frame_size;
715 }
716
717
718 /**
719  * Return the frame duration in seconds, return 0 if not available.
720  */
721 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
722                                    AVCodecParserContext *pc, AVPacket *pkt)
723 {
724     int frame_size;
725
726     *pnum = 0;
727     *pden = 0;
728     switch(st->codec->codec_type) {
729     case CODEC_TYPE_VIDEO:
730         if(st->time_base.num*1000LL > st->time_base.den){
731             *pnum = st->time_base.num;
732             *pden = st->time_base.den;
733         }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
734             *pnum = st->codec->time_base.num;
735             *pden = st->codec->time_base.den;
736             if (pc && pc->repeat_pict) {
737                 *pden *= 2;
738                 *pnum = (*pnum) * (2 + pc->repeat_pict);
739             }
740         }
741         break;
742     case CODEC_TYPE_AUDIO:
743         frame_size = get_audio_frame_size(st->codec, pkt->size);
744         if (frame_size < 0)
745             break;
746         *pnum = frame_size;
747         *pden = st->codec->sample_rate;
748         break;
749     default:
750         break;
751     }
752 }
753
754 static int is_intra_only(AVCodecContext *enc){
755     if(enc->codec_type == CODEC_TYPE_AUDIO){
756         return 1;
757     }else if(enc->codec_type == CODEC_TYPE_VIDEO){
758         switch(enc->codec_id){
759         case CODEC_ID_MJPEG:
760         case CODEC_ID_MJPEGB:
761         case CODEC_ID_LJPEG:
762         case CODEC_ID_RAWVIDEO:
763         case CODEC_ID_DVVIDEO:
764         case CODEC_ID_HUFFYUV:
765         case CODEC_ID_FFVHUFF:
766         case CODEC_ID_ASV1:
767         case CODEC_ID_ASV2:
768         case CODEC_ID_VCR1:
769             return 1;
770         default: break;
771         }
772     }
773     return 0;
774 }
775
776 static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
777     int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
778     int64_t delta= last_ts - mask/2;
779     return  ((lsb - delta)&mask) + delta;
780 }
781
782 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
783                                AVCodecParserContext *pc, AVPacket *pkt)
784 {
785     int num, den, presentation_delayed;
786     /* handle wrapping */
787     if(st->cur_dts != AV_NOPTS_VALUE){
788         if(pkt->pts != AV_NOPTS_VALUE)
789             pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
790         if(pkt->dts != AV_NOPTS_VALUE)
791             pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
792     }
793
794     if (pkt->duration == 0) {
795         compute_frame_duration(&num, &den, st, pc, pkt);
796         if (den && num) {
797             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
798         }
799     }
800
801     if(is_intra_only(st->codec))
802         pkt->flags |= PKT_FLAG_KEY;
803
804     /* do we have a video B frame ? */
805     presentation_delayed = 0;
806     if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
807         /* XXX: need has_b_frame, but cannot get it if the codec is
808            not initialized */
809         if ((   st->codec->codec_id == CODEC_ID_H264
810              || st->codec->has_b_frames) &&
811             pc && pc->pict_type != FF_B_TYPE)
812             presentation_delayed = 1;
813         /* this may be redundant, but it shouldnt hurt */
814         if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
815             presentation_delayed = 1;
816     }
817
818     if(st->cur_dts == AV_NOPTS_VALUE){
819         if(presentation_delayed) st->cur_dts = -pkt->duration;
820         else                     st->cur_dts = 0;
821     }
822
823 //    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%lld, dts:%lld cur_dts:%lld st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
824     /* interpolate PTS and DTS if they are not present */
825     if (presentation_delayed) {
826         /* DTS = decompression time stamp */
827         /* PTS = presentation time stamp */
828         if (pkt->dts == AV_NOPTS_VALUE) {
829             /* if we know the last pts, use it */
830             if(st->last_IP_pts != AV_NOPTS_VALUE)
831                 st->cur_dts = pkt->dts = st->last_IP_pts;
832             else
833                 pkt->dts = st->cur_dts;
834         } else {
835             st->cur_dts = pkt->dts;
836         }
837         /* this is tricky: the dts must be incremented by the duration
838            of the frame we are displaying, i.e. the last I or P frame */
839         if (st->last_IP_duration == 0)
840             st->cur_dts += pkt->duration;
841         else
842             st->cur_dts += st->last_IP_duration;
843         st->last_IP_duration  = pkt->duration;
844         st->last_IP_pts= pkt->pts;
845         /* cannot compute PTS if not present (we can compute it only
846            by knowing the futur */
847     } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
848         if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
849             int64_t old_diff= ABS(st->cur_dts - pkt->duration - pkt->pts);
850             int64_t new_diff= ABS(st->cur_dts - pkt->pts);
851             if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
852                 pkt->pts += pkt->duration;
853 //                av_log(NULL, AV_LOG_DEBUG, "id:%d old:%Ld new:%Ld dur:%d cur:%Ld size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
854             }
855         }
856
857         /* presentation is not delayed : PTS and DTS are the same */
858         if (pkt->pts == AV_NOPTS_VALUE) {
859             if (pkt->dts == AV_NOPTS_VALUE) {
860                 pkt->pts = st->cur_dts;
861                 pkt->dts = st->cur_dts;
862             }
863             else {
864                 st->cur_dts = pkt->dts;
865                 pkt->pts = pkt->dts;
866             }
867         } else {
868             st->cur_dts = pkt->pts;
869             pkt->dts = pkt->pts;
870         }
871         st->cur_dts += pkt->duration;
872     }
873 //    av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
874
875     /* update flags */
876     if (pc) {
877         pkt->flags = 0;
878         /* key frame computation */
879         switch(st->codec->codec_type) {
880         case CODEC_TYPE_VIDEO:
881             if (pc->pict_type == FF_I_TYPE)
882                 pkt->flags |= PKT_FLAG_KEY;
883             break;
884         case CODEC_TYPE_AUDIO:
885             pkt->flags |= PKT_FLAG_KEY;
886             break;
887         default:
888             break;
889         }
890     }
891 }
892
893 void av_destruct_packet_nofree(AVPacket *pkt)
894 {
895     pkt->data = NULL; pkt->size = 0;
896 }
897
898 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
899 {
900     AVStream *st;
901     int len, ret, i;
902
903     for(;;) {
904         /* select current input stream component */
905         st = s->cur_st;
906         if (st) {
907             if (!st->need_parsing || !st->parser) {
908                 /* no parsing needed: we just output the packet as is */
909                 /* raw data support */
910                 *pkt = s->cur_pkt;
911                 compute_pkt_fields(s, st, NULL, pkt);
912                 s->cur_st = NULL;
913                 break;
914             } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
915                 len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
916                                       s->cur_ptr, s->cur_len,
917                                       s->cur_pkt.pts, s->cur_pkt.dts);
918                 s->cur_pkt.pts = AV_NOPTS_VALUE;
919                 s->cur_pkt.dts = AV_NOPTS_VALUE;
920                 /* increment read pointer */
921                 s->cur_ptr += len;
922                 s->cur_len -= len;
923
924                 /* return packet if any */
925                 if (pkt->size) {
926                 got_packet:
927                     pkt->duration = 0;
928                     pkt->stream_index = st->index;
929                     pkt->pts = st->parser->pts;
930                     pkt->dts = st->parser->dts;
931                     pkt->destruct = av_destruct_packet_nofree;
932                     compute_pkt_fields(s, st, st->parser, pkt);
933                     break;
934                 }
935             } else {
936                 /* free packet */
937                 av_free_packet(&s->cur_pkt);
938                 s->cur_st = NULL;
939             }
940         } else {
941             /* read next packet */
942             ret = av_read_packet(s, &s->cur_pkt);
943             if (ret < 0) {
944                 if (ret == -EAGAIN)
945                     return ret;
946                 /* return the last frames, if any */
947                 for(i = 0; i < s->nb_streams; i++) {
948                     st = s->streams[i];
949                     if (st->parser && st->need_parsing) {
950                         av_parser_parse(st->parser, st->codec,
951                                         &pkt->data, &pkt->size,
952                                         NULL, 0,
953                                         AV_NOPTS_VALUE, AV_NOPTS_VALUE);
954                         if (pkt->size)
955                             goto got_packet;
956                     }
957                 }
958                 /* no more packets: really terminates parsing */
959                 return ret;
960             }
961
962             st = s->streams[s->cur_pkt.stream_index];
963             if(st->codec->debug & FF_DEBUG_PTS)
964                 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%lld, dts=%lld, size=%d\n",
965                     s->cur_pkt.stream_index,
966                     s->cur_pkt.pts,
967                     s->cur_pkt.dts,
968                     s->cur_pkt.size);
969
970             s->cur_st = st;
971             s->cur_ptr = s->cur_pkt.data;
972             s->cur_len = s->cur_pkt.size;
973             if (st->need_parsing && !st->parser) {
974                 st->parser = av_parser_init(st->codec->codec_id);
975                 if (!st->parser) {
976                     /* no parser available : just output the raw packets */
977                     st->need_parsing = 0;
978                 }else if(st->need_parsing == 2){
979                     st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
980                 }
981             }
982         }
983     }
984     if(st->codec->debug & FF_DEBUG_PTS)
985         av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%lld, dts=%lld, size=%d\n",
986             pkt->stream_index,
987             pkt->pts,
988             pkt->dts,
989             pkt->size);
990
991     return 0;
992 }
993
994 /**
995  * Return the next frame of a stream.
996  *
997  * The returned packet is valid
998  * until the next av_read_frame() or until av_close_input_file() and
999  * must be freed with av_free_packet. For video, the packet contains
1000  * exactly one frame. For audio, it contains an integer number of
1001  * frames if each frame has a known fixed size (e.g. PCM or ADPCM
1002  * data). If the audio frames have a variable size (e.g. MPEG audio),
1003  * then it contains one frame.
1004  *
1005  * pkt->pts, pkt->dts and pkt->duration are always set to correct
1006  * values in AV_TIME_BASE unit (and guessed if the format cannot
1007  * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
1008  * has B frames, so it is better to rely on pkt->dts if you do not
1009  * decompress the payload.
1010  *
1011  * @return 0 if OK, < 0 if error or end of file.
1012  */
1013 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1014 {
1015     AVPacketList *pktl;
1016     int eof=0;
1017     const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1018
1019     for(;;){
1020         pktl = s->packet_buffer;
1021         if (pktl) {
1022             AVPacket *next_pkt= &pktl->pkt;
1023
1024             if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1025                 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1026                     if(   pktl->pkt.stream_index == next_pkt->stream_index
1027                        && next_pkt->dts < pktl->pkt.dts
1028                        && pktl->pkt.pts != pktl->pkt.dts //not b frame
1029                        /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1030                         next_pkt->pts= pktl->pkt.dts;
1031                     }
1032                     pktl= pktl->next;
1033                 }
1034                 pktl = s->packet_buffer;
1035             }
1036
1037             if(   next_pkt->pts != AV_NOPTS_VALUE
1038                || next_pkt->dts == AV_NOPTS_VALUE
1039                || !genpts || eof){
1040                 /* read packet from packet buffer, if there is data */
1041                 *pkt = *next_pkt;
1042                 s->packet_buffer = pktl->next;
1043                 av_free(pktl);
1044                 return 0;
1045             }
1046         }
1047         if(genpts){
1048             AVPacketList **plast_pktl= &s->packet_buffer;
1049             int ret= av_read_frame_internal(s, pkt);
1050             if(ret<0){
1051                 if(pktl && ret != -EAGAIN){
1052                     eof=1;
1053                     continue;
1054                 }else
1055                     return ret;
1056             }
1057
1058             /* duplicate the packet */
1059             if (av_dup_packet(pkt) < 0)
1060                 return AVERROR_NOMEM;
1061
1062             while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
1063
1064             pktl = av_mallocz(sizeof(AVPacketList));
1065             if (!pktl)
1066                 return AVERROR_NOMEM;
1067
1068             /* add the packet in the buffered packet list */
1069             *plast_pktl = pktl;
1070             pktl->pkt= *pkt;
1071         }else{
1072             assert(!s->packet_buffer);
1073             return av_read_frame_internal(s, pkt);
1074         }
1075     }
1076 }
1077
1078 /* XXX: suppress the packet queue */
1079 static void flush_packet_queue(AVFormatContext *s)
1080 {
1081     AVPacketList *pktl;
1082
1083     for(;;) {
1084         pktl = s->packet_buffer;
1085         if (!pktl)
1086             break;
1087         s->packet_buffer = pktl->next;
1088         av_free_packet(&pktl->pkt);
1089         av_free(pktl);
1090     }
1091 }
1092
1093 /*******************************************************/
1094 /* seek support */
1095
1096 int av_find_default_stream_index(AVFormatContext *s)
1097 {
1098     int i;
1099     AVStream *st;
1100
1101     if (s->nb_streams <= 0)
1102         return -1;
1103     for(i = 0; i < s->nb_streams; i++) {
1104         st = s->streams[i];
1105         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1106             return i;
1107         }
1108     }
1109     return 0;
1110 }
1111
1112 /**
1113  * Flush the frame reader.
1114  */
1115 static void av_read_frame_flush(AVFormatContext *s)
1116 {
1117     AVStream *st;
1118     int i;
1119
1120     flush_packet_queue(s);
1121
1122     /* free previous packet */
1123     if (s->cur_st) {
1124         if (s->cur_st->parser)
1125             av_free_packet(&s->cur_pkt);
1126         s->cur_st = NULL;
1127     }
1128     /* fail safe */
1129     s->cur_ptr = NULL;
1130     s->cur_len = 0;
1131
1132     /* for each stream, reset read state */
1133     for(i = 0; i < s->nb_streams; i++) {
1134         st = s->streams[i];
1135
1136         if (st->parser) {
1137             av_parser_close(st->parser);
1138             st->parser = NULL;
1139         }
1140         st->last_IP_pts = AV_NOPTS_VALUE;
1141         st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
1142     }
1143 }
1144
1145 /**
1146  * Updates cur_dts of all streams based on given timestamp and AVStream.
1147  *
1148  * Stream ref_st unchanged, others set cur_dts in their native timebase
1149  * only needed for timestamp wrapping or if (dts not set and pts!=dts)
1150  * @param timestamp new dts expressed in time_base of param ref_st
1151  * @param ref_st reference stream giving time_base of param timestamp
1152  */
1153 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1154     int i;
1155
1156     for(i = 0; i < s->nb_streams; i++) {
1157         AVStream *st = s->streams[i];
1158
1159         st->cur_dts = av_rescale(timestamp,
1160                                  st->time_base.den * (int64_t)ref_st->time_base.num,
1161                                  st->time_base.num * (int64_t)ref_st->time_base.den);
1162     }
1163 }
1164
1165 /**
1166  * Add a index entry into a sorted list updateing if it is already there.
1167  *
1168  * @param timestamp timestamp in the timebase of the given stream
1169  */
1170 int av_add_index_entry(AVStream *st,
1171                             int64_t pos, int64_t timestamp, int size, int distance, int flags)
1172 {
1173     AVIndexEntry *entries, *ie;
1174     int index;
1175
1176     if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1177         return -1;
1178
1179     entries = av_fast_realloc(st->index_entries,
1180                               &st->index_entries_allocated_size,
1181                               (st->nb_index_entries + 1) *
1182                               sizeof(AVIndexEntry));
1183     if(!entries)
1184         return -1;
1185
1186     st->index_entries= entries;
1187
1188     index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1189
1190     if(index<0){
1191         index= st->nb_index_entries++;
1192         ie= &entries[index];
1193         assert(index==0 || ie[-1].timestamp < timestamp);
1194     }else{
1195         ie= &entries[index];
1196         if(ie->timestamp != timestamp){
1197             if(ie->timestamp <= timestamp)
1198                 return -1;
1199             memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1200             st->nb_index_entries++;
1201         }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
1202             distance= ie->min_distance;
1203     }
1204
1205     ie->pos = pos;
1206     ie->timestamp = timestamp;
1207     ie->min_distance= distance;
1208     ie->size= size;
1209     ie->flags = flags;
1210
1211     return index;
1212 }
1213
1214 /**
1215  * build an index for raw streams using a parser.
1216  */
1217 static void av_build_index_raw(AVFormatContext *s)
1218 {
1219     AVPacket pkt1, *pkt = &pkt1;
1220     int ret;
1221     AVStream *st;
1222
1223     st = s->streams[0];
1224     av_read_frame_flush(s);
1225     url_fseek(&s->pb, s->data_offset, SEEK_SET);
1226
1227     for(;;) {
1228         ret = av_read_frame(s, pkt);
1229         if (ret < 0)
1230             break;
1231         if (pkt->stream_index == 0 && st->parser &&
1232             (pkt->flags & PKT_FLAG_KEY)) {
1233             av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1234                             0, 0, AVINDEX_KEYFRAME);
1235         }
1236         av_free_packet(pkt);
1237     }
1238 }
1239
1240 /**
1241  * Returns TRUE if we deal with a raw stream.
1242  *
1243  * Raw codec data and parsing needed.
1244  */
1245 static int is_raw_stream(AVFormatContext *s)
1246 {
1247     AVStream *st;
1248
1249     if (s->nb_streams != 1)
1250         return 0;
1251     st = s->streams[0];
1252     if (!st->need_parsing)
1253         return 0;
1254     return 1;
1255 }
1256
1257 /**
1258  * Gets the index for a specific timestamp.
1259  * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
1260  *                 the timestamp which is <= the requested one, if backward is 0
1261  *                 then it will be >=
1262  *              if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
1263  * @return < 0 if no such timestamp could be found
1264  */
1265 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1266                               int flags)
1267 {
1268     AVIndexEntry *entries= st->index_entries;
1269     int nb_entries= st->nb_index_entries;
1270     int a, b, m;
1271     int64_t timestamp;
1272
1273     a = - 1;
1274     b = nb_entries;
1275
1276     while (b - a > 1) {
1277         m = (a + b) >> 1;
1278         timestamp = entries[m].timestamp;
1279         if(timestamp >= wanted_timestamp)
1280             b = m;
1281         if(timestamp <= wanted_timestamp)
1282             a = m;
1283     }
1284     m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1285
1286     if(!(flags & AVSEEK_FLAG_ANY)){
1287         while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1288             m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1289         }
1290     }
1291
1292     if(m == nb_entries)
1293         return -1;
1294     return  m;
1295 }
1296
1297 #define DEBUG_SEEK
1298
1299 /**
1300  * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1301  * this isnt supposed to be called directly by a user application, but by demuxers
1302  * @param target_ts target timestamp in the time base of the given stream
1303  * @param stream_index stream number
1304  */
1305 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1306     AVInputFormat *avif= s->iformat;
1307     int64_t pos_min, pos_max, pos, pos_limit;
1308     int64_t ts_min, ts_max, ts;
1309     int64_t start_pos, filesize;
1310     int index, no_change;
1311     AVStream *st;
1312
1313     if (stream_index < 0)
1314         return -1;
1315
1316 #ifdef DEBUG_SEEK
1317     av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1318 #endif
1319
1320     ts_max=
1321     ts_min= AV_NOPTS_VALUE;
1322     pos_limit= -1; //gcc falsely says it may be uninitalized
1323
1324     st= s->streams[stream_index];
1325     if(st->index_entries){
1326         AVIndexEntry *e;
1327
1328         index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non keyframe entries in index case, especially read_timestamp()
1329         index= FFMAX(index, 0);
1330         e= &st->index_entries[index];
1331
1332         if(e->timestamp <= target_ts || e->pos == e->min_distance){
1333             pos_min= e->pos;
1334             ts_min= e->timestamp;
1335 #ifdef DEBUG_SEEK
1336         av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1337                pos_min,ts_min);
1338 #endif
1339         }else{
1340             assert(index==0);
1341         }
1342
1343         index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1344         assert(index < st->nb_index_entries);
1345         if(index >= 0){
1346             e= &st->index_entries[index];
1347             assert(e->timestamp >= target_ts);
1348             pos_max= e->pos;
1349             ts_max= e->timestamp;
1350             pos_limit= pos_max - e->min_distance;
1351 #ifdef DEBUG_SEEK
1352         av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1353                pos_max,pos_limit, ts_max);
1354 #endif
1355         }
1356     }
1357
1358     if(ts_min == AV_NOPTS_VALUE){
1359         pos_min = s->data_offset;
1360         ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1361         if (ts_min == AV_NOPTS_VALUE)
1362             return -1;
1363     }
1364
1365     if(ts_max == AV_NOPTS_VALUE){
1366         int step= 1024;
1367         filesize = url_fsize(&s->pb);
1368         pos_max = filesize - 1;
1369         do{
1370             pos_max -= step;
1371             ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1372             step += step;
1373         }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1374         if (ts_max == AV_NOPTS_VALUE)
1375             return -1;
1376
1377         for(;;){
1378             int64_t tmp_pos= pos_max + 1;
1379             int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1380             if(tmp_ts == AV_NOPTS_VALUE)
1381                 break;
1382             ts_max= tmp_ts;
1383             pos_max= tmp_pos;
1384             if(tmp_pos >= filesize)
1385                 break;
1386         }
1387         pos_limit= pos_max;
1388     }
1389
1390     if(ts_min > ts_max){
1391         return -1;
1392     }else if(ts_min == ts_max){
1393         pos_limit= pos_min;
1394     }
1395
1396     no_change=0;
1397     while (pos_min < pos_limit) {
1398 #ifdef DEBUG_SEEK
1399         av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1400                pos_min, pos_max,
1401                ts_min, ts_max);
1402 #endif
1403         assert(pos_limit <= pos_max);
1404
1405         if(no_change==0){
1406             int64_t approximate_keyframe_distance= pos_max - pos_limit;
1407             // interpolate position (better than dichotomy)
1408             pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1409                 + pos_min - approximate_keyframe_distance;
1410         }else if(no_change==1){
1411             // bisection, if interpolation failed to change min or max pos last time
1412             pos = (pos_min + pos_limit)>>1;
1413         }else{
1414             // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1415             pos=pos_min;
1416         }
1417         if(pos <= pos_min)
1418             pos= pos_min + 1;
1419         else if(pos > pos_limit)
1420             pos= pos_limit;
1421         start_pos= pos;
1422
1423         ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1424         if(pos == pos_max)
1425             no_change++;
1426         else
1427             no_change=0;
1428 #ifdef DEBUG_SEEK
1429 av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1430 #endif
1431         assert(ts != AV_NOPTS_VALUE);
1432         if (target_ts <= ts) {
1433             pos_limit = start_pos - 1;
1434             pos_max = pos;
1435             ts_max = ts;
1436         }
1437         if (target_ts >= ts) {
1438             pos_min = pos;
1439             ts_min = ts;
1440         }
1441     }
1442
1443     pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1444     ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1445 #ifdef DEBUG_SEEK
1446     pos_min = pos;
1447     ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1448     pos_min++;
1449     ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1450     av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1451            pos, ts_min, target_ts, ts_max);
1452 #endif
1453     /* do the seek */
1454     url_fseek(&s->pb, pos, SEEK_SET);
1455
1456     av_update_cur_dts(s, st, ts);
1457
1458     return 0;
1459 }
1460
1461 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1462     int64_t pos_min, pos_max;
1463 #if 0
1464     AVStream *st;
1465
1466     if (stream_index < 0)
1467         return -1;
1468
1469     st= s->streams[stream_index];
1470 #endif
1471
1472     pos_min = s->data_offset;
1473     pos_max = url_fsize(&s->pb) - 1;
1474
1475     if     (pos < pos_min) pos= pos_min;
1476     else if(pos > pos_max) pos= pos_max;
1477
1478     url_fseek(&s->pb, pos, SEEK_SET);
1479
1480 #if 0
1481     av_update_cur_dts(s, st, ts);
1482 #endif
1483     return 0;
1484 }
1485
1486 static int av_seek_frame_generic(AVFormatContext *s,
1487                                  int stream_index, int64_t timestamp, int flags)
1488 {
1489     int index;
1490     AVStream *st;
1491     AVIndexEntry *ie;
1492
1493     if (!s->index_built) {
1494         if (is_raw_stream(s)) {
1495             av_build_index_raw(s);
1496         } else {
1497             return -1;
1498         }
1499         s->index_built = 1;
1500     }
1501
1502     st = s->streams[stream_index];
1503     index = av_index_search_timestamp(st, timestamp, flags);
1504     if (index < 0)
1505         return -1;
1506
1507     /* now we have found the index, we can seek */
1508     ie = &st->index_entries[index];
1509     av_read_frame_flush(s);
1510     url_fseek(&s->pb, ie->pos, SEEK_SET);
1511
1512     av_update_cur_dts(s, st, ie->timestamp);
1513
1514     return 0;
1515 }
1516
1517 /**
1518  * Seek to the key frame at timestamp.
1519  * 'timestamp' in 'stream_index'.
1520  * @param stream_index If stream_index is (-1), a default
1521  * stream is selected, and timestamp is automatically converted
1522  * from AV_TIME_BASE units to the stream specific time_base.
1523  * @param timestamp timestamp in AVStream.time_base units
1524  *        or if there is no stream specified then in AV_TIME_BASE units
1525  * @param flags flags which select direction and seeking mode
1526  * @return >= 0 on success
1527  */
1528 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1529 {
1530     int ret;
1531     AVStream *st;
1532
1533     av_read_frame_flush(s);
1534
1535     if(flags & AVSEEK_FLAG_BYTE)
1536         return av_seek_frame_byte(s, stream_index, timestamp, flags);
1537
1538     if(stream_index < 0){
1539         stream_index= av_find_default_stream_index(s);
1540         if(stream_index < 0)
1541             return -1;
1542
1543         st= s->streams[stream_index];
1544        /* timestamp for default must be expressed in AV_TIME_BASE units */
1545         timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1546     }
1547     st= s->streams[stream_index];
1548
1549     /* first, we try the format specific seek */
1550     if (s->iformat->read_seek)
1551         ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1552     else
1553         ret = -1;
1554     if (ret >= 0) {
1555         return 0;
1556     }
1557
1558     if(s->iformat->read_timestamp)
1559         return av_seek_frame_binary(s, stream_index, timestamp, flags);
1560     else
1561         return av_seek_frame_generic(s, stream_index, timestamp, flags);
1562 }
1563
1564 /*******************************************************/
1565
1566 /**
1567  * Returns TRUE if the stream has accurate timings in any stream.
1568  *
1569  * @return TRUE if the stream has accurate timings for at least one component.
1570  */
1571 static int av_has_timings(AVFormatContext *ic)
1572 {
1573     int i;
1574     AVStream *st;
1575
1576     for(i = 0;i < ic->nb_streams; i++) {
1577         st = ic->streams[i];
1578         if (st->start_time != AV_NOPTS_VALUE &&
1579             st->duration != AV_NOPTS_VALUE)
1580             return 1;
1581     }
1582     return 0;
1583 }
1584
1585 /**
1586  * Estimate the stream timings from the one of each components.
1587  *
1588  * Also computes the global bitrate if possible.
1589  */
1590 static void av_update_stream_timings(AVFormatContext *ic)
1591 {
1592     int64_t start_time, start_time1, end_time, end_time1;
1593     int i;
1594     AVStream *st;
1595
1596     start_time = MAXINT64;
1597     end_time = MININT64;
1598     for(i = 0;i < ic->nb_streams; i++) {
1599         st = ic->streams[i];
1600         if (st->start_time != AV_NOPTS_VALUE) {
1601             start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1602             if (start_time1 < start_time)
1603                 start_time = start_time1;
1604             if (st->duration != AV_NOPTS_VALUE) {
1605                 end_time1 = start_time1
1606                           + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1607                 if (end_time1 > end_time)
1608                     end_time = end_time1;
1609             }
1610         }
1611     }
1612     if (start_time != MAXINT64) {
1613         ic->start_time = start_time;
1614         if (end_time != MININT64) {
1615             ic->duration = end_time - start_time;
1616             if (ic->file_size > 0) {
1617                 /* compute the bit rate */
1618                 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1619                     (double)ic->duration;
1620             }
1621         }
1622     }
1623
1624 }
1625
1626 static void fill_all_stream_timings(AVFormatContext *ic)
1627 {
1628     int i;
1629     AVStream *st;
1630
1631     av_update_stream_timings(ic);
1632     for(i = 0;i < ic->nb_streams; i++) {
1633         st = ic->streams[i];
1634         if (st->start_time == AV_NOPTS_VALUE) {
1635             if(ic->start_time != AV_NOPTS_VALUE)
1636                 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1637             if(ic->duration != AV_NOPTS_VALUE)
1638                 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1639         }
1640     }
1641 }
1642
1643 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1644 {
1645     int64_t filesize, duration;
1646     int bit_rate, i;
1647     AVStream *st;
1648
1649     /* if bit_rate is already set, we believe it */
1650     if (ic->bit_rate == 0) {
1651         bit_rate = 0;
1652         for(i=0;i<ic->nb_streams;i++) {
1653             st = ic->streams[i];
1654             bit_rate += st->codec->bit_rate;
1655         }
1656         ic->bit_rate = bit_rate;
1657     }
1658
1659     /* if duration is already set, we believe it */
1660     if (ic->duration == AV_NOPTS_VALUE &&
1661         ic->bit_rate != 0 &&
1662         ic->file_size != 0)  {
1663         filesize = ic->file_size;
1664         if (filesize > 0) {
1665             for(i = 0; i < ic->nb_streams; i++) {
1666                 st = ic->streams[i];
1667                 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1668                 if (st->start_time == AV_NOPTS_VALUE ||
1669                     st->duration == AV_NOPTS_VALUE) {
1670                     st->start_time = 0;
1671                     st->duration = duration;
1672                 }
1673             }
1674         }
1675     }
1676 }
1677
1678 #define DURATION_MAX_READ_SIZE 250000
1679
1680 /* only usable for MPEG-PS streams */
1681 static void av_estimate_timings_from_pts(AVFormatContext *ic)
1682 {
1683     AVPacket pkt1, *pkt = &pkt1;
1684     AVStream *st;
1685     int read_size, i, ret;
1686     int64_t end_time;
1687     int64_t filesize, offset, duration;
1688
1689     /* free previous packet */
1690     if (ic->cur_st && ic->cur_st->parser)
1691         av_free_packet(&ic->cur_pkt);
1692     ic->cur_st = NULL;
1693
1694     /* flush packet queue */
1695     flush_packet_queue(ic);
1696
1697     for(i=0;i<ic->nb_streams;i++) {
1698         st = ic->streams[i];
1699         if (st->parser) {
1700             av_parser_close(st->parser);
1701             st->parser= NULL;
1702         }
1703     }
1704
1705     /* we read the first packets to get the first PTS (not fully
1706        accurate, but it is enough now) */
1707     url_fseek(&ic->pb, 0, SEEK_SET);
1708     read_size = 0;
1709     for(;;) {
1710         if (read_size >= DURATION_MAX_READ_SIZE)
1711             break;
1712         /* if all info is available, we can stop */
1713         for(i = 0;i < ic->nb_streams; i++) {
1714             st = ic->streams[i];
1715             if (st->start_time == AV_NOPTS_VALUE)
1716                 break;
1717         }
1718         if (i == ic->nb_streams)
1719             break;
1720
1721         ret = av_read_packet(ic, pkt);
1722         if (ret != 0)
1723             break;
1724         read_size += pkt->size;
1725         st = ic->streams[pkt->stream_index];
1726         if (pkt->pts != AV_NOPTS_VALUE) {
1727             if (st->start_time == AV_NOPTS_VALUE)
1728                 st->start_time = pkt->pts;
1729         }
1730         av_free_packet(pkt);
1731     }
1732
1733     /* estimate the end time (duration) */
1734     /* XXX: may need to support wrapping */
1735     filesize = ic->file_size;
1736     offset = filesize - DURATION_MAX_READ_SIZE;
1737     if (offset < 0)
1738         offset = 0;
1739
1740     url_fseek(&ic->pb, offset, SEEK_SET);
1741     read_size = 0;
1742     for(;;) {
1743         if (read_size >= DURATION_MAX_READ_SIZE)
1744             break;
1745         /* if all info is available, we can stop */
1746         for(i = 0;i < ic->nb_streams; i++) {
1747             st = ic->streams[i];
1748             if (st->duration == AV_NOPTS_VALUE)
1749                 break;
1750         }
1751         if (i == ic->nb_streams)
1752             break;
1753
1754         ret = av_read_packet(ic, pkt);
1755         if (ret != 0)
1756             break;
1757         read_size += pkt->size;
1758         st = ic->streams[pkt->stream_index];
1759         if (pkt->pts != AV_NOPTS_VALUE) {
1760             end_time = pkt->pts;
1761             duration = end_time - st->start_time;
1762             if (duration > 0) {
1763                 if (st->duration == AV_NOPTS_VALUE ||
1764                     st->duration < duration)
1765                     st->duration = duration;
1766             }
1767         }
1768         av_free_packet(pkt);
1769     }
1770
1771     fill_all_stream_timings(ic);
1772
1773     url_fseek(&ic->pb, 0, SEEK_SET);
1774 }
1775
1776 static void av_estimate_timings(AVFormatContext *ic)
1777 {
1778     int64_t file_size;
1779
1780     /* get the file size, if possible */
1781     if (ic->iformat->flags & AVFMT_NOFILE) {
1782         file_size = 0;
1783     } else {
1784         file_size = url_fsize(&ic->pb);
1785         if (file_size < 0)
1786             file_size = 0;
1787     }
1788     ic->file_size = file_size;
1789
1790     if ((!strcmp(ic->iformat->name, "mpeg") ||
1791          !strcmp(ic->iformat->name, "mpegts")) &&
1792         file_size && !ic->pb.is_streamed) {
1793         /* get accurate estimate from the PTSes */
1794         av_estimate_timings_from_pts(ic);
1795     } else if (av_has_timings(ic)) {
1796         /* at least one components has timings - we use them for all
1797            the components */
1798         fill_all_stream_timings(ic);
1799     } else {
1800         /* less precise: use bit rate info */
1801         av_estimate_timings_from_bit_rate(ic);
1802     }
1803     av_update_stream_timings(ic);
1804
1805 #if 0
1806     {
1807         int i;
1808         AVStream *st;
1809         for(i = 0;i < ic->nb_streams; i++) {
1810             st = ic->streams[i];
1811         printf("%d: start_time: %0.3f duration: %0.3f\n",
1812                i, (double)st->start_time / AV_TIME_BASE,
1813                (double)st->duration / AV_TIME_BASE);
1814         }
1815         printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1816                (double)ic->start_time / AV_TIME_BASE,
1817                (double)ic->duration / AV_TIME_BASE,
1818                ic->bit_rate / 1000);
1819     }
1820 #endif
1821 }
1822
1823 static int has_codec_parameters(AVCodecContext *enc)
1824 {
1825     int val;
1826     switch(enc->codec_type) {
1827     case CODEC_TYPE_AUDIO:
1828         val = enc->sample_rate;
1829         break;
1830     case CODEC_TYPE_VIDEO:
1831         val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1832         break;
1833     default:
1834         val = 1;
1835         break;
1836     }
1837     return (val != 0);
1838 }
1839
1840 static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1841 {
1842     int16_t *samples;
1843     AVCodec *codec;
1844     int got_picture, ret=0;
1845     AVFrame picture;
1846
1847   if(!st->codec->codec){
1848     codec = avcodec_find_decoder(st->codec->codec_id);
1849     if (!codec)
1850         return -1;
1851     ret = avcodec_open(st->codec, codec);
1852     if (ret < 0)
1853         return ret;
1854   }
1855
1856   if(!has_codec_parameters(st->codec)){
1857     switch(st->codec->codec_type) {
1858     case CODEC_TYPE_VIDEO:
1859         ret = avcodec_decode_video(st->codec, &picture,
1860                                    &got_picture, (uint8_t *)data, size);
1861         break;
1862     case CODEC_TYPE_AUDIO:
1863         samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1864         if (!samples)
1865             goto fail;
1866         ret = avcodec_decode_audio(st->codec, samples,
1867                                    &got_picture, (uint8_t *)data, size);
1868         av_free(samples);
1869         break;
1870     default:
1871         break;
1872     }
1873   }
1874  fail:
1875     return ret;
1876 }
1877
1878 /* absolute maximum size we read until we abort */
1879 #define MAX_READ_SIZE        5000000
1880
1881 /* maximum duration until we stop analysing the stream */
1882 #define MAX_STREAM_DURATION  ((int)(AV_TIME_BASE * 3.0))
1883
1884 /**
1885  * Read the beginning of a media file to get stream information. This
1886  * is useful for file formats with no headers such as MPEG. This
1887  * function also compute the real frame rate in case of mpeg2 repeat
1888  * frame mode.
1889  *
1890  * @param ic media file handle
1891  * @return >=0 if OK. AVERROR_xxx if error.
1892  * @todo let user decide somehow what information is needed so we dont waste time geting stuff the user doesnt need
1893  */
1894 int av_find_stream_info(AVFormatContext *ic)
1895 {
1896     int i, count, ret, read_size, j;
1897     AVStream *st;
1898     AVPacket pkt1, *pkt;
1899     AVPacketList *pktl=NULL, **ppktl;
1900     int64_t last_dts[MAX_STREAMS];
1901     int64_t duration_sum[MAX_STREAMS];
1902     int duration_count[MAX_STREAMS]={0};
1903
1904     for(i=0;i<ic->nb_streams;i++) {
1905         st = ic->streams[i];
1906         if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1907 /*            if(!st->time_base.num)
1908                 st->time_base= */
1909             if(!st->codec->time_base.num)
1910                 st->codec->time_base= st->time_base;
1911         }
1912         //only for the split stuff
1913         if (!st->parser) {
1914             st->parser = av_parser_init(st->codec->codec_id);
1915             if(st->need_parsing == 2 && st->parser){
1916                 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1917             }
1918         }
1919     }
1920
1921     for(i=0;i<MAX_STREAMS;i++){
1922         last_dts[i]= AV_NOPTS_VALUE;
1923         duration_sum[i]= INT64_MAX;
1924     }
1925
1926     count = 0;
1927     read_size = 0;
1928     ppktl = &ic->packet_buffer;
1929     for(;;) {
1930         /* check if one codec still needs to be handled */
1931         for(i=0;i<ic->nb_streams;i++) {
1932             st = ic->streams[i];
1933             if (!has_codec_parameters(st->codec))
1934                 break;
1935             /* variable fps and no guess at the real fps */
1936             if(   st->codec->time_base.den >= 101LL*st->codec->time_base.num
1937                && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
1938                 break;
1939             if(st->parser && st->parser->parser->split && !st->codec->extradata)
1940                 break;
1941         }
1942         if (i == ic->nb_streams) {
1943             /* NOTE: if the format has no header, then we need to read
1944                some packets to get most of the streams, so we cannot
1945                stop here */
1946             if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1947                 /* if we found the info for all the codecs, we can stop */
1948                 ret = count;
1949                 break;
1950             }
1951         } else {
1952             /* we did not get all the codec info, but we read too much data */
1953             if (read_size >= MAX_READ_SIZE) {
1954                 ret = count;
1955                 break;
1956             }
1957         }
1958
1959         /* NOTE: a new stream can be added there if no header in file
1960            (AVFMTCTX_NOHEADER) */
1961         ret = av_read_frame_internal(ic, &pkt1);
1962         if (ret < 0) {
1963             /* EOF or error */
1964             ret = -1; /* we could not have all the codec parameters before EOF */
1965             for(i=0;i<ic->nb_streams;i++) {
1966                 st = ic->streams[i];
1967                 if (!has_codec_parameters(st->codec)){
1968                     char buf[256];
1969                     avcodec_string(buf, sizeof(buf), st->codec, 0);
1970                     av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
1971                 } else {
1972                     ret = 0;
1973                 }
1974             }
1975             break;
1976         }
1977
1978         pktl = av_mallocz(sizeof(AVPacketList));
1979         if (!pktl) {
1980             ret = AVERROR_NOMEM;
1981             break;
1982         }
1983
1984         /* add the packet in the buffered packet list */
1985         *ppktl = pktl;
1986         ppktl = &pktl->next;
1987
1988         pkt = &pktl->pkt;
1989         *pkt = pkt1;
1990
1991         /* duplicate the packet */
1992         if (av_dup_packet(pkt) < 0) {
1993                 ret = AVERROR_NOMEM;
1994                 break;
1995         }
1996
1997         read_size += pkt->size;
1998
1999         st = ic->streams[pkt->stream_index];
2000         st->codec_info_duration += pkt->duration;
2001         if (pkt->duration != 0)
2002             st->codec_info_nb_frames++;
2003
2004         {
2005             int index= pkt->stream_index;
2006             int64_t last= last_dts[index];
2007             int64_t duration= pkt->dts - last;
2008
2009             if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2010                 if(duration*duration_count[index]*10/9 < duration_sum[index]){
2011                     duration_sum[index]= duration;
2012                     duration_count[index]=1;
2013                 }else{
2014                     int factor= av_rescale(duration, duration_count[index], duration_sum[index]);
2015                     duration_sum[index] += duration;
2016                     duration_count[index]+= factor;
2017                 }
2018                 if(st->codec_info_nb_frames == 0 && 0)
2019                     st->codec_info_duration += duration;
2020             }
2021             last_dts[pkt->stream_index]= pkt->dts;
2022         }
2023         if(st->parser && st->parser->parser->split && !st->codec->extradata){
2024             int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2025             if(i){
2026                 st->codec->extradata_size= i;
2027                 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2028                 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2029                 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2030             }
2031         }
2032
2033         /* if still no information, we try to open the codec and to
2034            decompress the frame. We try to avoid that in most cases as
2035            it takes longer and uses more memory. For MPEG4, we need to
2036            decompress for Quicktime. */
2037         if (!has_codec_parameters(st->codec) /*&&
2038             (st->codec->codec_id == CODEC_ID_FLV1 ||
2039              st->codec->codec_id == CODEC_ID_H264 ||
2040              st->codec->codec_id == CODEC_ID_H263 ||
2041              st->codec->codec_id == CODEC_ID_H261 ||
2042              st->codec->codec_id == CODEC_ID_VORBIS ||
2043              st->codec->codec_id == CODEC_ID_MJPEG ||
2044              st->codec->codec_id == CODEC_ID_PNG ||
2045              st->codec->codec_id == CODEC_ID_PAM ||
2046              st->codec->codec_id == CODEC_ID_PGM ||
2047              st->codec->codec_id == CODEC_ID_PGMYUV ||
2048              st->codec->codec_id == CODEC_ID_PBM ||
2049              st->codec->codec_id == CODEC_ID_PPM ||
2050              st->codec->codec_id == CODEC_ID_SHORTEN ||
2051              (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2052             try_decode_frame(st, pkt->data, pkt->size);
2053
2054         if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= MAX_STREAM_DURATION) {
2055             break;
2056         }
2057         count++;
2058     }
2059
2060     // close codecs which where opened in try_decode_frame()
2061     for(i=0;i<ic->nb_streams;i++) {
2062         st = ic->streams[i];
2063         if(st->codec->codec)
2064             avcodec_close(st->codec);
2065     }
2066     for(i=0;i<ic->nb_streams;i++) {
2067         st = ic->streams[i];
2068         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2069             if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2070                 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2071
2072             if(duration_count[i] && st->codec->time_base.num*101LL <= st->codec->time_base.den &&
2073                st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den){
2074                 int64_t num, den, error, best_error;
2075
2076                 num= st->time_base.den*duration_count[i];
2077                 den= st->time_base.num*duration_sum[i];
2078
2079                 best_error= INT64_MAX;
2080                 for(j=1; j<60*12; j++){
2081                     error= ABS(1001*12*num - 1001*j*den);
2082                     if(error < best_error){
2083                         best_error= error;
2084                         av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j, 12, INT_MAX);
2085                     }
2086                 }
2087                 for(j=24; j<=30; j+=6){
2088                     error= ABS(1001*12*num - 1000*12*j*den);
2089                     if(error < best_error){
2090                         best_error= error;
2091                         av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j*1000, 1001, INT_MAX);
2092                     }
2093                 }
2094             }
2095
2096             /* set real frame rate info */
2097             /* compute the real frame rate for telecine */
2098             if ((st->codec->codec_id == CODEC_ID_MPEG1VIDEO ||
2099                  st->codec->codec_id == CODEC_ID_MPEG2VIDEO) &&
2100                 st->codec->sub_id == 2) {
2101                 if (st->codec_info_nb_frames >= 20) {
2102                     float coded_frame_rate, est_frame_rate;
2103                     est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
2104                         (double)st->codec_info_duration ;
2105                     coded_frame_rate = 1.0/av_q2d(st->codec->time_base);
2106 #if 0
2107                     printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
2108                            coded_frame_rate, est_frame_rate);
2109 #endif
2110                     /* if we detect that it could be a telecine, we
2111                        signal it. It would be better to do it at a
2112                        higher level as it can change in a film */
2113                     if (coded_frame_rate >= 24.97 &&
2114                         (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
2115                         st->r_frame_rate = (AVRational){24000, 1001};
2116                     }
2117                 }
2118             }
2119             /* if no real frame rate, use the codec one */
2120             if (!st->r_frame_rate.num){
2121                 st->r_frame_rate.num = st->codec->time_base.den;
2122                 st->r_frame_rate.den = st->codec->time_base.num;
2123             }
2124         }
2125     }
2126
2127     av_estimate_timings(ic);
2128 #if 0
2129     /* correct DTS for b frame streams with no timestamps */
2130     for(i=0;i<ic->nb_streams;i++) {
2131         st = ic->streams[i];
2132         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2133             if(b-frames){
2134                 ppktl = &ic->packet_buffer;
2135                 while(ppkt1){
2136                     if(ppkt1->stream_index != i)
2137                         continue;
2138                     if(ppkt1->pkt->dts < 0)
2139                         break;
2140                     if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2141                         break;
2142                     ppkt1->pkt->dts -= delta;
2143                     ppkt1= ppkt1->next;
2144                 }
2145                 if(ppkt1)
2146                     continue;
2147                 st->cur_dts -= delta;
2148             }
2149         }
2150     }
2151 #endif
2152     return ret;
2153 }
2154
2155 /*******************************************************/
2156
2157 /**
2158  * start playing a network based stream (e.g. RTSP stream) at the
2159  * current position
2160  */
2161 int av_read_play(AVFormatContext *s)
2162 {
2163     if (!s->iformat->read_play)
2164         return AVERROR_NOTSUPP;
2165     return s->iformat->read_play(s);
2166 }
2167
2168 /**
2169  * Pause a network based stream (e.g. RTSP stream).
2170  *
2171  * Use av_read_play() to resume it.
2172  */
2173 int av_read_pause(AVFormatContext *s)
2174 {
2175     if (!s->iformat->read_pause)
2176         return AVERROR_NOTSUPP;
2177     return s->iformat->read_pause(s);
2178 }
2179
2180 /**
2181  * Close a media file (but not its codecs).
2182  *
2183  * @param s media file handle
2184  */
2185 void av_close_input_file(AVFormatContext *s)
2186 {
2187     int i, must_open_file;
2188     AVStream *st;
2189
2190     /* free previous packet */
2191     if (s->cur_st && s->cur_st->parser)
2192         av_free_packet(&s->cur_pkt);
2193
2194     if (s->iformat->read_close)
2195         s->iformat->read_close(s);
2196     for(i=0;i<s->nb_streams;i++) {
2197         /* free all data in a stream component */
2198         st = s->streams[i];
2199         if (st->parser) {
2200             av_parser_close(st->parser);
2201         }
2202         av_free(st->index_entries);
2203         av_free(st->codec->extradata);
2204         av_free(st->codec);
2205         av_free(st);
2206     }
2207     flush_packet_queue(s);
2208     must_open_file = 1;
2209     if (s->iformat->flags & AVFMT_NOFILE) {
2210         must_open_file = 0;
2211     }
2212     if (must_open_file) {
2213         url_fclose(&s->pb);
2214     }
2215     av_freep(&s->priv_data);
2216     av_free(s);
2217 }
2218
2219 /**
2220  * Add a new stream to a media file.
2221  *
2222  * Can only be called in the read_header() function. If the flag
2223  * AVFMTCTX_NOHEADER is in the format context, then new streams
2224  * can be added in read_packet too.
2225  *
2226  * @param s media file handle
2227  * @param id file format dependent stream id
2228  */
2229 AVStream *av_new_stream(AVFormatContext *s, int id)
2230 {
2231     AVStream *st;
2232     int i;
2233
2234     if (s->nb_streams >= MAX_STREAMS)
2235         return NULL;
2236
2237     st = av_mallocz(sizeof(AVStream));
2238     if (!st)
2239         return NULL;
2240
2241     st->codec= avcodec_alloc_context();
2242     if (s->iformat) {
2243         /* no default bitrate if decoding */
2244         st->codec->bit_rate = 0;
2245     }
2246     st->index = s->nb_streams;
2247     st->id = id;
2248     st->start_time = AV_NOPTS_VALUE;
2249     st->duration = AV_NOPTS_VALUE;
2250     st->cur_dts = AV_NOPTS_VALUE;
2251
2252     /* default pts settings is MPEG like */
2253     av_set_pts_info(st, 33, 1, 90000);
2254     st->last_IP_pts = AV_NOPTS_VALUE;
2255     for(i=0; i<MAX_REORDER_DELAY+1; i++)
2256         st->pts_buffer[i]= AV_NOPTS_VALUE;
2257
2258     s->streams[s->nb_streams++] = st;
2259     return st;
2260 }
2261
2262 /************************************************************/
2263 /* output media file */
2264
2265 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2266 {
2267     int ret;
2268
2269     if (s->oformat->priv_data_size > 0) {
2270         s->priv_data = av_mallocz(s->oformat->priv_data_size);
2271         if (!s->priv_data)
2272             return AVERROR_NOMEM;
2273     } else
2274         s->priv_data = NULL;
2275
2276     if (s->oformat->set_parameters) {
2277         ret = s->oformat->set_parameters(s, ap);
2278         if (ret < 0)
2279             return ret;
2280     }
2281     return 0;
2282 }
2283
2284 /**
2285  * allocate the stream private data and write the stream header to an
2286  * output media file
2287  *
2288  * @param s media file handle
2289  * @return 0 if OK. AVERROR_xxx if error.
2290  */
2291 int av_write_header(AVFormatContext *s)
2292 {
2293     int ret, i;
2294     AVStream *st;
2295
2296     // some sanity checks
2297     for(i=0;i<s->nb_streams;i++) {
2298         st = s->streams[i];
2299
2300         switch (st->codec->codec_type) {
2301         case CODEC_TYPE_AUDIO:
2302             if(st->codec->sample_rate<=0){
2303                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2304                 return -1;
2305             }
2306             break;
2307         case CODEC_TYPE_VIDEO:
2308             if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2309                 av_log(s, AV_LOG_ERROR, "time base not set\n");
2310                 return -1;
2311             }
2312             if(st->codec->width<=0 || st->codec->height<=0){
2313                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2314                 return -1;
2315             }
2316             break;
2317         }
2318     }
2319
2320     if(s->oformat->write_header){
2321         ret = s->oformat->write_header(s);
2322         if (ret < 0)
2323             return ret;
2324     }
2325
2326     /* init PTS generation */
2327     for(i=0;i<s->nb_streams;i++) {
2328         int64_t den = AV_NOPTS_VALUE;
2329         st = s->streams[i];
2330
2331         switch (st->codec->codec_type) {
2332         case CODEC_TYPE_AUDIO:
2333             den = (int64_t)st->time_base.num * st->codec->sample_rate;
2334             break;
2335         case CODEC_TYPE_VIDEO:
2336             den = (int64_t)st->time_base.num * st->codec->time_base.den;
2337             break;
2338         default:
2339             break;
2340         }
2341         if (den != AV_NOPTS_VALUE) {
2342             if (den <= 0)
2343                 return AVERROR_INVALIDDATA;
2344             av_frac_init(&st->pts, 0, 0, den);
2345         }
2346     }
2347     return 0;
2348 }
2349
2350 //FIXME merge with compute_pkt_fields
2351 static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2352     int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2353     int num, den, frame_size, i;
2354
2355 //    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts:%lld dts:%lld cur_dts:%lld b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2356
2357 /*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2358         return -1;*/
2359
2360     /* duration field */
2361     if (pkt->duration == 0) {
2362         compute_frame_duration(&num, &den, st, NULL, pkt);
2363         if (den && num) {
2364             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2365         }
2366     }
2367
2368     //XXX/FIXME this is a temporary hack until all encoders output pts
2369     if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2370         pkt->dts=
2371 //        pkt->pts= st->cur_dts;
2372         pkt->pts= st->pts.val;
2373     }
2374
2375     //calculate dts from pts
2376     if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2377         st->pts_buffer[0]= pkt->pts;
2378         for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2379             st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2380         for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2381             SWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2382
2383         pkt->dts= st->pts_buffer[0];
2384     }
2385
2386     if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2387         av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2388         return -1;
2389     }
2390     if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2391         av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
2392         return -1;
2393     }
2394
2395 //    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
2396     st->cur_dts= pkt->dts;
2397     st->pts.val= pkt->dts;
2398
2399     /* update pts */
2400     switch (st->codec->codec_type) {
2401     case CODEC_TYPE_AUDIO:
2402         frame_size = get_audio_frame_size(st->codec, pkt->size);
2403
2404         /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2405            but it would be better if we had the real timestamps from the encoder */
2406         if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2407             av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2408         }
2409         break;
2410     case CODEC_TYPE_VIDEO:
2411         av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2412         break;
2413     default:
2414         break;
2415     }
2416     return 0;
2417 }
2418
2419 static void truncate_ts(AVStream *st, AVPacket *pkt){
2420     int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2421
2422 //    if(pkt->dts < 0)
2423 //        pkt->dts= 0;  //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
2424
2425     pkt->pts &= pts_mask;
2426     pkt->dts &= pts_mask;
2427 }
2428
2429 /**
2430  * Write a packet to an output media file.
2431  *
2432  * The packet shall contain one audio or video frame.
2433  *
2434  * @param s media file handle
2435  * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2436  * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2437  */
2438 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2439 {
2440     int ret;
2441
2442     ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2443     if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2444         return ret;
2445
2446     truncate_ts(s->streams[pkt->stream_index], pkt);
2447
2448     ret= s->oformat->write_packet(s, pkt);
2449     if(!ret)
2450         ret= url_ferror(&s->pb);
2451     return ret;
2452 }
2453
2454 /**
2455  * Interleave a packet per DTS in an output media file.
2456  *
2457  * Packets with pkt->destruct == av_destruct_packet will be freed inside this function,
2458  * so they cannot be used after it, note calling av_free_packet() on them is still safe.
2459  *
2460  * @param s media file handle
2461  * @param out the interleaved packet will be output here
2462  * @param in the input packet
2463  * @param flush 1 if no further packets are available as input and all
2464  *              remaining packets should be output
2465  * @return 1 if a packet was output, 0 if no packet could be output,
2466  *         < 0 if an error occured
2467  */
2468 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2469     AVPacketList *pktl, **next_point, *this_pktl;
2470     int stream_count=0;
2471     int streams[MAX_STREAMS];
2472
2473     if(pkt){
2474         AVStream *st= s->streams[ pkt->stream_index];
2475
2476 //        assert(pkt->destruct != av_destruct_packet); //FIXME
2477
2478         this_pktl = av_mallocz(sizeof(AVPacketList));
2479         this_pktl->pkt= *pkt;
2480         if(pkt->destruct == av_destruct_packet)
2481             pkt->destruct= NULL; // non shared -> must keep original from being freed
2482         else
2483             av_dup_packet(&this_pktl->pkt);  //shared -> must dup
2484
2485         next_point = &s->packet_buffer;
2486         while(*next_point){
2487             AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2488             int64_t left=  st2->time_base.num * (int64_t)st ->time_base.den;
2489             int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2490             if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2491                 break;
2492             next_point= &(*next_point)->next;
2493         }
2494         this_pktl->next= *next_point;
2495         *next_point= this_pktl;
2496     }
2497
2498     memset(streams, 0, sizeof(streams));
2499     pktl= s->packet_buffer;
2500     while(pktl){
2501 //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2502         if(streams[ pktl->pkt.stream_index ] == 0)
2503             stream_count++;
2504         streams[ pktl->pkt.stream_index ]++;
2505         pktl= pktl->next;
2506     }
2507
2508     if(s->nb_streams == stream_count || (flush && stream_count)){
2509         pktl= s->packet_buffer;
2510         *out= pktl->pkt;
2511
2512         s->packet_buffer= pktl->next;
2513         av_freep(&pktl);
2514         return 1;
2515     }else{
2516         av_init_packet(out);
2517         return 0;
2518     }
2519 }
2520
2521 /**
2522  * Interleaves a AVPacket correctly so it can be muxed.
2523  * @param out the interleaved packet will be output here
2524  * @param in the input packet
2525  * @param flush 1 if no further packets are available as input and all
2526  *              remaining packets should be output
2527  * @return 1 if a packet was output, 0 if no packet could be output,
2528  *         < 0 if an error occured
2529  */
2530 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2531     if(s->oformat->interleave_packet)
2532         return s->oformat->interleave_packet(s, out, in, flush);
2533     else
2534         return av_interleave_packet_per_dts(s, out, in, flush);
2535 }
2536
2537 /**
2538  * Writes a packet to an output media file ensuring correct interleaving.
2539  *
2540  * The packet must contain one audio or video frame.
2541  * If the packets are already correctly interleaved the application should
2542  * call av_write_frame() instead as its slightly faster, its also important
2543  * to keep in mind that completly non interleaved input will need huge amounts
2544  * of memory to interleave with this, so its prefereable to interleave at the
2545  * demuxer level
2546  *
2547  * @param s media file handle
2548  * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2549  * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2550  */
2551 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2552     AVStream *st= s->streams[ pkt->stream_index];
2553
2554     //FIXME/XXX/HACK drop zero sized packets
2555     if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2556         return 0;
2557
2558 //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %Ld %Ld\n", pkt->size, pkt->dts, pkt->pts);
2559     if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2560         return -1;
2561
2562     if(pkt->dts == AV_NOPTS_VALUE)
2563         return -1;
2564
2565     for(;;){
2566         AVPacket opkt;
2567         int ret= av_interleave_packet(s, &opkt, pkt, 0);
2568         if(ret<=0) //FIXME cleanup needed for ret<0 ?
2569             return ret;
2570
2571         truncate_ts(s->streams[opkt.stream_index], &opkt);
2572         ret= s->oformat->write_packet(s, &opkt);
2573
2574         av_free_packet(&opkt);
2575         pkt= NULL;
2576
2577         if(ret<0)
2578             return ret;
2579         if(url_ferror(&s->pb))
2580             return url_ferror(&s->pb);
2581     }
2582 }
2583
2584 /**
2585  * @brief Write the stream trailer to an output media file and
2586  *        free the file private data.
2587  *
2588  * @param s media file handle
2589  * @return 0 if OK. AVERROR_xxx if error.
2590  */
2591 int av_write_trailer(AVFormatContext *s)
2592 {
2593     int ret, i;
2594
2595     for(;;){
2596         AVPacket pkt;
2597         ret= av_interleave_packet(s, &pkt, NULL, 1);
2598         if(ret<0) //FIXME cleanup needed for ret<0 ?
2599             goto fail;
2600         if(!ret)
2601             break;
2602
2603         truncate_ts(s->streams[pkt.stream_index], &pkt);
2604         ret= s->oformat->write_packet(s, &pkt);
2605
2606         av_free_packet(&pkt);
2607
2608         if(ret<0)
2609             goto fail;
2610         if(url_ferror(&s->pb))
2611             goto fail;
2612     }
2613
2614     if(s->oformat->write_trailer)
2615         ret = s->oformat->write_trailer(s);
2616 fail:
2617     if(ret == 0)
2618        ret=url_ferror(&s->pb);
2619     for(i=0;i<s->nb_streams;i++)
2620         av_freep(&s->streams[i]->priv_data);
2621     av_freep(&s->priv_data);
2622     return ret;
2623 }
2624
2625 /* "user interface" functions */
2626
2627 void dump_format(AVFormatContext *ic,
2628                  int index,
2629                  const char *url,
2630                  int is_output)
2631 {
2632     int i, flags;
2633     char buf[256];
2634
2635     av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2636             is_output ? "Output" : "Input",
2637             index,
2638             is_output ? ic->oformat->name : ic->iformat->name,
2639             is_output ? "to" : "from", url);
2640     if (!is_output) {
2641         av_log(NULL, AV_LOG_INFO, "  Duration: ");
2642         if (ic->duration != AV_NOPTS_VALUE) {
2643             int hours, mins, secs, us;
2644             secs = ic->duration / AV_TIME_BASE;
2645             us = ic->duration % AV_TIME_BASE;
2646             mins = secs / 60;
2647             secs %= 60;
2648             hours = mins / 60;
2649             mins %= 60;
2650             av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
2651                    (10 * us) / AV_TIME_BASE);
2652         } else {
2653             av_log(NULL, AV_LOG_INFO, "N/A");
2654         }
2655         if (ic->start_time != AV_NOPTS_VALUE) {
2656             int secs, us;
2657             av_log(NULL, AV_LOG_INFO, ", start: ");
2658             secs = ic->start_time / AV_TIME_BASE;
2659             us = ic->start_time % AV_TIME_BASE;
2660             av_log(NULL, AV_LOG_INFO, "%d.%06d",
2661                    secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2662         }
2663         av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2664         if (ic->bit_rate) {
2665             av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2666         } else {
2667             av_log(NULL, AV_LOG_INFO, "N/A");
2668         }
2669         av_log(NULL, AV_LOG_INFO, "\n");
2670     }
2671     for(i=0;i<ic->nb_streams;i++) {
2672         AVStream *st = ic->streams[i];
2673         int g= ff_gcd(st->time_base.num, st->time_base.den);
2674         avcodec_string(buf, sizeof(buf), st->codec, is_output);
2675         av_log(NULL, AV_LOG_INFO, "  Stream #%d.%d", index, i);
2676         /* the pid is an important information, so we display it */
2677         /* XXX: add a generic system */
2678         if (is_output)
2679             flags = ic->oformat->flags;
2680         else
2681             flags = ic->iformat->flags;
2682         if (flags & AVFMT_SHOW_IDS) {
2683             av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2684         }
2685         if (strlen(st->language) > 0) {
2686             av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2687         }
2688         av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2689         av_log(NULL, AV_LOG_INFO, ": %s", buf);
2690         if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2691             if(st->r_frame_rate.den && st->r_frame_rate.num)
2692                 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
2693 /*            else if(st->time_base.den && st->time_base.num)
2694                 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
2695             else
2696                 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
2697         }
2698         av_log(NULL, AV_LOG_INFO, "\n");
2699     }
2700 }
2701
2702 typedef struct {
2703     const char *abv;
2704     int width, height;
2705     int frame_rate, frame_rate_base;
2706 } AbvEntry;
2707
2708 static AbvEntry frame_abvs[] = {
2709     { "ntsc",      720, 480, 30000, 1001 },
2710     { "pal",       720, 576,    25,    1 },
2711     { "qntsc",     352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2712     { "qpal",      352, 288,    25,    1 }, /* VCD compliant pal */
2713     { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
2714     { "spal",      768, 576,    25,    1 }, /* square pixel pal */
2715     { "film",      352, 240,    24,    1 },
2716     { "ntsc-film", 352, 240, 24000, 1001 },
2717     { "sqcif",     128,  96,     0,    0 },
2718     { "qcif",      176, 144,     0,    0 },
2719     { "cif",       352, 288,     0,    0 },
2720     { "4cif",      704, 576,     0,    0 },
2721 };
2722
2723 /**
2724  * parses width and height out of string str.
2725  */
2726 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2727 {
2728     int i;
2729     int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2730     const char *p;
2731     int frame_width = 0, frame_height = 0;
2732
2733     for(i=0;i<n;i++) {
2734         if (!strcmp(frame_abvs[i].abv, str)) {
2735             frame_width = frame_abvs[i].width;
2736             frame_height = frame_abvs[i].height;
2737             break;
2738         }
2739     }
2740     if (i == n) {
2741         p = str;
2742         frame_width = strtol(p, (char **)&p, 10);
2743         if (*p)
2744             p++;
2745         frame_height = strtol(p, (char **)&p, 10);
2746     }
2747     if (frame_width <= 0 || frame_height <= 0)
2748         return -1;
2749     *width_ptr = frame_width;
2750     *height_ptr = frame_height;
2751     return 0;
2752 }
2753
2754 /**
2755  * Converts frame rate from string to a fraction.
2756  *
2757  * First we try to get an exact integer or fractional frame rate.
2758  * If this fails we convert the frame rate to a double and return
2759  * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
2760  */
2761 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2762 {
2763     int i;
2764     char* cp;
2765
2766     /* First, we check our abbreviation table */
2767     for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2768          if (!strcmp(frame_abvs[i].abv, arg)) {
2769              *frame_rate = frame_abvs[i].frame_rate;
2770              *frame_rate_base = frame_abvs[i].frame_rate_base;
2771              return 0;
2772          }
2773
2774     /* Then, we try to parse it as fraction */
2775     cp = strchr(arg, '/');
2776     if (!cp)
2777         cp = strchr(arg, ':');
2778     if (cp) {
2779         char* cpp;
2780         *frame_rate = strtol(arg, &cpp, 10);
2781         if (cpp != arg || cpp == cp)
2782             *frame_rate_base = strtol(cp+1, &cpp, 10);
2783         else
2784            *frame_rate = 0;
2785     }
2786     else {
2787         /* Finally we give up and parse it as double */
2788         AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
2789         *frame_rate_base = time_base.den;
2790         *frame_rate = time_base.num;
2791     }
2792     if (!*frame_rate || !*frame_rate_base)
2793         return -1;
2794     else
2795         return 0;
2796 }
2797
2798 /**
2799  * Converts date string to number of seconds since Jan 1st, 1970.
2800  *
2801  * @code
2802  * Syntax:
2803  * - If not a duration:
2804  *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2805  * Time is localtime unless Z is suffixed to the end. In this case GMT
2806  * Return the date in micro seconds since 1970
2807  *
2808  * - If a duration:
2809  *  HH[:MM[:SS[.m...]]]
2810  *  S+[.m...]
2811  * @endcode
2812  */
2813 #ifndef CONFIG_WINCE
2814 int64_t parse_date(const char *datestr, int duration)
2815 {
2816     const char *p;
2817     int64_t t;
2818     struct tm dt;
2819     int i;
2820     static const char *date_fmt[] = {
2821         "%Y-%m-%d",
2822         "%Y%m%d",
2823     };
2824     static const char *time_fmt[] = {
2825         "%H:%M:%S",
2826         "%H%M%S",
2827     };
2828     const char *q;
2829     int is_utc, len;
2830     char lastch;
2831     int negative = 0;
2832
2833 #undef time
2834     time_t now = time(0);
2835
2836     len = strlen(datestr);
2837     if (len > 0)
2838         lastch = datestr[len - 1];
2839     else
2840         lastch = '\0';
2841     is_utc = (lastch == 'z' || lastch == 'Z');
2842
2843     memset(&dt, 0, sizeof(dt));
2844
2845     p = datestr;
2846     q = NULL;
2847     if (!duration) {
2848         for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2849             q = small_strptime(p, date_fmt[i], &dt);
2850             if (q) {
2851                 break;
2852             }
2853         }
2854
2855         if (!q) {
2856             if (is_utc) {
2857                 dt = *gmtime(&now);
2858             } else {
2859                 dt = *localtime(&now);
2860             }
2861             dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2862         } else {
2863             p = q;
2864         }
2865
2866         if (*p == 'T' || *p == 't' || *p == ' ')
2867             p++;
2868
2869         for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2870             q = small_strptime(p, time_fmt[i], &dt);
2871             if (q) {
2872                 break;
2873             }
2874         }
2875     } else {
2876         if (p[0] == '-') {
2877             negative = 1;
2878             ++p;
2879         }
2880         q = small_strptime(p, time_fmt[0], &dt);
2881         if (!q) {
2882             dt.tm_sec = strtol(p, (char **)&q, 10);
2883             dt.tm_min = 0;
2884             dt.tm_hour = 0;
2885         }
2886     }
2887
2888     /* Now we have all the fields that we can get */
2889     if (!q) {
2890         if (duration)
2891             return 0;
2892         else
2893             return now * int64_t_C(1000000);
2894     }
2895
2896     if (duration) {
2897         t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2898     } else {
2899         dt.tm_isdst = -1;       /* unknown */
2900         if (is_utc) {
2901             t = mktimegm(&dt);
2902         } else {
2903             t = mktime(&dt);
2904         }
2905     }
2906
2907     t *= 1000000;
2908
2909     if (*q == '.') {
2910         int val, n;
2911         q++;
2912         for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2913             if (!isdigit(*q))
2914                 break;
2915             val += n * (*q - '0');
2916         }
2917         t += val;
2918     }
2919     return negative ? -t : t;
2920 }
2921 #endif /* CONFIG_WINCE */
2922
2923 /**
2924  * Attempts to find a specific tag in a URL.
2925  *
2926  * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
2927  * Return 1 if found.
2928  */
2929 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2930 {
2931     const char *p;
2932     char tag[128], *q;
2933
2934     p = info;
2935     if (*p == '?')
2936         p++;
2937     for(;;) {
2938         q = tag;
2939         while (*p != '\0' && *p != '=' && *p != '&') {
2940             if ((q - tag) < sizeof(tag) - 1)
2941                 *q++ = *p;
2942             p++;
2943         }
2944         *q = '\0';
2945         q = arg;
2946         if (*p == '=') {
2947             p++;
2948             while (*p != '&' && *p != '\0') {
2949                 if ((q - arg) < arg_size - 1) {
2950                     if (*p == '+')
2951                         *q++ = ' ';
2952                     else
2953                         *q++ = *p;
2954                 }
2955                 p++;
2956             }
2957             *q = '\0';
2958         }
2959         if (!strcmp(tag, tag1))
2960             return 1;
2961         if (*p != '&')
2962             break;
2963         p++;
2964     }
2965     return 0;
2966 }
2967
2968 /**
2969  * Returns in 'buf' the path with '%d' replaced by number.
2970
2971  * Also handles the '%0nd' format where 'n' is the total number
2972  * of digits and '%%'.
2973  *
2974  * @param buf destination buffer
2975  * @param buf_size destination buffer size
2976  * @param path numbered sequence string
2977  * @number frame number
2978  * @return 0 if OK, -1 if format error.
2979  */
2980 int av_get_frame_filename(char *buf, int buf_size,
2981                           const char *path, int number)
2982 {
2983     const char *p;
2984     char *q, buf1[20], c;
2985     int nd, len, percentd_found;
2986
2987     q = buf;
2988     p = path;
2989     percentd_found = 0;
2990     for(;;) {
2991         c = *p++;
2992         if (c == '\0')
2993             break;
2994         if (c == '%') {
2995             do {
2996                 nd = 0;
2997                 while (isdigit(*p)) {
2998                     nd = nd * 10 + *p++ - '0';
2999                 }
3000                 c = *p++;
3001             } while (isdigit(c));
3002
3003             switch(c) {
3004             case '%':
3005                 goto addchar;
3006             case 'd':
3007                 if (percentd_found)
3008                     goto fail;
3009                 percentd_found = 1;
3010                 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3011                 len = strlen(buf1);
3012                 if ((q - buf + len) > buf_size - 1)
3013                     goto fail;
3014                 memcpy(q, buf1, len);
3015                 q += len;
3016                 break;
3017             default:
3018                 goto fail;
3019             }
3020         } else {
3021         addchar:
3022             if ((q - buf) < buf_size - 1)
3023                 *q++ = c;
3024         }
3025     }
3026     if (!percentd_found)
3027         goto fail;
3028     *q = '\0';
3029     return 0;
3030  fail:
3031     *q = '\0';
3032     return -1;
3033 }
3034
3035 /**
3036  * Print  nice hexa dump of a buffer
3037  * @param f stream for output
3038  * @param buf buffer
3039  * @param size buffer size
3040  */
3041 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3042 {
3043     int len, i, j, c;
3044
3045     for(i=0;i<size;i+=16) {
3046         len = size - i;
3047         if (len > 16)
3048             len = 16;
3049         fprintf(f, "%08x ", i);
3050         for(j=0;j<16;j++) {
3051             if (j < len)
3052                 fprintf(f, " %02x", buf[i+j]);
3053             else
3054                 fprintf(f, "   ");
3055         }
3056         fprintf(f, " ");
3057         for(j=0;j<len;j++) {
3058             c = buf[i+j];
3059             if (c < ' ' || c > '~')
3060                 c = '.';
3061             fprintf(f, "%c", c);
3062         }
3063         fprintf(f, "\n");
3064     }
3065 }
3066
3067 /**
3068  * Print on 'f' a nice dump of a packet
3069  * @param f stream for output
3070  * @param pkt packet to dump
3071  * @param dump_payload true if the payload must be displayed too
3072  */
3073  //FIXME needs to know the time_base
3074 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3075 {
3076     fprintf(f, "stream #%d:\n", pkt->stream_index);
3077     fprintf(f, "  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3078     fprintf(f, "  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3079     /* DTS is _always_ valid after av_read_frame() */
3080     fprintf(f, "  dts=");
3081     if (pkt->dts == AV_NOPTS_VALUE)
3082         fprintf(f, "N/A");
3083     else
3084         fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
3085     /* PTS may be not known if B frames are present */
3086     fprintf(f, "  pts=");
3087     if (pkt->pts == AV_NOPTS_VALUE)
3088         fprintf(f, "N/A");
3089     else
3090         fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
3091     fprintf(f, "\n");
3092     fprintf(f, "  size=%d\n", pkt->size);
3093     if (dump_payload)
3094         av_hex_dump(f, pkt->data, pkt->size);
3095 }
3096
3097 void url_split(char *proto, int proto_size,
3098                char *authorization, int authorization_size,
3099                char *hostname, int hostname_size,
3100                int *port_ptr,
3101                char *path, int path_size,
3102                const char *url)
3103 {
3104     const char *p;
3105     char *q;
3106     int port;
3107
3108     port = -1;
3109
3110     p = url;
3111     q = proto;
3112     while (*p != ':' && *p != '\0') {
3113         if ((q - proto) < proto_size - 1)
3114             *q++ = *p;
3115         p++;
3116     }
3117     if (proto_size > 0)
3118         *q = '\0';
3119     if (authorization_size > 0)
3120         authorization[0] = '\0';
3121     if (*p == '\0') {
3122         if (proto_size > 0)
3123             proto[0] = '\0';
3124         if (hostname_size > 0)
3125             hostname[0] = '\0';
3126         p = url;
3127     } else {
3128         char *at,*slash; // PETR: position of '@' character and '/' character
3129
3130         p++;
3131         if (*p == '/')
3132             p++;
3133         if (*p == '/')
3134             p++;
3135         at = strchr(p,'@'); // PETR: get the position of '@'
3136         slash = strchr(p,'/');  // PETR: get position of '/' - end of hostname
3137         if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
3138
3139         q = at ? authorization : hostname;  // PETR: if '@' exists starting with auth.
3140
3141          while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
3142             if (*p == '@') {    // PETR: passed '@'
3143               if (authorization_size > 0)
3144                   *q = '\0';
3145               q = hostname;
3146               at = NULL;
3147             } else if (!at) {   // PETR: hostname
3148               if ((q - hostname) < hostname_size - 1)
3149                   *q++ = *p;
3150             } else {
3151               if ((q - authorization) < authorization_size - 1)
3152                 *q++ = *p;
3153             }
3154             p++;
3155         }
3156         if (hostname_size > 0)
3157             *q = '\0';
3158         if (*p == ':') {
3159             p++;
3160             port = strtoul(p, (char **)&p, 10);
3161         }
3162     }
3163     if (port_ptr)
3164         *port_ptr = port;
3165     pstrcpy(path, path_size, p);
3166 }
3167
3168 /**
3169  * Set the pts for a given stream.
3170  *
3171  * @param s stream
3172  * @param pts_wrap_bits number of bits effectively used by the pts
3173  *        (used for wrap control, 33 is the value for MPEG)
3174  * @param pts_num numerator to convert to seconds (MPEG: 1)
3175  * @param pts_den denominator to convert to seconds (MPEG: 90000)
3176  */
3177 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3178                      int pts_num, int pts_den)
3179 {
3180     s->pts_wrap_bits = pts_wrap_bits;
3181     s->time_base.num = pts_num;
3182     s->time_base.den = pts_den;
3183 }
3184
3185 /* fraction handling */
3186
3187 /**
3188  * f = val + (num / den) + 0.5.
3189  *
3190  * 'num' is normalized so that it is such as 0 <= num < den.
3191  *
3192  * @param f fractional number
3193  * @param val integer value
3194  * @param num must be >= 0
3195  * @param den must be >= 1
3196  */
3197 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
3198 {
3199     num += (den >> 1);
3200     if (num >= den) {
3201         val += num / den;
3202         num = num % den;
3203     }
3204     f->val = val;
3205     f->num = num;
3206     f->den = den;
3207 }
3208
3209 /**
3210  * Set f to (val + 0.5).
3211  */
3212 static void av_frac_set(AVFrac *f, int64_t val)
3213 {
3214     f->val = val;
3215     f->num = f->den >> 1;
3216 }
3217
3218 /**
3219  * Fractionnal addition to f: f = f + (incr / f->den).
3220  *
3221  * @param f fractional number
3222  * @param incr increment, can be positive or negative
3223  */
3224 static void av_frac_add(AVFrac *f, int64_t incr)
3225 {
3226     int64_t num, den;
3227
3228     num = f->num + incr;
3229     den = f->den;
3230     if (num < 0) {
3231         f->val += num / den;
3232         num = num % den;
3233         if (num < 0) {
3234             num += den;
3235             f->val--;
3236         }
3237     } else if (num >= den) {
3238         f->val += num / den;
3239         num = num % den;
3240     }
3241     f->num = num;
3242 }
3243
3244 /**
3245  * register a new image format
3246  * @param img_fmt Image format descriptor
3247  */
3248 void av_register_image_format(AVImageFormat *img_fmt)
3249 {
3250     AVImageFormat **p;
3251
3252     p = &first_image_format;
3253     while (*p != NULL) p = &(*p)->next;
3254     *p = img_fmt;
3255     img_fmt->next = NULL;
3256 }
3257
3258 /**
3259  * Guesses image format based on data in the image.
3260  */
3261 AVImageFormat *av_probe_image_format(AVProbeData *pd)
3262 {
3263     AVImageFormat *fmt1, *fmt;
3264     int score, score_max;
3265
3266     fmt = NULL;
3267     score_max = 0;
3268     for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3269         if (fmt1->img_probe) {
3270             score = fmt1->img_probe(pd);
3271             if (score > score_max) {
3272                 score_max = score;
3273                 fmt = fmt1;
3274             }
3275         }
3276     }
3277     return fmt;
3278 }
3279
3280 /**
3281  * Guesses image format based on file name extensions.
3282  */
3283 AVImageFormat *guess_image_format(const char *filename)
3284 {
3285     AVImageFormat *fmt1;
3286
3287     for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3288         if (fmt1->extensions && match_ext(filename, fmt1->extensions))
3289             return fmt1;
3290     }
3291     return NULL;
3292 }
3293
3294 /**
3295  * Read an image from a stream.
3296  * @param gb byte stream containing the image
3297  * @param fmt image format, NULL if probing is required
3298  */
3299 int av_read_image(ByteIOContext *pb, const char *filename,
3300                   AVImageFormat *fmt,
3301                   int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
3302 {
3303     uint8_t buf[PROBE_BUF_MIN];
3304     AVProbeData probe_data, *pd = &probe_data;
3305     offset_t pos;
3306     int ret;
3307
3308     if (!fmt) {
3309         pd->filename = filename;
3310         pd->buf = buf;
3311         pos = url_ftell(pb);
3312         pd->buf_size = get_buffer(pb, buf, PROBE_BUF_MIN);
3313         url_fseek(pb, pos, SEEK_SET);
3314         fmt = av_probe_image_format(pd);
3315     }
3316     if (!fmt)
3317         return AVERROR_NOFMT;
3318     ret = fmt->img_read(pb, alloc_cb, opaque);
3319     return ret;
3320 }
3321
3322 /**
3323  * Write an image to a stream.
3324  * @param pb byte stream for the image output
3325  * @param fmt image format
3326  * @param img image data and informations
3327  */
3328 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
3329 {
3330     return fmt->img_write(pb, img);
3331 }
3332