Sunshine master
Self-hosted game stream host for Moonlight.
video.h
Go to the documentation of this file.
1
5#pragma once
6
7// standard includes
8#include <chrono>
9
10// local includes
11#include "input.h"
12#include "platform/common.h"
13#include "thread_safe.h"
14#include "video_colorspace.h"
15
16extern "C" {
17#include <libavcodec/avcodec.h>
18#include <libswscale/swscale.h>
19}
20
21struct AVPacket;
22
23namespace video {
24
42
49 platf::mem_type_e map_base_dev_type(AVHWDeviceType type);
56 platf::pix_fmt_e map_pix_fmt(AVPixelFormat fmt);
57
63 void free_ctx(AVCodecContext *ctx);
69 void free_frame(AVFrame *frame);
75 void free_buffer(AVBufferRef *ref);
76
96 using img_event_t = std::shared_ptr<safe::event_t<std::shared_ptr<platf::img_t>>>;
97
109
117 using init_buffer_function_t = std::function<util::Either<avcodec_buffer_t, int>(platf::avcodec_encode_device_t *)>;
118
155
156 AVHWDeviceType avcodec_base_dev_type;
158 AVPixelFormat avcodec_dev_pix_fmt;
159 AVPixelFormat avcodec_pix_fmt_8bit;
160 AVPixelFormat avcodec_pix_fmt_10bit;
163
165 };
166
194
198 struct encoder_t {
199 std::string_view name;
200
213
220 static std::string_view from_flag(flag_e flag) {
221#ifndef DOXYGEN
222 #define _CONVERT(x) \
223 case flag_e::x: \
224 return std::string_view(#x)
225#endif
226 switch (flag) {
227 _CONVERT(PASSED);
228 _CONVERT(REF_FRAMES_RESTRICT);
229 _CONVERT(DYNAMIC_RANGE);
230 _CONVERT(YUV444);
231 _CONVERT(DYNAMIC_RANGE_YUV444);
232 _CONVERT(VUI_PARAMETERS);
233 _CONVERT(MAX_FLAGS);
234 }
235#undef _CONVERT
236
237 return {"unknown"};
238 }
239
243 struct option_t {
248 option_t(const option_t &) = default;
249
250 std::string name;
251 std::variant<int, int *, std::optional<int> *, std::function<int()>, std::string, std::string *, std::function<const std::string(const config_t &)>> value;
252
259 option_t(std::string &&name, decltype(value) &&value):
260 name {std::move(name)},
261 value {std::move(value)} {
262 }
263 };
264
265 const std::unique_ptr<const encoder_platform_formats_t> platform_formats;
266
270 struct codec_t {
271 std::vector<option_t> common_options;
272 std::vector<option_t> sdr_options;
273 std::vector<option_t> hdr_options;
274 std::vector<option_t> sdr444_options;
275 std::vector<option_t> hdr444_options;
276 std::vector<option_t> fallback_options;
277
278 std::string name;
279 std::bitset<MAX_FLAGS> capabilities;
280
287 bool operator[](flag_e flag) const {
288 return capabilities[(std::size_t) flag];
289 }
290
297 std::bitset<MAX_FLAGS>::reference operator[](flag_e flag) {
298 return capabilities[(std::size_t) flag];
299 }
300 };
301
305
312 const codec_t &codec_from_config(const config_t &config) const {
313 switch (config.videoFormat) {
314 default:
315 BOOST_LOG(error) << "Unknown video format " << config.videoFormat << ", falling back to H.264";
316 // fallthrough
317 case 0:
318 return h264;
319 case 1:
320 return hevc;
321 case 2:
322 return av1;
323 }
324 }
325
326 uint32_t flags;
327 };
328
333 virtual ~encode_session_t() = default;
334
341 virtual int convert(platf::img_t &img) = 0;
342
346 virtual void request_idr_frame() = 0;
347
351 virtual void request_normal_frame() = 0;
352
359 virtual void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) = 0;
360 };
361
362 // encoders
363 extern encoder_t software;
364
365#if !defined(__APPLE__)
366 extern encoder_t nvenc; // available for windows and linux
367#endif
368
369#ifdef _WIN32
370 extern encoder_t amdvce;
371 extern encoder_t quicksync;
373#endif
374
375#if defined(__linux__) || defined(linux) || defined(__linux) || defined(__FreeBSD__)
376 extern encoder_t vaapi;
377#endif
378
379#ifdef __APPLE__
380 extern encoder_t videotoolbox;
381#endif
382
387 virtual ~packet_raw_t() = default;
388
394 virtual bool is_idr() = 0;
395
401 virtual int64_t frame_index() = 0;
402
408 virtual uint8_t *data() = 0;
409
415 virtual size_t data_size() = 0;
416
420 struct replace_t {
421 std::string_view old;
422 std::string_view _new;
423
425
426
432 replace_t(std::string_view old, std::string_view _new) noexcept:
433 old {std::move(old)},
434 _new {std::move(_new)} {
435 }
436 };
437
438 std::vector<replace_t> *replacements = nullptr;
439 void *channel_data = nullptr;
441 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
442 };
443
449 av_packet = av_packet_alloc();
450 }
451
453 av_packet_free(&this->av_packet);
454 }
455
461 bool is_idr() override {
462 return av_packet->flags & AV_PKT_FLAG_KEY;
463 }
464
470 int64_t frame_index() override {
471 return av_packet->pts;
472 }
473
479 uint8_t *data() override {
480 return av_packet->data;
481 }
482
488 size_t data_size() override {
489 return av_packet->size;
490 }
491
492 AVPacket *av_packet;
493 };
494
506 packet_raw_generic(std::vector<uint8_t> &&frame_data, int64_t frame_index, bool idr):
507 frame_data {std::move(frame_data)},
509 idr {idr} {
510 }
511
517 bool is_idr() override {
518 return idr;
519 }
520
526 int64_t frame_index() override {
527 return index;
528 }
529
535 uint8_t *data() override {
536 return frame_data.data();
537 }
538
544 size_t data_size() override {
545 return frame_data.size();
546 }
547
548 std::vector<uint8_t> frame_data;
549 int64_t index;
550 bool idr;
551 };
552
556 using packet_t = std::unique_ptr<packet_raw_t>;
557
567 explicit hdr_info_raw_t(bool enabled):
569 metadata {} {};
576 explicit hdr_info_raw_t(bool enabled, const SS_HDR_METADATA &metadata):
578 metadata {metadata} {};
579
580 bool enabled;
581 SS_HDR_METADATA metadata;
582 };
583
587 using hdr_info_t = std::unique_ptr<hdr_info_raw_t>;
588
589 extern int active_hevc_mode;
590 extern int active_av1_mode;
592 extern std::array<bool, 3> last_encoder_probe_supported_yuv444_for_codec; // 0 - H.264, 1 - HEVC, 2 - AV1
593
594 void capture(
596 config_t config,
597 void *channel_data
598 );
599
607 bool validate_encoder(encoder_t &encoder, bool expect_failure);
608
618 int probe_encoders();
619
620 // Several NTSC standard refresh rates are hardcoded here, because their
621 // true rate requires a denominator of 1001. ffmpeg's av_d2q() would assume it could
622 // reduce 29.97 to 2997/100 but this would be slightly wrong. We also include
623 // support for 23.976 film in case someone wants to stream a film at the perfect
624 // framerate.
631 inline AVRational framerateX100_to_rational(const int framerateX100) {
632 if (framerateX100 % 2997 == 0) {
633 // Multiples of NTSC 29.97 e.g. 59.94, 119.88
634 return AVRational {(framerateX100 / 2997) * 30000, 1001};
635 }
636 switch (framerateX100) {
637 case 2397: // the other weird NTSC framerate, assume these want 23.976 film
638 case 2398:
639 return AVRational {24000, 1001};
640 default:
641 // any other fractional rate can be reduced by ffmpeg. Max is set to 1 << 26 based on docs:
642 // "rational numbers with |num| <= 1<<26 && |den| <= 1<<26 can be recovered exactly from their double representation"
643 return av_d2q((double) framerateX100 / 100.0f, 1 << 26);
644 }
645 }
646
655 inline AVRational framerate_to_rational(const config_t &config) {
656 if (config.framerateX100 > 0) {
658 }
659 return AVRational {config.framerate, 1};
660 }
661
669 inline std::chrono::nanoseconds capture_frame_interval(const config_t &config) {
670 const AVRational fps = framerate_to_rational(config);
671 return std::chrono::nanoseconds {(static_cast<int64_t>(fps.den) * 1'000'000'000LL) / fps.num};
672 }
673} // namespace video
Unique pointer wrapper with customizable pointer and deleter types.
Definition utility.h:820
Declarations for common platform specific utilities.
mem_type_e
Enumerates supported mem type options.
Definition common.h:303
pix_fmt_e
Enumerates supported pix fmt options.
Definition common.h:316
video_t video
Default video configuration values used before file and CLI overrides.
Definition config.cpp:623
void free_frame(AVFrame *frame)
Release an FFmpeg frame allocated by the capture or conversion backend.
Definition graphics.cpp:1403
Declarations for gamepad, keyboard, and mouse input handling.
bl::sources::severity_logger< int > error
Recoverable errors.
Definition logging.cpp:44
Handles process-wide communication.
Definition globals.h:34
Standalone NVENC encoder.
Definition nvenc_base.cpp:94
AVCodec-backed encode device and frame state.
Definition common.h:566
Captured frame buffer shared between capture and encode stages.
Definition common.h:502
Encoding configuration requested by a remote client.
Definition video.h:28
int encoderCscMode
Requested color range and SDR colorspace; HDR always uses BT.2020 and ST2084.
Definition video.h:36
int enableIntraRefresh
Intra refresh setting: 0 = disabled, 1 = enabled.
Definition video.h:40
int framerateX100
Optional NTSC-style framerate value, e.g. 59.94 as 5994.
Definition video.h:32
int videoFormat
Video codec format: 0 = H.264, 1 = HEVC, 2 = AV1.
Definition video.h:37
int width
Video width in pixels.
Definition video.h:29
int bitrate
Video bitrate in kilobits for the requested framerate.
Definition video.h:33
int numRefFrames
Maximum number of reference frames.
Definition video.h:35
int height
Video height in pixels.
Definition video.h:30
int slicesPerFrame
Number of slices per frame.
Definition video.h:34
int framerate
Requested framerate used in the per-frame bitrate budget.
Definition video.h:31
int dynamicRange
Encoding color depth: 0 = 8-bit, 1 = 10-bit.
Definition video.h:38
int chromaSamplingType
Chroma sampling type: 0 = 4:2:0, 1 = 4:4:4.
Definition video.h:39
Encoder session state shared by capture and encoding threads.
Definition video.h:332
virtual int convert(platf::img_t &img)=0
Convert a captured frame into the encoder's required input representation.
virtual void request_idr_frame()=0
Mark the frame as a request for an IDR frame.
virtual void request_normal_frame()=0
Mark the frame as a request for a normal inter frame.
virtual void invalidate_ref_frames(int64_t first_frame, int64_t last_frame)=0
Mark the frame range whose references must be invalidated.
AVCodec-specific pixel formats supported by a platform.
Definition video.h:113
AVPixelFormat avcodec_pix_fmt_8bit
FFmpeg 8-bit 4:2:0 software pixel format for this encoder.
Definition video.h:159
encoder_platform_formats_avcodec(const AVHWDeviceType &avcodec_base_dev_type, const AVHWDeviceType &avcodec_derived_dev_type, const AVPixelFormat &avcodec_dev_pix_fmt, const AVPixelFormat &avcodec_pix_fmt_8bit, const AVPixelFormat &avcodec_pix_fmt_10bit, const AVPixelFormat &avcodec_pix_fmt_yuv444_8bit, const AVPixelFormat &avcodec_pix_fmt_yuv444_10bit, const init_buffer_function_t &init_avcodec_hardware_input_buffer_function)
Construct AVCodec platform format mappings.
Definition video.h:131
AVPixelFormat avcodec_pix_fmt_10bit
FFmpeg 10-bit 4:2:0 software pixel format for this encoder.
Definition video.h:160
AVHWDeviceType avcodec_derived_dev_type
FFmpeg device type derived from the primary hardware context.
Definition video.h:157
AVPixelFormat avcodec_pix_fmt_yuv444_8bit
FFmpeg 8-bit 4:4:4 software pixel format for this encoder.
Definition video.h:161
std::function< util::Either< avcodec_buffer_t, int >(platf::avcodec_encode_device_t *)> init_buffer_function_t
Callback that prepares an FFmpeg hardware input buffer for the encode device.
Definition video.h:117
AVPixelFormat avcodec_pix_fmt_yuv444_10bit
FFmpeg 10-bit 4:4:4 software pixel format for this encoder.
Definition video.h:162
init_buffer_function_t init_avcodec_hardware_input_buffer
Backend hook that allocates or imports hardware frames for FFmpeg.
Definition video.h:164
AVPixelFormat avcodec_dev_pix_fmt
FFmpeg hardware-device pixel format for frames handed to the encoder.
Definition video.h:158
AVHWDeviceType avcodec_base_dev_type
FFmpeg device type used to create the primary hardware context.
Definition video.h:156
NVENC-specific pixel formats supported by a platform.
Definition video.h:170
encoder_platform_formats_nvenc(const platf::mem_type_e &dev_type, const platf::pix_fmt_e &pix_fmt_8bit, const platf::pix_fmt_e &pix_fmt_10bit, const platf::pix_fmt_e &pix_fmt_yuv444_8bit, const platf::pix_fmt_e &pix_fmt_yuv444_10bit)
Construct NVENC platform format mappings.
Definition video.h:180
Pixel formats supported by one encoder backend.
Definition video.h:101
platf::mem_type_e dev_type
Platform memory type required by this encoder.
Definition video.h:103
platf::pix_fmt_e pix_fmt_10bit
10-bit 4:2:0 input format accepted by this encoder.
Definition video.h:105
platf::pix_fmt_e pix_fmt_yuv444_8bit
8-bit 4:4:4 input format accepted by this encoder.
Definition video.h:106
platf::pix_fmt_e pix_fmt_8bit
8-bit 4:2:0 input format accepted by this encoder.
Definition video.h:104
platf::pix_fmt_e pix_fmt_yuv444_10bit
10-bit 4:4:4 input format accepted by this encoder.
Definition video.h:107
Codec capabilities for AV1, HEVC, or H.264.
Definition video.h:270
std::bitset< MAX_FLAGS > capabilities
Capability flags supported by this codec on the encoder.
Definition video.h:279
std::vector< option_t > sdr_options
Options applied to SDR 4:2:0 streams.
Definition video.h:272
std::string name
Codec name passed to the encoder backend.
Definition video.h:278
std::vector< option_t > sdr444_options
Options applied to SDR 4:4:4 streams.
Definition video.h:274
std::vector< option_t > common_options
Options applied to every encode mode for this codec.
Definition video.h:271
std::bitset< MAX_FLAGS >::reference operator[](flag_e flag)
Return a mutable reference to a codec capability flag.
Definition video.h:297
std::vector< option_t > hdr_options
Options applied to HDR 4:2:0 streams.
Definition video.h:273
bool operator[](flag_e flag) const
Test whether a codec capability is enabled.
Definition video.h:287
std::vector< option_t > fallback_options
Options used when the preferred mode cannot be selected.
Definition video.h:276
std::vector< option_t > hdr444_options
Options applied to HDR 4:4:4 streams.
Definition video.h:275
Runtime encoder option exposed to configuration parsing.
Definition video.h:243
std::variant< int, int *, std::optional< int > *, std::function< int()>, std::string, std::string *, std::function< const std::string(const config_t &)> > value
Literal, pointer, or callback that supplies the option value.
Definition video.h:251
std::string name
Encoder command-line option name.
Definition video.h:250
Encoder name and feature flags advertised by Sunshine.
Definition video.h:198
codec_t av1
AV1 codec capability and option set.
Definition video.h:302
codec_t hevc
HEVC codec capability and option set.
Definition video.h:303
static std::string_view from_flag(flag_e flag)
Convert an encoder capability flag to its diagnostic string.
Definition video.h:220
const std::unique_ptr< const encoder_platform_formats_t > platform_formats
Platform-specific memory and pixel formats accepted by the encoder.
Definition video.h:265
const codec_t & codec_from_config(const config_t &config) const
Select the codec descriptor requested by a stream configuration.
Definition video.h:312
std::string_view name
Encoder name used in logs, configuration, and capability probes.
Definition video.h:199
flag_e
Capability flags that describe which stream modes an encoder supports.
Definition video.h:204
@ DYNAMIC_RANGE
HDR support.
Definition video.h:207
@ DYNAMIC_RANGE_YUV444
YUV 4:4:4 HDR support.
Definition video.h:209
@ VUI_PARAMETERS
AMD encoder with VAAPI doesn't add VUI parameters to SPS.
Definition video.h:210
@ PASSED
Indicates the encoder is supported.
Definition video.h:205
@ REF_FRAMES_RESTRICT
Set maximum reference frames.
Definition video.h:206
@ YUV444
YUV 4:4:4 support.
Definition video.h:208
@ MAX_FLAGS
Maximum number of flags.
Definition video.h:211
uint32_t flags
Encoder flags advertised to clients through GameStream capability responses.
Definition video.h:326
codec_t h264
H.264 codec capability and option set.
Definition video.h:304
Raw HDR metadata fields parsed from the display backend.
Definition video.h:561
bool enabled
Whether HDR mode should be enabled.
Definition video.h:580
SS_HDR_METADATA metadata
Display HDR metadata forwarded to the encoder and client.
Definition video.h:581
hdr_info_raw_t(bool enabled, const SS_HDR_METADATA &metadata)
Initialize HDR metadata with display metadata from the backend.
Definition video.h:576
hdr_info_raw_t(bool enabled)
Initialize HDR metadata with only the enabled state.
Definition video.h:567
AVCodec packet wrapper with codec-specific metadata.
Definition video.h:447
uint8_t * data() override
Return writable access to the FFmpeg packet payload.
Definition video.h:479
size_t data_size() override
Return the FFmpeg packet payload length.
Definition video.h:488
AVPacket * av_packet
FFmpeg packet that owns encoded data and frame metadata.
Definition video.h:492
bool is_idr() override
Report whether the FFmpeg packet is marked as a key frame.
Definition video.h:461
int64_t frame_index() override
Return the FFmpeg packet PTS used as Sunshine's frame index.
Definition video.h:470
Generic encoded packet bytes and metadata.
Definition video.h:498
uint8_t * data() override
Return writable access to the generic packet payload.
Definition video.h:535
bool is_idr() override
Report whether the generic packet starts an IDR frame.
Definition video.h:517
std::vector< uint8_t > frame_data
Encoded frame bytes owned by this packet.
Definition video.h:548
int64_t frame_index() override
Return the stored frame index for this generic packet.
Definition video.h:526
int64_t index
Monotonic frame index assigned to this packet.
Definition video.h:549
packet_raw_generic(std::vector< uint8_t > &&frame_data, int64_t frame_index, bool idr)
Wrap generic encoded frame bytes in Sunshine packet metadata.
Definition video.h:506
bool idr
Whether the packet belongs to an IDR frame.
Definition video.h:550
size_t data_size() override
Return the generic packet payload length.
Definition video.h:544
Packet byte-range replacement descriptor.
Definition video.h:420
std::string_view _new
Byte sequence that replaces old before transmission.
Definition video.h:422
std::string_view old
Byte sequence to find in the encoded packet.
Definition video.h:421
Encoded packet wrapper used by the streaming pipeline.
Definition video.h:386
virtual size_t data_size()=0
Return the encoded payload length.
virtual bool is_idr()=0
Report whether this packet starts an IDR frame.
std::vector< replace_t > * replacements
Optional encoded-byte substitutions applied before packetization.
Definition video.h:438
void * channel_data
Platform or protocol state carried with this packet.
Definition video.h:439
virtual int64_t frame_index()=0
Return the frame index associated with this encoded packet.
bool after_ref_frame_invalidation
Whether the frame follows reference-frame invalidation.
Definition video.h:440
virtual uint8_t * data()=0
Return writable access to the encoded packet bytes.
std::optional< std::chrono::steady_clock::time_point > frame_timestamp
Capture timestamp associated with the frame.
Definition video.h:441
Declarations for thread-safe data structures.
std::shared_ptr< mail_raw_t > mail_t
Shared mailbox handle used by event and queue wrappers.
Definition thread_safe.h:737
#define KITTY_DEFAULT_CONSTR_MOVE(x)
Declare defaulted noexcept move construction and assignment for a type.
Definition utility.h:120
encoder_t vaapi
VA-API.
Definition video.cpp:1178
platf::mem_type_e map_base_dev_type(AVHWDeviceType type)
Map base dev type values.
Definition video.cpp:3633
bool validate_encoder(encoder_t &encoder, bool expect_failure)
Validate encoder before it is used.
Definition video.cpp:2997
encoder_t mediafoundation
Mediafoundation.
Definition video.cpp:1043
int active_hevc_mode
HEVC mode selected by the most recent encoder probe.
Definition video.cpp:1404
void free_ctx(AVCodecContext *ctx)
Release context resources.
Definition video.cpp:78
int active_av1_mode
AV1 mode selected by the most recent encoder probe.
Definition video.cpp:1405
std::array< bool, 3 > last_encoder_probe_supported_yuv444_for_codec
YUV444 support discovered for each probed codec.
Definition video.cpp:1407
encoder_t amdvce
Amdvce.
Definition video.cpp:934
int probe_encoders()
Probe encoders and select the preferred encoder. This is called once at startup and each time a strea...
Definition video.cpp:3199
encoder_t quicksync
Quicksync.
Definition video.cpp:823
bool last_encoder_probe_supported_ref_frames_invalidation
Whether the last probe found reference-frame invalidation support.
Definition video.cpp:1406
platf::pix_fmt_e map_pix_fmt(AVPixelFormat fmt)
Map pix fmt values.
Definition video.cpp:3659
encoder_t videotoolbox
Videotoolbox.
Definition video.cpp:1311
encoder_t software
Software.
Definition video.cpp:1104
AVRational framerateX100_to_rational(const int framerateX100)
Convert a framerate stored as hundredths of Hz to an FFmpeg rational.
Definition video.h:631
std::chrono::nanoseconds capture_frame_interval(const config_t &config)
Capture frame interval for the requested framerate. Uses the exact fractional rate when the client pr...
Definition video.h:669
std::unique_ptr< packet_raw_t > packet_t
Owning pointer to an encoded packet abstraction.
Definition video.h:556
std::shared_ptr< safe::event_t< std::shared_ptr< platf::img_t > > > img_event_t
Shared event that transports captured images between capture and encode threads.
Definition video.h:96
AVRational framerate_to_rational(const config_t &config)
Requested framerate as an exact rational. Uses the exact fractional rate when the client provided an ...
Definition video.h:655
std::unique_ptr< hdr_info_raw_t > hdr_info_t
Owning pointer to optional HDR metadata for a captured display.
Definition video.h:587
Declarations for colorspace functions.