@geastack/host 0.1.10 → 0.1.12

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 +205 -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 +189 -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 +23 -0
  24. package/include/host/mjpeg_parser.h +126 -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,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
@@ -0,0 +1,170 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ #include <array>
5
+ #include <cstdint>
6
+ #include <optional>
7
+ #include <span>
8
+ #include <cstring>
9
+ #include "host/video_pixels.h"
10
+
11
+ namespace gea::host::rtc::rtp {
12
+
13
+ inline uint16_t read16(const uint8_t* bytes) {
14
+ return (uint16_t(bytes[0]) << 8) | bytes[1];
15
+ }
16
+
17
+ inline uint32_t read32(const uint8_t* bytes) {
18
+ return (uint32_t(read16(bytes)) << 16) | read16(bytes + 2);
19
+ }
20
+
21
+ inline void write32(uint8_t* bytes, uint32_t value) {
22
+ bytes[0] = uint8_t(value >> 24);
23
+ bytes[1] = uint8_t(value >> 16);
24
+ bytes[2] = uint8_t(value >> 8);
25
+ bytes[3] = uint8_t(value);
26
+ }
27
+
28
+ struct Packet {
29
+ std::span<const uint8_t> payload;
30
+ uint32_t ssrc = 0;
31
+ uint32_t timestamp = 0;
32
+ uint16_t sequence = 0;
33
+ uint8_t payloadType = 0;
34
+ bool marker = false;
35
+ };
36
+
37
+ // The caller MUST authenticate/decrypt SRTP first. Bounds cover RFC 3550's
38
+ // CSRC list, optional extension block and padding before exposing a payload.
39
+ inline std::optional<Packet> parse(std::span<const uint8_t> bytes) {
40
+ if (bytes.size() < 12 || bytes[0] >> 6 != 2) return std::nullopt;
41
+ // RFC 5761: this range is reserved for RTCP on a multiplexed transport.
42
+ if (bytes[1] >= 192 && bytes[1] <= 223) return std::nullopt;
43
+ size_t offset = 12 + 4 * (bytes[0] & 15);
44
+ if (offset > bytes.size()) return std::nullopt;
45
+ if (bytes[0] & 0x10) {
46
+ if (bytes.size() - offset < 4) return std::nullopt;
47
+ const size_t length = 4 + size_t(read16(bytes.data() + offset + 2)) * 4;
48
+ if (length > bytes.size() - offset) return std::nullopt;
49
+ offset += length;
50
+ }
51
+ size_t end = bytes.size();
52
+ if (bytes[0] & 0x20) {
53
+ const auto padding = bytes.back();
54
+ if (!padding || padding > end - offset) return std::nullopt;
55
+ end -= padding;
56
+ }
57
+ if (offset == end) return std::nullopt;
58
+ return Packet{bytes.subspan(offset, end - offset), read32(bytes.data() + 8),
59
+ read32(bytes.data() + 4), read16(bytes.data() + 2),
60
+ uint8_t(bytes[1] & 127), bool(bytes[1] & 128)};
61
+ }
62
+
63
+ // No delay for in-order traffic. Only a sequence gap starts a bounded wait.
64
+ // The callback runs synchronously; its packet spans must not escape it.
65
+ class Reorder {
66
+ public:
67
+ static constexpr size_t capacity = 64;
68
+ static constexpr size_t maxPacketBytes = 4096;
69
+ static constexpr uint64_t gapWaitMs = 30;
70
+
71
+ void reset() {
72
+ for (auto& slot : slots_) slot.clear();
73
+ queued_ = 0;
74
+ initialized_ = false;
75
+ }
76
+
77
+ template<class Deliver>
78
+ void push(std::span<const uint8_t> bytes, uint64_t nowMs, Deliver&& deliver) {
79
+ if (bytes.size() > maxPacketBytes) return;
80
+ const auto packet = parse(bytes);
81
+ if (!packet) return;
82
+ if (!initialized_) {
83
+ next_ = packet->sequence;
84
+ initialized_ = true;
85
+ }
86
+ const auto distance = uint16_t(packet->sequence - next_);
87
+ if (distance >= 0x8000) return; // Duplicate or late, including sequence wrap.
88
+ if (distance >= capacity) {
89
+ // Decoder overload or a large network loss: discard stale queued packets.
90
+ // The downstream assembler sees the sequence gap and requires a keyframe.
91
+ for (auto& slot : slots_) slot.clear();
92
+ queued_ = 0;
93
+ next_ = packet->sequence;
94
+ }
95
+ if (packet->sequence == next_) {
96
+ // The normal path is already ordered: deliver the caller's authenticated
97
+ // span directly, without copying or reserving a full packet window.
98
+ ++next_;
99
+ deliver(*packet);
100
+ poll(nowMs, deliver);
101
+ return;
102
+ }
103
+ auto& slot = slots_[packet->sequence % capacity];
104
+ if (!slot.bytes.empty()) return;
105
+ try { slot.bytes.assign(bytes.begin(), bytes.end()); }
106
+ catch (const std::bad_alloc&) { return; } // Packet loss, never a device abort.
107
+ slot.arrivedMs = nowMs;
108
+ ++queued_;
109
+ poll(nowMs, deliver);
110
+ }
111
+
112
+ template<class Deliver>
113
+ void poll(uint64_t nowMs, Deliver&& deliver) {
114
+ if (!initialized_) return;
115
+ // Almost all packets are already ordered. Do not scan 63 PSRAM-backed
116
+ // slots after every audio/video packet (or every transport timer tick)
117
+ // when there is no outstanding sequence gap.
118
+ while (queued_) {
119
+ auto& slot = slots_[next_ % capacity];
120
+ if (!slot.bytes.empty()) {
121
+ // Release the temporary PSRAM allocation after synchronous delivery;
122
+ // retaining capacity per sequence slot grows to half a megabyte across
123
+ // the two tracks even when no packets are currently out of order.
124
+ Slot::Bytes bytes;
125
+ bytes.swap(slot.bytes);
126
+ --queued_;
127
+ const auto packet = parse(std::span(bytes.data(), bytes.size()));
128
+ // The bounded window guarantees that this slot belongs to next_.
129
+ ++next_;
130
+ if (packet) deliver(*packet);
131
+ continue;
132
+ }
133
+ size_t nearest = capacity;
134
+ uint64_t earliest = nowMs;
135
+ for (size_t distance = 1; distance < capacity; ++distance) {
136
+ const auto& queued = slots_[uint16_t(next_ + distance) % capacity];
137
+ if (queued.bytes.empty()) continue;
138
+ if (nearest == capacity) nearest = distance;
139
+ if (queued.arrivedMs < earliest) earliest = queued.arrivedMs;
140
+ }
141
+ if (nearest == capacity || nowMs - earliest < gapWaitMs) return;
142
+ next_ = uint16_t(next_ + nearest);
143
+ }
144
+ }
145
+
146
+ private:
147
+ struct Slot {
148
+ // Only genuinely reordered packets own a buffer. The allocator explicitly
149
+ // uses PSRAM on ESP32, including for small packets below IDF's threshold.
150
+ using Bytes = std::vector<uint8_t, media::VideoAllocator<uint8_t>>;
151
+ Bytes bytes;
152
+ uint64_t arrivedMs = 0;
153
+ void clear() { Bytes{}.swap(bytes); arrivedMs = 0; }
154
+ };
155
+ std::array<Slot, capacity> slots_;
156
+ size_t queued_ = 0;
157
+ uint16_t next_ = 0;
158
+ bool initialized_ = false;
159
+ };
160
+
161
+ // RFC 4585 picture loss indication. Caller protects this with SRTCP before
162
+ // transmission. Reduced-size RTCP must have been negotiated for standalone PLI.
163
+ inline std::array<uint8_t, 12> pictureLossIndication(uint32_t sender, uint32_t media) {
164
+ std::array<uint8_t, 12> bytes{0x81, 206, 0, 2};
165
+ write32(bytes.data() + 4, sender);
166
+ write32(bytes.data() + 8, media);
167
+ return bytes;
168
+ }
169
+
170
+ } // namespace gea::host::rtc::rtp
@@ -0,0 +1,71 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include <string>
4
+ #include <string_view>
5
+ #include <vector>
6
+
7
+ namespace gea::host::rtc {
8
+ // RFC 7587: the RTP clock stays 48000/2. These receiver hints describe the
9
+ // actual PCM sink, avoiding decoding bandwidth the device cannot reproduce.
10
+ inline std::string opusPcmCapabilities(const std::string &sdp, int rate, int channels) {
11
+ const std::string newline = sdp.find("\r\n") != std::string::npos ? "\r\n" : "\n";
12
+ const bool terminated = !sdp.empty() && sdp.back() == '\n';
13
+ std::vector<std::string> lines;
14
+ for (std::size_t at = 0; at < sdp.size();) {
15
+ auto end = sdp.find('\n', at);
16
+ auto line = sdp.substr(at, end == std::string::npos ? end : end - at);
17
+ if (!line.empty() && line.back() == '\r') line.pop_back();
18
+ lines.push_back(std::move(line));
19
+ if (end == std::string::npos) break;
20
+ at = end + 1;
21
+ }
22
+ for (std::size_t start = 0; start < lines.size();) {
23
+ if (lines[start].rfind("m=audio ", 0) != 0) { ++start; continue; }
24
+ std::size_t end = start + 1;
25
+ while (end < lines.size() && lines[end].rfind("m=", 0) != 0) ++end;
26
+ std::vector<std::string> payloads;
27
+ for (auto i = start + 1; i < end; ++i) {
28
+ if (lines[i].rfind("a=rtpmap:", 0) != 0) continue;
29
+ const auto space = lines[i].find(' ');
30
+ if (space != std::string::npos && lines[i].substr(space + 1) == "opus/48000/2")
31
+ payloads.push_back(lines[i].substr(9, space - 9));
32
+ }
33
+ for (const auto &payload : payloads) {
34
+ const auto prefix = "a=fmtp:" + payload + " ";
35
+ std::size_t index = start + 1;
36
+ while (index < end && lines[index].rfind(prefix, 0) != 0) ++index;
37
+ std::string parameters;
38
+ if (index < end) {
39
+ const auto existing = lines[index].substr(prefix.size());
40
+ for (std::size_t at = 0; at < existing.size();) {
41
+ const auto next = existing.find(';', at);
42
+ auto parameter = existing.substr(at, next == std::string::npos ? next : next - at);
43
+ const auto first = parameter.find_first_not_of(" \t");
44
+ if (first != std::string::npos) parameter.erase(0, first);
45
+ const auto equal = parameter.find('=');
46
+ auto key = parameter.substr(0, equal);
47
+ const auto last = key.find_last_not_of(" \t");
48
+ if (last != std::string::npos) key.resize(last + 1);
49
+ if (!parameter.empty() && key != "maxplaybackrate" && key != "sprop-maxcapturerate" &&
50
+ key != "stereo" && key != "sprop-stereo") parameters += parameter + ";";
51
+ if (next == std::string::npos) break;
52
+ at = next + 1;
53
+ }
54
+ }
55
+ parameters += "maxplaybackrate=" + std::to_string(rate) +
56
+ ";sprop-maxcapturerate=" + std::to_string(rate) +
57
+ ";stereo=" + (channels == 1 ? "0" : "1") +
58
+ ";sprop-stereo=" + (channels == 1 ? "0" : "1");
59
+ if (index < end) lines[index] = prefix + parameters;
60
+ else { lines.insert(lines.begin() + end, prefix + parameters); ++end; }
61
+ }
62
+ start = end;
63
+ }
64
+ std::string result;
65
+ for (std::size_t i = 0; i < lines.size(); ++i) {
66
+ result += lines[i];
67
+ if (i + 1 < lines.size() || terminated) result += newline;
68
+ }
69
+ return result;
70
+ }
71
+ } // namespace gea::host::rtc
@@ -0,0 +1,166 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include "host/media.h"
4
+ #include "host/rtc_ice_candidate.h"
5
+ #include <cstdint>
6
+ #include <functional>
7
+ #include <memory>
8
+ #include <optional>
9
+ #include <stdexcept>
10
+ #include <string>
11
+ #include <utility>
12
+ #include <vector>
13
+
14
+ namespace gea::host {
15
+ namespace rtc {
16
+ struct PeerLifetime;
17
+ std::shared_ptr<PeerLifetime> retain_peer(uint32_t handle);
18
+ std::shared_ptr<PeerLifetime> retain_object(uint32_t handle);
19
+ }
20
+ struct RTCIceServer {
21
+ std::vector<std::string> urls;
22
+ std::string username;
23
+ std::string credential;
24
+ };
25
+ struct RTCConfiguration {
26
+ std::vector<RTCIceServer> iceServers;
27
+ std::string iceTransportPolicy = "all";
28
+ };
29
+ struct RTCSessionDescription {
30
+ std::string type;
31
+ std::string sdp;
32
+ };
33
+
34
+ // Description getters preserve object identity until the peer replaces its
35
+ // SDP snapshot. JSON dictionaries are separate, mutable copies.
36
+ class RTCSessionDescriptionObject {
37
+ public:
38
+ RTCSessionDescriptionObject() = default;
39
+ explicit RTCSessionDescriptionObject(RTCSessionDescription fields)
40
+ : fields_(std::make_shared<RTCSessionDescription>(std::move(fields))) { validateType(fields_->type); }
41
+ std::string type() const { return fields().type; }
42
+ std::string sdp() const { return fields().sdp; }
43
+ const RTCSessionDescription &fields() const {
44
+ if (!fields_) throw std::logic_error("null RTCSessionDescription");
45
+ return *fields_;
46
+ }
47
+ explicit operator bool() const { return static_cast<bool>(fields_); }
48
+ bool operator==(const RTCSessionDescriptionObject &other) const { return fields_ == other.fields_; }
49
+ bool operator==(std::nullptr_t) const { return !fields_; }
50
+
51
+ private:
52
+ static void validateType(const std::string &type) {
53
+ if (type != "offer" && type != "answer" && type != "pranswer" && type != "rollback")
54
+ throw std::invalid_argument("invalid RTCSessionDescription type");
55
+ }
56
+ std::shared_ptr<const RTCSessionDescription> fields_;
57
+ };
58
+ struct RTCDataChannelInit {
59
+ bool ordered = true;
60
+ std::optional<double> maxPacketLifeTime;
61
+ std::optional<double> maxRetransmits;
62
+ std::string protocol;
63
+ bool negotiated = false;
64
+ std::optional<double> id;
65
+ };
66
+ struct RTCRtpTransceiverInit {
67
+ std::string direction = "sendrecv";
68
+ };
69
+ class RTCDataChannel {
70
+ public:
71
+ uint32_t nativeHandle = 0;
72
+ RTCDataChannel() = default;
73
+ explicit RTCDataChannel(uint32_t handle) : nativeHandle(handle), lifetime_(rtc::retain_object(handle)) {}
74
+ explicit operator bool() const { return nativeHandle != 0; }
75
+ bool operator==(std::nullptr_t) const { return nativeHandle == 0; }
76
+ bool operator!=(std::nullptr_t) const { return nativeHandle != 0; }
77
+ bool operator==(const RTCDataChannel& other) const { return nativeHandle == other.nativeHandle; }
78
+ std::string label() const;
79
+ std::string protocol() const;
80
+ std::string readyState() const;
81
+ std::string binaryType() const;
82
+ void setBinaryType(const std::string&) const;
83
+ bool ordered() const;
84
+ std::optional<double> id() const;
85
+ std::optional<double> maxRetransmits() const;
86
+ std::optional<double> maxPacketLifeTime() const;
87
+ double bufferedAmount() const;
88
+ double bufferedAmountLowThreshold() const;
89
+ void setBufferedAmountLowThreshold(double) const;
90
+ void send(const std::string&) const;
91
+ void send(const std::vector<uint8_t>&) const;
92
+ void close() const;
93
+ private:
94
+ std::shared_ptr<rtc::PeerLifetime> lifetime_;
95
+ };
96
+ class RTCRtpSender {
97
+ public:
98
+ uint32_t nativeHandle = 0;
99
+ RTCRtpSender() = default;
100
+ explicit RTCRtpSender(uint32_t handle) : nativeHandle(handle), lifetime_(rtc::retain_object(handle)) {}
101
+ std::optional<MediaStreamTrack> track() const;
102
+ void replaceTrack(MediaStreamTrack) const;
103
+ void replaceTrack() const;
104
+ private:
105
+ std::shared_ptr<rtc::PeerLifetime> lifetime_;
106
+ };
107
+ class RTCRtpReceiver {
108
+ public:
109
+ uint32_t nativeHandle = 0;
110
+ RTCRtpReceiver() = default;
111
+ explicit RTCRtpReceiver(uint32_t handle) : nativeHandle(handle), lifetime_(rtc::retain_object(handle)) {}
112
+ std::optional<MediaStreamTrack> track() const;
113
+ private:
114
+ std::shared_ptr<rtc::PeerLifetime> lifetime_;
115
+ };
116
+ class RTCRtpTransceiver {
117
+ public:
118
+ uint32_t nativeHandle = 0;
119
+ RTCRtpTransceiver() = default;
120
+ explicit RTCRtpTransceiver(uint32_t handle) : nativeHandle(handle), lifetime_(rtc::retain_object(handle)) {}
121
+ RTCRtpSender sender() const { return RTCRtpSender(nativeHandle); }
122
+ RTCRtpReceiver receiver() const { return RTCRtpReceiver(nativeHandle); }
123
+ std::optional<std::string> mid() const;
124
+ std::string direction() const;
125
+ void setDirection(const std::string&) const;
126
+ std::optional<std::string> currentDirection() const;
127
+ bool stopped() const;
128
+ void stop() const;
129
+ private:
130
+ std::shared_ptr<rtc::PeerLifetime> lifetime_;
131
+ };
132
+ class RTCTrackEvent {
133
+ public:
134
+ RTCTrackEvent() = default;
135
+ RTCTrackEvent(MediaStreamTrack track, RTCRtpTransceiver transceiver, std::vector<MediaStream> streams)
136
+ : fields_(std::make_shared<const Fields>(Fields{track, transceiver, std::move(streams)})) {}
137
+ MediaStreamTrack track() const { return fields().track; }
138
+ RTCRtpTransceiver transceiver() const { return fields().transceiver; }
139
+ RTCRtpReceiver receiver() const { return transceiver().receiver(); }
140
+ const std::vector<MediaStream>& streams() const { return fields().streams; }
141
+ bool operator==(const RTCTrackEvent& other) const { return fields_ == other.fields_; }
142
+ private:
143
+ struct Fields {
144
+ MediaStreamTrack track;
145
+ RTCRtpTransceiver transceiver;
146
+ std::vector<MediaStream> streams;
147
+ };
148
+ const Fields& fields() const {
149
+ if (!fields_) throw std::logic_error("null RTCTrackEvent");
150
+ return *fields_;
151
+ }
152
+ std::shared_ptr<const Fields> fields_;
153
+ };
154
+ namespace rtc {
155
+ struct DataChannelCallbacks {
156
+ std::function<void()> on_open, on_close, on_buffered_amount_low;
157
+ std::function<void(const std::string&)> on_error;
158
+ std::function<void(const std::vector<uint8_t>&, bool)> on_message;
159
+ };
160
+ DataChannelCallbacks& channel_callbacks(uint32_t channel);
161
+ void enqueue_channel_open(uint32_t peer, const std::string& label, uint16_t stream);
162
+ void enqueue_channel_close(uint32_t peer, uint16_t stream);
163
+ void enqueue_channel_message(uint32_t peer, uint16_t stream, const uint8_t* bytes, size_t size, bool text);
164
+ RTCConfiguration configuration(uint32_t peer);
165
+ }
166
+ }