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.

1448 lines
47KB

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