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.

866 lines
28KB

  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/mathematics.h"
  35. #include "libavutil/parseutils.h"
  36. #include "libavutil/time.h"
  37. #include "riff.h"
  38. #include "audiointerleave.h"
  39. #include "url.h"
  40. #include <stdarg.h>
  41. #if CONFIG_NETWORK
  42. #include "network.h"
  43. #endif
  44. #undef NDEBUG
  45. #include <assert.h>
  46. /**
  47. * @file
  48. * muxing functions for use within libavformat
  49. */
  50. /* fraction handling */
  51. /**
  52. * f = val + (num / den) + 0.5.
  53. *
  54. * 'num' is normalized so that it is such as 0 <= num < den.
  55. *
  56. * @param f fractional number
  57. * @param val integer value
  58. * @param num must be >= 0
  59. * @param den must be >= 1
  60. */
  61. static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
  62. {
  63. num += (den >> 1);
  64. if (num >= den) {
  65. val += num / den;
  66. num = num % den;
  67. }
  68. f->val = val;
  69. f->num = num;
  70. f->den = den;
  71. }
  72. /**
  73. * Fractional addition to f: f = f + (incr / f->den).
  74. *
  75. * @param f fractional number
  76. * @param incr increment, can be positive or negative
  77. */
  78. static void frac_add(AVFrac *f, int64_t incr)
  79. {
  80. int64_t num, den;
  81. num = f->num + incr;
  82. den = f->den;
  83. if (num < 0) {
  84. f->val += num / den;
  85. num = num % den;
  86. if (num < 0) {
  87. num += den;
  88. f->val--;
  89. }
  90. } else if (num >= den) {
  91. f->val += num / den;
  92. num = num % den;
  93. }
  94. f->num = num;
  95. }
  96. AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precission)
  97. {
  98. AVRational q;
  99. int j;
  100. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  101. q = (AVRational){1, st->codec->sample_rate};
  102. } else {
  103. q = st->codec->time_base;
  104. }
  105. for (j=2; j<14; j+= 1+(j>2))
  106. while (q.den / q.num < min_precission && q.num % j == 0)
  107. q.num /= j;
  108. while (q.den / q.num < min_precission && q.den < (1<<24))
  109. q.den <<= 1;
  110. return q;
  111. }
  112. int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
  113. const char *format, const char *filename)
  114. {
  115. AVFormatContext *s = avformat_alloc_context();
  116. int ret = 0;
  117. *avctx = NULL;
  118. if (!s)
  119. goto nomem;
  120. if (!oformat) {
  121. if (format) {
  122. oformat = av_guess_format(format, NULL, NULL);
  123. if (!oformat) {
  124. av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
  125. ret = AVERROR(EINVAL);
  126. goto error;
  127. }
  128. } else {
  129. oformat = av_guess_format(NULL, filename, NULL);
  130. if (!oformat) {
  131. ret = AVERROR(EINVAL);
  132. av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
  133. filename);
  134. goto error;
  135. }
  136. }
  137. }
  138. s->oformat = oformat;
  139. if (s->oformat->priv_data_size > 0) {
  140. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  141. if (!s->priv_data)
  142. goto nomem;
  143. if (s->oformat->priv_class) {
  144. *(const AVClass**)s->priv_data= s->oformat->priv_class;
  145. av_opt_set_defaults(s->priv_data);
  146. }
  147. } else
  148. s->priv_data = NULL;
  149. if (filename)
  150. av_strlcpy(s->filename, filename, sizeof(s->filename));
  151. *avctx = s;
  152. return 0;
  153. nomem:
  154. av_log(s, AV_LOG_ERROR, "Out of memory\n");
  155. ret = AVERROR(ENOMEM);
  156. error:
  157. avformat_free_context(s);
  158. return ret;
  159. }
  160. #if FF_API_ALLOC_OUTPUT_CONTEXT
  161. AVFormatContext *avformat_alloc_output_context(const char *format,
  162. AVOutputFormat *oformat, const char *filename)
  163. {
  164. AVFormatContext *avctx;
  165. int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
  166. return ret < 0 ? NULL : avctx;
  167. }
  168. #endif
  169. static int validate_codec_tag(AVFormatContext *s, AVStream *st)
  170. {
  171. const AVCodecTag *avctag;
  172. int n;
  173. enum AVCodecID id = AV_CODEC_ID_NONE;
  174. unsigned int tag = 0;
  175. /**
  176. * Check that tag + id is in the table
  177. * If neither is in the table -> OK
  178. * If tag is in the table with another id -> FAIL
  179. * If id is in the table with another tag -> FAIL unless strict < normal
  180. */
  181. for (n = 0; s->oformat->codec_tag[n]; n++) {
  182. avctag = s->oformat->codec_tag[n];
  183. while (avctag->id != AV_CODEC_ID_NONE) {
  184. if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
  185. id = avctag->id;
  186. if (id == st->codec->codec_id)
  187. return 1;
  188. }
  189. if (avctag->id == st->codec->codec_id)
  190. tag = avctag->tag;
  191. avctag++;
  192. }
  193. }
  194. if (id != AV_CODEC_ID_NONE)
  195. return 0;
  196. if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
  197. return 0;
  198. return 1;
  199. }
  200. static int init_muxer(AVFormatContext *s, AVDictionary **options)
  201. {
  202. int ret = 0, i;
  203. AVStream *st;
  204. AVDictionary *tmp = NULL;
  205. AVCodecContext *codec = NULL;
  206. AVOutputFormat *of = s->oformat;
  207. if (options)
  208. av_dict_copy(&tmp, *options, 0);
  209. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  210. goto fail;
  211. if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
  212. (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  213. goto fail;
  214. // some sanity checks
  215. if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
  216. av_log(s, AV_LOG_ERROR, "no streams\n");
  217. ret = AVERROR(EINVAL);
  218. goto fail;
  219. }
  220. for (i = 0; i < s->nb_streams; i++) {
  221. st = s->streams[i];
  222. codec = st->codec;
  223. switch (codec->codec_type) {
  224. case AVMEDIA_TYPE_AUDIO:
  225. if (codec->sample_rate <= 0) {
  226. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  227. ret = AVERROR(EINVAL);
  228. goto fail;
  229. }
  230. if (!codec->block_align)
  231. codec->block_align = codec->channels *
  232. av_get_bits_per_sample(codec->codec_id) >> 3;
  233. break;
  234. case AVMEDIA_TYPE_VIDEO:
  235. if (codec->time_base.num <= 0 ||
  236. codec->time_base.den <= 0) { //FIXME audio too?
  237. av_log(s, AV_LOG_ERROR, "time base not set\n");
  238. ret = AVERROR(EINVAL);
  239. goto fail;
  240. }
  241. if ((codec->width <= 0 || codec->height <= 0) &&
  242. !(of->flags & AVFMT_NODIMENSIONS)) {
  243. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  244. ret = AVERROR(EINVAL);
  245. goto fail;
  246. }
  247. if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
  248. && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
  249. ) {
  250. if (st->sample_aspect_ratio.num != 0 &&
  251. st->sample_aspect_ratio.den != 0 &&
  252. codec->sample_aspect_ratio.den != 0 &&
  253. codec->sample_aspect_ratio.den != 0) {
  254. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
  255. "(%d/%d) and encoder layer (%d/%d)\n",
  256. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  257. codec->sample_aspect_ratio.num,
  258. codec->sample_aspect_ratio.den);
  259. ret = AVERROR(EINVAL);
  260. goto fail;
  261. }
  262. }
  263. break;
  264. }
  265. if (of->codec_tag) {
  266. if ( codec->codec_tag
  267. && codec->codec_id == AV_CODEC_ID_RAWVIDEO
  268. && ( av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
  269. || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
  270. && !validate_codec_tag(s, st)) {
  271. // the current rawvideo encoding system ends up setting
  272. // the wrong codec_tag for avi/mov, we override it here
  273. codec->codec_tag = 0;
  274. }
  275. if (codec->codec_tag) {
  276. if (!validate_codec_tag(s, st)) {
  277. char tagbuf[32], tagbuf2[32];
  278. av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
  279. av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
  280. av_log(s, AV_LOG_ERROR,
  281. "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
  282. tagbuf, codec->codec_tag, codec->codec_id, tagbuf2);
  283. ret = AVERROR_INVALIDDATA;
  284. goto fail;
  285. }
  286. } else
  287. codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
  288. }
  289. if (of->flags & AVFMT_GLOBALHEADER &&
  290. !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
  291. av_log(s, AV_LOG_WARNING,
  292. "Codec for stream %d does not use global headers "
  293. "but container format requires global headers\n", i);
  294. }
  295. if (!s->priv_data && of->priv_data_size > 0) {
  296. s->priv_data = av_mallocz(of->priv_data_size);
  297. if (!s->priv_data) {
  298. ret = AVERROR(ENOMEM);
  299. goto fail;
  300. }
  301. if (of->priv_class) {
  302. *(const AVClass **)s->priv_data = of->priv_class;
  303. av_opt_set_defaults(s->priv_data);
  304. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  305. goto fail;
  306. }
  307. }
  308. /* set muxer identification string */
  309. if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  310. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  311. }
  312. if (options) {
  313. av_dict_free(options);
  314. *options = tmp;
  315. }
  316. return 0;
  317. fail:
  318. av_dict_free(&tmp);
  319. return ret;
  320. }
  321. static int init_pts(AVFormatContext *s)
  322. {
  323. int i;
  324. AVStream *st;
  325. /* init PTS generation */
  326. for (i = 0; i < s->nb_streams; i++) {
  327. int64_t den = AV_NOPTS_VALUE;
  328. st = s->streams[i];
  329. switch (st->codec->codec_type) {
  330. case AVMEDIA_TYPE_AUDIO:
  331. den = (int64_t)st->time_base.num * st->codec->sample_rate;
  332. break;
  333. case AVMEDIA_TYPE_VIDEO:
  334. den = (int64_t)st->time_base.num * st->codec->time_base.den;
  335. break;
  336. default:
  337. break;
  338. }
  339. if (den != AV_NOPTS_VALUE) {
  340. if (den <= 0)
  341. return AVERROR_INVALIDDATA;
  342. frac_init(&st->pts, 0, 0, den);
  343. }
  344. }
  345. return 0;
  346. }
  347. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  348. {
  349. int ret = 0;
  350. if (ret = init_muxer(s, options))
  351. return ret;
  352. if (s->oformat->write_header) {
  353. ret = s->oformat->write_header(s);
  354. if (ret >= 0 && s->pb && s->pb->error < 0)
  355. ret = s->pb->error;
  356. if (ret < 0)
  357. return ret;
  358. }
  359. if ((ret = init_pts(s)) < 0)
  360. return ret;
  361. if (s->avoid_negative_ts < 0) {
  362. if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
  363. s->avoid_negative_ts = 0;
  364. } else
  365. s->avoid_negative_ts = 1;
  366. }
  367. return 0;
  368. }
  369. //FIXME merge with compute_pkt_fields
  370. static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  371. {
  372. int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
  373. int num, den, frame_size, i;
  374. av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
  375. av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
  376. /* duration field */
  377. if (pkt->duration == 0) {
  378. ff_compute_frame_duration(&num, &den, st, NULL, pkt);
  379. if (den && num) {
  380. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  381. }
  382. }
  383. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  384. pkt->pts = pkt->dts;
  385. //XXX/FIXME this is a temporary hack until all encoders output pts
  386. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  387. static int warned;
  388. if (!warned) {
  389. av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
  390. warned = 1;
  391. }
  392. pkt->dts =
  393. // pkt->pts= st->cur_dts;
  394. pkt->pts = st->pts.val;
  395. }
  396. //calculate dts from pts
  397. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  398. st->pts_buffer[0] = pkt->pts;
  399. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  400. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  401. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  402. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  403. pkt->dts = st->pts_buffer[0];
  404. }
  405. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  406. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  407. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  408. av_log(s, AV_LOG_ERROR,
  409. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
  410. st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
  411. return AVERROR(EINVAL);
  412. }
  413. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  414. av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
  415. av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
  416. return AVERROR(EINVAL);
  417. }
  418. av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
  419. av_ts2str(pkt->pts), av_ts2str(pkt->dts));
  420. st->cur_dts = pkt->dts;
  421. st->pts.val = pkt->dts;
  422. /* update pts */
  423. switch (st->codec->codec_type) {
  424. case AVMEDIA_TYPE_AUDIO:
  425. frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
  426. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  427. * likely equal to the encoder delay, but it would be better if we
  428. * had the real timestamps from the encoder */
  429. if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
  430. frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  431. }
  432. break;
  433. case AVMEDIA_TYPE_VIDEO:
  434. frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  435. break;
  436. default:
  437. break;
  438. }
  439. return 0;
  440. }
  441. /**
  442. * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  443. * sidedata.
  444. *
  445. * FIXME: this function should NEVER get undefined pts/dts beside when the
  446. * AVFMT_NOTIMESTAMPS is set.
  447. * Those additional safety checks should be dropped once the correct checks
  448. * are set in the callers.
  449. */
  450. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  451. {
  452. int ret, did_split;
  453. if (s->avoid_negative_ts > 0) {
  454. AVStream *st = s->streams[pkt->stream_index];
  455. int64_t offset = st->mux_ts_offset;
  456. if (pkt->dts < 0 && pkt->dts != AV_NOPTS_VALUE && !s->offset) {
  457. s->offset = -pkt->dts;
  458. s->offset_timebase = st->time_base;
  459. }
  460. if (s->offset && !offset) {
  461. offset = st->mux_ts_offset =
  462. av_rescale_q_rnd(s->offset,
  463. s->offset_timebase,
  464. st->time_base,
  465. AV_ROUND_UP);
  466. }
  467. if (pkt->dts != AV_NOPTS_VALUE)
  468. pkt->dts += offset;
  469. if (pkt->pts != AV_NOPTS_VALUE)
  470. pkt->pts += offset;
  471. av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0);
  472. }
  473. did_split = av_packet_split_side_data(pkt);
  474. ret = s->oformat->write_packet(s, pkt);
  475. if (s->flush_packets && s->pb && s->pb->error >= 0)
  476. avio_flush(s->pb);
  477. if (did_split)
  478. av_packet_merge_side_data(pkt);
  479. return ret;
  480. }
  481. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  482. {
  483. int ret;
  484. if (!pkt) {
  485. if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
  486. ret = s->oformat->write_packet(s, NULL);
  487. if (s->flush_packets && s->pb && s->pb->error >= 0)
  488. avio_flush(s->pb);
  489. if (ret >= 0 && s->pb && s->pb->error < 0)
  490. ret = s->pb->error;
  491. return ret;
  492. }
  493. return 1;
  494. }
  495. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  496. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  497. return ret;
  498. ret = write_packet(s, pkt);
  499. if (ret >= 0 && s->pb && s->pb->error < 0)
  500. ret = s->pb->error;
  501. if (ret >= 0)
  502. s->streams[pkt->stream_index]->nb_frames++;
  503. return ret;
  504. }
  505. #define CHUNK_START 0x1000
  506. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  507. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  508. {
  509. AVPacketList **next_point, *this_pktl;
  510. AVStream *st = s->streams[pkt->stream_index];
  511. int chunked = s->max_chunk_size || s->max_chunk_duration;
  512. this_pktl = av_mallocz(sizeof(AVPacketList));
  513. if (!this_pktl)
  514. return AVERROR(ENOMEM);
  515. this_pktl->pkt = *pkt;
  516. #if FF_API_DESTRUCT_PACKET
  517. pkt->destruct = NULL; // do not free original but only the copy
  518. #endif
  519. pkt->buf = NULL;
  520. av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-allocated memory
  521. av_copy_packet_side_data(&this_pktl->pkt, &this_pktl->pkt); // copy side data
  522. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  523. next_point = &(st->last_in_packet_buffer->next);
  524. } else {
  525. next_point = &s->packet_buffer;
  526. }
  527. if (chunked) {
  528. uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
  529. st->interleaver_chunk_size += pkt->size;
  530. st->interleaver_chunk_duration += pkt->duration;
  531. if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
  532. || (max && st->interleaver_chunk_duration > max)) {
  533. st->interleaver_chunk_size = 0;
  534. this_pktl->pkt.flags |= CHUNK_START;
  535. if (max && st->interleaver_chunk_duration > max) {
  536. int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
  537. int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
  538. st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
  539. } else
  540. st->interleaver_chunk_duration = 0;
  541. }
  542. }
  543. if (*next_point) {
  544. if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
  545. goto next_non_null;
  546. if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
  547. while ( *next_point
  548. && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
  549. || !compare(s, &(*next_point)->pkt, pkt)))
  550. next_point = &(*next_point)->next;
  551. if (*next_point)
  552. goto next_non_null;
  553. } else {
  554. next_point = &(s->packet_buffer_end->next);
  555. }
  556. }
  557. av_assert1(!*next_point);
  558. s->packet_buffer_end = this_pktl;
  559. next_non_null:
  560. this_pktl->next = *next_point;
  561. s->streams[pkt->stream_index]->last_in_packet_buffer =
  562. *next_point = this_pktl;
  563. return 0;
  564. }
  565. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  566. AVPacket *pkt)
  567. {
  568. AVStream *st = s->streams[pkt->stream_index];
  569. AVStream *st2 = s->streams[next->stream_index];
  570. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  571. st->time_base);
  572. if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
  573. int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO);
  574. int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO);
  575. if (ts == ts2) {
  576. ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
  577. -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
  578. ts2=0;
  579. }
  580. comp= (ts>ts2) - (ts<ts2);
  581. }
  582. if (comp == 0)
  583. return pkt->stream_index < next->stream_index;
  584. return comp > 0;
  585. }
  586. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  587. AVPacket *pkt, int flush)
  588. {
  589. AVPacketList *pktl;
  590. int stream_count = 0, noninterleaved_count = 0;
  591. int64_t delta_dts_max = 0;
  592. int i, ret;
  593. if (pkt) {
  594. ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts);
  595. if (ret < 0)
  596. return ret;
  597. }
  598. for (i = 0; i < s->nb_streams; i++) {
  599. if (s->streams[i]->last_in_packet_buffer) {
  600. ++stream_count;
  601. } else if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  602. ++noninterleaved_count;
  603. }
  604. }
  605. if (s->nb_streams == stream_count) {
  606. flush = 1;
  607. } else if (!flush) {
  608. for (i=0; i < s->nb_streams; i++) {
  609. if (s->streams[i]->last_in_packet_buffer) {
  610. int64_t delta_dts =
  611. av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
  612. s->streams[i]->time_base,
  613. AV_TIME_BASE_Q) -
  614. av_rescale_q(s->packet_buffer->pkt.dts,
  615. s->streams[s->packet_buffer->pkt.stream_index]->time_base,
  616. AV_TIME_BASE_Q);
  617. delta_dts_max= FFMAX(delta_dts_max, delta_dts);
  618. }
  619. }
  620. if (s->nb_streams == stream_count+noninterleaved_count &&
  621. delta_dts_max > 20*AV_TIME_BASE) {
  622. av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
  623. flush = 1;
  624. }
  625. }
  626. if (stream_count && flush) {
  627. AVStream *st;
  628. pktl = s->packet_buffer;
  629. *out = pktl->pkt;
  630. st = s->streams[out->stream_index];
  631. s->packet_buffer = pktl->next;
  632. if (!s->packet_buffer)
  633. s->packet_buffer_end = NULL;
  634. if (st->last_in_packet_buffer == pktl)
  635. st->last_in_packet_buffer = NULL;
  636. av_freep(&pktl);
  637. return 1;
  638. } else {
  639. av_init_packet(out);
  640. return 0;
  641. }
  642. }
  643. /**
  644. * Interleave an AVPacket correctly so it can be muxed.
  645. * @param out the interleaved packet will be output here
  646. * @param in the input packet
  647. * @param flush 1 if no further packets are available as input and all
  648. * remaining packets should be output
  649. * @return 1 if a packet was output, 0 if no packet could be output,
  650. * < 0 if an error occurred
  651. */
  652. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  653. {
  654. if (s->oformat->interleave_packet) {
  655. int ret = s->oformat->interleave_packet(s, out, in, flush);
  656. if (in)
  657. av_free_packet(in);
  658. return ret;
  659. } else
  660. return ff_interleave_packet_per_dts(s, out, in, flush);
  661. }
  662. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  663. {
  664. int ret, flush = 0;
  665. if (pkt) {
  666. AVStream *st = s->streams[pkt->stream_index];
  667. //FIXME/XXX/HACK drop zero sized packets
  668. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
  669. return 0;
  670. av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
  671. pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
  672. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  673. return ret;
  674. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  675. return AVERROR(EINVAL);
  676. } else {
  677. av_dlog(s, "av_interleaved_write_frame FLUSH\n");
  678. flush = 1;
  679. }
  680. for (;; ) {
  681. AVPacket opkt;
  682. int ret = interleave_packet(s, &opkt, pkt, flush);
  683. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  684. return ret;
  685. ret = write_packet(s, &opkt);
  686. if (ret >= 0)
  687. s->streams[opkt.stream_index]->nb_frames++;
  688. av_free_packet(&opkt);
  689. pkt = NULL;
  690. if (ret < 0)
  691. return ret;
  692. if(s->pb && s->pb->error)
  693. return s->pb->error;
  694. }
  695. }
  696. int av_write_trailer(AVFormatContext *s)
  697. {
  698. int ret, i;
  699. for (;; ) {
  700. AVPacket pkt;
  701. ret = interleave_packet(s, &pkt, NULL, 1);
  702. if (ret < 0) //FIXME cleanup needed for ret<0 ?
  703. goto fail;
  704. if (!ret)
  705. break;
  706. ret = write_packet(s, &pkt);
  707. if (ret >= 0)
  708. s->streams[pkt.stream_index]->nb_frames++;
  709. av_free_packet(&pkt);
  710. if (ret < 0)
  711. goto fail;
  712. if(s->pb && s->pb->error)
  713. goto fail;
  714. }
  715. if (s->oformat->write_trailer)
  716. ret = s->oformat->write_trailer(s);
  717. fail:
  718. if (s->pb)
  719. avio_flush(s->pb);
  720. if (ret == 0)
  721. ret = s->pb ? s->pb->error : 0;
  722. for (i = 0; i < s->nb_streams; i++) {
  723. av_freep(&s->streams[i]->priv_data);
  724. av_freep(&s->streams[i]->index_entries);
  725. }
  726. if (s->oformat->priv_class)
  727. av_opt_free(s->priv_data);
  728. av_freep(&s->priv_data);
  729. return ret;
  730. }
  731. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  732. int64_t *dts, int64_t *wall)
  733. {
  734. if (!s->oformat || !s->oformat->get_output_timestamp)
  735. return AVERROR(ENOSYS);
  736. s->oformat->get_output_timestamp(s, stream, dts, wall);
  737. return 0;
  738. }
  739. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  740. AVFormatContext *src)
  741. {
  742. AVPacket local_pkt;
  743. local_pkt = *pkt;
  744. local_pkt.stream_index = dst_stream;
  745. if (pkt->pts != AV_NOPTS_VALUE)
  746. local_pkt.pts = av_rescale_q(pkt->pts,
  747. src->streams[pkt->stream_index]->time_base,
  748. dst->streams[dst_stream]->time_base);
  749. if (pkt->dts != AV_NOPTS_VALUE)
  750. local_pkt.dts = av_rescale_q(pkt->dts,
  751. src->streams[pkt->stream_index]->time_base,
  752. dst->streams[dst_stream]->time_base);
  753. if (pkt->duration)
  754. local_pkt.duration = av_rescale_q(pkt->duration,
  755. src->streams[pkt->stream_index]->time_base,
  756. dst->streams[dst_stream]->time_base);
  757. return av_write_frame(dst, &local_pkt);
  758. }