]> git.sesse.net Git - ffmpeg/blob - libavformat/utils.c
avformat: Remove deprecated old open callbacks
[ffmpeg] / libavformat / utils.c
1 /*
2  * various utility functions for use within FFmpeg
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <stdint.h>
23
24 #include "config.h"
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/internal.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/parseutils.h"
33 #include "libavutil/pixfmt.h"
34 #include "libavutil/thread.h"
35 #include "libavutil/time.h"
36 #include "libavutil/timestamp.h"
37
38 #include "libavcodec/bytestream.h"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/packet_internal.h"
41 #include "libavcodec/raw.h"
42
43 #include "avformat.h"
44 #include "avio_internal.h"
45 #include "id3v2.h"
46 #include "internal.h"
47 #if CONFIG_NETWORK
48 #include "network.h"
49 #endif
50 #include "url.h"
51
52 #include "libavutil/ffversion.h"
53 const char av_format_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
54
55 static AVMutex avformat_mutex = AV_MUTEX_INITIALIZER;
56
57 /**
58  * @file
59  * various utility functions for use within FFmpeg
60  */
61
62 unsigned avformat_version(void)
63 {
64     av_assert0(LIBAVFORMAT_VERSION_MICRO >= 100);
65     return LIBAVFORMAT_VERSION_INT;
66 }
67
68 const char *avformat_configuration(void)
69 {
70     return FFMPEG_CONFIGURATION;
71 }
72
73 const char *avformat_license(void)
74 {
75 #define LICENSE_PREFIX "libavformat license: "
76     return &LICENSE_PREFIX FFMPEG_LICENSE[sizeof(LICENSE_PREFIX) - 1];
77 }
78
79 int ff_lock_avformat(void)
80 {
81     return ff_mutex_lock(&avformat_mutex) ? -1 : 0;
82 }
83
84 int ff_unlock_avformat(void)
85 {
86     return ff_mutex_unlock(&avformat_mutex) ? -1 : 0;
87 }
88
89 #define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
90
91 static int is_relative(int64_t ts) {
92     return ts > (RELATIVE_TS_BASE - (1LL<<48));
93 }
94
95 /**
96  * Wrap a given time stamp, if there is an indication for an overflow
97  *
98  * @param st stream
99  * @param timestamp the time stamp to wrap
100  * @return resulting time stamp
101  */
102 static int64_t wrap_timestamp(const AVStream *st, int64_t timestamp)
103 {
104     if (st->internal->pts_wrap_behavior != AV_PTS_WRAP_IGNORE && st->pts_wrap_bits < 64 &&
105         st->internal->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
106         if (st->internal->pts_wrap_behavior == AV_PTS_WRAP_ADD_OFFSET &&
107             timestamp < st->internal->pts_wrap_reference)
108             return timestamp + (1ULL << st->pts_wrap_bits);
109         else if (st->internal->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
110             timestamp >= st->internal->pts_wrap_reference)
111             return timestamp - (1ULL << st->pts_wrap_bits);
112     }
113     return timestamp;
114 }
115
116 #if FF_API_FORMAT_GET_SET
117 MAKE_ACCESSORS(AVStream, stream, AVRational, r_frame_rate)
118 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
119 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
120 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
121 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, data_codec)
122 MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
123 MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
124 MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
125 #endif
126
127 int64_t av_stream_get_end_pts(const AVStream *st)
128 {
129     if (st->internal->priv_pts) {
130         return st->internal->priv_pts->val;
131     } else
132         return AV_NOPTS_VALUE;
133 }
134
135 struct AVCodecParserContext *av_stream_get_parser(const AVStream *st)
136 {
137     return st->parser;
138 }
139
140 void av_format_inject_global_side_data(AVFormatContext *s)
141 {
142     int i;
143     s->internal->inject_global_side_data = 1;
144     for (i = 0; i < s->nb_streams; i++) {
145         AVStream *st = s->streams[i];
146         st->internal->inject_global_side_data = 1;
147     }
148 }
149
150 int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
151 {
152     av_assert0(!dst->codec_whitelist &&
153                !dst->format_whitelist &&
154                !dst->protocol_whitelist &&
155                !dst->protocol_blacklist);
156     dst-> codec_whitelist = av_strdup(src->codec_whitelist);
157     dst->format_whitelist = av_strdup(src->format_whitelist);
158     dst->protocol_whitelist = av_strdup(src->protocol_whitelist);
159     dst->protocol_blacklist = av_strdup(src->protocol_blacklist);
160     if (   (src-> codec_whitelist && !dst-> codec_whitelist)
161         || (src->  format_whitelist && !dst->  format_whitelist)
162         || (src->protocol_whitelist && !dst->protocol_whitelist)
163         || (src->protocol_blacklist && !dst->protocol_blacklist)) {
164         av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
165         return AVERROR(ENOMEM);
166     }
167     return 0;
168 }
169
170 static const AVCodec *find_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
171 {
172 #if FF_API_LAVF_AVCTX
173 FF_DISABLE_DEPRECATION_WARNINGS
174     if (st->codec->codec)
175         return st->codec->codec;
176 FF_ENABLE_DEPRECATION_WARNINGS
177 #endif
178
179     switch (st->codecpar->codec_type) {
180     case AVMEDIA_TYPE_VIDEO:
181         if (s->video_codec)    return s->video_codec;
182         break;
183     case AVMEDIA_TYPE_AUDIO:
184         if (s->audio_codec)    return s->audio_codec;
185         break;
186     case AVMEDIA_TYPE_SUBTITLE:
187         if (s->subtitle_codec) return s->subtitle_codec;
188         break;
189     }
190
191     return avcodec_find_decoder(codec_id);
192 }
193
194 static const AVCodec *find_probe_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
195 {
196     const AVCodec *codec;
197
198 #if CONFIG_H264_DECODER
199     /* Other parts of the code assume this decoder to be used for h264,
200      * so force it if possible. */
201     if (codec_id == AV_CODEC_ID_H264)
202         return avcodec_find_decoder_by_name("h264");
203 #endif
204
205     codec = find_decoder(s, st, codec_id);
206     if (!codec)
207         return NULL;
208
209     if (codec->capabilities & AV_CODEC_CAP_AVOID_PROBING) {
210         const AVCodec *probe_codec = NULL;
211         void *iter = NULL;
212         while ((probe_codec = av_codec_iterate(&iter))) {
213             if (probe_codec->id == codec->id &&
214                     av_codec_is_decoder(probe_codec) &&
215                     !(probe_codec->capabilities & (AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_EXPERIMENTAL))) {
216                 return probe_codec;
217             }
218         }
219     }
220
221     return codec;
222 }
223
224 #if FF_API_FORMAT_GET_SET
225 int av_format_get_probe_score(const AVFormatContext *s)
226 {
227     return s->probe_score;
228 }
229 #endif
230
231 /* an arbitrarily chosen "sane" max packet size -- 50M */
232 #define SANE_CHUNK_SIZE (50000000)
233
234 int ffio_limit(AVIOContext *s, int size)
235 {
236     if (s->maxsize>= 0) {
237         int64_t pos = avio_tell(s);
238         int64_t remaining= s->maxsize - pos;
239         if (remaining < size) {
240             int64_t newsize = avio_size(s);
241             if (!s->maxsize || s->maxsize<newsize)
242                 s->maxsize = newsize - !newsize;
243             if (pos > s->maxsize && s->maxsize >= 0)
244                 s->maxsize = AVERROR(EIO);
245             if (s->maxsize >= 0)
246                 remaining = s->maxsize - pos;
247         }
248
249         if (s->maxsize >= 0 && remaining < size && size > 1) {
250             av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG,
251                    "Truncating packet of size %d to %"PRId64"\n",
252                    size, remaining + !remaining);
253             size = remaining + !remaining;
254         }
255     }
256     return size;
257 }
258
259 /* Read the data in sane-sized chunks and append to pkt.
260  * Return the number of bytes read or an error. */
261 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
262 {
263     int orig_size      = pkt->size;
264     int ret;
265
266     do {
267         int prev_size = pkt->size;
268         int read_size;
269
270         /* When the caller requests a lot of data, limit it to the amount
271          * left in file or SANE_CHUNK_SIZE when it is not known. */
272         read_size = size;
273         if (read_size > SANE_CHUNK_SIZE/10) {
274             read_size = ffio_limit(s, read_size);
275             // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
276             if (s->maxsize < 0)
277                 read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
278         }
279
280         ret = av_grow_packet(pkt, read_size);
281         if (ret < 0)
282             break;
283
284         ret = avio_read(s, pkt->data + prev_size, read_size);
285         if (ret != read_size) {
286             av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
287             break;
288         }
289
290         size -= read_size;
291     } while (size > 0);
292     if (size > 0)
293         pkt->flags |= AV_PKT_FLAG_CORRUPT;
294
295     if (!pkt->size)
296         av_packet_unref(pkt);
297     return pkt->size > orig_size ? pkt->size - orig_size : ret;
298 }
299
300 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
301 {
302 #if FF_API_INIT_PACKET
303 FF_DISABLE_DEPRECATION_WARNINGS
304     av_init_packet(pkt);
305     pkt->data = NULL;
306     pkt->size = 0;
307 FF_ENABLE_DEPRECATION_WARNINGS
308 #else
309     av_packet_unref(pkt);
310 #endif
311     pkt->pos  = avio_tell(s);
312
313     return append_packet_chunked(s, pkt, size);
314 }
315
316 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
317 {
318     if (!pkt->size)
319         return av_get_packet(s, pkt, size);
320     return append_packet_chunked(s, pkt, size);
321 }
322
323 int av_filename_number_test(const char *filename)
324 {
325     char buf[1024];
326     return filename &&
327            (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
328 }
329
330 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
331                                      AVProbeData *pd)
332 {
333     static const struct {
334         const char *name;
335         enum AVCodecID id;
336         enum AVMediaType type;
337     } fmt_id_type[] = {
338         { "aac",       AV_CODEC_ID_AAC,        AVMEDIA_TYPE_AUDIO },
339         { "ac3",       AV_CODEC_ID_AC3,        AVMEDIA_TYPE_AUDIO },
340         { "aptx",      AV_CODEC_ID_APTX,       AVMEDIA_TYPE_AUDIO },
341         { "dts",       AV_CODEC_ID_DTS,        AVMEDIA_TYPE_AUDIO },
342         { "dvbsub",    AV_CODEC_ID_DVB_SUBTITLE,AVMEDIA_TYPE_SUBTITLE },
343         { "dvbtxt",    AV_CODEC_ID_DVB_TELETEXT,AVMEDIA_TYPE_SUBTITLE },
344         { "eac3",      AV_CODEC_ID_EAC3,       AVMEDIA_TYPE_AUDIO },
345         { "h264",      AV_CODEC_ID_H264,       AVMEDIA_TYPE_VIDEO },
346         { "hevc",      AV_CODEC_ID_HEVC,       AVMEDIA_TYPE_VIDEO },
347         { "loas",      AV_CODEC_ID_AAC_LATM,   AVMEDIA_TYPE_AUDIO },
348         { "m4v",       AV_CODEC_ID_MPEG4,      AVMEDIA_TYPE_VIDEO },
349         { "mjpeg_2000",AV_CODEC_ID_JPEG2000,   AVMEDIA_TYPE_VIDEO },
350         { "mp3",       AV_CODEC_ID_MP3,        AVMEDIA_TYPE_AUDIO },
351         { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
352         { "truehd",    AV_CODEC_ID_TRUEHD,     AVMEDIA_TYPE_AUDIO },
353         { 0 }
354     };
355     int score;
356     const AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
357
358     if (fmt) {
359         int i;
360         av_log(s, AV_LOG_DEBUG,
361                "Probe with size=%d, packets=%d detected %s with score=%d\n",
362                pd->buf_size, s->max_probe_packets - st->probe_packets,
363                fmt->name, score);
364         for (i = 0; fmt_id_type[i].name; i++) {
365             if (!strcmp(fmt->name, fmt_id_type[i].name)) {
366                 if (fmt_id_type[i].type != AVMEDIA_TYPE_AUDIO &&
367                     st->codecpar->sample_rate)
368                     continue;
369                 if (st->internal->request_probe > score &&
370                     st->codecpar->codec_id != fmt_id_type[i].id)
371                     continue;
372                 st->codecpar->codec_id   = fmt_id_type[i].id;
373                 st->codecpar->codec_type = fmt_id_type[i].type;
374                 st->internal->need_context_update = 1;
375 #if FF_API_LAVF_AVCTX
376 FF_DISABLE_DEPRECATION_WARNINGS
377                 st->codec->codec_type = st->codecpar->codec_type;
378                 st->codec->codec_id   = st->codecpar->codec_id;
379 FF_ENABLE_DEPRECATION_WARNINGS
380 #endif
381                 return score;
382             }
383         }
384     }
385     return 0;
386 }
387
388 /************************************************************/
389 /* input media file */
390
391 #if FF_API_DEMUXER_OPEN
392 int av_demuxer_open(AVFormatContext *ic) {
393     int err;
394
395     if (ic->format_whitelist && av_match_list(ic->iformat->name, ic->format_whitelist, ',') <= 0) {
396         av_log(ic, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", ic->format_whitelist);
397         return AVERROR(EINVAL);
398     }
399
400     if (ic->iformat->read_header) {
401         err = ic->iformat->read_header(ic);
402         if (err < 0)
403             return err;
404     }
405
406     if (ic->pb && !ic->internal->data_offset)
407         ic->internal->data_offset = avio_tell(ic->pb);
408
409     return 0;
410 }
411 #endif
412 /* Open input file and probe the format if necessary. */
413 static int init_input(AVFormatContext *s, const char *filename,
414                       AVDictionary **options)
415 {
416     int ret;
417     AVProbeData pd = { filename, NULL, 0 };
418     int score = AVPROBE_SCORE_RETRY;
419
420     if (s->pb) {
421         s->flags |= AVFMT_FLAG_CUSTOM_IO;
422         if (!s->iformat)
423             return av_probe_input_buffer2(s->pb, &s->iformat, filename,
424                                          s, 0, s->format_probesize);
425         else if (s->iformat->flags & AVFMT_NOFILE)
426             av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
427                                       "will be ignored with AVFMT_NOFILE format.\n");
428         return 0;
429     }
430
431     if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
432         (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
433         return score;
434
435     if ((ret = s->io_open(s, &s->pb, filename, AVIO_FLAG_READ | s->avio_flags, options)) < 0)
436         return ret;
437
438     if (s->iformat)
439         return 0;
440     return av_probe_input_buffer2(s->pb, &s->iformat, filename,
441                                  s, 0, s->format_probesize);
442 }
443
444 int avformat_queue_attached_pictures(AVFormatContext *s)
445 {
446     int i, ret;
447     for (i = 0; i < s->nb_streams; i++)
448         if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
449             s->streams[i]->discard < AVDISCARD_ALL) {
450             if (s->streams[i]->attached_pic.size <= 0) {
451                 av_log(s, AV_LOG_WARNING,
452                     "Attached picture on stream %d has invalid size, "
453                     "ignoring\n", i);
454                 continue;
455             }
456
457             ret = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
458                                      &s->internal->raw_packet_buffer_end,
459                                      &s->streams[i]->attached_pic,
460                                      av_packet_ref, 0);
461             if (ret < 0)
462                 return ret;
463         }
464     return 0;
465 }
466
467 int ff_add_attached_pic(AVFormatContext *s, AVStream *st0, AVIOContext *pb,
468                         AVBufferRef **buf, int size)
469 {
470     AVStream *st = st0;
471     AVPacket *pkt;
472     int ret;
473
474     if (!st && !(st = avformat_new_stream(s, NULL)))
475         return AVERROR(ENOMEM);
476     pkt = &st->attached_pic;
477     if (buf) {
478         av_assert1(*buf);
479         av_packet_unref(pkt);
480         pkt->buf  = *buf;
481         pkt->data = (*buf)->data;
482         pkt->size = (*buf)->size - AV_INPUT_BUFFER_PADDING_SIZE;
483         *buf = NULL;
484     } else {
485         ret = av_get_packet(pb, pkt, size);
486         if (ret < 0)
487             goto fail;
488     }
489     st->disposition         |= AV_DISPOSITION_ATTACHED_PIC;
490     st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
491
492     pkt->stream_index = st->index;
493     pkt->flags       |= AV_PKT_FLAG_KEY;
494
495     return 0;
496 fail:
497     if (!st0)
498         ff_free_stream(s, st);
499     return ret;
500 }
501
502 static int update_stream_avctx(AVFormatContext *s)
503 {
504     int i, ret;
505     for (i = 0; i < s->nb_streams; i++) {
506         AVStream *st = s->streams[i];
507
508         if (!st->internal->need_context_update)
509             continue;
510
511         /* close parser, because it depends on the codec */
512         if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
513             av_parser_close(st->parser);
514             st->parser = NULL;
515         }
516
517         /* update internal codec context, for the parser */
518         ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
519         if (ret < 0)
520             return ret;
521
522 #if FF_API_LAVF_AVCTX
523 FF_DISABLE_DEPRECATION_WARNINGS
524         /* update deprecated public codec context */
525         ret = avcodec_parameters_to_context(st->codec, st->codecpar);
526         if (ret < 0)
527             return ret;
528 FF_ENABLE_DEPRECATION_WARNINGS
529 #endif
530
531         st->internal->need_context_update = 0;
532     }
533     return 0;
534 }
535
536
537 int avformat_open_input(AVFormatContext **ps, const char *filename,
538                         const AVInputFormat *fmt, AVDictionary **options)
539 {
540     AVFormatContext *s = *ps;
541     int i, ret = 0;
542     AVDictionary *tmp = NULL;
543     ID3v2ExtraMeta *id3v2_extra_meta = NULL;
544
545     if (!s && !(s = avformat_alloc_context()))
546         return AVERROR(ENOMEM);
547     if (!s->av_class) {
548         av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
549         return AVERROR(EINVAL);
550     }
551     if (fmt)
552         s->iformat = fmt;
553
554     if (options)
555         av_dict_copy(&tmp, *options, 0);
556
557     if (s->pb) // must be before any goto fail
558         s->flags |= AVFMT_FLAG_CUSTOM_IO;
559
560     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
561         goto fail;
562
563     if (!(s->url = av_strdup(filename ? filename : ""))) {
564         ret = AVERROR(ENOMEM);
565         goto fail;
566     }
567
568 #if FF_API_FORMAT_FILENAME
569 FF_DISABLE_DEPRECATION_WARNINGS
570     av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
571 FF_ENABLE_DEPRECATION_WARNINGS
572 #endif
573     if ((ret = init_input(s, filename, &tmp)) < 0)
574         goto fail;
575     s->probe_score = ret;
576
577     if (!s->protocol_whitelist && s->pb && s->pb->protocol_whitelist) {
578         s->protocol_whitelist = av_strdup(s->pb->protocol_whitelist);
579         if (!s->protocol_whitelist) {
580             ret = AVERROR(ENOMEM);
581             goto fail;
582         }
583     }
584
585     if (!s->protocol_blacklist && s->pb && s->pb->protocol_blacklist) {
586         s->protocol_blacklist = av_strdup(s->pb->protocol_blacklist);
587         if (!s->protocol_blacklist) {
588             ret = AVERROR(ENOMEM);
589             goto fail;
590         }
591     }
592
593     if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
594         av_log(s, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", s->format_whitelist);
595         ret = AVERROR(EINVAL);
596         goto fail;
597     }
598
599     avio_skip(s->pb, s->skip_initial_bytes);
600
601     /* Check filename in case an image number is expected. */
602     if (s->iformat->flags & AVFMT_NEEDNUMBER) {
603         if (!av_filename_number_test(filename)) {
604             ret = AVERROR(EINVAL);
605             goto fail;
606         }
607     }
608
609     s->duration = s->start_time = AV_NOPTS_VALUE;
610
611     /* Allocate private data. */
612     if (s->iformat->priv_data_size > 0) {
613         if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
614             ret = AVERROR(ENOMEM);
615             goto fail;
616         }
617         if (s->iformat->priv_class) {
618             *(const AVClass **) s->priv_data = s->iformat->priv_class;
619             av_opt_set_defaults(s->priv_data);
620             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
621                 goto fail;
622         }
623     }
624
625     /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
626     if (s->pb)
627         ff_id3v2_read_dict(s->pb, &s->internal->id3v2_meta, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
628
629 #if FF_API_DEMUXER_OPEN
630     if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
631 #else
632     if (s->iformat->read_header)
633 #endif
634         if ((ret = s->iformat->read_header(s)) < 0)
635             goto fail;
636
637     if (!s->metadata) {
638         s->metadata = s->internal->id3v2_meta;
639         s->internal->id3v2_meta = NULL;
640     } else if (s->internal->id3v2_meta) {
641         av_log(s, AV_LOG_WARNING, "Discarding ID3 tags because more suitable tags were found.\n");
642         av_dict_free(&s->internal->id3v2_meta);
643     }
644
645     if (id3v2_extra_meta) {
646         if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
647             !strcmp(s->iformat->name, "tta") || !strcmp(s->iformat->name, "wav")) {
648             if ((ret = ff_id3v2_parse_apic(s, id3v2_extra_meta)) < 0)
649                 goto close;
650             if ((ret = ff_id3v2_parse_chapters(s, id3v2_extra_meta)) < 0)
651                 goto close;
652             if ((ret = ff_id3v2_parse_priv(s, id3v2_extra_meta)) < 0)
653                 goto close;
654         } else
655             av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
656     }
657     ff_id3v2_free_extra_meta(&id3v2_extra_meta);
658
659     if ((ret = avformat_queue_attached_pictures(s)) < 0)
660         goto close;
661
662 #if FF_API_DEMUXER_OPEN
663     if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->internal->data_offset)
664 #else
665     if (s->pb && !s->internal->data_offset)
666 #endif
667         s->internal->data_offset = avio_tell(s->pb);
668
669     s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
670
671     update_stream_avctx(s);
672
673     for (i = 0; i < s->nb_streams; i++)
674         s->streams[i]->internal->orig_codec_id = s->streams[i]->codecpar->codec_id;
675
676     if (options) {
677         av_dict_free(options);
678         *options = tmp;
679     }
680     *ps = s;
681     return 0;
682
683 close:
684     if (s->iformat->read_close)
685         s->iformat->read_close(s);
686 fail:
687     ff_id3v2_free_extra_meta(&id3v2_extra_meta);
688     av_dict_free(&tmp);
689     if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
690         avio_closep(&s->pb);
691     avformat_free_context(s);
692     *ps = NULL;
693     return ret;
694 }
695
696 /*******************************************************/
697
698 static void force_codec_ids(AVFormatContext *s, AVStream *st)
699 {
700     switch (st->codecpar->codec_type) {
701     case AVMEDIA_TYPE_VIDEO:
702         if (s->video_codec_id)
703             st->codecpar->codec_id = s->video_codec_id;
704         break;
705     case AVMEDIA_TYPE_AUDIO:
706         if (s->audio_codec_id)
707             st->codecpar->codec_id = s->audio_codec_id;
708         break;
709     case AVMEDIA_TYPE_SUBTITLE:
710         if (s->subtitle_codec_id)
711             st->codecpar->codec_id = s->subtitle_codec_id;
712         break;
713     case AVMEDIA_TYPE_DATA:
714         if (s->data_codec_id)
715             st->codecpar->codec_id = s->data_codec_id;
716         break;
717     }
718 }
719
720 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
721 {
722     if (st->internal->request_probe>0) {
723         AVProbeData *pd = &st->internal->probe_data;
724         int end;
725         av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
726         --st->probe_packets;
727
728         if (pkt) {
729             uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
730             if (!new_buf) {
731                 av_log(s, AV_LOG_WARNING,
732                        "Failed to reallocate probe buffer for stream %d\n",
733                        st->index);
734                 goto no_packet;
735             }
736             pd->buf = new_buf;
737             memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
738             pd->buf_size += pkt->size;
739             memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
740         } else {
741 no_packet:
742             st->probe_packets = 0;
743             if (!pd->buf_size) {
744                 av_log(s, AV_LOG_WARNING,
745                        "nothing to probe for stream %d\n", st->index);
746             }
747         }
748
749         end=    s->internal->raw_packet_buffer_remaining_size <= 0
750                 || st->probe_packets<= 0;
751
752         if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
753             int score = set_codec_from_probe_data(s, st, pd);
754             if (    (st->codecpar->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
755                 || end) {
756                 pd->buf_size = 0;
757                 av_freep(&pd->buf);
758                 st->internal->request_probe = -1;
759                 if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
760                     av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
761                 } else
762                     av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
763             }
764             force_codec_ids(s, st);
765         }
766     }
767     return 0;
768 }
769
770 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
771 {
772     int64_t ref = pkt->dts;
773     int i, pts_wrap_behavior;
774     int64_t pts_wrap_reference;
775     AVProgram *first_program;
776
777     if (ref == AV_NOPTS_VALUE)
778         ref = pkt->pts;
779     if (st->internal->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
780         return 0;
781     ref &= (1LL << st->pts_wrap_bits)-1;
782
783     // reference time stamp should be 60 s before first time stamp
784     pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
785     // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
786     pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
787         (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
788         AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;
789
790     first_program = av_find_program_from_stream(s, NULL, stream_index);
791
792     if (!first_program) {
793         int default_stream_index = av_find_default_stream_index(s);
794         if (s->streams[default_stream_index]->internal->pts_wrap_reference == AV_NOPTS_VALUE) {
795             for (i = 0; i < s->nb_streams; i++) {
796                 if (av_find_program_from_stream(s, NULL, i))
797                     continue;
798                 s->streams[i]->internal->pts_wrap_reference = pts_wrap_reference;
799                 s->streams[i]->internal->pts_wrap_behavior = pts_wrap_behavior;
800             }
801         }
802         else {
803             st->internal->pts_wrap_reference = s->streams[default_stream_index]->internal->pts_wrap_reference;
804             st->internal->pts_wrap_behavior = s->streams[default_stream_index]->internal->pts_wrap_behavior;
805         }
806     }
807     else {
808         AVProgram *program = first_program;
809         while (program) {
810             if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
811                 pts_wrap_reference = program->pts_wrap_reference;
812                 pts_wrap_behavior = program->pts_wrap_behavior;
813                 break;
814             }
815             program = av_find_program_from_stream(s, program, stream_index);
816         }
817
818         // update every program with differing pts_wrap_reference
819         program = first_program;
820         while (program) {
821             if (program->pts_wrap_reference != pts_wrap_reference) {
822                 for (i = 0; i<program->nb_stream_indexes; i++) {
823                     s->streams[program->stream_index[i]]->internal->pts_wrap_reference = pts_wrap_reference;
824                     s->streams[program->stream_index[i]]->internal->pts_wrap_behavior = pts_wrap_behavior;
825                 }
826
827                 program->pts_wrap_reference = pts_wrap_reference;
828                 program->pts_wrap_behavior = pts_wrap_behavior;
829             }
830             program = av_find_program_from_stream(s, program, stream_index);
831         }
832     }
833     return 1;
834 }
835
836 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
837 {
838     int err, i;
839     AVStream *st;
840
841 #if FF_API_INIT_PACKET
842 FF_DISABLE_DEPRECATION_WARNINGS
843     pkt->data = NULL;
844     pkt->size = 0;
845     av_init_packet(pkt);
846 FF_ENABLE_DEPRECATION_WARNINGS
847 #else
848     av_packet_unref(pkt);
849 #endif
850
851     for (;;) {
852         PacketList *pktl = s->internal->raw_packet_buffer;
853         const AVPacket *pkt1;
854
855         if (pktl) {
856             st = s->streams[pktl->pkt.stream_index];
857             if (s->internal->raw_packet_buffer_remaining_size <= 0)
858                 if ((err = probe_codec(s, st, NULL)) < 0)
859                     return err;
860             if (st->internal->request_probe <= 0) {
861                 avpriv_packet_list_get(&s->internal->raw_packet_buffer,
862                                    &s->internal->raw_packet_buffer_end, pkt);
863                 s->internal->raw_packet_buffer_remaining_size += pkt->size;
864                 return 0;
865             }
866         }
867
868         err = s->iformat->read_packet(s, pkt);
869         if (err < 0) {
870             av_packet_unref(pkt);
871
872             /* Some demuxers return FFERROR_REDO when they consume
873                data and discard it (ignored streams, junk, extradata).
874                We must re-call the demuxer to get the real packet. */
875             if (err == FFERROR_REDO)
876                 continue;
877             if (!pktl || err == AVERROR(EAGAIN))
878                 return err;
879             for (i = 0; i < s->nb_streams; i++) {
880                 st = s->streams[i];
881                 if (st->probe_packets || st->internal->request_probe > 0)
882                     if ((err = probe_codec(s, st, NULL)) < 0)
883                         return err;
884                 av_assert0(st->internal->request_probe <= 0);
885             }
886             continue;
887         }
888
889         err = av_packet_make_refcounted(pkt);
890         if (err < 0) {
891             av_packet_unref(pkt);
892             return err;
893         }
894
895         if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
896             av_log(s, AV_LOG_WARNING,
897                    "Packet corrupt (stream = %d, dts = %s)",
898                    pkt->stream_index, av_ts2str(pkt->dts));
899             if (s->flags & AVFMT_FLAG_DISCARD_CORRUPT) {
900                 av_log(s, AV_LOG_WARNING, ", dropping it.\n");
901                 av_packet_unref(pkt);
902                 continue;
903             }
904             av_log(s, AV_LOG_WARNING, ".\n");
905         }
906
907         av_assert0(pkt->stream_index < (unsigned)s->nb_streams &&
908                    "Invalid stream index.\n");
909
910         st = s->streams[pkt->stream_index];
911
912         if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->internal->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
913             // correct first time stamps to negative values
914             if (!is_relative(st->first_dts))
915                 st->first_dts = wrap_timestamp(st, st->first_dts);
916             if (!is_relative(st->start_time))
917                 st->start_time = wrap_timestamp(st, st->start_time);
918             if (!is_relative(st->cur_dts))
919                 st->cur_dts = wrap_timestamp(st, st->cur_dts);
920         }
921
922         pkt->dts = wrap_timestamp(st, pkt->dts);
923         pkt->pts = wrap_timestamp(st, pkt->pts);
924
925         force_codec_ids(s, st);
926
927         /* TODO: audio: time filter; video: frame reordering (pts != dts) */
928         if (s->use_wallclock_as_timestamps)
929             pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
930
931         if (!pktl && st->internal->request_probe <= 0)
932             return 0;
933
934         err = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
935                                  &s->internal->raw_packet_buffer_end,
936                                  pkt, NULL, 0);
937         if (err < 0) {
938             av_packet_unref(pkt);
939             return err;
940         }
941         pkt1 = &s->internal->raw_packet_buffer_end->pkt;
942         s->internal->raw_packet_buffer_remaining_size -= pkt1->size;
943
944         if ((err = probe_codec(s, st, pkt1)) < 0)
945             return err;
946     }
947 }
948
949
950 /**********************************************************/
951
952 static int determinable_frame_size(AVCodecContext *avctx)
953 {
954     switch(avctx->codec_id) {
955     case AV_CODEC_ID_MP1:
956     case AV_CODEC_ID_MP2:
957     case AV_CODEC_ID_MP3:
958     case AV_CODEC_ID_CODEC2:
959         return 1;
960     }
961
962     return 0;
963 }
964
965 /**
966  * Return the frame duration in seconds. Return 0 if not available.
967  */
968 void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
969                                AVCodecParserContext *pc, AVPacket *pkt)
970 {
971     AVRational codec_framerate = s->iformat ? st->internal->avctx->framerate :
972                                               av_mul_q(av_inv_q(st->internal->avctx->time_base), (AVRational){1, st->internal->avctx->ticks_per_frame});
973     int frame_size, sample_rate;
974
975 #if FF_API_LAVF_AVCTX
976 FF_DISABLE_DEPRECATION_WARNINGS
977     if ((!codec_framerate.den || !codec_framerate.num) && st->codec->time_base.den && st->codec->time_base.num)
978         codec_framerate = av_mul_q(av_inv_q(st->codec->time_base), (AVRational){1, st->codec->ticks_per_frame});
979 FF_ENABLE_DEPRECATION_WARNINGS
980 #endif
981
982     *pnum = 0;
983     *pden = 0;
984     switch (st->codecpar->codec_type) {
985     case AVMEDIA_TYPE_VIDEO:
986         if (st->r_frame_rate.num && !pc && s->iformat) {
987             *pnum = st->r_frame_rate.den;
988             *pden = st->r_frame_rate.num;
989         } else if (st->time_base.num * 1000LL > st->time_base.den) {
990             *pnum = st->time_base.num;
991             *pden = st->time_base.den;
992         } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
993             av_assert0(st->internal->avctx->ticks_per_frame);
994             av_reduce(pnum, pden,
995                       codec_framerate.den,
996                       codec_framerate.num * (int64_t)st->internal->avctx->ticks_per_frame,
997                       INT_MAX);
998
999             if (pc && pc->repeat_pict) {
1000                 av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
1001                 av_reduce(pnum, pden,
1002                           (*pnum) * (1LL + pc->repeat_pict),
1003                           (*pden),
1004                           INT_MAX);
1005             }
1006             /* If this codec can be interlaced or progressive then we need
1007              * a parser to compute duration of a packet. Thus if we have
1008              * no parser in such case leave duration undefined. */
1009             if (st->internal->avctx->ticks_per_frame > 1 && !pc)
1010                 *pnum = *pden = 0;
1011         }
1012         break;
1013     case AVMEDIA_TYPE_AUDIO:
1014         if (st->internal->avctx_inited) {
1015             frame_size = av_get_audio_frame_duration(st->internal->avctx, pkt->size);
1016             sample_rate = st->internal->avctx->sample_rate;
1017         } else {
1018             frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
1019             sample_rate = st->codecpar->sample_rate;
1020         }
1021         if (frame_size <= 0 || sample_rate <= 0)
1022             break;
1023         *pnum = frame_size;
1024         *pden = sample_rate;
1025         break;
1026     default:
1027         break;
1028     }
1029 }
1030
1031 int ff_is_intra_only(enum AVCodecID id)
1032 {
1033     const AVCodecDescriptor *d = avcodec_descriptor_get(id);
1034     if (!d)
1035         return 0;
1036     if ((d->type == AVMEDIA_TYPE_VIDEO || d->type == AVMEDIA_TYPE_AUDIO) &&
1037         !(d->props & AV_CODEC_PROP_INTRA_ONLY))
1038         return 0;
1039     return 1;
1040 }
1041
1042 static int has_decode_delay_been_guessed(AVStream *st)
1043 {
1044     if (st->codecpar->codec_id != AV_CODEC_ID_H264) return 1;
1045     if (!st->internal->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
1046         return 1;
1047 #if CONFIG_H264_DECODER
1048     if (st->internal->avctx->has_b_frames &&
1049        avpriv_h264_has_num_reorder_frames(st->internal->avctx) == st->internal->avctx->has_b_frames)
1050         return 1;
1051 #endif
1052     if (st->internal->avctx->has_b_frames<3)
1053         return st->internal->nb_decoded_frames >= 7;
1054     else if (st->internal->avctx->has_b_frames<4)
1055         return st->internal->nb_decoded_frames >= 18;
1056     else
1057         return st->internal->nb_decoded_frames >= 20;
1058 }
1059
1060 static PacketList *get_next_pkt(AVFormatContext *s, AVStream *st, PacketList *pktl)
1061 {
1062     if (pktl->next)
1063         return pktl->next;
1064     if (pktl == s->internal->packet_buffer_end)
1065         return s->internal->parse_queue;
1066     return NULL;
1067 }
1068
1069 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
1070     int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1071                        st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1072
1073     if(!onein_oneout) {
1074         int delay = st->internal->avctx->has_b_frames;
1075         int i;
1076
1077         if (dts == AV_NOPTS_VALUE) {
1078             int64_t best_score = INT64_MAX;
1079             for (i = 0; i<delay; i++) {
1080                 if (st->internal->pts_reorder_error_count[i]) {
1081                     int64_t score = st->internal->pts_reorder_error[i] / st->internal->pts_reorder_error_count[i];
1082                     if (score < best_score) {
1083                         best_score = score;
1084                         dts = pts_buffer[i];
1085                     }
1086                 }
1087             }
1088         } else {
1089             for (i = 0; i<delay; i++) {
1090                 if (pts_buffer[i] != AV_NOPTS_VALUE) {
1091                     int64_t diff =  FFABS(pts_buffer[i] - dts)
1092                                     + (uint64_t)st->internal->pts_reorder_error[i];
1093                     diff = FFMAX(diff, st->internal->pts_reorder_error[i]);
1094                     st->internal->pts_reorder_error[i] = diff;
1095                     st->internal->pts_reorder_error_count[i]++;
1096                     if (st->internal->pts_reorder_error_count[i] > 250) {
1097                         st->internal->pts_reorder_error[i] >>= 1;
1098                         st->internal->pts_reorder_error_count[i] >>= 1;
1099                     }
1100                 }
1101             }
1102         }
1103     }
1104
1105     if (dts == AV_NOPTS_VALUE)
1106         dts = pts_buffer[0];
1107
1108     return dts;
1109 }
1110
1111 /**
1112  * Updates the dts of packets of a stream in pkt_buffer, by re-ordering the pts
1113  * of the packets in a window.
1114  */
1115 static void update_dts_from_pts(AVFormatContext *s, int stream_index,
1116                                 PacketList *pkt_buffer)
1117 {
1118     AVStream *st       = s->streams[stream_index];
1119     int delay          = st->internal->avctx->has_b_frames;
1120     int i;
1121
1122     int64_t pts_buffer[MAX_REORDER_DELAY+1];
1123
1124     for (i = 0; i<MAX_REORDER_DELAY+1; i++)
1125         pts_buffer[i] = AV_NOPTS_VALUE;
1126
1127     for (; pkt_buffer; pkt_buffer = get_next_pkt(s, st, pkt_buffer)) {
1128         if (pkt_buffer->pkt.stream_index != stream_index)
1129             continue;
1130
1131         if (pkt_buffer->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1132             pts_buffer[0] = pkt_buffer->pkt.pts;
1133             for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
1134                 FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
1135
1136             pkt_buffer->pkt.dts = select_from_pts_buffer(st, pts_buffer, pkt_buffer->pkt.dts);
1137         }
1138     }
1139 }
1140
1141 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
1142                                       int64_t dts, int64_t pts, AVPacket *pkt)
1143 {
1144     AVStream *st       = s->streams[stream_index];
1145     PacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1146     PacketList *pktl_it;
1147
1148     uint64_t shift;
1149
1150     if (st->first_dts != AV_NOPTS_VALUE ||
1151         dts           == AV_NOPTS_VALUE ||
1152         st->cur_dts   == AV_NOPTS_VALUE ||
1153         st->cur_dts < INT_MIN + RELATIVE_TS_BASE ||
1154         dts  < INT_MIN + (st->cur_dts - RELATIVE_TS_BASE) ||
1155         is_relative(dts))
1156         return;
1157
1158     st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
1159     st->cur_dts   = dts;
1160     shift         = (uint64_t)st->first_dts - RELATIVE_TS_BASE;
1161
1162     if (is_relative(pts))
1163         pts += shift;
1164
1165     for (pktl_it = pktl; pktl_it; pktl_it = get_next_pkt(s, st, pktl_it)) {
1166         if (pktl_it->pkt.stream_index != stream_index)
1167             continue;
1168         if (is_relative(pktl_it->pkt.pts))
1169             pktl_it->pkt.pts += shift;
1170
1171         if (is_relative(pktl_it->pkt.dts))
1172             pktl_it->pkt.dts += shift;
1173
1174         if (st->start_time == AV_NOPTS_VALUE && pktl_it->pkt.pts != AV_NOPTS_VALUE) {
1175             st->start_time = pktl_it->pkt.pts;
1176             if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
1177                 st->start_time = av_sat_add64(st->start_time, av_rescale_q(st->internal->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base));
1178         }
1179     }
1180
1181     if (has_decode_delay_been_guessed(st)) {
1182         update_dts_from_pts(s, stream_index, pktl);
1183     }
1184
1185     if (st->start_time == AV_NOPTS_VALUE) {
1186         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || !(pkt->flags & AV_PKT_FLAG_DISCARD)) {
1187             st->start_time = pts;
1188         }
1189         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
1190             st->start_time = av_sat_add64(st->start_time, av_rescale_q(st->internal->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base));
1191     }
1192 }
1193
1194 static void update_initial_durations(AVFormatContext *s, AVStream *st,
1195                                      int stream_index, int64_t duration)
1196 {
1197     PacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1198     int64_t cur_dts    = RELATIVE_TS_BASE;
1199
1200     if (st->first_dts != AV_NOPTS_VALUE) {
1201         if (st->internal->update_initial_durations_done)
1202             return;
1203         st->internal->update_initial_durations_done = 1;
1204         cur_dts = st->first_dts;
1205         for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1206             if (pktl->pkt.stream_index == stream_index) {
1207                 if (pktl->pkt.pts != pktl->pkt.dts  ||
1208                     pktl->pkt.dts != AV_NOPTS_VALUE ||
1209                     pktl->pkt.duration)
1210                     break;
1211                 cur_dts -= duration;
1212             }
1213         }
1214         if (pktl && pktl->pkt.dts != st->first_dts) {
1215             av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
1216                    av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
1217             return;
1218         }
1219         if (!pktl) {
1220             av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
1221             return;
1222         }
1223         pktl          = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1224         st->first_dts = cur_dts;
1225     } else if (st->cur_dts != RELATIVE_TS_BASE)
1226         return;
1227
1228     for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1229         if (pktl->pkt.stream_index != stream_index)
1230             continue;
1231         if ((pktl->pkt.pts == pktl->pkt.dts ||
1232              pktl->pkt.pts == AV_NOPTS_VALUE) &&
1233             (pktl->pkt.dts == AV_NOPTS_VALUE ||
1234              pktl->pkt.dts == st->first_dts ||
1235              pktl->pkt.dts == RELATIVE_TS_BASE) &&
1236             !pktl->pkt.duration) {
1237             pktl->pkt.dts = cur_dts;
1238             if (!st->internal->avctx->has_b_frames)
1239                 pktl->pkt.pts = cur_dts;
1240             pktl->pkt.duration = duration;
1241         } else
1242             break;
1243         cur_dts = pktl->pkt.dts + pktl->pkt.duration;
1244     }
1245     if (!pktl)
1246         st->cur_dts = cur_dts;
1247 }
1248
1249 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
1250                                AVCodecParserContext *pc, AVPacket *pkt,
1251                                int64_t next_dts, int64_t next_pts)
1252 {
1253     int num, den, presentation_delayed, delay, i;
1254     int64_t offset;
1255     AVRational duration;
1256     int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1257                        st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1258
1259     if (s->flags & AVFMT_FLAG_NOFILLIN)
1260         return;
1261
1262     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1263         if (pkt->dts == pkt->pts && st->internal->last_dts_for_order_check != AV_NOPTS_VALUE) {
1264             if (st->internal->last_dts_for_order_check <= pkt->dts) {
1265                 st->internal->dts_ordered++;
1266             } else {
1267                 av_log(s, st->internal->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
1268                        "DTS %"PRIi64" < %"PRIi64" out of order\n",
1269                        pkt->dts,
1270                        st->internal->last_dts_for_order_check);
1271                 st->internal->dts_misordered++;
1272             }
1273             if (st->internal->dts_ordered + st->internal->dts_misordered > 250) {
1274                 st->internal->dts_ordered    >>= 1;
1275                 st->internal->dts_misordered >>= 1;
1276             }
1277         }
1278
1279         st->internal->last_dts_for_order_check = pkt->dts;
1280         if (st->internal->dts_ordered < 8*st->internal->dts_misordered && pkt->dts == pkt->pts)
1281             pkt->dts = AV_NOPTS_VALUE;
1282     }
1283
1284     if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1285         pkt->dts = AV_NOPTS_VALUE;
1286
1287     if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1288         && !st->internal->avctx->has_b_frames)
1289         //FIXME Set low_delay = 0 when has_b_frames = 1
1290         st->internal->avctx->has_b_frames = 1;
1291
1292     /* do we have a video B-frame ? */
1293     delay = st->internal->avctx->has_b_frames;
1294     presentation_delayed = 0;
1295
1296     /* XXX: need has_b_frame, but cannot get it if the codec is
1297      *  not initialized */
1298     if (delay &&
1299         pc && pc->pict_type != AV_PICTURE_TYPE_B)
1300         presentation_delayed = 1;
1301
1302     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1303         st->pts_wrap_bits < 63 && pkt->dts > INT64_MIN + (1LL << st->pts_wrap_bits) &&
1304         pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1305         if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
1306             pkt->dts -= 1LL << st->pts_wrap_bits;
1307         } else
1308             pkt->pts += 1LL << st->pts_wrap_bits;
1309     }
1310
1311     /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1312      * We take the conservative approach and discard both.
1313      * Note: If this is misbehaving for an H.264 file, then possibly
1314      * presentation_delayed is not set correctly. */
1315     if (delay == 1 && pkt->dts == pkt->pts &&
1316         pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1317         av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1318         if (    strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1319              && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1320             pkt->dts = AV_NOPTS_VALUE;
1321     }
1322
1323     duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1324     if (pkt->duration <= 0) {
1325         ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1326         if (den && num) {
1327             duration = (AVRational) {num, den};
1328             pkt->duration = av_rescale_rnd(1,
1329                                            num * (int64_t) st->time_base.den,
1330                                            den * (int64_t) st->time_base.num,
1331                                            AV_ROUND_DOWN);
1332         }
1333     }
1334
1335     if (pkt->duration > 0 && (s->internal->packet_buffer || s->internal->parse_queue))
1336         update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1337
1338     /* Correct timestamps with byte offset if demuxers only have timestamps
1339      * on packet boundaries */
1340     if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1341         /* this will estimate bitrate based on this frame's duration and size */
1342         offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1343         if (pkt->pts != AV_NOPTS_VALUE)
1344             pkt->pts += offset;
1345         if (pkt->dts != AV_NOPTS_VALUE)
1346             pkt->dts += offset;
1347     }
1348
1349     /* This may be redundant, but it should not hurt. */
1350     if (pkt->dts != AV_NOPTS_VALUE &&
1351         pkt->pts != AV_NOPTS_VALUE &&
1352         pkt->pts > pkt->dts)
1353         presentation_delayed = 1;
1354
1355     if (s->debug & FF_FDEBUG_TS)
1356         av_log(s, AV_LOG_DEBUG,
1357             "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%"PRId64" delay:%d onein_oneout:%d\n",
1358             presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1359             pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1360
1361     /* Interpolate PTS and DTS if they are not present. We skip H264
1362      * currently because delay and has_b_frames are not reliably set. */
1363     if ((delay == 0 || (delay == 1 && pc)) &&
1364         onein_oneout) {
1365         if (presentation_delayed) {
1366             /* DTS = decompression timestamp */
1367             /* PTS = presentation timestamp */
1368             if (pkt->dts == AV_NOPTS_VALUE)
1369                 pkt->dts = st->last_IP_pts;
1370             update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1371             if (pkt->dts == AV_NOPTS_VALUE)
1372                 pkt->dts = st->cur_dts;
1373
1374             /* This is tricky: the dts must be incremented by the duration
1375              * of the frame we are displaying, i.e. the last I- or P-frame. */
1376             if (st->last_IP_duration == 0 && (uint64_t)pkt->duration <= INT32_MAX)
1377                 st->last_IP_duration = pkt->duration;
1378             if (pkt->dts != AV_NOPTS_VALUE)
1379                 st->cur_dts = av_sat_add64(pkt->dts, st->last_IP_duration);
1380             if (pkt->dts != AV_NOPTS_VALUE &&
1381                 pkt->pts == AV_NOPTS_VALUE &&
1382                 st->last_IP_duration > 0 &&
1383                 ((uint64_t)st->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1384                 next_dts != next_pts &&
1385                 next_pts != AV_NOPTS_VALUE)
1386                 pkt->pts = next_dts;
1387
1388             if ((uint64_t)pkt->duration <= INT32_MAX)
1389                 st->last_IP_duration = pkt->duration;
1390             st->last_IP_pts      = pkt->pts;
1391             /* Cannot compute PTS if not present (we can compute it only
1392              * by knowing the future. */
1393         } else if (pkt->pts != AV_NOPTS_VALUE ||
1394                    pkt->dts != AV_NOPTS_VALUE ||
1395                    pkt->duration > 0             ) {
1396
1397             /* presentation is not delayed : PTS and DTS are the same */
1398             if (pkt->pts == AV_NOPTS_VALUE)
1399                 pkt->pts = pkt->dts;
1400             update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1401                                       pkt->pts, pkt);
1402             if (pkt->pts == AV_NOPTS_VALUE)
1403                 pkt->pts = st->cur_dts;
1404             pkt->dts = pkt->pts;
1405             if (pkt->pts != AV_NOPTS_VALUE && duration.num >= 0)
1406                 st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1407         }
1408     }
1409
1410     if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1411         st->internal->pts_buffer[0] = pkt->pts;
1412         for (i = 0; i<delay && st->internal->pts_buffer[i] > st->internal->pts_buffer[i + 1]; i++)
1413             FFSWAP(int64_t, st->internal->pts_buffer[i], st->internal->pts_buffer[i + 1]);
1414
1415         if(has_decode_delay_been_guessed(st))
1416             pkt->dts = select_from_pts_buffer(st, st->internal->pts_buffer, pkt->dts);
1417     }
1418     // We skipped it above so we try here.
1419     if (!onein_oneout)
1420         // This should happen on the first packet
1421         update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1422     if (pkt->dts > st->cur_dts)
1423         st->cur_dts = pkt->dts;
1424
1425     if (s->debug & FF_FDEBUG_TS)
1426         av_log(s, AV_LOG_DEBUG, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s st:%d (%d)\n",
1427             presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), st->index, st->id);
1428
1429     /* update flags */
1430     if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || ff_is_intra_only(st->codecpar->codec_id))
1431         pkt->flags |= AV_PKT_FLAG_KEY;
1432 }
1433
1434 /**
1435  * Parse a packet, add all split parts to parse_queue.
1436  *
1437  * @param pkt   Packet to parse; must not be NULL.
1438  * @param flush Indicates whether to flush. If set, pkt must be blank.
1439  */
1440 static int parse_packet(AVFormatContext *s, AVPacket *pkt,
1441                         int stream_index, int flush)
1442 {
1443     AVPacket *out_pkt = s->internal->parse_pkt;
1444     AVStream *st = s->streams[stream_index];
1445     uint8_t *data = pkt->data;
1446     int size      = pkt->size;
1447     int ret = 0, got_output = flush;
1448
1449     if (!size && !flush && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1450         // preserve 0-size sync packets
1451         compute_pkt_fields(s, st, st->parser, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1452     }
1453
1454     while (size > 0 || (flush && got_output)) {
1455         int len;
1456         int64_t next_pts = pkt->pts;
1457         int64_t next_dts = pkt->dts;
1458
1459         len = av_parser_parse2(st->parser, st->internal->avctx,
1460                                &out_pkt->data, &out_pkt->size, data, size,
1461                                pkt->pts, pkt->dts, pkt->pos);
1462
1463         pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1464         pkt->pos = -1;
1465         /* increment read pointer */
1466         av_assert1(data || !len);
1467         data  = len ? data + len : data;
1468         size -= len;
1469
1470         got_output = !!out_pkt->size;
1471
1472         if (!out_pkt->size)
1473             continue;
1474
1475         if (pkt->buf && out_pkt->data == pkt->data) {
1476             /* reference pkt->buf only when out_pkt->data is guaranteed to point
1477              * to data in it and not in the parser's internal buffer. */
1478             /* XXX: Ensure this is the case with all parsers when st->parser->flags
1479              * is PARSER_FLAG_COMPLETE_FRAMES and check for that instead? */
1480             out_pkt->buf = av_buffer_ref(pkt->buf);
1481             if (!out_pkt->buf) {
1482                 ret = AVERROR(ENOMEM);
1483                 goto fail;
1484             }
1485         } else {
1486             ret = av_packet_make_refcounted(out_pkt);
1487             if (ret < 0)
1488                 goto fail;
1489         }
1490
1491         if (pkt->side_data) {
1492             out_pkt->side_data       = pkt->side_data;
1493             out_pkt->side_data_elems = pkt->side_data_elems;
1494             pkt->side_data          = NULL;
1495             pkt->side_data_elems    = 0;
1496         }
1497
1498         /* set the duration */
1499         out_pkt->duration = (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;
1500         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1501             if (st->internal->avctx->sample_rate > 0) {
1502                 out_pkt->duration =
1503                     av_rescale_q_rnd(st->parser->duration,
1504                                      (AVRational) { 1, st->internal->avctx->sample_rate },
1505                                      st->time_base,
1506                                      AV_ROUND_DOWN);
1507             }
1508         }
1509
1510         out_pkt->stream_index = st->index;
1511         out_pkt->pts          = st->parser->pts;
1512         out_pkt->dts          = st->parser->dts;
1513         out_pkt->pos          = st->parser->pos;
1514         out_pkt->flags       |= pkt->flags & AV_PKT_FLAG_DISCARD;
1515
1516         if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1517             out_pkt->pos = st->parser->frame_offset;
1518
1519         if (st->parser->key_frame == 1 ||
1520             (st->parser->key_frame == -1 &&
1521              st->parser->pict_type == AV_PICTURE_TYPE_I))
1522             out_pkt->flags |= AV_PKT_FLAG_KEY;
1523
1524         if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1525             out_pkt->flags |= AV_PKT_FLAG_KEY;
1526
1527         compute_pkt_fields(s, st, st->parser, out_pkt, next_dts, next_pts);
1528
1529         ret = avpriv_packet_list_put(&s->internal->parse_queue,
1530                                  &s->internal->parse_queue_end,
1531                                  out_pkt, NULL, 0);
1532         if (ret < 0)
1533             goto fail;
1534     }
1535
1536     /* end of the stream => close and free the parser */
1537     if (flush) {
1538         av_parser_close(st->parser);
1539         st->parser = NULL;
1540     }
1541
1542 fail:
1543     if (ret < 0)
1544         av_packet_unref(out_pkt);
1545     av_packet_unref(pkt);
1546     return ret;
1547 }
1548
1549 static int64_t ts_to_samples(AVStream *st, int64_t ts)
1550 {
1551     return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
1552 }
1553
1554 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1555 {
1556     int ret, i, got_packet = 0;
1557     AVDictionary *metadata = NULL;
1558
1559     while (!got_packet && !s->internal->parse_queue) {
1560         AVStream *st;
1561
1562         /* read next packet */
1563         ret = ff_read_packet(s, pkt);
1564         if (ret < 0) {
1565             if (ret == AVERROR(EAGAIN))
1566                 return ret;
1567             /* flush the parsers */
1568             for (i = 0; i < s->nb_streams; i++) {
1569                 st = s->streams[i];
1570                 if (st->parser && st->need_parsing)
1571                     parse_packet(s, pkt, st->index, 1);
1572             }
1573             /* all remaining packets are now in parse_queue =>
1574              * really terminate parsing */
1575             break;
1576         }
1577         ret = 0;
1578         st  = s->streams[pkt->stream_index];
1579
1580         st->event_flags |= AVSTREAM_EVENT_FLAG_NEW_PACKETS;
1581
1582         /* update context if required */
1583         if (st->internal->need_context_update) {
1584             if (avcodec_is_open(st->internal->avctx)) {
1585                 av_log(s, AV_LOG_DEBUG, "Demuxer context update while decoder is open, closing and trying to re-open\n");
1586                 avcodec_close(st->internal->avctx);
1587                 st->internal->info->found_decoder = 0;
1588             }
1589
1590             /* close parser, because it depends on the codec */
1591             if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
1592                 av_parser_close(st->parser);
1593                 st->parser = NULL;
1594             }
1595
1596             ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
1597             if (ret < 0) {
1598                 av_packet_unref(pkt);
1599                 return ret;
1600             }
1601
1602 #if FF_API_LAVF_AVCTX
1603 FF_DISABLE_DEPRECATION_WARNINGS
1604             /* update deprecated public codec context */
1605             ret = avcodec_parameters_to_context(st->codec, st->codecpar);
1606             if (ret < 0) {
1607                 av_packet_unref(pkt);
1608                 return ret;
1609             }
1610 FF_ENABLE_DEPRECATION_WARNINGS
1611 #endif
1612
1613             st->internal->need_context_update = 0;
1614         }
1615
1616         if (pkt->pts != AV_NOPTS_VALUE &&
1617             pkt->dts != AV_NOPTS_VALUE &&
1618             pkt->pts < pkt->dts) {
1619             av_log(s, AV_LOG_WARNING,
1620                    "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1621                    pkt->stream_index,
1622                    av_ts2str(pkt->pts),
1623                    av_ts2str(pkt->dts),
1624                    pkt->size);
1625         }
1626         if (s->debug & FF_FDEBUG_TS)
1627             av_log(s, AV_LOG_DEBUG,
1628                    "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%"PRId64", flags=%d\n",
1629                    pkt->stream_index,
1630                    av_ts2str(pkt->pts),
1631                    av_ts2str(pkt->dts),
1632                    pkt->size, pkt->duration, pkt->flags);
1633
1634         if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1635             st->parser = av_parser_init(st->codecpar->codec_id);
1636             if (!st->parser) {
1637                 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1638                        "%s, packets or times may be invalid.\n",
1639                        avcodec_get_name(st->codecpar->codec_id));
1640                 /* no parser available: just output the raw packets */
1641                 st->need_parsing = AVSTREAM_PARSE_NONE;
1642             } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1643                 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1644             else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1645                 st->parser->flags |= PARSER_FLAG_ONCE;
1646             else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1647                 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1648         }
1649
1650         if (!st->need_parsing || !st->parser) {
1651             /* no parsing needed: we just output the packet as is */
1652             compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1653             if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1654                 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1655                 ff_reduce_index(s, st->index);
1656                 av_add_index_entry(st, pkt->pos, pkt->dts,
1657                                    0, 0, AVINDEX_KEYFRAME);
1658             }
1659             got_packet = 1;
1660         } else if (st->discard < AVDISCARD_ALL) {
1661             if ((ret = parse_packet(s, pkt, pkt->stream_index, 0)) < 0)
1662                 return ret;
1663             st->codecpar->sample_rate = st->internal->avctx->sample_rate;
1664             st->codecpar->bit_rate = st->internal->avctx->bit_rate;
1665             st->codecpar->channels = st->internal->avctx->channels;
1666             st->codecpar->channel_layout = st->internal->avctx->channel_layout;
1667             st->codecpar->codec_id = st->internal->avctx->codec_id;
1668         } else {
1669             /* free packet */
1670             av_packet_unref(pkt);
1671         }
1672         if (pkt->flags & AV_PKT_FLAG_KEY)
1673             st->internal->skip_to_keyframe = 0;
1674         if (st->internal->skip_to_keyframe) {
1675             av_packet_unref(pkt);
1676             got_packet = 0;
1677         }
1678     }
1679
1680     if (!got_packet && s->internal->parse_queue)
1681         ret = avpriv_packet_list_get(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
1682
1683     if (ret >= 0) {
1684         AVStream *st = s->streams[pkt->stream_index];
1685         int discard_padding = 0;
1686         if (st->internal->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1687             int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1688             int64_t sample = ts_to_samples(st, pts);
1689             int duration = ts_to_samples(st, pkt->duration);
1690             int64_t end_sample = sample + duration;
1691             if (duration > 0 && end_sample >= st->internal->first_discard_sample &&
1692                 sample < st->internal->last_discard_sample)
1693                 discard_padding = FFMIN(end_sample - st->internal->first_discard_sample, duration);
1694         }
1695         if (st->internal->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
1696             st->internal->skip_samples = st->internal->start_skip_samples;
1697         if (st->internal->skip_samples || discard_padding) {
1698             uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1699             if (p) {
1700                 AV_WL32(p, st->internal->skip_samples);
1701                 AV_WL32(p + 4, discard_padding);
1702                 av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d / discard %d\n", st->internal->skip_samples, discard_padding);
1703             }
1704             st->internal->skip_samples = 0;
1705         }
1706
1707         if (st->internal->inject_global_side_data) {
1708             for (i = 0; i < st->nb_side_data; i++) {
1709                 AVPacketSideData *src_sd = &st->side_data[i];
1710                 uint8_t *dst_data;
1711
1712                 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1713                     continue;
1714
1715                 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1716                 if (!dst_data) {
1717                     av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1718                     continue;
1719                 }
1720
1721                 memcpy(dst_data, src_sd->data, src_sd->size);
1722             }
1723             st->internal->inject_global_side_data = 0;
1724         }
1725     }
1726
1727     av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1728     if (metadata) {
1729         s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1730         av_dict_copy(&s->metadata, metadata, 0);
1731         av_dict_free(&metadata);
1732         av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
1733     }
1734
1735 #if FF_API_LAVF_AVCTX
1736     update_stream_avctx(s);
1737 #endif
1738
1739     if (s->debug & FF_FDEBUG_TS)
1740         av_log(s, AV_LOG_DEBUG,
1741                "read_frame_internal stream=%d, pts=%s, dts=%s, "
1742                "size=%d, duration=%"PRId64", flags=%d\n",
1743                pkt->stream_index,
1744                av_ts2str(pkt->pts),
1745                av_ts2str(pkt->dts),
1746                pkt->size, pkt->duration, pkt->flags);
1747
1748     /* A demuxer might have returned EOF because of an IO error, let's
1749      * propagate this back to the user. */
1750     if (ret == AVERROR_EOF && s->pb && s->pb->error < 0 && s->pb->error != AVERROR(EAGAIN))
1751         ret = s->pb->error;
1752
1753     return ret;
1754 }
1755
1756 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1757 {
1758     const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1759     int eof = 0;
1760     int ret;
1761     AVStream *st;
1762
1763     if (!genpts) {
1764         ret = s->internal->packet_buffer
1765               ? avpriv_packet_list_get(&s->internal->packet_buffer,
1766                                         &s->internal->packet_buffer_end, pkt)
1767               : read_frame_internal(s, pkt);
1768         if (ret < 0)
1769             return ret;
1770         goto return_packet;
1771     }
1772
1773     for (;;) {
1774         PacketList *pktl = s->internal->packet_buffer;
1775
1776         if (pktl) {
1777             AVPacket *next_pkt = &pktl->pkt;
1778
1779             if (next_pkt->dts != AV_NOPTS_VALUE) {
1780                 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1781                 // last dts seen for this stream. if any of packets following
1782                 // current one had no dts, we will set this to AV_NOPTS_VALUE.
1783                 int64_t last_dts = next_pkt->dts;
1784                 av_assert2(wrap_bits <= 64);
1785                 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1786                     if (pktl->pkt.stream_index == next_pkt->stream_index &&
1787                         av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) {
1788                         if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) {
1789                             // not B-frame
1790                             next_pkt->pts = pktl->pkt.dts;
1791                         }
1792                         if (last_dts != AV_NOPTS_VALUE) {
1793                             // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1794                             last_dts = pktl->pkt.dts;
1795                         }
1796                     }
1797                     pktl = pktl->next;
1798                 }
1799                 if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1800                     // Fixing the last reference frame had none pts issue (For MXF etc).
1801                     // We only do this when
1802                     // 1. eof.
1803                     // 2. we are not able to resolve a pts value for current packet.
1804                     // 3. the packets for this stream at the end of the files had valid dts.
1805                     next_pkt->pts = last_dts + next_pkt->duration;
1806                 }
1807                 pktl = s->internal->packet_buffer;
1808             }
1809
1810             /* read packet from packet buffer, if there is data */
1811             st = s->streams[next_pkt->stream_index];
1812             if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1813                   next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1814                 ret = avpriv_packet_list_get(&s->internal->packet_buffer,
1815                                                &s->internal->packet_buffer_end, pkt);
1816                 goto return_packet;
1817             }
1818         }
1819
1820         ret = read_frame_internal(s, pkt);
1821         if (ret < 0) {
1822             if (pktl && ret != AVERROR(EAGAIN)) {
1823                 eof = 1;
1824                 continue;
1825             } else
1826                 return ret;
1827         }
1828
1829         ret = avpriv_packet_list_put(&s->internal->packet_buffer,
1830                                  &s->internal->packet_buffer_end,
1831                                  pkt, NULL, 0);
1832         if (ret < 0) {
1833             av_packet_unref(pkt);
1834             return ret;
1835         }
1836     }
1837
1838 return_packet:
1839
1840     st = s->streams[pkt->stream_index];
1841     if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1842         ff_reduce_index(s, st->index);
1843         av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1844     }
1845
1846     if (is_relative(pkt->dts))
1847         pkt->dts -= RELATIVE_TS_BASE;
1848     if (is_relative(pkt->pts))
1849         pkt->pts -= RELATIVE_TS_BASE;
1850
1851     return ret;
1852 }
1853
1854 /* XXX: suppress the packet queue */
1855 static void flush_packet_queue(AVFormatContext *s)
1856 {
1857     if (!s->internal)
1858         return;
1859     avpriv_packet_list_free(&s->internal->parse_queue,       &s->internal->parse_queue_end);
1860     avpriv_packet_list_free(&s->internal->packet_buffer,     &s->internal->packet_buffer_end);
1861     avpriv_packet_list_free(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
1862
1863     s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1864 }
1865
1866 /*******************************************************/
1867 /* seek support */
1868
1869 int av_find_default_stream_index(AVFormatContext *s)
1870 {
1871     int i;
1872     AVStream *st;
1873     int best_stream = 0;
1874     int best_score = INT_MIN;
1875
1876     if (s->nb_streams <= 0)
1877         return -1;
1878     for (i = 0; i < s->nb_streams; i++) {
1879         int score = 0;
1880         st = s->streams[i];
1881         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1882             if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
1883                 score -= 400;
1884             if (st->codecpar->width && st->codecpar->height)
1885                 score += 50;
1886             score+= 25;
1887         }
1888         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1889             if (st->codecpar->sample_rate)
1890                 score += 50;
1891         }
1892         if (st->codec_info_nb_frames)
1893             score += 12;
1894
1895         if (st->discard != AVDISCARD_ALL)
1896             score += 200;
1897
1898         if (score > best_score) {
1899             best_score = score;
1900             best_stream = i;
1901         }
1902     }
1903     return best_stream;
1904 }
1905
1906 /** Flush the frame reader. */
1907 void ff_read_frame_flush(AVFormatContext *s)
1908 {
1909     AVStream *st;
1910     int i, j;
1911
1912     flush_packet_queue(s);
1913
1914     /* Reset read state for each stream. */
1915     for (i = 0; i < s->nb_streams; i++) {
1916         st = s->streams[i];
1917
1918         if (st->parser) {
1919             av_parser_close(st->parser);
1920             st->parser = NULL;
1921         }
1922         st->last_IP_pts = AV_NOPTS_VALUE;
1923         st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
1924         if (st->first_dts == AV_NOPTS_VALUE)
1925             st->cur_dts = RELATIVE_TS_BASE;
1926         else
1927             /* We set the current DTS to an unspecified origin. */
1928             st->cur_dts = AV_NOPTS_VALUE;
1929
1930         st->probe_packets = s->max_probe_packets;
1931
1932         for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1933             st->internal->pts_buffer[j] = AV_NOPTS_VALUE;
1934
1935         if (s->internal->inject_global_side_data)
1936             st->internal->inject_global_side_data = 1;
1937
1938         st->internal->skip_samples = 0;
1939     }
1940 }
1941
1942 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1943 {
1944     int i;
1945
1946     for (i = 0; i < s->nb_streams; i++) {
1947         AVStream *st = s->streams[i];
1948
1949         st->cur_dts =
1950             av_rescale(timestamp,
1951                        st->time_base.den * (int64_t) ref_st->time_base.num,
1952                        st->time_base.num * (int64_t) ref_st->time_base.den);
1953     }
1954 }
1955
1956 void ff_reduce_index(AVFormatContext *s, int stream_index)
1957 {
1958     AVStream *st             = s->streams[stream_index];
1959     unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1960
1961     if ((unsigned) st->internal->nb_index_entries >= max_entries) {
1962         int i;
1963         for (i = 0; 2 * i < st->internal->nb_index_entries; i++)
1964             st->internal->index_entries[i] = st->internal->index_entries[2 * i];
1965         st->internal->nb_index_entries = i;
1966     }
1967 }
1968
1969 int ff_add_index_entry(AVIndexEntry **index_entries,
1970                        int *nb_index_entries,
1971                        unsigned int *index_entries_allocated_size,
1972                        int64_t pos, int64_t timestamp,
1973                        int size, int distance, int flags)
1974 {
1975     AVIndexEntry *entries, *ie;
1976     int index;
1977
1978     if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1979         return -1;
1980
1981     if (timestamp == AV_NOPTS_VALUE)
1982         return AVERROR(EINVAL);
1983
1984     if (size < 0 || size > 0x3FFFFFFF)
1985         return AVERROR(EINVAL);
1986
1987     if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1988         timestamp -= RELATIVE_TS_BASE;
1989
1990     entries = av_fast_realloc(*index_entries,
1991                               index_entries_allocated_size,
1992                               (*nb_index_entries + 1) *
1993                               sizeof(AVIndexEntry));
1994     if (!entries)
1995         return -1;
1996
1997     *index_entries = entries;
1998
1999     index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
2000                                       timestamp, AVSEEK_FLAG_ANY);
2001
2002     if (index < 0) {
2003         index = (*nb_index_entries)++;
2004         ie    = &entries[index];
2005         av_assert0(index == 0 || ie[-1].timestamp < timestamp);
2006     } else {
2007         ie = &entries[index];
2008         if (ie->timestamp != timestamp) {
2009             if (ie->timestamp <= timestamp)
2010                 return -1;
2011             memmove(entries + index + 1, entries + index,
2012                     sizeof(AVIndexEntry) * (*nb_index_entries - index));
2013             (*nb_index_entries)++;
2014         } else if (ie->pos == pos && distance < ie->min_distance)
2015             // do not reduce the distance
2016             distance = ie->min_distance;
2017     }
2018
2019     ie->pos          = pos;
2020     ie->timestamp    = timestamp;
2021     ie->min_distance = distance;
2022     ie->size         = size;
2023     ie->flags        = flags;
2024
2025     return index;
2026 }
2027
2028 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
2029                        int size, int distance, int flags)
2030 {
2031     timestamp = wrap_timestamp(st, timestamp);
2032     return ff_add_index_entry(&st->internal->index_entries, &st->internal->nb_index_entries,
2033                               &st->internal->index_entries_allocated_size, pos,
2034                               timestamp, size, distance, flags);
2035 }
2036
2037 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
2038                               int64_t wanted_timestamp, int flags)
2039 {
2040     int a, b, m;
2041     int64_t timestamp;
2042
2043     a = -1;
2044     b = nb_entries;
2045
2046     // Optimize appending index entries at the end.
2047     if (b && entries[b - 1].timestamp < wanted_timestamp)
2048         a = b - 1;
2049
2050     while (b - a > 1) {
2051         m         = (a + b) >> 1;
2052
2053         // Search for the next non-discarded packet.
2054         while ((entries[m].flags & AVINDEX_DISCARD_FRAME) && m < b && m < nb_entries - 1) {
2055             m++;
2056             if (m == b && entries[m].timestamp >= wanted_timestamp) {
2057                 m = b - 1;
2058                 break;
2059             }
2060         }
2061
2062         timestamp = entries[m].timestamp;
2063         if (timestamp >= wanted_timestamp)
2064             b = m;
2065         if (timestamp <= wanted_timestamp)
2066             a = m;
2067     }
2068     m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
2069
2070     if (!(flags & AVSEEK_FLAG_ANY))
2071         while (m >= 0 && m < nb_entries &&
2072                !(entries[m].flags & AVINDEX_KEYFRAME))
2073             m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
2074
2075     if (m == nb_entries)
2076         return -1;
2077     return m;
2078 }
2079
2080 void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
2081 {
2082     int ist1, ist2;
2083     int64_t pos_delta = 0;
2084     int64_t skip = 0;
2085     //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable
2086     const char *proto = avio_find_protocol_name(s->url);
2087
2088     av_assert0(time_tolerance >= 0);
2089
2090     if (!proto) {
2091         av_log(s, AV_LOG_INFO,
2092                "Protocol name not provided, cannot determine if input is local or "
2093                "a network protocol, buffers and access patterns cannot be configured "
2094                "optimally without knowing the protocol\n");
2095     }
2096
2097     if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))
2098         return;
2099
2100     for (ist1 = 0; ist1 < s->nb_streams; ist1++) {
2101         AVStream *st1 = s->streams[ist1];
2102         for (ist2 = 0; ist2 < s->nb_streams; ist2++) {
2103             AVStream *st2 = s->streams[ist2];
2104             int i1, i2;
2105
2106             if (ist1 == ist2)
2107                 continue;
2108
2109             for (i1 = i2 = 0; i1 < st1->internal->nb_index_entries; i1++) {
2110                 AVIndexEntry *e1 = &st1->internal->index_entries[i1];
2111                 int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);
2112
2113                 skip = FFMAX(skip, e1->size);
2114                 for (; i2 < st2->internal->nb_index_entries; i2++) {
2115                     AVIndexEntry *e2 = &st2->internal->index_entries[i2];
2116                     int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);
2117                     if (e2_pts < e1_pts || e2_pts - (uint64_t)e1_pts < time_tolerance)
2118                         continue;
2119                     pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);
2120                     break;
2121                 }
2122             }
2123         }
2124     }
2125
2126     pos_delta *= 2;
2127     /* XXX This could be adjusted depending on protocol*/
2128     if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {
2129         av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);
2130
2131         /* realloc the buffer and the original data will be retained */
2132         if (ffio_realloc_buf(s->pb, pos_delta)) {
2133             av_log(s, AV_LOG_ERROR, "Realloc buffer fail.\n");
2134             return;
2135         }
2136
2137         s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);
2138     }
2139
2140     if (skip < (1<<23)) {
2141         s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, skip);
2142     }
2143 }
2144
2145 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
2146 {
2147     return ff_index_search_timestamp(st->internal->index_entries, st->internal->nb_index_entries,
2148                                      wanted_timestamp, flags);
2149 }
2150
2151 int avformat_index_get_entries_count(const AVStream *st)
2152 {
2153     return st->internal->nb_index_entries;
2154 }
2155
2156 const AVIndexEntry *avformat_index_get_entry(const AVStream *st, int idx)
2157 {
2158     if (idx < 0 || idx >= st->internal->nb_index_entries)
2159         return NULL;
2160
2161     return &st->internal->index_entries[idx];
2162 }
2163
2164 const AVIndexEntry *avformat_index_get_entry_from_timestamp(const AVStream *st,
2165                                                             int64_t wanted_timestamp,
2166                                                             int flags)
2167 {
2168     int idx = ff_index_search_timestamp(st->internal->index_entries,
2169                                         st->internal->nb_index_entries,
2170                                         wanted_timestamp, flags);
2171
2172     if (idx < 0)
2173         return NULL;
2174
2175     return &st->internal->index_entries[idx];
2176 }
2177
2178 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
2179                                  int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2180 {
2181     int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
2182     if (stream_index >= 0)
2183         ts = wrap_timestamp(s->streams[stream_index], ts);
2184     return ts;
2185 }
2186
2187 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
2188                          int64_t target_ts, int flags)
2189 {
2190     const AVInputFormat *avif = s->iformat;
2191     int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
2192     int64_t ts_min, ts_max, ts;
2193     int index;
2194     int64_t ret;
2195     AVStream *st;
2196
2197     if (stream_index < 0)
2198         return -1;
2199
2200     av_log(s, AV_LOG_TRACE, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2201
2202     ts_max =
2203     ts_min = AV_NOPTS_VALUE;
2204     pos_limit = -1; // GCC falsely says it may be uninitialized.
2205
2206     st = s->streams[stream_index];
2207     if (st->internal->index_entries) {
2208         AVIndexEntry *e;
2209
2210         /* FIXME: Whole function must be checked for non-keyframe entries in
2211          * index case, especially read_timestamp(). */
2212         index = av_index_search_timestamp(st, target_ts,
2213                                           flags | AVSEEK_FLAG_BACKWARD);
2214         index = FFMAX(index, 0);
2215         e     = &st->internal->index_entries[index];
2216
2217         if (e->timestamp <= target_ts || e->pos == e->min_distance) {
2218             pos_min = e->pos;
2219             ts_min  = e->timestamp;
2220             av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
2221                     pos_min, av_ts2str(ts_min));
2222         } else {
2223             av_assert1(index == 0);
2224         }
2225
2226         index = av_index_search_timestamp(st, target_ts,
2227                                           flags & ~AVSEEK_FLAG_BACKWARD);
2228         av_assert0(index < st->internal->nb_index_entries);
2229         if (index >= 0) {
2230             e = &st->internal->index_entries[index];
2231             av_assert1(e->timestamp >= target_ts);
2232             pos_max   = e->pos;
2233             ts_max    = e->timestamp;
2234             pos_limit = pos_max - e->min_distance;
2235             av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
2236                     " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
2237         }
2238     }
2239
2240     pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
2241                         ts_min, ts_max, flags, &ts, avif->read_timestamp);
2242     if (pos < 0)
2243         return -1;
2244
2245     /* do the seek */
2246     if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
2247         return ret;
2248
2249     ff_read_frame_flush(s);
2250     ff_update_cur_dts(s, st, ts);
2251
2252     return 0;
2253 }
2254
2255 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
2256                     int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2257 {
2258     int64_t step = 1024;
2259     int64_t limit, ts_max;
2260     int64_t filesize = avio_size(s->pb);
2261     int64_t pos_max  = filesize - 1;
2262     do {
2263         limit = pos_max;
2264         pos_max = FFMAX(0, (pos_max) - step);
2265         ts_max  = ff_read_timestamp(s, stream_index,
2266                                     &pos_max, limit, read_timestamp);
2267         step   += step;
2268     } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
2269     if (ts_max == AV_NOPTS_VALUE)
2270         return -1;
2271
2272     for (;;) {
2273         int64_t tmp_pos = pos_max + 1;
2274         int64_t tmp_ts  = ff_read_timestamp(s, stream_index,
2275                                             &tmp_pos, INT64_MAX, read_timestamp);
2276         if (tmp_ts == AV_NOPTS_VALUE)
2277             break;
2278         av_assert0(tmp_pos > pos_max);
2279         ts_max  = tmp_ts;
2280         pos_max = tmp_pos;
2281         if (tmp_pos >= filesize)
2282             break;
2283     }
2284
2285     if (ts)
2286         *ts = ts_max;
2287     if (pos)
2288         *pos = pos_max;
2289
2290     return 0;
2291 }
2292
2293 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
2294                       int64_t pos_min, int64_t pos_max, int64_t pos_limit,
2295                       int64_t ts_min, int64_t ts_max,
2296                       int flags, int64_t *ts_ret,
2297                       int64_t (*read_timestamp)(struct AVFormatContext *, int,
2298                                                 int64_t *, int64_t))
2299 {
2300     int64_t pos, ts;
2301     int64_t start_pos;
2302     int no_change;
2303     int ret;
2304
2305     av_log(s, AV_LOG_TRACE, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2306
2307     if (ts_min == AV_NOPTS_VALUE) {
2308         pos_min = s->internal->data_offset;
2309         ts_min  = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2310         if (ts_min == AV_NOPTS_VALUE)
2311             return -1;
2312     }
2313
2314     if (ts_min >= target_ts) {
2315         *ts_ret = ts_min;
2316         return pos_min;
2317     }
2318
2319     if (ts_max == AV_NOPTS_VALUE) {
2320         if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
2321             return ret;
2322         pos_limit = pos_max;
2323     }
2324
2325     if (ts_max <= target_ts) {
2326         *ts_ret = ts_max;
2327         return pos_max;
2328     }
2329
2330     av_assert0(ts_min < ts_max);
2331
2332     no_change = 0;
2333     while (pos_min < pos_limit) {
2334         av_log(s, AV_LOG_TRACE,
2335                 "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2336                 pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2337         av_assert0(pos_limit <= pos_max);
2338
2339         if (no_change == 0) {
2340             int64_t approximate_keyframe_distance = pos_max - pos_limit;
2341             // interpolate position (better than dichotomy)
2342             pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
2343                              ts_max - ts_min) +
2344                   pos_min - approximate_keyframe_distance;
2345         } else if (no_change == 1) {
2346             // bisection if interpolation did not change min / max pos last time
2347             pos = (pos_min + pos_limit) >> 1;
2348         } else {
2349             /* linear search if bisection failed, can only happen if there
2350              * are very few or no keyframes between min/max */
2351             pos = pos_min;
2352         }
2353         if (pos <= pos_min)
2354             pos = pos_min + 1;
2355         else if (pos > pos_limit)
2356             pos = pos_limit;
2357         start_pos = pos;
2358
2359         // May pass pos_limit instead of -1.
2360         ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2361         if (pos == pos_max)
2362             no_change++;
2363         else
2364             no_change = 0;
2365         av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2366                 " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2367                 pos_min, pos, pos_max,
2368                 av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2369                 pos_limit, start_pos, no_change);
2370         if (ts == AV_NOPTS_VALUE) {
2371             av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
2372             return -1;
2373         }
2374         if (target_ts <= ts) {
2375             pos_limit = start_pos - 1;
2376             pos_max   = pos;
2377             ts_max    = ts;
2378         }
2379         if (target_ts >= ts) {
2380             pos_min = pos;
2381             ts_min  = ts;
2382         }
2383     }
2384
2385     pos     = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
2386     ts      = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min  : ts_max;
2387 #if 0
2388     pos_min = pos;
2389     ts_min  = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2390     pos_min++;
2391     ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2392     av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2393             pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2394 #endif
2395     *ts_ret = ts;
2396     return pos;
2397 }
2398
2399 static int seek_frame_byte(AVFormatContext *s, int stream_index,
2400                            int64_t pos, int flags)
2401 {
2402     int64_t pos_min, pos_max;
2403
2404     pos_min = s->internal->data_offset;
2405     pos_max = avio_size(s->pb) - 1;
2406
2407     if (pos < pos_min)
2408         pos = pos_min;
2409     else if (pos > pos_max)
2410         pos = pos_max;
2411
2412     avio_seek(s->pb, pos, SEEK_SET);
2413
2414     s->io_repositioned = 1;
2415
2416     return 0;
2417 }
2418
2419 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2420                               int64_t timestamp, int flags)
2421 {
2422     int index;
2423     int64_t ret;
2424     AVStream *st;
2425     AVIndexEntry *ie;
2426
2427     st = s->streams[stream_index];
2428
2429     index = av_index_search_timestamp(st, timestamp, flags);
2430
2431     if (index < 0 && st->internal->nb_index_entries &&
2432         timestamp < st->internal->index_entries[0].timestamp)
2433         return -1;
2434
2435     if (index < 0 || index == st->internal->nb_index_entries - 1) {
2436         AVPacket *pkt = s->internal->pkt;
2437         int nonkey = 0;
2438
2439         if (st->internal->nb_index_entries) {
2440             av_assert0(st->internal->index_entries);
2441             ie = &st->internal->index_entries[st->internal->nb_index_entries - 1];
2442             if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2443                 return ret;
2444             ff_update_cur_dts(s, st, ie->timestamp);
2445         } else {
2446             if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
2447                 return ret;
2448         }
2449         av_packet_unref(pkt);
2450         for (;;) {
2451             int read_status;
2452             do {
2453                 read_status = av_read_frame(s, pkt);
2454             } while (read_status == AVERROR(EAGAIN));
2455             if (read_status < 0)
2456                 break;
2457             if (stream_index == pkt->stream_index && pkt->dts > timestamp) {
2458                 if (pkt->flags & AV_PKT_FLAG_KEY) {
2459                     av_packet_unref(pkt);
2460                     break;
2461                 }
2462                 if (nonkey++ > 1000 && st->codecpar->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2463                     av_log(s, AV_LOG_ERROR,"seek_frame_generic failed as this stream seems to contain no keyframes after the target timestamp, %d non keyframes found\n", nonkey);
2464                     av_packet_unref(pkt);
2465                     break;
2466                 }
2467             }
2468             av_packet_unref(pkt);
2469         }
2470         index = av_index_search_timestamp(st, timestamp, flags);
2471     }
2472     if (index < 0)
2473         return -1;
2474
2475     ff_read_frame_flush(s);
2476     if (s->iformat->read_seek)
2477         if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2478             return 0;
2479     ie = &st->internal->index_entries[index];
2480     if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2481         return ret;
2482     ff_update_cur_dts(s, st, ie->timestamp);
2483
2484     return 0;
2485 }
2486
2487 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2488                                int64_t timestamp, int flags)
2489 {
2490     int ret;
2491     AVStream *st;
2492
2493     if (flags & AVSEEK_FLAG_BYTE) {
2494         if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2495             return -1;
2496         ff_read_frame_flush(s);
2497         return seek_frame_byte(s, stream_index, timestamp, flags);
2498     }
2499
2500     if (stream_index < 0) {
2501         stream_index = av_find_default_stream_index(s);
2502         if (stream_index < 0)
2503             return -1;
2504
2505         st = s->streams[stream_index];
2506         /* timestamp for default must be expressed in AV_TIME_BASE units */
2507         timestamp = av_rescale(timestamp, st->time_base.den,
2508                                AV_TIME_BASE * (int64_t) st->time_base.num);
2509     }
2510
2511     /* first, we try the format specific seek */
2512     if (s->iformat->read_seek) {
2513         ff_read_frame_flush(s);
2514         ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2515     } else
2516         ret = -1;
2517     if (ret >= 0)
2518         return 0;
2519
2520     if (s->iformat->read_timestamp &&
2521         !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2522         ff_read_frame_flush(s);
2523         return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2524     } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2525         ff_read_frame_flush(s);
2526         return seek_frame_generic(s, stream_index, timestamp, flags);
2527     } else
2528         return -1;
2529 }
2530
2531 int av_seek_frame(AVFormatContext *s, int stream_index,
2532                   int64_t timestamp, int flags)
2533 {
2534     int ret;
2535
2536     if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2537         int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2538         if ((flags & AVSEEK_FLAG_BACKWARD))
2539             max_ts = timestamp;
2540         else
2541             min_ts = timestamp;
2542         return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2543                                   flags & ~AVSEEK_FLAG_BACKWARD);
2544     }
2545
2546     ret = seek_frame_internal(s, stream_index, timestamp, flags);
2547
2548     if (ret >= 0)
2549         ret = avformat_queue_attached_pictures(s);
2550
2551     return ret;
2552 }
2553
2554 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2555                        int64_t ts, int64_t max_ts, int flags)
2556 {
2557     if (min_ts > ts || max_ts < ts)
2558         return -1;
2559     if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2560         return AVERROR(EINVAL);
2561
2562     if (s->seek2any>0)
2563         flags |= AVSEEK_FLAG_ANY;
2564     flags &= ~AVSEEK_FLAG_BACKWARD;
2565
2566     if (s->iformat->read_seek2) {
2567         int ret;
2568         ff_read_frame_flush(s);
2569
2570         if (stream_index == -1 && s->nb_streams == 1) {
2571             AVRational time_base = s->streams[0]->time_base;
2572             ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2573             min_ts = av_rescale_rnd(min_ts, time_base.den,
2574                                     time_base.num * (int64_t)AV_TIME_BASE,
2575                                     AV_ROUND_UP   | AV_ROUND_PASS_MINMAX);
2576             max_ts = av_rescale_rnd(max_ts, time_base.den,
2577                                     time_base.num * (int64_t)AV_TIME_BASE,
2578                                     AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2579             stream_index = 0;
2580         }
2581
2582         ret = s->iformat->read_seek2(s, stream_index, min_ts,
2583                                      ts, max_ts, flags);
2584
2585         if (ret >= 0)
2586             ret = avformat_queue_attached_pictures(s);
2587         return ret;
2588     }
2589
2590     if (s->iformat->read_timestamp) {
2591         // try to seek via read_timestamp()
2592     }
2593
2594     // Fall back on old API if new is not implemented but old is.
2595     // Note the old API has somewhat different semantics.
2596     if (s->iformat->read_seek || 1) {
2597         int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2598         int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2599         if (ret<0 && ts != min_ts && max_ts != ts) {
2600             ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2601             if (ret >= 0)
2602                 ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2603         }
2604         return ret;
2605     }
2606
2607     // try some generic seek like seek_frame_generic() but with new ts semantics
2608     return -1; //unreachable
2609 }
2610
2611 int avformat_flush(AVFormatContext *s)
2612 {
2613     ff_read_frame_flush(s);
2614     return 0;
2615 }
2616
2617 /*******************************************************/
2618
2619 /**
2620  * Return TRUE if the stream has accurate duration in any stream.
2621  *
2622  * @return TRUE if the stream has accurate duration for at least one component.
2623  */
2624 static int has_duration(AVFormatContext *ic)
2625 {
2626     int i;
2627     AVStream *st;
2628
2629     for (i = 0; i < ic->nb_streams; i++) {
2630         st = ic->streams[i];
2631         if (st->duration != AV_NOPTS_VALUE)
2632             return 1;
2633     }
2634     if (ic->duration != AV_NOPTS_VALUE)
2635         return 1;
2636     return 0;
2637 }
2638
2639 /**
2640  * Estimate the stream timings from the one of each components.
2641  *
2642  * Also computes the global bitrate if possible.
2643  */
2644 static void update_stream_timings(AVFormatContext *ic)
2645 {
2646     int64_t start_time, start_time1, start_time_text, end_time, end_time1, end_time_text;
2647     int64_t duration, duration1, duration_text, filesize;
2648     int i;
2649     AVProgram *p;
2650
2651     start_time = INT64_MAX;
2652     start_time_text = INT64_MAX;
2653     end_time   = INT64_MIN;
2654     end_time_text   = INT64_MIN;
2655     duration   = INT64_MIN;
2656     duration_text = INT64_MIN;
2657
2658     for (i = 0; i < ic->nb_streams; i++) {
2659         AVStream *st = ic->streams[i];
2660         int is_text = st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ||
2661                       st->codecpar->codec_type == AVMEDIA_TYPE_DATA;
2662         if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2663             start_time1 = av_rescale_q(st->start_time, st->time_base,
2664                                        AV_TIME_BASE_Q);
2665             if (is_text)
2666                 start_time_text = FFMIN(start_time_text, start_time1);
2667             else
2668                 start_time = FFMIN(start_time, start_time1);
2669             end_time1 = av_rescale_q_rnd(st->duration, st->time_base,
2670                                          AV_TIME_BASE_Q,
2671                                          AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
2672             if (end_time1 != AV_NOPTS_VALUE && (end_time1 > 0 ? start_time1 <= INT64_MAX - end_time1 : start_time1 >= INT64_MIN - end_time1)) {
2673                 end_time1 += start_time1;
2674                 if (is_text)
2675                     end_time_text = FFMAX(end_time_text, end_time1);
2676                 else
2677                     end_time = FFMAX(end_time, end_time1);
2678             }
2679             for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2680                 if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2681                     p->start_time = start_time1;
2682                 if (p->end_time < end_time1)
2683                     p->end_time = end_time1;
2684             }
2685         }
2686         if (st->duration != AV_NOPTS_VALUE) {
2687             duration1 = av_rescale_q(st->duration, st->time_base,
2688                                      AV_TIME_BASE_Q);
2689             if (is_text)
2690                 duration_text = FFMAX(duration_text, duration1);
2691             else
2692                 duration = FFMAX(duration, duration1);
2693         }
2694     }
2695     if (start_time == INT64_MAX || (start_time > start_time_text && start_time - (uint64_t)start_time_text < AV_TIME_BASE))
2696         start_time = start_time_text;
2697     else if (start_time > start_time_text)
2698         av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2699
2700     if (end_time == INT64_MIN || (end_time < end_time_text && end_time_text - (uint64_t)end_time < AV_TIME_BASE))
2701         end_time = end_time_text;
2702     else if (end_time < end_time_text)
2703         av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream endtime %f\n", end_time_text / (float)AV_TIME_BASE);
2704
2705      if (duration == INT64_MIN || (duration < duration_text && duration_text - duration < AV_TIME_BASE))
2706          duration = duration_text;
2707      else if (duration < duration_text)
2708          av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream duration %f\n", duration_text / (float)AV_TIME_BASE);
2709
2710     if (start_time != INT64_MAX) {
2711         ic->start_time = start_time;
2712         if (end_time != INT64_MIN) {
2713             if (ic->nb_programs > 1) {
2714                 for (i = 0; i < ic->nb_programs; i++) {
2715                     p = ic->programs[i];
2716                     if (p->start_time != AV_NOPTS_VALUE &&
2717                         p->end_time > p->start_time &&
2718                         p->end_time - (uint64_t)p->start_time <= INT64_MAX)
2719                         duration = FFMAX(duration, p->end_time - p->start_time);
2720                 }
2721             } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) {
2722                 duration = FFMAX(duration, end_time - start_time);
2723             }
2724         }
2725     }
2726     if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2727         ic->duration = duration;
2728     }
2729     if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) {
2730         /* compute the bitrate */
2731         double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2732                          (double) ic->duration;
2733         if (bitrate >= 0 && bitrate <= INT64_MAX)
2734             ic->bit_rate = bitrate;
2735     }
2736 }
2737
2738 static void fill_all_stream_timings(AVFormatContext *ic)
2739 {
2740     int i;
2741     AVStream *st;
2742
2743     update_stream_timings(ic);
2744     for (i = 0; i < ic->nb_streams; i++) {
2745         st = ic->streams[i];
2746         if (st->start_time == AV_NOPTS_VALUE) {
2747             if (ic->start_time != AV_NOPTS_VALUE)
2748                 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
2749                                               st->time_base);
2750             if (ic->duration != AV_NOPTS_VALUE)
2751                 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
2752                                             st->time_base);
2753         }
2754     }
2755 }
2756
2757 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2758 {
2759     int64_t filesize, duration;
2760     int i, show_warning = 0;
2761     AVStream *st;
2762
2763     /* if bit_rate is already set, we believe it */
2764     if (ic->bit_rate <= 0) {
2765         int64_t bit_rate = 0;
2766         for (i = 0; i < ic->nb_streams; i++) {
2767             st = ic->streams[i];
2768             if (st->codecpar->bit_rate <= 0 && st->internal->avctx->bit_rate > 0)
2769                 st->codecpar->bit_rate = st->internal->avctx->bit_rate;
2770             if (st->codecpar->bit_rate > 0) {
2771                 if (INT64_MAX - st->codecpar->bit_rate < bit_rate) {
2772                     bit_rate = 0;
2773                     break;
2774                 }
2775                 bit_rate += st->codecpar->bit_rate;
2776             } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 1) {
2777                 // If we have a videostream with packets but without a bitrate
2778                 // then consider the sum not known
2779                 bit_rate = 0;
2780                 break;
2781             }
2782         }
2783         ic->bit_rate = bit_rate;
2784     }
2785
2786     /* if duration is already set, we believe it */
2787     if (ic->duration == AV_NOPTS_VALUE &&
2788         ic->bit_rate != 0) {
2789         filesize = ic->pb ? avio_size(ic->pb) : 0;
2790         if (filesize > ic->internal->data_offset) {
2791             filesize -= ic->internal->data_offset;
2792             for (i = 0; i < ic->nb_streams; i++) {
2793                 st      = ic->streams[i];
2794                 if (   st->time_base.num <= INT64_MAX / ic->bit_rate
2795                     && st->duration == AV_NOPTS_VALUE) {
2796                     duration = av_rescale(filesize, 8LL * st->time_base.den,
2797                                           ic->bit_rate *
2798                                           (int64_t) st->time_base.num);
2799                     st->duration = duration;
2800                     show_warning = 1;
2801                 }
2802             }
2803         }
2804     }
2805     if (show_warning)
2806         av_log(ic, AV_LOG_WARNING,
2807                "Estimating duration from bitrate, this may be inaccurate\n");
2808 }
2809
2810 #define DURATION_MAX_READ_SIZE 250000LL
2811 #define DURATION_MAX_RETRY 6
2812
2813 /* only usable for MPEG-PS streams */
2814 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2815 {
2816     AVPacket *pkt = ic->internal->pkt;
2817     AVStream *st;
2818     int num, den, read_size, i, ret;
2819     int found_duration = 0;
2820     int is_end;
2821     int64_t filesize, offset, duration;
2822     int retry = 0;
2823
2824     /* flush packet queue */
2825     flush_packet_queue(ic);
2826
2827     for (i = 0; i < ic->nb_streams; i++) {
2828         st = ic->streams[i];
2829         if (st->start_time == AV_NOPTS_VALUE &&
2830             st->first_dts == AV_NOPTS_VALUE &&
2831             st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN)
2832             av_log(ic, AV_LOG_WARNING,
2833                    "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2834
2835         if (st->parser) {
2836             av_parser_close(st->parser);
2837             st->parser = NULL;
2838         }
2839     }
2840
2841     if (ic->skip_estimate_duration_from_pts) {
2842         av_log(ic, AV_LOG_INFO, "Skipping duration calculation in estimate_timings_from_pts\n");
2843         goto skip_duration_calc;
2844     }
2845
2846     av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2847     /* estimate the end time (duration) */
2848     /* XXX: may need to support wrapping */
2849     filesize = ic->pb ? avio_size(ic->pb) : 0;
2850     do {
2851         is_end = found_duration;
2852         offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2853         if (offset < 0)
2854             offset = 0;
2855
2856         avio_seek(ic->pb, offset, SEEK_SET);
2857         read_size = 0;
2858         for (;;) {
2859             if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2860                 break;
2861
2862             do {
2863                 ret = ff_read_packet(ic, pkt);
2864             } while (ret == AVERROR(EAGAIN));
2865             if (ret != 0)
2866                 break;
2867             read_size += pkt->size;
2868             st         = ic->streams[pkt->stream_index];
2869             if (pkt->pts != AV_NOPTS_VALUE &&
2870                 (st->start_time != AV_NOPTS_VALUE ||
2871                  st->first_dts  != AV_NOPTS_VALUE)) {
2872                 if (pkt->duration == 0) {
2873                     ff_compute_frame_duration(ic, &num, &den, st, st->parser, pkt);
2874                     if (den && num) {
2875                         pkt->duration = av_rescale_rnd(1,
2876                                            num * (int64_t) st->time_base.den,
2877                                            den * (int64_t) st->time_base.num,
2878                                            AV_ROUND_DOWN);
2879                     }
2880                 }
2881                 duration = pkt->pts + pkt->duration;
2882                 found_duration = 1;
2883                 if (st->start_time != AV_NOPTS_VALUE)
2884                     duration -= st->start_time;
2885                 else
2886                     duration -= st->first_dts;
2887                 if (duration > 0) {
2888                     if (st->duration == AV_NOPTS_VALUE || st->internal->info->last_duration<= 0 ||
2889                         (st->duration < duration && FFABS(duration - st->internal->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2890                         st->duration = duration;
2891                     st->internal->info->last_duration = duration;
2892                 }
2893             }
2894             av_packet_unref(pkt);
2895         }
2896
2897         /* check if all audio/video streams have valid duration */
2898         if (!is_end) {
2899             is_end = 1;
2900             for (i = 0; i < ic->nb_streams; i++) {
2901                 st = ic->streams[i];
2902                 switch (st->codecpar->codec_type) {
2903                     case AVMEDIA_TYPE_VIDEO:
2904                     case AVMEDIA_TYPE_AUDIO:
2905                         if (st->duration == AV_NOPTS_VALUE)
2906                             is_end = 0;
2907                 }
2908             }
2909         }
2910     } while (!is_end &&
2911              offset &&
2912              ++retry <= DURATION_MAX_RETRY);
2913
2914     av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);
2915
2916     /* warn about audio/video streams which duration could not be estimated */
2917     for (i = 0; i < ic->nb_streams; i++) {
2918         st = ic->streams[i];
2919         if (st->duration == AV_NOPTS_VALUE) {
2920             switch (st->codecpar->codec_type) {
2921             case AVMEDIA_TYPE_VIDEO:
2922             case AVMEDIA_TYPE_AUDIO:
2923                 if (st->start_time != AV_NOPTS_VALUE || st->first_dts  != AV_NOPTS_VALUE) {
2924                     av_log(ic, AV_LOG_WARNING, "stream %d : no PTS found at end of file, duration not set\n", i);
2925                 } else
2926                     av_log(ic, AV_LOG_WARNING, "stream %d : no TS found at start of file, duration not set\n", i);
2927             }
2928         }
2929     }
2930 skip_duration_calc:
2931     fill_all_stream_timings(ic);
2932
2933     avio_seek(ic->pb, old_offset, SEEK_SET);
2934     for (i = 0; i < ic->nb_streams; i++) {
2935         int j;
2936
2937         st              = ic->streams[i];
2938         st->cur_dts     = st->first_dts;
2939         st->last_IP_pts = AV_NOPTS_VALUE;
2940         st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
2941         for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2942             st->internal->pts_buffer[j] = AV_NOPTS_VALUE;
2943     }
2944 }
2945
2946 /* 1:1 map to AVDurationEstimationMethod */
2947 static const char *const duration_name[] = {
2948     [AVFMT_DURATION_FROM_PTS]     = "pts",
2949     [AVFMT_DURATION_FROM_STREAM]  = "stream",
2950     [AVFMT_DURATION_FROM_BITRATE] = "bit rate",
2951 };
2952
2953 static const char *duration_estimate_name(enum AVDurationEstimationMethod method)
2954 {
2955     return duration_name[method];
2956 }
2957
2958 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2959 {
2960     int64_t file_size;
2961
2962     /* get the file size, if possible */
2963     if (ic->iformat->flags & AVFMT_NOFILE) {
2964         file_size = 0;
2965     } else {
2966         file_size = avio_size(ic->pb);
2967         file_size = FFMAX(0, file_size);
2968     }
2969
2970     if ((!strcmp(ic->iformat->name, "mpeg") ||
2971          !strcmp(ic->iformat->name, "mpegts")) &&
2972         file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
2973         /* get accurate estimate from the PTSes */
2974         estimate_timings_from_pts(ic, old_offset);
2975         ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2976     } else if (has_duration(ic)) {
2977         /* at least one component has timings - we use them for all
2978          * the components */
2979         fill_all_stream_timings(ic);
2980         /* nut demuxer estimate the duration from PTS */
2981         if(!strcmp(ic->iformat->name, "nut"))
2982             ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2983         else
2984             ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2985     } else {
2986         /* less precise: use bitrate info */
2987         estimate_timings_from_bit_rate(ic);
2988         ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2989     }
2990     update_stream_timings(ic);
2991
2992     for (unsigned i = 0; i < ic->nb_streams; i++) {
2993         AVStream *st = ic->streams[i];
2994         if (st->time_base.den)
2995             av_log(ic, AV_LOG_TRACE, "stream %u: start_time: %s duration: %s\n", i,
2996                    av_ts2timestr(st->start_time, &st->time_base),
2997                    av_ts2timestr(st->duration, &st->time_base));
2998     }
2999     av_log(ic, AV_LOG_TRACE,
3000            "format: start_time: %s duration: %s (estimate from %s) bitrate=%"PRId64" kb/s\n",
3001            av_ts2timestr(ic->start_time, &AV_TIME_BASE_Q),
3002            av_ts2timestr(ic->duration, &AV_TIME_BASE_Q),
3003            duration_estimate_name(ic->duration_estimation_method),
3004            (int64_t)ic->bit_rate / 1000);
3005 }
3006
3007 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
3008 {
3009     AVCodecContext *avctx = st->internal->avctx;
3010
3011 #define FAIL(errmsg) do {                                         \
3012         if (errmsg_ptr)                                           \
3013             *errmsg_ptr = errmsg;                                 \
3014         return 0;                                                 \
3015     } while (0)
3016
3017     if (   avctx->codec_id == AV_CODEC_ID_NONE
3018         && avctx->codec_type != AVMEDIA_TYPE_DATA)
3019         FAIL("unknown codec");
3020     switch (avctx->codec_type) {
3021     case AVMEDIA_TYPE_AUDIO:
3022         if (!avctx->frame_size && determinable_frame_size(avctx))
3023             FAIL("unspecified frame size");
3024         if (st->internal->info->found_decoder >= 0 &&
3025             avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
3026             FAIL("unspecified sample format");
3027         if (!avctx->sample_rate)
3028             FAIL("unspecified sample rate");
3029         if (!avctx->channels)
3030             FAIL("unspecified number of channels");
3031         if (st->internal->info->found_decoder >= 0 && !st->internal->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
3032             FAIL("no decodable DTS frames");
3033         break;
3034     case AVMEDIA_TYPE_VIDEO:
3035         if (!avctx->width)
3036             FAIL("unspecified size");
3037         if (st->internal->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
3038             FAIL("unspecified pixel format");
3039         if (st->codecpar->codec_id == AV_CODEC_ID_RV30 || st->codecpar->codec_id == AV_CODEC_ID_RV40)
3040             if (!st->sample_aspect_ratio.num && !st->codecpar->sample_aspect_ratio.num && !st->codec_info_nb_frames)
3041                 FAIL("no frame in rv30/40 and no sar");
3042         break;
3043     case AVMEDIA_TYPE_SUBTITLE:
3044         if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
3045             FAIL("unspecified size");
3046         break;
3047     case AVMEDIA_TYPE_DATA:
3048         if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
3049     }
3050
3051     return 1;
3052 }
3053
3054 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
3055 static int try_decode_frame(AVFormatContext *s, AVStream *st,
3056                             const AVPacket *avpkt, AVDictionary **options)
3057 {
3058     AVCodecContext *avctx = st->internal->avctx;
3059     const AVCodec *codec;
3060     int got_picture = 1, ret = 0;
3061     AVFrame *frame = av_frame_alloc();
3062     AVSubtitle subtitle;
3063     AVPacket pkt = *avpkt;
3064     int do_skip_frame = 0;
3065     enum AVDiscard skip_frame;
3066
3067     if (!frame)
3068         return AVERROR(ENOMEM);
3069
3070     if (!avcodec_is_open(avctx) &&
3071         st->internal->info->found_decoder <= 0 &&
3072         (st->codecpar->codec_id != -st->internal->info->found_decoder || !st->codecpar->codec_id)) {
3073         AVDictionary *thread_opt = NULL;
3074
3075         codec = find_probe_decoder(s, st, st->codecpar->codec_id);
3076
3077         if (!codec) {
3078             st->internal->info->found_decoder = -st->codecpar->codec_id;
3079             ret                     = -1;
3080             goto fail;
3081         }
3082
3083         /* Force thread count to 1 since the H.264 decoder will not extract
3084          * SPS and PPS to extradata during multi-threaded decoding. */
3085         av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
3086         /* Force lowres to 0. The decoder might reduce the video size by the
3087          * lowres factor, and we don't want that propagated to the stream's
3088          * codecpar */
3089         av_dict_set(options ? options : &thread_opt, "lowres", "0", 0);
3090         if (s->codec_whitelist)
3091             av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
3092         ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
3093         if (!options)
3094             av_dict_free(&thread_opt);
3095         if (ret < 0) {
3096             st->internal->info->found_decoder = -avctx->codec_id;
3097             goto fail;
3098         }
3099         st->internal->info->found_decoder = 1;
3100     } else if (!st->internal->info->found_decoder)
3101         st->internal->info->found_decoder = 1;
3102
3103     if (st->internal->info->found_decoder < 0) {
3104         ret = -1;
3105         goto fail;
3106     }
3107
3108     if (avpriv_codec_get_cap_skip_frame_fill_param(avctx->codec)) {
3109         do_skip_frame = 1;
3110         skip_frame = avctx->skip_frame;
3111         avctx->skip_frame = AVDISCARD_ALL;
3112     }
3113
3114     while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
3115            ret >= 0 &&
3116            (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
3117             (!st->codec_info_nb_frames &&
3118              (avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
3119         got_picture = 0;
3120         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3121             avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
3122             ret = avcodec_send_packet(avctx, &pkt);
3123             if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3124                 break;
3125             if (ret >= 0)
3126                 pkt.size = 0;
3127             ret = avcodec_receive_frame(avctx, frame);
3128             if (ret >= 0)
3129                 got_picture = 1;
3130             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
3131                 ret = 0;
3132         } else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3133             ret = avcodec_decode_subtitle2(avctx, &subtitle,
3134                                            &got_picture, &pkt);
3135             if (got_picture)
3136                 avsubtitle_free(&subtitle);
3137             if (ret >= 0)
3138                 pkt.size = 0;
3139         }
3140         if (ret >= 0) {
3141             if (got_picture)
3142                 st->internal->nb_decoded_frames++;
3143             ret       = got_picture;
3144         }
3145     }
3146
3147     if (!pkt.data && !got_picture)
3148         ret = -1;
3149
3150 fail:
3151     if (do_skip_frame) {
3152         avctx->skip_frame = skip_frame;
3153     }
3154
3155     av_frame_free(&frame);
3156     return ret;
3157 }
3158
3159 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
3160 {
3161     while (tags->id != AV_CODEC_ID_NONE) {
3162         if (tags->id == id)
3163             return tags->tag;
3164         tags++;
3165     }
3166     return 0;
3167 }
3168
3169 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
3170 {
3171     int i;
3172     for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3173         if (tag == tags[i].tag)
3174             return tags[i].id;
3175     for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3176         if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
3177             return tags[i].id;
3178     return AV_CODEC_ID_NONE;
3179 }
3180
3181 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
3182 {
3183     if (bps <= 0 || bps > 64)
3184         return AV_CODEC_ID_NONE;
3185
3186     if (flt) {
3187         switch (bps) {
3188         case 32:
3189             return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
3190         case 64:
3191             return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
3192         default:
3193             return AV_CODEC_ID_NONE;
3194         }
3195     } else {
3196         bps  += 7;
3197         bps >>= 3;
3198         if (sflags & (1 << (bps - 1))) {
3199             switch (bps) {
3200             case 1:
3201                 return AV_CODEC_ID_PCM_S8;
3202             case 2:
3203                 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
3204             case 3:
3205                 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
3206             case 4:
3207                 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
3208             case 8:
3209                 return be ? AV_CODEC_ID_PCM_S64BE : AV_CODEC_ID_PCM_S64LE;
3210             default:
3211                 return AV_CODEC_ID_NONE;
3212             }
3213         } else {
3214             switch (bps) {
3215             case 1:
3216                 return AV_CODEC_ID_PCM_U8;
3217             case 2:
3218                 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
3219             case 3:
3220                 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
3221             case 4:
3222                 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
3223             default:
3224                 return AV_CODEC_ID_NONE;
3225             }
3226         }
3227     }
3228 }
3229
3230 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
3231 {
3232     unsigned int tag;
3233     if (!av_codec_get_tag2(tags, id, &tag))
3234         return 0;
3235     return tag;
3236 }
3237
3238 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
3239                       unsigned int *tag)
3240 {
3241     int i;
3242     for (i = 0; tags && tags[i]; i++) {
3243         const AVCodecTag *codec_tags = tags[i];
3244         while (codec_tags->id != AV_CODEC_ID_NONE) {
3245             if (codec_tags->id == id) {
3246                 *tag = codec_tags->tag;
3247                 return 1;
3248             }
3249             codec_tags++;
3250         }
3251     }
3252     return 0;
3253 }
3254
3255 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
3256 {
3257     int i;
3258     for (i = 0; tags && tags[i]; i++) {
3259         enum AVCodecID id = ff_codec_get_id(tags[i], tag);
3260         if (id != AV_CODEC_ID_NONE)
3261             return id;
3262     }
3263     return AV_CODEC_ID_NONE;
3264 }
3265
3266 static int chapter_start_cmp(const void *p1, const void *p2)
3267 {
3268     AVChapter *ch1 = *(AVChapter**)p1;
3269     AVChapter *ch2 = *(AVChapter**)p2;
3270     int delta = av_compare_ts(ch1->start, ch1->time_base, ch2->start, ch2->time_base);
3271     if (delta)
3272         return delta;
3273     return (ch1 > ch2) - (ch1 < ch2);
3274 }
3275
3276 static int compute_chapters_end(AVFormatContext *s)
3277 {
3278     unsigned int i;
3279     int64_t max_time = 0;
3280     AVChapter **timetable = av_malloc(s->nb_chapters * sizeof(*timetable));
3281
3282     if (!timetable)
3283         return AVERROR(ENOMEM);
3284
3285     if (s->duration > 0 && s->start_time < INT64_MAX - s->duration)
3286         max_time = s->duration +
3287                        ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
3288
3289     for (i = 0; i < s->nb_chapters; i++)
3290         timetable[i] = s->chapters[i];
3291     qsort(timetable, s->nb_chapters, sizeof(*timetable), chapter_start_cmp);
3292
3293     for (i = 0; i < s->nb_chapters; i++)
3294         if (timetable[i]->end == AV_NOPTS_VALUE) {
3295             AVChapter *ch = timetable[i];
3296             int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
3297                                                 ch->time_base)
3298                                 : INT64_MAX;
3299
3300             if (i + 1 < s->nb_chapters) {
3301                 AVChapter *ch1     = timetable[i + 1];
3302                 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
3303                                                 ch->time_base);
3304                 if (next_start > ch->start && next_start < end)
3305                     end = next_start;
3306             }
3307             ch->end = (end == INT64_MAX || end < ch->start) ? ch->start : end;
3308         }
3309     av_free(timetable);
3310     return 0;
3311 }
3312
3313 static int get_std_framerate(int i)
3314 {
3315     if (i < 30*12)
3316         return (i + 1) * 1001;
3317     i -= 30*12;
3318
3319     if (i < 30)
3320         return (i + 31) * 1001 * 12;
3321     i -= 30;
3322
3323     if (i < 3)
3324         return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;
3325
3326     i -= 3;
3327
3328     return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
3329 }
3330
3331 /* Is the time base unreliable?
3332  * This is a heuristic to balance between quick acceptance of the values in
3333  * the headers vs. some extra checks.
3334  * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
3335  * MPEG-2 commonly misuses field repeat flags to store different framerates.
3336  * And there are "variable" fps files this needs to detect as well. */
3337 static int tb_unreliable(AVCodecContext *c)
3338 {
3339     if (c->time_base.den >= 101LL * c->time_base.num ||
3340         c->time_base.den <    5LL * c->time_base.num ||
3341         // c->codec_tag == AV_RL32("DIVX") ||
3342         // c->codec_tag == AV_RL32("XVID") ||
3343         c->codec_tag == AV_RL32("mp4v") ||
3344         c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
3345         c->codec_id == AV_CODEC_ID_GIF ||
3346         c->codec_id == AV_CODEC_ID_HEVC ||
3347         c->codec_id == AV_CODEC_ID_H264)
3348         return 1;
3349     return 0;
3350 }
3351
3352 int ff_alloc_extradata(AVCodecParameters *par, int size)
3353 {
3354     av_freep(&par->extradata);
3355     par->extradata_size = 0;
3356
3357     if (size < 0 || size >= INT32_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
3358         return AVERROR(EINVAL);
3359
3360     par->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
3361     if (!par->extradata)
3362         return AVERROR(ENOMEM);
3363
3364     memset(par->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3365     par->extradata_size = size;
3366
3367     return 0;
3368 }
3369
3370 int ff_get_extradata(AVFormatContext *s, AVCodecParameters *par, AVIOContext *pb, int size)
3371 {
3372     int ret = ff_alloc_extradata(par, size);
3373     if (ret < 0)
3374         return ret;
3375     ret = avio_read(pb, par->extradata, size);
3376     if (ret != size) {
3377         av_freep(&par->extradata);
3378         par->extradata_size = 0;
3379         av_log(s, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
3380         return ret < 0 ? ret : AVERROR_INVALIDDATA;
3381     }
3382
3383     return ret;
3384 }
3385
3386 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
3387 {
3388     int i, j;
3389     int64_t last = st->internal->info->last_dts;
3390
3391     if (   ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
3392        && ts - (uint64_t)last < INT64_MAX) {
3393         double dts = (is_relative(ts) ?  ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
3394         int64_t duration = ts - last;
3395
3396         if (!st->internal->info->duration_error)
3397             st->internal->info->duration_error = av_mallocz(sizeof(st->internal->info->duration_error[0])*2);
3398         if (!st->internal->info->duration_error)
3399             return AVERROR(ENOMEM);
3400
3401 //         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3402 //             av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
3403         for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3404             if (st->internal->info->duration_error[0][1][i] < 1e10) {
3405                 int framerate = get_std_framerate(i);
3406                 double sdts = dts*framerate/(1001*12);
3407                 for (j= 0; j<2; j++) {
3408                     int64_t ticks = llrint(sdts+j*0.5);
3409                     double error= sdts - ticks + j*0.5;
3410                     st->internal->info->duration_error[j][0][i] += error;
3411                     st->internal->info->duration_error[j][1][i] += error*error;
3412                 }
3413             }
3414         }
3415         if (st->internal->info->rfps_duration_sum <= INT64_MAX - duration) {
3416             st->internal->info->duration_count++;
3417             st->internal->info->rfps_duration_sum += duration;
3418         }
3419
3420         if (st->internal->info->duration_count % 10 == 0) {
3421             int n = st->internal->info->duration_count;
3422             for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3423                 if (st->internal->info->duration_error[0][1][i] < 1e10) {
3424                     double a0     = st->internal->info->duration_error[0][0][i] / n;
3425                     double error0 = st->internal->info->duration_error[0][1][i] / n - a0*a0;
3426                     double a1     = st->internal->info->duration_error[1][0][i] / n;
3427                     double error1 = st->internal->info->duration_error[1][1][i] / n - a1*a1;
3428                     if (error0 > 0.04 && error1 > 0.04) {
3429                         st->internal->info->duration_error[0][1][i] = 2e10;
3430                         st->internal->info->duration_error[1][1][i] = 2e10;
3431                     }
3432                 }
3433             }
3434         }
3435
3436         // ignore the first 4 values, they might have some random jitter
3437         if (st->internal->info->duration_count > 3 && is_relative(ts) == is_relative(last))
3438             st->internal->info->duration_gcd = av_gcd(st->internal->info->duration_gcd, duration);
3439     }
3440     if (ts != AV_NOPTS_VALUE)
3441         st->internal->info->last_dts = ts;
3442
3443     return 0;
3444 }
3445
3446 void ff_rfps_calculate(AVFormatContext *ic)
3447 {
3448     int i, j;
3449
3450     for (i = 0; i < ic->nb_streams; i++) {
3451         AVStream *st = ic->streams[i];
3452
3453         if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
3454             continue;
3455         // the check for tb_unreliable() is not completely correct, since this is not about handling
3456         // an unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3457         // ipmovie.c produces.
3458         if (tb_unreliable(st->internal->avctx) && st->internal->info->duration_count > 15 && st->internal->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num &&
3459             st->internal->info->duration_gcd < INT64_MAX / st->time_base.num)
3460             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->internal->info->duration_gcd, INT_MAX);
3461         if (st->internal->info->duration_count>1 && !st->r_frame_rate.num
3462             && tb_unreliable(st->internal->avctx)) {
3463             int num = 0;
3464             double best_error= 0.01;
3465             AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3466
3467             for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3468                 int k;
3469
3470                 if (st->internal->info->codec_info_duration &&
3471                     st->internal->info->codec_info_duration*av_q2d(st->time_base) < (1001*11.5)/get_std_framerate(j))
3472                     continue;
3473                 if (!st->internal->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3474                     continue;
3475
3476                 if (av_q2d(st->time_base) * st->internal->info->rfps_duration_sum / st->internal->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
3477                     continue;
3478
3479                 for (k= 0; k<2; k++) {
3480                     int n = st->internal->info->duration_count;
3481                     double a= st->internal->info->duration_error[k][0][j] / n;
3482                     double error= st->internal->info->duration_error[k][1][j]/n - a*a;
3483
3484                     if (error < best_error && best_error> 0.000000001) {
3485                         best_error= error;
3486                         num = get_std_framerate(j);
3487                     }
3488                     if (error < 0.02)
3489                         av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3490                 }
3491             }
3492             // do not increase frame rate by more than 1 % in order to match a standard rate.
3493             if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3494                 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3495         }
3496         if (   !st->avg_frame_rate.num
3497             && st->r_frame_rate.num && st->internal->info->rfps_duration_sum
3498             && st->internal->info->codec_info_duration <= 0
3499             && st->internal->info->duration_count > 2
3500             && fabs(1.0 / (av_q2d(st->r_frame_rate) * av_q2d(st->time_base)) - st->internal->info->rfps_duration_sum / (double)st->internal->info->duration_count) <= 1.0
3501             ) {
3502             av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3503             st->avg_frame_rate = st->r_frame_rate;
3504         }
3505
3506         av_freep(&st->internal->info->duration_error);
3507         st->internal->info->last_dts = AV_NOPTS_VALUE;
3508         st->internal->info->duration_count = 0;
3509         st->internal->info->rfps_duration_sum = 0;
3510     }
3511 }
3512
3513 static int extract_extradata_check(AVStream *st)
3514 {
3515     const AVBitStreamFilter *f;
3516
3517     f = av_bsf_get_by_name("extract_extradata");
3518     if (!f)
3519         return 0;
3520
3521     if (f->codec_ids) {
3522         const enum AVCodecID *ids;
3523         for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
3524             if (*ids == st->codecpar->codec_id)
3525                 return 1;
3526     }
3527
3528     return 0;
3529 }
3530
3531 static int extract_extradata_init(AVStream *st)
3532 {
3533     AVStreamInternal *sti = st->internal;
3534     const AVBitStreamFilter *f;
3535     int ret;
3536
3537     f = av_bsf_get_by_name("extract_extradata");
3538     if (!f)
3539         goto finish;
3540
3541     /* check that the codec id is supported */
3542     ret = extract_extradata_check(st);
3543     if (!ret)
3544         goto finish;
3545
3546     ret = av_bsf_alloc(f, &sti->extract_extradata.bsf);
3547     if (ret < 0)
3548         return ret;
3549
3550     ret = avcodec_parameters_copy(sti->extract_extradata.bsf->par_in,
3551                                   st->codecpar);
3552     if (ret < 0)
3553         goto fail;
3554
3555     sti->extract_extradata.bsf->time_base_in = st->time_base;
3556
3557     ret = av_bsf_init(sti->extract_extradata.bsf);
3558     if (ret < 0)
3559         goto fail;
3560
3561 finish:
3562     sti->extract_extradata.inited = 1;
3563
3564     return 0;
3565 fail:
3566     av_bsf_free(&sti->extract_extradata.bsf);
3567     return ret;
3568 }
3569
3570 static int extract_extradata(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
3571 {
3572     AVStreamInternal *sti = st->internal;
3573     AVPacket *pkt_ref = s->internal->parse_pkt;
3574     int ret;
3575
3576     if (!sti->extract_extradata.inited) {
3577         ret = extract_extradata_init(st);
3578         if (ret < 0)
3579             return ret;
3580     }
3581
3582     if (sti->extract_extradata.inited && !sti->extract_extradata.bsf)
3583         return 0;
3584
3585     ret = av_packet_ref(pkt_ref, pkt);
3586     if (ret < 0)
3587         return ret;
3588
3589     ret = av_bsf_send_packet(sti->extract_extradata.bsf, pkt_ref);
3590     if (ret < 0) {
3591         av_packet_unref(pkt_ref);
3592         return ret;
3593     }
3594
3595     while (ret >= 0 && !sti->avctx->extradata) {
3596         ret = av_bsf_receive_packet(sti->extract_extradata.bsf, pkt_ref);
3597         if (ret < 0) {
3598             if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3599                 return ret;
3600             continue;
3601         }
3602
3603         for (int i = 0; i < pkt_ref->side_data_elems; i++) {
3604             AVPacketSideData *side_data = &pkt_ref->side_data[i];
3605             if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) {
3606                 sti->avctx->extradata      = side_data->data;
3607                 sti->avctx->extradata_size = side_data->size;
3608                 side_data->data = NULL;
3609                 side_data->size = 0;
3610                 break;
3611             }
3612         }
3613         av_packet_unref(pkt_ref);
3614     }
3615
3616     return 0;
3617 }
3618
3619 static int add_coded_side_data(AVStream *st, AVCodecContext *avctx)
3620 {
3621     int i;
3622
3623     for (i = 0; i < avctx->nb_coded_side_data; i++) {
3624         const AVPacketSideData *sd_src = &avctx->coded_side_data[i];
3625         uint8_t *dst_data;
3626         dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
3627         if (!dst_data)
3628             return AVERROR(ENOMEM);
3629         memcpy(dst_data, sd_src->data, sd_src->size);
3630     }
3631     return 0;
3632 }
3633
3634 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3635 {
3636     int i, count = 0, ret = 0, j;
3637     int64_t read_size;
3638     AVStream *st;
3639     AVCodecContext *avctx;
3640     AVPacket *pkt1 = ic->internal->pkt;
3641     int64_t old_offset  = avio_tell(ic->pb);
3642     // new streams might appear, no options for those
3643     int orig_nb_streams = ic->nb_streams;
3644     int flush_codecs;
3645     int64_t max_analyze_duration = ic->max_analyze_duration;
3646     int64_t max_stream_analyze_duration;
3647     int64_t max_subtitle_analyze_duration;
3648     int64_t probesize = ic->probesize;
3649     int eof_reached = 0;
3650     int *missing_streams = av_opt_ptr(ic->iformat->priv_class, ic->priv_data, "missing_streams");
3651
3652     flush_codecs = probesize > 0;
3653
3654     av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3655
3656     max_stream_analyze_duration = max_analyze_duration;
3657     max_subtitle_analyze_duration = max_analyze_duration;
3658     if (!max_analyze_duration) {
3659         max_stream_analyze_duration =
3660         max_analyze_duration        = 5*AV_TIME_BASE;
3661         max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3662         if (!strcmp(ic->iformat->name, "flv"))
3663             max_stream_analyze_duration = 90*AV_TIME_BASE;
3664         if (!strcmp(ic->iformat->name, "mpeg") || !strcmp(ic->iformat->name, "mpegts"))
3665             max_stream_analyze_duration = 7*AV_TIME_BASE;
3666     }
3667
3668     if (ic->pb)
3669         av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
3670                avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, ic->nb_streams);
3671
3672     for (i = 0; i < ic->nb_streams; i++) {
3673         const AVCodec *codec;
3674         AVDictionary *thread_opt = NULL;
3675         st = ic->streams[i];
3676         avctx = st->internal->avctx;
3677
3678         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3679             st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3680 /*            if (!st->time_base.num)
3681                 st->time_base = */
3682             if (!avctx->time_base.num)
3683                 avctx->time_base = st->time_base;
3684         }
3685
3686         /* check if the caller has overridden the codec id */
3687 #if FF_API_LAVF_AVCTX
3688 FF_DISABLE_DEPRECATION_WARNINGS
3689         if (st->codec->codec_id != st->internal->orig_codec_id) {
3690             st->codecpar->codec_id   = st->codec->codec_id;
3691             st->codecpar->codec_type = st->codec->codec_type;
3692             st->internal->orig_codec_id = st->codec->codec_id;
3693         }
3694 FF_ENABLE_DEPRECATION_WARNINGS
3695 #endif
3696         // only for the split stuff
3697         if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && st->internal->request_probe <= 0) {
3698             st->parser = av_parser_init(st->codecpar->codec_id);
3699             if (st->parser) {
3700                 if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3701                     st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3702                 } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3703                     st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
3704                 }
3705             } else if (st->need_parsing) {
3706                 av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3707                        "%s, packets or times may be invalid.\n",
3708                        avcodec_get_name(st->codecpar->codec_id));
3709             }
3710         }
3711
3712         if (st->codecpar->codec_id != st->internal->orig_codec_id)
3713             st->internal->orig_codec_id = st->codecpar->codec_id;
3714
3715         ret = avcodec_parameters_to_context(avctx, st->codecpar);
3716         if (ret < 0)
3717             goto find_stream_info_err;
3718         if (st->internal->request_probe <= 0)
3719             st->internal->avctx_inited = 1;
3720
3721         codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3722
3723         /* Force thread count to 1 since the H.264 decoder will not extract
3724          * SPS and PPS to extradata during multi-threaded decoding. */
3725         av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3726         /* Force lowres to 0. The decoder might reduce the video size by the
3727          * lowres factor, and we don't want that propagated to the stream's
3728          * codecpar */
3729         av_dict_set(options ? &options[i] : &thread_opt, "lowres", "0", 0);
3730
3731         if (ic->codec_whitelist)
3732             av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3733
3734         // Try to just open decoders, in case this is enough to get parameters.
3735         // Also ensure that subtitle_header is properly set.
3736         if (!has_codec_parameters(st, NULL) && st->internal->request_probe <= 0 ||
3737             st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3738             if (codec && !avctx->codec)
3739                 if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3740                     av_log(ic, AV_LOG_WARNING,
3741                            "Failed to open codec in %s\n",__FUNCTION__);
3742         }
3743         if (!options)
3744             av_dict_free(&thread_opt);
3745     }
3746
3747     for (i = 0; i < ic->nb_streams; i++) {
3748 #if FF_API_R_FRAME_RATE
3749         ic->streams[i]->internal->info->last_dts = AV_NOPTS_VALUE;
3750 #endif
3751         ic->streams[i]->internal->info->fps_first_dts = AV_NOPTS_VALUE;
3752         ic->streams[i]->internal->info->fps_last_dts  = AV_NOPTS_VALUE;
3753     }
3754
3755     read_size = 0;
3756     for (;;) {
3757         const AVPacket *pkt;
3758         int analyzed_all_streams;
3759         if (ff_check_interrupt(&ic->interrupt_callback)) {
3760             ret = AVERROR_EXIT;
3761             av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3762             break;
3763         }
3764
3765         /* check if one codec still needs to be handled */
3766         for (i = 0; i < ic->nb_streams; i++) {
3767             int fps_analyze_framecount = 20;
3768             int count;
3769
3770             st = ic->streams[i];
3771             if (!has_codec_parameters(st, NULL))
3772                 break;
3773             /* If the timebase is coarse (like the usual millisecond precision
3774              * of mkv), we need to analyze more frames to reliably arrive at
3775              * the correct fps. */
3776             if (av_q2d(st->time_base) > 0.0005)
3777                 fps_analyze_framecount *= 2;
3778             if (!tb_unreliable(st->internal->avctx))
3779                 fps_analyze_framecount = 0;
3780             if (ic->fps_probe_size >= 0)
3781                 fps_analyze_framecount = ic->fps_probe_size;
3782             if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3783                 fps_analyze_framecount = 0;
3784             /* variable fps and no guess at the real fps */
3785             count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
3786                        st->internal->info->codec_info_duration_fields/2 :
3787                        st->internal->info->duration_count;
3788             if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3789                 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3790                 if (count < fps_analyze_framecount)
3791                     break;
3792             }
3793             // Look at the first 3 frames if there is evidence of frame delay
3794             // but the decoder delay is not set.
3795             if (st->internal->info->frame_delay_evidence && count < 2 && st->internal->avctx->has_b_frames == 0)
3796                 break;
3797             if (!st->internal->avctx->extradata &&
3798                 (!st->internal->extract_extradata.inited ||
3799                  st->internal->extract_extradata.bsf) &&
3800                 extract_extradata_check(st))
3801                 break;
3802             if (st->first_dts == AV_NOPTS_VALUE &&
3803                 !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3804                 st->codec_info_nb_frames < ((st->disposition & AV_DISPOSITION_ATTACHED_PIC) ? 1 : ic->max_ts_probe) &&
3805                 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3806                  st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
3807                 break;
3808         }
3809         analyzed_all_streams = 0;
3810         if (!missing_streams || !*missing_streams)
3811             if (i == ic->nb_streams) {
3812                 analyzed_all_streams = 1;
3813                 /* NOTE: If the format has no header, then we need to read some
3814                  * packets to get most of the streams, so we cannot stop here. */
3815                 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3816                     /* If we found the info for all the codecs, we can stop. */
3817                     ret = count;
3818                     av_log(ic, AV_LOG_DEBUG, "All info found\n");
3819                     flush_codecs = 0;
3820                     break;
3821                 }
3822             }
3823         /* We did not get all the codec info, but we read too much data. */
3824         if (read_size >= probesize) {
3825             ret = count;
3826             av_log(ic, AV_LOG_DEBUG,
3827                    "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3828             for (i = 0; i < ic->nb_streams; i++)
3829                 if (!ic->streams[i]->r_frame_rate.num &&
3830                     ic->streams[i]->internal->info->duration_count <= 1 &&
3831                     ic->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
3832                     strcmp(ic->iformat->name, "image2"))
3833                     av_log(ic, AV_LOG_WARNING,
3834                            "Stream #%d: not enough frames to estimate rate; "
3835                            "consider increasing probesize\n", i);
3836             break;
3837         }
3838
3839         /* NOTE: A new stream can be added there if no header in file
3840          * (AVFMTCTX_NOHEADER). */
3841         ret = read_frame_internal(ic, pkt1);
3842         if (ret == AVERROR(EAGAIN))
3843             continue;
3844
3845         if (ret < 0) {
3846             /* EOF or error*/
3847             eof_reached = 1;
3848             break;
3849         }
3850
3851         if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
3852             ret = avpriv_packet_list_put(&ic->internal->packet_buffer,
3853                                      &ic->internal->packet_buffer_end,
3854                                      pkt1, NULL, 0);
3855             if (ret < 0)
3856                 goto unref_then_goto_end;
3857
3858             pkt = &ic->internal->packet_buffer_end->pkt;
3859         } else {
3860             pkt = pkt1;
3861         }
3862
3863         st = ic->streams[pkt->stream_index];
3864         if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
3865             read_size += pkt->size;
3866
3867         avctx = st->internal->avctx;
3868         if (!st->internal->avctx_inited) {
3869             ret = avcodec_parameters_to_context(avctx, st->codecpar);
3870             if (ret < 0)
3871                 goto unref_then_goto_end;
3872             st->internal->avctx_inited = 1;
3873         }
3874
3875         if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3876             /* check for non-increasing dts */
3877             if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3878                 st->internal->info->fps_last_dts >= pkt->dts) {
3879                 av_log(ic, AV_LOG_DEBUG,
3880                        "Non-increasing DTS in stream %d: packet %d with DTS "
3881                        "%"PRId64", packet %d with DTS %"PRId64"\n",
3882                        st->index, st->internal->info->fps_last_dts_idx,
3883                        st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3884                        pkt->dts);
3885                 st->internal->info->fps_first_dts =
3886                 st->internal->info->fps_last_dts  = AV_NOPTS_VALUE;
3887             }
3888             /* Check for a discontinuity in dts. If the difference in dts
3889              * is more than 1000 times the average packet duration in the
3890              * sequence, we treat it as a discontinuity. */
3891             if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3892                 st->internal->info->fps_last_dts_idx > st->internal->info->fps_first_dts_idx &&
3893                 (pkt->dts - (uint64_t)st->internal->info->fps_last_dts) / 1000 >
3894                 (st->internal->info->fps_last_dts     - (uint64_t)st->internal->info->fps_first_dts) /
3895                 (st->internal->info->fps_last_dts_idx - st->internal->info->fps_first_dts_idx)) {
3896                 av_log(ic, AV_LOG_WARNING,
3897                        "DTS discontinuity in stream %d: packet %d with DTS "
3898                        "%"PRId64", packet %d with DTS %"PRId64"\n",
3899                        st->index, st->internal->info->fps_last_dts_idx,
3900                        st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3901                        pkt->dts);
3902                 st->internal->info->fps_first_dts =
3903                 st->internal->info->fps_last_dts  = AV_NOPTS_VALUE;
3904             }
3905
3906             /* update stored dts values */
3907             if (st->internal->info->fps_first_dts == AV_NOPTS_VALUE) {
3908                 st->internal->info->fps_first_dts     = pkt->dts;
3909                 st->internal->info->fps_first_dts_idx = st->codec_info_nb_frames;
3910             }
3911             st->internal->info->fps_last_dts     = pkt->dts;
3912             st->internal->info->fps_last_dts_idx = st->codec_info_nb_frames;
3913         }
3914         if (st->codec_info_nb_frames>1) {
3915             int64_t t = 0;
3916             int64_t limit;
3917
3918             if (st->time_base.den > 0)
3919                 t = av_rescale_q(st->internal->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
3920             if (st->avg_frame_rate.num > 0)
3921                 t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3922
3923             if (   t == 0
3924                 && st->codec_info_nb_frames>30
3925                 && st->internal->info->fps_first_dts != AV_NOPTS_VALUE
3926                 && st->internal->info->fps_last_dts  != AV_NOPTS_VALUE) {
3927                 int64_t dur = av_sat_sub64(st->internal->info->fps_last_dts, st->internal->info->fps_first_dts);
3928                 t = FFMAX(t, av_rescale_q(dur, st->time_base, AV_TIME_BASE_Q));
3929             }
3930
3931             if (analyzed_all_streams)                                limit = max_analyze_duration;
3932             else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3933             else                                                     limit = max_stream_analyze_duration;
3934
3935             if (t >= limit) {
3936                 av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3937                        limit,
3938                        t, pkt->stream_index);
3939                 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3940                     av_packet_unref(pkt1);
3941                 break;
3942             }
3943             if (pkt->duration) {
3944                 if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE && pkt->pts != AV_NOPTS_VALUE && st->start_time != AV_NOPTS_VALUE && pkt->pts >= st->start_time) {
3945                     st->internal->info->codec_info_duration = FFMIN(pkt->pts - st->start_time, st->internal->info->codec_info_duration + pkt->duration);
3946                 } else
3947                     st->internal->info->codec_info_duration += pkt->duration;
3948                 st->internal->info->codec_info_duration_fields += st->parser && st->need_parsing && avctx->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3949             }
3950         }
3951         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3952 #if FF_API_R_FRAME_RATE
3953             ff_rfps_add_frame(ic, st, pkt->dts);
3954 #endif
3955             if (pkt->dts != pkt->pts && pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
3956                 st->internal->info->frame_delay_evidence = 1;
3957         }
3958         if (!st->internal->avctx->extradata) {
3959             ret = extract_extradata(ic, st, pkt);
3960             if (ret < 0)
3961                 goto unref_then_goto_end;
3962         }
3963
3964         /* If still no information, we try to open the codec and to
3965          * decompress the frame. We try to avoid that in most cases as
3966          * it takes longer and uses more memory. For MPEG-4, we need to
3967          * decompress for QuickTime.
3968          *
3969          * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3970          * least one frame of codec data, this makes sure the codec initializes
3971          * the channel configuration and does not only trust the values from
3972          * the container. */
3973         try_decode_frame(ic, st, pkt,
3974                          (options && i < orig_nb_streams) ? &options[i] : NULL);
3975
3976         if (ic->flags & AVFMT_FLAG_NOBUFFER)
3977             av_packet_unref(pkt1);
3978
3979         st->codec_info_nb_frames++;
3980         count++;
3981     }
3982
3983     if (eof_reached) {
3984         int stream_index;
3985         for (stream_index = 0; stream_index < ic->nb_streams; stream_index++) {
3986             st = ic->streams[stream_index];
3987             avctx = st->internal->avctx;
3988             if (!has_codec_parameters(st, NULL)) {
3989                 const AVCodec *codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3990                 if (codec && !avctx->codec) {
3991                     AVDictionary *opts = NULL;
3992                     if (ic->codec_whitelist)
3993                         av_dict_set(&opts, "codec_whitelist", ic->codec_whitelist, 0);
3994                     if (avcodec_open2(avctx, codec, (options && stream_index < orig_nb_streams) ? &options[stream_index] : &opts) < 0)
3995                         av_log(ic, AV_LOG_WARNING,
3996                                "Failed to open codec in %s\n",__FUNCTION__);
3997                     av_dict_free(&opts);
3998                 }
3999             }
4000
4001             // EOF already reached while reading the stream above.
4002             // So continue with reoordering DTS with whatever delay we have.
4003             if (ic->internal->packet_buffer && !has_decode_delay_been_guessed(st)) {
4004                 update_dts_from_pts(ic, stream_index, ic->internal->packet_buffer);
4005             }
4006         }
4007     }
4008
4009     if (flush_codecs) {
4010         AVPacket *empty_pkt = ic->internal->pkt;
4011         int err = 0;
4012         av_packet_unref(empty_pkt);
4013
4014         for (i = 0; i < ic->nb_streams; i++) {
4015
4016             st = ic->streams[i];
4017
4018             /* flush the decoders */
4019             if (st->internal->info->found_decoder == 1) {
4020                 do {
4021                     err = try_decode_frame(ic, st, empty_pkt,
4022                                             (options && i < orig_nb_streams)
4023                                             ? &options[i] : NULL);
4024                 } while (err > 0 && !has_codec_parameters(st, NULL));
4025
4026                 if (err < 0) {
4027                     av_log(ic, AV_LOG_INFO,
4028                         "decoding for stream %d failed\n", st->index);
4029                 }
4030             }
4031         }
4032     }
4033
4034     ff_rfps_calculate(ic);
4035
4036     for (i = 0; i < ic->nb_streams; i++) {
4037         st = ic->streams[i];
4038         avctx = st->internal->avctx;
4039         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
4040             if (avctx->codec_id == AV_CODEC_ID_RAWVIDEO && !avctx->codec_tag && !avctx->bits_per_coded_sample) {
4041                 uint32_t tag= avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
4042                 if (avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), tag) == avctx->pix_fmt)
4043                     avctx->codec_tag= tag;
4044             }
4045
4046             /* estimate average framerate if not set by demuxer */
4047             if (st->internal->info->codec_info_duration_fields &&
4048                 !st->avg_frame_rate.num &&
4049                 st->internal->info->codec_info_duration) {
4050                 int best_fps      = 0;
4051                 double best_error = 0.01;
4052                 AVRational codec_frame_rate = avctx->framerate;
4053
4054                 if (st->internal->info->codec_info_duration        >= INT64_MAX / st->time_base.num / 2||
4055                     st->internal->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
4056                     st->internal->info->codec_info_duration        < 0)
4057                     continue;
4058                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4059                           st->internal->info->codec_info_duration_fields * (int64_t) st->time_base.den,
4060                           st->internal->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
4061
4062                 /* Round guessed framerate to a "standard" framerate if it's
4063                  * within 1% of the original estimate. */
4064                 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
4065                     AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
4066                     double error       = fabs(av_q2d(st->avg_frame_rate) /
4067                                               av_q2d(std_fps) - 1);
4068
4069                     if (error < best_error) {
4070                         best_error = error;
4071                         best_fps   = std_fps.num;
4072                     }
4073
4074                     if (ic->internal->prefer_codec_framerate && codec_frame_rate.num > 0 && codec_frame_rate.den > 0) {
4075                         error       = fabs(av_q2d(codec_frame_rate) /
4076                                            av_q2d(std_fps) - 1);
4077                         if (error < best_error) {
4078                             best_error = error;
4079                             best_fps   = std_fps.num;
4080                         }
4081                     }
4082                 }
4083                 if (best_fps)
4084                     av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4085                               best_fps, 12 * 1001, INT_MAX);
4086             }
4087
4088             if (!st->r_frame_rate.num) {
4089                 if (    avctx->time_base.den * (int64_t) st->time_base.num
4090                     <= avctx->time_base.num * avctx->ticks_per_frame * (uint64_t) st->time_base.den) {
4091                     av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4092                               avctx->time_base.den, (int64_t)avctx->time_base.num * avctx->ticks_per_frame, INT_MAX);
4093                 } else {
4094                     st->r_frame_rate.num = st->time_base.den;
4095                     st->r_frame_rate.den = st->time_base.num;
4096                 }
4097             }
4098             if (st->internal->display_aspect_ratio.num && st->internal->display_aspect_ratio.den) {
4099                 AVRational hw_ratio = { avctx->height, avctx->width };
4100                 st->sample_aspect_ratio = av_mul_q(st->internal->display_aspect_ratio,
4101                                                    hw_ratio);
4102             }
4103         } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
4104             if (!avctx->bits_per_coded_sample)
4105                 avctx->bits_per_coded_sample =
4106                     av_get_bits_per_sample(avctx->codec_id);
4107             // set stream disposition based on audio service type
4108             switch (avctx->audio_service_type) {
4109             case AV_AUDIO_SERVICE_TYPE_EFFECTS:
4110                 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
4111                 break;
4112             case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
4113                 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
4114                 break;
4115             case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
4116                 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
4117                 break;
4118             case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
4119                 st->disposition = AV_DISPOSITION_COMMENT;
4120                 break;
4121             case AV_AUDIO_SERVICE_TYPE_KARAOKE:
4122                 st->disposition = AV_DISPOSITION_KARAOKE;
4123                 break;
4124             }
4125         }
4126     }
4127
4128     if (probesize)
4129         estimate_timings(ic, old_offset);
4130
4131     av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
4132
4133     if (ret >= 0 && ic->nb_streams)
4134         /* We could not have all the codec parameters before EOF. */
4135         ret = -1;
4136     for (i = 0; i < ic->nb_streams; i++) {
4137         const char *errmsg;
4138         st = ic->streams[i];
4139
4140         /* if no packet was ever seen, update context now for has_codec_parameters */
4141         if (!st->internal->avctx_inited) {
4142             if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
4143                 st->codecpar->format == AV_SAMPLE_FMT_NONE)
4144                 st->codecpar->format = st->internal->avctx->sample_fmt;
4145             ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
4146             if (ret < 0)
4147                 goto find_stream_info_err;
4148         }
4149         if (!has_codec_parameters(st, &errmsg)) {
4150             char buf[256];
4151             avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
4152             av_log(ic, AV_LOG_WARNING,
4153                    "Could not find codec parameters for stream %d (%s): %s\n"
4154                    "Consider increasing the value for the 'analyzeduration' (%"PRId64") and 'probesize' (%"PRId64") options\n",
4155                    i, buf, errmsg, ic->max_analyze_duration, ic->probesize);
4156         } else {
4157             ret = 0;
4158         }
4159     }
4160
4161     ret = compute_chapters_end(ic);
4162     if (ret < 0)
4163         goto find_stream_info_err;
4164
4165     /* update the stream parameters from the internal codec contexts */
4166     for (i = 0; i < ic->nb_streams; i++) {
4167         st = ic->streams[i];
4168
4169         if (st->internal->avctx_inited) {
4170             ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
4171             if (ret < 0)
4172                 goto find_stream_info_err;
4173             ret = add_coded_side_data(st, st->internal->avctx);
4174             if (ret < 0)
4175                 goto find_stream_info_err;
4176         }
4177
4178 #if FF_API_LAVF_AVCTX
4179 FF_DISABLE_DEPRECATION_WARNINGS
4180         ret = avcodec_parameters_to_context(st->codec, st->codecpar);
4181         if (ret < 0)
4182             goto find_stream_info_err;
4183
4184         // The old API (AVStream.codec) "requires" the resolution to be adjusted
4185         // by the lowres factor.
4186         if (st->internal->avctx->lowres && st->internal->avctx->width) {
4187             st->codec->lowres = st->internal->avctx->lowres;
4188             st->codec->width = st->internal->avctx->width;
4189             st->codec->height = st->internal->avctx->height;
4190         }
4191
4192         if (st->codec->codec_tag != MKTAG('t','m','c','d')) {
4193             st->codec->time_base = st->internal->avctx->time_base;
4194             st->codec->ticks_per_frame = st->internal->avctx->ticks_per_frame;
4195         }
4196         st->codec->framerate = st->avg_frame_rate;
4197
4198         if (st->internal->avctx->subtitle_header) {
4199             st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
4200             if (!st->codec->subtitle_header)
4201                 goto find_stream_info_err;
4202             st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
4203             memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
4204                    st->codec->subtitle_header_size);
4205         }
4206
4207         // Fields unavailable in AVCodecParameters
4208         st->codec->coded_width = st->internal->avctx->coded_width;
4209         st->codec->coded_height = st->internal->avctx->coded_height;
4210         st->codec->properties = st->internal->avctx->properties;
4211 FF_ENABLE_DEPRECATION_WARNINGS
4212 #endif
4213
4214         st->internal->avctx_inited = 0;
4215     }
4216
4217 find_stream_info_err:
4218     for (i = 0; i < ic->nb_streams; i++) {
4219         st = ic->streams[i];
4220         if (st->internal->info)
4221             av_freep(&st->internal->info->duration_error);
4222         avcodec_close(ic->streams[i]->internal->avctx);
4223         av_freep(&ic->streams[i]->internal->info);
4224         av_bsf_free(&ic->streams[i]->internal->extract_extradata.bsf);
4225     }
4226     if (ic->pb)
4227         av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
4228                avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
4229     return ret;
4230
4231 unref_then_goto_end:
4232     av_packet_unref(pkt1);
4233     goto find_stream_info_err;
4234 }
4235
4236 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
4237 {
4238     int i, j;
4239
4240     for (i = 0; i < ic->nb_programs; i++) {
4241         if (ic->programs[i] == last) {
4242             last = NULL;
4243         } else {
4244             if (!last)
4245                 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
4246                     if (ic->programs[i]->stream_index[j] == s)
4247                         return ic->programs[i];
4248         }
4249     }
4250     return NULL;
4251 }
4252
4253 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
4254                         int wanted_stream_nb, int related_stream,
4255                         AVCodec **decoder_ret, int flags)
4256 {
4257     int i, nb_streams = ic->nb_streams;
4258     int ret = AVERROR_STREAM_NOT_FOUND;
4259     int best_count = -1, best_multiframe = -1, best_disposition = -1;
4260     int count, multiframe, disposition;
4261     int64_t best_bitrate = -1;
4262     int64_t bitrate;
4263     unsigned *program = NULL;
4264     const AVCodec *decoder = NULL, *best_decoder = NULL;
4265
4266     if (related_stream >= 0 && wanted_stream_nb < 0) {
4267         AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
4268         if (p) {
4269             program    = p->stream_index;
4270             nb_streams = p->nb_stream_indexes;
4271         }
4272     }
4273     for (i = 0; i < nb_streams; i++) {
4274         int real_stream_index = program ? program[i] : i;
4275         AVStream *st          = ic->streams[real_stream_index];
4276         AVCodecParameters *par = st->codecpar;
4277         if (par->codec_type != type)
4278             continue;
4279         if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
4280             continue;
4281         if (type == AVMEDIA_TYPE_AUDIO && !(par->channels && par->sample_rate))
4282             continue;
4283         if (decoder_ret) {
4284             decoder = find_decoder(ic, st, par->codec_id);
4285             if (!decoder) {
4286                 if (ret < 0)
4287                     ret = AVERROR_DECODER_NOT_FOUND;
4288                 continue;
4289             }
4290         }
4291         disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED))
4292                       + !! (st->disposition & AV_DISPOSITION_DEFAULT);
4293         count = st->codec_info_nb_frames;
4294         bitrate = par->bit_rate;
4295         multiframe = FFMIN(5, count);
4296         if ((best_disposition >  disposition) ||
4297             (best_disposition == disposition && best_multiframe >  multiframe) ||
4298             (best_disposition == disposition && best_multiframe == multiframe && best_bitrate >  bitrate) ||
4299             (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
4300             continue;
4301         best_disposition = disposition;
4302         best_count   = count;
4303         best_bitrate = bitrate;
4304         best_multiframe = multiframe;
4305         ret          = real_stream_index;
4306         best_decoder = decoder;
4307         if (program && i == nb_streams - 1 && ret < 0) {
4308             program    = NULL;
4309             nb_streams = ic->nb_streams;
4310             /* no related stream found, try again with everything */
4311             i = 0;
4312         }
4313     }
4314     if (decoder_ret)
4315         *decoder_ret = (AVCodec*)best_decoder;
4316     return ret;
4317 }
4318
4319 /*******************************************************/
4320
4321 int av_read_play(AVFormatContext *s)
4322 {
4323     if (s->iformat->read_play)
4324         return s->iformat->read_play(s);
4325     if (s->pb)
4326         return avio_pause(s->pb, 0);
4327     return AVERROR(ENOSYS);
4328 }
4329
4330 int av_read_pause(AVFormatContext *s)
4331 {
4332     if (s->iformat->read_pause)
4333         return s->iformat->read_pause(s);
4334     if (s->pb)
4335         return avio_pause(s->pb, 1);
4336     return AVERROR(ENOSYS);
4337 }
4338
4339 int ff_stream_encode_params_copy(AVStream *dst, const AVStream *src)
4340 {
4341     int ret, i;
4342
4343     dst->id                  = src->id;
4344     dst->time_base           = src->time_base;
4345     dst->nb_frames           = src->nb_frames;
4346     dst->disposition         = src->disposition;
4347     dst->sample_aspect_ratio = src->sample_aspect_ratio;
4348     dst->avg_frame_rate      = src->avg_frame_rate;
4349     dst->r_frame_rate        = src->r_frame_rate;
4350
4351     av_dict_free(&dst->metadata);
4352     ret = av_dict_copy(&dst->metadata, src->metadata, 0);
4353     if (ret < 0)
4354         return ret;
4355
4356     ret = avcodec_parameters_copy(dst->codecpar, src->codecpar);
4357     if (ret < 0)
4358         return ret;
4359
4360     /* Free existing side data*/
4361     for (i = 0; i < dst->nb_side_data; i++)
4362         av_free(dst->side_data[i].data);
4363     av_freep(&dst->side_data);
4364     dst->nb_side_data = 0;
4365
4366     /* Copy side data if present */
4367     if (src->nb_side_data) {
4368         dst->side_data = av_mallocz_array(src->nb_side_data,
4369                                           sizeof(AVPacketSideData));
4370         if (!dst->side_data)
4371             return AVERROR(ENOMEM);
4372         dst->nb_side_data = src->nb_side_data;
4373
4374         for (i = 0; i < src->nb_side_data; i++) {
4375             uint8_t *data = av_memdup(src->side_data[i].data,
4376                                       src->side_data[i].size);
4377             if (!data)
4378                 return AVERROR(ENOMEM);
4379             dst->side_data[i].type = src->side_data[i].type;
4380             dst->side_data[i].size = src->side_data[i].size;
4381             dst->side_data[i].data = data;
4382         }
4383     }
4384
4385     return 0;
4386 }
4387
4388 static void free_stream(AVStream **pst)
4389 {
4390     AVStream *st = *pst;
4391     int i;
4392
4393     if (!st)
4394         return;
4395
4396     for (i = 0; i < st->nb_side_data; i++)
4397         av_freep(&st->side_data[i].data);
4398     av_freep(&st->side_data);
4399
4400     if (st->parser)
4401         av_parser_close(st->parser);
4402
4403     if (st->attached_pic.data)
4404         av_packet_unref(&st->attached_pic);
4405
4406     if (st->internal) {
4407         avcodec_free_context(&st->internal->avctx);
4408         av_bsf_free(&st->internal->bsfc);
4409         av_freep(&st->internal->priv_pts);
4410         av_freep(&st->internal->index_entries);
4411         av_freep(&st->internal->probe_data.buf);
4412
4413         av_bsf_free(&st->internal->extract_extradata.bsf);
4414
4415         if (st->internal->info)
4416             av_freep(&st->internal->info->duration_error);
4417         av_freep(&st->internal->info);
4418     }
4419     av_freep(&st->internal);
4420
4421     av_dict_free(&st->metadata);
4422     avcodec_parameters_free(&st->codecpar);
4423 #if FF_API_LAVF_AVCTX
4424 FF_DISABLE_DEPRECATION_WARNINGS
4425     avcodec_free_context(&st->codec);
4426 FF_ENABLE_DEPRECATION_WARNINGS
4427 #endif
4428     av_freep(&st->priv_data);
4429
4430     av_freep(pst);
4431 }
4432
4433 void ff_free_stream(AVFormatContext *s, AVStream *st)
4434 {
4435     av_assert0(s->nb_streams>0);
4436     av_assert0(s->streams[ s->nb_streams - 1 ] == st);
4437
4438     free_stream(&s->streams[ --s->nb_streams ]);
4439 }
4440
4441 void avformat_free_context(AVFormatContext *s)
4442 {
4443     int i;
4444
4445     if (!s)
4446         return;
4447
4448     if (s->oformat && s->oformat->deinit && s->internal->initialized)
4449         s->oformat->deinit(s);
4450
4451     av_opt_free(s);
4452     if (s->iformat && s->iformat->priv_class && s->priv_data)
4453         av_opt_free(s->priv_data);
4454     if (s->oformat && s->oformat->priv_class && s->priv_data)
4455         av_opt_free(s->priv_data);
4456
4457     for (i = 0; i < s->nb_streams; i++)
4458         free_stream(&s->streams[i]);
4459     s->nb_streams = 0;
4460
4461     for (i = 0; i < s->nb_programs; i++) {
4462         av_dict_free(&s->programs[i]->metadata);
4463         av_freep(&s->programs[i]->stream_index);
4464         av_freep(&s->programs[i]);
4465     }
4466     s->nb_programs = 0;
4467
4468     av_freep(&s->programs);
4469     av_freep(&s->priv_data);
4470     while (s->nb_chapters--) {
4471         av_dict_free(&s->chapters[s->nb_chapters]->metadata);
4472         av_freep(&s->chapters[s->nb_chapters]);
4473     }
4474     av_freep(&s->chapters);
4475     av_dict_free(&s->metadata);
4476     av_dict_free(&s->internal->id3v2_meta);
4477     av_packet_free(&s->internal->pkt);
4478     av_packet_free(&s->internal->parse_pkt);
4479     av_freep(&s->streams);
4480     flush_packet_queue(s);
4481     av_freep(&s->internal);
4482     av_freep(&s->url);
4483     av_free(s);
4484 }
4485
4486 void avformat_close_input(AVFormatContext **ps)
4487 {
4488     AVFormatContext *s;
4489     AVIOContext *pb;
4490
4491     if (!ps || !*ps)
4492         return;
4493
4494     s  = *ps;
4495     pb = s->pb;
4496
4497     if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
4498         (s->flags & AVFMT_FLAG_CUSTOM_IO))
4499         pb = NULL;
4500
4501     flush_packet_queue(s);
4502
4503     if (s->iformat)
4504         if (s->iformat->read_close)
4505             s->iformat->read_close(s);
4506
4507     avformat_free_context(s);
4508
4509     *ps = NULL;
4510
4511     avio_close(pb);
4512 }
4513
4514 AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
4515 {
4516     AVStream *st;
4517     int i;
4518     AVStream **streams;
4519
4520     if (s->nb_streams >= s->max_streams) {
4521         av_log(s, AV_LOG_ERROR, "Number of streams exceeds max_streams parameter"
4522                " (%d), see the documentation if you wish to increase it\n",
4523                s->max_streams);
4524         return NULL;
4525     }
4526     streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
4527     if (!streams)
4528         return NULL;
4529     s->streams = streams;
4530
4531     st = av_mallocz(sizeof(AVStream));
4532     if (!st)
4533         return NULL;
4534
4535 #if FF_API_LAVF_AVCTX
4536 FF_DISABLE_DEPRECATION_WARNINGS
4537     st->codec = avcodec_alloc_context3(c);
4538     if (!st->codec) {
4539         av_free(st);
4540         return NULL;
4541     }
4542 FF_ENABLE_DEPRECATION_WARNINGS
4543 #endif
4544
4545     st->internal = av_mallocz(sizeof(*st->internal));
4546     if (!st->internal)
4547         goto fail;
4548
4549     st->internal->info = av_mallocz(sizeof(*st->internal->info));
4550     if (!st->internal->info)
4551         goto fail;
4552     st->internal->info->last_dts = AV_NOPTS_VALUE;
4553
4554     st->codecpar = avcodec_parameters_alloc();
4555     if (!st->codecpar)
4556         goto fail;
4557
4558     st->internal->avctx = avcodec_alloc_context3(NULL);
4559     if (!st->internal->avctx)
4560         goto fail;
4561
4562     if (s->iformat) {
4563 #if FF_API_LAVF_AVCTX
4564 FF_DISABLE_DEPRECATION_WARNINGS
4565         /* no default bitrate if decoding */
4566         st->codec->bit_rate = 0;
4567 FF_ENABLE_DEPRECATION_WARNINGS
4568 #endif
4569
4570         /* default pts setting is MPEG-like */
4571         avpriv_set_pts_info(st, 33, 1, 90000);
4572         /* we set the current DTS to 0 so that formats without any timestamps
4573          * but durations get some timestamps, formats with some unknown
4574          * timestamps have their first few packets buffered and the
4575          * timestamps corrected before they are returned to the user */
4576         st->cur_dts = RELATIVE_TS_BASE;
4577     } else {
4578         st->cur_dts = AV_NOPTS_VALUE;
4579     }
4580
4581     st->index      = s->nb_streams;
4582     st->start_time = AV_NOPTS_VALUE;
4583     st->duration   = AV_NOPTS_VALUE;
4584     st->first_dts     = AV_NOPTS_VALUE;
4585     st->probe_packets = s->max_probe_packets;
4586     st->internal->pts_wrap_reference = AV_NOPTS_VALUE;
4587     st->internal->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4588
4589     st->last_IP_pts = AV_NOPTS_VALUE;
4590     st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
4591     for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
4592         st->internal->pts_buffer[i] = AV_NOPTS_VALUE;
4593
4594     st->sample_aspect_ratio = (AVRational) { 0, 1 };
4595
4596 #if FF_API_R_FRAME_RATE
4597     st->internal->info->last_dts      = AV_NOPTS_VALUE;
4598 #endif
4599     st->internal->info->fps_first_dts = AV_NOPTS_VALUE;
4600     st->internal->info->fps_last_dts  = AV_NOPTS_VALUE;
4601
4602     st->internal->inject_global_side_data = s->internal->inject_global_side_data;
4603
4604     st->internal->need_context_update = 1;
4605
4606     s->streams[s->nb_streams++] = st;
4607     return st;
4608 fail:
4609     free_stream(&st);
4610     return NULL;
4611 }
4612
4613 AVProgram *av_new_program(AVFormatContext *ac, int id)
4614 {
4615     AVProgram *program = NULL;
4616     int i, ret;
4617
4618     av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
4619
4620     for (i = 0; i < ac->nb_programs; i++)
4621         if (ac->programs[i]->id == id)
4622             program = ac->programs[i];
4623
4624     if (!program) {
4625         program = av_mallocz(sizeof(AVProgram));
4626         if (!program)
4627             return NULL;
4628         ret = av_dynarray_add_nofree(&ac->programs, &ac->nb_programs, program);
4629         if (ret < 0) {
4630             av_free(program);
4631             return NULL;
4632         }
4633         program->discard = AVDISCARD_NONE;
4634         program->pmt_version = -1;
4635         program->id = id;
4636         program->pts_wrap_reference = AV_NOPTS_VALUE;
4637         program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4638         program->start_time =
4639         program->end_time   = AV_NOPTS_VALUE;
4640     }
4641     return program;
4642 }
4643
4644 #if FF_API_CHAPTER_ID_INT
4645 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
4646 #else
4647 AVChapter *avpriv_new_chapter(AVFormatContext *s, int64_t id, AVRational time_base,
4648 #endif
4649                               int64_t start, int64_t end, const char *title)
4650 {
4651     AVChapter *chapter = NULL;
4652     int i, ret;
4653
4654     if (end != AV_NOPTS_VALUE && start > end) {
4655         av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
4656         return NULL;
4657     }
4658
4659     if (!s->nb_chapters) {
4660         s->internal->chapter_ids_monotonic = 1;
4661     } else if (!s->internal->chapter_ids_monotonic || s->chapters[s->nb_chapters-1]->id >= id) {
4662         s->internal->chapter_ids_monotonic = 0;
4663         for (i = 0; i < s->nb_chapters; i++)
4664             if (s->chapters[i]->id == id)
4665                 chapter = s->chapters[i];
4666     }
4667
4668     if (!chapter) {
4669         chapter = av_mallocz(sizeof(AVChapter));
4670         if (!chapter)
4671             return NULL;
4672         ret = av_dynarray_add_nofree(&s->chapters, &s->nb_chapters, chapter);
4673         if (ret < 0) {
4674             av_free(chapter);
4675             return NULL;
4676         }
4677     }
4678     av_dict_set(&chapter->metadata, "title", title, 0);
4679     chapter->id        = id;
4680     chapter->time_base = time_base;
4681     chapter->start     = start;
4682     chapter->end       = end;
4683
4684     return chapter;
4685 }
4686
4687 void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
4688 {
4689     int i, j;
4690     AVProgram *program = NULL;
4691     void *tmp;
4692
4693     if (idx >= ac->nb_streams) {
4694         av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
4695         return;
4696     }
4697
4698     for (i = 0; i < ac->nb_programs; i++) {
4699         if (ac->programs[i]->id != progid)
4700             continue;
4701         program = ac->programs[i];
4702         for (j = 0; j < program->nb_stream_indexes; j++)
4703             if (program->stream_index[j] == idx)
4704                 return;
4705
4706         tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
4707         if (!tmp)
4708             return;
4709         program->stream_index = tmp;
4710         program->stream_index[program->nb_stream_indexes++] = idx;
4711         return;
4712     }
4713 }
4714
4715 uint64_t ff_ntp_time(void)
4716 {
4717     return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
4718 }
4719
4720 uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us)
4721 {
4722     uint64_t ntp_ts, frac_part, sec;
4723     uint32_t usec;
4724
4725     //current ntp time in seconds and micro seconds
4726     sec = ntp_time_us / 1000000;
4727     usec = ntp_time_us % 1000000;
4728
4729     //encoding in ntp timestamp format
4730     frac_part = usec * 0xFFFFFFFFULL;
4731     frac_part /= 1000000;
4732
4733     if (sec > 0xFFFFFFFFULL)
4734         av_log(NULL, AV_LOG_WARNING, "NTP time format roll over detected\n");
4735
4736     ntp_ts = sec << 32;
4737     ntp_ts |= frac_part;
4738
4739     return ntp_ts;
4740 }
4741
4742 uint64_t ff_parse_ntp_time(uint64_t ntp_ts)
4743 {
4744     uint64_t sec = ntp_ts >> 32;
4745     uint64_t frac_part = ntp_ts & 0xFFFFFFFFULL;
4746     uint64_t usec = (frac_part * 1000000) / 0xFFFFFFFFULL;
4747
4748     return (sec * 1000000) + usec;
4749 }
4750
4751 int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number, int flags)
4752 {
4753     const char *p;
4754     char *q, buf1[20], c;
4755     int nd, len, percentd_found;
4756
4757     q = buf;
4758     p = path;
4759     percentd_found = 0;
4760     for (;;) {
4761         c = *p++;
4762         if (c == '\0')
4763             break;
4764         if (c == '%') {
4765             do {
4766                 nd = 0;
4767                 while (av_isdigit(*p)) {
4768                     if (nd >= INT_MAX / 10 - 255)
4769                         goto fail;
4770                     nd = nd * 10 + *p++ - '0';
4771                 }
4772                 c = *p++;
4773             } while (av_isdigit(c));
4774
4775             switch (c) {
4776             case '%':
4777                 goto addchar;
4778             case 'd':
4779                 if (!(flags & AV_FRAME_FILENAME_FLAGS_MULTIPLE) && percentd_found)
4780                     goto fail;
4781                 percentd_found = 1;
4782                 if (number < 0)
4783                     nd += 1;
4784                 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
4785                 len = strlen(buf1);
4786                 if ((q - buf + len) > buf_size - 1)
4787                     goto fail;
4788                 memcpy(q, buf1, len);
4789                 q += len;
4790                 break;
4791             default:
4792                 goto fail;
4793             }
4794         } else {
4795 addchar:
4796             if ((q - buf) < buf_size - 1)
4797                 *q++ = c;
4798         }
4799     }
4800     if (!percentd_found)
4801         goto fail;
4802     *q = '\0';
4803     return 0;
4804 fail:
4805     *q = '\0';
4806     return -1;
4807 }
4808
4809 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
4810 {
4811     return av_get_frame_filename2(buf, buf_size, path, number, 0);
4812 }
4813
4814 void av_url_split(char *proto, int proto_size,
4815                   char *authorization, int authorization_size,
4816                   char *hostname, int hostname_size,
4817                   int *port_ptr, char *path, int path_size, const char *url)
4818 {
4819     const char *p, *ls, *at, *at2, *col, *brk;
4820
4821     if (port_ptr)
4822         *port_ptr = -1;
4823     if (proto_size > 0)
4824         proto[0] = 0;
4825     if (authorization_size > 0)
4826         authorization[0] = 0;
4827     if (hostname_size > 0)
4828         hostname[0] = 0;
4829     if (path_size > 0)
4830         path[0] = 0;
4831
4832     /* parse protocol */
4833     if ((p = strchr(url, ':'))) {
4834         av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
4835         p++; /* skip ':' */
4836         if (*p == '/')
4837             p++;
4838         if (*p == '/')
4839             p++;
4840     } else {
4841         /* no protocol means plain filename */
4842         av_strlcpy(path, url, path_size);
4843         return;
4844     }
4845
4846     /* separate path from hostname */
4847     ls = p + strcspn(p, "/?#");
4848     av_strlcpy(path, ls, path_size);
4849
4850     /* the rest is hostname, use that to parse auth/port */
4851     if (ls != p) {
4852         /* authorization (user[:pass]@hostname) */
4853         at2 = p;
4854         while ((at = strchr(p, '@')) && at < ls) {
4855             av_strlcpy(authorization, at2,
4856                        FFMIN(authorization_size, at + 1 - at2));
4857             p = at + 1; /* skip '@' */
4858         }
4859
4860         if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
4861             /* [host]:port */
4862             av_strlcpy(hostname, p + 1,
4863                        FFMIN(hostname_size, brk - p));
4864             if (brk[1] == ':' && port_ptr)
4865                 *port_ptr = atoi(brk + 2);
4866         } else if ((col = strchr(p, ':')) && col < ls) {
4867             av_strlcpy(hostname, p,
4868                        FFMIN(col + 1 - p, hostname_size));
4869             if (port_ptr)
4870                 *port_ptr = atoi(col + 1);
4871         } else
4872             av_strlcpy(hostname, p,
4873                        FFMIN(ls + 1 - p, hostname_size));
4874     }
4875 }
4876
4877 int ff_mkdir_p(const char *path)
4878 {
4879     int ret = 0;
4880     char *temp = av_strdup(path);
4881     char *pos = temp;
4882     char tmp_ch = '\0';
4883
4884     if (!path || !temp) {
4885         return -1;
4886     }
4887
4888     if (!av_strncasecmp(temp, "/", 1) || !av_strncasecmp(temp, "\\", 1)) {
4889         pos++;
4890     } else if (!av_strncasecmp(temp, "./", 2) || !av_strncasecmp(temp, ".\\", 2)) {
4891         pos += 2;
4892     }
4893
4894     for ( ; *pos != '\0'; ++pos) {
4895         if (*pos == '/' || *pos == '\\') {
4896             tmp_ch = *pos;
4897             *pos = '\0';
4898             ret = mkdir(temp, 0755);
4899             *pos = tmp_ch;
4900         }
4901     }
4902
4903     if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
4904         ret = mkdir(temp, 0755);
4905     }
4906
4907     av_free(temp);
4908     return ret;
4909 }
4910
4911 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4912 {
4913     int i;
4914     static const char hex_table_uc[16] = { '0', '1', '2', '3',
4915                                            '4', '5', '6', '7',
4916                                            '8', '9', 'A', 'B',
4917                                            'C', 'D', 'E', 'F' };
4918     static const char hex_table_lc[16] = { '0', '1', '2', '3',
4919                                            '4', '5', '6', '7',
4920                                            '8', '9', 'a', 'b',
4921                                            'c', 'd', 'e', 'f' };
4922     const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
4923
4924     for (i = 0; i < s; i++) {
4925         buff[i * 2]     = hex_table[src[i] >> 4];
4926         buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4927     }
4928
4929     return buff;
4930 }
4931
4932 int ff_hex_to_data(uint8_t *data, const char *p)
4933 {
4934     int c, len, v;
4935
4936     len = 0;
4937     v   = 1;
4938     for (;;) {
4939         p += strspn(p, SPACE_CHARS);
4940         if (*p == '\0')
4941             break;
4942         c = av_toupper((unsigned char) *p++);
4943         if (c >= '0' && c <= '9')
4944             c = c - '0';
4945         else if (c >= 'A' && c <= 'F')
4946             c = c - 'A' + 10;
4947         else
4948             break;
4949         v = (v << 4) | c;
4950         if (v & 0x100) {
4951             if (data)
4952                 data[len] = v;
4953             len++;
4954             v = 1;
4955         }
4956     }
4957     return len;
4958 }
4959
4960 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
4961                          unsigned int pts_num, unsigned int pts_den)
4962 {
4963     AVRational new_tb;
4964     if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
4965         if (new_tb.num != pts_num)
4966             av_log(NULL, AV_LOG_DEBUG,
4967                    "st:%d removing common factor %d from timebase\n",
4968                    s->index, pts_num / new_tb.num);
4969     } else
4970         av_log(NULL, AV_LOG_WARNING,
4971                "st:%d has too large timebase, reducing\n", s->index);
4972
4973     if (new_tb.num <= 0 || new_tb.den <= 0) {
4974         av_log(NULL, AV_LOG_ERROR,
4975                "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
4976                new_tb.num, new_tb.den,
4977                s->index);
4978         return;
4979     }
4980     s->time_base     = new_tb;
4981 #if FF_API_LAVF_AVCTX
4982 FF_DISABLE_DEPRECATION_WARNINGS
4983     s->codec->pkt_timebase = new_tb;
4984 FF_ENABLE_DEPRECATION_WARNINGS
4985 #endif
4986     s->internal->avctx->pkt_timebase = new_tb;
4987     s->pts_wrap_bits = pts_wrap_bits;
4988 }
4989
4990 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4991                         void *context)
4992 {
4993     const char *ptr = str;
4994
4995     /* Parse key=value pairs. */
4996     for (;;) {
4997         const char *key;
4998         char *dest = NULL, *dest_end;
4999         int key_len, dest_len = 0;
5000
5001         /* Skip whitespace and potential commas. */
5002         while (*ptr && (av_isspace(*ptr) || *ptr == ','))
5003             ptr++;
5004         if (!*ptr)
5005             break;
5006
5007         key = ptr;
5008
5009         if (!(ptr = strchr(key, '=')))
5010             break;
5011         ptr++;
5012         key_len = ptr - key;
5013
5014         callback_get_buf(context, key, key_len, &dest, &dest_len);
5015         dest_end = dest + dest_len - 1;
5016
5017         if (*ptr == '\"') {
5018             ptr++;
5019             while (*ptr && *ptr != '\"') {
5020                 if (*ptr == '\\') {
5021                     if (!ptr[1])
5022                         break;
5023                     if (dest && dest < dest_end)
5024                         *dest++ = ptr[1];
5025                     ptr += 2;
5026                 } else {
5027                     if (dest && dest < dest_end)
5028                         *dest++ = *ptr;
5029                     ptr++;
5030                 }
5031             }
5032             if (*ptr == '\"')
5033                 ptr++;
5034         } else {
5035             for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
5036                 if (dest && dest < dest_end)
5037                     *dest++ = *ptr;
5038         }
5039         if (dest)
5040             *dest = 0;
5041     }
5042 }
5043
5044 int ff_find_stream_index(AVFormatContext *s, int id)
5045 {
5046     int i;
5047     for (i = 0; i < s->nb_streams; i++)
5048         if (s->streams[i]->id == id)
5049             return i;
5050     return -1;
5051 }
5052
5053 int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
5054                          int std_compliance)
5055 {
5056     if (ofmt) {
5057         unsigned int codec_tag;
5058         if (ofmt->query_codec)
5059             return ofmt->query_codec(codec_id, std_compliance);
5060         else if (ofmt->codec_tag)
5061             return !!av_codec_get_tag2(ofmt->codec_tag, codec_id, &codec_tag);
5062         else if (codec_id == ofmt->video_codec ||
5063                  codec_id == ofmt->audio_codec ||
5064                  codec_id == ofmt->subtitle_codec ||
5065                  codec_id == ofmt->data_codec)
5066             return 1;
5067     }
5068     return AVERROR_PATCHWELCOME;
5069 }
5070
5071 int avformat_network_init(void)
5072 {
5073 #if CONFIG_NETWORK
5074     int ret;
5075     if ((ret = ff_network_init()) < 0)
5076         return ret;
5077     if ((ret = ff_tls_init()) < 0)
5078         return ret;
5079 #endif
5080     return 0;
5081 }
5082
5083 int avformat_network_deinit(void)
5084 {
5085 #if CONFIG_NETWORK
5086     ff_network_close();
5087     ff_tls_deinit();
5088 #endif
5089     return 0;
5090 }
5091
5092 int ff_add_param_change(AVPacket *pkt, int32_t channels,
5093                         uint64_t channel_layout, int32_t sample_rate,
5094                         int32_t width, int32_t height)
5095 {
5096     uint32_t flags = 0;
5097     int size = 4;
5098     uint8_t *data;
5099     if (!pkt)
5100         return AVERROR(EINVAL);
5101     if (channels) {
5102         size  += 4;
5103         flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
5104     }
5105     if (channel_layout) {
5106         size  += 8;
5107         flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
5108     }
5109     if (sample_rate) {
5110         size  += 4;
5111         flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
5112     }
5113     if (width || height) {
5114         size  += 8;
5115         flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
5116     }
5117     data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
5118     if (!data)
5119         return AVERROR(ENOMEM);
5120     bytestream_put_le32(&data, flags);
5121     if (channels)
5122         bytestream_put_le32(&data, channels);
5123     if (channel_layout)
5124         bytestream_put_le64(&data, channel_layout);
5125     if (sample_rate)
5126         bytestream_put_le32(&data, sample_rate);
5127     if (width || height) {
5128         bytestream_put_le32(&data, width);
5129         bytestream_put_le32(&data, height);
5130     }
5131     return 0;
5132 }
5133
5134 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
5135 {
5136     AVRational undef = {0, 1};
5137     AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
5138     AVRational codec_sample_aspect_ratio  = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
5139     AVRational frame_sample_aspect_ratio  = frame  ? frame->sample_aspect_ratio  : codec_sample_aspect_ratio;
5140
5141     av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
5142                stream_sample_aspect_ratio.num,  stream_sample_aspect_ratio.den, INT_MAX);
5143     if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
5144         stream_sample_aspect_ratio = undef;
5145
5146     av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
5147                frame_sample_aspect_ratio.num,  frame_sample_aspect_ratio.den, INT_MAX);
5148     if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
5149         frame_sample_aspect_ratio = undef;
5150
5151     if (stream_sample_aspect_ratio.num)
5152         return stream_sample_aspect_ratio;
5153     else
5154         return frame_sample_aspect_ratio;
5155 }
5156
5157 AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
5158 {
5159     AVRational fr = st->r_frame_rate;
5160     AVRational codec_fr = st->internal->avctx->framerate;
5161     AVRational   avg_fr = st->avg_frame_rate;
5162
5163     if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
5164         av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
5165         fr = avg_fr;
5166     }
5167
5168
5169     if (st->internal->avctx->ticks_per_frame > 1) {
5170         if (   codec_fr.num > 0 && codec_fr.den > 0 &&
5171             (fr.num == 0 || av_q2d(codec_fr) < av_q2d(fr)*0.7 && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1))
5172             fr = codec_fr;
5173     }
5174
5175     return fr;
5176 }
5177
5178 /**
5179  * Matches a stream specifier (but ignores requested index).
5180  *
5181  * @param indexptr set to point to the requested stream index if there is one
5182  *
5183  * @return <0 on error
5184  *         0  if st is NOT a matching stream
5185  *         >0 if st is a matching stream
5186  */
5187 static int match_stream_specifier(AVFormatContext *s, AVStream *st,
5188                                   const char *spec, const char **indexptr, AVProgram **p)
5189 {
5190     int match = 1;                      /* Stores if the specifier matches so far. */
5191     while (*spec) {
5192         if (*spec <= '9' && *spec >= '0') { /* opt:index */
5193             if (indexptr)
5194                 *indexptr = spec;
5195             return match;
5196         } else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
5197                    *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
5198             enum AVMediaType type;
5199             int nopic = 0;
5200
5201             switch (*spec++) {
5202             case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
5203             case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
5204             case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
5205             case 'd': type = AVMEDIA_TYPE_DATA;       break;
5206             case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
5207             case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
5208             default:  av_assert0(0);
5209             }
5210             if (*spec && *spec++ != ':')         /* If we are not at the end, then another specifier must follow. */
5211                 return AVERROR(EINVAL);
5212
5213 #if FF_API_LAVF_AVCTX
5214 FF_DISABLE_DEPRECATION_WARNINGS
5215             if (type != st->codecpar->codec_type
5216                && (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN || st->codec->codec_type != type))
5217                 match = 0;
5218     FF_ENABLE_DEPRECATION_WARNINGS
5219 #else
5220             if (type != st->codecpar->codec_type)
5221                 match = 0;
5222 #endif
5223             if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
5224                 match = 0;
5225         } else if (*spec == 'p' && *(spec + 1) == ':') {
5226             int prog_id, i, j;
5227             int found = 0;
5228             char *endptr;
5229             spec += 2;
5230             prog_id = strtol(spec, &endptr, 0);
5231             /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
5232             if (spec == endptr || (*endptr && *endptr++ != ':'))
5233                 return AVERROR(EINVAL);
5234             spec = endptr;
5235             if (match) {
5236                 for (i = 0; i < s->nb_programs; i++) {
5237                     if (s->programs[i]->id != prog_id)
5238                         continue;
5239
5240                     for (j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
5241                         if (st->index == s->programs[i]->stream_index[j]) {
5242                             found = 1;
5243                             if (p)
5244                                 *p = s->programs[i];
5245                             i = s->nb_programs;
5246                             break;
5247                         }
5248                     }
5249                 }
5250             }
5251             if (!found)
5252                 match = 0;
5253         } else if (*spec == '#' ||
5254                    (*spec == 'i' && *(spec + 1) == ':')) {
5255             int stream_id;
5256             char *endptr;
5257             spec += 1 + (*spec == 'i');
5258             stream_id = strtol(spec, &endptr, 0);
5259             if (spec == endptr || *endptr)                /* Disallow empty id and make sure we are at the end. */
5260                 return AVERROR(EINVAL);
5261             return match && (stream_id == st->id);
5262         } else if (*spec == 'm' && *(spec + 1) == ':') {
5263             AVDictionaryEntry *tag;
5264             char *key, *val;
5265             int ret;
5266
5267             if (match) {
5268                spec += 2;
5269                val = strchr(spec, ':');
5270
5271                key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
5272                if (!key)
5273                    return AVERROR(ENOMEM);
5274
5275                tag = av_dict_get(st->metadata, key, NULL, 0);
5276                if (tag) {
5277                    if (!val || !strcmp(tag->value, val + 1))
5278                        ret = 1;
5279                    else
5280                        ret = 0;
5281                } else
5282                    ret = 0;
5283
5284                av_freep(&key);
5285             }
5286             return match && ret;
5287         } else if (*spec == 'u' && *(spec + 1) == '\0') {
5288             AVCodecParameters *par = st->codecpar;
5289 #if FF_API_LAVF_AVCTX
5290 FF_DISABLE_DEPRECATION_WARNINGS
5291             AVCodecContext *codec = st->codec;
5292 FF_ENABLE_DEPRECATION_WARNINGS
5293 #endif
5294             int val;
5295             switch (par->codec_type) {
5296             case AVMEDIA_TYPE_AUDIO:
5297                 val = par->sample_rate && par->channels;
5298 #if FF_API_LAVF_AVCTX
5299                 val = val || (codec->sample_rate && codec->channels);
5300 #endif
5301                 if (par->format == AV_SAMPLE_FMT_NONE
5302 #if FF_API_LAVF_AVCTX
5303                     && codec->sample_fmt == AV_SAMPLE_FMT_NONE
5304 #endif
5305                     )
5306                     return 0;
5307                 break;
5308             case AVMEDIA_TYPE_VIDEO:
5309                 val = par->width && par->height;
5310 #if FF_API_LAVF_AVCTX
5311                 val = val || (codec->width && codec->height);
5312 #endif
5313                 if (par->format == AV_PIX_FMT_NONE
5314 #if FF_API_LAVF_AVCTX
5315                     && codec->pix_fmt == AV_PIX_FMT_NONE
5316 #endif
5317                     )
5318                     return 0;
5319                 break;
5320             case AVMEDIA_TYPE_UNKNOWN:
5321                 val = 0;
5322                 break;
5323             default:
5324                 val = 1;
5325                 break;
5326             }
5327 #if FF_API_LAVF_AVCTX
5328             return match && ((par->codec_id != AV_CODEC_ID_NONE || codec->codec_id != AV_CODEC_ID_NONE) && val != 0);
5329 #else
5330             return match && (par->codec_id != AV_CODEC_ID_NONE && val != 0);
5331 #endif
5332         } else {
5333             return AVERROR(EINVAL);
5334         }
5335     }
5336
5337     return match;
5338 }
5339
5340
5341 int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
5342                                     const char *spec)
5343 {
5344     int ret, index;
5345     char *endptr;
5346     const char *indexptr = NULL;
5347     AVProgram *p = NULL;
5348     int nb_streams;
5349
5350     ret = match_stream_specifier(s, st, spec, &indexptr, &p);
5351     if (ret < 0)
5352         goto error;
5353
5354     if (!indexptr)
5355         return ret;
5356
5357     index = strtol(indexptr, &endptr, 0);
5358     if (*endptr) {                  /* We can't have anything after the requested index. */
5359         ret = AVERROR(EINVAL);
5360         goto error;
5361     }
5362
5363     /* This is not really needed but saves us a loop for simple stream index specifiers. */
5364     if (spec == indexptr)
5365         return (index == st->index);
5366
5367     /* If we requested a matching stream index, we have to ensure st is that. */
5368     nb_streams = p ? p->nb_stream_indexes : s->nb_streams;
5369     for (int i = 0; i < nb_streams && index >= 0; i++) {
5370         AVStream *candidate = p ? s->streams[p->stream_index[i]] : s->streams[i];
5371         ret = match_stream_specifier(s, candidate, spec, NULL, NULL);
5372         if (ret < 0)
5373             goto error;
5374         if (ret > 0 && index-- == 0 && st == candidate)
5375             return 1;
5376     }
5377     return 0;
5378
5379 error:
5380     if (ret == AVERROR(EINVAL))
5381         av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
5382     return ret;
5383 }
5384
5385 int ff_generate_avci_extradata(AVStream *st)
5386 {
5387     static const uint8_t avci100_1080p_extradata[] = {
5388         // SPS
5389         0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5390         0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5391         0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5392         0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
5393         0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
5394         0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
5395         0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
5396         0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
5397         0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
5398         // PPS
5399         0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5400         0xd0
5401     };
5402     static const uint8_t avci100_1080i_extradata[] = {
5403         // SPS
5404         0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5405         0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5406         0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5407         0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
5408         0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
5409         0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
5410         0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
5411         0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
5412         0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
5413         0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
5414         0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
5415         // PPS
5416         0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5417         0xd0
5418     };
5419     static const uint8_t avci50_1080p_extradata[] = {
5420         // SPS
5421         0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5422         0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5423         0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5424         0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5425         0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5426         0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
5427         0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
5428         0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
5429         0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
5430         // PPS
5431         0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5432         0x11
5433     };
5434     static const uint8_t avci50_1080i_extradata[] = {
5435         // SPS
5436         0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5437         0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5438         0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5439         0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
5440         0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
5441         0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
5442         0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
5443         0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
5444         0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
5445         0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
5446         0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
5447         // PPS
5448         0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5449         0x11
5450     };
5451     static const uint8_t avci100_720p_extradata[] = {
5452         // SPS
5453         0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5454         0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
5455         0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
5456         0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
5457         0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
5458         0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
5459         0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
5460         0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
5461         0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
5462         0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
5463         // PPS
5464         0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
5465         0x11
5466     };
5467     static const uint8_t avci50_720p_extradata[] = {
5468         // SPS
5469         0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
5470         0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5471         0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5472         0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5473         0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5474         0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
5475         0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
5476         0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
5477         0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
5478         // PPS
5479         0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5480         0x11
5481     };
5482
5483     const uint8_t *data = NULL;
5484     int ret, size       = 0;
5485
5486     if (st->codecpar->width == 1920) {
5487         if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5488             data = avci100_1080p_extradata;
5489             size = sizeof(avci100_1080p_extradata);
5490         } else {
5491             data = avci100_1080i_extradata;
5492             size = sizeof(avci100_1080i_extradata);
5493         }
5494     } else if (st->codecpar->width == 1440) {
5495         if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5496             data = avci50_1080p_extradata;
5497             size = sizeof(avci50_1080p_extradata);
5498         } else {
5499             data = avci50_1080i_extradata;
5500             size = sizeof(avci50_1080i_extradata);
5501         }
5502     } else if (st->codecpar->width == 1280) {
5503         data = avci100_720p_extradata;
5504         size = sizeof(avci100_720p_extradata);
5505     } else if (st->codecpar->width == 960) {
5506         data = avci50_720p_extradata;
5507         size = sizeof(avci50_720p_extradata);
5508     }
5509
5510     if (!size)
5511         return 0;
5512
5513     if ((ret = ff_alloc_extradata(st->codecpar, size)) < 0)
5514         return ret;
5515     memcpy(st->codecpar->extradata, data, size);
5516
5517     return 0;
5518 }
5519
5520 uint8_t *av_stream_get_side_data(const AVStream *st,
5521                                  enum AVPacketSideDataType type, buffer_size_t *size)
5522 {
5523     int i;
5524
5525     for (i = 0; i < st->nb_side_data; i++) {
5526         if (st->side_data[i].type == type) {
5527             if (size)
5528                 *size = st->side_data[i].size;
5529             return st->side_data[i].data;
5530         }
5531     }
5532     if (size)
5533         *size = 0;
5534     return NULL;
5535 }
5536
5537 int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
5538                             uint8_t *data, size_t size)
5539 {
5540     AVPacketSideData *sd, *tmp;
5541     int i;
5542
5543     for (i = 0; i < st->nb_side_data; i++) {
5544         sd = &st->side_data[i];
5545
5546         if (sd->type == type) {
5547             av_freep(&sd->data);
5548             sd->data = data;
5549             sd->size = size;
5550             return 0;
5551         }
5552     }
5553
5554     if ((unsigned)st->nb_side_data + 1 >= INT_MAX / sizeof(*st->side_data))
5555         return AVERROR(ERANGE);
5556
5557     tmp = av_realloc(st->side_data, (st->nb_side_data + 1) * sizeof(*tmp));
5558     if (!tmp) {
5559         return AVERROR(ENOMEM);
5560     }
5561
5562     st->side_data = tmp;
5563     st->nb_side_data++;
5564
5565     sd = &st->side_data[st->nb_side_data - 1];
5566     sd->type = type;
5567     sd->data = data;
5568     sd->size = size;
5569
5570     return 0;
5571 }
5572
5573 uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
5574                                  buffer_size_t size)
5575 {
5576     int ret;
5577     uint8_t *data = av_malloc(size);
5578
5579     if (!data)
5580         return NULL;
5581
5582     ret = av_stream_add_side_data(st, type, data, size);
5583     if (ret < 0) {
5584         av_freep(&data);
5585         return NULL;
5586     }
5587
5588     return data;
5589 }
5590
5591 int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
5592 {
5593     int ret;
5594     const AVBitStreamFilter *bsf;
5595     AVBSFContext *bsfc;
5596
5597     av_assert0(!st->internal->bsfc);
5598
5599     if (!(bsf = av_bsf_get_by_name(name))) {
5600         av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter '%s'\n", name);
5601         return AVERROR_BSF_NOT_FOUND;
5602     }
5603
5604     if ((ret = av_bsf_alloc(bsf, &bsfc)) < 0)
5605         return ret;
5606
5607     bsfc->time_base_in = st->time_base;
5608     if ((ret = avcodec_parameters_copy(bsfc->par_in, st->codecpar)) < 0) {
5609         av_bsf_free(&bsfc);
5610         return ret;
5611     }
5612
5613     if (args && bsfc->filter->priv_class) {
5614         const AVOption *opt = av_opt_next(bsfc->priv_data, NULL);
5615         const char * shorthand[2] = {NULL};
5616
5617         if (opt)
5618             shorthand[0] = opt->name;
5619
5620         if ((ret = av_opt_set_from_string(bsfc->priv_data, args, shorthand, "=", ":")) < 0) {
5621             av_bsf_free(&bsfc);
5622             return ret;
5623         }
5624     }
5625
5626     if ((ret = av_bsf_init(bsfc)) < 0) {
5627         av_bsf_free(&bsfc);
5628         return ret;
5629     }
5630
5631     st->internal->bsfc = bsfc;
5632
5633     av_log(NULL, AV_LOG_VERBOSE,
5634            "Automatically inserted bitstream filter '%s'; args='%s'\n",
5635            name, args ? args : "");
5636     return 1;
5637 }
5638
5639 int ff_format_output_open(AVFormatContext *s, const char *url, AVDictionary **options)
5640 {
5641     if (!s->oformat)
5642         return AVERROR(EINVAL);
5643
5644     if (!(s->oformat->flags & AVFMT_NOFILE))
5645         return s->io_open(s, &s->pb, url, AVIO_FLAG_WRITE, options);
5646     return 0;
5647 }
5648
5649 void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
5650 {
5651     if (*pb)
5652         s->io_close(s, *pb);
5653     *pb = NULL;
5654 }
5655
5656 int ff_is_http_proto(char *filename) {
5657     const char *proto = avio_find_protocol_name(filename);
5658     return proto ? (!av_strcasecmp(proto, "http") || !av_strcasecmp(proto, "https")) : 0;
5659 }
5660
5661 int ff_parse_creation_time_metadata(AVFormatContext *s, int64_t *timestamp, int return_seconds)
5662 {
5663     AVDictionaryEntry *entry;
5664     int64_t parsed_timestamp;
5665     int ret;
5666     if ((entry = av_dict_get(s->metadata, "creation_time", NULL, 0))) {
5667         if ((ret = av_parse_time(&parsed_timestamp, entry->value, 0)) >= 0) {
5668             *timestamp = return_seconds ? parsed_timestamp / 1000000 : parsed_timestamp;
5669             return 1;
5670         } else {
5671             av_log(s, AV_LOG_WARNING, "Failed to parse creation_time %s\n", entry->value);
5672             return ret;
5673         }
5674     }
5675     return 0;
5676 }
5677
5678 int ff_standardize_creation_time(AVFormatContext *s)
5679 {
5680     int64_t timestamp;
5681     int ret = ff_parse_creation_time_metadata(s, &timestamp, 0);
5682     if (ret == 1)
5683         return avpriv_dict_set_timestamp(&s->metadata, "creation_time", timestamp);
5684     return ret;
5685 }
5686
5687 int ff_get_packet_palette(AVFormatContext *s, AVPacket *pkt, int ret, uint32_t *palette)
5688 {
5689     uint8_t *side_data;
5690     buffer_size_t size;
5691
5692     side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_PALETTE, &size);
5693     if (side_data) {
5694         if (size != AVPALETTE_SIZE) {
5695             av_log(s, AV_LOG_ERROR, "Invalid palette side data\n");
5696             return AVERROR_INVALIDDATA;
5697         }
5698         memcpy(palette, side_data, AVPALETTE_SIZE);
5699         return 1;
5700     }
5701
5702     if (ret == CONTAINS_PAL) {
5703         int i;
5704         for (i = 0; i < AVPALETTE_COUNT; i++)
5705             palette[i] = AV_RL32(pkt->data + pkt->size - AVPALETTE_SIZE + i*4);
5706         return 1;
5707     }
5708
5709     return 0;
5710 }
5711
5712 int ff_bprint_to_codecpar_extradata(AVCodecParameters *par, struct AVBPrint *buf)
5713 {
5714     int ret;
5715     char *str;
5716
5717     ret = av_bprint_finalize(buf, &str);
5718     if (ret < 0)
5719         return ret;
5720     if (!av_bprint_is_complete(buf)) {
5721         av_free(str);
5722         return AVERROR(ENOMEM);
5723     }
5724
5725     par->extradata = str;
5726     /* Note: the string is NUL terminated (so extradata can be read as a
5727      * string), but the ending character is not accounted in the size (in
5728      * binary formats you are likely not supposed to mux that character). When
5729      * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
5730      * zeros. */
5731     par->extradata_size = buf->len;
5732     return 0;
5733 }
5734
5735 int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
5736                                                   AVStream *ost, const AVStream *ist,
5737                                                   enum AVTimebaseSource copy_tb)
5738 {
5739     //TODO: use [io]st->internal->avctx
5740     const AVCodecContext *dec_ctx;
5741     AVCodecContext       *enc_ctx;
5742
5743 #if FF_API_LAVF_AVCTX
5744 FF_DISABLE_DEPRECATION_WARNINGS
5745     dec_ctx = ist->codec;
5746     enc_ctx = ost->codec;
5747 FF_ENABLE_DEPRECATION_WARNINGS
5748 #else
5749     dec_ctx = ist->internal->avctx;
5750     enc_ctx = ost->internal->avctx;
5751 #endif
5752
5753     enc_ctx->time_base = ist->time_base;
5754     /*
5755      * Avi is a special case here because it supports variable fps but
5756      * having the fps and timebase differe significantly adds quite some
5757      * overhead
5758      */
5759     if (!strcmp(ofmt->name, "avi")) {
5760 #if FF_API_R_FRAME_RATE
5761         if (copy_tb == AVFMT_TBCF_AUTO && ist->r_frame_rate.num
5762             && av_q2d(ist->r_frame_rate) >= av_q2d(ist->avg_frame_rate)
5763             && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(ist->time_base)
5764             && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(dec_ctx->time_base)
5765             && av_q2d(ist->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
5766             || copy_tb == AVFMT_TBCF_R_FRAMERATE) {
5767             enc_ctx->time_base.num = ist->r_frame_rate.den;
5768             enc_ctx->time_base.den = 2*ist->r_frame_rate.num;
5769             enc_ctx->ticks_per_frame = 2;
5770         } else
5771 #endif
5772             if (copy_tb == AVFMT_TBCF_AUTO && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->time_base)
5773                    && av_q2d(ist->time_base) < 1.0/500
5774                    || copy_tb == AVFMT_TBCF_DECODER) {
5775             enc_ctx->time_base = dec_ctx->time_base;
5776             enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5777             enc_ctx->time_base.den *= 2;
5778             enc_ctx->ticks_per_frame = 2;
5779         }
5780     } else if (!(ofmt->flags & AVFMT_VARIABLE_FPS)
5781                && !av_match_name(ofmt->name, "mov,mp4,3gp,3g2,psp,ipod,ismv,f4v")) {
5782         if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx->time_base.den
5783             && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->time_base)
5784             && av_q2d(ist->time_base) < 1.0/500
5785             || copy_tb == AVFMT_TBCF_DECODER) {
5786             enc_ctx->time_base = dec_ctx->time_base;
5787             enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5788         }
5789     }
5790
5791     if ((enc_ctx->codec_tag == AV_RL32("tmcd") || ost->codecpar->codec_tag == AV_RL32("tmcd"))
5792         && dec_ctx->time_base.num < dec_ctx->time_base.den
5793         && dec_ctx->time_base.num > 0
5794         && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
5795         enc_ctx->time_base = dec_ctx->time_base;
5796     }
5797
5798     av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
5799               enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
5800
5801     return 0;
5802 }
5803
5804 AVRational av_stream_get_codec_timebase(const AVStream *st)
5805 {
5806     // See avformat_transfer_internal_stream_timing_info() TODO.
5807 #if FF_API_LAVF_AVCTX
5808 FF_DISABLE_DEPRECATION_WARNINGS
5809     return st->codec->time_base;
5810 FF_ENABLE_DEPRECATION_WARNINGS
5811 #else
5812     return st->internal->avctx->time_base;
5813 #endif
5814 }
5815
5816 void ff_format_set_url(AVFormatContext *s, char *url)
5817 {
5818     av_assert0(url);
5819     av_freep(&s->url);
5820     s->url = url;
5821 #if FF_API_FORMAT_FILENAME
5822 FF_DISABLE_DEPRECATION_WARNINGS
5823     av_strlcpy(s->filename, url, sizeof(s->filename));
5824 FF_ENABLE_DEPRECATION_WARNINGS
5825 #endif
5826 }