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