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