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