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.

821 lines
26KB

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