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.

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