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