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