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.

5272 lines
181KB

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