From 16c71cac0d5c81e84271222d1ed0c501fe723d56 Mon Sep 17 00:00:00 2001 From: "Steinar H. Gunderson" Date: Mon, 18 Apr 2016 19:35:18 +0200 Subject: [PATCH] Synchronize the Mux class, since both H264EncoderImpl and X264Encoder are writing to it (from different threads). --- mux.cpp | 15 +++++++++++---- mux.h | 5 ++++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/mux.cpp b/mux.cpp index eff336f..534d56a 100644 --- a/mux.cpp +++ b/mux.cpp @@ -1,5 +1,6 @@ #include +#include #include #include @@ -86,7 +87,10 @@ Mux::~Mux() void Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts) { AVPacket pkt_copy; - av_copy_packet(&pkt_copy, &pkt); + if (av_copy_packet(&pkt_copy, &pkt) < 0) { + fprintf(stderr, "av_copy_packet() failed\n"); + exit(1); + } if (pkt.stream_index == 0) { pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_video->time_base); pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_video->time_base); @@ -106,9 +110,12 @@ void Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts) } } - if (av_interleaved_write_frame(avctx, &pkt_copy) < 0) { - fprintf(stderr, "av_interleaved_write_frame() failed\n"); - exit(1); + { + lock_guard lock(ctx_mu); + if (av_interleaved_write_frame(avctx, &pkt_copy) < 0) { + fprintf(stderr, "av_interleaved_write_frame() failed\n"); + exit(1); + } } av_packet_unref(&pkt_copy); diff --git a/mux.h b/mux.h index 2eb8eea..d645916 100644 --- a/mux.h +++ b/mux.h @@ -9,6 +9,8 @@ extern "C" { #include } +#include + class KeyFrameSignalReceiver { public: // Needs to automatically turn the flag off again after actually receiving data. @@ -28,7 +30,8 @@ public: void add_packet(const AVPacket &pkt, int64_t pts, int64_t dts); private: - AVFormatContext *avctx; + std::mutex ctx_mu; + AVFormatContext *avctx; // Protected by . AVStream *avstream_video, *avstream_audio; KeyFrameSignalReceiver *keyframe_signal_receiver; }; -- 2.39.2