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