Sunshine latest
Self-hosted game stream host for Moonlight.
common.h
Go to the documentation of this file.
1
5#pragma once
6
7// standard includes
8#include <bitset>
9#include <filesystem>
10#include <functional>
11#include <mutex>
12#include <string>
13
14// lib includes
15#include <boost/core/noncopyable.hpp>
16#ifndef _WIN32
17 #include <boost/asio.hpp>
18 #include <boost/process.hpp>
19#endif
20
21// local includes
22#include "src/config.h"
23#include "src/logging.h"
24#include "src/thread_safe.h"
25#include "src/utility.h"
27
28extern "C" {
29#include <moonlight-common-c/src/Limelight.h>
30}
31
32using namespace std::literals;
33
34struct sockaddr;
35struct AVFrame;
36struct AVBufferRef;
37struct AVHWFramesContext;
38struct AVCodecContext;
39struct AVDictionary;
40
41#ifdef _WIN32
42// Forward declarations of boost classes to avoid having to include boost headers
43// here, which results in issues with Windows.h and WinSock2.h include order.
44namespace boost {
45 namespace asio {
46 namespace ip {
47 class address;
48 } // namespace ip
49 } // namespace asio
50
51 namespace filesystem {
52 class path;
53 }
54
55 namespace process::inline v1 {
56 class child;
57 class group;
58 template<typename Char>
61 } // namespace process::inline v1
62} // namespace boost
63#endif
64namespace video {
65 struct config_t;
66} // namespace video
67
68namespace nvenc {
69 class nvenc_base;
70}
71
72namespace platf {
73 // Limited by bits in activeGamepadMask
74 constexpr auto MAX_GAMEPADS = 16;
75
76 constexpr std::uint32_t DPAD_UP = 0x0001;
77 constexpr std::uint32_t DPAD_DOWN = 0x0002;
78 constexpr std::uint32_t DPAD_LEFT = 0x0004;
79 constexpr std::uint32_t DPAD_RIGHT = 0x0008;
80 constexpr std::uint32_t START = 0x0010;
81 constexpr std::uint32_t BACK = 0x0020;
82 constexpr std::uint32_t LEFT_STICK = 0x0040;
83 constexpr std::uint32_t RIGHT_STICK = 0x0080;
84 constexpr std::uint32_t LEFT_BUTTON = 0x0100;
85 constexpr std::uint32_t RIGHT_BUTTON = 0x0200;
86 constexpr std::uint32_t HOME = 0x0400;
87 constexpr std::uint32_t A = 0x1000;
88 constexpr std::uint32_t B = 0x2000;
89 constexpr std::uint32_t X = 0x4000;
90 constexpr std::uint32_t Y = 0x8000;
91 constexpr std::uint32_t PADDLE1 = 0x010000;
92 constexpr std::uint32_t PADDLE2 = 0x020000;
93 constexpr std::uint32_t PADDLE3 = 0x040000;
94 constexpr std::uint32_t PADDLE4 = 0x080000;
95 constexpr std::uint32_t TOUCHPAD_BUTTON = 0x100000;
96 constexpr std::uint32_t MISC_BUTTON = 0x200000;
97
99 std::string name;
100 bool is_enabled;
101 std::string reason_disabled;
102 };
103
110
112 static gamepad_feedback_msg_t make_rumble(std::uint16_t id, std::uint16_t lowfreq, std::uint16_t highfreq) {
114 msg.type = gamepad_feedback_e::rumble;
115 msg.id = id;
116 msg.data.rumble = {lowfreq, highfreq};
117 return msg;
118 }
119
120 static gamepad_feedback_msg_t make_rumble_triggers(std::uint16_t id, std::uint16_t left, std::uint16_t right) {
122 msg.type = gamepad_feedback_e::rumble_triggers;
123 msg.id = id;
124 msg.data.rumble_triggers = {left, right};
125 return msg;
126 }
127
128 static gamepad_feedback_msg_t make_motion_event_state(std::uint16_t id, std::uint8_t motion_type, std::uint16_t report_rate) {
130 msg.type = gamepad_feedback_e::set_motion_event_state;
131 msg.id = id;
132 msg.data.motion_event_state.motion_type = motion_type;
133 msg.data.motion_event_state.report_rate = report_rate;
134 return msg;
135 }
136
137 static gamepad_feedback_msg_t make_rgb_led(std::uint16_t id, std::uint8_t r, std::uint8_t g, std::uint8_t b) {
139 msg.type = gamepad_feedback_e::set_rgb_led;
140 msg.id = id;
141 msg.data.rgb_led = {r, g, b};
142 return msg;
143 }
144
146 std::uint16_t id;
147
148 union {
149 struct {
150 std::uint16_t lowfreq;
151 std::uint16_t highfreq;
152 } rumble;
153
154 struct {
155 std::uint16_t left_trigger;
156 std::uint16_t right_trigger;
157 } rumble_triggers;
158
159 struct {
160 std::uint16_t report_rate;
161 std::uint8_t motion_type;
162 } motion_event_state;
163
164 struct {
165 std::uint8_t r;
166 std::uint8_t g;
167 std::uint8_t b;
168 } rgb_led;
169 } data;
170 };
171
172 using feedback_queue_t = safe::mail_raw_t::queue_t<gamepad_feedback_msg_t>;
173
174 namespace speaker {
186
187 constexpr std::uint8_t map_stereo[] {
188 FRONT_LEFT,
189 FRONT_RIGHT
190 };
191 constexpr std::uint8_t map_surround51[] {
192 FRONT_LEFT,
193 FRONT_RIGHT,
194 FRONT_CENTER,
195 LOW_FREQUENCY,
196 BACK_LEFT,
197 BACK_RIGHT,
198 };
199 constexpr std::uint8_t map_surround71[] {
204 BACK_LEFT,
206 SIDE_LEFT,
208 };
209 } // namespace speaker
210
211 enum class mem_type_e {
212 system,
213 vaapi,
214 dxgi,
215 cuda,
216 videotoolbox,
217 unknown
218 };
219
220 enum class pix_fmt_e {
221 yuv420p,
222 yuv420p10,
223 nv12,
224 p010,
225 ayuv,
226 yuv444p16,
227 y410,
228 unknown
229 };
230
231 inline std::string_view from_pix_fmt(pix_fmt_e pix_fmt) {
232 using namespace std::literals;
233#define _CONVERT(x) \
234 case pix_fmt_e::x: \
235 return #x##sv
236 switch (pix_fmt) {
237 _CONVERT(yuv420p);
238 _CONVERT(yuv420p10);
239 _CONVERT(nv12);
240 _CONVERT(p010);
241 _CONVERT(ayuv);
242 _CONVERT(yuv444p16);
243 _CONVERT(y410);
244 _CONVERT(unknown);
245 }
246#undef _CONVERT
247
248 return "unknown"sv;
249 }
250
251 // Dimensions for touchscreen input
253 int offset_x, offset_y;
254 int width, height;
255 };
256
257 // These values must match Limelight-internal.h's SS_FF_* constants!
258 namespace platform_caps {
259 typedef uint32_t caps_t;
260
261 constexpr caps_t pen_touch = 0x01; // Pen and touch events
262 constexpr caps_t controller_touch = 0x02; // Controller touch events
263 }; // namespace platform_caps
264
266 std::uint32_t buttonFlags;
267 std::uint8_t lt;
268 std::uint8_t rt;
269 std::int16_t lsX;
270 std::int16_t lsY;
271 std::int16_t rsX;
272 std::int16_t rsY;
273 };
274
276 // The global index is used when looking up gamepads in the platform's
277 // gamepad array. It identifies gamepads uniquely among all clients.
278 int globalIndex;
279
280 // The client-relative index is the controller number as reported by the
281 // client. It must be used when communicating back to the client via
282 // the input feedback queue.
283 std::uint8_t clientRelativeIndex;
284 };
285
287 std::uint8_t type;
288 std::uint16_t capabilities;
289 std::uint32_t supportedButtons;
290 };
291
293 gamepad_id_t id;
294 std::uint8_t eventType;
295 std::uint32_t pointerId;
296 float x;
297 float y;
298 float pressure;
299 };
300
302 gamepad_id_t id;
303 std::uint8_t motionType;
304
305 // Accel: m/s^2
306 // Gyro: deg/s
307 float x;
308 float y;
309 float z;
310 };
311
313 gamepad_id_t id;
314 std::uint8_t state;
315 std::uint8_t percentage;
316 };
317
319 std::uint8_t eventType;
320 std::uint16_t rotation; // Degrees (0..360) or LI_ROT_UNKNOWN
321 std::uint32_t pointerId;
322 float x;
323 float y;
324 float pressureOrDistance; // Distance for hover and pressure for contact
325 float contactAreaMajor;
326 float contactAreaMinor;
327 };
328
329 struct pen_input_t {
330 std::uint8_t eventType;
331 std::uint8_t toolType;
332 std::uint8_t penButtons;
333 std::uint8_t tilt; // Degrees (0..90) or LI_TILT_UNKNOWN
334 std::uint16_t rotation; // Degrees (0..360) or LI_ROT_UNKNOWN
335 float x;
336 float y;
337 float pressureOrDistance; // Distance for hover and pressure for contact
338 float contactAreaMajor;
339 float contactAreaMinor;
340 };
341
342 class deinit_t {
343 public:
344 virtual ~deinit_t() = default;
345 };
346
347 struct img_t: std::enable_shared_from_this<img_t> {
348 public:
349 img_t() = default;
350
351 img_t(img_t &&) = delete;
352 img_t(const img_t &) = delete;
353 img_t &operator=(img_t &&) = delete;
354 img_t &operator=(const img_t &) = delete;
355
356 std::uint8_t *data {};
357 std::int32_t width {};
358 std::int32_t height {};
359 std::int32_t pixel_pitch {};
360 std::int32_t row_pitch {};
361
362 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
363
364 virtual ~img_t() = default;
365 };
366
367 struct sink_t {
368 // Play on host PC
369 std::string host;
370
371 // On macOS and Windows, it is not possible to create a virtual sink
372 // Therefore, it is optional
373 struct null_t {
374 std::string stereo;
375 std::string surround51;
376 std::string surround71;
377 };
378
379 std::optional<null_t> null;
380 };
381
383 virtual ~encode_device_t() = default;
384
385 virtual int convert(platf::img_t &img) = 0;
386
388 };
389
391 void *data {};
392 AVFrame *frame {};
393
394 int convert(platf::img_t &img) override {
395 return -1;
396 }
397
398 virtual void apply_colorspace() {
399 }
400
405 virtual int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) {
406 BOOST_LOG(error) << "Illegal call to hwdevice_t::set_frame(). Did you forget to override it?";
407 return -1;
408 };
409
414 virtual void init_hwframes(AVHWFramesContext *frames) {};
415
420 virtual void init_codec_options(AVCodecContext *ctx, AVDictionary **options) {};
421
426 virtual int prepare_to_derive_context(int hw_device_type) {
427 return 0;
428 };
429 };
430
432 virtual bool init_encoder(const video::config_t &client_config, const video::sunshine_colorspace_t &colorspace) = 0;
433
434 nvenc::nvenc_base *nvenc = nullptr;
435 };
436
437 enum class capture_e : int {
438 ok,
439 reinit,
440 timeout,
442 error
443 };
444
445 class display_t {
446 public:
454 using push_captured_image_cb_t = std::function<bool(std::shared_ptr<img_t> &&img, bool frame_captured)>;
455
463 using pull_free_image_cb_t = std::function<bool(std::shared_ptr<img_t> &img_out)>;
464
465 display_t() noexcept:
466 offset_x {0},
467 offset_y {0} {
468 }
469
482 virtual capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor) = 0;
483
484 virtual std::shared_ptr<img_t> alloc_img() = 0;
485
486 virtual int dummy_img(img_t *img) = 0;
487
488 virtual std::unique_ptr<avcodec_encode_device_t> make_avcodec_encode_device(pix_fmt_e pix_fmt) {
489 return nullptr;
490 }
491
492 virtual std::unique_ptr<nvenc_encode_device_t> make_nvenc_encode_device(pix_fmt_e pix_fmt) {
493 return nullptr;
494 }
495
496 virtual bool is_hdr() {
497 return false;
498 }
499
500 virtual bool get_hdr_metadata(SS_HDR_METADATA &metadata) {
501 std::memset(&metadata, 0, sizeof(metadata));
502 return false;
503 }
504
511 virtual bool is_codec_supported(std::string_view name, const ::video::config_t &config) {
512 return true;
513 }
514
515 virtual ~display_t() = default;
516
517 // Offsets for when streaming a specific monitor. By default, they are 0.
518 int offset_x, offset_y;
519 int env_width, env_height;
520
521 int width, height;
522
523 protected:
524 // collect capture timing data (at loglevel debug)
525 logging::time_delta_periodic_logger sleep_overshoot_logger = {debug, "Frame capture sleep overshoot"};
526 };
527
528 class mic_t {
529 public:
530 virtual capture_e sample(std::vector<float> &frame_buffer) = 0;
531
532 virtual ~mic_t() = default;
533 };
534
536 public:
537 virtual int set_sink(const std::string &sink) = 0;
538
539 virtual std::unique_ptr<mic_t> microphone(const std::uint8_t *mapping, int channels, std::uint32_t sample_rate, std::uint32_t frame_size) = 0;
540
546 virtual bool is_sink_available(const std::string &sink) = 0;
547
548 virtual std::optional<sink_t> sink_info() = 0;
549
550 virtual ~audio_control_t() = default;
551 };
552
553 void freeInput(void *);
554
556
557 std::filesystem::path appdata();
558
559 std::string get_mac_address(const std::string_view &address);
560
561 std::string from_sockaddr(const sockaddr *const);
562 std::pair<std::uint16_t, std::string> from_sockaddr_ex(const sockaddr *const);
563
564 std::unique_ptr<audio_control_t> audio_control();
565
574 std::shared_ptr<display_t> display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config);
575
576 // A list of names of displays accepted as display_name with the mem_type_e
577 std::vector<std::string> display_names(mem_type_e hwdevice_type);
578
584
585 boost::process::v1::child run_command(bool elevated, bool interactive, const std::string &cmd, boost::filesystem::path &working_dir, const boost::process::v1::environment &env, FILE *file, std::error_code &ec, boost::process::v1::group *group);
586
587 enum class thread_priority_e : int {
588 low,
589 normal,
590 high,
591 critical
592 };
593 void adjust_thread_priority(thread_priority_e priority);
594
595 // Allow OS-specific actions to be taken to prepare for streaming
596 void streaming_will_start();
597 void streaming_will_stop();
598
599 void restart();
600
607 int set_env(const std::string &name, const std::string &value);
608
614 int unset_env(const std::string &name);
615
617 const char *buffer;
618 size_t size;
619
620 // Constructors required for emplace_back() prior to C++20
621 buffer_descriptor_t(const char *buffer, size_t size):
622 buffer(buffer),
623 size(size) {
624 }
625
627 buffer(nullptr),
628 size(0) {
629 }
630 };
631
633 // Optional headers to be prepended to each packet
634 const char *headers;
635 size_t header_size;
636
637 // One or more data buffers to use for the payloads
638 //
639 // NB: Data buffers must be aligned to payload size!
640 std::vector<buffer_descriptor_t> &payload_buffers;
641 size_t payload_size;
642
643 // The offset (in header+payload message blocks) in the header and payload
644 // buffers to begin sending messages from
645 size_t block_offset;
646
647 // The number of header+payload message blocks to send
648 size_t block_count;
649
650 std::uintptr_t native_socket;
651 boost::asio::ip::address &target_address;
652 uint16_t target_port;
653 boost::asio::ip::address &source_address;
654
661 for (const auto &desc : payload_buffers) {
662 if (offset < desc.size) {
663 return {
664 desc.buffer + offset,
665 desc.size - offset,
666 };
667 } else {
668 offset -= desc.size;
669 }
670 }
671 return {};
672 }
673 };
674
675 bool send_batch(batched_send_info_t &send_info);
676
677 struct send_info_t {
678 const char *header;
679 size_t header_size;
680 const char *payload;
681 size_t payload_size;
682
683 std::uintptr_t native_socket;
684 boost::asio::ip::address &target_address;
685 uint16_t target_port;
686 boost::asio::ip::address &source_address;
687 };
688
689 bool send(send_info_t &send_info);
690
691 enum class qos_data_type_e : int {
692 audio,
693 video
694 };
695
704 std::unique_ptr<deinit_t> enable_socket_qos(uintptr_t native_socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging);
705
710 void open_url(const std::string &url);
711
717 bool request_process_group_exit(std::uintptr_t native_handle);
718
724 bool process_group_running(std::uintptr_t native_handle);
725
726 input_t input();
735 util::point_t get_mouse_loc(input_t &input);
736 void move_mouse(input_t &input, int deltaX, int deltaY);
737 void abs_mouse(input_t &input, const touch_port_t &touch_port, float x, float y);
738 void button_mouse(input_t &input, int button, bool release);
739 void scroll(input_t &input, int distance);
740 void hscroll(input_t &input, int distance);
741 void keyboard_update(input_t &input, uint16_t modcode, bool release, uint8_t flags);
742 void gamepad_update(input_t &input, int nr, const gamepad_state_t &gamepad_state);
743 void unicode(input_t &input, char *utf8, int size);
744
745 typedef deinit_t client_input_t;
746
752 std::unique_ptr<client_input_t> allocate_client_input_context(input_t &input);
753
760 void touch_update(client_input_t *input, const touch_port_t &touch_port, const touch_input_t &touch);
761
768 void pen_update(client_input_t *input, const touch_port_t &touch_port, const pen_input_t &pen);
769
775 void gamepad_touch(input_t &input, const gamepad_touch_t &touch);
776
782 void gamepad_motion(input_t &input, const gamepad_motion_t &motion);
783
789 void gamepad_battery(input_t &input, const gamepad_battery_t &battery);
790
799 int alloc_gamepad(input_t &input, const gamepad_id_t &id, const gamepad_arrival_t &metadata, feedback_queue_t feedback_queue);
800 void free_gamepad(input_t &input, int nr);
801
806 platform_caps::caps_t get_capabilities();
807
808#define SERVICE_NAME "Sunshine"
809#define SERVICE_TYPE "_nvstream._tcp"
810
811 namespace publish {
812 [[nodiscard]] std::unique_ptr<deinit_t> start();
813 }
814
815 [[nodiscard]] std::unique_ptr<deinit_t> init();
816
821 std::string get_host_name();
822
829 std::vector<supported_gamepad_t> &supported_gamepads(input_t *input);
830
831 struct high_precision_timer: private boost::noncopyable {
832 virtual ~high_precision_timer() = default;
833
838 virtual void sleep_for(const std::chrono::nanoseconds &duration) = 0;
839
844 virtual operator bool() = 0;
845 };
846
851 std::unique_ptr<high_precision_timer> create_high_precision_timer();
852
853} // namespace platf
Definition common.h:59
A helper class for tracking and logging short time intervals across a period of time.
Definition logging.h:166
Abstract platform-agnostic base of standalone NVENC encoder. Derived classes perform platform-specifi...
Definition nvenc_base.h:26
Definition common.h:535
virtual bool is_sink_available(const std::string &sink)=0
Check if the audio sink is available in the system.
Definition common.h:342
Definition common.h:445
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:511
std::function< bool(std::shared_ptr< img_t > &&img, bool frame_captured)> push_captured_image_cb_t
Callback for when a new image is ready. When display has a new image ready or a timeout occurs,...
Definition common.h:454
std::function< bool(std::shared_ptr< img_t > &img_out)> pull_free_image_cb_t
Get free image from pool. Calls must be synchronized. Blocks until there is free image in the pool or...
Definition common.h:463
virtual capture_e capture(const push_captured_image_cb_t &push_captured_image_cb, const pull_free_image_cb_t &pull_free_image_cb, bool *cursor)=0
Capture a frame.
Definition common.h:528
Definition utility.h:530
mem_type_e
Definition common.h:211
@ system
System memory.
speaker_e
Definition common.h:175
@ BACK_LEFT
Back left.
Definition common.h:180
@ LOW_FREQUENCY
Low frequency.
Definition common.h:179
@ SIDE_RIGHT
Side right.
Definition common.h:183
@ MAX_SPEAKERS
Maximum number of speakers.
Definition common.h:184
@ FRONT_LEFT
Front left.
Definition common.h:176
@ SIDE_LEFT
Side left.
Definition common.h:182
@ FRONT_CENTER
Front center.
Definition common.h:178
@ BACK_RIGHT
Back right.
Definition common.h:181
@ FRONT_RIGHT
Front right.
Definition common.h:177
std::vector< supported_gamepad_t > & supported_gamepads(input_t *input)
Gets the supported gamepads for this platform backend.
Definition inputtino.cpp:130
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:864
pix_fmt_e
Definition common.h:220
@ yuv420p10
YUV 4:2:0 10-bit.
@ yuv444p16
Planar 10-bit (shifted to 16-bit) YUV 4:4:4.
@ yuv420p
YUV 4:2:0.
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
Definition misc.cpp:108
qos_data_type_e
Definition common.h:691
std::unique_ptr< high_precision_timer > create_high_precision_timer()
Create platform-specific timer capable of high-precision sleep.
Definition misc.cpp:971
bool needs_encoder_reenumeration()
Check if GPUs/drivers have changed since the last call to this function.
Definition misc.cpp:859
gamepad_feedback_e
Definition common.h:104
@ rumble_triggers
Rumble triggers.
@ set_motion_event_state
Set motion event state.
thread_priority_e
Definition common.h:587
@ critical
Critical priority.
@ high
High priority.
@ normal
Normal priority.
std::string get_host_name()
Returns the current computer name in UTF-8.
Definition misc.cpp:765
capture_e
Definition common.h:437
@ timeout
Timeout.
@ reinit
Need to reinitialize.
@ interrupted
Capture was interrupted.
Declarations for the configuration of Sunshine.
std::unique_ptr< platf::deinit_t > init(const std::filesystem::path &persistence_filepath, const config::video_t &video_config)
Initialize the implementation and perform the initial state recovery (if needed).
Definition display_device.cpp:704
Declarations for logging related functions.
Standalone NVENC encoder.
Definition nvenc_base.cpp:87
Definition common.h:390
virtual int prepare_to_derive_context(int hw_device_type)
Prepare to derive a context.
Definition common.h:426
virtual void init_codec_options(AVCodecContext *ctx, AVDictionary **options)
Provides a hook for allow platform-specific code to adjust codec options.
Definition common.h:420
virtual int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx)
Set the frame to be encoded.
Definition common.h:405
virtual void init_hwframes(AVHWFramesContext *frames)
Initialize the hwframes context.
Definition common.h:414
Definition common.h:632
buffer_descriptor_t buffer_for_payload_offset(ptrdiff_t offset)
Returns a payload buffer descriptor for the given payload offset.
Definition common.h:660
Definition common.h:616
Definition common.h:382
Definition common.h:286
Definition common.h:312
Definition common.h:111
Definition common.h:275
Definition common.h:301
Definition common.h:265
Definition common.h:292
Definition common.h:831
virtual void sleep_for(const std::chrono::nanoseconds &duration)=0
Sleep for the duration.
Definition common.h:347
Definition common.h:431
Definition common.h:329
Definition common.h:677
Definition common.h:373
Definition common.h:367
Definition common.h:98
Definition common.h:318
Definition common.h:252
Definition utility.h:966
Definition video.h:23
Definition video_colorspace.h:20
Declarations for thread-safe data structures.
Declarations for utility functions.
Declarations for colorspace functions.