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.

642 lines
19KB

  1. /*
  2. * muxing functions for use within Libav
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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 "metadata.h"
  30. #include "id3v2.h"
  31. #include "libavutil/avassert.h"
  32. #include "libavutil/avstring.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/parseutils.h"
  35. #include "libavutil/time.h"
  36. #include "riff.h"
  37. #include "audiointerleave.h"
  38. #include "url.h"
  39. #include <stdarg.h>
  40. #if CONFIG_NETWORK
  41. #include "network.h"
  42. #endif
  43. #undef NDEBUG
  44. #include <assert.h>
  45. /**
  46. * @file
  47. * muxing functions for use within Libav
  48. */
  49. /* fraction handling */
  50. /**
  51. * f = val + (num / den) + 0.5.
  52. *
  53. * 'num' is normalized so that it is such as 0 <= num < den.
  54. *
  55. * @param f fractional number
  56. * @param val integer value
  57. * @param num must be >= 0
  58. * @param den must be >= 1
  59. */
  60. static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
  61. {
  62. num += (den >> 1);
  63. if (num >= den) {
  64. val += num / den;
  65. num = num % den;
  66. }
  67. f->val = val;
  68. f->num = num;
  69. f->den = den;
  70. }
  71. /**
  72. * Fractional addition to f: f = f + (incr / f->den).
  73. *
  74. * @param f fractional number
  75. * @param incr increment, can be positive or negative
  76. */
  77. static void frac_add(AVFrac *f, int64_t incr)
  78. {
  79. int64_t num, den;
  80. num = f->num + incr;
  81. den = f->den;
  82. if (num < 0) {
  83. f->val += num / den;
  84. num = num % den;
  85. if (num < 0) {
  86. num += den;
  87. f->val--;
  88. }
  89. } else if (num >= den) {
  90. f->val += num / den;
  91. num = num % den;
  92. }
  93. f->num = num;
  94. }
  95. static int validate_codec_tag(AVFormatContext *s, AVStream *st)
  96. {
  97. const AVCodecTag *avctag;
  98. int n;
  99. enum AVCodecID id = AV_CODEC_ID_NONE;
  100. unsigned int tag = 0;
  101. /**
  102. * Check that tag + id is in the table
  103. * If neither is in the table -> OK
  104. * If tag is in the table with another id -> FAIL
  105. * If id is in the table with another tag -> FAIL unless strict < normal
  106. */
  107. for (n = 0; s->oformat->codec_tag[n]; n++) {
  108. avctag = s->oformat->codec_tag[n];
  109. while (avctag->id != AV_CODEC_ID_NONE) {
  110. if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
  111. id = avctag->id;
  112. if (id == st->codec->codec_id)
  113. return 1;
  114. }
  115. if (avctag->id == st->codec->codec_id)
  116. tag = avctag->tag;
  117. avctag++;
  118. }
  119. }
  120. if (id != AV_CODEC_ID_NONE)
  121. return 0;
  122. if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
  123. return 0;
  124. return 1;
  125. }
  126. static int init_muxer(AVFormatContext *s, AVDictionary **options)
  127. {
  128. int ret = 0, i;
  129. AVStream *st;
  130. AVDictionary *tmp = NULL;
  131. AVCodecContext *codec = NULL;
  132. AVOutputFormat *of = s->oformat;
  133. if (options)
  134. av_dict_copy(&tmp, *options, 0);
  135. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  136. goto fail;
  137. // some sanity checks
  138. if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
  139. av_log(s, AV_LOG_ERROR, "no streams\n");
  140. ret = AVERROR(EINVAL);
  141. goto fail;
  142. }
  143. for (i = 0; i < s->nb_streams; i++) {
  144. st = s->streams[i];
  145. codec = st->codec;
  146. switch (codec->codec_type) {
  147. case AVMEDIA_TYPE_AUDIO:
  148. if (codec->sample_rate <= 0) {
  149. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  150. ret = AVERROR(EINVAL);
  151. goto fail;
  152. }
  153. if (!codec->block_align)
  154. codec->block_align = codec->channels *
  155. av_get_bits_per_sample(codec->codec_id) >> 3;
  156. break;
  157. case AVMEDIA_TYPE_VIDEO:
  158. if (codec->time_base.num <= 0 ||
  159. codec->time_base.den <= 0) { //FIXME audio too?
  160. av_log(s, AV_LOG_ERROR, "time base not set\n");
  161. ret = AVERROR(EINVAL);
  162. goto fail;
  163. }
  164. if ((codec->width <= 0 || codec->height <= 0) &&
  165. !(of->flags & AVFMT_NODIMENSIONS)) {
  166. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  167. ret = AVERROR(EINVAL);
  168. goto fail;
  169. }
  170. if (av_cmp_q(st->sample_aspect_ratio,
  171. codec->sample_aspect_ratio)) {
  172. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
  173. "(%d/%d) and encoder layer (%d/%d)\n",
  174. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  175. codec->sample_aspect_ratio.num,
  176. codec->sample_aspect_ratio.den);
  177. ret = AVERROR(EINVAL);
  178. goto fail;
  179. }
  180. break;
  181. }
  182. if (of->codec_tag) {
  183. if (codec->codec_tag &&
  184. codec->codec_id == AV_CODEC_ID_RAWVIDEO &&
  185. !av_codec_get_tag(of->codec_tag, codec->codec_id) &&
  186. !validate_codec_tag(s, st)) {
  187. // the current rawvideo encoding system ends up setting
  188. // the wrong codec_tag for avi, we override it here
  189. codec->codec_tag = 0;
  190. }
  191. if (codec->codec_tag) {
  192. if (!validate_codec_tag(s, st)) {
  193. char tagbuf[32];
  194. av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
  195. av_log(s, AV_LOG_ERROR,
  196. "Tag %s/0x%08x incompatible with output codec id '%d'\n",
  197. tagbuf, codec->codec_tag, codec->codec_id);
  198. ret = AVERROR_INVALIDDATA;
  199. goto fail;
  200. }
  201. } else
  202. codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
  203. }
  204. if (of->flags & AVFMT_GLOBALHEADER &&
  205. !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
  206. av_log(s, AV_LOG_WARNING,
  207. "Codec for stream %d does not use global headers "
  208. "but container format requires global headers\n", i);
  209. }
  210. if (!s->priv_data && of->priv_data_size > 0) {
  211. s->priv_data = av_mallocz(of->priv_data_size);
  212. if (!s->priv_data) {
  213. ret = AVERROR(ENOMEM);
  214. goto fail;
  215. }
  216. if (of->priv_class) {
  217. *(const AVClass **)s->priv_data = of->priv_class;
  218. av_opt_set_defaults(s->priv_data);
  219. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  220. goto fail;
  221. }
  222. }
  223. /* set muxer identification string */
  224. if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  225. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  226. }
  227. if (options) {
  228. av_dict_free(options);
  229. *options = tmp;
  230. }
  231. return 0;
  232. fail:
  233. av_dict_free(&tmp);
  234. return ret;
  235. }
  236. static int init_pts(AVFormatContext *s)
  237. {
  238. int i;
  239. AVStream *st;
  240. /* init PTS generation */
  241. for (i = 0; i < s->nb_streams; i++) {
  242. int64_t den = AV_NOPTS_VALUE;
  243. st = s->streams[i];
  244. switch (st->codec->codec_type) {
  245. case AVMEDIA_TYPE_AUDIO:
  246. den = (int64_t)st->time_base.num * st->codec->sample_rate;
  247. break;
  248. case AVMEDIA_TYPE_VIDEO:
  249. den = (int64_t)st->time_base.num * st->codec->time_base.den;
  250. break;
  251. default:
  252. break;
  253. }
  254. if (den != AV_NOPTS_VALUE) {
  255. if (den <= 0)
  256. return AVERROR_INVALIDDATA;
  257. frac_init(&st->pts, 0, 0, den);
  258. }
  259. }
  260. return 0;
  261. }
  262. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  263. {
  264. int ret = 0;
  265. if (ret = init_muxer(s, options))
  266. return ret;
  267. if (s->oformat->write_header) {
  268. ret = s->oformat->write_header(s);
  269. if (ret < 0)
  270. return ret;
  271. }
  272. if ((ret = init_pts(s)) < 0)
  273. return ret;
  274. return 0;
  275. }
  276. //FIXME merge with compute_pkt_fields
  277. static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  278. {
  279. int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
  280. int num, den, frame_size, i;
  281. av_dlog(s, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
  282. pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
  283. /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
  284. * return AVERROR(EINVAL);*/
  285. /* duration field */
  286. if (pkt->duration == 0) {
  287. ff_compute_frame_duration(&num, &den, st, NULL, pkt);
  288. if (den && num) {
  289. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  290. }
  291. }
  292. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  293. pkt->pts = pkt->dts;
  294. //XXX/FIXME this is a temporary hack until all encoders output pts
  295. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  296. pkt->dts =
  297. // pkt->pts= st->cur_dts;
  298. pkt->pts = st->pts.val;
  299. }
  300. //calculate dts from pts
  301. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  302. st->pts_buffer[0] = pkt->pts;
  303. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  304. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  305. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  306. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  307. pkt->dts = st->pts_buffer[0];
  308. }
  309. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  310. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  311. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  312. av_log(s, AV_LOG_ERROR,
  313. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
  314. st->index, st->cur_dts, pkt->dts);
  315. return AVERROR(EINVAL);
  316. }
  317. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  318. av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
  319. return AVERROR(EINVAL);
  320. }
  321. av_dlog(s, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
  322. pkt->pts, pkt->dts);
  323. st->cur_dts = pkt->dts;
  324. st->pts.val = pkt->dts;
  325. /* update pts */
  326. switch (st->codec->codec_type) {
  327. case AVMEDIA_TYPE_AUDIO:
  328. frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
  329. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  330. * likely equal to the encoder delay, but it would be better if we
  331. * had the real timestamps from the encoder */
  332. if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
  333. frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  334. }
  335. break;
  336. case AVMEDIA_TYPE_VIDEO:
  337. frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  338. break;
  339. default:
  340. break;
  341. }
  342. return 0;
  343. }
  344. /*
  345. * FIXME: this function should NEVER get undefined pts/dts beside when the
  346. * AVFMT_NOTIMESTAMPS is set.
  347. * Those additional safety checks should be dropped once the correct checks
  348. * are set in the callers.
  349. */
  350. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  351. {
  352. if (!(s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS))) {
  353. AVRational time_base = s->streams[pkt->stream_index]->time_base;
  354. int64_t offset = 0;
  355. if (!s->offset && pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
  356. s->offset = -pkt->dts;
  357. s->offset_timebase = time_base;
  358. }
  359. if (s->offset)
  360. offset = av_rescale_q(s->offset, s->offset_timebase, time_base);
  361. if (pkt->dts != AV_NOPTS_VALUE)
  362. pkt->dts += offset;
  363. if (pkt->pts != AV_NOPTS_VALUE)
  364. pkt->pts += offset;
  365. }
  366. return s->oformat->write_packet(s, pkt);
  367. }
  368. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  369. {
  370. int ret;
  371. if (!pkt) {
  372. if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
  373. return s->oformat->write_packet(s, pkt);
  374. return 1;
  375. }
  376. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  377. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  378. return ret;
  379. ret = write_packet(s, pkt);
  380. if (ret >= 0)
  381. s->streams[pkt->stream_index]->nb_frames++;
  382. return ret;
  383. }
  384. void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  385. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  386. {
  387. AVPacketList **next_point, *this_pktl;
  388. this_pktl = av_mallocz(sizeof(AVPacketList));
  389. this_pktl->pkt = *pkt;
  390. #if FF_API_DESTRUCT_PACKET
  391. pkt->destruct = NULL; // do not free original but only the copy
  392. #endif
  393. pkt->buf = NULL;
  394. av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
  395. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  396. next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
  397. } else
  398. next_point = &s->packet_buffer;
  399. if (*next_point) {
  400. if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
  401. while (!compare(s, &(*next_point)->pkt, pkt))
  402. next_point = &(*next_point)->next;
  403. goto next_non_null;
  404. } else {
  405. next_point = &(s->packet_buffer_end->next);
  406. }
  407. }
  408. assert(!*next_point);
  409. s->packet_buffer_end = this_pktl;
  410. next_non_null:
  411. this_pktl->next = *next_point;
  412. s->streams[pkt->stream_index]->last_in_packet_buffer =
  413. *next_point = this_pktl;
  414. }
  415. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  416. AVPacket *pkt)
  417. {
  418. AVStream *st = s->streams[pkt->stream_index];
  419. AVStream *st2 = s->streams[next->stream_index];
  420. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  421. st->time_base);
  422. if (comp == 0)
  423. return pkt->stream_index < next->stream_index;
  424. return comp > 0;
  425. }
  426. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  427. AVPacket *pkt, int flush)
  428. {
  429. AVPacketList *pktl;
  430. int stream_count = 0;
  431. int i;
  432. if (pkt) {
  433. ff_interleave_add_packet(s, pkt, interleave_compare_dts);
  434. }
  435. for (i = 0; i < s->nb_streams; i++)
  436. stream_count += !!s->streams[i]->last_in_packet_buffer;
  437. if (stream_count && (s->nb_streams == stream_count || flush)) {
  438. pktl = s->packet_buffer;
  439. *out = pktl->pkt;
  440. s->packet_buffer = pktl->next;
  441. if (!s->packet_buffer)
  442. s->packet_buffer_end = NULL;
  443. if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
  444. s->streams[out->stream_index]->last_in_packet_buffer = NULL;
  445. av_freep(&pktl);
  446. return 1;
  447. } else {
  448. av_init_packet(out);
  449. return 0;
  450. }
  451. }
  452. /**
  453. * Interleave an AVPacket correctly so it can be muxed.
  454. * @param out the interleaved packet will be output here
  455. * @param in the input packet
  456. * @param flush 1 if no further packets are available as input and all
  457. * remaining packets should be output
  458. * @return 1 if a packet was output, 0 if no packet could be output,
  459. * < 0 if an error occurred
  460. */
  461. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  462. {
  463. if (s->oformat->interleave_packet) {
  464. int ret = s->oformat->interleave_packet(s, out, in, flush);
  465. if (in)
  466. av_free_packet(in);
  467. return ret;
  468. } else
  469. return ff_interleave_packet_per_dts(s, out, in, flush);
  470. }
  471. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  472. {
  473. int ret, flush = 0;
  474. if (pkt) {
  475. AVStream *st = s->streams[pkt->stream_index];
  476. //FIXME/XXX/HACK drop zero sized packets
  477. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
  478. return 0;
  479. av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
  480. pkt->size, pkt->dts, pkt->pts);
  481. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  482. return ret;
  483. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  484. return AVERROR(EINVAL);
  485. } else {
  486. av_dlog(s, "av_interleaved_write_frame FLUSH\n");
  487. flush = 1;
  488. }
  489. for (;; ) {
  490. AVPacket opkt;
  491. int ret = interleave_packet(s, &opkt, pkt, flush);
  492. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  493. return ret;
  494. ret = write_packet(s, &opkt);
  495. if (ret >= 0)
  496. s->streams[opkt.stream_index]->nb_frames++;
  497. av_free_packet(&opkt);
  498. pkt = NULL;
  499. if (ret < 0)
  500. return ret;
  501. }
  502. }
  503. int av_write_trailer(AVFormatContext *s)
  504. {
  505. int ret, i;
  506. for (;; ) {
  507. AVPacket pkt;
  508. ret = interleave_packet(s, &pkt, NULL, 1);
  509. if (ret < 0) //FIXME cleanup needed for ret<0 ?
  510. goto fail;
  511. if (!ret)
  512. break;
  513. ret = write_packet(s, &pkt);
  514. if (ret >= 0)
  515. s->streams[pkt.stream_index]->nb_frames++;
  516. av_free_packet(&pkt);
  517. if (ret < 0)
  518. goto fail;
  519. }
  520. if (s->oformat->write_trailer)
  521. ret = s->oformat->write_trailer(s);
  522. if (!(s->oformat->flags & AVFMT_NOFILE))
  523. avio_flush(s->pb);
  524. fail:
  525. for (i = 0; i < s->nb_streams; i++) {
  526. av_freep(&s->streams[i]->priv_data);
  527. av_freep(&s->streams[i]->index_entries);
  528. }
  529. if (s->oformat->priv_class)
  530. av_opt_free(s->priv_data);
  531. av_freep(&s->priv_data);
  532. return ret;
  533. }
  534. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  535. AVFormatContext *src)
  536. {
  537. AVPacket local_pkt;
  538. local_pkt = *pkt;
  539. local_pkt.stream_index = dst_stream;
  540. if (pkt->pts != AV_NOPTS_VALUE)
  541. local_pkt.pts = av_rescale_q(pkt->pts,
  542. src->streams[pkt->stream_index]->time_base,
  543. dst->streams[dst_stream]->time_base);
  544. if (pkt->dts != AV_NOPTS_VALUE)
  545. local_pkt.dts = av_rescale_q(pkt->dts,
  546. src->streams[pkt->stream_index]->time_base,
  547. dst->streams[dst_stream]->time_base);
  548. return av_write_frame(dst, &local_pkt);
  549. }