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