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.

1016 lines
32KB

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