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.

1389 lines
45KB

  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. /* Note: using sizeof(AVFrame) from outside lavu is unsafe in general, but
  486. it is only being used internally to this file as a consistency check.
  487. The value is chosen to be very unlikely to appear on its own and to cause
  488. immediate failure if used anywhere as a real size. */
  489. #define UNCODED_FRAME_PACKET_SIZE (INT_MIN / 3 * 2 + (int)sizeof(AVFrame))
  490. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  491. FF_DISABLE_DEPRECATION_WARNINGS
  492. //FIXME merge with compute_pkt_fields
  493. static int compute_muxer_pkt_fields(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  494. {
  495. int delay = FFMAX(st->codecpar->video_delay, st->internal->avctx->max_b_frames > 0);
  496. int num, den, i;
  497. int frame_size;
  498. if (!s->internal->missing_ts_warning &&
  499. !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
  500. (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC) || (st->disposition & AV_DISPOSITION_TIMED_THUMBNAILS)) &&
  501. (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
  502. av_log(s, AV_LOG_WARNING,
  503. "Timestamps are unset in a packet for stream %d. "
  504. "This is deprecated and will stop working in the future. "
  505. "Fix your code to set the timestamps properly\n", st->index);
  506. s->internal->missing_ts_warning = 1;
  507. }
  508. if (s->debug & FF_FDEBUG_TS)
  509. av_log(s, AV_LOG_DEBUG, "compute_muxer_pkt_fields: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
  510. av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
  511. if (pkt->duration < 0 && st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
  512. av_log(s, AV_LOG_WARNING, "Packet with invalid duration %"PRId64" in stream %d\n",
  513. pkt->duration, pkt->stream_index);
  514. pkt->duration = 0;
  515. }
  516. /* duration field */
  517. if (pkt->duration == 0) {
  518. ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
  519. if (den && num) {
  520. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  521. }
  522. }
  523. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  524. pkt->pts = pkt->dts;
  525. //XXX/FIXME this is a temporary hack until all encoders output pts
  526. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  527. static int warned;
  528. if (!warned) {
  529. av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
  530. warned = 1;
  531. }
  532. pkt->dts =
  533. // pkt->pts= st->cur_dts;
  534. pkt->pts = st->internal->priv_pts->val;
  535. }
  536. //calculate dts from pts
  537. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  538. st->pts_buffer[0] = pkt->pts;
  539. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  540. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  541. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  542. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  543. pkt->dts = st->pts_buffer[0];
  544. }
  545. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  546. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  547. st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE &&
  548. st->codecpar->codec_type != AVMEDIA_TYPE_DATA &&
  549. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  550. av_log(s, AV_LOG_ERROR,
  551. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
  552. st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
  553. return AVERROR(EINVAL);
  554. }
  555. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  556. av_log(s, AV_LOG_ERROR,
  557. "pts (%s) < dts (%s) in stream %d\n",
  558. av_ts2str(pkt->pts), av_ts2str(pkt->dts),
  559. st->index);
  560. return AVERROR(EINVAL);
  561. }
  562. if (s->debug & FF_FDEBUG_TS)
  563. av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%s dts2:%s\n",
  564. av_ts2str(pkt->pts), av_ts2str(pkt->dts));
  565. st->cur_dts = pkt->dts;
  566. st->internal->priv_pts->val = pkt->dts;
  567. /* update pts */
  568. switch (st->codecpar->codec_type) {
  569. case AVMEDIA_TYPE_AUDIO:
  570. frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
  571. ((AVFrame *)pkt->data)->nb_samples :
  572. av_get_audio_frame_duration(st->codec, pkt->size);
  573. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  574. * likely equal to the encoder delay, but it would be better if we
  575. * had the real timestamps from the encoder */
  576. if (frame_size >= 0 && (pkt->size || st->internal->priv_pts->num != st->internal->priv_pts->den >> 1 || st->internal->priv_pts->val)) {
  577. frac_add(st->internal->priv_pts, (int64_t)st->time_base.den * frame_size);
  578. }
  579. break;
  580. case AVMEDIA_TYPE_VIDEO:
  581. frac_add(st->internal->priv_pts, (int64_t)st->time_base.den * st->time_base.num);
  582. break;
  583. }
  584. return 0;
  585. }
  586. FF_ENABLE_DEPRECATION_WARNINGS
  587. #endif
  588. /**
  589. * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  590. * sidedata.
  591. *
  592. * FIXME: this function should NEVER get undefined pts/dts beside when the
  593. * AVFMT_NOTIMESTAMPS is set.
  594. * Those additional safety checks should be dropped once the correct checks
  595. * are set in the callers.
  596. */
  597. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  598. {
  599. int ret;
  600. int64_t pts_backup, dts_backup;
  601. pts_backup = pkt->pts;
  602. dts_backup = pkt->dts;
  603. // If the timestamp offsetting below is adjusted, adjust
  604. // ff_interleaved_peek similarly.
  605. if (s->output_ts_offset) {
  606. AVStream *st = s->streams[pkt->stream_index];
  607. int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
  608. if (pkt->dts != AV_NOPTS_VALUE)
  609. pkt->dts += offset;
  610. if (pkt->pts != AV_NOPTS_VALUE)
  611. pkt->pts += offset;
  612. }
  613. if (s->avoid_negative_ts > 0) {
  614. AVStream *st = s->streams[pkt->stream_index];
  615. int64_t offset = st->mux_ts_offset;
  616. int64_t ts = s->internal->avoid_negative_ts_use_pts ? pkt->pts : pkt->dts;
  617. if (s->internal->offset == AV_NOPTS_VALUE && ts != AV_NOPTS_VALUE &&
  618. (ts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
  619. s->internal->offset = -ts;
  620. s->internal->offset_timebase = st->time_base;
  621. }
  622. if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
  623. offset = st->mux_ts_offset =
  624. av_rescale_q_rnd(s->internal->offset,
  625. s->internal->offset_timebase,
  626. st->time_base,
  627. AV_ROUND_UP);
  628. }
  629. if (pkt->dts != AV_NOPTS_VALUE)
  630. pkt->dts += offset;
  631. if (pkt->pts != AV_NOPTS_VALUE)
  632. pkt->pts += offset;
  633. if (s->internal->avoid_negative_ts_use_pts) {
  634. if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
  635. av_log(s, AV_LOG_WARNING, "failed to avoid negative "
  636. "pts %s in stream %d.\n"
  637. "Try -avoid_negative_ts 1 as a possible workaround.\n",
  638. av_ts2str(pkt->pts),
  639. pkt->stream_index
  640. );
  641. }
  642. } else {
  643. av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0 || s->max_interleave_delta > 0);
  644. if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
  645. av_log(s, AV_LOG_WARNING,
  646. "Packets poorly interleaved, failed to avoid negative "
  647. "timestamp %s in stream %d.\n"
  648. "Try -max_interleave_delta 0 as a possible workaround.\n",
  649. av_ts2str(pkt->dts),
  650. pkt->stream_index
  651. );
  652. }
  653. }
  654. }
  655. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  656. AVFrame *frame = (AVFrame *)pkt->data;
  657. av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
  658. ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
  659. av_frame_free(&frame);
  660. } else {
  661. ret = s->oformat->write_packet(s, pkt);
  662. }
  663. if (s->pb && ret >= 0) {
  664. flush_if_needed(s);
  665. if (s->pb->error < 0)
  666. ret = s->pb->error;
  667. }
  668. if (ret < 0) {
  669. pkt->pts = pts_backup;
  670. pkt->dts = dts_backup;
  671. }
  672. return ret;
  673. }
  674. static int check_packet(AVFormatContext *s, AVPacket *pkt)
  675. {
  676. if (!pkt)
  677. return 0;
  678. if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
  679. av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
  680. pkt->stream_index);
  681. return AVERROR(EINVAL);
  682. }
  683. if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
  684. av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
  685. return AVERROR(EINVAL);
  686. }
  687. return 0;
  688. }
  689. static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
  690. {
  691. int ret;
  692. ret = check_packet(s, pkt);
  693. if (ret < 0)
  694. return ret;
  695. #if !FF_API_COMPUTE_PKT_FIELDS2 || !FF_API_LAVF_AVCTX
  696. /* sanitize the timestamps */
  697. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  698. AVStream *st = s->streams[pkt->stream_index];
  699. /* when there is no reordering (so dts is equal to pts), but
  700. * only one of them is set, set the other as well */
  701. if (!st->internal->reorder) {
  702. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
  703. pkt->pts = pkt->dts;
  704. if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
  705. pkt->dts = pkt->pts;
  706. }
  707. /* check that the timestamps are set */
  708. if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
  709. av_log(s, AV_LOG_ERROR,
  710. "Timestamps are unset in a packet for stream %d\n", st->index);
  711. return AVERROR(EINVAL);
  712. }
  713. /* check that the dts are increasing (or at least non-decreasing,
  714. * if the format allows it */
  715. if (st->cur_dts != AV_NOPTS_VALUE &&
  716. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
  717. st->cur_dts > pkt->dts)) {
  718. av_log(s, AV_LOG_ERROR,
  719. "Application provided invalid, non monotonically increasing "
  720. "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
  721. st->index, st->cur_dts, pkt->dts);
  722. return AVERROR(EINVAL);
  723. }
  724. if (pkt->pts < pkt->dts) {
  725. av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
  726. pkt->pts, pkt->dts, st->index);
  727. return AVERROR(EINVAL);
  728. }
  729. }
  730. #endif
  731. return 0;
  732. }
  733. static int do_packet_auto_bsf(AVFormatContext *s, AVPacket *pkt) {
  734. AVStream *st = s->streams[pkt->stream_index];
  735. int i, ret;
  736. if (!(s->flags & AVFMT_FLAG_AUTO_BSF))
  737. return 1;
  738. if (s->oformat->check_bitstream) {
  739. if (!st->internal->bitstream_checked) {
  740. if ((ret = s->oformat->check_bitstream(s, pkt)) < 0)
  741. return ret;
  742. else if (ret == 1)
  743. st->internal->bitstream_checked = 1;
  744. }
  745. }
  746. for (i = 0; i < st->internal->nb_bsfcs; i++) {
  747. AVBSFContext *ctx = st->internal->bsfcs[i];
  748. // TODO: when any bitstream filter requires flushing at EOF, we'll need to
  749. // flush each stream's BSF chain on write_trailer.
  750. if ((ret = av_bsf_send_packet(ctx, pkt)) < 0) {
  751. av_log(ctx, AV_LOG_ERROR,
  752. "Failed to send packet to filter %s for stream %d\n",
  753. ctx->filter->name, pkt->stream_index);
  754. return ret;
  755. }
  756. // TODO: when any automatically-added bitstream filter is generating multiple
  757. // output packets for a single input one, we'll need to call this in a loop
  758. // and write each output packet.
  759. if ((ret = av_bsf_receive_packet(ctx, pkt)) < 0) {
  760. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  761. return 0;
  762. av_log(ctx, AV_LOG_ERROR,
  763. "Failed to receive packet from filter %s for stream %d\n",
  764. ctx->filter->name, pkt->stream_index);
  765. if (s->error_recognition & AV_EF_EXPLODE)
  766. return ret;
  767. return 0;
  768. }
  769. }
  770. return 1;
  771. }
  772. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  773. {
  774. int ret;
  775. ret = prepare_input_packet(s, pkt);
  776. if (ret < 0)
  777. return ret;
  778. if (!pkt) {
  779. if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
  780. ret = s->oformat->write_packet(s, NULL);
  781. flush_if_needed(s);
  782. if (ret >= 0 && s->pb && s->pb->error < 0)
  783. ret = s->pb->error;
  784. return ret;
  785. }
  786. return 1;
  787. }
  788. ret = do_packet_auto_bsf(s, pkt);
  789. if (ret <= 0)
  790. return ret;
  791. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  792. ret = compute_muxer_pkt_fields(s, s->streams[pkt->stream_index], pkt);
  793. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  794. return ret;
  795. #endif
  796. ret = write_packet(s, pkt);
  797. if (ret >= 0 && s->pb && s->pb->error < 0)
  798. ret = s->pb->error;
  799. if (ret >= 0)
  800. s->streams[pkt->stream_index]->nb_frames++;
  801. return ret;
  802. }
  803. #define CHUNK_START 0x1000
  804. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  805. int (*compare)(AVFormatContext *, const AVPacket *, const AVPacket *))
  806. {
  807. int ret;
  808. AVPacketList **next_point, *this_pktl;
  809. AVStream *st = s->streams[pkt->stream_index];
  810. int chunked = s->max_chunk_size || s->max_chunk_duration;
  811. this_pktl = av_mallocz(sizeof(AVPacketList));
  812. if (!this_pktl)
  813. return AVERROR(ENOMEM);
  814. if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
  815. av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
  816. av_assert0(((AVFrame *)pkt->data)->buf);
  817. this_pktl->pkt = *pkt;
  818. pkt->buf = NULL;
  819. pkt->side_data = NULL;
  820. pkt->side_data_elems = 0;
  821. } else {
  822. if ((ret = av_packet_ref(&this_pktl->pkt, pkt)) < 0) {
  823. av_free(this_pktl);
  824. return ret;
  825. }
  826. }
  827. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  828. next_point = &(st->last_in_packet_buffer->next);
  829. } else {
  830. next_point = &s->internal->packet_buffer;
  831. }
  832. if (chunked) {
  833. uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
  834. st->interleaver_chunk_size += pkt->size;
  835. st->interleaver_chunk_duration += pkt->duration;
  836. if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
  837. || (max && st->interleaver_chunk_duration > max)) {
  838. st->interleaver_chunk_size = 0;
  839. this_pktl->pkt.flags |= CHUNK_START;
  840. if (max && st->interleaver_chunk_duration > max) {
  841. int64_t syncoffset = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
  842. int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
  843. st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
  844. } else
  845. st->interleaver_chunk_duration = 0;
  846. }
  847. }
  848. if (*next_point) {
  849. if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
  850. goto next_non_null;
  851. if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
  852. while ( *next_point
  853. && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
  854. || !compare(s, &(*next_point)->pkt, pkt)))
  855. next_point = &(*next_point)->next;
  856. if (*next_point)
  857. goto next_non_null;
  858. } else {
  859. next_point = &(s->internal->packet_buffer_end->next);
  860. }
  861. }
  862. av_assert1(!*next_point);
  863. s->internal->packet_buffer_end = this_pktl;
  864. next_non_null:
  865. this_pktl->next = *next_point;
  866. s->streams[pkt->stream_index]->last_in_packet_buffer =
  867. *next_point = this_pktl;
  868. av_packet_unref(pkt);
  869. return 0;
  870. }
  871. static int interleave_compare_dts(AVFormatContext *s, const AVPacket *next,
  872. const AVPacket *pkt)
  873. {
  874. AVStream *st = s->streams[pkt->stream_index];
  875. AVStream *st2 = s->streams[next->stream_index];
  876. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  877. st->time_base);
  878. if (s->audio_preload) {
  879. int preload = st ->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
  880. int preload2 = st2->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
  881. if (preload != preload2) {
  882. int64_t ts, ts2;
  883. preload *= s->audio_preload;
  884. preload2 *= s->audio_preload;
  885. ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - preload;
  886. ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - preload2;
  887. if (ts == ts2) {
  888. ts = ((uint64_t)pkt ->dts*st ->time_base.num*AV_TIME_BASE - (uint64_t)preload *st ->time_base.den)*st2->time_base.den
  889. - ((uint64_t)next->dts*st2->time_base.num*AV_TIME_BASE - (uint64_t)preload2*st2->time_base.den)*st ->time_base.den;
  890. ts2 = 0;
  891. }
  892. comp = (ts2 > ts) - (ts2 < ts);
  893. }
  894. }
  895. if (comp == 0)
  896. return pkt->stream_index < next->stream_index;
  897. return comp > 0;
  898. }
  899. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  900. AVPacket *pkt, int flush)
  901. {
  902. AVPacketList *pktl;
  903. int stream_count = 0;
  904. int noninterleaved_count = 0;
  905. int i, ret;
  906. int eof = flush;
  907. if (pkt) {
  908. if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
  909. return ret;
  910. }
  911. for (i = 0; i < s->nb_streams; i++) {
  912. if (s->streams[i]->last_in_packet_buffer) {
  913. ++stream_count;
  914. } else if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
  915. s->streams[i]->codecpar->codec_id != AV_CODEC_ID_VP8 &&
  916. s->streams[i]->codecpar->codec_id != AV_CODEC_ID_VP9) {
  917. ++noninterleaved_count;
  918. }
  919. }
  920. if (s->internal->nb_interleaved_streams == stream_count)
  921. flush = 1;
  922. if (s->max_interleave_delta > 0 &&
  923. s->internal->packet_buffer &&
  924. !flush &&
  925. s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
  926. ) {
  927. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  928. int64_t delta_dts = INT64_MIN;
  929. int64_t top_dts = av_rescale_q(top_pkt->dts,
  930. s->streams[top_pkt->stream_index]->time_base,
  931. AV_TIME_BASE_Q);
  932. for (i = 0; i < s->nb_streams; i++) {
  933. int64_t last_dts;
  934. const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
  935. if (!last)
  936. continue;
  937. last_dts = av_rescale_q(last->pkt.dts,
  938. s->streams[i]->time_base,
  939. AV_TIME_BASE_Q);
  940. delta_dts = FFMAX(delta_dts, last_dts - top_dts);
  941. }
  942. if (delta_dts > s->max_interleave_delta) {
  943. av_log(s, AV_LOG_DEBUG,
  944. "Delay between the first packet and last packet in the "
  945. "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
  946. delta_dts, s->max_interleave_delta);
  947. flush = 1;
  948. }
  949. }
  950. if (s->internal->packet_buffer &&
  951. eof &&
  952. (s->flags & AVFMT_FLAG_SHORTEST) &&
  953. s->internal->shortest_end == AV_NOPTS_VALUE) {
  954. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  955. s->internal->shortest_end = av_rescale_q(top_pkt->dts,
  956. s->streams[top_pkt->stream_index]->time_base,
  957. AV_TIME_BASE_Q);
  958. }
  959. if (s->internal->shortest_end != AV_NOPTS_VALUE) {
  960. while (s->internal->packet_buffer) {
  961. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  962. AVStream *st;
  963. int64_t top_dts = av_rescale_q(top_pkt->dts,
  964. s->streams[top_pkt->stream_index]->time_base,
  965. AV_TIME_BASE_Q);
  966. if (s->internal->shortest_end + 1 >= top_dts)
  967. break;
  968. pktl = s->internal->packet_buffer;
  969. st = s->streams[pktl->pkt.stream_index];
  970. s->internal->packet_buffer = pktl->next;
  971. if (!s->internal->packet_buffer)
  972. s->internal->packet_buffer_end = NULL;
  973. if (st->last_in_packet_buffer == pktl)
  974. st->last_in_packet_buffer = NULL;
  975. av_packet_unref(&pktl->pkt);
  976. av_freep(&pktl);
  977. flush = 0;
  978. }
  979. }
  980. if (stream_count && flush) {
  981. AVStream *st;
  982. pktl = s->internal->packet_buffer;
  983. *out = pktl->pkt;
  984. st = s->streams[out->stream_index];
  985. s->internal->packet_buffer = pktl->next;
  986. if (!s->internal->packet_buffer)
  987. s->internal->packet_buffer_end = NULL;
  988. if (st->last_in_packet_buffer == pktl)
  989. st->last_in_packet_buffer = NULL;
  990. av_freep(&pktl);
  991. return 1;
  992. } else {
  993. av_init_packet(out);
  994. return 0;
  995. }
  996. }
  997. int ff_interleaved_peek(AVFormatContext *s, int stream,
  998. AVPacket *pkt, int add_offset)
  999. {
  1000. AVPacketList *pktl = s->internal->packet_buffer;
  1001. while (pktl) {
  1002. if (pktl->pkt.stream_index == stream) {
  1003. *pkt = pktl->pkt;
  1004. if (add_offset) {
  1005. AVStream *st = s->streams[pkt->stream_index];
  1006. int64_t offset = st->mux_ts_offset;
  1007. if (s->output_ts_offset)
  1008. offset += av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
  1009. if (pkt->dts != AV_NOPTS_VALUE)
  1010. pkt->dts += offset;
  1011. if (pkt->pts != AV_NOPTS_VALUE)
  1012. pkt->pts += offset;
  1013. }
  1014. return 0;
  1015. }
  1016. pktl = pktl->next;
  1017. }
  1018. return AVERROR(ENOENT);
  1019. }
  1020. /**
  1021. * Interleave an AVPacket correctly so it can be muxed.
  1022. * @param out the interleaved packet will be output here
  1023. * @param in the input packet
  1024. * @param flush 1 if no further packets are available as input and all
  1025. * remaining packets should be output
  1026. * @return 1 if a packet was output, 0 if no packet could be output,
  1027. * < 0 if an error occurred
  1028. */
  1029. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  1030. {
  1031. if (s->oformat->interleave_packet) {
  1032. int ret = s->oformat->interleave_packet(s, out, in, flush);
  1033. if (in)
  1034. av_packet_unref(in);
  1035. return ret;
  1036. } else
  1037. return ff_interleave_packet_per_dts(s, out, in, flush);
  1038. }
  1039. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  1040. {
  1041. int ret, flush = 0;
  1042. ret = prepare_input_packet(s, pkt);
  1043. if (ret < 0)
  1044. goto fail;
  1045. if (pkt) {
  1046. AVStream *st = s->streams[pkt->stream_index];
  1047. ret = do_packet_auto_bsf(s, pkt);
  1048. if (ret == 0)
  1049. return 0;
  1050. else if (ret < 0)
  1051. goto fail;
  1052. if (s->debug & FF_FDEBUG_TS)
  1053. av_log(s, AV_LOG_DEBUG, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
  1054. pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
  1055. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  1056. if ((ret = compute_muxer_pkt_fields(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  1057. goto fail;
  1058. #endif
  1059. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  1060. ret = AVERROR(EINVAL);
  1061. goto fail;
  1062. }
  1063. } else {
  1064. av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
  1065. flush = 1;
  1066. }
  1067. for (;; ) {
  1068. AVPacket opkt;
  1069. int ret = interleave_packet(s, &opkt, pkt, flush);
  1070. if (pkt) {
  1071. memset(pkt, 0, sizeof(*pkt));
  1072. av_init_packet(pkt);
  1073. pkt = NULL;
  1074. }
  1075. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  1076. return ret;
  1077. ret = write_packet(s, &opkt);
  1078. if (ret >= 0)
  1079. s->streams[opkt.stream_index]->nb_frames++;
  1080. av_packet_unref(&opkt);
  1081. if (ret < 0)
  1082. return ret;
  1083. if(s->pb && s->pb->error)
  1084. return s->pb->error;
  1085. }
  1086. fail:
  1087. av_packet_unref(pkt);
  1088. return ret;
  1089. }
  1090. int av_write_trailer(AVFormatContext *s)
  1091. {
  1092. int ret, i;
  1093. for (;; ) {
  1094. AVPacket pkt;
  1095. ret = interleave_packet(s, &pkt, NULL, 1);
  1096. if (ret < 0)
  1097. goto fail;
  1098. if (!ret)
  1099. break;
  1100. ret = write_packet(s, &pkt);
  1101. if (ret >= 0)
  1102. s->streams[pkt.stream_index]->nb_frames++;
  1103. av_packet_unref(&pkt);
  1104. if (ret < 0)
  1105. goto fail;
  1106. if(s->pb && s->pb->error)
  1107. goto fail;
  1108. }
  1109. fail:
  1110. if (s->oformat->write_trailer) {
  1111. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  1112. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  1113. if (ret >= 0) {
  1114. ret = s->oformat->write_trailer(s);
  1115. } else {
  1116. s->oformat->write_trailer(s);
  1117. }
  1118. }
  1119. deinit_muxer(s);
  1120. if (s->pb)
  1121. avio_flush(s->pb);
  1122. if (ret == 0)
  1123. ret = s->pb ? s->pb->error : 0;
  1124. for (i = 0; i < s->nb_streams; i++) {
  1125. av_freep(&s->streams[i]->priv_data);
  1126. av_freep(&s->streams[i]->index_entries);
  1127. }
  1128. if (s->oformat->priv_class)
  1129. av_opt_free(s->priv_data);
  1130. av_freep(&s->priv_data);
  1131. return ret;
  1132. }
  1133. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  1134. int64_t *dts, int64_t *wall)
  1135. {
  1136. if (!s->oformat || !s->oformat->get_output_timestamp)
  1137. return AVERROR(ENOSYS);
  1138. s->oformat->get_output_timestamp(s, stream, dts, wall);
  1139. return 0;
  1140. }
  1141. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  1142. AVFormatContext *src, int interleave)
  1143. {
  1144. AVPacket local_pkt;
  1145. int ret;
  1146. local_pkt = *pkt;
  1147. local_pkt.stream_index = dst_stream;
  1148. av_packet_rescale_ts(&local_pkt,
  1149. src->streams[pkt->stream_index]->time_base,
  1150. dst->streams[dst_stream]->time_base);
  1151. if (interleave) ret = av_interleaved_write_frame(dst, &local_pkt);
  1152. else ret = av_write_frame(dst, &local_pkt);
  1153. pkt->buf = local_pkt.buf;
  1154. pkt->side_data = local_pkt.side_data;
  1155. pkt->side_data_elems = local_pkt.side_data_elems;
  1156. return ret;
  1157. }
  1158. static int av_write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
  1159. AVFrame *frame, int interleaved)
  1160. {
  1161. AVPacket pkt, *pktp;
  1162. av_assert0(s->oformat);
  1163. if (!s->oformat->write_uncoded_frame)
  1164. return AVERROR(ENOSYS);
  1165. if (!frame) {
  1166. pktp = NULL;
  1167. } else {
  1168. pktp = &pkt;
  1169. av_init_packet(&pkt);
  1170. pkt.data = (void *)frame;
  1171. pkt.size = UNCODED_FRAME_PACKET_SIZE;
  1172. pkt.pts =
  1173. pkt.dts = frame->pts;
  1174. pkt.duration = frame->pkt_duration;
  1175. pkt.stream_index = stream_index;
  1176. pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
  1177. }
  1178. return interleaved ? av_interleaved_write_frame(s, pktp) :
  1179. av_write_frame(s, pktp);
  1180. }
  1181. int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
  1182. AVFrame *frame)
  1183. {
  1184. return av_write_uncoded_frame_internal(s, stream_index, frame, 0);
  1185. }
  1186. int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
  1187. AVFrame *frame)
  1188. {
  1189. return av_write_uncoded_frame_internal(s, stream_index, frame, 1);
  1190. }
  1191. int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
  1192. {
  1193. av_assert0(s->oformat);
  1194. if (!s->oformat->write_uncoded_frame)
  1195. return AVERROR(ENOSYS);
  1196. return s->oformat->write_uncoded_frame(s, stream_index, NULL,
  1197. AV_WRITE_UNCODED_FRAME_QUERY);
  1198. }