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.

781 lines
25KB

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