Sunshine/sunshine/video.cpp

1646 lines
46 KiB
C++
Raw Normal View History

//
// Created by loki on 6/6/19.
//
2020-02-08 16:26:38 +01:00
#include <atomic>
#include <bitset>
2021-05-17 21:21:57 +02:00
#include <thread>
extern "C" {
#include <libswscale/swscale.h>
}
2021-05-17 21:21:57 +02:00
#include "config.h"
#include "main.h"
#include "platform/common.h"
#include "round_robin.h"
#include "sync.h"
#include "video.h"
2020-04-15 19:16:20 +02:00
#ifdef _WIN32
extern "C" {
#include <libavutil/hwcontext_d3d11va.h>
}
#endif
namespace video {
using namespace std::literals;
void free_ctx(AVCodecContext *ctx) {
avcodec_free_context(&ctx);
}
void free_frame(AVFrame *frame) {
av_frame_free(&frame);
}
2020-03-25 10:51:32 +01:00
void free_buffer(AVBufferRef *ref) {
av_buffer_unref(&ref);
}
using ctx_t = util::safe_ptr<AVCodecContext, free_ctx>;
using frame_t = util::safe_ptr<AVFrame, free_frame>;
2020-03-25 10:51:32 +01:00
using buffer_t = util::safe_ptr<AVBufferRef, free_buffer>;
using sws_t = util::safe_ptr<SwsContext, sws_freeContext>;
2020-02-08 16:26:38 +01:00
using img_event_t = std::shared_ptr<safe::event_t<std::shared_ptr<platf::img_t>>>;
platf::mem_type_e map_dev_type(AVHWDeviceType type);
2020-04-15 19:16:20 +02:00
platf::pix_fmt_e map_pix_fmt(AVPixelFormat fmt);
util::Either<buffer_t, int> dxgi_make_hwdevice_ctx(platf::hwdevice_t *hwdevice_ctx);
util::Either<buffer_t, int> vaapi_make_hwdevice_ctx(platf::hwdevice_t *hwdevice_ctx);
2020-04-15 19:16:20 +02:00
int hwframe_ctx(ctx_t &ctx, buffer_t &hwdevice, AVPixelFormat format);
class swdevice_t : public platf::hwdevice_t {
public:
int convert(platf::img_t &img) override {
av_frame_make_writable(sw_frame.get());
2020-04-15 19:16:20 +02:00
const int linesizes[2] {
img.row_pitch, 0
};
std::uint8_t *data[4];
data[0] = sw_frame->data[0] + offset;
if(sw_frame->format == AV_PIX_FMT_NV12) {
data[1] = sw_frame->data[1] + offset;
data[2] = nullptr;
}
else {
data[1] = sw_frame->data[1] + offset / 2;
data[2] = sw_frame->data[2] + offset / 2;
data[3] = nullptr;
}
int ret = sws_scale(sws.get(), (std::uint8_t *const *)&img.data, linesizes, 0, img.height, data, sw_frame->linesize);
2020-04-15 19:16:20 +02:00
if(ret <= 0) {
BOOST_LOG(error) << "Couldn't convert image to required format and/or size"sv;
2020-04-15 19:16:20 +02:00
return -1;
}
// If frame is not a software frame, it means we still need to transfer from main memory
// to vram memory
if(frame->hw_frames_ctx) {
auto status = av_hwframe_transfer_data(frame, sw_frame.get(), 0);
if(status < 0) {
char string[AV_ERROR_MAX_STRING_SIZE];
BOOST_LOG(error) << "Failed to transfer image data to hardware frame: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status);
return -1;
}
}
2020-04-15 19:16:20 +02:00
return 0;
}
int set_frame(AVFrame *frame) {
this->frame = frame;
// If it's a hwframe, allocate buffers for hardware
2021-06-04 21:35:00 +02:00
if(frame->hw_frames_ctx) {
hw_frame.reset(frame);
if(av_hwframe_get_buffer(frame->hw_frames_ctx, frame, 0)) return -1;
}
if(!frame->hw_frames_ctx) {
sw_frame.reset(frame);
}
return 0;
}
void set_colorspace(std::uint32_t colorspace, std::uint32_t color_range) override {
2020-04-15 19:16:20 +02:00
sws_setColorspaceDetails(sws.get(),
sws_getCoefficients(SWS_CS_DEFAULT), 0,
2021-05-17 21:21:57 +02:00
sws_getCoefficients(colorspace), color_range - 1,
0, 1 << 16, 1 << 16);
2020-04-15 19:16:20 +02:00
}
/**
* When preserving aspect ratio, ensure that padding is black
*/
int prefill() {
2021-06-04 21:35:00 +02:00
auto frame = sw_frame ? sw_frame.get() : this->frame;
auto width = frame->width;
auto height = frame->height;
2021-06-04 21:35:00 +02:00
av_frame_get_buffer(frame, 0);
sws_t sws {
sws_getContext(
width, height, AV_PIX_FMT_BGR0,
2021-06-04 21:35:00 +02:00
width, height, (AVPixelFormat)frame->format,
SWS_LANCZOS | SWS_ACCURATE_RND,
nullptr, nullptr, nullptr)
};
if(!sws) {
return -1;
}
util::buffer_t<std::uint32_t> img { (std::size_t)(width * height) };
std::fill(std::begin(img), std::end(img), 0);
const int linesizes[2] {
width, 0
};
2021-06-04 21:35:00 +02:00
av_frame_make_writable(frame);
auto data = img.begin();
2021-06-04 21:35:00 +02:00
int ret = sws_scale(sws.get(), (std::uint8_t *const *)&data, linesizes, 0, height, frame->data, frame->linesize);
if(ret <= 0) {
BOOST_LOG(error) << "Couldn't convert image to required format and/or size"sv;
return -1;
}
return 0;
}
int init(int in_width, int in_height, AVFrame *frame, AVPixelFormat format) {
// If the device used is hardware, yet the image resides on main memory
if(frame->hw_frames_ctx) {
2021-06-04 21:35:00 +02:00
sw_frame.reset(av_frame_alloc());
sw_frame->width = frame->width;
sw_frame->height = frame->height;
sw_frame->format = format;
}
else {
2021-06-04 21:35:00 +02:00
this->frame = frame;
}
if(prefill()) {
return -1;
}
auto out_width = frame->width;
auto out_height = frame->height;
// Ensure aspect ratio is maintained
auto scalar = std::fminf((float)out_width / in_width, (float)out_height / in_height);
out_width = in_width * scalar;
out_height = in_height * scalar;
// result is always positive
auto offsetX = (frame->width - out_width) / 2;
auto offsetY = (frame->height - out_height) / 2;
offset = offsetX + offsetY * frame->width;
2020-04-15 19:16:20 +02:00
sws.reset(sws_getContext(
in_width, in_height, AV_PIX_FMT_BGR0,
out_width, out_height, format,
SWS_LANCZOS | SWS_ACCURATE_RND,
2021-05-17 21:21:57 +02:00
nullptr, nullptr, nullptr));
2020-04-15 19:16:20 +02:00
return sws ? 0 : -1;
}
2021-06-04 21:35:00 +02:00
~swdevice_t() override {}
// Store ownsership when frame is hw_frame
frame_t hw_frame;
2020-04-15 19:16:20 +02:00
frame_t sw_frame;
2020-04-15 19:16:20 +02:00
sws_t sws;
// offset of input image to output frame in pixels
int offset;
2020-04-15 19:16:20 +02:00
};
2020-03-25 10:51:32 +01:00
enum flag_e {
DEFAULT = 0x00,
SYSTEM_MEMORY = 0x01,
H264_ONLY = 0x02,
LIMITED_GOP_SIZE = 0x04,
};
2020-03-25 10:51:32 +01:00
struct encoder_t {
2020-04-14 00:15:24 +03:00
std::string_view name;
enum flag_e {
2021-05-17 21:21:57 +02:00
PASSED, // Is supported
REF_FRAMES_RESTRICT, // Set maximum reference frames
REF_FRAMES_AUTOSELECT, // Allow encoder to select maximum reference frames (If !REF_FRAMES_RESTRICT --> REF_FRAMES_AUTOSELECT)
SLICE, // Allow frame to be partitioned into multiple slices
DYNAMIC_RANGE, // hdr
MAX_FLAGS
};
static std::string_view from_flag(flag_e flag) {
#define _CONVERT(x) \
case flag_e::x: \
return #x##sv
switch(flag) {
_CONVERT(PASSED);
_CONVERT(REF_FRAMES_RESTRICT);
_CONVERT(REF_FRAMES_AUTOSELECT);
_CONVERT(SLICE);
_CONVERT(DYNAMIC_RANGE);
_CONVERT(MAX_FLAGS);
}
#undef _CONVERT
return "unknown"sv;
}
2020-03-25 10:51:32 +01:00
struct option_t {
2020-04-14 00:15:24 +03:00
KITTY_DEFAULT_CONSTR(option_t)
option_t(const option_t &) = default;
2020-03-25 10:51:32 +01:00
std::string name;
2021-05-17 21:21:57 +02:00
std::variant<int, int *, std::optional<int> *, std::string, std::string *> value;
2020-04-14 00:15:24 +03:00
2021-05-17 21:21:57 +02:00
option_t(std::string &&name, decltype(value) &&value) : name { std::move(name) }, value { std::move(value) } {}
2020-03-25 10:51:32 +01:00
};
struct {
int h264_high;
int hevc_main;
int hevc_main_10;
} profile;
AVHWDeviceType dev_type;
2020-04-06 23:15:03 +03:00
AVPixelFormat dev_pix_fmt;
2020-03-25 10:51:32 +01:00
2020-04-06 23:15:03 +03:00
AVPixelFormat static_pix_fmt;
AVPixelFormat dynamic_pix_fmt;
2020-03-25 10:51:32 +01:00
struct {
std::vector<option_t> options;
2020-04-14 00:15:24 +03:00
std::optional<option_t> crf, qp;
2020-03-25 10:51:32 +01:00
std::string name;
std::bitset<MAX_FLAGS> capabilities;
2020-04-07 14:54:56 +03:00
bool operator[](flag_e flag) const {
return capabilities[(std::size_t)flag];
}
std::bitset<MAX_FLAGS>::reference operator[](flag_e flag) {
return capabilities[(std::size_t)flag];
}
2020-03-25 10:51:32 +01:00
} hevc, h264;
int flags;
2020-03-25 10:51:32 +01:00
2020-04-15 19:16:20 +02:00
std::function<util::Either<buffer_t, int>(platf::hwdevice_t *hwdevice)> make_hwdevice_ctx;
2020-03-25 10:51:32 +01:00
};
2020-04-15 19:16:20 +02:00
class session_t {
public:
2020-04-14 00:15:24 +03:00
session_t() = default;
session_t(ctx_t &&ctx, util::wrap_ptr<platf::hwdevice_t> &&device) : ctx { std::move(ctx) }, device { std::move(device) } {}
2020-04-15 19:16:20 +02:00
session_t(session_t &&other) noexcept : ctx { std::move(other.ctx) }, device { std::move(other.device) } {}
2020-04-14 00:15:24 +03:00
// Ensure objects are destroyed in the correct order
session_t &operator=(session_t &&other) {
2020-04-15 19:16:20 +02:00
device = std::move(other.device);
2021-05-17 21:21:57 +02:00
ctx = std::move(other.ctx);
2020-04-14 00:15:24 +03:00
return *this;
}
2020-03-25 10:51:32 +01:00
ctx_t ctx;
2020-04-15 19:16:20 +02:00
util::wrap_ptr<platf::hwdevice_t> device;
2020-03-25 10:51:32 +01:00
};
2020-04-15 19:16:20 +02:00
struct sync_session_ctx_t {
2020-04-12 02:33:17 +03:00
safe::signal_t *shutdown_event;
safe::signal_t *join_event;
packet_queue_t packets;
idr_event_t idr_events;
config_t config;
int frame_nr;
int key_frame_nr;
void *channel_data;
};
2020-04-15 19:16:20 +02:00
struct sync_session_t {
sync_session_ctx_t *ctx;
2021-05-17 21:21:57 +02:00
2020-04-12 02:33:17 +03:00
std::chrono::steady_clock::time_point next_frame;
std::chrono::nanoseconds delay;
2020-04-12 02:33:17 +03:00
platf::img_t *img_tmp;
2020-04-15 19:16:20 +02:00
std::shared_ptr<platf::hwdevice_t> hwdevice;
2020-04-12 02:33:17 +03:00
session_t session;
};
2020-04-15 19:16:20 +02:00
using encode_session_ctx_queue_t = safe::queue_t<sync_session_ctx_t>;
2021-05-17 21:21:57 +02:00
using encode_e = platf::capture_e;
2020-04-12 02:33:17 +03:00
2020-04-14 00:15:24 +03:00
struct capture_ctx_t {
img_event_t images;
std::chrono::nanoseconds delay;
};
2020-04-15 19:16:20 +02:00
struct capture_thread_async_ctx_t {
2020-04-14 00:15:24 +03:00
std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue;
std::thread capture_thread;
safe::signal_t reinit_event;
const encoder_t *encoder_p;
util::sync_t<std::weak_ptr<platf::display_t>> display_wp;
};
2020-04-15 19:16:20 +02:00
struct capture_thread_sync_ctx_t {
encode_session_ctx_queue_t encode_session_ctx_queue { 30 };
2020-04-12 02:33:17 +03:00
};
2020-04-15 19:16:20 +02:00
int start_capture_sync(capture_thread_sync_ctx_t &ctx);
void end_capture_sync(capture_thread_sync_ctx_t &ctx);
int start_capture_async(capture_thread_async_ctx_t &ctx);
void end_capture_async(capture_thread_async_ctx_t &ctx);
2020-04-14 00:15:24 +03:00
// Keep a reference counter to ensure the capture thread only runs when other threads have a reference to the capture thread
2020-04-15 19:16:20 +02:00
auto capture_thread_async = safe::make_shared<capture_thread_async_ctx_t>(start_capture_async, end_capture_async);
2021-05-17 21:21:57 +02:00
auto capture_thread_sync = safe::make_shared<capture_thread_sync_ctx_t>(start_capture_sync, end_capture_sync);
2020-04-12 02:33:17 +03:00
2020-04-15 19:16:20 +02:00
#ifdef _WIN32
2020-03-25 10:51:32 +01:00
static encoder_t nvenc {
2020-04-14 00:15:24 +03:00
"nvenc"sv,
2020-04-12 02:33:17 +03:00
{ (int)nv::profile_h264_e::high, (int)nv::profile_hevc_e::main, (int)nv::profile_hevc_e::main_10 },
2020-03-25 10:51:32 +01:00
AV_HWDEVICE_TYPE_D3D11VA,
AV_PIX_FMT_D3D11,
AV_PIX_FMT_NV12, AV_PIX_FMT_P010,
2020-03-25 10:51:32 +01:00
{
{
{ "forced-idr"s, 1 },
2020-04-14 00:15:24 +03:00
{ "zerolatency"s, 1 },
{ "preset"s, &config::video.nv.preset },
{ "rc"s, &config::video.nv.rc },
},
2021-05-17 21:21:57 +02:00
std::nullopt,
std::nullopt,
2020-04-14 00:15:24 +03:00
"hevc_nvenc"s,
2020-03-25 10:51:32 +01:00
},
{
{
{ "forced-idr"s, 1 },
2020-04-14 00:15:24 +03:00
{ "zerolatency"s, 1 },
{ "preset"s, &config::video.nv.preset },
{ "rc"s, &config::video.nv.rc },
{ "coder"s, &config::video.nv.coder },
},
std::nullopt,
std::make_optional<encoder_t::option_t>({ "qp"s, &config::video.qp }),
"h264_nvenc"s,
},
DEFAULT,
2020-03-25 10:51:32 +01:00
dxgi_img_to_frame,
dxgi_make_hwdevice_ctx
2020-03-25 10:51:32 +01:00
};
2021-01-28 18:32:58 -05:00
static encoder_t amdvce {
"amdvce"sv,
2021-05-09 16:19:05 +02:00
{ FF_PROFILE_H264_HIGH, FF_PROFILE_HEVC_MAIN },
2021-01-28 18:32:58 -05:00
AV_HWDEVICE_TYPE_D3D11VA,
AV_PIX_FMT_D3D11,
AV_PIX_FMT_NV12, AV_PIX_FMT_P010,
2021-01-28 18:32:58 -05:00
{
{
{ "header_insertion_mode"s, "idr"s },
2021-04-01 14:25:38 +02:00
{ "gops_per_idr"s, 30 },
{ "usage"s, "ultralowlatency"s },
2021-01-28 18:32:58 -05:00
{ "quality"s, &config::video.amd.quality },
{ "rc"s, &config::video.amd.rc },
},
2021-05-17 21:21:57 +02:00
std::nullopt,
std::make_optional<encoder_t::option_t>({ "qp"s, &config::video.qp }),
2021-01-28 18:32:58 -05:00
"hevc_amf"s,
},
{
{
2021-04-01 14:25:38 +02:00
{ "usage"s, "ultralowlatency"s },
2021-01-28 18:32:58 -05:00
{ "quality"s, &config::video.amd.quality },
2021-04-01 14:25:38 +02:00
{ "rc"s, &config::video.amd.rc },
2021-05-17 21:21:57 +02:00
{ "log_to_dbg"s, "1"s },
2021-01-28 18:32:58 -05:00
},
std::nullopt,
std::make_optional<encoder_t::option_t>({ "qp"s, &config::video.qp }),
"h264_amf"s,
},
DEFAULT,
2021-01-28 18:32:58 -05:00
dxgi_make_hwdevice_ctx
2021-01-28 18:32:58 -05:00
};
2020-04-15 19:16:20 +02:00
#endif
2020-03-25 10:51:32 +01:00
static encoder_t software {
2020-04-14 00:15:24 +03:00
"software"sv,
2020-03-25 10:51:32 +01:00
{ FF_PROFILE_H264_HIGH, FF_PROFILE_HEVC_MAIN, FF_PROFILE_HEVC_MAIN_10 },
AV_HWDEVICE_TYPE_NONE,
AV_PIX_FMT_NONE,
2020-04-06 23:15:03 +03:00
AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV420P10,
{
// x265's Info SEI is so long that it causes the IDR picture data to be
2020-03-25 10:51:32 +01:00
// kicked to the 2nd packet in the frame, breaking Moonlight's parsing logic.
// It also looks like gop_size isn't passed on to x265, so we have to set
// 'keyint=-1' in the parameters ourselves.
{
{ "forced-idr"s, 1 },
{ "x265-params"s, "info=0:keyint=-1"s },
2020-04-14 00:15:24 +03:00
{ "preset"s, &config::video.sw.preset },
{ "tune"s, &config::video.sw.tune },
},
std::make_optional<encoder_t::option_t>("crf"s, &config::video.crf),
std::make_optional<encoder_t::option_t>("qp"s, &config::video.qp),
"libx265"s,
},
{
{
{ "preset"s, &config::video.sw.preset },
{ "tune"s, &config::video.sw.tune },
},
std::make_optional<encoder_t::option_t>("crf"s, &config::video.crf),
std::make_optional<encoder_t::option_t>("qp"s, &config::video.qp),
"libx264"s,
},
H264_ONLY | SYSTEM_MEMORY,
2020-03-25 10:51:32 +01:00
2020-04-06 23:15:03 +03:00
nullptr
2020-03-25 10:51:32 +01:00
};
#ifdef __linux__
static encoder_t vaapi {
"vaapi"sv,
{ FF_PROFILE_H264_HIGH, FF_PROFILE_HEVC_MAIN, FF_PROFILE_HEVC_MAIN_10 },
AV_HWDEVICE_TYPE_VAAPI,
AV_PIX_FMT_VAAPI,
AV_PIX_FMT_NV12, AV_PIX_FMT_YUV420P10,
{
{
{ "sei"s, 0 },
{ "idr_interval"s, std::numeric_limits<int>::max() },
},
std::nullopt,
std::nullopt,
"hevc_vaapi"s,
},
{
{
{ "sei"s, 0 },
{ "idr_interval"s, std::numeric_limits<int>::max() },
},
std::nullopt,
std::nullopt,
"h264_vaapi"s,
},
LIMITED_GOP_SIZE | SYSTEM_MEMORY,
vaapi_make_hwdevice_ctx
};
#endif
2020-03-25 10:51:32 +01:00
static std::vector<encoder_t> encoders {
2020-04-15 19:16:20 +02:00
#ifdef _WIN32
nvenc,
2021-01-28 18:32:58 -05:00
amdvce,
#endif
#ifdef __linux__
vaapi,
2020-04-15 19:16:20 +02:00
#endif
software
2020-03-25 10:51:32 +01:00
};
void reset_display(std::shared_ptr<platf::display_t> &disp, AVHWDeviceType type) {
// We try this twice, in case we still get an error on reinitialization
for(int x = 0; x < 2; ++x) {
disp.reset();
2020-04-12 02:33:17 +03:00
disp = platf::display(map_dev_type(type));
if(disp) {
break;
}
2021-05-17 21:21:57 +02:00
std::this_thread::sleep_for(200ms);
}
}
void captureThread(
std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue,
util::sync_t<std::weak_ptr<platf::display_t>> &display_wp,
safe::signal_t &reinit_event,
2021-05-17 21:21:57 +02:00
const encoder_t &encoder) {
2020-02-08 16:26:38 +01:00
std::vector<capture_ctx_t> capture_ctxs;
auto fg = util::fail_guard([&]() {
capture_ctx_queue->stop();
// Stop all sessions listening to this thread
for(auto &capture_ctx : capture_ctxs) {
capture_ctx.images->stop();
}
for(auto &capture_ctx : capture_ctx_queue->unsafe()) {
capture_ctx.images->stop();
}
});
std::chrono::nanoseconds delay = 1s;
2020-04-12 02:33:17 +03:00
auto disp = platf::display(map_dev_type(encoder.dev_type));
if(!disp) {
return;
}
display_wp = disp;
std::vector<std::shared_ptr<platf::img_t>> imgs(12);
2020-04-10 15:39:50 +03:00
auto round_robin = util::make_round_robin<std::shared_ptr<platf::img_t>>(std::begin(imgs), std::end(imgs));
for(auto &img : imgs) {
img = disp->alloc_img();
if(!img) {
BOOST_LOG(error) << "Couldn't initialize an image"sv;
return;
}
}
2020-04-10 15:39:50 +03:00
2021-05-17 21:21:57 +02:00
if(auto capture_ctx = capture_ctx_queue->pop()) {
2020-04-10 15:39:50 +03:00
capture_ctxs.emplace_back(std::move(*capture_ctx));
delay = capture_ctxs.back().delay;
2020-04-06 23:15:03 +03:00
}
auto next_frame = std::chrono::steady_clock::now();
2020-02-08 16:26:38 +01:00
while(capture_ctx_queue->running()) {
while(capture_ctx_queue->peek()) {
capture_ctxs.emplace_back(std::move(*capture_ctx_queue->pop()));
delay = std::min(delay, capture_ctxs.back().delay);
2020-02-08 16:26:38 +01:00
}
auto now = std::chrono::steady_clock::now();
auto &img = *round_robin++;
2020-04-07 18:57:59 +03:00
while(img.use_count() > 1) {}
2020-04-08 02:15:08 +03:00
2020-04-10 15:39:50 +03:00
auto status = disp->snapshot(img.get(), 1000ms, display_cursor);
2021-05-17 21:21:57 +02:00
switch(status) {
case platf::capture_e::reinit: {
reinit_event.raise(true);
2021-05-17 21:21:57 +02:00
// Some classes of images contain references to the display --> display won't delete unless img is deleted
for(auto &img : imgs) {
img.reset();
}
2021-05-17 21:21:57 +02:00
// Some classes of display cannot have multiple instances at once
disp.reset();
2021-05-17 21:21:57 +02:00
// display_wp is modified in this thread only
while(!display_wp->expired()) {
std::this_thread::sleep_for(100ms);
}
2021-05-17 21:21:57 +02:00
while(capture_ctx_queue->running()) {
reset_display(disp, encoder.dev_type);
2021-05-17 21:21:57 +02:00
if(disp) {
break;
}
2021-05-17 21:21:57 +02:00
std::this_thread::sleep_for(200ms);
}
if(!disp) {
return;
}
2021-05-17 21:21:57 +02:00
display_wp = disp;
// Re-allocate images
for(auto &img : imgs) {
img = disp->alloc_img();
if(!img) {
BOOST_LOG(error) << "Couldn't initialize an image"sv;
return;
}
}
2021-05-17 21:21:57 +02:00
reinit_event.reset();
continue;
}
case platf::capture_e::error:
return;
case platf::capture_e::timeout:
std::this_thread::sleep_for(1ms);
continue;
case platf::capture_e::ok:
break;
default:
BOOST_LOG(error) << "Unrecognized capture status ["sv << (int)status << ']';
return;
2020-02-09 17:30:11 +01:00
}
2020-02-08 16:26:38 +01:00
KITTY_WHILE_LOOP(auto capture_ctx = std::begin(capture_ctxs), capture_ctx != std::end(capture_ctxs), {
2020-02-08 16:26:38 +01:00
if(!capture_ctx->images->running()) {
auto tmp_delay = capture_ctx->delay;
2021-05-17 21:21:57 +02:00
capture_ctx = capture_ctxs.erase(capture_ctx);
2020-02-08 16:26:38 +01:00
if(tmp_delay == delay) {
delay = std::min_element(std::begin(capture_ctxs), std::end(capture_ctxs), [](const auto &l, const auto &r) {
return l.delay < r.delay;
})->delay;
}
continue;
2020-02-08 16:26:38 +01:00
}
2020-02-09 17:30:11 +01:00
capture_ctx->images->raise(img);
2020-02-09 17:30:11 +01:00
++capture_ctx;
})
2020-04-10 15:39:50 +03:00
if(next_frame > now) {
std::this_thread::sleep_until(next_frame);
}
next_frame += delay;
2020-02-08 16:26:38 +01:00
}
}
int encode(int64_t frame_nr, ctx_t &ctx, frame_t::pointer frame, packet_queue_t &packets, void *channel_data) {
2020-03-25 10:51:32 +01:00
frame->pts = frame_nr;
/* send the frame to the encoder */
auto ret = avcodec_send_frame(ctx.get(), frame);
2021-05-17 21:21:57 +02:00
if(ret < 0) {
char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 };
2020-04-06 23:15:03 +03:00
BOOST_LOG(error) << "Could not send a frame for encoding: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, ret);
return -1;
}
2021-05-17 21:21:57 +02:00
while(ret >= 0) {
2020-02-08 16:26:38 +01:00
auto packet = std::make_unique<packet_t::element_type>(nullptr);
ret = avcodec_receive_packet(ctx.get(), packet.get());
2021-05-17 21:21:57 +02:00
if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
return 0;
2020-01-18 11:33:16 +01:00
}
2021-05-17 21:21:57 +02:00
else if(ret < 0) {
return ret;
}
2020-02-08 16:26:38 +01:00
packet->channel_data = channel_data;
2019-12-11 19:06:52 +01:00
packets->raise(std::move(packet));
}
return 0;
}
2020-04-15 19:16:20 +02:00
std::optional<session_t> make_session(const encoder_t &encoder, const config_t &config, int width, int height, platf::hwdevice_t *hwdevice) {
bool hardware = encoder.dev_type != AV_HWDEVICE_TYPE_NONE;
2020-03-25 10:51:32 +01:00
auto &video_format = config.videoFormat == 0 ? encoder.h264 : encoder.hevc;
2020-04-14 00:15:24 +03:00
if(!video_format[encoder_t::PASSED]) {
2021-05-17 21:21:57 +02:00
BOOST_LOG(error) << encoder.name << ": "sv << video_format.name << " mode not supported"sv;
2020-04-14 00:15:24 +03:00
return std::nullopt;
}
if(config.dynamicRange && !video_format[encoder_t::DYNAMIC_RANGE]) {
BOOST_LOG(error) << video_format.name << ": dynamic range not supported"sv;
return std::nullopt;
}
2020-02-08 16:26:38 +01:00
2020-03-25 10:51:32 +01:00
auto codec = avcodec_find_encoder_by_name(video_format.name.c_str());
if(!codec) {
BOOST_LOG(error) << "Couldn't open ["sv << video_format.name << ']';
2020-02-08 16:26:38 +01:00
2020-03-25 10:51:32 +01:00
return std::nullopt;
2020-02-08 16:26:38 +01:00
}
2020-04-15 19:16:20 +02:00
ctx_t ctx { avcodec_alloc_context3(codec) };
2021-05-17 21:21:57 +02:00
ctx->width = config.width;
ctx->height = config.height;
ctx->time_base = AVRational { 1, config.framerate };
ctx->framerate = AVRational { config.framerate, 1 };
if(config.videoFormat == 0) {
2020-03-25 10:51:32 +01:00
ctx->profile = encoder.profile.h264_high;
}
else if(config.dynamicRange == 0) {
2020-03-25 10:51:32 +01:00
ctx->profile = encoder.profile.hevc_main;
}
else {
2020-03-25 10:51:32 +01:00
ctx->profile = encoder.profile.hevc_main_10;
}
2020-03-25 10:51:32 +01:00
// B-frames delay decoder output, so never use them
ctx->max_b_frames = 0;
// Use an infinite GOP length since I-frames are generated on demand
ctx->gop_size = encoder.flags & LIMITED_GOP_SIZE ?
std::numeric_limits<std::int16_t>::max() :
std::numeric_limits<int>::max();
ctx->keyint_min = std::numeric_limits<int>::max();
2020-03-25 10:51:32 +01:00
2020-04-07 14:54:56 +03:00
if(config.numRefFrames == 0) {
2020-04-17 18:42:55 +02:00
ctx->refs = video_format[encoder_t::REF_FRAMES_AUTOSELECT] ? 0 : 16;
2020-04-07 14:54:56 +03:00
}
else {
// Some client decoders have limits on the number of reference frames
ctx->refs = video_format[encoder_t::REF_FRAMES_RESTRICT] ? config.numRefFrames : 0;
}
2020-03-25 10:51:32 +01:00
ctx->flags |= (AV_CODEC_FLAG_CLOSED_GOP | AV_CODEC_FLAG_LOW_DELAY);
ctx->flags2 |= AV_CODEC_FLAG2_FAST;
ctx->color_range = (config.encoderCscMode & 0x1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2020-03-25 10:51:32 +01:00
int sws_color_space;
2021-05-17 21:21:57 +02:00
switch(config.encoderCscMode >> 1) {
case 0:
default:
// Rec. 601
BOOST_LOG(info) << "Color coding [Rec. 601]"sv;
ctx->color_primaries = AVCOL_PRI_SMPTE170M;
ctx->color_trc = AVCOL_TRC_SMPTE170M;
ctx->colorspace = AVCOL_SPC_SMPTE170M;
sws_color_space = SWS_CS_SMPTE170M;
break;
2021-05-17 21:21:57 +02:00
case 1:
// Rec. 709
BOOST_LOG(info) << "Color coding [Rec. 709]"sv;
ctx->color_primaries = AVCOL_PRI_BT709;
ctx->color_trc = AVCOL_TRC_BT709;
ctx->colorspace = AVCOL_SPC_BT709;
sws_color_space = SWS_CS_ITU709;
break;
2021-05-17 21:21:57 +02:00
case 2:
// Rec. 2020
BOOST_LOG(info) << "Color coding [Rec. 2020]"sv;
ctx->color_primaries = AVCOL_PRI_BT2020;
ctx->color_trc = AVCOL_TRC_BT2020_10;
ctx->colorspace = AVCOL_SPC_BT2020_NCL;
sws_color_space = SWS_CS_BT2020;
break;
}
2021-05-03 22:06:55 +02:00
BOOST_LOG(info) << "Color range: ["sv << ((config.encoderCscMode & 0x1) ? "JPEG"sv : "MPEG"sv) << ']';
AVPixelFormat sw_fmt;
2020-03-25 10:51:32 +01:00
if(config.dynamicRange == 0) {
2020-04-06 23:15:03 +03:00
sw_fmt = encoder.static_pix_fmt;
2020-03-25 10:51:32 +01:00
}
else {
2020-04-06 23:15:03 +03:00
sw_fmt = encoder.dynamic_pix_fmt;
2020-03-25 10:51:32 +01:00
}
2020-04-15 19:16:20 +02:00
buffer_t hwdevice_ctx;
2020-03-25 10:51:32 +01:00
if(hardware) {
2020-04-06 23:15:03 +03:00
ctx->pix_fmt = encoder.dev_pix_fmt;
2020-03-25 10:51:32 +01:00
2020-04-15 19:16:20 +02:00
auto buf_or_error = encoder.make_hwdevice_ctx(hwdevice);
2020-04-06 23:15:03 +03:00
if(buf_or_error.has_right()) {
return std::nullopt;
}
2020-04-15 19:16:20 +02:00
hwdevice_ctx = std::move(buf_or_error.left());
if(hwframe_ctx(ctx, hwdevice_ctx, sw_fmt)) {
2020-03-25 10:51:32 +01:00
return std::nullopt;
}
2020-04-10 15:39:50 +03:00
ctx->slices = config.slicesPerFrame;
2020-03-25 10:51:32 +01:00
}
else /* software */ {
ctx->pix_fmt = sw_fmt;
2020-03-25 10:51:32 +01:00
// Clients will request for the fewest slices per frame to get the
// most efficient encode, but we may want to provide more slices than
// requested to ensure we have enough parallelism for good performance.
ctx->slices = std::max(config.slicesPerFrame, config::video.min_threads);
}
if(!video_format[encoder_t::SLICE]) {
ctx->slices = 1;
}
2021-05-17 21:21:57 +02:00
ctx->thread_type = FF_THREAD_SLICE;
2020-04-14 00:15:24 +03:00
ctx->thread_count = ctx->slices;
2021-05-17 21:21:57 +02:00
AVDictionary *options { nullptr };
2020-04-14 00:15:24 +03:00
auto handle_option = [&options](const encoder_t::option_t &option) {
2021-05-17 21:21:57 +02:00
std::visit(
util::overloaded {
[&](int v) { av_dict_set_int(&options, option.name.c_str(), v, 0); },
[&](int *v) { av_dict_set_int(&options, option.name.c_str(), *v, 0); },
[&](std::optional<int> *v) { if(*v) av_dict_set_int(&options, option.name.c_str(), **v, 0); },
[&](const std::string &v) { av_dict_set(&options, option.name.c_str(), v.c_str(), 0); },
[&](std::string *v) { if(!v->empty()) av_dict_set(&options, option.name.c_str(), v->c_str(), 0); } },
option.value);
2020-04-14 00:15:24 +03:00
};
for(auto &option : video_format.options) {
handle_option(option);
2020-03-25 10:51:32 +01:00
}
2019-12-21 16:41:51 +01:00
if(config.bitrate > 500) {
2021-05-17 21:21:57 +02:00
auto bitrate = config.bitrate * 1000;
ctx->rc_max_rate = bitrate;
2020-04-10 15:39:50 +03:00
ctx->rc_buffer_size = bitrate / config.framerate;
2021-05-17 21:21:57 +02:00
ctx->bit_rate = bitrate;
ctx->rc_min_rate = bitrate;
2019-12-21 16:41:51 +01:00
}
2020-04-14 00:15:24 +03:00
else if(video_format.crf && config::video.crf != 0) {
handle_option(*video_format.crf);
}
else if(video_format.qp) {
handle_option(*video_format.qp);
2019-12-12 13:13:10 +01:00
}
else {
2020-04-14 00:15:24 +03:00
BOOST_LOG(error) << "Couldn't set video quality: encoder "sv << encoder.name << " doesn't support either crf or qp"sv;
return std::nullopt;
2019-12-12 13:13:10 +01:00
}
if(auto status = avcodec_open2(ctx.get(), codec, &options)) {
char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 };
BOOST_LOG(error)
<< "Could not open codec ["sv
<< video_format.name << "]: "sv
<< av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, status);
return std::nullopt;
}
2020-03-25 10:51:32 +01:00
2021-05-17 21:21:57 +02:00
frame_t frame { av_frame_alloc() };
2020-03-25 10:51:32 +01:00
frame->format = ctx->pix_fmt;
2020-04-15 19:16:20 +02:00
frame->width = ctx->width;
2020-03-25 10:51:32 +01:00
frame->height = ctx->height;
if(hardware) {
2020-04-06 23:15:03 +03:00
frame->hw_frames_ctx = av_buffer_ref(ctx->hw_frames_ctx);
2020-03-25 10:51:32 +01:00
}
2020-04-15 19:16:20 +02:00
util::wrap_ptr<platf::hwdevice_t> device;
if(!hwdevice->data) {
auto device_tmp = std::make_unique<swdevice_t>();
if(device_tmp->init(width, height, frame.get(), sw_fmt)) {
2020-04-15 19:16:20 +02:00
return std::nullopt;
}
device = std::move(device_tmp);
}
else {
device = hwdevice;
}
if(device->set_frame(frame.release())) {
return std::nullopt;
}
2020-04-15 19:16:20 +02:00
device->set_colorspace(sws_color_space, ctx->color_range);
2020-03-25 10:51:32 +01:00
return std::make_optional(session_t {
std::move(ctx),
std::move(device),
});
2020-03-25 10:51:32 +01:00
}
void encode_run(
int &frame_nr, int &key_frame_nr, // Store progress of the frame number
2021-05-17 21:21:57 +02:00
safe::signal_t *shutdown_event, // Signal for shutdown event of the session
2020-03-25 10:51:32 +01:00
packet_queue_t packets,
idr_event_t idr_events,
img_event_t images,
2020-03-25 10:51:32 +01:00
config_t config,
2020-04-15 19:16:20 +02:00
int width, int height,
platf::hwdevice_t *hwdevice,
safe::signal_t &reinit_event,
const encoder_t &encoder,
2020-03-25 10:51:32 +01:00
void *channel_data) {
2020-04-15 19:16:20 +02:00
auto session = make_session(encoder, config, width, height, hwdevice);
2020-03-25 10:51:32 +01:00
if(!session) {
return;
}
2020-04-10 15:39:50 +03:00
auto delay = std::chrono::floor<std::chrono::nanoseconds>(1s) / config.framerate;
auto next_frame = std::chrono::steady_clock::now();
auto frame = session->device->frame;
while(true) {
if(shutdown_event->peek() || reinit_event.peek() || !images->running()) {
2020-02-08 16:26:38 +01:00
break;
}
if(idr_events->peek()) {
frame->pict_type = AV_PICTURE_TYPE_I;
frame->key_frame = 1;
auto event = idr_events->pop();
2020-04-14 00:15:24 +03:00
if(!event) {
return;
}
2021-05-17 21:21:57 +02:00
auto end = event->second;
frame_nr = end;
2020-03-25 10:51:32 +01:00
key_frame_nr = end + config.framerate;
}
2020-03-25 10:51:32 +01:00
else if(frame_nr == key_frame_nr) {
auto frame = session->device->frame;
frame->pict_type = AV_PICTURE_TYPE_I;
frame->key_frame = 1;
}
std::this_thread::sleep_until(next_frame);
next_frame += delay;
// When Moonlight request an IDR frame, send frames even if there is no new captured frame
2020-03-25 10:51:32 +01:00
if(frame_nr > (key_frame_nr + config.framerate) || images->peek()) {
if(auto img = images->pop(delay)) {
2020-04-15 19:16:20 +02:00
session->device->convert(*img);
}
else if(images->running()) {
continue;
}
else {
break;
}
}
2021-05-17 21:21:57 +02:00
if(encode(frame_nr++, session->ctx, frame, packets, channel_data)) {
2020-04-14 00:15:24 +03:00
BOOST_LOG(error) << "Could not encode video packet"sv;
return;
2020-04-10 15:39:50 +03:00
}
frame->pict_type = AV_PICTURE_TYPE_NONE;
frame->key_frame = 0;
2020-04-10 15:39:50 +03:00
}
}
2020-04-15 19:16:20 +02:00
std::optional<sync_session_t> make_synced_session(platf::display_t *disp, const encoder_t &encoder, platf::img_t &img, sync_session_ctx_t &ctx) {
sync_session_t encode_session;
2020-04-10 15:39:50 +03:00
2021-05-17 21:21:57 +02:00
encode_session.ctx = &ctx;
2020-04-12 02:33:17 +03:00
encode_session.next_frame = std::chrono::steady_clock::now();
2020-04-10 15:39:50 +03:00
encode_session.delay = std::chrono::nanoseconds { 1s } / ctx.config.framerate;
2020-04-10 15:39:50 +03:00
2021-05-17 21:21:57 +02:00
auto pix_fmt = ctx.config.dynamicRange == 0 ? map_pix_fmt(encoder.static_pix_fmt) : map_pix_fmt(encoder.dynamic_pix_fmt);
2020-04-15 19:16:20 +02:00
auto hwdevice = disp->make_hwdevice(ctx.config.width, ctx.config.height, pix_fmt);
if(!hwdevice) {
2020-04-12 02:33:17 +03:00
return std::nullopt;
2020-04-10 15:39:50 +03:00
}
2020-04-15 19:16:20 +02:00
auto session = make_session(encoder, ctx.config, img.width, img.height, hwdevice.get());
2020-04-10 15:39:50 +03:00
if(!session) {
2020-04-12 02:33:17 +03:00
return std::nullopt;
2020-04-10 15:39:50 +03:00
}
2021-05-17 21:21:57 +02:00
encode_session.img_tmp = &img;
2020-04-15 19:16:20 +02:00
encode_session.hwdevice = std::move(hwdevice);
2021-05-17 21:21:57 +02:00
encode_session.session = std::move(*session);
2020-04-10 15:39:50 +03:00
2020-04-12 02:33:17 +03:00
return std::move(encode_session);
}
2020-04-10 15:39:50 +03:00
2020-04-15 19:16:20 +02:00
encode_e encode_run_sync(std::vector<std::unique_ptr<sync_session_ctx_t>> &synced_session_ctxs, encode_session_ctx_queue_t &encode_session_ctx_queue) {
2020-04-12 02:33:17 +03:00
const auto &encoder = encoders.front();
std::shared_ptr<platf::display_t> disp;
while(encode_session_ctx_queue.running()) {
reset_display(disp, encoder.dev_type);
if(disp) {
break;
}
std::this_thread::sleep_for(200ms);
}
2020-04-12 02:33:17 +03:00
if(!disp) {
return encode_e::error;
}
2020-04-10 15:39:50 +03:00
2020-05-01 22:54:21 +02:00
auto img = disp->alloc_img();
2020-04-10 15:39:50 +03:00
2020-05-01 22:54:21 +02:00
auto img_tmp = img.get();
2020-04-12 02:33:17 +03:00
if(disp->dummy_img(img_tmp)) {
return encode_e::error;
}
2020-04-10 15:39:50 +03:00
// absolute mouse coordinates require that the dimensions of the screen are known
input::touch_port_event->raise(disp->offset_x, disp->offset_y, disp->width, disp->height);
2020-04-15 19:16:20 +02:00
std::vector<sync_session_t> synced_sessions;
for(auto &ctx : synced_session_ctxs) {
2020-05-01 22:54:21 +02:00
auto synced_session = make_synced_session(disp.get(), encoder, *img, *ctx);
2020-04-15 19:16:20 +02:00
if(!synced_session) {
2020-04-12 02:33:17 +03:00
return encode_e::error;
}
2020-04-15 19:16:20 +02:00
synced_sessions.emplace_back(std::move(*synced_session));
2020-04-12 02:33:17 +03:00
}
2020-04-10 15:39:50 +03:00
auto next_frame = std::chrono::steady_clock::now();
2020-04-12 02:33:17 +03:00
while(encode_session_ctx_queue.running()) {
while(encode_session_ctx_queue.peek()) {
auto encode_session_ctx = encode_session_ctx_queue.pop();
2021-05-17 21:21:57 +02:00
if(!encode_session_ctx) {
2020-04-12 02:33:17 +03:00
return encode_e::ok;
}
2020-04-10 15:39:50 +03:00
2020-04-15 19:16:20 +02:00
synced_session_ctxs.emplace_back(std::make_unique<sync_session_ctx_t>(std::move(*encode_session_ctx)));
2020-04-10 15:39:50 +03:00
2020-05-01 22:54:21 +02:00
auto encode_session = make_synced_session(disp.get(), encoder, *img, *synced_session_ctxs.back());
2020-04-12 02:33:17 +03:00
if(!encode_session) {
return encode_e::error;
}
2020-04-15 19:16:20 +02:00
synced_sessions.emplace_back(std::move(*encode_session));
2020-04-12 02:33:17 +03:00
next_frame = std::chrono::steady_clock::now();
2020-04-10 15:39:50 +03:00
}
2020-04-10 15:39:50 +03:00
auto delay = std::max(0ms, std::chrono::duration_cast<std::chrono::milliseconds>(next_frame - std::chrono::steady_clock::now()));
2020-05-01 22:54:21 +02:00
auto status = disp->snapshot(img.get(), delay, display_cursor);
2021-05-17 21:21:57 +02:00
switch(status) {
case platf::capture_e::reinit:
case platf::capture_e::error:
return status;
case platf::capture_e::timeout:
break;
case platf::capture_e::ok:
img_tmp = img.get();
break;
2020-04-08 02:15:08 +03:00
}
2021-05-17 21:21:57 +02:00
2020-04-12 02:33:17 +03:00
auto now = std::chrono::steady_clock::now();
2021-05-17 21:21:57 +02:00
2020-04-12 02:33:17 +03:00
next_frame = now + 1s;
2020-04-15 19:16:20 +02:00
KITTY_WHILE_LOOP(auto pos = std::begin(synced_sessions), pos != std::end(synced_sessions), {
auto frame = pos->session.device->frame;
auto ctx = pos->ctx;
2020-04-12 02:33:17 +03:00
if(ctx->shutdown_event->peek()) {
// Let waiting thread know it can delete shutdown_event
ctx->join_event->raise(true);
2021-05-17 21:21:57 +02:00
2020-04-15 19:16:20 +02:00
pos = synced_sessions.erase(pos);
2021-05-17 21:21:57 +02:00
synced_session_ctxs.erase(std::find_if(std::begin(synced_session_ctxs), std::end(synced_session_ctxs), [&ctx_p = ctx](auto &ctx) {
2020-04-12 02:33:17 +03:00
return ctx.get() == ctx_p;
}));
2020-04-15 19:16:20 +02:00
if(synced_sessions.empty()) {
2020-04-12 02:33:17 +03:00
return encode_e::ok;
}
continue;
}
if(ctx->idr_events->peek()) {
frame->pict_type = AV_PICTURE_TYPE_I;
frame->key_frame = 1;
2020-04-12 02:33:17 +03:00
auto event = ctx->idr_events->pop();
2021-05-17 21:21:57 +02:00
auto end = event->second;
2020-04-12 02:33:17 +03:00
2021-05-17 21:21:57 +02:00
ctx->frame_nr = end;
2020-04-12 02:33:17 +03:00
ctx->key_frame_nr = end + ctx->config.framerate;
}
else if(ctx->frame_nr == ctx->key_frame_nr) {
frame->pict_type = AV_PICTURE_TYPE_I;
frame->key_frame = 1;
2020-04-12 02:33:17 +03:00
}
if(img_tmp) {
pos->img_tmp = img_tmp;
}
auto timeout = now > pos->next_frame;
if(timeout) {
pos->next_frame += pos->delay;
}
2020-05-01 22:54:21 +02:00
2020-04-12 02:33:17 +03:00
next_frame = std::min(next_frame, pos->next_frame);
if(!timeout) {
++pos;
continue;
}
if(pos->img_tmp) {
2020-04-15 19:16:20 +02:00
if(pos->hwdevice->convert(*pos->img_tmp)) {
BOOST_LOG(error) << "Could not convert image"sv;
ctx->shutdown_event->raise(true);
continue;
}
2020-04-12 02:33:17 +03:00
pos->img_tmp = nullptr;
}
if(encode(ctx->frame_nr++, pos->session.ctx, frame, ctx->packets, ctx->channel_data)) {
2020-04-14 00:15:24 +03:00
BOOST_LOG(error) << "Could not encode video packet"sv;
ctx->shutdown_event->raise(true);
continue;
2020-04-12 02:33:17 +03:00
}
frame->pict_type = AV_PICTURE_TYPE_NONE;
frame->key_frame = 0;
2020-04-12 02:33:17 +03:00
++pos;
2020-04-14 00:15:24 +03:00
})
2020-04-12 02:33:17 +03:00
img_tmp = nullptr;
}
return encode_e::ok;
}
void captureThreadSync() {
auto ref = capture_thread_sync.ref();
2020-04-15 19:16:20 +02:00
std::vector<std::unique_ptr<sync_session_ctx_t>> synced_session_ctxs;
2020-04-10 15:39:50 +03:00
2020-04-12 02:33:17 +03:00
auto &ctx = ref->encode_session_ctx_queue;
2021-05-17 21:21:57 +02:00
auto lg = util::fail_guard([&]() {
2020-04-12 02:33:17 +03:00
ctx.stop();
2020-04-15 19:16:20 +02:00
for(auto &ctx : synced_session_ctxs) {
2020-04-12 02:33:17 +03:00
ctx->shutdown_event->raise(true);
ctx->join_event->raise(true);
2020-04-08 02:15:08 +03:00
}
2020-04-12 02:33:17 +03:00
for(auto &ctx : ctx.unsafe()) {
ctx.shutdown_event->raise(true);
ctx.join_event->raise(true);
}
2020-04-12 02:33:17 +03:00
});
2020-03-25 10:51:32 +01:00
while(encode_run_sync(synced_session_ctxs, ctx) == encode_e::reinit) {}
2020-04-12 02:33:17 +03:00
}
2020-04-10 15:39:50 +03:00
void capture_async(
safe::signal_t *shutdown_event,
2020-04-14 00:15:24 +03:00
packet_queue_t &packets,
idr_event_t &idr_events,
config_t &config,
void *channel_data) {
auto images = std::make_shared<img_event_t::element_type>();
2021-05-17 21:21:57 +02:00
auto lg = util::fail_guard([&]() {
2020-04-06 23:15:03 +03:00
images->stop();
shutdown_event->raise(true);
});
2020-04-15 19:16:20 +02:00
auto ref = capture_thread_async.ref();
if(!ref) {
return;
}
auto delay = std::chrono::floor<std::chrono::nanoseconds>(1s) / config.framerate;
ref->capture_ctx_queue->raise(capture_ctx_t {
2021-05-17 21:21:57 +02:00
images, delay });
if(!ref->capture_ctx_queue->running()) {
return;
}
2021-05-17 21:21:57 +02:00
int frame_nr = 1;
int key_frame_nr = 1;
2020-04-17 18:42:55 +02:00
while(!shutdown_event->peek() && images->running()) {
// Wait for the main capture event when the display is being reinitialized
if(ref->reinit_event.peek()) {
std::this_thread::sleep_for(100ms);
continue;
}
// Wait for the display to be ready
2020-04-08 02:15:08 +03:00
std::shared_ptr<platf::display_t> display;
{
auto lg = ref->display_wp.lock();
if(ref->display_wp->expired()) {
continue;
}
2020-04-08 02:15:08 +03:00
display = ref->display_wp->lock();
}
2020-04-02 20:13:44 +02:00
2021-05-17 21:21:57 +02:00
auto pix_fmt = config.dynamicRange == 0 ? platf::pix_fmt_e::yuv420p : platf::pix_fmt_e::yuv420p10;
2020-04-15 19:16:20 +02:00
auto hwdevice = display->make_hwdevice(config.width, config.height, pix_fmt);
if(!hwdevice) {
2020-04-08 02:15:08 +03:00
return;
}
2020-04-10 15:39:50 +03:00
auto dummy_img = display->alloc_img();
if(display->dummy_img(dummy_img.get())) {
return;
}
2020-04-10 15:39:50 +03:00
images->raise(std::move(dummy_img));
// absolute mouse coordinates require that the dimensions of the screen are known
input::touch_port_event->raise(display->offset_x, display->offset_y, display->width, display->height);
2020-04-15 19:16:20 +02:00
encode_run(
frame_nr, key_frame_nr,
shutdown_event,
packets, idr_events, images,
config, display->width, display->height,
hwdevice.get(),
ref->reinit_event, *ref->encoder_p,
channel_data);
}
}
2020-04-14 00:15:24 +03:00
void capture(
safe::signal_t *shutdown_event,
packet_queue_t packets,
idr_event_t idr_events,
config_t config,
void *channel_data) {
2020-04-17 18:42:55 +02:00
idr_events->raise(std::make_pair(0, 1));
if(encoders.front().flags & SYSTEM_MEMORY) {
2020-04-14 00:15:24 +03:00
capture_async(shutdown_event, packets, idr_events, config, channel_data);
}
else {
safe::signal_t join_event;
auto ref = capture_thread_sync.ref();
2020-04-15 19:16:20 +02:00
ref->encode_session_ctx_queue.raise(sync_session_ctx_t {
2021-05-17 21:21:57 +02:00
shutdown_event, &join_event, packets, idr_events, config, 1, 1, channel_data });
2020-04-14 00:15:24 +03:00
// Wait for join signal
join_event.view();
}
}
bool validate_config(std::shared_ptr<platf::display_t> &disp, const encoder_t &encoder, const config_t &config) {
reset_display(disp, encoder.dev_type);
2020-04-02 20:13:44 +02:00
if(!disp) {
return false;
}
2021-05-17 21:21:57 +02:00
auto pix_fmt = config.dynamicRange == 0 ? map_pix_fmt(encoder.static_pix_fmt) : map_pix_fmt(encoder.dynamic_pix_fmt);
2020-04-15 19:16:20 +02:00
auto hwdevice = disp->make_hwdevice(config.width, config.height, pix_fmt);
if(!hwdevice) {
2020-04-06 23:15:03 +03:00
return false;
}
2020-04-02 20:13:44 +02:00
2020-04-15 19:16:20 +02:00
auto session = make_session(encoder, config, disp->width, disp->height, hwdevice.get());
if(!session) {
return false;
}
2020-04-02 20:13:44 +02:00
auto img = disp->alloc_img();
2020-04-10 15:39:50 +03:00
if(disp->dummy_img(img.get())) {
2020-04-06 23:15:03 +03:00
return false;
}
2020-04-15 19:16:20 +02:00
if(session->device->convert(*img)) {
return false;
}
auto frame = session->device->frame;
frame->pict_type = AV_PICTURE_TYPE_I;
auto packets = std::make_shared<packet_queue_t::element_type>(30);
if(encode(1, session->ctx, frame, packets, nullptr)) {
return false;
}
return true;
}
bool validate_encoder(encoder_t &encoder) {
std::shared_ptr<platf::display_t> disp;
2020-04-07 14:54:56 +03:00
BOOST_LOG(info) << "Trying encoder ["sv << encoder.name << ']';
auto fg = util::fail_guard([&]() {
BOOST_LOG(info) << "Encoder ["sv << encoder.name << "] failed"sv;
});
2020-04-14 00:15:24 +03:00
auto force_hevc = config::video.hevc_mode >= 2;
auto test_hevc = force_hevc || (config::video.hevc_mode == 0 && !(encoder.flags & H264_ONLY));
2020-04-14 00:15:24 +03:00
2020-04-07 14:54:56 +03:00
encoder.h264.capabilities.set();
encoder.hevc.capabilities.set();
encoder.hevc[encoder_t::PASSED] = test_hevc;
// First, test encoder viability
2020-04-14 00:15:24 +03:00
config_t config_max_ref_frames { 1920, 1080, 60, 1000, 1, 1, 1, 0, 0 };
2021-05-17 21:21:57 +02:00
config_t config_autoselect { 1920, 1080, 60, 1000, 1, 0, 1, 0, 0 };
auto max_ref_frames_h264 = validate_config(disp, encoder, config_max_ref_frames);
auto autoselect_h264 = validate_config(disp, encoder, config_autoselect);
if(!max_ref_frames_h264 && !autoselect_h264) {
return false;
}
2021-05-17 21:21:57 +02:00
encoder.h264[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_h264;
encoder.h264[encoder_t::REF_FRAMES_AUTOSELECT] = autoselect_h264;
2021-05-17 21:21:57 +02:00
encoder.h264[encoder_t::PASSED] = true;
encoder.h264[encoder_t::SLICE] = validate_config(disp, encoder, config_max_ref_frames);
2020-04-14 00:15:24 +03:00
if(test_hevc) {
config_max_ref_frames.videoFormat = 1;
2021-05-17 21:21:57 +02:00
config_autoselect.videoFormat = 1;
2020-04-14 00:15:24 +03:00
auto max_ref_frames_hevc = validate_config(disp, encoder, config_max_ref_frames);
auto autoselect_hevc = validate_config(disp, encoder, config_autoselect);
// If HEVC must be supported, but it is not supported
if(force_hevc && !max_ref_frames_hevc && !autoselect_hevc) {
return false;
}
2021-05-17 21:21:57 +02:00
encoder.hevc[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_hevc;
2020-04-14 00:15:24 +03:00
encoder.hevc[encoder_t::REF_FRAMES_AUTOSELECT] = autoselect_hevc;
encoder.hevc[encoder_t::PASSED] = max_ref_frames_hevc || autoselect_hevc;
2020-04-14 00:15:24 +03:00
}
std::vector<std::pair<encoder_t::flag_e, config_t>> configs {
{ encoder_t::DYNAMIC_RANGE, { 1920, 1080, 60, 1000, 1, 0, 3, 1, 1 } },
{ encoder_t::SLICE, { 1920, 1080, 60, 1000, 2, 1, 1, 0, 0 } },
2020-04-14 00:15:24 +03:00
};
for(auto &[flag, config] : configs) {
auto h264 = config;
auto hevc = config;
h264.videoFormat = 0;
hevc.videoFormat = 1;
2020-04-07 18:57:59 +03:00
encoder.h264[flag] = validate_config(disp, encoder, h264);
if(encoder.hevc[encoder_t::PASSED]) {
2020-04-14 00:15:24 +03:00
encoder.hevc[flag] = validate_config(disp, encoder, hevc);
}
}
2020-04-14 00:15:24 +03:00
fg.disable();
return true;
}
2020-04-14 00:15:24 +03:00
int init() {
// video depends on input for input::touch_port_event
input::init();
BOOST_LOG(info) << "//////////////////////////////////////////////////////////////////"sv;
BOOST_LOG(info) << "// //"sv;
BOOST_LOG(info) << "// Testing for available encoders, this may generate errors. //"sv;
BOOST_LOG(info) << "// You can safely ignore those errors. //"sv;
BOOST_LOG(info) << "// //"sv;
BOOST_LOG(info) << "//////////////////////////////////////////////////////////////////"sv;
KITTY_WHILE_LOOP(auto pos = std::begin(encoders), pos != std::end(encoders), {
2020-04-14 00:15:24 +03:00
if(
2021-05-17 21:21:57 +02:00
(!config::video.encoder.empty() && pos->name != config::video.encoder) ||
!validate_encoder(*pos) ||
(config::video.hevc_mode == 3 && !pos->hevc[encoder_t::DYNAMIC_RANGE])) {
pos = encoders.erase(pos);
continue;
}
2020-04-14 00:15:24 +03:00
break;
})
BOOST_LOG(info);
BOOST_LOG(info) << "//////////////////////////////////////////////////////////////"sv;
BOOST_LOG(info) << "// //"sv;
BOOST_LOG(info) << "// Ignore any errors mentioned above, they are not relevant //"sv;
BOOST_LOG(info) << "// //"sv;
BOOST_LOG(info) << "//////////////////////////////////////////////////////////////"sv;
BOOST_LOG(info);
2020-04-14 00:15:24 +03:00
if(encoders.empty()) {
2021-05-17 21:21:57 +02:00
if(config::video.encoder.empty()) {
2020-04-14 00:15:24 +03:00
BOOST_LOG(fatal) << "Couldn't find any encoder"sv;
}
else {
BOOST_LOG(fatal) << "Couldn't find any encoder matching ["sv << config::video.encoder << ']';
}
return -1;
}
auto &encoder = encoders.front();
BOOST_LOG(debug) << "------ h264 ------"sv;
for(int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
auto flag = (encoder_t::flag_e)x;
BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.h264[flag] ? ": supported"sv : ": unsupported"sv);
}
BOOST_LOG(debug) << "-------------------"sv;
2020-04-14 00:15:24 +03:00
if(encoder.hevc[encoder_t::PASSED]) {
BOOST_LOG(debug) << "------ hevc ------"sv;
for(int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
auto flag = (encoder_t::flag_e)x;
BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.hevc[flag] ? ": supported"sv : ": unsupported"sv);
}
BOOST_LOG(debug) << "-------------------"sv;
2020-04-14 00:15:24 +03:00
BOOST_LOG(info) << "Found encoder "sv << encoder.name << ": ["sv << encoder.h264.name << ", "sv << encoder.hevc.name << ']';
}
else {
2021-05-17 21:21:57 +02:00
BOOST_LOG(info) << "Found encoder "sv << encoder.name << ": ["sv << encoder.h264.name << ']';
}
2020-04-14 00:15:24 +03:00
if(config::video.hevc_mode == 0) {
config::video.hevc_mode = encoder.hevc[encoder_t::PASSED] ? (encoder.hevc[encoder_t::DYNAMIC_RANGE] ? 3 : 2) : 1;
}
return 0;
}
2020-04-15 19:16:20 +02:00
int hwframe_ctx(ctx_t &ctx, buffer_t &hwdevice, AVPixelFormat format) {
2021-05-17 21:21:57 +02:00
buffer_t frame_ref { av_hwframe_ctx_alloc(hwdevice.get()) };
2020-04-15 19:16:20 +02:00
2021-05-17 21:21:57 +02:00
auto frame_ctx = (AVHWFramesContext *)frame_ref->data;
frame_ctx->format = ctx->pix_fmt;
frame_ctx->sw_format = format;
frame_ctx->height = ctx->height;
frame_ctx->width = ctx->width;
frame_ctx->initial_pool_size = 0;
2020-04-15 19:16:20 +02:00
if(auto err = av_hwframe_ctx_init(frame_ref.get()); err < 0) {
return err;
}
ctx->hw_frames_ctx = av_buffer_ref(frame_ref.get());
return 0;
}
// Linux only declaration
typedef int (*vaapi_make_hwdevice_ctx_fn)(platf::hwdevice_t *base, AVBufferRef **hw_device_buf);
util::Either<buffer_t, int> vaapi_make_hwdevice_ctx(platf::hwdevice_t *base) {
buffer_t hw_device_buf;
// If an egl hwdevice
if(base->data) {
if(((vaapi_make_hwdevice_ctx_fn)base->data)(base, &hw_device_buf)) {
return -1;
}
return hw_device_buf;
}
auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VAAPI, "/dev/dri/renderD129", nullptr, 0);
if(status < 0) {
char string[AV_ERROR_MAX_STRING_SIZE];
BOOST_LOG(error) << "Failed to create a VAAPI device: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status);
return -1;
}
return hw_device_buf;
}
2020-04-15 19:16:20 +02:00
#ifdef _WIN32
2021-05-05 11:28:57 +02:00
}
// Ugly, but need to declare for wio
namespace platf::dxgi {
void lock(void *hwdevice);
void unlock(void *hwdevice);
2021-05-17 21:21:57 +02:00
} // namespace platf::dxgi
void do_nothing(void *) {}
2021-05-05 11:28:57 +02:00
namespace video {
void dxgi_img_to_frame(const platf::img_t &img, frame_t &frame) {
2020-04-15 19:16:20 +02:00
if(img.data == frame->data[0]) {
return;
}
2021-05-17 21:21:57 +02:00
2020-04-06 23:15:03 +03:00
// Need to have something refcounted
if(!frame->buf[0]) {
2020-04-08 02:15:08 +03:00
frame->buf[0] = av_buffer_allocz(sizeof(AVD3D11FrameDescriptor));
2020-04-06 23:15:03 +03:00
}
2021-05-17 21:21:57 +02:00
auto desc = (AVD3D11FrameDescriptor *)frame->buf[0]->data;
desc->texture = (ID3D11Texture2D *)img.data;
desc->index = 0;
2020-04-06 23:15:03 +03:00
frame->data[0] = img.data;
frame->data[1] = 0;
frame->linesize[0] = img.row_pitch;
frame->height = img.height;
2021-05-17 21:21:57 +02:00
frame->width = img.width;
}
2020-04-06 23:15:03 +03:00
util::Either<buffer_t, int> dxgi_make_hwdevice_ctx(platf::hwdevice_t *hwdevice_ctx) {
2020-04-06 23:15:03 +03:00
buffer_t ctx_buf { av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_D3D11VA) };
2021-05-17 21:21:57 +02:00
auto ctx = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)ctx_buf->data)->hwctx;
std::fill_n((std::uint8_t *)ctx, sizeof(AVD3D11VADeviceContext), 0);
2020-04-17 12:28:23 +02:00
2021-05-17 21:21:57 +02:00
auto device = (ID3D11Device *)hwdevice_ctx->data;
2021-05-05 11:28:57 +02:00
2020-04-17 12:28:23 +02:00
device->AddRef();
ctx->device = device;
2020-04-06 23:15:03 +03:00
2021-05-17 21:21:57 +02:00
ctx->lock_ctx = (void *)1;
ctx->lock = do_nothing;
ctx->unlock = do_nothing;
2021-05-05 11:28:57 +02:00
2020-04-06 23:15:03 +03:00
auto err = av_hwdevice_ctx_init(ctx_buf.get());
if(err) {
2021-05-17 21:21:57 +02:00
char err_str[AV_ERROR_MAX_STRING_SIZE] { 0 };
2021-05-05 11:28:57 +02:00
BOOST_LOG(error) << "Failed to create FFMpeg hardware device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err);
2020-04-06 23:15:03 +03:00
return err;
}
return ctx_buf;
}
2020-04-15 19:16:20 +02:00
#endif
int start_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) {
capture_thread_ctx.encoder_p = &encoders.front();
capture_thread_ctx.reinit_event.reset();
capture_thread_ctx.capture_ctx_queue = std::make_shared<safe::queue_t<capture_ctx_t>>(30);
2020-04-15 19:16:20 +02:00
capture_thread_ctx.capture_thread = std::thread {
captureThread,
capture_thread_ctx.capture_ctx_queue,
std::ref(capture_thread_ctx.display_wp),
std::ref(capture_thread_ctx.reinit_event),
std::ref(*capture_thread_ctx.encoder_p)
};
return 0;
}
void end_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) {
capture_thread_ctx.capture_ctx_queue->stop();
capture_thread_ctx.capture_thread.join();
}
int start_capture_sync(capture_thread_sync_ctx_t &ctx) {
std::thread { &captureThreadSync }.detach();
return 0;
}
void end_capture_sync(capture_thread_sync_ctx_t &ctx) {}
platf::mem_type_e map_dev_type(AVHWDeviceType type) {
2020-04-15 19:16:20 +02:00
switch(type) {
2021-05-17 21:21:57 +02:00
case AV_HWDEVICE_TYPE_D3D11VA:
return platf::mem_type_e::dxgi;
case AV_HWDEVICE_TYPE_VAAPI:
return platf::mem_type_e::vaapi;
case AV_PICTURE_TYPE_NONE:
return platf::mem_type_e::system;
2021-05-17 21:21:57 +02:00
default:
return platf::mem_type_e::unknown;
2020-04-15 19:16:20 +02:00
}
return platf::mem_type_e::unknown;
2020-04-15 19:16:20 +02:00
}
platf::pix_fmt_e map_pix_fmt(AVPixelFormat fmt) {
switch(fmt) {
2021-05-17 21:21:57 +02:00
case AV_PIX_FMT_YUV420P10:
return platf::pix_fmt_e::yuv420p10;
case AV_PIX_FMT_YUV420P:
return platf::pix_fmt_e::yuv420p;
case AV_PIX_FMT_NV12:
return platf::pix_fmt_e::nv12;
case AV_PIX_FMT_P010:
return platf::pix_fmt_e::p010;
default:
return platf::pix_fmt_e::unknown;
2020-04-15 19:16:20 +02:00
}
return platf::pix_fmt_e::unknown;
}
color_t make_color_matrix(float Cr, float Cb, float U_max, float V_max, float add_Y, float add_UV, const float2 &range_Y, const float2 &range_UV) {
float Cg = 1.0f - Cr - Cb;
float Cr_i = 1.0f - Cr;
float Cb_i = 1.0f - Cb;
float shift_y = range_Y[0] / 256.0f;
float shift_uv = range_UV[0] / 256.0f;
float scale_y = (range_Y[1] - range_Y[0]) / 256.0f;
float scale_uv = (range_UV[1] - range_UV[0]) / 256.0f;
return {
{ Cr, Cg, Cb, add_Y },
{ -(Cr * U_max / Cb_i), -(Cg * U_max / Cb_i), U_max, add_UV },
{ V_max, -(Cg * V_max / Cr_i), -(Cb * V_max / Cr_i), add_UV },
{ scale_y, shift_y },
{ scale_uv, shift_uv },
};
}
color_t colors[] {
make_color_matrix(0.299f, 0.114f, 0.436f, 0.615f, 0.0625, 0.5f, { 16.0f, 235.0f }, { 16.0f, 240.0f }), // BT601 MPEG
make_color_matrix(0.299f, 0.114f, 0.5f, 0.5f, 0.0f, 0.5f, { 0.0f, 255.0f }, { 0.0f, 255.0f }), // BT601 JPEG
make_color_matrix(0.2126f, 0.0722f, 0.436f, 0.615f, 0.0625, 0.5f, { 16.0f, 235.0f }, { 16.0f, 240.0f }), // BT701 MPEG
make_color_matrix(0.2126f, 0.0722f, 0.5f, 0.5f, 0.0f, 0.5f, { 0.0f, 255.0f }, { 0.0f, 255.0f }), // BT701 JPEG
};
}