Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
video.h
Go to the documentation of this file.
1
5#pragma once
6
7// standard includes
8#include <optional>
9#include <string>
10#include <vector>
11
12// local includes
13#include "input.h"
14#include "platform/common.h"
15#include "thread_safe.h"
16#include "video_colorspace.h"
17
18extern "C" {
19#include <libavcodec/avcodec.h>
20#include <libswscale/swscale.h>
21}
22
23struct AVPacket;
24
25namespace video {
26
27 // PyroWave's place in the protocol, as Hestia's moonlight-common-c defines
28 // it (VIDEO_FORMAT_PYROWAVE in Limelight.h). Sunshine hands out its codec
29 // bits and stream formats in sequence - the next ServerCodecModeSupport bit
30 // after SCM_AV1_HIGH10_444 is 0x00800000 and bitStreamFormat went 0, 1, 2 -
31 // so these stay well clear of them: a codec Sunshine adds next can't be read
32 // as PyroWave, and a client asking for it can't get PyroWave.
33 inline constexpr int PYROWAVE_VIDEO_FORMAT = 64; // x-nv-vqos[0].bitStreamFormat
34 inline constexpr uint32_t PYROWAVE_SERVER_CODEC_MODE = 0x40000000; // SCM_PYROWAVE
35
36 /* Encoding configuration requested by remote client */
37 struct config_t {
38 // DO NOT CHANGE ORDER OR ADD FIELDS IN THE MIDDLE!!!!!
39 // ONLY APPEND NEW FIELD AFTERWARDS!!!!!!!!!
40 // BIG F WORD to Sunshine!!!!!!!!!
41 int width; // Video width in pixels
42 int height; // Video height in pixels
43 int framerate; // Requested framerate, used in individual frame bitrate budget calculation
44 int bitrate; // Video bitrate in kilobits (1000 bits) for requested framerate
45 int slicesPerFrame; // Number of slices per frame
46 int numRefFrames; // Max number of reference frames
47
48 /* Requested color range and SDR encoding colorspace, HDR encoding colorspace is always BT.2020+ST2084
49 Color range (encoderCscMode & 0x1) : 0 - limited, 1 - full
50 SDR encoding colorspace (encoderCscMode >> 1) : 0 - BT.601, 1 - BT.709, 2 - BT.2020 */
51 int encoderCscMode;
52
53 int videoFormat; // 0 - H.264, 1 - HEVC, 2 - AV1, PYROWAVE_VIDEO_FORMAT - PyroWave
54
55 /* Encoding color depth (bit depth): 0 - 8-bit, 1 - 10-bit
56 HDR encoding activates when color depth is higher than 8-bit and the display which is being captured is operating in HDR mode */
57 int dynamicRange;
58
59 int chromaSamplingType; // 0 - 4:2:0, 1 - 4:4:4
60
61 int enableIntraRefresh; // 0 - disabled, 1 - enabled
62
63 int encodingFramerate; // Requested display framerate
64 bool input_only;
65 // Experimental Hermes-KMS multi-output: an empty value preserves the
66 // legacy process-wide capture selection.
67 std::string display_name;
68 // Internal capability probing encodes synthetic frames, never a stream.
69 bool encoder_probe {false};
70 // Explicit native detached endpoints; empty preserves existing capture.
71 std::string kwin_wayland_socket;
72 std::string kwin_pipewire_socket;
73 };
74
75 platf::mem_type_e map_base_dev_type(AVHWDeviceType type);
76 platf::pix_fmt_e map_pix_fmt(AVPixelFormat fmt);
77
78 void free_ctx(AVCodecContext *ctx);
79 void free_frame(AVFrame *frame);
80 void free_buffer(AVBufferRef *ref);
81
82 using avcodec_ctx_t = util::safe_ptr<AVCodecContext, free_ctx>;
83 using avcodec_frame_t = util::safe_ptr<AVFrame, free_frame>;
84 using avcodec_buffer_t = util::safe_ptr<AVBufferRef, free_buffer>;
85 using sws_t = util::safe_ptr<SwsContext, sws_freeContext>;
86 using img_event_t = std::shared_ptr<safe::event_t<std::shared_ptr<platf::img_t>>>;
87
89 virtual ~encoder_platform_formats_t() = default;
90 platf::mem_type_e dev_type;
91 platf::pix_fmt_e pix_fmt_8bit, pix_fmt_10bit;
92 platf::pix_fmt_e pix_fmt_yuv444_8bit, pix_fmt_yuv444_10bit;
93 };
94
95 struct encoder_platform_formats_avcodec: encoder_platform_formats_t {
96 using init_buffer_function_t = std::function<util::Either<avcodec_buffer_t, int>(platf::avcodec_encode_device_t *)>;
97
98 encoder_platform_formats_avcodec(
99 const AVHWDeviceType &avcodec_base_dev_type,
100 const AVHWDeviceType &avcodec_derived_dev_type,
101 const AVPixelFormat &avcodec_dev_pix_fmt,
102 const AVPixelFormat &avcodec_pix_fmt_8bit,
103 const AVPixelFormat &avcodec_pix_fmt_10bit,
104 const AVPixelFormat &avcodec_pix_fmt_yuv444_8bit,
105 const AVPixelFormat &avcodec_pix_fmt_yuv444_10bit,
106 const init_buffer_function_t &init_avcodec_hardware_input_buffer_function
107 ):
108 avcodec_base_dev_type {avcodec_base_dev_type},
109 avcodec_derived_dev_type {avcodec_derived_dev_type},
110 avcodec_dev_pix_fmt {avcodec_dev_pix_fmt},
111 avcodec_pix_fmt_8bit {avcodec_pix_fmt_8bit},
112 avcodec_pix_fmt_10bit {avcodec_pix_fmt_10bit},
113 avcodec_pix_fmt_yuv444_8bit {avcodec_pix_fmt_yuv444_8bit},
114 avcodec_pix_fmt_yuv444_10bit {avcodec_pix_fmt_yuv444_10bit},
115 init_avcodec_hardware_input_buffer {init_avcodec_hardware_input_buffer_function} {
116 dev_type = map_base_dev_type(avcodec_base_dev_type);
117 pix_fmt_8bit = map_pix_fmt(avcodec_pix_fmt_8bit);
118 pix_fmt_10bit = map_pix_fmt(avcodec_pix_fmt_10bit);
119 pix_fmt_yuv444_8bit = map_pix_fmt(avcodec_pix_fmt_yuv444_8bit);
120 pix_fmt_yuv444_10bit = map_pix_fmt(avcodec_pix_fmt_yuv444_10bit);
121 }
122
123 AVHWDeviceType avcodec_base_dev_type, avcodec_derived_dev_type;
124 AVPixelFormat avcodec_dev_pix_fmt;
125 AVPixelFormat avcodec_pix_fmt_8bit, avcodec_pix_fmt_10bit;
126 AVPixelFormat avcodec_pix_fmt_yuv444_8bit, avcodec_pix_fmt_yuv444_10bit;
127
128 init_buffer_function_t init_avcodec_hardware_input_buffer;
129 };
130
131 struct encoder_platform_formats_nvenc: encoder_platform_formats_t {
132 encoder_platform_formats_nvenc(
133 const platf::mem_type_e &dev_type,
134 const platf::pix_fmt_e &pix_fmt_8bit,
135 const platf::pix_fmt_e &pix_fmt_10bit,
136 const platf::pix_fmt_e &pix_fmt_yuv444_8bit,
137 const platf::pix_fmt_e &pix_fmt_yuv444_10bit
138 ) {
139 encoder_platform_formats_t::dev_type = dev_type;
140 encoder_platform_formats_t::pix_fmt_8bit = pix_fmt_8bit;
141 encoder_platform_formats_t::pix_fmt_10bit = pix_fmt_10bit;
142 encoder_platform_formats_t::pix_fmt_yuv444_8bit = pix_fmt_yuv444_8bit;
143 encoder_platform_formats_t::pix_fmt_yuv444_10bit = pix_fmt_yuv444_10bit;
144 }
145 };
146
147 struct encoder_t {
148 std::string_view name;
149
158
159 static std::string_view from_flag(flag_e flag) {
160#define _CONVERT(x) \
161 case flag_e::x: \
162 return std::string_view(#x)
163 switch (flag) {
164 _CONVERT(PASSED);
165 _CONVERT(REF_FRAMES_RESTRICT);
166 _CONVERT(DYNAMIC_RANGE);
167 _CONVERT(YUV444);
168 _CONVERT(VUI_PARAMETERS);
169 _CONVERT(MAX_FLAGS);
170 }
171#undef _CONVERT
172
173 return {"unknown"};
174 }
175
176 struct option_t {
177 KITTY_DEFAULT_CONSTR_MOVE(option_t)
178 option_t(const option_t &) = default;
179
180 std::string name;
181 std::variant<int, int *, std::optional<int> *, std::function<int()>, std::string, std::string *, std::function<const std::string(const config_t &)>> value;
182
183 option_t(std::string &&name, decltype(value) &&value):
184 name {std::move(name)},
185 value {std::move(value)} {
186 }
187 };
188
189 const std::unique_ptr<const encoder_platform_formats_t> platform_formats;
190
191 struct codec_t {
192 std::vector<option_t> common_options;
193 std::vector<option_t> sdr_options;
194 std::vector<option_t> hdr_options;
195 std::vector<option_t> sdr444_options;
196 std::vector<option_t> hdr444_options;
197 std::vector<option_t> fallback_options;
198
199 std::string name;
200 std::bitset<MAX_FLAGS> capabilities;
201
202 bool operator[](flag_e flag) const {
203 return capabilities[(std::size_t) flag];
204 }
205
206 std::bitset<MAX_FLAGS>::reference operator[](flag_e flag) {
207 return capabilities[(std::size_t) flag];
208 }
209 } av1, hevc, h264;
210
211 const codec_t &codec_from_config(const config_t &config) const {
212 switch (config.videoFormat) {
213 default:
214 BOOST_LOG(error) << "Unknown video format " << config.videoFormat << ", falling back to H.264";
215 // fallthrough
216 case 0:
217 return h264;
218 case 1:
219 return hevc;
220 case 2:
221 return av1;
222 case PYROWAVE_VIDEO_FORMAT:
223 // PyroWave uses this encoder only for capture and RGB-to-YUV
224 // conversion; its bitstream is produced by the PyroWave API.
225 return h264;
226 }
227 }
228
229 uint32_t flags;
230 };
231
233 virtual ~encode_session_t() = default;
234
235 virtual int convert(platf::img_t &img) = 0;
236
237 virtual void request_idr_frame() = 0;
238
239 virtual void request_normal_frame() = 0;
240
241 virtual void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) = 0;
242 };
243
244 // encoders
245 extern encoder_t software;
246
247 // True only when this build has a compatible PyroWave C API and a usable
248 // Vulkan device. The probe is cached for the process lifetime.
249 bool pyrowave_available();
250
259 std::size_t pyrowave_frame_budget(const config_t &config);
260
261 extern encoder_t nvenc;
262
263
264 extern encoder_t vaapi;
265
266
268 virtual ~packet_raw_t() = default;
269
270 virtual bool is_idr() = 0;
271
272 virtual int64_t frame_index() = 0;
273
274 virtual uint8_t *data() = 0;
275
276 virtual size_t data_size() = 0;
277
278 struct replace_t {
279 std::string_view old;
280 std::string_view _new;
281
282 KITTY_DEFAULT_CONSTR_MOVE(replace_t)
283
284 replace_t(std::string_view old, std::string_view _new) noexcept:
285 old {std::move(old)},
286 _new {std::move(_new)} {
287 }
288 };
289
290 std::vector<replace_t> *replacements = nullptr;
291 void *channel_data = nullptr;
292 bool after_ref_frame_invalidation = false;
293 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
294 };
295
296 struct packet_raw_avcodec: packet_raw_t {
297 packet_raw_avcodec() {
298 av_packet = av_packet_alloc();
299 }
300
301 ~packet_raw_avcodec() {
302 av_packet_free(&this->av_packet);
303 }
304
305 bool is_idr() override {
306 return av_packet->flags & AV_PKT_FLAG_KEY;
307 }
308
309 int64_t frame_index() override {
310 return av_packet->pts;
311 }
312
313 uint8_t *data() override {
314 return av_packet->data;
315 }
316
317 size_t data_size() override {
318 return av_packet->size;
319 }
320
321 AVPacket *av_packet;
322 };
323
324 struct packet_raw_generic: packet_raw_t {
325 packet_raw_generic(std::vector<uint8_t> &&frame_data, int64_t frame_index, bool idr):
326 frame_data {std::move(frame_data)},
327 index {frame_index},
328 idr {idr} {
329 }
330
331 bool is_idr() override {
332 return idr;
333 }
334
335 int64_t frame_index() override {
336 return index;
337 }
338
339 uint8_t *data() override {
340 return frame_data.data();
341 }
342
343 size_t data_size() override {
344 return frame_data.size();
345 }
346
347 std::vector<uint8_t> frame_data;
348 int64_t index;
349 bool idr;
350 };
351
352 using packet_t = std::unique_ptr<packet_raw_t>;
353
354 struct hdr_info_raw_t {
355 explicit hdr_info_raw_t(bool enabled):
356 enabled {enabled},
357 metadata {} {};
358 explicit hdr_info_raw_t(bool enabled, const SS_HDR_METADATA &metadata):
359 enabled {enabled},
360 metadata {metadata} {};
361
362 bool enabled;
363 SS_HDR_METADATA metadata;
364 };
365
366 using hdr_info_t = std::unique_ptr<hdr_info_raw_t>;
367
368 extern int active_hevc_mode;
369 extern int active_av1_mode;
370 extern bool last_encoder_probe_supported_ref_frames_invalidation;
371 extern std::array<bool, 3> last_encoder_probe_supported_yuv444_for_codec; // 0 - H.264, 1 - HEVC, 2 - AV1
372
373 void capture(
374 safe::mail_t mail,
375 config_t config,
376 void *channel_data
377 );
378
379 bool validate_encoder(encoder_t &encoder, bool expect_failure);
380
389 bool display_present();
390
399 int probe_encoders();
400
411
417 std::optional<capture_readiness_mode_t> choose_capture_readiness_mode(
418 bool client_hdr_requested, bool display_hdr, bool hevc_hdr_supported, bool av1_hdr_supported
419 );
420
436 int check_capture_path(const config_t &stream, std::string &failure, const std::string &client = {});
437
442 bool checked {false};
443 bool ok {false};
444 bool frame_seen {false};
445 std::string capture;
446 int width {0};
447 int height {0};
448 int framerate {0};
449 std::string encoder;
450 std::string gpu;
451 std::string failure;
452 std::int64_t checked_at {0};
453 std::string client;
454 };
455
460
465 void forget_capture_readiness(const std::string &client);
466
475
485 std::string name;
486 bool selected = false;
487 std::string outcome;
488 };
489
491 bool probed = false;
492 std::string encoder;
493 bool hardware = false;
494 bool h264 = false;
495 bool hevc = false;
496 bool av1 = false;
499 std::vector<encoder_attempt_t> attempts;
502 };
503
506
515 bool valid = false;
516 double encode_ms = 0.0;
517 double capture_to_encode_ms = 0.0;
518 double fps = 0.0;
519 double bitrate_kbps = 0.0;
520 uint64_t frames_encoded = 0;
521 uint64_t frames_dropped = 0;
522 int width = 0;
523 int height = 0;
524 };
525
532 void metrics_record_frame(double encode_ms, double capture_to_encode_ms, size_t packet_bytes);
533
535 void metrics_record_drop();
536
538 void metrics_reset();
539
549 void metrics_set_resolution(int width, int height);
550
553} // namespace video
Declarations for common platform specific utilities.
mem_type_e
Definition common.h:211
pix_fmt_e
Definition common.h:218
Declarations for gamepad, keyboard, and mouse input handling.
Handles process-wide communication.
Definition globals.h:25
Standalone NVENC encoder.
Codec and color depth for a capture readiness check.
Definition video.h:407
int dynamic_range
0: SDR 8-bit, 1: HDR 10-bit.
Definition video.h:409
int video_format
0: H.264, 1: HEVC, 2: AV1.
Definition video.h:408
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 frame_seen
Whether a real frame was captured and encoded.
Definition video.h:444
std::string encoder
The encoder, such as vaapi or nvenc.
Definition video.h:449
bool ok
Whether a frame went all the way through, or the display was only idle.
Definition video.h:443
std::string capture
What was captured, and how.
Definition video.h:445
bool checked
Whether a check has run since Hermes started.
Definition video.h:442
std::string gpu
The GPU it encodes on, where the platform can say.
Definition video.h:450
Result of the last encoder probe, for diagnostics/metrics.
Definition video.h:484
bool selected
True if this was the encoder ultimately chosen.
Definition video.h:486
std::string name
Encoder backend name (e.g. "nvenc", "vaapi").
Definition video.h:485
std::string outcome
Human-readable result, e.g. "selected", "unsupported_on_gpu", "probe_failed".
Definition video.h:487
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
Live per-frame pipeline metrics, for diagnostics/metrics.
Definition video.h:514
int width
Active stream width in pixels (0 until a session sets it).
Definition video.h:522
double fps
Measured frames encoded per second.
Definition video.h:518
int height
Active stream height in pixels (0 until a session sets it).
Definition video.h:523
double encode_ms
Avg time spent in the encoder per frame.
Definition video.h:516
uint64_t frames_encoded
Total frames encoded this session.
Definition video.h:520
uint64_t frames_dropped
Total frames dropped (encoder errors/timeouts).
Definition video.h:521
double bitrate_kbps
Measured output bitrate (kilobits/s).
Definition video.h:519
bool valid
At least one frame has been measured.
Definition video.h:515
double capture_to_encode_ms
Avg latency from capture to encode start.
Definition video.h:517
Declarations for thread-safe data structures.
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
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
encoder_status_t get_encoder_status()
Snapshot of the last encoder probe result (thread-safe copy).
Definition video.cpp:852
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 colorspace functions.