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