Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
video.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <atomic>
7#include <bitset>
8#include <list>
9#include <mutex>
10#include <thread>
11
12// lib includes
13#include <boost/pointer_cast.hpp>
14
15extern "C" {
16#include <libavutil/imgutils.h>
17#include <libavutil/mastering_display_metadata.h>
18#include <libavutil/opt.h>
19#include <libavutil/pixdesc.h>
20}
21
22// local includes
23#include "process.h"
24#include "annexb_filler.h"
25#include "cbs.h"
26#include "config.h"
27#include "display_device.h"
28#include "globals.h"
29#include "input.h"
30#include "logging.h"
31#include "nvenc/nvenc_base.h"
32#include "platform/common.h"
33#include "sync.h"
34#include "video.h"
35
36#ifdef HAVE_PYROWAVE
37 // pyrowave.h refuses to compile unless the Vulkan types come first.
38 // clang-format off
39 #include <vulkan/vulkan.h>
40 #include <pyrowave.h>
41 // clang-format on
43#endif
44
45#include "platform/linux/misc.h"
46
47
48using namespace std::literals;
49
50namespace video {
51
53 // The kernel only reports monitors on real KMS devices. A nested or
54 // headless compositor can still capture, so a negative result is only
55 // used when a virtual display can take over.
56 if (proc::vDisplayDriverStatus != VDISPLAY::DRIVER_STATUS::OK) {
57 return true;
58 }
59 if (!VDISPLAY::matchDisplay("VIRTUAL-").empty()) {
60 return true;
61 }
62 // An output Hermes itself keeps lit for the login greeter is not a monitor.
63 return VDISPLAY::displayConnectorLit("/sys/class/drm", VDISPLAY::parkedConnector()).value_or(true);
64 }
65
66 void free_ctx(AVCodecContext *ctx) {
67 avcodec_free_context(&ctx);
68 }
69
70 void free_frame(AVFrame *frame) {
71 av_frame_free(&frame);
72 }
73
74 void free_buffer(AVBufferRef *ref) {
75 av_buffer_unref(&ref);
76 }
77
78 namespace nv {
79
80 enum class profile_h264_e : int {
81 high = 2,
83 };
84
85 enum class profile_hevc_e : int {
86 main = 0,
87 main_10 = 1,
88 rext = 2,
89 };
90
91 } // namespace nv
92
93 util::Either<avcodec_buffer_t, int> vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
94 util::Either<avcodec_buffer_t, int> cuda_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
95
97 public:
98 int convert(platf::img_t &img) override {
99 // If we need to add aspect ratio padding, we need to scale into an intermediate output buffer
100 bool requires_padding = (sw_frame->width != sws_output_frame->width || sw_frame->height != sws_output_frame->height);
101
102 // Setup the input frame using the caller's img_t
103 sws_input_frame->data[0] = img.data;
104 sws_input_frame->linesize[0] = img.row_pitch;
105
106 // Perform color conversion and scaling to the final size
107 auto status = sws_scale_frame(sws.get(), requires_padding ? sws_output_frame.get() : sw_frame.get(), sws_input_frame.get());
108 if (status < 0) {
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);
111 return -1;
112 }
113
114 // If we require aspect ratio padding, copy the output frame into the final padded frame
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];
122
123 // Copy line-by-line to preserve leading padding for each row
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);
126 }
127 }
128 }
129
130 // If frame is not a software frame, it means we still need to transfer from main memory
131 // to vram memory
132 if (frame->hw_frames_ctx) {
133 auto status = av_hwframe_transfer_data(frame, sw_frame.get(), 0);
134 if (status < 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);
137 return -1;
138 }
139 }
140
141 return 0;
142 }
143
144 int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override {
145 this->frame = frame;
146
147 // If it's a hwframe, allocate buffers for hardware
148 if (hw_frames_ctx) {
149 hw_frame.reset(frame);
150
151 if (av_hwframe_get_buffer(hw_frames_ctx, frame, 0)) {
152 return -1;
153 }
154 } else {
155 sw_frame.reset(frame);
156 }
157
158 return 0;
159 }
160
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);
164 }
165
169 void prefill() {
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);
175 }
176
177 int init(int in_width, int in_height, AVFrame *frame, AVPixelFormat format, bool hardware) {
178 // If the device used is hardware, yet the image resides on main memory
179 if (hardware) {
180 sw_frame.reset(av_frame_alloc());
181
182 sw_frame->width = frame->width;
183 sw_frame->height = frame->height;
184 sw_frame->format = format;
185 } else {
186 this->frame = frame;
187 }
188
189 // Fill aspect ratio padding in the destination frame
190 prefill();
191
192 auto out_width = frame->width;
193 auto out_height = frame->height;
194
195 // Ensure aspect ratio is maintained
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;
199
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;
204
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;
209
210 // Result is always positive
211 offsetW = (frame->width - out_width) / 2;
212 offsetH = (frame->height - out_height) / 2;
213
214 sws.reset(sws_alloc_context());
215 if (!sws) {
216 return -1;
217 }
218
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);
228
229 auto status = av_opt_set_dict(sws.get(), &options);
230 av_dict_free(&options);
231 if (status < 0) {
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);
234 return -1;
235 }
236
237 status = sws_init_context(sws.get(), nullptr, nullptr);
238 if (status < 0) {
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);
241 return -1;
242 }
243
244 return 0;
245 }
246
247 // Store ownership when frame is hw_frame
248 avcodec_frame_t hw_frame;
249
250 avcodec_frame_t sw_frame;
251 avcodec_frame_t sws_input_frame;
252 avcodec_frame_t sws_output_frame;
253 sws_t sws;
254
255 // Offset of input image to output frame in pixels
256 int offsetW;
257 int offsetH;
258 };
259
260 enum flag_e : uint32_t {
263 H264_ONLY = 1 << 2,
266 CBR_WITH_VBR = 1 << 5,
270 ALWAYS_REPROBE = 1 << 9,
271 YUV444_SUPPORT = 1 << 10,
272 ASYNC_TEARDOWN = 1 << 11,
273 };
274
275#ifdef HAVE_PYROWAVE
276 namespace {
277 bool pyrowave_succeeded(pyrowave_result result, std::string_view operation) {
278 if (result == PYROWAVE_SUCCESS) {
279 return true;
280 }
281
282 BOOST_LOG(error) << "PyroWave "sv << operation << " failed with status "sv << static_cast<int>(result);
283 return false;
284 }
285 } // namespace
286
292 struct pyrowave_gpu_source_t {
293 pyrowave::gpu_encode_device_t *device {};
294
295 explicit operator bool() const {
296 return device != nullptr;
297 }
298 };
299
300 class pyrowave_encode_session_t: public encode_session_t {
301 public:
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,
306 bool owns_device,
307 pyrowave_encoder pyrowave_encoder_handle,
308 size_t maximum_frame_bytes
309 ):
310 device {std::move(encode_device)},
311 gpu {gpu},
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) {
317 }
318
319 ~pyrowave_encode_session_t() override {
320 // The encoder before the device it was created on. On the GPU path the
321 // device belongs to the encode device, which is destroyed after this.
322 if (pyrowave_encoder_handle) {
323 pyrowave_encoder_destroy(pyrowave_encoder_handle);
324 }
325 if (owns_device && pyrowave_device_handle) {
326 pyrowave_device_destroy(pyrowave_device_handle);
327 }
328 }
329
330 int convert(platf::img_t &img) override {
331 return device ? device->convert(img) : -1;
332 }
333
334 void request_idr_frame() override {
335 // PyroWave is intra-only, so every encoded frame is independently decodable.
336 }
337
338 void request_normal_frame() override {
339 }
340
341 void invalidate_ref_frames(int64_t, int64_t) override {
342 }
343
344 std::unique_ptr<platf::avcodec_encode_device_t> device;
345 pyrowave_gpu_source_t gpu;
346 pyrowave_device pyrowave_device_handle {};
347 bool owns_device {};
348 pyrowave_encoder pyrowave_encoder_handle {};
349 size_t maximum_frame_bytes {};
351 std::vector<uint8_t> bitstream;
352 };
353#endif
354
355 std::size_t pyrowave_frame_budget(const config_t &config) {
356 // Older clients send the frame rate in thousandths.
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));
361 }
362
363 bool pyrowave_available() {
364#ifdef HAVE_PYROWAVE
365 static std::once_flag probe_once;
366 static bool available = false;
367 std::call_once(probe_once, []() {
368 uint32_t major = 0;
369 uint32_t minor = 0;
370 uint32_t patch = 0;
371 pyrowave_get_api_version(&major, &minor, &patch);
372 // Every 0.x release shares the soname, yet 0.x promises no ABI
373 // stability, so until 1.0 only the minor version Hermes was built
374 // against is safe to call into.
375 const bool compatible = major == PYROWAVE_API_VERSION_MAJOR &&
376 (major == 0 ? minor == PYROWAVE_API_VERSION_MINOR : minor >= PYROWAVE_API_VERSION_MINOR);
377 if (!compatible) {
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;
382 return;
383 }
384
385 pyrowave_device device {};
386 if (!pyrowave_succeeded(pyrowave_create_default_device(&device), "Vulkan device probe"sv)) {
387 return;
388 }
389 auto cleanup_device = util::fail_guard([device]() {
390 pyrowave_device_destroy(device);
391 });
392 // A Vulkan device alone does not imply encoder support (for example,
393 // subgroup requirements can reject an otherwise usable Vulkan driver).
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)) {
401 return;
402 }
403 pyrowave_encoder_destroy(encoder);
404 available = true;
405 });
406 return available;
407#else
408 return false;
409#endif
410 }
411
412 class avcodec_encode_session_t: public encode_session_t {
413 public:
414 avcodec_encode_session_t() = default;
415
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)},
419 inject {inject} {
420 }
421
422 avcodec_encode_session_t(avcodec_encode_session_t &&other) noexcept = default;
423
424 ~avcodec_encode_session_t() {
425 // Some hardware encoders cannot be flushed safely before accepting
426 // their first frame. This can happen when importing the first captured
427 // DMA-BUF fails and the pipeline immediately tears the session down.
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);
432 }
433
434 // Order matters here because the context relies on the hwdevice still being valid
435 avcodec_ctx.reset();
436 device.reset();
437 }
438
439 // Ensure objects are destroyed in the correct order
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);
446
447 inject = other.inject;
448 frame_submitted = other.frame_submitted;
449 other.frame_submitted = false;
450 intra_refresh_frames = other.intra_refresh_frames;
451 next_after_invalidation = other.next_after_invalidation;
452 recovering_until = other.recovering_until;
453
454 return *this;
455 }
456
457 int convert(platf::img_t &img) override {
458 if (!device) {
459 return -1;
460 }
461 return device->convert(img);
462 }
463
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;
469 }
470 }
471
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;
477 }
478 }
479
480 void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) override {
481 if (intra_refresh_frames <= 0) {
482 BOOST_LOG(error) << "Encoder doesn't support reference frame invalidation";
483 request_idr_frame();
484 return;
485 }
486
487 // The encoder refreshes a band of rows in every frame, so whatever the
488 // lost frames damaged heals within one full refresh. Let the client go
489 // on decoding from the next frame instead of freezing for a key frame.
490 //
491 // Until a frame marked as following the invalidation reaches it, the
492 // client drops every frame and asks again, with the same first frame
493 // and a later last one. Those repeats are the same loss: mark the next
494 // frame again and nothing more. If the picture does not recover, the
495 // client asks for a key frame itself after too many dropped frames.
497 if (first_frame <= recovering_until) {
498 recovering_until = std::max(recovering_until, last_frame);
499 return;
500 }
501 recovering_until = last_frame;
502 BOOST_LOG(info) << "Frames "sv << first_frame << '-' << last_frame
503 << " lost; intra refresh heals them within "sv << intra_refresh_frames << " frames"sv;
504 }
505
506 avcodec_ctx_t avcodec_ctx;
507 std::unique_ptr<platf::avcodec_encode_device_t> device;
508
509 std::vector<packet_raw_t::replace_t> replacements;
510
511 cbs::nal_t sps;
512 cbs::nal_t vps;
513
514 // inject sps/vps data into idr pictures
515 int inject;
516 bool frame_submitted {false};
518 bool filler_stripped {false};
524 int64_t recovering_until {-1};
525 };
526
527 class nvenc_encode_session_t: public encode_session_t {
528 public:
529 nvenc_encode_session_t(std::unique_ptr<platf::nvenc_encode_device_t> encode_device):
530 device(std::move(encode_device)) {
531 }
532
533 int convert(platf::img_t &img) override {
534 if (!device) {
535 return -1;
536 }
537 return device->convert(img);
538 }
539
540 void request_idr_frame() override {
541 force_idr = true;
542 }
543
544 void request_normal_frame() override {
545 force_idr = false;
546 }
547
548 void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) override {
549 if (!device || !device->nvenc) {
550 return;
551 }
552
553 if (!device->nvenc->invalidate_ref_frames(first_frame, last_frame)) {
554 force_idr = true;
555 }
556 }
557
558 nvenc::nvenc_encoded_frame encode_frame(uint64_t frame_index) {
559 if (!device || !device->nvenc) {
560 return {};
561 }
562
563 auto result = device->nvenc->encode_frame(frame_index, force_idr);
564 force_idr = false;
565 return result;
566 }
567
568 private:
569 std::unique_ptr<platf::nvenc_encode_device_t> device;
570 bool force_idr = false;
571 };
572
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;
580
581 config_t config;
582 int frame_nr;
583 void *channel_data;
584 };
585
588 std::unique_ptr<encode_session_t> session;
589 };
590
591 using encode_session_ctx_queue_t = safe::queue_t<sync_session_ctx_t>;
592 using encode_e = platf::capture_e;
593
595 img_event_t images;
596 config_t config;
597 };
598
600 std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue;
601 std::thread capture_thread;
602
603 safe::signal_t reinit_event;
604 const encoder_t *encoder_p;
606 };
607
609 encode_session_ctx_queue_t encode_session_ctx_queue {30};
610 };
611
612 int start_capture_sync(capture_thread_sync_ctx_t &ctx);
613 void end_capture_sync(capture_thread_sync_ctx_t &ctx);
614 int start_capture_async(capture_thread_async_ctx_t &ctx);
615 int start_capture_async_with_encoder(capture_thread_async_ctx_t &ctx, const encoder_t *encoder);
616 void end_capture_async(capture_thread_async_ctx_t &ctx);
617
618 // Keep a reference counter to ensure the capture thread only runs when other threads have a reference to the capture thread
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);
621
623 "nvenc"sv,
624 std::make_unique<encoder_platform_formats_avcodec>(
625 AV_HWDEVICE_TYPE_CUDA,
626 AV_HWDEVICE_TYPE_NONE,
627 AV_PIX_FMT_CUDA,
628 AV_PIX_FMT_NV12,
629 AV_PIX_FMT_P010,
630 AV_PIX_FMT_NONE,
631 AV_PIX_FMT_NONE,
632 cuda_init_avcodec_hardware_input_buffer
633 ),
634 {
635 // Common options
636 {
637 {"delay"s, 0},
638 {"forced-idr"s, 1},
639 {"zerolatency"s, 1},
640 {"surfaces"s, 1},
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},
647 },
648 {}, // SDR-specific options
649 {}, // HDR-specific options
650 {}, // YUV444 SDR-specific options
651 {}, // YUV444 HDR-specific options
652 {}, // Fallback options
653 "av1_nvenc"s,
654 },
655 {
656 // Common options
657 {
658 {"delay"s, 0},
659 {"forced-idr"s, 1},
660 {"zerolatency"s, 1},
661 {"surfaces"s, 1},
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},
668 },
669 {
670 // SDR-specific options
671 {"profile"s, (int) nv::profile_hevc_e::main},
672 },
673 {
674 // HDR-specific options
675 {"profile"s, (int) nv::profile_hevc_e::main_10},
676 },
677 {}, // YUV444 SDR-specific options
678 {}, // YUV444 HDR-specific options
679 {}, // Fallback options
680 "hevc_nvenc"s,
681 },
682 {
683 {
684 {"delay"s, 0},
685 {"forced-idr"s, 1},
686 {"zerolatency"s, 1},
687 {"surfaces"s, 1},
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},
695 },
696 {
697 // SDR-specific options
698 {"profile"s, (int) nv::profile_h264_e::high},
699 },
700 {}, // HDR-specific options
701 {}, // YUV444 SDR-specific options
702 {}, // YUV444 HDR-specific options
703 {}, // Fallback options
704 "h264_nvenc"s,
705 },
707 };
708
709
710 encoder_t software {
711 "software"sv,
712 std::make_unique<encoder_platform_formats_avcodec>(
713 AV_HWDEVICE_TYPE_NONE,
714 AV_HWDEVICE_TYPE_NONE,
715 AV_PIX_FMT_NONE,
716 AV_PIX_FMT_YUV420P,
717 AV_PIX_FMT_YUV420P10,
718 AV_PIX_FMT_YUV444P,
719 AV_PIX_FMT_YUV444P10,
720 nullptr
721 ),
722 {
723 // libsvtav1 takes different presets than libx264/libx265.
724 // We set an infinite GOP length, use a low delay prediction structure,
725 // force I frames to be key frames, and set max bitrate to default to work
726 // around a FFmpeg bug with CBR mode.
727 {
728 {"svtav1-params"s, "keyint=-1:pred-struct=1:force-key-frames=1:mbr=0"s},
729 {"preset"s, &config::video.sw.svtav1_preset},
730 },
731 {}, // SDR-specific options
732 {}, // HDR-specific options
733 {}, // YUV444 SDR-specific options
734 {}, // YUV444 HDR-specific options
735 {}, // Fallback options
736
737#ifdef ENABLE_BROKEN_AV1_ENCODER
738 // Due to bugs preventing on-demand IDR frames from working and very poor
739 // real-time encoding performance, we do not enable libsvtav1 by default.
740 // It is only suitable for testing AV1 until the IDR frame issue is fixed.
741 "libsvtav1"s,
742#else
743 {},
744#endif
745 },
746 {
747 // x265's Info SEI is so long that it causes the IDR picture data to be
748 // kicked to the 2nd packet in the frame, breaking Moonlight's parsing logic.
749 // It also looks like gop_size isn't passed on to x265, so we have to set
750 // 'keyint=-1' in the parameters ourselves.
751 {
752 {"forced-idr"s, 1},
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},
756 },
757 {}, // SDR-specific options
758 {}, // HDR-specific options
759 {}, // YUV444 SDR-specific options
760 {}, // YUV444 HDR-specific options
761 {}, // Fallback options
762 "libx265"s,
763 },
764 {
765 // Common options
766 {
767 {"preset"s, &config::video.sw.sw_preset},
768 {"tune"s, &config::video.sw.sw_tune},
769 },
770 {}, // SDR-specific options
771 {}, // HDR-specific options
772 {}, // YUV444 SDR-specific options
773 {}, // YUV444 HDR-specific options
774 {}, // Fallback options
775 "libx264"s,
776 },
778 };
779
780 encoder_t vaapi {
781 "vaapi"sv,
782 std::make_unique<encoder_platform_formats_avcodec>(
783 AV_HWDEVICE_TYPE_VAAPI,
784 AV_HWDEVICE_TYPE_NONE,
785 AV_PIX_FMT_VAAPI,
786 AV_PIX_FMT_NV12,
787 AV_PIX_FMT_P010,
788 AV_PIX_FMT_NONE,
789 AV_PIX_FMT_NONE,
790 vaapi_init_avcodec_hardware_input_buffer
791 ),
792 {
793 // Common options
794 {
795 {"async_depth"s, 1},
796 {"idr_interval"s, std::numeric_limits<int>::max()},
797 },
798 {}, // SDR-specific options
799 {}, // HDR-specific options
800 {}, // YUV444 SDR-specific options
801 {}, // YUV444 HDR-specific options
802 {}, // Fallback options
803 "av1_vaapi"s,
804 },
805 {
806 // Common options
807 {
808 {"async_depth"s, 1},
809 {"sei"s, 0},
810 {"idr_interval"s, std::numeric_limits<int>::max()},
811 },
812 {}, // SDR-specific options
813 {}, // HDR-specific options
814 {}, // YUV444 SDR-specific options
815 {}, // YUV444 HDR-specific options
816 {}, // Fallback options
817 "hevc_vaapi"s,
818 },
819 {
820 // Common options
821 {
822 {"async_depth"s, 1},
823 {"sei"s, 0},
824 {"idr_interval"s, std::numeric_limits<int>::max()},
825 },
826 {}, // SDR-specific options
827 {}, // HDR-specific options
828 {}, // YUV444 SDR-specific options
829 {}, // YUV444 HDR-specific options
830 {}, // Fallback options
831 "h264_vaapi"s,
832 },
834 };
835
836
837 static const std::vector<encoder_t *> encoders {
838 &nvenc,
839 &vaapi,
840 &software
841 };
842
843 static encoder_t *chosen_encoder;
844 int active_hevc_mode;
845 int active_av1_mode;
846
847 // Last encoder probe result, for the diagnostics endpoint. Written at the end
848 // of probe_encoders(); read via get_encoder_status() under its own mutex.
849 static std::mutex encoder_status_mutex;
850 static encoder_status_t encoder_status_state;
851
853 std::lock_guard lg {encoder_status_mutex};
854 return encoder_status_state;
855 }
856
857 // Live per-frame pipeline metrics. Accumulated over a window and averaged so
858 // the diagnostics endpoint can show where per-frame time goes.
859 static std::mutex pipeline_metrics_mutex;
861 double encode_ms_sum = 0.0;
862 double capture_to_encode_ms_sum = 0.0;
863 uint64_t window_frames = 0;
864 uint64_t window_bytes = 0;
865 uint64_t frames_encoded = 0;
866 uint64_t frames_dropped = 0;
867 int width = 0;
868 int height = 0;
869 std::chrono::steady_clock::time_point window_start = std::chrono::steady_clock::now();
871 };
872 static pipeline_metrics_accum_t pipeline_metrics_state;
873
874 void metrics_record_frame(double encode_ms, double capture_to_encode_ms, size_t packet_bytes) {
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;
880 s.window_frames++;
881 s.frames_encoded++;
882
883 // Recompute the published averages roughly once per second.
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;
898 s.window_bytes = 0;
899 s.window_frames = 0;
900 s.window_start = now;
901 }
902 }
903
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;
908 }
909
911 std::lock_guard lg {pipeline_metrics_mutex};
912 pipeline_metrics_state = pipeline_metrics_accum_t {};
913 }
914
915 void metrics_set_resolution(int width, int height) {
916 std::lock_guard lg {pipeline_metrics_mutex};
917 auto &s = pipeline_metrics_state;
918 s.width = width;
919 s.height = height;
920 // Publish immediately so diagnostics can report the resolution even before
921 // the first averaging window completes.
922 s.published.width = width;
923 s.published.height = height;
924 }
925
927 std::lock_guard lg {pipeline_metrics_mutex};
928 return pipeline_metrics_state.published;
929 }
930 namespace {
932 bool vaapi_intra_refresh_requested() {
933 return config::video.vaapi.intra_refresh;
934 }
935
937 bool probe_saw_intra_refresh = false;
938 } // namespace
939
940 bool last_encoder_probe_supported_ref_frames_invalidation = false;
941 std::array<bool, 3> last_encoder_probe_supported_yuv444_for_codec = {
942 true,
943 true,
944 true
945 };
946
947 // Set only for the duration of probe_encoders_without_display().
948 bool probe_without_display = false;
949
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) {
952 disp = platf::encoder_probe_display(type, config);
953 return;
954 }
955 // We try this twice, in case we still get an error on reinitialization
956 for (int x = 0; x < 2; ++x) {
957 disp.reset();
958 disp = platf::display(type, display_name, config);
959 if (disp) {
960 break;
961 }
962
963 // The capture code depends on us to sleep between failures
964 std::this_thread::sleep_for(200ms);
965 }
966 }
967
975 void refresh_displays(platf::mem_type_e dev_type, std::vector<std::string> &display_names, int &current_display_index, std::string &preferred_display_name) {
976 // It is possible that the output name may be empty even if it wasn't before (device disconnected) or vice-versa
977 const auto output_name { display_device::map_output_name(config::video.output_name) };
978 std::string current_display_name = preferred_display_name;
979
980 // If we have a current display index, let's start with that
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);
983 }
984
985 // Refresh the display names
986 auto old_display_names = std::move(display_names);
987 display_names = platf::display_names(dev_type);
988
989 // If we now have no displays, let's put the old display array back and fail
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);
993 return;
994 } else if (display_names.empty()) {
995 display_names.emplace_back(output_name);
996 }
997
998 // We now have a new display name list, so reset the index back to 0
999 current_display_index = 0;
1000
1001 if (current_display_name.empty()) {
1002 current_display_name = display_device::map_output_name(config::video.output_name);
1003 }
1004
1005 // If we had a name previously, let's try to find it in the new list
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;
1010 return;
1011 }
1012 }
1013
1014 // The old display was removed, so we'll start back at the first display again
1015 BOOST_LOG(warning) << "Previous active display ["sv << current_display_name << "] is no longer present"sv;
1016 } else {
1017 for (int x = 0; x < display_names.size(); ++x) {
1018 if (display_names[x] == output_name) {
1019 current_display_index = x;
1020 return;
1021 }
1022 }
1023 }
1024 }
1025
1026 void refresh_displays(platf::mem_type_e dev_type, std::vector<std::string> &display_names, int &current_display_index) {
1027 static std::string empty_str = "";
1028 refresh_displays(dev_type, display_names, current_display_index, empty_str);
1029 }
1030
1031 void captureThread(
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,
1035 const encoder_t &encoder
1036 ) {
1037 std::vector<capture_ctx_t> capture_ctxs;
1038
1039 auto fg = util::fail_guard([&]() {
1040 capture_ctx_queue->stop();
1041
1042 // Stop all sessions listening to this thread
1043 for (auto &capture_ctx : capture_ctxs) {
1044 capture_ctx.images->stop();
1045 }
1046 for (auto &capture_ctx : capture_ctx_queue->unsafe()) {
1047 capture_ctx.images->stop();
1048 }
1049 });
1050
1051 auto switch_display_event = mail::man->event<int>(mail::switch_display);
1052
1053 // Wait for the initial capture context or a request to stop the queue
1054 auto initial_capture_ctx = capture_ctx_queue->pop();
1055 if (!initial_capture_ctx) {
1056 return;
1057 }
1058 capture_ctxs.emplace_back(std::move(*initial_capture_ctx));
1059
1060 std::vector<std::string> display_names;
1061 int display_p = -1;
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;
1071 return;
1072 }
1073 }
1074 if (!disp) {
1075 // Get all the monitor names now, rather than at boot, to
1076 // get the most up-to-date list available monitors
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);
1079 if (disp) {
1080 capture_display_name = display_names[display_p];
1081 proc::proc.display_name = capture_display_name;
1082 } else {
1083 return;
1084 }
1085 }
1086
1087 display_wp = disp;
1088
1089 constexpr auto capture_buffer_size = 12;
1090 std::list<std::shared_ptr<platf::img_t>> imgs(capture_buffer_size);
1091
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 = [&]() {
1095 // count allocated and used within current pool
1096 size_t allocated_count = 0;
1097 size_t used_count = 0;
1098 for (const auto &img : imgs) {
1099 if (img) {
1100 allocated_count += 1;
1101 if (img.use_count() > 1) {
1102 used_count += 1;
1103 }
1104 }
1105 }
1106
1107 // remember the timestamp of currently used count
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);
1111 }
1112 imgs_used_timestamps[used_count] = now;
1113
1114 // decide whether to trim allocated unused above the currently used count
1115 // based on last used timestamp and universal timeout
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) {
1119 trim_target = i;
1120 }
1121 }
1122
1123 // trim allocated unused above the newly decided trim target
1124 if (allocated_count > trim_target) {
1125 size_t to_trim = allocated_count - trim_target;
1126 // prioritize trimming least recently used
1127 for (auto it = imgs.rbegin(); it != imgs.rend(); it++) {
1128 auto &img = *it;
1129 if (img && img.use_count() == 1) {
1130 img.reset();
1131 to_trim -= 1;
1132 if (to_trim == 0) {
1133 break;
1134 }
1135 }
1136 }
1137 // forget timestamps that no longer relevant
1138 imgs_used_timestamps.resize(trim_target + 1);
1139 }
1140 };
1141
1142 auto pull_free_image_callback = [&](std::shared_ptr<platf::img_t> &img_out) -> bool {
1143 img_out.reset();
1144 while (capture_ctx_queue->running()) {
1145 // pick first allocated but unused
1146 for (auto it = imgs.begin(); it != imgs.end(); it++) {
1147 if (*it && it->use_count() == 1) {
1148 img_out = *it;
1149 if (it != imgs.begin()) {
1150 // move image to the front of the list to prioritize its reusal
1151 imgs.erase(it);
1152 imgs.push_front(img_out);
1153 }
1154 break;
1155 }
1156 }
1157 // otherwise pick first unallocated
1158 if (!img_out) {
1159 for (auto it = imgs.begin(); it != imgs.end(); it++) {
1160 if (!*it) {
1161 // allocate image
1162 *it = disp->alloc_img();
1163 img_out = *it;
1164 if (it != imgs.begin()) {
1165 // move image to the front of the list to prioritize its reusal
1166 imgs.erase(it);
1167 imgs.push_front(img_out);
1168 }
1169 break;
1170 }
1171 }
1172 }
1173 if (img_out) {
1174 // trim allocated but unused portion of the pool based on timeouts
1175 trim_imgs();
1176 img_out->frame_timestamp.reset();
1177 return true;
1178 } else {
1179 // sleep and retry if image pool is full
1180 std::this_thread::sleep_for(1ms);
1181 }
1182 }
1183 return false;
1184 };
1185
1186 // Capture takes place on this thread
1187 platf::adjust_thread_priority(platf::thread_priority_e::critical);
1188
1189 while (capture_ctx_queue->running()) {
1190 bool artificial_reinit = false;
1191
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);
1196
1197 continue;
1198 }
1199
1200 if (frame_captured) {
1201 capture_ctx->images->raise(img);
1202 }
1203
1204 ++capture_ctx;
1205 })
1206
1207 if (!capture_ctx_queue->running()) {
1208 return false;
1209 }
1210
1211 while (capture_ctx_queue->peek()) {
1212 capture_ctxs.emplace_back(std::move(*capture_ctx_queue->pop()));
1213 }
1214
1215 if (!session_scoped_display && switch_display_event->peek()) {
1216 artificial_reinit = true;
1217 return false;
1218 }
1219
1220 return true;
1221 };
1222
1223 auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &display_cursor);
1224
1225 if (artificial_reinit && status != platf::capture_e::error) {
1226 status = platf::capture_e::reinit;
1227
1228 artificial_reinit = false;
1229 }
1230
1231 switch (status) {
1232 case platf::capture_e::reinit:
1233 {
1234 reinit_event.raise(true);
1235
1236 // Some classes of images contain references to the display --> display won't delete unless img is deleted
1237 for (auto &img : imgs) {
1238 img.reset();
1239 }
1240
1241 // display_wp is modified in this thread only
1242 // Wait for the other shared_ptr's of display to be destroyed.
1243 // New displays will only be created in this thread.
1244 while (display_wp->use_count() != 1) {
1245 // Free images that weren't consumed by the encoders. These can reference the display and prevent
1246 // the ref count from reaching 1. We do this here rather than on the encoder thread to avoid race
1247 // conditions where the encoding loop might free a good frame after reinitializing if we capture
1248 // a new frame here before the encoder has finished reinitializing.
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);
1252 continue;
1253 }
1254
1255 while (capture_ctx->images->peek()) {
1256 capture_ctx->images->pop();
1257 }
1258
1259 ++capture_ctx;
1260 });
1261
1262 std::this_thread::sleep_for(20ms);
1263 }
1264
1265 while (capture_ctx_queue->running()) {
1266 // Release the display before reenumerating displays, since some capture backends
1267 // only support a single display session per device/application.
1268 disp.reset();
1269
1270 // Refresh display names since a display removal might have caused the reinitialization
1271 if (!session_scoped_display) {
1272 refresh_displays(encoder.platform_formats->dev_type, display_names, display_p, proc::proc.display_name);
1273
1274 // Process any pending display switch with the new list of displays
1275 if (switch_display_event->peek()) {
1276 display_p = std::clamp(*switch_display_event->pop(), 0, (int) display_names.size() - 1);
1277 }
1278 capture_display_name = display_names[display_p];
1279 }
1280
1281 // reset_display() will sleep between retries
1282 reset_display(disp, encoder.platform_formats->dev_type, capture_display_name, capture_ctxs.front().config);
1283 if (disp) {
1284 if (!session_scoped_display) {
1285 proc::proc.display_name = capture_display_name;
1286 }
1287 break;
1288 }
1289 }
1290 if (!disp) {
1291 return;
1292 }
1293
1294 display_wp = disp;
1295
1296 reinit_event.reset();
1297 continue;
1298 }
1299 case platf::capture_e::error:
1300 case platf::capture_e::ok:
1301 case platf::capture_e::timeout:
1302 case platf::capture_e::interrupted:
1303 return;
1304 default:
1305 BOOST_LOG(error) << "Unrecognized capture status ["sv << (int) status << ']';
1306 return;
1307 }
1308 }
1309 }
1310
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;
1314
1315 auto &ctx = session.avcodec_ctx;
1316
1317 auto &sps = session.sps;
1318 auto &vps = session.vps;
1319
1320 // Measure encode time and capture->encode latency for the metrics endpoint.
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;
1326 }
1327
1328 // send the frame to the encoder
1329 auto ret = avcodec_send_frame(ctx.get(), frame);
1330 if (ret < 0) {
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);
1333
1335 return -1;
1336 }
1337 session.frame_submitted = true;
1338
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)
1343 .count();
1344 metrics_record_frame(encode_ms, capture_to_encode_ms, packet_bytes);
1345 };
1346
1347 while (ret >= 0) {
1348 auto packet = std::make_unique<packet_raw_avcodec>();
1349 auto av_packet = packet.get()->av_packet;
1350
1351 ret = avcodec_receive_packet(ctx.get(), av_packet);
1352 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
1353 record_frame_metrics();
1354 return 0;
1355 } else if (ret < 0) {
1356 return ret;
1357 }
1358
1359 // In CBR, radeonsi pads H.264 and HEVC frames with filler data up to the
1360 // target bitrate: a still screen would stream at the full bitrate. The
1361 // decoder discards filler, so remove it before anything reads the frame.
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);
1366 const auto stripped = annexb::strip_filler_data(av_packet->data, size, codec);
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;
1371 }
1372 av_shrink_packet(av_packet, static_cast<int>(stripped));
1373 }
1374 }
1375
1376 if (av_packet) {
1377 packet_bytes += static_cast<size_t>(av_packet->size > 0 ? av_packet->size : 0);
1378 }
1379
1380 if (av_packet->flags & AV_PKT_FLAG_KEY) {
1381 BOOST_LOG(debug) << "Frame "sv << frame_nr << ": IDR Keyframe (AV_FRAME_FLAG_KEY)"sv;
1382 }
1383
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;
1386 }
1387
1388 if (session.inject) {
1389 if (session.inject == 1) {
1390 auto h264 = cbs::make_sps_h264(ctx.get(), av_packet);
1391
1392 sps = std::move(h264.sps);
1393 } else {
1394 auto hevc = cbs::make_sps_hevc(ctx.get(), av_packet);
1395
1396 sps = std::move(hevc.sps);
1397 vps = std::move(hevc.vps);
1398
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())
1402 );
1403 }
1404
1405 session.inject = 0;
1406
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())
1410 );
1411 }
1412
1413 if (av_packet && av_packet->pts == frame_nr) {
1414 packet->frame_timestamp = frame_timestamp;
1415 }
1416
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;
1420 }
1421 session.next_after_invalidation = false;
1422 }
1423
1424 packet->replacements = &session.replacements;
1425 packet->channel_data = channel_data;
1426 packets->raise(std::move(packet));
1427 }
1428
1429 record_frame_metrics();
1430 return 0;
1431 }
1432
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;
1439 }
1440
1441 auto encoded_frame = session.encode_frame(frame_nr);
1442 if (encoded_frame.data.empty()) {
1443 BOOST_LOG(error) << "NvENC returned empty packet";
1445 return -1;
1446 }
1447
1448 if (frame_nr != encoded_frame.frame_index) {
1449 BOOST_LOG(error) << "NvENC frame index mismatch " << frame_nr << " " << encoded_frame.frame_index;
1450 }
1451
1452 // Capture the encoded size before the buffer is moved into the packet.
1453 const size_t packet_bytes = encoded_frame.data.size();
1454
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));
1460
1461 const auto encode_ms = std::chrono::duration<double, std::milli>(
1462 std::chrono::steady_clock::now() - encode_start)
1463 .count();
1464 metrics_record_frame(encode_ms, capture_to_encode_ms, packet_bytes);
1465
1466 return 0;
1467 }
1468
1469#ifdef HAVE_PYROWAVE
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;
1476 }
1477
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;
1484 }
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);
1489 }
1490
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);
1497 }
1498
1499 const pyrowave_rate_control rate_control {session.maximum_frame_bytes};
1500 pyrowave_result encoded;
1501 // The planes' semaphore may only be released once the encode that waits
1502 // on it has finished, which packetization below waits for.
1503 auto release_planes = util::fail_guard([&session]() {
1504 if (session.gpu) {
1505 session.gpu.device->encoded();
1506 }
1507 });
1508 if (session.gpu) {
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;
1515 return 0;
1516 }
1517 encoded = pyrowave_encoder_encode_gpu_synchronous(session.pyrowave_encoder_handle, acquire, release, &buffers, &rate_control);
1518 } else
1519 {
1520 encoded = encode_pyrowave_cpu(session, rate_control);
1521 }
1522 if (!pyrowave_succeeded(encoded, "frame encode"sv)) {
1524 return -1;
1525 }
1526
1527 // One packet for the whole frame: the stream layer splits it for the
1528 // network and protects it with FEC like any other codec's frame.
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) {
1532 return -1;
1533 }
1534
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()) {
1539 return -1;
1540 }
1541
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;
1547 return -1;
1548 }
1549
1550 // Every PyroWave frame is intra, so every frame is a key frame.
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)),
1553 frame_nr,
1554 true
1555 );
1556 packet->channel_data = channel_data;
1557 packet->frame_timestamp = frame_timestamp;
1558 packets->raise(std::move(packet));
1559
1560 const auto encode_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - encode_start).count();
1561 metrics_record_frame(encode_ms, capture_to_encode_ms, encoded_size);
1562 return 0;
1563 }
1564#endif
1565
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) {
1567 if (auto avcodec_session = dynamic_cast<avcodec_encode_session_t *>(&session)) {
1568 return encode_avcodec(frame_nr, *avcodec_session, packets, channel_data, frame_timestamp);
1569 } else if (auto nvenc_session = dynamic_cast<nvenc_encode_session_t *>(&session)) {
1570 return encode_nvenc(frame_nr, *nvenc_session, packets, channel_data, frame_timestamp);
1571#ifdef HAVE_PYROWAVE
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);
1574#endif
1575 }
1576
1577 return -1;
1578 }
1579
1580 std::unique_ptr<avcodec_encode_session_t> make_avcodec_encode_session(
1581 platf::display_t *disp,
1582 const encoder_t &encoder,
1583 const config_t &config,
1584 int width,
1585 int height,
1586 std::unique_ptr<platf::avcodec_encode_device_t> encode_device
1587 ) {
1588 auto platform_formats = dynamic_cast<const encoder_platform_formats_avcodec *>(encoder.platform_formats.get());
1589 if (!platform_formats) {
1590 return nullptr;
1591 }
1592
1593 bool hardware = platform_formats->avcodec_base_dev_type != AV_HWDEVICE_TYPE_NONE;
1594
1595 auto &video_format = encoder.codec_from_config(config);
1596 if (!video_format[encoder_t::PASSED] || !disp->is_codec_supported(video_format.name, config)) {
1597 BOOST_LOG(error) << encoder.name << ": "sv << video_format.name << " mode not supported"sv;
1598 return nullptr;
1599 }
1600
1601 if (config.dynamicRange && !video_format[encoder_t::DYNAMIC_RANGE]) {
1602 BOOST_LOG(error) << video_format.name << ": dynamic range not supported"sv;
1603 return nullptr;
1604 }
1605
1606 if (config.chromaSamplingType == 1 && !video_format[encoder_t::YUV444]) {
1607 BOOST_LOG(error) << video_format.name << ": YUV 4:4:4 not supported"sv;
1608 return nullptr;
1609 }
1610
1611 auto codec = avcodec_find_encoder_by_name(video_format.name.c_str());
1612 if (!codec) {
1613 BOOST_LOG(error) << "Couldn't open ["sv << video_format.name << ']';
1614
1615 return nullptr;
1616 }
1617
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 :
1623 AV_PIX_FMT_NONE;
1624
1625 // Allow up to 1 retry to apply the set of fallback options.
1626 //
1627 // Note: If we later end up needing multiple sets of
1628 // fallback options, we may need to allow more retries
1629 // to try applying each set.
1630 avcodec_ctx_t ctx;
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};
1637
1638 switch (config.videoFormat) {
1639 case 0:
1640 // 10-bit h264 encoding is not supported by our streaming protocol
1641 assert(!config.dynamicRange);
1642 ctx->profile = (config.chromaSamplingType == 1) ? AV_PROFILE_H264_HIGH_444_PREDICTIVE : AV_PROFILE_H264_HIGH;
1643 break;
1644
1645 case 1:
1646 if (config.chromaSamplingType == 1) {
1647 // HEVC uses the same RExt profile for both 8 and 10 bit YUV 4:4:4 encoding
1648 ctx->profile = AV_PROFILE_HEVC_REXT;
1649 } else {
1650 ctx->profile = config.dynamicRange ? AV_PROFILE_HEVC_MAIN_10 : AV_PROFILE_HEVC_MAIN;
1651 }
1652 break;
1653
1654 case 2:
1655 // AV1 supports both 8 and 10 bit encoding with the same Main profile
1656 // but YUV 4:4:4 sampling requires High profile
1657 ctx->profile = (config.chromaSamplingType == 1) ? AV_PROFILE_AV1_HIGH : AV_PROFILE_AV1_MAIN;
1658 break;
1659 }
1660
1661 // B-frames delay decoder output, so never use them
1662 ctx->max_b_frames = 0;
1663
1664 // Use an infinite GOP length since I-frames are generated on demand
1665 ctx->gop_size = encoder.flags & LIMITED_GOP_SIZE ?
1666 std::numeric_limits<std::int16_t>::max() :
1667 std::numeric_limits<int>::max();
1668
1669 ctx->keyint_min = std::numeric_limits<int>::max();
1670
1671 // Some client decoders have limits on the number of reference frames
1672 if (config.numRefFrames) {
1673 if (video_format[encoder_t::REF_FRAMES_RESTRICT]) {
1674 ctx->refs = config.numRefFrames;
1675 } else {
1676 BOOST_LOG(warning) << "Client requested reference frame limit, but encoder doesn't support it!"sv;
1677 }
1678 }
1679
1680 // We forcefully reset the flags to avoid clash on reuse of AVCodecContext
1681 ctx->flags = 0;
1682 ctx->flags |= AV_CODEC_FLAG_CLOSED_GOP | AV_CODEC_FLAG_LOW_DELAY;
1683
1684 ctx->flags2 |= AV_CODEC_FLAG2_FAST;
1685
1686 auto avcodec_colorspace = avcodec_colorspace_from_sunshine_colorspace(colorspace);
1687
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;
1692
1693 // Used by cbs::make_sps_hevc
1694 ctx->sw_pix_fmt = sw_fmt;
1695
1696 if (hardware) {
1697 avcodec_buffer_t encoding_stream_context;
1698
1699 ctx->pix_fmt = platform_formats->avcodec_dev_pix_fmt;
1700
1701 // Create the base hwdevice context
1702 auto buf_or_error = platform_formats->init_avcodec_hardware_input_buffer(encode_device.get());
1703 if (buf_or_error.has_right()) {
1704 return nullptr;
1705 }
1706 encoding_stream_context = std::move(buf_or_error.left());
1707
1708 // If this encoder requires derivation from the base, derive the desired type
1709 if (platform_formats->avcodec_derived_dev_type != AV_HWDEVICE_TYPE_NONE) {
1710 avcodec_buffer_t derived_context;
1711
1712 // Allow the hwdevice to prepare for this type of context to be derived
1713 if (encode_device->prepare_to_derive_context(platform_formats->avcodec_derived_dev_type)) {
1714 return nullptr;
1715 }
1716
1717 auto err = av_hwdevice_ctx_create_derived(&derived_context, platform_formats->avcodec_derived_dev_type, encoding_stream_context.get(), 0);
1718 if (err) {
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);
1721
1722 return nullptr;
1723 }
1724
1725 encoding_stream_context = std::move(derived_context);
1726 }
1727
1728 // Initialize avcodec hardware frames
1729 {
1730 avcodec_buffer_t frame_ref {av_hwframe_ctx_alloc(encoding_stream_context.get())};
1731
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;
1738
1739 // Allow the hwdevice to modify hwframe context parameters
1740 encode_device->init_hwframes(frame_ctx);
1741
1742 if (auto err = av_hwframe_ctx_init(frame_ref.get()); err < 0) {
1743 return nullptr;
1744 }
1745
1746 ctx->hw_frames_ctx = av_buffer_ref(frame_ref.get());
1747 }
1748
1749 ctx->slices = config.slicesPerFrame;
1750 } else /* software */ {
1751 ctx->pix_fmt = sw_fmt;
1752
1753 // Clients will request for the fewest slices per frame to get the
1754 // most efficient encode, but we may want to provide more slices than
1755 // requested to ensure we have enough parallelism for good performance.
1756 ctx->slices = std::max(config.slicesPerFrame, config::video.min_threads);
1757 }
1758
1759 if (encoder.flags & SINGLE_SLICE_ONLY) {
1760 ctx->slices = 1;
1761 }
1762
1763 ctx->thread_type = FF_THREAD_SLICE;
1764 ctx->thread_count = ctx->slices;
1765
1766 AVDictionary *options {nullptr};
1767 auto handle_option = [&options, &config](const encoder_t::option_t &option) {
1768 std::visit(
1769 util::overloaded {
1770 [&](int v) {
1771 av_dict_set_int(&options, option.name.c_str(), v, 0);
1772 },
1773 [&](int *v) {
1774 av_dict_set_int(&options, option.name.c_str(), *v, 0);
1775 },
1776 [&](std::optional<int> *v) {
1777 if (*v) {
1778 av_dict_set_int(&options, option.name.c_str(), **v, 0);
1779 }
1780 },
1781 [&](const std::function<int()> &v) {
1782 av_dict_set_int(&options, option.name.c_str(), v(), 0);
1783 },
1784 [&](const std::string &v) {
1785 av_dict_set(&options, option.name.c_str(), v.c_str(), 0);
1786 },
1787 [&](std::string *v) {
1788 if (!v->empty()) {
1789 av_dict_set(&options, option.name.c_str(), v->c_str(), 0);
1790 }
1791 },
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);
1794 }
1795 },
1796 option.value
1797 );
1798 };
1799
1800 // Apply common options, then format-specific overrides
1801 for (auto &option : video_format.common_options) {
1802 handle_option(option);
1803 }
1804 for (auto &option : (config.dynamicRange ? video_format.hdr_options : video_format.sdr_options)) {
1805 handle_option(option);
1806 }
1807 if (config::video.vaapi.quality >= 0 && encoder.name == "vaapi") {
1808 av_dict_set_int(&options, "quality", config::video.vaapi.quality, 0);
1809 }
1810 if (config.chromaSamplingType == 1) {
1811 for (auto &option : (config.dynamicRange ? video_format.hdr444_options : video_format.sdr444_options)) {
1812 handle_option(option);
1813 }
1814 }
1815 if (retries > 0) {
1816 for (auto &option : video_format.fallback_options) {
1817 handle_option(option);
1818 }
1819 }
1820
1821 auto bitrate = config.bitrate * 1000;
1822 ctx->rc_max_rate = bitrate;
1823 ctx->bit_rate = bitrate;
1824
1825 if (encoder.flags & CBR_WITH_VBR) {
1826 // Ensure rc_max_bitrate != bit_rate to force VBR mode
1827 ctx->bit_rate--;
1828 } else {
1829 ctx->rc_min_rate = bitrate;
1830 }
1831
1832 if (encoder.flags & RELAXED_COMPLIANCE) {
1833 ctx->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
1834 }
1835
1836 if (!(encoder.flags & NO_RC_BUF_LIMIT)) {
1837 if (!hardware && (ctx->slices > 1 || config.videoFormat == 1)) {
1838 // Use a larger rc_buffer_size for software encoding when slices are enabled,
1839 // because libx264 can severely degrade quality if the buffer is too small.
1840 // libx265 encounters this issue more frequently, so always scale the
1841 // buffer by 1.5x for software HEVC encoding.
1842 ctx->rc_buffer_size = bitrate / ((config.framerate * 10) / 15);
1843 } else {
1844 ctx->rc_buffer_size = bitrate / config.framerate;
1845
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;
1848 }
1849 }
1850 }
1851
1852 // Rolling intra refresh lets a client recover from a lost frame
1853 // without a key frame (see invalidate_ref_frames()). It needs an
1854 // FFmpeg whose VAAPI encoders have the option; others ignore it.
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);
1857 }
1858
1859 // Allow the encoding device a final opportunity to set/unset or override any options
1860 encode_device->init_codec_options(ctx.get(), &options);
1861
1862 if (auto status = avcodec_open2(ctx.get(), codec, &options)) {
1863 char err_str[AV_ERROR_MAX_STRING_SIZE] {0};
1864
1865 if (!video_format.fallback_options.empty() && retries == 0) {
1866 BOOST_LOG(info)
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);
1869
1870 continue;
1871 } else {
1872 BOOST_LOG(error)
1873 << "Could not open codec ["sv
1874 << video_format.name << "]: "sv
1875 << av_make_error_string(err_str, AV_ERROR_MAX_STRING_SIZE, status);
1876
1877 return nullptr;
1878 }
1879 }
1880
1881 // Successfully opened the codec
1882 break;
1883 }
1884
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;
1894
1895 // Attach HDR metadata to the AVFrame
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());
1900
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);
1907
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);
1910
1911 mdm->min_luminance = av_make_q(hdr_metadata.minDisplayLuminance, 10000);
1912 mdm->max_luminance = av_make_q(hdr_metadata.maxDisplayLuminance, 1);
1913
1914 mdm->has_luminance = hdr_metadata.maxDisplayLuminance != 0 ? 1 : 0;
1915 mdm->has_primaries = hdr_metadata.displayPrimaries[0].x != 0 ? 1 : 0;
1916
1917 if (hdr_metadata.maxContentLightLevel != 0 || hdr_metadata.maxFrameAverageLightLevel != 0) {
1918 auto clm = av_content_light_metadata_create_side_data(frame.get());
1919
1920 clm->MaxCLL = hdr_metadata.maxContentLightLevel;
1921 clm->MaxFALL = hdr_metadata.maxFrameAverageLightLevel;
1922 }
1923 } else {
1924 BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one";
1925 }
1926 }
1927
1928 std::unique_ptr<platf::avcodec_encode_device_t> encode_device_final;
1929
1930 if (!encode_device->data) {
1931 auto software_encode_device = std::make_unique<avcodec_software_encode_device_t>();
1932
1933 if (software_encode_device->init(width, height, frame.get(), sw_fmt, hardware)) {
1934 return nullptr;
1935 }
1936 software_encode_device->colorspace = colorspace;
1937
1938 encode_device_final = std::move(software_encode_device);
1939 } else {
1940 encode_device_final = std::move(encode_device);
1941 }
1942
1943 if (encode_device_final->set_frame(frame.release(), ctx->hw_frames_ctx)) {
1944 return nullptr;
1945 }
1946
1947 encode_device_final->apply_colorspace();
1948
1949 int64_t intra_refresh_frames = 0;
1950 if (encoder.name == "vaapi"sv && vaapi_intra_refresh_requested()) {
1951 // The patched encoder reads 0 back when the driver cannot do it.
1952 if (av_opt_get_int(ctx->priv_data, "intra_refresh", 0, &intra_refresh_frames) < 0) {
1953 intra_refresh_frames = 0;
1954 }
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;
1960 }
1961 } else if (!config.encoder_probe) {
1962 BOOST_LOG(warning) << "VAAPI intra refresh was requested, but this FFmpeg or driver cannot do it"sv;
1963 }
1964 }
1965
1966 auto session = std::make_unique<avcodec_encode_session_t>(
1967 std::move(ctx),
1968 std::move(encode_device_final),
1969
1970 // 0 ==> don't inject, 1 ==> inject for h264, 2 ==> inject for hevc
1971 config.videoFormat <= 1 ? (1 - (int) video_format[encoder_t::VUI_PARAMETERS]) * (1 + config.videoFormat) : 0
1972 );
1973 session->intra_refresh_frames = static_cast<int>(intra_refresh_frames);
1974
1975 return session;
1976 }
1977
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)) {
1980 return nullptr;
1981 }
1982
1983 return std::make_unique<nvenc_encode_session_t>(std::move(encode_device));
1984 }
1985
1986#ifdef HAVE_PYROWAVE
1987 std::unique_ptr<pyrowave_encode_session_t> make_pyrowave_encode_session(
1988 const config_t &config,
1989 int width,
1990 int height,
1991 std::unique_ptr<platf::avcodec_encode_device_t> encode_device
1992 ) {
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;
1995 return nullptr;
1996 }
1997
1998 auto colorspace = encode_device->colorspace;
1999 auto avcodec_colorspace = avcodec_colorspace_from_sunshine_colorspace(colorspace);
2000 avcodec_frame_t frame {av_frame_alloc()};
2001 if (!frame) {
2002 return nullptr;
2003 }
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;
2011
2012 pyrowave_gpu_source_t gpu;
2013 gpu.device = dynamic_cast<pyrowave::gpu_encode_device_t *>(encode_device.get());
2014
2015 std::unique_ptr<platf::avcodec_encode_device_t> conversion_device;
2016 if (gpu) {
2017 // The frame only carries the output size; the planes are the device's.
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)) {
2022 return nullptr;
2023 }
2024 software_device->colorspace = colorspace;
2025 conversion_device = std::move(software_device);
2026 } else {
2027 // A hardware encoder's device writes into its own surfaces, which the
2028 // CPU path cannot read.
2029 BOOST_LOG(error) << "PyroWave cannot take frames from this capture's hardware encode device"sv;
2030 return nullptr;
2031 }
2032
2033 if (conversion_device->set_frame(frame.release(), nullptr)) {
2034 return nullptr;
2035 }
2036 conversion_device->apply_colorspace();
2037
2038 // The GPU path must encode on the device its planes were imported into.
2039 pyrowave_device pyrowave_device_handle {};
2040 bool owns_device = false;
2041 if (gpu) {
2042 pyrowave_device_handle = gpu.device->device();
2043 }
2044 if (!pyrowave_device_handle) {
2045 if (!pyrowave_succeeded(pyrowave_create_default_device(&pyrowave_device_handle), "device creation"sv)) {
2046 return nullptr;
2047 }
2048 owns_device = true;
2049 // The game renders in another process; async compute keeps the encode
2050 // from queueing behind its graphics work.
2051 pyrowave_device_set_queue_type(pyrowave_device_handle, VK_QUEUE_COMPUTE_BIT);
2052 }
2053
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;
2059
2060 pyrowave_encoder pyrowave_encoder_handle {};
2061 if (!pyrowave_succeeded(pyrowave_encoder_create(&encoder_info, &pyrowave_encoder_handle), "encoder creation"sv)) {
2062 if (owns_device) {
2063 pyrowave_device_destroy(pyrowave_device_handle);
2064 }
2065 return nullptr;
2066 }
2067
2068 const size_t maximum_frame_bytes = pyrowave_frame_budget(config);
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),
2073 gpu,
2074 pyrowave_device_handle,
2075 owns_device,
2076 pyrowave_encoder_handle,
2077 maximum_frame_bytes
2078 );
2079 }
2080#endif
2081
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) {
2083#ifdef HAVE_PYROWAVE
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;
2088 return nullptr;
2089 }
2090 return make_pyrowave_encode_session(config, width, height, std::move(avcodec_encode_device));
2091 }
2092#endif
2093 if (dynamic_cast<platf::avcodec_encode_device_t *>(encode_device.get())) {
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));
2096 } else if (dynamic_cast<platf::nvenc_encode_device_t *>(encode_device.get())) {
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));
2099 }
2100
2101 return nullptr;
2102 }
2103
2104 void encode_run(
2105 int &frame_nr, // Store progress of the frame number
2106 safe::mail_t mail,
2107 img_event_t images,
2108 config_t config,
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,
2113 void *channel_data
2114 ) {
2115 auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device));
2116 if (!session) {
2117 return;
2118 }
2119
2120 // Record the stream resolution so diagnostics can report the real output
2121 // dimensions (the RTSP layer already reset the counters at session start).
2122 metrics_set_resolution(config.width, config.height);
2123
2124 // As a workaround for NVENC hangs and to generally speed up encoder reinit,
2125 // we will complete the encoder teardown in a separate thread if supported.
2126 // This will move expensive processing off the encoder thread to allow us
2127 // to restart encoding as soon as possible. For cases where the NVENC driver
2128 // hang occurs, this thread may probably never exit, but it will allow
2129 // streaming to continue without requiring a full restart of Sunshine.
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";
2134 session.reset();
2135 BOOST_LOG(info) << "Async encoder teardown complete";
2136 }};
2137 encoder_teardown_thread.detach();
2138 }
2139 });
2140
2141 // set max frame time based on client-requested target framerate.
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;
2149
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);
2154
2155 {
2156 // Load a dummy image into the AVFrame to ensure we have something to encode
2157 // even if we timeout waiting on the first frame. This is a relatively large
2158 // allocation which can be freed immediately after convert(), so we do this
2159 // in a separate scope.
2160 auto dummy_img = disp->alloc_img();
2161 if (!dummy_img || disp->dummy_img(dummy_img.get()) || session->convert(*dummy_img)) {
2162 return;
2163 }
2164 }
2165
2166 if (config.input_only) {
2167 BOOST_LOG(info) << "Input only session, video will not be captured."sv;
2168
2169 // Encode the dummy img only once
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;
2172 return;
2173 }
2174
2175 while (true) {
2176 if (shutdown_event->peek() || !images->running() || (reinit_event.peek())) {
2177 return;
2178 } else {
2179 std::this_thread::sleep_for(300ms);
2180 }
2181 }
2182 }
2183
2184 std::chrono::steady_clock::time_point encode_frame_timestamp;
2185 bool missing_frame_timestamp_warning_logged = false;
2186
2187 while (true) {
2188 // Break out of the encoding loop if any of the following are true:
2189 // a) The stream is ending
2190 // b) Sunshine is quitting
2191 // c) The capture side is waiting to reinit and we've encoded at least one frame
2192 //
2193 // If we have to reinit before we have received any captured frames, we will encode
2194 // the blank dummy frame just to let Moonlight know that we're alive.
2195 if (shutdown_event->peek() || !images->running() || (reinit_event.peek() && frame_nr > 1)) {
2196 break;
2197 }
2198
2199 bool requested_idr_frame = false;
2200
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);
2204 }
2205 }
2206
2207 if (idr_events->peek()) {
2208 requested_idr_frame = true;
2209 idr_events->pop();
2210 }
2211
2212 if (requested_idr_frame) {
2213 session->request_idr_frame();
2214 }
2215
2216 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
2217
2218 // Encode at a minimum FPS to avoid image quality issues with static content
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;
2226 }
2227 frame_timestamp = std::chrono::steady_clock::now();
2228 }
2229
2230 auto current_timestamp = *frame_timestamp;
2231 auto time_diff = current_timestamp - encode_frame_timestamp;
2232
2233 // If new frame comes in way too fast, just drop
2234 if (time_diff < -frame_variation_threshold) {
2235 continue;
2236 }
2237
2238 if (session->convert(*img)) {
2239 BOOST_LOG(error) << "Could not convert image"sv;
2240 break;
2241 }
2242
2243 if (time_diff < frame_variation_threshold) {
2244 *frame_timestamp = encode_frame_timestamp;
2245 } else {
2246 encode_frame_timestamp = current_timestamp;
2247 }
2248
2249 encode_frame_timestamp += encode_frame_threshold;
2250 } else if (!images->running()) {
2251 break;
2252 }
2253 }
2254
2255 if (encode(frame_nr++, *session, packets, channel_data, frame_timestamp)) {
2256 BOOST_LOG(error) << "Could not encode video packet"sv;
2257 break;
2258 }
2259
2260 session->request_normal_frame();
2261 }
2262 }
2263
2264 input::touch_port_t make_port(platf::display_t *display, const config_t &config) {
2265 float wd = display->width;
2266 float hd = display->height;
2267
2268 float wt = config.width;
2269 float ht = config.height;
2270
2271 auto scalar = std::fminf(wt / wd, ht / hd);
2272
2273 auto w2 = scalar * wd;
2274 auto h2 = scalar * hd;
2275
2276 auto offsetX = (config.width - w2) * 0.5f;
2277 auto offsetY = (config.height - h2) * 0.5f;
2278
2279 return input::touch_port_t {
2280 {
2281 display->offset_x,
2282 display->offset_y,
2283 config.width,
2284 config.height,
2285 },
2286 display->env_width,
2287 display->env_height,
2289 display->width,
2290 display->height,
2291 display->offset_x,
2292 display->offset_y,
2293 display->env_width,
2294 display->env_height,
2296 ),
2297 offsetX,
2298 offsetY,
2299 1.0f / scalar,
2300 };
2301 }
2302
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;
2305
2306 auto colorspace = colorspace_from_client_config(config, disp.is_hdr());
2307
2308 platf::pix_fmt_e pix_fmt;
2309 if (config.chromaSamplingType == 1) {
2310 // YUV 4:4:4
2311 if (!(encoder.flags & YUV444_SUPPORT)) {
2312 // Encoder can't support YUV 4:4:4 regardless of hardware capabilities
2313 return {};
2314 }
2315 pix_fmt = (colorspace.bit_depth == 10) ?
2316 encoder.platform_formats->pix_fmt_yuv444_10bit :
2317 encoder.platform_formats->pix_fmt_yuv444_8bit;
2318 } else {
2319 // YUV 4:2:0
2320 pix_fmt = (colorspace.bit_depth == 10) ?
2321 encoder.platform_formats->pix_fmt_10bit :
2322 encoder.platform_formats->pix_fmt_8bit;
2323 }
2324
2325 const bool pyrowave = config.videoFormat == PYROWAVE_VIDEO_FORMAT;
2326 {
2327 // PyroWave borrows another encoder's capture, whose codec it does not use.
2328 std::string encoder_name = pyrowave ? "pyrowave"s : encoder.codec_from_config(config).name;
2329
2330 BOOST_LOG(info) << "Creating encoder " << logging::bracket(encoder_name);
2331
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)" :
2336 "unknown";
2337
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");
2341 }
2342
2343 if (pyrowave) {
2344 // The capture knows where its frames live. One into GPU buffers keeps
2345 // them there or fails, rather than silently copying every frame through
2346 // RAM; one into system memory converts on the GPU when it can and on the
2347 // CPU otherwise.
2348 result = disp.make_pyrowave_encode_device();
2349 if (!result && encoder.platform_formats->dev_type == platf::mem_type_e::system) {
2350 result = disp.make_avcodec_encode_device(platf::pix_fmt_e::yuv420p);
2351 }
2352 if (!result) {
2353 BOOST_LOG(error) << "This capture cannot hand its frames to PyroWave"sv;
2354 }
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);
2359 }
2360
2361 if (result) {
2362 result->colorspace = colorspace;
2363 }
2364
2365 return result;
2366 }
2367
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;
2370
2371 encode_session.ctx = &ctx;
2372
2373 auto encode_device = make_encode_device(*disp, encoder, ctx.config);
2374 if (!encode_device) {
2375 return std::nullopt;
2376 }
2377
2378 // absolute mouse coordinates require that the dimensions of the screen are known
2379 ctx.touch_port_events->raise(make_port(disp, ctx.config));
2380
2381 // Update client with our current HDR display state
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;
2386 } else {
2387 BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one";
2388 }
2389 }
2390 ctx.hdr_events->raise(std::move(hdr_info));
2391
2392 auto session = make_encode_session(disp, encoder, ctx.config, img.width, img.height, std::move(encode_device));
2393 if (!session) {
2394 return std::nullopt;
2395 }
2396
2397 // Load the initial image to prepare for encoding
2398 if (session->convert(img)) {
2399 BOOST_LOG(error) << "Could not convert initial image"sv;
2400 return std::nullopt;
2401 }
2402
2403 encode_session.session = std::move(session);
2404
2405 return encode_session;
2406 }
2407
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,
2412 int &display_p
2413 ) {
2414 const auto &encoder = *chosen_encoder;
2415
2416 std::shared_ptr<platf::display_t> disp;
2417
2418 auto switch_display_event = mail::man->event<int>(mail::switch_display);
2419
2420 if (synced_session_ctxs.empty()) {
2421 auto ctx = encode_session_ctx_queue.pop();
2422 if (!ctx) {
2423 return encode_e::ok;
2424 }
2425
2426 synced_session_ctxs.emplace_back(std::make_unique<sync_session_ctx_t>(std::move(*ctx)));
2427 }
2428
2429 while (encode_session_ctx_queue.running()) {
2430 // Refresh display names since a display removal might have caused the reinitialization
2431 refresh_displays(encoder.platform_formats->dev_type, display_names, display_p);
2432
2433 // Process any pending display switch with the new list of displays
2434 if (switch_display_event->peek()) {
2435 display_p = std::clamp(*switch_display_event->pop(), 0, (int) display_names.size() - 1);
2436 }
2437
2438 // reset_display() will sleep between retries
2439 reset_display(disp, encoder.platform_formats->dev_type, display_names[display_p], synced_session_ctxs.front()->config);
2440 if (disp) {
2441 break;
2442 }
2443 }
2444
2445 if (!disp) {
2446 return encode_e::error;
2447 }
2448
2449 auto img = disp->alloc_img();
2450 if (!img || disp->dummy_img(img.get())) {
2451 return encode_e::error;
2452 }
2453
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;
2459 }
2460
2461 synced_sessions.emplace_back(std::move(*synced_session));
2462 }
2463
2464 auto ec = platf::capture_e::ok;
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) {
2470 return false;
2471 }
2472
2473 synced_session_ctxs.emplace_back(std::make_unique<sync_session_ctx_t>(std::move(*encode_session_ctx)));
2474
2475 auto encode_session = make_synced_session(disp.get(), encoder, *img, *synced_session_ctxs.back());
2476 if (!encode_session) {
2478 return false;
2479 }
2480
2481 synced_sessions.emplace_back(std::move(*encode_session));
2482 }
2483
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()) {
2487 // Let waiting thread know it can delete shutdown_event
2488 ctx->join_event->raise(true);
2489
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;
2493 }));
2494
2495 if (synced_sessions.empty()) {
2496 return false;
2497 }
2498
2499 continue;
2500 }
2501
2502 if (ctx->idr_events->peek()) {
2503 pos->session->request_idr_frame();
2504 ctx->idr_events->pop();
2505 }
2506
2507 if (frame_captured && pos->session->convert(*img)) {
2508 BOOST_LOG(error) << "Could not convert image"sv;
2509 ctx->shutdown_event->raise(true);
2510
2511 continue;
2512 }
2513
2514 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
2515 if (img) {
2516 frame_timestamp = img->frame_timestamp;
2517 }
2518
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);
2522
2523 continue;
2524 }
2525
2526 pos->session->request_normal_frame();
2527
2528 ++pos;
2529 })
2530
2531 if (switch_display_event->peek()) {
2533 return false;
2534 }
2535
2536 return true;
2537 };
2538
2539 auto pull_free_image_callback = [&img](std::shared_ptr<platf::img_t> &img_out) -> bool {
2540 img_out = img;
2541 img_out->frame_timestamp.reset();
2542 return true;
2543 };
2544
2545 auto status = disp->capture(push_captured_image_callback, pull_free_image_callback, &display_cursor);
2546 switch (status) {
2552 return ec != platf::capture_e::ok ? ec : status;
2553 }
2554 }
2555
2556 return encode_e::ok;
2557 }
2558
2559 void captureThreadSync() {
2560 auto ref = capture_thread_sync.ref();
2561
2562 std::vector<std::unique_ptr<sync_session_ctx_t>> synced_session_ctxs;
2563
2564 auto &ctx = ref->encode_session_ctx_queue;
2565 auto lg = util::fail_guard([&]() {
2566 ctx.stop();
2567
2568 for (auto &ctx : synced_session_ctxs) {
2569 ctx->shutdown_event->raise(true);
2570 ctx->join_event->raise(true);
2571 }
2572
2573 for (auto &ctx : ctx.unsafe()) {
2574 ctx.shutdown_event->raise(true);
2575 ctx.join_event->raise(true);
2576 }
2577 });
2578
2579 // Encoding and capture takes place on this thread
2580 platf::adjust_thread_priority(platf::thread_priority_e::high);
2581
2582 std::vector<std::string> display_names;
2583 int display_p = -1;
2584 while (encode_run_sync(synced_session_ctxs, ctx, display_names, display_p) == encode_e::reinit) {}
2585 }
2586
2587 void capture_async_with_context(
2588 capture_thread_async_ctx_t &capture_context,
2589 safe::mail_t mail,
2590 config_t &config,
2591 void *channel_data
2592 ) {
2593 auto shutdown_event = mail->event<bool>(mail::shutdown);
2594
2595 auto images = std::make_shared<img_event_t::element_type>();
2596 auto lg = util::fail_guard([&]() {
2597 images->stop();
2598 shutdown_event->raise(true);
2599 });
2600
2601 capture_context.capture_ctx_queue->raise(capture_ctx_t {images, config});
2602
2603 if (!capture_context.capture_ctx_queue->running()) {
2604 return;
2605 }
2606
2607 int frame_nr = 1;
2608
2609 auto touch_port_event = mail->event<input::touch_port_t>(mail::touch_port);
2610 auto hdr_event = mail->event<hdr_info_t>(mail::hdr);
2611
2612 // Encoding takes place on this thread
2613 platf::adjust_thread_priority(platf::thread_priority_e::high);
2614
2615 while (!shutdown_event->peek() && images->running()) {
2616 // Wait for the main capture event when the display is being reinitialized
2617 if (capture_context.reinit_event.peek()) {
2618 std::this_thread::sleep_for(20ms);
2619 continue;
2620 }
2621 // Wait for the display to be ready
2622 std::shared_ptr<platf::display_t> display;
2623 {
2624 auto lg = capture_context.display_wp.lock();
2625 if (capture_context.display_wp->expired()) {
2626 continue;
2627 }
2628
2629 display = capture_context.display_wp->lock();
2630 }
2631
2632 auto &encoder = *capture_context.encoder_p;
2633
2634 auto encode_device = make_encode_device(*display, encoder, config);
2635 if (!encode_device) {
2636 return;
2637 }
2638
2639 // absolute mouse coordinates require that the dimensions of the screen are known
2640 touch_port_event->raise(make_port(display.get(), config));
2641
2642 // Update client with our current HDR display state
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;
2647 } else {
2648 BOOST_LOG(error) << "Couldn't get display hdr metadata when colorspace selection indicates it should have one";
2649 }
2650 }
2651 hdr_event->raise(std::move(hdr_info));
2652
2653 encode_run(
2654 frame_nr,
2655 mail,
2656 images,
2657 config,
2658 display,
2659 std::move(encode_device),
2660 capture_context.reinit_event,
2661 *capture_context.encoder_p,
2662 channel_data
2663 );
2664 }
2665 }
2666
2677 static const encoder_t *pyrowave_capture_encoder() {
2678 if (chosen_encoder) {
2679 const auto memory = chosen_encoder->platform_formats->dev_type;
2680 if (memory == platf::mem_type_e::vaapi || memory == platf::mem_type_e::cuda) {
2681 return chosen_encoder;
2682 }
2683 }
2684 return &software;
2685 }
2686
2687 void capture_async(
2688 safe::mail_t mail,
2689 config_t &config,
2690 void *channel_data
2691 ) {
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)) {
2697 return;
2698 }
2699 auto cleanup = util::fail_guard([&session_capture]() {
2700 end_capture_async(session_capture);
2701 });
2702 capture_async_with_context(session_capture, std::move(mail), config, channel_data);
2703 return;
2704 }
2705
2706 auto ref = capture_thread_async.ref();
2707 if (!ref) {
2708 return;
2709 }
2710 capture_async_with_context(*ref.get(), std::move(mail), config, channel_data);
2711 }
2712
2713 void capture(
2714 safe::mail_t mail,
2715 config_t config,
2716 void *channel_data
2717 ) {
2718 auto idr_events = mail->event<bool>(mail::idr);
2719
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;
2723 return;
2724 }
2725 if (config.videoFormat == PYROWAVE_VIDEO_FORMAT || (chosen_encoder->flags & PARALLEL_ENCODING)) {
2726 capture_async(std::move(mail), config, channel_data);
2727 } else {
2728 safe::signal_t join_event;
2729 auto ref = capture_thread_sync.ref();
2730 ref->encode_session_ctx_queue.raise(sync_session_ctx_t {
2731 &join_event,
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),
2736 mail->event<input::touch_port_t>(mail::touch_port),
2737 config,
2738 1,
2739 channel_data,
2740 });
2741
2742 // Wait for join signal
2743 join_event.view();
2744 }
2745 }
2746
2748 VUI_PARAMS = 0x01,
2749 };
2750
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) {
2754 return -1;
2755 }
2756
2757 auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device));
2758 if (!session) {
2759 return -1;
2760 }
2761
2762 {
2763 // Image buffers are large, so we use a separate scope to free it immediately after convert()
2764 auto img = disp->alloc_img();
2765 if (!img || disp->dummy_img(img.get()) || session->convert(*img)) {
2766 return -1;
2767 }
2768 }
2769
2770 session->request_idr_frame();
2771
2772 auto packets = mail::man->queue<packet_t>(mail::video_packets);
2773 while (!packets->peek()) {
2774 if (encode(1, *session, packets, nullptr, {})) {
2775 return -1;
2776 }
2777 }
2778
2779 auto packet = packets->pop();
2780 if (!packet->is_idr()) {
2781 BOOST_LOG(error) << "First packet type is not an IDR frame"sv;
2782
2783 return -1;
2784 }
2785
2786 int flag = 0;
2787
2788 // This check only applies for H.264 and HEVC
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)) {
2792 flag |= VUI_PARAMS;
2793 }
2794 } else {
2795 // Don't check it for non-avcodec encoders.
2796 flag |= VUI_PARAMS;
2797 }
2798 }
2799
2800 return flag;
2801 }
2802
2803 bool validate_encoder(encoder_t &encoder, bool expect_failure) {
2804 const auto output_name {display_device::map_output_name(config::video.output_name)};
2805 std::shared_ptr<platf::display_t> disp;
2806
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;
2810 });
2811
2812 probe_saw_intra_refresh = false;
2813
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));
2816
2817 encoder.h264.capabilities.set();
2818 encoder.hevc.capabilities.set();
2819 encoder.av1.capabilities.set();
2820
2821 // First, test encoder viability
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;
2826
2827 // If the encoder isn't supported at all (not even H.264), bail early
2828 reset_display(disp, encoder.platform_formats->dev_type, output_name, config_autoselect);
2829 if (!disp) {
2830 return false;
2831 }
2832 if (!disp->is_codec_supported(encoder.h264.name, config_autoselect)) {
2833 fg.disable();
2834 BOOST_LOG(info) << "Encoder ["sv << encoder.name << "] is not supported on this GPU"sv;
2835 return false;
2836 }
2837
2838 // If we're expecting failure, use the autoselect ref config first since that will always succeed
2839 // if the encoder is available.
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) {
2843 return false;
2844 } else if (expect_failure) {
2845 // We expected failure, but actually succeeded. Do the max_ref_frames probe we skipped.
2846 max_ref_frames_h264 = validate_config(disp, encoder, config_max_ref_frames);
2847 }
2848
2849 std::vector<std::pair<validate_flag_e, encoder_t::flag_e>> packet_deficiencies {
2850 {VUI_PARAMS, encoder_t::VUI_PARAMETERS},
2851 };
2852
2853 for (auto [validate_flag, encoder_flag] : packet_deficiencies) {
2854 encoder.h264[encoder_flag] = (max_ref_frames_h264 & validate_flag && autoselect_h264 & validate_flag);
2855 }
2856
2857 encoder.h264[encoder_t::REF_FRAMES_RESTRICT] = max_ref_frames_h264 >= 0;
2858 encoder.h264[encoder_t::PASSED] = true;
2859
2860 if (test_hevc) {
2861 config_max_ref_frames.videoFormat = 1;
2862 config_autoselect.videoFormat = 1;
2863
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);
2866
2867 // If H.264 succeeded with max ref frames specified, assume that we can count on
2868 // HEVC to also succeed with max ref frames specified if HEVC is supported.
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);
2872
2873 for (auto [validate_flag, encoder_flag] : packet_deficiencies) {
2874 encoder.hevc[encoder_flag] = (max_ref_frames_hevc & validate_flag && autoselect_hevc & validate_flag);
2875 }
2876
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;
2879 } else {
2880 BOOST_LOG(info) << "Encoder ["sv << encoder.hevc.name << "] is not supported on this GPU"sv;
2881 encoder.hevc.capabilities.reset();
2882 }
2883 } else {
2884 // Clear all cap bits for HEVC if we didn't probe it
2885 encoder.hevc.capabilities.reset();
2886 }
2887
2888 if (test_av1) {
2889 config_max_ref_frames.videoFormat = 2;
2890 config_autoselect.videoFormat = 2;
2891
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);
2894
2895 // If H.264 succeeded with max ref frames specified, assume that we can count on
2896 // AV1 to also succeed with max ref frames specified if AV1 is supported.
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);
2900
2901 for (auto [validate_flag, encoder_flag] : packet_deficiencies) {
2902 encoder.av1[encoder_flag] = (max_ref_frames_av1 & validate_flag && autoselect_av1 & validate_flag);
2903 }
2904
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;
2907 } else {
2908 BOOST_LOG(info) << "Encoder ["sv << encoder.av1.name << "] is not supported on this GPU"sv;
2909 encoder.av1.capabilities.reset();
2910 }
2911 } else {
2912 // Clear all cap bits for AV1 if we didn't probe it
2913 encoder.av1.capabilities.reset();
2914 }
2915
2916 // Test HDR and YUV444 support
2917 {
2918 // H.264 is special because encoders may support YUV 4:4:4 without supporting 10-bit color depth
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;
2923 } else {
2924 encoder.h264[encoder_t::YUV444] = false;
2925 }
2926
2927 config_t generic_hdr_config = {1920, 1080, 60, 1000, 1, 0, 3, 1, 1, 0};
2928 generic_hdr_config.encoder_probe = true;
2929
2930 // Reset the display since we're switching from SDR to HDR
2931 reset_display(disp, encoder.platform_formats->dev_type, output_name, generic_hdr_config);
2932 if (!disp) {
2933 return false;
2934 }
2935
2936 auto test_hdr_and_yuv444 = [&](auto &flag_map, auto video_format) {
2937 auto config = generic_hdr_config;
2938 config.videoFormat = video_format;
2939
2940 if (!flag_map[encoder_t::PASSED]) {
2941 return;
2942 }
2943
2944 auto encoder_codec_name = encoder.codec_from_config(config).name;
2945
2946 // Test 4:4:4 HDR first. If 4:4:4 is supported, 4:2:0 should also be supported.
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;
2953 return;
2954 } else {
2955 flag_map[encoder_t::YUV444] = false;
2956 }
2957
2958 // Test 4:2:0 HDR
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;
2963 } else {
2964 flag_map[encoder_t::DYNAMIC_RANGE] = false;
2965 }
2966 };
2967
2968 // HDR is not supported with H.264. Don't bother even trying it.
2969 encoder.h264[encoder_t::DYNAMIC_RANGE] = false;
2970
2971 test_hdr_and_yuv444(encoder.hevc, 1);
2972 test_hdr_and_yuv444(encoder.av1, 2);
2973 }
2974
2975 // A VAAPI encoder doing rolling intra refresh can answer a client's
2976 // reference frame invalidation; advertise it only when a probe session
2977 // actually had it.
2978 if (encoder.name == "vaapi"sv) {
2979 if (probe_saw_intra_refresh) {
2980 encoder.flags |= REF_FRAMES_INVALIDATION;
2981 BOOST_LOG(info) << encoder.name << ": rolling intra refresh available; offering reference frame invalidation"sv;
2982 } else {
2983 encoder.flags &= ~REF_FRAMES_INVALIDATION;
2984 }
2985 }
2986
2987 encoder.h264[encoder_t::VUI_PARAMETERS] = encoder.h264[encoder_t::VUI_PARAMETERS] && !config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE];
2988 encoder.hevc[encoder_t::VUI_PARAMETERS] = encoder.hevc[encoder_t::VUI_PARAMETERS] && !config::sunshine.flags[config::flag::FORCE_VIDEO_HEADER_REPLACE];
2989
2990 if (!encoder.h264[encoder_t::VUI_PARAMETERS]) {
2991 BOOST_LOG(warning) << encoder.name << ": h264 missing sps->vui parameters"sv;
2992 }
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;
2995 }
2996
2997 fg.disable();
2998 return true;
2999 }
3000
3001 std::optional<capture_readiness_mode_t> choose_capture_readiness_mode(
3002 bool client_hdr_requested, bool display_hdr, bool hevc_hdr_supported, bool av1_hdr_supported
3003 ) {
3004 if (!display_hdr) {
3005 // The driver or output may have downgraded a requested HDR launch to SDR.
3006 return capture_readiness_mode_t {0, 0};
3007 }
3008 if (!client_hdr_requested) {
3009 // Never pass HDR/PQ frames through an SDR encoder without tone mapping.
3010 return std::nullopt;
3011 }
3012 if (hevc_hdr_supported) {
3013 return capture_readiness_mode_t {1, 1};
3014 }
3015 if (av1_hdr_supported) {
3016 return capture_readiness_mode_t {2, 1};
3017 }
3018 return std::nullopt;
3019 }
3020
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";
3025 return -1;
3026 }
3027 const auto &encoder = *chosen_encoder;
3028 // The display the stream's capture will open, chosen the same way: the
3029 // session's own, else the one this launch set up, else the configured
3030 // output among those present.
3031 auto name = stream.display_name.empty() ? proc::proc.display_name : stream.display_name;
3032 if (name.empty()) {
3033 std::vector<std::string> display_names;
3034 int display_p = -1;
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];
3038 }
3039 }
3040 // Name what is captured as the user knows it: the output, and how.
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;
3046
3047 // First open a probe-only display to learn the effective output mode;
3048 // virtual displays may legitimately fall back to SDR despite an HDR request,
3049 // and standard Moonlight clients do not pass hdrMode on HTTP /launch.
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);
3065 if (!disp) {
3066 failure = "Capture could not open " + label;
3067 return -1;
3068 }
3069
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);
3073 if (validate_hdr) {
3074 const auto mode = choose_capture_readiness_mode(
3075 true, display_hdr,
3076 encoder.hevc[encoder_t::DYNAMIC_RANGE],
3077 encoder.av1[encoder_t::DYNAMIC_RANGE]
3078 );
3079 if (!mode) {
3080 failure = "Capture output is HDR, but encoder [" + std::string {encoder.name} +
3081 "] has no supported HDR codec (HEVC Main10 or AV1 Main10)";
3082 return -1;
3083 }
3084
3085 config.videoFormat = mode->video_format;
3086 config.dynamicRange = mode->dynamic_range;
3087 }
3088
3089 // Do not validate the relaxed encoder probe: reopen with real stream
3090 // restrictions and test capture, conversion and encoding on that path.
3091 config.encoder_probe = false;
3092 disp.reset();
3093 disp = platf::display(encoder.platform_formats->dev_type, name, config);
3094 if (!disp) {
3095 failure = "Capture could not open " + label +
3096 (validate_hdr && display_hdr ? " in HDR mode" : "");
3097 return -1;
3098 }
3099 if (disp->is_hdr() != display_hdr) {
3100 failure = "Capture color mode changed while checking " + label;
3101 return -1;
3102 }
3103
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;
3110 result.gpu = platf::encode_gpu_description(encoder.platform_formats->dev_type == platf::mem_type_e::cuda);
3111
3112 // One real frame. Capture backends call back on every poll, with
3113 // frame_captured false when nothing changed, so a deadline here ends it.
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);
3123 return false;
3124 }
3125 if (std::chrono::steady_clock::now() >= deadline) {
3126 timed_out = true;
3127 return false;
3128 }
3129 return true;
3130 },
3131 [&](std::shared_ptr<platf::img_t> &img_out) {
3132 for (auto &img : pool) {
3133 if (img.use_count() == 1) {
3134 img_out = img;
3135 return true;
3136 }
3137 }
3138 if (pool.size() >= 3) {
3139 return false;
3140 }
3141 img_out = pool.emplace_back(disp->alloc_img());
3142 return static_cast<bool>(img_out);
3143 },
3144 &cursor
3145 );
3146 if (!frame) {
3147 if (timed_out || status == platf::capture_e::timeout) {
3148 // A display that is up but has nothing new to show is not broken.
3149 BOOST_LOG(warning) << "Capture readiness: " << label << " produced no new frame within 5 seconds; continuing"sv;
3150 return 0;
3151 }
3152 failure = "Capture failed on " + label;
3153 return -1;
3154 }
3155
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;
3160 return -1;
3161 }
3162 auto session = make_encode_session(disp.get(), encoder, config, disp->width, disp->height, std::move(encode_device));
3163 if (!session) {
3164 failure = "The " + std::string {encoder.name} + " encoder could not start for " + label;
3165 return -1;
3166 }
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";
3169 return -1;
3170 }
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;
3176 return -1;
3177 }
3178 }
3179 packets->pop();
3180
3181 // Report the GPU that encoded, not the one adapter_name names: KMS
3182 // capture encodes on the GPU the captured display is on.
3183 if (std::string_view {encoder.name} == "vaapi"sv) {
3184 if (auto actual = platf::last_vaapi_encode_gpu(); !actual.empty()) {
3185 result.gpu = std::move(actual);
3186 }
3187 }
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);
3193 return 0;
3194 }
3195
3196 static std::mutex capture_readiness_mutex;
3197 static capture_readiness_t capture_readiness;
3198
3199 int check_capture_path(const config_t &stream, std::string &failure, const std::string &client) {
3200 capture_readiness_t result;
3201 result.client = client;
3202 const int status = check_capture_path_impl(stream, failure, result);
3203 result.checked = true;
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);
3209 return status;
3210 }
3211
3213 std::lock_guard lock {capture_readiness_mutex};
3214 return capture_readiness;
3215 }
3216
3217 void forget_capture_readiness(const std::string &client) {
3218 std::lock_guard lock {capture_readiness_mutex};
3219 if (capture_readiness.checked && capture_readiness.client == client) {
3220 capture_readiness = {};
3221 }
3222 }
3223
3225 probe_without_display = true;
3226 auto reset = util::fail_guard([]() {
3227 probe_without_display = false;
3228 });
3229 return probe_encoders();
3230 }
3231
3233 auto encoder_list = encoders;
3234
3235 // If we already have a good encoder, check to see if another probe is required
3236 if (chosen_encoder && !(chosen_encoder->flags & ALWAYS_REPROBE) && !platf::needs_encoder_reenumeration()) {
3237 return 0;
3238 }
3239
3240 // Before validation starts: a configured encoder is validated first, and
3241 // its failures (an unsupported codec, for one) are among those errors.
3242 BOOST_LOG(info) << "// Testing for available encoders, this may generate errors. You can safely ignore those errors. //"sv;
3243
3244 // Restart encoder selection
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;
3250
3251 auto adjust_encoder_constraints = [&](encoder_t *encoder) {
3252 // If we can't satisfy both the encoder and codec requirement, prefer the encoder over codec support
3253 if (active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) {
3254 BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC Main10 on this system"sv;
3255 active_hevc_mode = 0;
3256 } else if (active_hevc_mode == 2 && !encoder->hevc[encoder_t::PASSED]) {
3257 BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support HEVC on this system"sv;
3258 active_hevc_mode = 0;
3259 }
3260
3261 if (active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE]) {
3262 BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 Main10 on this system"sv;
3263 active_av1_mode = 0;
3264 } else if (active_av1_mode == 2 && !encoder->av1[encoder_t::PASSED]) {
3265 BOOST_LOG(warning) << "Encoder ["sv << encoder->name << "] does not support AV1 on this system"sv;
3266 active_av1_mode = 0;
3267 }
3268 };
3269
3270 if (!config::video.encoder.empty()) {
3271 // If there is a specific encoder specified, use it if it passes validation
3272 KITTY_WHILE_LOOP(auto pos = std::begin(encoder_list), pos != std::end(encoder_list), {
3273 auto encoder = *pos;
3274
3275 if (encoder->name == config::video.encoder) {
3276 // Remove the encoder from the list entirely if it fails validation
3277 if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) {
3278 pos = encoder_list.erase(pos);
3279 break;
3280 }
3281
3282 // We will return an encoder here even if it fails one of the codec requirements specified by the user
3283 adjust_encoder_constraints(encoder);
3284
3285 chosen_encoder = encoder;
3286 break;
3287 }
3288
3289 pos++;
3290 });
3291
3292 if (chosen_encoder == nullptr) {
3293 BOOST_LOG(error) << "Couldn't find any working encoder matching ["sv << config::video.encoder << ']';
3294 }
3295 }
3296
3297 // If we haven't found an encoder yet, but we want one with specific codec support, search for that now.
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;
3301
3302 // Remove the encoder from the list entirely if it fails validation
3303 if (!validate_encoder(*encoder, previous_encoder && previous_encoder != encoder)) {
3304 pos = encoder_list.erase(pos);
3305 continue;
3306 }
3307
3308 // Skip it if it doesn't support the specified codec at all
3309 if ((active_hevc_mode >= 2 && !encoder->hevc[encoder_t::PASSED]) ||
3310 (active_av1_mode >= 2 && !encoder->av1[encoder_t::PASSED])) {
3311 pos++;
3312 continue;
3313 }
3314
3315 // Skip it if it doesn't support HDR on the specified codec
3316 if ((active_hevc_mode == 3 && !encoder->hevc[encoder_t::DYNAMIC_RANGE]) ||
3317 (active_av1_mode == 3 && !encoder->av1[encoder_t::DYNAMIC_RANGE])) {
3318 pos++;
3319 continue;
3320 }
3321
3322 chosen_encoder = encoder;
3323 break;
3324 });
3325
3326 if (chosen_encoder == nullptr) {
3327 BOOST_LOG(error) << "Couldn't find any working encoder that meets HEVC/AV1 requirements"sv;
3328 }
3329 }
3330
3331 // If no encoder was specified or the specified encoder was unusable, keep trying
3332 // the remaining encoders until we find one that passes validation. Record each
3333 // hardware encoder we reject here so diagnostics can explain a software fallback.
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;
3338
3339 // If we've used a previous encoder and it's not this one, we expect this encoder to
3340 // fail to validate. It will use a slightly different order of checks to more quickly
3341 // eliminate failing encoders.
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"});
3345 }
3346 pos = encoder_list.erase(pos);
3347 continue;
3348 }
3349
3350 // We will return an encoder here even if it fails one of the codec requirements specified by the user
3351 adjust_encoder_constraints(encoder);
3352
3353 chosen_encoder = encoder;
3354 break;
3355 });
3356 }
3357
3358 if (chosen_encoder == nullptr) {
3359 const auto output_name {display_device::map_output_name(config::video.output_name)};
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;
3363 } else {
3364 BOOST_LOG(fatal) << "Please check that a display is connected and powered on."sv;
3365 }
3366 return -1;
3367 }
3368
3369 BOOST_LOG(info);
3370 BOOST_LOG(info) << "// Ignore any errors mentioned above, they are not relevant. //"sv;
3371 BOOST_LOG(info);
3372
3373 auto &encoder = *chosen_encoder;
3374
3375 last_encoder_probe_supported_ref_frames_invalidation = (encoder.flags & REF_FRAMES_INVALIDATION);
3376 last_encoder_probe_supported_yuv444_for_codec[0] = encoder.h264[encoder_t::PASSED] &&
3377 encoder.h264[encoder_t::YUV444];
3378 last_encoder_probe_supported_yuv444_for_codec[1] = encoder.hevc[encoder_t::PASSED] &&
3379 encoder.hevc[encoder_t::YUV444];
3380 last_encoder_probe_supported_yuv444_for_codec[2] = encoder.av1[encoder_t::PASSED] &&
3381 encoder.av1[encoder_t::YUV444];
3382
3383 // Record the selected encoder for the diagnostics endpoint so users can see
3384 // whether hardware or software encoding is actually in use, and which codecs
3385 // the chosen encoder supports.
3386 {
3387 encoder_status_t status;
3388 status.probed = true;
3389 status.encoder = std::string {encoder.name};
3390 status.hardware = encoder.name != "software";
3391 status.h264 = encoder.h264[encoder_t::PASSED];
3392 status.hevc = encoder.hevc[encoder_t::PASSED];
3393 status.av1 = encoder.av1[encoder_t::PASSED];
3394 status.attempts = std::move(rejected_attempts);
3395 status.attempts.push_back({std::string {encoder.name}, true, "selected"});
3396 status.fell_back_to_software = !status.hardware && status.attempts.size() > 1;
3397 if (!status.hardware) {
3398 std::string tried;
3399 for (const auto &attempt : status.attempts) {
3400 if (attempt.selected) {
3401 continue;
3402 }
3403 if (!tried.empty()) {
3404 tried += ", ";
3405 }
3406 tried += attempt.name;
3407 }
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;
3411 } else {
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;
3415 }
3416 }
3417 std::lock_guard lg {encoder_status_mutex};
3418 encoder_status_state = std::move(status);
3419 }
3420
3421 BOOST_LOG(debug) << "------ h264 ------"sv;
3422 for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
3423 auto flag = (encoder_t::flag_e) x;
3424 BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.h264[flag] ? ": supported"sv : ": unsupported"sv);
3425 }
3426 BOOST_LOG(debug) << "-------------------"sv;
3427 BOOST_LOG(info) << "Found H.264 encoder: "sv << encoder.h264.name << " ["sv << encoder.name << ']';
3428
3429 if (encoder.hevc[encoder_t::PASSED]) {
3430 BOOST_LOG(debug) << "------ hevc ------"sv;
3431 for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
3432 auto flag = (encoder_t::flag_e) x;
3433 BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.hevc[flag] ? ": supported"sv : ": unsupported"sv);
3434 }
3435 BOOST_LOG(debug) << "-------------------"sv;
3436
3437 BOOST_LOG(info) << "Found HEVC encoder: "sv << encoder.hevc.name << " ["sv << encoder.name << ']';
3438 }
3439
3440 if (encoder.av1[encoder_t::PASSED]) {
3441 BOOST_LOG(debug) << "------ av1 ------"sv;
3442 for (int x = 0; x < encoder_t::MAX_FLAGS; ++x) {
3443 auto flag = (encoder_t::flag_e) x;
3444 BOOST_LOG(debug) << encoder_t::from_flag(flag) << (encoder.av1[flag] ? ": supported"sv : ": unsupported"sv);
3445 }
3446 BOOST_LOG(debug) << "-------------------"sv;
3447
3448 BOOST_LOG(info) << "Found AV1 encoder: "sv << encoder.av1.name << " ["sv << encoder.name << ']';
3449 }
3450
3451 if (active_hevc_mode == 0) {
3452 active_hevc_mode = encoder.hevc[encoder_t::PASSED] ? (encoder.hevc[encoder_t::DYNAMIC_RANGE] ? 3 : 2) : 1;
3453 }
3454
3455 if (active_av1_mode == 0) {
3456 active_av1_mode = encoder.av1[encoder_t::PASSED] ? (encoder.av1[encoder_t::DYNAMIC_RANGE] ? 3 : 2) : 1;
3457 }
3458
3459 return 0;
3460 }
3461
3462 // Linux only declaration
3463 typedef int (*vaapi_init_avcodec_hardware_input_buffer_fn)(platf::avcodec_encode_device_t *encode_device, AVBufferRef **hw_device_buf);
3464
3465 util::Either<avcodec_buffer_t, int> vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) {
3466 avcodec_buffer_t hw_device_buf;
3467
3468 // If an egl hwdevice
3469 if (encode_device->data) {
3470 if (((vaapi_init_avcodec_hardware_input_buffer_fn) encode_device->data)(encode_device, &hw_device_buf)) {
3471 return -1;
3472 }
3473
3474 return hw_device_buf;
3475 }
3476
3477 auto render_device = config::video.adapter_name.empty() ? nullptr : config::video.adapter_name.c_str();
3478
3479 auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_VAAPI, render_device, nullptr, 0);
3480 if (status < 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);
3483 return -1;
3484 }
3485
3486 return hw_device_buf;
3487 }
3488
3489 util::Either<avcodec_buffer_t, int> cuda_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *encode_device) {
3490 avcodec_buffer_t hw_device_buf;
3491
3492 auto status = av_hwdevice_ctx_create(&hw_device_buf, AV_HWDEVICE_TYPE_CUDA, nullptr, nullptr, 1 /* AV_CUDA_USE_PRIMARY_CONTEXT */);
3493 if (status < 0) {
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);
3496 return -1;
3497 }
3498
3499 return hw_device_buf;
3500 }
3501
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);
3504 }
3505
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();
3509
3510 capture_thread_ctx.capture_ctx_queue = std::make_shared<safe::queue_t<capture_ctx_t>>(30);
3511
3512 capture_thread_ctx.capture_thread = std::thread {
3513 captureThread,
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)
3518 };
3519
3520 return 0;
3521 }
3522
3523 void end_capture_async(capture_thread_async_ctx_t &capture_thread_ctx) {
3524 capture_thread_ctx.capture_ctx_queue->stop();
3525
3526 capture_thread_ctx.capture_thread.join();
3527 }
3528
3529 int start_capture_sync(capture_thread_sync_ctx_t &ctx) {
3530 std::thread {&captureThreadSync}.detach();
3531 return 0;
3532 }
3533
3534 void end_capture_sync(capture_thread_sync_ctx_t &ctx) {
3535 }
3536
3537 platf::mem_type_e map_base_dev_type(AVHWDeviceType type) {
3538 switch (type) {
3539 case AV_HWDEVICE_TYPE_VAAPI:
3541 case AV_HWDEVICE_TYPE_CUDA:
3543 case AV_HWDEVICE_TYPE_NONE:
3545 default:
3547 }
3548
3550 }
3551
3552 platf::pix_fmt_e map_pix_fmt(AVPixelFormat fmt) {
3553 switch (fmt) {
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:
3566 default:
3568 }
3569
3571 }
3572
3573} // namespace video
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.
Definition cbs.cpp:222
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.
Definition common.h:530
virtual std::unique_ptr< avcodec_encode_device_t > make_pyrowave_encode_device()
Make a device that converts captured frames into PyroWave's GPU planes.
Definition common.h:500
bool next_after_invalidation
The next frame is the first the client may decode after a loss.
Definition video.cpp:522
int intra_refresh_frames
Frames per full rolling intra refresh, when the encoder is doing one; 0 otherwise.
Definition video.cpp:520
bool filler_stripped
Filler data has been removed from a frame of this session (logged once).
Definition video.cpp:518
int64_t recovering_until
The last frame of the loss being recovered; requests up to it are repeats.
Definition video.cpp:524
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override
Set the frame to be encoded.
Definition video.cpp:144
Declarations for common platform specific utilities.
mem_type_e
Definition common.h:211
@ system
System memory.
Definition common.h:212
@ vaapi
VAAPI.
Definition common.h:213
@ unknown
Unknown.
Definition common.h:215
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...
Definition misc.cpp:1658
pix_fmt_e
Definition common.h:218
@ yuv420p10
YUV 4:2:0 10-bit.
Definition common.h:220
@ unknown
Unknown.
Definition common.h:226
@ yuv420p
YUV 4:2:0.
Definition common.h:219
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.
Definition misc.cpp:1653
@ high
High priority.
Definition common.h:696
bool touch_binds_to_output()
Whether the session binds a touchscreen or a pen to one output.
Definition misc.cpp:198
capture_e
Definition common.h:435
@ ok
Success.
Definition common.h:436
@ timeout
Timeout.
Definition common.h:438
@ reinit
Need to reinitialize.
Definition common.h:437
@ error
Error.
Definition common.h:440
@ interrupted
Capture was interrupted.
Definition common.h:439
Declarations for the configuration of Sunshine.
@ FORCE_VIDEO_HEADER_REPLACE
force replacing headers inside video data
Definition config.h:210
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.
Definition globals.cpp:10
Declarations for globally accessible variables and functions.
platf::touch_port_t direct_device_port(int output_width, int output_height, int offset_x, int offset_y, int env_width, int env_height, bool binds_to_output)
The rectangle a touchscreen or a pen is addressed in.
Definition input.cpp:963
Declarations for gamepad, keyboard, and mouse input handling.
Declarations for logging related functions.
int main(int argc, char *argv[])
Main application entry point.
Definition main.cpp:104
Miscellaneous declarations for Linux.
std::string bracket(const std::string &input)
Enclose string in square brackets.
Definition logging.cpp:233
Handles process-wide communication.
Definition globals.h:25
safe::mail_t man
A process-wide communication mechanism.
Definition globals.cpp:8
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.
Definition video.h:407
What the last capture-path check found, for a client to show.
Definition video.h:441
std::string client
The paired client whose launch ran the check.
Definition video.h:453
std::int64_t checked_at
Unix time of the check, in seconds.
Definition video.h:452
std::string failure
The failed step and its reason, when not ok.
Definition video.h:451
bool ok
Whether a frame went all the way through, or the display was only idle.
Definition video.h:443
bool checked
Whether a check has run since Hermes started.
Definition video.h:442
std::vector< encoder_attempt_t > attempts
Definition video.h:499
std::string encoder
Selected encoder backend (e.g. "nvenc", "vaapi", "software").
Definition video.h:492
bool hardware
True if the selected encoder is hardware-accelerated.
Definition video.h:493
bool probed
A probe has completed at least once.
Definition video.h:491
bool fell_back_to_software
True if a hardware encoder was rejected and we fell back to software.
Definition video.h:501
bool h264
H.264 supported by the selected encoder.
Definition video.h:494
bool hevc
HEVC supported.
Definition video.h:495
@ DYNAMIC_RANGE
HDR support.
Definition video.h:153
@ VUI_PARAMETERS
AMD encoder with VAAPI doesn't add VUI parameters to SPS.
Definition video.h:155
@ PASSED
Indicates the encoder is supported.
Definition video.h:151
@ REF_FRAMES_RESTRICT
Set maximum reference frames.
Definition video.h:152
@ YUV444
YUV 4:4:4 support.
Definition video.h:154
@ MAX_FLAGS
Maximum number of flags.
Definition video.h:156
pipeline_metrics_t published
Last computed averages.
Definition video.cpp:870
uint64_t window_frames
Frames in the current averaging window.
Definition video.cpp:863
int width
Active stream resolution, set at session start.
Definition video.cpp:867
uint64_t window_bytes
Encoded bytes in the current window.
Definition video.cpp:864
uint64_t frames_encoded
Total this session.
Definition video.cpp:865
Live per-frame pipeline metrics, for diagnostics/metrics.
Definition video.h:514
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,...
Definition video.cpp:3217
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.
Definition video.cpp:3001
@ PARALLEL_ENCODING
Capture and encoding can run concurrently on separate threads.
Definition video.cpp:262
@ CBR_WITH_VBR
Use a VBR rate control mode to simulate CBR.
Definition video.cpp:266
@ REF_FRAMES_INVALIDATION
Support reference frames invalidation.
Definition video.cpp:269
@ YUV444_SUPPORT
Encoder may support 4:4:4 chroma sampling depending on hardware.
Definition video.cpp:271
@ ALWAYS_REPROBE
This is an encoder of last resort and we want to aggressively probe for a better one.
Definition video.cpp:270
@ RELAXED_COMPLIANCE
Use FF_COMPLIANCE_UNOFFICIAL compliance mode.
Definition video.cpp:267
@ ASYNC_TEARDOWN
Encoder supports async teardown on a different thread.
Definition video.cpp:272
@ DEFAULT
Default flags.
Definition video.cpp:261
@ LIMITED_GOP_SIZE
Some encoders don't like it when you have an infinite GOP_SIZE. e.g. VAAPI.
Definition video.cpp:264
@ SINGLE_SLICE_ONLY
Never use multiple slices. Older intel iGPU's ruin it for everyone else.
Definition video.cpp:265
@ NO_RC_BUF_LIMIT
Don't set rc_buffer_size.
Definition video.cpp:268
@ H264_ONLY
When HEVC is too heavy.
Definition video.cpp:263
profile_h264_e
Definition video.cpp:80
@ high
High profile.
Definition video.cpp:81
@ high_444p
High 4:4:4 Predictive profile.
Definition video.cpp:82
void metrics_reset()
Reset pipeline metrics at the start of a streaming session.
Definition video.cpp:910
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.
Definition video.cpp:874
bool display_present()
Whether the host has a display to capture without creating one.
Definition video.cpp:52
profile_hevc_e
Definition video.cpp:85
@ main_10
Main 10 profile.
Definition video.cpp:87
@ rext
Rext profile.
Definition video.cpp:88
@ main
Main profile.
Definition video.cpp:86
encoder_status_t get_encoder_status()
Snapshot of the last encoder probe result (thread-safe copy).
Definition video.cpp:852
void refresh_displays(platf::mem_type_e dev_type, std::vector< std::string > &display_names, int &current_display_index, std::string &preferred_display_name)
Update the list of display names before or during a stream.
Definition video.cpp:975
validate_flag_e
Definition video.cpp:2747
@ VUI_PARAMS
VUI parameters.
Definition video.cpp:2748
void metrics_record_drop()
Record one dropped frame (encoder error/timeout).
Definition video.cpp:904
std::size_t pyrowave_frame_budget(const config_t &config)
The most bytes one PyroWave frame may take.
Definition video.cpp:355
capture_readiness_t last_capture_readiness()
The result of the last check_capture_path().
Definition video.cpp:3212
int probe_encoders()
Probe encoders and select the preferred encoder. This is called once at startup and each time a strea...
Definition video.cpp:3232
pipeline_metrics_t get_pipeline_metrics()
Snapshot of the live pipeline metrics (thread-safe copy).
Definition video.cpp:926
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.
Definition video.cpp:3199
void metrics_set_resolution(int width, int height)
Record the active stream resolution for diagnostics.
Definition video.cpp:915
int probe_encoders_without_display()
Probe encoders without opening any screen.
Definition video.cpp:3224
Declarations for video.
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.