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.

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