ffmpeg_mux.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include "ffmpeg.h"
  21. #include "libavutil/fifo.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "libavutil/log.h"
  24. #include "libavutil/mem.h"
  25. #include "libavutil/timestamp.h"
  26. #include "libavcodec/packet.h"
  27. #include "libavformat/avformat.h"
  28. #include "libavformat/avio.h"
  29. static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
  30. {
  31. int i;
  32. for (i = 0; i < nb_output_streams; i++) {
  33. OutputStream *ost2 = output_streams[i];
  34. ost2->finished |= ost == ost2 ? this_stream : others;
  35. }
  36. }
  37. void of_write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost,
  38. int unqueue)
  39. {
  40. AVFormatContext *s = of->ctx;
  41. AVStream *st = ost->st;
  42. int ret;
  43. /*
  44. * Audio encoders may split the packets -- #frames in != #packets out.
  45. * But there is no reordering, so we can limit the number of output packets
  46. * by simply dropping them here.
  47. * Counting encoded video frames needs to be done separately because of
  48. * reordering, see do_video_out().
  49. * Do not count the packet when unqueued because it has been counted when queued.
  50. */
  51. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
  52. if (ost->frame_number >= ost->max_frames) {
  53. av_packet_unref(pkt);
  54. return;
  55. }
  56. ost->frame_number++;
  57. }
  58. if (!of->header_written) {
  59. AVPacket *tmp_pkt;
  60. /* the muxer is not initialized yet, buffer the packet */
  61. if (!av_fifo_can_write(ost->muxing_queue)) {
  62. size_t cur_size = av_fifo_can_read(ost->muxing_queue);
  63. unsigned int are_we_over_size =
  64. (ost->muxing_queue_data_size + pkt->size) > ost->muxing_queue_data_threshold;
  65. size_t limit = are_we_over_size ? ost->max_muxing_queue_size : SIZE_MAX;
  66. size_t new_size = FFMIN(2 * cur_size, limit);
  67. if (new_size <= cur_size) {
  68. av_log(NULL, AV_LOG_ERROR,
  69. "Too many packets buffered for output stream %d:%d.\n",
  70. ost->file_index, ost->st->index);
  71. exit_program(1);
  72. }
  73. ret = av_fifo_grow2(ost->muxing_queue, new_size - cur_size);
  74. if (ret < 0)
  75. exit_program(1);
  76. }
  77. ret = av_packet_make_refcounted(pkt);
  78. if (ret < 0)
  79. exit_program(1);
  80. tmp_pkt = av_packet_alloc();
  81. if (!tmp_pkt)
  82. exit_program(1);
  83. av_packet_move_ref(tmp_pkt, pkt);
  84. ost->muxing_queue_data_size += tmp_pkt->size;
  85. av_fifo_write(ost->muxing_queue, &tmp_pkt, 1);
  86. return;
  87. }
  88. if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->vsync_method == VSYNC_DROP) ||
  89. (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
  90. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
  91. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  92. if (ost->frame_rate.num && ost->is_cfr) {
  93. if (pkt->duration > 0)
  94. av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
  95. pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
  96. ost->mux_timebase);
  97. }
  98. }
  99. av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
  100. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  101. if (pkt->dts != AV_NOPTS_VALUE &&
  102. pkt->pts != AV_NOPTS_VALUE &&
  103. pkt->dts > pkt->pts) {
  104. av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
  105. pkt->dts, pkt->pts,
  106. ost->file_index, ost->st->index);
  107. pkt->pts =
  108. pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
  109. - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
  110. - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
  111. }
  112. if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
  113. pkt->dts != AV_NOPTS_VALUE &&
  114. ost->last_mux_dts != AV_NOPTS_VALUE) {
  115. int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
  116. if (pkt->dts < max) {
  117. int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
  118. if (exit_on_error)
  119. loglevel = AV_LOG_ERROR;
  120. av_log(s, loglevel, "Non-monotonous DTS in output stream "
  121. "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
  122. ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
  123. if (exit_on_error) {
  124. av_log(NULL, AV_LOG_FATAL, "aborting.\n");
  125. exit_program(1);
  126. }
  127. av_log(s, loglevel, "changing to %"PRId64". This may result "
  128. "in incorrect timestamps in the output file.\n",
  129. max);
  130. if (pkt->pts >= pkt->dts)
  131. pkt->pts = FFMAX(pkt->pts, max);
  132. pkt->dts = max;
  133. }
  134. }
  135. }
  136. ost->last_mux_dts = pkt->dts;
  137. ost->data_size += pkt->size;
  138. ost->packets_written++;
  139. pkt->stream_index = ost->index;
  140. if (debug_ts) {
  141. av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
  142. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s duration:%s duration_time:%s size:%d\n",
  143. av_get_media_type_string(ost->enc_ctx->codec_type),
  144. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
  145. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
  146. av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &ost->st->time_base),
  147. pkt->size
  148. );
  149. }
  150. ret = av_interleaved_write_frame(s, pkt);
  151. if (ret < 0) {
  152. print_error("av_interleaved_write_frame()", ret);
  153. main_return_code = 1;
  154. close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
  155. }
  156. }
  157. static int print_sdp(void)
  158. {
  159. char sdp[16384];
  160. int i;
  161. int j, ret;
  162. AVIOContext *sdp_pb;
  163. AVFormatContext **avc;
  164. for (i = 0; i < nb_output_files; i++) {
  165. if (!output_files[i]->header_written)
  166. return 0;
  167. }
  168. avc = av_malloc_array(nb_output_files, sizeof(*avc));
  169. if (!avc)
  170. exit_program(1);
  171. for (i = 0, j = 0; i < nb_output_files; i++) {
  172. if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
  173. avc[j] = output_files[i]->ctx;
  174. j++;
  175. }
  176. }
  177. if (!j) {
  178. av_log(NULL, AV_LOG_ERROR, "No output streams in the SDP.\n");
  179. ret = AVERROR(EINVAL);
  180. goto fail;
  181. }
  182. ret = av_sdp_create(avc, j, sdp, sizeof(sdp));
  183. if (ret < 0)
  184. goto fail;
  185. if (!sdp_filename) {
  186. printf("SDP:\n%s\n", sdp);
  187. fflush(stdout);
  188. } else {
  189. ret = avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL);
  190. if (ret < 0) {
  191. av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
  192. goto fail;
  193. }
  194. avio_print(sdp_pb, sdp);
  195. avio_closep(&sdp_pb);
  196. av_freep(&sdp_filename);
  197. }
  198. fail:
  199. av_freep(&avc);
  200. return ret;
  201. }
  202. /* open the muxer when all the streams are initialized */
  203. int of_check_init(OutputFile *of)
  204. {
  205. int ret, i;
  206. for (i = 0; i < of->ctx->nb_streams; i++) {
  207. OutputStream *ost = output_streams[of->ost_index + i];
  208. if (!ost->initialized)
  209. return 0;
  210. }
  211. ret = avformat_write_header(of->ctx, &of->opts);
  212. if (ret < 0) {
  213. av_log(NULL, AV_LOG_ERROR,
  214. "Could not write header for output file #%d "
  215. "(incorrect codec parameters ?): %s\n",
  216. of->index, av_err2str(ret));
  217. return ret;
  218. }
  219. //assert_avoptions(of->opts);
  220. of->header_written = 1;
  221. av_dump_format(of->ctx, of->index, of->ctx->url, 1);
  222. nb_output_dumped++;
  223. if (sdp_filename || want_sdp) {
  224. ret = print_sdp();
  225. if (ret < 0) {
  226. av_log(NULL, AV_LOG_ERROR, "Error writing the SDP.\n");
  227. return ret;
  228. }
  229. }
  230. /* flush the muxing queues */
  231. for (i = 0; i < of->ctx->nb_streams; i++) {
  232. OutputStream *ost = output_streams[of->ost_index + i];
  233. AVPacket *pkt;
  234. /* try to improve muxing time_base (only possible if nothing has been written yet) */
  235. if (!av_fifo_can_read(ost->muxing_queue))
  236. ost->mux_timebase = ost->st->time_base;
  237. while (av_fifo_read(ost->muxing_queue, &pkt, 1) >= 0) {
  238. ost->muxing_queue_data_size -= pkt->size;
  239. of_write_packet(of, pkt, ost, 1);
  240. av_packet_free(&pkt);
  241. }
  242. }
  243. return 0;
  244. }
  245. int of_write_trailer(OutputFile *of)
  246. {
  247. int ret;
  248. if (!of->header_written) {
  249. av_log(NULL, AV_LOG_ERROR,
  250. "Nothing was written into output file %d (%s), because "
  251. "at least one of its streams received no packets.\n",
  252. of->index, of->ctx->url);
  253. return AVERROR(EINVAL);
  254. }
  255. ret = av_write_trailer(of->ctx);
  256. if (ret < 0) {
  257. av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s\n", of->ctx->url, av_err2str(ret));
  258. return ret;
  259. }
  260. return 0;
  261. }
  262. void of_close(OutputFile **pof)
  263. {
  264. OutputFile *of = *pof;
  265. AVFormatContext *s;
  266. if (!of)
  267. return;
  268. s = of->ctx;
  269. if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
  270. avio_closep(&s->pb);
  271. avformat_free_context(s);
  272. av_dict_free(&of->opts);
  273. av_freep(pof);
  274. }