Skip to content

Commit

Permalink
🐛 Fixing video encoder multithread bug
Browse files Browse the repository at this point in the history
  • Loading branch information
elieserdejesus committed Oct 7, 2017
1 parent 28b6f26 commit 43e59da
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
21 changes: 16 additions & 5 deletions src/Common/video/FFMpegMuxer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ FFMpegMuxer::FFMpegMuxer()
startNewIntervalRequested(false)
{
av_register_all();

threadPool.setMaxThreadCount(1);
}

void FFMpegMuxer::initialize()
Expand All @@ -115,18 +117,19 @@ FFMpegMuxer::~FFMpegMuxer()
void FFMpegMuxer::encodeImage(const QImage &image)
{
// encoding in a separated thread
QtConcurrent::run([=](){

auto lambda = [=](){

if (startNewIntervalRequested) {
if (prepareToEncodeNewInterval())
startNewIntervalRequested = false;
else
qCritical() << "Can't prepare for next interval!";
}

if (encodeVideo && !image.isNull())
encodeVideo = !doEncodeVideoFrame(image.copy());
});
};

QtConcurrent::run(&threadPool, lambda);
}

void FFMpegMuxer::encodeAudioFrame()
Expand Down Expand Up @@ -180,6 +183,11 @@ bool FFMpegMuxer::prepareToEncodeNewInterval()

// streaming to memory https://trac.ffmpeg.org/ticket/984
avioContext = avio_alloc_context(buffer, FFMPEG_BUFFER_SIZE, 1, this, nullptr, writeCallback, nullptr);
if (!avioContext) {
qCritical() << "Can't create avio context!";
return false;
}

avioContext->seekable = 0; // no seek
formatContext->pb = avioContext;

Expand All @@ -203,7 +211,7 @@ bool FFMpegMuxer::prepareToEncodeNewInterval()

ret = avformat_write_header(formatContext, nullptr); // Write the stream header, if any.
if (ret < 0) {
qCritical() << "Error occurred when opening output file: " << av_err2str(ret);
qCritical() << "Error occurred when opening output file: " << ret;
return false;
}

Expand Down Expand Up @@ -685,6 +693,9 @@ void FFMpegMuxer::fillFrameWithImageData(const QImage &image)
*/
bool FFMpegMuxer::doEncodeVideoFrame(const QImage &image)
{
if (!initialized)
return false;

if (!videoStream)
return false;

Expand Down
5 changes: 2 additions & 3 deletions src/Common/video/FFMpegMuxer.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
#include <QImage>
#include <QSize>
#include <QFile>
#include <QMutex>
#include <QThread>
#include <QDebug>
#include <QWaitCondition>
#include <QThreadPool>

#include "FFMpegCommon.h"

Expand Down Expand Up @@ -106,6 +104,7 @@ public slots:
bool initialized;
bool startNewIntervalRequested;

QThreadPool threadPool;
};

inline void FFMpegMuxer::setVideoQuality(VideoQuality quality)
Expand Down

0 comments on commit 43e59da

Please sign in to comment.