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.

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