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