You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5841 lines
203KB

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