Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
stream.cpp
Go to the documentation of this file.
1
5
6// standard includes
7#include <csignal>
8#include <fstream>
9#include <future>
10#include <iomanip>
11#include <queue>
12#include <system_error>
13
14// lib includes
15#include <boost/endian/arithmetic.hpp>
16#include <openssl/err.h>
17
18extern "C" {
19 // clang-format off
20#include <moonlight-common-c/src/Limelight-internal.h>
21#include "rswrapper.h"
22 // clang-format on
23}
24
25// local includes
26#include "adaptive_fec.h"
27#include "client_mic_router.h"
28#include "config.h"
29#include "crypto.h"
30#include "display_device.h"
31#include "globals.h"
32#include "input.h"
33#include "logging.h"
34#include "network.h"
35#include "platform/common.h"
36#include "process.h"
38#include "stream.h"
39#include "sync.h"
40#include "system_tray.h"
41#include "thread_safe.h"
42#include "utility.h"
43#include "video_fec_budget.h"
44#include "video_loss_monitor.h"
45
47
48#define IDX_START_A 0
49#define IDX_START_B 1
50#define IDX_INVALIDATE_REF_FRAMES 2
51#define IDX_LOSS_STATS 3
52#define IDX_INPUT_DATA 5
53#define IDX_RUMBLE_DATA 6
54#define IDX_TERMINATION 7
55#define IDX_PERIODIC_PING 8
56#define IDX_REQUEST_IDR_FRAME 9
57#define IDX_ENCRYPTED 10
58#define IDX_HDR_MODE 11
59#define IDX_RUMBLE_TRIGGER_DATA 12
60#define IDX_SET_MOTION_EVENT 13
61#define IDX_SET_RGB_LED 14
62#define IDX_EXEC_SERVER_CMD 15
63#define IDX_SET_CLIPBOARD 16
64#define IDX_FILE_TRANSFER_NONCE_REQUEST 17
65#define IDX_SET_ADAPTIVE_TRIGGERS 18
66
67static const short packetTypes[] = {
68 0x0305, // Start A
69 0x0307, // Start B
70 0x0301, // Invalidate reference frames
71 0x0201, // Loss Stats
72 0x0204, // Frame Stats (unused)
73 0x0206, // Input data
74 0x010b, // Rumble data
75 0x0109, // Termination
76 0x0200, // Periodic Ping
77 0x0302, // IDR frame
78 0x0001, // fully encrypted
79 0x010e, // HDR mode
80 0x5500, // Rumble triggers (Sunshine protocol extension)
81 0x5501, // Set motion event (Sunshine protocol extension)
82 0x5502, // Set RGB LED (Sunshine protocol extension)
83 0x3000, // Execute Server Command (Apollo protocol extension)
84 0x3001, // Set Clipboard (Apollo protocol extension)
85 0x3002, // File transfer nonce request (Apollo protocol extension)
86 0x5503, // Set Adaptive triggers (Sunshine protocol extension)
87};
88
89namespace asio = boost::asio;
90namespace sys = boost::system;
91
92using asio::ip::tcp;
93using asio::ip::udp;
94
95using namespace std::literals;
96
97namespace stream {
98
99 enum class socket_e : int {
100 video,
101 audio
102 };
103
104#pragma pack(push, 1)
105
107 uint8_t *payload() {
108 return (uint8_t *) (this + 1);
109 }
110
111 std::uint8_t headerType; // Always 0x01 for short headers
112
113 // Sunshine extension
114 // Frame processing latency, in 1/10 ms units
115 // zero when the frame is repeated or there is no backend implementation
116 boost::endian::little_uint16_at frame_processing_latency;
117
118 // Currently known values:
119 // 1 = Normal P-frame
120 // 2 = IDR-frame
121 // 4 = P-frame with intra-refresh blocks
122 // 5 = P-frame after reference frame invalidation
123 std::uint8_t frameType;
124
125 // Length of the final packet payload for codecs that cannot handle
126 // zero padding, such as AV1 (Sunshine extension).
127 boost::endian::little_uint16_at lastPayloadLen;
128
129 std::uint8_t unknown[2];
130 };
131
132 static_assert(
133 sizeof(video_short_frame_header_t) == 8,
134 "Short frame header must be 8 bytes"
135 );
136
138 uint8_t *payload() {
139 return (uint8_t *) (this + 1);
140 }
141
142 RTP_PACKET rtp;
143 char reserved[4];
144
145 NV_VIDEO_PACKET packet;
146 };
147
149 std::uint8_t iv[12]; // 12-byte IV is ideal for AES-GCM
150 std::uint32_t frameNumber;
151 std::uint8_t tag[16];
152 };
153
155 RTP_PACKET rtp;
156 };
157
159 std::uint16_t type;
160 std::uint16_t payloadLength;
161
162 uint8_t *payload() {
163 return (uint8_t *) (this + 1);
164 }
165 };
166
168 control_header_v2 header;
169
170 std::uint32_t ec;
171 };
172
174 control_header_v2 header;
175
176 std::uint32_t useless;
177
178 std::uint16_t id;
179 std::uint16_t lowfreq;
180 std::uint16_t highfreq;
181 };
182
184 control_header_v2 header;
185
186 std::uint16_t id;
187 std::uint16_t left;
188 std::uint16_t right;
189 };
190
192 control_header_v2 header;
193
194 std::uint16_t id;
195 std::uint16_t reportrate;
196 std::uint8_t type;
197 };
198
200 control_header_v2 header;
201
202 std::uint16_t id;
203 std::uint8_t r;
204 std::uint8_t g;
205 std::uint8_t b;
206 };
207
209 control_header_v2 header;
210
211 std::uint16_t id;
216 std::uint8_t event_flags;
217 std::uint8_t type_left;
218 std::uint8_t type_right;
219 std::uint8_t left[DS_EFFECT_PAYLOAD_SIZE];
220 std::uint8_t right[DS_EFFECT_PAYLOAD_SIZE];
221 };
222
224 control_header_v2 header;
225
226 std::uint8_t enabled;
227
228 // Sunshine protocol extension
229 SS_HDR_METADATA metadata;
230 };
231
232 typedef struct control_encrypted_t {
233 std::uint16_t encryptedHeaderType; // Always LE 0x0001
234 std::uint16_t length; // sizeof(seq) + 16 byte tag + secondary header and data
235
236 // seq is accepted as an arbitrary value in Moonlight
237 std::uint32_t seq; // Monotonically increasing sequence number (used as IV for AES-GCM)
238
239 uint8_t *payload() {
240 return (uint8_t *) (this + 1);
241 }
242
243 // encrypted control_header_v2 and payload data follow
244 } *control_encrypted_p;
245
247 RTP_PACKET rtp;
248 AUDIO_FEC_HEADER fecHeader;
249 };
250
251 // A client microphone packet (Apollo's mic passthrough), followed by Opus.
253 std::uint8_t flags;
254 std::uint8_t packetType;
255 boost::endian::little_uint16_at sequenceNumber;
256 boost::endian::little_uint32_at timestamp;
257 boost::endian::little_uint32_at ssrc;
258 };
259
260 constexpr std::uint8_t MIC_PACKET_TYPE_OPUS = 0x61;
261 constexpr std::uint32_t MIC_PACKET_MAGIC = 0x12345678;
262
263#pragma pack(pop)
264
265 constexpr std::size_t round_to_pkcs7_padded(std::size_t size) {
266 return ((size + 15) / 16) * 16;
267 }
268
269 constexpr std::size_t MAX_AUDIO_PACKET_SIZE = 1400;
270
271 using audio_aes_t = std::array<char, round_to_pkcs7_padded(MAX_AUDIO_PACKET_SIZE)>;
272
273 using av_session_id_t = std::variant<asio::ip::address, std::string>; // IP address or SS-Ping-Payload from RTSP handshake
274 using message_queue_t = std::shared_ptr<safe::queue_t<std::pair<udp::endpoint, std::string>>>;
275 using message_queue_queue_t = std::shared_ptr<safe::queue_t<std::tuple<socket_e, av_session_id_t, message_queue_t>>>;
276
277 // return bytes written on success
278 // return -1 on error
279 static inline int encode_audio(bool encrypted, const audio::buffer_t &plaintext, uint8_t *destination, crypto::aes_t &iv, crypto::cipher::cbc_t &cbc) {
280 // If encryption isn't enabled
281 if (!encrypted) {
282 std::copy(std::begin(plaintext), std::end(plaintext), destination);
283 return plaintext.size();
284 }
285
286 return cbc.encrypt(std::string_view {(char *) std::begin(plaintext), plaintext.size()}, destination, &iv);
287 }
288
289 static inline void while_starting_do_nothing(std::atomic<session::state_e> &state) {
290 while (state.load(std::memory_order_acquire) == session::state_e::STARTING) {
291 std::this_thread::sleep_for(1ms);
292 }
293 }
294
296 public:
297 int bind(net::af_e address_family, std::uint16_t port, boost::system::error_code &ec) {
298 _host = net::host_create(address_family, _addr, port, &ec);
299
300 return !(bool) _host;
301 }
302
303 // Get session associated with address.
304 // If none are found, try to find a session not yet claimed. (It will be marked by a port of value 0
305 // If none of those are found, return nullptr
306 session_t *get_session(const net::peer_t peer, uint32_t connect_data);
307
308 // Circular dependency:
309 // iterate refers to session
310 // session refers to broadcast_ctx_t
311 // broadcast_ctx_t refers to control_server_t
312 // Therefore, iterate is implemented further down the source file
313 void iterate(std::chrono::milliseconds timeout);
314
322 void call(std::uint16_t type, session_t *session, const std::string_view &payload, bool reinjected);
323
324 void map(uint16_t type, std::function<void(session_t *, const std::string_view &)> cb) {
325 _map_type_cb.emplace(type, std::move(cb));
326 }
327
328 int send(const std::string_view &payload, net::peer_t peer) {
329 auto packet = enet_packet_create(payload.data(), payload.size(), ENET_PACKET_FLAG_RELIABLE);
330 if (enet_peer_send(peer, 0, packet)) {
331 enet_packet_destroy(packet);
332
333 return -1;
334 }
335
336 return 0;
337 }
338
339 void flush() {
340 enet_host_flush(_host.get());
341 }
342
343 // Callbacks
344 std::unordered_map<std::uint16_t, std::function<void(session_t *, const std::string_view &)>> _map_type_cb;
345
346 // All active sessions (including those still waiting for a peer to connect)
348
349 // ENet peer to session mapping for sessions with a peer connected
351
352 ENetAddress _addr;
353 net::host_t _host;
354 };
355
357 message_queue_queue_t message_queue_queue;
358
359 std::thread recv_thread;
360 std::thread mic_thread;
361 std::thread video_thread;
362 std::thread audio_thread;
363 std::thread control_thread;
364
365 asio::io_context io_context;
366
367 udp::socket video_sock {io_context};
368 udp::socket audio_sock {io_context};
369 udp::socket mic_sock {io_context};
370
371 control_server_t control_server;
372 };
373
374 struct session_t {
375 ~session_t() {
376 if (isolated_session) {
377 proc::proc.disconnect_isolated(isolated_runtime_owner_id);
378 } else if (session_scoped_virtual_display) {
379 if (!VDISPLAY::removeVirtualDisplay(display_guid)) {
380 BOOST_LOG(warning) << "Failed to release session-scoped virtual display " << display_name;
381 }
382 }
383 }
384
385 config_t config;
386
387 safe::mail_t mail;
388
389 std::shared_ptr<input::input_t> input;
390
391 std::thread audioThread;
392 std::thread videoThread;
393
394 std::chrono::steady_clock::time_point pingTimeout;
395
397
398 boost::asio::ip::address localAddress;
399
400 struct {
401 std::string ping_payload;
402
403 int lowseq;
404 udp::endpoint peer;
405
406 std::optional<crypto::cipher::gcm_t> cipher;
407 std::uint64_t gcm_iv_counter;
408
409 safe::mail_raw_t::event_t<bool> idr_events;
410 safe::mail_raw_t::event_t<std::pair<int64_t, int64_t>> invalidate_ref_frames_events;
411
412 std::unique_ptr<platf::deinit_t> qos;
413 } video;
414
415 struct {
417 std::string ping_payload;
418
419 std::uint16_t sequenceNumber;
420 // avRiKeyId == util::endian::big(First (sizeof(avRiKeyId)) bytes of launch_session->iv)
421 std::uint32_t avRiKeyId;
422 std::uint32_t timestamp;
423 udp::endpoint peer;
424
427
428 audio_fec_packet_t fec_packet;
429 std::unique_ptr<platf::deinit_t> qos;
430
432 std::shared_ptr<audio::client_mic_t> mic;
433 bool mic_heard {};
434 udp::endpoint mic_peer;
435 } audio;
436
437 struct {
439 crypto::aes_t legacy_input_enc_iv; // Only used when the client doesn't support full control stream encryption
440 crypto::aes_t incoming_iv;
441 crypto::aes_t outgoing_iv;
442
443 std::uint32_t connect_data; // Used for new clients with ML_FF_SESSION_ID_V1
444 std::string expected_peer_address; // Only used for legacy clients without ML_FF_SESSION_ID_V1
445
446 net::peer_t peer;
447 std::uint32_t seq;
448
451 std::atomic_bool send_termination {false};
452
453 platf::feedback_queue_t feedback_queue;
454 safe::mail_raw_t::event_t<video::hdr_info_t> hdr_queue;
455 } control;
456
457 std::uint32_t launch_session_id;
458 std::uint32_t isolated_runtime_owner_id {};
459 std::string device_name;
460 std::string device_uuid;
461 bool isolated_session {false};
462 std::string isolated_runtime_id;
463 std::string isolated_seat_id;
464 bool session_scoped_virtual_display {false};
465 std::string display_name;
466 uuid_util::uuid_t display_guid {};
467 crypto::PERM permission;
468
469 std::list<crypto::command_entry_t> do_cmds;
470 std::list<crypto::command_entry_t> undo_cmds;
471
472 safe::mail_raw_t::event_t<bool> shutdown_event;
473 safe::signal_t controlEnd;
474
475 std::atomic<session::state_e> state;
476 std::atomic<session::termination_reason_e> termination_reason {session::termination_reason_e::UNKNOWN};
477
481 unsigned int client_silences_logged {0};
482
487 };
488
489 // A client on a bad link can go silent every second; past this many the
490 // silences are only counted, and the session summary still reports them all.
491 constexpr unsigned int max_logged_client_silences = 50;
492
493 void log_client_silence(session_t &session, std::chrono::milliseconds silence) {
494 if (session.client_silences_logged >= max_logged_client_silences) {
495 return;
496 }
497 ++session.client_silences_logged;
498 BOOST_LOG(info) << "Client ["sv << session.device_name << "] sent nothing for "sv << silence.count()
499 << " ms while the host kept streaming: its network link or the client itself stalled"sv
500 << (session.client_silences_logged == max_logged_client_silences ? " (further silences are only counted)"sv : ""sv);
501 }
502
507 void note_recovery_after_silence(session_t &session, std::string_view request) {
508 const auto now = std::chrono::steady_clock::now();
509 if (const auto silence = session.client_link.silence_before(now)) {
510 BOOST_LOG(info) << "Client ["sv << session.device_name << "] asked for "sv << request << ' '
511 << session.client_link.since_last_silence(now).count() << " ms after a "sv << silence->count()
512 << " ms silence: the frames sent meanwhile did not reach it"sv;
513 }
514 }
515
522 template<std::size_t max_payload_size>
523 static inline std::string_view encode_control(session_t *session, const std::string_view &plaintext, std::array<std::uint8_t, max_payload_size> &tagged_cipher) {
524 static_assert(
525 max_payload_size >= sizeof(control_encrypted_t) + sizeof(crypto::cipher::tag_size),
526 "max_payload_size >= sizeof(control_encrypted_t) + sizeof(crypto::cipher::tag_size)"
527 );
528
529 if (session->config.controlProtocolType != 13) {
530 return plaintext;
531 }
532
533 auto seq = session->control.seq++;
534
535 auto &iv = session->control.outgoing_iv;
536 if (session->config.encryptionFlagsEnabled & SS_ENC_CONTROL_V2) {
537 // We use the deterministic IV construction algorithm specified in NIST SP 800-38D
538 // Section 8.2.1. The sequence number is our "invocation" field and the 'CH' in the
539 // high bytes is the "fixed" field. Because each client provides their own unique
540 // key, our values in the fixed field need only uniquely identify each independent
541 // use of the client's key with AES-GCM in our code.
542 //
543 // The sequence number is 32 bits long which allows for 2^32 control stream messages
544 // to be sent to each client before the IV repeats.
545 iv.resize(12);
546 std::copy_n((uint8_t *) &seq, sizeof(seq), std::begin(iv));
547 iv[10] = 'H'; // Host originated
548 iv[11] = 'C'; // Control stream
549 } else {
550 // Nvidia's old style encryption uses a 16-byte IV
551 iv.resize(16);
552
553 iv[0] = (std::uint8_t) seq;
554 }
555
556 auto packet = (control_encrypted_p) tagged_cipher.data();
557
558 auto bytes = session->control.cipher.encrypt(plaintext, packet->payload(), &iv);
559 if (bytes <= 0) {
560 BOOST_LOG(error) << "Couldn't encrypt control data"sv;
561 return {};
562 }
563
564 std::uint16_t packet_length = bytes + crypto::cipher::tag_size + sizeof(control_encrypted_t::seq);
565
566 packet->encryptedHeaderType = util::endian::little(0x0001);
567 packet->length = util::endian::little(packet_length);
568 packet->seq = util::endian::little(seq);
569
570 return std::string_view {(char *) tagged_cipher.data(), packet_length + sizeof(control_encrypted_t) - sizeof(control_encrypted_t::seq)};
571 }
572
573 int start_broadcast(broadcast_ctx_t &ctx);
574 void end_broadcast(broadcast_ctx_t &ctx);
575
576 static auto broadcast = safe::make_shared<broadcast_ctx_t>(start_broadcast, end_broadcast);
577
578 session_t *control_server_t::get_session(const net::peer_t peer, uint32_t connect_data) {
579 {
580 // Fast path - look up existing session by peer
581 auto lg = _peer_to_session.lock();
582 auto it = _peer_to_session->find(peer);
583 if (it != _peer_to_session->end()) {
584 return it->second;
585 }
586 }
587
588 // Slow path - process new session
589 TUPLE_2D(peer_port, peer_addr, platf::from_sockaddr_ex((sockaddr *) &peer->address.address));
590 auto lg = _sessions.lock();
591 for (auto pos = std::begin(*_sessions); pos != std::end(*_sessions); ++pos) {
592 auto session_p = *pos;
593
594 // Skip sessions that are already established
595 if (session_p->control.peer) {
596 continue;
597 }
598
599 // Identify the connection by the unique connect data if the client supports it.
600 // Only fall back to IP address matching for clients without session ID support.
601 if (session_p->config.mlFeatureFlags & ML_FF_SESSION_ID_V1) {
602 if (session_p->control.connect_data != connect_data) {
603 continue;
604 } else {
605 BOOST_LOG(debug) << "Initialized new control stream session by connect data match [v2]"sv;
606 }
607 } else {
608 if (session_p->control.expected_peer_address != peer_addr) {
609 continue;
610 } else {
611 BOOST_LOG(debug) << "Initialized new control stream session by IP address match [v1]"sv;
612 }
613 }
614
615 // Once the control stream connection is established, RTSP session state can be torn down
616 rtsp_stream::launch_session_clear(session_p->launch_session_id);
617
618 session_p->control.peer = peer;
619
620 // Use the local address from the control connection as the source address
621 // for other communications to the client. This is necessary to ensure
622 // proper routing on multi-homed hosts.
623 auto local_address = platf::from_sockaddr((sockaddr *) &peer->localAddress.address);
624 session_p->localAddress = boost::asio::ip::make_address(local_address);
625
626 BOOST_LOG(debug) << "Control local address ["sv << local_address << ']';
627 BOOST_LOG(debug) << "Control peer address ["sv << peer_addr << ':' << peer_port << ']';
628
629 // Insert this into the map for O(1) lookups in the future
630 auto ptslg = _peer_to_session.lock();
631 _peer_to_session->emplace(peer, session_p);
632 return session_p;
633 }
634
635 return nullptr;
636 }
637
645 void control_server_t::call(std::uint16_t type, session_t *session, const std::string_view &payload, bool reinjected) {
646 // If we are using the encrypted control stream protocol, drop any messages that come off the wire unencrypted
647 if (session->config.controlProtocolType == 13 && !reinjected && type != packetTypes[IDX_ENCRYPTED]) {
648 BOOST_LOG(error) << "Dropping unencrypted message on encrypted control stream: "sv << util::hex(type).to_string_view();
649 return;
650 }
651
652 auto cb = _map_type_cb.find(type);
653 if (cb == std::end(_map_type_cb)) {
654 BOOST_LOG(debug)
655 << "type [Unknown] { "sv << util::hex(type).to_string_view() << " }"sv << std::endl
656 << "---data---"sv << std::endl
657 << util::hex_vec(payload) << std::endl
658 << "---end data---"sv;
659 } else {
660 cb->second(session, payload);
661 }
662 }
663
664 void control_server_t::iterate(std::chrono::milliseconds timeout) {
665 ENetEvent event;
666 auto res = enet_host_service(_host.get(), &event, timeout.count());
667
668 if (res > 0) {
669 auto session = get_session(event.peer, event.data);
670 if (!session) {
671 BOOST_LOG(warning) << "Rejected connection from ["sv << platf::from_sockaddr((sockaddr *) &event.peer->address.address) << "]: it's not properly set up"sv;
672 enet_peer_disconnect_now(event.peer, 0);
673
674 return;
675 }
676
677 session->pingTimeout = std::chrono::steady_clock::now() + config::stream.ping_timeout;
678
679 switch (event.type) {
680 case ENET_EVENT_TYPE_RECEIVE:
681 {
682 net::packet_t packet {event.packet};
683
684 if (const auto silence = session->client_link.on_message(std::chrono::steady_clock::now())) {
685 log_client_silence(*session, *silence);
686 }
687
688 auto type = *(std::uint16_t *) packet->data;
689 std::string_view payload {(char *) packet->data + sizeof(type), packet->dataLength - sizeof(type)};
690
691 call(type, session, payload, false);
692 }
693 break;
694 case ENET_EVENT_TYPE_CONNECT:
695 BOOST_LOG(info) << "CLIENT CONNECTED"sv;
696 break;
697 case ENET_EVENT_TYPE_DISCONNECT:
698 BOOST_LOG(info) << "CLIENT DISCONNECTED"sv;
699 // No more clients to send video data to ^_^
700 if (session->state == session::state_e::RUNNING) {
701 // ENet delivered a disconnect: the client closed the stream itself.
702 session::stop(*session, session::termination_reason_e::CLIENT_QUIT);
703 }
704 break;
705 case ENET_EVENT_TYPE_NONE:
706 break;
707 }
708 }
709 }
710
711 namespace fec {
712 using rs_t = util::safe_ptr<reed_solomon, [](reed_solomon *rs) {
713 reed_solomon_release(rs);
714 }>;
715
716 struct fec_t {
717 size_t data_shards;
718 size_t nr_shards;
719 size_t percentage;
720
721 size_t blocksize;
722 size_t prefixsize;
724 util::buffer_t<char> headers;
726
727 std::vector<platf::buffer_descriptor_t> payload_buffers;
728
729 char *data(size_t el) {
730 return (char *) shards_p[el];
731 }
732
733 char *prefix(size_t el) {
734 return prefixsize ? &headers[el * prefixsize] : nullptr;
735 }
736
737 size_t size() const {
738 return nr_shards;
739 }
740 };
741
742 static fec_t encode(const std::string_view &payload, size_t blocksize, size_t fecpercentage, size_t minparityshards, size_t prefixsize) {
743 auto payload_size = payload.size();
744
745 auto pad = payload_size % blocksize != 0;
746
747 auto aligned_data_shards = payload_size / blocksize;
748 auto data_shards = aligned_data_shards + (pad ? 1 : 0);
749 auto parity_shards = (data_shards * fecpercentage + 99) / 100;
750
751 // increase the FEC percentage for this frame if the parity shard minimum is not met
752 if (parity_shards < minparityshards && fecpercentage != 0) {
753 parity_shards = minparityshards;
754 fecpercentage = (100 * parity_shards) / data_shards;
755
756 BOOST_LOG(verbose) << "Increasing FEC percentage to "sv << fecpercentage << " to meet parity shard minimum"sv << std::endl;
757 }
758
759 auto nr_shards = data_shards + parity_shards;
760
761 // If we need to store a zero-padded data shard, allocate that first to
762 // to keep the shards in order and reduce buffer fragmentation
763 auto parity_shard_offset = pad ? 1 : 0;
764 util::buffer_t<char> shards {(parity_shard_offset + parity_shards) * blocksize};
765 util::buffer_t<uint8_t *> shards_p {nr_shards};
766 std::vector<platf::buffer_descriptor_t> payload_buffers;
767 payload_buffers.reserve(2);
768
769 // Point into the payload buffer for all except the final padded data shard
770 auto next = std::begin(payload);
771 for (auto x = 0; x < aligned_data_shards; ++x) {
772 shards_p[x] = (uint8_t *) next;
773 next += blocksize;
774 }
775 payload_buffers.emplace_back(std::begin(payload), aligned_data_shards * blocksize);
776
777 // If the last data shard needs to be zero-padded, we must use the shards buffer
778 if (pad) {
779 shards_p[aligned_data_shards] = (uint8_t *) &shards[0];
780
781 // GCC doesn't figure out that std::copy_n() can be replaced with memcpy() here
782 // and ends up compiling a horribly slow element-by-element copy loop, so we
783 // help it by using memcpy()/memset() directly.
784 auto copy_len = std::min<size_t>(blocksize, std::end(payload) - next);
785 std::memcpy(shards_p[aligned_data_shards], next, copy_len);
786 if (copy_len < blocksize) {
787 // Zero any additional space after the end of the payload
788 std::memset(shards_p[aligned_data_shards] + copy_len, 0, blocksize - copy_len);
789 }
790 }
791
792 // Add a payload buffer describing the shard buffer
793 payload_buffers.emplace_back(std::begin(shards), shards.size());
794
795 if (fecpercentage != 0) {
796 // Point into our allocated buffer for the parity shards
797 for (auto x = 0; x < parity_shards; ++x) {
798 shards_p[data_shards + x] = (uint8_t *) &shards[(parity_shard_offset + x) * blocksize];
799 }
800
801 // packets = parity_shards + data_shards
802 rs_t rs {reed_solomon_new(data_shards, parity_shards)};
803
804 reed_solomon_encode(rs.get(), shards_p.begin(), nr_shards, blocksize);
805 }
806
807 return {
808 data_shards,
809 nr_shards,
810 fecpercentage,
811 blocksize,
812 prefixsize,
813 std::move(shards),
814 util::buffer_t<char> {nr_shards * prefixsize},
815 std::move(shards_p),
816 std::move(payload_buffers),
817 };
818 }
819 } // namespace fec
820
828 std::vector<uint8_t> concat_and_insert(uint64_t insert_size, uint64_t slice_size, const std::string_view &data1, const std::string_view &data2) {
829 auto data_size = data1.size() + data2.size();
830 auto pad = data_size % slice_size != 0;
831 auto elements = data_size / slice_size + (pad ? 1 : 0);
832
833 std::vector<uint8_t> result;
834 result.resize(elements * insert_size + data_size);
835
836 auto next = std::begin(data1);
837 auto end = std::end(data1);
838 for (auto x = 0; x < elements; ++x) {
839 void *p = &result[x * (insert_size + slice_size)];
840
841 // For the last iteration, only copy to the end of the data
842 if (x == elements - 1) {
843 slice_size = data_size - (x * slice_size);
844 }
845
846 // Test if this slice will extend into the next buffer
847 if (next + slice_size > end) {
848 // Copy the first portion from the first buffer
849 auto copy_len = end - next;
850 std::copy(next, end, (char *) p + insert_size);
851
852 // Copy the remaining portion from the second buffer
853 next = std::begin(data2);
854 end = std::end(data2);
855 std::copy(next, next + (slice_size - copy_len), (char *) p + copy_len + insert_size);
856 next += slice_size - copy_len;
857 } else {
858 std::copy(next, next + slice_size, (char *) p + insert_size);
859 next += slice_size;
860 }
861 }
862
863 return result;
864 }
865
866 std::vector<uint8_t> replace(const std::string_view &original, const std::string_view &old, const std::string_view &_new) {
867 std::vector<uint8_t> replaced;
868 replaced.reserve(original.size() + _new.size() - old.size());
869
870 auto begin = std::begin(original);
871 auto end = std::end(original);
872 auto next = std::search(begin, end, std::begin(old), std::end(old));
873
874 std::copy(begin, next, std::back_inserter(replaced));
875 if (next != end) {
876 std::copy(std::begin(_new), std::end(_new), std::back_inserter(replaced));
877 std::copy(next + old.size(), end, std::back_inserter(replaced));
878 }
879
880 return replaced;
881 }
882
890 if (!session->control.peer) {
891 BOOST_LOG(warning) << "Couldn't send gamepad feedback data, still waiting for PING from the client"sv;
892 // Still waiting for PING from the client
893 return -1;
894 }
895
896 std::string payload;
897 if (msg.type == platf::gamepad_feedback_e::rumble) {
898 control_rumble_t plaintext;
899 plaintext.header.type = packetTypes[IDX_RUMBLE_DATA];
900 plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2);
901
902 auto &data = msg.data.rumble;
903
904 plaintext.useless = 0xC0FFEE;
905 plaintext.id = util::endian::little(msg.id);
906 plaintext.lowfreq = util::endian::little(data.lowfreq);
907 plaintext.highfreq = util::endian::little(data.highfreq);
908
909 BOOST_LOG(verbose) << "Rumble: "sv << msg.id << " :: "sv << util::hex(data.lowfreq).to_string_view() << " :: "sv << util::hex(data.highfreq).to_string_view();
910 std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
911 encrypted_payload;
912
913 payload = encode_control(session, util::view(plaintext), encrypted_payload);
914 } else if (msg.type == platf::gamepad_feedback_e::rumble_triggers) {
916 plaintext.header.type = packetTypes[IDX_RUMBLE_TRIGGER_DATA];
917 plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2);
918
919 auto &data = msg.data.rumble_triggers;
920
921 plaintext.id = util::endian::little(msg.id);
922 plaintext.left = util::endian::little(data.left_trigger);
923 plaintext.right = util::endian::little(data.right_trigger);
924
925 BOOST_LOG(verbose) << "Rumble triggers: "sv << msg.id << " :: "sv << util::hex(data.left_trigger).to_string_view() << " :: "sv << util::hex(data.right_trigger).to_string_view();
926 std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
927 encrypted_payload;
928
929 payload = encode_control(session, util::view(plaintext), encrypted_payload);
932 plaintext.header.type = packetTypes[IDX_SET_MOTION_EVENT];
933 plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2);
934
935 auto &data = msg.data.motion_event_state;
936
937 plaintext.id = util::endian::little(msg.id);
938 plaintext.reportrate = util::endian::little(data.report_rate);
939 plaintext.type = data.motion_type;
940
941 BOOST_LOG(verbose) << "Motion event state: "sv << msg.id << " :: "sv << util::hex(data.report_rate).to_string_view() << " :: "sv << util::hex(data.motion_type).to_string_view();
942 std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
943 encrypted_payload;
944
945 payload = encode_control(session, util::view(plaintext), encrypted_payload);
946 } else if (msg.type == platf::gamepad_feedback_e::set_rgb_led) {
947 control_set_rgb_led_t plaintext;
948 plaintext.header.type = packetTypes[IDX_SET_RGB_LED];
949 plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2);
950
951 auto &data = msg.data.rgb_led;
952
953 plaintext.id = util::endian::little(msg.id);
954 plaintext.r = data.r;
955 plaintext.g = data.g;
956 plaintext.b = data.b;
957
958 BOOST_LOG(verbose) << "RGB: "sv << msg.id << " :: "sv << util::hex(data.r).to_string_view() << util::hex(data.g).to_string_view() << util::hex(data.b).to_string_view();
959 std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
960 encrypted_payload;
961
962 payload = encode_control(session, util::view(plaintext), encrypted_payload);
965 plaintext.header.type = packetTypes[IDX_SET_ADAPTIVE_TRIGGERS];
966 plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2);
967
968 plaintext.id = util::endian::little(msg.id);
969 plaintext.event_flags = msg.data.adaptive_triggers.event_flags;
970 plaintext.type_left = msg.data.adaptive_triggers.type_left;
971 std::ranges::copy(msg.data.adaptive_triggers.left, plaintext.left);
972 plaintext.type_right = msg.data.adaptive_triggers.type_right;
973 std::ranges::copy(msg.data.adaptive_triggers.right, plaintext.right);
974
975 std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
976 encrypted_payload;
977
978 payload = encode_control(session, util::view(plaintext), encrypted_payload);
979 } else {
980 BOOST_LOG(error) << "Unknown gamepad feedback message type"sv;
981 return -1;
982 }
983
984 if (session->broadcast_ref->control_server.send(payload, session->control.peer)) {
985 TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address));
986 BOOST_LOG(warning) << "Couldn't send gamepad feedback to ["sv << addr << ':' << port << ']';
987
988 return -1;
989 }
990
991 return 0;
992 }
993
994 int send_hdr_mode(session_t *session, video::hdr_info_t hdr_info) {
995 if (!session->control.peer) {
996 BOOST_LOG(warning) << "Couldn't send HDR mode, still waiting for PING from the client"sv;
997 // Still waiting for PING from the client
998 return -1;
999 }
1000
1001 control_hdr_mode_t plaintext {};
1002 plaintext.header.type = packetTypes[IDX_HDR_MODE];
1003 plaintext.header.payloadLength = sizeof(control_hdr_mode_t) - sizeof(control_header_v2);
1004
1005 plaintext.enabled = hdr_info->enabled;
1006 plaintext.metadata = hdr_info->metadata;
1007
1008 std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
1009 encrypted_payload;
1010
1011 auto payload = encode_control(session, util::view(plaintext), encrypted_payload);
1012 if (session->broadcast_ref->control_server.send(payload, session->control.peer)) {
1013 TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address));
1014 BOOST_LOG(warning) << "Couldn't send HDR mode to ["sv << addr << ':' << port << ']';
1015
1016 return -1;
1017 }
1018
1019 BOOST_LOG(debug) << "Sent HDR mode: " << hdr_info->enabled;
1020 return 0;
1021 }
1022
1031 control_terminate_t plaintext;
1032 plaintext.header.type = packetTypes[IDX_TERMINATION];
1033 plaintext.header.payloadLength = sizeof(plaintext.ec);
1034 plaintext.ec = util::endian::big<uint32_t>(0x80030023); // graceful termination
1035
1036 std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
1037 encrypted_payload;
1038 auto payload = encode_control(session, util::view(plaintext), encrypted_payload);
1039 if (server->send(payload, session->control.peer)) {
1040 TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address));
1041 BOOST_LOG(warning) << "Couldn't send termination code to ["sv << addr << ':' << port << ']';
1042 }
1043 server->flush();
1044 }
1045
1046 void controlBroadcastThread(control_server_t *server) {
1047 server->map(packetTypes[IDX_PERIODIC_PING], [](session_t *session, const std::string_view &payload) {
1048 BOOST_LOG(verbose) << "type [IDX_PERIODIC_PING]"sv;
1049 session->client_link.on_periodic_ping();
1050 });
1051
1052 server->map(frame_fec_status_type, [](session_t *session, const std::string_view &payload) {
1053 const auto report = video_loss_monitor_t::parse(payload);
1054 if (!report) {
1055 BOOST_LOG(debug) << "Ignoring a malformed frame FEC status report ("sv << payload.size() << " bytes)"sv;
1056 return;
1057 }
1058 BOOST_LOG(verbose) << "Client lost "sv << report->missing_packets() << " packets of frame "sv << report->frame_index
1059 << (report->lost() ? " and dropped it"sv : "; parity repaired them"sv);
1060 session->video_loss.on_report(*report);
1061 });
1062
1063 server->map(packetTypes[IDX_START_A], [&](session_t *session, const std::string_view &payload) {
1064 BOOST_LOG(debug) << "type [IDX_START_A]"sv;
1065 });
1066
1067 server->map(packetTypes[IDX_START_B], [&](session_t *session, const std::string_view &payload) {
1068 BOOST_LOG(debug) << "type [IDX_START_B]"sv;
1069 });
1070
1071 server->map(packetTypes[IDX_LOSS_STATS], [&](session_t *session, const std::string_view &payload) {
1072 int32_t *stats = (int32_t *) payload.data();
1073 auto count = stats[0];
1074 std::chrono::milliseconds t {stats[1]};
1075
1076 auto lastGoodFrame = stats[3];
1077
1078 BOOST_LOG(verbose)
1079 << "type [IDX_LOSS_STATS]"sv << std::endl
1080 << "---begin stats---" << std::endl
1081 << "loss count since last report [" << count << ']' << std::endl
1082 << "time in milli since last report [" << t.count() << ']' << std::endl
1083 << "last good frame [" << lastGoodFrame << ']' << std::endl
1084 << "---end stats---";
1085 });
1086
1087 server->map(packetTypes[IDX_REQUEST_IDR_FRAME], [&](session_t *session, const std::string_view &payload) {
1088 BOOST_LOG(debug) << "type [IDX_REQUEST_IDR_FRAME]"sv;
1089 note_recovery_after_silence(*session, "a key frame"sv);
1090
1091 session->video.idr_events->raise(true);
1092 });
1093
1094 server->map(packetTypes[IDX_INVALIDATE_REF_FRAMES], [&](session_t *session, const std::string_view &payload) {
1095 auto frames = (std::int64_t *) payload.data();
1096 auto firstFrame = frames[0];
1097 auto lastFrame = frames[1];
1098
1099 BOOST_LOG(debug)
1100 << "type [IDX_INVALIDATE_REF_FRAMES]"sv << std::endl
1101 << "firstFrame [" << firstFrame << ']' << std::endl
1102 << "lastFrame [" << lastFrame << ']';
1103
1104 note_recovery_after_silence(*session, "reference frame invalidation"sv);
1105
1106 session->video.invalidate_ref_frames_events->raise(std::make_pair(firstFrame, lastFrame));
1107 });
1108
1109 server->map(packetTypes[IDX_INPUT_DATA], [&](session_t *session, const std::string_view &payload) {
1110 BOOST_LOG(debug) << "type [IDX_INPUT_DATA]"sv;
1111
1112 auto tagged_cipher_length = util::endian::big(*(int32_t *) payload.data());
1113 std::string_view tagged_cipher {payload.data() + sizeof(tagged_cipher_length), (size_t) tagged_cipher_length};
1114
1115 std::vector<uint8_t> plaintext;
1116
1117 auto &cipher = session->control.cipher;
1118 auto &iv = session->control.legacy_input_enc_iv;
1119 if (cipher.decrypt(tagged_cipher, plaintext, &iv)) {
1120 // something went wrong :(
1121
1122 BOOST_LOG(error) << "Failed to verify tag"sv;
1123
1124 session::stop(*session, session::termination_reason_e::PROTOCOL_ERROR);
1125 return;
1126 }
1127
1128 if (tagged_cipher_length >= 16 + iv.size()) {
1129 std::copy(payload.end() - 16, payload.end(), std::begin(iv));
1130 }
1131
1132 input::passthrough(session->input, std::move(plaintext), session->permission);
1133 });
1134
1135 server->map(packetTypes[IDX_EXEC_SERVER_CMD], [server](session_t *session, const std::string_view &payload) {
1136 BOOST_LOG(debug) << "type [IDX_EXEC_SERVER_CMD]"sv;
1137
1138 if (!(session->permission & crypto::PERM::server_cmd)) {
1139 BOOST_LOG(debug) << "Permission Exec Server Cmd deined for [" << session->device_name << "]";
1140 return;
1141 }
1142
1143 uint8_t cmdIndex = *(uint8_t*)payload.data();
1144
1145 if (cmdIndex < config::sunshine.server_cmds.size()) {
1146 const auto& cmd = config::sunshine.server_cmds[cmdIndex];
1147 BOOST_LOG(info) << "Executing server command: " << cmd.cmd_name;
1148
1149 auto exec_thread = std::thread([&cmd]{
1150 std::error_code ec;
1151 auto env = proc::proc.get_env();
1152 boost::filesystem::path working_dir = proc::find_working_directory(cmd.cmd_val, env);
1153 auto child = platf::run_command(cmd.elevated, true, cmd.cmd_val, working_dir, env, nullptr, ec, nullptr);
1154
1155 if (ec) {
1156 BOOST_LOG(error) << "Failed to execute server command: " << ec.message();
1157 } else {
1158 child.detach();
1159 }
1160 });
1161
1162 exec_thread.detach();
1163 } else {
1164 BOOST_LOG(error) << "Invalid server command index: " << (int)cmdIndex;
1165 }
1166 });
1167
1168 server->map(packetTypes[IDX_SET_CLIPBOARD], [server](session_t *session, const std::string_view &payload) {
1169 BOOST_LOG(info) << "type [IDX_SET_CLIPBOARD]: "sv << payload << " size: " << payload.size();
1170
1171 if (!(session->permission & crypto::PERM::clipboard_set)) {
1172 BOOST_LOG(debug) << "Permission Clipboard Set deined for [" << session->device_name << "]";
1173 return;
1174 }
1175 });
1176
1177 server->map(packetTypes[IDX_FILE_TRANSFER_NONCE_REQUEST], [server](session_t *session, const std::string_view &payload) {
1178 BOOST_LOG(info) << "type [IDX_FILE_TRANSFER_NONCE_REQUEST]: "sv << payload << " size: " << payload.size();
1179
1180 if (!(session->permission & crypto::PERM::file_upload)) {
1181 BOOST_LOG(debug) << "Permission File Upload deined for [" << session->device_name << "]";
1182 return;
1183 }
1184 });
1185
1186 server->map(packetTypes[IDX_ENCRYPTED], [server](session_t *session, const std::string_view &payload) {
1187 BOOST_LOG(verbose) << "type [IDX_ENCRYPTED]"sv;
1188
1189 auto header = (control_encrypted_p) (payload.data() - 2);
1190
1191 auto length = util::endian::little(header->length);
1192 auto seq = util::endian::little(header->seq);
1193
1194 if (length < (16 + 4 + 4)) {
1195 BOOST_LOG(warning) << "Control: Runt packet"sv;
1196 return;
1197 }
1198
1199 auto tagged_cipher_length = length - 4;
1200 std::string_view tagged_cipher {(char *) header->payload(), (size_t) tagged_cipher_length};
1201
1202 auto &cipher = session->control.cipher;
1203 auto &iv = session->control.incoming_iv;
1204 if (session->config.encryptionFlagsEnabled & SS_ENC_CONTROL_V2) {
1205 // We use the deterministic IV construction algorithm specified in NIST SP 800-38D
1206 // Section 8.2.1. The sequence number is our "invocation" field and the 'CC' in the
1207 // high bytes is the "fixed" field. Because each client provides their own unique
1208 // key, our values in the fixed field need only uniquely identify each independent
1209 // use of the client's key with AES-GCM in our code.
1210 //
1211 // The sequence number is 32 bits long which allows for 2^32 control stream messages
1212 // to be received from each client before the IV repeats.
1213 iv.resize(12);
1214 std::copy_n((uint8_t *) &seq, sizeof(seq), std::begin(iv));
1215 iv[10] = 'C'; // Client originated
1216 iv[11] = 'C'; // Control stream
1217 } else {
1218 // Nvidia's old style encryption uses a 16-byte IV
1219 iv.resize(16);
1220
1221 iv[0] = (std::uint8_t) seq;
1222 }
1223
1224 std::vector<uint8_t> plaintext;
1225 if (cipher.decrypt(tagged_cipher, plaintext, &iv)) {
1226 // something went wrong :(
1227
1228 BOOST_LOG(error) << "Failed to verify tag"sv;
1229
1230 session::stop(*session, session::termination_reason_e::PROTOCOL_ERROR);
1231 return;
1232 }
1233
1234 auto type = *(std::uint16_t *) plaintext.data();
1235 std::string_view next_payload {(char *) plaintext.data() + 4, plaintext.size() - 4};
1236
1237 if (type == packetTypes[IDX_ENCRYPTED]) {
1238 BOOST_LOG(error) << "Bad packet type [IDX_ENCRYPTED] found"sv;
1239 session::stop(*session, session::termination_reason_e::PROTOCOL_ERROR);
1240 return;
1241 }
1242
1243 // IDX_INPUT_DATA callback will attempt to decrypt unencrypted data, therefore we need pass it directly
1244 if (type == packetTypes[IDX_INPUT_DATA]) {
1245 plaintext.erase(std::begin(plaintext), std::begin(plaintext) + 4);
1246 input::passthrough(session->input, std::move(plaintext), session->permission);
1247 } else {
1248 server->call(type, session, next_payload, true);
1249 }
1250 });
1251
1252 // This thread handles latency-sensitive control messages
1253 platf::adjust_thread_priority(platf::thread_priority_e::critical);
1254
1255 // Check for both the full shutdown event and the shutdown event for this
1256 // broadcast to ensure we can inform connected clients of our graceful
1257 // termination when we shut down.
1258 auto shutdown_event = mail::man->event<bool>(mail::shutdown);
1259 auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown);
1260 while (!shutdown_event->peek() && !broadcast_shutdown_event->peek()) {
1261 bool has_session_awaiting_peer = false;
1262
1263 {
1264 auto lg = server->_sessions.lock();
1265
1266 auto now = std::chrono::steady_clock::now();
1267
1268 KITTY_WHILE_LOOP(auto pos = std::begin(*server->_sessions), pos != std::end(*server->_sessions), {
1269 // Don't perform additional session processing if we're shutting down
1270 if (shutdown_event->peek() || broadcast_shutdown_event->peek()) {
1271 break;
1272 }
1273
1274 auto session = *pos;
1275
1276 if (now > session->pingTimeout) {
1277 auto address = session->control.peer ? platf::from_sockaddr((sockaddr *) &session->control.peer->address.address) : session->control.expected_peer_address;
1278 BOOST_LOG(info) << address << ": Ping Timeout"sv;
1279 session::stop(*session, session::termination_reason_e::CLIENT_LOST);
1280 }
1281
1282 if (session->state.load(std::memory_order_acquire) == session::state_e::STOPPING) {
1283 pos = server->_sessions->erase(pos);
1284
1285 if (session->control.peer) {
1286 {
1287 auto ptslg = server->_peer_to_session.lock();
1288 server->_peer_to_session->erase(session->control.peer);
1289 }
1290
1291 // A graceful stop's termination message is sent here, on the
1292 // thread that owns the session's control cipher and peer.
1293 if (session->control.send_termination.load(std::memory_order_acquire)) {
1294 send_termination(server, session);
1295 }
1296
1297 enet_peer_disconnect_now(session->control.peer, 0);
1298 }
1299
1300 session->controlEnd.raise(true);
1301 continue;
1302 }
1303
1304 // Remember if we have a session that's waiting for a peer to connect to the
1305 // control stream. This ensures the clients are properly notified even when
1306 // the app terminates before they finish connecting.
1307 if (!session->control.peer) {
1308 has_session_awaiting_peer = true;
1309 } else {
1310 auto &feedback_queue = session->control.feedback_queue;
1311 while (feedback_queue->peek()) {
1312 auto feedback_msg = feedback_queue->pop();
1313
1314 send_feedback_msg(session, *feedback_msg);
1315 }
1316
1317 auto &hdr_queue = session->control.hdr_queue;
1318 while (session->control.peer && hdr_queue->peek()) {
1319 auto hdr_info = hdr_queue->pop();
1320
1321 send_hdr_mode(session, std::move(hdr_info));
1322 }
1323 }
1324
1325 ++pos;
1326 })
1327 }
1328
1329 // Don't break until any pending sessions either expire or connect
1330 if (!proc::proc.any_running() && !has_session_awaiting_peer) {
1331 BOOST_LOG(info) << "Process terminated"sv;
1332 break;
1333 }
1334
1335 server->iterate(150ms);
1336 }
1337
1338 // Let all remaining connections know the server is shutting down
1339 // reason: graceful termination
1340 std::uint32_t reason = 0x80030023;
1341
1342 control_terminate_t plaintext;
1343 plaintext.header.type = packetTypes[IDX_TERMINATION];
1344 plaintext.header.payloadLength = sizeof(plaintext.ec);
1345 plaintext.ec = util::endian::big<uint32_t>(reason);
1346
1347 std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
1348 encrypted_payload;
1349
1350 auto lg = server->_sessions.lock();
1351 for (auto pos = std::begin(*server->_sessions); pos != std::end(*server->_sessions); ++pos) {
1352 auto session = *pos;
1353
1354 // We may not have gotten far enough to have an ENet connection yet
1355 if (session->control.peer) {
1356 auto payload = encode_control(session, util::view(plaintext), encrypted_payload);
1357
1358 if (server->send(payload, session->control.peer)) {
1359 TUPLE_2D(port, addr, platf::from_sockaddr_ex((sockaddr *) &session->control.peer->address.address));
1360 BOOST_LOG(warning) << "Couldn't send termination code to ["sv << addr << ':' << port << ']';
1361 }
1362 }
1363
1364 session->shutdown_event->raise(true);
1365 session->controlEnd.raise(true);
1366 }
1367
1368 server->flush();
1369 }
1370
1371 void recvThread(broadcast_ctx_t &ctx) {
1372 std::map<av_session_id_t, message_queue_t> peer_to_video_session;
1373 std::map<av_session_id_t, message_queue_t> peer_to_audio_session;
1374
1375 auto &video_sock = ctx.video_sock;
1376 auto &audio_sock = ctx.audio_sock;
1377
1378 auto &message_queue_queue = ctx.message_queue_queue;
1379 auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown);
1380
1381 auto &io = ctx.io_context;
1382
1383 // The audio and video receives are pending at the same time; each needs
1384 // its own endpoint, or one overwrites the other's sender address.
1385 std::array<udp::endpoint, 2> peers;
1386
1387 std::array<char, 2048> buf[2];
1388 std::function<void(const boost::system::error_code, size_t)> recv_func[2];
1389
1390 auto populate_peer_to_session = [&]() {
1391 while (message_queue_queue->peek()) {
1392 auto message_queue_opt = message_queue_queue->pop();
1393 TUPLE_3D_REF(socket_type, session_id, message_queue, *message_queue_opt);
1394
1395 switch (socket_type) {
1396 case socket_e::video:
1397 if (message_queue) {
1398 peer_to_video_session.emplace(session_id, message_queue);
1399 } else {
1400 peer_to_video_session.erase(session_id);
1401 }
1402 break;
1403 case socket_e::audio:
1404 if (message_queue) {
1405 peer_to_audio_session.emplace(session_id, message_queue);
1406 } else {
1407 peer_to_audio_session.erase(session_id);
1408 }
1409 break;
1410 }
1411 }
1412 };
1413
1414 auto recv_func_init = [&](udp::socket &sock, int buf_elem, std::map<av_session_id_t, message_queue_t> &peer_to_session) {
1415 recv_func[buf_elem] = [&, buf_elem](const boost::system::error_code &ec, size_t bytes) {
1416 auto &peer = peers[buf_elem];
1417 auto fg = util::fail_guard([&]() {
1418 sock.async_receive_from(asio::buffer(buf[buf_elem]), peer, 0, recv_func[buf_elem]);
1419 });
1420
1421 auto type_str = buf_elem ? "AUDIO"sv : "VIDEO"sv;
1422 BOOST_LOG(verbose) << "Recv: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str;
1423
1424 populate_peer_to_session();
1425
1426 // No data, yet no error
1427 if (ec == boost::system::errc::connection_refused || ec == boost::system::errc::connection_reset) {
1428 return;
1429 }
1430
1431 if (ec || !bytes) {
1432 BOOST_LOG(error) << "Couldn't receive data from udp socket: "sv << ec.message();
1433 return;
1434 }
1435
1436 if (bytes == 4) {
1437 // For legacy PING packets, find the matching session by address.
1438 auto it = peer_to_session.find(peer.address());
1439 if (it != std::end(peer_to_session)) {
1440 BOOST_LOG(debug) << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str;
1441 it->second->raise(peer, std::string {buf[buf_elem].data(), bytes});
1442 }
1443 } else if (bytes >= sizeof(SS_PING)) {
1444 auto ping = (PSS_PING) buf[buf_elem].data();
1445
1446 // For new PING packets that include a client identifier, search by payload.
1447 auto it = peer_to_session.find(std::string {ping->payload, sizeof(ping->payload)});
1448 if (it != std::end(peer_to_session)) {
1449 BOOST_LOG(debug) << "RAISE: "sv << peer.address().to_string() << ':' << peer.port() << " :: " << type_str;
1450 it->second->raise(peer, std::string {buf[buf_elem].data(), bytes});
1451 }
1452 }
1453 };
1454 };
1455
1456 recv_func_init(video_sock, 0, peer_to_video_session);
1457 recv_func_init(audio_sock, 1, peer_to_audio_session);
1458
1459 video_sock.async_receive_from(asio::buffer(buf[0]), peers[0], 0, recv_func[0]);
1460 audio_sock.async_receive_from(asio::buffer(buf[1]), peers[1], 0, recv_func[1]);
1461
1462 while (!broadcast_shutdown_event->peek()) {
1463 io.run();
1464 }
1465 }
1466
1467 void micRecvThread(broadcast_ctx_t &ctx) {
1468 auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown);
1469 std::array<char, 2048> buf;
1470 udp::endpoint peer;
1471
1472 while (!broadcast_shutdown_event->peek()) {
1473 boost::system::error_code ec;
1474 const auto bytes = ctx.mic_sock.receive_from(asio::buffer(buf), peer, 0, ec);
1475 if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) {
1476 std::this_thread::sleep_for(2ms);
1477 continue;
1478 }
1479 if (ec || bytes <= sizeof(mic_packet_header_t)) {
1480 continue;
1481 }
1482
1483 const auto *header = reinterpret_cast<const mic_packet_header_t *>(buf.data());
1484 if (header->packetType != MIC_PACKET_TYPE_OPUS || header->ssrc != MIC_PACKET_MAGIC) {
1485 continue;
1486 }
1487 const std::uint16_t sequence = header->sequenceNumber;
1488 const std::string_view cipher {buf.data() + sizeof(mic_packet_header_t), bytes - sizeof(mic_packet_header_t)};
1489
1490 std::shared_ptr<audio::client_mic_t> mic;
1491 std::optional<audio::routed_mic_packet_t> decoded;
1492 {
1493 auto lg = ctx.control_server._sessions.lock();
1494 std::vector<session_t *> sessions;
1495 std::vector<audio::mic_candidate_t> candidates;
1496 for (auto *session : *ctx.control_server._sessions) {
1497 if (!session->audio.mic || session->audio.peer.address() != peer.address() || (session->audio.mic_peer.port() != 0 && session->audio.mic_peer != peer) || session->state.load(std::memory_order_relaxed) != session::state_e::RUNNING) {
1498 continue;
1499 }
1500 sessions.push_back(session);
1501 candidates.push_back({&session->audio.cipher, session->audio.avRiKeyId});
1502 }
1503 decoded = audio::route_mic_packet(candidates, sequence, cipher);
1504 if (decoded) {
1505 auto *session = sessions[decoded->candidate];
1506 session->audio.mic_peer = peer;
1507 if (!session->audio.mic_heard) {
1508 session->audio.mic_heard = true;
1509 BOOST_LOG(info) << "Receiving the microphone of ["sv << session->device_name << "] into ["sv << session->config.mic_source << ']';
1510 }
1511 mic = session->audio.mic;
1512 }
1513 }
1514
1515 if (mic) {
1516 mic->write(sequence, decoded->opus.data(), decoded->opus.size());
1517 }
1518 }
1519 }
1520
1521 void videoBroadcastThread(udp::socket &sock) {
1522 auto shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown);
1523 auto packets = mail::man->queue<video::packet_t>(mail::video_packets);
1524 auto video_epoch = std::chrono::steady_clock::now();
1525
1526 // Video traffic is sent on this thread
1527 platf::adjust_thread_priority(platf::thread_priority_e::high);
1528
1529 logging::min_max_avg_periodic_logger<double> frame_processing_latency_logger(debug, "Frame processing latency", "ms");
1530
1531 logging::time_delta_periodic_logger frame_send_batch_latency_logger(debug, "Network: each send_batch() latency");
1532 logging::time_delta_periodic_logger frame_fec_latency_logger(debug, "Network: each FEC block latency");
1533 logging::time_delta_periodic_logger frame_network_latency_logger(debug, "Network: frame's overall network latency");
1534
1535 crypto::aes_t iv(12);
1536
1538 if (!timer || !*timer) {
1539 BOOST_LOG(error) << "Failed to create timer, aborting video broadcast thread";
1540 return;
1541 }
1542
1543 auto ratecontrol_next_frame_start = std::chrono::steady_clock::now();
1544
1545 while (auto packet = packets->pop()) {
1546 if (shutdown_event->peek()) {
1547 break;
1548 }
1549
1550 frame_network_latency_logger.first_point_now();
1551
1552 auto session = (session_t *) packet->channel_data;
1553 auto lowseq = session->video.lowseq;
1554
1555 std::string_view payload {(char *) packet->data(), packet->data_size()};
1556 std::vector<uint8_t> payload_with_replacements;
1557
1558 // Apply replacements on the packet payload before performing any other operations.
1559 // We need to know the final frame size to calculate the last packet size, and we
1560 // must avoid matching replacements against the frame header or any other non-video
1561 // part of the payload.
1562 if (packet->is_idr() && packet->replacements) {
1563 for (auto &replacement : *packet->replacements) {
1564 auto frame_old = replacement.old;
1565 auto frame_new = replacement._new;
1566
1567 payload_with_replacements = replace(payload, frame_old, frame_new);
1568 payload = {(char *) payload_with_replacements.data(), payload_with_replacements.size()};
1569 }
1570 }
1571
1572 video_short_frame_header_t frame_header = {};
1573 frame_header.headerType = 0x01; // Short header type
1574 frame_header.frameType = packet->is_idr() ? 2 :
1575 packet->after_ref_frame_invalidation ? 5 :
1576 1;
1577 frame_header.lastPayloadLen = (payload.size() + sizeof(frame_header)) % (session->config.packetsize - sizeof(NV_VIDEO_PACKET));
1578 if (frame_header.lastPayloadLen == 0) {
1579 frame_header.lastPayloadLen = session->config.packetsize - sizeof(NV_VIDEO_PACKET);
1580 }
1581
1582 if (packet->frame_timestamp) {
1583 auto duration_to_latency = [](const std::chrono::steady_clock::duration &duration) {
1584 const auto duration_us = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
1585 return (uint16_t) std::clamp<decltype(duration_us)>((duration_us + 50) / 100, 0, std::numeric_limits<uint16_t>::max());
1586 };
1587
1588 uint16_t latency = duration_to_latency(std::chrono::steady_clock::now() - *packet->frame_timestamp);
1589 frame_header.frame_processing_latency = latency;
1590 frame_processing_latency_logger.collect_and_log(latency / 10.);
1591 } else {
1592 frame_header.frame_processing_latency = 0;
1593 }
1594
1595 auto fecPercentage = config::stream.fec_percentage;
1596 if (config::stream.adaptive_fec) {
1597 // The client already reports what it lost (SS_FRAME_FEC_STATUS), so the host
1598 // can size parity to the observed worst second instead of a fixed guess.
1599 const auto since_epoch = std::chrono::steady_clock::now().time_since_epoch();
1600 const auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(since_epoch).count();
1601 fecPercentage = session->adaptive_fec.percentage(session->video_loss.sent_data_packets(), session->video_loss.missing_packets(), session->video_loss.reported_blocks(), now_ms, config::stream.fec_percentage, config::stream.adaptive_fec_max_percentage);
1602 }
1603
1604 // Insert space for packet headers
1605 auto blocksize = session->config.packetsize + MAX_RTP_HEADER_SIZE;
1606 auto payload_blocksize = blocksize - sizeof(video_packet_raw_t);
1607 auto payload_new = concat_and_insert(sizeof(video_packet_raw_t), payload_blocksize, std::string_view {(char *) &frame_header, sizeof(frame_header)}, payload);
1608
1609 payload = std::string_view {(char *) payload_new.data(), payload_new.size()};
1610
1611 // There are 2 bits for FEC block count for a maximum of 4 FEC blocks
1612 constexpr auto MAX_FEC_BLOCKS = 4;
1613
1614 // The max number of data shards per block is found by solving this system of equations for D:
1615 // D = 255 - P
1616 // P = D * F
1617 // which results in the solution:
1618 // D = 255 / (1 + F)
1619 // multiplied by 100 since F is the percentage as an integer:
1620 // D = (255 * 100) / (100 + F)
1621 auto max_data_shards_per_fec_block = (DATA_SHARDS_MAX * 100) / (100 + fecPercentage);
1622
1623 // Compute the number of FEC blocks needed for this frame using the block size and max shards
1624 auto max_data_per_fec_block = max_data_shards_per_fec_block * blocksize;
1625 auto fec_blocks_needed = (payload.size() + (max_data_per_fec_block - 1)) / max_data_per_fec_block;
1626
1627 // A frame that needs more FEC blocks than the protocol carries (over 800
1628 // packets at 20%) keeps as much FEC as still fits in MAX_FEC_BLOCKS,
1629 // rather than none: one lost packet would otherwise drop the frame.
1630 if (fec_blocks_needed > MAX_FEC_BLOCKS) {
1631 static_assert(static_cast<std::size_t>(MAX_FEC_BLOCKS) == max_fec_blocks);
1632 const auto data_packets = (payload.size() + blocksize - 1) / blocksize;
1633 const auto reduced = large_frame_fec_percentage(data_packets, fecPercentage, session->config.minRequiredFecPackets);
1634 BOOST_LOG(warning) << "Abnormally large encoded "sv << (packet->is_idr() ? "key frame"sv : "frame"sv) << " ("sv
1635 << payload.size() / 1024 << " KiB in "sv << data_packets << " packets) needed "sv << fec_blocks_needed
1636 << " FEC blocks; sending it with "sv << reduced << "% FEC instead of "sv << fecPercentage << '%';
1637 fecPercentage = reduced;
1638 fec_blocks_needed = MAX_FEC_BLOCKS;
1639 }
1640
1641 std::array<std::string_view, MAX_FEC_BLOCKS> fec_blocks;
1642 decltype(fec_blocks)::iterator
1643 fec_blocks_begin = std::begin(fec_blocks),
1644 fec_blocks_end = std::begin(fec_blocks) + fec_blocks_needed;
1645
1646 BOOST_LOG(verbose) << "Generating "sv << fec_blocks_needed << " FEC blocks"sv;
1647
1648 // Align individual FEC blocks to blocksize
1649 auto unaligned_size = payload.size() / fec_blocks_needed;
1650 auto aligned_size = ((unaligned_size + (blocksize - 1)) / blocksize) * blocksize;
1651
1652 // If we exceed the 10-bit FEC packet index (which means our frame exceeded 4096 packets),
1653 // the frame will be unrecoverable. Log an error for this case.
1654 if (aligned_size / blocksize >= 1024) {
1655 BOOST_LOG(error) << "Encoder produced a frame too large to send! Is the encoder broken? (needed "sv << (aligned_size / blocksize) << " packets)"sv;
1656 }
1657
1658 // Split the data into aligned FEC blocks
1659 for (int x = 0; x < fec_blocks_needed; ++x) {
1660 if (x == fec_blocks_needed - 1) {
1661 // The last block must extend to the end of the payload
1662 fec_blocks[x] = payload.substr(x * aligned_size);
1663 } else {
1664 // Earlier blocks just extend to the next block offset
1665 fec_blocks[x] = payload.substr(x * aligned_size, aligned_size);
1666 }
1667 }
1668
1669 try {
1670 // Use around 80% of 1Gbps 1Gbps percent ms packet byte
1671 size_t ratecontrol_packets_in_1ms = std::giga::num * 80 / 100 / 1000 / blocksize / 8;
1672
1673 // Send less than 64K in a single batch.
1674 // On Windows, batches above 64K seem to bypass SO_SNDBUF regardless of its size,
1675 // appear in "Other I/O" and begin waiting for interrupts.
1676 // This gives inconsistent performance so we'd rather avoid it.
1677 size_t send_batch_size = 64 * 1024 / blocksize;
1678 // Also don't exceed 64 packets, which can happen when Moonlight requests
1679 // unusually small packet size.
1680 // Generic Segmentation Offload on Linux can't do more than 64.
1681 send_batch_size = std::min<size_t>(64, send_batch_size);
1682
1683 // Don't ignore the last ratecontrol group of the previous frame
1684 auto ratecontrol_frame_start = std::max(ratecontrol_next_frame_start, std::chrono::steady_clock::now());
1685
1686 size_t ratecontrol_frame_packets_sent = 0;
1687 size_t ratecontrol_group_packets_sent = 0;
1688
1689 auto blockIndex = 0;
1690 std::for_each(fec_blocks_begin, fec_blocks_end, [&](std::string_view &current_payload) {
1691 auto packets = (current_payload.size() + (blocksize - 1)) / blocksize;
1692
1693 for (int x = 0; x < packets; ++x) {
1694 auto *inspect = (video_packet_raw_t *) &current_payload[x * blocksize];
1695
1696 inspect->packet.frameIndex = packet->frame_index();
1697 inspect->packet.streamPacketIndex = ((uint32_t) lowseq + x) << 8;
1698
1699 // Match multiFecFlags with Moonlight
1700 inspect->packet.multiFecFlags = 0x10;
1701 inspect->packet.multiFecBlocks = (blockIndex << 4) | ((fec_blocks_needed - 1) << 6);
1702
1703 inspect->packet.flags = FLAG_CONTAINS_PIC_DATA;
1704 if (x == 0) {
1705 inspect->packet.flags |= FLAG_SOF;
1706 }
1707 if (x == packets - 1) {
1708 inspect->packet.flags |= FLAG_EOF;
1709 }
1710 }
1711
1712 frame_fec_latency_logger.first_point_now();
1713 // If video encryption is enabled, we allocate space for the encryption header before each shard
1714 auto shards = fec::encode(current_payload, blocksize, fecPercentage, session->config.minRequiredFecPackets, session->video.cipher ? sizeof(video_packet_enc_prefix_t) : 0);
1715 frame_fec_latency_logger.second_point_now_and_log();
1716
1717 auto peer_address = session->video.peer.address();
1718 auto batch_info = platf::batched_send_info_t {
1719 shards.headers.begin(),
1720 shards.prefixsize,
1721 shards.payload_buffers,
1722 shards.blocksize,
1723 0,
1724 0,
1725 (uintptr_t) sock.native_handle(),
1726 peer_address,
1727 session->video.peer.port(),
1728 session->localAddress,
1729 };
1730
1731 size_t next_shard_to_send = 0;
1732
1733 // RTP video timestamps use a 90 KHz clock and the frame_timestamp from when the frame was captured
1734 // When a timestamp isn't available (duplicate frames), the timestamp from rate control is used instead.
1735 bool frame_is_dupe = false;
1736 if (!packet->frame_timestamp) {
1737 packet->frame_timestamp = ratecontrol_next_frame_start;
1738 frame_is_dupe = true;
1739 }
1740 using rtp_tick = std::chrono::duration<uint32_t, std::ratio<1, 90000>>;
1741 uint32_t timestamp = std::chrono::round<rtp_tick>(*packet->frame_timestamp - video_epoch).count();
1742
1743 // set FEC info now that we know for sure what our percentage will be for this frame
1744 for (auto x = 0; x < shards.size(); ++x) {
1745 auto *inspect = (video_packet_raw_t *) shards.data(x);
1746
1747 inspect->packet.fecInfo =
1748 (x << 12 |
1749 shards.data_shards << 22 |
1750 shards.percentage << 4);
1751
1752 inspect->rtp.header = 0x80 | FLAG_EXTENSION;
1753 inspect->rtp.sequenceNumber = util::endian::big<uint16_t>(lowseq + x);
1754 inspect->rtp.timestamp = util::endian::big<uint32_t>(timestamp);
1755
1756 inspect->packet.multiFecBlocks = (blockIndex << 4) | ((fec_blocks_needed - 1) << 6);
1757 inspect->packet.frameIndex = packet->frame_index();
1758
1759 // Encrypt this shard if video encryption is enabled
1760 if (session->video.cipher) {
1761 // We use the deterministic IV construction algorithm specified in NIST SP 800-38D
1762 // Section 8.2.1. The sequence number is our "invocation" field and the 'V' in the
1763 // high bytes is the "fixed" field. Because each client provides their own unique
1764 // key, our values in the fixed field need only uniquely identify each independent
1765 // use of the client's key with AES-GCM in our code.
1766 //
1767 // The IV counter is 64 bits long which allows for 2^64 encrypted video packets
1768 // to be sent to each client before the IV repeats.
1769 std::copy_n((uint8_t *) &session->video.gcm_iv_counter, sizeof(session->video.gcm_iv_counter), std::begin(iv));
1770 iv[11] = 'V'; // Video stream
1771 session->video.gcm_iv_counter++;
1772
1773 // Encrypt the target buffer in place
1774 auto *prefix = (video_packet_enc_prefix_t *) shards.prefix(x);
1775 prefix->frameNumber = packet->frame_index();
1776 std::copy(std::begin(iv), std::end(iv), prefix->iv);
1777 session->video.cipher->encrypt(std::string_view {(char *) inspect, (size_t) blocksize}, prefix->tag, (uint8_t *) inspect, &iv);
1778 }
1779
1780 if (x - next_shard_to_send + 1 >= send_batch_size ||
1781 x + 1 == shards.size()) {
1782 // Do pacing within the frame.
1783 // Also trigger pacing before the first send_batch() of the frame
1784 // to account for the last send_batch() of the previous frame.
1785 if (ratecontrol_group_packets_sent >= ratecontrol_packets_in_1ms ||
1786 ratecontrol_frame_packets_sent == 0) {
1787 auto due = ratecontrol_frame_start +
1788 std::chrono::duration_cast<std::chrono::nanoseconds>(1ms) *
1789 ratecontrol_frame_packets_sent / ratecontrol_packets_in_1ms;
1790
1791 auto now = std::chrono::steady_clock::now();
1792 if (now < due) {
1793 timer->sleep_for(due - now);
1794 }
1795
1796 ratecontrol_group_packets_sent = 0;
1797 }
1798
1799 size_t current_batch_size = x - next_shard_to_send + 1;
1800 batch_info.block_offset = next_shard_to_send;
1801 batch_info.block_count = current_batch_size;
1802
1803 frame_send_batch_latency_logger.first_point_now();
1804 // Use a batched send if it's supported on this platform
1805 if (!platf::send_batch(batch_info)) {
1806 // Batched send is not available, so send each packet individually
1807 BOOST_LOG(verbose) << "Falling back to unbatched send"sv;
1808 for (auto y = 0; y < current_batch_size; y++) {
1809 auto send_info = platf::send_info_t {
1810 shards.prefix(next_shard_to_send + y),
1811 shards.prefixsize,
1812 shards.data(next_shard_to_send + y),
1813 shards.blocksize,
1814 (uintptr_t) sock.native_handle(),
1815 peer_address,
1816 session->video.peer.port(),
1817 session->localAddress,
1818 };
1819
1820 platf::send(send_info);
1821 }
1822 }
1823 frame_send_batch_latency_logger.second_point_now_and_log();
1824
1825 ratecontrol_group_packets_sent += current_batch_size;
1826 ratecontrol_frame_packets_sent += current_batch_size;
1827 next_shard_to_send = x + 1;
1828 }
1829 }
1830
1831 // remember this in case the next frame comes immediately
1832 ratecontrol_next_frame_start = ratecontrol_frame_start +
1833 std::chrono::duration_cast<std::chrono::nanoseconds>(1ms) *
1834 ratecontrol_frame_packets_sent / ratecontrol_packets_in_1ms;
1835
1836 frame_network_latency_logger.second_point_now_and_log();
1837
1838 BOOST_LOG(verbose) << "Sent Frame seq ["sv << packet->frame_index() << "] pts ["sv << timestamp
1839 << "] shards ["sv << shards.size() << "/"sv << shards.percentage << "%]"sv
1840 << (frame_is_dupe ? " Dupe" : "")
1841 << (packet->is_idr() ? " Key" : "")
1842 << (packet->after_ref_frame_invalidation ? " RFI" : "");
1843
1844 ++blockIndex;
1845 lowseq += shards.size();
1846 session->video_loss.on_sent(shards.size(), shards.data_shards);
1847 });
1848
1849 session->video.lowseq = lowseq;
1850 } catch (const std::exception &e) {
1851 BOOST_LOG(error) << "Broadcast video failed "sv << e.what();
1852 std::this_thread::sleep_for(100ms);
1853 }
1854 }
1855
1856 shutdown_event->raise(true);
1857 }
1858
1859 void audioBroadcastThread(udp::socket &sock) {
1860 auto shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown);
1861 auto packets = mail::man->queue<audio::packet_t>(mail::audio_packets);
1862
1863 audio_packet_t audio_packet;
1864 fec::rs_t rs {reed_solomon_new(RTPA_DATA_SHARDS, RTPA_FEC_SHARDS)};
1865 crypto::aes_t iv(16);
1866
1867 // For unknown reasons, the RS parity matrix computed by our RS implementation
1868 // doesn't match the one Nvidia uses for audio data. I'm not exactly sure why,
1869 // but we can simply replace it with the matrix generated by OpenFEC which
1870 // works correctly. This is possible because the data and FEC shard count is
1871 // constant and known in advance.
1872 const unsigned char parity[] = {0x77, 0x40, 0x38, 0x0e, 0xc7, 0xa7, 0x0d, 0x6c};
1873 memcpy(rs.get()->p, parity, sizeof(parity));
1874
1875 audio_packet.rtp.header = 0x80;
1876 audio_packet.rtp.packetType = 97;
1877 audio_packet.rtp.ssrc = 0;
1878
1879 // Audio traffic is sent on this thread
1880 platf::adjust_thread_priority(platf::thread_priority_e::high);
1881
1882 while (auto packet = packets->pop()) {
1883 if (shutdown_event->peek()) {
1884 break;
1885 }
1886
1887 TUPLE_2D_REF(channel_data, packet_data, *packet);
1888 auto session = (session_t *) channel_data;
1889
1890 auto sequenceNumber = session->audio.sequenceNumber;
1891 auto timestamp = session->audio.timestamp;
1892
1893 *(std::uint32_t *) iv.data() = util::endian::big<std::uint32_t>(session->audio.avRiKeyId + sequenceNumber);
1894
1895 auto &shards_p = session->audio.shards_p;
1896
1897 auto bytes = encode_audio(session->config.encryptionFlagsEnabled & SS_ENC_AUDIO, packet_data, shards_p[sequenceNumber % RTPA_DATA_SHARDS], iv, session->audio.cipher);
1898 if (bytes < 0) {
1899 BOOST_LOG(error) << "Couldn't encode audio packet"sv;
1900 break;
1901 }
1902
1903 BOOST_LOG(verbose) << "Audio [seq "sv << sequenceNumber << ", pts "sv << timestamp << "] :: send..."sv;
1904
1905 audio_packet.rtp.sequenceNumber = util::endian::big(sequenceNumber);
1906 audio_packet.rtp.timestamp = util::endian::big(timestamp);
1907
1908 session->audio.sequenceNumber++;
1909 session->audio.timestamp += session->config.audio.packetDuration;
1910
1911 auto peer_address = session->audio.peer.address();
1912 try {
1913 auto send_info = platf::send_info_t {
1914 (const char *) &audio_packet,
1915 sizeof(audio_packet),
1916 (const char *) shards_p[sequenceNumber % RTPA_DATA_SHARDS],
1917 (size_t) bytes,
1918 (uintptr_t) sock.native_handle(),
1919 peer_address,
1920 session->audio.peer.port(),
1921 session->localAddress,
1922 };
1923 platf::send(send_info);
1924
1925 auto &fec_packet = session->audio.fec_packet;
1926 // initialize the FEC header at the beginning of the FEC block
1927 if (sequenceNumber % RTPA_DATA_SHARDS == 0) {
1928 fec_packet.fecHeader.baseSequenceNumber = util::endian::big(sequenceNumber);
1929 fec_packet.fecHeader.baseTimestamp = util::endian::big(timestamp);
1930 }
1931
1932 // generate parity shards at the end of the FEC block
1933 if ((sequenceNumber + 1) % RTPA_DATA_SHARDS == 0) {
1934 reed_solomon_encode(rs.get(), shards_p.begin(), RTPA_TOTAL_SHARDS, bytes);
1935
1936 for (auto x = 0; x < RTPA_FEC_SHARDS; ++x) {
1937 fec_packet.rtp.sequenceNumber = util::endian::big<std::uint16_t>(sequenceNumber + x + 1);
1938 fec_packet.fecHeader.fecShardIndex = x;
1939
1940 auto send_info = platf::send_info_t {
1941 (const char *) &fec_packet,
1942 sizeof(fec_packet),
1943 (const char *) shards_p[RTPA_DATA_SHARDS + x],
1944 (size_t) bytes,
1945 (uintptr_t) sock.native_handle(),
1946 peer_address,
1947 session->audio.peer.port(),
1948 session->localAddress,
1949 };
1950 platf::send(send_info);
1951 BOOST_LOG(verbose) << "Audio FEC ["sv << (sequenceNumber & ~(RTPA_DATA_SHARDS - 1)) << ' ' << x << "] :: send..."sv;
1952 }
1953 }
1954 } catch (const std::exception &e) {
1955 BOOST_LOG(error) << "Broadcast audio failed "sv << e.what();
1956 std::this_thread::sleep_for(100ms);
1957 }
1958 }
1959
1960 shutdown_event->raise(true);
1961 }
1962
1971 static void report_stream_start_failure(const std::string &reason) {
1972 BOOST_LOG(error) << reason;
1973#if defined HERMES_TRAY && HERMES_TRAY >= 1
1975#endif
1976 }
1977
1978 int start_broadcast(broadcast_ctx_t &ctx) {
1979 auto address_family = net::af_from_enum_string(config::sunshine.address_family);
1980 auto protocol = address_family == net::IPV4 ? udp::v4() : udp::v6();
1981 auto control_port = net::map_port(CONTROL_PORT);
1982 auto video_port = net::map_port(VIDEO_STREAM_PORT);
1983 auto audio_port = net::map_port(AUDIO_STREAM_PORT);
1984
1985 boost::system::error_code ec;
1986 const auto report_bind_failure = [](const char *transport, std::uint16_t port, const boost::system::error_code &error) {
1987 auto reason = std::string {"Could not initialize the "} + transport + " stream on UDP port " +
1988 std::to_string(port) + ": " + error.message() + " (" + error.category().name() +
1989 ':' + std::to_string(error.value()) + ").";
1990 if (error == boost::asio::error::address_in_use) {
1991 reason += " The port is already in use. Check which process holds it, including any remaining Hermes or helper process.";
1992 }
1993 report_stream_start_failure(reason);
1994 };
1995
1996 if (ctx.control_server.bind(address_family, control_port, ec)) {
1997 report_bind_failure("control", control_port, ec);
1998
1999 return -1;
2000 }
2001
2002 ctx.video_sock.open(protocol, ec);
2003 if (!ec) {
2004 net::prevent_socket_inheritance(ctx.video_sock.native_handle(), ec);
2005 }
2006 if (ec) {
2007 report_bind_failure("video", video_port, ec);
2008
2009 return -1;
2010 }
2011
2012 // Set video socket send buffer size (SO_SENDBUF) to 1MB
2013 try {
2014 ctx.video_sock.set_option(boost::asio::socket_base::send_buffer_size(1024 * 1024));
2015 } catch (...) {
2016 BOOST_LOG(error) << "Failed to set video socket send buffer size (SO_SENDBUF)";
2017 }
2018
2019 ctx.video_sock.bind(udp::endpoint(protocol, video_port), ec);
2020 if (ec) {
2021 report_bind_failure("video", video_port, ec);
2022
2023 return -1;
2024 }
2025
2026 ctx.audio_sock.open(protocol, ec);
2027 if (!ec) {
2028 net::prevent_socket_inheritance(ctx.audio_sock.native_handle(), ec);
2029 }
2030 if (ec) {
2031 report_bind_failure("audio", audio_port, ec);
2032
2033 return -1;
2034 }
2035
2036 ctx.audio_sock.bind(udp::endpoint(protocol, audio_port), ec);
2037 if (ec) {
2038 report_bind_failure("audio", audio_port, ec);
2039
2040 return -1;
2041 }
2042
2043 ctx.message_queue_queue = std::make_shared<message_queue_queue_t::element_type>(30);
2044
2045 // If a later thread cannot start, join the ones already created before
2046 // shared_t destroys this partially initialized context.
2047 auto rollback = util::fail_guard([&ctx]() {
2048 end_broadcast(ctx);
2049 });
2050 try {
2051 ctx.video_thread = std::thread {videoBroadcastThread, std::ref(ctx.video_sock)};
2052 ctx.audio_thread = std::thread {audioBroadcastThread, std::ref(ctx.audio_sock)};
2053 ctx.control_thread = std::thread {controlBroadcastThread, &ctx.control_server};
2054 ctx.recv_thread = std::thread {recvThread, std::ref(ctx)};
2055 } catch (const std::system_error &error) {
2056 report_stream_start_failure(std::string {"Could not start streaming threads: "} + error.what());
2057 return -1;
2058 }
2059 if (config::audio.stream_mic) {
2060 const auto mic_port = net::map_port(MIC_STREAM_PORT);
2061 ctx.mic_sock.open(protocol, ec);
2062 if (!ec) {
2063 net::prevent_socket_inheritance(ctx.mic_sock.native_handle(), ec);
2064 }
2065 if (!ec) {
2066 ctx.mic_sock.bind(udp::endpoint(protocol, mic_port), ec);
2067 }
2068 if (!ec) {
2069 ctx.mic_sock.non_blocking(true, ec);
2070 }
2071 if (ec) {
2072 BOOST_LOG(error) << "Couldn't listen for client microphones on port ["sv << mic_port << "]: "sv << ec.message();
2073 ctx.mic_sock.close(ec);
2074 } else {
2075 try {
2076 ctx.mic_thread = std::thread {micRecvThread, std::ref(ctx)};
2077 } catch (const std::system_error &error) {
2078 report_stream_start_failure(std::string {"Could not start client microphone thread: "} + error.what());
2079 return -1;
2080 }
2081 }
2082 }
2083 rollback.disable();
2084 BOOST_LOG(debug) << "Streaming transports ready: control=" << control_port
2085 << " video=" << video_port << " audio=" << audio_port;
2086
2087 return 0;
2088 }
2089
2090 void end_broadcast(broadcast_ctx_t &ctx) {
2091 auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown);
2092
2093 broadcast_shutdown_event->raise(true);
2094
2095 auto video_packets = mail::man->queue<video::packet_t>(mail::video_packets);
2096 auto audio_packets = mail::man->queue<audio::packet_t>(mail::audio_packets);
2097
2098 // Minimize delay stopping video/audio threads
2099 video_packets->stop();
2100 audio_packets->stop();
2101
2102 ctx.message_queue_queue->stop();
2103 ctx.io_context.stop();
2104
2105 boost::system::error_code ec;
2106 ctx.video_sock.close(ec);
2107 ctx.audio_sock.close(ec);
2108
2109 video_packets.reset();
2110 audio_packets.reset();
2111
2112 BOOST_LOG(debug) << "Waiting for main listening thread to end..."sv;
2113 if (ctx.recv_thread.joinable()) {
2114 ctx.recv_thread.join();
2115 }
2116 BOOST_LOG(debug) << "Waiting for main video thread to end..."sv;
2117 if (ctx.video_thread.joinable()) {
2118 ctx.video_thread.join();
2119 }
2120 BOOST_LOG(debug) << "Waiting for main audio thread to end..."sv;
2121 if (ctx.audio_thread.joinable()) {
2122 ctx.audio_thread.join();
2123 }
2124 BOOST_LOG(debug) << "Waiting for main control thread to end..."sv;
2125 if (ctx.control_thread.joinable()) {
2126 ctx.control_thread.join();
2127 }
2128 if (ctx.mic_thread.joinable()) {
2129 // Nonblocking receive observes broadcast_shutdown within 2 ms, even
2130 // when a client never sent a microphone packet.
2131 ctx.mic_thread.join();
2132 }
2133 boost::system::error_code mic_ec;
2134 ctx.mic_sock.close(mic_ec);
2135
2136 // ENet must be released after its last user joins.
2137 ctx.control_server._host.reset();
2138 BOOST_LOG(debug) << "All broadcasting threads ended; streaming sockets released"sv;
2139
2140 broadcast_shutdown_event->reset();
2141 }
2142
2143 int recv_ping(session_t *session, decltype(broadcast)::ptr_t ref, socket_e type, std::string_view expected_payload, udp::endpoint &peer, std::chrono::milliseconds timeout) {
2144 auto messages = std::make_shared<message_queue_t::element_type>(30);
2145 av_session_id_t session_id = std::string {expected_payload};
2146
2147 // Only allow matches on the peer address for legacy clients
2148 if (!(session->config.mlFeatureFlags & ML_FF_SESSION_ID_V1)) {
2149 ref->message_queue_queue->raise(type, peer.address(), messages);
2150 }
2151 ref->message_queue_queue->raise(type, session_id, messages);
2152
2153 auto fg = util::fail_guard([&]() {
2154 messages->stop();
2155
2156 // remove message queue from session
2157 if (!(session->config.mlFeatureFlags & ML_FF_SESSION_ID_V1)) {
2158 ref->message_queue_queue->raise(type, peer.address(), nullptr);
2159 }
2160 ref->message_queue_queue->raise(type, session_id, nullptr);
2161 });
2162
2163 const auto deadline = std::chrono::steady_clock::now() + timeout;
2164 const auto poll_interval = std::chrono::duration_cast<std::chrono::steady_clock::duration>(100ms);
2165
2166 while (session->state.load(std::memory_order_acquire) == session::state_e::RUNNING) {
2167 const auto now = std::chrono::steady_clock::now();
2168 if (now >= deadline) {
2169 break;
2170 }
2171
2172 // A stopped session must not spend its teardown budget waiting for a
2173 // client that never completed the handshake.
2174 auto msg_opt = messages->pop(std::min(deadline - now, poll_interval));
2175 if (session->state.load(std::memory_order_acquire) != session::state_e::RUNNING) {
2176 return -1;
2177 }
2178 if (!msg_opt) {
2179 continue;
2180 }
2181
2182 TUPLE_2D_REF(recv_peer, msg, *msg_opt);
2183 if (msg.find(expected_payload) != std::string::npos) {
2184 // Match the new PING payload format
2185 BOOST_LOG(debug) << "Received ping [v2] from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']';
2186 } else if (!(session->config.mlFeatureFlags & ML_FF_SESSION_ID_V1) && msg == "PING"sv) {
2187 // Match the legacy fixed PING payload only if the new type is not supported
2188 BOOST_LOG(debug) << "Received ping [v1] from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']';
2189 } else {
2190 BOOST_LOG(debug) << "Received non-ping from "sv << recv_peer.address() << ':' << recv_peer.port() << " ["sv << util::hex_vec(msg) << ']';
2191 continue;
2192 }
2193
2194 // Update connection details.
2195 peer = recv_peer;
2196 return 0;
2197 }
2198
2199 if (session->state.load(std::memory_order_acquire) == session::state_e::RUNNING) {
2200 BOOST_LOG(error) << "Initial Ping Timeout"sv;
2201 }
2202 return -1;
2203 }
2204
2205 void videoThread(session_t *session) {
2206 // If this is the first stop (the video handshake never completed), record
2207 // it as a handshake failure. If the session already stopped for another
2208 // reason, stop() keeps that earlier reason.
2209 auto fg = util::fail_guard([&]() {
2210 session::stop(*session, session::termination_reason_e::HANDSHAKE_FAILED);
2211 });
2212
2213 while_starting_do_nothing(session->state);
2214
2215 auto ref = broadcast.ref();
2216 auto error = recv_ping(session, ref, socket_e::video, session->video.ping_payload, session->video.peer, config::stream.ping_timeout);
2217 if (error < 0) {
2218 return;
2219 }
2220
2221 // Enable local prioritization and QoS tagging on video traffic if requested by the client
2222 auto address = session->video.peer.address();
2223 session->video.qos = platf::enable_socket_qos(ref->video_sock.native_handle(), address, session->video.peer.port(), platf::qos_data_type_e::video, session->config.videoQosType != 0);
2224
2225 BOOST_LOG(debug) << "Start capturing Video"sv;
2226 video::capture(session->mail, session->config.monitor, session);
2227 }
2228
2229 void audioThread(session_t *session) {
2230 auto fg = util::fail_guard([&]() {
2231 session::stop(*session, session::termination_reason_e::HANDSHAKE_FAILED);
2232 });
2233
2234 while_starting_do_nothing(session->state);
2235
2236 auto ref = broadcast.ref();
2237 auto error = recv_ping(session, ref, socket_e::audio, session->audio.ping_payload, session->audio.peer, config::stream.ping_timeout);
2238 if (error < 0) {
2239 return;
2240 }
2241
2242 // Enable local prioritization and QoS tagging on audio traffic if requested by the client
2243 auto address = session->audio.peer.address();
2244 session->audio.qos = platf::enable_socket_qos(ref->audio_sock.native_handle(), address, session->audio.peer.port(), platf::qos_data_type_e::audio, session->config.audioQosType != 0);
2245
2246 BOOST_LOG(debug) << "Start capturing Audio"sv;
2247 audio::capture(session->mail, session->config.audio, session);
2248 }
2249
2250 namespace session {
2251 session_activity_counter_t running_sessions;
2252 std::atomic_uint shared_running_sessions;
2253
2254 state_e state(session_t &session) {
2255 return session.state.load(std::memory_order_relaxed);
2256 }
2257
2258 inline bool send(session_t& session, const std::string_view &payload) {
2259 return session.broadcast_ref->control_server.send(payload, session.control.peer);
2260 }
2261
2262 std::string uuid(const session_t& session) {
2263 return session.device_uuid;
2264 }
2265
2266 bool uuid_match(const session_t &session, const std::string_view& uuid) {
2267 return session.device_uuid == uuid;
2268 }
2269
2270 bool isolated(const session_t &session) {
2271 return session.isolated_session;
2272 }
2273
2274 bool update_device_info(session_t& session, const std::string& name, const crypto::PERM& newPerm) {
2275 session.permission = newPerm;
2276 if (!(newPerm & crypto::PERM::_allow_view)) {
2277 BOOST_LOG(debug) << "Session: View permission revoked for [" << session.device_name << "], disconnecting...";
2278 session.termination_reason.store(termination_reason_e::PERMISSION_REVOKED, std::memory_order_relaxed);
2279 graceful_stop(session);
2280 return true;
2281 }
2282
2283 BOOST_LOG(debug) << "Session: Permission updated for [" << session.device_name << "]";
2284
2285 if (session.device_name != name) {
2286 BOOST_LOG(debug) << "Session: Device name changed from [" << session.device_name << "] to [" << name << "]";
2287 session.device_name = name;
2288 }
2289
2290 return false;
2291 }
2292
2293 std::atomic<termination_reason_e> last_termination_reason_v {termination_reason_e::UNKNOWN};
2294
2295 // Reconnection/termination observability. Updated once per session-end (the
2296 // first stop() that wins the reason), read by the diagnostics endpoint.
2297 std::mutex termination_stats_mutex;
2298 std::optional<std::chrono::steady_clock::time_point> last_termination_time_v;
2299 uint64_t total_ended_v {0};
2300 uint64_t client_lost_count_v {0};
2301
2302 std::string_view termination_reason_str(termination_reason_e reason) {
2303 switch (reason) {
2304 case termination_reason_e::CLIENT_QUIT:
2305 return "client_quit"sv;
2306 case termination_reason_e::CLIENT_LOST:
2307 return "client_lost"sv;
2308 case termination_reason_e::HANDSHAKE_FAILED:
2309 return "handshake_failed"sv;
2310 case termination_reason_e::PROTOCOL_ERROR:
2311 return "protocol_error"sv;
2312 case termination_reason_e::SERVER_STOPPED:
2313 return "server_stopped"sv;
2314 case termination_reason_e::PERMISSION_REVOKED:
2315 return "permission_revoked"sv;
2316 case termination_reason_e::UNKNOWN:
2317 default:
2318 return "unknown"sv;
2319 }
2320 }
2321
2323 return last_termination_reason_v.load(std::memory_order_relaxed);
2324 }
2325
2328 out.last_reason = last_termination_reason_v.load(std::memory_order_relaxed);
2329 std::lock_guard lg {termination_stats_mutex};
2330 if (last_termination_time_v) {
2331 out.ms_since_last_end = static_cast<uint64_t>(
2332 std::chrono::duration_cast<std::chrono::milliseconds>(
2333 std::chrono::steady_clock::now() - *last_termination_time_v)
2334 .count());
2335 }
2336 out.total_ended = total_ended_v;
2337 out.client_lost_count = client_lost_count_v;
2338 return out;
2339 }
2340
2341 void stop(session_t &session, termination_reason_e reason) {
2342 while_starting_do_nothing(session.state);
2343 auto expected = state_e::RUNNING;
2344 auto already_stopping = !session.state.compare_exchange_strong(expected, state_e::STOPPING);
2345 if (already_stopping) {
2346 return;
2347 }
2348
2349 // First stop() call for this session wins the reason; later calls (e.g. a
2350 // shutdown sweep after the client already dropped) don't overwrite it.
2351 session.termination_reason.store(reason, std::memory_order_relaxed);
2352 last_termination_reason_v.store(reason, std::memory_order_relaxed);
2353
2354 // Record reconnection/termination stats. Only the stop() that won the
2355 // RUNNING->STOPPING transition reaches here, so each session-end is
2356 // counted exactly once.
2357 {
2358 std::lock_guard lg {termination_stats_mutex};
2359 last_termination_time_v = std::chrono::steady_clock::now();
2360 ++total_ended_v;
2361 if (reason == termination_reason_e::CLIENT_LOST) {
2362 ++client_lost_count_v;
2363 }
2364 }
2365
2366 if (const auto silences = session.client_link.silence_count()) {
2367 BOOST_LOG(info) << "Client ["sv << session.device_name << "] went silent "sv << silences
2368 << (silences == 1 ? " time"sv : " times"sv) << " for "sv
2369 << client_link_monitor_t::silence_threshold.count() << " ms or more (longest "sv
2370 << session.client_link.longest_silence().count() << " ms, "sv
2371 << session.client_link.total_silence().count() << " ms in all)"sv;
2372 }
2373
2374 if (const auto missing = session.video_loss.missing_packets()) {
2375 const auto sent = session.video_loss.sent_packets();
2376 const auto dropped = session.video_loss.dropped_frames();
2377 BOOST_LOG(info) << "Client ["sv << session.device_name << "] lost "sv << missing << " of "sv << sent
2378 << " video packets ("sv << std::fixed << std::setprecision(2) << (sent ? 100.0 * missing / sent : 0.0) << "%): "sv
2379 << session.video_loss.repaired_blocks() << " frame blocks repaired by FEC, "sv
2380 << dropped << (dropped == 1 ? " frame"sv : " frames"sv) << " dropped"sv;
2381 }
2382
2383 if (reason == termination_reason_e::CLIENT_LOST) {
2384 BOOST_LOG(warning) << "Session ended: client ["sv << session.device_name << "] stopped responding (network loss or crash)"sv;
2385 } else {
2386 BOOST_LOG(info) << "Session ended: ["sv << session.device_name << "] reason="sv << termination_reason_str(reason);
2387 }
2388
2389 session.shutdown_event->raise(true);
2390 }
2391
2392 void graceful_stop(session_t& session) {
2393 while_starting_do_nothing(session.state);
2394 // Preserve a more specific reason set by the caller (e.g. permission
2395 // revoked); otherwise this is a host-initiated graceful stop.
2396 {
2397 auto expected_reason = termination_reason_e::UNKNOWN;
2398 session.termination_reason.compare_exchange_strong(expected_reason, termination_reason_e::SERVER_STOPPED);
2399 }
2400 auto expected = state_e::RUNNING;
2401 auto already_stopping = !session.state.compare_exchange_strong(expected, state_e::STOPPING);
2402 if (already_stopping) {
2403 return;
2404 }
2405
2406 const auto graceful_reason = session.termination_reason.load(std::memory_order_relaxed);
2407 last_termination_reason_v.store(graceful_reason, std::memory_order_relaxed);
2408
2409 // Count this session-end too (graceful_stop wins its own RUNNING->STOPPING
2410 // transition, so it never overlaps with the stop() accounting above).
2411 {
2412 std::lock_guard lg {termination_stats_mutex};
2413 last_termination_time_v = std::chrono::steady_clock::now();
2414 ++total_ended_v;
2415 if (graceful_reason == termination_reason_e::CLIENT_LOST) {
2416 ++client_lost_count_v;
2417 }
2418 }
2419
2420 BOOST_LOG(info) << "Session ended: ["sv << session.device_name << "] reason="sv << termination_reason_str(graceful_reason);
2421
2422 // The control thread sends the termination message and then releases
2423 // join(). Doing either here, on an HTTP thread, raced that thread for
2424 // the session's control cipher, and let join() free the session while
2425 // the control server still listed it, which the control thread then
2426 // used (a crash when it encrypted the next termination message).
2427 session.control.send_termination.store(true, std::memory_order_release);
2428 session.shutdown_event->raise(true);
2429 }
2430
2431 void join(session_t &session) {
2432 // Current Nvidia drivers have a bug where NVENC can deadlock the encoder thread with hardware-accelerated
2433 // GPU scheduling enabled. If this happens, we will terminate ourselves and the service can restart.
2434 // The alternative is that Sunshine can never start another session until it's manually restarted.
2435 auto task = []() {
2436 BOOST_LOG(fatal) << "Hang detected! Session failed to terminate in 10 seconds."sv;
2439 };
2440 auto force_kill = task_pool.pushDelayed(task, 10s).task_id;
2441 auto fg = util::fail_guard([&force_kill]() {
2442 // Cancel the kill task if we manage to return from this function
2443 task_pool.cancel(force_kill);
2444 });
2445
2446 BOOST_LOG(debug) << "Waiting for video to end..."sv;
2447 session.videoThread.join();
2448 BOOST_LOG(debug) << "Waiting for audio to end..."sv;
2449 session.audioThread.join();
2450 BOOST_LOG(debug) << "Waiting for control to end..."sv;
2451 session.controlEnd.view();
2452 // Reset input on session stop to avoid stuck repeated keys
2453 BOOST_LOG(debug) << "Resetting Input..."sv;
2454 input::reset(session.input);
2455
2456 if (!session.undo_cmds.empty()) {
2457 auto session_env = proc::proc.get_session_env(
2458 session.isolated_session ?
2459 session.isolated_runtime_owner_id :
2460 session.launch_session_id
2461 );
2462 auto exec_thread = std::thread([
2463 cmd_list = session.undo_cmds,
2464 env = std::move(session_env)
2465 ]() mutable {
2466 for (auto &cmd : cmd_list) {
2467 std::error_code ec;
2468 boost::filesystem::path working_dir = proc::find_working_directory(cmd.cmd, env);
2469 auto child = platf::run_command(cmd.elevated, true, cmd.cmd, working_dir, env, nullptr, ec, nullptr);
2470 BOOST_LOG(info) << "Spawning client undo command ["sv << cmd.cmd << "] in ["sv << working_dir << ']';
2471 if (ec) {
2472 BOOST_LOG(warning) << "Couldn't spawn ["sv << cmd.cmd << "]: System: "sv << ec.message();
2473 } else {
2474 child.detach();
2475 }
2476 }
2477 });
2478
2479 exec_thread.detach();
2480 }
2481
2482 if (!session.isolated_session && --shared_running_sessions == 0) {
2483 bool revert_display_config {config::video.dd.config_revert_on_disconnect};
2484
2485 if (proc::proc.running()) {
2486 proc::proc.pause();
2487 } else {
2488 revert_display_config = true;
2489 }
2490
2491 if (revert_display_config) {
2493 }
2494 }
2495
2496 // Platform-wide streaming state still spans both ownership domains.
2497 running_sessions.stopped([] {
2498 platf::streaming_will_stop();
2499 });
2500
2501 BOOST_LOG(debug) << "Session ended"sv;
2502 }
2503
2504 int start(session_t &session, const std::string &addr_string) {
2505 // Reject incomplete private routes before allocating host input.
2506 const auto &monitor = session.config.monitor;
2507 if (monitor.kwin_wayland_socket.empty() != monitor.kwin_pipewire_socket.empty()) {
2508 BOOST_LOG(error) << "Private KWin session requires both Wayland and PipeWire endpoints";
2509 return -1;
2510 }
2511 try {
2512 session.input = input::alloc(
2513 session.mail,
2514 session.isolated_session ? session.isolated_seat_id : std::string {},
2515 session.isolated_session ? session.config.gcmap.value_or(0) : 0,
2516 monitor.kwin_wayland_socket,
2517 session.device_uuid
2518 );
2519 } catch (const std::exception &error) {
2520 BOOST_LOG(::error) << "Could not initialize session input: " << error.what();
2521 return -1;
2522 }
2523
2524 session.broadcast_ref = broadcast.ref();
2525 if (!session.broadcast_ref) {
2526 return -1;
2527 }
2528
2529 session.control.expected_peer_address = addr_string;
2530 BOOST_LOG(debug) << "Expecting incoming session connections from "sv << addr_string;
2531
2532 if (!session.config.mic_source.empty()) {
2533 session.audio.mic = audio::open_client_mic(session.config.mic_source);
2534 }
2535
2536 auto addr = boost::asio::ip::make_address(addr_string);
2537 session.video.peer.address(addr);
2538 session.video.peer.port(0);
2539
2540 session.audio.peer.address(addr);
2541 session.audio.peer.port(0);
2542
2543 session.pingTimeout = std::chrono::steady_clock::now() + config::stream.ping_timeout;
2544 session.state.store(state_e::STARTING, std::memory_order_relaxed);
2545
2546 // Publish only after the control deadline and peer addresses are initialized.
2547 // The control thread may inspect the session as soon as this lock is released.
2548 {
2549 auto lg = session.broadcast_ref->control_server._sessions.lock();
2550 session.broadcast_ref->control_server._sessions->push_back(&session);
2551 }
2552
2553 session.audioThread = std::thread {audioThread, &session};
2554 session.videoThread = std::thread {videoThread, &session};
2555
2556 session.state.store(state_e::RUNNING, std::memory_order_release);
2557
2558 // Platform-wide callbacks track every stream, while the legacy process
2559 // lifecycle belongs only to streams attached to the shared host session.
2560 running_sessions.started([] {
2561 platf::streaming_will_start();
2562 });
2563
2564 if (!session.isolated_session && ++shared_running_sessions == 1) {
2565 proc::proc.resume();
2566 }
2567
2568 if (!session.do_cmds.empty()) {
2569 auto session_env = proc::proc.get_session_env(
2570 session.isolated_session ?
2571 session.isolated_runtime_owner_id :
2572 session.launch_session_id
2573 );
2574 auto exec_thread = std::thread([
2575 cmd_list = session.do_cmds,
2576 env = std::move(session_env)
2577 ]() mutable {
2578 for (auto &cmd : cmd_list) {
2579 std::error_code ec;
2580 boost::filesystem::path working_dir = proc::find_working_directory(cmd.cmd, env);
2581 auto child = platf::run_command(cmd.elevated, true, cmd.cmd, working_dir, env, nullptr, ec, nullptr);
2582 BOOST_LOG(info) << "Spawning client do command ["sv << cmd.cmd << "] in ["sv << working_dir << ']';
2583 if (ec) {
2584 BOOST_LOG(warning) << "Couldn't spawn ["sv << cmd.cmd << "]: System: "sv << ec.message();
2585 } else {
2586 child.detach();
2587 }
2588 }
2589 });
2590
2591 exec_thread.detach();
2592 }
2593
2594 return 0;
2595 }
2596
2597 std::shared_ptr<session_t> alloc(config_t &config, rtsp_stream::launch_session_t &launch_session) {
2598 auto session = std::make_shared<session_t>();
2599
2600 auto mail = std::make_shared<safe::mail_raw_t>();
2601
2602 session->shutdown_event = mail->event<bool>(mail::shutdown);
2603 session->launch_session_id = launch_session.id;
2604 session->device_name = launch_session.device_name;
2605 session->device_uuid = launch_session.unique_id;
2606 session->permission = launch_session.perm;
2607 session->isolated_session = launch_session.isolated_session;
2608 session->isolated_runtime_owner_id = launch_session.isolated_runtime_owner_id;
2609 session->isolated_runtime_id = launch_session.isolated_runtime_id;
2610 session->isolated_seat_id = launch_session.isolated_seat_id;
2611 session->session_scoped_virtual_display = launch_session.session_scoped_virtual_display;
2612 session->display_name = launch_session.display_name;
2613 session->display_guid = launch_session.display_guid;
2614
2615 session->do_cmds = std::move(launch_session.client_do_cmds);
2616 session->undo_cmds = std::move(launch_session.client_undo_cmds);
2617
2618 session->config = config;
2619 session->config.monitor.display_name = launch_session.display_name;
2620 session->config.monitor.kwin_wayland_socket = launch_session.kwin_wayland_socket;
2621 session->config.monitor.kwin_pipewire_socket = launch_session.kwin_pipewire_socket;
2622 if (!launch_session.kwin_wayland_socket.empty()) {
2623 session->config.monitor.display_name = "kwin:" + launch_session.kwin_wayland_socket;
2624 }
2625 // Preserve the session-scoped marker for process-level cleanup decisions,
2626 // but move responsibility for releasing the output into session_t.
2627 launch_session.session_virtual_display_cleanup_pending = false;
2628
2629 session->control.connect_data = launch_session.control_connect_data;
2630 session->control.feedback_queue = mail->queue<platf::gamepad_feedback_msg_t>(mail::gamepad_feedback);
2631 session->control.hdr_queue = mail->event<video::hdr_info_t>(mail::hdr);
2632 session->control.legacy_input_enc_iv = launch_session.iv;
2633 session->control.cipher = crypto::cipher::gcm_t {
2634 launch_session.gcm_key,
2635 false
2636 };
2637
2638 session->video.idr_events = mail->event<bool>(mail::idr);
2639 session->video.invalidate_ref_frames_events = mail->event<std::pair<int64_t, int64_t>>(mail::invalidate_ref_frames);
2640 session->video.lowseq = 0;
2641 session->video.ping_payload = launch_session.av_ping_payload;
2642 if (config.encryptionFlagsEnabled & SS_ENC_VIDEO) {
2643 BOOST_LOG(info) << "Video encryption enabled"sv;
2644 session->video.cipher = crypto::cipher::gcm_t {
2645 launch_session.gcm_key,
2646 false
2647 };
2648 session->video.gcm_iv_counter = 0;
2649 }
2650
2651 constexpr auto max_block_size = crypto::cipher::round_to_pkcs7_padded(2048);
2652
2653 util::buffer_t<char> shards {RTPA_TOTAL_SHARDS * max_block_size};
2654 util::buffer_t<uint8_t *> shards_p {RTPA_TOTAL_SHARDS};
2655
2656 for (auto x = 0; x < RTPA_TOTAL_SHARDS; ++x) {
2657 shards_p[x] = (uint8_t *) &shards[x * max_block_size];
2658 }
2659
2660 // Audio FEC spans multiple audio packets,
2661 // therefore its session specific
2662 session->audio.shards = std::move(shards);
2663 session->audio.shards_p = std::move(shards_p);
2664
2665 session->audio.fec_packet.rtp.header = 0x80;
2666 session->audio.fec_packet.rtp.packetType = 127;
2667 session->audio.fec_packet.rtp.timestamp = 0;
2668 session->audio.fec_packet.rtp.ssrc = 0;
2669
2670 session->audio.fec_packet.fecHeader.payloadType = 97;
2671 session->audio.fec_packet.fecHeader.ssrc = 0;
2672
2673 session->audio.cipher = crypto::cipher::cbc_t {
2674 launch_session.gcm_key,
2675 true
2676 };
2677
2678 session->audio.ping_payload = launch_session.av_ping_payload;
2679 session->audio.avRiKeyId = util::endian::big(*(std::uint32_t *) launch_session.iv.data());
2680 session->audio.sequenceNumber = 0;
2681 session->audio.timestamp = 0;
2682
2683 session->control.peer = nullptr;
2684 session->state.store(state_e::STOPPED, std::memory_order_relaxed);
2685
2686 session->mail = std::move(mail);
2687
2688 return session;
2689 }
2690 } // namespace session
2691} // namespace stream
Picks the FEC percentage for the next frame from what the client reports losing.
std::unique_ptr< client_mic_t > open_client_mic(const std::string &source)
nullptr if the session mic cannot be opened.
Definition audio.cpp:547
int encrypt(const std::string_view &plaintext, std::uint8_t *cipher, aes_t *iv)
Encrypts the plaintext using AES CBC mode. length of cipher must be at least: round_to_pkcs7_padded(p...
Definition crypto.cpp:279
A helper class for tracking and logging numerical values across a period of time.
Definition logging.h:102
A helper class for tracking and logging short time intervals across a period of time.
Definition logging.h:166
boost::process::v1::environment get_session_env(uint32_t launch_session_id)
Definition process.cpp:3180
void iterate()
Runs an iteration of the RTSP server loop.
Definition rtsp.cpp:674
void call(std::uint16_t type, session_t *session, const std::string_view &payload, bool reinjected)
Call the handler for a given control stream message.
Definition stream.cpp:645
std::uint64_t sent_packets() const
Video packets sent to the client, parity included.
static std::optional< report_t > parse(std::string_view payload)
std::uint64_t dropped_frames() const
Frames the client dropped because a block could not be rebuilt.
std::uint64_t repaired_blocks() const
Blocks the client rebuilt from parity: lost packets, no lost picture.
std::uint64_t missing_packets() const
Packets missing from the blocks the client reported.
Route legacy encrypted client-microphone packets to one session.
Declarations for common platform specific utilities.
std::unique_ptr< high_precision_timer > create_high_precision_timer()
Create platform-specific timer capable of high-precision sleep.
Definition misc.cpp:1811
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)
Enable QoS on the given socket for traffic to the specified destination.
Definition misc.cpp:1470
@ rumble_triggers
Rumble triggers.
Definition common.h:88
@ set_adaptive_triggers
Set adaptive triggers.
Definition common.h:91
@ set_motion_event_state
Set motion event state.
Definition common.h:89
@ set_rgb_led
Set RGB LED.
Definition common.h:90
@ high
High priority.
Definition common.h:696
@ timeout
Timeout.
Definition common.h:438
Declarations for the configuration of Sunshine.
void start()
Start the HTTPS server.
Declarations for cryptography functions.
PERM
The permissions of a client.
Definition crypto.h:45
void revert_configuration()
Revert the display configuration and restore the previous state.
Declarations for display device handling.
thread_pool_util::ThreadPool task_pool
A thread pool for processing tasks.
Definition globals.cpp:9
Declarations for globally accessible variables and functions.
std::shared_ptr< input_t > alloc(safe::mail_t mail, const std::string &session_tag, int launch_gamepads, const std::string &wayland_socket, const std::string &client_id)
Definition input.cpp:1854
Declarations for gamepad, keyboard, and mouse input handling.
Declarations for logging related functions.
void debug_trap()
Breaks into the debugger or terminates Sunshine if no debugger is attached.
void log_flush()
Flush the log.
Definition logging.cpp:205
Handles process-wide communication.
Definition globals.h:25
safe::mail_t man
A process-wide communication mechanism.
Definition globals.cpp:8
bool update_device_info(const std::string &uuid, const std::string &name, const std::string &display_mode, const cmd_list_t &do_cmds, const cmd_list_t &undo_cmds, const crypto::PERM newPerm, const bool enable_legacy_ordering, const bool allow_client_commands, const bool always_use_virtual_display)
Update device info.
Definition nvhttp.cpp:2436
void update_tray_session_error(std::string reason)
Spawns a notification for a session that could not start at all.
std::uint16_t map_port(int port)
Map a specified port based on the base port.
Definition network.cpp:350
af_e af_from_enum_string(const std::string_view &view)
Get the address family enum value from a string.
Definition network.cpp:166
Declarations for networking related functions.
af_e
Definition network.h:45
@ IPV4
IPv4 only.
Definition network.h:46
report_t report()
assess(collect_facts()).
Definition prelogin.cpp:609
@ missing
Known to be absent; fix says what to do.
Definition prelogin.h:25
Declarations for the startup and shutdown of the apps started by a streaming Session.
Wrappers for nanors vectorization.
void launch_session_clear(uint32_t launch_session_id)
Clear state for the specified launch session.
Definition rtsp.cpp:765
std::string_view last_termination_reason()
Get a short identifier for why the most recent session ended.
Definition rtsp.cpp:785
Serialized lifecycle transitions for platform-wide streaming state.
void note_recovery_after_silence(session_t &session, std::string_view request)
Definition stream.cpp:507
void send_termination(control_server_t *server, session_t *session)
Tell a client its stream ended gracefully, and flush it out.
Definition stream.cpp:1030
std::vector< uint8_t > concat_and_insert(uint64_t insert_size, uint64_t slice_size, const std::string_view &data1, const std::string_view &data2)
Combines two buffers and inserts new buffers at each slice boundary of the result.
Definition stream.cpp:828
termination_stats_t termination_stats()
Snapshot of the termination/reconnection stats.
Definition stream.cpp:2326
int send_feedback_msg(session_t *session, platf::gamepad_feedback_msg_t &msg)
Pass gamepad feedback data back to the client.
Definition stream.cpp:889
Declarations for the streaming protocols.
@ STARTING
The session is starting.
Definition stream.h:55
@ STOPPING
The session is stopping.
Definition stream.h:54
termination_reason_e
Why a streaming session ended.
Definition stream.h:66
@ PROTOCOL_ERROR
Malformed/failed control-stream exchange.
Definition stream.h:71
bool config_revert_on_disconnect
Specify whether to revert display configuration on client disconnect.
Definition config.h:119
Aggregate reconnection/termination stats for diagnostics.
Definition stream.h:86
uint64_t ms_since_last_end
Steady-clock ms since the last session ended; 0 if none has ended yet.
Definition stream.h:89
uint64_t client_lost_count
Of those, ended by client loss (drops).
Definition stream.h:91
uint64_t total_ended
Sessions that have ended this run.
Definition stream.h:90
std::shared_ptr< audio::client_mic_t > mic
Set before the session is listed, and only read after.
unsigned int client_silences_logged
Silences logged individually so far; the control thread owns it.
Definition stream.cpp:481
video_loss_monitor_t video_loss
Video the client reported losing on the way to it.
Definition stream.cpp:484
adaptive_fec_t adaptive_fec
Parity percentage for the next frame, from what the client reported losing.
Definition stream.cpp:486
client_link_monitor_t client_link
Gaps in what the client sends on the control connection.
Definition stream.cpp:479
Declarations for synchronization utilities.
Declarations for the system tray icon and notification system.
Declarations for thread-safe data structures.
Declarations for utility functions.
How much FEC a frame too large for the protocol's FEC blocks can keep.
constexpr std::size_t max_fec_blocks
The video packet header has 2 bits for the FEC block count.
constexpr int large_frame_fec_percentage(std::size_t data_packets, int configured, int min_parity)
Counts the video a client reports losing on the way to it.
constexpr std::uint16_t frame_fec_status_type
bool removeVirtualDisplay(const uuid_util::uuid_t &guid)
Remove a virtual display.