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.

1050 lines
34KB

  1. /*
  2. * muxing functions for use within FFmpeg
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "avformat.h"
  22. #include "avio_internal.h"
  23. #include "internal.h"
  24. #include "libavcodec/internal.h"
  25. #include "libavcodec/bytestream.h"
  26. #include "libavutil/opt.h"
  27. #include "libavutil/dict.h"
  28. #include "libavutil/pixdesc.h"
  29. #include "libavutil/timestamp.h"
  30. #include "metadata.h"
  31. #include "id3v2.h"
  32. #include "libavutil/avassert.h"
  33. #include "libavutil/avstring.h"
  34. #include "libavutil/internal.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavutil/parseutils.h"
  37. #include "libavutil/time.h"
  38. #include "riff.h"
  39. #include "audiointerleave.h"
  40. #include "url.h"
  41. #include <stdarg.h>
  42. #if CONFIG_NETWORK
  43. #include "network.h"
  44. #endif
  45. /**
  46. * @file
  47. * muxing functions for use within libavformat
  48. */
  49. /* fraction handling */
  50. /**
  51. * f = val + (num / den) + 0.5.
  52. *
  53. * 'num' is normalized so that it is such as 0 <= num < den.
  54. *
  55. * @param f fractional number
  56. * @param val integer value
  57. * @param num must be >= 0
  58. * @param den must be >= 1
  59. */
  60. static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
  61. {
  62. num += (den >> 1);
  63. if (num >= den) {
  64. val += num / den;
  65. num = num % den;
  66. }
  67. f->val = val;
  68. f->num = num;
  69. f->den = den;
  70. }
  71. /**
  72. * Fractional addition to f: f = f + (incr / f->den).
  73. *
  74. * @param f fractional number
  75. * @param incr increment, can be positive or negative
  76. */
  77. static void frac_add(AVFrac *f, int64_t incr)
  78. {
  79. int64_t num, den;
  80. num = f->num + incr;
  81. den = f->den;
  82. if (num < 0) {
  83. f->val += num / den;
  84. num = num % den;
  85. if (num < 0) {
  86. num += den;
  87. f->val--;
  88. }
  89. } else if (num >= den) {
  90. f->val += num / den;
  91. num = num % den;
  92. }
  93. f->num = num;
  94. }
  95. AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precision)
  96. {
  97. AVRational q;
  98. int j;
  99. q = st->time_base;
  100. for (j=2; j<14; j+= 1+(j>2))
  101. while (q.den / q.num < min_precision && q.num % j == 0)
  102. q.num /= j;
  103. while (q.den / q.num < min_precision && q.den < (1<<24))
  104. q.den <<= 1;
  105. return q;
  106. }
  107. int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
  108. const char *format, const char *filename)
  109. {
  110. AVFormatContext *s = avformat_alloc_context();
  111. int ret = 0;
  112. *avctx = NULL;
  113. if (!s)
  114. goto nomem;
  115. if (!oformat) {
  116. if (format) {
  117. oformat = av_guess_format(format, NULL, NULL);
  118. if (!oformat) {
  119. av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
  120. ret = AVERROR(EINVAL);
  121. goto error;
  122. }
  123. } else {
  124. oformat = av_guess_format(NULL, filename, NULL);
  125. if (!oformat) {
  126. ret = AVERROR(EINVAL);
  127. av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
  128. filename);
  129. goto error;
  130. }
  131. }
  132. }
  133. s->oformat = oformat;
  134. if (s->oformat->priv_data_size > 0) {
  135. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  136. if (!s->priv_data)
  137. goto nomem;
  138. if (s->oformat->priv_class) {
  139. *(const AVClass**)s->priv_data= s->oformat->priv_class;
  140. av_opt_set_defaults(s->priv_data);
  141. }
  142. } else
  143. s->priv_data = NULL;
  144. if (filename)
  145. av_strlcpy(s->filename, filename, sizeof(s->filename));
  146. *avctx = s;
  147. return 0;
  148. nomem:
  149. av_log(s, AV_LOG_ERROR, "Out of memory\n");
  150. ret = AVERROR(ENOMEM);
  151. error:
  152. avformat_free_context(s);
  153. return ret;
  154. }
  155. static int validate_codec_tag(AVFormatContext *s, AVStream *st)
  156. {
  157. const AVCodecTag *avctag;
  158. int n;
  159. enum AVCodecID id = AV_CODEC_ID_NONE;
  160. int64_t tag = -1;
  161. /**
  162. * Check that tag + id is in the table
  163. * If neither is in the table -> OK
  164. * If tag is in the table with another id -> FAIL
  165. * If id is in the table with another tag -> FAIL unless strict < normal
  166. */
  167. for (n = 0; s->oformat->codec_tag[n]; n++) {
  168. avctag = s->oformat->codec_tag[n];
  169. while (avctag->id != AV_CODEC_ID_NONE) {
  170. if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
  171. id = avctag->id;
  172. if (id == st->codec->codec_id)
  173. return 1;
  174. }
  175. if (avctag->id == st->codec->codec_id)
  176. tag = avctag->tag;
  177. avctag++;
  178. }
  179. }
  180. if (id != AV_CODEC_ID_NONE)
  181. return 0;
  182. if (tag >= 0 && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
  183. return 0;
  184. return 1;
  185. }
  186. static int init_muxer(AVFormatContext *s, AVDictionary **options)
  187. {
  188. int ret = 0, i;
  189. AVStream *st;
  190. AVDictionary *tmp = NULL;
  191. AVCodecContext *codec = NULL;
  192. AVOutputFormat *of = s->oformat;
  193. AVDictionaryEntry *e;
  194. if (options)
  195. av_dict_copy(&tmp, *options, 0);
  196. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  197. goto fail;
  198. if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
  199. (ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
  200. goto fail;
  201. #if FF_API_LAVF_BITEXACT
  202. if (s->nb_streams && s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)
  203. s->flags |= AVFMT_FLAG_BITEXACT;
  204. #endif
  205. // some sanity checks
  206. if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
  207. av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
  208. ret = AVERROR(EINVAL);
  209. goto fail;
  210. }
  211. for (i = 0; i < s->nb_streams; i++) {
  212. st = s->streams[i];
  213. codec = st->codec;
  214. #if FF_API_LAVF_CODEC_TB
  215. FF_DISABLE_DEPRECATION_WARNINGS
  216. if (!st->time_base.num && codec->time_base.num) {
  217. av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
  218. "timebase hint to the muxer is deprecated. Set "
  219. "AVStream.time_base instead.\n");
  220. avpriv_set_pts_info(st, 64, codec->time_base.num, codec->time_base.den);
  221. }
  222. FF_ENABLE_DEPRECATION_WARNINGS
  223. #endif
  224. if (!st->time_base.num) {
  225. /* fall back on the default timebase values */
  226. if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->sample_rate)
  227. avpriv_set_pts_info(st, 64, 1, codec->sample_rate);
  228. else
  229. avpriv_set_pts_info(st, 33, 1, 90000);
  230. }
  231. switch (codec->codec_type) {
  232. case AVMEDIA_TYPE_AUDIO:
  233. if (codec->sample_rate <= 0) {
  234. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  235. ret = AVERROR(EINVAL);
  236. goto fail;
  237. }
  238. if (!codec->block_align)
  239. codec->block_align = codec->channels *
  240. av_get_bits_per_sample(codec->codec_id) >> 3;
  241. break;
  242. case AVMEDIA_TYPE_VIDEO:
  243. if ((codec->width <= 0 || codec->height <= 0) &&
  244. !(of->flags & AVFMT_NODIMENSIONS)) {
  245. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  246. ret = AVERROR(EINVAL);
  247. goto fail;
  248. }
  249. if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
  250. && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
  251. ) {
  252. if (st->sample_aspect_ratio.num != 0 &&
  253. st->sample_aspect_ratio.den != 0 &&
  254. codec->sample_aspect_ratio.num != 0 &&
  255. codec->sample_aspect_ratio.den != 0) {
  256. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
  257. "(%d/%d) and encoder layer (%d/%d)\n",
  258. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  259. codec->sample_aspect_ratio.num,
  260. codec->sample_aspect_ratio.den);
  261. ret = AVERROR(EINVAL);
  262. goto fail;
  263. }
  264. }
  265. break;
  266. }
  267. if (of->codec_tag) {
  268. if ( codec->codec_tag
  269. && codec->codec_id == AV_CODEC_ID_RAWVIDEO
  270. && ( av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
  271. || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
  272. && !validate_codec_tag(s, st)) {
  273. // the current rawvideo encoding system ends up setting
  274. // the wrong codec_tag for avi/mov, we override it here
  275. codec->codec_tag = 0;
  276. }
  277. if (codec->codec_tag) {
  278. if (!validate_codec_tag(s, st)) {
  279. char tagbuf[32], tagbuf2[32];
  280. av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
  281. av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
  282. av_log(s, AV_LOG_ERROR,
  283. "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
  284. tagbuf, codec->codec_tag, codec->codec_id, tagbuf2);
  285. ret = AVERROR_INVALIDDATA;
  286. goto fail;
  287. }
  288. } else
  289. codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
  290. }
  291. if (of->flags & AVFMT_GLOBALHEADER &&
  292. !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
  293. av_log(s, AV_LOG_WARNING,
  294. "Codec for stream %d does not use global headers "
  295. "but container format requires global headers\n", i);
  296. if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
  297. s->internal->nb_interleaved_streams++;
  298. }
  299. if (!s->priv_data && of->priv_data_size > 0) {
  300. s->priv_data = av_mallocz(of->priv_data_size);
  301. if (!s->priv_data) {
  302. ret = AVERROR(ENOMEM);
  303. goto fail;
  304. }
  305. if (of->priv_class) {
  306. *(const AVClass **)s->priv_data = of->priv_class;
  307. av_opt_set_defaults(s->priv_data);
  308. if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
  309. goto fail;
  310. }
  311. }
  312. /* set muxer identification string */
  313. if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
  314. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  315. } else {
  316. av_dict_set(&s->metadata, "encoder", NULL, 0);
  317. }
  318. for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {
  319. av_dict_set(&s->metadata, e->key, NULL, 0);
  320. }
  321. if (options) {
  322. av_dict_free(options);
  323. *options = tmp;
  324. }
  325. return 0;
  326. fail:
  327. av_dict_free(&tmp);
  328. return ret;
  329. }
  330. static int init_pts(AVFormatContext *s)
  331. {
  332. int i;
  333. AVStream *st;
  334. /* init PTS generation */
  335. for (i = 0; i < s->nb_streams; i++) {
  336. int64_t den = AV_NOPTS_VALUE;
  337. st = s->streams[i];
  338. switch (st->codec->codec_type) {
  339. case AVMEDIA_TYPE_AUDIO:
  340. den = (int64_t)st->time_base.num * st->codec->sample_rate;
  341. break;
  342. case AVMEDIA_TYPE_VIDEO:
  343. den = (int64_t)st->time_base.num * st->codec->time_base.den;
  344. break;
  345. default:
  346. break;
  347. }
  348. if (den != AV_NOPTS_VALUE) {
  349. if (den <= 0)
  350. return AVERROR_INVALIDDATA;
  351. frac_init(&st->pts, 0, 0, den);
  352. }
  353. }
  354. return 0;
  355. }
  356. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  357. {
  358. int ret = 0;
  359. if (ret = init_muxer(s, options))
  360. return ret;
  361. if (s->oformat->write_header) {
  362. ret = s->oformat->write_header(s);
  363. if (ret >= 0 && s->pb && s->pb->error < 0)
  364. ret = s->pb->error;
  365. if (ret < 0)
  366. return ret;
  367. if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  368. avio_flush(s->pb);
  369. }
  370. if ((ret = init_pts(s)) < 0)
  371. return ret;
  372. if (s->avoid_negative_ts < 0) {
  373. av_assert2(s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO);
  374. if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
  375. s->avoid_negative_ts = 0;
  376. } else
  377. s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
  378. }
  379. return 0;
  380. }
  381. #define AV_PKT_FLAG_UNCODED_FRAME 0x2000
  382. /* Note: using sizeof(AVFrame) from outside lavu is unsafe in general, but
  383. it is only being used internally to this file as a consistency check.
  384. The value is chosen to be very unlikely to appear on its own and to cause
  385. immediate failure if used anywhere as a real size. */
  386. #define UNCODED_FRAME_PACKET_SIZE (INT_MIN / 3 * 2 + (int)sizeof(AVFrame))
  387. //FIXME merge with compute_pkt_fields
  388. static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  389. {
  390. int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
  391. int num, den, i;
  392. int frame_size;
  393. av_log(s, AV_LOG_TRACE, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
  394. av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
  395. if (pkt->duration < 0 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
  396. av_log(s, AV_LOG_WARNING, "Packet with invalid duration %d in stream %d\n",
  397. pkt->duration, pkt->stream_index);
  398. pkt->duration = 0;
  399. }
  400. /* duration field */
  401. if (pkt->duration == 0) {
  402. ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
  403. if (den && num) {
  404. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  405. }
  406. }
  407. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  408. pkt->pts = pkt->dts;
  409. //XXX/FIXME this is a temporary hack until all encoders output pts
  410. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  411. static int warned;
  412. if (!warned) {
  413. av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
  414. warned = 1;
  415. }
  416. pkt->dts =
  417. // pkt->pts= st->cur_dts;
  418. pkt->pts = st->pts.val;
  419. }
  420. //calculate dts from pts
  421. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  422. st->pts_buffer[0] = pkt->pts;
  423. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  424. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  425. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  426. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  427. pkt->dts = st->pts_buffer[0];
  428. }
  429. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  430. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  431. st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE &&
  432. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  433. av_log(s, AV_LOG_ERROR,
  434. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
  435. st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
  436. return AVERROR(EINVAL);
  437. }
  438. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  439. av_log(s, AV_LOG_ERROR,
  440. "pts (%s) < dts (%s) in stream %d\n",
  441. av_ts2str(pkt->pts), av_ts2str(pkt->dts),
  442. st->index);
  443. return AVERROR(EINVAL);
  444. }
  445. av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%s dts2:%s\n",
  446. av_ts2str(pkt->pts), av_ts2str(pkt->dts));
  447. st->cur_dts = pkt->dts;
  448. st->pts.val = pkt->dts;
  449. /* update pts */
  450. switch (st->codec->codec_type) {
  451. case AVMEDIA_TYPE_AUDIO:
  452. frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
  453. ((AVFrame *)pkt->data)->nb_samples :
  454. av_get_audio_frame_duration(st->codec, pkt->size);
  455. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  456. * likely equal to the encoder delay, but it would be better if we
  457. * had the real timestamps from the encoder */
  458. if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
  459. frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  460. }
  461. break;
  462. case AVMEDIA_TYPE_VIDEO:
  463. frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  464. break;
  465. }
  466. return 0;
  467. }
  468. /**
  469. * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  470. * sidedata.
  471. *
  472. * FIXME: this function should NEVER get undefined pts/dts beside when the
  473. * AVFMT_NOTIMESTAMPS is set.
  474. * Those additional safety checks should be dropped once the correct checks
  475. * are set in the callers.
  476. */
  477. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  478. {
  479. int ret, did_split;
  480. if (s->output_ts_offset) {
  481. AVStream *st = s->streams[pkt->stream_index];
  482. int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
  483. if (pkt->dts != AV_NOPTS_VALUE)
  484. pkt->dts += offset;
  485. if (pkt->pts != AV_NOPTS_VALUE)
  486. pkt->pts += offset;
  487. }
  488. if (s->avoid_negative_ts > 0) {
  489. AVStream *st = s->streams[pkt->stream_index];
  490. int64_t offset = st->mux_ts_offset;
  491. if (s->internal->offset == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
  492. (pkt->dts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
  493. s->internal->offset = -pkt->dts;
  494. s->internal->offset_timebase = st->time_base;
  495. }
  496. if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
  497. offset = st->mux_ts_offset =
  498. av_rescale_q_rnd(s->internal->offset,
  499. s->internal->offset_timebase,
  500. st->time_base,
  501. AV_ROUND_UP);
  502. }
  503. if (pkt->dts != AV_NOPTS_VALUE)
  504. pkt->dts += offset;
  505. if (pkt->pts != AV_NOPTS_VALUE)
  506. pkt->pts += offset;
  507. av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0 || s->max_interleave_delta > 0);
  508. if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
  509. av_log(s, AV_LOG_WARNING,
  510. "Packets poorly interleaved, failed to avoid negative "
  511. "timestamp %s in stream %d.\n"
  512. "Try -max_interleave_delta 0 as a possible workaround.\n",
  513. av_ts2str(pkt->dts),
  514. pkt->stream_index
  515. );
  516. }
  517. }
  518. did_split = av_packet_split_side_data(pkt);
  519. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  520. AVFrame *frame = (AVFrame *)pkt->data;
  521. av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
  522. ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
  523. av_frame_free(&frame);
  524. } else {
  525. ret = s->oformat->write_packet(s, pkt);
  526. }
  527. if (s->flush_packets && s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  528. avio_flush(s->pb);
  529. if (did_split)
  530. av_packet_merge_side_data(pkt);
  531. return ret;
  532. }
  533. static int check_packet(AVFormatContext *s, AVPacket *pkt)
  534. {
  535. if (!pkt)
  536. return 0;
  537. if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
  538. av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
  539. pkt->stream_index);
  540. return AVERROR(EINVAL);
  541. }
  542. if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
  543. av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
  544. return AVERROR(EINVAL);
  545. }
  546. return 0;
  547. }
  548. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  549. {
  550. int ret;
  551. ret = check_packet(s, pkt);
  552. if (ret < 0)
  553. return ret;
  554. if (!pkt) {
  555. if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
  556. ret = s->oformat->write_packet(s, NULL);
  557. if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  558. avio_flush(s->pb);
  559. if (ret >= 0 && s->pb && s->pb->error < 0)
  560. ret = s->pb->error;
  561. return ret;
  562. }
  563. return 1;
  564. }
  565. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  566. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  567. return ret;
  568. ret = write_packet(s, pkt);
  569. if (ret >= 0 && s->pb && s->pb->error < 0)
  570. ret = s->pb->error;
  571. if (ret >= 0)
  572. s->streams[pkt->stream_index]->nb_frames++;
  573. return ret;
  574. }
  575. #define CHUNK_START 0x1000
  576. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  577. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  578. {
  579. int ret;
  580. AVPacketList **next_point, *this_pktl;
  581. AVStream *st = s->streams[pkt->stream_index];
  582. int chunked = s->max_chunk_size || s->max_chunk_duration;
  583. this_pktl = av_mallocz(sizeof(AVPacketList));
  584. if (!this_pktl)
  585. return AVERROR(ENOMEM);
  586. this_pktl->pkt = *pkt;
  587. #if FF_API_DESTRUCT_PACKET
  588. FF_DISABLE_DEPRECATION_WARNINGS
  589. pkt->destruct = NULL; // do not free original but only the copy
  590. FF_ENABLE_DEPRECATION_WARNINGS
  591. #endif
  592. pkt->buf = NULL;
  593. pkt->side_data = NULL;
  594. pkt->side_data_elems = 0;
  595. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  596. av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
  597. av_assert0(((AVFrame *)pkt->data)->buf);
  598. } else {
  599. // Duplicate the packet if it uses non-allocated memory
  600. if ((ret = av_dup_packet(&this_pktl->pkt)) < 0) {
  601. av_free(this_pktl);
  602. return ret;
  603. }
  604. }
  605. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  606. next_point = &(st->last_in_packet_buffer->next);
  607. } else {
  608. next_point = &s->internal->packet_buffer;
  609. }
  610. if (chunked) {
  611. uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
  612. st->interleaver_chunk_size += pkt->size;
  613. st->interleaver_chunk_duration += pkt->duration;
  614. if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
  615. || (max && st->interleaver_chunk_duration > max)) {
  616. st->interleaver_chunk_size = 0;
  617. this_pktl->pkt.flags |= CHUNK_START;
  618. if (max && st->interleaver_chunk_duration > max) {
  619. int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
  620. int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
  621. st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
  622. } else
  623. st->interleaver_chunk_duration = 0;
  624. }
  625. }
  626. if (*next_point) {
  627. if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
  628. goto next_non_null;
  629. if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
  630. while ( *next_point
  631. && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
  632. || !compare(s, &(*next_point)->pkt, pkt)))
  633. next_point = &(*next_point)->next;
  634. if (*next_point)
  635. goto next_non_null;
  636. } else {
  637. next_point = &(s->internal->packet_buffer_end->next);
  638. }
  639. }
  640. av_assert1(!*next_point);
  641. s->internal->packet_buffer_end = this_pktl;
  642. next_non_null:
  643. this_pktl->next = *next_point;
  644. s->streams[pkt->stream_index]->last_in_packet_buffer =
  645. *next_point = this_pktl;
  646. return 0;
  647. }
  648. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  649. AVPacket *pkt)
  650. {
  651. AVStream *st = s->streams[pkt->stream_index];
  652. AVStream *st2 = s->streams[next->stream_index];
  653. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  654. st->time_base);
  655. if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
  656. int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO);
  657. int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO);
  658. if (ts == ts2) {
  659. ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
  660. -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
  661. ts2=0;
  662. }
  663. comp= (ts>ts2) - (ts<ts2);
  664. }
  665. if (comp == 0)
  666. return pkt->stream_index < next->stream_index;
  667. return comp > 0;
  668. }
  669. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  670. AVPacket *pkt, int flush)
  671. {
  672. AVPacketList *pktl;
  673. int stream_count = 0;
  674. int noninterleaved_count = 0;
  675. int i, ret;
  676. if (pkt) {
  677. if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
  678. return ret;
  679. }
  680. for (i = 0; i < s->nb_streams; i++) {
  681. if (s->streams[i]->last_in_packet_buffer) {
  682. ++stream_count;
  683. } else if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
  684. s->streams[i]->codec->codec_id != AV_CODEC_ID_VP8 &&
  685. s->streams[i]->codec->codec_id != AV_CODEC_ID_VP9) {
  686. ++noninterleaved_count;
  687. }
  688. }
  689. if (s->internal->nb_interleaved_streams == stream_count)
  690. flush = 1;
  691. if (s->max_interleave_delta > 0 &&
  692. s->internal->packet_buffer &&
  693. !flush &&
  694. s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
  695. ) {
  696. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  697. int64_t delta_dts = INT64_MIN;
  698. int64_t top_dts = av_rescale_q(top_pkt->dts,
  699. s->streams[top_pkt->stream_index]->time_base,
  700. AV_TIME_BASE_Q);
  701. for (i = 0; i < s->nb_streams; i++) {
  702. int64_t last_dts;
  703. const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
  704. if (!last)
  705. continue;
  706. last_dts = av_rescale_q(last->pkt.dts,
  707. s->streams[i]->time_base,
  708. AV_TIME_BASE_Q);
  709. delta_dts = FFMAX(delta_dts, last_dts - top_dts);
  710. }
  711. if (delta_dts > s->max_interleave_delta) {
  712. av_log(s, AV_LOG_DEBUG,
  713. "Delay between the first packet and last packet in the "
  714. "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
  715. delta_dts, s->max_interleave_delta);
  716. flush = 1;
  717. }
  718. }
  719. if (stream_count && flush) {
  720. AVStream *st;
  721. pktl = s->internal->packet_buffer;
  722. *out = pktl->pkt;
  723. st = s->streams[out->stream_index];
  724. s->internal->packet_buffer = pktl->next;
  725. if (!s->internal->packet_buffer)
  726. s->internal->packet_buffer_end = NULL;
  727. if (st->last_in_packet_buffer == pktl)
  728. st->last_in_packet_buffer = NULL;
  729. av_freep(&pktl);
  730. return 1;
  731. } else {
  732. av_init_packet(out);
  733. return 0;
  734. }
  735. }
  736. /**
  737. * Interleave an AVPacket correctly so it can be muxed.
  738. * @param out the interleaved packet will be output here
  739. * @param in the input packet
  740. * @param flush 1 if no further packets are available as input and all
  741. * remaining packets should be output
  742. * @return 1 if a packet was output, 0 if no packet could be output,
  743. * < 0 if an error occurred
  744. */
  745. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  746. {
  747. if (s->oformat->interleave_packet) {
  748. int ret = s->oformat->interleave_packet(s, out, in, flush);
  749. if (in)
  750. av_free_packet(in);
  751. return ret;
  752. } else
  753. return ff_interleave_packet_per_dts(s, out, in, flush);
  754. }
  755. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  756. {
  757. int ret, flush = 0;
  758. ret = check_packet(s, pkt);
  759. if (ret < 0)
  760. goto fail;
  761. if (pkt) {
  762. AVStream *st = s->streams[pkt->stream_index];
  763. av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
  764. pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
  765. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  766. goto fail;
  767. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  768. ret = AVERROR(EINVAL);
  769. goto fail;
  770. }
  771. } else {
  772. av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
  773. flush = 1;
  774. }
  775. for (;; ) {
  776. AVPacket opkt;
  777. int ret = interleave_packet(s, &opkt, pkt, flush);
  778. if (pkt) {
  779. memset(pkt, 0, sizeof(*pkt));
  780. av_init_packet(pkt);
  781. pkt = NULL;
  782. }
  783. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  784. return ret;
  785. ret = write_packet(s, &opkt);
  786. if (ret >= 0)
  787. s->streams[opkt.stream_index]->nb_frames++;
  788. av_free_packet(&opkt);
  789. if (ret < 0)
  790. return ret;
  791. if(s->pb && s->pb->error)
  792. return s->pb->error;
  793. }
  794. fail:
  795. av_packet_unref(pkt);
  796. return ret;
  797. }
  798. int av_write_trailer(AVFormatContext *s)
  799. {
  800. int ret, i;
  801. for (;; ) {
  802. AVPacket pkt;
  803. ret = interleave_packet(s, &pkt, NULL, 1);
  804. if (ret < 0)
  805. goto fail;
  806. if (!ret)
  807. break;
  808. ret = write_packet(s, &pkt);
  809. if (ret >= 0)
  810. s->streams[pkt.stream_index]->nb_frames++;
  811. av_free_packet(&pkt);
  812. if (ret < 0)
  813. goto fail;
  814. if(s->pb && s->pb->error)
  815. goto fail;
  816. }
  817. fail:
  818. if (s->oformat->write_trailer)
  819. if (ret >= 0) {
  820. ret = s->oformat->write_trailer(s);
  821. } else {
  822. s->oformat->write_trailer(s);
  823. }
  824. if (s->pb)
  825. avio_flush(s->pb);
  826. if (ret == 0)
  827. ret = s->pb ? s->pb->error : 0;
  828. for (i = 0; i < s->nb_streams; i++) {
  829. av_freep(&s->streams[i]->priv_data);
  830. av_freep(&s->streams[i]->index_entries);
  831. }
  832. if (s->oformat->priv_class)
  833. av_opt_free(s->priv_data);
  834. av_freep(&s->priv_data);
  835. return ret;
  836. }
  837. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  838. int64_t *dts, int64_t *wall)
  839. {
  840. if (!s->oformat || !s->oformat->get_output_timestamp)
  841. return AVERROR(ENOSYS);
  842. s->oformat->get_output_timestamp(s, stream, dts, wall);
  843. return 0;
  844. }
  845. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  846. AVFormatContext *src, int interleave)
  847. {
  848. AVPacket local_pkt;
  849. int ret;
  850. local_pkt = *pkt;
  851. local_pkt.stream_index = dst_stream;
  852. if (pkt->pts != AV_NOPTS_VALUE)
  853. local_pkt.pts = av_rescale_q(pkt->pts,
  854. src->streams[pkt->stream_index]->time_base,
  855. dst->streams[dst_stream]->time_base);
  856. if (pkt->dts != AV_NOPTS_VALUE)
  857. local_pkt.dts = av_rescale_q(pkt->dts,
  858. src->streams[pkt->stream_index]->time_base,
  859. dst->streams[dst_stream]->time_base);
  860. if (pkt->duration)
  861. local_pkt.duration = av_rescale_q(pkt->duration,
  862. src->streams[pkt->stream_index]->time_base,
  863. dst->streams[dst_stream]->time_base);
  864. if (interleave) ret = av_interleaved_write_frame(dst, &local_pkt);
  865. else ret = av_write_frame(dst, &local_pkt);
  866. pkt->buf = local_pkt.buf;
  867. pkt->destruct = local_pkt.destruct;
  868. return ret;
  869. }
  870. static int av_write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
  871. AVFrame *frame, int interleaved)
  872. {
  873. AVPacket pkt, *pktp;
  874. av_assert0(s->oformat);
  875. if (!s->oformat->write_uncoded_frame)
  876. return AVERROR(ENOSYS);
  877. if (!frame) {
  878. pktp = NULL;
  879. } else {
  880. pktp = &pkt;
  881. av_init_packet(&pkt);
  882. pkt.data = (void *)frame;
  883. pkt.size = UNCODED_FRAME_PACKET_SIZE;
  884. pkt.pts =
  885. pkt.dts = frame->pts;
  886. pkt.duration = av_frame_get_pkt_duration(frame);
  887. pkt.stream_index = stream_index;
  888. pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
  889. }
  890. return interleaved ? av_interleaved_write_frame(s, pktp) :
  891. av_write_frame(s, pktp);
  892. }
  893. int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
  894. AVFrame *frame)
  895. {
  896. return av_write_uncoded_frame_internal(s, stream_index, frame, 0);
  897. }
  898. int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
  899. AVFrame *frame)
  900. {
  901. return av_write_uncoded_frame_internal(s, stream_index, frame, 1);
  902. }
  903. int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
  904. {
  905. av_assert0(s->oformat);
  906. if (!s->oformat->write_uncoded_frame)
  907. return AVERROR(ENOSYS);
  908. return s->oformat->write_uncoded_frame(s, stream_index, NULL,
  909. AV_WRITE_UNCODED_FRAME_QUERY);
  910. }