13#include <boost/pointer_cast.hpp>
16#include <libavutil/imgutils.h>
17#include <libavutil/mastering_display_metadata.h>
18#include <libavutil/opt.h>
19#include <libavutil/pixdesc.h>
39 #include <vulkan/vulkan.h>
48using namespace std::literals;
66 void free_ctx(AVCodecContext *ctx) {
67 avcodec_free_context(&ctx);
70 void free_frame(AVFrame *frame) {
71 av_frame_free(&frame);
74 void free_buffer(AVBufferRef *ref) {
75 av_buffer_unref(&ref);
100 bool requires_padding = (sw_frame->width != sws_output_frame->width || sw_frame->height != sws_output_frame->height);
103 sws_input_frame->data[0] = img.data;
104 sws_input_frame->linesize[0] = img.row_pitch;
107 auto status = sws_scale_frame(sws.get(), requires_padding ? sws_output_frame.get() : sw_frame.get(), sws_input_frame.get());
109 char string[AV_ERROR_MAX_STRING_SIZE];
110 BOOST_LOG(error) <<
"Couldn't scale frame: "sv << av_make_error_string(
string, AV_ERROR_MAX_STRING_SIZE, status);
115 if (requires_padding) {
116 auto fmt_desc = av_pix_fmt_desc_get((AVPixelFormat) sws_output_frame->format);
117 auto planes = av_pix_fmt_count_planes((AVPixelFormat) sws_output_frame->format);
118 for (
int plane = 0; plane < planes; plane++) {
119 auto shift_h = plane == 0 ? 0 : fmt_desc->log2_chroma_h;
120 auto shift_w = plane == 0 ? 0 : fmt_desc->log2_chroma_w;
121 auto offset = ((offsetW >> shift_w) * fmt_desc->comp[plane].step) + (offsetH >> shift_h) * sw_frame->linesize[plane];
124 for (
int line = 0; line < sws_output_frame->height >> shift_h; line++) {
125 memcpy(sw_frame->data[plane] + offset + (line * sw_frame->linesize[plane]), sws_output_frame->data[plane] + (line * sws_output_frame->linesize[plane]), (
size_t) (sws_output_frame->width >> shift_w) * fmt_desc->comp[plane].step);
132 if (frame->hw_frames_ctx) {
133 auto status = av_hwframe_transfer_data(frame, sw_frame.get(), 0);
135 char string[AV_ERROR_MAX_STRING_SIZE];
136 BOOST_LOG(error) <<
"Failed to transfer image data to hardware frame: "sv << av_make_error_string(
string, AV_ERROR_MAX_STRING_SIZE, status);
144 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx)
override {
149 hw_frame.reset(frame);
151 if (av_hwframe_get_buffer(hw_frames_ctx, frame, 0)) {
155 sw_frame.reset(frame);
161 void apply_colorspace()
override {
162 auto avcodec_colorspace = avcodec_colorspace_from_sunshine_colorspace(colorspace);
163 sws_setColorspaceDetails(sws.get(), sws_getCoefficients(SWS_CS_DEFAULT), 0, sws_getCoefficients(avcodec_colorspace.software_format), avcodec_colorspace.range - 1, 0, 1 << 16, 1 << 16);
170 auto frame = sw_frame ? sw_frame.get() : this->frame;
171 av_frame_get_buffer(frame, 0);
172 av_frame_make_writable(frame);
173 ptrdiff_t linesize[4] = {frame->linesize[0], frame->linesize[1], frame->linesize[2], frame->linesize[3]};
174 av_image_fill_black(frame->data, linesize, (AVPixelFormat) frame->format, frame->color_range, frame->width, frame->height);
177 int init(
int in_width,
int in_height, AVFrame *frame, AVPixelFormat format,
bool hardware) {
180 sw_frame.reset(av_frame_alloc());
182 sw_frame->width = frame->width;
183 sw_frame->height = frame->height;
184 sw_frame->format = format;
192 auto out_width = frame->width;
193 auto out_height = frame->height;
196 auto scalar = std::fminf((
float) out_width / in_width, (
float) out_height / in_height);
197 out_width = in_width * scalar;
198 out_height = in_height * scalar;
200 sws_input_frame.reset(av_frame_alloc());
201 sws_input_frame->width = in_width;
202 sws_input_frame->height = in_height;
203 sws_input_frame->format = AV_PIX_FMT_BGR0;
205 sws_output_frame.reset(av_frame_alloc());
206 sws_output_frame->width = out_width;
207 sws_output_frame->height = out_height;
208 sws_output_frame->format = format;
211 offsetW = (frame->width - out_width) / 2;
212 offsetH = (frame->height - out_height) / 2;
214 sws.reset(sws_alloc_context());
219 AVDictionary *options {
nullptr};
220 av_dict_set_int(&options,
"srcw", sws_input_frame->width, 0);
221 av_dict_set_int(&options,
"srch", sws_input_frame->height, 0);
222 av_dict_set_int(&options,
"src_format", sws_input_frame->format, 0);
223 av_dict_set_int(&options,
"dstw", sws_output_frame->width, 0);
224 av_dict_set_int(&options,
"dsth", sws_output_frame->height, 0);
225 av_dict_set_int(&options,
"dst_format", sws_output_frame->format, 0);
226 av_dict_set_int(&options,
"sws_flags", SWS_LANCZOS | SWS_ACCURATE_RND, 0);
227 av_dict_set_int(&options,
"threads", config::video.min_threads, 0);
229 auto status = av_opt_set_dict(sws.get(), &options);
230 av_dict_free(&options);
232 char string[AV_ERROR_MAX_STRING_SIZE];
233 BOOST_LOG(error) <<
"Failed to set SWS options: "sv << av_make_error_string(
string, AV_ERROR_MAX_STRING_SIZE, status);
237 status = sws_init_context(sws.get(),
nullptr,
nullptr);
239 char string[AV_ERROR_MAX_STRING_SIZE];
240 BOOST_LOG(error) <<
"Failed to initialize SWS: "sv << av_make_error_string(
string, AV_ERROR_MAX_STRING_SIZE, status);
248 avcodec_frame_t hw_frame;
250 avcodec_frame_t sw_frame;
251 avcodec_frame_t sws_input_frame;
252 avcodec_frame_t sws_output_frame;
277 bool pyrowave_succeeded(pyrowave_result result, std::string_view operation) {
278 if (result == PYROWAVE_SUCCESS) {
282 BOOST_LOG(error) <<
"PyroWave "sv << operation <<
" failed with status "sv << static_cast<int>(result);
292 struct pyrowave_gpu_source_t {
293 pyrowave::gpu_encode_device_t *device {};
295 explicit operator bool()
const {
296 return device !=
nullptr;
302 pyrowave_encode_session_t(
303 std::unique_ptr<platf::avcodec_encode_device_t> encode_device,
304 pyrowave_gpu_source_t gpu,
305 pyrowave_device pyrowave_device_handle,
307 pyrowave_encoder pyrowave_encoder_handle,
308 size_t maximum_frame_bytes
310 device {std::move(encode_device)},
312 pyrowave_device_handle {pyrowave_device_handle},
313 owns_device {owns_device},
314 pyrowave_encoder_handle {pyrowave_encoder_handle},
315 maximum_frame_bytes {maximum_frame_bytes},
316 bitstream(maximum_frame_bytes) {
319 ~pyrowave_encode_session_t()
override {
322 if (pyrowave_encoder_handle) {
323 pyrowave_encoder_destroy(pyrowave_encoder_handle);
325 if (owns_device && pyrowave_device_handle) {
326 pyrowave_device_destroy(pyrowave_device_handle);
330 int convert(platf::img_t &img)
override {
331 return device ? device->convert(img) : -1;
334 void request_idr_frame()
override {
338 void request_normal_frame()
override {
341 void invalidate_ref_frames(int64_t, int64_t)
override {
344 std::unique_ptr<platf::avcodec_encode_device_t> device;
345 pyrowave_gpu_source_t gpu;
346 pyrowave_device pyrowave_device_handle {};
348 pyrowave_encoder pyrowave_encoder_handle {};
349 size_t maximum_frame_bytes {};
351 std::vector<uint8_t> bitstream;
357 const int fps = std::max(1, config.framerate > 1000 ? config.framerate / 1000 : config.framerate);
358 const std::size_t bitrate_frame_bytes =
static_cast<std::size_t
>(std::max(1, config.bitrate)) * 1000u / 8u /
static_cast<std::size_t
>(fps);
359 const std::size_t raw_frame_bytes =
static_cast<std::size_t
>(std::max(0, config.width)) *
static_cast<std::size_t
>(std::max(0, config.height)) * 3u / 2u;
360 return std::min(raw_frame_bytes, std::max<std::size_t>(16u * 1024u, bitrate_frame_bytes));
363 bool pyrowave_available() {
365 static std::once_flag probe_once;
366 static bool available =
false;
367 std::call_once(probe_once, []() {
371 pyrowave_get_api_version(&major, &minor, &patch);
375 const bool compatible = major == PYROWAVE_API_VERSION_MAJOR &&
376 (major == 0 ? minor == PYROWAVE_API_VERSION_MINOR : minor >= PYROWAVE_API_VERSION_MINOR);
378 BOOST_LOG(error) <<
"Incompatible PyroWave API "sv
379 << major <<
'.' << minor <<
'.' << patch
380 <<
" (need "sv << PYROWAVE_API_VERSION_MAJOR <<
'.'
381 << PYROWAVE_API_VERSION_MINOR <<
".x)"sv;
385 pyrowave_device device {};
386 if (!pyrowave_succeeded(pyrowave_create_default_device(&device),
"Vulkan device probe"sv)) {
389 auto cleanup_device = util::fail_guard([device]() {
390 pyrowave_device_destroy(device);
394 pyrowave_encoder_create_info probe_info {};
395 probe_info.device = device;
396 probe_info.width = 64;
397 probe_info.height = 64;
398 probe_info.chroma = PYROWAVE_CHROMA_SUBSAMPLING_420;
399 pyrowave_encoder encoder {};
400 if (!pyrowave_succeeded(pyrowave_encoder_create(&probe_info, &encoder),
"Vulkan encoder probe"sv)) {
403 pyrowave_encoder_destroy(encoder);
414 avcodec_encode_session_t() =
default;
416 avcodec_encode_session_t(avcodec_ctx_t &&avcodec_ctx, std::unique_ptr<platf::avcodec_encode_device_t> encode_device,
int inject):
417 avcodec_ctx {std::move(avcodec_ctx)},
418 device {std::move(encode_device)},
422 avcodec_encode_session_t(avcodec_encode_session_t &&other)
noexcept =
default;
424 ~avcodec_encode_session_t() {
428 if (frame_submitted && avcodec_ctx &&
429 avcodec_send_frame(avcodec_ctx.get(),
nullptr) == 0) {
431 while (avcodec_receive_packet(avcodec_ctx.get(), pkt.av_packet) == 0);
440 avcodec_encode_session_t &operator=(avcodec_encode_session_t &&other) {
441 device = std::move(other.device);
442 avcodec_ctx = std::move(other.avcodec_ctx);
443 replacements = std::move(other.replacements);
444 sps = std::move(other.sps);
445 vps = std::move(other.vps);
447 inject = other.inject;
448 frame_submitted = other.frame_submitted;
449 other.frame_submitted =
false;
461 return device->convert(img);
464 void request_idr_frame()
override {
465 if (device && device->frame) {
466 auto &frame = device->frame;
467 frame->pict_type = AV_PICTURE_TYPE_I;
468 frame->flags |= AV_FRAME_FLAG_KEY;
472 void request_normal_frame()
override {
473 if (device && device->frame) {
474 auto &frame = device->frame;
475 frame->pict_type = AV_PICTURE_TYPE_NONE;
476 frame->flags &= ~AV_FRAME_FLAG_KEY;
480 void invalidate_ref_frames(int64_t first_frame, int64_t last_frame)
override {
482 BOOST_LOG(error) <<
"Encoder doesn't support reference frame invalidation";
502 BOOST_LOG(info) <<
"Frames "sv << first_frame <<
'-' << last_frame
506 avcodec_ctx_t avcodec_ctx;
507 std::unique_ptr<platf::avcodec_encode_device_t> device;
509 std::vector<packet_raw_t::replace_t> replacements;
516 bool frame_submitted {
false};
529 nvenc_encode_session_t(std::unique_ptr<platf::nvenc_encode_device_t> encode_device):
530 device(std::move(encode_device)) {
537 return device->convert(img);
540 void request_idr_frame()
override {
544 void request_normal_frame()
override {
548 void invalidate_ref_frames(int64_t first_frame, int64_t last_frame)
override {
549 if (!device || !device->nvenc) {
553 if (!device->nvenc->invalidate_ref_frames(first_frame, last_frame)) {
559 if (!device || !device->nvenc) {
563 auto result = device->nvenc->encode_frame(frame_index, force_idr);
569 std::unique_ptr<platf::nvenc_encode_device_t> device;
570 bool force_idr =
false;
574 safe::signal_t *join_event;
575 safe::mail_raw_t::event_t<bool> shutdown_event;
576 safe::mail_raw_t::queue_t<packet_t> packets;
577 safe::mail_raw_t::event_t<bool> idr_events;
578 safe::mail_raw_t::event_t<hdr_info_t> hdr_events;
579 safe::mail_raw_t::event_t<input::touch_port_t> touch_port_events;
588 std::unique_ptr<encode_session_t> session;
600 std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue;
601 std::thread capture_thread;
603 safe::signal_t reinit_event;
609 encode_session_ctx_queue_t encode_session_ctx_queue {30};
619 auto capture_thread_async = safe::make_shared<capture_thread_async_ctx_t>(start_capture_async, end_capture_async);
620 auto capture_thread_sync = safe::make_shared<capture_thread_sync_ctx_t>(start_capture_sync, end_capture_sync);
624 std::make_unique<encoder_platform_formats_avcodec>(
625 AV_HWDEVICE_TYPE_CUDA,
626 AV_HWDEVICE_TYPE_NONE,
632 cuda_init_avcodec_hardware_input_buffer
641 {
"cbr_padding"s,
false},
642 {
"preset"s, &config::video.nv_legacy.preset},
643 {
"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY},
644 {
"rc"s, NV_ENC_PARAMS_RC_CBR},
645 {
"multipass"s, &config::video.nv_legacy.multipass},
646 {
"aq"s, &config::video.nv_legacy.aq},
662 {
"cbr_padding"s,
false},
663 {
"preset"s, &config::video.nv_legacy.preset},
664 {
"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY},
665 {
"rc"s, NV_ENC_PARAMS_RC_CBR},
666 {
"multipass"s, &config::video.nv_legacy.multipass},
667 {
"aq"s, &config::video.nv_legacy.aq},
688 {
"cbr_padding"s,
false},
689 {
"preset"s, &config::video.nv_legacy.preset},
690 {
"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY},
691 {
"rc"s, NV_ENC_PARAMS_RC_CBR},
692 {
"coder"s, &config::video.nv_legacy.h264_coder},
693 {
"multipass"s, &config::video.nv_legacy.multipass},
694 {
"aq"s, &config::video.nv_legacy.aq},
712 std::make_unique<encoder_platform_formats_avcodec>(
713 AV_HWDEVICE_TYPE_NONE,
714 AV_HWDEVICE_TYPE_NONE,
717 AV_PIX_FMT_YUV420P10,
719 AV_PIX_FMT_YUV444P10,
728 {
"svtav1-params"s,
"keyint=-1:pred-struct=1:force-key-frames=1:mbr=0"s},
729 {
"preset"s, &config::video.sw.svtav1_preset},
737#ifdef ENABLE_BROKEN_AV1_ENCODER
753 {
"x265-params"s,
"info=0:keyint=-1"s},
754 {
"preset"s, &config::video.sw.sw_preset},
755 {
"tune"s, &config::video.sw.sw_tune},
767 {
"preset"s, &config::video.sw.sw_preset},
768 {
"tune"s, &config::video.sw.sw_tune},
782 std::make_unique<encoder_platform_formats_avcodec>(
783 AV_HWDEVICE_TYPE_VAAPI,
784 AV_HWDEVICE_TYPE_NONE,
790 vaapi_init_avcodec_hardware_input_buffer
796 {
"idr_interval"s, std::numeric_limits<int>::max()},
810 {
"idr_interval"s, std::numeric_limits<int>::max()},
824 {
"idr_interval"s, std::numeric_limits<int>::max()},
837 static const std::vector<encoder_t *> encoders {
844 int active_hevc_mode;
849 static std::mutex encoder_status_mutex;
853 std::lock_guard lg {encoder_status_mutex};
854 return encoder_status_state;
859 static std::mutex pipeline_metrics_mutex;
861 double encode_ms_sum = 0.0;
862 double capture_to_encode_ms_sum = 0.0;
866 uint64_t frames_dropped = 0;
869 std::chrono::steady_clock::time_point window_start = std::chrono::steady_clock::now();
875 std::lock_guard lg {pipeline_metrics_mutex};
876 auto &s = pipeline_metrics_state;
877 s.encode_ms_sum += encode_ms;
878 s.capture_to_encode_ms_sum += capture_to_encode_ms;
879 s.window_bytes += packet_bytes;
884 const auto now = std::chrono::steady_clock::now();
885 const auto elapsed = std::chrono::duration<double>(now - s.window_start).count();
886 if (elapsed >= 1.0 && s.window_frames > 0) {
887 s.published.valid =
true;
888 s.published.encode_ms = s.encode_ms_sum / s.window_frames;
889 s.published.capture_to_encode_ms = s.capture_to_encode_ms_sum / s.window_frames;
890 s.published.fps = s.window_frames / elapsed;
891 s.published.bitrate_kbps = (s.window_bytes * 8.0 / 1000.0) / elapsed;
892 s.published.frames_encoded = s.frames_encoded;
893 s.published.frames_dropped = s.frames_dropped;
894 s.published.width = s.width;
895 s.published.height = s.height;
896 s.encode_ms_sum = 0.0;
897 s.capture_to_encode_ms_sum = 0.0;
900 s.window_start = now;
905 std::lock_guard lg {pipeline_metrics_mutex};
906 pipeline_metrics_state.frames_dropped++;
907 pipeline_metrics_state.published.frames_dropped = pipeline_metrics_state.frames_dropped;
911 std::lock_guard lg {pipeline_metrics_mutex};
916 std::lock_guard lg {pipeline_metrics_mutex};
917 auto &s = pipeline_metrics_state;
922 s.published.width = width;
923 s.published.height = height;
927 std::lock_guard lg {pipeline_metrics_mutex};
928 return pipeline_metrics_state.published;
932 bool vaapi_intra_refresh_requested() {
933 return config::video.vaapi.intra_refresh;
937 bool probe_saw_intra_refresh =
false;
940 bool last_encoder_probe_supported_ref_frames_invalidation =
false;
941 std::array<bool, 3> last_encoder_probe_supported_yuv444_for_codec = {
948 bool probe_without_display =
false;
950 void reset_display(std::shared_ptr<platf::display_t> &disp,
const platf::mem_type_e &type,
const std::string &display_name,
const config_t &config) {
951 if (probe_without_display && config.encoder_probe) {
956 for (
int x = 0; x < 2; ++x) {
964 std::this_thread::sleep_for(200ms);
978 std::string current_display_name = preferred_display_name;
981 if (current_display_name.empty() && current_display_index >= 0 && current_display_index < display_names.size()) {
982 current_display_name = display_names.at(current_display_index);
986 auto old_display_names = std::move(display_names);
987 display_names = platf::display_names(dev_type);
990 if (display_names.empty() && !old_display_names.empty()) {
991 BOOST_LOG(error) <<
"No displays were found after reenumeration!"sv;
992 display_names = std::move(old_display_names);
994 }
else if (display_names.empty()) {
995 display_names.emplace_back(output_name);
999 current_display_index = 0;
1001 if (current_display_name.empty()) {
1006 if (!current_display_name.empty()) {
1007 for (
int x = 0; x < display_names.size(); ++x) {
1008 if (display_names[x] == current_display_name) {
1009 current_display_index = x;
1015 BOOST_LOG(warning) <<
"Previous active display ["sv << current_display_name <<
"] is no longer present"sv;
1017 for (
int x = 0; x < display_names.size(); ++x) {
1018 if (display_names[x] == output_name) {
1019 current_display_index = x;
1026 void refresh_displays(
platf::mem_type_e dev_type, std::vector<std::string> &display_names,
int ¤t_display_index) {
1027 static std::string empty_str =
"";
1028 refresh_displays(dev_type, display_names, current_display_index, empty_str);
1032 std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue,
1033 sync_util::sync_t<std::weak_ptr<platf::display_t>> &display_wp,
1034 safe::signal_t &reinit_event,
1037 std::vector<capture_ctx_t> capture_ctxs;
1039 auto fg = util::fail_guard([&]() {
1040 capture_ctx_queue->stop();
1043 for (
auto &capture_ctx : capture_ctxs) {
1044 capture_ctx.images->stop();
1046 for (
auto &capture_ctx : capture_ctx_queue->unsafe()) {
1047 capture_ctx.images->stop();
1051 auto switch_display_event =
mail::man->event<
int>(mail::switch_display);
1054 auto initial_capture_ctx = capture_ctx_queue->pop();
1055 if (!initial_capture_ctx) {
1058 capture_ctxs.emplace_back(std::move(*initial_capture_ctx));
1060 std::vector<std::string> display_names;
1062 std::shared_ptr<platf::display_t> disp;
1063 const bool session_scoped_display = !capture_ctxs.front().config.display_name.empty();
1064 std::string capture_display_name =
1065 session_scoped_display ? capture_ctxs.front().config.display_name : proc::proc.display_name;
1066 if (!capture_display_name.empty()) {
1067 disp =
platf::display(encoder.platform_formats->dev_type, capture_display_name, capture_ctxs.front().config);
1068 if (!disp && session_scoped_display) {
1069 BOOST_LOG(error) <<
"Session-scoped capture display ["sv << capture_display_name
1070 <<
"] is unavailable; refusing fallback to another monitor."sv;
1077 refresh_displays(encoder.platform_formats->dev_type, display_names, display_p);
1078 disp =
platf::display(encoder.platform_formats->dev_type, display_names[display_p], capture_ctxs.front().config);
1080 capture_display_name = display_names[display_p];
1081 proc::proc.display_name = capture_display_name;
1089 constexpr auto capture_buffer_size = 12;
1090 std::list<std::shared_ptr<platf::img_t>> imgs(capture_buffer_size);
1092 std::vector<std::optional<std::chrono::steady_clock::time_point>> imgs_used_timestamps;
1093 const std::chrono::seconds trim_timeot = 3s;
1094 auto trim_imgs = [&]() {
1096 size_t allocated_count = 0;
1097 size_t used_count = 0;
1098 for (
const auto &img : imgs) {
1100 allocated_count += 1;
1101 if (img.use_count() > 1) {
1108 const auto now = std::chrono::steady_clock::now();
1109 if (imgs_used_timestamps.size() <= used_count) {
1110 imgs_used_timestamps.resize(used_count + 1);
1112 imgs_used_timestamps[used_count] = now;
1116 size_t trim_target = used_count;
1117 for (
size_t i = used_count; i < imgs_used_timestamps.size(); i++) {
1118 if (imgs_used_timestamps[i] && now - *imgs_used_timestamps[i] < trim_timeot) {
1124 if (allocated_count > trim_target) {
1125 size_t to_trim = allocated_count - trim_target;
1127 for (
auto it = imgs.rbegin(); it != imgs.rend(); it++) {
1129 if (img && img.use_count() == 1) {
1138 imgs_used_timestamps.resize(trim_target + 1);
1142 auto pull_free_image_callback = [&](std::shared_ptr<platf::img_t> &img_out) ->
bool {
1144 while (capture_ctx_queue->running()) {
1146 for (
auto it = imgs.begin(); it != imgs.end(); it++) {
1147 if (*it && it->use_count() == 1) {
1149 if (it != imgs.begin()) {
1152 imgs.push_front(img_out);
1159 for (
auto it = imgs.begin(); it != imgs.end(); it++) {
1162 *it = disp->alloc_img();
1164 if (it != imgs.begin()) {
1167 imgs.push_front(img_out);
1176 img_out->frame_timestamp.reset();
1180 std::this_thread::sleep_for(1ms);
1187 platf::adjust_thread_priority(platf::thread_priority_e::critical);
1189 while (capture_ctx_queue->running()) {
1190 bool artificial_reinit =
false;
1192 auto push_captured_image_callback = [&](std::shared_ptr<platf::img_t> &&img,
bool frame_captured) ->
bool {
1193 KITTY_WHILE_LOOP(
auto capture_ctx = std::begin(capture_ctxs), capture_ctx != std::end(capture_ctxs), {
1194 if (!capture_ctx->images->running()) {
1195 capture_ctx = capture_ctxs.erase(capture_ctx);
1200 if (frame_captured) {
1201 capture_ctx->images->raise(img);
1207 if (!capture_ctx_queue->running()) {
1211 while (capture_ctx_queue->peek()) {
1212 capture_ctxs.emplace_back(std::move(*capture_ctx_queue->pop()));
1215 if (!session_scoped_display && switch_display_event->peek()) {
1216 artificial_reinit =
true;
1223 auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &
display_cursor);
1225 if (artificial_reinit && status != platf::capture_e::error) {
1226 status = platf::capture_e::reinit;
1228 artificial_reinit =
false;
1232 case platf::capture_e::reinit:
1234 reinit_event.raise(
true);
1237 for (
auto &img : imgs) {
1244 while (display_wp->use_count() != 1) {
1249 KITTY_WHILE_LOOP(
auto capture_ctx = std::begin(capture_ctxs), capture_ctx != std::end(capture_ctxs), {
1250 if (!capture_ctx->images->running()) {
1251 capture_ctx = capture_ctxs.erase(capture_ctx);
1255 while (capture_ctx->images->peek()) {
1256 capture_ctx->images->pop();
1262 std::this_thread::sleep_for(20ms);
1265 while (capture_ctx_queue->running()) {
1271 if (!session_scoped_display) {
1272 refresh_displays(encoder.platform_formats->dev_type, display_names, display_p, proc::proc.display_name);
1275 if (switch_display_event->peek()) {
1276 display_p = std::clamp(*switch_display_event->pop(), 0, (
int) display_names.size() - 1);
1278 capture_display_name = display_names[display_p];
1282 reset_display(disp, encoder.platform_formats->dev_type, capture_display_name, capture_ctxs.front().config);
1284 if (!session_scoped_display) {
1285 proc::proc.display_name = capture_display_name;
1296 reinit_event.reset();
1299 case platf::capture_e::error:
1300 case platf::capture_e::ok:
1301 case platf::capture_e::timeout:
1302 case platf::capture_e::interrupted:
1305 BOOST_LOG(error) <<
"Unrecognized capture status ["sv << (int) status <<
']';
1311 int encode_avcodec(int64_t frame_nr,
avcodec_encode_session_t &session, safe::mail_raw_t::queue_t<packet_t> &packets,
void *channel_data, std::optional<std::chrono::steady_clock::time_point> frame_timestamp) {
1312 auto &frame = session.device->frame;
1313 frame->pts = frame_nr;
1315 auto &ctx = session.avcodec_ctx;
1317 auto &sps = session.sps;
1318 auto &vps = session.vps;
1321 const auto encode_start = std::chrono::steady_clock::now();
1322 double capture_to_encode_ms = 0.0;
1323 if (frame_timestamp) {
1324 const auto cap_to_enc = std::chrono::duration<double, std::milli>(encode_start - *frame_timestamp).count();
1325 capture_to_encode_ms = cap_to_enc >= 0.0 ? cap_to_enc : 0.0;
1329 auto ret = avcodec_send_frame(ctx.get(), frame);
1331 char err_str[AV_ERROR_MAX_STRING_SIZE] {0};
1332 BOOST_LOG(error) <<
"Could not send a frame for encoding: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, ret);
1337 session.frame_submitted =
true;
1339 size_t packet_bytes = 0;
1340 auto record_frame_metrics = [&]() {
1341 const auto encode_ms = std::chrono::duration<double, std::milli>(
1342 std::chrono::steady_clock::now() - encode_start)
1348 auto packet = std::make_unique<packet_raw_avcodec>();
1349 auto av_packet = packet.get()->av_packet;
1351 ret = avcodec_receive_packet(ctx.get(), av_packet);
1352 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
1353 record_frame_metrics();
1355 }
else if (ret < 0) {
1362 if ((ctx->codec_id == AV_CODEC_ID_H264 || ctx->codec_id == AV_CODEC_ID_HEVC) && av_packet->size > 0 &&
1363 av_packet_make_writable(av_packet) == 0) {
1364 const auto codec = ctx->codec_id == AV_CODEC_ID_H264 ? annexb::codec_e::h264 : annexb::codec_e::hevc;
1365 const auto size =
static_cast<std::size_t
>(av_packet->size);
1367 if (stripped < size) {
1368 if (!session.filler_stripped) {
1369 BOOST_LOG(info) <<
"Removing the filler data the encoder pads frames with"sv;
1370 session.filler_stripped =
true;
1372 av_shrink_packet(av_packet,
static_cast<int>(stripped));
1377 packet_bytes +=
static_cast<size_t>(av_packet->size > 0 ? av_packet->size : 0);
1380 if (av_packet->flags & AV_PKT_FLAG_KEY) {
1381 BOOST_LOG(debug) <<
"Frame "sv << frame_nr <<
": IDR Keyframe (AV_FRAME_FLAG_KEY)"sv;
1384 if ((frame->flags & AV_FRAME_FLAG_KEY) && !(av_packet->flags & AV_PKT_FLAG_KEY)) {
1385 BOOST_LOG(error) <<
"Encoder did not produce IDR frame when requested!"sv;
1388 if (session.inject) {
1389 if (session.inject == 1) {
1390 auto h264 = cbs::make_sps_h264(ctx.get(), av_packet);
1392 sps = std::move(h264.sps);
1394 auto hevc = cbs::make_sps_hevc(ctx.get(), av_packet);
1396 sps = std::move(hevc.sps);
1397 vps = std::move(hevc.vps);
1399 session.replacements.emplace_back(
1400 std::string_view((
char *) std::begin(vps.old), vps.old.size()),
1401 std::string_view((
char *) std::begin(vps._new), vps._new.size())
1407 session.replacements.emplace_back(
1408 std::string_view((
char *) std::begin(sps.old), sps.old.size()),
1409 std::string_view((
char *) std::begin(sps._new), sps._new.size())
1413 if (av_packet && av_packet->pts == frame_nr) {
1414 packet->frame_timestamp = frame_timestamp;
1417 if (session.intra_refresh_frames > 0) {
1418 if (session.next_after_invalidation && !(av_packet->flags & AV_PKT_FLAG_KEY)) {
1419 packet->after_ref_frame_invalidation =
true;
1421 session.next_after_invalidation =
false;
1424 packet->replacements = &session.replacements;
1425 packet->channel_data = channel_data;
1426 packets->raise(std::move(packet));
1429 record_frame_metrics();
1433 int encode_nvenc(int64_t frame_nr,
nvenc_encode_session_t &session, safe::mail_raw_t::queue_t<packet_t> &packets,
void *channel_data, std::optional<std::chrono::steady_clock::time_point> frame_timestamp) {
1434 const auto encode_start = std::chrono::steady_clock::now();
1435 double capture_to_encode_ms = 0.0;
1436 if (frame_timestamp) {
1437 const auto cap_to_enc = std::chrono::duration<double, std::milli>(encode_start - *frame_timestamp).count();
1438 capture_to_encode_ms = cap_to_enc >= 0.0 ? cap_to_enc : 0.0;
1441 auto encoded_frame = session.encode_frame(frame_nr);
1442 if (encoded_frame.data.empty()) {
1443 BOOST_LOG(error) <<
"NvENC returned empty packet";
1448 if (frame_nr != encoded_frame.frame_index) {
1449 BOOST_LOG(error) <<
"NvENC frame index mismatch " << frame_nr <<
" " << encoded_frame.frame_index;
1453 const size_t packet_bytes = encoded_frame.data.size();
1455 auto packet = std::make_unique<packet_raw_generic>(std::move(encoded_frame.data), encoded_frame.frame_index, encoded_frame.idr);
1456 packet->channel_data = channel_data;
1457 packet->after_ref_frame_invalidation = encoded_frame.after_ref_frame_invalidation;
1458 packet->frame_timestamp = frame_timestamp;
1459 packets->raise(std::move(packet));
1461 const auto encode_ms = std::chrono::duration<double, std::milli>(
1462 std::chrono::steady_clock::now() - encode_start)
1471 pyrowave_result encode_pyrowave_cpu(pyrowave_encode_session_t &session,
const pyrowave_rate_control &rate_control) {
1472 auto *frame = session.device ? session.device->frame :
nullptr;
1473 if (!frame || !frame->data[0] || !frame->data[1] || !frame->data[2]) {
1474 BOOST_LOG(error) <<
"PyroWave encoder received an invalid YUV frame"sv;
1475 return PYROWAVE_ERROR_INVALID_ARGUMENT;
1478 pyrowave_cpu_buffer input {};
1479 for (
int plane = 0; plane < 3; ++plane) {
1480 const auto rows =
static_cast<size_t>(plane == 0 ? frame->height : frame->height / 2);
1481 input.data[plane] = frame->data[plane];
1482 input.row_stride_in_bytes[plane] =
static_cast<size_t>(frame->linesize[plane]);
1483 input.plane_size_in_bytes[plane] = input.row_stride_in_bytes[plane] * rows;
1485 input.width = frame->width;
1486 input.height = frame->height;
1487 input.format = PYROWAVE_CPU_BUFFER_FORMAT_YUV420P;
1488 return pyrowave_encoder_encode_cpu_synchronous(session.pyrowave_encoder_handle, &input, &rate_control);
1491 int encode_pyrowave(int64_t frame_nr, pyrowave_encode_session_t &session, safe::mail_raw_t::queue_t<packet_t> &packets,
void *channel_data, std::optional<std::chrono::steady_clock::time_point> frame_timestamp) {
1492 const auto encode_start = std::chrono::steady_clock::now();
1493 double capture_to_encode_ms = 0.0;
1494 if (frame_timestamp) {
1495 const auto elapsed = std::chrono::duration<double, std::milli>(encode_start - *frame_timestamp).count();
1496 capture_to_encode_ms = std::max(0.0, elapsed);
1499 const pyrowave_rate_control rate_control {session.maximum_frame_bytes};
1500 pyrowave_result encoded;
1503 auto release_planes = util::fail_guard([&session]() {
1505 session.gpu.device->encoded();
1509 pyrowave_gpu_buffers buffers {};
1510 const pyrowave_gpu_sync_operation *acquire =
nullptr;
1511 const pyrowave_gpu_sync_operation *
release =
nullptr;
1512 if (!session.gpu.device->planes(buffers, acquire, release)) {
1513 BOOST_LOG(warning) <<
"PyroWave conversion is not ready; skipping this independent frame"sv;
1517 encoded = pyrowave_encoder_encode_gpu_synchronous(session.pyrowave_encoder_handle, acquire, release, &buffers, &rate_control);
1520 encoded = encode_pyrowave_cpu(session, rate_control);
1522 if (!pyrowave_succeeded(encoded,
"frame encode"sv)) {
1529 size_t num_packets = 0;
1530 if (!pyrowave_succeeded(pyrowave_encoder_compute_num_packets(session.pyrowave_encoder_handle, session.maximum_frame_bytes, &num_packets),
"packet count"sv) || num_packets == 0) {
1535 std::vector<pyrowave_packet> pyrowave_packets(num_packets);
1536 size_t written_packets = 0;
1537 if (!pyrowave_succeeded(pyrowave_encoder_packetize(session.pyrowave_encoder_handle, pyrowave_packets.data(), session.maximum_frame_bytes, &written_packets, session.bitstream.data(), session.bitstream.size()),
"packetization"sv) || written_packets == 0 || written_packets > pyrowave_packets.size()) {
1542 const auto &last_packet = pyrowave_packets[written_packets - 1];
1543 const size_t encoded_size = last_packet.offset + last_packet.size;
1544 if (encoded_size == 0 || encoded_size > session.bitstream.size()) {
1545 BOOST_LOG(error) <<
"PyroWave returned an invalid encoded frame size"sv;
1551 auto packet = std::make_unique<packet_raw_generic>(
1552 std::vector<uint8_t>(session.bitstream.begin(), session.bitstream.begin() +
static_cast<std::ptrdiff_t
>(encoded_size)),
1556 packet->channel_data = channel_data;
1557 packet->frame_timestamp = frame_timestamp;
1558 packets->raise(std::move(packet));
1560 const auto encode_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - encode_start).count();
1566 int encode(int64_t frame_nr,
encode_session_t &session, safe::mail_raw_t::queue_t<packet_t> &packets,
void *channel_data, std::optional<std::chrono::steady_clock::time_point> frame_timestamp) {
1568 return encode_avcodec(frame_nr, *avcodec_session, packets, channel_data, frame_timestamp);
1570 return encode_nvenc(frame_nr, *nvenc_session, packets, channel_data, frame_timestamp);
1572 }
else if (
auto pyrowave_session =
dynamic_cast<pyrowave_encode_session_t *
>(&session)) {
1573 return encode_pyrowave(frame_nr, *pyrowave_session, packets, channel_data, frame_timestamp);
1580 std::unique_ptr<avcodec_encode_session_t> make_avcodec_encode_session(
1581 platf::display_t *disp,
1586 std::unique_ptr<platf::avcodec_encode_device_t> encode_device
1589 if (!platform_formats) {
1593 bool hardware = platform_formats->avcodec_base_dev_type != AV_HWDEVICE_TYPE_NONE;
1595 auto &video_format = encoder.codec_from_config(config);
1597 BOOST_LOG(error) << encoder.name <<
": "sv << video_format.name <<
" mode not supported"sv;
1602 BOOST_LOG(error) << video_format.name <<
": dynamic range not supported"sv;
1607 BOOST_LOG(error) << video_format.name <<
": YUV 4:4:4 not supported"sv;
1611 auto codec = avcodec_find_encoder_by_name(video_format.name.c_str());
1613 BOOST_LOG(error) <<
"Couldn't open ["sv << video_format.name <<
']';
1618 auto colorspace = encode_device->colorspace;
1619 auto sw_fmt = (colorspace.bit_depth == 8 && config.chromaSamplingType == 0) ? platform_formats->avcodec_pix_fmt_8bit :
1620 (colorspace.bit_depth == 8 && config.chromaSamplingType == 1) ? platform_formats->avcodec_pix_fmt_yuv444_8bit :
1621 (colorspace.bit_depth == 10 && config.chromaSamplingType == 0) ? platform_formats->avcodec_pix_fmt_10bit :
1622 (colorspace.bit_depth == 10 && config.chromaSamplingType == 1) ? platform_formats->avcodec_pix_fmt_yuv444_10bit :
1631 for (
int retries = 0; retries < 2; retries++) {
1632 ctx.reset(avcodec_alloc_context3(codec));
1633 ctx->width = config.width;
1634 ctx->height = config.height;
1635 ctx->time_base = AVRational {1, config.framerate};
1636 ctx->framerate = AVRational {config.framerate, 1};
1638 switch (config.videoFormat) {
1641 assert(!config.dynamicRange);
1642 ctx->profile = (config.chromaSamplingType == 1) ? AV_PROFILE_H264_HIGH_444_PREDICTIVE : AV_PROFILE_H264_HIGH;
1646 if (config.chromaSamplingType == 1) {
1648 ctx->profile = AV_PROFILE_HEVC_REXT;
1650 ctx->profile = config.dynamicRange ? AV_PROFILE_HEVC_MAIN_10 : AV_PROFILE_HEVC_MAIN;
1657 ctx->profile = (config.chromaSamplingType == 1) ? AV_PROFILE_AV1_HIGH : AV_PROFILE_AV1_MAIN;
1662 ctx->max_b_frames = 0;
1666 std::numeric_limits<std::int16_t>::max() :
1667 std::numeric_limits<int>::max();
1669 ctx->keyint_min = std::numeric_limits<int>::max();
1672 if (config.numRefFrames) {
1674 ctx->refs = config.numRefFrames;
1676 BOOST_LOG(warning) <<
"Client requested reference frame limit, but encoder doesn't support it!"sv;
1682 ctx->flags |= AV_CODEC_FLAG_CLOSED_GOP | AV_CODEC_FLAG_LOW_DELAY;
1684 ctx->flags2 |= AV_CODEC_FLAG2_FAST;
1686 auto avcodec_colorspace = avcodec_colorspace_from_sunshine_colorspace(colorspace);
1688 ctx->color_range = avcodec_colorspace.range;
1689 ctx->color_primaries = avcodec_colorspace.primaries;
1690 ctx->color_trc = avcodec_colorspace.transfer_function;
1691 ctx->colorspace = avcodec_colorspace.matrix;
1694 ctx->sw_pix_fmt = sw_fmt;
1697 avcodec_buffer_t encoding_stream_context;
1699 ctx->pix_fmt = platform_formats->avcodec_dev_pix_fmt;
1702 auto buf_or_error = platform_formats->init_avcodec_hardware_input_buffer(encode_device.get());
1703 if (buf_or_error.has_right()) {
1706 encoding_stream_context = std::move(buf_or_error.left());
1709 if (platform_formats->avcodec_derived_dev_type != AV_HWDEVICE_TYPE_NONE) {
1710 avcodec_buffer_t derived_context;
1713 if (encode_device->prepare_to_derive_context(platform_formats->avcodec_derived_dev_type)) {
1717 auto err = av_hwdevice_ctx_create_derived(&derived_context, platform_formats->avcodec_derived_dev_type, encoding_stream_context.get(), 0);
1719 char err_str[AV_ERROR_MAX_STRING_SIZE] {0};
1720 BOOST_LOG(error) <<
"Failed to derive device context: "sv << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, err);
1725 encoding_stream_context = std::move(derived_context);
1730 avcodec_buffer_t frame_ref {av_hwframe_ctx_alloc(encoding_stream_context.get())};
1732 auto frame_ctx = (AVHWFramesContext *) frame_ref->data;
1733 frame_ctx->format = ctx->pix_fmt;
1734 frame_ctx->sw_format = sw_fmt;
1735 frame_ctx->height = ctx->height;
1736 frame_ctx->width = ctx->width;
1737 frame_ctx->initial_pool_size = 0;
1740 encode_device->init_hwframes(frame_ctx);
1742 if (
auto err = av_hwframe_ctx_init(frame_ref.get()); err < 0) {
1746 ctx->hw_frames_ctx = av_buffer_ref(frame_ref.get());
1749 ctx->slices = config.slicesPerFrame;
1751 ctx->pix_fmt = sw_fmt;
1756 ctx->slices = std::max(config.slicesPerFrame, config::video.min_threads);
1763 ctx->thread_type = FF_THREAD_SLICE;
1764 ctx->thread_count = ctx->slices;
1766 AVDictionary *options {
nullptr};
1771 av_dict_set_int(&options, option.name.c_str(), v, 0);
1774 av_dict_set_int(&options, option.name.c_str(), *v, 0);
1776 [&](std::optional<int> *v) {
1778 av_dict_set_int(&options, option.name.c_str(), **v, 0);
1781 [&](
const std::function<int()> &v) {
1782 av_dict_set_int(&options, option.name.c_str(), v(), 0);
1784 [&](
const std::string &v) {
1785 av_dict_set(&options, option.name.c_str(), v.c_str(), 0);
1787 [&](std::string *v) {
1789 av_dict_set(&options, option.name.c_str(), v->c_str(), 0);
1792 [&](
const std::function<
const std::string(
const config_t &cfg)> &v) {
1793 av_dict_set(&options, option.name.c_str(), v(config).c_str(), 0);
1801 for (
auto &option : video_format.common_options) {
1802 handle_option(option);
1804 for (
auto &option : (config.dynamicRange ? video_format.hdr_options : video_format.sdr_options)) {
1805 handle_option(option);
1807 if (config::video.vaapi.quality >= 0 && encoder.name ==
"vaapi") {
1808 av_dict_set_int(&options,
"quality", config::video.vaapi.quality, 0);
1810 if (config.chromaSamplingType == 1) {
1811 for (
auto &option : (config.dynamicRange ? video_format.hdr444_options : video_format.sdr444_options)) {
1812 handle_option(option);
1816 for (
auto &option : video_format.fallback_options) {
1817 handle_option(option);
1821 auto bitrate = config.bitrate * 1000;
1822 ctx->rc_max_rate = bitrate;
1823 ctx->bit_rate = bitrate;
1829 ctx->rc_min_rate = bitrate;
1833 ctx->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
1837 if (!hardware && (ctx->slices > 1 || config.videoFormat == 1)) {
1842 ctx->rc_buffer_size = bitrate / ((config.framerate * 10) / 15);
1844 ctx->rc_buffer_size = bitrate / config.framerate;
1846 if (encoder.name ==
"nvenc" && config::video.nv_legacy.vbv_percentage_increase > 0) {
1847 ctx->rc_buffer_size += ctx->rc_buffer_size * config::video.nv_legacy.vbv_percentage_increase / 100;
1855 if (encoder.name ==
"vaapi"sv && vaapi_intra_refresh_requested()) {
1856 av_dict_set_int(&options,
"intra_refresh", std::max(1, config.framerate / 2), 0);
1860 encode_device->init_codec_options(ctx.get(), &options);
1862 if (
auto status = avcodec_open2(ctx.get(), codec, &options)) {
1863 char err_str[AV_ERROR_MAX_STRING_SIZE] {0};
1865 if (!video_format.fallback_options.empty() && retries == 0) {
1867 <<
"Retrying with fallback configuration options for ["sv << video_format.name <<
"] after error: "sv
1868 << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, status);
1873 <<
"Could not open codec ["sv
1874 << video_format.name <<
"]: "sv
1875 << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, status);
1885 avcodec_frame_t frame {av_frame_alloc()};
1886 frame->format = ctx->pix_fmt;
1887 frame->width = ctx->width;
1888 frame->height = ctx->height;
1889 frame->color_range = ctx->color_range;
1890 frame->color_primaries = ctx->color_primaries;
1891 frame->color_trc = ctx->color_trc;
1892 frame->colorspace = ctx->colorspace;
1893 frame->chroma_location = ctx->chroma_sample_location;
1896 if (colorspace_is_hdr(colorspace)) {
1897 SS_HDR_METADATA hdr_metadata;
1898 if (disp->get_hdr_metadata(hdr_metadata)) {
1899 auto mdm = av_mastering_display_metadata_create_side_data(frame.get());
1901 mdm->display_primaries[0][0] = av_make_q(hdr_metadata.displayPrimaries[0].x, 50000);
1902 mdm->display_primaries[0][1] = av_make_q(hdr_metadata.displayPrimaries[0].y, 50000);
1903 mdm->display_primaries[1][0] = av_make_q(hdr_metadata.displayPrimaries[1].x, 50000);
1904 mdm->display_primaries[1][1] = av_make_q(hdr_metadata.displayPrimaries[1].y, 50000);
1905 mdm->display_primaries[2][0] = av_make_q(hdr_metadata.displayPrimaries[2].x, 50000);
1906 mdm->display_primaries[2][1] = av_make_q(hdr_metadata.displayPrimaries[2].y, 50000);
1908 mdm->white_point[0] = av_make_q(hdr_metadata.whitePoint.x, 50000);
1909 mdm->white_point[1] = av_make_q(hdr_metadata.whitePoint.y, 50000);
1911 mdm->min_luminance = av_make_q(hdr_metadata.minDisplayLuminance, 10000);
1912 mdm->max_luminance = av_make_q(hdr_metadata.maxDisplayLuminance, 1);
1914 mdm->has_luminance = hdr_metadata.maxDisplayLuminance != 0 ? 1 : 0;
1915 mdm->has_primaries = hdr_metadata.displayPrimaries[0].x != 0 ? 1 : 0;
1917 if (hdr_metadata.maxContentLightLevel != 0 || hdr_metadata.maxFrameAverageLightLevel != 0) {
1918 auto clm = av_content_light_metadata_create_side_data(frame.get());
1920 clm->MaxCLL = hdr_metadata.maxContentLightLevel;
1921 clm->MaxFALL = hdr_metadata.maxFrameAverageLightLevel;
1924 BOOST_LOG(error) <<
"Couldn't get display hdr metadata when colorspace selection indicates it should have one";
1928 std::unique_ptr<platf::avcodec_encode_device_t> encode_device_final;
1930 if (!encode_device->data) {
1931 auto software_encode_device = std::make_unique<avcodec_software_encode_device_t>();
1933 if (software_encode_device->init(width, height, frame.get(), sw_fmt, hardware)) {
1936 software_encode_device->colorspace = colorspace;
1938 encode_device_final = std::move(software_encode_device);
1940 encode_device_final = std::move(encode_device);
1943 if (encode_device_final->set_frame(frame.release(), ctx->hw_frames_ctx)) {
1947 encode_device_final->apply_colorspace();
1949 int64_t intra_refresh_frames = 0;
1950 if (encoder.name ==
"vaapi"sv && vaapi_intra_refresh_requested()) {
1952 if (av_opt_get_int(ctx->priv_data,
"intra_refresh", 0, &intra_refresh_frames) < 0) {
1953 intra_refresh_frames = 0;
1955 if (intra_refresh_frames > 0) {
1956 probe_saw_intra_refresh =
true;
1957 if (!config.encoder_probe) {
1958 BOOST_LOG(info) <<
"VAAPI rolling intra refresh: the whole picture every "sv << intra_refresh_frames
1959 <<
" frames, so a lost frame heals without a key frame"sv;
1961 }
else if (!config.encoder_probe) {
1962 BOOST_LOG(warning) <<
"VAAPI intra refresh was requested, but this FFmpeg or driver cannot do it"sv;
1966 auto session = std::make_unique<avcodec_encode_session_t>(
1968 std::move(encode_device_final),
1973 session->intra_refresh_frames =
static_cast<int>(intra_refresh_frames);
1978 std::unique_ptr<nvenc_encode_session_t> make_nvenc_encode_session(
const config_t &client_config, std::unique_ptr<platf::nvenc_encode_device_t> encode_device) {
1979 if (!encode_device->init_encoder(client_config, encode_device->colorspace)) {
1983 return std::make_unique<nvenc_encode_session_t>(std::move(encode_device));
1987 std::unique_ptr<pyrowave_encode_session_t> make_pyrowave_encode_session(
1988 const config_t &config,
1991 std::unique_ptr<platf::avcodec_encode_device_t> encode_device
1993 if (!pyrowave_available() || config.dynamicRange || config.chromaSamplingType != 0 || config.width <= 0 || config.height <= 0 || (config.width & 1) || (config.height & 1)) {
1994 BOOST_LOG(error) <<
"PyroWave requires even dimensions and 8-bit YUV 4:2:0 input"sv;
1998 auto colorspace = encode_device->colorspace;
1999 auto avcodec_colorspace = avcodec_colorspace_from_sunshine_colorspace(colorspace);
2000 avcodec_frame_t frame {av_frame_alloc()};
2004 frame->format = AV_PIX_FMT_YUV420P;
2005 frame->width = config.width;
2006 frame->height = config.height;
2007 frame->color_range = avcodec_colorspace.range;
2008 frame->color_primaries = avcodec_colorspace.primaries;
2009 frame->color_trc = avcodec_colorspace.transfer_function;
2010 frame->colorspace = avcodec_colorspace.matrix;
2012 pyrowave_gpu_source_t gpu;
2013 gpu.device =
dynamic_cast<pyrowave::gpu_encode_device_t *
>(encode_device.get());
2015 std::unique_ptr<platf::avcodec_encode_device_t> conversion_device;
2018 conversion_device = std::move(encode_device);
2019 }
else if (!encode_device->data) {
2020 auto software_device = std::make_unique<avcodec_software_encode_device_t>();
2021 if (software_device->init(width, height, frame.get(), AV_PIX_FMT_YUV420P,
false)) {
2024 software_device->colorspace = colorspace;
2025 conversion_device = std::move(software_device);
2029 BOOST_LOG(error) <<
"PyroWave cannot take frames from this capture's hardware encode device"sv;
2033 if (conversion_device->set_frame(frame.release(),
nullptr)) {
2036 conversion_device->apply_colorspace();
2039 pyrowave_device pyrowave_device_handle {};
2040 bool owns_device =
false;
2042 pyrowave_device_handle = gpu.device->device();
2044 if (!pyrowave_device_handle) {
2045 if (!pyrowave_succeeded(pyrowave_create_default_device(&pyrowave_device_handle),
"device creation"sv)) {
2051 pyrowave_device_set_queue_type(pyrowave_device_handle, VK_QUEUE_COMPUTE_BIT);
2054 pyrowave_encoder_create_info encoder_info {};
2055 encoder_info.device = pyrowave_device_handle;
2056 encoder_info.width = config.width;
2057 encoder_info.height = config.height;
2058 encoder_info.chroma = PYROWAVE_CHROMA_SUBSAMPLING_420;
2060 pyrowave_encoder pyrowave_encoder_handle {};
2061 if (!pyrowave_succeeded(pyrowave_encoder_create(&encoder_info, &pyrowave_encoder_handle),
"encoder creation"sv)) {
2063 pyrowave_device_destroy(pyrowave_device_handle);
2069 BOOST_LOG(info) <<
"Creating experimental PyroWave encoder with "sv << maximum_frame_bytes
2070 <<
" bytes per-frame budget, converting "sv << (gpu ?
"on the GPU"sv :
"on the CPU"sv);
2071 return std::make_unique<pyrowave_encode_session_t>(
2072 std::move(conversion_device),
2074 pyrowave_device_handle,
2076 pyrowave_encoder_handle,
2082 std::unique_ptr<encode_session_t> make_encode_session(
platf::display_t *disp,
const encoder_t &encoder,
const config_t &config,
int width,
int height, std::unique_ptr<platf::encode_device_t> encode_device) {
2084 if (config.videoFormat == PYROWAVE_VIDEO_FORMAT) {
2085 auto avcodec_encode_device = boost::dynamic_pointer_cast<platf::avcodec_encode_device_t>(std::move(encode_device));
2086 if (!avcodec_encode_device) {
2087 BOOST_LOG(error) <<
"PyroWave requires the software capture conversion path"sv;
2090 return make_pyrowave_encode_session(config, width, height, std::move(avcodec_encode_device));
2094 auto avcodec_encode_device = boost::dynamic_pointer_cast<platf::avcodec_encode_device_t>(std::move(encode_device));
2095 return make_avcodec_encode_session(disp, encoder, config, width, height, std::move(avcodec_encode_device));
2097 auto nvenc_encode_device = boost::dynamic_pointer_cast<platf::nvenc_encode_device_t>(std::move(encode_device));
2098 return make_nvenc_encode_session(config, std::move(nvenc_encode_device));
2109 std::shared_ptr<platf::display_t> disp,
2110 std::unique_ptr<platf::encode_device_t> encode_device,
2111 safe::signal_t &reinit_event,
2112 const encoder_t &encoder,
2115 auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device));
2130 auto fail_guard = util::fail_guard([&encoder, &session] {
2131 if (encoder.flags & ASYNC_TEARDOWN) {
2132 std::thread encoder_teardown_thread {[session = std::move(session)]()
mutable {
2133 BOOST_LOG(info) <<
"Starting async encoder teardown";
2135 BOOST_LOG(info) <<
"Async encoder teardown complete";
2137 encoder_teardown_thread.detach();
2142 double minimum_fps_target = (config::video.minimum_fps_target > 0.0) ? config::video.minimum_fps_target * 1000 : std::max(config.encodingFramerate / 5, 10000);
2143 auto max_frametime = std::chrono::nanoseconds(1000ms) * 1000 / minimum_fps_target;
2144 auto encode_frame_threshold = std::chrono::nanoseconds(1000ms) * 1000 / config.encodingFramerate;
2145 auto frame_variation_threshold = encode_frame_threshold / 4;
2146 auto min_frame_diff = encode_frame_threshold - frame_variation_threshold;
2147 BOOST_LOG(info) <<
"Minimum FPS target set to ~"sv << (minimum_fps_target / 2000) <<
"fps ("sv << max_frametime * 2 <<
")"sv;
2148 BOOST_LOG(info) <<
"Encoding Frame threshold: "sv << encode_frame_threshold;
2150 auto shutdown_event =
mail->event<
bool>(mail::shutdown);
2151 auto packets =
mail::man->queue<packet_t>(mail::video_packets);
2152 auto idr_events =
mail->event<
bool>(mail::idr);
2153 auto invalidate_ref_frames_events =
mail->event<std::pair<int64_t, int64_t>>(mail::invalidate_ref_frames);
2160 auto dummy_img = disp->alloc_img();
2161 if (!dummy_img || disp->dummy_img(dummy_img.get()) || session->convert(*dummy_img)) {
2166 if (config.input_only) {
2167 BOOST_LOG(info) <<
"Input only session, video will not be captured."sv;
2170 if (encode(frame_nr++, *session, packets, channel_data, std::chrono::steady_clock::now())) {
2171 BOOST_LOG(error) <<
"Could not encode dummy video packet"sv;
2176 if (shutdown_event->peek() || !images->running() || (reinit_event.peek())) {
2179 std::this_thread::sleep_for(300ms);
2184 std::chrono::steady_clock::time_point encode_frame_timestamp;
2185 bool missing_frame_timestamp_warning_logged =
false;
2195 if (shutdown_event->peek() || !images->running() || (reinit_event.peek() && frame_nr > 1)) {
2199 bool requested_idr_frame =
false;
2201 while (invalidate_ref_frames_events->peek()) {
2202 if (
auto frames = invalidate_ref_frames_events->pop(0ms)) {
2203 session->invalidate_ref_frames(frames->first, frames->second);
2207 if (idr_events->peek()) {
2208 requested_idr_frame =
true;
2212 if (requested_idr_frame) {
2213 session->request_idr_frame();
2216 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
2219 if (!requested_idr_frame || images->peek()) {
2220 if (
auto img = images->pop(max_frametime)) {
2221 frame_timestamp = img->frame_timestamp;
2222 if (!frame_timestamp) {
2223 if (!missing_frame_timestamp_warning_logged) {
2224 BOOST_LOG(warning) <<
"Encoder received image without frame timestamp; substituting steady_clock::now()"sv;
2225 missing_frame_timestamp_warning_logged =
true;
2227 frame_timestamp = std::chrono::steady_clock::now();
2230 auto current_timestamp = *frame_timestamp;
2231 auto time_diff = current_timestamp - encode_frame_timestamp;
2234 if (time_diff < -frame_variation_threshold) {
2238 if (session->convert(*img)) {
2239 BOOST_LOG(error) <<
"Could not convert image"sv;
2243 if (time_diff < frame_variation_threshold) {
2244 *frame_timestamp = encode_frame_timestamp;
2246 encode_frame_timestamp = current_timestamp;
2249 encode_frame_timestamp += encode_frame_threshold;
2250 }
else if (!images->running()) {
2255 if (encode(frame_nr++, *session, packets, channel_data, frame_timestamp)) {
2256 BOOST_LOG(error) <<
"Could not encode video packet"sv;
2260 session->request_normal_frame();
2268 float wt = config.width;
2269 float ht = config.height;
2271 auto scalar = std::fminf(wt / wd, ht / hd);
2273 auto w2 = scalar * wd;
2274 auto h2 = scalar * hd;
2276 auto offsetX = (config.width - w2) * 0.5f;
2277 auto offsetY = (config.height - h2) * 0.5f;
2303 std::unique_ptr<platf::encode_device_t> make_encode_device(
platf::display_t &disp,
const encoder_t &encoder,
const config_t &config) {
2304 std::unique_ptr<platf::encode_device_t> result;
2306 auto colorspace = colorspace_from_client_config(config, disp.is_hdr());
2309 if (config.chromaSamplingType == 1) {
2311 if (!(encoder.flags & YUV444_SUPPORT)) {
2315 pix_fmt = (colorspace.bit_depth == 10) ?
2316 encoder.platform_formats->pix_fmt_yuv444_10bit :
2317 encoder.platform_formats->pix_fmt_yuv444_8bit;
2320 pix_fmt = (colorspace.bit_depth == 10) ?
2321 encoder.platform_formats->pix_fmt_10bit :
2322 encoder.platform_formats->pix_fmt_8bit;
2325 const bool pyrowave = config.videoFormat == PYROWAVE_VIDEO_FORMAT;
2328 std::string encoder_name = pyrowave ?
"pyrowave"s : encoder.codec_from_config(config).name;
2332 auto color_coding = colorspace.colorspace == colorspace_e::bt2020 ?
"HDR (Rec. 2020 + SMPTE 2084 PQ)" :
2333 colorspace.colorspace == colorspace_e::rec601 ?
"SDR (Rec. 601)" :
2334 colorspace.colorspace == colorspace_e::rec709 ?
"SDR (Rec. 709)" :
2335 colorspace.colorspace == colorspace_e::bt2020sdr ?
"SDR (Rec. 2020)" :
2338 BOOST_LOG(info) <<
"Color coding: " << color_coding;
2339 BOOST_LOG(info) <<
"Color depth: " << colorspace.bit_depth <<
"-bit";
2340 BOOST_LOG(info) <<
"Color range: " << (colorspace.full_range ?
"JPEG" :
"MPEG");
2353 BOOST_LOG(error) <<
"This capture cannot hand its frames to PyroWave"sv;
2355 }
else if (
dynamic_cast<const encoder_platform_formats_avcodec *
>(encoder.platform_formats.get())) {
2356 result = disp.make_avcodec_encode_device(pix_fmt);
2357 }
else if (
dynamic_cast<const encoder_platform_formats_nvenc *
>(encoder.platform_formats.get())) {
2358 result = disp.make_nvenc_encode_device(pix_fmt);
2362 result->colorspace = colorspace;
2368 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) {
2369 sync_session_t encode_session;
2371 encode_session.ctx = &ctx;
2373 auto encode_device = make_encode_device(*disp, encoder, ctx.config);
2374 if (!encode_device) {
2375 return std::nullopt;
2379 ctx.touch_port_events->raise(make_port(disp, ctx.config));
2382 hdr_info_t hdr_info = std::make_unique<hdr_info_raw_t>(
false);
2383 if (colorspace_is_hdr(encode_device->colorspace)) {
2384 if (disp->get_hdr_metadata(hdr_info->metadata)) {
2385 hdr_info->enabled =
true;
2387 BOOST_LOG(error) <<
"Couldn't get display hdr metadata when colorspace selection indicates it should have one";
2390 ctx.hdr_events->raise(std::move(hdr_info));
2392 auto session = make_encode_session(disp, encoder, ctx.config, img.width, img.height, std::move(encode_device));
2394 return std::nullopt;
2398 if (session->convert(img)) {
2399 BOOST_LOG(error) <<
"Could not convert initial image"sv;
2400 return std::nullopt;
2403 encode_session.session = std::move(session);
2405 return encode_session;
2408 encode_e encode_run_sync(
2409 std::vector<std::unique_ptr<sync_session_ctx_t>> &synced_session_ctxs,
2410 encode_session_ctx_queue_t &encode_session_ctx_queue,
2411 std::vector<std::string> &display_names,
2414 const auto &encoder = *chosen_encoder;
2416 std::shared_ptr<platf::display_t> disp;
2418 auto switch_display_event =
mail::man->event<
int>(mail::switch_display);
2420 if (synced_session_ctxs.empty()) {
2421 auto ctx = encode_session_ctx_queue.pop();
2423 return encode_e::ok;
2426 synced_session_ctxs.emplace_back(std::make_unique<sync_session_ctx_t>(std::move(*ctx)));
2429 while (encode_session_ctx_queue.running()) {
2431 refresh_displays(encoder.platform_formats->dev_type, display_names, display_p);
2434 if (switch_display_event->peek()) {
2435 display_p = std::clamp(*switch_display_event->pop(), 0, (
int) display_names.size() - 1);
2439 reset_display(disp, encoder.platform_formats->dev_type, display_names[display_p], synced_session_ctxs.front()->config);
2446 return encode_e::error;
2449 auto img = disp->alloc_img();
2450 if (!img || disp->dummy_img(img.get())) {
2451 return encode_e::error;
2454 std::vector<sync_session_t> synced_sessions;
2455 for (
auto &ctx : synced_session_ctxs) {
2456 auto synced_session = make_synced_session(disp.get(), encoder, *img, *ctx);
2457 if (!synced_session) {
2458 return encode_e::error;
2461 synced_sessions.emplace_back(std::move(*synced_session));
2465 while (encode_session_ctx_queue.running()) {
2466 auto push_captured_image_callback = [&](std::shared_ptr<platf::img_t> &&img,
bool frame_captured) ->
bool {
2467 while (encode_session_ctx_queue.peek()) {
2468 auto encode_session_ctx = encode_session_ctx_queue.pop();
2469 if (!encode_session_ctx) {
2473 synced_session_ctxs.emplace_back(std::make_unique<sync_session_ctx_t>(std::move(*encode_session_ctx)));
2475 auto encode_session = make_synced_session(disp.get(), encoder, *img, *synced_session_ctxs.back());
2476 if (!encode_session) {
2481 synced_sessions.emplace_back(std::move(*encode_session));
2484 KITTY_WHILE_LOOP(
auto pos = std::begin(synced_sessions), pos != std::end(synced_sessions), {
2485 auto ctx = pos->ctx;
2486 if (ctx->shutdown_event->peek()) {
2488 ctx->join_event->raise(
true);
2490 pos = synced_sessions.erase(pos);
2491 synced_session_ctxs.erase(std::find_if(std::begin(synced_session_ctxs), std::end(synced_session_ctxs), [&ctx_p = ctx](
auto &ctx) {
2492 return ctx.get() == ctx_p;
2495 if (synced_sessions.empty()) {
2502 if (ctx->idr_events->peek()) {
2503 pos->session->request_idr_frame();
2504 ctx->idr_events->pop();
2507 if (frame_captured && pos->session->convert(*img)) {
2508 BOOST_LOG(error) <<
"Could not convert image"sv;
2509 ctx->shutdown_event->raise(
true);
2514 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
2516 frame_timestamp = img->frame_timestamp;
2519 if (encode(ctx->frame_nr++, *pos->session, ctx->packets, ctx->channel_data, frame_timestamp)) {
2520 BOOST_LOG(error) <<
"Could not encode video packet"sv;
2521 ctx->shutdown_event->raise(
true);
2526 pos->session->request_normal_frame();
2531 if (switch_display_event->peek()) {
2539 auto pull_free_image_callback = [&img](std::shared_ptr<platf::img_t> &img_out) ->
bool {
2541 img_out->frame_timestamp.reset();
2545 auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &
display_cursor);
2556 return encode_e::ok;
2559 void captureThreadSync() {
2560 auto ref = capture_thread_sync.ref();
2562 std::vector<std::unique_ptr<sync_session_ctx_t>> synced_session_ctxs;
2564 auto &ctx = ref->encode_session_ctx_queue;
2565 auto lg = util::fail_guard([&]() {
2568 for (
auto &ctx : synced_session_ctxs) {
2569 ctx->shutdown_event->raise(
true);
2570 ctx->join_event->raise(
true);
2573 for (
auto &ctx : ctx.unsafe()) {
2574 ctx.shutdown_event->raise(
true);
2575 ctx.join_event->raise(
true);
2582 std::vector<std::string> display_names;
2584 while (encode_run_sync(synced_session_ctxs, ctx, display_names, display_p) == encode_e::reinit) {}
2587 void capture_async_with_context(
2588 capture_thread_async_ctx_t &capture_context,
2593 auto shutdown_event =
mail->event<
bool>(mail::shutdown);
2595 auto images = std::make_shared<img_event_t::element_type>();
2596 auto lg = util::fail_guard([&]() {
2598 shutdown_event->raise(
true);
2601 capture_context.capture_ctx_queue->raise(capture_ctx_t {images, config});
2603 if (!capture_context.capture_ctx_queue->running()) {
2610 auto hdr_event =
mail->event<hdr_info_t>(mail::hdr);
2615 while (!shutdown_event->peek() && images->running()) {
2617 if (capture_context.reinit_event.peek()) {
2618 std::this_thread::sleep_for(20ms);
2622 std::shared_ptr<platf::display_t>
display;
2624 auto lg = capture_context.display_wp.lock();
2625 if (capture_context.display_wp->expired()) {
2629 display = capture_context.display_wp->lock();
2632 auto &encoder = *capture_context.encoder_p;
2634 auto encode_device = make_encode_device(*display, encoder, config);
2635 if (!encode_device) {
2640 touch_port_event->raise(make_port(
display.get(), config));
2643 hdr_info_t hdr_info = std::make_unique<hdr_info_raw_t>(
false);
2644 if (colorspace_is_hdr(encode_device->colorspace)) {
2645 if (
display->get_hdr_metadata(hdr_info->metadata)) {
2646 hdr_info->enabled =
true;
2648 BOOST_LOG(error) <<
"Couldn't get display hdr metadata when colorspace selection indicates it should have one";
2651 hdr_event->raise(std::move(hdr_info));
2659 std::move(encode_device),
2660 capture_context.reinit_event,
2661 *capture_context.encoder_p,
2677 static const encoder_t *pyrowave_capture_encoder() {
2678 if (chosen_encoder) {
2679 const auto memory = chosen_encoder->platform_formats->dev_type;
2681 return chosen_encoder;
2692 if (!config.display_name.empty() || config.videoFormat == PYROWAVE_VIDEO_FORMAT) {
2693 capture_thread_async_ctx_t session_capture;
2694 const encoder_t *capture_encoder =
2695 config.videoFormat == PYROWAVE_VIDEO_FORMAT ? pyrowave_capture_encoder() : chosen_encoder;
2696 if (start_capture_async_with_encoder(session_capture, capture_encoder)) {
2699 auto cleanup = util::fail_guard([&session_capture]() {
2700 end_capture_async(session_capture);
2702 capture_async_with_context(session_capture, std::move(
mail), config, channel_data);
2706 auto ref = capture_thread_async.ref();
2710 capture_async_with_context(*ref.get(), std::move(
mail), config, channel_data);
2718 auto idr_events =
mail->event<
bool>(mail::idr);
2720 idr_events->raise(
true);
2721 if (!config.display_name.empty() && config.videoFormat != PYROWAVE_VIDEO_FORMAT && !(chosen_encoder->flags & PARALLEL_ENCODING)) {
2722 BOOST_LOG(error) <<
"Session-scoped multi-output capture requires a parallel encoder pipeline."sv;
2725 if (config.videoFormat == PYROWAVE_VIDEO_FORMAT || (chosen_encoder->flags & PARALLEL_ENCODING)) {
2726 capture_async(std::move(
mail), config, channel_data);
2728 safe::signal_t join_event;
2729 auto ref = capture_thread_sync.ref();
2730 ref->encode_session_ctx_queue.raise(sync_session_ctx_t {
2732 mail->event<
bool>(mail::shutdown),
2733 mail::man->queue<packet_t>(mail::video_packets),
2734 std::move(idr_events),
2735 mail->event<hdr_info_t>(mail::hdr),
2751 int validate_config(std::shared_ptr<platf::display_t> disp,
const encoder_t &encoder,
const config_t &config) {
2752 auto encode_device = make_encode_device(*disp, encoder, config);
2753 if (!encode_device) {
2757 auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device));
2764 auto img = disp->alloc_img();
2765 if (!img || disp->dummy_img(img.get()) || session->convert(*img)) {
2770 session->request_idr_frame();
2772 auto packets =
mail::man->queue<packet_t>(mail::video_packets);
2773 while (!packets->peek()) {
2774 if (encode(1, *session, packets,
nullptr, {})) {
2779 auto packet = packets->pop();
2780 if (!packet->is_idr()) {
2781 BOOST_LOG(error) <<
"First packet type is not an IDR frame"sv;
2789 if (config.videoFormat <= 1) {
2790 if (
auto packet_avcodec =
dynamic_cast<packet_raw_avcodec *
>(packet.get())) {
2791 if (
cbs::validate_sps(packet_avcodec->av_packet, config.videoFormat ? AV_CODEC_ID_H265 : AV_CODEC_ID_H264)) {
2803 bool validate_encoder(encoder_t &encoder,
bool expect_failure) {
2805 std::shared_ptr<platf::display_t> disp;
2807 BOOST_LOG(info) <<
"Trying encoder ["sv << encoder.name <<
']';
2808 auto fg = util::fail_guard([&]() {
2809 BOOST_LOG(info) <<
"Encoder ["sv << encoder.name <<
"] failed"sv;
2812 probe_saw_intra_refresh =
false;
2814 auto test_hevc = active_hevc_mode >= 2 || (active_hevc_mode == 0 && !(encoder.flags &
H264_ONLY));
2815 auto test_av1 = active_av1_mode >= 2 || (active_av1_mode == 0 && !(encoder.flags &
H264_ONLY));
2817 encoder.h264.capabilities.set();
2818 encoder.hevc.capabilities.set();
2819 encoder.av1.capabilities.set();
2822 config_t config_max_ref_frames {1920, 1080, 60, 1000, 1, 1, 1, 0, 0, 0};
2823 config_t config_autoselect {1920, 1080, 60, 1000, 1, 0, 1, 0, 0, 0};
2824 config_max_ref_frames.encoder_probe =
true;
2825 config_autoselect.encoder_probe =
true;
2828 reset_display(disp, encoder.platform_formats->dev_type, output_name, config_autoselect);
2832 if (!disp->is_codec_supported(encoder.h264.name, config_autoselect)) {
2834 BOOST_LOG(info) <<
"Encoder ["sv << encoder.name <<
"] is not supported on this GPU"sv;
2840 auto max_ref_frames_h264 = expect_failure ? -1 : validate_config(disp, encoder, config_max_ref_frames);
2841 auto autoselect_h264 = max_ref_frames_h264 >= 0 ? max_ref_frames_h264 : validate_config(disp, encoder, config_autoselect);
2842 if (autoselect_h264 < 0) {
2844 }
else if (expect_failure) {
2846 max_ref_frames_h264 = validate_config(disp, encoder, config_max_ref_frames);
2849 std::vector<std::pair<validate_flag_e, encoder_t::flag_e>> packet_deficiencies {
2853 for (
auto [validate_flag, encoder_flag] : packet_deficiencies) {
2854 encoder.h264[encoder_flag] = (max_ref_frames_h264 & validate_flag && autoselect_h264 & validate_flag);
2857 encoder.h264[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_h264 >= 0;
2858 encoder.h264[encoder_t::PASSED] =
true;
2861 config_max_ref_frames.videoFormat = 1;
2862 config_autoselect.videoFormat = 1;
2864 if (disp->is_codec_supported(encoder.hevc.name, config_autoselect)) {
2865 auto max_ref_frames_hevc = validate_config(disp, encoder, config_max_ref_frames);
2869 auto autoselect_hevc = (max_ref_frames_hevc >= 0 || max_ref_frames_h264 >= 0) ?
2870 max_ref_frames_hevc :
2871 validate_config(disp, encoder, config_autoselect);
2873 for (
auto [validate_flag, encoder_flag] : packet_deficiencies) {
2874 encoder.hevc[encoder_flag] = (max_ref_frames_hevc & validate_flag && autoselect_hevc & validate_flag);
2877 encoder.hevc[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_hevc >= 0;
2878 encoder.hevc[encoder_t::PASSED] = max_ref_frames_hevc >= 0 || autoselect_hevc >= 0;
2880 BOOST_LOG(info) <<
"Encoder ["sv << encoder.hevc.name <<
"] is not supported on this GPU"sv;
2881 encoder.hevc.capabilities.reset();
2885 encoder.hevc.capabilities.reset();
2889 config_max_ref_frames.videoFormat = 2;
2890 config_autoselect.videoFormat = 2;
2892 if (disp->is_codec_supported(encoder.av1.name, config_autoselect)) {
2893 auto max_ref_frames_av1 = validate_config(disp, encoder, config_max_ref_frames);
2897 auto autoselect_av1 = (max_ref_frames_av1 >= 0 || max_ref_frames_h264 >= 0) ?
2898 max_ref_frames_av1 :
2899 validate_config(disp, encoder, config_autoselect);
2901 for (
auto [validate_flag, encoder_flag] : packet_deficiencies) {
2902 encoder.av1[encoder_flag] = (max_ref_frames_av1 & validate_flag && autoselect_av1 & validate_flag);
2905 encoder.av1[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_av1 >= 0;
2906 encoder.av1[encoder_t::PASSED] = max_ref_frames_av1 >= 0 || autoselect_av1 >= 0;
2908 BOOST_LOG(info) <<
"Encoder ["sv << encoder.av1.name <<
"] is not supported on this GPU"sv;
2909 encoder.av1.capabilities.reset();
2913 encoder.av1.capabilities.reset();
2919 if (encoder.flags & YUV444_SUPPORT) {
2920 config_t config_h264_yuv444 {1920, 1080, 60, 1000, 1, 0, 1, 0, 0, 1};
2921 encoder.h264[encoder_t::YUV444] = disp->is_codec_supported(encoder.h264.name, config_h264_yuv444) &&
2922 validate_config(disp, encoder, config_h264_yuv444) >= 0;
2924 encoder.h264[encoder_t::YUV444] =
false;
2927 config_t generic_hdr_config = {1920, 1080, 60, 1000, 1, 0, 3, 1, 1, 0};
2928 generic_hdr_config.encoder_probe =
true;
2931 reset_display(disp, encoder.platform_formats->dev_type, output_name, generic_hdr_config);
2936 auto test_hdr_and_yuv444 = [&](
auto &flag_map,
auto video_format) {
2937 auto config = generic_hdr_config;
2938 config.videoFormat = video_format;
2940 if (!flag_map[encoder_t::PASSED]) {
2944 auto encoder_codec_name = encoder.codec_from_config(config).name;
2947 config.chromaSamplingType = 1;
2948 if ((encoder.flags & YUV444_SUPPORT) &&
2949 disp->is_codec_supported(encoder_codec_name, config) &&
2950 validate_config(disp, encoder, config) >= 0) {
2951 flag_map[encoder_t::DYNAMIC_RANGE] =
true;
2952 flag_map[encoder_t::YUV444] =
true;
2955 flag_map[encoder_t::YUV444] =
false;
2959 config.chromaSamplingType = 0;
2960 if (disp->is_codec_supported(encoder_codec_name, config) &&
2961 validate_config(disp, encoder, config) >= 0) {
2962 flag_map[encoder_t::DYNAMIC_RANGE] =
true;
2964 flag_map[encoder_t::DYNAMIC_RANGE] =
false;
2969 encoder.h264[encoder_t::DYNAMIC_RANGE] =
false;
2971 test_hdr_and_yuv444(encoder.hevc, 1);
2972 test_hdr_and_yuv444(encoder.av1, 2);
2978 if (encoder.name ==
"vaapi"sv) {
2979 if (probe_saw_intra_refresh) {
2981 BOOST_LOG(info) << encoder.name <<
": rolling intra refresh available; offering reference frame invalidation"sv;
2983 encoder.flags &= ~REF_FRAMES_INVALIDATION;
2990 if (!encoder.h264[encoder_t::VUI_PARAMETERS]) {
2991 BOOST_LOG(warning) << encoder.name <<
": h264 missing sps->vui parameters"sv;
2993 if (encoder.hevc[encoder_t::PASSED] && !encoder.hevc[encoder_t::VUI_PARAMETERS]) {
2994 BOOST_LOG(warning) << encoder.name <<
": hevc missing sps->vui parameters"sv;
3002 bool client_hdr_requested,
bool display_hdr,
bool hevc_hdr_supported,
bool av1_hdr_supported
3008 if (!client_hdr_requested) {
3010 return std::nullopt;
3012 if (hevc_hdr_supported) {
3015 if (av1_hdr_supported) {
3018 return std::nullopt;
3021 static int check_capture_path_impl(
const config_t &stream, std::string &failure, capture_readiness_t &result) {
3022 using namespace std::literals;
3023 if (!chosen_encoder) {
3024 failure =
"No working video encoder was found";
3027 const auto &encoder = *chosen_encoder;
3031 auto name = stream.display_name.empty() ? proc::proc.display_name : stream.display_name;
3033 std::vector<std::string> display_names;
3035 refresh_displays(encoder.platform_formats->dev_type, display_names, display_p);
3036 if (display_p >= 0 && display_p <
static_cast<int>(display_names.size())) {
3037 name = display_names[display_p];
3041 const auto label = !stream.kwin_wayland_socket.empty() ?
3042 "the detached desktop via KWin screencast"s :
3043 (name.empty() ?
"the primary display"s :
"display ["s + name +
']') +
3044 (config::video.capture.empty() ?
""s :
" via "s + config::video.capture);
3045 result.capture = label;
3050 config_t config = stream;
3051 config.width = 1920;
3052 config.height = 1080;
3053 config.framerate = stream.framerate > 0 ? stream.framerate : 60;
3054 config.bitrate = 1000;
3055 config.slicesPerFrame = 1;
3056 config.numRefFrames = 0;
3057 config.encoderCscMode = 1;
3058 config.videoFormat = 0;
3059 config.dynamicRange = 0;
3060 config.chromaSamplingType = 0;
3061 config.enableIntraRefresh = 0;
3062 config.input_only =
false;
3063 config.encoder_probe =
true;
3064 auto disp =
platf::display(encoder.platform_formats->dev_type, name, config);
3066 failure =
"Capture could not open " + label;
3070 const bool display_hdr = disp->is_hdr();
3071 const bool requires_hdr = disp->requires_hdr_for_hdr_output();
3072 const bool validate_hdr = stream.dynamicRange || (display_hdr && requires_hdr);
3076 encoder.hevc[encoder_t::DYNAMIC_RANGE],
3077 encoder.av1[encoder_t::DYNAMIC_RANGE]
3080 failure =
"Capture output is HDR, but encoder [" + std::string {encoder.name} +
3081 "] has no supported HDR codec (HEVC Main10 or AV1 Main10)";
3085 config.videoFormat = mode->video_format;
3086 config.dynamicRange = mode->dynamic_range;
3091 config.encoder_probe =
false;
3093 disp =
platf::display(encoder.platform_formats->dev_type, name, config);
3095 failure =
"Capture could not open " + label +
3096 (validate_hdr && display_hdr ?
" in HDR mode" :
"");
3099 if (disp->is_hdr() != display_hdr) {
3100 failure =
"Capture color mode changed while checking " + label;
3104 config.width = disp->width;
3105 config.height = disp->height;
3106 result.width = disp->width;
3107 result.height = disp->height;
3108 result.framerate = config.framerate;
3109 result.encoder = encoder.name;
3114 std::shared_ptr<platf::img_t> frame;
3115 const auto deadline = std::chrono::steady_clock::now() + 5s;
3116 bool timed_out =
false;
3117 std::vector<std::shared_ptr<platf::img_t>> pool;
3118 bool cursor =
false;
3119 const auto status = disp->capture(
3120 [&](std::shared_ptr<platf::img_t> &&img,
bool frame_captured) {
3121 if (frame_captured && img) {
3122 frame = std::move(img);
3125 if (std::chrono::steady_clock::now() >= deadline) {
3131 [&](std::shared_ptr<platf::img_t> &img_out) {
3132 for (
auto &img : pool) {
3133 if (img.use_count() == 1) {
3138 if (pool.size() >= 3) {
3141 img_out = pool.emplace_back(disp->alloc_img());
3142 return static_cast<bool>(img_out);
3149 BOOST_LOG(warning) <<
"Capture readiness: " << label <<
" produced no new frame within 5 seconds; continuing"sv;
3152 failure =
"Capture failed on " + label;
3157 auto encode_device = make_encode_device(*disp, encoder, config);
3158 if (!encode_device) {
3159 failure =
"The " + std::string {encoder.name} +
" encoder cannot take frames from " + label;
3162 auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device));
3164 failure =
"The " + std::string {encoder.name} +
" encoder could not start for " + label;
3167 if (session->convert(*frame)) {
3168 failure =
"A frame from " + label +
" could not be imported or converted on the " + std::string {encoder.name} +
" encoder's GPU";
3171 session->request_idr_frame();
3172 auto packets =
mail::man->queue<packet_t>(mail::video_packets);
3173 for (
int attempt = 0; !packets->peek(); ++attempt) {
3174 if (attempt == 10 || encode(1, *session, packets,
nullptr, {})) {
3175 failure =
"The " + std::string {encoder.name} +
" encoder failed on a frame from " + label;
3183 if (std::string_view {encoder.name} ==
"vaapi"sv) {
3185 result.gpu = std::move(actual);
3188 const auto &gpu = result.gpu;
3189 result.frame_seen =
true;
3190 BOOST_LOG(info) <<
"Capture readiness: " << label <<
" (" << disp->width <<
'x' << disp->height <<
" at "
3191 << config.framerate <<
" fps) captured, converted and encoded by " << encoder.name
3192 << (gpu.empty() ?
""s :
" on "s + gpu);
3196 static std::mutex capture_readiness_mutex;
3197 static capture_readiness_t capture_readiness;
3202 const int status = check_capture_path_impl(stream, failure, result);
3204 result.
ok = status == 0;
3205 result.
failure = status ? failure : std::string {};
3206 result.
checked_at = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
3207 std::lock_guard lock {capture_readiness_mutex};
3208 capture_readiness = std::move(result);
3213 std::lock_guard lock {capture_readiness_mutex};
3214 return capture_readiness;
3218 std::lock_guard lock {capture_readiness_mutex};
3219 if (capture_readiness.checked && capture_readiness.client == client) {
3220 capture_readiness = {};
3225 probe_without_display =
true;
3226 auto reset = util::fail_guard([]() {
3227 probe_without_display =
false;
3233 auto encoder_list = encoders;
3242 BOOST_LOG(info) <<
"// Testing for available encoders, this may generate errors. You can safely ignore those errors. //"sv;
3245 auto previous_encoder = chosen_encoder;
3246 chosen_encoder =
nullptr;
3247 active_hevc_mode = config::video.hevc_mode;
3248 active_av1_mode = config::video.av1_mode;
3249 last_encoder_probe_supported_ref_frames_invalidation =
false;
3251 auto adjust_encoder_constraints = [&](
encoder_t *encoder) {
3254 BOOST_LOG(warning) <<
"Encoder ["sv << encoder->name <<
"] does not support HEVC Main10 on this system"sv;
3255 active_hevc_mode = 0;
3257 BOOST_LOG(warning) <<
"Encoder ["sv << encoder->name <<
"] does not support HEVC on this system"sv;
3258 active_hevc_mode = 0;
3262 BOOST_LOG(warning) <<
"Encoder ["sv << encoder->name <<
"] does not support AV1 Main10 on this system"sv;
3263 active_av1_mode = 0;
3265 BOOST_LOG(warning) <<
"Encoder ["sv << encoder->name <<
"] does not support AV1 on this system"sv;
3266 active_av1_mode = 0;
3270 if (!config::video.encoder.empty()) {
3272 KITTY_WHILE_LOOP(
auto pos = std::begin(encoder_list), pos != std::end(encoder_list), {
3273 auto encoder = *pos;
3275 if (encoder->name == config::video.encoder) {
3277 if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) {
3278 pos = encoder_list.erase(pos);
3283 adjust_encoder_constraints(encoder);
3285 chosen_encoder = encoder;
3292 if (chosen_encoder ==
nullptr) {
3293 BOOST_LOG(error) <<
"Couldn't find any working encoder matching ["sv << config::video.encoder <<
']';
3298 if (chosen_encoder ==
nullptr && (active_hevc_mode >= 2 || active_av1_mode >= 2)) {
3299 KITTY_WHILE_LOOP(
auto pos = std::begin(encoder_list), pos != std::end(encoder_list), {
3300 auto encoder = *pos;
3303 if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) {
3304 pos = encoder_list.erase(pos);
3322 chosen_encoder = encoder;
3326 if (chosen_encoder ==
nullptr) {
3327 BOOST_LOG(error) <<
"Couldn't find any working encoder that meets HEVC/AV1 requirements"sv;
3334 std::vector<encoder_attempt_t> rejected_attempts;
3335 if (chosen_encoder ==
nullptr) {
3336 KITTY_WHILE_LOOP(
auto pos = std::begin(encoder_list), pos != std::end(encoder_list), {
3337 auto encoder = *pos;
3342 if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) {
3343 if (encoder->name !=
"software") {
3344 rejected_attempts.push_back({std::string {encoder->name},
false,
"probe_failed"});
3346 pos = encoder_list.erase(pos);
3351 adjust_encoder_constraints(encoder);
3353 chosen_encoder = encoder;
3358 if (chosen_encoder ==
nullptr) {
3360 BOOST_LOG(fatal) <<
"Unable to find display or encoder during startup."sv;
3361 if (!config::video.adapter_name.empty() || !output_name.empty()) {
3362 BOOST_LOG(fatal) <<
"Please ensure your manually chosen GPU and monitor are connected and powered on."sv;
3364 BOOST_LOG(fatal) <<
"Please check that a display is connected and powered on."sv;
3370 BOOST_LOG(info) <<
"// Ignore any errors mentioned above, they are not relevant. //"sv;
3373 auto &encoder = *chosen_encoder;
3376 last_encoder_probe_supported_yuv444_for_codec[0] = encoder.h264[
encoder_t::PASSED] &&
3378 last_encoder_probe_supported_yuv444_for_codec[1] = encoder.hevc[
encoder_t::PASSED] &&
3380 last_encoder_probe_supported_yuv444_for_codec[2] = encoder.av1[
encoder_t::PASSED] &&
3389 status.
encoder = std::string {encoder.name};
3390 status.
hardware = encoder.name !=
"software";
3394 status.
attempts = std::move(rejected_attempts);
3395 status.
attempts.push_back({std::string {encoder.name},
true,
"selected"});
3399 for (
const auto &attempt : status.
attempts) {
3400 if (attempt.selected) {
3403 if (!tried.empty()) {
3406 tried += attempt.name;
3408 if (tried.empty()) {
3409 BOOST_LOG(warning) <<
"Using SOFTWARE video encoding (no hardware encoder was available). "sv
3410 <<
"Expect higher CPU use and latency; check GPU driver/VAAPI/NVENC availability."sv;
3412 BOOST_LOG(warning) <<
"Using SOFTWARE video encoding: hardware encoder(s) ["sv << tried
3413 <<
"] failed probing. Expect higher CPU use and latency; "sv
3414 <<
"check GPU driver/VAAPI/NVENC availability and permissions."sv;
3417 std::lock_guard lg {encoder_status_mutex};
3418 encoder_status_state = std::move(status);
3421 BOOST_LOG(debug) <<
"------ h264 ------"sv;
3424 BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.h264[flag] ?
": supported"sv :
": unsupported"sv);
3426 BOOST_LOG(debug) <<
"-------------------"sv;
3427 BOOST_LOG(info) <<
"Found H.264 encoder: "sv << encoder.h264.name <<
" ["sv << encoder.name <<
']';
3430 BOOST_LOG(debug) <<
"------ hevc ------"sv;
3433 BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.hevc[flag] ?
": supported"sv :
": unsupported"sv);
3435 BOOST_LOG(debug) <<
"-------------------"sv;
3437 BOOST_LOG(info) <<
"Found HEVC encoder: "sv << encoder.hevc.name <<
" ["sv << encoder.name <<
']';
3441 BOOST_LOG(debug) <<
"------ av1 ------"sv;
3444 BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.av1[flag] ?
": supported"sv :
": unsupported"sv);
3446 BOOST_LOG(debug) <<
"-------------------"sv;
3448 BOOST_LOG(info) <<
"Found AV1 encoder: "sv << encoder.av1.name <<
" ["sv << encoder.name <<
']';
3451 if (active_hevc_mode == 0) {
3455 if (active_av1_mode == 0) {
3466 avcodec_buffer_t hw_device_buf;
3469 if (encode_device->data) {
3470 if (((vaapi_init_avcodec_hardware_input_buffer_fn) encode_device->data)(encode_device, &hw_device_buf)) {
3474 return hw_device_buf;
3477 auto render_device = config::video.adapter_name.empty() ? nullptr : config::video.adapter_name.c_str();
3479 auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VAAPI, render_device,
nullptr, 0);
3481 char string[AV_ERROR_MAX_STRING_SIZE];
3482 BOOST_LOG(error) <<
"Failed to create a VAAPI device: "sv << av_make_error_string(
string, AV_ERROR_MAX_STRING_SIZE, status);
3486 return hw_device_buf;
3490 avcodec_buffer_t hw_device_buf;
3492 auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_CUDA,
nullptr,
nullptr, 1 );
3494 char string[AV_ERROR_MAX_STRING_SIZE];
3495 BOOST_LOG(error) <<
"Failed to create a CUDA device: "sv << av_make_error_string(
string, AV_ERROR_MAX_STRING_SIZE, status);
3499 return hw_device_buf;
3502 int start_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) {
3503 return start_capture_async_with_encoder(capture_thread_ctx, chosen_encoder);
3506 int start_capture_async_with_encoder(capture_thread_async_ctx_t &capture_thread_ctx,
const encoder_t *encoder) {
3507 capture_thread_ctx.encoder_p = encoder;
3508 capture_thread_ctx.reinit_event.reset();
3510 capture_thread_ctx.capture_ctx_queue = std::make_shared<safe::queue_t<capture_ctx_t>>(30);
3512 capture_thread_ctx.capture_thread = std::thread {
3514 capture_thread_ctx.capture_ctx_queue,
3515 std::ref(capture_thread_ctx.display_wp),
3516 std::ref(capture_thread_ctx.reinit_event),
3517 std::ref(*capture_thread_ctx.encoder_p)
3523 void end_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) {
3524 capture_thread_ctx.capture_ctx_queue->stop();
3526 capture_thread_ctx.capture_thread.join();
3529 int start_capture_sync(capture_thread_sync_ctx_t &ctx) {
3530 std::thread {&captureThreadSync}.detach();
3534 void end_capture_sync(capture_thread_sync_ctx_t &ctx) {
3539 case AV_HWDEVICE_TYPE_VAAPI:
3541 case AV_HWDEVICE_TYPE_CUDA:
3543 case AV_HWDEVICE_TYPE_NONE:
3554 case AV_PIX_FMT_VUYX:
3556 case AV_PIX_FMT_XV30:
3558 case AV_PIX_FMT_YUV420P10:
3560 case AV_PIX_FMT_YUV420P:
3562 case AV_PIX_FMT_NV12:
3564 case AV_PIX_FMT_P010:
Removing filler data units from an Annex B H.264 or HEVC frame.
std::size_t strip_filler_data(std::uint8_t *data, std::size_t size, codec_e codec)
bool available()
Whether a broker socket is there to talk to.
bool validate_sps(const AVPacket *packet, int codec_id)
Validates the Sequence Parameter Set (SPS) of a given packet.
Declarations for FFmpeg Coded Bitstream API.
virtual bool is_codec_supported(std::string_view name, const ::video::config_t &config)
Check that a given codec is supported by the display device.
virtual std::unique_ptr< avcodec_encode_device_t > make_pyrowave_encode_device()
Make a device that converts captured frames into PyroWave's GPU planes.
bool next_after_invalidation
The next frame is the first the client may decode after a loss.
int intra_refresh_frames
Frames per full rolling intra refresh, when the encoder is doing one; 0 otherwise.
bool filler_stripped
Filler data has been removed from a frame of this session (logged once).
int64_t recovering_until
The last frame of the loss being recovered; requests up to it are repeats.
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override
Set the frame to be encoded.
Declarations for common platform specific utilities.
std::shared_ptr< display_t > display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config)
Get the display_t instance for the given hwdevice_type. If display_name is empty, use the first monit...
@ yuv420p10
YUV 4:2:0 10-bit.
std::shared_ptr< display_t > encoder_probe_display(mem_type_e hwdevice_type, const video::config_t &config)
A display with no screen behind it, for validating encoders.
bool needs_encoder_reenumeration()
Check if GPUs/drivers have changed since the last call to this function.
bool touch_binds_to_output()
Whether the session binds a touchscreen or a pen to one output.
@ reinit
Need to reinitialize.
@ interrupted
Capture was interrupted.
Declarations for the configuration of Sunshine.
@ FORCE_VIDEO_HEADER_REPLACE
force replacing headers inside video data
std::string map_output_name(const std::string &output_name)
Map the output name to a specific display.
Declarations for display device handling.
void note_vaapi_encode_gpu(int fd)
Record the GPU a VAAPI encoder actually opened, from its DRM fd.
std::string encode_gpu_description(bool nvenc)
Describe the GPU a stream encodes on, for logs and diagnostics: its render node, driver and the name ...
std::string last_vaapi_encode_gpu()
The GPU the last VAAPI encoder opened, described as encode_gpu_description() does,...
bool display_cursor
A boolean flag to indicate whether the cursor should be displayed.
Declarations for globally accessible variables and functions.
Declarations for logging related functions.
int main(int argc, char *argv[])
Main application entry point.
Miscellaneous declarations for Linux.
std::string bracket(const std::string &input)
Enclose string in square brackets.
Handles process-wide communication.
safe::mail_t man
A process-wide communication mechanism.
Standalone NVENC encoder.
Declarations for abstract platform-agnostic base of standalone NVENC encoder.
Declarations for the startup and shutdown of the apps started by a streaming Session.
GPU conversion for the experimental PyroWave codec.
Codec and color depth for a capture readiness check.
What the last capture-path check found, for a client to show.
std::string client
The paired client whose launch ran the check.
std::int64_t checked_at
Unix time of the check, in seconds.
std::string failure
The failed step and its reason, when not ok.
bool ok
Whether a frame went all the way through, or the display was only idle.
bool checked
Whether a check has run since Hermes started.
std::vector< encoder_attempt_t > attempts
std::string encoder
Selected encoder backend (e.g. "nvenc", "vaapi", "software").
bool hardware
True if the selected encoder is hardware-accelerated.
bool probed
A probe has completed at least once.
bool fell_back_to_software
True if a hardware encoder was rejected and we fell back to software.
bool h264
H.264 supported by the selected encoder.
@ DYNAMIC_RANGE
HDR support.
@ VUI_PARAMETERS
AMD encoder with VAAPI doesn't add VUI parameters to SPS.
@ PASSED
Indicates the encoder is supported.
@ REF_FRAMES_RESTRICT
Set maximum reference frames.
@ YUV444
YUV 4:4:4 support.
@ MAX_FLAGS
Maximum number of flags.
pipeline_metrics_t published
Last computed averages.
uint64_t window_frames
Frames in the current averaging window.
int width
Active stream resolution, set at session start.
uint64_t window_bytes
Encoded bytes in the current window.
uint64_t frames_encoded
Total this session.
Live per-frame pipeline metrics, for diagnostics/metrics.
Declarations for synchronization utilities.
void forget_capture_readiness(const std::string &client)
Forget the last check if it was for client's launch: a later launch of theirs ran without one,...
std::optional< capture_readiness_mode_t > choose_capture_readiness_mode(bool client_hdr_requested, bool display_hdr, bool hevc_hdr_supported, bool av1_hdr_supported)
Choose a readiness mode without ever encoding PQ scanout as SDR.
@ PARALLEL_ENCODING
Capture and encoding can run concurrently on separate threads.
@ CBR_WITH_VBR
Use a VBR rate control mode to simulate CBR.
@ REF_FRAMES_INVALIDATION
Support reference frames invalidation.
@ YUV444_SUPPORT
Encoder may support 4:4:4 chroma sampling depending on hardware.
@ ALWAYS_REPROBE
This is an encoder of last resort and we want to aggressively probe for a better one.
@ RELAXED_COMPLIANCE
Use FF_COMPLIANCE_UNOFFICIAL compliance mode.
@ ASYNC_TEARDOWN
Encoder supports async teardown on a different thread.
@ LIMITED_GOP_SIZE
Some encoders don't like it when you have an infinite GOP_SIZE. e.g. VAAPI.
@ SINGLE_SLICE_ONLY
Never use multiple slices. Older intel iGPU's ruin it for everyone else.
@ NO_RC_BUF_LIMIT
Don't set rc_buffer_size.
@ H264_ONLY
When HEVC is too heavy.
@ high_444p
High 4:4:4 Predictive profile.
void metrics_reset()
Reset pipeline metrics at the start of a streaming session.
void metrics_record_frame(double encode_ms, double capture_to_encode_ms, size_t packet_bytes)
Record one encoded frame's timings and output size.
bool display_present()
Whether the host has a display to capture without creating one.
@ main_10
Main 10 profile.
encoder_status_t get_encoder_status()
Snapshot of the last encoder probe result (thread-safe copy).
void refresh_displays(platf::mem_type_e dev_type, std::vector< std::string > &display_names, int ¤t_display_index, std::string &preferred_display_name)
Update the list of display names before or during a stream.
@ VUI_PARAMS
VUI parameters.
void metrics_record_drop()
Record one dropped frame (encoder error/timeout).
std::size_t pyrowave_frame_budget(const config_t &config)
The most bytes one PyroWave frame may take.
capture_readiness_t last_capture_readiness()
The result of the last check_capture_path().
int probe_encoders()
Probe encoders and select the preferred encoder. This is called once at startup and each time a strea...
pipeline_metrics_t get_pipeline_metrics()
Snapshot of the live pipeline metrics (thread-safe copy).
int check_capture_path(const config_t &stream, std::string &failure, const std::string &client)
Run one real frame through the path a stream will use.
void metrics_set_resolution(int width, int height)
Record the active stream resolution for diagnostics.
int probe_encoders_without_display()
Probe encoders without opening any screen.
std::vector< std::string > matchDisplay(const std::string &sMatch)
Match displays by a given pattern.
std::optional< bool > displayConnectorLit(const std::filesystem::path &drm_class, const std::string &ignored_connector)
Whether any DRM connector is lighting a monitor right now.
std::string parkedConnector()
The connector of the output being kept for the login greeter, or empty. It is lit,...
@ OK
Driver is operational.
void release(input_raw_t *raw, int index)
Free a gamepad whose stream ended; a detached desktop keeps it.