mux.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. /*
  2. * muxing functions for use within Libav
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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 "metadata.h"
  30. #include "id3v2.h"
  31. #include "libavutil/avstring.h"
  32. #include "libavutil/internal.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/parseutils.h"
  35. #include "libavutil/time.h"
  36. #include "riff.h"
  37. #include "audiointerleave.h"
  38. #include "url.h"
  39. #include <stdarg.h>
  40. #if CONFIG_NETWORK
  41. #include "network.h"
  42. #endif
  43. #undef NDEBUG
  44. #include <assert.h>
  45. /**
  46. * @file
  47. * muxing functions for use within Libav
  48. */
  49. static int validate_codec_tag(AVFormatContext *s, AVStream *st)
  50. {
  51. const AVCodecTag *avctag;
  52. int n;
  53. enum AVCodecID id = AV_CODEC_ID_NONE;
  54. unsigned int tag = 0;
  55. /**
  56. * Check that tag + id is in the table
  57. * If neither is in the table -> OK
  58. * If tag is in the table with another id -> FAIL
  59. * If id is in the table with another tag -> FAIL unless strict < normal
  60. */
  61. for (n = 0; s->oformat->codec_tag[n]; n++) {
  62. avctag = s->oformat->codec_tag[n];
  63. while (avctag->id != AV_CODEC_ID_NONE) {
  64. if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codecpar->codec_tag)) {
  65. id = avctag->id;
  66. if (id == st->codecpar->codec_id)
  67. return 1;
  68. }
  69. if (avctag->id == st->codecpar->codec_id)
  70. tag = avctag->tag;
  71. avctag++;
  72. }
  73. }
  74. if (id != AV_CODEC_ID_NONE)
  75. return 0;
  76. if (tag && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
  77. return 0;
  78. return 1;
  79. }
  80. static int init_muxer(AVFormatContext *s, AVDictionary **options)
  81. {
  82. int ret = 0, i;
  83. AVStream *st;
  84. AVDictionary *tmp = NULL;
  85. AVCodecParameters *par = NULL;
  86. AVOutputFormat *of = s->oformat;
  87. const AVCodecDescriptor *desc;
  88. if (options)
  89. av_dict_copy(&tmp, *options, 0);
  90. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  91. goto fail;
  92. #if FF_API_LAVF_BITEXACT && FF_API_LAVF_AVCTX
  93. FF_DISABLE_DEPRECATION_WARNINGS
  94. if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT)
  95. s->flags |= AVFMT_FLAG_BITEXACT;
  96. FF_ENABLE_DEPRECATION_WARNINGS
  97. #endif
  98. // some sanity checks
  99. if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
  100. av_log(s, AV_LOG_ERROR, "no streams\n");
  101. ret = AVERROR(EINVAL);
  102. goto fail;
  103. }
  104. for (i = 0; i < s->nb_streams; i++) {
  105. st = s->streams[i];
  106. par = st->codecpar;
  107. #if FF_API_LAVF_CODEC_TB && FF_API_LAVF_AVCTX
  108. FF_DISABLE_DEPRECATION_WARNINGS
  109. if (!st->time_base.num && st->codec->time_base.num) {
  110. av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
  111. "timebase hint to the muxer is deprecated. Set "
  112. "AVStream.time_base instead.\n");
  113. avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
  114. }
  115. FF_ENABLE_DEPRECATION_WARNINGS
  116. #endif
  117. #if FF_API_LAVF_AVCTX
  118. FF_DISABLE_DEPRECATION_WARNINGS
  119. if (st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
  120. st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
  121. av_log(s, AV_LOG_WARNING, "Using AVStream.codec to pass codec "
  122. "parameters to muxers is deprecated, use AVStream.codecpar "
  123. "instead.\n");
  124. ret = avcodec_parameters_from_context(st->codecpar, st->codec);
  125. if (ret < 0)
  126. goto fail;
  127. }
  128. FF_ENABLE_DEPRECATION_WARNINGS
  129. #endif
  130. if (!st->time_base.num) {
  131. /* fall back on the default timebase values */
  132. if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)
  133. avpriv_set_pts_info(st, 64, 1, par->sample_rate);
  134. else
  135. avpriv_set_pts_info(st, 33, 1, 90000);
  136. }
  137. switch (par->codec_type) {
  138. case AVMEDIA_TYPE_AUDIO:
  139. if (par->sample_rate <= 0) {
  140. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  141. ret = AVERROR(EINVAL);
  142. goto fail;
  143. }
  144. if (!par->block_align)
  145. par->block_align = par->channels *
  146. av_get_bits_per_sample(par->codec_id) >> 3;
  147. break;
  148. case AVMEDIA_TYPE_VIDEO:
  149. if ((par->width <= 0 || par->height <= 0) &&
  150. !(of->flags & AVFMT_NODIMENSIONS)) {
  151. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  152. ret = AVERROR(EINVAL);
  153. goto fail;
  154. }
  155. if (av_cmp_q(st->sample_aspect_ratio,
  156. par->sample_aspect_ratio)) {
  157. if (st->sample_aspect_ratio.num != 0 &&
  158. st->sample_aspect_ratio.den != 0 &&
  159. par->sample_aspect_ratio.den != 0 &&
  160. par->sample_aspect_ratio.den != 0) {
  161. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
  162. "(%d/%d) and encoder layer (%d/%d)\n",
  163. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  164. par->sample_aspect_ratio.num,
  165. par->sample_aspect_ratio.den);
  166. ret = AVERROR(EINVAL);
  167. goto fail;
  168. }
  169. }
  170. break;
  171. }
  172. desc = avcodec_descriptor_get(par->codec_id);
  173. if (desc && desc->props & AV_CODEC_PROP_REORDER)
  174. st->internal->reorder = 1;
  175. if (of->codec_tag) {
  176. if (par->codec_tag &&
  177. par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  178. !av_codec_get_tag(of->codec_tag, par->codec_id) &&
  179. !validate_codec_tag(s, st)) {
  180. // the current rawvideo encoding system ends up setting
  181. // the wrong codec_tag for avi, we override it here
  182. par->codec_tag = 0;
  183. }
  184. if (par->codec_tag) {
  185. if (!validate_codec_tag(s, st)) {
  186. char tagbuf[32];
  187. av_get_codec_tag_string(tagbuf, sizeof(tagbuf), par->codec_tag);
  188. av_log(s, AV_LOG_ERROR,
  189. "Tag %s/0x%08x incompatible with output codec id '%d'\n",
  190. tagbuf, par->codec_tag, par->codec_id);
  191. ret = AVERROR_INVALIDDATA;
  192. goto fail;
  193. }
  194. } else
  195. par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);
  196. }
  197. if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)
  198. s->internal->nb_interleaved_streams++;
  199. }
  200. if (!s->priv_data && of->priv_data_size > 0) {
  201. s->priv_data = av_mallocz(of->priv_data_size);
  202. if (!s->priv_data) {
  203. ret = AVERROR(ENOMEM);
  204. goto fail;
  205. }
  206. if (of->priv_class) {
  207. *(const AVClass **)s->priv_data = of->priv_class;
  208. av_opt_set_defaults(s->priv_data);
  209. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  210. goto fail;
  211. }
  212. }
  213. /* set muxer identification string */
  214. if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
  215. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  216. }
  217. if (options) {
  218. av_dict_free(options);
  219. *options = tmp;
  220. }
  221. return 0;
  222. fail:
  223. av_dict_free(&tmp);
  224. return ret;
  225. }
  226. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  227. {
  228. int ret = 0;
  229. if (ret = init_muxer(s, options))
  230. return ret;
  231. if (s->oformat->write_header) {
  232. ret = s->oformat->write_header(s);
  233. if (ret < 0)
  234. return ret;
  235. }
  236. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) {
  237. if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
  238. s->avoid_negative_ts = 0;
  239. } else
  240. s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
  241. }
  242. return 0;
  243. }
  244. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  245. FF_DISABLE_DEPRECATION_WARNINGS
  246. //FIXME merge with compute_pkt_fields
  247. static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  248. {
  249. int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
  250. int num, den, i;
  251. if (!s->internal->missing_ts_warning &&
  252. !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
  253. (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
  254. av_log(s, AV_LOG_WARNING,
  255. "Timestamps are unset in a packet for stream %d. "
  256. "This is deprecated and will stop working in the future. "
  257. "Fix your code to set the timestamps properly\n", st->index);
  258. s->internal->missing_ts_warning = 1;
  259. }
  260. av_log(s, AV_LOG_TRACE, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
  261. pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
  262. /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
  263. * return AVERROR(EINVAL);*/
  264. /* duration field */
  265. if (pkt->duration == 0) {
  266. ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
  267. if (den && num) {
  268. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  269. }
  270. }
  271. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  272. pkt->pts = pkt->dts;
  273. //calculate dts from pts
  274. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  275. st->pts_buffer[0] = pkt->pts;
  276. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  277. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  278. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  279. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  280. pkt->dts = st->pts_buffer[0];
  281. }
  282. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  283. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  284. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  285. av_log(s, AV_LOG_ERROR,
  286. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
  287. st->index, st->cur_dts, pkt->dts);
  288. return AVERROR(EINVAL);
  289. }
  290. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  291. av_log(s, AV_LOG_ERROR,
  292. "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
  293. pkt->pts, pkt->dts,
  294. st->index);
  295. return AVERROR(EINVAL);
  296. }
  297. av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
  298. pkt->pts, pkt->dts);
  299. st->cur_dts = pkt->dts;
  300. return 0;
  301. }
  302. FF_ENABLE_DEPRECATION_WARNINGS
  303. #endif
  304. /*
  305. * FIXME: this function should NEVER get undefined pts/dts beside when the
  306. * AVFMT_NOTIMESTAMPS is set.
  307. * Those additional safety checks should be dropped once the correct checks
  308. * are set in the callers.
  309. */
  310. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  311. {
  312. int ret;
  313. if (s->avoid_negative_ts > 0) {
  314. AVRational time_base = s->streams[pkt->stream_index]->time_base;
  315. int64_t offset = 0;
  316. if (s->internal->offset == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
  317. (pkt->dts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
  318. s->internal->offset = -pkt->dts;
  319. s->internal->offset_timebase = time_base;
  320. }
  321. if (s->internal->offset != AV_NOPTS_VALUE)
  322. offset = av_rescale_q(s->internal->offset, s->internal->offset_timebase, time_base);
  323. if (pkt->dts != AV_NOPTS_VALUE)
  324. pkt->dts += offset;
  325. if (pkt->pts != AV_NOPTS_VALUE)
  326. pkt->pts += offset;
  327. if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
  328. av_log(s, AV_LOG_WARNING,
  329. "Packets poorly interleaved, failed to avoid negative "
  330. "timestamp %"PRId64" in stream %d.\n"
  331. "Try -max_interleave_delta 0 as a possible workaround.\n",
  332. pkt->dts, pkt->stream_index);
  333. }
  334. }
  335. ret = s->oformat->write_packet(s, pkt);
  336. if (s->pb && ret >= 0) {
  337. if (s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  338. avio_flush(s->pb);
  339. if (s->pb->error < 0)
  340. ret = s->pb->error;
  341. }
  342. return ret;
  343. }
  344. static int check_packet(AVFormatContext *s, AVPacket *pkt)
  345. {
  346. if (!pkt)
  347. return 0;
  348. if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
  349. av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
  350. pkt->stream_index);
  351. return AVERROR(EINVAL);
  352. }
  353. if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
  354. av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
  355. return AVERROR(EINVAL);
  356. }
  357. return 0;
  358. }
  359. static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
  360. {
  361. int ret;
  362. ret = check_packet(s, pkt);
  363. if (ret < 0)
  364. return ret;
  365. #if !FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  366. /* sanitize the timestamps */
  367. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  368. AVStream *st = s->streams[pkt->stream_index];
  369. /* when there is no reordering (so dts is equal to pts), but
  370. * only one of them is set, set the other as well */
  371. if (!st->internal->reorder) {
  372. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
  373. pkt->pts = pkt->dts;
  374. if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
  375. pkt->dts = pkt->pts;
  376. }
  377. /* check that the timestamps are set */
  378. if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
  379. av_log(s, AV_LOG_ERROR,
  380. "Timestamps are unset in a packet for stream %d\n", st->index);
  381. return AVERROR(EINVAL);
  382. }
  383. /* check that the dts are increasing (or at least non-decreasing,
  384. * if the format allows it */
  385. if (st->cur_dts != AV_NOPTS_VALUE &&
  386. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
  387. st->cur_dts > pkt->dts)) {
  388. av_log(s, AV_LOG_ERROR,
  389. "Application provided invalid, non monotonically increasing "
  390. "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
  391. st->index, st->cur_dts, pkt->dts);
  392. return AVERROR(EINVAL);
  393. }
  394. if (pkt->pts < pkt->dts) {
  395. av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
  396. pkt->pts, pkt->dts, st->index);
  397. return AVERROR(EINVAL);
  398. }
  399. }
  400. #endif
  401. return 0;
  402. }
  403. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  404. {
  405. int ret;
  406. ret = prepare_input_packet(s, pkt);
  407. if (ret < 0)
  408. return ret;
  409. if (!pkt) {
  410. if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
  411. return s->oformat->write_packet(s, pkt);
  412. return 1;
  413. }
  414. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  415. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  416. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  417. return ret;
  418. #endif
  419. ret = write_packet(s, pkt);
  420. if (ret >= 0)
  421. s->streams[pkt->stream_index]->nb_frames++;
  422. return ret;
  423. }
  424. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  425. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  426. {
  427. int ret;
  428. AVPacketList **next_point, *this_pktl;
  429. this_pktl = av_mallocz(sizeof(AVPacketList));
  430. if (!this_pktl)
  431. return AVERROR(ENOMEM);
  432. if ((ret = av_packet_ref(&this_pktl->pkt, pkt)) < 0) {
  433. av_free(this_pktl);
  434. return ret;
  435. }
  436. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  437. next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
  438. } else
  439. next_point = &s->internal->packet_buffer;
  440. if (*next_point) {
  441. if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
  442. while (!compare(s, &(*next_point)->pkt, pkt))
  443. next_point = &(*next_point)->next;
  444. goto next_non_null;
  445. } else {
  446. next_point = &(s->internal->packet_buffer_end->next);
  447. }
  448. }
  449. assert(!*next_point);
  450. s->internal->packet_buffer_end = this_pktl;
  451. next_non_null:
  452. this_pktl->next = *next_point;
  453. s->streams[pkt->stream_index]->last_in_packet_buffer =
  454. *next_point = this_pktl;
  455. av_packet_unref(pkt);
  456. return 0;
  457. }
  458. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  459. AVPacket *pkt)
  460. {
  461. AVStream *st = s->streams[pkt->stream_index];
  462. AVStream *st2 = s->streams[next->stream_index];
  463. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  464. st->time_base);
  465. if (comp == 0)
  466. return pkt->stream_index < next->stream_index;
  467. return comp > 0;
  468. }
  469. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  470. AVPacket *pkt, int flush)
  471. {
  472. AVPacketList *pktl;
  473. int stream_count = 0;
  474. int i, ret;
  475. if (pkt) {
  476. if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
  477. return ret;
  478. }
  479. if (s->max_interleave_delta > 0 && s->internal->packet_buffer && !flush) {
  480. AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
  481. int64_t delta_dts = INT64_MIN;
  482. int64_t top_dts = av_rescale_q(top_pkt->dts,
  483. s->streams[top_pkt->stream_index]->time_base,
  484. AV_TIME_BASE_Q);
  485. for (i = 0; i < s->nb_streams; i++) {
  486. int64_t last_dts;
  487. const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
  488. if (!last)
  489. continue;
  490. last_dts = av_rescale_q(last->pkt.dts,
  491. s->streams[i]->time_base,
  492. AV_TIME_BASE_Q);
  493. delta_dts = FFMAX(delta_dts, last_dts - top_dts);
  494. stream_count++;
  495. }
  496. if (delta_dts > s->max_interleave_delta) {
  497. av_log(s, AV_LOG_DEBUG,
  498. "Delay between the first packet and last packet in the "
  499. "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
  500. delta_dts, s->max_interleave_delta);
  501. flush = 1;
  502. }
  503. } else {
  504. for (i = 0; i < s->nb_streams; i++)
  505. stream_count += !!s->streams[i]->last_in_packet_buffer;
  506. }
  507. if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
  508. pktl = s->internal->packet_buffer;
  509. *out = pktl->pkt;
  510. s->internal->packet_buffer = pktl->next;
  511. if (!s->internal->packet_buffer)
  512. s->internal->packet_buffer_end = NULL;
  513. if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
  514. s->streams[out->stream_index]->last_in_packet_buffer = NULL;
  515. av_freep(&pktl);
  516. return 1;
  517. } else {
  518. av_init_packet(out);
  519. return 0;
  520. }
  521. }
  522. /**
  523. * Interleave an AVPacket correctly so it can be muxed.
  524. * @param out the interleaved packet will be output here
  525. * @param in the input packet
  526. * @param flush 1 if no further packets are available as input and all
  527. * remaining packets should be output
  528. * @return 1 if a packet was output, 0 if no packet could be output,
  529. * < 0 if an error occurred
  530. */
  531. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  532. {
  533. if (s->oformat->interleave_packet) {
  534. int ret = s->oformat->interleave_packet(s, out, in, flush);
  535. if (in)
  536. av_packet_unref(in);
  537. return ret;
  538. } else
  539. return ff_interleave_packet_per_dts(s, out, in, flush);
  540. }
  541. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  542. {
  543. int ret, flush = 0;
  544. ret = prepare_input_packet(s, pkt);
  545. if (ret < 0)
  546. goto fail;
  547. if (pkt) {
  548. #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
  549. AVStream *st = s->streams[pkt->stream_index];
  550. av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
  551. pkt->size, pkt->dts, pkt->pts);
  552. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  553. goto fail;
  554. #endif
  555. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  556. ret = AVERROR(EINVAL);
  557. goto fail;
  558. }
  559. } else {
  560. av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
  561. flush = 1;
  562. }
  563. for (;; ) {
  564. AVPacket opkt;
  565. int ret = interleave_packet(s, &opkt, pkt, flush);
  566. if (pkt) {
  567. memset(pkt, 0, sizeof(*pkt));
  568. av_init_packet(pkt);
  569. pkt = NULL;
  570. }
  571. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  572. return ret;
  573. ret = write_packet(s, &opkt);
  574. if (ret >= 0)
  575. s->streams[opkt.stream_index]->nb_frames++;
  576. av_packet_unref(&opkt);
  577. if (ret < 0)
  578. return ret;
  579. }
  580. fail:
  581. av_packet_unref(pkt);
  582. return ret;
  583. }
  584. int av_write_trailer(AVFormatContext *s)
  585. {
  586. int ret, i;
  587. for (;; ) {
  588. AVPacket pkt;
  589. ret = interleave_packet(s, &pkt, NULL, 1);
  590. if (ret < 0) //FIXME cleanup needed for ret<0 ?
  591. goto fail;
  592. if (!ret)
  593. break;
  594. ret = write_packet(s, &pkt);
  595. if (ret >= 0)
  596. s->streams[pkt.stream_index]->nb_frames++;
  597. av_packet_unref(&pkt);
  598. if (ret < 0)
  599. goto fail;
  600. }
  601. if (s->oformat->write_trailer)
  602. ret = s->oformat->write_trailer(s);
  603. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  604. avio_flush(s->pb);
  605. fail:
  606. for (i = 0; i < s->nb_streams; i++) {
  607. av_freep(&s->streams[i]->priv_data);
  608. av_freep(&s->streams[i]->index_entries);
  609. }
  610. if (s->oformat->priv_class)
  611. av_opt_free(s->priv_data);
  612. av_freep(&s->priv_data);
  613. return ret;
  614. }
  615. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  616. AVFormatContext *src)
  617. {
  618. AVPacket local_pkt;
  619. local_pkt = *pkt;
  620. local_pkt.stream_index = dst_stream;
  621. if (pkt->pts != AV_NOPTS_VALUE)
  622. local_pkt.pts = av_rescale_q(pkt->pts,
  623. src->streams[pkt->stream_index]->time_base,
  624. dst->streams[dst_stream]->time_base);
  625. if (pkt->dts != AV_NOPTS_VALUE)
  626. local_pkt.dts = av_rescale_q(pkt->dts,
  627. src->streams[pkt->stream_index]->time_base,
  628. dst->streams[dst_stream]->time_base);
  629. return av_write_frame(dst, &local_pkt);
  630. }