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