ffmpeg_mux.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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 <stdatomic.h>
  19. #include <stdio.h>
  20. #include <string.h>
  21. #include "ffmpeg.h"
  22. #include "ffmpeg_mux.h"
  23. #include "objpool.h"
  24. #include "sync_queue.h"
  25. #include "thread_queue.h"
  26. #include "libavutil/fifo.h"
  27. #include "libavutil/intreadwrite.h"
  28. #include "libavutil/log.h"
  29. #include "libavutil/mem.h"
  30. #include "libavutil/timestamp.h"
  31. #include "libavutil/thread.h"
  32. #include "libavcodec/packet.h"
  33. #include "libavformat/avformat.h"
  34. #include "libavformat/avio.h"
  35. int want_sdp = 1;
  36. static Muxer *mux_from_of(OutputFile *of)
  37. {
  38. return (Muxer*)of;
  39. }
  40. static int64_t filesize(AVIOContext *pb)
  41. {
  42. int64_t ret = -1;
  43. if (pb) {
  44. ret = avio_size(pb);
  45. if (ret <= 0) // FIXME improve avio_size() so it works with non seekable output too
  46. ret = avio_tell(pb);
  47. }
  48. return ret;
  49. }
  50. static int write_packet(Muxer *mux, OutputStream *ost, AVPacket *pkt)
  51. {
  52. MuxStream *ms = ms_from_ost(ost);
  53. AVFormatContext *s = mux->fc;
  54. int64_t fs;
  55. uint64_t frame_num;
  56. int ret;
  57. fs = filesize(s->pb);
  58. atomic_store(&mux->last_filesize, fs);
  59. if (fs >= mux->limit_filesize) {
  60. ret = AVERROR_EOF;
  61. goto fail;
  62. }
  63. if (ost->type == AVMEDIA_TYPE_VIDEO && ost->vsync_method == VSYNC_DROP)
  64. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
  65. av_packet_rescale_ts(pkt, pkt->time_base, ost->st->time_base);
  66. pkt->time_base = ost->st->time_base;
  67. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  68. if (pkt->dts != AV_NOPTS_VALUE &&
  69. pkt->pts != AV_NOPTS_VALUE &&
  70. pkt->dts > pkt->pts) {
  71. av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
  72. pkt->dts, pkt->pts,
  73. ost->file_index, ost->st->index);
  74. pkt->pts =
  75. pkt->dts = pkt->pts + pkt->dts + ms->last_mux_dts + 1
  76. - FFMIN3(pkt->pts, pkt->dts, ms->last_mux_dts + 1)
  77. - FFMAX3(pkt->pts, pkt->dts, ms->last_mux_dts + 1);
  78. }
  79. if ((ost->type == AVMEDIA_TYPE_AUDIO || ost->type == AVMEDIA_TYPE_VIDEO || ost->type == AVMEDIA_TYPE_SUBTITLE) &&
  80. pkt->dts != AV_NOPTS_VALUE &&
  81. ms->last_mux_dts != AV_NOPTS_VALUE) {
  82. int64_t max = ms->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
  83. if (pkt->dts < max) {
  84. int loglevel = max - pkt->dts > 2 || ost->type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
  85. if (exit_on_error)
  86. loglevel = AV_LOG_ERROR;
  87. av_log(s, loglevel, "Non-monotonous DTS in output stream "
  88. "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
  89. ost->file_index, ost->st->index, ms->last_mux_dts, pkt->dts);
  90. if (exit_on_error) {
  91. ret = AVERROR(EINVAL);
  92. goto fail;
  93. }
  94. av_log(s, loglevel, "changing to %"PRId64". This may result "
  95. "in incorrect timestamps in the output file.\n",
  96. max);
  97. if (pkt->pts >= pkt->dts)
  98. pkt->pts = FFMAX(pkt->pts, max);
  99. pkt->dts = max;
  100. }
  101. }
  102. }
  103. ms->last_mux_dts = pkt->dts;
  104. ms->data_size_mux += pkt->size;
  105. frame_num = atomic_fetch_add(&ost->packets_written, 1);
  106. pkt->stream_index = ost->index;
  107. if (debug_ts) {
  108. av_log(ost, AV_LOG_INFO, "muxer <- type:%s "
  109. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s duration:%s duration_time:%s size:%d\n",
  110. av_get_media_type_string(ost->type),
  111. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
  112. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
  113. av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &ost->st->time_base),
  114. pkt->size
  115. );
  116. }
  117. if (ms->stats.io)
  118. enc_stats_write(ost, &ms->stats, NULL, pkt, frame_num);
  119. ret = av_interleaved_write_frame(s, pkt);
  120. if (ret < 0) {
  121. av_log(ost, AV_LOG_ERROR,
  122. "Error submitting a packet to the muxer: %s\n",
  123. av_err2str(ret));
  124. goto fail;
  125. }
  126. return 0;
  127. fail:
  128. av_packet_unref(pkt);
  129. return ret;
  130. }
  131. static int sync_queue_process(Muxer *mux, OutputStream *ost, AVPacket *pkt, int *stream_eof)
  132. {
  133. OutputFile *of = &mux->of;
  134. if (ost->sq_idx_mux >= 0) {
  135. int ret = sq_send(mux->sq_mux, ost->sq_idx_mux, SQPKT(pkt));
  136. if (ret < 0) {
  137. if (ret == AVERROR_EOF)
  138. *stream_eof = 1;
  139. return ret;
  140. }
  141. while (1) {
  142. ret = sq_receive(mux->sq_mux, -1, SQPKT(mux->sq_pkt));
  143. if (ret < 0)
  144. return (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) ? 0 : ret;
  145. ret = write_packet(mux, of->streams[ret],
  146. mux->sq_pkt);
  147. if (ret < 0)
  148. return ret;
  149. }
  150. } else if (pkt)
  151. return write_packet(mux, ost, pkt);
  152. return 0;
  153. }
  154. static void thread_set_name(OutputFile *of)
  155. {
  156. char name[16];
  157. snprintf(name, sizeof(name), "mux%d:%s", of->index, of->format->name);
  158. ff_thread_setname(name);
  159. }
  160. static void *muxer_thread(void *arg)
  161. {
  162. Muxer *mux = arg;
  163. OutputFile *of = &mux->of;
  164. AVPacket *pkt = NULL;
  165. int ret = 0;
  166. pkt = av_packet_alloc();
  167. if (!pkt) {
  168. ret = AVERROR(ENOMEM);
  169. goto finish;
  170. }
  171. thread_set_name(of);
  172. while (1) {
  173. OutputStream *ost;
  174. int stream_idx, stream_eof = 0;
  175. ret = tq_receive(mux->tq, &stream_idx, pkt);
  176. if (stream_idx < 0) {
  177. av_log(mux, AV_LOG_VERBOSE, "All streams finished\n");
  178. ret = 0;
  179. break;
  180. }
  181. ost = of->streams[stream_idx];
  182. ret = sync_queue_process(mux, ost, ret < 0 ? NULL : pkt, &stream_eof);
  183. av_packet_unref(pkt);
  184. if (ret == AVERROR_EOF) {
  185. if (stream_eof) {
  186. tq_receive_finish(mux->tq, stream_idx);
  187. } else {
  188. av_log(mux, AV_LOG_VERBOSE, "Muxer returned EOF\n");
  189. ret = 0;
  190. break;
  191. }
  192. } else if (ret < 0) {
  193. av_log(mux, AV_LOG_ERROR, "Error muxing a packet\n");
  194. break;
  195. }
  196. }
  197. finish:
  198. av_packet_free(&pkt);
  199. for (unsigned int i = 0; i < mux->fc->nb_streams; i++)
  200. tq_receive_finish(mux->tq, i);
  201. av_log(mux, AV_LOG_VERBOSE, "Terminating muxer thread\n");
  202. return (void*)(intptr_t)ret;
  203. }
  204. static int thread_submit_packet(Muxer *mux, OutputStream *ost, AVPacket *pkt)
  205. {
  206. int ret = 0;
  207. if (!pkt || ost->finished & MUXER_FINISHED)
  208. goto finish;
  209. ret = tq_send(mux->tq, ost->index, pkt);
  210. if (ret < 0)
  211. goto finish;
  212. return 0;
  213. finish:
  214. if (pkt)
  215. av_packet_unref(pkt);
  216. ost->finished |= MUXER_FINISHED;
  217. tq_send_finish(mux->tq, ost->index);
  218. return ret == AVERROR_EOF ? 0 : ret;
  219. }
  220. static int queue_packet(OutputStream *ost, AVPacket *pkt)
  221. {
  222. MuxStream *ms = ms_from_ost(ost);
  223. AVPacket *tmp_pkt = NULL;
  224. int ret;
  225. if (!av_fifo_can_write(ms->muxing_queue)) {
  226. size_t cur_size = av_fifo_can_read(ms->muxing_queue);
  227. size_t pkt_size = pkt ? pkt->size : 0;
  228. unsigned int are_we_over_size =
  229. (ms->muxing_queue_data_size + pkt_size) > ms->muxing_queue_data_threshold;
  230. size_t limit = are_we_over_size ? ms->max_muxing_queue_size : SIZE_MAX;
  231. size_t new_size = FFMIN(2 * cur_size, limit);
  232. if (new_size <= cur_size) {
  233. av_log(ost, AV_LOG_ERROR,
  234. "Too many packets buffered for output stream %d:%d.\n",
  235. ost->file_index, ost->st->index);
  236. return AVERROR(ENOSPC);
  237. }
  238. ret = av_fifo_grow2(ms->muxing_queue, new_size - cur_size);
  239. if (ret < 0)
  240. return ret;
  241. }
  242. if (pkt) {
  243. ret = av_packet_make_refcounted(pkt);
  244. if (ret < 0)
  245. return ret;
  246. tmp_pkt = av_packet_alloc();
  247. if (!tmp_pkt)
  248. return AVERROR(ENOMEM);
  249. av_packet_move_ref(tmp_pkt, pkt);
  250. ms->muxing_queue_data_size += tmp_pkt->size;
  251. }
  252. av_fifo_write(ms->muxing_queue, &tmp_pkt, 1);
  253. return 0;
  254. }
  255. static int submit_packet(Muxer *mux, AVPacket *pkt, OutputStream *ost)
  256. {
  257. int ret;
  258. if (mux->tq) {
  259. return thread_submit_packet(mux, ost, pkt);
  260. } else {
  261. /* the muxer is not initialized yet, buffer the packet */
  262. ret = queue_packet(ost, pkt);
  263. if (ret < 0) {
  264. if (pkt)
  265. av_packet_unref(pkt);
  266. return ret;
  267. }
  268. }
  269. return 0;
  270. }
  271. void of_output_packet(OutputFile *of, OutputStream *ost, AVPacket *pkt)
  272. {
  273. Muxer *mux = mux_from_of(of);
  274. MuxStream *ms = ms_from_ost(ost);
  275. const char *err_msg;
  276. int ret = 0;
  277. if (pkt && pkt->dts != AV_NOPTS_VALUE)
  278. ost->last_mux_dts = av_rescale_q(pkt->dts, pkt->time_base, AV_TIME_BASE_Q);
  279. /* rescale timestamps to the muxing timebase */
  280. if (pkt) {
  281. av_packet_rescale_ts(pkt, pkt->time_base, ost->mux_timebase);
  282. pkt->time_base = ost->mux_timebase;
  283. }
  284. /* apply the output bitstream filters */
  285. if (ms->bsf_ctx) {
  286. int bsf_eof = 0;
  287. ret = av_bsf_send_packet(ms->bsf_ctx, pkt);
  288. if (ret < 0) {
  289. err_msg = "submitting a packet for bitstream filtering";
  290. goto fail;
  291. }
  292. while (!bsf_eof) {
  293. ret = av_bsf_receive_packet(ms->bsf_ctx, ms->bsf_pkt);
  294. if (ret == AVERROR(EAGAIN))
  295. return;
  296. else if (ret == AVERROR_EOF)
  297. bsf_eof = 1;
  298. else if (ret < 0) {
  299. err_msg = "applying bitstream filters to a packet";
  300. goto fail;
  301. }
  302. ret = submit_packet(mux, bsf_eof ? NULL : ms->bsf_pkt, ost);
  303. if (ret < 0)
  304. goto mux_fail;
  305. }
  306. } else {
  307. ret = submit_packet(mux, pkt, ost);
  308. if (ret < 0)
  309. goto mux_fail;
  310. }
  311. return;
  312. mux_fail:
  313. err_msg = "submitting a packet to the muxer";
  314. fail:
  315. av_log(ost, AV_LOG_ERROR, "Error %s\n", err_msg);
  316. if (exit_on_error)
  317. exit_program(1);
  318. }
  319. void of_streamcopy(OutputStream *ost, const AVPacket *pkt, int64_t dts)
  320. {
  321. OutputFile *of = output_files[ost->file_index];
  322. MuxStream *ms = ms_from_ost(ost);
  323. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  324. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
  325. AVPacket *opkt = ost->pkt;
  326. av_packet_unref(opkt);
  327. if (of->recording_time != INT64_MAX &&
  328. dts >= of->recording_time + start_time)
  329. pkt = NULL;
  330. // EOF: flush output bitstream filters.
  331. if (!pkt) {
  332. of_output_packet(of, ost, NULL);
  333. return;
  334. }
  335. if (!ms->streamcopy_started && !(pkt->flags & AV_PKT_FLAG_KEY) &&
  336. !ms->copy_initial_nonkeyframes)
  337. return;
  338. if (!ms->streamcopy_started) {
  339. if (!ms->copy_prior_start &&
  340. (pkt->pts == AV_NOPTS_VALUE ?
  341. dts < ms->ts_copy_start :
  342. pkt->pts < av_rescale_q(ms->ts_copy_start, AV_TIME_BASE_Q, pkt->time_base)))
  343. return;
  344. if (of->start_time != AV_NOPTS_VALUE && dts < of->start_time)
  345. return;
  346. }
  347. if (av_packet_ref(opkt, pkt) < 0)
  348. exit_program(1);
  349. opkt->time_base = ost->mux_timebase;
  350. if (pkt->pts != AV_NOPTS_VALUE)
  351. opkt->pts = av_rescale_q(pkt->pts, pkt->time_base, opkt->time_base) - ost_tb_start_time;
  352. if (pkt->dts == AV_NOPTS_VALUE) {
  353. opkt->dts = av_rescale_q(dts, AV_TIME_BASE_Q, opkt->time_base);
  354. } else if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  355. int duration = av_get_audio_frame_duration2(ost->par_in, pkt->size);
  356. if(!duration)
  357. duration = ost->par_in->frame_size;
  358. opkt->dts = av_rescale_delta(pkt->time_base, pkt->dts,
  359. (AVRational){1, ost->par_in->sample_rate}, duration,
  360. &ms->ts_rescale_delta_last, opkt->time_base);
  361. /* dts will be set immediately afterwards to what pts is now */
  362. opkt->pts = opkt->dts - ost_tb_start_time;
  363. } else
  364. opkt->dts = av_rescale_q(pkt->dts, pkt->time_base, opkt->time_base);
  365. opkt->dts -= ost_tb_start_time;
  366. opkt->duration = av_rescale_q(pkt->duration, pkt->time_base, opkt->time_base);
  367. {
  368. int ret = trigger_fix_sub_duration_heartbeat(ost, pkt);
  369. if (ret < 0) {
  370. av_log(NULL, AV_LOG_ERROR,
  371. "Subtitle heartbeat logic failed in %s! (%s)\n",
  372. __func__, av_err2str(ret));
  373. exit_program(1);
  374. }
  375. }
  376. of_output_packet(of, ost, opkt);
  377. ms->streamcopy_started = 1;
  378. }
  379. static int thread_stop(Muxer *mux)
  380. {
  381. void *ret;
  382. if (!mux || !mux->tq)
  383. return 0;
  384. for (unsigned int i = 0; i < mux->fc->nb_streams; i++)
  385. tq_send_finish(mux->tq, i);
  386. pthread_join(mux->thread, &ret);
  387. tq_free(&mux->tq);
  388. return (int)(intptr_t)ret;
  389. }
  390. static void pkt_move(void *dst, void *src)
  391. {
  392. av_packet_move_ref(dst, src);
  393. }
  394. static int thread_start(Muxer *mux)
  395. {
  396. AVFormatContext *fc = mux->fc;
  397. ObjPool *op;
  398. int ret;
  399. op = objpool_alloc_packets();
  400. if (!op)
  401. return AVERROR(ENOMEM);
  402. mux->tq = tq_alloc(fc->nb_streams, mux->thread_queue_size, op, pkt_move);
  403. if (!mux->tq) {
  404. objpool_free(&op);
  405. return AVERROR(ENOMEM);
  406. }
  407. ret = pthread_create(&mux->thread, NULL, muxer_thread, (void*)mux);
  408. if (ret) {
  409. tq_free(&mux->tq);
  410. return AVERROR(ret);
  411. }
  412. /* flush the muxing queues */
  413. for (int i = 0; i < fc->nb_streams; i++) {
  414. OutputStream *ost = mux->of.streams[i];
  415. MuxStream *ms = ms_from_ost(ost);
  416. AVPacket *pkt;
  417. /* try to improve muxing time_base (only possible if nothing has been written yet) */
  418. if (!av_fifo_can_read(ms->muxing_queue))
  419. ost->mux_timebase = ost->st->time_base;
  420. while (av_fifo_read(ms->muxing_queue, &pkt, 1) >= 0) {
  421. ret = thread_submit_packet(mux, ost, pkt);
  422. if (pkt) {
  423. ms->muxing_queue_data_size -= pkt->size;
  424. av_packet_free(&pkt);
  425. }
  426. if (ret < 0)
  427. return ret;
  428. }
  429. }
  430. return 0;
  431. }
  432. static int print_sdp(void)
  433. {
  434. char sdp[16384];
  435. int i;
  436. int j, ret;
  437. AVIOContext *sdp_pb;
  438. AVFormatContext **avc;
  439. for (i = 0; i < nb_output_files; i++) {
  440. if (!mux_from_of(output_files[i])->header_written)
  441. return 0;
  442. }
  443. avc = av_malloc_array(nb_output_files, sizeof(*avc));
  444. if (!avc)
  445. return AVERROR(ENOMEM);
  446. for (i = 0, j = 0; i < nb_output_files; i++) {
  447. if (!strcmp(output_files[i]->format->name, "rtp")) {
  448. avc[j] = mux_from_of(output_files[i])->fc;
  449. j++;
  450. }
  451. }
  452. if (!j) {
  453. av_log(NULL, AV_LOG_ERROR, "No output streams in the SDP.\n");
  454. ret = AVERROR(EINVAL);
  455. goto fail;
  456. }
  457. ret = av_sdp_create(avc, j, sdp, sizeof(sdp));
  458. if (ret < 0)
  459. goto fail;
  460. if (!sdp_filename) {
  461. printf("SDP:\n%s\n", sdp);
  462. fflush(stdout);
  463. } else {
  464. ret = avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL);
  465. if (ret < 0) {
  466. av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
  467. goto fail;
  468. }
  469. avio_print(sdp_pb, sdp);
  470. avio_closep(&sdp_pb);
  471. av_freep(&sdp_filename);
  472. }
  473. // SDP successfully written, allow muxer threads to start
  474. ret = 1;
  475. fail:
  476. av_freep(&avc);
  477. return ret;
  478. }
  479. int mux_check_init(Muxer *mux)
  480. {
  481. OutputFile *of = &mux->of;
  482. AVFormatContext *fc = mux->fc;
  483. int ret, i;
  484. for (i = 0; i < fc->nb_streams; i++) {
  485. OutputStream *ost = of->streams[i];
  486. if (!ost->initialized)
  487. return 0;
  488. }
  489. ret = avformat_write_header(fc, &mux->opts);
  490. if (ret < 0) {
  491. av_log(mux, AV_LOG_ERROR, "Could not write header (incorrect codec "
  492. "parameters ?): %s\n", av_err2str(ret));
  493. return ret;
  494. }
  495. //assert_avoptions(of->opts);
  496. mux->header_written = 1;
  497. av_dump_format(fc, of->index, fc->url, 1);
  498. nb_output_dumped++;
  499. if (sdp_filename || want_sdp) {
  500. ret = print_sdp();
  501. if (ret < 0) {
  502. av_log(NULL, AV_LOG_ERROR, "Error writing the SDP.\n");
  503. return ret;
  504. } else if (ret == 1) {
  505. /* SDP is written only after all the muxers are ready, so now we
  506. * start ALL the threads */
  507. for (i = 0; i < nb_output_files; i++) {
  508. ret = thread_start(mux_from_of(output_files[i]));
  509. if (ret < 0)
  510. return ret;
  511. }
  512. }
  513. } else {
  514. ret = thread_start(mux_from_of(of));
  515. if (ret < 0)
  516. return ret;
  517. }
  518. return 0;
  519. }
  520. static int bsf_init(MuxStream *ms)
  521. {
  522. OutputStream *ost = &ms->ost;
  523. AVBSFContext *ctx = ms->bsf_ctx;
  524. int ret;
  525. if (!ctx)
  526. return avcodec_parameters_copy(ost->st->codecpar, ost->par_in);
  527. ret = avcodec_parameters_copy(ctx->par_in, ost->par_in);
  528. if (ret < 0)
  529. return ret;
  530. ctx->time_base_in = ost->st->time_base;
  531. ret = av_bsf_init(ctx);
  532. if (ret < 0) {
  533. av_log(ms, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
  534. ctx->filter->name);
  535. return ret;
  536. }
  537. ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
  538. if (ret < 0)
  539. return ret;
  540. ost->st->time_base = ctx->time_base_out;
  541. ms->bsf_pkt = av_packet_alloc();
  542. if (!ms->bsf_pkt)
  543. return AVERROR(ENOMEM);
  544. return 0;
  545. }
  546. int of_stream_init(OutputFile *of, OutputStream *ost)
  547. {
  548. Muxer *mux = mux_from_of(of);
  549. MuxStream *ms = ms_from_ost(ost);
  550. int ret;
  551. /* initialize bitstream filters for the output stream
  552. * needs to be done here, because the codec id for streamcopy is not
  553. * known until now */
  554. ret = bsf_init(ms);
  555. if (ret < 0)
  556. return ret;
  557. if (ms->stream_duration) {
  558. ost->st->duration = av_rescale_q(ms->stream_duration, ms->stream_duration_tb,
  559. ost->st->time_base);
  560. }
  561. ost->initialized = 1;
  562. return mux_check_init(mux);
  563. }
  564. static int check_written(OutputFile *of)
  565. {
  566. int64_t total_packets_written = 0;
  567. int pass1_used = 1;
  568. int ret = 0;
  569. for (int i = 0; i < of->nb_streams; i++) {
  570. OutputStream *ost = of->streams[i];
  571. uint64_t packets_written = atomic_load(&ost->packets_written);
  572. total_packets_written += packets_written;
  573. if (ost->enc_ctx &&
  574. (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
  575. != AV_CODEC_FLAG_PASS1)
  576. pass1_used = 0;
  577. if (!packets_written &&
  578. (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM)) {
  579. av_log(ost, AV_LOG_FATAL, "Empty output stream\n");
  580. ret = err_merge(ret, AVERROR(EINVAL));
  581. }
  582. }
  583. if (!total_packets_written) {
  584. int level = AV_LOG_WARNING;
  585. if (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT) {
  586. ret = err_merge(ret, AVERROR(EINVAL));
  587. level = AV_LOG_FATAL;
  588. }
  589. av_log(of, level, "Output file is empty, nothing was encoded%s\n",
  590. pass1_used ? "" : "(check -ss / -t / -frames parameters if used)");
  591. }
  592. return ret;
  593. }
  594. static void mux_final_stats(Muxer *mux)
  595. {
  596. OutputFile *of = &mux->of;
  597. uint64_t total_packets = 0, total_size = 0;
  598. uint64_t video_size = 0, audio_size = 0, subtitle_size = 0,
  599. extra_size = 0, other_size = 0;
  600. uint8_t overhead[16] = "unknown";
  601. int64_t file_size = of_filesize(of);
  602. av_log(of, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
  603. of->index, of->url);
  604. for (int j = 0; j < of->nb_streams; j++) {
  605. OutputStream *ost = of->streams[j];
  606. MuxStream *ms = ms_from_ost(ost);
  607. const AVCodecParameters *par = ost->st->codecpar;
  608. const enum AVMediaType type = par->codec_type;
  609. const uint64_t s = ms->data_size_mux;
  610. switch (type) {
  611. case AVMEDIA_TYPE_VIDEO: video_size += s; break;
  612. case AVMEDIA_TYPE_AUDIO: audio_size += s; break;
  613. case AVMEDIA_TYPE_SUBTITLE: subtitle_size += s; break;
  614. default: other_size += s; break;
  615. }
  616. extra_size += par->extradata_size;
  617. total_size += s;
  618. total_packets += atomic_load(&ost->packets_written);
  619. av_log(of, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
  620. of->index, j, av_get_media_type_string(type));
  621. if (ost->enc) {
  622. av_log(of, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
  623. ost->frames_encoded);
  624. if (type == AVMEDIA_TYPE_AUDIO)
  625. av_log(of, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
  626. av_log(of, AV_LOG_VERBOSE, "; ");
  627. }
  628. av_log(of, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
  629. atomic_load(&ost->packets_written), s);
  630. av_log(of, AV_LOG_VERBOSE, "\n");
  631. }
  632. av_log(of, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
  633. total_packets, total_size);
  634. if (total_size && file_size > 0 && file_size >= total_size) {
  635. snprintf(overhead, sizeof(overhead), "%f%%",
  636. 100.0 * (file_size - total_size) / total_size);
  637. }
  638. av_log(of, AV_LOG_INFO,
  639. "video:%1.0fkB audio:%1.0fkB subtitle:%1.0fkB other streams:%1.0fkB "
  640. "global headers:%1.0fkB muxing overhead: %s\n",
  641. video_size / 1024.0,
  642. audio_size / 1024.0,
  643. subtitle_size / 1024.0,
  644. other_size / 1024.0,
  645. extra_size / 1024.0,
  646. overhead);
  647. }
  648. int of_write_trailer(OutputFile *of)
  649. {
  650. Muxer *mux = mux_from_of(of);
  651. AVFormatContext *fc = mux->fc;
  652. int ret, mux_result = 0;
  653. if (!mux->tq) {
  654. av_log(mux, AV_LOG_ERROR,
  655. "Nothing was written into output file, because "
  656. "at least one of its streams received no packets.\n");
  657. return AVERROR(EINVAL);
  658. }
  659. mux_result = thread_stop(mux);
  660. ret = av_write_trailer(fc);
  661. if (ret < 0) {
  662. av_log(mux, AV_LOG_ERROR, "Error writing trailer: %s\n", av_err2str(ret));
  663. mux_result = err_merge(mux_result, ret);
  664. }
  665. mux->last_filesize = filesize(fc->pb);
  666. if (!(of->format->flags & AVFMT_NOFILE)) {
  667. ret = avio_closep(&fc->pb);
  668. if (ret < 0) {
  669. av_log(mux, AV_LOG_ERROR, "Error closing file: %s\n", av_err2str(ret));
  670. mux_result = err_merge(mux_result, ret);
  671. }
  672. }
  673. mux_final_stats(mux);
  674. // check whether anything was actually written
  675. ret = check_written(of);
  676. mux_result = err_merge(mux_result, ret);
  677. return mux_result;
  678. }
  679. static void ost_free(OutputStream **post)
  680. {
  681. OutputStream *ost = *post;
  682. MuxStream *ms;
  683. if (!ost)
  684. return;
  685. ms = ms_from_ost(ost);
  686. enc_free(&ost->enc);
  687. if (ost->logfile) {
  688. if (fclose(ost->logfile))
  689. av_log(ms, AV_LOG_ERROR,
  690. "Error closing logfile, loss of information possible: %s\n",
  691. av_err2str(AVERROR(errno)));
  692. ost->logfile = NULL;
  693. }
  694. if (ms->muxing_queue) {
  695. AVPacket *pkt;
  696. while (av_fifo_read(ms->muxing_queue, &pkt, 1) >= 0)
  697. av_packet_free(&pkt);
  698. av_fifo_freep2(&ms->muxing_queue);
  699. }
  700. avcodec_parameters_free(&ost->par_in);
  701. av_bsf_free(&ms->bsf_ctx);
  702. av_packet_free(&ms->bsf_pkt);
  703. av_packet_free(&ost->pkt);
  704. av_dict_free(&ost->encoder_opts);
  705. av_freep(&ost->kf.pts);
  706. av_expr_free(ost->kf.pexpr);
  707. av_freep(&ost->logfile_prefix);
  708. av_freep(&ost->apad);
  709. #if FFMPEG_OPT_MAP_CHANNEL
  710. av_freep(&ost->audio_channels_map);
  711. ost->audio_channels_mapped = 0;
  712. #endif
  713. av_dict_free(&ost->sws_dict);
  714. av_dict_free(&ost->swr_opts);
  715. if (ost->enc_ctx)
  716. av_freep(&ost->enc_ctx->stats_in);
  717. avcodec_free_context(&ost->enc_ctx);
  718. for (int i = 0; i < ost->enc_stats_pre.nb_components; i++)
  719. av_freep(&ost->enc_stats_pre.components[i].str);
  720. av_freep(&ost->enc_stats_pre.components);
  721. for (int i = 0; i < ost->enc_stats_post.nb_components; i++)
  722. av_freep(&ost->enc_stats_post.components[i].str);
  723. av_freep(&ost->enc_stats_post.components);
  724. for (int i = 0; i < ms->stats.nb_components; i++)
  725. av_freep(&ms->stats.components[i].str);
  726. av_freep(&ms->stats.components);
  727. av_freep(post);
  728. }
  729. static void fc_close(AVFormatContext **pfc)
  730. {
  731. AVFormatContext *fc = *pfc;
  732. if (!fc)
  733. return;
  734. if (!(fc->oformat->flags & AVFMT_NOFILE))
  735. avio_closep(&fc->pb);
  736. avformat_free_context(fc);
  737. *pfc = NULL;
  738. }
  739. void of_close(OutputFile **pof)
  740. {
  741. OutputFile *of = *pof;
  742. Muxer *mux;
  743. if (!of)
  744. return;
  745. mux = mux_from_of(of);
  746. thread_stop(mux);
  747. sq_free(&of->sq_encode);
  748. sq_free(&mux->sq_mux);
  749. for (int i = 0; i < of->nb_streams; i++)
  750. ost_free(&of->streams[i]);
  751. av_freep(&of->streams);
  752. av_dict_free(&mux->opts);
  753. av_packet_free(&mux->sq_pkt);
  754. fc_close(&mux->fc);
  755. av_freep(pof);
  756. }
  757. int64_t of_filesize(OutputFile *of)
  758. {
  759. Muxer *mux = mux_from_of(of);
  760. return atomic_load(&mux->last_filesize);
  761. }