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.

1384 lines
44KB

  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. /**
  46. * @file
  47. * muxing functions for use within libavformat
  48. */
  49. /* fraction handling */
  50. /**
  51. * f = val + (num / den) + 0.5.
  52. *
  53. * 'num' is normalized so that it is such as 0 <= num < den.
  54. *
  55. * @param f fractional number
  56. * @param val integer value
  57. * @param num must be >= 0
  58. * @param den must be >= 1
  59. */
  60. static void frac_init(FFFrac *f, int64_t val, int64_t num, int64_t den)
  61. {
  62. num += (den >> 1);
  63. if (num >= den) {
  64. val += num / den;
  65. num = num % den;
  66. }
  67. f->val = val;
  68. f->num = num;
  69. f->den = den;
  70. }
  71. /**
  72. * Fractional addition to f: f = f + (incr / f->den).
  73. *
  74. * @param f fractional number
  75. * @param incr increment, can be positive or negative
  76. */
  77. static void frac_add(FFFrac *f, int64_t incr)
  78. {
  79. int64_t num, den;
  80. num = f->num + incr;
  81. den = f->den;
  82. if (num < 0) {
  83. f->val += num / den;
  84. num = num % den;
  85. if (num < 0) {
  86. num += den;
  87. f->val--;
  88. }
  89. } else if (num >= den) {
  90. f->val += num / den;
  91. num = num % den;
  92. }
  93. f->num = num;
  94. }
  95. AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precision)
  96. {
  97. AVRational q;
  98. int j;
  99. q = st->time_base;
  100. for (j=2; j<14; j+= 1+(j>2))
  101. while (q.den / q.num < min_precision && q.num % j == 0)
  102. q.num /= j;
  103. while (q.den / q.num < min_precision && q.den < (1<<24))
  104. q.den <<= 1;
  105. return q;
  106. }
  107. enum AVChromaLocation ff_choose_chroma_location(AVFormatContext *s, AVStream *st)
  108. {
  109. AVCodecParameters *par = st->codecpar;
  110. const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(par->format);
  111. if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED)
  112. return par->chroma_location;
  113. if (pix_desc) {
  114. if (pix_desc->log2_chroma_h == 0) {
  115. return AVCHROMA_LOC_TOPLEFT;
  116. } else if (pix_desc->log2_chroma_w == 1 && pix_desc->log2_chroma_h == 1) {
  117. if (par->field_order == AV_FIELD_UNKNOWN || par->field_order == AV_FIELD_PROGRESSIVE) {
  118. switch (par->codec_id) {
  119. case AV_CODEC_ID_MJPEG:
  120. case AV_CODEC_ID_MPEG1VIDEO: return AVCHROMA_LOC_CENTER;
  121. }
  122. }
  123. if (par->field_order == AV_FIELD_UNKNOWN || par->field_order != AV_FIELD_PROGRESSIVE) {
  124. switch (par->codec_id) {
  125. case AV_CODEC_ID_MPEG2VIDEO: return AVCHROMA_LOC_LEFT;
  126. }
  127. }
  128. }
  129. }
  130. return AVCHROMA_LOC_UNSPECIFIED;
  131. }
  132. int avformat_alloc_output_context2(AVFormatContext **avctx, ff_const59 AVOutputFormat *oformat,
  133. const char *format, const char *filename)
  134. {
  135. AVFormatContext *s = avformat_alloc_context();
  136. int ret = 0;
  137. *avctx = NULL;
  138. if (!s)
  139. goto nomem;
  140. if (!oformat) {
  141. if (format) {
  142. oformat = av_guess_format(format, NULL, NULL);
  143. if (!oformat) {
  144. av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
  145. ret = AVERROR(EINVAL);
  146. goto error;
  147. }
  148. } else {
  149. oformat = av_guess_format(NULL, filename, NULL);
  150. if (!oformat) {
  151. ret = AVERROR(EINVAL);
  152. av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
  153. filename);
  154. goto error;
  155. }
  156. }
  157. }
  158. s->oformat = oformat;
  159. if (s->oformat->priv_data_size > 0) {
  160. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  161. if (!s->priv_data)
  162. goto nomem;
  163. if (s->oformat->priv_class) {
  164. *(const AVClass**)s->priv_data= s->oformat->priv_class;
  165. av_opt_set_defaults(s->priv_data);
  166. }
  167. } else
  168. s->priv_data = NULL;
  169. if (filename) {
  170. #if FF_API_FORMAT_FILENAME
  171. FF_DISABLE_DEPRECATION_WARNINGS
  172. av_strlcpy(s->filename, filename, sizeof(s->filename));
  173. FF_ENABLE_DEPRECATION_WARNINGS
  174. #endif
  175. if (!(s->url = av_strdup(filename)))
  176. goto nomem;
  177. }
  178. *avctx = s;
  179. return 0;
  180. nomem:
  181. av_log(s, AV_LOG_ERROR, "Out of memory\n");
  182. ret = AVERROR(ENOMEM);
  183. error:
  184. avformat_free_context(s);
  185. return ret;
  186. }
  187. static int validate_codec_tag(AVFormatContext *s, AVStream *st)
  188. {
  189. const AVCodecTag *avctag;
  190. int n;
  191. enum AVCodecID id = AV_CODEC_ID_NONE;
  192. int64_t tag = -1;
  193. /**
  194. * Check that tag + id is in the table
  195. * If neither is in the table -> OK
  196. * If tag is in the table with another id -> FAIL
  197. * If id is in the table with another tag -> FAIL unless strict < normal
  198. */
  199. for (n = 0; s->oformat->codec_tag[n]; n++) {
  200. avctag = s->oformat->codec_tag[n];
  201. while (avctag->id != AV_CODEC_ID_NONE) {
  202. if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codecpar->codec_tag)) {
  203. id = avctag->id;
  204. if (id == st->codecpar->codec_id)
  205. return 1;
  206. }
  207. if (avctag->id == st->codecpar->codec_id)
  208. tag = avctag->tag;
  209. avctag++;
  210. }
  211. }
  212. if (id != AV_CODEC_ID_NONE)
  213. return 0;
  214. if (tag >= 0 && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
  215. return 0;
  216. return 1;
  217. }
  218. static int init_muxer(AVFormatContext *s, AVDictionary **options)
  219. {
  220. int ret = 0, i;
  221. AVStream *st;
  222. AVDictionary *tmp = NULL;
  223. AVCodecParameters *par = NULL;
  224. const AVOutputFormat *of = s->oformat;
  225. const AVCodecDescriptor *desc;
  226. AVDictionaryEntry *e;
  227. if (options)
  228. av_dict_copy(&tmp, *options, 0);
  229. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  230. goto fail;
  231. if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
  232. (ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
  233. goto fail;
  234. #if FF_API_FORMAT_FILENAME
  235. FF_DISABLE_DEPRECATION_WARNINGS
  236. if (!s->url && !(s->url = av_strdup(s->filename))) {
  237. FF_ENABLE_DEPRECATION_WARNINGS
  238. #else
  239. if (!s->url && !(s->url = av_strdup(""))) {
  240. #endif
  241. ret = AVERROR(ENOMEM);
  242. goto fail;
  243. }
  244. #if FF_API_LAVF_AVCTX
  245. FF_DISABLE_DEPRECATION_WARNINGS
  246. if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT) {
  247. if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
  248. av_log(s, AV_LOG_WARNING,
  249. "The AVFormatContext is not in set to bitexact mode, only "
  250. "the AVCodecContext. If this is not intended, set "
  251. "AVFormatContext.flags |= AVFMT_FLAG_BITEXACT.\n");
  252. }
  253. }
  254. FF_ENABLE_DEPRECATION_WARNINGS
  255. #endif
  256. // some sanity checks
  257. if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
  258. av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
  259. ret = AVERROR(EINVAL);
  260. goto fail;
  261. }
  262. for (i = 0; i < s->nb_streams; i++) {
  263. st = s->streams[i];
  264. par = st->codecpar;
  265. #if FF_API_LAVF_AVCTX
  266. FF_DISABLE_DEPRECATION_WARNINGS
  267. if (st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
  268. st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
  269. av_log(s, AV_LOG_WARNING, "Using AVStream.codec to pass codec "
  270. "parameters to muxers is deprecated, use AVStream.codecpar "
  271. "instead.\n");
  272. ret = avcodec_parameters_from_context(st->codecpar, st->codec);
  273. if (ret < 0)
  274. goto fail;
  275. }
  276. FF_ENABLE_DEPRECATION_WARNINGS
  277. #endif
  278. if (!st->time_base.num) {
  279. /* fall back on the default timebase values */
  280. if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)
  281. avpriv_set_pts_info(st, 64, 1, par->sample_rate);
  282. else
  283. avpriv_set_pts_info(st, 33, 1, 90000);
  284. }
  285. switch (par->codec_type) {
  286. case AVMEDIA_TYPE_AUDIO:
  287. if (par->sample_rate <= 0) {
  288. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  289. ret = AVERROR(EINVAL);
  290. goto fail;
  291. }
  292. if (!par->block_align)
  293. par->block_align = par->channels *
  294. av_get_bits_per_sample(par->codec_id) >> 3;
  295. break;
  296. case AVMEDIA_TYPE_VIDEO:
  297. if ((par->width <= 0 || par->height <= 0) &&
  298. !(of->flags & AVFMT_NODIMENSIONS)) {
  299. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  300. ret = AVERROR(EINVAL);
  301. goto fail;
  302. }
  303. if (av_cmp_q(st->sample_aspect_ratio, par->sample_aspect_ratio)
  304. && fabs(av_q2d(st->sample_aspect_ratio) - av_q2d(par->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
  305. ) {
  306. if (st->sample_aspect_ratio.num != 0 &&
  307. st->sample_aspect_ratio.den != 0 &&
  308. par->sample_aspect_ratio.num != 0 &&
  309. par->sample_aspect_ratio.den != 0) {
  310. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
  311. "(%d/%d) and encoder layer (%d/%d)\n",
  312. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  313. par->sample_aspect_ratio.num,
  314. par->sample_aspect_ratio.den);
  315. ret = AVERROR(EINVAL);
  316. goto fail;
  317. }
  318. }
  319. break;
  320. }
  321. desc = avcodec_descriptor_get(par->codec_id);
  322. if (desc && desc->props & AV_CODEC_PROP_REORDER)
  323. st->internal->reorder = 1;
  324. if (of->codec_tag) {
  325. if ( par->codec_tag
  326. && par->codec_id == AV_CODEC_ID_RAWVIDEO
  327. && ( av_codec_get_tag(of->codec_tag, par->codec_id) == 0
  328. || av_codec_get_tag(of->codec_tag, par->codec_id) == MKTAG('r', 'a', 'w', ' '))
  329. && !validate_codec_tag(s, st)) {
  330. // the current rawvideo encoding system ends up setting
  331. // the wrong codec_tag for avi/mov, we override it here
  332. par->codec_tag = 0;
  333. }
  334. if (par->codec_tag) {
  335. if (!validate_codec_tag(s, st)) {
  336. const uint32_t otag = av_codec_get_tag(s->oformat->codec_tag, par->codec_id);
  337. av_log(s, AV_LOG_ERROR,
  338. "Tag %s incompatible with output codec id '%d' (%s)\n",
  339. av_fourcc2str(par->codec_tag), par->codec_id, av_fourcc2str(otag));
  340. ret = AVERROR_INVALIDDATA;
  341. goto fail;
  342. }
  343. } else
  344. par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);
  345. }
  346. if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)
  347. s->internal->nb_interleaved_streams++;
  348. }
  349. if (!s->priv_data && of->priv_data_size > 0) {
  350. s->priv_data = av_mallocz(of->priv_data_size);
  351. if (!s->priv_data) {
  352. ret = AVERROR(ENOMEM);
  353. goto fail;
  354. }
  355. if (of->priv_class) {
  356. *(const AVClass **)s->priv_data = of->priv_class;
  357. av_opt_set_defaults(s->priv_data);
  358. if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
  359. goto fail;
  360. }
  361. }
  362. /* set muxer identification string */
  363. if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
  364. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  365. } else {
  366. av_dict_set(&s->metadata, "encoder", NULL, 0);
  367. }
  368. for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {
  369. av_dict_set(&s->metadata, e->key, NULL, 0);
  370. }
  371. if (options) {
  372. av_dict_free(options);
  373. *options = tmp;
  374. }
  375. if (s->oformat->init) {
  376. if ((ret = s->oformat->init(s)) < 0) {
  377. if (s->oformat->deinit)
  378. s->oformat->deinit(s);
  379. return ret;
  380. }
  381. return ret == 0;
  382. }
  383. return 0;
  384. fail:
  385. av_dict_free(&tmp);
  386. return ret;
  387. }
  388. static int init_pts(AVFormatContext *s)
  389. {
  390. int i;
  391. AVStream *st;
  392. /* init PTS generation */
  393. for (i = 0; i < s->nb_streams; i++) {
  394. int64_t den = AV_NOPTS_VALUE;
  395. st = s->streams[i];
  396. switch (st->codecpar->codec_type) {
  397. case AVMEDIA_TYPE_AUDIO:
  398. den = (int64_t)st->time_base.num * st->codecpar->sample_rate;
  399. break;
  400. case AVMEDIA_TYPE_VIDEO:
  401. den = (int64_t)st->time_base.num * st->time_base.den;
  402. break;
  403. default:
  404. break;
  405. }
  406. if (!st->internal->priv_pts)
  407. st->internal->priv_pts = av_mallocz(sizeof(*st->internal->priv_pts));
  408. if (!st->internal->priv_pts)
  409. return AVERROR(ENOMEM);
  410. if (den != AV_NOPTS_VALUE) {
  411. if (den <= 0)
  412. return AVERROR_INVALIDDATA;
  413. frac_init(st->internal->priv_pts, 0, 0, den);
  414. }
  415. }
  416. if (s->avoid_negative_ts < 0) {
  417. av_assert2(s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO);
  418. if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
  419. s->avoid_negative_ts = 0;
  420. } else
  421. s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
  422. }
  423. return 0;
  424. }
  425. static void flush_if_needed(AVFormatContext *s)
  426. {
  427. if (s->pb && s->pb->error >= 0) {
  428. if (s->flush_packets == 1 || s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  429. avio_flush(s->pb);
  430. else if (s->flush_packets && !(s->oformat->flags & AVFMT_NOFILE))
  431. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
  432. }
  433. }
  434. static void deinit_muxer(AVFormatContext *s)
  435. {
  436. if (s->oformat && s->oformat->deinit && s->internal->initialized)
  437. s->oformat->deinit(s);
  438. s->internal->initialized =
  439. s->internal->streams_initialized = 0;
  440. }
  441. int avformat_init_output(AVFormatContext *s, AVDictionary **options)
  442. {
  443. int ret = 0;
  444. if ((ret = init_muxer(s, options)) < 0)
  445. return ret;
  446. s->internal->initialized = 1;
  447. s->internal->streams_initialized = ret;
  448. if (s->oformat->init && ret) {
  449. if ((ret = init_pts(s)) < 0)
  450. return ret;
  451. return AVSTREAM_INIT_IN_INIT_OUTPUT;
  452. }
  453. return AVSTREAM_INIT_IN_WRITE_HEADER;
  454. }
  455. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  456. {
  457. int ret = 0;
  458. int already_initialized = s->internal->initialized;
  459. int streams_already_initialized = s->internal->streams_initialized;
  460. if (!already_initialized)
  461. if ((ret = avformat_init_output(s, options)) < 0)
  462. return ret;
  463. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  464. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
  465. if (s->oformat->write_header) {
  466. ret = s->oformat->write_header(s);
  467. if (ret >= 0 && s->pb && s->pb->error < 0)
  468. ret = s->pb->error;
  469. if (ret < 0)
  470. goto fail;
  471. flush_if_needed(s);
  472. }
  473. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  474. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_UNKNOWN);
  475. if (!s->internal->streams_initialized) {
  476. if ((ret = init_pts(s)) < 0)
  477. goto fail;
  478. }
  479. return streams_already_initialized;
  480. fail:
  481. deinit_muxer(s);
  482. return ret;
  483. }
  484. #define AV_PKT_FLAG_UNCODED_FRAME 0x2000
  485. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  486. FF_DISABLE_DEPRECATION_WARNINGS
  487. //FIXME merge with compute_pkt_fields
  488. static int compute_muxer_pkt_fields(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  489. {
  490. int delay = FFMAX(st->codecpar->video_delay, st->internal->avctx->max_b_frames > 0);
  491. int num, den, i;
  492. int frame_size;
  493. if (!s->internal->missing_ts_warning &&
  494. !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
  495. (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC) || (st->disposition & AV_DISPOSITION_TIMED_THUMBNAILS)) &&
  496. (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
  497. av_log(s, AV_LOG_WARNING,
  498. "Timestamps are unset in a packet for stream %d. "
  499. "This is deprecated and will stop working in the future. "
  500. "Fix your code to set the timestamps properly\n", st->index);
  501. s->internal->missing_ts_warning = 1;
  502. }
  503. if (s->debug & FF_FDEBUG_TS)
  504. av_log(s, AV_LOG_DEBUG, "compute_muxer_pkt_fields: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
  505. av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
  506. if (pkt->duration < 0 && st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
  507. av_log(s, AV_LOG_WARNING, "Packet with invalid duration %"PRId64" in stream %d\n",
  508. pkt->duration, pkt->stream_index);
  509. pkt->duration = 0;
  510. }
  511. /* duration field */
  512. if (pkt->duration == 0) {
  513. ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
  514. if (den && num) {
  515. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  516. }
  517. }
  518. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  519. pkt->pts = pkt->dts;
  520. //XXX/FIXME this is a temporary hack until all encoders output pts
  521. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  522. static int warned;
  523. if (!warned) {
  524. av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
  525. warned = 1;
  526. }
  527. pkt->dts =
  528. // pkt->pts= st->cur_dts;
  529. pkt->pts = st->internal->priv_pts->val;
  530. }
  531. //calculate dts from pts
  532. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  533. st->pts_buffer[0] = pkt->pts;
  534. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  535. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  536. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  537. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  538. pkt->dts = st->pts_buffer[0];
  539. }
  540. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  541. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  542. st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE &&
  543. st->codecpar->codec_type != AVMEDIA_TYPE_DATA &&
  544. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  545. av_log(s, AV_LOG_ERROR,
  546. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
  547. st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
  548. return AVERROR(EINVAL);
  549. }
  550. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  551. av_log(s, AV_LOG_ERROR,
  552. "pts (%s) < dts (%s) in stream %d\n",
  553. av_ts2str(pkt->pts), av_ts2str(pkt->dts),
  554. st->index);
  555. return AVERROR(EINVAL);
  556. }
  557. if (s->debug & FF_FDEBUG_TS)
  558. av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%s dts2:%s\n",
  559. av_ts2str(pkt->pts), av_ts2str(pkt->dts));
  560. st->cur_dts = pkt->dts;
  561. st->internal->priv_pts->val = pkt->dts;
  562. /* update pts */
  563. switch (st->codecpar->codec_type) {
  564. case AVMEDIA_TYPE_AUDIO:
  565. frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
  566. (*(AVFrame **)pkt->data)->nb_samples :
  567. av_get_audio_frame_duration(st->codec, pkt->size);
  568. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  569. * likely equal to the encoder delay, but it would be better if we
  570. * had the real timestamps from the encoder */
  571. if (frame_size >= 0 && (pkt->size || st->internal->priv_pts->num != st->internal->priv_pts->den >> 1 || st->internal->priv_pts->val)) {
  572. frac_add(st->internal->priv_pts, (int64_t)st->time_base.den * frame_size);
  573. }
  574. break;
  575. case AVMEDIA_TYPE_VIDEO:
  576. frac_add(st->internal->priv_pts, (int64_t)st->time_base.den * st->time_base.num);
  577. break;
  578. }
  579. return 0;
  580. }
  581. FF_ENABLE_DEPRECATION_WARNINGS
  582. #endif
  583. /**
  584. * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  585. * sidedata.
  586. *
  587. * FIXME: this function should NEVER get undefined pts/dts beside when the
  588. * AVFMT_NOTIMESTAMPS is set.
  589. * Those additional safety checks should be dropped once the correct checks
  590. * are set in the callers.
  591. */
  592. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  593. {
  594. int ret;
  595. int64_t pts_backup, dts_backup;
  596. pts_backup = pkt->pts;
  597. dts_backup = pkt->dts;
  598. // If the timestamp offsetting below is adjusted, adjust
  599. // ff_interleaved_peek similarly.
  600. if (s->output_ts_offset) {
  601. AVStream *st = s->streams[pkt->stream_index];
  602. int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
  603. if (pkt->dts != AV_NOPTS_VALUE)
  604. pkt->dts += offset;
  605. if (pkt->pts != AV_NOPTS_VALUE)
  606. pkt->pts += offset;
  607. }
  608. if (s->avoid_negative_ts > 0) {
  609. AVStream *st = s->streams[pkt->stream_index];
  610. int64_t offset = st->mux_ts_offset;
  611. int64_t ts = s->internal->avoid_negative_ts_use_pts ? pkt->pts : pkt->dts;
  612. if (s->internal->offset == AV_NOPTS_VALUE && ts != AV_NOPTS_VALUE &&
  613. (ts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
  614. s->internal->offset = -ts;
  615. s->internal->offset_timebase = st->time_base;
  616. }
  617. if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
  618. offset = st->mux_ts_offset =
  619. av_rescale_q_rnd(s->internal->offset,
  620. s->internal->offset_timebase,
  621. st->time_base,
  622. AV_ROUND_UP);
  623. }
  624. if (pkt->dts != AV_NOPTS_VALUE)
  625. pkt->dts += offset;
  626. if (pkt->pts != AV_NOPTS_VALUE)
  627. pkt->pts += offset;
  628. if (s->internal->avoid_negative_ts_use_pts) {
  629. if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
  630. av_log(s, AV_LOG_WARNING, "failed to avoid negative "
  631. "pts %s in stream %d.\n"
  632. "Try -avoid_negative_ts 1 as a possible workaround.\n",
  633. av_ts2str(pkt->pts),
  634. pkt->stream_index
  635. );
  636. }
  637. } else {
  638. av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0 || s->max_interleave_delta > 0);
  639. if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
  640. av_log(s, AV_LOG_WARNING,
  641. "Packets poorly interleaved, failed to avoid negative "
  642. "timestamp %s in stream %d.\n"
  643. "Try -max_interleave_delta 0 as a possible workaround.\n",
  644. av_ts2str(pkt->dts),
  645. pkt->stream_index
  646. );
  647. }
  648. }
  649. }
  650. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  651. AVFrame **frame = (AVFrame **)pkt->data;
  652. av_assert0(pkt->size == sizeof(*frame));
  653. ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, frame, 0);
  654. } else {
  655. ret = s->oformat->write_packet(s, pkt);
  656. }
  657. if (s->pb && ret >= 0) {
  658. flush_if_needed(s);
  659. if (s->pb->error < 0)
  660. ret = s->pb->error;
  661. }
  662. if (ret < 0) {
  663. pkt->pts = pts_backup;
  664. pkt->dts = dts_backup;
  665. } else
  666. s->streams[pkt->stream_index]->nb_frames++;
  667. return ret;
  668. }
  669. static int check_packet(AVFormatContext *s, AVPacket *pkt)
  670. {
  671. if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
  672. av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
  673. pkt->stream_index);
  674. return AVERROR(EINVAL);
  675. }
  676. if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
  677. av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
  678. return AVERROR(EINVAL);
  679. }
  680. return 0;
  681. }
  682. static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
  683. {
  684. int ret;
  685. ret = check_packet(s, pkt);
  686. if (ret < 0)
  687. return ret;
  688. #if !FF_API_COMPUTE_PKT_FIELDS2 || !FF_API_LAVF_AVCTX
  689. /* sanitize the timestamps */
  690. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  691. AVStream *st = s->streams[pkt->stream_index];
  692. /* when there is no reordering (so dts is equal to pts), but
  693. * only one of them is set, set the other as well */
  694. if (!st->internal->reorder) {
  695. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
  696. pkt->pts = pkt->dts;
  697. if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
  698. pkt->dts = pkt->pts;
  699. }
  700. /* check that the timestamps are set */
  701. if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
  702. av_log(s, AV_LOG_ERROR,
  703. "Timestamps are unset in a packet for stream %d\n", st->index);
  704. return AVERROR(EINVAL);
  705. }
  706. /* check that the dts are increasing (or at least non-decreasing,
  707. * if the format allows it */
  708. if (st->cur_dts != AV_NOPTS_VALUE &&
  709. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
  710. st->cur_dts > pkt->dts)) {
  711. av_log(s, AV_LOG_ERROR,
  712. "Application provided invalid, non monotonically increasing "
  713. "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
  714. st->index, st->cur_dts, pkt->dts);
  715. return AVERROR(EINVAL);
  716. }
  717. if (pkt->pts < pkt->dts) {
  718. av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
  719. pkt->pts, pkt->dts, st->index);
  720. return AVERROR(EINVAL);
  721. }
  722. }
  723. #endif
  724. return 0;
  725. }
  726. static int do_packet_auto_bsf(AVFormatContext *s, AVPacket *pkt) {
  727. AVStream *st = s->streams[pkt->stream_index];
  728. int i, ret;
  729. if (!(s->flags & AVFMT_FLAG_AUTO_BSF))
  730. return 1;
  731. if (s->oformat->check_bitstream) {
  732. if (!st->internal->bitstream_checked) {
  733. if ((ret = s->oformat->check_bitstream(s, pkt)) < 0)
  734. return ret;
  735. else if (ret == 1)
  736. st->internal->bitstream_checked = 1;
  737. }
  738. }
  739. for (i = 0; i < st->internal->nb_bsfcs; i++) {
  740. AVBSFContext *ctx = st->internal->bsfcs[i];
  741. // TODO: when any bitstream filter requires flushing at EOF, we'll need to
  742. // flush each stream's BSF chain on write_trailer.
  743. if ((ret = av_bsf_send_packet(ctx, pkt)) < 0) {
  744. av_log(ctx, AV_LOG_ERROR,
  745. "Failed to send packet to filter %s for stream %d\n",
  746. ctx->filter->name, pkt->stream_index);
  747. return ret;
  748. }
  749. // TODO: when any automatically-added bitstream filter is generating multiple
  750. // output packets for a single input one, we'll need to call this in a loop
  751. // and write each output packet.
  752. if ((ret = av_bsf_receive_packet(ctx, pkt)) < 0) {
  753. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  754. return 0;
  755. av_log(ctx, AV_LOG_ERROR,
  756. "Failed to receive packet from filter %s for stream %d\n",
  757. ctx->filter->name, pkt->stream_index);
  758. if (s->error_recognition & AV_EF_EXPLODE)
  759. return ret;
  760. return 0;
  761. }
  762. }
  763. return 1;
  764. }
  765. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  766. {
  767. int ret;
  768. if (!pkt) {
  769. if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
  770. ret = s->oformat->write_packet(s, NULL);
  771. flush_if_needed(s);
  772. if (ret >= 0 && s->pb && s->pb->error < 0)
  773. ret = s->pb->error;
  774. return ret;
  775. }
  776. return 1;
  777. }
  778. ret = prepare_input_packet(s, pkt);
  779. if (ret < 0)
  780. return ret;
  781. ret = do_packet_auto_bsf(s, pkt);
  782. if (ret <= 0)
  783. return ret;
  784. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  785. ret = compute_muxer_pkt_fields(s, s->streams[pkt->stream_index], pkt);
  786. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  787. return ret;
  788. #endif
  789. return write_packet(s, pkt);
  790. }
  791. #define CHUNK_START 0x1000
  792. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  793. int (*compare)(AVFormatContext *, const AVPacket *, const AVPacket *))
  794. {
  795. int ret;
  796. AVPacketList **next_point, *this_pktl;
  797. AVStream *st = s->streams[pkt->stream_index];
  798. int chunked = s->max_chunk_size || s->max_chunk_duration;
  799. this_pktl = av_malloc(sizeof(AVPacketList));
  800. if (!this_pktl) {
  801. av_packet_unref(pkt);
  802. return AVERROR(ENOMEM);
  803. }
  804. if ((ret = av_packet_make_refcounted(pkt)) < 0) {
  805. av_free(this_pktl);
  806. av_packet_unref(pkt);
  807. return ret;
  808. }
  809. av_packet_move_ref(&this_pktl->pkt, pkt);
  810. pkt = &this_pktl->pkt;
  811. if (st->last_in_packet_buffer) {
  812. next_point = &(st->last_in_packet_buffer->next);
  813. } else {
  814. next_point = &s->internal->packet_buffer;
  815. }
  816. if (chunked) {
  817. uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
  818. st->interleaver_chunk_size += pkt->size;
  819. st->interleaver_chunk_duration += pkt->duration;
  820. if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
  821. || (max && st->interleaver_chunk_duration > max)) {
  822. st->interleaver_chunk_size = 0;
  823. pkt->flags |= CHUNK_START;
  824. if (max && st->interleaver_chunk_duration > max) {
  825. int64_t syncoffset = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
  826. int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
  827. st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
  828. } else
  829. st->interleaver_chunk_duration = 0;
  830. }
  831. }
  832. if (*next_point) {
  833. if (chunked && !(pkt->flags & CHUNK_START))
  834. goto next_non_null;
  835. if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
  836. while ( *next_point
  837. && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
  838. || !compare(s, &(*next_point)->pkt, pkt)))
  839. next_point = &(*next_point)->next;
  840. if (*next_point)
  841. goto next_non_null;
  842. } else {
  843. next_point = &(s->internal->packet_buffer_end->next);
  844. }
  845. }
  846. av_assert1(!*next_point);
  847. s->internal->packet_buffer_end = this_pktl;
  848. next_non_null:
  849. this_pktl->next = *next_point;
  850. st->last_in_packet_buffer = *next_point = this_pktl;
  851. return 0;
  852. }
  853. static int interleave_compare_dts(AVFormatContext *s, const AVPacket *next,
  854. const AVPacket *pkt)
  855. {
  856. AVStream *st = s->streams[pkt->stream_index];
  857. AVStream *st2 = s->streams[next->stream_index];
  858. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  859. st->time_base);
  860. if (s->audio_preload) {
  861. int preload = st ->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
  862. int preload2 = st2->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
  863. if (preload != preload2) {
  864. int64_t ts, ts2;
  865. preload *= s->audio_preload;
  866. preload2 *= s->audio_preload;
  867. ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - preload;
  868. ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - preload2;
  869. if (ts == ts2) {
  870. ts = ((uint64_t)pkt ->dts*st ->time_base.num*AV_TIME_BASE - (uint64_t)preload *st ->time_base.den)*st2->time_base.den
  871. - ((uint64_t)next->dts*st2->time_base.num*AV_TIME_BASE - (uint64_t)preload2*st2->time_base.den)*st ->time_base.den;
  872. ts2 = 0;
  873. }
  874. comp = (ts2 > ts) - (ts2 < ts);
  875. }
  876. }
  877. if (comp == 0)
  878. return pkt->stream_index < next->stream_index;
  879. return comp > 0;
  880. }
  881. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  882. AVPacket *pkt, int flush)
  883. {
  884. AVPacketList *pktl;
  885. int stream_count = 0;
  886. int noninterleaved_count = 0;
  887. int i, ret;
  888. int eof = flush;
  889. if (pkt) {
  890. if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
  891. return ret;
  892. }
  893. for (i = 0; i < s->nb_streams; i++) {
  894. if (s->streams[i]->last_in_packet_buffer) {
  895. ++stream_count;
  896. } else if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
  897. s->streams[i]->codecpar->codec_id != AV_CODEC_ID_VP8 &&
  898. s->streams[i]->codecpar->codec_id != AV_CODEC_ID_VP9) {
  899. ++noninterleaved_count;
  900. }
  901. }
  902. if (s->internal->nb_interleaved_streams == stream_count)
  903. flush = 1;
  904. if (s->max_interleave_delta > 0 &&
  905. s->internal->packet_buffer &&
  906. !flush &&
  907. s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
  908. ) {
  909. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  910. int64_t delta_dts = INT64_MIN;
  911. int64_t top_dts = av_rescale_q(top_pkt->dts,
  912. s->streams[top_pkt->stream_index]->time_base,
  913. AV_TIME_BASE_Q);
  914. for (i = 0; i < s->nb_streams; i++) {
  915. int64_t last_dts;
  916. const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
  917. if (!last)
  918. continue;
  919. last_dts = av_rescale_q(last->pkt.dts,
  920. s->streams[i]->time_base,
  921. AV_TIME_BASE_Q);
  922. delta_dts = FFMAX(delta_dts, last_dts - top_dts);
  923. }
  924. if (delta_dts > s->max_interleave_delta) {
  925. av_log(s, AV_LOG_DEBUG,
  926. "Delay between the first packet and last packet in the "
  927. "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
  928. delta_dts, s->max_interleave_delta);
  929. flush = 1;
  930. }
  931. }
  932. if (s->internal->packet_buffer &&
  933. eof &&
  934. (s->flags & AVFMT_FLAG_SHORTEST) &&
  935. s->internal->shortest_end == AV_NOPTS_VALUE) {
  936. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  937. s->internal->shortest_end = av_rescale_q(top_pkt->dts,
  938. s->streams[top_pkt->stream_index]->time_base,
  939. AV_TIME_BASE_Q);
  940. }
  941. if (s->internal->shortest_end != AV_NOPTS_VALUE) {
  942. while (s->internal->packet_buffer) {
  943. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  944. AVStream *st;
  945. int64_t top_dts = av_rescale_q(top_pkt->dts,
  946. s->streams[top_pkt->stream_index]->time_base,
  947. AV_TIME_BASE_Q);
  948. if (s->internal->shortest_end + 1 >= top_dts)
  949. break;
  950. pktl = s->internal->packet_buffer;
  951. st = s->streams[pktl->pkt.stream_index];
  952. s->internal->packet_buffer = pktl->next;
  953. if (!s->internal->packet_buffer)
  954. s->internal->packet_buffer_end = NULL;
  955. if (st->last_in_packet_buffer == pktl)
  956. st->last_in_packet_buffer = NULL;
  957. av_packet_unref(&pktl->pkt);
  958. av_freep(&pktl);
  959. flush = 0;
  960. }
  961. }
  962. if (stream_count && flush) {
  963. AVStream *st;
  964. pktl = s->internal->packet_buffer;
  965. *out = pktl->pkt;
  966. st = s->streams[out->stream_index];
  967. s->internal->packet_buffer = pktl->next;
  968. if (!s->internal->packet_buffer)
  969. s->internal->packet_buffer_end = NULL;
  970. if (st->last_in_packet_buffer == pktl)
  971. st->last_in_packet_buffer = NULL;
  972. av_freep(&pktl);
  973. return 1;
  974. } else {
  975. av_init_packet(out);
  976. return 0;
  977. }
  978. }
  979. int ff_interleaved_peek(AVFormatContext *s, int stream,
  980. AVPacket *pkt, int add_offset)
  981. {
  982. AVPacketList *pktl = s->internal->packet_buffer;
  983. while (pktl) {
  984. if (pktl->pkt.stream_index == stream) {
  985. *pkt = pktl->pkt;
  986. if (add_offset) {
  987. AVStream *st = s->streams[pkt->stream_index];
  988. int64_t offset = st->mux_ts_offset;
  989. if (s->output_ts_offset)
  990. offset += av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
  991. if (pkt->dts != AV_NOPTS_VALUE)
  992. pkt->dts += offset;
  993. if (pkt->pts != AV_NOPTS_VALUE)
  994. pkt->pts += offset;
  995. }
  996. return 0;
  997. }
  998. pktl = pktl->next;
  999. }
  1000. return AVERROR(ENOENT);
  1001. }
  1002. /**
  1003. * Interleave an AVPacket correctly so it can be muxed.
  1004. * @param out the interleaved packet will be output here
  1005. * @param in the input packet; will always be blank on return if not NULL
  1006. * @param flush 1 if no further packets are available as input and all
  1007. * remaining packets should be output
  1008. * @return 1 if a packet was output, 0 if no packet could be output,
  1009. * < 0 if an error occurred
  1010. */
  1011. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  1012. {
  1013. if (s->oformat->interleave_packet) {
  1014. int ret = s->oformat->interleave_packet(s, out, in, flush);
  1015. if (in)
  1016. av_packet_unref(in);
  1017. return ret;
  1018. } else
  1019. return ff_interleave_packet_per_dts(s, out, in, flush);
  1020. }
  1021. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  1022. {
  1023. int ret, flush = 0;
  1024. if (pkt) {
  1025. AVStream *st = s->streams[pkt->stream_index];
  1026. ret = prepare_input_packet(s, pkt);
  1027. if (ret < 0)
  1028. goto fail;
  1029. ret = do_packet_auto_bsf(s, pkt);
  1030. if (ret == 0)
  1031. return 0;
  1032. else if (ret < 0)
  1033. goto fail;
  1034. if (s->debug & FF_FDEBUG_TS)
  1035. av_log(s, AV_LOG_DEBUG, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
  1036. pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
  1037. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  1038. if ((ret = compute_muxer_pkt_fields(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  1039. goto fail;
  1040. #endif
  1041. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  1042. ret = AVERROR(EINVAL);
  1043. goto fail;
  1044. }
  1045. } else {
  1046. av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
  1047. flush = 1;
  1048. }
  1049. for (;; ) {
  1050. AVPacket opkt;
  1051. int ret = interleave_packet(s, &opkt, pkt, flush);
  1052. if (ret <= 0)
  1053. return ret;
  1054. pkt = NULL;
  1055. ret = write_packet(s, &opkt);
  1056. av_packet_unref(&opkt);
  1057. if (ret < 0)
  1058. return ret;
  1059. }
  1060. fail:
  1061. av_packet_unref(pkt);
  1062. return ret;
  1063. }
  1064. int av_write_trailer(AVFormatContext *s)
  1065. {
  1066. int ret, i;
  1067. for (;; ) {
  1068. AVPacket pkt;
  1069. ret = interleave_packet(s, &pkt, NULL, 1);
  1070. if (ret < 0)
  1071. goto fail;
  1072. if (!ret)
  1073. break;
  1074. ret = write_packet(s, &pkt);
  1075. av_packet_unref(&pkt);
  1076. if (ret < 0)
  1077. goto fail;
  1078. }
  1079. fail:
  1080. if (s->oformat->write_trailer) {
  1081. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  1082. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  1083. if (ret >= 0) {
  1084. ret = s->oformat->write_trailer(s);
  1085. } else {
  1086. s->oformat->write_trailer(s);
  1087. }
  1088. }
  1089. deinit_muxer(s);
  1090. if (s->pb)
  1091. avio_flush(s->pb);
  1092. if (ret == 0)
  1093. ret = s->pb ? s->pb->error : 0;
  1094. for (i = 0; i < s->nb_streams; i++) {
  1095. av_freep(&s->streams[i]->priv_data);
  1096. av_freep(&s->streams[i]->index_entries);
  1097. }
  1098. if (s->oformat->priv_class)
  1099. av_opt_free(s->priv_data);
  1100. av_freep(&s->priv_data);
  1101. return ret;
  1102. }
  1103. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  1104. int64_t *dts, int64_t *wall)
  1105. {
  1106. if (!s->oformat || !s->oformat->get_output_timestamp)
  1107. return AVERROR(ENOSYS);
  1108. s->oformat->get_output_timestamp(s, stream, dts, wall);
  1109. return 0;
  1110. }
  1111. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  1112. AVFormatContext *src, int interleave)
  1113. {
  1114. AVPacket local_pkt;
  1115. int ret;
  1116. local_pkt = *pkt;
  1117. local_pkt.stream_index = dst_stream;
  1118. av_packet_rescale_ts(&local_pkt,
  1119. src->streams[pkt->stream_index]->time_base,
  1120. dst->streams[dst_stream]->time_base);
  1121. if (interleave) ret = av_interleaved_write_frame(dst, &local_pkt);
  1122. else ret = av_write_frame(dst, &local_pkt);
  1123. pkt->buf = local_pkt.buf;
  1124. pkt->side_data = local_pkt.side_data;
  1125. pkt->side_data_elems = local_pkt.side_data_elems;
  1126. return ret;
  1127. }
  1128. static void uncoded_frame_free(void *unused, uint8_t *data)
  1129. {
  1130. av_frame_free((AVFrame **)data);
  1131. av_free(data);
  1132. }
  1133. static int write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
  1134. AVFrame *frame, int interleaved)
  1135. {
  1136. AVPacket pkt, *pktp;
  1137. int ret;
  1138. av_assert0(s->oformat);
  1139. if (!s->oformat->write_uncoded_frame) {
  1140. av_frame_free(&frame);
  1141. return AVERROR(ENOSYS);
  1142. }
  1143. if (!frame) {
  1144. pktp = NULL;
  1145. } else {
  1146. size_t bufsize = sizeof(frame) + AV_INPUT_BUFFER_PADDING_SIZE;
  1147. AVFrame **framep = av_mallocz(bufsize);
  1148. if (!framep)
  1149. goto fail;
  1150. pktp = &pkt;
  1151. av_init_packet(&pkt);
  1152. pkt.buf = av_buffer_create((void *)framep, bufsize,
  1153. uncoded_frame_free, NULL, 0);
  1154. if (!pkt.buf) {
  1155. av_free(framep);
  1156. fail:
  1157. av_frame_free(&frame);
  1158. return AVERROR(ENOMEM);
  1159. }
  1160. *framep = frame;
  1161. pkt.data = (void *)framep;
  1162. pkt.size = sizeof(frame);
  1163. pkt.pts =
  1164. pkt.dts = frame->pts;
  1165. pkt.duration = frame->pkt_duration;
  1166. pkt.stream_index = stream_index;
  1167. pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
  1168. }
  1169. ret = interleaved ? av_interleaved_write_frame(s, pktp) :
  1170. av_write_frame(s, pktp);
  1171. if (pktp)
  1172. av_packet_unref(pktp);
  1173. return ret;
  1174. }
  1175. int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
  1176. AVFrame *frame)
  1177. {
  1178. return write_uncoded_frame_internal(s, stream_index, frame, 0);
  1179. }
  1180. int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
  1181. AVFrame *frame)
  1182. {
  1183. return write_uncoded_frame_internal(s, stream_index, frame, 1);
  1184. }
  1185. int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
  1186. {
  1187. av_assert0(s->oformat);
  1188. if (!s->oformat->write_uncoded_frame)
  1189. return AVERROR(ENOSYS);
  1190. return s->oformat->write_uncoded_frame(s, stream_index, NULL,
  1191. AV_WRITE_UNCODED_FRAME_QUERY);
  1192. }