]> git.sesse.net Git - ffmpeg/blob - libavformat/utils.c
mpegvideo: use the AVVideoEncParams API for exporting QP tables
[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 *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 void compute_chapters_end(AVFormatContext *s)
3197 {
3198     unsigned int i, j;
3199     int64_t max_time = 0;
3200
3201     if (s->duration > 0 && s->start_time < INT64_MAX - s->duration)
3202         max_time = s->duration +
3203                        ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
3204
3205     for (i = 0; i < s->nb_chapters; i++)
3206         if (s->chapters[i]->end == AV_NOPTS_VALUE) {
3207             AVChapter *ch = s->chapters[i];
3208             int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
3209                                                   ch->time_base)
3210                                    : INT64_MAX;
3211
3212             for (j = 0; j < s->nb_chapters; j++) {
3213                 AVChapter *ch1     = s->chapters[j];
3214                 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
3215                                                   ch->time_base);
3216                 if (j != i && next_start > ch->start && next_start < end)
3217                     end = next_start;
3218             }
3219             ch->end = (end == INT64_MAX || end < ch->start) ? ch->start : end;
3220         }
3221 }
3222
3223 static int get_std_framerate(int i)
3224 {
3225     if (i < 30*12)
3226         return (i + 1) * 1001;
3227     i -= 30*12;
3228
3229     if (i < 30)
3230         return (i + 31) * 1001 * 12;
3231     i -= 30;
3232
3233     if (i < 3)
3234         return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;
3235
3236     i -= 3;
3237
3238     return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
3239 }
3240
3241 /* Is the time base unreliable?
3242  * This is a heuristic to balance between quick acceptance of the values in
3243  * the headers vs. some extra checks.
3244  * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
3245  * MPEG-2 commonly misuses field repeat flags to store different framerates.
3246  * And there are "variable" fps files this needs to detect as well. */
3247 static int tb_unreliable(AVCodecContext *c)
3248 {
3249     if (c->time_base.den >= 101LL * c->time_base.num ||
3250         c->time_base.den <    5LL * c->time_base.num ||
3251         // c->codec_tag == AV_RL32("DIVX") ||
3252         // c->codec_tag == AV_RL32("XVID") ||
3253         c->codec_tag == AV_RL32("mp4v") ||
3254         c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
3255         c->codec_id == AV_CODEC_ID_GIF ||
3256         c->codec_id == AV_CODEC_ID_HEVC ||
3257         c->codec_id == AV_CODEC_ID_H264)
3258         return 1;
3259     return 0;
3260 }
3261
3262 int ff_alloc_extradata(AVCodecParameters *par, int size)
3263 {
3264     av_freep(&par->extradata);
3265     par->extradata_size = 0;
3266
3267     if (size < 0 || size >= INT32_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
3268         return AVERROR(EINVAL);
3269
3270     par->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
3271     if (!par->extradata)
3272         return AVERROR(ENOMEM);
3273
3274     memset(par->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3275     par->extradata_size = size;
3276
3277     return 0;
3278 }
3279
3280 int ff_get_extradata(AVFormatContext *s, AVCodecParameters *par, AVIOContext *pb, int size)
3281 {
3282     int ret = ff_alloc_extradata(par, size);
3283     if (ret < 0)
3284         return ret;
3285     ret = avio_read(pb, par->extradata, size);
3286     if (ret != size) {
3287         av_freep(&par->extradata);
3288         par->extradata_size = 0;
3289         av_log(s, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
3290         return ret < 0 ? ret : AVERROR_INVALIDDATA;
3291     }
3292
3293     return ret;
3294 }
3295
3296 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
3297 {
3298     int i, j;
3299     int64_t last = st->internal->info->last_dts;
3300
3301     if (   ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
3302        && ts - (uint64_t)last < INT64_MAX) {
3303         double dts = (is_relative(ts) ?  ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
3304         int64_t duration = ts - last;
3305
3306         if (!st->internal->info->duration_error)
3307             st->internal->info->duration_error = av_mallocz(sizeof(st->internal->info->duration_error[0])*2);
3308         if (!st->internal->info->duration_error)
3309             return AVERROR(ENOMEM);
3310
3311 //         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3312 //             av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
3313         for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3314             if (st->internal->info->duration_error[0][1][i] < 1e10) {
3315                 int framerate = get_std_framerate(i);
3316                 double sdts = dts*framerate/(1001*12);
3317                 for (j= 0; j<2; j++) {
3318                     int64_t ticks = llrint(sdts+j*0.5);
3319                     double error= sdts - ticks + j*0.5;
3320                     st->internal->info->duration_error[j][0][i] += error;
3321                     st->internal->info->duration_error[j][1][i] += error*error;
3322                 }
3323             }
3324         }
3325         if (st->internal->info->rfps_duration_sum <= INT64_MAX - duration) {
3326             st->internal->info->duration_count++;
3327             st->internal->info->rfps_duration_sum += duration;
3328         }
3329
3330         if (st->internal->info->duration_count % 10 == 0) {
3331             int n = st->internal->info->duration_count;
3332             for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3333                 if (st->internal->info->duration_error[0][1][i] < 1e10) {
3334                     double a0     = st->internal->info->duration_error[0][0][i] / n;
3335                     double error0 = st->internal->info->duration_error[0][1][i] / n - a0*a0;
3336                     double a1     = st->internal->info->duration_error[1][0][i] / n;
3337                     double error1 = st->internal->info->duration_error[1][1][i] / n - a1*a1;
3338                     if (error0 > 0.04 && error1 > 0.04) {
3339                         st->internal->info->duration_error[0][1][i] = 2e10;
3340                         st->internal->info->duration_error[1][1][i] = 2e10;
3341                     }
3342                 }
3343             }
3344         }
3345
3346         // ignore the first 4 values, they might have some random jitter
3347         if (st->internal->info->duration_count > 3 && is_relative(ts) == is_relative(last))
3348             st->internal->info->duration_gcd = av_gcd(st->internal->info->duration_gcd, duration);
3349     }
3350     if (ts != AV_NOPTS_VALUE)
3351         st->internal->info->last_dts = ts;
3352
3353     return 0;
3354 }
3355
3356 void ff_rfps_calculate(AVFormatContext *ic)
3357 {
3358     int i, j;
3359
3360     for (i = 0; i < ic->nb_streams; i++) {
3361         AVStream *st = ic->streams[i];
3362
3363         if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
3364             continue;
3365         // the check for tb_unreliable() is not completely correct, since this is not about handling
3366         // an unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3367         // ipmovie.c produces.
3368         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)
3369             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);
3370         if (st->internal->info->duration_count>1 && !st->r_frame_rate.num
3371             && tb_unreliable(st->internal->avctx)) {
3372             int num = 0;
3373             double best_error= 0.01;
3374             AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3375
3376             for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3377                 int k;
3378
3379                 if (st->internal->info->codec_info_duration &&
3380                     st->internal->info->codec_info_duration*av_q2d(st->time_base) < (1001*11.5)/get_std_framerate(j))
3381                     continue;
3382                 if (!st->internal->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3383                     continue;
3384
3385                 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))
3386                     continue;
3387
3388                 for (k= 0; k<2; k++) {
3389                     int n = st->internal->info->duration_count;
3390                     double a= st->internal->info->duration_error[k][0][j] / n;
3391                     double error= st->internal->info->duration_error[k][1][j]/n - a*a;
3392
3393                     if (error < best_error && best_error> 0.000000001) {
3394                         best_error= error;
3395                         num = get_std_framerate(j);
3396                     }
3397                     if (error < 0.02)
3398                         av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3399                 }
3400             }
3401             // do not increase frame rate by more than 1 % in order to match a standard rate.
3402             if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3403                 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3404         }
3405         if (   !st->avg_frame_rate.num
3406             && st->r_frame_rate.num && st->internal->info->rfps_duration_sum
3407             && st->internal->info->codec_info_duration <= 0
3408             && st->internal->info->duration_count > 2
3409             && 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
3410             ) {
3411             av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3412             st->avg_frame_rate = st->r_frame_rate;
3413         }
3414
3415         av_freep(&st->internal->info->duration_error);
3416         st->internal->info->last_dts = AV_NOPTS_VALUE;
3417         st->internal->info->duration_count = 0;
3418         st->internal->info->rfps_duration_sum = 0;
3419     }
3420 }
3421
3422 static int extract_extradata_check(AVStream *st)
3423 {
3424     const AVBitStreamFilter *f;
3425
3426     f = av_bsf_get_by_name("extract_extradata");
3427     if (!f)
3428         return 0;
3429
3430     if (f->codec_ids) {
3431         const enum AVCodecID *ids;
3432         for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
3433             if (*ids == st->codecpar->codec_id)
3434                 return 1;
3435     }
3436
3437     return 0;
3438 }
3439
3440 static int extract_extradata_init(AVStream *st)
3441 {
3442     AVStreamInternal *sti = st->internal;
3443     const AVBitStreamFilter *f;
3444     int ret;
3445
3446     f = av_bsf_get_by_name("extract_extradata");
3447     if (!f)
3448         goto finish;
3449
3450     /* check that the codec id is supported */
3451     ret = extract_extradata_check(st);
3452     if (!ret)
3453         goto finish;
3454
3455     sti->extract_extradata.pkt = av_packet_alloc();
3456     if (!sti->extract_extradata.pkt)
3457         return AVERROR(ENOMEM);
3458
3459     ret = av_bsf_alloc(f, &sti->extract_extradata.bsf);
3460     if (ret < 0)
3461         goto fail;
3462
3463     ret = avcodec_parameters_copy(sti->extract_extradata.bsf->par_in,
3464                                   st->codecpar);
3465     if (ret < 0)
3466         goto fail;
3467
3468     sti->extract_extradata.bsf->time_base_in = st->time_base;
3469
3470     ret = av_bsf_init(sti->extract_extradata.bsf);
3471     if (ret < 0)
3472         goto fail;
3473
3474 finish:
3475     sti->extract_extradata.inited = 1;
3476
3477     return 0;
3478 fail:
3479     av_bsf_free(&sti->extract_extradata.bsf);
3480     av_packet_free(&sti->extract_extradata.pkt);
3481     return ret;
3482 }
3483
3484 static int extract_extradata(AVStream *st, const AVPacket *pkt)
3485 {
3486     AVStreamInternal *sti = st->internal;
3487     AVPacket *pkt_ref;
3488     int ret;
3489
3490     if (!sti->extract_extradata.inited) {
3491         ret = extract_extradata_init(st);
3492         if (ret < 0)
3493             return ret;
3494     }
3495
3496     if (sti->extract_extradata.inited && !sti->extract_extradata.bsf)
3497         return 0;
3498
3499     pkt_ref = sti->extract_extradata.pkt;
3500     ret = av_packet_ref(pkt_ref, pkt);
3501     if (ret < 0)
3502         return ret;
3503
3504     ret = av_bsf_send_packet(sti->extract_extradata.bsf, pkt_ref);
3505     if (ret < 0) {
3506         av_packet_unref(pkt_ref);
3507         return ret;
3508     }
3509
3510     while (ret >= 0 && !sti->avctx->extradata) {
3511         ret = av_bsf_receive_packet(sti->extract_extradata.bsf, pkt_ref);
3512         if (ret < 0) {
3513             if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3514                 return ret;
3515             continue;
3516         }
3517
3518         for (int i = 0; i < pkt_ref->side_data_elems; i++) {
3519             AVPacketSideData *side_data = &pkt_ref->side_data[i];
3520             if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) {
3521                 sti->avctx->extradata      = side_data->data;
3522                 sti->avctx->extradata_size = side_data->size;
3523                 side_data->data = NULL;
3524                 side_data->size = 0;
3525                 break;
3526             }
3527         }
3528         av_packet_unref(pkt_ref);
3529     }
3530
3531     return 0;
3532 }
3533
3534 static int add_coded_side_data(AVStream *st, AVCodecContext *avctx)
3535 {
3536     int i;
3537
3538     for (i = 0; i < avctx->nb_coded_side_data; i++) {
3539         const AVPacketSideData *sd_src = &avctx->coded_side_data[i];
3540         uint8_t *dst_data;
3541         dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
3542         if (!dst_data)
3543             return AVERROR(ENOMEM);
3544         memcpy(dst_data, sd_src->data, sd_src->size);
3545     }
3546     return 0;
3547 }
3548
3549 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3550 {
3551     int i, count = 0, ret = 0, j;
3552     int64_t read_size;
3553     AVStream *st;
3554     AVCodecContext *avctx;
3555     AVPacket pkt1;
3556     int64_t old_offset  = avio_tell(ic->pb);
3557     // new streams might appear, no options for those
3558     int orig_nb_streams = ic->nb_streams;
3559     int flush_codecs;
3560     int64_t max_analyze_duration = ic->max_analyze_duration;
3561     int64_t max_stream_analyze_duration;
3562     int64_t max_subtitle_analyze_duration;
3563     int64_t probesize = ic->probesize;
3564     int eof_reached = 0;
3565     int *missing_streams = av_opt_ptr(ic->iformat->priv_class, ic->priv_data, "missing_streams");
3566
3567     flush_codecs = probesize > 0;
3568
3569     av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3570
3571     max_stream_analyze_duration = max_analyze_duration;
3572     max_subtitle_analyze_duration = max_analyze_duration;
3573     if (!max_analyze_duration) {
3574         max_stream_analyze_duration =
3575         max_analyze_duration        = 5*AV_TIME_BASE;
3576         max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3577         if (!strcmp(ic->iformat->name, "flv"))
3578             max_stream_analyze_duration = 90*AV_TIME_BASE;
3579         if (!strcmp(ic->iformat->name, "mpeg") || !strcmp(ic->iformat->name, "mpegts"))
3580             max_stream_analyze_duration = 7*AV_TIME_BASE;
3581     }
3582
3583     if (ic->pb)
3584         av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
3585                avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, ic->nb_streams);
3586
3587     for (i = 0; i < ic->nb_streams; i++) {
3588         const AVCodec *codec;
3589         AVDictionary *thread_opt = NULL;
3590         st = ic->streams[i];
3591         avctx = st->internal->avctx;
3592
3593         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3594             st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3595 /*            if (!st->time_base.num)
3596                 st->time_base = */
3597             if (!avctx->time_base.num)
3598                 avctx->time_base = st->time_base;
3599         }
3600
3601         /* check if the caller has overridden the codec id */
3602 #if FF_API_LAVF_AVCTX
3603 FF_DISABLE_DEPRECATION_WARNINGS
3604         if (st->codec->codec_id != st->internal->orig_codec_id) {
3605             st->codecpar->codec_id   = st->codec->codec_id;
3606             st->codecpar->codec_type = st->codec->codec_type;
3607             st->internal->orig_codec_id = st->codec->codec_id;
3608         }
3609 FF_ENABLE_DEPRECATION_WARNINGS
3610 #endif
3611         // only for the split stuff
3612         if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && st->internal->request_probe <= 0) {
3613             st->parser = av_parser_init(st->codecpar->codec_id);
3614             if (st->parser) {
3615                 if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3616                     st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3617                 } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3618                     st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
3619                 }
3620             } else if (st->need_parsing) {
3621                 av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3622                        "%s, packets or times may be invalid.\n",
3623                        avcodec_get_name(st->codecpar->codec_id));
3624             }
3625         }
3626
3627         if (st->codecpar->codec_id != st->internal->orig_codec_id)
3628             st->internal->orig_codec_id = st->codecpar->codec_id;
3629
3630         ret = avcodec_parameters_to_context(avctx, st->codecpar);
3631         if (ret < 0)
3632             goto find_stream_info_err;
3633         if (st->internal->request_probe <= 0)
3634             st->internal->avctx_inited = 1;
3635
3636         codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3637
3638         /* Force thread count to 1 since the H.264 decoder will not extract
3639          * SPS and PPS to extradata during multi-threaded decoding. */
3640         av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3641
3642         if (ic->codec_whitelist)
3643             av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3644
3645         /* Ensure that subtitle_header is properly set. */
3646         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE
3647             && codec && !avctx->codec) {
3648             if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3649                 av_log(ic, AV_LOG_WARNING,
3650                        "Failed to open codec in %s\n",__FUNCTION__);
3651         }
3652
3653         // Try to just open decoders, in case this is enough to get parameters.
3654         if (!has_codec_parameters(st, NULL) && st->internal->request_probe <= 0) {
3655             if (codec && !avctx->codec)
3656                 if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3657                     av_log(ic, AV_LOG_WARNING,
3658                            "Failed to open codec in %s\n",__FUNCTION__);
3659         }
3660         if (!options)
3661             av_dict_free(&thread_opt);
3662     }
3663
3664     for (i = 0; i < ic->nb_streams; i++) {
3665 #if FF_API_R_FRAME_RATE
3666         ic->streams[i]->internal->info->last_dts = AV_NOPTS_VALUE;
3667 #endif
3668         ic->streams[i]->internal->info->fps_first_dts = AV_NOPTS_VALUE;
3669         ic->streams[i]->internal->info->fps_last_dts  = AV_NOPTS_VALUE;
3670     }
3671
3672     read_size = 0;
3673     for (;;) {
3674         const AVPacket *pkt;
3675         int analyzed_all_streams;
3676         if (ff_check_interrupt(&ic->interrupt_callback)) {
3677             ret = AVERROR_EXIT;
3678             av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3679             break;
3680         }
3681
3682         /* check if one codec still needs to be handled */
3683         for (i = 0; i < ic->nb_streams; i++) {
3684             int fps_analyze_framecount = 20;
3685             int count;
3686
3687             st = ic->streams[i];
3688             if (!has_codec_parameters(st, NULL))
3689                 break;
3690             /* If the timebase is coarse (like the usual millisecond precision
3691              * of mkv), we need to analyze more frames to reliably arrive at
3692              * the correct fps. */
3693             if (av_q2d(st->time_base) > 0.0005)
3694                 fps_analyze_framecount *= 2;
3695             if (!tb_unreliable(st->internal->avctx))
3696                 fps_analyze_framecount = 0;
3697             if (ic->fps_probe_size >= 0)
3698                 fps_analyze_framecount = ic->fps_probe_size;
3699             if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3700                 fps_analyze_framecount = 0;
3701             /* variable fps and no guess at the real fps */
3702             count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
3703                        st->internal->info->codec_info_duration_fields/2 :
3704                        st->internal->info->duration_count;
3705             if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3706                 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3707                 if (count < fps_analyze_framecount)
3708                     break;
3709             }
3710             // Look at the first 3 frames if there is evidence of frame delay
3711             // but the decoder delay is not set.
3712             if (st->internal->info->frame_delay_evidence && count < 2 && st->internal->avctx->has_b_frames == 0)
3713                 break;
3714             if (!st->internal->avctx->extradata &&
3715                 (!st->internal->extract_extradata.inited ||
3716                  st->internal->extract_extradata.bsf) &&
3717                 extract_extradata_check(st))
3718                 break;
3719             if (st->first_dts == AV_NOPTS_VALUE &&
3720                 !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3721                 st->codec_info_nb_frames < ((st->disposition & AV_DISPOSITION_ATTACHED_PIC) ? 1 : ic->max_ts_probe) &&
3722                 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3723                  st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
3724                 break;
3725         }
3726         analyzed_all_streams = 0;
3727         if (!missing_streams || !*missing_streams)
3728             if (i == ic->nb_streams) {
3729                 analyzed_all_streams = 1;
3730                 /* NOTE: If the format has no header, then we need to read some
3731                  * packets to get most of the streams, so we cannot stop here. */
3732                 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3733                     /* If we found the info for all the codecs, we can stop. */
3734                     ret = count;
3735                     av_log(ic, AV_LOG_DEBUG, "All info found\n");
3736                     flush_codecs = 0;
3737                     break;
3738                 }
3739             }
3740         /* We did not get all the codec info, but we read too much data. */
3741         if (read_size >= probesize) {
3742             ret = count;
3743             av_log(ic, AV_LOG_DEBUG,
3744                    "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3745             for (i = 0; i < ic->nb_streams; i++)
3746                 if (!ic->streams[i]->r_frame_rate.num &&
3747                     ic->streams[i]->internal->info->duration_count <= 1 &&
3748                     ic->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
3749                     strcmp(ic->iformat->name, "image2"))
3750                     av_log(ic, AV_LOG_WARNING,
3751                            "Stream #%d: not enough frames to estimate rate; "
3752                            "consider increasing probesize\n", i);
3753             break;
3754         }
3755
3756         /* NOTE: A new stream can be added there if no header in file
3757          * (AVFMTCTX_NOHEADER). */
3758         ret = read_frame_internal(ic, &pkt1);
3759         if (ret == AVERROR(EAGAIN))
3760             continue;
3761
3762         if (ret < 0) {
3763             /* EOF or error*/
3764             eof_reached = 1;
3765             break;
3766         }
3767
3768         if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
3769             ret = avpriv_packet_list_put(&ic->internal->packet_buffer,
3770                                      &ic->internal->packet_buffer_end,
3771                                      &pkt1, NULL, 0);
3772             if (ret < 0)
3773                 goto unref_then_goto_end;
3774
3775             pkt = &ic->internal->packet_buffer_end->pkt;
3776         } else {
3777             pkt = &pkt1;
3778         }
3779
3780         st = ic->streams[pkt->stream_index];
3781         if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
3782             read_size += pkt->size;
3783
3784         avctx = st->internal->avctx;
3785         if (!st->internal->avctx_inited) {
3786             ret = avcodec_parameters_to_context(avctx, st->codecpar);
3787             if (ret < 0)
3788                 goto unref_then_goto_end;
3789             st->internal->avctx_inited = 1;
3790         }
3791
3792         if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3793             /* check for non-increasing dts */
3794             if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3795                 st->internal->info->fps_last_dts >= pkt->dts) {
3796                 av_log(ic, AV_LOG_DEBUG,
3797                        "Non-increasing DTS in stream %d: packet %d with DTS "
3798                        "%"PRId64", packet %d with DTS %"PRId64"\n",
3799                        st->index, st->internal->info->fps_last_dts_idx,
3800                        st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3801                        pkt->dts);
3802                 st->internal->info->fps_first_dts =
3803                 st->internal->info->fps_last_dts  = AV_NOPTS_VALUE;
3804             }
3805             /* Check for a discontinuity in dts. If the difference in dts
3806              * is more than 1000 times the average packet duration in the
3807              * sequence, we treat it as a discontinuity. */
3808             if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3809                 st->internal->info->fps_last_dts_idx > st->internal->info->fps_first_dts_idx &&
3810                 (pkt->dts - (uint64_t)st->internal->info->fps_last_dts) / 1000 >
3811                 (st->internal->info->fps_last_dts     - (uint64_t)st->internal->info->fps_first_dts) /
3812                 (st->internal->info->fps_last_dts_idx - st->internal->info->fps_first_dts_idx)) {
3813                 av_log(ic, AV_LOG_WARNING,
3814                        "DTS discontinuity in stream %d: packet %d with DTS "
3815                        "%"PRId64", packet %d with DTS %"PRId64"\n",
3816                        st->index, st->internal->info->fps_last_dts_idx,
3817                        st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3818                        pkt->dts);
3819                 st->internal->info->fps_first_dts =
3820                 st->internal->info->fps_last_dts  = AV_NOPTS_VALUE;
3821             }
3822
3823             /* update stored dts values */
3824             if (st->internal->info->fps_first_dts == AV_NOPTS_VALUE) {
3825                 st->internal->info->fps_first_dts     = pkt->dts;
3826                 st->internal->info->fps_first_dts_idx = st->codec_info_nb_frames;
3827             }
3828             st->internal->info->fps_last_dts     = pkt->dts;
3829             st->internal->info->fps_last_dts_idx = st->codec_info_nb_frames;
3830         }
3831         if (st->codec_info_nb_frames>1) {
3832             int64_t t = 0;
3833             int64_t limit;
3834
3835             if (st->time_base.den > 0)
3836                 t = av_rescale_q(st->internal->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
3837             if (st->avg_frame_rate.num > 0)
3838                 t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3839
3840             if (   t == 0
3841                 && st->codec_info_nb_frames>30
3842                 && st->internal->info->fps_first_dts != AV_NOPTS_VALUE
3843                 && st->internal->info->fps_last_dts  != AV_NOPTS_VALUE)
3844                 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));
3845
3846             if (analyzed_all_streams)                                limit = max_analyze_duration;
3847             else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3848             else                                                     limit = max_stream_analyze_duration;
3849
3850             if (t >= limit) {
3851                 av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3852                        limit,
3853                        t, pkt->stream_index);
3854                 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3855                     av_packet_unref(&pkt1);
3856                 break;
3857             }
3858             if (pkt->duration) {
3859                 if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE && pkt->pts != AV_NOPTS_VALUE && st->start_time != AV_NOPTS_VALUE && pkt->pts >= st->start_time) {
3860                     st->internal->info->codec_info_duration = FFMIN(pkt->pts - st->start_time, st->internal->info->codec_info_duration + pkt->duration);
3861                 } else
3862                     st->internal->info->codec_info_duration += pkt->duration;
3863                 st->internal->info->codec_info_duration_fields += st->parser && st->need_parsing && avctx->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3864             }
3865         }
3866         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3867 #if FF_API_R_FRAME_RATE
3868             ff_rfps_add_frame(ic, st, pkt->dts);
3869 #endif
3870             if (pkt->dts != pkt->pts && pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
3871                 st->internal->info->frame_delay_evidence = 1;
3872         }
3873         if (!st->internal->avctx->extradata) {
3874             ret = extract_extradata(st, pkt);
3875             if (ret < 0)
3876                 goto unref_then_goto_end;
3877         }
3878
3879         /* If still no information, we try to open the codec and to
3880          * decompress the frame. We try to avoid that in most cases as
3881          * it takes longer and uses more memory. For MPEG-4, we need to
3882          * decompress for QuickTime.
3883          *
3884          * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3885          * least one frame of codec data, this makes sure the codec initializes
3886          * the channel configuration and does not only trust the values from
3887          * the container. */
3888         try_decode_frame(ic, st, pkt,
3889                          (options && i < orig_nb_streams) ? &options[i] : NULL);
3890
3891         if (ic->flags & AVFMT_FLAG_NOBUFFER)
3892             av_packet_unref(&pkt1);
3893
3894         st->codec_info_nb_frames++;
3895         count++;
3896     }
3897
3898     if (eof_reached) {
3899         int stream_index;
3900         for (stream_index = 0; stream_index < ic->nb_streams; stream_index++) {
3901             st = ic->streams[stream_index];
3902             avctx = st->internal->avctx;
3903             if (!has_codec_parameters(st, NULL)) {
3904                 const AVCodec *codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3905                 if (codec && !avctx->codec) {
3906                     AVDictionary *opts = NULL;
3907                     if (ic->codec_whitelist)
3908                         av_dict_set(&opts, "codec_whitelist", ic->codec_whitelist, 0);
3909                     if (avcodec_open2(avctx, codec, (options && stream_index < orig_nb_streams) ? &options[stream_index] : &opts) < 0)
3910                         av_log(ic, AV_LOG_WARNING,
3911                                "Failed to open codec in %s\n",__FUNCTION__);
3912                     av_dict_free(&opts);
3913                 }
3914             }
3915
3916             // EOF already reached while reading the stream above.
3917             // So continue with reoordering DTS with whatever delay we have.
3918             if (ic->internal->packet_buffer && !has_decode_delay_been_guessed(st)) {
3919                 update_dts_from_pts(ic, stream_index, ic->internal->packet_buffer);
3920             }
3921         }
3922     }
3923
3924     if (flush_codecs) {
3925         AVPacket empty_pkt = { 0 };
3926         int err = 0;
3927         av_init_packet(&empty_pkt);
3928
3929         for (i = 0; i < ic->nb_streams; i++) {
3930
3931             st = ic->streams[i];
3932
3933             /* flush the decoders */
3934             if (st->internal->info->found_decoder == 1) {
3935                 do {
3936                     err = try_decode_frame(ic, st, &empty_pkt,
3937                                             (options && i < orig_nb_streams)
3938                                             ? &options[i] : NULL);
3939                 } while (err > 0 && !has_codec_parameters(st, NULL));
3940
3941                 if (err < 0) {
3942                     av_log(ic, AV_LOG_INFO,
3943                         "decoding for stream %d failed\n", st->index);
3944                 }
3945             }
3946         }
3947     }
3948
3949     ff_rfps_calculate(ic);
3950
3951     for (i = 0; i < ic->nb_streams; i++) {
3952         st = ic->streams[i];
3953         avctx = st->internal->avctx;
3954         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3955             if (avctx->codec_id == AV_CODEC_ID_RAWVIDEO && !avctx->codec_tag && !avctx->bits_per_coded_sample) {
3956                 uint32_t tag= avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
3957                 if (avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), tag) == avctx->pix_fmt)
3958                     avctx->codec_tag= tag;
3959             }
3960
3961             /* estimate average framerate if not set by demuxer */
3962             if (st->internal->info->codec_info_duration_fields &&
3963                 !st->avg_frame_rate.num &&
3964                 st->internal->info->codec_info_duration) {
3965                 int best_fps      = 0;
3966                 double best_error = 0.01;
3967                 AVRational codec_frame_rate = avctx->framerate;
3968
3969                 if (st->internal->info->codec_info_duration        >= INT64_MAX / st->time_base.num / 2||
3970                     st->internal->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
3971                     st->internal->info->codec_info_duration        < 0)
3972                     continue;
3973                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3974                           st->internal->info->codec_info_duration_fields * (int64_t) st->time_base.den,
3975                           st->internal->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3976
3977                 /* Round guessed framerate to a "standard" framerate if it's
3978                  * within 1% of the original estimate. */
3979                 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
3980                     AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
3981                     double error       = fabs(av_q2d(st->avg_frame_rate) /
3982                                               av_q2d(std_fps) - 1);
3983
3984                     if (error < best_error) {
3985                         best_error = error;
3986                         best_fps   = std_fps.num;
3987                     }
3988
3989                     if (ic->internal->prefer_codec_framerate && codec_frame_rate.num > 0 && codec_frame_rate.den > 0) {
3990                         error       = fabs(av_q2d(codec_frame_rate) /
3991                                            av_q2d(std_fps) - 1);
3992                         if (error < best_error) {
3993                             best_error = error;
3994                             best_fps   = std_fps.num;
3995                         }
3996                     }
3997                 }
3998                 if (best_fps)
3999                     av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4000                               best_fps, 12 * 1001, INT_MAX);
4001             }
4002
4003             if (!st->r_frame_rate.num) {
4004                 if (    avctx->time_base.den * (int64_t) st->time_base.num
4005                     <= avctx->time_base.num * avctx->ticks_per_frame * (uint64_t) st->time_base.den) {
4006                     av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4007                               avctx->time_base.den, (int64_t)avctx->time_base.num * avctx->ticks_per_frame, INT_MAX);
4008                 } else {
4009                     st->r_frame_rate.num = st->time_base.den;
4010                     st->r_frame_rate.den = st->time_base.num;
4011                 }
4012             }
4013             if (st->internal->display_aspect_ratio.num && st->internal->display_aspect_ratio.den) {
4014                 AVRational hw_ratio = { avctx->height, avctx->width };
4015                 st->sample_aspect_ratio = av_mul_q(st->internal->display_aspect_ratio,
4016                                                    hw_ratio);
4017             }
4018         } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
4019             if (!avctx->bits_per_coded_sample)
4020                 avctx->bits_per_coded_sample =
4021                     av_get_bits_per_sample(avctx->codec_id);
4022             // set stream disposition based on audio service type
4023             switch (avctx->audio_service_type) {
4024             case AV_AUDIO_SERVICE_TYPE_EFFECTS:
4025                 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
4026                 break;
4027             case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
4028                 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
4029                 break;
4030             case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
4031                 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
4032                 break;
4033             case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
4034                 st->disposition = AV_DISPOSITION_COMMENT;
4035                 break;
4036             case AV_AUDIO_SERVICE_TYPE_KARAOKE:
4037                 st->disposition = AV_DISPOSITION_KARAOKE;
4038                 break;
4039             }
4040         }
4041     }
4042
4043     if (probesize)
4044         estimate_timings(ic, old_offset);
4045
4046     av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
4047
4048     if (ret >= 0 && ic->nb_streams)
4049         /* We could not have all the codec parameters before EOF. */
4050         ret = -1;
4051     for (i = 0; i < ic->nb_streams; i++) {
4052         const char *errmsg;
4053         st = ic->streams[i];
4054
4055         /* if no packet was ever seen, update context now for has_codec_parameters */
4056         if (!st->internal->avctx_inited) {
4057             if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
4058                 st->codecpar->format == AV_SAMPLE_FMT_NONE)
4059                 st->codecpar->format = st->internal->avctx->sample_fmt;
4060             ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
4061             if (ret < 0)
4062                 goto find_stream_info_err;
4063         }
4064         if (!has_codec_parameters(st, &errmsg)) {
4065             char buf[256];
4066             avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
4067             av_log(ic, AV_LOG_WARNING,
4068                    "Could not find codec parameters for stream %d (%s): %s\n"
4069                    "Consider increasing the value for the 'analyzeduration' (%"PRId64") and 'probesize' (%"PRId64") options\n",
4070                    i, buf, errmsg, ic->max_analyze_duration, ic->probesize);
4071         } else {
4072             ret = 0;
4073         }
4074     }
4075
4076     compute_chapters_end(ic);
4077
4078     /* update the stream parameters from the internal codec contexts */
4079     for (i = 0; i < ic->nb_streams; i++) {
4080         st = ic->streams[i];
4081
4082         if (st->internal->avctx_inited) {
4083             int orig_w = st->codecpar->width;
4084             int orig_h = st->codecpar->height;
4085             ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
4086             if (ret < 0)
4087                 goto find_stream_info_err;
4088             ret = add_coded_side_data(st, st->internal->avctx);
4089             if (ret < 0)
4090                 goto find_stream_info_err;
4091 #if FF_API_LOWRES
4092             // The decoder might reduce the video size by the lowres factor.
4093             if (st->internal->avctx->lowres && orig_w) {
4094                 st->codecpar->width = orig_w;
4095                 st->codecpar->height = orig_h;
4096             }
4097 #endif
4098         }
4099
4100 #if FF_API_LAVF_AVCTX
4101 FF_DISABLE_DEPRECATION_WARNINGS
4102         ret = avcodec_parameters_to_context(st->codec, st->codecpar);
4103         if (ret < 0)
4104             goto find_stream_info_err;
4105
4106 #if FF_API_LOWRES
4107         // The old API (AVStream.codec) "requires" the resolution to be adjusted
4108         // by the lowres factor.
4109         if (st->internal->avctx->lowres && st->internal->avctx->width) {
4110             st->codec->lowres = st->internal->avctx->lowres;
4111             st->codec->width = st->internal->avctx->width;
4112             st->codec->height = st->internal->avctx->height;
4113         }
4114 #endif
4115
4116         if (st->codec->codec_tag != MKTAG('t','m','c','d')) {
4117             st->codec->time_base = st->internal->avctx->time_base;
4118             st->codec->ticks_per_frame = st->internal->avctx->ticks_per_frame;
4119         }
4120         st->codec->framerate = st->avg_frame_rate;
4121
4122         if (st->internal->avctx->subtitle_header) {
4123             st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
4124             if (!st->codec->subtitle_header)
4125                 goto find_stream_info_err;
4126             st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
4127             memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
4128                    st->codec->subtitle_header_size);
4129         }
4130
4131         // Fields unavailable in AVCodecParameters
4132         st->codec->coded_width = st->internal->avctx->coded_width;
4133         st->codec->coded_height = st->internal->avctx->coded_height;
4134         st->codec->properties = st->internal->avctx->properties;
4135 FF_ENABLE_DEPRECATION_WARNINGS
4136 #endif
4137
4138         st->internal->avctx_inited = 0;
4139     }
4140
4141 find_stream_info_err:
4142     for (i = 0; i < ic->nb_streams; i++) {
4143         st = ic->streams[i];
4144         if (st->internal->info)
4145             av_freep(&st->internal->info->duration_error);
4146         avcodec_close(ic->streams[i]->internal->avctx);
4147         av_freep(&ic->streams[i]->internal->info);
4148         av_bsf_free(&ic->streams[i]->internal->extract_extradata.bsf);
4149         av_packet_free(&ic->streams[i]->internal->extract_extradata.pkt);
4150     }
4151     if (ic->pb)
4152         av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
4153                avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
4154     return ret;
4155
4156 unref_then_goto_end:
4157     av_packet_unref(&pkt1);
4158     goto find_stream_info_err;
4159 }
4160
4161 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
4162 {
4163     int i, j;
4164
4165     for (i = 0; i < ic->nb_programs; i++) {
4166         if (ic->programs[i] == last) {
4167             last = NULL;
4168         } else {
4169             if (!last)
4170                 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
4171                     if (ic->programs[i]->stream_index[j] == s)
4172                         return ic->programs[i];
4173         }
4174     }
4175     return NULL;
4176 }
4177
4178 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
4179                         int wanted_stream_nb, int related_stream,
4180                         AVCodec **decoder_ret, int flags)
4181 {
4182     int i, nb_streams = ic->nb_streams;
4183     int ret = AVERROR_STREAM_NOT_FOUND;
4184     int best_count = -1, best_multiframe = -1, best_disposition = -1;
4185     int count, multiframe, disposition;
4186     int64_t best_bitrate = -1;
4187     int64_t bitrate;
4188     unsigned *program = NULL;
4189     const AVCodec *decoder = NULL, *best_decoder = NULL;
4190
4191     if (related_stream >= 0 && wanted_stream_nb < 0) {
4192         AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
4193         if (p) {
4194             program    = p->stream_index;
4195             nb_streams = p->nb_stream_indexes;
4196         }
4197     }
4198     for (i = 0; i < nb_streams; i++) {
4199         int real_stream_index = program ? program[i] : i;
4200         AVStream *st          = ic->streams[real_stream_index];
4201         AVCodecParameters *par = st->codecpar;
4202         if (par->codec_type != type)
4203             continue;
4204         if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
4205             continue;
4206         if (type == AVMEDIA_TYPE_AUDIO && !(par->channels && par->sample_rate))
4207             continue;
4208         if (decoder_ret) {
4209             decoder = find_decoder(ic, st, par->codec_id);
4210             if (!decoder) {
4211                 if (ret < 0)
4212                     ret = AVERROR_DECODER_NOT_FOUND;
4213                 continue;
4214             }
4215         }
4216         disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED))
4217                       + !! (st->disposition & AV_DISPOSITION_DEFAULT);
4218         count = st->codec_info_nb_frames;
4219         bitrate = par->bit_rate;
4220         multiframe = FFMIN(5, count);
4221         if ((best_disposition >  disposition) ||
4222             (best_disposition == disposition && best_multiframe >  multiframe) ||
4223             (best_disposition == disposition && best_multiframe == multiframe && best_bitrate >  bitrate) ||
4224             (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
4225             continue;
4226         best_disposition = disposition;
4227         best_count   = count;
4228         best_bitrate = bitrate;
4229         best_multiframe = multiframe;
4230         ret          = real_stream_index;
4231         best_decoder = decoder;
4232         if (program && i == nb_streams - 1 && ret < 0) {
4233             program    = NULL;
4234             nb_streams = ic->nb_streams;
4235             /* no related stream found, try again with everything */
4236             i = 0;
4237         }
4238     }
4239     if (decoder_ret)
4240         *decoder_ret = (AVCodec*)best_decoder;
4241     return ret;
4242 }
4243
4244 /*******************************************************/
4245
4246 int av_read_play(AVFormatContext *s)
4247 {
4248     if (s->iformat->read_play)
4249         return s->iformat->read_play(s);
4250     if (s->pb)
4251         return avio_pause(s->pb, 0);
4252     return AVERROR(ENOSYS);
4253 }
4254
4255 int av_read_pause(AVFormatContext *s)
4256 {
4257     if (s->iformat->read_pause)
4258         return s->iformat->read_pause(s);
4259     if (s->pb)
4260         return avio_pause(s->pb, 1);
4261     return AVERROR(ENOSYS);
4262 }
4263
4264 int ff_stream_encode_params_copy(AVStream *dst, const AVStream *src)
4265 {
4266     int ret, i;
4267
4268     dst->id                  = src->id;
4269     dst->time_base           = src->time_base;
4270     dst->nb_frames           = src->nb_frames;
4271     dst->disposition         = src->disposition;
4272     dst->sample_aspect_ratio = src->sample_aspect_ratio;
4273     dst->avg_frame_rate      = src->avg_frame_rate;
4274     dst->r_frame_rate        = src->r_frame_rate;
4275
4276     av_dict_free(&dst->metadata);
4277     ret = av_dict_copy(&dst->metadata, src->metadata, 0);
4278     if (ret < 0)
4279         return ret;
4280
4281     ret = avcodec_parameters_copy(dst->codecpar, src->codecpar);
4282     if (ret < 0)
4283         return ret;
4284
4285     /* Free existing side data*/
4286     for (i = 0; i < dst->nb_side_data; i++)
4287         av_free(dst->side_data[i].data);
4288     av_freep(&dst->side_data);
4289     dst->nb_side_data = 0;
4290
4291     /* Copy side data if present */
4292     if (src->nb_side_data) {
4293         dst->side_data = av_mallocz_array(src->nb_side_data,
4294                                           sizeof(AVPacketSideData));
4295         if (!dst->side_data)
4296             return AVERROR(ENOMEM);
4297         dst->nb_side_data = src->nb_side_data;
4298
4299         for (i = 0; i < src->nb_side_data; i++) {
4300             uint8_t *data = av_memdup(src->side_data[i].data,
4301                                       src->side_data[i].size);
4302             if (!data)
4303                 return AVERROR(ENOMEM);
4304             dst->side_data[i].type = src->side_data[i].type;
4305             dst->side_data[i].size = src->side_data[i].size;
4306             dst->side_data[i].data = data;
4307         }
4308     }
4309
4310 #if FF_API_LAVF_FFSERVER
4311 FF_DISABLE_DEPRECATION_WARNINGS
4312     av_freep(&dst->recommended_encoder_configuration);
4313     if (src->recommended_encoder_configuration) {
4314         const char *conf_str = src->recommended_encoder_configuration;
4315         dst->recommended_encoder_configuration = av_strdup(conf_str);
4316         if (!dst->recommended_encoder_configuration)
4317             return AVERROR(ENOMEM);
4318     }
4319 FF_ENABLE_DEPRECATION_WARNINGS
4320 #endif
4321
4322     return 0;
4323 }
4324
4325 static void free_stream(AVStream **pst)
4326 {
4327     AVStream *st = *pst;
4328     int i;
4329
4330     if (!st)
4331         return;
4332
4333     for (i = 0; i < st->nb_side_data; i++)
4334         av_freep(&st->side_data[i].data);
4335     av_freep(&st->side_data);
4336
4337     if (st->parser)
4338         av_parser_close(st->parser);
4339
4340     if (st->attached_pic.data)
4341         av_packet_unref(&st->attached_pic);
4342
4343     if (st->internal) {
4344         avcodec_free_context(&st->internal->avctx);
4345         av_bsf_free(&st->internal->bsfc);
4346         av_freep(&st->internal->priv_pts);
4347         av_freep(&st->internal->index_entries);
4348         av_freep(&st->internal->probe_data.buf);
4349
4350         av_bsf_free(&st->internal->extract_extradata.bsf);
4351         av_packet_free(&st->internal->extract_extradata.pkt);
4352
4353         if (st->internal->info)
4354             av_freep(&st->internal->info->duration_error);
4355         av_freep(&st->internal->info);
4356     }
4357     av_freep(&st->internal);
4358
4359     av_dict_free(&st->metadata);
4360     avcodec_parameters_free(&st->codecpar);
4361 #if FF_API_LAVF_AVCTX
4362 FF_DISABLE_DEPRECATION_WARNINGS
4363     avcodec_free_context(&st->codec);
4364 FF_ENABLE_DEPRECATION_WARNINGS
4365 #endif
4366     av_freep(&st->priv_data);
4367 #if FF_API_LAVF_FFSERVER
4368 FF_DISABLE_DEPRECATION_WARNINGS
4369     av_freep(&st->recommended_encoder_configuration);
4370 FF_ENABLE_DEPRECATION_WARNINGS
4371 #endif
4372
4373     av_freep(pst);
4374 }
4375
4376 void ff_free_stream(AVFormatContext *s, AVStream *st)
4377 {
4378     av_assert0(s->nb_streams>0);
4379     av_assert0(s->streams[ s->nb_streams - 1 ] == st);
4380
4381     free_stream(&s->streams[ --s->nb_streams ]);
4382 }
4383
4384 void avformat_free_context(AVFormatContext *s)
4385 {
4386     int i;
4387
4388     if (!s)
4389         return;
4390
4391     if (s->oformat && s->oformat->deinit && s->internal->initialized)
4392         s->oformat->deinit(s);
4393
4394     av_opt_free(s);
4395     if (s->iformat && s->iformat->priv_class && s->priv_data)
4396         av_opt_free(s->priv_data);
4397     if (s->oformat && s->oformat->priv_class && s->priv_data)
4398         av_opt_free(s->priv_data);
4399
4400     for (i = 0; i < s->nb_streams; i++)
4401         free_stream(&s->streams[i]);
4402     s->nb_streams = 0;
4403
4404     for (i = 0; i < s->nb_programs; i++) {
4405         av_dict_free(&s->programs[i]->metadata);
4406         av_freep(&s->programs[i]->stream_index);
4407         av_freep(&s->programs[i]);
4408     }
4409     s->nb_programs = 0;
4410
4411     av_freep(&s->programs);
4412     av_freep(&s->priv_data);
4413     while (s->nb_chapters--) {
4414         av_dict_free(&s->chapters[s->nb_chapters]->metadata);
4415         av_freep(&s->chapters[s->nb_chapters]);
4416     }
4417     av_freep(&s->chapters);
4418     av_dict_free(&s->metadata);
4419     av_dict_free(&s->internal->id3v2_meta);
4420     av_freep(&s->streams);
4421     flush_packet_queue(s);
4422     av_freep(&s->internal);
4423     av_freep(&s->url);
4424     av_free(s);
4425 }
4426
4427 void avformat_close_input(AVFormatContext **ps)
4428 {
4429     AVFormatContext *s;
4430     AVIOContext *pb;
4431
4432     if (!ps || !*ps)
4433         return;
4434
4435     s  = *ps;
4436     pb = s->pb;
4437
4438     if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
4439         (s->flags & AVFMT_FLAG_CUSTOM_IO))
4440         pb = NULL;
4441
4442     flush_packet_queue(s);
4443
4444     if (s->iformat)
4445         if (s->iformat->read_close)
4446             s->iformat->read_close(s);
4447
4448     avformat_free_context(s);
4449
4450     *ps = NULL;
4451
4452     avio_close(pb);
4453 }
4454
4455 AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
4456 {
4457     AVStream *st;
4458     int i;
4459     AVStream **streams;
4460
4461     if (s->nb_streams >= FFMIN(s->max_streams, INT_MAX/sizeof(*streams))) {
4462         if (s->max_streams < INT_MAX/sizeof(*streams))
4463             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);
4464         return NULL;
4465     }
4466     streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
4467     if (!streams)
4468         return NULL;
4469     s->streams = streams;
4470
4471     st = av_mallocz(sizeof(AVStream));
4472     if (!st)
4473         return NULL;
4474
4475 #if FF_API_LAVF_AVCTX
4476 FF_DISABLE_DEPRECATION_WARNINGS
4477     st->codec = avcodec_alloc_context3(c);
4478     if (!st->codec) {
4479         av_free(st);
4480         return NULL;
4481     }
4482 FF_ENABLE_DEPRECATION_WARNINGS
4483 #endif
4484
4485     st->internal = av_mallocz(sizeof(*st->internal));
4486     if (!st->internal)
4487         goto fail;
4488
4489     st->internal->info = av_mallocz(sizeof(*st->internal->info));
4490     if (!st->internal->info)
4491         goto fail;
4492     st->internal->info->last_dts = AV_NOPTS_VALUE;
4493
4494     st->codecpar = avcodec_parameters_alloc();
4495     if (!st->codecpar)
4496         goto fail;
4497
4498     st->internal->avctx = avcodec_alloc_context3(NULL);
4499     if (!st->internal->avctx)
4500         goto fail;
4501
4502     if (s->iformat) {
4503 #if FF_API_LAVF_AVCTX
4504 FF_DISABLE_DEPRECATION_WARNINGS
4505         /* no default bitrate if decoding */
4506         st->codec->bit_rate = 0;
4507 FF_ENABLE_DEPRECATION_WARNINGS
4508 #endif
4509
4510         /* default pts setting is MPEG-like */
4511         avpriv_set_pts_info(st, 33, 1, 90000);
4512         /* we set the current DTS to 0 so that formats without any timestamps
4513          * but durations get some timestamps, formats with some unknown
4514          * timestamps have their first few packets buffered and the
4515          * timestamps corrected before they are returned to the user */
4516         st->cur_dts = RELATIVE_TS_BASE;
4517     } else {
4518         st->cur_dts = AV_NOPTS_VALUE;
4519     }
4520
4521     st->index      = s->nb_streams;
4522     st->start_time = AV_NOPTS_VALUE;
4523     st->duration   = AV_NOPTS_VALUE;
4524     st->first_dts     = AV_NOPTS_VALUE;
4525     st->probe_packets = s->max_probe_packets;
4526     st->internal->pts_wrap_reference = AV_NOPTS_VALUE;
4527     st->internal->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4528
4529     st->last_IP_pts = AV_NOPTS_VALUE;
4530     st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
4531     for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
4532         st->internal->pts_buffer[i] = AV_NOPTS_VALUE;
4533
4534     st->sample_aspect_ratio = (AVRational) { 0, 1 };
4535
4536 #if FF_API_R_FRAME_RATE
4537     st->internal->info->last_dts      = AV_NOPTS_VALUE;
4538 #endif
4539     st->internal->info->fps_first_dts = AV_NOPTS_VALUE;
4540     st->internal->info->fps_last_dts  = AV_NOPTS_VALUE;
4541
4542     st->internal->inject_global_side_data = s->internal->inject_global_side_data;
4543
4544     st->internal->need_context_update = 1;
4545
4546     s->streams[s->nb_streams++] = st;
4547     return st;
4548 fail:
4549     free_stream(&st);
4550     return NULL;
4551 }
4552
4553 AVProgram *av_new_program(AVFormatContext *ac, int id)
4554 {
4555     AVProgram *program = NULL;
4556     int i;
4557
4558     av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
4559
4560     for (i = 0; i < ac->nb_programs; i++)
4561         if (ac->programs[i]->id == id)
4562             program = ac->programs[i];
4563
4564     if (!program) {
4565         program = av_mallocz(sizeof(AVProgram));
4566         if (!program)
4567             return NULL;
4568         dynarray_add(&ac->programs, &ac->nb_programs, program);
4569         program->discard = AVDISCARD_NONE;
4570         program->pmt_version = -1;
4571     }
4572     program->id = id;
4573     program->pts_wrap_reference = AV_NOPTS_VALUE;
4574     program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4575
4576     program->start_time =
4577     program->end_time   = AV_NOPTS_VALUE;
4578
4579     return program;
4580 }
4581
4582 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
4583                               int64_t start, int64_t end, const char *title)
4584 {
4585     AVChapter *chapter = NULL;
4586     int i;
4587
4588     if (end != AV_NOPTS_VALUE && start > end) {
4589         av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
4590         return NULL;
4591     }
4592
4593     for (i = 0; i < s->nb_chapters; i++)
4594         if (s->chapters[i]->id == id)
4595             chapter = s->chapters[i];
4596
4597     if (!chapter) {
4598         chapter = av_mallocz(sizeof(AVChapter));
4599         if (!chapter)
4600             return NULL;
4601         dynarray_add(&s->chapters, &s->nb_chapters, chapter);
4602     }
4603     av_dict_set(&chapter->metadata, "title", title, 0);
4604     chapter->id        = id;
4605     chapter->time_base = time_base;
4606     chapter->start     = start;
4607     chapter->end       = end;
4608
4609     return chapter;
4610 }
4611
4612 void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
4613 {
4614     int i, j;
4615     AVProgram *program = NULL;
4616     void *tmp;
4617
4618     if (idx >= ac->nb_streams) {
4619         av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
4620         return;
4621     }
4622
4623     for (i = 0; i < ac->nb_programs; i++) {
4624         if (ac->programs[i]->id != progid)
4625             continue;
4626         program = ac->programs[i];
4627         for (j = 0; j < program->nb_stream_indexes; j++)
4628             if (program->stream_index[j] == idx)
4629                 return;
4630
4631         tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
4632         if (!tmp)
4633             return;
4634         program->stream_index = tmp;
4635         program->stream_index[program->nb_stream_indexes++] = idx;
4636         return;
4637     }
4638 }
4639
4640 uint64_t ff_ntp_time(void)
4641 {
4642     return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
4643 }
4644
4645 uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us)
4646 {
4647     uint64_t ntp_ts, frac_part, sec;
4648     uint32_t usec;
4649
4650     //current ntp time in seconds and micro seconds
4651     sec = ntp_time_us / 1000000;
4652     usec = ntp_time_us % 1000000;
4653
4654     //encoding in ntp timestamp format
4655     frac_part = usec * 0xFFFFFFFFULL;
4656     frac_part /= 1000000;
4657
4658     if (sec > 0xFFFFFFFFULL)
4659         av_log(NULL, AV_LOG_WARNING, "NTP time format roll over detected\n");
4660
4661     ntp_ts = sec << 32;
4662     ntp_ts |= frac_part;
4663
4664     return ntp_ts;
4665 }
4666
4667 int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number, int flags)
4668 {
4669     const char *p;
4670     char *q, buf1[20], c;
4671     int nd, len, percentd_found;
4672
4673     q = buf;
4674     p = path;
4675     percentd_found = 0;
4676     for (;;) {
4677         c = *p++;
4678         if (c == '\0')
4679             break;
4680         if (c == '%') {
4681             do {
4682                 nd = 0;
4683                 while (av_isdigit(*p))
4684                     nd = nd * 10 + *p++ - '0';
4685                 c = *p++;
4686             } while (av_isdigit(c));
4687
4688             switch (c) {
4689             case '%':
4690                 goto addchar;
4691             case 'd':
4692                 if (!(flags & AV_FRAME_FILENAME_FLAGS_MULTIPLE) && percentd_found)
4693                     goto fail;
4694                 percentd_found = 1;
4695                 if (number < 0)
4696                     nd += 1;
4697                 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
4698                 len = strlen(buf1);
4699                 if ((q - buf + len) > buf_size - 1)
4700                     goto fail;
4701                 memcpy(q, buf1, len);
4702                 q += len;
4703                 break;
4704             default:
4705                 goto fail;
4706             }
4707         } else {
4708 addchar:
4709             if ((q - buf) < buf_size - 1)
4710                 *q++ = c;
4711         }
4712     }
4713     if (!percentd_found)
4714         goto fail;
4715     *q = '\0';
4716     return 0;
4717 fail:
4718     *q = '\0';
4719     return -1;
4720 }
4721
4722 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
4723 {
4724     return av_get_frame_filename2(buf, buf_size, path, number, 0);
4725 }
4726
4727 void av_url_split(char *proto, int proto_size,
4728                   char *authorization, int authorization_size,
4729                   char *hostname, int hostname_size,
4730                   int *port_ptr, char *path, int path_size, const char *url)
4731 {
4732     const char *p, *ls, *at, *at2, *col, *brk;
4733
4734     if (port_ptr)
4735         *port_ptr = -1;
4736     if (proto_size > 0)
4737         proto[0] = 0;
4738     if (authorization_size > 0)
4739         authorization[0] = 0;
4740     if (hostname_size > 0)
4741         hostname[0] = 0;
4742     if (path_size > 0)
4743         path[0] = 0;
4744
4745     /* parse protocol */
4746     if ((p = strchr(url, ':'))) {
4747         av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
4748         p++; /* skip ':' */
4749         if (*p == '/')
4750             p++;
4751         if (*p == '/')
4752             p++;
4753     } else {
4754         /* no protocol means plain filename */
4755         av_strlcpy(path, url, path_size);
4756         return;
4757     }
4758
4759     /* separate path from hostname */
4760     ls = p + strcspn(p, "/?#");
4761     av_strlcpy(path, ls, path_size);
4762
4763     /* the rest is hostname, use that to parse auth/port */
4764     if (ls != p) {
4765         /* authorization (user[:pass]@hostname) */
4766         at2 = p;
4767         while ((at = strchr(p, '@')) && at < ls) {
4768             av_strlcpy(authorization, at2,
4769                        FFMIN(authorization_size, at + 1 - at2));
4770             p = at + 1; /* skip '@' */
4771         }
4772
4773         if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
4774             /* [host]:port */
4775             av_strlcpy(hostname, p + 1,
4776                        FFMIN(hostname_size, brk - p));
4777             if (brk[1] == ':' && port_ptr)
4778                 *port_ptr = atoi(brk + 2);
4779         } else if ((col = strchr(p, ':')) && col < ls) {
4780             av_strlcpy(hostname, p,
4781                        FFMIN(col + 1 - p, hostname_size));
4782             if (port_ptr)
4783                 *port_ptr = atoi(col + 1);
4784         } else
4785             av_strlcpy(hostname, p,
4786                        FFMIN(ls + 1 - p, hostname_size));
4787     }
4788 }
4789
4790 int ff_mkdir_p(const char *path)
4791 {
4792     int ret = 0;
4793     char *temp = av_strdup(path);
4794     char *pos = temp;
4795     char tmp_ch = '\0';
4796
4797     if (!path || !temp) {
4798         return -1;
4799     }
4800
4801     if (!av_strncasecmp(temp, "/", 1) || !av_strncasecmp(temp, "\\", 1)) {
4802         pos++;
4803     } else if (!av_strncasecmp(temp, "./", 2) || !av_strncasecmp(temp, ".\\", 2)) {
4804         pos += 2;
4805     }
4806
4807     for ( ; *pos != '\0'; ++pos) {
4808         if (*pos == '/' || *pos == '\\') {
4809             tmp_ch = *pos;
4810             *pos = '\0';
4811             ret = mkdir(temp, 0755);
4812             *pos = tmp_ch;
4813         }
4814     }
4815
4816     if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
4817         ret = mkdir(temp, 0755);
4818     }
4819
4820     av_free(temp);
4821     return ret;
4822 }
4823
4824 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4825 {
4826     int i;
4827     static const char hex_table_uc[16] = { '0', '1', '2', '3',
4828                                            '4', '5', '6', '7',
4829                                            '8', '9', 'A', 'B',
4830                                            'C', 'D', 'E', 'F' };
4831     static const char hex_table_lc[16] = { '0', '1', '2', '3',
4832                                            '4', '5', '6', '7',
4833                                            '8', '9', 'a', 'b',
4834                                            'c', 'd', 'e', 'f' };
4835     const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
4836
4837     for (i = 0; i < s; i++) {
4838         buff[i * 2]     = hex_table[src[i] >> 4];
4839         buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4840     }
4841
4842     return buff;
4843 }
4844
4845 int ff_hex_to_data(uint8_t *data, const char *p)
4846 {
4847     int c, len, v;
4848
4849     len = 0;
4850     v   = 1;
4851     for (;;) {
4852         p += strspn(p, SPACE_CHARS);
4853         if (*p == '\0')
4854             break;
4855         c = av_toupper((unsigned char) *p++);
4856         if (c >= '0' && c <= '9')
4857             c = c - '0';
4858         else if (c >= 'A' && c <= 'F')
4859             c = c - 'A' + 10;
4860         else
4861             break;
4862         v = (v << 4) | c;
4863         if (v & 0x100) {
4864             if (data)
4865                 data[len] = v;
4866             len++;
4867             v = 1;
4868         }
4869     }
4870     return len;
4871 }
4872
4873 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
4874                          unsigned int pts_num, unsigned int pts_den)
4875 {
4876     AVRational new_tb;
4877     if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
4878         if (new_tb.num != pts_num)
4879             av_log(NULL, AV_LOG_DEBUG,
4880                    "st:%d removing common factor %d from timebase\n",
4881                    s->index, pts_num / new_tb.num);
4882     } else
4883         av_log(NULL, AV_LOG_WARNING,
4884                "st:%d has too large timebase, reducing\n", s->index);
4885
4886     if (new_tb.num <= 0 || new_tb.den <= 0) {
4887         av_log(NULL, AV_LOG_ERROR,
4888                "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
4889                new_tb.num, new_tb.den,
4890                s->index);
4891         return;
4892     }
4893     s->time_base     = new_tb;
4894 #if FF_API_LAVF_AVCTX
4895 FF_DISABLE_DEPRECATION_WARNINGS
4896     s->codec->pkt_timebase = new_tb;
4897 FF_ENABLE_DEPRECATION_WARNINGS
4898 #endif
4899     s->internal->avctx->pkt_timebase = new_tb;
4900     s->pts_wrap_bits = pts_wrap_bits;
4901 }
4902
4903 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4904                         void *context)
4905 {
4906     const char *ptr = str;
4907
4908     /* Parse key=value pairs. */
4909     for (;;) {
4910         const char *key;
4911         char *dest = NULL, *dest_end;
4912         int key_len, dest_len = 0;
4913
4914         /* Skip whitespace and potential commas. */
4915         while (*ptr && (av_isspace(*ptr) || *ptr == ','))
4916             ptr++;
4917         if (!*ptr)
4918             break;
4919
4920         key = ptr;
4921
4922         if (!(ptr = strchr(key, '=')))
4923             break;
4924         ptr++;
4925         key_len = ptr - key;
4926
4927         callback_get_buf(context, key, key_len, &dest, &dest_len);
4928         dest_end = dest + dest_len - 1;
4929
4930         if (*ptr == '\"') {
4931             ptr++;
4932             while (*ptr && *ptr != '\"') {
4933                 if (*ptr == '\\') {
4934                     if (!ptr[1])
4935                         break;
4936                     if (dest && dest < dest_end)
4937                         *dest++ = ptr[1];
4938                     ptr += 2;
4939                 } else {
4940                     if (dest && dest < dest_end)
4941                         *dest++ = *ptr;
4942                     ptr++;
4943                 }
4944             }
4945             if (*ptr == '\"')
4946                 ptr++;
4947         } else {
4948             for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
4949                 if (dest && dest < dest_end)
4950                     *dest++ = *ptr;
4951         }
4952         if (dest)
4953             *dest = 0;
4954     }
4955 }
4956
4957 int ff_find_stream_index(AVFormatContext *s, int id)
4958 {
4959     int i;
4960     for (i = 0; i < s->nb_streams; i++)
4961         if (s->streams[i]->id == id)
4962             return i;
4963     return -1;
4964 }
4965
4966 int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
4967                          int std_compliance)
4968 {
4969     if (ofmt) {
4970         unsigned int codec_tag;
4971         if (ofmt->query_codec)
4972             return ofmt->query_codec(codec_id, std_compliance);
4973         else if (ofmt->codec_tag)
4974             return !!av_codec_get_tag2(ofmt->codec_tag, codec_id, &codec_tag);
4975         else if (codec_id == ofmt->video_codec ||
4976                  codec_id == ofmt->audio_codec ||
4977                  codec_id == ofmt->subtitle_codec ||
4978                  codec_id == ofmt->data_codec)
4979             return 1;
4980     }
4981     return AVERROR_PATCHWELCOME;
4982 }
4983
4984 int avformat_network_init(void)
4985 {
4986 #if CONFIG_NETWORK
4987     int ret;
4988     if ((ret = ff_network_init()) < 0)
4989         return ret;
4990     if ((ret = ff_tls_init()) < 0)
4991         return ret;
4992 #endif
4993     return 0;
4994 }
4995
4996 int avformat_network_deinit(void)
4997 {
4998 #if CONFIG_NETWORK
4999     ff_network_close();
5000     ff_tls_deinit();
5001 #endif
5002     return 0;
5003 }
5004
5005 int ff_add_param_change(AVPacket *pkt, int32_t channels,
5006                         uint64_t channel_layout, int32_t sample_rate,
5007                         int32_t width, int32_t height)
5008 {
5009     uint32_t flags = 0;
5010     int size = 4;
5011     uint8_t *data;
5012     if (!pkt)
5013         return AVERROR(EINVAL);
5014     if (channels) {
5015         size  += 4;
5016         flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
5017     }
5018     if (channel_layout) {
5019         size  += 8;
5020         flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
5021     }
5022     if (sample_rate) {
5023         size  += 4;
5024         flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
5025     }
5026     if (width || height) {
5027         size  += 8;
5028         flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
5029     }
5030     data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
5031     if (!data)
5032         return AVERROR(ENOMEM);
5033     bytestream_put_le32(&data, flags);
5034     if (channels)
5035         bytestream_put_le32(&data, channels);
5036     if (channel_layout)
5037         bytestream_put_le64(&data, channel_layout);
5038     if (sample_rate)
5039         bytestream_put_le32(&data, sample_rate);
5040     if (width || height) {
5041         bytestream_put_le32(&data, width);
5042         bytestream_put_le32(&data, height);
5043     }
5044     return 0;
5045 }
5046
5047 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
5048 {
5049     AVRational undef = {0, 1};
5050     AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
5051     AVRational codec_sample_aspect_ratio  = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
5052     AVRational frame_sample_aspect_ratio  = frame  ? frame->sample_aspect_ratio  : codec_sample_aspect_ratio;
5053
5054     av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
5055                stream_sample_aspect_ratio.num,  stream_sample_aspect_ratio.den, INT_MAX);
5056     if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
5057         stream_sample_aspect_ratio = undef;
5058
5059     av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
5060                frame_sample_aspect_ratio.num,  frame_sample_aspect_ratio.den, INT_MAX);
5061     if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
5062         frame_sample_aspect_ratio = undef;
5063
5064     if (stream_sample_aspect_ratio.num)
5065         return stream_sample_aspect_ratio;
5066     else
5067         return frame_sample_aspect_ratio;
5068 }
5069
5070 AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
5071 {
5072     AVRational fr = st->r_frame_rate;
5073     AVRational codec_fr = st->internal->avctx->framerate;
5074     AVRational   avg_fr = st->avg_frame_rate;
5075
5076     if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
5077         av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
5078         fr = avg_fr;
5079     }
5080
5081
5082     if (st->internal->avctx->ticks_per_frame > 1) {
5083         if (   codec_fr.num > 0 && codec_fr.den > 0 &&
5084             (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))
5085             fr = codec_fr;
5086     }
5087
5088     return fr;
5089 }
5090
5091 /**
5092  * Matches a stream specifier (but ignores requested index).
5093  *
5094  * @param indexptr set to point to the requested stream index if there is one
5095  *
5096  * @return <0 on error
5097  *         0  if st is NOT a matching stream
5098  *         >0 if st is a matching stream
5099  */
5100 static int match_stream_specifier(AVFormatContext *s, AVStream *st,
5101                                   const char *spec, const char **indexptr, AVProgram **p)
5102 {
5103     int match = 1;                      /* Stores if the specifier matches so far. */
5104     while (*spec) {
5105         if (*spec <= '9' && *spec >= '0') { /* opt:index */
5106             if (indexptr)
5107                 *indexptr = spec;
5108             return match;
5109         } else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
5110                    *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
5111             enum AVMediaType type;
5112             int nopic = 0;
5113
5114             switch (*spec++) {
5115             case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
5116             case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
5117             case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
5118             case 'd': type = AVMEDIA_TYPE_DATA;       break;
5119             case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
5120             case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
5121             default:  av_assert0(0);
5122             }
5123             if (*spec && *spec++ != ':')         /* If we are not at the end, then another specifier must follow. */
5124                 return AVERROR(EINVAL);
5125
5126 #if FF_API_LAVF_AVCTX
5127 FF_DISABLE_DEPRECATION_WARNINGS
5128             if (type != st->codecpar->codec_type
5129                && (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN || st->codec->codec_type != type))
5130                 match = 0;
5131     FF_ENABLE_DEPRECATION_WARNINGS
5132 #else
5133             if (type != st->codecpar->codec_type)
5134                 match = 0;
5135 #endif
5136             if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
5137                 match = 0;
5138         } else if (*spec == 'p' && *(spec + 1) == ':') {
5139             int prog_id, i, j;
5140             int found = 0;
5141             char *endptr;
5142             spec += 2;
5143             prog_id = strtol(spec, &endptr, 0);
5144             /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
5145             if (spec == endptr || (*endptr && *endptr++ != ':'))
5146                 return AVERROR(EINVAL);
5147             spec = endptr;
5148             if (match) {
5149                 for (i = 0; i < s->nb_programs; i++) {
5150                     if (s->programs[i]->id != prog_id)
5151                         continue;
5152
5153                     for (j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
5154                         if (st->index == s->programs[i]->stream_index[j]) {
5155                             found = 1;
5156                             if (p)
5157                                 *p = s->programs[i];
5158                             i = s->nb_programs;
5159                             break;
5160                         }
5161                     }
5162                 }
5163             }
5164             if (!found)
5165                 match = 0;
5166         } else if (*spec == '#' ||
5167                    (*spec == 'i' && *(spec + 1) == ':')) {
5168             int stream_id;
5169             char *endptr;
5170             spec += 1 + (*spec == 'i');
5171             stream_id = strtol(spec, &endptr, 0);
5172             if (spec == endptr || *endptr)                /* Disallow empty id and make sure we are at the end. */
5173                 return AVERROR(EINVAL);
5174             return match && (stream_id == st->id);
5175         } else if (*spec == 'm' && *(spec + 1) == ':') {
5176             AVDictionaryEntry *tag;
5177             char *key, *val;
5178             int ret;
5179
5180             if (match) {
5181                spec += 2;
5182                val = strchr(spec, ':');
5183
5184                key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
5185                if (!key)
5186                    return AVERROR(ENOMEM);
5187
5188                tag = av_dict_get(st->metadata, key, NULL, 0);
5189                if (tag) {
5190                    if (!val || !strcmp(tag->value, val + 1))
5191                        ret = 1;
5192                    else
5193                        ret = 0;
5194                } else
5195                    ret = 0;
5196
5197                av_freep(&key);
5198             }
5199             return match && ret;
5200         } else if (*spec == 'u' && *(spec + 1) == '\0') {
5201             AVCodecParameters *par = st->codecpar;
5202 #if FF_API_LAVF_AVCTX
5203 FF_DISABLE_DEPRECATION_WARNINGS
5204             AVCodecContext *codec = st->codec;
5205 FF_ENABLE_DEPRECATION_WARNINGS
5206 #endif
5207             int val;
5208             switch (par->codec_type) {
5209             case AVMEDIA_TYPE_AUDIO:
5210                 val = par->sample_rate && par->channels;
5211 #if FF_API_LAVF_AVCTX
5212                 val = val || (codec->sample_rate && codec->channels);
5213 #endif
5214                 if (par->format == AV_SAMPLE_FMT_NONE
5215 #if FF_API_LAVF_AVCTX
5216                     && codec->sample_fmt == AV_SAMPLE_FMT_NONE
5217 #endif
5218                     )
5219                     return 0;
5220                 break;
5221             case AVMEDIA_TYPE_VIDEO:
5222                 val = par->width && par->height;
5223 #if FF_API_LAVF_AVCTX
5224                 val = val || (codec->width && codec->height);
5225 #endif
5226                 if (par->format == AV_PIX_FMT_NONE
5227 #if FF_API_LAVF_AVCTX
5228                     && codec->pix_fmt == AV_PIX_FMT_NONE
5229 #endif
5230                     )
5231                     return 0;
5232                 break;
5233             case AVMEDIA_TYPE_UNKNOWN:
5234                 val = 0;
5235                 break;
5236             default:
5237                 val = 1;
5238                 break;
5239             }
5240 #if FF_API_LAVF_AVCTX
5241             return match && ((par->codec_id != AV_CODEC_ID_NONE || codec->codec_id != AV_CODEC_ID_NONE) && val != 0);
5242 #else
5243             return match && (par->codec_id != AV_CODEC_ID_NONE && val != 0);
5244 #endif
5245         } else {
5246             return AVERROR(EINVAL);
5247         }
5248     }
5249
5250     return match;
5251 }
5252
5253
5254 int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
5255                                     const char *spec)
5256 {
5257     int ret, index;
5258     char *endptr;
5259     const char *indexptr = NULL;
5260     AVProgram *p = NULL;
5261     int nb_streams;
5262
5263     ret = match_stream_specifier(s, st, spec, &indexptr, &p);
5264     if (ret < 0)
5265         goto error;
5266
5267     if (!indexptr)
5268         return ret;
5269
5270     index = strtol(indexptr, &endptr, 0);
5271     if (*endptr) {                  /* We can't have anything after the requested index. */
5272         ret = AVERROR(EINVAL);
5273         goto error;
5274     }
5275
5276     /* This is not really needed but saves us a loop for simple stream index specifiers. */
5277     if (spec == indexptr)
5278         return (index == st->index);
5279
5280     /* If we requested a matching stream index, we have to ensure st is that. */
5281     nb_streams = p ? p->nb_stream_indexes : s->nb_streams;
5282     for (int i = 0; i < nb_streams && index >= 0; i++) {
5283         AVStream *candidate = p ? s->streams[p->stream_index[i]] : s->streams[i];
5284         ret = match_stream_specifier(s, candidate, spec, NULL, NULL);
5285         if (ret < 0)
5286             goto error;
5287         if (ret > 0 && index-- == 0 && st == candidate)
5288             return 1;
5289     }
5290     return 0;
5291
5292 error:
5293     if (ret == AVERROR(EINVAL))
5294         av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
5295     return ret;
5296 }
5297
5298 int ff_generate_avci_extradata(AVStream *st)
5299 {
5300     static const uint8_t avci100_1080p_extradata[] = {
5301         // SPS
5302         0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5303         0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5304         0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5305         0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
5306         0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
5307         0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
5308         0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
5309         0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
5310         0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
5311         // PPS
5312         0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5313         0xd0
5314     };
5315     static const uint8_t avci100_1080i_extradata[] = {
5316         // SPS
5317         0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5318         0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5319         0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5320         0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
5321         0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
5322         0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
5323         0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
5324         0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
5325         0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
5326         0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
5327         0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
5328         // PPS
5329         0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5330         0xd0
5331     };
5332     static const uint8_t avci50_1080p_extradata[] = {
5333         // SPS
5334         0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5335         0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5336         0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5337         0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5338         0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5339         0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
5340         0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
5341         0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
5342         0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
5343         // PPS
5344         0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5345         0x11
5346     };
5347     static const uint8_t avci50_1080i_extradata[] = {
5348         // SPS
5349         0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5350         0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5351         0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5352         0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
5353         0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
5354         0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
5355         0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
5356         0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
5357         0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
5358         0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
5359         0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
5360         // PPS
5361         0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5362         0x11
5363     };
5364     static const uint8_t avci100_720p_extradata[] = {
5365         // SPS
5366         0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5367         0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
5368         0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
5369         0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
5370         0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
5371         0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
5372         0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
5373         0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
5374         0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
5375         0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
5376         // PPS
5377         0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
5378         0x11
5379     };
5380     static const uint8_t avci50_720p_extradata[] = {
5381         // SPS
5382         0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
5383         0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5384         0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5385         0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5386         0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5387         0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
5388         0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
5389         0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
5390         0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
5391         // PPS
5392         0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5393         0x11
5394     };
5395
5396     const uint8_t *data = NULL;
5397     int ret, size       = 0;
5398
5399     if (st->codecpar->width == 1920) {
5400         if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5401             data = avci100_1080p_extradata;
5402             size = sizeof(avci100_1080p_extradata);
5403         } else {
5404             data = avci100_1080i_extradata;
5405             size = sizeof(avci100_1080i_extradata);
5406         }
5407     } else if (st->codecpar->width == 1440) {
5408         if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5409             data = avci50_1080p_extradata;
5410             size = sizeof(avci50_1080p_extradata);
5411         } else {
5412             data = avci50_1080i_extradata;
5413             size = sizeof(avci50_1080i_extradata);
5414         }
5415     } else if (st->codecpar->width == 1280) {
5416         data = avci100_720p_extradata;
5417         size = sizeof(avci100_720p_extradata);
5418     } else if (st->codecpar->width == 960) {
5419         data = avci50_720p_extradata;
5420         size = sizeof(avci50_720p_extradata);
5421     }
5422
5423     if (!size)
5424         return 0;
5425
5426     if ((ret = ff_alloc_extradata(st->codecpar, size)) < 0)
5427         return ret;
5428     memcpy(st->codecpar->extradata, data, size);
5429
5430     return 0;
5431 }
5432
5433 uint8_t *av_stream_get_side_data(const AVStream *st,
5434                                  enum AVPacketSideDataType type, int *size)
5435 {
5436     int i;
5437
5438     for (i = 0; i < st->nb_side_data; i++) {
5439         if (st->side_data[i].type == type) {
5440             if (size)
5441                 *size = st->side_data[i].size;
5442             return st->side_data[i].data;
5443         }
5444     }
5445     if (size)
5446         *size = 0;
5447     return NULL;
5448 }
5449
5450 int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
5451                             uint8_t *data, size_t size)
5452 {
5453     AVPacketSideData *sd, *tmp;
5454     int i;
5455
5456     for (i = 0; i < st->nb_side_data; i++) {
5457         sd = &st->side_data[i];
5458
5459         if (sd->type == type) {
5460             av_freep(&sd->data);
5461             sd->data = data;
5462             sd->size = size;
5463             return 0;
5464         }
5465     }
5466
5467     if ((unsigned)st->nb_side_data + 1 >= INT_MAX / sizeof(*st->side_data))
5468         return AVERROR(ERANGE);
5469
5470     tmp = av_realloc(st->side_data, (st->nb_side_data + 1) * sizeof(*tmp));
5471     if (!tmp) {
5472         return AVERROR(ENOMEM);
5473     }
5474
5475     st->side_data = tmp;
5476     st->nb_side_data++;
5477
5478     sd = &st->side_data[st->nb_side_data - 1];
5479     sd->type = type;
5480     sd->data = data;
5481     sd->size = size;
5482
5483     return 0;
5484 }
5485
5486 uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
5487                                  int size)
5488 {
5489     int ret;
5490     uint8_t *data = av_malloc(size);
5491
5492     if (!data)
5493         return NULL;
5494
5495     ret = av_stream_add_side_data(st, type, data, size);
5496     if (ret < 0) {
5497         av_freep(&data);
5498         return NULL;
5499     }
5500
5501     return data;
5502 }
5503
5504 int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
5505 {
5506     int ret;
5507     const AVBitStreamFilter *bsf;
5508     AVBSFContext *bsfc;
5509
5510     av_assert0(!st->internal->bsfc);
5511
5512     if (!(bsf = av_bsf_get_by_name(name))) {
5513         av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter '%s'\n", name);
5514         return AVERROR_BSF_NOT_FOUND;
5515     }
5516
5517     if ((ret = av_bsf_alloc(bsf, &bsfc)) < 0)
5518         return ret;
5519
5520     bsfc->time_base_in = st->time_base;
5521     if ((ret = avcodec_parameters_copy(bsfc->par_in, st->codecpar)) < 0) {
5522         av_bsf_free(&bsfc);
5523         return ret;
5524     }
5525
5526     if (args && bsfc->filter->priv_class) {
5527         const AVOption *opt = av_opt_next(bsfc->priv_data, NULL);
5528         const char * shorthand[2] = {NULL};
5529
5530         if (opt)
5531             shorthand[0] = opt->name;
5532
5533         if ((ret = av_opt_set_from_string(bsfc->priv_data, args, shorthand, "=", ":")) < 0) {
5534             av_bsf_free(&bsfc);
5535             return ret;
5536         }
5537     }
5538
5539     if ((ret = av_bsf_init(bsfc)) < 0) {
5540         av_bsf_free(&bsfc);
5541         return ret;
5542     }
5543
5544     st->internal->bsfc = bsfc;
5545
5546     av_log(NULL, AV_LOG_VERBOSE,
5547            "Automatically inserted bitstream filter '%s'; args='%s'\n",
5548            name, args ? args : "");
5549     return 1;
5550 }
5551
5552 #if FF_API_OLD_BSF
5553 FF_DISABLE_DEPRECATION_WARNINGS
5554 int av_apply_bitstream_filters(AVCodecContext *codec, AVPacket *pkt,
5555                                AVBitStreamFilterContext *bsfc)
5556 {
5557     int ret = 0;
5558     while (bsfc) {
5559         AVPacket new_pkt = *pkt;
5560         int a = av_bitstream_filter_filter(bsfc, codec, NULL,
5561                                            &new_pkt.data, &new_pkt.size,
5562                                            pkt->data, pkt->size,
5563                                            pkt->flags & AV_PKT_FLAG_KEY);
5564         if (a == 0 && new_pkt.size == 0 && new_pkt.side_data_elems == 0) {
5565             av_packet_unref(pkt);
5566             memset(pkt, 0, sizeof(*pkt));
5567             return 0;
5568         }
5569         if(a == 0 && new_pkt.data != pkt->data) {
5570             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
5571             if (t) {
5572                 memcpy(t, new_pkt.data, new_pkt.size);
5573                 memset(t + new_pkt.size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5574                 new_pkt.data = t;
5575                 new_pkt.buf = NULL;
5576                 a = 1;
5577             } else {
5578                 a = AVERROR(ENOMEM);
5579             }
5580         }
5581         if (a > 0) {
5582             new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
5583                                            av_buffer_default_free, NULL, 0);
5584             if (new_pkt.buf) {
5585                 pkt->side_data = NULL;
5586                 pkt->side_data_elems = 0;
5587                 av_packet_unref(pkt);
5588             } else {
5589                 av_freep(&new_pkt.data);
5590                 a = AVERROR(ENOMEM);
5591             }
5592         }
5593         if (a < 0) {
5594             av_log(codec, AV_LOG_ERROR,
5595                    "Failed to open bitstream filter %s for stream %d with codec %s",
5596                    bsfc->filter->name, pkt->stream_index,
5597                    codec->codec ? codec->codec->name : "copy");
5598             ret = a;
5599             break;
5600         }
5601         *pkt = new_pkt;
5602
5603         bsfc = bsfc->next;
5604     }
5605     return ret;
5606 }
5607 FF_ENABLE_DEPRECATION_WARNINGS
5608 #endif
5609
5610 int ff_format_output_open(AVFormatContext *s, const char *url, AVDictionary **options)
5611 {
5612     if (!s->oformat)
5613         return AVERROR(EINVAL);
5614
5615     if (!(s->oformat->flags & AVFMT_NOFILE))
5616         return s->io_open(s, &s->pb, url, AVIO_FLAG_WRITE, options);
5617     return 0;
5618 }
5619
5620 void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
5621 {
5622     if (*pb)
5623         s->io_close(s, *pb);
5624     *pb = NULL;
5625 }
5626
5627 int ff_is_http_proto(char *filename) {
5628     const char *proto = avio_find_protocol_name(filename);
5629     return proto ? (!av_strcasecmp(proto, "http") || !av_strcasecmp(proto, "https")) : 0;
5630 }
5631
5632 int ff_parse_creation_time_metadata(AVFormatContext *s, int64_t *timestamp, int return_seconds)
5633 {
5634     AVDictionaryEntry *entry;
5635     int64_t parsed_timestamp;
5636     int ret;
5637     if ((entry = av_dict_get(s->metadata, "creation_time", NULL, 0))) {
5638         if ((ret = av_parse_time(&parsed_timestamp, entry->value, 0)) >= 0) {
5639             *timestamp = return_seconds ? parsed_timestamp / 1000000 : parsed_timestamp;
5640             return 1;
5641         } else {
5642             av_log(s, AV_LOG_WARNING, "Failed to parse creation_time %s\n", entry->value);
5643             return ret;
5644         }
5645     }
5646     return 0;
5647 }
5648
5649 int ff_standardize_creation_time(AVFormatContext *s)
5650 {
5651     int64_t timestamp;
5652     int ret = ff_parse_creation_time_metadata(s, &timestamp, 0);
5653     if (ret == 1)
5654         return avpriv_dict_set_timestamp(&s->metadata, "creation_time", timestamp);
5655     return ret;
5656 }
5657
5658 int ff_get_packet_palette(AVFormatContext *s, AVPacket *pkt, int ret, uint32_t *palette)
5659 {
5660     uint8_t *side_data;
5661     int size;
5662
5663     side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_PALETTE, &size);
5664     if (side_data) {
5665         if (size != AVPALETTE_SIZE) {
5666             av_log(s, AV_LOG_ERROR, "Invalid palette side data\n");
5667             return AVERROR_INVALIDDATA;
5668         }
5669         memcpy(palette, side_data, AVPALETTE_SIZE);
5670         return 1;
5671     }
5672
5673     if (ret == CONTAINS_PAL) {
5674         int i;
5675         for (i = 0; i < AVPALETTE_COUNT; i++)
5676             palette[i] = AV_RL32(pkt->data + pkt->size - AVPALETTE_SIZE + i*4);
5677         return 1;
5678     }
5679
5680     return 0;
5681 }
5682
5683 int ff_bprint_to_codecpar_extradata(AVCodecParameters *par, struct AVBPrint *buf)
5684 {
5685     int ret;
5686     char *str;
5687
5688     ret = av_bprint_finalize(buf, &str);
5689     if (ret < 0)
5690         return ret;
5691     if (!av_bprint_is_complete(buf)) {
5692         av_free(str);
5693         return AVERROR(ENOMEM);
5694     }
5695
5696     par->extradata = str;
5697     /* Note: the string is NUL terminated (so extradata can be read as a
5698      * string), but the ending character is not accounted in the size (in
5699      * binary formats you are likely not supposed to mux that character). When
5700      * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
5701      * zeros. */
5702     par->extradata_size = buf->len;
5703     return 0;
5704 }
5705
5706 int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
5707                                                   AVStream *ost, const AVStream *ist,
5708                                                   enum AVTimebaseSource copy_tb)
5709 {
5710     //TODO: use [io]st->internal->avctx
5711     const AVCodecContext *dec_ctx;
5712     AVCodecContext       *enc_ctx;
5713
5714 #if FF_API_LAVF_AVCTX
5715 FF_DISABLE_DEPRECATION_WARNINGS
5716     dec_ctx = ist->codec;
5717     enc_ctx = ost->codec;
5718 FF_ENABLE_DEPRECATION_WARNINGS
5719 #else
5720     dec_ctx = ist->internal->avctx;
5721     enc_ctx = ost->internal->avctx;
5722 #endif
5723
5724     enc_ctx->time_base = ist->time_base;
5725     /*
5726      * Avi is a special case here because it supports variable fps but
5727      * having the fps and timebase differe significantly adds quite some
5728      * overhead
5729      */
5730     if (!strcmp(ofmt->name, "avi")) {
5731 #if FF_API_R_FRAME_RATE
5732         if (copy_tb == AVFMT_TBCF_AUTO && ist->r_frame_rate.num
5733             && av_q2d(ist->r_frame_rate) >= av_q2d(ist->avg_frame_rate)
5734             && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(ist->time_base)
5735             && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(dec_ctx->time_base)
5736             && av_q2d(ist->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
5737             || copy_tb == AVFMT_TBCF_R_FRAMERATE) {
5738             enc_ctx->time_base.num = ist->r_frame_rate.den;
5739             enc_ctx->time_base.den = 2*ist->r_frame_rate.num;
5740             enc_ctx->ticks_per_frame = 2;
5741         } else
5742 #endif
5743             if (copy_tb == AVFMT_TBCF_AUTO && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->time_base)
5744                    && av_q2d(ist->time_base) < 1.0/500
5745                    || copy_tb == AVFMT_TBCF_DECODER) {
5746             enc_ctx->time_base = dec_ctx->time_base;
5747             enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5748             enc_ctx->time_base.den *= 2;
5749             enc_ctx->ticks_per_frame = 2;
5750         }
5751     } else if (!(ofmt->flags & AVFMT_VARIABLE_FPS)
5752                && !av_match_name(ofmt->name, "mov,mp4,3gp,3g2,psp,ipod,ismv,f4v")) {
5753         if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx->time_base.den
5754             && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->time_base)
5755             && av_q2d(ist->time_base) < 1.0/500
5756             || copy_tb == AVFMT_TBCF_DECODER) {
5757             enc_ctx->time_base = dec_ctx->time_base;
5758             enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5759         }
5760     }
5761
5762     if ((enc_ctx->codec_tag == AV_RL32("tmcd") || ost->codecpar->codec_tag == AV_RL32("tmcd"))
5763         && dec_ctx->time_base.num < dec_ctx->time_base.den
5764         && dec_ctx->time_base.num > 0
5765         && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
5766         enc_ctx->time_base = dec_ctx->time_base;
5767     }
5768
5769     if (ost->avg_frame_rate.num)
5770         enc_ctx->time_base = av_inv_q(ost->avg_frame_rate);
5771
5772     av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
5773               enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
5774
5775     return 0;
5776 }
5777
5778 AVRational av_stream_get_codec_timebase(const AVStream *st)
5779 {
5780     // See avformat_transfer_internal_stream_timing_info() TODO.
5781 #if FF_API_LAVF_AVCTX
5782 FF_DISABLE_DEPRECATION_WARNINGS
5783     return st->codec->time_base;
5784 FF_ENABLE_DEPRECATION_WARNINGS
5785 #else
5786     return st->internal->avctx->time_base;
5787 #endif
5788 }
5789
5790 void ff_format_set_url(AVFormatContext *s, char *url)
5791 {
5792     av_assert0(url);
5793     av_freep(&s->url);
5794     s->url = url;
5795 #if FF_API_FORMAT_FILENAME
5796 FF_DISABLE_DEPRECATION_WARNINGS
5797     av_strlcpy(s->filename, url, sizeof(s->filename));
5798 FF_ENABLE_DEPRECATION_WARNINGS
5799 #endif
5800 }