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.

603 lines
18KB

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