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