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.

1033 lines
33KB

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