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