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