ffmpeg_mux.c 26 KB

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