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.

1017 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_dict(s->priv_data, &tmp)) < 0)
  214. goto fail;
  215. // some sanity checks
  216. if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
  217. av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
  218. ret = AVERROR(EINVAL);
  219. goto fail;
  220. }
  221. for (i = 0; i < s->nb_streams; i++) {
  222. st = s->streams[i];
  223. codec = st->codec;
  224. switch (codec->codec_type) {
  225. case AVMEDIA_TYPE_AUDIO:
  226. if (codec->sample_rate <= 0) {
  227. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  228. ret = AVERROR(EINVAL);
  229. goto fail;
  230. }
  231. if (!codec->block_align)
  232. codec->block_align = codec->channels *
  233. av_get_bits_per_sample(codec->codec_id) >> 3;
  234. break;
  235. case AVMEDIA_TYPE_VIDEO:
  236. if (codec->time_base.num <= 0 ||
  237. codec->time_base.den <= 0) { //FIXME audio too?
  238. av_log(s, AV_LOG_ERROR, "time base not set\n");
  239. ret = AVERROR(EINVAL);
  240. goto fail;
  241. }
  242. if ((codec->width <= 0 || codec->height <= 0) &&
  243. !(of->flags & AVFMT_NODIMENSIONS)) {
  244. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  245. ret = AVERROR(EINVAL);
  246. goto fail;
  247. }
  248. if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
  249. && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
  250. ) {
  251. if (st->sample_aspect_ratio.num != 0 &&
  252. st->sample_aspect_ratio.den != 0 &&
  253. codec->sample_aspect_ratio.den != 0 &&
  254. codec->sample_aspect_ratio.den != 0) {
  255. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
  256. "(%d/%d) and encoder layer (%d/%d)\n",
  257. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  258. codec->sample_aspect_ratio.num,
  259. codec->sample_aspect_ratio.den);
  260. ret = AVERROR(EINVAL);
  261. goto fail;
  262. }
  263. }
  264. break;
  265. }
  266. if (of->codec_tag) {
  267. if ( codec->codec_tag
  268. && codec->codec_id == AV_CODEC_ID_RAWVIDEO
  269. && ( av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
  270. || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
  271. && !validate_codec_tag(s, st)) {
  272. // the current rawvideo encoding system ends up setting
  273. // the wrong codec_tag for avi/mov, we override it here
  274. codec->codec_tag = 0;
  275. }
  276. if (codec->codec_tag) {
  277. if (!validate_codec_tag(s, st)) {
  278. char tagbuf[32], tagbuf2[32];
  279. av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
  280. av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
  281. av_log(s, AV_LOG_ERROR,
  282. "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
  283. tagbuf, codec->codec_tag, codec->codec_id, tagbuf2);
  284. ret = AVERROR_INVALIDDATA;
  285. goto fail;
  286. }
  287. } else
  288. codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
  289. }
  290. if (of->flags & AVFMT_GLOBALHEADER &&
  291. !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
  292. av_log(s, AV_LOG_WARNING,
  293. "Codec for stream %d does not use global headers "
  294. "but container format requires global headers\n", i);
  295. if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
  296. s->internal->nb_interleaved_streams++;
  297. }
  298. if (!s->priv_data && of->priv_data_size > 0) {
  299. s->priv_data = av_mallocz(of->priv_data_size);
  300. if (!s->priv_data) {
  301. ret = AVERROR(ENOMEM);
  302. goto fail;
  303. }
  304. if (of->priv_class) {
  305. *(const AVClass **)s->priv_data = of->priv_class;
  306. av_opt_set_defaults(s->priv_data);
  307. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  308. goto fail;
  309. }
  310. }
  311. /* set muxer identification string */
  312. if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  313. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  314. } else {
  315. av_dict_set(&s->metadata, "encoder", NULL, 0);
  316. }
  317. if (options) {
  318. av_dict_free(options);
  319. *options = tmp;
  320. }
  321. return 0;
  322. fail:
  323. av_dict_free(&tmp);
  324. return ret;
  325. }
  326. static int init_pts(AVFormatContext *s)
  327. {
  328. int i;
  329. AVStream *st;
  330. /* init PTS generation */
  331. for (i = 0; i < s->nb_streams; i++) {
  332. int64_t den = AV_NOPTS_VALUE;
  333. st = s->streams[i];
  334. switch (st->codec->codec_type) {
  335. case AVMEDIA_TYPE_AUDIO:
  336. den = (int64_t)st->time_base.num * st->codec->sample_rate;
  337. break;
  338. case AVMEDIA_TYPE_VIDEO:
  339. den = (int64_t)st->time_base.num * st->codec->time_base.den;
  340. break;
  341. default:
  342. break;
  343. }
  344. if (den != AV_NOPTS_VALUE) {
  345. if (den <= 0)
  346. return AVERROR_INVALIDDATA;
  347. frac_init(&st->pts, 0, 0, den);
  348. }
  349. }
  350. return 0;
  351. }
  352. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  353. {
  354. int ret = 0;
  355. if (ret = init_muxer(s, options))
  356. return ret;
  357. if (s->oformat->write_header) {
  358. ret = s->oformat->write_header(s);
  359. if (ret >= 0 && s->pb && s->pb->error < 0)
  360. ret = s->pb->error;
  361. if (ret < 0)
  362. return ret;
  363. }
  364. if ((ret = init_pts(s)) < 0)
  365. return ret;
  366. if (s->avoid_negative_ts < 0) {
  367. if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
  368. s->avoid_negative_ts = 0;
  369. } else
  370. s->avoid_negative_ts = 1;
  371. }
  372. return 0;
  373. }
  374. #define AV_PKT_FLAG_UNCODED_FRAME 0x2000
  375. /* Note: using sizeof(AVFrame) from outside lavu is unsafe in general, but
  376. it is only being used internally to this file as a consistency check.
  377. The value is chosen to be very unlikely to appear on its own and to cause
  378. immediate failure if used anywhere as a real size. */
  379. #define UNCODED_FRAME_PACKET_SIZE (INT_MIN / 3 * 2 + (int)sizeof(AVFrame))
  380. //FIXME merge with compute_pkt_fields
  381. static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  382. {
  383. int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
  384. int num, den, frame_size, i;
  385. av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
  386. av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
  387. if (pkt->duration < 0 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
  388. av_log(s, AV_LOG_WARNING, "Packet with invalid duration %d in stream %d\n",
  389. pkt->duration, pkt->stream_index);
  390. pkt->duration = 0;
  391. }
  392. /* duration field */
  393. if (pkt->duration == 0) {
  394. ff_compute_frame_duration(&num, &den, st, NULL, pkt);
  395. if (den && num) {
  396. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  397. }
  398. }
  399. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  400. pkt->pts = pkt->dts;
  401. //XXX/FIXME this is a temporary hack until all encoders output pts
  402. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  403. static int warned;
  404. if (!warned) {
  405. av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
  406. warned = 1;
  407. }
  408. pkt->dts =
  409. // pkt->pts= st->cur_dts;
  410. pkt->pts = st->pts.val;
  411. }
  412. //calculate dts from pts
  413. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  414. st->pts_buffer[0] = pkt->pts;
  415. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  416. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  417. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  418. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  419. pkt->dts = st->pts_buffer[0];
  420. }
  421. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  422. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  423. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  424. av_log(s, AV_LOG_ERROR,
  425. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
  426. st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
  427. return AVERROR(EINVAL);
  428. }
  429. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  430. av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
  431. av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
  432. return AVERROR(EINVAL);
  433. }
  434. av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
  435. av_ts2str(pkt->pts), av_ts2str(pkt->dts));
  436. st->cur_dts = pkt->dts;
  437. st->pts.val = pkt->dts;
  438. /* update pts */
  439. switch (st->codec->codec_type) {
  440. case AVMEDIA_TYPE_AUDIO:
  441. frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
  442. ((AVFrame *)pkt->data)->nb_samples :
  443. ff_get_audio_frame_size(st->codec, pkt->size, 1);
  444. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  445. * likely equal to the encoder delay, but it would be better if we
  446. * had the real timestamps from the encoder */
  447. if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
  448. frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  449. }
  450. break;
  451. case AVMEDIA_TYPE_VIDEO:
  452. frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  453. break;
  454. default:
  455. break;
  456. }
  457. return 0;
  458. }
  459. /**
  460. * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  461. * sidedata.
  462. *
  463. * FIXME: this function should NEVER get undefined pts/dts beside when the
  464. * AVFMT_NOTIMESTAMPS is set.
  465. * Those additional safety checks should be dropped once the correct checks
  466. * are set in the callers.
  467. */
  468. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  469. {
  470. int ret, did_split;
  471. if (s->output_ts_offset) {
  472. AVStream *st = s->streams[pkt->stream_index];
  473. int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
  474. if (pkt->dts != AV_NOPTS_VALUE)
  475. pkt->dts += offset;
  476. if (pkt->pts != AV_NOPTS_VALUE)
  477. pkt->pts += offset;
  478. }
  479. if (s->avoid_negative_ts > 0) {
  480. AVStream *st = s->streams[pkt->stream_index];
  481. int64_t offset = st->mux_ts_offset;
  482. if ((pkt->dts < 0 || s->avoid_negative_ts == 2) && pkt->dts != AV_NOPTS_VALUE && !s->offset) {
  483. s->offset = -pkt->dts;
  484. s->offset_timebase = st->time_base;
  485. }
  486. if (s->offset && !offset) {
  487. offset = st->mux_ts_offset =
  488. av_rescale_q_rnd(s->offset,
  489. s->offset_timebase,
  490. st->time_base,
  491. AV_ROUND_UP);
  492. }
  493. if (pkt->dts != AV_NOPTS_VALUE)
  494. pkt->dts += offset;
  495. if (pkt->pts != AV_NOPTS_VALUE)
  496. pkt->pts += offset;
  497. av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0);
  498. }
  499. did_split = av_packet_split_side_data(pkt);
  500. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  501. AVFrame *frame = (AVFrame *)pkt->data;
  502. av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
  503. ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
  504. av_frame_free(&frame);
  505. } else {
  506. ret = s->oformat->write_packet(s, pkt);
  507. }
  508. if (s->flush_packets && s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  509. avio_flush(s->pb);
  510. if (did_split)
  511. av_packet_merge_side_data(pkt);
  512. return ret;
  513. }
  514. static int check_packet(AVFormatContext *s, AVPacket *pkt)
  515. {
  516. if (!pkt)
  517. return 0;
  518. if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
  519. av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
  520. pkt->stream_index);
  521. return AVERROR(EINVAL);
  522. }
  523. if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
  524. av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
  525. return AVERROR(EINVAL);
  526. }
  527. return 0;
  528. }
  529. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  530. {
  531. int ret;
  532. ret = check_packet(s, pkt);
  533. if (ret < 0)
  534. return ret;
  535. if (!pkt) {
  536. if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
  537. ret = s->oformat->write_packet(s, NULL);
  538. if (s->flush_packets && s->pb && s->pb->error >= 0)
  539. avio_flush(s->pb);
  540. if (ret >= 0 && s->pb && s->pb->error < 0)
  541. ret = s->pb->error;
  542. return ret;
  543. }
  544. return 1;
  545. }
  546. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  547. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  548. return ret;
  549. ret = write_packet(s, pkt);
  550. if (ret >= 0 && s->pb && s->pb->error < 0)
  551. ret = s->pb->error;
  552. if (ret >= 0)
  553. s->streams[pkt->stream_index]->nb_frames++;
  554. return ret;
  555. }
  556. #define CHUNK_START 0x1000
  557. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  558. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  559. {
  560. AVPacketList **next_point, *this_pktl;
  561. AVStream *st = s->streams[pkt->stream_index];
  562. int chunked = s->max_chunk_size || s->max_chunk_duration;
  563. int ret;
  564. this_pktl = av_mallocz(sizeof(AVPacketList));
  565. if (!this_pktl)
  566. return AVERROR(ENOMEM);
  567. this_pktl->pkt = *pkt;
  568. #if FF_API_DESTRUCT_PACKET
  569. FF_DISABLE_DEPRECATION_WARNINGS
  570. pkt->destruct = NULL; // do not free original but only the copy
  571. FF_ENABLE_DEPRECATION_WARNINGS
  572. #endif
  573. pkt->buf = NULL;
  574. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  575. av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
  576. av_assert0(((AVFrame *)pkt->data)->buf);
  577. } else {
  578. // duplicate the packet if it uses non-allocated memory
  579. if ((ret = av_dup_packet(&this_pktl->pkt)) < 0) {
  580. av_free(this_pktl);
  581. return ret;
  582. }
  583. av_copy_packet_side_data(&this_pktl->pkt, &this_pktl->pkt); // copy side data
  584. }
  585. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  586. next_point = &(st->last_in_packet_buffer->next);
  587. } else {
  588. next_point = &s->packet_buffer;
  589. }
  590. if (chunked) {
  591. uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
  592. st->interleaver_chunk_size += pkt->size;
  593. st->interleaver_chunk_duration += pkt->duration;
  594. if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
  595. || (max && st->interleaver_chunk_duration > max)) {
  596. st->interleaver_chunk_size = 0;
  597. this_pktl->pkt.flags |= CHUNK_START;
  598. if (max && st->interleaver_chunk_duration > max) {
  599. int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
  600. int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
  601. st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
  602. } else
  603. st->interleaver_chunk_duration = 0;
  604. }
  605. }
  606. if (*next_point) {
  607. if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
  608. goto next_non_null;
  609. if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
  610. while ( *next_point
  611. && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
  612. || !compare(s, &(*next_point)->pkt, pkt)))
  613. next_point = &(*next_point)->next;
  614. if (*next_point)
  615. goto next_non_null;
  616. } else {
  617. next_point = &(s->packet_buffer_end->next);
  618. }
  619. }
  620. av_assert1(!*next_point);
  621. s->packet_buffer_end = this_pktl;
  622. next_non_null:
  623. this_pktl->next = *next_point;
  624. s->streams[pkt->stream_index]->last_in_packet_buffer =
  625. *next_point = this_pktl;
  626. return 0;
  627. }
  628. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  629. AVPacket *pkt)
  630. {
  631. AVStream *st = s->streams[pkt->stream_index];
  632. AVStream *st2 = s->streams[next->stream_index];
  633. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  634. st->time_base);
  635. if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
  636. 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);
  637. 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);
  638. if (ts == ts2) {
  639. 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
  640. -( 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;
  641. ts2=0;
  642. }
  643. comp= (ts>ts2) - (ts<ts2);
  644. }
  645. if (comp == 0)
  646. return pkt->stream_index < next->stream_index;
  647. return comp > 0;
  648. }
  649. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  650. AVPacket *pkt, int flush)
  651. {
  652. AVPacketList *pktl;
  653. int stream_count = 0, noninterleaved_count = 0;
  654. int i, ret;
  655. if (pkt) {
  656. ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts);
  657. if (ret < 0)
  658. return ret;
  659. }
  660. for (i = 0; i < s->nb_streams; i++) {
  661. if (s->streams[i]->last_in_packet_buffer) {
  662. ++stream_count;
  663. } else if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  664. ++noninterleaved_count;
  665. }
  666. }
  667. if (s->internal->nb_interleaved_streams == stream_count)
  668. flush = 1;
  669. if (s->max_interleave_delta > 0 && s->packet_buffer && !flush) {
  670. AVPacket *top_pkt = &s->packet_buffer->pkt;
  671. int64_t delta_dts = INT64_MIN;
  672. int64_t top_dts = av_rescale_q(top_pkt->dts,
  673. s->streams[top_pkt->stream_index]->time_base,
  674. AV_TIME_BASE_Q);
  675. for (i = 0; i < s->nb_streams; i++) {
  676. int64_t last_dts;
  677. const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
  678. if (!last)
  679. continue;
  680. last_dts = av_rescale_q(last->pkt.dts,
  681. s->streams[i]->time_base,
  682. AV_TIME_BASE_Q);
  683. delta_dts = FFMAX(delta_dts, last_dts - top_dts);
  684. }
  685. if (delta_dts > s->max_interleave_delta) {
  686. av_log(s, AV_LOG_DEBUG,
  687. "Delay between the first packet and last packet in the "
  688. "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
  689. delta_dts, s->max_interleave_delta);
  690. flush = 1;
  691. }
  692. }
  693. if (stream_count && flush) {
  694. AVStream *st;
  695. pktl = s->packet_buffer;
  696. *out = pktl->pkt;
  697. st = s->streams[out->stream_index];
  698. s->packet_buffer = pktl->next;
  699. if (!s->packet_buffer)
  700. s->packet_buffer_end = NULL;
  701. if (st->last_in_packet_buffer == pktl)
  702. st->last_in_packet_buffer = NULL;
  703. av_freep(&pktl);
  704. return 1;
  705. } else {
  706. av_init_packet(out);
  707. return 0;
  708. }
  709. }
  710. /**
  711. * Interleave an AVPacket correctly so it can be muxed.
  712. * @param out the interleaved packet will be output here
  713. * @param in the input packet
  714. * @param flush 1 if no further packets are available as input and all
  715. * remaining packets should be output
  716. * @return 1 if a packet was output, 0 if no packet could be output,
  717. * < 0 if an error occurred
  718. */
  719. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  720. {
  721. if (s->oformat->interleave_packet) {
  722. int ret = s->oformat->interleave_packet(s, out, in, flush);
  723. if (in)
  724. av_free_packet(in);
  725. return ret;
  726. } else
  727. return ff_interleave_packet_per_dts(s, out, in, flush);
  728. }
  729. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  730. {
  731. int ret, flush = 0;
  732. ret = check_packet(s, pkt);
  733. if (ret < 0)
  734. goto fail;
  735. if (pkt) {
  736. AVStream *st = s->streams[pkt->stream_index];
  737. //FIXME/XXX/HACK drop zero sized packets
  738. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0) {
  739. ret = 0;
  740. goto fail;
  741. }
  742. av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
  743. pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
  744. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  745. goto fail;
  746. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  747. ret = AVERROR(EINVAL);
  748. goto fail;
  749. }
  750. } else {
  751. av_dlog(s, "av_interleaved_write_frame FLUSH\n");
  752. flush = 1;
  753. }
  754. for (;; ) {
  755. AVPacket opkt;
  756. int ret = interleave_packet(s, &opkt, pkt, flush);
  757. if (pkt) {
  758. memset(pkt, 0, sizeof(*pkt));
  759. av_init_packet(pkt);
  760. pkt = NULL;
  761. }
  762. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  763. return ret;
  764. ret = write_packet(s, &opkt);
  765. if (ret >= 0)
  766. s->streams[opkt.stream_index]->nb_frames++;
  767. av_free_packet(&opkt);
  768. if (ret < 0)
  769. return ret;
  770. if(s->pb && s->pb->error)
  771. return s->pb->error;
  772. }
  773. fail:
  774. av_packet_unref(pkt);
  775. return ret;
  776. }
  777. int av_write_trailer(AVFormatContext *s)
  778. {
  779. int ret, i;
  780. for (;; ) {
  781. AVPacket pkt;
  782. ret = interleave_packet(s, &pkt, NULL, 1);
  783. if (ret < 0) //FIXME cleanup needed for ret<0 ?
  784. goto fail;
  785. if (!ret)
  786. break;
  787. ret = write_packet(s, &pkt);
  788. if (ret >= 0)
  789. s->streams[pkt.stream_index]->nb_frames++;
  790. av_free_packet(&pkt);
  791. if (ret < 0)
  792. goto fail;
  793. if(s->pb && s->pb->error)
  794. goto fail;
  795. }
  796. if (s->oformat->write_trailer)
  797. ret = s->oformat->write_trailer(s);
  798. fail:
  799. if (s->pb)
  800. avio_flush(s->pb);
  801. if (ret == 0)
  802. ret = s->pb ? s->pb->error : 0;
  803. for (i = 0; i < s->nb_streams; i++) {
  804. av_freep(&s->streams[i]->priv_data);
  805. av_freep(&s->streams[i]->index_entries);
  806. }
  807. if (s->oformat->priv_class)
  808. av_opt_free(s->priv_data);
  809. av_freep(&s->priv_data);
  810. return ret;
  811. }
  812. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  813. int64_t *dts, int64_t *wall)
  814. {
  815. if (!s->oformat || !s->oformat->get_output_timestamp)
  816. return AVERROR(ENOSYS);
  817. s->oformat->get_output_timestamp(s, stream, dts, wall);
  818. return 0;
  819. }
  820. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  821. AVFormatContext *src)
  822. {
  823. AVPacket local_pkt;
  824. local_pkt = *pkt;
  825. local_pkt.stream_index = dst_stream;
  826. if (pkt->pts != AV_NOPTS_VALUE)
  827. local_pkt.pts = av_rescale_q(pkt->pts,
  828. src->streams[pkt->stream_index]->time_base,
  829. dst->streams[dst_stream]->time_base);
  830. if (pkt->dts != AV_NOPTS_VALUE)
  831. local_pkt.dts = av_rescale_q(pkt->dts,
  832. src->streams[pkt->stream_index]->time_base,
  833. dst->streams[dst_stream]->time_base);
  834. if (pkt->duration)
  835. local_pkt.duration = av_rescale_q(pkt->duration,
  836. src->streams[pkt->stream_index]->time_base,
  837. dst->streams[dst_stream]->time_base);
  838. return av_write_frame(dst, &local_pkt);
  839. }
  840. static int av_write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
  841. AVFrame *frame, int interleaved)
  842. {
  843. AVPacket pkt, *pktp;
  844. av_assert0(s->oformat);
  845. if (!s->oformat->write_uncoded_frame)
  846. return AVERROR(ENOSYS);
  847. if (!frame) {
  848. pktp = NULL;
  849. } else {
  850. pktp = &pkt;
  851. av_init_packet(&pkt);
  852. pkt.data = (void *)frame;
  853. pkt.size = UNCODED_FRAME_PACKET_SIZE;
  854. pkt.pts =
  855. pkt.dts = frame->pts;
  856. pkt.duration = av_frame_get_pkt_duration(frame);
  857. pkt.stream_index = stream_index;
  858. pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
  859. }
  860. return interleaved ? av_interleaved_write_frame(s, pktp) :
  861. av_write_frame(s, pktp);
  862. }
  863. int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
  864. AVFrame *frame)
  865. {
  866. return av_write_uncoded_frame_internal(s, stream_index, frame, 0);
  867. }
  868. int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
  869. AVFrame *frame)
  870. {
  871. return av_write_uncoded_frame_internal(s, stream_index, frame, 1);
  872. }
  873. int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
  874. {
  875. av_assert0(s->oformat);
  876. if (!s->oformat->write_uncoded_frame)
  877. return AVERROR(ENOSYS);
  878. return s->oformat->write_uncoded_frame(s, stream_index, NULL,
  879. AV_WRITE_UNCODED_FRAME_QUERY);
  880. }