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.

839 lines
27KB

  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. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
  251. "(%d/%d) and encoder layer (%d/%d)\n",
  252. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  253. codec->sample_aspect_ratio.num,
  254. codec->sample_aspect_ratio.den);
  255. ret = AVERROR(EINVAL);
  256. goto fail;
  257. }
  258. break;
  259. }
  260. if (of->codec_tag) {
  261. if ( codec->codec_tag
  262. && codec->codec_id == AV_CODEC_ID_RAWVIDEO
  263. && ( av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
  264. || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
  265. && !validate_codec_tag(s, st)) {
  266. // the current rawvideo encoding system ends up setting
  267. // the wrong codec_tag for avi/mov, we override it here
  268. codec->codec_tag = 0;
  269. }
  270. if (codec->codec_tag) {
  271. if (!validate_codec_tag(s, st)) {
  272. char tagbuf[32], cortag[32];
  273. av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
  274. av_get_codec_tag_string(cortag, sizeof(cortag), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
  275. av_log(s, AV_LOG_ERROR,
  276. "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
  277. tagbuf, codec->codec_tag, codec->codec_id, cortag);
  278. ret = AVERROR_INVALIDDATA;
  279. goto fail;
  280. }
  281. } else
  282. codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
  283. }
  284. if (of->flags & AVFMT_GLOBALHEADER &&
  285. !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
  286. av_log(s, AV_LOG_WARNING,
  287. "Codec for stream %d does not use global headers "
  288. "but container format requires global headers\n", i);
  289. }
  290. if (!s->priv_data && of->priv_data_size > 0) {
  291. s->priv_data = av_mallocz(of->priv_data_size);
  292. if (!s->priv_data) {
  293. ret = AVERROR(ENOMEM);
  294. goto fail;
  295. }
  296. if (of->priv_class) {
  297. *(const AVClass **)s->priv_data = of->priv_class;
  298. av_opt_set_defaults(s->priv_data);
  299. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  300. goto fail;
  301. }
  302. }
  303. /* set muxer identification string */
  304. if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  305. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  306. }
  307. if (options) {
  308. av_dict_free(options);
  309. *options = tmp;
  310. }
  311. return 0;
  312. fail:
  313. av_dict_free(&tmp);
  314. return ret;
  315. }
  316. static int init_pts(AVFormatContext *s)
  317. {
  318. int i;
  319. AVStream *st;
  320. /* init PTS generation */
  321. for (i = 0; i < s->nb_streams; i++) {
  322. int64_t den = AV_NOPTS_VALUE;
  323. st = s->streams[i];
  324. switch (st->codec->codec_type) {
  325. case AVMEDIA_TYPE_AUDIO:
  326. den = (int64_t)st->time_base.num * st->codec->sample_rate;
  327. break;
  328. case AVMEDIA_TYPE_VIDEO:
  329. den = (int64_t)st->time_base.num * st->codec->time_base.den;
  330. break;
  331. default:
  332. break;
  333. }
  334. if (den != AV_NOPTS_VALUE) {
  335. if (den <= 0)
  336. return AVERROR_INVALIDDATA;
  337. frac_init(&st->pts, 0, 0, den);
  338. }
  339. }
  340. return 0;
  341. }
  342. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  343. {
  344. int ret = 0;
  345. if (ret = init_muxer(s, options))
  346. return ret;
  347. if (s->oformat->write_header) {
  348. ret = s->oformat->write_header(s);
  349. if (ret >= 0 && s->pb && s->pb->error < 0)
  350. ret = s->pb->error;
  351. if (ret < 0)
  352. return ret;
  353. }
  354. if ((ret = init_pts(s)) < 0)
  355. return ret;
  356. if (s->avoid_negative_ts < 0) {
  357. if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
  358. s->avoid_negative_ts = 0;
  359. } else
  360. s->avoid_negative_ts = 1;
  361. }
  362. return 0;
  363. }
  364. //FIXME merge with compute_pkt_fields
  365. static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  366. {
  367. int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
  368. int num, den, frame_size, i;
  369. av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
  370. av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
  371. /* duration field */
  372. if (pkt->duration == 0) {
  373. ff_compute_frame_duration(&num, &den, st, NULL, pkt);
  374. if (den && num) {
  375. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  376. }
  377. }
  378. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  379. pkt->pts = pkt->dts;
  380. //XXX/FIXME this is a temporary hack until all encoders output pts
  381. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  382. static int warned;
  383. if (!warned) {
  384. av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
  385. warned = 1;
  386. }
  387. pkt->dts =
  388. // pkt->pts= st->cur_dts;
  389. pkt->pts = st->pts.val;
  390. }
  391. //calculate dts from pts
  392. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  393. st->pts_buffer[0] = pkt->pts;
  394. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  395. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  396. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  397. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  398. pkt->dts = st->pts_buffer[0];
  399. }
  400. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  401. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  402. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  403. av_log(s, AV_LOG_ERROR,
  404. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
  405. st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
  406. return AVERROR(EINVAL);
  407. }
  408. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  409. av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
  410. av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
  411. return AVERROR(EINVAL);
  412. }
  413. av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
  414. av_ts2str(pkt->pts), av_ts2str(pkt->dts));
  415. st->cur_dts = pkt->dts;
  416. st->pts.val = pkt->dts;
  417. /* update pts */
  418. switch (st->codec->codec_type) {
  419. case AVMEDIA_TYPE_AUDIO:
  420. frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
  421. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  422. * likely equal to the encoder delay, but it would be better if we
  423. * had the real timestamps from the encoder */
  424. if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
  425. frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  426. }
  427. break;
  428. case AVMEDIA_TYPE_VIDEO:
  429. frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  430. break;
  431. default:
  432. break;
  433. }
  434. return 0;
  435. }
  436. /**
  437. * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  438. * sidedata.
  439. *
  440. * FIXME: this function should NEVER get undefined pts/dts beside when the
  441. * AVFMT_NOTIMESTAMPS is set.
  442. * Those additional safety checks should be dropped once the correct checks
  443. * are set in the callers.
  444. */
  445. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  446. {
  447. int ret, did_split;
  448. if (s->avoid_negative_ts > 0) {
  449. AVStream *st = s->streams[pkt->stream_index];
  450. int64_t offset = st->mux_ts_offset;
  451. if (pkt->dts < 0 && pkt->dts != AV_NOPTS_VALUE && !s->offset) {
  452. s->offset = -pkt->dts;
  453. s->offset_timebase = st->time_base;
  454. }
  455. if (s->offset && !offset) {
  456. offset = st->mux_ts_offset =
  457. av_rescale_q_rnd(s->offset,
  458. s->offset_timebase,
  459. st->time_base,
  460. AV_ROUND_UP);
  461. }
  462. if (pkt->dts != AV_NOPTS_VALUE)
  463. pkt->dts += offset;
  464. if (pkt->pts != AV_NOPTS_VALUE)
  465. pkt->pts += offset;
  466. av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0);
  467. }
  468. did_split = av_packet_split_side_data(pkt);
  469. ret = s->oformat->write_packet(s, pkt);
  470. if (s->flush_packets && s->pb && s->pb->error >= 0)
  471. avio_flush(s->pb);
  472. if (did_split)
  473. av_packet_merge_side_data(pkt);
  474. return ret;
  475. }
  476. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  477. {
  478. int ret;
  479. if (!pkt) {
  480. if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
  481. ret = s->oformat->write_packet(s, NULL);
  482. if (s->flush_packets && s->pb && s->pb->error >= 0)
  483. avio_flush(s->pb);
  484. if (ret >= 0 && s->pb && s->pb->error < 0)
  485. ret = s->pb->error;
  486. return ret;
  487. }
  488. return 1;
  489. }
  490. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  491. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  492. return ret;
  493. ret = write_packet(s, pkt);
  494. if (ret >= 0 && s->pb && s->pb->error < 0)
  495. ret = s->pb->error;
  496. if (ret >= 0)
  497. s->streams[pkt->stream_index]->nb_frames++;
  498. return ret;
  499. }
  500. #define CHUNK_START 0x1000
  501. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  502. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  503. {
  504. AVPacketList **next_point, *this_pktl;
  505. AVStream *st = s->streams[pkt->stream_index];
  506. int chunked = s->max_chunk_size || s->max_chunk_duration;
  507. this_pktl = av_mallocz(sizeof(AVPacketList));
  508. if (!this_pktl)
  509. return AVERROR(ENOMEM);
  510. this_pktl->pkt = *pkt;
  511. #if FF_API_DESTRUCT_PACKET
  512. pkt->destruct = NULL; // do not free original but only the copy
  513. #endif
  514. pkt->buf = NULL;
  515. av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-allocated memory
  516. av_copy_packet_side_data(&this_pktl->pkt, &this_pktl->pkt); // copy side data
  517. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  518. next_point = &(st->last_in_packet_buffer->next);
  519. } else {
  520. next_point = &s->packet_buffer;
  521. }
  522. if (chunked) {
  523. uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
  524. st->interleaver_chunk_size += pkt->size;
  525. st->interleaver_chunk_duration += pkt->duration;
  526. if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
  527. || (max && st->interleaver_chunk_duration > max)) {
  528. st->interleaver_chunk_size = 0;
  529. this_pktl->pkt.flags |= CHUNK_START;
  530. if (max && st->interleaver_chunk_duration > max) {
  531. int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
  532. int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
  533. st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
  534. } else
  535. st->interleaver_chunk_duration = 0;
  536. }
  537. }
  538. if (*next_point) {
  539. if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
  540. goto next_non_null;
  541. if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
  542. while ( *next_point
  543. && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
  544. || !compare(s, &(*next_point)->pkt, pkt)))
  545. next_point = &(*next_point)->next;
  546. if (*next_point)
  547. goto next_non_null;
  548. } else {
  549. next_point = &(s->packet_buffer_end->next);
  550. }
  551. }
  552. av_assert1(!*next_point);
  553. s->packet_buffer_end = this_pktl;
  554. next_non_null:
  555. this_pktl->next = *next_point;
  556. s->streams[pkt->stream_index]->last_in_packet_buffer =
  557. *next_point = this_pktl;
  558. return 0;
  559. }
  560. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  561. AVPacket *pkt)
  562. {
  563. AVStream *st = s->streams[pkt->stream_index];
  564. AVStream *st2 = s->streams[next->stream_index];
  565. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  566. st->time_base);
  567. if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
  568. 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);
  569. 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);
  570. if (ts == ts2) {
  571. 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
  572. -( 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;
  573. ts2=0;
  574. }
  575. comp= (ts>ts2) - (ts<ts2);
  576. }
  577. if (comp == 0)
  578. return pkt->stream_index < next->stream_index;
  579. return comp > 0;
  580. }
  581. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  582. AVPacket *pkt, int flush)
  583. {
  584. AVPacketList *pktl;
  585. int stream_count = 0, noninterleaved_count = 0;
  586. int64_t delta_dts_max = 0;
  587. int i, ret;
  588. if (pkt) {
  589. ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts);
  590. if (ret < 0)
  591. return ret;
  592. }
  593. for (i = 0; i < s->nb_streams; i++) {
  594. if (s->streams[i]->last_in_packet_buffer) {
  595. ++stream_count;
  596. } else if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  597. ++noninterleaved_count;
  598. }
  599. }
  600. if (s->nb_streams == stream_count) {
  601. flush = 1;
  602. } else if (!flush) {
  603. for (i=0; i < s->nb_streams; i++) {
  604. if (s->streams[i]->last_in_packet_buffer) {
  605. int64_t delta_dts =
  606. av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
  607. s->streams[i]->time_base,
  608. AV_TIME_BASE_Q) -
  609. av_rescale_q(s->packet_buffer->pkt.dts,
  610. s->streams[s->packet_buffer->pkt.stream_index]->time_base,
  611. AV_TIME_BASE_Q);
  612. delta_dts_max= FFMAX(delta_dts_max, delta_dts);
  613. }
  614. }
  615. if (s->nb_streams == stream_count+noninterleaved_count &&
  616. delta_dts_max > 20*AV_TIME_BASE) {
  617. av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
  618. flush = 1;
  619. }
  620. }
  621. if (stream_count && flush) {
  622. AVStream *st;
  623. pktl = s->packet_buffer;
  624. *out = pktl->pkt;
  625. st = s->streams[out->stream_index];
  626. s->packet_buffer = pktl->next;
  627. if (!s->packet_buffer)
  628. s->packet_buffer_end = NULL;
  629. if (st->last_in_packet_buffer == pktl)
  630. st->last_in_packet_buffer = NULL;
  631. av_freep(&pktl);
  632. return 1;
  633. } else {
  634. av_init_packet(out);
  635. return 0;
  636. }
  637. }
  638. /**
  639. * Interleave an AVPacket correctly so it can be muxed.
  640. * @param out the interleaved packet will be output here
  641. * @param in the input packet
  642. * @param flush 1 if no further packets are available as input and all
  643. * remaining packets should be output
  644. * @return 1 if a packet was output, 0 if no packet could be output,
  645. * < 0 if an error occurred
  646. */
  647. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  648. {
  649. if (s->oformat->interleave_packet) {
  650. int ret = s->oformat->interleave_packet(s, out, in, flush);
  651. if (in)
  652. av_free_packet(in);
  653. return ret;
  654. } else
  655. return ff_interleave_packet_per_dts(s, out, in, flush);
  656. }
  657. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  658. {
  659. int ret, flush = 0;
  660. if (pkt) {
  661. AVStream *st = s->streams[pkt->stream_index];
  662. //FIXME/XXX/HACK drop zero sized packets
  663. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
  664. return 0;
  665. av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
  666. pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
  667. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  668. return ret;
  669. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  670. return AVERROR(EINVAL);
  671. } else {
  672. av_dlog(s, "av_interleaved_write_frame FLUSH\n");
  673. flush = 1;
  674. }
  675. for (;; ) {
  676. AVPacket opkt;
  677. int ret = interleave_packet(s, &opkt, pkt, flush);
  678. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  679. return ret;
  680. ret = write_packet(s, &opkt);
  681. if (ret >= 0)
  682. s->streams[opkt.stream_index]->nb_frames++;
  683. av_free_packet(&opkt);
  684. pkt = NULL;
  685. if (ret < 0)
  686. return ret;
  687. if(s->pb && s->pb->error)
  688. return s->pb->error;
  689. }
  690. }
  691. int av_write_trailer(AVFormatContext *s)
  692. {
  693. int ret, i;
  694. for (;; ) {
  695. AVPacket pkt;
  696. ret = interleave_packet(s, &pkt, NULL, 1);
  697. if (ret < 0) //FIXME cleanup needed for ret<0 ?
  698. goto fail;
  699. if (!ret)
  700. break;
  701. ret = write_packet(s, &pkt);
  702. if (ret >= 0)
  703. s->streams[pkt.stream_index]->nb_frames++;
  704. av_free_packet(&pkt);
  705. if (ret < 0)
  706. goto fail;
  707. if(s->pb && s->pb->error)
  708. goto fail;
  709. }
  710. if (s->oformat->write_trailer)
  711. ret = s->oformat->write_trailer(s);
  712. fail:
  713. if (s->pb)
  714. avio_flush(s->pb);
  715. if (ret == 0)
  716. ret = s->pb ? s->pb->error : 0;
  717. for (i = 0; i < s->nb_streams; i++) {
  718. av_freep(&s->streams[i]->priv_data);
  719. av_freep(&s->streams[i]->index_entries);
  720. }
  721. if (s->oformat->priv_class)
  722. av_opt_free(s->priv_data);
  723. av_freep(&s->priv_data);
  724. return ret;
  725. }
  726. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  727. int64_t *dts, int64_t *wall)
  728. {
  729. if (!s->oformat || !s->oformat->get_output_timestamp)
  730. return AVERROR(ENOSYS);
  731. s->oformat->get_output_timestamp(s, stream, dts, wall);
  732. return 0;
  733. }