@geastack/host 0.1.10 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/audio_runtime.cpp +97 -3
  2. package/host/audio.cpp +395 -10
  3. package/host/audio_worklet.cpp +611 -0
  4. package/host/fetch.cpp +17 -0
  5. package/host/media.cpp +308 -27
  6. package/host/mjpeg.cpp +199 -0
  7. package/host/rtc.cpp +458 -48
  8. package/host/rtc_esp.cpp +897 -75
  9. package/host/rtc_objects.inc +246 -0
  10. package/host/timers.cpp +18 -0
  11. package/host/video.cpp +152 -0
  12. package/host/websocket.cpp +623 -72
  13. package/host/worker.cpp +621 -0
  14. package/include/gea/audio-worklet-runtime.h +165 -0
  15. package/include/gea/base64-runtime.h +26 -0
  16. package/include/gea/embedded-host.h +1 -0
  17. package/include/gea/worker-runtime.h +184 -0
  18. package/include/host/audio.h +94 -6
  19. package/include/host/audio_level.h +37 -0
  20. package/include/host/audio_worklet.h +103 -0
  21. package/include/host/h264_layout.h +170 -0
  22. package/include/host/media.h +67 -0
  23. package/include/host/mjpeg.h +22 -0
  24. package/include/host/mjpeg_parser.h +84 -0
  25. package/include/host/pcm_stream.h +122 -0
  26. package/include/host/rtc.h +38 -20
  27. package/include/host/rtc_h264.h +76 -0
  28. package/include/host/rtc_ice_candidate.h +141 -0
  29. package/include/host/rtc_opus.h +136 -0
  30. package/include/host/rtc_receive_sdp.h +245 -0
  31. package/include/host/rtc_rtp.h +170 -0
  32. package/include/host/rtc_sdp.h +71 -0
  33. package/include/host/rtc_types.h +166 -0
  34. package/include/host/rtc_vp8.h +115 -0
  35. package/include/host/rtc_vp8_capture.h +129 -0
  36. package/include/host/rtc_vp8_decoder.h +169 -0
  37. package/include/host/rtc_vp8_receiver.h +55 -0
  38. package/include/host/timers.h +3 -2
  39. package/include/host/video.h +39 -0
  40. package/include/host/video_color.h +90 -0
  41. package/include/host/video_frame_pool.h +50 -0
  42. package/include/host/video_pixels.h +178 -0
  43. package/include/host/websocket.h +20 -1
  44. package/include/host/websocket_message.h +66 -0
  45. package/include/host/worker.h +131 -0
  46. package/package.json +1 -1
  47. package/services/diagnostics.cpp +120 -19
