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.

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