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.

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