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.

1067 lines
35KB

  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)) < 0)
  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. if (s->debug & FF_FDEBUG_TS)
  394. av_log(s, AV_LOG_TRACE, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
  395. av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
  396. if (pkt->duration < 0 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
  397. av_log(s, AV_LOG_WARNING, "Packet with invalid duration %d in stream %d\n",
  398. pkt->duration, pkt->stream_index);
  399. pkt->duration = 0;
  400. }
  401. /* duration field */
  402. if (pkt->duration == 0) {
  403. ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
  404. if (den && num) {
  405. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  406. }
  407. }
  408. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  409. pkt->pts = pkt->dts;
  410. //XXX/FIXME this is a temporary hack until all encoders output pts
  411. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  412. static int warned;
  413. if (!warned) {
  414. av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
  415. warned = 1;
  416. }
  417. pkt->dts =
  418. // pkt->pts= st->cur_dts;
  419. pkt->pts = st->pts.val;
  420. }
  421. //calculate dts from pts
  422. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  423. st->pts_buffer[0] = pkt->pts;
  424. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  425. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  426. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  427. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  428. pkt->dts = st->pts_buffer[0];
  429. }
  430. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  431. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  432. st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE &&
  433. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  434. av_log(s, AV_LOG_ERROR,
  435. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
  436. st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
  437. return AVERROR(EINVAL);
  438. }
  439. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  440. av_log(s, AV_LOG_ERROR,
  441. "pts (%s) < dts (%s) in stream %d\n",
  442. av_ts2str(pkt->pts), av_ts2str(pkt->dts),
  443. st->index);
  444. return AVERROR(EINVAL);
  445. }
  446. if (s->debug & FF_FDEBUG_TS)
  447. av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%s dts2:%s\n",
  448. av_ts2str(pkt->pts), av_ts2str(pkt->dts));
  449. st->cur_dts = pkt->dts;
  450. st->pts.val = pkt->dts;
  451. /* update pts */
  452. switch (st->codec->codec_type) {
  453. case AVMEDIA_TYPE_AUDIO:
  454. frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
  455. ((AVFrame *)pkt->data)->nb_samples :
  456. av_get_audio_frame_duration(st->codec, pkt->size);
  457. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  458. * likely equal to the encoder delay, but it would be better if we
  459. * had the real timestamps from the encoder */
  460. if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
  461. frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  462. }
  463. break;
  464. case AVMEDIA_TYPE_VIDEO:
  465. frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  466. break;
  467. }
  468. return 0;
  469. }
  470. /**
  471. * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  472. * sidedata.
  473. *
  474. * FIXME: this function should NEVER get undefined pts/dts beside when the
  475. * AVFMT_NOTIMESTAMPS is set.
  476. * Those additional safety checks should be dropped once the correct checks
  477. * are set in the callers.
  478. */
  479. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  480. {
  481. int ret, did_split;
  482. if (s->output_ts_offset) {
  483. AVStream *st = s->streams[pkt->stream_index];
  484. int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
  485. if (pkt->dts != AV_NOPTS_VALUE)
  486. pkt->dts += offset;
  487. if (pkt->pts != AV_NOPTS_VALUE)
  488. pkt->pts += offset;
  489. }
  490. if (s->avoid_negative_ts > 0) {
  491. AVStream *st = s->streams[pkt->stream_index];
  492. int64_t offset = st->mux_ts_offset;
  493. int64_t ts = s->internal->avoid_negative_ts_use_pts ? pkt->pts : pkt->dts;
  494. if (s->internal->offset == AV_NOPTS_VALUE && ts != AV_NOPTS_VALUE &&
  495. (ts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
  496. s->internal->offset = -ts;
  497. s->internal->offset_timebase = st->time_base;
  498. }
  499. if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
  500. offset = st->mux_ts_offset =
  501. av_rescale_q_rnd(s->internal->offset,
  502. s->internal->offset_timebase,
  503. st->time_base,
  504. AV_ROUND_UP);
  505. }
  506. if (pkt->dts != AV_NOPTS_VALUE)
  507. pkt->dts += offset;
  508. if (pkt->pts != AV_NOPTS_VALUE)
  509. pkt->pts += offset;
  510. if (s->internal->avoid_negative_ts_use_pts) {
  511. if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
  512. av_log(s, AV_LOG_WARNING, "failed to avoid negative "
  513. "pts %s in stream %d.\n"
  514. "Try -avoid_negative_ts 1 as a possible workaround.\n",
  515. av_ts2str(pkt->dts),
  516. pkt->stream_index
  517. );
  518. }
  519. } else {
  520. av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0 || s->max_interleave_delta > 0);
  521. if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
  522. av_log(s, AV_LOG_WARNING,
  523. "Packets poorly interleaved, failed to avoid negative "
  524. "timestamp %s in stream %d.\n"
  525. "Try -max_interleave_delta 0 as a possible workaround.\n",
  526. av_ts2str(pkt->dts),
  527. pkt->stream_index
  528. );
  529. }
  530. }
  531. }
  532. did_split = av_packet_split_side_data(pkt);
  533. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  534. AVFrame *frame = (AVFrame *)pkt->data;
  535. av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
  536. ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
  537. av_frame_free(&frame);
  538. } else {
  539. ret = s->oformat->write_packet(s, pkt);
  540. }
  541. if (s->flush_packets && s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  542. avio_flush(s->pb);
  543. if (did_split)
  544. av_packet_merge_side_data(pkt);
  545. return ret;
  546. }
  547. static int check_packet(AVFormatContext *s, AVPacket *pkt)
  548. {
  549. if (!pkt)
  550. return 0;
  551. if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
  552. av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
  553. pkt->stream_index);
  554. return AVERROR(EINVAL);
  555. }
  556. if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
  557. av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
  558. return AVERROR(EINVAL);
  559. }
  560. return 0;
  561. }
  562. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  563. {
  564. int ret;
  565. ret = check_packet(s, pkt);
  566. if (ret < 0)
  567. return ret;
  568. if (!pkt) {
  569. if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
  570. ret = s->oformat->write_packet(s, NULL);
  571. if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  572. avio_flush(s->pb);
  573. if (ret >= 0 && s->pb && s->pb->error < 0)
  574. ret = s->pb->error;
  575. return ret;
  576. }
  577. return 1;
  578. }
  579. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  580. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  581. return ret;
  582. ret = write_packet(s, pkt);
  583. if (ret >= 0 && s->pb && s->pb->error < 0)
  584. ret = s->pb->error;
  585. if (ret >= 0)
  586. s->streams[pkt->stream_index]->nb_frames++;
  587. return ret;
  588. }
  589. #define CHUNK_START 0x1000
  590. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  591. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  592. {
  593. int ret;
  594. AVPacketList **next_point, *this_pktl;
  595. AVStream *st = s->streams[pkt->stream_index];
  596. int chunked = s->max_chunk_size || s->max_chunk_duration;
  597. this_pktl = av_mallocz(sizeof(AVPacketList));
  598. if (!this_pktl)
  599. return AVERROR(ENOMEM);
  600. this_pktl->pkt = *pkt;
  601. #if FF_API_DESTRUCT_PACKET
  602. FF_DISABLE_DEPRECATION_WARNINGS
  603. pkt->destruct = NULL; // do not free original but only the copy
  604. FF_ENABLE_DEPRECATION_WARNINGS
  605. #endif
  606. pkt->buf = NULL;
  607. pkt->side_data = NULL;
  608. pkt->side_data_elems = 0;
  609. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  610. av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
  611. av_assert0(((AVFrame *)pkt->data)->buf);
  612. } else {
  613. // Duplicate the packet if it uses non-allocated memory
  614. if ((ret = av_dup_packet(&this_pktl->pkt)) < 0) {
  615. av_free(this_pktl);
  616. return ret;
  617. }
  618. }
  619. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  620. next_point = &(st->last_in_packet_buffer->next);
  621. } else {
  622. next_point = &s->internal->packet_buffer;
  623. }
  624. if (chunked) {
  625. uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
  626. st->interleaver_chunk_size += pkt->size;
  627. st->interleaver_chunk_duration += pkt->duration;
  628. if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
  629. || (max && st->interleaver_chunk_duration > max)) {
  630. st->interleaver_chunk_size = 0;
  631. this_pktl->pkt.flags |= CHUNK_START;
  632. if (max && st->interleaver_chunk_duration > max) {
  633. int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
  634. int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
  635. st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
  636. } else
  637. st->interleaver_chunk_duration = 0;
  638. }
  639. }
  640. if (*next_point) {
  641. if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
  642. goto next_non_null;
  643. if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
  644. while ( *next_point
  645. && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
  646. || !compare(s, &(*next_point)->pkt, pkt)))
  647. next_point = &(*next_point)->next;
  648. if (*next_point)
  649. goto next_non_null;
  650. } else {
  651. next_point = &(s->internal->packet_buffer_end->next);
  652. }
  653. }
  654. av_assert1(!*next_point);
  655. s->internal->packet_buffer_end = this_pktl;
  656. next_non_null:
  657. this_pktl->next = *next_point;
  658. s->streams[pkt->stream_index]->last_in_packet_buffer =
  659. *next_point = this_pktl;
  660. return 0;
  661. }
  662. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  663. AVPacket *pkt)
  664. {
  665. AVStream *st = s->streams[pkt->stream_index];
  666. AVStream *st2 = s->streams[next->stream_index];
  667. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  668. st->time_base);
  669. if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
  670. 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);
  671. 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);
  672. if (ts == ts2) {
  673. 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
  674. -( 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;
  675. ts2=0;
  676. }
  677. comp= (ts>ts2) - (ts<ts2);
  678. }
  679. if (comp == 0)
  680. return pkt->stream_index < next->stream_index;
  681. return comp > 0;
  682. }
  683. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  684. AVPacket *pkt, int flush)
  685. {
  686. AVPacketList *pktl;
  687. int stream_count = 0;
  688. int noninterleaved_count = 0;
  689. int i, ret;
  690. if (pkt) {
  691. if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
  692. return ret;
  693. }
  694. for (i = 0; i < s->nb_streams; i++) {
  695. if (s->streams[i]->last_in_packet_buffer) {
  696. ++stream_count;
  697. } else if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
  698. s->streams[i]->codec->codec_id != AV_CODEC_ID_VP8 &&
  699. s->streams[i]->codec->codec_id != AV_CODEC_ID_VP9) {
  700. ++noninterleaved_count;
  701. }
  702. }
  703. if (s->internal->nb_interleaved_streams == stream_count)
  704. flush = 1;
  705. if (s->max_interleave_delta > 0 &&
  706. s->internal->packet_buffer &&
  707. !flush &&
  708. s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
  709. ) {
  710. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  711. int64_t delta_dts = INT64_MIN;
  712. int64_t top_dts = av_rescale_q(top_pkt->dts,
  713. s->streams[top_pkt->stream_index]->time_base,
  714. AV_TIME_BASE_Q);
  715. for (i = 0; i < s->nb_streams; i++) {
  716. int64_t last_dts;
  717. const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
  718. if (!last)
  719. continue;
  720. last_dts = av_rescale_q(last->pkt.dts,
  721. s->streams[i]->time_base,
  722. AV_TIME_BASE_Q);
  723. delta_dts = FFMAX(delta_dts, last_dts - top_dts);
  724. }
  725. if (delta_dts > s->max_interleave_delta) {
  726. av_log(s, AV_LOG_DEBUG,
  727. "Delay between the first packet and last packet in the "
  728. "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
  729. delta_dts, s->max_interleave_delta);
  730. flush = 1;
  731. }
  732. }
  733. if (stream_count && flush) {
  734. AVStream *st;
  735. pktl = s->internal->packet_buffer;
  736. *out = pktl->pkt;
  737. st = s->streams[out->stream_index];
  738. s->internal->packet_buffer = pktl->next;
  739. if (!s->internal->packet_buffer)
  740. s->internal->packet_buffer_end = NULL;
  741. if (st->last_in_packet_buffer == pktl)
  742. st->last_in_packet_buffer = NULL;
  743. av_freep(&pktl);
  744. return 1;
  745. } else {
  746. av_init_packet(out);
  747. return 0;
  748. }
  749. }
  750. /**
  751. * Interleave an AVPacket correctly so it can be muxed.
  752. * @param out the interleaved packet will be output here
  753. * @param in the input packet
  754. * @param flush 1 if no further packets are available as input and all
  755. * remaining packets should be output
  756. * @return 1 if a packet was output, 0 if no packet could be output,
  757. * < 0 if an error occurred
  758. */
  759. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  760. {
  761. if (s->oformat->interleave_packet) {
  762. int ret = s->oformat->interleave_packet(s, out, in, flush);
  763. if (in)
  764. av_free_packet(in);
  765. return ret;
  766. } else
  767. return ff_interleave_packet_per_dts(s, out, in, flush);
  768. }
  769. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  770. {
  771. int ret, flush = 0;
  772. ret = check_packet(s, pkt);
  773. if (ret < 0)
  774. goto fail;
  775. if (pkt) {
  776. AVStream *st = s->streams[pkt->stream_index];
  777. if (s->debug & FF_FDEBUG_TS)
  778. av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
  779. pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
  780. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  781. goto fail;
  782. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  783. ret = AVERROR(EINVAL);
  784. goto fail;
  785. }
  786. } else {
  787. av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
  788. flush = 1;
  789. }
  790. for (;; ) {
  791. AVPacket opkt;
  792. int ret = interleave_packet(s, &opkt, pkt, flush);
  793. if (pkt) {
  794. memset(pkt, 0, sizeof(*pkt));
  795. av_init_packet(pkt);
  796. pkt = NULL;
  797. }
  798. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  799. return ret;
  800. ret = write_packet(s, &opkt);
  801. if (ret >= 0)
  802. s->streams[opkt.stream_index]->nb_frames++;
  803. av_free_packet(&opkt);
  804. if (ret < 0)
  805. return ret;
  806. if(s->pb && s->pb->error)
  807. return s->pb->error;
  808. }
  809. fail:
  810. av_packet_unref(pkt);
  811. return ret;
  812. }
  813. int av_write_trailer(AVFormatContext *s)
  814. {
  815. int ret, i;
  816. for (;; ) {
  817. AVPacket pkt;
  818. ret = interleave_packet(s, &pkt, NULL, 1);
  819. if (ret < 0)
  820. goto fail;
  821. if (!ret)
  822. break;
  823. ret = write_packet(s, &pkt);
  824. if (ret >= 0)
  825. s->streams[pkt.stream_index]->nb_frames++;
  826. av_free_packet(&pkt);
  827. if (ret < 0)
  828. goto fail;
  829. if(s->pb && s->pb->error)
  830. goto fail;
  831. }
  832. fail:
  833. if (s->oformat->write_trailer)
  834. if (ret >= 0) {
  835. ret = s->oformat->write_trailer(s);
  836. } else {
  837. s->oformat->write_trailer(s);
  838. }
  839. if (s->pb)
  840. avio_flush(s->pb);
  841. if (ret == 0)
  842. ret = s->pb ? s->pb->error : 0;
  843. for (i = 0; i < s->nb_streams; i++) {
  844. av_freep(&s->streams[i]->priv_data);
  845. av_freep(&s->streams[i]->index_entries);
  846. }
  847. if (s->oformat->priv_class)
  848. av_opt_free(s->priv_data);
  849. av_freep(&s->priv_data);
  850. return ret;
  851. }
  852. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  853. int64_t *dts, int64_t *wall)
  854. {
  855. if (!s->oformat || !s->oformat->get_output_timestamp)
  856. return AVERROR(ENOSYS);
  857. s->oformat->get_output_timestamp(s, stream, dts, wall);
  858. return 0;
  859. }
  860. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  861. AVFormatContext *src, int interleave)
  862. {
  863. AVPacket local_pkt;
  864. int ret;
  865. local_pkt = *pkt;
  866. local_pkt.stream_index = dst_stream;
  867. if (pkt->pts != AV_NOPTS_VALUE)
  868. local_pkt.pts = av_rescale_q(pkt->pts,
  869. src->streams[pkt->stream_index]->time_base,
  870. dst->streams[dst_stream]->time_base);
  871. if (pkt->dts != AV_NOPTS_VALUE)
  872. local_pkt.dts = av_rescale_q(pkt->dts,
  873. src->streams[pkt->stream_index]->time_base,
  874. dst->streams[dst_stream]->time_base);
  875. if (pkt->duration)
  876. local_pkt.duration = av_rescale_q(pkt->duration,
  877. src->streams[pkt->stream_index]->time_base,
  878. dst->streams[dst_stream]->time_base);
  879. if (interleave) ret = av_interleaved_write_frame(dst, &local_pkt);
  880. else ret = av_write_frame(dst, &local_pkt);
  881. pkt->buf = local_pkt.buf;
  882. pkt->destruct = local_pkt.destruct;
  883. return ret;
  884. }
  885. static int av_write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
  886. AVFrame *frame, int interleaved)
  887. {
  888. AVPacket pkt, *pktp;
  889. av_assert0(s->oformat);
  890. if (!s->oformat->write_uncoded_frame)
  891. return AVERROR(ENOSYS);
  892. if (!frame) {
  893. pktp = NULL;
  894. } else {
  895. pktp = &pkt;
  896. av_init_packet(&pkt);
  897. pkt.data = (void *)frame;
  898. pkt.size = UNCODED_FRAME_PACKET_SIZE;
  899. pkt.pts =
  900. pkt.dts = frame->pts;
  901. pkt.duration = av_frame_get_pkt_duration(frame);
  902. pkt.stream_index = stream_index;
  903. pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
  904. }
  905. return interleaved ? av_interleaved_write_frame(s, pktp) :
  906. av_write_frame(s, pktp);
  907. }
  908. int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
  909. AVFrame *frame)
  910. {
  911. return av_write_uncoded_frame_internal(s, stream_index, frame, 0);
  912. }
  913. int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
  914. AVFrame *frame)
  915. {
  916. return av_write_uncoded_frame_internal(s, stream_index, frame, 1);
  917. }
  918. int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
  919. {
  920. av_assert0(s->oformat);
  921. if (!s->oformat->write_uncoded_frame)
  922. return AVERROR(ENOSYS);
  923. return s->oformat->write_uncoded_frame(s, stream_index, NULL,
  924. AV_WRITE_UNCODED_FRAME_QUERY);
  925. }