Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
client_mic_router.h
Go to the documentation of this file.
1
5#pragma once
6
7#include "crypto.h"
8#include "utility.h"
9
10#include <array>
11#include <cstring>
12#include <optional>
13#include <opus/opus.h>
14#include <span>
15#include <vector>
16
17namespace audio {
20 std::uint32_t key_id;
21 };
22
24 std::size_t candidate;
25 std::vector<std::uint8_t> opus;
26 };
27
28 // Several clients can share an address (NAT). A failed decryption for the
29 // first session must not prevent trying the next one. The legacy CBC format
30 // has no authenticated session ID, so require a valid Opus frame and reject
31 // ambiguous matches instead of sending one client's voice to another.
32 inline std::optional<routed_mic_packet_t> route_mic_packet(
33 std::span<const mic_candidate_t> candidates,
34 std::uint16_t sequence,
35 std::string_view encrypted
36 ) {
37 if (encrypted.empty() || encrypted.size() > 2048 || encrypted.size() % 16 != 0) {
38 return std::nullopt;
39 }
40 std::optional<routed_mic_packet_t> result;
41 for (std::size_t index = 0; index < candidates.size(); ++index) {
42 const auto &candidate = candidates[index];
43 if (!candidate.cipher) {
44 continue;
45 }
46 crypto::aes_t iv(16);
47 const auto first = util::endian::big<std::uint32_t>(candidate.key_id + sequence);
48 std::memcpy(iv.data(), &first, sizeof(first));
49 std::vector<std::uint8_t> plaintext;
50 if (candidate.cipher->decrypt(encrypted, plaintext, &iv) != 0 || plaintext.empty()) {
51 continue;
52 }
53 const int samples = opus_packet_get_nb_samples(plaintext.data(), static_cast<opus_int32>(plaintext.size()), 48000);
54 if (samples <= 0 || samples > 5760) {
55 continue;
56 }
57 unsigned char toc;
58 std::array<const unsigned char *, 48> frames;
59 std::array<opus_int16, 48> sizes;
60 int payload_offset;
61 if (opus_packet_parse(plaintext.data(), static_cast<opus_int32>(plaintext.size()), &toc, frames.data(), sizes.data(), &payload_offset) <= 0) {
62 continue;
63 }
64 if (result) {
65 return std::nullopt;
66 }
67 result = routed_mic_packet_t {index, std::move(plaintext)};
68 }
69 return result;
70 }
71} // namespace audio
Declarations for cryptography functions.
Declarations for utility functions.