@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,103 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ #include "host/media.h"
5
+ #include "host/worker.h"
6
+ #include <functional>
7
+ #include <memory>
8
+ #include <string>
9
+ #include <unordered_map>
10
+ #include <vector>
11
+
12
+ namespace gea::host {
13
+ using workers::MessagePort;
14
+ struct AudioContext;
15
+ struct AudioDestinationNode;
16
+ struct AudioDestinationProperty;
17
+ class AudioWorkletNode;
18
+
19
+ using AudioWorkletChannels = std::vector<std::vector<float>>;
20
+ using AudioWorkletBus = std::vector<AudioWorkletChannels>;
21
+ using AudioWorkletParameters = std::unordered_map<std::string, std::vector<float>>;
22
+
23
+ namespace audio_worklet {
24
+ struct ContextState;
25
+ struct NodeState;
26
+ struct NodeControl;
27
+ constexpr std::size_t renderQuantum = 128;
28
+ std::shared_ptr<ContextState> createContext(double sampleRate);
29
+ double contextBaseLatency(const std::shared_ptr<ContextState>& context);
30
+ double contextTime(const std::shared_ptr<ContextState>&);
31
+ std::string contextState(const std::shared_ptr<ContextState>&);
32
+ void resume(const std::shared_ptr<ContextState>&);
33
+ void suspend(const std::shared_ptr<ContextState>&);
34
+ void close(const std::shared_ptr<ContextState>&);
35
+ // Module entries and processor factories are generated C++; no JS evaluator.
36
+ void registerModule(const std::string& url, std::function<void()> entry);
37
+ double sampleRate();
38
+ double currentTime();
39
+ double currentFrame();
40
+ workers::MessagePort processorPort();
41
+ void flushOutput();
42
+ }
43
+
44
+ class AudioWorkletProcessor {
45
+ public:
46
+ AudioWorkletProcessor();
47
+ virtual ~AudioWorkletProcessor() = default;
48
+ workers::MessagePort port;
49
+ virtual bool process(const AudioWorkletBus& inputs, AudioWorkletBus& outputs,
50
+ const AudioWorkletParameters& parameters) { return false; }
51
+ };
52
+
53
+ namespace audio_worklet {
54
+ using ProcessorFactory = std::function<std::shared_ptr<AudioWorkletProcessor>()>;
55
+ void registerProcessor(const std::string& name, ProcessorFactory factory);
56
+ }
57
+
58
+ class AudioWorklet {
59
+ public:
60
+ AudioWorklet() = default;
61
+ explicit AudioWorklet(std::shared_ptr<audio_worklet::ContextState> context) : context_(std::move(context)) {}
62
+ void addModule(const std::string& url) const;
63
+ private:
64
+ std::shared_ptr<audio_worklet::ContextState> context_;
65
+ };
66
+
67
+ struct AudioWorkletNodeOptions {
68
+ unsigned numberOfInputs = 1;
69
+ unsigned numberOfOutputs = 1;
70
+ unsigned channelCount = 1;
71
+ };
72
+
73
+ class AudioWorkletNode {
74
+ public:
75
+ AudioWorkletNode() = default;
76
+ AudioWorkletNode(const AudioContext& context, const std::string& name);
77
+ AudioWorkletNode(const AudioContext& context, const std::string& name, const AudioWorkletNodeOptions& options);
78
+ workers::MessagePort port;
79
+ AudioDestinationNode connect(AudioDestinationNode destination) const;
80
+ AudioDestinationNode connect(AudioDestinationProperty destination) const;
81
+ void disconnect() const;
82
+ void setOnProcessorError(std::function<void(const std::string&)> callback) const;
83
+ explicit operator bool() const { return static_cast<bool>(state_); }
84
+ bool operator==(std::nullptr_t) const { return !state_; }
85
+ private:
86
+ std::shared_ptr<audio_worklet::NodeState> state_;
87
+ std::shared_ptr<audio_worklet::NodeControl> control_;
88
+ friend class MediaStreamAudioSourceNode;
89
+ };
90
+
91
+ class MediaStreamAudioSourceNode {
92
+ public:
93
+ MediaStreamAudioSourceNode() = default;
94
+ explicit operator bool() const { return static_cast<bool>(state_); }
95
+ bool operator==(std::nullptr_t) const { return !state_; }
96
+ MediaStreamAudioSourceNode(std::shared_ptr<audio_worklet::ContextState> context, MediaStream stream);
97
+ AudioWorkletNode connect(AudioWorkletNode destination) const;
98
+ void disconnect() const;
99
+ private:
100
+ struct State;
101
+ std::shared_ptr<State> state_;
102
+ };
103
+ } // namespace gea::host
@@ -0,0 +1,170 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include <algorithm>
4
+ #include <cstdint>
5
+ #include <cstddef>
6
+
7
+ namespace gea::host::rtc::h264 {
8
+ struct Metadata {
9
+ int width = 0, height = 0, left = 0, top = 0;
10
+ int visibleWidth = 0, visibleHeight = 0;
11
+ bool fullRange = false, bt709 = false;
12
+ };
13
+
14
+ // Read RBSP in place, skipping emulation-prevention bytes without another
15
+ // compressed-frame allocation. Only progressive 8-bit baseline streams are accepted.
16
+ class Bits {
17
+ public:
18
+ Bits(const std::uint8_t *data, std::size_t length) : data_(data), length_(length) {}
19
+ std::uint32_t read(unsigned count) {
20
+ if (count > 32) { ok = false; return 0; }
21
+ std::uint32_t value = 0;
22
+ while (count--) {
23
+ if (!left_) {
24
+ if (position_ >= length_) { ok = false; return 0; }
25
+ byte_ = data_[position_++];
26
+ if (zeros_ >= 2 && byte_ == 3) {
27
+ if (position_ >= length_ || data_[position_] > 3) { ok = false; return 0; }
28
+ byte_ = data_[position_++];
29
+ zeros_ = 0;
30
+ }
31
+ zeros_ = byte_ == 0 ? zeros_ + 1 : 0;
32
+ left_ = 8;
33
+ }
34
+ value = (value << 1) | ((byte_ >> --left_) & 1);
35
+ }
36
+ return value;
37
+ }
38
+ std::uint32_t ue() {
39
+ unsigned zeros = 0;
40
+ while (ok && !read(1)) {
41
+ if (++zeros > 30) { ok = false; return 0; }
42
+ }
43
+ return ok ? ((1u << zeros) - 1) + read(zeros) : 0;
44
+ }
45
+ bool ok = true;
46
+ private:
47
+ const std::uint8_t *data_;
48
+ std::size_t length_, position_ = 0;
49
+ unsigned byte_ = 0, left_ = 0, zeros_ = 0;
50
+ };
51
+
52
+ inline bool parseSps(const std::uint8_t *data, std::size_t length, Metadata &out) {
53
+ Bits bits(data, length);
54
+ if (bits.read(8) != 66) return false; // constrained/baseline, 8-bit 4:2:0
55
+ bits.read(8); bits.read(8); // constraint flags, level
56
+ if (bits.ue() != 0) return false; // one SPS/PPS set per stream
57
+ if (bits.ue() > 12) return false; // log2_max_frame_num_minus4
58
+ const auto poc = bits.ue();
59
+ if (poc == 0) { if (bits.ue() > 12) return false; }
60
+ else if (poc == 1) {
61
+ bits.read(1); bits.ue(); bits.ue(); // signed Exp-Golomb values have the same extent
62
+ const auto cycle = bits.ue();
63
+ if (cycle > 255) return false;
64
+ for (unsigned i = 0; i < cycle; ++i) bits.ue();
65
+ } else if (poc != 2) return false;
66
+ if (bits.ue() > 16) return false; // max_num_ref_frames
67
+ bits.read(1); // gaps_in_frame_num_value_allowed_flag
68
+ const auto mbWidth = bits.ue(), mbHeight = bits.ue();
69
+ if (mbWidth > 63 || mbHeight > 63 || bits.read(1) != 1) return false;
70
+ bits.read(1); // direct_8x8_inference_flag
71
+ std::uint32_t left = 0, right = 0, top = 0, bottom = 0;
72
+ if (bits.read(1)) { left = bits.ue(); right = bits.ue(); top = bits.ue(); bottom = bits.ue(); }
73
+ const int width = (mbWidth + 1) * 16, height = (mbHeight + 1) * 16;
74
+ if (!bits.ok || left > 512 || right > 512 || top > 512 || bottom > 512 ||
75
+ width <= 2 * int(left + right) || height <= 2 * int(top + bottom))
76
+ return false;
77
+ Metadata next{width, height, int(left * 2), int(top * 2),
78
+ width - int(2 * (left + right)), height - int(2 * (top + bottom))};
79
+ if (bits.read(1)) { // vui_parameters_present_flag; colour fields precede timing/HRD
80
+ if (bits.read(1) && bits.read(8) == 255) { bits.read(16); bits.read(16); }
81
+ if (bits.read(1)) bits.read(1); // overscan
82
+ if (bits.read(1)) {
83
+ bits.read(3); next.fullRange = bits.read(1);
84
+ if (bits.read(1)) {
85
+ bits.read(8); bits.read(8); // primaries, transfer characteristics
86
+ const auto matrix = bits.read(8);
87
+ if (matrix != 1 && matrix != 2 && matrix != 5 && matrix != 6) return false;
88
+ next.bt709 = matrix == 1;
89
+ }
90
+ }
91
+ }
92
+ if (!bits.ok) return false;
93
+ out = next;
94
+ return true;
95
+ }
96
+
97
+ inline std::size_t startCode(const std::uint8_t *data, std::size_t length, std::size_t from, unsigned &prefix) {
98
+ for (std::size_t i = from; i + 3 <= length; ++i) {
99
+ if (data[i] || data[i + 1]) continue;
100
+ if (data[i + 2] == 1) { prefix = 3; return i; }
101
+ if (i + 4 <= length && data[i + 2] == 0 && data[i + 3] == 1) { prefix = 4; return i; }
102
+ }
103
+ prefix = 0;
104
+ return length;
105
+ }
106
+
107
+ inline bool inspectAccessUnit(const std::uint8_t *data, std::size_t length, Metadata &metadata) {
108
+ unsigned prefix = 0;
109
+ std::size_t position = startCode(data, length, 0, prefix);
110
+ if (position == length) return false;
111
+ for (std::size_t i = 0; i < position; ++i) if (data[i]) return false;
112
+ while (position < length) {
113
+ const auto nal = position + prefix;
114
+ unsigned nextPrefix = 0;
115
+ const auto next = startCode(data, length, nal, nextPrefix);
116
+ if (nal >= next || (data[nal] & 128)) return false;
117
+ const auto type = data[nal] & 31;
118
+ if (type == 7 && !parseSps(data + nal + 1, next - nal - 1, metadata)) return false;
119
+ if (type == 8) {
120
+ Bits bits(data + nal + 1, next - nal - 1);
121
+ if (bits.ue() != 0 || bits.ue() != 0 || !bits.ok) return false;
122
+ }
123
+ if (type == 1 || type == 5) {
124
+ Bits bits(data + nal + 1, next - nal - 1);
125
+ bits.ue(); bits.ue();
126
+ if (bits.ue() != 0 || !bits.ok || !metadata.width) return false;
127
+ }
128
+ position = next; prefix = nextPrefix;
129
+ }
130
+ return metadata.width != 0;
131
+ }
132
+
133
+ // Four output pixels share one U/V pair. The frame stays I420 inside the
134
+ // reference decoder; only visible pixels are converted into the owned image.
135
+ inline void convertI420(const std::uint8_t *source, const Metadata &meta, std::uint16_t *output) {
136
+ const int visibleWidth = meta.visibleWidth, visibleHeight = meta.visibleHeight;
137
+ const int stride = meta.width, chromaStride = stride / 2;
138
+ const auto *uPlane = source + meta.width * meta.height;
139
+ const auto *vPlane = uPlane + (meta.width * meta.height) / 4;
140
+ const int yScale = meta.fullRange ? 256 : 298;
141
+ const int yBias = meta.fullRange ? 0 : 16;
142
+ const int rV = meta.bt709 ? (meta.fullRange ? 403 : 459) : (meta.fullRange ? 359 : 409);
143
+ const int gU = meta.bt709 ? (meta.fullRange ? 48 : 55) : (meta.fullRange ? 88 : 100);
144
+ const int gV = meta.bt709 ? (meta.fullRange ? 120 : 136) : (meta.fullRange ? 183 : 208);
145
+ const int bU = meta.bt709 ? (meta.fullRange ? 475 : 541) : (meta.fullRange ? 454 : 516);
146
+ for (int y = 0; y < visibleHeight; y += 2) {
147
+ const auto *row0 = source + (meta.top + y) * stride + meta.left;
148
+ const auto *row1 = row0 + stride;
149
+ const int chroma = ((meta.top + y) / 2) * chromaStride + meta.left / 2;
150
+ auto *dst0 = output + y * visibleWidth;
151
+ auto *dst1 = dst0 + visibleWidth;
152
+ for (int x = 0; x < visibleWidth; x += 2) {
153
+ const int u = int(uPlane[chroma + x / 2]) - 128;
154
+ const int v = int(vPlane[chroma + x / 2]) - 128;
155
+ const int red = rV * v, green = -gU * u - gV * v, blue = bU * u;
156
+ const auto pack = [&](int luma) {
157
+ const int value = yScale * (luma - yBias) + 128;
158
+ const auto r = std::clamp((value + red) >> 8, 0, 255);
159
+ const auto g = std::clamp((value + green) >> 8, 0, 255);
160
+ const auto b = std::clamp((value + blue) >> 8, 0, 255);
161
+ return static_cast<std::uint16_t>(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3));
162
+ };
163
+ dst0[x] = pack(row0[x]); dst0[x + 1] = pack(row0[x + 1]);
164
+ dst1[x] = pack(row1[x]); dst1[x + 1] = pack(row1[x + 1]);
165
+ }
166
+ }
167
+ }
168
+
169
+
170
+ } // namespace gea::host::rtc::h264
@@ -4,8 +4,10 @@
4
4
  #include <cstddef>
