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