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.

5798 lines
201KB

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