@@ -0,0 +1,76 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include "host/h264_layout.h"
4
+ #include "host/media.h"
5
+ #include "esp_h264_dec_sw.h"
6
+ #include <memory>
7
+ #include <limits>
8
+
9
+ namespace gea::host::rtc::h264 {
10
+
11
+ // Owned by the decode worker, never by the RTP/audio callback thread.
12
+ class Decoder {
13
+ public:
14
+ Decoder() = default;
15
+ Decoder(const Decoder&) = delete;
16
+ Decoder& operator=(const Decoder&) = delete;
17
+ ~Decoder() { reset(); }
18
+
19
+ void reset() {
20
+ if (decoder_) { esp_h264_dec_close(decoder_); esp_h264_dec_del(decoder_); }
21
+ decoder_ = nullptr;
22
+ parameters_ = nullptr;
23
+ metadata_ = {};
24
+ }
25
+
26
+ std::unique_ptr<media::VideoFrame> decode(const uint8_t* bytes, size_t length, uint32_t timestamp) {
27
+ if (!length || length > std::numeric_limits<uint32_t>::max() ||
28
+ !inspectAccessUnit(bytes, length, metadata_) || !open()) {
29
+ reset(); return nullptr;
30
+ }
31
+ esp_h264_dec_in_frame_t input{};
32
+ input.raw_data.buffer = const_cast<uint8_t*>(bytes);
33
+ input.raw_data.len = static_cast<uint32_t>(length);
34
+ std::unique_ptr<media::VideoFrame> latest;
35
+ while (input.raw_data.len) {
36
+ input.consume = 0;
37
+ esp_h264_dec_out_frame_t decoded{};
38
+ const auto rc = esp_h264_dec_process(decoder_, &input, &decoded);
39
+ if (rc != ESP_H264_ERR_OK || !input.consume || input.consume > input.raw_data.len) {
40
+ reset(); return nullptr;
41
+ }
42
+ if (decoded.out_size) {
43
+ esp_h264_resolution_t resolution{};
44
+ const auto expected = size_t(metadata_.width) * metadata_.height * 3 / 2;
45
+ if (esp_h264_dec_get_resolution(parameters_, &resolution) != ESP_H264_ERR_OK || !decoded.outbuf ||
46
+ resolution.width != metadata_.width || resolution.height != metadata_.height || decoded.out_size != expected) {
47
+ reset(); return nullptr;
48
+ }
49
+ latest = std::make_unique<media::VideoFrame>();
50
+ latest->width = metadata_.visibleWidth;
51
+ latest->height = metadata_.visibleHeight;
52
+ latest->timestampMs = timestamp;
53
+ latest->rgb565.resize(size_t(latest->width) * latest->height);
54
+ convertI420(decoded.outbuf, metadata_, latest->rgb565.data());
55
+ }
56
+ input.raw_data.buffer += input.consume;
57
+ input.raw_data.len -= input.consume;
58
+ }
59
+ return latest;
60
+ }
61
+
62
+ private:
63
+ bool open() {
64
+ if (decoder_) return true;
65
+ esp_h264_dec_cfg_sw_t config{};
66
+ config.pic_type = ESP_H264_RAW_FMT_I420;
67
+ auto rc = esp_h264_dec_sw_new(&config, &decoder_);
68
+ if (rc == ESP_H264_ERR_OK) rc = esp_h264_dec_open(decoder_);
69
+ if (rc == ESP_H264_ERR_OK) rc = esp_h264_dec_sw_get_param_hd(decoder_, &parameters_);
70
+ return rc == ESP_H264_ERR_OK;
71
+ }
72
+ esp_h264_dec_handle_t decoder_ = nullptr;
73
+ esp_h264_dec_param_sw_handle_t parameters_ = nullptr;
74
+ Metadata metadata_;
75
+ };
76
+ } // namespace gea::host::rtc::h264
@@ -0,0 +1,141 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include <cstdint>
4
+ #include <memory>
5
+ #include <optional>
6
+ #include <stdexcept>
7
+ #include <string>
8
+ #include <string_view>
9
+ #include <utility>
10
+ #include <vector>
11
+
12
+ namespace gea::host {
13
+ struct RTCIceCandidateInit {
14
+ std::string candidate;
15
+ std::optional<std::string> sdpMid;
16
+ std::optional<double> sdpMLineIndex;
17
+ std::optional<std::string> usernameFragment;
18
+ std::optional<std::string> relayProtocol;
19
+ std::optional<std::string> url;
20
+ };
21
+
22
+ class RTCIceCandidate {
23
+ struct Fields {
24
+ RTCIceCandidateInit init;
25
+ std::optional<std::string> foundation, component, address, protocol, type, tcpType, relatedAddress;
26
+ std::optional<double> priority, port, relatedPort;
27
+ };
28
+
29
+ public:
30
+ RTCIceCandidate() = default;
31
+ explicit RTCIceCandidate(RTCIceCandidateInit init) {
32
+ if (!init.sdpMid && !init.sdpMLineIndex)
33
+ throw std::invalid_argument("RTCIceCandidate requires sdpMid or sdpMLineIndex");
34
+ auto fields = std::make_shared<Fields>();
35
+ fields->init = std::move(init);
36
+ // Malformed candidate text is retained verbatim; none of its derived
37
+ // attributes may leak out of a partially successful parse.
38
+ Fields parsed;
39
+ if (parse(fields->init.candidate, parsed)) {
40
+ parsed.init = std::move(fields->init);
41
+ *fields = std::move(parsed);
42
+ }
43
+ fields_ = std::move(fields);
44
+ }
45
+ const RTCIceCandidateInit& fields() const { return data().init; }
46
+ std::string candidate() const { return fields().candidate; }
47
+ std::optional<std::string> sdpMid() const { return fields().sdpMid; }
48
+ std::optional<double> sdpMLineIndex() const { return fields().sdpMLineIndex; }
49
+ std::optional<std::string> usernameFragment() const { return fields().usernameFragment; }
50
+ std::optional<std::string> relayProtocol() const { return fields().relayProtocol; }
51
+ std::optional<std::string> url() const { return fields().url; }
52
+ #define GEA_ICE_GETTER(Type, Name) std::optional<Type> Name() const { return data().Name; }
53
+ GEA_ICE_GETTER(std::string, foundation)
54
+ GEA_ICE_GETTER(std::string, component)
55
+ GEA_ICE_GETTER(std::string, address)
56
+ GEA_ICE_GETTER(std::string, protocol)
57
+ GEA_ICE_GETTER(std::string, type)
58
+ GEA_ICE_GETTER(std::string, tcpType)
59
+ GEA_ICE_GETTER(std::string, relatedAddress)
60
+ GEA_ICE_GETTER(double, priority)
61
+ GEA_ICE_GETTER(double, port)
62
+ GEA_ICE_GETTER(double, relatedPort)
63
+ #undef GEA_ICE_GETTER
64
+ explicit operator bool() const { return static_cast<bool>(fields_); }
65
+ bool operator==(std::nullptr_t) const { return !fields_; }
66
+ bool operator==(const RTCIceCandidate& other) const { return fields_ == other.fields_; }
67
+
68
+ private:
69
+ const Fields& data() const {
70
+ if (!fields_) throw std::logic_error("null RTCIceCandidate");
71
+ return *fields_;
72
+ }
73
+ static bool unsignedNumber(std::string_view text, uint64_t max, double& result) {
74
+ if (text.empty()) return false;
75
+ uint64_t value = 0;
76
+ for (const char ch : text) {
77
+ if (ch < '0' || ch > '9') return false;
78
+ const auto digit = static_cast<uint64_t>(ch - '0');
79
+ if (value > max / 10 || (value == max / 10 && digit > max % 10)) return false;
80
+ value = value * 10 + digit;
81
+ }
82
+ result = static_cast<double>(value);
83
+ return true;
84
+ }
85
+ static std::string lower(std::string_view text) {
86
+ std::string out(text);
87
+ for (char& ch : out) if (ch >= 'A' && ch <= 'Z') ch += 'a' - 'A';
88
+ return out;
89
+ }
90
+ static bool parse(const std::string& text, Fields& result) {
91
+ if (!text.starts_with("candidate:")) return false;
92
+ std::vector<std::string_view> tokens;
93
+ const std::string_view source(text);
94
+ size_t start = 10;
95
+ for (size_t i = start; i <= source.size(); ++i) {
96
+ if (i < source.size() && source[i] != ' ') {
97
+ if (static_cast<unsigned char>(source[i]) < 0x21 || static_cast<unsigned char>(source[i]) > 0x7e) return false;
98
+ continue;
99
+ }
100
+ if (i == start) return false;
101
+ tokens.push_back(source.substr(start, i - start));
102
+ start = i + 1;
103
+ }
104
+ if (tokens.size() < 8 || tokens.size() % 2 != 0 || tokens[0].size() > 32) return false;
105
+ for (char ch : tokens[0])
106
+ if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
107
+ (ch >= '0' && ch <= '9') || ch == '+' || ch == '/')) return false;
108
+ double component, priority, port;
109
+ if (!unsignedNumber(tokens[1], 2, component) || component == 0 ||
110
+ !unsignedNumber(tokens[3], UINT32_MAX, priority) || !unsignedNumber(tokens[5], UINT16_MAX, port)) return false;
111
+ const auto protocol = lower(tokens[2]);
112
+ const auto type = lower(tokens[7]);
113
+ if ((protocol != "udp" && protocol != "tcp") || lower(tokens[6]) != "typ" ||
114
+ (type != "host" && type != "srflx" && type != "prflx" && type != "relay")) return false;
115
+ result.foundation = tokens[0];
116
+ result.component = component == 1 ? "rtp" : "rtcp";
117
+ result.priority = priority;
118
+ result.address = tokens[4];
119
+ result.protocol = protocol;
120
+ result.port = port;
121
+ result.type = type;
122
+ for (size_t i = 8; i < tokens.size(); i += 2) {
123
+ const auto key = lower(tokens[i]);
124
+ if (key == "raddr") {
125
+ if (result.relatedAddress) return false;
126
+ result.relatedAddress = tokens[i + 1];
127
+ } else if (key == "rport") {
128
+ double relatedPort;
129
+ if (result.relatedPort || !unsignedNumber(tokens[i + 1], UINT16_MAX, relatedPort)) return false;
130
+ result.relatedPort = relatedPort;
131
+ } else if (key == "tcptype") {
132
+ const auto tcpType = lower(tokens[i + 1]);
133
+ if (result.tcpType || protocol != "tcp" || (tcpType != "active" && tcpType != "passive" && tcpType != "so")) return false;
134
+ result.tcpType = tcpType;
135
+ }
136
+ }
137
+ return protocol != "tcp" || result.tcpType.has_value();
138
+ }
139
+ std::shared_ptr<const Fields> fields_;
140
+ };
141
+ }
@@ -0,0 +1,136 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #if defined(ESP_PLATFORM) && __has_include("esp_opus_enc.h")
4
+ #define GEA_RTC_ESP_OPUS 1
5
+ #include "esp_opus_enc.h"
6
+ #include "esp_opus_dec.h"
7
+ #else
8
+ #include <opus.h>
9
+ #endif
10
+ #include <array>
11
+ #include <cstdint>
12
+ #include <stdexcept>
13
+
14
+ namespace gea::host::rtc {
15
+ // esp_peer transports encoded RTP payloads. The media-track boundary is PCM.
16
+ // Decode at the track's 16 kHz rate; Opus's RTP clock remains 48 kHz.
17
+ class OpusAudio {
18
+ public:
19
+ // Amortize SRTP/socket work across two 20 ms Opus frames. At 50 sends/sec
20
+ // the S3 spent ~11 ms encoding plus ~10 ms sending each 20 ms of capture,
21
+ // accumulating old microphone audio. This adds only 20 ms packetization.
22
+ static constexpr int sampleRate = 16000, frameDurationMs = 40;
23
+ static constexpr int frameSamples = sampleRate * frameDurationMs / 1000;
24
+ static constexpr int maxDecodeSamples = sampleRate * 120 / 1000;
25
+ enum class Application { LowDelay, Voice };
26
+ enum class Direction { Both, Encode, Decode };
27
+ explicit OpusAudio(Application application = Application::LowDelay,
28
+ Direction direction = Direction::Both) {
29
+ #if GEA_RTC_ESP_OPUS
30
+ if (direction != Direction::Decode) {
31
+ esp_opus_enc_config_t config{};
32
+ config.sample_rate = sampleRate;
33
+ config.channel = 1;
34
+ config.bits_per_sample = 16;
35
+ config.bitrate = 24000;
36
+ config.frame_duration = ESP_OPUS_ENC_FRAME_DURATION_40_MS;
37
+ // CELT-only low-delay mode avoids SILK's analysis work competing with
38
+ // AEC on the S3. The RTP codec, PCM rate and 24 kbps bitrate are unchanged.
39
+ config.application_mode = application == Application::LowDelay
40
+ ? ESP_OPUS_ENC_APPLICATION_LOWDELAY : ESP_OPUS_ENC_APPLICATION_VOIP;
41
+ config.complexity = 0;
42
+ config.enable_vbr = true;
43
+ if (esp_opus_enc_open(&config, sizeof(config), &encoder) != ESP_AUDIO_ERR_OK)
44
+ throw std::runtime_error("RTC Opus encoder allocation failed");
45
+ }
46
+ if (direction != Direction::Encode) {
47
+ esp_opus_dec_cfg_t receive{};
48
+ receive.sample_rate = sampleRate;
49
+ receive.channel = 1;
50
+ receive.frame_duration = ESP_OPUS_DEC_FRAME_DURATION_120_MS;
51
+ receive.self_delimited = false;
52
+ if (esp_opus_dec_open(&receive, sizeof(receive), &decoder) != ESP_AUDIO_ERR_OK) {
53
+ if (encoder) esp_opus_enc_close(encoder);
54
+ throw std::runtime_error("RTC Opus decoder allocation failed");
55
+ }
56
+ }
57
+ #else
58
+ int error;
59
+ if (direction != Direction::Decode) {
60
+ encoder = opus_encoder_create(sampleRate, 1, application == Application::LowDelay
61
+ ? OPUS_APPLICATION_RESTRICTED_LOWDELAY : OPUS_APPLICATION_VOIP, &error);
62
+ if (!encoder) throw std::runtime_error("RTC Opus encoder allocation failed");
63
+ }
64
+ if (direction != Direction::Encode) {
65
+ decoder = opus_decoder_create(sampleRate, 1, &error);
66
+ if (!decoder) {
67
+ if (encoder) opus_encoder_destroy(encoder);
68
+ throw std::runtime_error("RTC Opus decoder allocation failed");
69
+ }
70
+ }
71
+ if (encoder) {
72
+ opus_encoder_ctl(encoder, OPUS_SET_BITRATE(24000));
73
+ // On S3 the complexity-3 encoder missed its 20 ms deadline alongside
74
+ // incoming RTP. Keep the 24 kbps wire format, with real-time CPU cost.
75
+ opus_encoder_ctl(encoder, OPUS_SET_COMPLEXITY(0));
76
+ opus_encoder_ctl(encoder, OPUS_SET_DTX(0));
77
+ }
78
+ #endif
79
+ }
80
+ ~OpusAudio() {
81
+ #if GEA_RTC_ESP_OPUS
82
+ if (encoder) esp_opus_enc_close(encoder);
83
+ if (decoder) esp_opus_dec_close(decoder);
84
+ #else
85
+ if (encoder) opus_encoder_destroy(encoder);
86
+ if (decoder) opus_decoder_destroy(decoder);
87
+ #endif
88
+ }
89
+ OpusAudio(const OpusAudio&) = delete;
90
+ OpusAudio& operator=(const OpusAudio&) = delete;
91
+ int encode(const int16_t* pcm) {
92
+ if (!encoder || !pcm) return -1;
93
+ #if GEA_RTC_ESP_OPUS
94
+ esp_audio_enc_in_frame_t input{};
95
+ input.buffer = reinterpret_cast<uint8_t*>(const_cast<int16_t*>(pcm));
96
+ input.len = frameSamples * sizeof(int16_t);
97
+ esp_audio_enc_out_frame_t output{};
98
+ output.buffer = packet.data();
99
+ output.len = packet.size();
100
+ return esp_opus_enc_process(encoder, &input, &output) == ESP_AUDIO_ERR_OK
101
+ ? int(output.encoded_bytes) : -1;
102
+ #else
103
+ return opus_encode(encoder, pcm, frameSamples, packet.data(), packet.size());
104
+ #endif
105
+ }
106
+ int decode(const uint8_t* bytes, int size) {
107
+ if (!decoder || !bytes || size <= 0) return -1;
108
+ #if GEA_RTC_ESP_OPUS
109
+ esp_audio_dec_in_raw_t input{};
110
+ input.buffer = const_cast<uint8_t*>(bytes);
111
+ input.len = size;
112
+ esp_audio_dec_out_frame_t output{};
113
+ output.buffer = reinterpret_cast<uint8_t*>(decoded.data());
114
+ output.len = sizeof(decoded);
115
+ esp_audio_dec_info_t info{};
116
+ const auto status = esp_opus_dec_decode(decoder, &input, &output, &info);
117
+ if (status != ESP_AUDIO_ERR_OK || input.consumed != unsigned(size) ||
118
+ output.decoded_size > sizeof(decoded) || info.channel != 1 || info.sample_rate != sampleRate)
119
+ return -1;
120
+ return int(output.decoded_size / sizeof(int16_t));
121
+ #else
122
+ return opus_decode(decoder, bytes, size, decoded.data(), decoded.size(), 0);
123
+ #endif
124
+ }
125
+ alignas(16) std::array<uint8_t, 1275> packet{};
126
+ alignas(16) std::array<int16_t, maxDecodeSamples> decoded{};
127
+ private:
128
+ #if GEA_RTC_ESP_OPUS
129
+ void* encoder = nullptr;
130
+ void* decoder = nullptr;
131
+ #else
132
+ OpusEncoder* encoder = nullptr;
133
+ OpusDecoder* decoder = nullptr;
134
+ #endif
135
+ };
136
+ }
@@ -0,0 +1,245 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ #include <algorithm>
5
+ #include <array>
6
+ #include <charconv>
7
+ #include <optional>
8
+ #include <string>
9
+ #include <string_view>
10
+ #include <vector>
11
+
12
+ namespace gea::host::rtc::receive {
13
+
14
+ inline std::vector<std::string_view> split(std::string_view value, char delimiter) {
15
+ std::vector<std::string_view> parts;
16
+ while (!value.empty()) {
17
+ const auto end = value.find(delimiter);
18
+ parts.push_back(value.substr(0, end));
19
+ if (end == value.npos) break;
20
+ value.remove_prefix(end + 1);
21
+ }
22
+ return parts;
23
+ }
24
+
25
+ inline std::optional<uint32_t> number(std::string_view value, uint32_t maximum) {
26
+ uint32_t result = 0;
27
+ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), result);
28
+ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || result > maximum)
29
+ return std::nullopt;
30
+ return result;
31
+ }
32
+
33
+ inline bool token(std::string_view value) {
34
+ return !value.empty() && std::all_of(value.begin(), value.end(), [](unsigned char c) {
35
+ return c >= 33 && c <= 126;
36
+ });
37
+ }
38
+
39
+ inline std::optional<std::array<uint8_t, 32>> fingerprint(std::string_view value) {
40
+ if (value.size() != 95) return std::nullopt;
41
+ std::array<uint8_t, 32> digest{};
42
+ auto hex = [](char c) -> int {
43
+ if (c >= '0' && c <= '9') return c - '0';
44
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
45
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
46
+ return -1;
47
+ };
48
+ for (size_t index = 0; index < digest.size(); ++index) {
49
+ const auto high = hex(value[index * 3]), low = hex(value[index * 3 + 1]);
50
+ if (high < 0 || low < 0 || (index < 31 && value[index * 3 + 2] != ':')) return std::nullopt;
51
+ digest[index] = uint8_t(high * 16 + low);
52
+ }
53
+ return digest;
54
+ }
55
+
56
+ struct Transport {
57
+ std::string ufrag, password, fingerprint, setup;
58
+ std::vector<std::string> candidates;
59
+ };
60
+
61
+ struct Track {
62
+ std::string kind, mid, codec;
63
+ uint8_t payloadType = 0;
64
+ uint32_t ssrc = 0;
65
+ bool rtcpMux = false, reducedRtcp = false, sends = false, pli = false;
66
+ Transport transport;
67
+ };
68
+
69
+ struct Offer {
70
+ std::vector<Track> tracks;
71
+ std::array<uint8_t, 32> peerFingerprint{};
72
+ std::string iceDescription;
73
+ };
74
+
75
+ inline bool assignOnce(std::string& target, std::string_view value) {
76
+ if (!target.empty() && target != value) return false;
77
+ target = value;
78
+ return true;
79
+ }
80
+
81
+ // One incoming Opus track, an Opus/VP8 BUNDLE, or an answer to our Opus microphone
82
+ // offer. Reject unsupported media/directions instead of connecting streams
83
+ // we cannot route. ICE and SHA-256 fingerprints must agree in BUNDLE.
84
+ inline std::optional<Offer> parseDescription(std::string_view sdp, bool receiving) {
85
+ if (sdp.size() > 64 * 1024 || sdp.find('\0') != sdp.npos) return std::nullopt;
86
+ Offer result;
87
+ Transport session;
88
+ std::vector<std::string_view> bundle;
89
+ bool iceLite = false;
90
+ for (auto line : split(sdp, '\n')) {
91
+ if (!line.empty() && line.back() == '\r') line.remove_suffix(1);
92
+ if (line.empty()) continue;
93
+ if (line.find('\r') != line.npos || line.size() > 2048) return std::nullopt;
94
+ if (line.starts_with("m=")) {
95
+ const auto fields = split(line.substr(2), ' ');
96
+ if (fields.size() != 4 || (fields[0] != "audio" && fields[0] != "video") ||
97
+ fields[2] != "UDP/TLS/RTP/SAVPF") return std::nullopt;
98
+ const auto port = number(fields[1], 65535), payload = number(fields[3], 127);
99
+ if (!port || !*port || !payload || (*payload >= 64 && *payload <= 95) ||
100
+ result.tracks.size() == 2) return std::nullopt;
101
+ Track track;
102
+ track.kind = fields[0];
103
+ track.payloadType = uint8_t(*payload);
104
+ track.transport = session;
105
+ result.tracks.push_back(std::move(track));
106
+ continue;
107
+ }
108
+ if (line.starts_with("a=group:BUNDLE ")) {
109
+ if (!bundle.empty() || !result.tracks.empty()) return std::nullopt;
110
+ bundle = split(line.substr(15), ' ');
111
+ continue;
112
+ }
113
+ if (line == "a=ice-lite") { iceLite = true; continue; }
114
+ auto& transport = result.tracks.empty() ? session : result.tracks.back().transport;
115
+ auto attribute = [&](std::string_view prefix, std::string& target) {
116
+ const auto value = line.substr(prefix.size());
117
+ return token(value) && assignOnce(target, value);
118
+ };
119
+ if (line.starts_with("a=ice-ufrag:")) {
120
+ if (!attribute("a=ice-ufrag:", transport.ufrag)) return std::nullopt;
121
+ } else if (line.starts_with("a=ice-pwd:")) {
122
+ if (!attribute("a=ice-pwd:", transport.password)) return std::nullopt;
123
+ } else if (line.starts_with("a=fingerprint:")) {
124
+ constexpr std::string_view prefix = "a=fingerprint:sha-256 ";
125
+ if (!line.starts_with(prefix) || !fingerprint(line.substr(prefix.size())) ||
126
+ !assignOnce(transport.fingerprint, line.substr(prefix.size()))) return std::nullopt;
127
+ } else if (line.starts_with("a=setup:")) {
128
+ if (!attribute("a=setup:", transport.setup)) return std::nullopt;
129
+ } else if (line.starts_with("a=candidate:")) {
130
+ if (transport.candidates.size() >= 32) return std::nullopt;
131
+ transport.candidates.emplace_back(line);
132
+ } else if (!result.tracks.empty()) {
133
+ auto& track = result.tracks.back();
134
+ if (line.starts_with("a=mid:")) {
135
+ if (!attribute("a=mid:", track.mid)) return std::nullopt;
136
+ } else if (line == (receiving ? "a=sendonly" : "a=recvonly")) track.sends = true;
137
+ else if (line == "a=sendonly" || line == "a=recvonly" || line == "a=sendrecv" || line == "a=inactive") return std::nullopt;
138
+ else if (line == "a=rtcp-mux") track.rtcpMux = true;
139
+ else if (line == "a=rtcp-rsize") track.reducedRtcp = true;
140
+ else if (line.starts_with("a=rtpmap:")) {
141
+ const auto fields = split(line.substr(9), ' ');
142
+ if (fields.size() != 2 || number(fields[0], 127) != track.payloadType ||
143
+ !assignOnce(track.codec, fields[1])) return std::nullopt;
144
+ } else if (line.starts_with("a=ssrc:")) {
145
+ const auto id = number(line.substr(7, line.find(' ') - 7), UINT32_MAX);
146
+ if (!id || !*id || (track.ssrc && track.ssrc != *id)) return std::nullopt;
147
+ track.ssrc = *id;
148
+ } else if (line == "a=rtcp-fb:" + std::to_string(track.payloadType) + " nack pli") {
149
+ track.pli = true;
150
+ }
151
+ }
152
+ }
153
+ if (result.tracks.empty() || (!receiving && result.tracks.size() != 1) ||
154
+ bundle.size() != result.tracks.size()) return std::nullopt;
155
+ const auto& first = result.tracks[0];
156
+ if (receiving && result.tracks.size() == 2) {
157
+ const auto& second = result.tracks[1];
158
+ if (bundle[0] == bundle[1] || first.kind == second.kind || first.mid == second.mid ||
159
+ first.ssrc == second.ssrc || first.payloadType == second.payloadType) return std::nullopt;
160
+ } else if (first.kind != "audio" || (!receiving && (first.mid != "0" || first.payloadType != 111))) return std::nullopt;
161
+ for (const auto& track : result.tracks) {
162
+ const auto& ice = track.transport;
163
+ if (std::find(bundle.begin(), bundle.end(), track.mid) == bundle.end() ||
164
+ !track.sends || !track.rtcpMux || (receiving && !track.ssrc) || !token(track.mid) ||
165
+ ice.ufrag.size() < 4 || ice.password.size() < 22 || ice.ufrag.size() > 256 ||
166
+ ice.password.size() > 256 || ice.candidates.empty() ||
167
+ (ice.setup != "passive" && (!receiving || ice.setup != "actpass")) ||
168
+ ice.ufrag != first.transport.ufrag || ice.password != first.transport.password ||
169
+ ice.fingerprint != first.transport.fingerprint || ice.setup != first.transport.setup)
170
+ return std::nullopt;
171
+ auto codec = track.codec;
172
+ std::transform(codec.begin(), codec.end(), codec.begin(), [](unsigned char c) {
173
+ return c >= 'A' && c <= 'Z' ? c + 'a' - 'A' : c;
174
+ });
175
+ if ((track.kind == "audio" && codec != "opus/48000/2") ||
176
+ (track.kind == "video" && (codec != "vp8/90000" || !track.pli))) return std::nullopt;
177
+ }
178
+ const auto digest = fingerprint(first.transport.fingerprint);
179
+ if (!digest) return std::nullopt;
180
+ result.peerFingerprint = *digest;
181
+ result.iceDescription = "a=ice-ufrag:" + first.transport.ufrag + "\r\na=ice-pwd:" +
182
+ first.transport.password + "\r\n";
183
+ if (iceLite) result.iceDescription += "a=ice-lite\r\n";
184
+ for (const auto& candidate : first.transport.candidates) result.iceDescription += candidate + "\r\n";
185
+ result.iceDescription += "a=end-of-candidates\r\n";
186
+ return result;
187
+ }
188
+
189
+ inline std::optional<Offer> parseOffer(std::string_view sdp) {
190
+ return parseDescription(sdp, true);
191
+ }
192
+
193
+ inline std::optional<Offer> parseMicrophoneAnswer(std::string_view sdp) {
194
+ return parseDescription(sdp, false);
195
+ }
196
+
197
+ inline std::optional<std::string> localIceAttributes(std::string_view localIce) {
198
+ std::string ice;
199
+ bool ufrag = false, password = false;
200
+ for (auto line : split(localIce, '\n')) {
201
+ if (!line.empty() && line.back() == '\r') line.remove_suffix(1);
202
+ if (line.find('\r') != line.npos || line.find('\0') != line.npos) return std::nullopt;
203
+ if (line.starts_with("a=ice-ufrag:")) ufrag = token(line.substr(12));
204
+ else if (line.starts_with("a=ice-pwd:")) password = token(line.substr(10));
205
+ else if (!line.starts_with("a=candidate:") && line != "a=end-of-candidates") continue;
206
+ ice += std::string(line) + "\r\n";
207
+ }
208
+ if (!ufrag || !password) return std::nullopt;
209
+ return ice;
210
+ }
211
+
212
+ inline std::optional<std::string> microphoneOffer(std::string_view localIce,
213
+ std::string_view localFingerprint, uint32_t ssrc) {
214
+ const auto ice = localIceAttributes(localIce);
215
+ if (!ice || !ssrc || !fingerprint(localFingerprint)) return std::nullopt;
216
+ return "v=0\r\no=- 1 1 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\n"
217
+ "a=msid-semantic: WMS gea\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\n"
218
+ "a=mid:0\r\na=sendonly\r\na=rtcp-mux\r\na=rtcp-rsize\r\n" + *ice +
219
+ "a=fingerprint:sha-256 " + std::string(localFingerprint) + "\r\na=setup:actpass\r\n"
220
+ "a=rtpmap:111 opus/48000/2\r\na=fmtp:111 minptime=10;useinbandfec=1\r\n"
221
+ "a=msid:gea microphone\r\na=ssrc:" + std::to_string(ssrc) + " cname:gea-mic\r\n"
222
+ "a=ssrc:" + std::to_string(ssrc) + " msid:gea microphone\r\n";
223
+ }
224
+
225
+ inline std::optional<std::string> answer(const Offer& offer, std::string_view localIce,
226
+ std::string_view localFingerprint) {
227
+ const auto ice = localIceAttributes(localIce);
228
+ if (!ice || !fingerprint(localFingerprint) || offer.tracks.empty() || offer.tracks.size() > 2)
229
+ return std::nullopt;
230
+ std::string result = "v=0\r\no=- 1 1 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE";
231
+ for (const auto& track : offer.tracks) result += " " + track.mid;
232
+ result += "\r\n";
233
+ for (const auto& track : offer.tracks) {
234
+ const auto pt = std::to_string(track.payloadType);
235
+ result += "m=" + track.kind + " 9 UDP/TLS/RTP/SAVPF " + pt + "\r\nc=IN IP4 0.0.0.0\r\na=mid:" +
236
+ track.mid + "\r\na=recvonly\r\na=rtcp-mux\r\n" + *ice + "a=fingerprint:sha-256 " +
237
+ std::string(localFingerprint) + "\r\na=setup:active\r\na=rtpmap:" + pt + " " + track.codec + "\r\n";
238
+ if (track.reducedRtcp) result += "a=rtcp-rsize\r\n";
239
+ if (track.pli) result += "a=rtcp-fb:" + pt + " nack pli\r\n";
240
+ if (track.kind == "audio") result += "a=fmtp:" + pt + " minptime=10;useinbandfec=1\r\n";
241
+ }
242
+ return result;
243
+ }
244
+
245
+ } // namespace gea::host::rtc::receive