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