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.

1103 lines
36KB

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