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.

3447 lines
109KB

  1. /*
  2. * various utility functions for use within Libav
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #undef NDEBUG
  22. #include <assert.h>
  23. #include <stdarg.h>
  24. #include <stdint.h>
  25. #include "config.h"
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/dict.h"
  29. #include "libavutil/internal.h"
  30. #include "libavutil/mathematics.h"
  31. #include "libavutil/opt.h"
  32. #include "libavutil/parseutils.h"
  33. #include "libavutil/pixdesc.h"
  34. #include "libavutil/time.h"
  35. #include "libavcodec/bytestream.h"
  36. #include "libavcodec/internal.h"
  37. #include "audiointerleave.h"
  38. #include "avformat.h"
  39. #include "id3v2.h"
  40. #include "internal.h"
  41. #include "metadata.h"
  42. #if CONFIG_NETWORK
  43. #include "network.h"
  44. #endif
  45. #include "riff.h"
  46. #include "url.h"
  47. /**
  48. * @file
  49. * various utility functions for use within Libav
  50. */
  51. unsigned avformat_version(void)
  52. {
  53. return LIBAVFORMAT_VERSION_INT;
  54. }
  55. const char *avformat_configuration(void)
  56. {
  57. return LIBAV_CONFIGURATION;
  58. }
  59. const char *avformat_license(void)
  60. {
  61. #define LICENSE_PREFIX "libavformat license: "
  62. return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
  63. }
  64. /* an arbitrarily chosen "sane" max packet size -- 50M */
  65. #define SANE_CHUNK_SIZE (50000000)
  66. /* Read the data in sane-sized chunks and append to pkt.
  67. * Return the number of bytes read or an error. */
  68. static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
  69. {
  70. int64_t chunk_size = size;
  71. int64_t orig_pos = pkt->pos; // av_grow_packet might reset pos
  72. int orig_size = pkt->size;
  73. int ret = 0;
  74. do {
  75. int prev_size = pkt->size;
  76. int read_size;
  77. /* When the caller requests a lot of data, limit it to the amount
  78. * left in file or SANE_CHUNK_SIZE when it is not known. */
  79. if (size > SANE_CHUNK_SIZE) {
  80. int64_t filesize = avio_size(s) - avio_tell(s);
  81. chunk_size = FFMAX(filesize, SANE_CHUNK_SIZE);
  82. }
  83. read_size = FFMIN(size, chunk_size);
  84. ret = av_grow_packet(pkt, read_size);
  85. if (ret < 0)
  86. break;
  87. ret = avio_read(s, pkt->data + prev_size, read_size);
  88. if (ret != read_size) {
  89. av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
  90. break;
  91. }
  92. size -= read_size;
  93. } while (size > 0);
  94. pkt->pos = orig_pos;
  95. if (!pkt->size)
  96. av_packet_unref(pkt);
  97. return pkt->size > orig_size ? pkt->size - orig_size : ret;
  98. }
  99. int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
  100. {
  101. av_init_packet(pkt);
  102. pkt->data = NULL;
  103. pkt->size = 0;
  104. pkt->pos = avio_tell(s);
  105. return append_packet_chunked(s, pkt, size);
  106. }
  107. int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
  108. {
  109. if (!pkt->size)
  110. return av_get_packet(s, pkt, size);
  111. return append_packet_chunked(s, pkt, size);
  112. }
  113. int av_filename_number_test(const char *filename)
  114. {
  115. char buf[1024];
  116. return filename &&
  117. (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
  118. }
  119. static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
  120. AVProbeData *pd, int score)
  121. {
  122. static const struct {
  123. const char *name;
  124. enum AVCodecID id;
  125. enum AVMediaType type;
  126. } fmt_id_type[] = {
  127. { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
  128. { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
  129. { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
  130. { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
  131. { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
  132. { "latm", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
  133. { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
  134. { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
  135. { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
  136. { 0 }
  137. };
  138. AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
  139. if (fmt) {
  140. int i;
  141. av_log(s, AV_LOG_DEBUG,
  142. "Probe with size=%d, packets=%d detected %s with score=%d\n",
  143. pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets,
  144. fmt->name, score);
  145. for (i = 0; fmt_id_type[i].name; i++) {
  146. if (!strcmp(fmt->name, fmt_id_type[i].name)) {
  147. st->codecpar->codec_id = fmt_id_type[i].id;
  148. st->codecpar->codec_type = fmt_id_type[i].type;
  149. #if FF_API_LAVF_AVCTX
  150. FF_DISABLE_DEPRECATION_WARNINGS
  151. st->codec->codec_type = st->codecpar->codec_type;
  152. st->codec->codec_id = st->codecpar->codec_id;
  153. FF_ENABLE_DEPRECATION_WARNINGS
  154. #endif
  155. break;
  156. }
  157. }
  158. }
  159. return !!fmt;
  160. }
  161. /************************************************************/
  162. /* input media file */
  163. /* Open input file and probe the format if necessary. */
  164. static int init_input(AVFormatContext *s, const char *filename,
  165. AVDictionary **options)
  166. {
  167. int ret;
  168. AVProbeData pd = { filename, NULL, 0 };
  169. if (s->pb) {
  170. s->flags |= AVFMT_FLAG_CUSTOM_IO;
  171. if (!s->iformat)
  172. return av_probe_input_buffer(s->pb, &s->iformat, filename,
  173. s, 0, s->probesize);
  174. else if (s->iformat->flags & AVFMT_NOFILE)
  175. return AVERROR(EINVAL);
  176. return 0;
  177. }
  178. if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
  179. (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
  180. return 0;
  181. ret = s->io_open(s, &s->pb, filename, AVIO_FLAG_READ, options);
  182. if (ret < 0)
  183. return ret;
  184. if (s->iformat)
  185. return 0;
  186. return av_probe_input_buffer(s->pb, &s->iformat, filename,
  187. s, 0, s->probesize);
  188. }
  189. static int add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
  190. AVPacketList **plast_pktl, int ref)
  191. {
  192. AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
  193. int ret;
  194. if (!pktl)
  195. return AVERROR(ENOMEM);
  196. if (ref) {
  197. if ((ret = av_packet_ref(&pktl->pkt, pkt)) < 0) {
  198. av_free(pktl);
  199. return ret;
  200. }
  201. } else {
  202. pktl->pkt = *pkt;
  203. }
  204. if (*packet_buffer)
  205. (*plast_pktl)->next = pktl;
  206. else
  207. *packet_buffer = pktl;
  208. /* Add the packet in the buffered packet list. */
  209. *plast_pktl = pktl;
  210. return 0;
  211. }
  212. static int queue_attached_pictures(AVFormatContext *s)
  213. {
  214. int i, ret;
  215. for (i = 0; i < s->nb_streams; i++)
  216. if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
  217. s->streams[i]->discard < AVDISCARD_ALL) {
  218. ret = add_to_pktbuf(&s->internal->raw_packet_buffer,
  219. &s->streams[i]->attached_pic,
  220. &s->internal->raw_packet_buffer_end, 1);
  221. if (ret < 0)
  222. return ret;
  223. }
  224. return 0;
  225. }
  226. #if FF_API_LAVF_AVCTX
  227. FF_DISABLE_DEPRECATION_WARNINGS
  228. static int update_stream_avctx(AVFormatContext *s)
  229. {
  230. int i, ret;
  231. for (i = 0; i < s->nb_streams; i++) {
  232. AVStream *st = s->streams[i];
  233. if (!st->internal->need_codec_update)
  234. continue;
  235. ret = avcodec_parameters_to_context(st->codec, st->codecpar);
  236. if (ret < 0)
  237. return ret;
  238. st->internal->need_codec_update = 0;
  239. }
  240. return 0;
  241. }
  242. FF_ENABLE_DEPRECATION_WARNINGS
  243. #endif
  244. int avformat_open_input(AVFormatContext **ps, const char *filename,
  245. AVInputFormat *fmt, AVDictionary **options)
  246. {
  247. AVFormatContext *s = *ps;
  248. int i, ret = 0;
  249. AVDictionary *tmp = NULL;
  250. ID3v2ExtraMeta *id3v2_extra_meta = NULL;
  251. if (!s && !(s = avformat_alloc_context()))
  252. return AVERROR(ENOMEM);
  253. if (fmt)
  254. s->iformat = fmt;
  255. if (options)
  256. av_dict_copy(&tmp, *options, 0);
  257. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  258. goto fail;
  259. if ((ret = init_input(s, filename, &tmp)) < 0)
  260. goto fail;
  261. /* Check filename in case an image number is expected. */
  262. if (s->iformat->flags & AVFMT_NEEDNUMBER) {
  263. if (!av_filename_number_test(filename)) {
  264. ret = AVERROR(EINVAL);
  265. goto fail;
  266. }
  267. }
  268. s->duration = s->start_time = AV_NOPTS_VALUE;
  269. av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
  270. /* Allocate private data. */
  271. if (s->iformat->priv_data_size > 0) {
  272. if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
  273. ret = AVERROR(ENOMEM);
  274. goto fail;
  275. }
  276. if (s->iformat->priv_class) {
  277. *(const AVClass **) s->priv_data = s->iformat->priv_class;
  278. av_opt_set_defaults(s->priv_data);
  279. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  280. goto fail;
  281. }
  282. }
  283. /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
  284. if (s->pb)
  285. ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
  286. if (s->iformat->read_header)
  287. if ((ret = s->iformat->read_header(s)) < 0)
  288. goto fail;
  289. if (id3v2_extra_meta &&
  290. (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
  291. goto fail;
  292. ff_id3v2_free_extra_meta(&id3v2_extra_meta);
  293. if ((ret = queue_attached_pictures(s)) < 0)
  294. goto fail;
  295. if (s->pb && !s->internal->data_offset)
  296. s->internal->data_offset = avio_tell(s->pb);
  297. s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
  298. #if FF_API_LAVF_AVCTX
  299. update_stream_avctx(s);
  300. #endif
  301. for (i = 0; i < s->nb_streams; i++)
  302. s->streams[i]->internal->orig_codec_id = s->streams[i]->codecpar->codec_id;
  303. if (options) {
  304. av_dict_free(options);
  305. *options = tmp;
  306. }
  307. *ps = s;
  308. return 0;
  309. fail:
  310. ff_id3v2_free_extra_meta(&id3v2_extra_meta);
  311. av_dict_free(&tmp);
  312. if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
  313. avio_close(s->pb);
  314. avformat_free_context(s);
  315. *ps = NULL;
  316. return ret;
  317. }
  318. /*******************************************************/
  319. static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
  320. {
  321. if (st->codecpar->codec_id == AV_CODEC_ID_PROBE) {
  322. AVProbeData *pd = &st->probe_data;
  323. av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
  324. --st->probe_packets;
  325. if (pkt) {
  326. int err;
  327. if ((err = av_reallocp(&pd->buf, pd->buf_size + pkt->size +
  328. AVPROBE_PADDING_SIZE)) < 0)
  329. return err;
  330. memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
  331. pd->buf_size += pkt->size;
  332. memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
  333. } else {
  334. st->probe_packets = 0;
  335. if (!pd->buf_size) {
  336. av_log(s, AV_LOG_ERROR,
  337. "nothing to probe for stream %d\n", st->index);
  338. return 0;
  339. }
  340. }
  341. if (!st->probe_packets ||
  342. av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
  343. set_codec_from_probe_data(s, st, pd, st->probe_packets > 0
  344. ? AVPROBE_SCORE_MAX / 4 : 0);
  345. if (st->codecpar->codec_id != AV_CODEC_ID_PROBE) {
  346. pd->buf_size = 0;
  347. av_freep(&pd->buf);
  348. av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
  349. }
  350. }
  351. }
  352. return 0;
  353. }
  354. int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
  355. {
  356. int ret, i, err;
  357. AVStream *st;
  358. for (;;) {
  359. AVPacketList *pktl = s->internal->raw_packet_buffer;
  360. if (pktl) {
  361. *pkt = pktl->pkt;
  362. st = s->streams[pkt->stream_index];
  363. if (st->codecpar->codec_id != AV_CODEC_ID_PROBE ||
  364. !st->probe_packets ||
  365. s->internal->raw_packet_buffer_remaining_size < pkt->size) {
  366. AVProbeData *pd;
  367. if (st->probe_packets)
  368. if ((err = probe_codec(s, st, NULL)) < 0)
  369. return err;
  370. pd = &st->probe_data;
  371. av_freep(&pd->buf);
  372. pd->buf_size = 0;
  373. s->internal->raw_packet_buffer = pktl->next;
  374. s->internal->raw_packet_buffer_remaining_size += pkt->size;
  375. av_free(pktl);
  376. return 0;
  377. }
  378. }
  379. pkt->data = NULL;
  380. pkt->size = 0;
  381. av_init_packet(pkt);
  382. ret = s->iformat->read_packet(s, pkt);
  383. if (ret < 0) {
  384. if (!pktl || ret == AVERROR(EAGAIN))
  385. return ret;
  386. for (i = 0; i < s->nb_streams; i++) {
  387. st = s->streams[i];
  388. if (st->probe_packets)
  389. if ((err = probe_codec(s, st, NULL)) < 0)
  390. return err;
  391. }
  392. continue;
  393. }
  394. if (!pkt->buf) {
  395. AVPacket tmp = { 0 };
  396. ret = av_packet_ref(&tmp, pkt);
  397. if (ret < 0)
  398. return ret;
  399. *pkt = tmp;
  400. }
  401. if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
  402. (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
  403. av_log(s, AV_LOG_WARNING,
  404. "Dropped corrupted packet (stream = %d)\n",
  405. pkt->stream_index);
  406. av_packet_unref(pkt);
  407. continue;
  408. }
  409. st = s->streams[pkt->stream_index];
  410. switch (st->codecpar->codec_type) {
  411. case AVMEDIA_TYPE_VIDEO:
  412. if (s->video_codec_id)
  413. st->codecpar->codec_id = s->video_codec_id;
  414. break;
  415. case AVMEDIA_TYPE_AUDIO:
  416. if (s->audio_codec_id)
  417. st->codecpar->codec_id = s->audio_codec_id;
  418. break;
  419. case AVMEDIA_TYPE_SUBTITLE:
  420. if (s->subtitle_codec_id)
  421. st->codecpar->codec_id = s->subtitle_codec_id;
  422. break;
  423. }
  424. if (!pktl && (st->codecpar->codec_id != AV_CODEC_ID_PROBE ||
  425. !st->probe_packets))
  426. return ret;
  427. err = add_to_pktbuf(&s->internal->raw_packet_buffer, pkt,
  428. &s->internal->raw_packet_buffer_end, 0);
  429. if (err)
  430. return err;
  431. s->internal->raw_packet_buffer_remaining_size -= pkt->size;
  432. if ((err = probe_codec(s, st, pkt)) < 0)
  433. return err;
  434. }
  435. }
  436. /**********************************************************/
  437. /**
  438. * Return the frame duration in seconds. Return 0 if not available.
  439. */
  440. void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
  441. AVCodecParserContext *pc, AVPacket *pkt)
  442. {
  443. AVRational codec_framerate = s->iformat ? st->internal->avctx->framerate :
  444. (AVRational){ 0, 1 };
  445. int frame_size;
  446. *pnum = 0;
  447. *pden = 0;
  448. switch (st->codecpar->codec_type) {
  449. case AVMEDIA_TYPE_VIDEO:
  450. if (st->avg_frame_rate.num) {
  451. *pnum = st->avg_frame_rate.den;
  452. *pden = st->avg_frame_rate.num;
  453. } else if (st->time_base.num * 1000LL > st->time_base.den) {
  454. *pnum = st->time_base.num;
  455. *pden = st->time_base.den;
  456. } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
  457. *pnum = codec_framerate.den;
  458. *pden = codec_framerate.num;
  459. if (pc && pc->repeat_pict) {
  460. if (*pnum > INT_MAX / (1 + pc->repeat_pict))
  461. *pden /= 1 + pc->repeat_pict;
  462. else
  463. *pnum *= 1 + pc->repeat_pict;
  464. }
  465. /* If this codec can be interlaced or progressive then we need
  466. * a parser to compute duration of a packet. Thus if we have
  467. * no parser in such case leave duration undefined. */
  468. if (st->internal->avctx->ticks_per_frame > 1 && !pc)
  469. *pnum = *pden = 0;
  470. }
  471. break;
  472. case AVMEDIA_TYPE_AUDIO:
  473. frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
  474. if (frame_size <= 0 || st->codecpar->sample_rate <= 0)
  475. break;
  476. *pnum = frame_size;
  477. *pden = st->codecpar->sample_rate;
  478. break;
  479. default:
  480. break;
  481. }
  482. }
  483. static int is_intra_only(enum AVCodecID id)
  484. {
  485. const AVCodecDescriptor *d = avcodec_descriptor_get(id);
  486. if (!d)
  487. return 0;
  488. if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
  489. return 0;
  490. return 1;
  491. }
  492. static void update_initial_timestamps(AVFormatContext *s, int stream_index,
  493. int64_t dts, int64_t pts)
  494. {
  495. AVStream *st = s->streams[stream_index];
  496. AVPacketList *pktl = s->internal->packet_buffer;
  497. if (st->first_dts != AV_NOPTS_VALUE ||
  498. dts == AV_NOPTS_VALUE ||
  499. st->cur_dts == AV_NOPTS_VALUE)
  500. return;
  501. st->first_dts = dts - st->cur_dts;
  502. st->cur_dts = dts;
  503. for (; pktl; pktl = pktl->next) {
  504. if (pktl->pkt.stream_index != stream_index)
  505. continue;
  506. // FIXME: think more about this check
  507. if (pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
  508. pktl->pkt.pts += st->first_dts;
  509. if (pktl->pkt.dts != AV_NOPTS_VALUE)
  510. pktl->pkt.dts += st->first_dts;
  511. if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
  512. st->start_time = pktl->pkt.pts;
  513. }
  514. if (st->start_time == AV_NOPTS_VALUE)
  515. st->start_time = pts;
  516. }
  517. static void update_initial_durations(AVFormatContext *s, AVStream *st,
  518. int stream_index, int duration)
  519. {
  520. AVPacketList *pktl = s->internal->packet_buffer;
  521. int64_t cur_dts = 0;
  522. if (st->first_dts != AV_NOPTS_VALUE) {
  523. cur_dts = st->first_dts;
  524. for (; pktl; pktl = pktl->next) {
  525. if (pktl->pkt.stream_index == stream_index) {
  526. if (pktl->pkt.pts != pktl->pkt.dts ||
  527. pktl->pkt.dts != AV_NOPTS_VALUE ||
  528. pktl->pkt.duration)
  529. break;
  530. cur_dts -= duration;
  531. }
  532. }
  533. pktl = s->internal->packet_buffer;
  534. st->first_dts = cur_dts;
  535. } else if (st->cur_dts)
  536. return;
  537. for (; pktl; pktl = pktl->next) {
  538. if (pktl->pkt.stream_index != stream_index)
  539. continue;
  540. if (pktl->pkt.pts == pktl->pkt.dts &&
  541. pktl->pkt.dts == AV_NOPTS_VALUE &&
  542. !pktl->pkt.duration) {
  543. pktl->pkt.dts = cur_dts;
  544. if (!st->internal->avctx->has_b_frames)
  545. pktl->pkt.pts = cur_dts;
  546. cur_dts += duration;
  547. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  548. pktl->pkt.duration = duration;
  549. } else
  550. break;
  551. }
  552. if (st->first_dts == AV_NOPTS_VALUE)
  553. st->cur_dts = cur_dts;
  554. }
  555. static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
  556. AVCodecParserContext *pc, AVPacket *pkt)
  557. {
  558. int num, den, presentation_delayed, delay, i;
  559. int64_t offset;
  560. if (s->flags & AVFMT_FLAG_NOFILLIN)
  561. return;
  562. if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
  563. pkt->dts = AV_NOPTS_VALUE;
  564. /* do we have a video B-frame ? */
  565. delay = st->internal->avctx->has_b_frames;
  566. presentation_delayed = 0;
  567. /* XXX: need has_b_frame, but cannot get it if the codec is
  568. * not initialized */
  569. if (delay &&
  570. pc && pc->pict_type != AV_PICTURE_TYPE_B)
  571. presentation_delayed = 1;
  572. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
  573. st->pts_wrap_bits < 63 &&
  574. pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
  575. pkt->dts -= 1LL << st->pts_wrap_bits;
  576. }
  577. /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
  578. * We take the conservative approach and discard both.
  579. * Note: If this is misbehaving for an H.264 file, then possibly
  580. * presentation_delayed is not set correctly. */
  581. if (delay == 1 && pkt->dts == pkt->pts &&
  582. pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
  583. av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
  584. pkt->dts = AV_NOPTS_VALUE;
  585. }
  586. if (pkt->duration == 0 && st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
  587. ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
  588. if (den && num) {
  589. pkt->duration = av_rescale_rnd(1, num * (int64_t) st->time_base.den,
  590. den * (int64_t) st->time_base.num,
  591. AV_ROUND_DOWN);
  592. if (pkt->duration != 0 && s->internal->packet_buffer)
  593. update_initial_durations(s, st, pkt->stream_index,
  594. pkt->duration);
  595. }
  596. }
  597. /* Correct timestamps with byte offset if demuxers only have timestamps
  598. * on packet boundaries */
  599. if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
  600. /* this will estimate bitrate based on this frame's duration and size */
  601. offset = av_rescale(pc->offset, pkt->duration, pkt->size);
  602. if (pkt->pts != AV_NOPTS_VALUE)
  603. pkt->pts += offset;
  604. if (pkt->dts != AV_NOPTS_VALUE)
  605. pkt->dts += offset;
  606. }
  607. /* This may be redundant, but it should not hurt. */
  608. if (pkt->dts != AV_NOPTS_VALUE &&
  609. pkt->pts != AV_NOPTS_VALUE &&
  610. pkt->pts > pkt->dts)
  611. presentation_delayed = 1;
  612. av_log(NULL, AV_LOG_TRACE,
  613. "IN delayed:%d pts:%"PRId64", dts:%"PRId64" "
  614. "cur_dts:%"PRId64" st:%d pc:%p\n",
  615. presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
  616. pkt->stream_index, pc);
  617. /* Interpolate PTS and DTS if they are not present. We skip H.264
  618. * currently because delay and has_b_frames are not reliably set. */
  619. if ((delay == 0 || (delay == 1 && pc)) &&
  620. st->codecpar->codec_id != AV_CODEC_ID_H264) {
  621. if (presentation_delayed) {
  622. /* DTS = decompression timestamp */
  623. /* PTS = presentation timestamp */
  624. if (pkt->dts == AV_NOPTS_VALUE)
  625. pkt->dts = st->last_IP_pts;
  626. update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
  627. if (pkt->dts == AV_NOPTS_VALUE)
  628. pkt->dts = st->cur_dts;
  629. /* This is tricky: the dts must be incremented by the duration
  630. * of the frame we are displaying, i.e. the last I- or P-frame. */
  631. if (st->last_IP_duration == 0)
  632. st->last_IP_duration = pkt->duration;
  633. if (pkt->dts != AV_NOPTS_VALUE)
  634. st->cur_dts = pkt->dts + st->last_IP_duration;
  635. st->last_IP_duration = pkt->duration;
  636. st->last_IP_pts = pkt->pts;
  637. /* Cannot compute PTS if not present (we can compute it only
  638. * by knowing the future. */
  639. } else if (pkt->pts != AV_NOPTS_VALUE ||
  640. pkt->dts != AV_NOPTS_VALUE ||
  641. pkt->duration ||
  642. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  643. int duration = pkt->duration;
  644. if (!duration && st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  645. ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
  646. if (den && num) {
  647. duration = av_rescale_rnd(1,
  648. num * (int64_t) st->time_base.den,
  649. den * (int64_t) st->time_base.num,
  650. AV_ROUND_DOWN);
  651. if (duration != 0 && s->internal->packet_buffer)
  652. update_initial_durations(s, st, pkt->stream_index,
  653. duration);
  654. }
  655. }
  656. if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
  657. duration) {
  658. /* presentation is not delayed : PTS and DTS are the same */
  659. if (pkt->pts == AV_NOPTS_VALUE)
  660. pkt->pts = pkt->dts;
  661. update_initial_timestamps(s, pkt->stream_index, pkt->pts,
  662. pkt->pts);
  663. if (pkt->pts == AV_NOPTS_VALUE)
  664. pkt->pts = st->cur_dts;
  665. pkt->dts = pkt->pts;
  666. if (pkt->pts != AV_NOPTS_VALUE)
  667. st->cur_dts = pkt->pts + duration;
  668. }
  669. }
  670. }
  671. if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  672. st->pts_buffer[0] = pkt->pts;
  673. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  674. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  675. if (pkt->dts == AV_NOPTS_VALUE)
  676. pkt->dts = st->pts_buffer[0];
  677. // We skipped it above so we try here.
  678. if (st->codecpar->codec_id == AV_CODEC_ID_H264)
  679. // This should happen on the first packet
  680. update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
  681. if (pkt->dts > st->cur_dts)
  682. st->cur_dts = pkt->dts;
  683. }
  684. av_log(NULL, AV_LOG_TRACE,
  685. "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
  686. presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
  687. /* update flags */
  688. if (is_intra_only(st->codecpar->codec_id))
  689. pkt->flags |= AV_PKT_FLAG_KEY;
  690. #if FF_API_CONVERGENCE_DURATION
  691. FF_DISABLE_DEPRECATION_WARNINGS
  692. if (pc)
  693. pkt->convergence_duration = pc->convergence_duration;
  694. FF_ENABLE_DEPRECATION_WARNINGS
  695. #endif
  696. }
  697. static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
  698. {
  699. while (*pkt_buf) {
  700. AVPacketList *pktl = *pkt_buf;
  701. *pkt_buf = pktl->next;
  702. av_packet_unref(&pktl->pkt);
  703. av_freep(&pktl);
  704. }
  705. *pkt_buf_end = NULL;
  706. }
  707. /**
  708. * Parse a packet, add all split parts to parse_queue.
  709. *
  710. * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
  711. */
  712. static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
  713. {
  714. AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
  715. AVStream *st = s->streams[stream_index];
  716. uint8_t *data = pkt ? pkt->data : NULL;
  717. int size = pkt ? pkt->size : 0;
  718. int ret = 0, got_output = 0;
  719. if (!pkt) {
  720. av_init_packet(&flush_pkt);
  721. pkt = &flush_pkt;
  722. got_output = 1;
  723. }
  724. while (size > 0 || (pkt == &flush_pkt && got_output)) {
  725. int len;
  726. av_init_packet(&out_pkt);
  727. len = av_parser_parse2(st->parser, st->internal->avctx,
  728. &out_pkt.data, &out_pkt.size, data, size,
  729. pkt->pts, pkt->dts, pkt->pos);
  730. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
  731. /* increment read pointer */
  732. data += len;
  733. size -= len;
  734. got_output = !!out_pkt.size;
  735. if (!out_pkt.size)
  736. continue;
  737. if (pkt->side_data) {
  738. out_pkt.side_data = pkt->side_data;
  739. out_pkt.side_data_elems = pkt->side_data_elems;
  740. pkt->side_data = NULL;
  741. pkt->side_data_elems = 0;
  742. }
  743. /* set the duration */
  744. out_pkt.duration = 0;
  745. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  746. if (st->internal->avctx->sample_rate > 0) {
  747. out_pkt.duration =
  748. av_rescale_q_rnd(st->parser->duration,
  749. (AVRational) { 1, st->internal->avctx->sample_rate },
  750. st->time_base,
  751. AV_ROUND_DOWN);
  752. }
  753. }
  754. out_pkt.stream_index = st->index;
  755. out_pkt.pts = st->parser->pts;
  756. out_pkt.dts = st->parser->dts;
  757. out_pkt.pos = st->parser->pos;
  758. if (st->parser->key_frame == 1 ||
  759. (st->parser->key_frame == -1 &&
  760. st->parser->pict_type == AV_PICTURE_TYPE_I))
  761. out_pkt.flags |= AV_PKT_FLAG_KEY;
  762. compute_pkt_fields(s, st, st->parser, &out_pkt);
  763. if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
  764. out_pkt.flags & AV_PKT_FLAG_KEY) {
  765. ff_reduce_index(s, st->index);
  766. av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
  767. 0, 0, AVINDEX_KEYFRAME);
  768. }
  769. if ((ret = add_to_pktbuf(&s->internal->parse_queue, &out_pkt,
  770. &s->internal->parse_queue_end,
  771. 1))) {
  772. av_packet_unref(&out_pkt);
  773. goto fail;
  774. }
  775. }
  776. /* end of the stream => close and free the parser */
  777. if (pkt == &flush_pkt) {
  778. av_parser_close(st->parser);
  779. st->parser = NULL;
  780. }
  781. fail:
  782. av_packet_unref(pkt);
  783. return ret;
  784. }
  785. static int read_from_packet_buffer(AVPacketList **pkt_buffer,
  786. AVPacketList **pkt_buffer_end,
  787. AVPacket *pkt)
  788. {
  789. AVPacketList *pktl;
  790. av_assert0(*pkt_buffer);
  791. pktl = *pkt_buffer;
  792. *pkt = pktl->pkt;
  793. *pkt_buffer = pktl->next;
  794. if (!pktl->next)
  795. *pkt_buffer_end = NULL;
  796. av_freep(&pktl);
  797. return 0;
  798. }
  799. static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
  800. {
  801. int ret = 0, i, got_packet = 0;
  802. AVDictionary *metadata = NULL;
  803. av_init_packet(pkt);
  804. while (!got_packet && !s->internal->parse_queue) {
  805. AVStream *st;
  806. AVPacket cur_pkt;
  807. /* read next packet */
  808. ret = ff_read_packet(s, &cur_pkt);
  809. if (ret < 0) {
  810. if (ret == AVERROR(EAGAIN))
  811. return ret;
  812. /* flush the parsers */
  813. for (i = 0; i < s->nb_streams; i++) {
  814. st = s->streams[i];
  815. if (st->parser && st->need_parsing)
  816. parse_packet(s, NULL, st->index);
  817. }
  818. /* all remaining packets are now in parse_queue =>
  819. * really terminate parsing */
  820. break;
  821. }
  822. ret = 0;
  823. st = s->streams[cur_pkt.stream_index];
  824. if (cur_pkt.pts != AV_NOPTS_VALUE &&
  825. cur_pkt.dts != AV_NOPTS_VALUE &&
  826. cur_pkt.pts < cur_pkt.dts) {
  827. av_log(s, AV_LOG_WARNING,
  828. "Invalid timestamps stream=%d, pts=%"PRId64", "
  829. "dts=%"PRId64", size=%d\n",
  830. cur_pkt.stream_index, cur_pkt.pts,
  831. cur_pkt.dts, cur_pkt.size);
  832. }
  833. if (s->debug & FF_FDEBUG_TS)
  834. av_log(s, AV_LOG_DEBUG,
  835. "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", "
  836. "size=%d, duration=%"PRId64", flags=%d\n",
  837. cur_pkt.stream_index, cur_pkt.pts, cur_pkt.dts,
  838. cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
  839. if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
  840. st->parser = av_parser_init(st->codecpar->codec_id);
  841. if (!st->parser)
  842. /* no parser available: just output the raw packets */
  843. st->need_parsing = AVSTREAM_PARSE_NONE;
  844. else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
  845. st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
  846. else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
  847. st->parser->flags |= PARSER_FLAG_ONCE;
  848. }
  849. if (!st->need_parsing || !st->parser) {
  850. /* no parsing needed: we just output the packet as is */
  851. *pkt = cur_pkt;
  852. compute_pkt_fields(s, st, NULL, pkt);
  853. if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
  854. (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
  855. ff_reduce_index(s, st->index);
  856. av_add_index_entry(st, pkt->pos, pkt->dts,
  857. 0, 0, AVINDEX_KEYFRAME);
  858. }
  859. got_packet = 1;
  860. } else if (st->discard < AVDISCARD_ALL) {
  861. if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
  862. return ret;
  863. } else {
  864. /* free packet */
  865. av_packet_unref(&cur_pkt);
  866. }
  867. }
  868. if (!got_packet && s->internal->parse_queue)
  869. ret = read_from_packet_buffer(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
  870. av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
  871. if (metadata) {
  872. s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  873. av_dict_copy(&s->metadata, metadata, 0);
  874. av_dict_free(&metadata);
  875. av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
  876. }
  877. #if FF_API_LAVF_AVCTX
  878. update_stream_avctx(s);
  879. #endif
  880. if (s->debug & FF_FDEBUG_TS)
  881. av_log(s, AV_LOG_DEBUG,
  882. "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", "
  883. "size=%d, duration=%"PRId64", flags=%d\n",
  884. pkt->stream_index, pkt->pts, pkt->dts,
  885. pkt->size, pkt->duration, pkt->flags);
  886. return ret;
  887. }
  888. int av_read_frame(AVFormatContext *s, AVPacket *pkt)
  889. {
  890. const int genpts = s->flags & AVFMT_FLAG_GENPTS;
  891. int eof = 0;
  892. if (!genpts)
  893. return s->internal->packet_buffer
  894. ? read_from_packet_buffer(&s->internal->packet_buffer,
  895. &s->internal->packet_buffer_end, pkt)
  896. : read_frame_internal(s, pkt);
  897. for (;;) {
  898. int ret;
  899. AVPacketList *pktl = s->internal->packet_buffer;
  900. if (pktl) {
  901. AVPacket *next_pkt = &pktl->pkt;
  902. if (next_pkt->dts != AV_NOPTS_VALUE) {
  903. int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
  904. while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
  905. if (pktl->pkt.stream_index == next_pkt->stream_index &&
  906. (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
  907. av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {
  908. // not B-frame
  909. next_pkt->pts = pktl->pkt.dts;
  910. }
  911. pktl = pktl->next;
  912. }
  913. pktl = s->internal->packet_buffer;
  914. }
  915. /* read packet from packet buffer, if there is data */
  916. if (!(next_pkt->pts == AV_NOPTS_VALUE &&
  917. next_pkt->dts != AV_NOPTS_VALUE && !eof))
  918. return read_from_packet_buffer(&s->internal->packet_buffer,
  919. &s->internal->packet_buffer_end, pkt);
  920. }
  921. ret = read_frame_internal(s, pkt);
  922. if (ret < 0) {
  923. if (pktl && ret != AVERROR(EAGAIN)) {
  924. eof = 1;
  925. continue;
  926. } else
  927. return ret;
  928. }
  929. ret = add_to_pktbuf(&s->internal->packet_buffer, pkt,
  930. &s->internal->packet_buffer_end, 1);
  931. if (ret < 0)
  932. return ret;
  933. }
  934. }
  935. /* XXX: suppress the packet queue */
  936. static void flush_packet_queue(AVFormatContext *s)
  937. {
  938. free_packet_buffer(&s->internal->parse_queue, &s->internal->parse_queue_end);
  939. free_packet_buffer(&s->internal->packet_buffer, &s->internal->packet_buffer_end);
  940. free_packet_buffer(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
  941. s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
  942. }
  943. /*******************************************************/
  944. /* seek support */
  945. int av_find_default_stream_index(AVFormatContext *s)
  946. {
  947. int first_audio_index = -1;
  948. int i;
  949. AVStream *st;
  950. if (s->nb_streams <= 0)
  951. return -1;
  952. for (i = 0; i < s->nb_streams; i++) {
  953. st = s->streams[i];
  954. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  955. !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
  956. return i;
  957. }
  958. if (first_audio_index < 0 &&
  959. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  960. first_audio_index = i;
  961. }
  962. return first_audio_index >= 0 ? first_audio_index : 0;
  963. }
  964. /** Flush the frame reader. */
  965. void ff_read_frame_flush(AVFormatContext *s)
  966. {
  967. AVStream *st;
  968. int i, j;
  969. flush_packet_queue(s);
  970. /* Reset read state for each stream. */
  971. for (i = 0; i < s->nb_streams; i++) {
  972. st = s->streams[i];
  973. if (st->parser) {
  974. av_parser_close(st->parser);
  975. st->parser = NULL;
  976. }
  977. st->last_IP_pts = AV_NOPTS_VALUE;
  978. /* We set the current DTS to an unspecified origin. */
  979. st->cur_dts = AV_NOPTS_VALUE;
  980. st->probe_packets = MAX_PROBE_PACKETS;
  981. for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
  982. st->pts_buffer[j] = AV_NOPTS_VALUE;
  983. }
  984. }
  985. void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
  986. {
  987. int i;
  988. for (i = 0; i < s->nb_streams; i++) {
  989. AVStream *st = s->streams[i];
  990. st->cur_dts =
  991. av_rescale(timestamp,
  992. st->time_base.den * (int64_t) ref_st->time_base.num,
  993. st->time_base.num * (int64_t) ref_st->time_base.den);
  994. }
  995. }
  996. void ff_reduce_index(AVFormatContext *s, int stream_index)
  997. {
  998. AVStream *st = s->streams[stream_index];
  999. unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
  1000. if ((unsigned) st->nb_index_entries >= max_entries) {
  1001. int i;
  1002. for (i = 0; 2 * i < st->nb_index_entries; i++)
  1003. st->index_entries[i] = st->index_entries[2 * i];
  1004. st->nb_index_entries = i;
  1005. }
  1006. }
  1007. int ff_add_index_entry(AVIndexEntry **index_entries,
  1008. int *nb_index_entries,
  1009. unsigned int *index_entries_allocated_size,
  1010. int64_t pos, int64_t timestamp,
  1011. int size, int distance, int flags)
  1012. {
  1013. AVIndexEntry *entries, *ie;
  1014. int index;
  1015. if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
  1016. return -1;
  1017. entries = av_fast_realloc(*index_entries,
  1018. index_entries_allocated_size,
  1019. (*nb_index_entries + 1) *
  1020. sizeof(AVIndexEntry));
  1021. if (!entries)
  1022. return -1;
  1023. *index_entries = entries;
  1024. index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
  1025. timestamp, AVSEEK_FLAG_ANY);
  1026. if (index < 0) {
  1027. index = (*nb_index_entries)++;
  1028. ie = &entries[index];
  1029. assert(index == 0 || ie[-1].timestamp < timestamp);
  1030. } else {
  1031. ie = &entries[index];
  1032. if (ie->timestamp != timestamp) {
  1033. if (ie->timestamp <= timestamp)
  1034. return -1;
  1035. memmove(entries + index + 1, entries + index,
  1036. sizeof(AVIndexEntry) * (*nb_index_entries - index));
  1037. (*nb_index_entries)++;
  1038. } else if (ie->pos == pos && distance < ie->min_distance)
  1039. // do not reduce the distance
  1040. distance = ie->min_distance;
  1041. }
  1042. ie->pos = pos;
  1043. ie->timestamp = timestamp;
  1044. ie->min_distance = distance;
  1045. ie->size = size;
  1046. ie->flags = flags;
  1047. return index;
  1048. }
  1049. int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
  1050. int size, int distance, int flags)
  1051. {
  1052. return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
  1053. &st->index_entries_allocated_size, pos,
  1054. timestamp, size, distance, flags);
  1055. }
  1056. int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
  1057. int64_t wanted_timestamp, int flags)
  1058. {
  1059. int a, b, m;
  1060. int64_t timestamp;
  1061. a = -1;
  1062. b = nb_entries;
  1063. // Optimize appending index entries at the end.
  1064. if (b && entries[b - 1].timestamp < wanted_timestamp)
  1065. a = b - 1;
  1066. while (b - a > 1) {
  1067. m = (a + b) >> 1;
  1068. timestamp = entries[m].timestamp;
  1069. if (timestamp >= wanted_timestamp)
  1070. b = m;
  1071. if (timestamp <= wanted_timestamp)
  1072. a = m;
  1073. }
  1074. m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
  1075. if (!(flags & AVSEEK_FLAG_ANY))
  1076. while (m >= 0 && m < nb_entries &&
  1077. !(entries[m].flags & AVINDEX_KEYFRAME))
  1078. m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
  1079. if (m == nb_entries)
  1080. return -1;
  1081. return m;
  1082. }
  1083. int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
  1084. {
  1085. return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
  1086. wanted_timestamp, flags);
  1087. }
  1088. int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
  1089. int64_t target_ts, int flags)
  1090. {
  1091. AVInputFormat *avif = s->iformat;
  1092. int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
  1093. int64_t ts_min, ts_max, ts;
  1094. int index;
  1095. int64_t ret;
  1096. AVStream *st;
  1097. if (stream_index < 0)
  1098. return -1;
  1099. av_log(s, AV_LOG_TRACE, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
  1100. ts_max =
  1101. ts_min = AV_NOPTS_VALUE;
  1102. pos_limit = -1; // GCC falsely says it may be uninitialized.
  1103. st = s->streams[stream_index];
  1104. if (st->index_entries) {
  1105. AVIndexEntry *e;
  1106. /* FIXME: Whole function must be checked for non-keyframe entries in
  1107. * index case, especially read_timestamp(). */
  1108. index = av_index_search_timestamp(st, target_ts,
  1109. flags | AVSEEK_FLAG_BACKWARD);
  1110. index = FFMAX(index, 0);
  1111. e = &st->index_entries[index];
  1112. if (e->timestamp <= target_ts || e->pos == e->min_distance) {
  1113. pos_min = e->pos;
  1114. ts_min = e->timestamp;
  1115. av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
  1116. pos_min, ts_min);
  1117. } else {
  1118. assert(index == 0);
  1119. }
  1120. index = av_index_search_timestamp(st, target_ts,
  1121. flags & ~AVSEEK_FLAG_BACKWARD);
  1122. assert(index < st->nb_index_entries);
  1123. if (index >= 0) {
  1124. e = &st->index_entries[index];
  1125. assert(e->timestamp >= target_ts);
  1126. pos_max = e->pos;
  1127. ts_max = e->timestamp;
  1128. pos_limit = pos_max - e->min_distance;
  1129. av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
  1130. " dts_max=%"PRId64"\n", pos_max, pos_limit, ts_max);
  1131. }
  1132. }
  1133. pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
  1134. ts_min, ts_max, flags, &ts, avif->read_timestamp);
  1135. if (pos < 0)
  1136. return -1;
  1137. /* do the seek */
  1138. if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
  1139. return ret;
  1140. ff_update_cur_dts(s, st, ts);
  1141. return 0;
  1142. }
  1143. int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
  1144. int64_t pos_min, int64_t pos_max, int64_t pos_limit,
  1145. int64_t ts_min, int64_t ts_max,
  1146. int flags, int64_t *ts_ret,
  1147. int64_t (*read_timestamp)(struct AVFormatContext *, int,
  1148. int64_t *, int64_t))
  1149. {
  1150. int64_t pos, ts;
  1151. int64_t start_pos, filesize;
  1152. int no_change;
  1153. av_log(s, AV_LOG_TRACE, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
  1154. if (ts_min == AV_NOPTS_VALUE) {
  1155. pos_min = s->internal->data_offset;
  1156. ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1157. if (ts_min == AV_NOPTS_VALUE)
  1158. return -1;
  1159. }
  1160. if (ts_max == AV_NOPTS_VALUE) {
  1161. int step = 1024;
  1162. filesize = avio_size(s->pb);
  1163. pos_max = filesize - 1;
  1164. do {
  1165. pos_max -= step;
  1166. ts_max = read_timestamp(s, stream_index, &pos_max,
  1167. pos_max + step);
  1168. step += step;
  1169. } while (ts_max == AV_NOPTS_VALUE && pos_max >= step);
  1170. if (ts_max == AV_NOPTS_VALUE)
  1171. return -1;
  1172. for (;;) {
  1173. int64_t tmp_pos = pos_max + 1;
  1174. int64_t tmp_ts = read_timestamp(s, stream_index,
  1175. &tmp_pos, INT64_MAX);
  1176. if (tmp_ts == AV_NOPTS_VALUE)
  1177. break;
  1178. ts_max = tmp_ts;
  1179. pos_max = tmp_pos;
  1180. if (tmp_pos >= filesize)
  1181. break;
  1182. }
  1183. pos_limit = pos_max;
  1184. }
  1185. if (ts_min > ts_max)
  1186. return -1;
  1187. else if (ts_min == ts_max)
  1188. pos_limit = pos_min;
  1189. no_change = 0;
  1190. while (pos_min < pos_limit) {
  1191. av_log(s, AV_LOG_TRACE, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64
  1192. " dts_max=%"PRId64"\n", pos_min, pos_max, ts_min, ts_max);
  1193. assert(pos_limit <= pos_max);
  1194. if (no_change == 0) {
  1195. int64_t approximate_keyframe_distance = pos_max - pos_limit;
  1196. // interpolate position (better than dichotomy)
  1197. pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
  1198. ts_max - ts_min) +
  1199. pos_min - approximate_keyframe_distance;
  1200. } else if (no_change == 1) {
  1201. // bisection if interpolation did not change min / max pos last time
  1202. pos = (pos_min + pos_limit) >> 1;
  1203. } else {
  1204. /* linear search if bisection failed, can only happen if there
  1205. * are very few or no keyframes between min/max */
  1206. pos = pos_min;
  1207. }
  1208. if (pos <= pos_min)
  1209. pos = pos_min + 1;
  1210. else if (pos > pos_limit)
  1211. pos = pos_limit;
  1212. start_pos = pos;
  1213. // May pass pos_limit instead of -1.
  1214. ts = read_timestamp(s, stream_index, &pos, INT64_MAX);
  1215. if (pos == pos_max)
  1216. no_change++;
  1217. else
  1218. no_change = 0;
  1219. av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64
  1220. " target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
  1221. pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
  1222. pos_limit, start_pos, no_change);
  1223. if (ts == AV_NOPTS_VALUE) {
  1224. av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
  1225. return -1;
  1226. }
  1227. assert(ts != AV_NOPTS_VALUE);
  1228. if (target_ts <= ts) {
  1229. pos_limit = start_pos - 1;
  1230. pos_max = pos;
  1231. ts_max = ts;
  1232. }
  1233. if (target_ts >= ts) {
  1234. pos_min = pos;
  1235. ts_min = ts;
  1236. }
  1237. }
  1238. pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
  1239. ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
  1240. pos_min = pos;
  1241. ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1242. pos_min++;
  1243. ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1244. av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
  1245. pos, ts_min, target_ts, ts_max);
  1246. *ts_ret = ts;
  1247. return pos;
  1248. }
  1249. static int seek_frame_byte(AVFormatContext *s, int stream_index,
  1250. int64_t pos, int flags)
  1251. {
  1252. int64_t pos_min, pos_max;
  1253. pos_min = s->internal->data_offset;
  1254. pos_max = avio_size(s->pb) - 1;
  1255. if (pos < pos_min)
  1256. pos = pos_min;
  1257. else if (pos > pos_max)
  1258. pos = pos_max;
  1259. avio_seek(s->pb, pos, SEEK_SET);
  1260. return 0;
  1261. }
  1262. static int seek_frame_generic(AVFormatContext *s, int stream_index,
  1263. int64_t timestamp, int flags)
  1264. {
  1265. int index;
  1266. int64_t ret;
  1267. AVStream *st;
  1268. AVIndexEntry *ie;
  1269. st = s->streams[stream_index];
  1270. index = av_index_search_timestamp(st, timestamp, flags);
  1271. if (index < 0 && st->nb_index_entries &&
  1272. timestamp < st->index_entries[0].timestamp)
  1273. return -1;
  1274. if (index < 0 || index == st->nb_index_entries - 1) {
  1275. AVPacket pkt;
  1276. if (st->nb_index_entries) {
  1277. assert(st->index_entries);
  1278. ie = &st->index_entries[st->nb_index_entries - 1];
  1279. if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
  1280. return ret;
  1281. ff_update_cur_dts(s, st, ie->timestamp);
  1282. } else {
  1283. if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
  1284. return ret;
  1285. }
  1286. for (;;) {
  1287. int read_status;
  1288. do {
  1289. read_status = av_read_frame(s, &pkt);
  1290. } while (read_status == AVERROR(EAGAIN));
  1291. if (read_status < 0)
  1292. break;
  1293. av_packet_unref(&pkt);
  1294. if (stream_index == pkt.stream_index)
  1295. if ((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
  1296. break;
  1297. }
  1298. index = av_index_search_timestamp(st, timestamp, flags);
  1299. }
  1300. if (index < 0)
  1301. return -1;
  1302. ff_read_frame_flush(s);
  1303. if (s->iformat->read_seek)
  1304. if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
  1305. return 0;
  1306. ie = &st->index_entries[index];
  1307. if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
  1308. return ret;
  1309. ff_update_cur_dts(s, st, ie->timestamp);
  1310. return 0;
  1311. }
  1312. static int seek_frame_internal(AVFormatContext *s, int stream_index,
  1313. int64_t timestamp, int flags)
  1314. {
  1315. int ret;
  1316. AVStream *st;
  1317. if (flags & AVSEEK_FLAG_BYTE) {
  1318. if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
  1319. return -1;
  1320. ff_read_frame_flush(s);
  1321. return seek_frame_byte(s, stream_index, timestamp, flags);
  1322. }
  1323. if (stream_index < 0) {
  1324. stream_index = av_find_default_stream_index(s);
  1325. if (stream_index < 0)
  1326. return -1;
  1327. st = s->streams[stream_index];
  1328. /* timestamp for default must be expressed in AV_TIME_BASE units */
  1329. timestamp = av_rescale(timestamp, st->time_base.den,
  1330. AV_TIME_BASE * (int64_t) st->time_base.num);
  1331. }
  1332. /* first, we try the format specific seek */
  1333. if (s->iformat->read_seek) {
  1334. ff_read_frame_flush(s);
  1335. ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
  1336. } else
  1337. ret = -1;
  1338. if (ret >= 0)
  1339. return 0;
  1340. if (s->iformat->read_timestamp &&
  1341. !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
  1342. ff_read_frame_flush(s);
  1343. return ff_seek_frame_binary(s, stream_index, timestamp, flags);
  1344. } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
  1345. ff_read_frame_flush(s);
  1346. return seek_frame_generic(s, stream_index, timestamp, flags);
  1347. } else
  1348. return -1;
  1349. }
  1350. int av_seek_frame(AVFormatContext *s, int stream_index,
  1351. int64_t timestamp, int flags)
  1352. {
  1353. int ret = seek_frame_internal(s, stream_index, timestamp, flags);
  1354. if (ret >= 0)
  1355. ret = queue_attached_pictures(s);
  1356. return ret;
  1357. }
  1358. int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
  1359. int64_t ts, int64_t max_ts, int flags)
  1360. {
  1361. if (min_ts > ts || max_ts < ts)
  1362. return -1;
  1363. if (s->iformat->read_seek2) {
  1364. int ret;
  1365. ff_read_frame_flush(s);
  1366. ret = s->iformat->read_seek2(s, stream_index, min_ts,
  1367. ts, max_ts, flags);
  1368. if (ret >= 0)
  1369. ret = queue_attached_pictures(s);
  1370. return ret;
  1371. }
  1372. if (s->iformat->read_timestamp) {
  1373. // try to seek via read_timestamp()
  1374. }
  1375. // Fall back on old API if new is not implemented but old is.
  1376. // Note the old API has somewhat different semantics.
  1377. if (s->iformat->read_seek || 1)
  1378. return av_seek_frame(s, stream_index, ts,
  1379. flags | ((uint64_t) ts - min_ts >
  1380. (uint64_t) max_ts - ts
  1381. ? AVSEEK_FLAG_BACKWARD : 0));
  1382. // try some generic seek like seek_frame_generic() but with new ts semantics
  1383. }
  1384. /*******************************************************/
  1385. /**
  1386. * Return TRUE if the stream has accurate duration in any stream.
  1387. *
  1388. * @return TRUE if the stream has accurate duration for at least one component.
  1389. */
  1390. static int has_duration(AVFormatContext *ic)
  1391. {
  1392. int i;
  1393. AVStream *st;
  1394. for (i = 0; i < ic->nb_streams; i++) {
  1395. st = ic->streams[i];
  1396. if (st->duration != AV_NOPTS_VALUE)
  1397. return 1;
  1398. }
  1399. if (ic->duration != AV_NOPTS_VALUE)
  1400. return 1;
  1401. return 0;
  1402. }
  1403. /**
  1404. * Estimate the stream timings from the one of each components.
  1405. *
  1406. * Also computes the global bitrate if possible.
  1407. */
  1408. static void update_stream_timings(AVFormatContext *ic)
  1409. {
  1410. int64_t start_time, start_time1, end_time, end_time1;
  1411. int64_t duration, duration1, filesize;
  1412. int i;
  1413. AVStream *st;
  1414. start_time = INT64_MAX;
  1415. end_time = INT64_MIN;
  1416. duration = INT64_MIN;
  1417. for (i = 0; i < ic->nb_streams; i++) {
  1418. st = ic->streams[i];
  1419. if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
  1420. start_time1 = av_rescale_q(st->start_time, st->time_base,
  1421. AV_TIME_BASE_Q);
  1422. start_time = FFMIN(start_time, start_time1);
  1423. if (st->duration != AV_NOPTS_VALUE) {
  1424. end_time1 = start_time1 +
  1425. av_rescale_q(st->duration, st->time_base,
  1426. AV_TIME_BASE_Q);
  1427. end_time = FFMAX(end_time, end_time1);
  1428. }
  1429. }
  1430. if (st->duration != AV_NOPTS_VALUE) {
  1431. duration1 = av_rescale_q(st->duration, st->time_base,
  1432. AV_TIME_BASE_Q);
  1433. duration = FFMAX(duration, duration1);
  1434. }
  1435. }
  1436. if (start_time != INT64_MAX) {
  1437. ic->start_time = start_time;
  1438. if (end_time != INT64_MIN)
  1439. duration = FFMAX(duration, end_time - start_time);
  1440. }
  1441. if (duration != INT64_MIN) {
  1442. ic->duration = duration;
  1443. if (ic->pb && (filesize = avio_size(ic->pb)) > 0)
  1444. /* compute the bitrate */
  1445. ic->bit_rate = (double) filesize * 8.0 * AV_TIME_BASE /
  1446. (double) ic->duration;
  1447. }
  1448. }
  1449. static void fill_all_stream_timings(AVFormatContext *ic)
  1450. {
  1451. int i;
  1452. AVStream *st;
  1453. update_stream_timings(ic);
  1454. for (i = 0; i < ic->nb_streams; i++) {
  1455. st = ic->streams[i];
  1456. if (st->start_time == AV_NOPTS_VALUE) {
  1457. if (ic->start_time != AV_NOPTS_VALUE)
  1458. st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
  1459. st->time_base);
  1460. if (ic->duration != AV_NOPTS_VALUE)
  1461. st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
  1462. st->time_base);
  1463. }
  1464. }
  1465. }
  1466. static void estimate_timings_from_bit_rate(AVFormatContext *ic)
  1467. {
  1468. int64_t filesize, duration;
  1469. int i;
  1470. AVStream *st;
  1471. /* if bit_rate is already set, we believe it */
  1472. if (ic->bit_rate <= 0) {
  1473. int bit_rate = 0;
  1474. for (i = 0; i < ic->nb_streams; i++) {
  1475. st = ic->streams[i];
  1476. if (st->codecpar->bit_rate > 0) {
  1477. if (INT_MAX - st->codecpar->bit_rate < bit_rate) {
  1478. bit_rate = 0;
  1479. break;
  1480. }
  1481. bit_rate += st->codecpar->bit_rate;
  1482. }
  1483. }
  1484. ic->bit_rate = bit_rate;
  1485. }
  1486. /* if duration is already set, we believe it */
  1487. if (ic->duration == AV_NOPTS_VALUE &&
  1488. ic->bit_rate != 0) {
  1489. filesize = ic->pb ? avio_size(ic->pb) : 0;
  1490. if (filesize > 0) {
  1491. for (i = 0; i < ic->nb_streams; i++) {
  1492. st = ic->streams[i];
  1493. duration = av_rescale(8 * filesize, st->time_base.den,
  1494. ic->bit_rate *
  1495. (int64_t) st->time_base.num);
  1496. if (st->duration == AV_NOPTS_VALUE)
  1497. st->duration = duration;
  1498. }
  1499. }
  1500. }
  1501. }
  1502. #define DURATION_MAX_READ_SIZE 250000
  1503. #define DURATION_MAX_RETRY 3
  1504. /* only usable for MPEG-PS streams */
  1505. static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
  1506. {
  1507. AVPacket pkt1, *pkt = &pkt1;
  1508. AVStream *st;
  1509. int read_size, i, ret;
  1510. int64_t end_time;
  1511. int64_t filesize, offset, duration;
  1512. int retry = 0;
  1513. /* flush packet queue */
  1514. flush_packet_queue(ic);
  1515. for (i = 0; i < ic->nb_streams; i++) {
  1516. st = ic->streams[i];
  1517. if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
  1518. av_log(ic, AV_LOG_WARNING,
  1519. "start time is not set in estimate_timings_from_pts\n");
  1520. if (st->parser) {
  1521. av_parser_close(st->parser);
  1522. st->parser = NULL;
  1523. }
  1524. }
  1525. /* estimate the end time (duration) */
  1526. /* XXX: may need to support wrapping */
  1527. filesize = ic->pb ? avio_size(ic->pb) : 0;
  1528. end_time = AV_NOPTS_VALUE;
  1529. do {
  1530. offset = filesize - (DURATION_MAX_READ_SIZE << retry);
  1531. if (offset < 0)
  1532. offset = 0;
  1533. avio_seek(ic->pb, offset, SEEK_SET);
  1534. read_size = 0;
  1535. for (;;) {
  1536. if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
  1537. break;
  1538. do {
  1539. ret = ff_read_packet(ic, pkt);
  1540. } while (ret == AVERROR(EAGAIN));
  1541. if (ret != 0)
  1542. break;
  1543. read_size += pkt->size;
  1544. st = ic->streams[pkt->stream_index];
  1545. if (pkt->pts != AV_NOPTS_VALUE &&
  1546. (st->start_time != AV_NOPTS_VALUE ||
  1547. st->first_dts != AV_NOPTS_VALUE)) {
  1548. duration = end_time = pkt->pts;
  1549. if (st->start_time != AV_NOPTS_VALUE)
  1550. duration -= st->start_time;
  1551. else
  1552. duration -= st->first_dts;
  1553. if (duration < 0)
  1554. duration += 1LL << st->pts_wrap_bits;
  1555. if (duration > 0) {
  1556. if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
  1557. st->duration = duration;
  1558. }
  1559. }
  1560. av_packet_unref(pkt);
  1561. }
  1562. } while (end_time == AV_NOPTS_VALUE &&
  1563. filesize > (DURATION_MAX_READ_SIZE << retry) &&
  1564. ++retry <= DURATION_MAX_RETRY);
  1565. fill_all_stream_timings(ic);
  1566. avio_seek(ic->pb, old_offset, SEEK_SET);
  1567. for (i = 0; i < ic->nb_streams; i++) {
  1568. st = ic->streams[i];
  1569. st->cur_dts = st->first_dts;
  1570. st->last_IP_pts = AV_NOPTS_VALUE;
  1571. }
  1572. }
  1573. static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
  1574. {
  1575. int64_t file_size;
  1576. /* get the file size, if possible */
  1577. if (ic->iformat->flags & AVFMT_NOFILE) {
  1578. file_size = 0;
  1579. } else {
  1580. file_size = avio_size(ic->pb);
  1581. file_size = FFMAX(0, file_size);
  1582. }
  1583. if ((!strcmp(ic->iformat->name, "mpeg") ||
  1584. !strcmp(ic->iformat->name, "mpegts")) &&
  1585. file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
  1586. /* get accurate estimate from the PTSes */
  1587. estimate_timings_from_pts(ic, old_offset);
  1588. } else if (has_duration(ic)) {
  1589. /* at least one component has timings - we use them for all
  1590. * the components */
  1591. fill_all_stream_timings(ic);
  1592. } else {
  1593. av_log(ic, AV_LOG_WARNING,
  1594. "Estimating duration from bitrate, this may be inaccurate\n");
  1595. /* less precise: use bitrate info */
  1596. estimate_timings_from_bit_rate(ic);
  1597. }
  1598. update_stream_timings(ic);
  1599. {
  1600. int i;
  1601. AVStream av_unused *st;
  1602. for (i = 0; i < ic->nb_streams; i++) {
  1603. st = ic->streams[i];
  1604. av_log(ic, AV_LOG_TRACE, "%d: start_time: %0.3f duration: %0.3f\n", i,
  1605. (double) st->start_time / AV_TIME_BASE,
  1606. (double) st->duration / AV_TIME_BASE);
  1607. }
  1608. av_log(ic, AV_LOG_TRACE,
  1609. "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
  1610. (double) ic->start_time / AV_TIME_BASE,
  1611. (double) ic->duration / AV_TIME_BASE,
  1612. ic->bit_rate / 1000);
  1613. }
  1614. }
  1615. static int has_codec_parameters(AVStream *st)
  1616. {
  1617. AVCodecContext *avctx = st->internal->avctx;
  1618. int val;
  1619. switch (avctx->codec_type) {
  1620. case AVMEDIA_TYPE_AUDIO:
  1621. val = avctx->sample_rate && avctx->channels;
  1622. if (st->info->found_decoder >= 0 &&
  1623. avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
  1624. return 0;
  1625. break;
  1626. case AVMEDIA_TYPE_VIDEO:
  1627. val = avctx->width;
  1628. if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
  1629. return 0;
  1630. break;
  1631. default:
  1632. val = 1;
  1633. break;
  1634. }
  1635. return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
  1636. }
  1637. static int has_decode_delay_been_guessed(AVStream *st)
  1638. {
  1639. return st->internal->avctx->codec_id != AV_CODEC_ID_H264 ||
  1640. st->info->nb_decoded_frames >= 6;
  1641. }
  1642. /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
  1643. static int try_decode_frame(AVFormatContext *s, AVStream *st, AVPacket *avpkt,
  1644. AVDictionary **options)
  1645. {
  1646. AVCodecContext *avctx = st->internal->avctx;
  1647. const AVCodec *codec;
  1648. int got_picture = 1, ret = 0;
  1649. AVFrame *frame = av_frame_alloc();
  1650. AVPacket pkt = *avpkt;
  1651. if (!frame)
  1652. return AVERROR(ENOMEM);
  1653. if (!avcodec_is_open(avctx) && !st->info->found_decoder) {
  1654. AVDictionary *thread_opt = NULL;
  1655. #if FF_API_LAVF_AVCTX
  1656. FF_DISABLE_DEPRECATION_WARNINGS
  1657. codec = st->codec->codec ? st->codec->codec
  1658. : avcodec_find_decoder(st->codecpar->codec_id);
  1659. FF_ENABLE_DEPRECATION_WARNINGS
  1660. #else
  1661. codec = avcodec_find_decoder(st->codecpar->codec_id);
  1662. #endif
  1663. if (!codec) {
  1664. st->info->found_decoder = -1;
  1665. ret = -1;
  1666. goto fail;
  1667. }
  1668. /* Force thread count to 1 since the H.264 decoder will not extract
  1669. * SPS and PPS to extradata during multi-threaded decoding. */
  1670. av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
  1671. ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
  1672. if (!options)
  1673. av_dict_free(&thread_opt);
  1674. if (ret < 0) {
  1675. st->info->found_decoder = -1;
  1676. goto fail;
  1677. }
  1678. st->info->found_decoder = 1;
  1679. } else if (!st->info->found_decoder)
  1680. st->info->found_decoder = 1;
  1681. if (st->info->found_decoder < 0) {
  1682. ret = -1;
  1683. goto fail;
  1684. }
  1685. while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
  1686. ret >= 0 &&
  1687. (!has_codec_parameters(st) || !has_decode_delay_been_guessed(st) ||
  1688. (!st->codec_info_nb_frames &&
  1689. (avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
  1690. got_picture = 0;
  1691. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  1692. avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1693. ret = avcodec_send_packet(avctx, &pkt);
  1694. if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
  1695. break;
  1696. if (ret >= 0)
  1697. pkt.size = 0;
  1698. ret = avcodec_receive_frame(avctx, frame);
  1699. if (ret >= 0)
  1700. got_picture = 1;
  1701. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  1702. ret = 0;
  1703. }
  1704. if (ret >= 0) {
  1705. if (got_picture)
  1706. st->info->nb_decoded_frames++;
  1707. ret = got_picture;
  1708. }
  1709. }
  1710. fail:
  1711. av_frame_free(&frame);
  1712. return ret;
  1713. }
  1714. unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
  1715. {
  1716. while (tags->id != AV_CODEC_ID_NONE) {
  1717. if (tags->id == id)
  1718. return tags->tag;
  1719. tags++;
  1720. }
  1721. return 0;
  1722. }
  1723. enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
  1724. {
  1725. int i;
  1726. for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
  1727. if (tag == tags[i].tag)
  1728. return tags[i].id;
  1729. for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
  1730. if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
  1731. return tags[i].id;
  1732. return AV_CODEC_ID_NONE;
  1733. }
  1734. enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
  1735. {
  1736. if (flt) {
  1737. switch (bps) {
  1738. case 32:
  1739. return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
  1740. case 64:
  1741. return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
  1742. default:
  1743. return AV_CODEC_ID_NONE;
  1744. }
  1745. } else {
  1746. bps >>= 3;
  1747. if (sflags & (1 << (bps - 1))) {
  1748. switch (bps) {
  1749. case 1:
  1750. return AV_CODEC_ID_PCM_S8;
  1751. case 2:
  1752. return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
  1753. case 3:
  1754. return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1755. case 4:
  1756. return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1757. default:
  1758. return AV_CODEC_ID_NONE;
  1759. }
  1760. } else {
  1761. switch (bps) {
  1762. case 1:
  1763. return AV_CODEC_ID_PCM_U8;
  1764. case 2:
  1765. return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
  1766. case 3:
  1767. return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
  1768. case 4:
  1769. return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
  1770. default:
  1771. return AV_CODEC_ID_NONE;
  1772. }
  1773. }
  1774. }
  1775. }
  1776. unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
  1777. {
  1778. int i;
  1779. for (i = 0; tags && tags[i]; i++) {
  1780. int tag = ff_codec_get_tag(tags[i], id);
  1781. if (tag)
  1782. return tag;
  1783. }
  1784. return 0;
  1785. }
  1786. enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
  1787. {
  1788. int i;
  1789. for (i = 0; tags && tags[i]; i++) {
  1790. enum AVCodecID id = ff_codec_get_id(tags[i], tag);
  1791. if (id != AV_CODEC_ID_NONE)
  1792. return id;
  1793. }
  1794. return AV_CODEC_ID_NONE;
  1795. }
  1796. static void compute_chapters_end(AVFormatContext *s)
  1797. {
  1798. unsigned int i, j;
  1799. int64_t max_time = s->duration +
  1800. ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
  1801. for (i = 0; i < s->nb_chapters; i++)
  1802. if (s->chapters[i]->end == AV_NOPTS_VALUE) {
  1803. AVChapter *ch = s->chapters[i];
  1804. int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
  1805. ch->time_base)
  1806. : INT64_MAX;
  1807. for (j = 0; j < s->nb_chapters; j++) {
  1808. AVChapter *ch1 = s->chapters[j];
  1809. int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
  1810. ch->time_base);
  1811. if (j != i && next_start > ch->start && next_start < end)
  1812. end = next_start;
  1813. }
  1814. ch->end = (end == INT64_MAX) ? ch->start : end;
  1815. }
  1816. }
  1817. static int get_std_framerate(int i)
  1818. {
  1819. if (i < 60 * 12)
  1820. return (i + 1) * 1001;
  1821. else
  1822. return ((const int[]) { 24, 30, 60, 12, 15 })[i - 60 * 12] * 1000 * 12;
  1823. }
  1824. static int extract_extradata_init(AVStream *st)
  1825. {
  1826. AVStreamInternal *i = st->internal;
  1827. const AVBitStreamFilter *f;
  1828. int ret;
  1829. f = av_bsf_get_by_name("extract_extradata");
  1830. if (!f)
  1831. goto finish;
  1832. /* check that the codec id is supported */
  1833. if (f->codec_ids) {
  1834. const enum AVCodecID *ids;
  1835. for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
  1836. if (*ids == st->codecpar->codec_id)
  1837. break;
  1838. if (*ids == AV_CODEC_ID_NONE)
  1839. goto finish;
  1840. }
  1841. i->extract_extradata.pkt = av_packet_alloc();
  1842. if (!i->extract_extradata.pkt)
  1843. return AVERROR(ENOMEM);
  1844. ret = av_bsf_alloc(f, &i->extract_extradata.bsf);
  1845. if (ret < 0)
  1846. goto fail;
  1847. ret = avcodec_parameters_copy(i->extract_extradata.bsf->par_in,
  1848. st->codecpar);
  1849. if (ret < 0)
  1850. goto fail;
  1851. i->extract_extradata.bsf->time_base_in = st->time_base;
  1852. /* if init fails here, we assume extracting extradata is just not
  1853. * supported for this codec, so we return success */
  1854. ret = av_bsf_init(i->extract_extradata.bsf);
  1855. if (ret < 0) {
  1856. av_bsf_free(&i->extract_extradata.bsf);
  1857. ret = 0;
  1858. }
  1859. finish:
  1860. i->extract_extradata.inited = 1;
  1861. return 0;
  1862. fail:
  1863. av_bsf_free(&i->extract_extradata.bsf);
  1864. av_packet_free(&i->extract_extradata.pkt);
  1865. return ret;
  1866. }
  1867. static int extract_extradata(AVStream *st, AVPacket *pkt)
  1868. {
  1869. AVStreamInternal *i = st->internal;
  1870. AVPacket *pkt_ref;
  1871. int ret;
  1872. if (!i->extract_extradata.inited) {
  1873. ret = extract_extradata_init(st);
  1874. if (ret < 0)
  1875. return ret;
  1876. }
  1877. if (i->extract_extradata.inited && !i->extract_extradata.bsf)
  1878. return 0;
  1879. pkt_ref = i->extract_extradata.pkt;
  1880. ret = av_packet_ref(pkt_ref, pkt);
  1881. if (ret < 0)
  1882. return ret;
  1883. ret = av_bsf_send_packet(i->extract_extradata.bsf, pkt_ref);
  1884. if (ret < 0) {
  1885. av_packet_unref(pkt_ref);
  1886. return ret;
  1887. }
  1888. while (ret >= 0 && !i->avctx->extradata) {
  1889. int extradata_size;
  1890. uint8_t *extradata;
  1891. ret = av_bsf_receive_packet(i->extract_extradata.bsf, pkt_ref);
  1892. if (ret < 0) {
  1893. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
  1894. return ret;
  1895. continue;
  1896. }
  1897. extradata = av_packet_get_side_data(pkt_ref, AV_PKT_DATA_NEW_EXTRADATA,
  1898. &extradata_size);
  1899. if (extradata) {
  1900. i->avctx->extradata = av_mallocz(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
  1901. if (!i->avctx->extradata) {
  1902. av_packet_unref(pkt_ref);
  1903. return AVERROR(ENOMEM);
  1904. }
  1905. memcpy(i->avctx->extradata, extradata, extradata_size);
  1906. i->avctx->extradata_size = extradata_size;
  1907. }
  1908. av_packet_unref(pkt_ref);
  1909. }
  1910. return 0;
  1911. }
  1912. int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
  1913. {
  1914. int i, count, ret, read_size, j;
  1915. AVStream *st;
  1916. AVCodecContext *avctx;
  1917. AVPacket pkt1, *pkt;
  1918. int64_t old_offset = avio_tell(ic->pb);
  1919. // new streams might appear, no options for those
  1920. int orig_nb_streams = ic->nb_streams;
  1921. for (i = 0; i < ic->nb_streams; i++) {
  1922. const AVCodec *codec;
  1923. AVDictionary *thread_opt = NULL;
  1924. st = ic->streams[i];
  1925. avctx = st->internal->avctx;
  1926. // only for the split stuff
  1927. if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
  1928. st->parser = av_parser_init(st->codecpar->codec_id);
  1929. if (st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser)
  1930. st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
  1931. }
  1932. /* check if the caller has overridden the codec id */
  1933. #if FF_API_LAVF_AVCTX
  1934. FF_DISABLE_DEPRECATION_WARNINGS
  1935. if (st->codec->codec_id != st->internal->orig_codec_id) {
  1936. st->codecpar->codec_id = st->codec->codec_id;
  1937. st->codecpar->codec_type = st->codec->codec_type;
  1938. st->internal->orig_codec_id = st->codec->codec_id;
  1939. }
  1940. FF_ENABLE_DEPRECATION_WARNINGS
  1941. #endif
  1942. if (st->codecpar->codec_id != st->internal->orig_codec_id)
  1943. st->internal->orig_codec_id = st->codecpar->codec_id;
  1944. ret = avcodec_parameters_to_context(avctx, st->codecpar);
  1945. if (ret < 0)
  1946. goto find_stream_info_err;
  1947. if (st->codecpar->codec_id != AV_CODEC_ID_PROBE &&
  1948. st->codecpar->codec_id != AV_CODEC_ID_NONE)
  1949. st->internal->avctx_inited = 1;
  1950. #if FF_API_LAVF_AVCTX
  1951. FF_DISABLE_DEPRECATION_WARNINGS
  1952. codec = st->codec->codec ? st->codec->codec
  1953. : avcodec_find_decoder(st->codecpar->codec_id);
  1954. FF_ENABLE_DEPRECATION_WARNINGS
  1955. #else
  1956. codec = avcodec_find_decoder(st->codecpar->codec_id);
  1957. #endif
  1958. /* Force thread count to 1 since the H.264 decoder will not extract
  1959. * SPS and PPS to extradata during multi-threaded decoding. */
  1960. av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
  1961. /* Ensure that subtitle_header is properly set. */
  1962. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE
  1963. && codec && !avctx->codec)
  1964. avcodec_open2(avctx, codec,
  1965. options ? &options[i] : &thread_opt);
  1966. // Try to just open decoders, in case this is enough to get parameters.
  1967. if (!has_codec_parameters(st)) {
  1968. if (codec && !avctx->codec)
  1969. avcodec_open2(avctx, codec,
  1970. options ? &options[i] : &thread_opt);
  1971. }
  1972. if (!options)
  1973. av_dict_free(&thread_opt);
  1974. }
  1975. for (i = 0; i < ic->nb_streams; i++) {
  1976. ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
  1977. ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
  1978. }
  1979. count = 0;
  1980. read_size = 0;
  1981. for (;;) {
  1982. if (ff_check_interrupt(&ic->interrupt_callback)) {
  1983. ret = AVERROR_EXIT;
  1984. av_log(ic, AV_LOG_DEBUG, "interrupted\n");
  1985. break;
  1986. }
  1987. /* check if one codec still needs to be handled */
  1988. for (i = 0; i < ic->nb_streams; i++) {
  1989. int fps_analyze_framecount = 20;
  1990. st = ic->streams[i];
  1991. if (!has_codec_parameters(st))
  1992. break;
  1993. /* If the timebase is coarse (like the usual millisecond precision
  1994. * of mkv), we need to analyze more frames to reliably arrive at
  1995. * the correct fps. */
  1996. if (av_q2d(st->time_base) > 0.0005)
  1997. fps_analyze_framecount *= 2;
  1998. if (ic->fps_probe_size >= 0)
  1999. fps_analyze_framecount = ic->fps_probe_size;
  2000. /* variable fps and no guess at the real fps */
  2001. if (!st->avg_frame_rate.num &&
  2002. st->codec_info_nb_frames < fps_analyze_framecount &&
  2003. st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  2004. break;
  2005. if (!st->codecpar->extradata &&
  2006. !st->internal->avctx->extradata &&
  2007. (!st->internal->extract_extradata.inited ||
  2008. st->internal->extract_extradata.bsf))
  2009. break;
  2010. if (st->first_dts == AV_NOPTS_VALUE &&
  2011. st->codec_info_nb_frames < ic->max_ts_probe &&
  2012. (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  2013. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
  2014. break;
  2015. }
  2016. if (i == ic->nb_streams) {
  2017. /* NOTE: If the format has no header, then we need to read some
  2018. * packets to get most of the streams, so we cannot stop here. */
  2019. if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
  2020. /* If we found the info for all the codecs, we can stop. */
  2021. ret = count;
  2022. av_log(ic, AV_LOG_DEBUG, "All info found\n");
  2023. break;
  2024. }
  2025. }
  2026. /* We did not get all the codec info, but we read too much data. */
  2027. if (read_size >= ic->probesize) {
  2028. ret = count;
  2029. av_log(ic, AV_LOG_DEBUG,
  2030. "Probe buffer size limit %d reached\n", ic->probesize);
  2031. break;
  2032. }
  2033. /* NOTE: A new stream can be added there if no header in file
  2034. * (AVFMTCTX_NOHEADER). */
  2035. ret = read_frame_internal(ic, &pkt1);
  2036. if (ret == AVERROR(EAGAIN))
  2037. continue;
  2038. if (ret < 0) {
  2039. /* EOF or error*/
  2040. AVPacket empty_pkt = { 0 };
  2041. int err = 0;
  2042. av_init_packet(&empty_pkt);
  2043. /* We could not have all the codec parameters before EOF. */
  2044. ret = -1;
  2045. for (i = 0; i < ic->nb_streams; i++) {
  2046. st = ic->streams[i];
  2047. /* flush the decoders */
  2048. if (st->info->found_decoder == 1) {
  2049. do {
  2050. err = try_decode_frame(ic, st, &empty_pkt,
  2051. (options && i < orig_nb_streams)
  2052. ? &options[i] : NULL);
  2053. } while (err > 0 && !has_codec_parameters(st));
  2054. }
  2055. if (err < 0) {
  2056. av_log(ic, AV_LOG_WARNING,
  2057. "decoding for stream %d failed\n", st->index);
  2058. } else if (!has_codec_parameters(st)) {
  2059. char buf[256];
  2060. avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
  2061. av_log(ic, AV_LOG_WARNING,
  2062. "Could not find codec parameters (%s)\n", buf);
  2063. } else {
  2064. ret = 0;
  2065. }
  2066. }
  2067. break;
  2068. }
  2069. pkt = &pkt1;
  2070. if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
  2071. ret = add_to_pktbuf(&ic->internal->packet_buffer, pkt,
  2072. &ic->internal->packet_buffer_end, 0);
  2073. if (ret < 0)
  2074. goto find_stream_info_err;
  2075. }
  2076. read_size += pkt->size;
  2077. st = ic->streams[pkt->stream_index];
  2078. avctx = st->internal->avctx;
  2079. if (!st->internal->avctx_inited) {
  2080. ret = avcodec_parameters_to_context(avctx, st->codecpar);
  2081. if (ret < 0)
  2082. goto find_stream_info_err;
  2083. st->internal->avctx_inited = 1;
  2084. }
  2085. if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
  2086. /* check for non-increasing dts */
  2087. if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
  2088. st->info->fps_last_dts >= pkt->dts) {
  2089. av_log(ic, AV_LOG_WARNING,
  2090. "Non-increasing DTS in stream %d: packet %d with DTS "
  2091. "%"PRId64", packet %d with DTS %"PRId64"\n",
  2092. st->index, st->info->fps_last_dts_idx,
  2093. st->info->fps_last_dts, st->codec_info_nb_frames,
  2094. pkt->dts);
  2095. st->info->fps_first_dts =
  2096. st->info->fps_last_dts = AV_NOPTS_VALUE;
  2097. }
  2098. /* Check for a discontinuity in dts. If the difference in dts
  2099. * is more than 1000 times the average packet duration in the
  2100. * sequence, we treat it as a discontinuity. */
  2101. if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
  2102. st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
  2103. (pkt->dts - st->info->fps_last_dts) / 1000 >
  2104. (st->info->fps_last_dts - st->info->fps_first_dts) /
  2105. (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
  2106. av_log(ic, AV_LOG_WARNING,
  2107. "DTS discontinuity in stream %d: packet %d with DTS "
  2108. "%"PRId64", packet %d with DTS %"PRId64"\n",
  2109. st->index, st->info->fps_last_dts_idx,
  2110. st->info->fps_last_dts, st->codec_info_nb_frames,
  2111. pkt->dts);
  2112. st->info->fps_first_dts =
  2113. st->info->fps_last_dts = AV_NOPTS_VALUE;
  2114. }
  2115. /* update stored dts values */
  2116. if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
  2117. st->info->fps_first_dts = pkt->dts;
  2118. st->info->fps_first_dts_idx = st->codec_info_nb_frames;
  2119. }
  2120. st->info->fps_last_dts = pkt->dts;
  2121. st->info->fps_last_dts_idx = st->codec_info_nb_frames;
  2122. /* check max_analyze_duration */
  2123. if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
  2124. AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
  2125. av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached\n",
  2126. ic->max_analyze_duration);
  2127. if (ic->flags & AVFMT_FLAG_NOBUFFER)
  2128. av_packet_unref(pkt);
  2129. break;
  2130. }
  2131. }
  2132. if (!st->internal->avctx->extradata) {
  2133. ret = extract_extradata(st, pkt);
  2134. if (ret < 0)
  2135. goto find_stream_info_err;
  2136. }
  2137. /* If still no information, we try to open the codec and to
  2138. * decompress the frame. We try to avoid that in most cases as
  2139. * it takes longer and uses more memory. For MPEG-4, we need to
  2140. * decompress for QuickTime.
  2141. *
  2142. * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
  2143. * least one frame of codec data, this makes sure the codec initializes
  2144. * the channel configuration and does not only trust the values from
  2145. * the container. */
  2146. try_decode_frame(ic, st, pkt,
  2147. (options && i < orig_nb_streams) ? &options[i] : NULL);
  2148. if (ic->flags & AVFMT_FLAG_NOBUFFER)
  2149. av_packet_unref(pkt);
  2150. st->codec_info_nb_frames++;
  2151. count++;
  2152. }
  2153. for (i = 0; i < ic->nb_streams; i++) {
  2154. st = ic->streams[i];
  2155. avctx = st->internal->avctx;
  2156. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  2157. /* estimate average framerate if not set by demuxer */
  2158. if (!st->avg_frame_rate.num &&
  2159. st->info->fps_last_dts != st->info->fps_first_dts) {
  2160. int64_t delta_dts = st->info->fps_last_dts -
  2161. st->info->fps_first_dts;
  2162. int delta_packets = st->info->fps_last_dts_idx -
  2163. st->info->fps_first_dts_idx;
  2164. int best_fps = 0;
  2165. double best_error = 0.01;
  2166. if (delta_dts >= INT64_MAX / st->time_base.num ||
  2167. delta_packets >= INT64_MAX / st->time_base.den ||
  2168. delta_dts < 0)
  2169. continue;
  2170. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  2171. delta_packets * (int64_t) st->time_base.den,
  2172. delta_dts * (int64_t) st->time_base.num, 60000);
  2173. /* Round guessed framerate to a "standard" framerate if it's
  2174. * within 1% of the original estimate. */
  2175. for (j = 0; j < MAX_STD_TIMEBASES; j++) {
  2176. AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
  2177. double error = fabs(av_q2d(st->avg_frame_rate) /
  2178. av_q2d(std_fps) - 1);
  2179. if (error < best_error) {
  2180. best_error = error;
  2181. best_fps = std_fps.num;
  2182. }
  2183. }
  2184. if (best_fps)
  2185. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  2186. best_fps, 12 * 1001, INT_MAX);
  2187. }
  2188. } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  2189. if (!avctx->bits_per_coded_sample)
  2190. avctx->bits_per_coded_sample =
  2191. av_get_bits_per_sample(avctx->codec_id);
  2192. // set stream disposition based on audio service type
  2193. switch (avctx->audio_service_type) {
  2194. case AV_AUDIO_SERVICE_TYPE_EFFECTS:
  2195. st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
  2196. break;
  2197. case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
  2198. st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
  2199. break;
  2200. case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
  2201. st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
  2202. break;
  2203. case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
  2204. st->disposition = AV_DISPOSITION_COMMENT;
  2205. break;
  2206. case AV_AUDIO_SERVICE_TYPE_KARAOKE:
  2207. st->disposition = AV_DISPOSITION_KARAOKE;
  2208. break;
  2209. }
  2210. }
  2211. }
  2212. compute_chapters_end(ic);
  2213. /* update the stream parameters from the internal codec contexts */
  2214. for (i = 0; i < ic->nb_streams; i++) {
  2215. st = ic->streams[i];
  2216. if (!st->internal->avctx_inited)
  2217. continue;
  2218. ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
  2219. if (ret < 0)
  2220. goto find_stream_info_err;
  2221. #if FF_API_LAVF_AVCTX
  2222. FF_DISABLE_DEPRECATION_WARNINGS
  2223. ret = avcodec_parameters_to_context(st->codec, st->codecpar);
  2224. if (ret < 0)
  2225. goto find_stream_info_err;
  2226. if (st->internal->avctx->subtitle_header) {
  2227. st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
  2228. if (!st->codec->subtitle_header)
  2229. goto find_stream_info_err;
  2230. st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
  2231. memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
  2232. st->codec->subtitle_header_size);
  2233. }
  2234. FF_ENABLE_DEPRECATION_WARNINGS
  2235. #endif
  2236. st->internal->avctx_inited = 0;
  2237. }
  2238. estimate_timings(ic, old_offset);
  2239. find_stream_info_err:
  2240. for (i = 0; i < ic->nb_streams; i++) {
  2241. avcodec_close(ic->streams[i]->internal->avctx);
  2242. av_freep(&ic->streams[i]->info);
  2243. av_bsf_free(&ic->streams[i]->internal->extract_extradata.bsf);
  2244. av_packet_free(&ic->streams[i]->internal->extract_extradata.pkt);
  2245. }
  2246. return ret;
  2247. }
  2248. static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
  2249. {
  2250. int i, j;
  2251. for (i = 0; i < ic->nb_programs; i++)
  2252. for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
  2253. if (ic->programs[i]->stream_index[j] == s)
  2254. return ic->programs[i];
  2255. return NULL;
  2256. }
  2257. int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
  2258. int wanted_stream_nb, int related_stream,
  2259. AVCodec **decoder_ret, int flags)
  2260. {
  2261. int i, nb_streams = ic->nb_streams;
  2262. int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
  2263. unsigned *program = NULL;
  2264. AVCodec *decoder = NULL, *best_decoder = NULL;
  2265. if (related_stream >= 0 && wanted_stream_nb < 0) {
  2266. AVProgram *p = find_program_from_stream(ic, related_stream);
  2267. if (p) {
  2268. program = p->stream_index;
  2269. nb_streams = p->nb_stream_indexes;
  2270. }
  2271. }
  2272. for (i = 0; i < nb_streams; i++) {
  2273. int real_stream_index = program ? program[i] : i;
  2274. AVStream *st = ic->streams[real_stream_index];
  2275. AVCodecParameters *par = st->codecpar;
  2276. if (par->codec_type != type)
  2277. continue;
  2278. if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
  2279. continue;
  2280. if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |
  2281. AV_DISPOSITION_VISUAL_IMPAIRED))
  2282. continue;
  2283. if (decoder_ret) {
  2284. decoder = avcodec_find_decoder(par->codec_id);
  2285. if (!decoder) {
  2286. if (ret < 0)
  2287. ret = AVERROR_DECODER_NOT_FOUND;
  2288. continue;
  2289. }
  2290. }
  2291. if (best_count >= st->codec_info_nb_frames)
  2292. continue;
  2293. best_count = st->codec_info_nb_frames;
  2294. ret = real_stream_index;
  2295. best_decoder = decoder;
  2296. if (program && i == nb_streams - 1 && ret < 0) {
  2297. program = NULL;
  2298. nb_streams = ic->nb_streams;
  2299. /* no related stream found, try again with everything */
  2300. i = 0;
  2301. }
  2302. }
  2303. if (decoder_ret)
  2304. *decoder_ret = best_decoder;
  2305. return ret;
  2306. }
  2307. /*******************************************************/
  2308. int av_read_play(AVFormatContext *s)
  2309. {
  2310. if (s->iformat->read_play)
  2311. return s->iformat->read_play(s);
  2312. if (s->pb)
  2313. return avio_pause(s->pb, 0);
  2314. return AVERROR(ENOSYS);
  2315. }
  2316. int av_read_pause(AVFormatContext *s)
  2317. {
  2318. if (s->iformat->read_pause)
  2319. return s->iformat->read_pause(s);
  2320. if (s->pb)
  2321. return avio_pause(s->pb, 1);
  2322. return AVERROR(ENOSYS);
  2323. }
  2324. static void free_stream(AVStream **pst)
  2325. {
  2326. AVStream *st = *pst;
  2327. int i;
  2328. if (!st)
  2329. return;
  2330. for (i = 0; i < st->nb_side_data; i++)
  2331. av_freep(&st->side_data[i].data);
  2332. av_freep(&st->side_data);
  2333. if (st->parser)
  2334. av_parser_close(st->parser);
  2335. if (st->attached_pic.data)
  2336. av_packet_unref(&st->attached_pic);
  2337. if (st->internal) {
  2338. avcodec_free_context(&st->internal->avctx);
  2339. av_bsf_free(&st->internal->extract_extradata.bsf);
  2340. av_packet_free(&st->internal->extract_extradata.pkt);
  2341. }
  2342. av_freep(&st->internal);
  2343. av_dict_free(&st->metadata);
  2344. avcodec_parameters_free(&st->codecpar);
  2345. av_freep(&st->probe_data.buf);
  2346. av_free(st->index_entries);
  2347. #if FF_API_LAVF_AVCTX
  2348. FF_DISABLE_DEPRECATION_WARNINGS
  2349. av_free(st->codec->extradata);
  2350. av_free(st->codec->subtitle_header);
  2351. av_free(st->codec);
  2352. FF_ENABLE_DEPRECATION_WARNINGS
  2353. #endif
  2354. av_free(st->priv_data);
  2355. av_free(st->info);
  2356. av_freep(pst);
  2357. }
  2358. void avformat_free_context(AVFormatContext *s)
  2359. {
  2360. int i;
  2361. if (!s)
  2362. return;
  2363. av_opt_free(s);
  2364. if (s->iformat && s->iformat->priv_class && s->priv_data)
  2365. av_opt_free(s->priv_data);
  2366. for (i = 0; i < s->nb_streams; i++)
  2367. free_stream(&s->streams[i]);
  2368. for (i = s->nb_programs - 1; i >= 0; i--) {
  2369. av_dict_free(&s->programs[i]->metadata);
  2370. av_freep(&s->programs[i]->stream_index);
  2371. av_freep(&s->programs[i]);
  2372. }
  2373. av_freep(&s->programs);
  2374. av_freep(&s->priv_data);
  2375. while (s->nb_chapters--) {
  2376. av_dict_free(&s->chapters[s->nb_chapters]->metadata);
  2377. av_free(s->chapters[s->nb_chapters]);
  2378. }
  2379. av_freep(&s->chapters);
  2380. av_dict_free(&s->metadata);
  2381. av_freep(&s->streams);
  2382. av_freep(&s->internal);
  2383. av_free(s);
  2384. }
  2385. void avformat_close_input(AVFormatContext **ps)
  2386. {
  2387. AVFormatContext *s = *ps;
  2388. AVIOContext *pb = s->pb;
  2389. if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
  2390. (s->flags & AVFMT_FLAG_CUSTOM_IO))
  2391. pb = NULL;
  2392. flush_packet_queue(s);
  2393. if (s->iformat)
  2394. if (s->iformat->read_close)
  2395. s->iformat->read_close(s);
  2396. avformat_free_context(s);
  2397. *ps = NULL;
  2398. avio_close(pb);
  2399. }
  2400. AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
  2401. {
  2402. AVStream *st;
  2403. int i;
  2404. if (av_reallocp_array(&s->streams, s->nb_streams + 1,
  2405. sizeof(*s->streams)) < 0) {
  2406. s->nb_streams = 0;
  2407. return NULL;
  2408. }
  2409. st = av_mallocz(sizeof(AVStream));
  2410. if (!st)
  2411. return NULL;
  2412. if (!(st->info = av_mallocz(sizeof(*st->info)))) {
  2413. av_free(st);
  2414. return NULL;
  2415. }
  2416. #if FF_API_LAVF_AVCTX
  2417. FF_DISABLE_DEPRECATION_WARNINGS
  2418. st->codec = avcodec_alloc_context3(c);
  2419. if (!st->codec) {
  2420. av_free(st->info);
  2421. av_free(st);
  2422. return NULL;
  2423. }
  2424. FF_ENABLE_DEPRECATION_WARNINGS
  2425. #endif
  2426. st->internal = av_mallocz(sizeof(*st->internal));
  2427. if (!st->internal)
  2428. goto fail;
  2429. if (s->iformat) {
  2430. #if FF_API_LAVF_AVCTX
  2431. FF_DISABLE_DEPRECATION_WARNINGS
  2432. /* no default bitrate if decoding */
  2433. st->codec->bit_rate = 0;
  2434. FF_ENABLE_DEPRECATION_WARNINGS
  2435. #endif
  2436. /* default pts setting is MPEG-like */
  2437. avpriv_set_pts_info(st, 33, 1, 90000);
  2438. /* we set the current DTS to 0 so that formats without any timestamps
  2439. * but durations get some timestamps, formats with some unknown
  2440. * timestamps have their first few packets buffered and the
  2441. * timestamps corrected before they are returned to the user */
  2442. st->cur_dts = 0;
  2443. } else {
  2444. st->cur_dts = AV_NOPTS_VALUE;
  2445. }
  2446. st->codecpar = avcodec_parameters_alloc();
  2447. if (!st->codecpar)
  2448. goto fail;
  2449. st->internal->avctx = avcodec_alloc_context3(NULL);
  2450. if (!st->internal->avctx)
  2451. goto fail;
  2452. st->index = s->nb_streams;
  2453. st->start_time = AV_NOPTS_VALUE;
  2454. st->duration = AV_NOPTS_VALUE;
  2455. st->first_dts = AV_NOPTS_VALUE;
  2456. st->probe_packets = MAX_PROBE_PACKETS;
  2457. st->last_IP_pts = AV_NOPTS_VALUE;
  2458. for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
  2459. st->pts_buffer[i] = AV_NOPTS_VALUE;
  2460. st->sample_aspect_ratio = (AVRational) { 0, 1 };
  2461. st->info->fps_first_dts = AV_NOPTS_VALUE;
  2462. st->info->fps_last_dts = AV_NOPTS_VALUE;
  2463. #if FF_API_LAVF_AVCTX
  2464. st->internal->need_codec_update = 1;
  2465. #endif
  2466. s->streams[s->nb_streams++] = st;
  2467. return st;
  2468. fail:
  2469. free_stream(&st);
  2470. return NULL;
  2471. }
  2472. AVProgram *av_new_program(AVFormatContext *ac, int id)
  2473. {
  2474. AVProgram *program = NULL;
  2475. int i;
  2476. av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
  2477. for (i = 0; i < ac->nb_programs; i++)
  2478. if (ac->programs[i]->id == id)
  2479. program = ac->programs[i];
  2480. if (!program) {
  2481. program = av_mallocz(sizeof(AVProgram));
  2482. if (!program)
  2483. return NULL;
  2484. dynarray_add(&ac->programs, &ac->nb_programs, program);
  2485. program->discard = AVDISCARD_NONE;
  2486. }
  2487. program->id = id;
  2488. return program;
  2489. }
  2490. AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
  2491. int64_t start, int64_t end, const char *title)
  2492. {
  2493. AVChapter *chapter = NULL;
  2494. int i;
  2495. for (i = 0; i < s->nb_chapters; i++)
  2496. if (s->chapters[i]->id == id)
  2497. chapter = s->chapters[i];
  2498. if (!chapter) {
  2499. chapter = av_mallocz(sizeof(AVChapter));
  2500. if (!chapter)
  2501. return NULL;
  2502. dynarray_add(&s->chapters, &s->nb_chapters, chapter);
  2503. }
  2504. av_dict_set(&chapter->metadata, "title", title, 0);
  2505. chapter->id = id;
  2506. chapter->time_base = time_base;
  2507. chapter->start = start;
  2508. chapter->end = end;
  2509. return chapter;
  2510. }
  2511. void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
  2512. {
  2513. int i, j;
  2514. AVProgram *program = NULL;
  2515. if (idx >= ac->nb_streams) {
  2516. av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
  2517. return;
  2518. }
  2519. for (i = 0; i < ac->nb_programs; i++) {
  2520. if (ac->programs[i]->id != progid)
  2521. continue;
  2522. program = ac->programs[i];
  2523. for (j = 0; j < program->nb_stream_indexes; j++)
  2524. if (program->stream_index[j] == idx)
  2525. return;
  2526. if (av_reallocp_array(&program->stream_index,
  2527. program->nb_stream_indexes + 1,
  2528. sizeof(*program->stream_index)) < 0) {
  2529. program->nb_stream_indexes = 0;
  2530. return;
  2531. }
  2532. program->stream_index[program->nb_stream_indexes++] = idx;
  2533. return;
  2534. }
  2535. }
  2536. uint64_t ff_ntp_time(void)
  2537. {
  2538. return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
  2539. }
  2540. int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
  2541. {
  2542. const char *p;
  2543. char *q, buf1[20], c;
  2544. int nd, len, percentd_found;
  2545. q = buf;
  2546. p = path;
  2547. percentd_found = 0;
  2548. for (;;) {
  2549. c = *p++;
  2550. if (c == '\0')
  2551. break;
  2552. if (c == '%') {
  2553. do {
  2554. nd = 0;
  2555. while (av_isdigit(*p))
  2556. nd = nd * 10 + *p++ - '0';
  2557. c = *p++;
  2558. } while (av_isdigit(c));
  2559. switch (c) {
  2560. case '%':
  2561. goto addchar;
  2562. case 'd':
  2563. if (percentd_found)
  2564. goto fail;
  2565. percentd_found = 1;
  2566. snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
  2567. len = strlen(buf1);
  2568. if ((q - buf + len) > buf_size - 1)
  2569. goto fail;
  2570. memcpy(q, buf1, len);
  2571. q += len;
  2572. break;
  2573. default:
  2574. goto fail;
  2575. }
  2576. } else {
  2577. addchar:
  2578. if ((q - buf) < buf_size - 1)
  2579. *q++ = c;
  2580. }
  2581. }
  2582. if (!percentd_found)
  2583. goto fail;
  2584. *q = '\0';
  2585. return 0;
  2586. fail:
  2587. *q = '\0';
  2588. return -1;
  2589. }
  2590. void av_url_split(char *proto, int proto_size,
  2591. char *authorization, int authorization_size,
  2592. char *hostname, int hostname_size,
  2593. int *port_ptr, char *path, int path_size, const char *url)
  2594. {
  2595. const char *p, *ls, *at, *col, *brk;
  2596. if (port_ptr)
  2597. *port_ptr = -1;
  2598. if (proto_size > 0)
  2599. proto[0] = 0;
  2600. if (authorization_size > 0)
  2601. authorization[0] = 0;
  2602. if (hostname_size > 0)
  2603. hostname[0] = 0;
  2604. if (path_size > 0)
  2605. path[0] = 0;
  2606. /* parse protocol */
  2607. if ((p = strchr(url, ':'))) {
  2608. av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
  2609. p++; /* skip ':' */
  2610. if (*p == '/')
  2611. p++;
  2612. if (*p == '/')
  2613. p++;
  2614. } else {
  2615. /* no protocol means plain filename */
  2616. av_strlcpy(path, url, path_size);
  2617. return;
  2618. }
  2619. /* separate path from hostname */
  2620. ls = strchr(p, '/');
  2621. if (!ls)
  2622. ls = strchr(p, '?');
  2623. if (ls)
  2624. av_strlcpy(path, ls, path_size);
  2625. else
  2626. ls = &p[strlen(p)]; // XXX
  2627. /* the rest is hostname, use that to parse auth/port */
  2628. if (ls != p) {
  2629. /* authorization (user[:pass]@hostname) */
  2630. if ((at = strchr(p, '@')) && at < ls) {
  2631. av_strlcpy(authorization, p,
  2632. FFMIN(authorization_size, at + 1 - p));
  2633. p = at + 1; /* skip '@' */
  2634. }
  2635. if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
  2636. /* [host]:port */
  2637. av_strlcpy(hostname, p + 1,
  2638. FFMIN(hostname_size, brk - p));
  2639. if (brk[1] == ':' && port_ptr)
  2640. *port_ptr = atoi(brk + 2);
  2641. } else if ((col = strchr(p, ':')) && col < ls) {
  2642. av_strlcpy(hostname, p,
  2643. FFMIN(col + 1 - p, hostname_size));
  2644. if (port_ptr)
  2645. *port_ptr = atoi(col + 1);
  2646. } else
  2647. av_strlcpy(hostname, p,
  2648. FFMIN(ls + 1 - p, hostname_size));
  2649. }
  2650. }
  2651. char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
  2652. {
  2653. int i;
  2654. static const char hex_table_uc[16] = { '0', '1', '2', '3',
  2655. '4', '5', '6', '7',
  2656. '8', '9', 'A', 'B',
  2657. 'C', 'D', 'E', 'F' };
  2658. static const char hex_table_lc[16] = { '0', '1', '2', '3',
  2659. '4', '5', '6', '7',
  2660. '8', '9', 'a', 'b',
  2661. 'c', 'd', 'e', 'f' };
  2662. const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
  2663. for (i = 0; i < s; i++) {
  2664. buff[i * 2] = hex_table[src[i] >> 4];
  2665. buff[i * 2 + 1] = hex_table[src[i] & 0xF];
  2666. }
  2667. return buff;
  2668. }
  2669. int ff_hex_to_data(uint8_t *data, const char *p)
  2670. {
  2671. int c, len, v;
  2672. len = 0;
  2673. v = 1;
  2674. for (;;) {
  2675. p += strspn(p, SPACE_CHARS);
  2676. if (*p == '\0')
  2677. break;
  2678. c = av_toupper((unsigned char) *p++);
  2679. if (c >= '0' && c <= '9')
  2680. c = c - '0';
  2681. else if (c >= 'A' && c <= 'F')
  2682. c = c - 'A' + 10;
  2683. else
  2684. break;
  2685. v = (v << 4) | c;
  2686. if (v & 0x100) {
  2687. if (data)
  2688. data[len] = v;
  2689. len++;
  2690. v = 1;
  2691. }
  2692. }
  2693. return len;
  2694. }
  2695. void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
  2696. unsigned int pts_num, unsigned int pts_den)
  2697. {
  2698. AVRational new_tb;
  2699. if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
  2700. if (new_tb.num != pts_num)
  2701. av_log(NULL, AV_LOG_DEBUG,
  2702. "st:%d removing common factor %d from timebase\n",
  2703. s->index, pts_num / new_tb.num);
  2704. } else
  2705. av_log(NULL, AV_LOG_WARNING,
  2706. "st:%d has too large timebase, reducing\n", s->index);
  2707. if (new_tb.num <= 0 || new_tb.den <= 0) {
  2708. av_log(NULL, AV_LOG_ERROR,
  2709. "Ignoring attempt to set invalid timebase for st:%d\n",
  2710. s->index);
  2711. return;
  2712. }
  2713. s->time_base = new_tb;
  2714. s->pts_wrap_bits = pts_wrap_bits;
  2715. }
  2716. void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
  2717. void *context)
  2718. {
  2719. const char *ptr = str;
  2720. /* Parse key=value pairs. */
  2721. for (;;) {
  2722. const char *key;
  2723. char *dest = NULL, *dest_end;
  2724. int key_len, dest_len = 0;
  2725. /* Skip whitespace and potential commas. */
  2726. while (*ptr && (av_isspace(*ptr) || *ptr == ','))
  2727. ptr++;
  2728. if (!*ptr)
  2729. break;
  2730. key = ptr;
  2731. if (!(ptr = strchr(key, '=')))
  2732. break;
  2733. ptr++;
  2734. key_len = ptr - key;
  2735. callback_get_buf(context, key, key_len, &dest, &dest_len);
  2736. dest_end = dest + dest_len - 1;
  2737. if (*ptr == '\"') {
  2738. ptr++;
  2739. while (*ptr && *ptr != '\"') {
  2740. if (*ptr == '\\') {
  2741. if (!ptr[1])
  2742. break;
  2743. if (dest && dest < dest_end)
  2744. *dest++ = ptr[1];
  2745. ptr += 2;
  2746. } else {
  2747. if (dest && dest < dest_end)
  2748. *dest++ = *ptr;
  2749. ptr++;
  2750. }
  2751. }
  2752. if (*ptr == '\"')
  2753. ptr++;
  2754. } else {
  2755. for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
  2756. if (dest && dest < dest_end)
  2757. *dest++ = *ptr;
  2758. }
  2759. if (dest)
  2760. *dest = 0;
  2761. }
  2762. }
  2763. int ff_find_stream_index(AVFormatContext *s, int id)
  2764. {
  2765. int i;
  2766. for (i = 0; i < s->nb_streams; i++)
  2767. if (s->streams[i]->id == id)
  2768. return i;
  2769. return -1;
  2770. }
  2771. int64_t ff_iso8601_to_unix_time(const char *datestr)
  2772. {
  2773. struct tm time1 = { 0 }, time2 = { 0 };
  2774. const char *ret1, *ret2;
  2775. ret1 = av_small_strptime(datestr, "%Y - %m - %d %T", &time1);
  2776. ret2 = av_small_strptime(datestr, "%Y - %m - %dT%T", &time2);
  2777. if (ret2 && !ret1)
  2778. return av_timegm(&time2);
  2779. else
  2780. return av_timegm(&time1);
  2781. }
  2782. int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
  2783. int std_compliance)
  2784. {
  2785. if (ofmt) {
  2786. if (ofmt->query_codec)
  2787. return ofmt->query_codec(codec_id, std_compliance);
  2788. else if (ofmt->codec_tag)
  2789. return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
  2790. else if (codec_id == ofmt->video_codec ||
  2791. codec_id == ofmt->audio_codec ||
  2792. codec_id == ofmt->subtitle_codec)
  2793. return 1;
  2794. }
  2795. return AVERROR_PATCHWELCOME;
  2796. }
  2797. int avformat_network_init(void)
  2798. {
  2799. #if CONFIG_NETWORK
  2800. int ret;
  2801. ff_network_inited_globally = 1;
  2802. if ((ret = ff_network_init()) < 0)
  2803. return ret;
  2804. ff_tls_init();
  2805. #endif
  2806. return 0;
  2807. }
  2808. int avformat_network_deinit(void)
  2809. {
  2810. #if CONFIG_NETWORK
  2811. ff_network_close();
  2812. ff_tls_deinit();
  2813. #endif
  2814. return 0;
  2815. }
  2816. int ff_add_param_change(AVPacket *pkt, int32_t channels,
  2817. uint64_t channel_layout, int32_t sample_rate,
  2818. int32_t width, int32_t height)
  2819. {
  2820. uint32_t flags = 0;
  2821. int size = 4;
  2822. uint8_t *data;
  2823. if (!pkt)
  2824. return AVERROR(EINVAL);
  2825. if (channels) {
  2826. size += 4;
  2827. flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
  2828. }
  2829. if (channel_layout) {
  2830. size += 8;
  2831. flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
  2832. }
  2833. if (sample_rate) {
  2834. size += 4;
  2835. flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
  2836. }
  2837. if (width || height) {
  2838. size += 8;
  2839. flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
  2840. }
  2841. data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
  2842. if (!data)
  2843. return AVERROR(ENOMEM);
  2844. bytestream_put_le32(&data, flags);
  2845. if (channels)
  2846. bytestream_put_le32(&data, channels);
  2847. if (channel_layout)
  2848. bytestream_put_le64(&data, channel_layout);
  2849. if (sample_rate)
  2850. bytestream_put_le32(&data, sample_rate);
  2851. if (width || height) {
  2852. bytestream_put_le32(&data, width);
  2853. bytestream_put_le32(&data, height);
  2854. }
  2855. return 0;
  2856. }
  2857. int ff_generate_avci_extradata(AVStream *st)
  2858. {
  2859. static const uint8_t avci100_1080p_extradata[] = {
  2860. // SPS
  2861. 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
  2862. 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
  2863. 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
  2864. 0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
  2865. 0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
  2866. 0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
  2867. 0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
  2868. 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
  2869. 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  2870. // PPS
  2871. 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
  2872. 0xd0
  2873. };
  2874. static const uint8_t avci100_1080i_extradata[] = {
  2875. // SPS
  2876. 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
  2877. 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
  2878. 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
  2879. 0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
  2880. 0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
  2881. 0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
  2882. 0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
  2883. 0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
  2884. 0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
  2885. 0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
  2886. 0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x00,
  2887. // PPS
  2888. 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
  2889. 0xd0
  2890. };
  2891. static const uint8_t avci50_1080i_extradata[] = {
  2892. // SPS
  2893. 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
  2894. 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
  2895. 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
  2896. 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
  2897. 0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
  2898. 0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
  2899. 0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
  2900. 0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
  2901. 0x81, 0x13, 0xf7, 0xff, 0x80, 0x01, 0x80, 0x02,
  2902. 0x71, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
  2903. 0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
  2904. // PPS
  2905. 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
  2906. 0x11
  2907. };
  2908. static const uint8_t avci100_720p_extradata[] = {
  2909. // SPS
  2910. 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
  2911. 0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
  2912. 0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
  2913. 0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
  2914. 0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
  2915. 0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
  2916. 0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
  2917. 0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
  2918. 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
  2919. 0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
  2920. // PPS
  2921. 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
  2922. 0x11
  2923. };
  2924. const uint8_t *data = NULL;
  2925. int size = 0;
  2926. if (st->codecpar->width == 1920) {
  2927. if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
  2928. data = avci100_1080p_extradata;
  2929. size = sizeof(avci100_1080p_extradata);
  2930. } else {
  2931. data = avci100_1080i_extradata;
  2932. size = sizeof(avci100_1080i_extradata);
  2933. }
  2934. } else if (st->codecpar->width == 1440) {
  2935. data = avci50_1080i_extradata;
  2936. size = sizeof(avci50_1080i_extradata);
  2937. } else if (st->codecpar->width == 1280) {
  2938. data = avci100_720p_extradata;
  2939. size = sizeof(avci100_720p_extradata);
  2940. }
  2941. if (!size)
  2942. return 0;
  2943. av_freep(&st->codecpar->extradata);
  2944. st->codecpar->extradata_size = 0;
  2945. st->codecpar->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
  2946. if (!st->codecpar->extradata)
  2947. return AVERROR(ENOMEM);
  2948. memcpy(st->codecpar->extradata, data, size);
  2949. st->codecpar->extradata_size = size;
  2950. return 0;
  2951. }
  2952. uint8_t *av_stream_get_side_data(AVStream *st, enum AVPacketSideDataType type,
  2953. int *size)
  2954. {
  2955. int i;
  2956. for (i = 0; i < st->nb_side_data; i++) {
  2957. if (st->side_data[i].type == type) {
  2958. if (size)
  2959. *size = st->side_data[i].size;
  2960. return st->side_data[i].data;
  2961. }
  2962. }
  2963. return NULL;
  2964. }
  2965. int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
  2966. uint8_t *data, size_t size)
  2967. {
  2968. AVPacketSideData *sd, *tmp;
  2969. int i;
  2970. for (i = 0; i < st->nb_side_data; i++) {
  2971. sd = &st->side_data[i];
  2972. if (sd->type == type) {
  2973. av_freep(&sd->data);
  2974. sd->data = data;
  2975. sd->size = size;
  2976. return 0;
  2977. }
  2978. }
  2979. if ((unsigned) st->nb_side_data + 1 >= INT_MAX / sizeof(*st->side_data))
  2980. return AVERROR(ERANGE);
  2981. tmp = av_realloc(st->side_data, (st->nb_side_data + 1) * sizeof(*tmp));
  2982. if (!tmp) {
  2983. return AVERROR(ENOMEM);
  2984. }
  2985. st->side_data = tmp;
  2986. st->nb_side_data++;
  2987. sd = &st->side_data[st->nb_side_data - 1];
  2988. sd->type = type;
  2989. sd->data = data;
  2990. sd->size = size;
  2991. return 0;
  2992. }
  2993. uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
  2994. int size)
  2995. {
  2996. int ret;
  2997. uint8_t *data = av_malloc(size);
  2998. if (!data)
  2999. return NULL;
  3000. ret = av_stream_add_side_data(st, type, data, size);
  3001. if (ret < 0) {
  3002. av_freep(&data);
  3003. return NULL;
  3004. }
  3005. return data;
  3006. }
  3007. void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
  3008. {
  3009. if (*pb)
  3010. s->io_close(s, *pb);
  3011. *pb = NULL;
  3012. }