You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
236 lines
6.6 KiB
236 lines
6.6 KiB
#ifndef LRF_PROXY_ONLY
|
|
|
|
#include "streamLiveEncoder.h"
|
|
|
|
extern "C"
|
|
{
|
|
#include <libavutil/opt.h>
|
|
}
|
|
|
|
#define LOG(X) m_pLog->Log("LIVE_ENC", this, X)
|
|
#define LOG_ERROR(X) m_pLog->Log("LIVE_ENC", this, _LOG_ERROR, X)
|
|
|
|
streamLiveEncoder::streamLiveEncoder(std::shared_ptr<mtx::MediaPath> path, int fps, int bitrateKbps) :
|
|
m_pLog(basicLogCollection::getInstance()), m_pPath(std::move(path)), m_oFeeder(m_pPath.get()), m_nFps(fps > 0 ? fps : 15), m_nBitrateKbps(bitrateKbps > 0 ? bitrateKbps : 2000),
|
|
m_bHavePending(false), m_bRun(true), m_nNextFrameUs(0), m_pCtx(NULL), m_pFrame(NULL), m_pPacket(NULL), m_pSws(NULL), m_nWidth(0), m_nHeight(0), m_nFrameIndex(0), m_nLastReaders(0),
|
|
m_bOpenFailed(false)
|
|
{
|
|
m_thread = std::thread(&streamLiveEncoder::run, this);
|
|
}
|
|
|
|
streamLiveEncoder::~streamLiveEncoder()
|
|
{
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
m_bRun = false;
|
|
}
|
|
m_cond.notify_all();
|
|
if (m_thread.joinable())
|
|
{
|
|
m_thread.join();
|
|
}
|
|
m_oFeeder.setParent(nullptr); // the path is not ready any more
|
|
closeEncoder();
|
|
}
|
|
|
|
void streamLiveEncoder::push(const cv::Mat & bgr)
|
|
{
|
|
if (bgr.empty() || m_bOpenFailed)
|
|
{
|
|
return;
|
|
}
|
|
// Nobody watches, nothing is recorded: no CPU for encoding
|
|
if (m_pPath->readerCount() == 0 && ! m_pPath->recording())
|
|
{
|
|
return;
|
|
}
|
|
int64_t tNow = mtx::nowUs();
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
if (tNow < m_nNextFrameUs)
|
|
{
|
|
return; // above the frame rate of the live stream
|
|
}
|
|
m_nNextFrameUs = (m_nNextFrameUs == 0 || tNow - m_nNextFrameUs > 1000000) ? tNow + 1000000 / m_nFps : m_nNextFrameUs + 1000000 / m_nFps;
|
|
bgr.copyTo(m_mPending); // replaces a frame the encoder did not take yet (it is late: drop)
|
|
m_bHavePending = true;
|
|
m_cond.notify_one();
|
|
}
|
|
|
|
void streamLiveEncoder::run()
|
|
{
|
|
pthread_setname_np(pthread_self(), "LiveEncoder");
|
|
cv::Mat tFrame;
|
|
while (true)
|
|
{
|
|
{
|
|
std::unique_lock<std::mutex> lock(m_mutex);
|
|
m_cond.wait(lock, [this] { return ! m_bRun || m_bHavePending; });
|
|
if (! m_bRun)
|
|
{
|
|
break;
|
|
}
|
|
cv::swap(tFrame, m_mPending);
|
|
m_bHavePending = false;
|
|
}
|
|
size_t tReaders = m_pPath->readerCount();
|
|
bool tIdr = tReaders > m_nLastReaders; // a new viewer: start it now, not at the next GOP
|
|
m_nLastReaders = tReaders;
|
|
if (m_pCtx != NULL && (tFrame.cols != m_nWidth || tFrame.rows != m_nHeight))
|
|
{
|
|
closeEncoder(); // the frame size changed (module settings)
|
|
}
|
|
if (m_pCtx == NULL)
|
|
{
|
|
if (! openEncoder(tFrame.cols, tFrame.rows))
|
|
{
|
|
m_bOpenFailed = true;
|
|
break;
|
|
}
|
|
tIdr = true;
|
|
}
|
|
if (! encode(tFrame, tIdr))
|
|
{
|
|
closeEncoder(); // opened again with the next frame
|
|
}
|
|
}
|
|
}
|
|
|
|
bool streamLiveEncoder::openEncoder(int width, int height)
|
|
{
|
|
const AVCodec * tCodec = avcodec_find_encoder_by_name("libx264");
|
|
if (tCodec == NULL)
|
|
{
|
|
tCodec = avcodec_find_encoder(AV_CODEC_ID_H264);
|
|
}
|
|
if (tCodec == NULL)
|
|
{
|
|
LOG_ERROR("No H264 encoder in libavcodec: live view of the processed frames is not possible");
|
|
return false;
|
|
}
|
|
m_pCtx = avcodec_alloc_context3(tCodec);
|
|
if (m_pCtx == NULL)
|
|
{
|
|
return false;
|
|
}
|
|
m_nWidth = width & ~1; // 4:2:0 needs even sizes
|
|
m_nHeight = height & ~1;
|
|
m_pCtx->width = m_nWidth;
|
|
m_pCtx->height = m_nHeight;
|
|
m_pCtx->pix_fmt = AV_PIX_FMT_YUV420P;
|
|
m_pCtx->time_base = AVRational {1, 90000};
|
|
m_pCtx->framerate = AVRational {m_nFps, 1};
|
|
m_pCtx->gop_size = m_nFps * 2; // a new viewer waits at most 2 s (and gets one at once, see run())
|
|
m_pCtx->max_b_frames = 0; // WebRTC / fMP4 writer: dts = pts
|
|
m_pCtx->bit_rate = (int64_t) m_nBitrateKbps * 1000;
|
|
m_pCtx->rc_max_rate = m_pCtx->bit_rate;
|
|
m_pCtx->rc_buffer_size = (int) m_pCtx->bit_rate; // 1 s
|
|
m_pCtx->thread_count = 2;
|
|
m_pCtx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE;
|
|
if (strcmp(tCodec->name, "libx264") == 0)
|
|
{
|
|
av_opt_set(m_pCtx->priv_data, "preset", "veryfast", 0);
|
|
av_opt_set(m_pCtx->priv_data, "tune", "zerolatency", 0);
|
|
av_opt_set(m_pCtx->priv_data, "profile", "baseline", 0);
|
|
av_opt_set(m_pCtx->priv_data, "x264-params", "repeat-headers=1", 0); // SPS / PPS with every IDR
|
|
av_opt_set(m_pCtx->priv_data, "forced-idr", "1", 0); // a forced key frame is an IDR
|
|
}
|
|
int tRet = avcodec_open2(m_pCtx, tCodec, NULL);
|
|
if (tRet < 0)
|
|
{
|
|
char tE[128], tB[256];
|
|
av_strerror(tRet, tE, sizeof(tE));
|
|
snprintf(tB, sizeof(tB), "Cannot open the H264 encoder %s: %s", tCodec->name, tE);
|
|
LOG_ERROR(tB);
|
|
avcodec_free_context(&m_pCtx);
|
|
return false;
|
|
}
|
|
m_pFrame = av_frame_alloc();
|
|
m_pPacket = av_packet_alloc();
|
|
m_pSws = sws_getContext(width, height, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL);
|
|
if (m_pFrame == NULL || m_pPacket == NULL || m_pSws == NULL)
|
|
{
|
|
LOG_ERROR("Live encoder: allocation failed");
|
|
closeEncoder();
|
|
return false;
|
|
}
|
|
m_pFrame->format = AV_PIX_FMT_YUV420P;
|
|
m_pFrame->width = m_nWidth;
|
|
m_pFrame->height = m_nHeight;
|
|
if (av_frame_get_buffer(m_pFrame, 32) < 0)
|
|
{
|
|
closeEncoder();
|
|
return false;
|
|
}
|
|
if (m_pCtx->extradata != NULL && m_pCtx->extradata_size > 0)
|
|
{
|
|
m_oFeeder.setExtradata(m_pCtx->extradata, m_pCtx->extradata_size);
|
|
}
|
|
char tB[200];
|
|
snprintf(tB, sizeof(tB), "H264 encoder %s opened: %dx%d, %d fps, %d kbit/s", tCodec->name, m_nWidth, m_nHeight, m_nFps, m_nBitrateKbps);
|
|
LOG(tB);
|
|
return true;
|
|
}
|
|
|
|
void streamLiveEncoder::closeEncoder()
|
|
{
|
|
if (m_pSws != NULL)
|
|
{
|
|
sws_freeContext(m_pSws);
|
|
m_pSws = NULL;
|
|
}
|
|
av_frame_free(&m_pFrame);
|
|
av_packet_free(&m_pPacket);
|
|
avcodec_free_context(&m_pCtx);
|
|
m_nWidth = 0;
|
|
m_nHeight = 0;
|
|
}
|
|
|
|
bool streamLiveEncoder::encode(const cv::Mat & bgr, bool forceIdr)
|
|
{
|
|
if (av_frame_make_writable(m_pFrame) < 0)
|
|
{
|
|
return false;
|
|
}
|
|
const uint8_t * tSrc[1] = {bgr.data};
|
|
int tStep[1] = {(int) bgr.step[0]};
|
|
sws_scale(m_pSws, tSrc, tStep, 0, bgr.rows, m_pFrame->data, m_pFrame->linesize);
|
|
int64_t tNowUs = mtx::nowUs();
|
|
m_pFrame->pts = tNowUs * 9 / 100; // 90 kHz wall clock: the real frame timing
|
|
m_pFrame->pict_type = forceIdr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE;
|
|
int tRet = avcodec_send_frame(m_pCtx, m_pFrame);
|
|
if (tRet < 0)
|
|
{
|
|
LOG_ERROR("Live encoder: send frame failed");
|
|
return false;
|
|
}
|
|
while (true)
|
|
{
|
|
tRet = avcodec_receive_packet(m_pCtx, m_pPacket);
|
|
if (tRet == AVERROR(EAGAIN) || tRet == AVERROR_EOF)
|
|
{
|
|
break;
|
|
}
|
|
if (tRet < 0)
|
|
{
|
|
LOG_ERROR("Live encoder: receive packet failed");
|
|
return false;
|
|
}
|
|
int64_t tPtsUs = (m_pPacket->pts != AV_NOPTS_VALUE) ? m_pPacket->pts * 100 / 9 : tNowUs;
|
|
if (m_oFeeder.avccLengthSize() > 0)
|
|
{
|
|
m_oFeeder.pushAvcc(m_pPacket->data, m_pPacket->size, m_oFeeder.avccLengthSize(), tPtsUs);
|
|
}
|
|
else
|
|
{
|
|
m_oFeeder.pushAnnexB(m_pPacket->data, m_pPacket->size, tPtsUs);
|
|
}
|
|
av_packet_unref(m_pPacket);
|
|
}
|
|
m_nFrameIndex++;
|
|
return true;
|
|
}
|
|
|
|
#undef LOG
|
|
#undef LOG_ERROR
|
|
|
|
#endif // !LRF_PROXY_ONLY
|