5
5
  #include <cstdint>
6
6
  #include <functional>
7
+ #include <memory>
7
8
  #include <string>
8
9
  #include <vector>
10
+ #include "host/video_pixels.h"
9
11
 
10
12
  namespace gea::host {
11
13
 
@@ -53,7 +55,12 @@ class MediaStream {
53
55
 
54
56
  std::string id() const;
55
57
  std::vector<MediaStreamTrack> getAudioTracks() const;
58
+ std::vector<MediaStreamTrack> getVideoTracks() const;
56
59
  std::vector<MediaStreamTrack> getTracks() const;
60
+ MediaStreamTrack getTrackById(const std::string &id) const;
61
+ bool active() const;
62
+ void addTrack(MediaStreamTrack track) const;
63
+ void removeTrack(MediaStreamTrack track) const;
57
64
  };
58
65
 
59
66
  struct GeaAudioBlob {
@@ -121,12 +128,72 @@ class MediaRecorder {
121
128
  namespace media {
122
129
 
123
130
  NativeMediaStreamHandle create_stream();
131
+ // Stream membership is independent of the capture/receiver that owns a track.
132
+ NativeMediaStreamHandle create_stream_from_tracks(const std::vector<MediaStreamTrack> &tracks);
133
+ inline MediaStream create_media_stream() { return MediaStream(create_stream_from_tracks({})); }
134
+ inline MediaStream create_media_stream(const MediaStream &source) {
135
+ return MediaStream(create_stream_from_tracks(source.getTracks()));
136
+ }
137
+ template <typename Tracks>
138
+ MediaStream create_media_stream(const Tracks &tracks) {
139
+ if constexpr (requires { tracks.has_value(); *tracks; }) {
140
+ return tracks.has_value() ? create_media_stream(*tracks) : create_media_stream();
141
+ } else if constexpr (requires { tracks.size(); tracks.at(0); }) {
142
+ std::vector<MediaStreamTrack> items;
143
+ items.reserve(tracks.size());
144
+ for (std::size_t i = 0; i < tracks.size(); ++i) items.push_back(tracks.at(i));
145
+ return MediaStream(create_stream_from_tracks(items));
146
+ } else if constexpr (requires { tracks.get(); *tracks; }) {
147
+ return tracks.get() ? create_media_stream(*tracks) : create_media_stream();
148
+ } else {
149
+ static_assert(sizeof(Tracks) == 0, "MediaStream initializer must be a stream or a track sequence");
150
+ }
151
+ }
152
+ // Received RTP audio must never attach to the microphone capture driver.
153
+ NativeMediaStreamHandle create_remote_stream();
154
+ NativeMediaStreamHandle create_remote_video_stream();
124
155
  void destroy_stream(NativeMediaStreamHandle handle);
125
156
  NativeMediaTrackHandle stream_audio_track(NativeMediaStreamHandle handle);
126
157
 
158
+ // Decoders publish ownership once. Every sink sees the newest immutable frame;
159
+ // a slow renderer cannot build a playback backlog or consume another sink's frame.
160
+ // RGB565 is logical host-endian unless panelEndian is set by a decoder for
161
+ // a matching embedded display. Other consumers normalize before conversion.
162
+ struct VideoFrame {
163
+ std::uint32_t width = 0, height = 0;
164
+ std::uint32_t timestampMs = 0;
165
+ std::uint64_t sequence = 0;
166
+ bool panelEndian = false;
167
+ VideoPixels rgb565;
168
+ };
169
+ bool publish_video_frame(NativeMediaTrackHandle handle, std::shared_ptr<VideoFrame> frame);
170
+ std::shared_ptr<const VideoFrame> latest_video_frame(NativeMediaTrackHandle handle);
171
+
127
172
  void track_inject_pcm(NativeMediaTrackHandle handle, const std::int16_t *samples, std::size_t count);
128
173
  std::size_t track_read_pcm(NativeMediaTrackHandle handle, std::int16_t *samples, std::size_t max_samples);
129
174
 
175
+ // Each sink gets its own cursor into the bounded track buffer. A new sink
176
+ // starts at live audio, not at samples retained for an existing consumer.
177
+ class TrackPcmReader {
178
+ public:
179
+ explicit TrackPcmReader(NativeMediaTrackHandle track, bool includeBuffered = false);
180
+ ~TrackPcmReader();
181
+ TrackPcmReader(const TrackPcmReader &) = delete;
182
+ TrackPcmReader &operator=(const TrackPcmReader &) = delete;
183
+ TrackPcmReader(TrackPcmReader &&other) noexcept;
184
+ TrackPcmReader &operator=(TrackPcmReader &&other) noexcept;
185
+ std::size_t read(std::int16_t *samples, std::size_t count);
186
+ std::uint64_t droppedSamples() const;
187
+ std::size_t pendingSamples() const;
188
+ void beginDrain();
189
+ void discardBuffered();
190
+
191
+ private:
192
+ void release();
193
+ NativeMediaTrackHandle track_ = 0;
194
+ std::uint64_t reader_ = 0;
195
+ };
196
+
130
197
  NativeMediaStreamHandle get_user_media_audio();
131
198
  NativeMediaRecorderHandle create_recorder(NativeMediaStreamHandle stream, const std::string &path, const std::string &mimeType);
132
199
  std::string recorder_state(NativeMediaRecorderHandle handle);
@@ -0,0 +1,23 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include "host/media.h"
4
+ #include <memory>
5
+ #include <string>
6
+
7
+ namespace gea::host::video {
8
+ // Network and optional JPEG decoding stay in native workers. Multipart RGB565
9
+ // writes directly into pooled pixels. The UI receives only the
10
+ // newest immutable RGB565 frame through the same media sink as WebRTC.
11
+ class MjpegStream {
12
+ public:
13
+ explicit MjpegStream(const std::string& url);
14
+ ~MjpegStream();
15
+ MjpegStream(const MjpegStream&) = delete;
16
+ MjpegStream& operator=(const MjpegStream&) = delete;
17
+ MediaStream stream() const;
18
+ void stop();
19
+ private:
20
+ struct State;
21
+ std::shared_ptr<State> state_;
22
+ };
23
+ } // namespace gea::host::video
@@ -0,0 +1,126 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include "host/video_frame_pool.h"
4
+ #include <bit>
5
+ #include <charconv>
6
+ #include <functional>
7
+ #include <span>
8
+ #include <string>
9
+ #include <string_view>
10
+ #include <vector>
11
+
12
+ namespace gea::host::video {
13
+ using JpegBytes = std::vector<uint8_t, media::VideoAllocator<uint8_t>>;
14
+ struct JpegPacket {
15
+ JpegBytes bytes;
16
+ uint32_t timestampMs = 0;
17
+ // Raw transport writes directly into the final pooled pixel allocation.
18
+ std::shared_ptr<media::VideoFrame> rawFrame;
19
+ };
20
+
21
+ // Length-delimited multipart parsing survives arbitrary TCP fragmentation.
22
+ // Never search the JPEG body for boundaries or allocate from untrusted sizes.
23
+ class MjpegParser {
24
+ public:
25
+ bool push(std::span<const uint8_t> bytes, const std::function<void(JpegPacket)>& emit) {
26
+ while (!bytes.empty()) {
27
+ if (remaining_) {
28
+ const auto count = std::min(remaining_, bytes.size());
29
+ if (format_ == Format::Jpeg) {
30
+ packet_.bytes.insert(packet_.bytes.end(), bytes.begin(), bytes.begin() + count);
31
+ } else if (packet_.rawFrame) {
32
+ std::memcpy(reinterpret_cast<uint8_t*>(packet_.rawFrame->rgb565.data()) + length_ - remaining_,
33
+ bytes.data(), count);
34
+ }
35
+ bytes = bytes.subspan(count);
36
+ remaining_ -= count;
37
+ if (!remaining_) {
38
+ if (format_ == Format::Jpeg) {
39
+ const auto& jpeg = packet_.bytes;
40
+ if (jpeg.size() < 4 || jpeg[0] != 0xff || jpeg[1] != 0xd8 ||
41
+ jpeg[jpeg.size() - 2] != 0xff || jpeg.back() != 0xd9) return false;
42
+ }
43
+ // Exhausted pool means a slow sink: consume/drop this whole picture,
44
+ // never overwrite a published buffer or grow a frame backlog.
45
+ if (format_ == Format::Jpeg || packet_.rawFrame) emit(std::move(packet_));
46
+ packet_ = {};
47
+ length_ = width_ = height_ = 0;
48
+ format_ = Format::None;
49
+ inHeaders_ = false;
50
+ }
51
+ continue;
52
+ }
53
+ const auto byte = bytes.front();
54
+ bytes = bytes.subspan(1);
55
+ if (line_.size() >= 1024 || ++headerBytes_ > 2048) return false;
56
+ line_ += char(byte);
57
+ if (byte != '\n') continue;
58
+ if (line_.size() < 2 || line_[line_.size() - 2] != '\r') return false;
59
+ line_.resize(line_.size() - 2);
60
+ if (line_.empty()) {
61
+ if (inHeaders_) {
62
+ if (!length_ || format_ == Format::None) return false;
63
+ if (format_ == Format::Jpeg) {
64
+ if (length_ > 65536) return false;
65
+ packet_.bytes.reserve(length_);
66
+ } else {
67
+ if (!width_ || !height_ || length_ != size_t(width_) * height_ * 2) return false;
68
+ packet_.rawFrame = frames_.acquire(width_, height_);
69
+ if (packet_.rawFrame) {
70
+ packet_.rawFrame->timestampMs = packet_.timestampMs;
71
+ packet_.rawFrame->panelEndian = (format_ == Format::Rgb565Be) !=
72
+ (std::endian::native == std::endian::big);
73
+ }
74
+ }
75
+ remaining_ = length_;
76
+ headerBytes_ = 0;
77
+ }
78
+ } else if (!inHeaders_) {
79
+ if (boundary_.empty()) {
80
+ if (!line_.starts_with("--") || line_.size() < 3 || line_.size() > 72) return false;
81
+ boundary_ = line_;
82
+ }
83
+ if (line_ != boundary_) return false;
84
+ inHeaders_ = true;
85
+ } else {
86
+ const auto colon = line_.find(':');
87
+ if (colon == line_.npos) return false;
88
+ auto name = line_.substr(0, colon);
89
+ for (auto& c : name) if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
90
+ auto value = std::string_view(line_).substr(colon + 1);
91
+ while (!value.empty() && value.front() == ' ') value.remove_prefix(1);
92
+ if (name == "content-length" || name == "x-timestamp-ms" || name == "x-width" || name == "x-height") {
93
+ uint32_t number = 0;
94
+ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), number);
95
+ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size()) return false;
96
+ if (name == "content-length") {
97
+ if (length_ || number < 4 || number > 512 * 512 * 2) return false;
98
+ length_ = number;
99
+ } else if (name == "x-width" || name == "x-height") {
100
+ auto& dimension = name == "x-width" ? width_ : height_;
101
+ if (dimension || !number || number > 512) return false;
102
+ dimension = number;
103
+ } else packet_.timestampMs = number;
104
+ } else if (name == "content-type") {
105
+ if (format_ != Format::None) return false;
106
+ if (value == "image/jpeg") format_ = Format::Jpeg;
107
+ else if (value == "application/x-rgb565-be") format_ = Format::Rgb565Be;
108
+ else if (value == "application/x-rgb565-le") format_ = Format::Rgb565Le;
109
+ else return false;
110
+ }
111
+ }
112
+ line_.clear();
113
+ }
114
+ return true;
115
+ }
116
+ private:
117
+ enum class Format { None, Jpeg, Rgb565Le, Rgb565Be };
118
+ std::string line_, boundary_;
119
+ JpegPacket packet_;
120
+ media::VideoFramePool frames_;
121
+ uint32_t width_ = 0, height_ = 0;
122
+ size_t remaining_ = 0, length_ = 0, headerBytes_ = 0;
123
+ bool inHeaders_ = false;
124
+ Format format_ = Format::None;
125
+ };
126
+ } // namespace gea::host::video
@@ -0,0 +1,122 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ #include <algorithm>
5
+ #include <cstdint>
6
+ #include <stdexcept>
7
+ #include <string>
8
+ #include <vector>
9
+ #include <memory>
10
+ #include <numeric>
11
+ #ifdef ESP_PLATFORM
12
+ #include "esp_heap_caps.h"
13
+ #endif
14
+
15
+ namespace gea::host::pcm {
16
+
17
+ // Small deque blocks would otherwise prefer internal RAM on ESP-IDF. Audio
18
+ // queued from a faster-than-realtime producer must not starve I2S DMA memory.
19
+ template <typename T>
20
+ struct QueueAllocator {
21
+ using value_type = T;
22
+ QueueAllocator() = default;
23
+ template <typename U> QueueAllocator(const QueueAllocator<U>&) {}
24
+ T *allocate(std::size_t count) {
25
+ #ifdef ESP_PLATFORM
26
+ auto *memory = heap_caps_malloc(count * sizeof(T), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
27
+ if (!memory) memory = heap_caps_malloc(count * sizeof(T), MALLOC_CAP_8BIT);
28
+ if (!memory) throw std::bad_alloc();
29
+ return static_cast<T *>(memory);
30
+ #else
31
+ return std::allocator<T>{}.allocate(count);
32
+ #endif
33
+ }
34
+ void deallocate(T *memory, std::size_t count) {
35
+ #ifdef ESP_PLATFORM
36
+ (void)count;
37
+ heap_caps_free(memory);
38
+ #else
39
+ std::allocator<T>{}.deallocate(memory, count);
40
+ #endif
41
+ }
42
+ template <typename U> bool operator==(const QueueAllocator<U>&) const { return true; }
43
+ };
44
+
45
+
46
+ // Causal linear conversion: preserve fractional position across every network
47
+ // chunk. Input/output are signed mono PCM, never independently resampled frames.
48
+ class Resampler {
49
+ public:
50
+ Resampler(int inputRate, int outputRate) : input_(inputRate), output_(outputRate) {
51
+ if (inputRate <= 0 || outputRate <= 0) throw std::invalid_argument("Invalid PCM rate");
52
+ const auto divisor = std::gcd(input_, output_);
53
+ input_ /= divisor;
54
+ output_ /= divisor;
55
+ }
56
+ template <typename Write>
57
+ void push(std::int16_t sample, Write write) {
58
+ if (!started_) { previous_ = sample; started_ = true; }
59
+ phase_ += output_;
60
+ while (phase_ >= input_) {
61
+ phase_ -= input_;
62
+ const auto delta = static_cast<std::int32_t>(sample) - previous_;
63
+ // Supported PCM rates reduce to ratios no larger than 3. Avoid a
64
+ // software 64-bit divide for every sample on 32-bit devices, retaining
65
+ // the wide fallback for arbitrary large coprime sample rates.
66
+ const auto interpolated = output_ <= 32768
67
+ ? delta * (output_ - phase_) / output_
68
+ : static_cast<std::int32_t>(std::int64_t(delta) * (output_ - phase_) / output_);
69
+ write(static_cast<std::int16_t>(previous_ + interpolated));
70
+ }
71
+ previous_ = sample;
72
+ }
73
+ void reset() { phase_ = previous_ = 0; started_ = false; }
74
+ private:
75
+ int input_, output_, phase_ = 0, previous_ = 0;
76
+ bool started_ = false;
77
+ };
78
+
79
+ inline std::string encode(const std::vector<std::int16_t>& pcm) {
80
+ constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
81
+ std::string result;
82
+ result.reserve((pcm.size() * 2 + 2) / 3 * 4);
83
+ std::uint32_t bits = 0;
84
+ int available = 0;
85
+ for (auto sample : pcm) {
86
+ for (int shift : {0, 8}) {
87
+ bits = (bits << 8) | ((static_cast<std::uint16_t>(sample) >> shift) & 255);
88
+ available += 8;
89
+ while (available >= 6) { available -= 6; result += alphabet[(bits >> available) & 63]; }
90
+ }
91
+ }
92
+ if (available) result += alphabet[(bits << (6 - available)) & 63];
93
+ while (result.size() % 4) result += '=';
94
+ return result;
95
+ }
96
+
97
+ inline std::vector<std::int16_t> decode(const std::string& encoded) {
98
+ if (encoded.size() % 4 || encoded.size() > 1024 * 1024)
99
+ throw std::invalid_argument("Invalid PCM base64 length");
100
+ std::vector<std::int16_t> result;
101
+ result.reserve(encoded.size() / 4 * 3 / 2);
102
+ std::uint32_t bits = 0;
103
+ int available = 0, low = -1, padding = 0;
104
+ for (unsigned char c : encoded) {
105
+ if (c == '=') { if (++padding > 2) throw std::invalid_argument("Invalid base64 padding"); continue; }
106
+ const int value = c >= 'A' && c <= 'Z' ? c - 'A' : c >= 'a' && c <= 'z' ? c - 'a' + 26 :
107
+ c >= '0' && c <= '9' ? c - '0' + 52 : c == '+' ? 62 : c == '/' ? 63 : -1;
108
+ if (value < 0 || padding) throw std::invalid_argument("Invalid PCM base64");
109
+ bits = (bits << 6) | value;
110
+ available += 6;
111
+ if (available >= 8) {
112
+ available -= 8;
113
+ const int byte = (bits >> available) & 255;
114
+ if (low < 0) low = byte;
115
+ else { result.push_back(static_cast<std::int16_t>(low | (byte << 8))); low = -1; }
116
+ }
117
+ }
118
+ if (low >= 0 || available != padding * 2 || (available && (bits & ((1u << available) - 1))))
119
+ throw std::invalid_argument("Incomplete PCM sample or invalid base64 padding");
120
+ return result;
121
+ }
122
+ } // namespace gea::host::pcm