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.

626 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. /* #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. /*
  346. * FIXME: this function should NEVER get undefined pts/dts beside when the
  347. * AVFMT_NOTIMESTAMPS is set.
  348. * Those additional safety checks should be dropped once the correct checks
  349. * are set in the callers.
  350. */
  351. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  352. {
  353. if (!(s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS))) {
  354. AVRational time_base = s->streams[pkt->stream_index]->time_base;
  355. int64_t offset = 0;
  356. if (!s->offset && pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
  357. s->offset = -pkt->dts;
  358. s->offset_timebase = time_base;
  359. }
  360. if (s->offset)
  361. offset = av_rescale_q(s->offset, s->offset_timebase, time_base);
  362. if (pkt->dts != AV_NOPTS_VALUE)
  363. pkt->dts += offset;
  364. if (pkt->pts != AV_NOPTS_VALUE)
  365. pkt->pts += offset;
  366. }
  367. return s->oformat->write_packet(s, pkt);
  368. }
  369. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  370. {
  371. int ret;
  372. if (!pkt) {
  373. if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
  374. return s->oformat->write_packet(s, pkt);
  375. return 1;
  376. }
  377. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  378. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  379. return ret;
  380. ret = write_packet(s, pkt);
  381. if (ret >= 0)
  382. s->streams[pkt->stream_index]->nb_frames++;
  383. return ret;
  384. }
  385. void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  386. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  387. {
  388. AVPacketList **next_point, *this_pktl;
  389. this_pktl = av_mallocz(sizeof(AVPacketList));
  390. this_pktl->pkt = *pkt;
  391. #if FF_API_DESTRUCT_PACKET
  392. pkt->destruct = NULL; // do not free original but only the copy
  393. #endif
  394. pkt->buf = NULL;
  395. av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
  396. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  397. next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
  398. } else
  399. next_point = &s->packet_buffer;
  400. if (*next_point) {
  401. if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
  402. while (!compare(s, &(*next_point)->pkt, pkt))
  403. next_point = &(*next_point)->next;
  404. goto next_non_null;
  405. } else {
  406. next_point = &(s->packet_buffer_end->next);
  407. }
  408. }
  409. assert(!*next_point);
  410. s->packet_buffer_end = this_pktl;
  411. next_non_null:
  412. this_pktl->next = *next_point;
  413. s->streams[pkt->stream_index]->last_in_packet_buffer =
  414. *next_point = this_pktl;
  415. }
  416. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  417. AVPacket *pkt)
  418. {
  419. AVStream *st = s->streams[pkt->stream_index];
  420. AVStream *st2 = s->streams[next->stream_index];
  421. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  422. st->time_base);
  423. if (comp == 0)
  424. return pkt->stream_index < next->stream_index;
  425. return comp > 0;
  426. }
  427. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  428. AVPacket *pkt, int flush)
  429. {
  430. AVPacketList *pktl;
  431. int stream_count = 0;
  432. int i;
  433. if (pkt) {
  434. ff_interleave_add_packet(s, pkt, interleave_compare_dts);
  435. }
  436. for (i = 0; i < s->nb_streams; i++)
  437. stream_count += !!s->streams[i]->last_in_packet_buffer;
  438. if (stream_count && (s->nb_streams == stream_count || flush)) {
  439. pktl = s->packet_buffer;
  440. *out = pktl->pkt;
  441. s->packet_buffer = pktl->next;
  442. if (!s->packet_buffer)
  443. s->packet_buffer_end = NULL;
  444. if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
  445. s->streams[out->stream_index]->last_in_packet_buffer = NULL;
  446. av_freep(&pktl);
  447. return 1;
  448. } else {
  449. av_init_packet(out);
  450. return 0;
  451. }
  452. }
  453. /**
  454. * Interleave an AVPacket correctly so it can be muxed.
  455. * @param out the interleaved packet will be output here
  456. * @param in the input packet
  457. * @param flush 1 if no further packets are available as input and all
  458. * remaining packets should be output
  459. * @return 1 if a packet was output, 0 if no packet could be output,
  460. * < 0 if an error occurred
  461. */
  462. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  463. {
  464. if (s->oformat->interleave_packet) {
  465. int ret = s->oformat->interleave_packet(s, out, in, flush);
  466. if (in)
  467. av_free_packet(in);
  468. return ret;
  469. } else
  470. return ff_interleave_packet_per_dts(s, out, in, flush);
  471. }
  472. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  473. {
  474. int ret, flush = 0;
  475. if (pkt) {
  476. AVStream *st = s->streams[pkt->stream_index];
  477. //FIXME/XXX/HACK drop zero sized packets
  478. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
  479. return 0;
  480. av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
  481. pkt->size, pkt->dts, pkt->pts);
  482. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  483. return ret;
  484. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  485. return AVERROR(EINVAL);
  486. } else {
  487. av_dlog(s, "av_interleaved_write_frame FLUSH\n");
  488. flush = 1;
  489. }
  490. for (;; ) {
  491. AVPacket opkt;
  492. int ret = interleave_packet(s, &opkt, pkt, flush);
  493. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  494. return ret;
  495. ret = write_packet(s, &opkt);
  496. if (ret >= 0)
  497. s->streams[opkt.stream_index]->nb_frames++;
  498. av_free_packet(&opkt);
  499. pkt = NULL;
  500. if (ret < 0)
  501. return ret;
  502. }
  503. }
  504. int av_write_trailer(AVFormatContext *s)
  505. {
  506. int ret, i;
  507. for (;; ) {
  508. AVPacket pkt;
  509. ret = interleave_packet(s, &pkt, NULL, 1);
  510. if (ret < 0) //FIXME cleanup needed for ret<0 ?
  511. goto fail;
  512. if (!ret)
  513. break;
  514. ret = write_packet(s, &pkt);
  515. if (ret >= 0)
  516. s->streams[pkt.stream_index]->nb_frames++;
  517. av_free_packet(&pkt);
  518. if (ret < 0)
  519. goto fail;
  520. }
  521. if (s->oformat->write_trailer)
  522. ret = s->oformat->write_trailer(s);
  523. if (!(s->oformat->flags & AVFMT_NOFILE))
  524. avio_flush(s->pb);
  525. fail:
  526. for (i = 0; i < s->nb_streams; i++) {
  527. av_freep(&s->streams[i]->priv_data);
  528. av_freep(&s->streams[i]->index_entries);
  529. }
  530. if (s->oformat->priv_class)
  531. av_opt_free(s->priv_data);
  532. av_freep(&s->priv_data);
  533. return ret;
  534. }