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.

1045 lines
34KB

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