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