Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
rtsp.cpp
Go to the documentation of this file.
1
5#define BOOST_BIND_GLOBAL_PLACEHOLDERS
6
7extern "C" {
8#include <moonlight-common-c/src/Limelight-internal.h>
9#include <moonlight-common-c/src/Rtsp.h>
10}
11
12// standard includes
13#include <array>
14#include <cctype>
15#include <format>
16#include <set>
17#include <unordered_map>
18#include <utility>
19
20// lib includes
21#include <boost/asio.hpp>
22#include <boost/bind.hpp>
23
24// local includes
25#include "config.h"
26#include "globals.h"
27#include "input.h"
28#include "logging.h"
29#include "network.h"
30#include "process.h"
31#include "rtsp.h"
32#include "stream.h"
33#include "sync.h"
34#include "video.h"
35
36namespace asio = boost::asio;
37
38using asio::ip::tcp;
39using asio::ip::udp;
40
41using namespace std::literals;
42
43namespace rtsp_stream {
44 static void release_pending_virtual_display(launch_session_t &session) {
45 if (session.isolated_session &&
46 session.session_virtual_display_cleanup_pending) {
47 proc::proc.terminate_isolated(
48 session.isolated_runtime_owner_id ?
49 session.isolated_runtime_owner_id :
50 session.id
51 );
52 session.session_virtual_display_cleanup_pending = false;
53 session.session_scoped_virtual_display = false;
54 session.isolated_session = false;
55 session.display_name.clear();
56 return;
57 }
58 if (session.session_virtual_display_cleanup_pending) {
59 VDISPLAY::removeVirtualDisplay(session.display_guid);
60 session.session_virtual_display_cleanup_pending = false;
61 session.session_scoped_virtual_display = false;
62 session.display_name.clear();
63 }
64 }
65
66 void free_msg(PRTSP_MESSAGE msg) {
67 freeMessage(msg);
68
69 delete msg;
70 }
71
72#pragma pack(push, 1)
73
75 // We set the MSB in encrypted RTSP messages to allow format-agnostic
76 // parsing code to be able to tell encrypted from plaintext messages.
77 static constexpr std::uint32_t ENCRYPTED_MESSAGE_TYPE_BIT = 0x80000000;
78
79 uint8_t *payload() {
80 return (uint8_t *) (this + 1);
81 }
82
83 std::uint32_t payload_length() {
84 return util::endian::big<std::uint32_t>(typeAndLength) & ~ENCRYPTED_MESSAGE_TYPE_BIT;
85 }
86
87 bool is_encrypted() {
88 return !!(util::endian::big<std::uint32_t>(typeAndLength) & ENCRYPTED_MESSAGE_TYPE_BIT);
89 }
90
91 // This field is the length of the payload + ENCRYPTED_MESSAGE_TYPE_BIT in big-endian
92 std::uint32_t typeAndLength;
93
94 // This field is the number used to initialize the bottom 4 bytes of the AES IV in big-endian
95 std::uint32_t sequenceNumber;
96
97 // This field is the AES GCM authentication tag
98 std::uint8_t tag[16];
99 };
100
101#pragma pack(pop)
102
103 class rtsp_server_t;
104
105 using msg_t = util::safe_ptr<RTSP_MESSAGE, free_msg>;
106 using cmd_func_t = std::function<void(rtsp_server_t *server, tcp::socket &, launch_session_t &, msg_t &&)>;
107
108 void print_msg(PRTSP_MESSAGE msg);
109 void cmd_not_found(tcp::socket &sock, launch_session_t &, msg_t &&req);
110 void respond(tcp::socket &sock, launch_session_t &session, POPTION_ITEM options, int statuscode, const char *status_msg, int seqn, const std::string_view &payload);
111
112 class socket_t: public std::enable_shared_from_this<socket_t> {
113 public:
114 socket_t(boost::asio::io_context &io_context, std::function<void(tcp::socket &sock, launch_session_t &, msg_t &&)> &&handle_data_fn):
115 handle_data_fn {std::move(handle_data_fn)},
116 sock {io_context} {
117 }
118
122 void read() {
123 if (begin == std::end(msg_buf) || (session->rtsp_cipher && begin + sizeof(encrypted_rtsp_header_t) >= std::end(msg_buf))) {
124 BOOST_LOG(error) << "RTSP: read(): Exceeded maximum rtsp packet size: "sv << msg_buf.size();
125
126 respond(sock, *session, nullptr, 400, "BAD REQUEST", 0, {});
127
128 boost::system::error_code ec;
129 sock.close(ec);
130
131 return;
132 }
133
134 if (session->rtsp_cipher) {
135 // For encrypted RTSP, we will read the the entire header first
136 boost::asio::async_read(sock, boost::asio::buffer(begin, sizeof(encrypted_rtsp_header_t)), boost::bind(&socket_t::handle_read_encrypted_header, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
137 } else {
138 sock.async_read_some(
139 boost::asio::buffer(begin, (std::size_t) (std::end(msg_buf) - begin)),
140 boost::bind(
142 shared_from_this(),
143 boost::asio::placeholders::error,
144 boost::asio::placeholders::bytes_transferred
145 )
146 );
147 }
148 }
149
156 static void handle_read_encrypted_header(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) {
157 BOOST_LOG(debug) << "handle_read_encrypted_header(): Handle read of size: "sv << bytes << " bytes"sv;
158
159 auto sock_close = util::fail_guard([&socket]() {
160 boost::system::error_code ec;
161 socket->sock.close(ec);
162
163 if (ec) {
164 BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Couldn't close tcp socket: "sv << ec.message();
165 }
166 });
167
168 if (ec || bytes < sizeof(encrypted_rtsp_header_t)) {
169 BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Couldn't read from tcp socket: "sv << ec.message();
170
171 respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
172 return;
173 }
174
175 auto header = (encrypted_rtsp_header_t *) socket->begin;
176 if (!header->is_encrypted()) {
177 BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Rejecting unencrypted RTSP message"sv;
178
179 respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
180 return;
181 }
182
183 auto payload_length = header->payload_length();
184
185 // Check if we have enough space to read this message
186 if (socket->begin + sizeof(*header) + payload_length >= std::end(socket->msg_buf)) {
187 BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Exceeded maximum rtsp packet size: "sv << socket->msg_buf.size();
188
189 respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
190 return;
191 }
192
193 sock_close.disable();
194
195 // Read the remainder of the header and full encrypted payload
196 boost::asio::async_read(socket->sock, boost::asio::buffer(socket->begin + bytes, payload_length), boost::bind(&socket_t::handle_read_encrypted_message, socket->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
197 }
198
205 static void handle_read_encrypted_message(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) {
206 BOOST_LOG(debug) << "handle_read_encrypted(): Handle read of size: "sv << bytes << " bytes"sv;
207
208 auto sock_close = util::fail_guard([&socket]() {
209 boost::system::error_code ec;
210 socket->sock.close(ec);
211
212 if (ec) {
213 BOOST_LOG(error) << "RTSP: handle_read_encrypted_message(): Couldn't close tcp socket: "sv << ec.message();
214 }
215 });
216
217 auto header = (encrypted_rtsp_header_t *) socket->begin;
218 auto payload_length = header->payload_length();
219 auto seq = util::endian::big<std::uint32_t>(header->sequenceNumber);
220
221 if (ec || bytes < payload_length) {
222 BOOST_LOG(error) << "RTSP: handle_read_encrypted(): Couldn't read from tcp socket: "sv << ec.message();
223
224 respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
225 return;
226 }
227
228 // We use the deterministic IV construction algorithm specified in NIST SP 800-38D
229 // Section 8.2.1. The sequence number is our "invocation" field and the 'RC' in the
230 // high bytes is the "fixed" field. Because each client provides their own unique
231 // key, our values in the fixed field need only uniquely identify each independent
232 // use of the client's key with AES-GCM in our code.
233 //
234 // The sequence number is 32 bits long which allows for 2^32 RTSP messages to be
235 // received from each client before the IV repeats.
236 crypto::aes_t iv(12);
237 std::copy_n((uint8_t *) &seq, sizeof(seq), std::begin(iv));
238 iv[10] = 'C'; // Client originated
239 iv[11] = 'R'; // RTSP
240
241 std::vector<uint8_t> plaintext;
242 if (socket->session->rtsp_cipher->decrypt(std::string_view {(const char *) header->tag, sizeof(header->tag) + bytes}, plaintext, &iv)) {
243 BOOST_LOG(error) << "Failed to verify RTSP message tag"sv;
244
245 respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
246 return;
247 }
248
249 msg_t req {new msg_t::element_type {}};
250 if (auto status = parseRtspMessage(req.get(), (char *) plaintext.data(), plaintext.size())) {
251 BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']';
252
253 respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
254 return;
255 }
256
257 sock_close.disable();
258
259 print_msg(req.get());
260
261 socket->handle_data(std::move(req));
262 }
263
268 if (begin == std::end(msg_buf)) {
269 BOOST_LOG(error) << "RTSP: read_plaintext_payload(): Exceeded maximum rtsp packet size: "sv << msg_buf.size();
270
271 respond(sock, *session, nullptr, 400, "BAD REQUEST", 0, {});
272
273 boost::system::error_code ec;
274 sock.close(ec);
275
276 return;
277 }
278
279 sock.async_read_some(
280 boost::asio::buffer(begin, (std::size_t) (std::end(msg_buf) - begin)),
281 boost::bind(
283 shared_from_this(),
284 boost::asio::placeholders::error,
285 boost::asio::placeholders::bytes_transferred
286 )
287 );
288 }
289
296 static void handle_plaintext_payload(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) {
297 BOOST_LOG(debug) << "handle_plaintext_payload(): Handle read of size: "sv << bytes << " bytes"sv;
298
299 auto sock_close = util::fail_guard([&socket]() {
300 boost::system::error_code ec;
301 socket->sock.close(ec);
302
303 if (ec) {
304 BOOST_LOG(error) << "RTSP: handle_plaintext_payload(): Couldn't close tcp socket: "sv << ec.message();
305 }
306 });
307
308 if (ec) {
309 BOOST_LOG(error) << "RTSP: handle_plaintext_payload(): Couldn't read from tcp socket: "sv << ec.message();
310
311 return;
312 }
313
314 auto end = socket->begin + bytes;
315 msg_t req {new msg_t::element_type {}};
316 if (auto status = parseRtspMessage(req.get(), socket->msg_buf.data(), (std::size_t) (end - socket->msg_buf.data()))) {
317 BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']';
318
319 respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
320 return;
321 }
322
323 sock_close.disable();
324
325 auto fg = util::fail_guard([&socket]() {
326 socket->read_plaintext_payload();
327 });
328
329 auto content_length = 0;
330 for (auto option = req->options; option != nullptr; option = option->next) {
331 if ("Content-length"sv == option->option) {
332 BOOST_LOG(debug) << "Found Content-Length: "sv << option->content << " bytes"sv;
333
334 // If content_length > bytes read, then we need to store current data read,
335 // to be appended by the next read.
336 std::string_view content {option->content};
337 auto begin = std::find_if(std::begin(content), std::end(content), [](auto ch) {
338 return (bool) std::isdigit(ch);
339 });
340
341 content_length = util::from_chars(begin, std::end(content));
342 break;
343 }
344 }
345
346 if (end - socket->crlf >= content_length) {
347 if (end - socket->crlf > content_length) {
348 BOOST_LOG(warning) << "(end - socket->crlf) > content_length -- "sv << (std::size_t) (end - socket->crlf) << " > "sv << content_length;
349 }
350
351 fg.disable();
352 print_msg(req.get());
353
354 socket->handle_data(std::move(req));
355 }
356
357 socket->begin = end;
358 }
359
366 static void handle_read_plaintext(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) {
367 BOOST_LOG(debug) << "handle_read_plaintext(): Handle read of size: "sv << bytes << " bytes"sv;
368
369 if (ec) {
370 BOOST_LOG(error) << "RTSP: handle_read_plaintext(): Couldn't read from tcp socket: "sv << ec.message();
371
372 boost::system::error_code ec;
373 socket->sock.close(ec);
374
375 if (ec) {
376 BOOST_LOG(error) << "RTSP: handle_read_plaintext(): Couldn't close tcp socket: "sv << ec.message();
377 }
378
379 return;
380 }
381
382 auto fg = util::fail_guard([&socket]() {
383 socket->read();
384 });
385
386 auto begin = std::max(socket->begin - 4, socket->begin);
387 auto buf_size = bytes + (begin - socket->begin);
388 auto end = begin + buf_size;
389
390 constexpr auto needle = "\r\n\r\n"sv;
391
392 auto it = std::search(begin, begin + buf_size, std::begin(needle), std::end(needle));
393 if (it == end) {
394 socket->begin = end;
395
396 return;
397 }
398
399 // Emulate read completion for payload data
400 socket->begin = it + needle.size();
401 socket->crlf = socket->begin;
402 buf_size = end - socket->begin;
403
404 fg.disable();
405 handle_plaintext_payload(socket, ec, buf_size);
406 }
407
408 void handle_data(msg_t &&req) {
409 handle_data_fn(sock, *session, std::move(req));
410 }
411
412 std::function<void(tcp::socket &sock, launch_session_t &, msg_t &&)> handle_data_fn;
413
414 tcp::socket sock;
415
416 std::array<char, 2048> msg_buf;
417
418 char *crlf;
419 char *begin = msg_buf.data();
420
421 std::shared_ptr<launch_session_t> session;
422 };
423
425 public:
427 clear();
428 }
429
430 int bind(net::af_e af, std::uint16_t port, boost::system::error_code &ec) {
431 acceptor.open(af == net::IPV4 ? tcp::v4() : tcp::v6(), ec);
432 if (ec) {
433 return -1;
434 }
435
436 acceptor.set_option(boost::asio::socket_base::reuse_address {true});
437
438 acceptor.bind(tcp::endpoint(af == net::IPV4 ? tcp::v4() : tcp::v6(), port), ec);
439 if (ec) {
440 return -1;
441 }
442
443 acceptor.listen(4096, ec);
444 if (ec) {
445 return -1;
446 }
447
448 next_socket = std::make_shared<socket_t>(io_context, [this](tcp::socket &sock, launch_session_t &session, msg_t &&msg) {
449 handle_msg(sock, session, std::move(msg));
450 });
451
452 acceptor.async_accept(next_socket->sock, [this](const auto &ec) {
453 handle_accept(ec);
454 });
455
456 return 0;
457 }
458
459 void handle_msg(tcp::socket &sock, launch_session_t &session, msg_t &&req) {
460 if (session.cancelled.load(std::memory_order_acquire)) {
461 BOOST_LOG(debug) << "Ignoring RTSP request for cancelled launch "
462 << session.id << " from " << session.device_name;
463 boost::system::error_code close_ec;
464 sock.close(close_ec);
465 return;
466 }
467
468 std::string command {req->message.request.command};
469 auto func = _map_cmd_cb.find(command);
470
471 // Nothing sits above these handlers but the accept loop, so an exception
472 // escaping one reaches std::terminate and takes the whole host down
473 // without a line in the log - the peer that vanished between accept() and
474 // remote_endpoint(), a bad_alloc, a parse that threw. A client that dies
475 // mid-handshake should cost that client its session and nothing else.
476 try {
477 if (func != std::end(_map_cmd_cb)) {
478 func->second(this, sock, session, std::move(req));
479 } else {
480 cmd_not_found(sock, session, std::move(req));
481 }
482 } catch (const std::exception &e) {
483 BOOST_LOG(error) << "RTSP ["sv << command << "] from ["sv << session.device_name
484 << "] failed: "sv << e.what();
485 } catch (...) {
486 BOOST_LOG(error) << "RTSP ["sv << command << "] from ["sv << session.device_name
487 << "] failed with an unknown exception"sv;
488 }
489
490 boost::system::error_code ec;
491 sock.shutdown(boost::asio::socket_base::shutdown_type::shutdown_both, ec);
492 }
493
494 void handle_accept(const boost::system::error_code &ec) {
495 if (ec) {
496 BOOST_LOG(error) << "Couldn't accept incoming connections: "sv << ec.message();
497
498 // Stop server
499 clear();
500 return;
501 }
502
503 auto socket = std::move(next_socket);
504
505 auto launch_session {launch_event.view(0s)};
506 if (launch_session) {
507 // Associate the current RTSP session with this socket and start reading
508 socket->session = launch_session;
509 socket->read();
510 } else {
511 // This can happen due to normal things like port scanning, so let's not make these visible by default
512 BOOST_LOG(debug) << "No pending session for incoming RTSP connection"sv;
513
514 // If there is no session pending, close the connection immediately
515 boost::system::error_code ec;
516 socket->sock.close(ec);
517 }
518
519 // Queue another asynchronous accept for the next incoming connection
520 next_socket = std::make_shared<socket_t>(io_context, [this](tcp::socket &sock, launch_session_t &session, msg_t &&msg) {
521 handle_msg(sock, session, std::move(msg));
522 });
523 acceptor.async_accept(next_socket->sock, [this](const auto &ec) {
524 handle_accept(ec);
525 });
526 }
527
528 void map(const std::string_view &type, cmd_func_t cb) {
529 _map_cmd_cb.emplace(type, std::move(cb));
530 }
531
538 bool session_raise(std::shared_ptr<launch_session_t> launch_session) {
539 // If a launch event is still pending, don't overwrite it.
540 if (launch_event.view(0s)) {
541 release_pending_virtual_display(*launch_session);
542 return false;
543 }
544
545 // Raise the new launch session to prepare for the RTSP handshake
546 launch_event.raise(std::move(launch_session));
547
548 // Arm the timer to expire this launch session if the client times out
549 raised_timer.expires_after(config::stream.ping_timeout);
550 raised_timer.async_wait([this](const boost::system::error_code &ec) {
551 if (!ec) {
552 auto discarded = launch_event.pop(0s);
553 if (discarded) {
554 BOOST_LOG(debug) << "Event timeout: "sv << discarded->unique_id;
555 release_pending_virtual_display(*discarded);
556 }
557 }
558 });
559 return true;
560 }
561
566 void session_clear(uint32_t launch_session_id) {
567 // We currently only support a single pending RTSP session,
568 // so the ID should always match the one for that session.
569 auto launch_session = launch_event.view(0s);
570 if (launch_session) {
571 if (launch_session->id != launch_session_id) {
572 BOOST_LOG(error) << "Attempted to clear unexpected session: "sv << launch_session_id << " vs "sv << launch_session->id;
573 } else {
574 raised_timer.cancel();
575 auto cleared = launch_event.pop();
576 if (cleared) {
577 release_pending_virtual_display(*cleared);
578 }
579 }
580 }
581 }
582
583 bool cancel_pending_launch(const std::string_view &uuid) {
584 auto launch_session = launch_event.view(0s);
585 if (!launch_session || launch_session->unique_id != uuid) {
586 return false;
587 }
588
589 {
590 // cmd_announce holds this from its final cancellation check through
591 // insertion/start. If it won the race, the HTTPS caller subsequently
592 // finds and terminates the newly active session.
593 std::lock_guard<std::mutex> lifecycle_lock {
594 launch_session->lifecycle_mutex
595 };
596 launch_session->cancelled.store(true, std::memory_order_release);
597 }
598 session_clear(launch_session->id);
599 return true;
600 }
601
607 auto lg = _session_slots.lock();
608 return _session_slots->size();
609 }
610
611 int shared_session_count() {
612 auto lg = _session_slots.lock();
613 int count = 0;
614 for (const auto &slot : *_session_slots) {
615 if (slot && !stream::session::isolated(*slot)) {
616 ++count;
617 }
618 }
619 return count;
620 }
621
622 safe::event_t<std::shared_ptr<launch_session_t>> launch_event;
623
631 void clear(bool all = true) {
632 auto lg = _session_slots.lock();
633
634 for (auto i = _session_slots->begin(); i != _session_slots->end();) {
635 auto &slot = *(*i);
636 if (all || stream::session::state(slot) == stream::session::state_e::STOPPING) {
638 stream::session::join(slot);
639
640 i = _session_slots->erase(i);
641 } else {
642 i++;
643 }
644 }
645 }
646
651 void remove(const std::shared_ptr<stream::session_t> &session) {
652 auto lg = _session_slots.lock();
653 _session_slots->erase(session);
654 }
655
660 void insert(const std::shared_ptr<stream::session_t> &session) {
661 auto lg = _session_slots.lock();
662 const bool first = _session_slots->empty();
663 _session_slots->emplace(session);
664 if (first) {
665 // Start pipeline metrics fresh for a new streaming session.
667 }
668 BOOST_LOG(info) << "New streaming session started [active sessions: "sv << _session_slots->size() << ']';
669 }
670
674 void iterate() {
675 // If we have a session, we will return to the server loop every
676 // 500ms to allow session cleanup to happen.
677 if (session_count() > 0) {
678 io_context.run_one_for(500ms);
679 } else {
680 io_context.run_one();
681 }
682 }
683
687 void stop() {
688 acceptor.close();
689 io_context.stop();
690 clear();
691 }
692
693 std::shared_ptr<stream::session_t>
694 find_session(const std::string_view& uuid) {
695 auto lg = _session_slots.lock();
696
697 for (auto &slot : *_session_slots) {
698 if (slot && stream::session::uuid_match(*slot, uuid)) {
699 return slot;
700 }
701 }
702
703 return nullptr;
704 }
705
706 std::list<std::string>
707 get_all_session_uuids() {
708 std::list<std::string> uuids;
709 auto lg = _session_slots.lock();
710 for (auto &slot : *_session_slots) {
711 if (slot) {
712 uuids.push_back(stream::session::uuid(*slot));
713 }
714 }
715 return uuids;
716 }
717
718 bool terminate_session(const std::string_view &uuid) {
719 auto lg = _session_slots.lock();
720 for (auto it = _session_slots->begin(); it != _session_slots->end(); ++it) {
721 const auto &slot = *it;
722 if (!slot || !stream::session::uuid_match(*slot, uuid)) {
723 continue;
724 }
725 stream::session::stop(*slot, stream::session::termination_reason_e::SERVER_STOPPED);
726 stream::session::join(*slot);
727 _session_slots->erase(it);
728 return true;
729 }
730 return false;
731 }
732
733 void terminate_shared_sessions() {
734 auto lg = _session_slots.lock();
735 for (auto it = _session_slots->begin(); it != _session_slots->end();) {
736 const auto &slot = *it;
737 if (!slot || stream::session::isolated(*slot)) {
738 ++it;
739 continue;
740 }
741 stream::session::stop(*slot, stream::session::termination_reason_e::SERVER_STOPPED);
742 stream::session::join(*slot);
743 it = _session_slots->erase(it);
744 }
745 }
746
747 private:
748 std::unordered_map<std::string_view, cmd_func_t> _map_cmd_cb;
749
750 sync_util::sync_t<std::set<std::shared_ptr<stream::session_t>>> _session_slots;
751
752 boost::asio::io_context io_context;
753 tcp::acceptor acceptor {io_context};
754 boost::asio::steady_timer raised_timer {io_context};
755
756 std::shared_ptr<socket_t> next_socket;
757 };
758
759 rtsp_server_t server {};
760
761 bool launch_session_raise(std::shared_ptr<launch_session_t> launch_session) {
762 return server.session_raise(std::move(launch_session));
763 }
764
765 void launch_session_clear(uint32_t launch_session_id) {
766 server.session_clear(launch_session_id);
767 }
768
769 bool cancel_pending_launch(const std::string_view &uuid) {
770 return server.cancel_pending_launch(uuid);
771 }
772
774 // Ensure session_count is up-to-date
775 server.clear(false);
776
777 return server.session_count();
778 }
779
780 int shared_session_count() {
781 server.clear(false);
782 return server.shared_session_count();
783 }
784
785 std::string_view last_termination_reason() {
786 return stream::session::termination_reason_str(stream::session::last_termination_reason());
787 }
788
789 std::shared_ptr<stream::session_t> find_session(const std::string_view& uuid) {
790 return server.find_session(uuid);
791 }
792
793 std::optional<bool> session_is_isolated(const std::string_view &uuid) {
794 const auto session = server.find_session(uuid);
795 if (!session) {
796 return std::nullopt;
797 }
798 return stream::session::isolated(*session);
799 }
800
801 std::list<std::string> get_all_session_uuids() {
802 return server.get_all_session_uuids();
803 }
804
805 bool terminate_session(const std::string_view &uuid) {
806 return server.terminate_session(uuid);
807 }
808
810 server.terminate_shared_sessions();
811 }
812
814 server.clear(true);
815 }
816
817 int send(tcp::socket &sock, const std::string_view &sv) {
818 std::size_t bytes_send = 0;
819
820 while (bytes_send != sv.size()) {
821 boost::system::error_code ec;
822 bytes_send += sock.send(boost::asio::buffer(sv.substr(bytes_send)), 0, ec);
823
824 if (ec) {
825 BOOST_LOG(error) << "RTSP: Couldn't send data over tcp socket: "sv << ec.message();
826 return -1;
827 }
828 }
829
830 return 0;
831 }
832
833 void respond(tcp::socket &sock, launch_session_t &session, msg_t &resp) {
834 auto payload = std::make_pair(resp->payload, resp->payloadLength);
835
836 // Restore response message for proper destruction
837 auto lg = util::fail_guard([&]() {
838 resp->payload = payload.first;
839 resp->payloadLength = payload.second;
840 });
841
842 resp->payload = nullptr;
843 resp->payloadLength = 0;
844
845 int serialized_len;
846 util::c_ptr<char> raw_resp {serializeRtspMessage(resp.get(), &serialized_len)};
847 BOOST_LOG(debug)
848 << "---Begin Response---"sv << std::endl
849 << std::string_view {raw_resp.get(), (std::size_t) serialized_len} << std::endl
850 << std::string_view {payload.first, (std::size_t) payload.second} << std::endl
851 << "---End Response---"sv << std::endl;
852
853 // Encrypt the RTSP message if encryption is enabled
854 if (session.rtsp_cipher) {
855 // We use the deterministic IV construction algorithm specified in NIST SP 800-38D
856 // Section 8.2.1. The sequence number is our "invocation" field and the 'RH' in the
857 // high bytes is the "fixed" field. Because each client provides their own unique
858 // key, our values in the fixed field need only uniquely identify each independent
859 // use of the client's key with AES-GCM in our code.
860 //
861 // The sequence number is 32 bits long which allows for 2^32 RTSP messages to be
862 // sent to each client before the IV repeats.
863 crypto::aes_t iv(12);
864 session.rtsp_iv_counter++;
865 std::copy_n((uint8_t *) &session.rtsp_iv_counter, sizeof(session.rtsp_iv_counter), std::begin(iv));
866 iv[10] = 'H'; // Host originated
867 iv[11] = 'R'; // RTSP
868
869 // Allocate the message with an empty header and reserved space for the payload
870 auto payload_length = serialized_len + payload.second;
871 std::vector<uint8_t> message(sizeof(encrypted_rtsp_header_t));
872 message.reserve(message.size() + payload_length);
873
874 // Copy the complete plaintext into the message
875 std::copy_n(raw_resp.get(), serialized_len, std::back_inserter(message));
876 std::copy_n(payload.first, payload.second, std::back_inserter(message));
877
878 // Initialize the message header
879 auto header = (encrypted_rtsp_header_t *) message.data();
880 header->typeAndLength = util::endian::big<std::uint32_t>(encrypted_rtsp_header_t::ENCRYPTED_MESSAGE_TYPE_BIT + payload_length);
881 header->sequenceNumber = util::endian::big<std::uint32_t>(session.rtsp_iv_counter);
882
883 // Encrypt the RTSP message in place
884 session.rtsp_cipher->encrypt(std::string_view {(const char *) header->payload(), (std::size_t) payload_length}, header->tag, &iv);
885
886 // Send the full encrypted message
887 send(sock, std::string_view {(char *) message.data(), message.size()});
888 } else {
889 std::string_view tmp_resp {raw_resp.get(), (size_t) serialized_len};
890
891 // Send the plaintext RTSP message header
892 if (send(sock, tmp_resp)) {
893 return;
894 }
895
896 // Send the plaintext RTSP message payload (if present)
897 send(sock, std::string_view {payload.first, (std::size_t) payload.second});
898 }
899 }
900
901 void respond(tcp::socket &sock, launch_session_t &session, POPTION_ITEM options, int statuscode, const char *status_msg, int seqn, const std::string_view &payload) {
902 msg_t resp {new msg_t::element_type};
903 createRtspResponse(resp.get(), nullptr, 0, const_cast<char *>("RTSP/1.0"), statuscode, const_cast<char *>(status_msg), seqn, options, const_cast<char *>(payload.data()), (int) payload.size());
904
905 respond(sock, session, resp);
906 }
907
908 void cmd_not_found(tcp::socket &sock, launch_session_t &session, msg_t &&req) {
909 respond(sock, session, nullptr, 404, "NOT FOUND", req->sequenceNumber, {});
910 }
911
912 void cmd_option(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
913 OPTION_ITEM option {};
914
915 // I know these string literals will not be modified
916 option.option = const_cast<char *>("CSeq");
917
918 auto seqn_str = std::to_string(req->sequenceNumber);
919 option.content = const_cast<char *>(seqn_str.c_str());
920
921 respond(sock, session, &option, 200, "OK", req->sequenceNumber, {});
922 }
923
924 std::string surround_params(int config) {
925 const auto &stream_config = audio::stream_configs[config];
926 std::uint8_t mapping[platf::speaker::MAX_SPEAKERS];
927 std::copy_n(stream_config.mapping, stream_config.channelCount, mapping);
928
935 if (config == audio::SURROUND51 || config == audio::SURROUND71) {
936 std::rotate(mapping + 3, mapping + 4, mapping + stream_config.channelCount);
937 }
938
939 std::string params = std::to_string(stream_config.channelCount) + std::to_string(stream_config.streams) + std::to_string(stream_config.coupledStreams);
940 std::for_each_n(mapping, stream_config.channelCount, [&params](std::uint8_t digit) {
941 params += static_cast<char>(digit + '0');
942 });
943 return params;
944 }
945
946 void cmd_describe(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
947 OPTION_ITEM option {};
948
949 // I know these string literals will not be modified
950 option.option = const_cast<char *>("CSeq");
951
952 auto seqn_str = std::to_string(req->sequenceNumber);
953 option.content = const_cast<char *>(seqn_str.c_str());
954
955 std::stringstream ss;
956
957 // Tell the client about our supported features
958 ss << "a=x-ss-general.featureFlags:" << (uint32_t) platf::get_capabilities() << std::endl;
959
960 // Always request new control stream encryption if the client supports it
961 uint32_t encryption_flags_supported = SS_ENC_CONTROL_V2 | SS_ENC_AUDIO;
962 uint32_t encryption_flags_requested = SS_ENC_CONTROL_V2;
963
964 // A client microphone is offered where a session mic exists, and always
965 // encrypted: it is heard by the session's applications.
966 const bool mic = !proc::proc.isolated_mic_source(
967 session.isolated_runtime_owner_id ? session.isolated_runtime_owner_id : session.id
968 ).empty();
969 if (mic) {
970 encryption_flags_supported |= SS_ENC_MICROPHONE;
971 encryption_flags_requested |= SS_ENC_MICROPHONE;
972 }
973
974 // Determine the encryption desired for this remote endpoint
975 auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address());
976 if (encryption_mode != config::ENCRYPTION_MODE_NEVER) {
977 // Advertise support for video encryption if it's not disabled
978 encryption_flags_supported |= SS_ENC_VIDEO;
979
980 // If it's mandatory, also request it to enable use if the client
981 // didn't explicitly opt in, but it otherwise has support.
982 if (encryption_mode == config::ENCRYPTION_MODE_MANDATORY) {
983 encryption_flags_requested |= SS_ENC_VIDEO | SS_ENC_AUDIO;
984 }
985 }
986
987 // Report supported and required encryption flags
988 ss << "a=x-ss-general.encryptionSupported:" << encryption_flags_supported << std::endl;
989 ss << "a=x-ss-general.encryptionRequested:" << encryption_flags_requested << std::endl;
990
991 if (video::last_encoder_probe_supported_ref_frames_invalidation) {
992 ss << "a=x-nv-video[0].refPicInvalidation:1"sv << std::endl;
993 }
994
995 if (video::active_hevc_mode != 1) {
996 ss << "sprop-parameter-sets=AAAAAU"sv << std::endl;
997 }
998
999 if (video::active_av1_mode != 1) {
1000 ss << "a=rtpmap:98 AV1/90000"sv << std::endl;
1001 }
1002
1003 if (config::video.pyrowave && video::pyrowave_available()) {
1004 ss << "a=rtpmap:98 PYROWAVE/90000"sv << std::endl;
1005 }
1006
1007 if (!session.surround_params.empty()) {
1008 // If we have our own surround parameters, advertise them twice first
1009 ss << "a=fmtp:97 surround-params="sv << session.surround_params << std::endl;
1010 ss << "a=fmtp:97 surround-params="sv << session.surround_params << std::endl;
1011 }
1012
1013 if (mic) {
1014 ss << "m=audio "sv << net::map_port(stream::MIC_STREAM_PORT) << " RTP/AVP 96"sv << std::endl;
1015 ss << "a=rtpmap:96 opus/48000/1"sv << std::endl;
1016 ss << "a=fmtp:96 minptime=10;useinbandfec=1"sv << std::endl;
1017 }
1018
1019 for (int x = 0; x < audio::MAX_STREAM_CONFIG; ++x) {
1020 ss << "a=fmtp:97 surround-params="sv << surround_params(x) << std::endl;
1021 }
1022
1023 respond(sock, session, &option, 200, "OK", req->sequenceNumber, ss.str());
1024 }
1025
1026 void cmd_setup(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
1027 OPTION_ITEM options[4] {};
1028
1029 auto &seqn = options[0];
1030 auto &session_option = options[1];
1031 auto &port_option = options[2];
1032 auto &payload_option = options[3];
1033
1034 seqn.option = const_cast<char *>("CSeq");
1035
1036 auto seqn_str = std::to_string(req->sequenceNumber);
1037 seqn.content = const_cast<char *>(seqn_str.c_str());
1038
1039 std::string_view target {req->message.request.target};
1040 auto begin = std::find(std::begin(target), std::end(target), '=') + 1;
1041 auto end = std::find(begin, std::end(target), '/');
1042 std::string_view type {begin, (size_t) std::distance(begin, end)};
1043
1044 std::uint16_t port;
1045 if (type == "audio"sv) {
1046 port = net::map_port(stream::AUDIO_STREAM_PORT);
1047 } else if (type == "video"sv) {
1048 port = net::map_port(stream::VIDEO_STREAM_PORT);
1049 } else if (type == "control"sv) {
1050 port = net::map_port(stream::CONTROL_PORT);
1051 } else if (type == "mic"sv && config::audio.stream_mic) {
1052 port = net::map_port(stream::MIC_STREAM_PORT);
1053 session.enable_mic = true;
1054 } else {
1055 cmd_not_found(sock, session, std::move(req));
1056
1057 return;
1058 }
1059
1060 seqn.next = &session_option;
1061
1062 session_option.option = const_cast<char *>("Session");
1063 session_option.content = const_cast<char *>("DEADBEEFCAFE;timeout = 90");
1064
1065 session_option.next = &port_option;
1066
1067 // Moonlight merely requires 'server_port=<port>'
1068 auto port_value = std::format("server_port={}", static_cast<int>(port));
1069
1070 port_option.option = const_cast<char *>("Transport");
1071 port_option.content = port_value.data();
1072
1073 // Send identifiers that will be echoed in the other connections
1074 auto connect_data = std::to_string(session.control_connect_data);
1075 if (type == "control"sv) {
1076 payload_option.option = const_cast<char *>("X-SS-Connect-Data");
1077 payload_option.content = connect_data.data();
1078 } else {
1079 payload_option.option = const_cast<char *>("X-SS-Ping-Payload");
1080 payload_option.content = session.av_ping_payload.data();
1081 }
1082
1083 port_option.next = &payload_option;
1084
1085 respond(sock, session, &seqn, 200, "OK", req->sequenceNumber, {});
1086 }
1087
1088 void cmd_announce(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
1089 OPTION_ITEM option {};
1090
1091 // I know these string literals will not be modified
1092 option.option = const_cast<char *>("CSeq");
1093
1094 auto seqn_str = std::to_string(req->sequenceNumber);
1095 option.content = const_cast<char *>(seqn_str.c_str());
1096
1097 std::string_view payload {req->payload, (size_t) req->payloadLength};
1098
1099 std::vector<std::string_view> lines;
1100
1101 auto whitespace = [](char ch) {
1102 return ch == '\n' || ch == '\r';
1103 };
1104
1105 {
1106 auto pos = std::begin(payload);
1107 auto begin = pos;
1108 while (pos != std::end(payload)) {
1109 if (whitespace(*pos++)) {
1110 lines.emplace_back(begin, pos - begin - 1);
1111
1112 while (pos != std::end(payload) && whitespace(*pos)) {
1113 ++pos;
1114 }
1115 begin = pos;
1116 }
1117 }
1118 }
1119
1120 std::string_view client;
1121 std::unordered_map<std::string_view, std::string_view> args;
1122
1123 for (auto line : lines) {
1124 auto type = line.substr(0, 2);
1125 if (type == "s="sv) {
1126 client = line.substr(2);
1127 } else if (type == "a=") {
1128 auto pos = line.find(':');
1129
1130 auto name = line.substr(2, pos - 2);
1131 auto val = line.substr(pos + 1);
1132
1133 if (val[val.size() - 1] == ' ') {
1134 val = val.substr(0, val.size() - 1);
1135 }
1136 args.emplace(name, val);
1137 }
1138 }
1139
1140 // Initialize any omitted parameters to defaults
1141 args.try_emplace("x-nv-video[0].encoderCscMode"sv, "0"sv);
1142 args.try_emplace("x-nv-vqos[0].bitStreamFormat"sv, "0"sv);
1143 args.try_emplace("x-nv-video[0].dynamicRangeMode"sv, "0"sv);
1144 args.try_emplace("x-nv-aqos.packetDuration"sv, "5"sv);
1145 args.try_emplace("x-nv-general.useReliableUdp"sv, "1"sv);
1146 args.try_emplace("x-nv-vqos[0].fec.minRequiredFecPackets"sv, "0"sv);
1147 args.try_emplace("x-nv-general.featureFlags"sv, "135"sv);
1148 args.try_emplace("x-ml-general.featureFlags"sv, "0"sv);
1149 args.try_emplace("x-nv-vqos[0].qosTrafficType"sv, "5"sv);
1150 args.try_emplace("x-nv-aqos.qosTrafficType"sv, "4"sv);
1151 args.try_emplace("x-ml-video.configuredBitrateKbps"sv, "0"sv);
1152 args.try_emplace("x-ss-general.encryptionEnabled"sv, "0"sv);
1153 args.try_emplace("x-ss-video[0].chromaSamplingType"sv, "0"sv);
1154 args.try_emplace("x-ss-video[0].intraRefresh"sv, "0"sv);
1155
1156 stream::config_t config;
1157
1158 std::int64_t configuredBitrateKbps;
1159 config.audio.flags[audio::config_t::HOST_AUDIO] = session.host_audio;
1160 // An isolated session records the sink that was made for it at launch,
1161 // rather than whichever one the machine currently defaults to. Empty for
1162 // every session that shares the host's desktop, which leaves their capture
1163 // exactly as it was.
1164 //
1165 // The runtime registry is keyed by the launch that started the session.
1166 // A resumed stream arrives with a launch id of its own, so asking by
1167 // session.id finds nothing, the sink comes back empty, and capture falls
1168 // through to the host path - which moves the host's default sink onto the
1169 // stream's virtual sink and takes the desktop's audio with it.
1170 config.audio.session_sink = proc::proc.isolated_audio_sink(
1171 session.isolated_runtime_owner_id ? session.isolated_runtime_owner_id : session.id
1172 );
1173 config.audio.session_server = proc::proc.isolated_audio_server(
1174 session.isolated_runtime_owner_id ? session.isolated_runtime_owner_id : session.id
1175 );
1176 try {
1177 config.audio.channels = util::from_view(args.at("x-nv-audio.surround.numChannels"sv));
1178 config.audio.mask = util::from_view(args.at("x-nv-audio.surround.channelMask"sv));
1179 config.audio.packetDuration = util::from_view(args.at("x-nv-aqos.packetDuration"sv));
1180
1181 config.audio.flags[audio::config_t::HIGH_QUALITY] =
1182 util::from_view(args.at("x-nv-audio.surround.AudioQuality"sv));
1183
1184 config.controlProtocolType = util::from_view(args.at("x-nv-general.useReliableUdp"sv));
1185 config.packetsize = util::from_view(args.at("x-nv-video[0].packetSize"sv));
1186 config.minRequiredFecPackets = util::from_view(args.at("x-nv-vqos[0].fec.minRequiredFecPackets"sv));
1187 config.mlFeatureFlags = util::from_view(args.at("x-ml-general.featureFlags"sv));
1188 config.audioQosType = util::from_view(args.at("x-nv-aqos.qosTrafficType"sv));
1189 config.videoQosType = util::from_view(args.at("x-nv-vqos[0].qosTrafficType"sv));
1190 config.encryptionFlagsEnabled = util::from_view(args.at("x-ss-general.encryptionEnabled"sv));
1191
1192 // Legacy clients use nvFeatureFlags to indicate support for audio encryption
1193 if (util::from_view(args.at("x-nv-general.featureFlags"sv)) & 0x20) {
1194 config.encryptionFlagsEnabled |= SS_ENC_AUDIO;
1195 }
1196
1197 config.monitor.height = util::from_view(args.at("x-nv-video[0].clientViewportHt"sv));
1198 config.monitor.width = util::from_view(args.at("x-nv-video[0].clientViewportWd"sv));
1199 config.monitor.framerate = util::from_view(args.at("x-nv-video[0].maxFPS"sv));
1200 config.monitor.bitrate = util::from_view(args.at("x-nv-vqos[0].bw.maximumBitrateKbps"sv));
1201 config.monitor.slicesPerFrame = util::from_view(args.at("x-nv-video[0].videoEncoderSlicesPerFrame"sv));
1202 config.monitor.numRefFrames = util::from_view(args.at("x-nv-video[0].maxNumReferenceFrames"sv));
1203 config.monitor.encoderCscMode = util::from_view(args.at("x-nv-video[0].encoderCscMode"sv));
1204 config.monitor.videoFormat = util::from_view(args.at("x-nv-vqos[0].bitStreamFormat"sv));
1205 config.monitor.dynamicRange = util::from_view(args.at("x-nv-video[0].dynamicRangeMode"sv));
1206 config.monitor.chromaSamplingType = util::from_view(args.at("x-ss-video[0].chromaSamplingType"sv));
1207 config.monitor.enableIntraRefresh = util::from_view(args.at("x-ss-video[0].intraRefresh"sv));
1208
1209 if (config::video.limit_framerate) {
1210 config.monitor.encodingFramerate = session.fps;
1211 } else {
1212 if (config.monitor.framerate > 1000) {
1213 config.monitor.encodingFramerate = config.monitor.framerate;
1214 } else {
1215 config.monitor.encodingFramerate = config.monitor.framerate * 1000;
1216 }
1217 }
1218
1219 // When fractional refresh rate requested from client side, it should be well above 1000fps
1220 // 4000fps is when Warp2 Mode is enabled on the client, requested framerate can be actual * 4
1221 if (config.monitor.framerate > 4000) {
1222 config.monitor.framerate = std::round((float)config.monitor.framerate / 1000);
1223 }
1224
1225 config.monitor.input_only = session.input_only;
1226
1227 configuredBitrateKbps = util::from_view(args.at("x-ml-video.configuredBitrateKbps"sv));
1228
1229 if (!configuredBitrateKbps) {
1230 configuredBitrateKbps = config.monitor.bitrate;
1231 }
1232
1233 BOOST_LOG(info) << "Client Requested bitrate is [" << configuredBitrateKbps << "kbps]";
1234
1235 if (config::video.max_bitrate > 0) {
1236 if (config::video.max_bitrate < configuredBitrateKbps) {
1237 configuredBitrateKbps = config::video.max_bitrate;
1238 }
1239 }
1240
1241 BOOST_LOG(info) << "Host Streaming bitrate is [" << configuredBitrateKbps << "kbps]";
1242
1243 // Hack: Restore bitrate for warp mode
1244 size_t warp_factor = std::round((float)config.monitor.framerate * 1000 / session.fps);
1245 if (config::video.limit_framerate && warp_factor >= 2) {
1246 configuredBitrateKbps *= warp_factor;
1247 BOOST_LOG(info) << "Warp factor [" << warp_factor << "] engaged";
1248 }
1249
1250 } catch (std::out_of_range &) {
1251 respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
1252 return;
1253 }
1254
1255 // When using stereo audio, the audio quality is (strangely) indicated by whether the Host field
1256 // in the RTSP message matches a local interface's IP address. Fortunately, Moonlight always sends
1257 // 0.0.0.0 when it wants low quality, so it is easy to check without enumerating interfaces.
1258 if (config.audio.channels == 2) {
1259 for (auto option = req->options; option != nullptr; option = option->next) {
1260 if ("Host"sv == option->option) {
1261 std::string_view content {option->content};
1262 BOOST_LOG(debug) << "Found Host: "sv << content;
1263 config.audio.flags[audio::config_t::HIGH_QUALITY] = (content.find("0.0.0.0"sv) == std::string::npos);
1264 }
1265 }
1266 } else if (session.surround_params.length() > 3) {
1267 // Channels
1268 std::uint8_t c = session.surround_params[0] - '0';
1269 // Streams
1270 std::uint8_t n = session.surround_params[1] - '0';
1271 // Coupled streams
1272 std::uint8_t m = session.surround_params[2] - '0';
1273 auto valid = false;
1274 if ((c == 6 || c == 8) && c == config.audio.channels && n + m == c && session.surround_params.length() == c + 3) {
1275 config.audio.customStreamParams.channelCount = c;
1276 config.audio.customStreamParams.streams = n;
1277 config.audio.customStreamParams.coupledStreams = m;
1278 valid = true;
1279 for (std::uint8_t i = 0; i < c; i++) {
1280 config.audio.customStreamParams.mapping[i] = session.surround_params[i + 3] - '0';
1281 if (config.audio.customStreamParams.mapping[i] >= c) {
1282 valid = false;
1283 break;
1284 }
1285 }
1286 }
1287 config.audio.flags[audio::config_t::CUSTOM_SURROUND_PARAMS] = valid;
1288 }
1289
1290 config.audio.input_only = session.input_only;
1291
1292 // If the client sent a configured bitrate, we will choose the actual bitrate ourselves
1293 // by using FEC percentage and audio quality settings. If the calculated bitrate ends up
1294 // too low, we'll allow it to exceed the limits rather than reducing the encoding bitrate
1295 // down to nearly nothing.
1296 if (configuredBitrateKbps) {
1297 BOOST_LOG(debug) << "Client configured bitrate is "sv << configuredBitrateKbps << " Kbps"sv;
1298
1299 // If the FEC percentage isn't too high, adjust the configured bitrate to ensure video
1300 // traffic doesn't exceed the user's selected bitrate when the FEC shards are included.
1301 if (config::stream.fec_percentage <= 80) {
1302 configuredBitrateKbps /= 100.f / (100 - config::stream.fec_percentage);
1303 }
1304
1305 // Adjust the bitrate to account for audio traffic bandwidth usage (capped at 20% reduction).
1306 // The bitrate per channel is 256 Kbps for high quality mode and 96 Kbps for normal quality.
1307 auto audioBitrateAdjustment = (config.audio.flags[audio::config_t::HIGH_QUALITY] ? 256 : 96) * config.audio.channels;
1308 configuredBitrateKbps -= std::min((std::int64_t) audioBitrateAdjustment, configuredBitrateKbps / 5);
1309
1310 // Reduce it by another 500Kbps to account for A/V packet overhead and control data
1311 // traffic (capped at 10% reduction).
1312 configuredBitrateKbps -= std::min((std::int64_t) 500, configuredBitrateKbps / 10);
1313
1314 BOOST_LOG(debug) << "Final adjusted video encoding bitrate is "sv << configuredBitrateKbps << " Kbps"sv;
1315 config.monitor.bitrate = configuredBitrateKbps;
1316 }
1317
1318 if (config.monitor.videoFormat == 1 && video::active_hevc_mode == 1) {
1319 BOOST_LOG(warning) << "HEVC is disabled, yet the client requested HEVC"sv;
1320
1321 respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
1322 return;
1323 }
1324
1325 if (config.monitor.videoFormat == 2 && video::active_av1_mode == 1) {
1326 BOOST_LOG(warning) << "AV1 is disabled, yet the client requested AV1"sv;
1327
1328 respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
1329 return;
1330 }
1331
1332 if (config.monitor.videoFormat == video::PYROWAVE_VIDEO_FORMAT &&
1333 (!config::video.pyrowave || !video::pyrowave_available())) {
1334 BOOST_LOG(warning) << "PyroWave is unavailable, yet the client requested PyroWave"sv;
1335
1336 respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
1337 return;
1338 }
1339
1340 if (config.monitor.videoFormat == video::PYROWAVE_VIDEO_FORMAT &&
1341 (config.monitor.dynamicRange != 0 || config.monitor.chromaSamplingType != 0)) {
1342 BOOST_LOG(warning) << "PyroWave currently supports only 8-bit YUV 4:2:0 streams"sv;
1343
1344 respond(sock, session, &option, 400, "BAD REQUEST", req->sequenceNumber, {});
1345 return;
1346 }
1347
1348 // Check that any required encryption is enabled
1349 auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address());
1350 if (encryption_mode == config::ENCRYPTION_MODE_MANDATORY &&
1351 (config.encryptionFlagsEnabled & (SS_ENC_VIDEO | SS_ENC_AUDIO)) != (SS_ENC_VIDEO | SS_ENC_AUDIO)) {
1352 BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv;
1353
1354 respond(sock, session, &option, 403, "Forbidden", req->sequenceNumber, {});
1355 return;
1356 }
1357
1358 if (session.enable_mic) {
1359 if (config.encryptionFlagsEnabled & SS_ENC_MICROPHONE) {
1360 config.mic_source = proc::proc.isolated_mic_source(
1361 session.isolated_runtime_owner_id ? session.isolated_runtime_owner_id : session.id
1362 );
1363 } else {
1364 BOOST_LOG(warning) << "Ignoring the microphone of ["sv << session.device_name << "]: it is not encrypted"sv;
1365 }
1366 }
1367
1368 std::lock_guard<std::mutex> lifecycle_lock {session.lifecycle_mutex};
1369 if (session.cancelled.load(std::memory_order_acquire)) {
1370 BOOST_LOG(info) << "Rejecting RTSP ANNOUNCE for cancelled launch "
1371 << session.id << " from " << session.device_name;
1372 respond(sock, session, &option, 410, "Gone", req->sequenceNumber, {});
1373 return;
1374 }
1375
1376 config.gcmap = session.gcmap;
1377 // A desktop on a helper account plays into that account's own audio
1378 // server, so it never has a sink here; only a same-user desktop must.
1379 const auto runtime_owner = session.isolated_runtime_owner_id ? session.isolated_runtime_owner_id : session.id;
1380 if (session.isolated_session && session.isolated_session_profile == "desktop" &&
1381 config.audio.session_sink.empty() && !proc::proc.isolated_session_has_account(runtime_owner)) {
1382 BOOST_LOG(error) << "[IsolatedSession] The detached desktop has no private audio sink; "
1383 "refusing to capture host audio.";
1384 respond(sock, session, &option, 503, "Service Unavailable", req->sequenceNumber, {});
1385 return;
1386 }
1387
1388 auto stream_session = stream::session::alloc(config, session);
1389 server->insert(stream_session);
1390 if (stream::session::start(*stream_session, sock.remote_endpoint().address().to_string())) {
1391 BOOST_LOG(error) << "Failed to start a streaming session"sv;
1392
1393 server->remove(stream_session);
1394 respond(sock, session, &option, 500, "Internal Server Error", req->sequenceNumber, {});
1395 return;
1396 }
1397
1398 respond(sock, session, &option, 200, "OK", req->sequenceNumber, {});
1399 }
1400
1401 void cmd_play(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
1402 OPTION_ITEM option {};
1403
1404 // I know these string literals will not be modified
1405 option.option = const_cast<char *>("CSeq");
1406
1407 auto seqn_str = std::to_string(req->sequenceNumber);
1408 option.content = const_cast<char *>(seqn_str.c_str());
1409
1410 respond(sock, session, &option, 200, "OK", req->sequenceNumber, {});
1411 }
1412
1413 void start() {
1414 auto shutdown_event = mail::man->event<bool>(mail::shutdown);
1415
1416 server.map("OPTIONS"sv, &cmd_option);
1417 server.map("DESCRIBE"sv, &cmd_describe);
1418 server.map("SETUP"sv, &cmd_setup);
1419 server.map("ANNOUNCE"sv, &cmd_announce);
1420 server.map("PLAY"sv, &cmd_play);
1421
1422 boost::system::error_code ec;
1423 if (server.bind(net::af_from_enum_string(config::sunshine.address_family), net::map_port(rtsp_stream::RTSP_SETUP_PORT), ec)) {
1424 BOOST_LOG(fatal) << "Couldn't bind RTSP server to port ["sv << net::map_port(rtsp_stream::RTSP_SETUP_PORT) << "], " << ec.message();
1425 shutdown_event->raise(true);
1426
1427 return;
1428 }
1429
1430 std::thread rtsp_thread {[&shutdown_event] {
1431 auto broadcast_shutdown_event = mail::man->event<bool>(mail::broadcast_shutdown);
1432
1433 while (!shutdown_event->peek()) {
1434 server.iterate();
1435
1436 if (broadcast_shutdown_event->peek()) {
1437 server.clear();
1438 } else {
1439 // cleanup all stopped sessions
1440 server.clear(false);
1441 }
1442 }
1443
1444 server.clear();
1445 }};
1446
1447 // Wait for shutdown
1448 shutdown_event->view();
1449
1450 // Stop the server and join the server thread
1451 server.stop();
1452 rtsp_thread.join();
1453 }
1454
1455 void print_msg(PRTSP_MESSAGE msg) {
1456 std::string_view type = msg->type == TYPE_RESPONSE ? "RESPONSE"sv : "REQUEST"sv;
1457
1458 std::string_view payload {msg->payload, (size_t) msg->payloadLength};
1459 std::string_view protocol {msg->protocol};
1460 auto seqnm = msg->sequenceNumber;
1461 std::string_view messageBuffer {msg->messageBuffer};
1462
1463 BOOST_LOG(debug) << "type ["sv << type << ']';
1464 BOOST_LOG(debug) << "sequence number ["sv << seqnm << ']';
1465 BOOST_LOG(debug) << "protocol :: "sv << protocol;
1466 BOOST_LOG(debug) << "payload :: "sv << payload;
1467
1468 if (msg->type == TYPE_RESPONSE) {
1469 auto &resp = msg->message.response;
1470
1471 auto statuscode = resp.statusCode;
1472 std::string_view status {resp.statusString};
1473
1474 BOOST_LOG(debug) << "statuscode :: "sv << statuscode;
1475 BOOST_LOG(debug) << "status :: "sv << status;
1476 } else {
1477 auto &req = msg->message.request;
1478
1479 std::string_view command {req.command};
1480 std::string_view target {req.target};
1481
1482 BOOST_LOG(debug) << "command :: "sv << command;
1483 BOOST_LOG(debug) << "target :: "sv << target;
1484 }
1485
1486 for (auto option = msg->options; option != nullptr; option = option->next) {
1487 std::string_view content {option->content};
1488 std::string_view name {option->option};
1489
1490 BOOST_LOG(debug) << name << " :: "sv << content;
1491 }
1492
1493 BOOST_LOG(debug) << "---Begin MessageBuffer---"sv << std::endl
1494 << messageBuffer << std::endl
1495 << "---End MessageBuffer---"sv << std::endl;
1496 }
1497} // namespace rtsp_stream
1498
@ SURROUND51
Surround 5.1.
Definition audio.h:23
@ SURROUND71
Surround 7.1.
Definition audio.h:25
@ MAX_STREAM_CONFIG
Maximum audio stream configuration.
Definition audio.h:27
std::string isolated_audio_sink(uint32_t launch_session_id)
The sink an isolated session plays into, or empty for one that shares the host's.
Definition process.cpp:3261
std::string isolated_audio_server(uint32_t launch_session_id)
Definition process.cpp:3273
std::string isolated_mic_source(uint32_t launch_session_id)
Definition process.cpp:3282
void terminate_isolated(uint32_t launch_session_id)
Definition process.cpp:3019
void remove(const std::shared_ptr< stream::session_t > &session)
Removes the provided session from the set of sessions.
Definition rtsp.cpp:651
int session_count()
Get the number of active sessions.
Definition rtsp.cpp:606
bool session_raise(std::shared_ptr< launch_session_t > launch_session)
Launch a new streaming session.
Definition rtsp.cpp:538
void clear(bool all=true)
Clear launch sessions.
Definition rtsp.cpp:631
void iterate()
Runs an iteration of the RTSP server loop.
Definition rtsp.cpp:674
void session_clear(uint32_t launch_session_id)
Clear state for the oldest launch session.
Definition rtsp.cpp:566
void stop()
Stop the RTSP server.
Definition rtsp.cpp:687
void insert(const std::shared_ptr< stream::session_t > &session)
Inserts the provided session into the set of sessions.
Definition rtsp.cpp:660
static void handle_read_encrypted_message(std::shared_ptr< socket_t > &socket, const boost::system::error_code &ec, std::size_t bytes)
Handle the final read of the content of an encrypted message.
Definition rtsp.cpp:205
void read_plaintext_payload()
Queue an asynchronous read of the payload portion of a plaintext message.
Definition rtsp.cpp:267
void read()
Queue an asynchronous read to begin the next message.
Definition rtsp.cpp:122
static void handle_read_encrypted_header(std::shared_ptr< socket_t > &socket, const boost::system::error_code &ec, std::size_t bytes)
Handle the initial read of the header of an encrypted message.
Definition rtsp.cpp:156
static void handle_plaintext_payload(std::shared_ptr< socket_t > &socket, const boost::system::error_code &ec, std::size_t bytes)
Handle the read of the payload portion of a plaintext message.
Definition rtsp.cpp:296
static void handle_read_plaintext(std::shared_ptr< socket_t > &socket, const boost::system::error_code &ec, std::size_t bytes)
Handle the read of the header portion of a plaintext message.
Definition rtsp.cpp:366
@ MAX_SPEAKERS
Maximum number of speakers.
Definition common.h:184
Declarations for the configuration of Sunshine.
Declarations for globally accessible variables and functions.
Declarations for gamepad, keyboard, and mouse input handling.
Declarations for logging related functions.
safe::mail_t man
A process-wide communication mechanism.
Definition globals.cpp:8
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
int encryption_mode_for_address(boost::asio::ip::address address)
Get the encryption mode for the given remote endpoint address.
Definition network.cpp:217
Declarations for networking related functions.
af_e
Definition network.h:45
@ IPV4
IPv4 only.
Definition network.h:46
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.
Definition prelogin.cpp:632
Declarations for the startup and shutdown of the apps started by a streaming Session.
void terminate_sessions()
Terminates all running streaming sessions.
Definition rtsp.cpp:813
bool terminate_session(const std::string_view &uuid)
Definition rtsp.cpp:805
bool cancel_pending_launch(const std::string_view &uuid)
Definition rtsp.cpp:769
void launch_session_clear(uint32_t launch_session_id)
Clear state for the specified launch session.
Definition rtsp.cpp:765
bool launch_session_raise(std::shared_ptr< launch_session_t > launch_session)
Definition rtsp.cpp:761
std::string_view last_termination_reason()
Get a short identifier for why the most recent session ended.
Definition rtsp.cpp:785
int session_count()
Get the number of active sessions.
Definition rtsp.cpp:773
void start()
Runs the RTSP server loop.
Definition rtsp.cpp:1413
void terminate_shared_sessions()
Definition rtsp.cpp:809
std::string surround_params(int config)
The surround-params value the RTSP DESCRIBE reply advertises for an audio layout.
Definition rtsp.cpp:924
Declarations for RTSP streaming.
Declarations for the streaming protocols.
@ STOPPING
The session is stopping.
Definition stream.h:54
@ SERVER_STOPPED
Host stopped the session (API stop, shutdown).
Definition stream.h:72
@ HIGH_QUALITY
High quality audio.
Definition audio.h:50
@ CUSTOM_SURROUND_PARAMS
Custom surround parameters.
Definition audio.h:52
@ HOST_AUDIO
Host audio.
Definition audio.h:51
std::string session_sink
Definition audio.h:81
std::string session_server
The audio server session_sink lives in, where the session has its own.
Definition audio.h:84
std::string mic_source
The session mic the client's microphone plays into; empty for none.
Definition stream.h:48
Declarations for synchronization utilities.
void metrics_reset()
Reset pipeline metrics at the start of a streaming session.
Definition video.cpp:910
Declarations for video.
bool removeVirtualDisplay(const uuid_util::uuid_t &guid)
Remove a virtual display.