@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.
- package/audio_runtime.cpp +97 -3
- package/host/audio.cpp +395 -10
- package/host/audio_worklet.cpp +611 -0
- package/host/fetch.cpp +17 -0
- package/host/media.cpp +308 -27
- package/host/mjpeg.cpp +199 -0
- package/host/rtc.cpp +458 -48
- package/host/rtc_esp.cpp +897 -75
- package/host/rtc_objects.inc +246 -0
- package/host/timers.cpp +18 -0
- package/host/video.cpp +152 -0
- package/host/websocket.cpp +623 -72
- package/host/worker.cpp +621 -0
- package/include/gea/audio-worklet-runtime.h +165 -0
- package/include/gea/base64-runtime.h +26 -0
- package/include/gea/embedded-host.h +1 -0
- package/include/gea/worker-runtime.h +184 -0
- package/include/host/audio.h +94 -6
- package/include/host/audio_level.h +37 -0
- package/include/host/audio_worklet.h +103 -0
- package/include/host/h264_layout.h +170 -0
- package/include/host/media.h +67 -0
- package/include/host/mjpeg.h +22 -0
- package/include/host/mjpeg_parser.h +84 -0
- package/include/host/pcm_stream.h +122 -0
- package/include/host/rtc.h +38 -20
- package/include/host/rtc_h264.h +76 -0
- package/include/host/rtc_ice_candidate.h +141 -0
- package/include/host/rtc_opus.h +136 -0
- package/include/host/rtc_receive_sdp.h +245 -0
- package/include/host/rtc_rtp.h +170 -0
- package/include/host/rtc_sdp.h +71 -0
- package/include/host/rtc_types.h +166 -0
- package/include/host/rtc_vp8.h +115 -0
- package/include/host/rtc_vp8_capture.h +129 -0
- package/include/host/rtc_vp8_decoder.h +169 -0
- package/include/host/rtc_vp8_receiver.h +55 -0
- package/include/host/timers.h +3 -2
- package/include/host/video.h +39 -0
- package/include/host/video_color.h +90 -0
- package/include/host/video_frame_pool.h +50 -0
- package/include/host/video_pixels.h +178 -0
- package/include/host/websocket.h +20 -1
- package/include/host/websocket_message.h +66 -0
- package/include/host/worker.h +131 -0
- package/package.json +1 -1
- package/services/diagnostics.cpp +120 -19
|
@@ -0,0 +1,611 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
#include "host/audio.h"
|
|
3
|
+
#include "host/pcm_stream.h"
|
|
4
|
+
#include <algorithm>
|
|
5
|
+
#include <array>
|
|
6
|
+
#include <atomic>
|
|
7
|
+
#include <chrono>
|
|
8
|
+
#include <cmath>
|
|
9
|
+
#include <condition_variable>
|
|
10
|
+
#include <cstdio>
|
|
11
|
+
#include <exception>
|
|
12
|
+
#include <mutex>
|
|
13
|
+
#include <stdexcept>
|
|
14
|
+
#include <unordered_set>
|
|
15
|
+
#ifdef ESP_PLATFORM
|
|
16
|
+
#include "freertos/FreeRTOS.h"
|
|
17
|
+
#include "freertos/task.h"
|
|
18
|
+
#include "esp_log.h"
|
|
19
|
+
#include "esp_timer.h"
|
|
20
|
+
#else
|
|
21
|
+
#include <thread>
|
|
22
|
+
#endif
|
|
23
|
+
|
|
24
|
+
namespace gea::host::audio_worklet {
|
|
25
|
+
namespace {
|
|
26
|
+
using Clock = std::chrono::steady_clock;
|
|
27
|
+
std::mutex moduleMutex;
|
|
28
|
+
std::unordered_map<std::string, std::function<void()>>& modules() {
|
|
29
|
+
static std::unordered_map<std::string, std::function<void()>> entries;
|
|
30
|
+
return entries;
|
|
31
|
+
}
|
|
32
|
+
thread_local ContextState* active = nullptr;
|
|
33
|
+
thread_local MessagePort constructingPort;
|
|
34
|
+
// Enough for the output driver's 512-frame pulls, but bounded independently of
|
|
35
|
+
// network rate. The producer never waits for the mixer or a network socket.
|
|
36
|
+
constexpr std::size_t outputCapacity = 2048;
|
|
37
|
+
constexpr std::size_t maxNodes = 16;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// JS-facing handlers live only in the node's creating realm. The audio task
|
|
41
|
+
// keeps a weak handle and posts native error text; it never copies a Ref capture.
|
|
42
|
+
struct NodeControl {
|
|
43
|
+
std::shared_ptr<workers::Context> owner;
|
|
44
|
+
std::function<void(const std::string&)> error;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
struct NodeState {
|
|
48
|
+
explicit NodeState(int rate) : capture(16000, rate) {}
|
|
49
|
+
std::weak_ptr<ContextState> context;
|
|
50
|
+
std::shared_ptr<AudioWorkletProcessor> processor;
|
|
51
|
+
MessagePort processorPort;
|
|
52
|
+
std::shared_ptr<workers::Context> owner;
|
|
53
|
+
std::weak_ptr<NodeControl> control;
|
|
54
|
+
std::shared_ptr<media::TrackPcmReader> reader;
|
|
55
|
+
MediaStreamTrack inputTrack;
|
|
56
|
+
bool captureInputLive = false;
|
|
57
|
+
std::weak_ptr<void> source;
|
|
58
|
+
pcm::Resampler capture;
|
|
59
|
+
AudioWorkletBus inputs{AudioWorkletChannels{}}, outputs{AudioWorkletChannels{std::vector<float>(renderQuantum)}};
|
|
60
|
+
AudioWorkletParameters parameters;
|
|
61
|
+
std::array<float, 512> inputPending{};
|
|
62
|
+
std::size_t inputRead = 0, inputCount = 0;
|
|
63
|
+
std::uint64_t captureDropped = 0;
|
|
64
|
+
bool connected = false, alive = true;
|
|
65
|
+
unsigned numberOfInputs = 1;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
69
|
+
explicit ContextState(int rate) : rate(rate), playback(rate, 16000) {}
|
|
70
|
+
~ContextState() {
|
|
71
|
+
if (output) gea::platform::audio::AudioSystem::stopPcmStream(output);
|
|
72
|
+
if (realm) realm->stop();
|
|
73
|
+
}
|
|
74
|
+
const int rate;
|
|
75
|
+
std::mutex startMutex;
|
|
76
|
+
std::mutex readyMutex;
|
|
77
|
+
std::condition_variable readySignal;
|
|
78
|
+
std::atomic<bool> ready{false};
|
|
79
|
+
std::shared_ptr<workers::Context> realm;
|
|
80
|
+
std::atomic<bool> closed{false}, running{true};
|
|
81
|
+
std::atomic<std::uint64_t> frames{0};
|
|
82
|
+
bool inputClockActive = false;
|
|
83
|
+
std::unordered_map<std::string, ProcessorFactory> factories;
|
|
84
|
+
std::unordered_set<std::string> loaded;
|
|
85
|
+
std::vector<std::shared_ptr<NodeState>> nodes;
|
|
86
|
+
std::mutex outputMutex;
|
|
87
|
+
std::vector<std::int16_t, pcm::QueueAllocator<std::int16_t>> outputPcm;
|
|
88
|
+
std::size_t outputRead = 0, outputCount = 0;
|
|
89
|
+
std::uint64_t output = 0;
|
|
90
|
+
pcm::Resampler playback;
|
|
91
|
+
std::array<float, renderQuantum> mix{};
|
|
92
|
+
#ifdef ESP_PLATFORM
|
|
93
|
+
std::int64_t statsStart = 0, maxRenderUs = 0, maxProcessUs = 0, maxLagUs = 0;
|
|
94
|
+
std::uint64_t statsQuanta = 0, capturedSamples = 0, lostCaptureSamples = 0;
|
|
95
|
+
std::uint64_t inputWaits = 0, realInputFrames = 0;
|
|
96
|
+
std::uint64_t processSumUs = 0, renderSumUs = 0, processCalls = 0, renderCalls = 0;
|
|
97
|
+
#if configUSE_TRACE_FACILITY && configGENERATE_RUN_TIME_STATS
|
|
98
|
+
decltype(TaskStatus_t{}.ulRunTimeCounter) statsCpuStart = 0;
|
|
99
|
+
#endif
|
|
100
|
+
std::size_t maxCapturePending = 0, maxOutputQueued = 0, emptyOutputPulls = 0, outputBackpressureWaits = 0;
|
|
101
|
+
void reportStats() {
|
|
102
|
+
const auto now = esp_timer_get_time();
|
|
103
|
+
if (statsStart && now - statsStart < 2000000) return;
|
|
104
|
+
std::int64_t cpuUs = -1;
|
|
105
|
+
#if configUSE_TRACE_FACILITY && configGENERATE_RUN_TIME_STATS
|
|
106
|
+
TaskStatus_t task{};
|
|
107
|
+
// Only this task, and no stack high-water scan: report actual scheduled
|
|
108
|
+
// CPU separately from render/process wall time, which includes preemption.
|
|
109
|
+
vTaskGetInfo(nullptr, &task, pdFALSE, eInvalid);
|
|
110
|
+
cpuUs = static_cast<std::int64_t>(task.ulRunTimeCounter - statsCpuStart);
|
|
111
|
+
statsCpuStart = task.ulRunTimeCounter;
|
|
112
|
+
#endif
|
|
113
|
+
if (!statsStart) { statsStart = now; return; }
|
|
114
|
+
std::size_t queued, peak, empty;
|
|
115
|
+
{ std::lock_guard lock(outputMutex);
|
|
116
|
+
queued = outputCount; peak = maxOutputQueued; empty = emptyOutputPulls;
|
|
117
|
+
maxOutputQueued = outputCount; emptyOutputPulls = 0;
|
|
118
|
+
}
|
|
119
|
+
ESP_LOGI("gea_worklet", "span_ms=%lld cpu_us=%lld rate=%d quanta=%llu render_avg_us=%llu process_avg_us=%llu render_max_us=%lld process_max_us=%lld lag_max_us=%lld capture_samples=%llu capture_pending_max=%u capture_lost=%llu input_waits=%llu input_real_frames=%llu output_queued=%u output_peak=%u empty_pulls=%u backpressure_waits=%u",
|
|
120
|
+
static_cast<long long>((now - statsStart) / 1000), static_cast<long long>(cpuUs), rate,
|
|
121
|
+
static_cast<unsigned long long>(statsQuanta),
|
|
122
|
+
static_cast<unsigned long long>(renderCalls ? renderSumUs / renderCalls : 0),
|
|
123
|
+
static_cast<unsigned long long>(processCalls ? processSumUs / processCalls : 0), static_cast<long long>(maxRenderUs),
|
|
124
|
+
static_cast<long long>(maxProcessUs), static_cast<long long>(maxLagUs),
|
|
125
|
+
static_cast<unsigned long long>(capturedSamples), static_cast<unsigned>(maxCapturePending),
|
|
126
|
+
static_cast<unsigned long long>(lostCaptureSamples),
|
|
127
|
+
static_cast<unsigned long long>(inputWaits), static_cast<unsigned long long>(realInputFrames),
|
|
128
|
+
static_cast<unsigned>(queued),
|
|
129
|
+
static_cast<unsigned>(peak), static_cast<unsigned>(empty), static_cast<unsigned>(outputBackpressureWaits));
|
|
130
|
+
statsStart = now; statsQuanta = capturedSamples = lostCaptureSamples = 0;
|
|
131
|
+
inputWaits = realInputFrames = 0;
|
|
132
|
+
maxRenderUs = maxProcessUs = maxLagUs = 0; maxCapturePending = outputBackpressureWaits = 0;
|
|
133
|
+
processSumUs = renderSumUs = processCalls = renderCalls = 0;
|
|
134
|
+
}
|
|
135
|
+
#endif
|
|
136
|
+
|
|
137
|
+
void clearOutput() {
|
|
138
|
+
std::lock_guard lock(outputMutex);
|
|
139
|
+
outputRead = outputCount = 0;
|
|
140
|
+
playback.reset();
|
|
141
|
+
}
|
|
142
|
+
void stopNodes() {
|
|
143
|
+
for (auto& node : nodes) {
|
|
144
|
+
node->processorPort.close();
|
|
145
|
+
node->processor.reset();
|
|
146
|
+
node->reader.reset();
|
|
147
|
+
node->alive = false;
|
|
148
|
+
}
|
|
149
|
+
nodes.clear();
|
|
150
|
+
// Generated factory captures and processor Ref fields die in their realm.
|
|
151
|
+
factories.clear();
|
|
152
|
+
loaded.clear();
|
|
153
|
+
}
|
|
154
|
+
void fail(const std::shared_ptr<NodeState>& node, const std::string& message) {
|
|
155
|
+
std::fprintf(stderr, "[AudioWorklet] processorerror: %s\n", message.c_str());
|
|
156
|
+
node->alive = false;
|
|
157
|
+
node->reader.reset();
|
|
158
|
+
node->processorPort.close();
|
|
159
|
+
if (node->owner) {
|
|
160
|
+
const auto control = node->control;
|
|
161
|
+
node->owner->post([control, message] {
|
|
162
|
+
if (const auto target = control.lock(); target && target->error) target->error(message);
|
|
163
|
+
}, message.size());
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
bool render() {
|
|
167
|
+
if (!running || closed) { inputClockActive = false; return true; }
|
|
168
|
+
const bool connected = std::any_of(nodes.begin(), nodes.end(),
|
|
169
|
+
[](const auto& node) { return node->alive && node->connected; });
|
|
170
|
+
if (connected) {
|
|
171
|
+
// Reserve a whole hardware quantum before process() advances playback
|
|
172
|
+
// or capture. Codec startup and mixer scheduling may temporarily fill
|
|
173
|
+
// this queue; yield until the consumer pulls, without dropping samples.
|
|
174
|
+
const auto required = (renderQuantum * 16000 + rate - 1) / rate;
|
|
175
|
+
std::lock_guard lock(outputMutex);
|
|
176
|
+
if (required > outputPcm.size() - outputCount) {
|
|
177
|
+
#ifdef ESP_PLATFORM
|
|
178
|
+
++outputBackpressureWaits;
|
|
179
|
+
#endif
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// Capture arrives on the hardware clock in AEC batches. Prepare a complete
|
|
184
|
+
// quantum for EVERY live input before invoking any processor. A transient
|
|
185
|
+
// shortage retains the partial input and deadline instead of inserting
|
|
186
|
+
// artificial silence and stretching the microphone timeline.
|
|
187
|
+
bool waitingForInput = false;
|
|
188
|
+
inputClockActive = false;
|
|
189
|
+
for (const auto& node : nodes) {
|
|
190
|
+
if (!node->alive || !node->connected || !node->reader) continue;
|
|
191
|
+
node->captureInputLive = node->inputTrack.enabled() && node->inputTrack.readyState() == "live";
|
|
192
|
+
if (!node->captureInputLive) {
|
|
193
|
+
// Disabled/ended tracks represent silence, not a stalled device clock.
|
|
194
|
+
node->reader->discardBuffered();
|
|
195
|
+
node->inputRead = node->inputCount = 0;
|
|
196
|
+
node->capture.reset();
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
inputClockActive = true;
|
|
200
|
+
{
|
|
201
|
+
#ifdef ESP_PLATFORM
|
|
202
|
+
maxCapturePending = std::max(maxCapturePending, node->reader->pendingSamples());
|
|
203
|
+
#endif
|
|
204
|
+
const auto dropped = node->reader->droppedSamples();
|
|
205
|
+
if (dropped != node->captureDropped) {
|
|
206
|
+
// Only the track's actual bounded-ring overwrite is a loss. A slow
|
|
207
|
+
// consumer must not silently discard a perfectly recoverable batch.
|
|
208
|
+
std::fprintf(stderr, "[AudioWorklet] capture ring overrun: %llu samples lost\n",
|
|
209
|
+
static_cast<unsigned long long>(dropped - node->captureDropped));
|
|
210
|
+
#ifdef ESP_PLATFORM
|
|
211
|
+
lostCaptureSamples += dropped - node->captureDropped;
|
|
212
|
+
#endif
|
|
213
|
+
node->captureDropped = dropped;
|
|
214
|
+
}
|
|
215
|
+
// AEC delivers batches (32 ms on ES8311), not one hardware sample at a
|
|
216
|
+
// time. Keep a partial converted quantum until it is complete; padding
|
|
217
|
+
// that partial quantum would insert silence inside captured speech.
|
|
218
|
+
while (node->inputCount < renderQuantum) {
|
|
219
|
+
std::array<std::int16_t, 128> pcm{};
|
|
220
|
+
const auto wanted = std::min<std::size_t>(pcm.size(),
|
|
221
|
+
((renderQuantum - node->inputCount) * 16000 + rate - 1) / rate);
|
|
222
|
+
const auto count = node->reader->read(pcm.data(), wanted);
|
|
223
|
+
if (!count) break;
|
|
224
|
+
#ifdef ESP_PLATFORM
|
|
225
|
+
capturedSamples += count;
|
|
226
|
+
#endif
|
|
227
|
+
for (std::size_t i = 0; i < count; ++i)
|
|
228
|
+
node->capture.push(pcm[i], [&](std::int16_t value) {
|
|
229
|
+
node->inputPending[(node->inputRead + node->inputCount++) % node->inputPending.size()] = value / 32768.0f;
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
waitingForInput |= node->inputCount < renderQuantum;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (waitingForInput) {
|
|
236
|
+
#ifdef ESP_PLATFORM
|
|
237
|
+
++inputWaits;
|
|
238
|
+
#endif
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
mix.fill(0);
|
|
242
|
+
bool hasDestination = false;
|
|
243
|
+
for (const auto& node : nodes) {
|
|
244
|
+
if (!node->alive || !node->connected) continue;
|
|
245
|
+
hasDestination = true;
|
|
246
|
+
for (auto& output : node->outputs)
|
|
247
|
+
for (auto& channel : output) std::fill(channel.begin(), channel.end(), 0.0f);
|
|
248
|
+
if (node->reader) {
|
|
249
|
+
auto& input = node->inputs[0][0];
|
|
250
|
+
if (node->captureInputLive) {
|
|
251
|
+
for (auto& sample : input) {
|
|
252
|
+
sample = node->inputPending[node->inputRead];
|
|
253
|
+
node->inputRead = (node->inputRead + 1) % node->inputPending.size();
|
|
254
|
+
--node->inputCount;
|
|
255
|
+
}
|
|
256
|
+
#ifdef ESP_PLATFORM
|
|
257
|
+
realInputFrames += renderQuantum;
|
|
258
|
+
#endif
|
|
259
|
+
} else {
|
|
260
|
+
std::fill(input.begin(), input.end(), 0.0f);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
#ifdef ESP_PLATFORM
|
|
265
|
+
const auto processStart = esp_timer_get_time();
|
|
266
|
+
#endif
|
|
267
|
+
const bool keep = node->processor->process(node->inputs, node->outputs, node->parameters);
|
|
268
|
+
#ifdef ESP_PLATFORM
|
|
269
|
+
const auto processUs = esp_timer_get_time() - processStart;
|
|
270
|
+
maxProcessUs = std::max(maxProcessUs, processUs);
|
|
271
|
+
processSumUs += processUs;
|
|
272
|
+
++processCalls;
|
|
273
|
+
#endif
|
|
274
|
+
const auto& channel = node->outputs.at(0).at(0);
|
|
275
|
+
if (channel.size() != renderQuantum) throw std::runtime_error("AudioWorklet changed render quantum geometry");
|
|
276
|
+
for (std::size_t i = 0; i < renderQuantum; ++i) mix[i] += channel[i];
|
|
277
|
+
if (!keep) node->alive = false;
|
|
278
|
+
} catch (const std::exception& error) { fail(node, error.what()); }
|
|
279
|
+
catch (...) { fail(node, "AudioWorklet processor failed"); }
|
|
280
|
+
}
|
|
281
|
+
frames.fetch_add(renderQuantum);
|
|
282
|
+
if (!hasDestination) return true;
|
|
283
|
+
std::array<std::int16_t, 256> block{};
|
|
284
|
+
std::size_t count = 0;
|
|
285
|
+
for (float sample : mix) {
|
|
286
|
+
const auto value = !std::isfinite(sample) ? 0 : static_cast<int>(std::clamp(sample, -1.0f, 1.0f) * 32768.0f);
|
|
287
|
+
playback.push(static_cast<std::int16_t>(std::clamp(value, -32768, 32767)),
|
|
288
|
+
[&](std::int16_t converted) { block[count++] = converted; });
|
|
289
|
+
}
|
|
290
|
+
bool overflow = false;
|
|
291
|
+
{
|
|
292
|
+
std::lock_guard lock(outputMutex);
|
|
293
|
+
overflow = count > outputPcm.size() - outputCount;
|
|
294
|
+
if (!overflow) {
|
|
295
|
+
for (std::size_t i = 0; i < count; ++i)
|
|
296
|
+
outputPcm[(outputRead + outputCount++) % outputPcm.size()] = block[i];
|
|
297
|
+
#ifdef ESP_PLATFORM
|
|
298
|
+
maxOutputQueued = std::max(maxOutputQueued, outputCount);
|
|
299
|
+
#endif
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (overflow) {
|
|
303
|
+
// Only the audio task produces samples, so preflight reservation makes
|
|
304
|
+
// this an internal invariant failure, not a temporary device delay.
|
|
305
|
+
for (const auto& node : nodes) if (node->alive) fail(node, "AudioWorklet output reservation was exceeded");
|
|
306
|
+
clearOutput();
|
|
307
|
+
}
|
|
308
|
+
return true;
|
|
309
|
+
}
|
|
310
|
+
void ensureStarted() {
|
|
311
|
+
std::lock_guard lock(startMutex);
|
|
312
|
+
if (closed) throw std::runtime_error("AudioContext is closed");
|
|
313
|
+
if (realm) return;
|
|
314
|
+
#ifdef ESP_PLATFORM
|
|
315
|
+
// ESP32-S3 pins an unpinned task to its current core on first FPU use.
|
|
316
|
+
// Choose explicitly so startup timing cannot pin the worklet beside the
|
|
317
|
+
// AEC/capture task on core 0. Single-core targets retain their only core.
|
|
318
|
+
constexpr int core = portNUM_PROCESSORS > 1 ? 1 : 0;
|
|
319
|
+
realm = workers::Context::create("gea_worklet", configMAX_PRIORITIES - 1, core);
|
|
320
|
+
#else
|
|
321
|
+
realm = workers::Context::create("gea_worklet", 24);
|
|
322
|
+
#endif
|
|
323
|
+
auto self = shared_from_this();
|
|
324
|
+
const std::weak_ptr<ContextState> weak = self;
|
|
325
|
+
realm->setErrorHandler([weak](const std::string& message) {
|
|
326
|
+
if (const auto context = weak.lock()) {
|
|
327
|
+
for (const auto& node : context->nodes)
|
|
328
|
+
if (node->alive) context->fail(node, message);
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
// Context supplies the native task, ownership scope, timers and cleanup.
|
|
332
|
+
// This entry owns its periodic render loop; runPending services only its
|
|
333
|
+
// bounded messages between process calls, never on the UI or mixer task.
|
|
334
|
+
realm->start([self] {
|
|
335
|
+
active = self.get();
|
|
336
|
+
{ std::lock_guard lock(self->readyMutex); self->ready = true; }
|
|
337
|
+
self->readySignal.notify_all();
|
|
338
|
+
const auto quantum = std::chrono::nanoseconds(128000000000LL / self->rate);
|
|
339
|
+
auto next = Clock::now();
|
|
340
|
+
while (!self->closed && !self->realm->stopped()) {
|
|
341
|
+
self->realm->runPending(0.5);
|
|
342
|
+
const auto now = Clock::now();
|
|
343
|
+
unsigned catchup = 0;
|
|
344
|
+
while ((self->inputClockActive || now >= next) && catchup++ < 4) {
|
|
345
|
+
#ifdef ESP_PLATFORM
|
|
346
|
+
const auto renderStart = esp_timer_get_time();
|
|
347
|
+
const auto framesBefore = self->frames.load();
|
|
348
|
+
self->maxLagUs = std::max<std::int64_t>(self->maxLagUs,
|
|
349
|
+
std::chrono::duration_cast<std::chrono::microseconds>(now - next).count());
|
|
350
|
+
#endif
|
|
351
|
+
if (!self->render()) break;
|
|
352
|
+
#ifdef ESP_PLATFORM
|
|
353
|
+
const auto renderUs = esp_timer_get_time() - renderStart;
|
|
354
|
+
self->maxRenderUs = std::max(self->maxRenderUs, renderUs);
|
|
355
|
+
self->renderSumUs += renderUs;
|
|
356
|
+
++self->renderCalls;
|
|
357
|
+
if (self->frames.load() != framesBefore) ++self->statsQuanta;
|
|
358
|
+
#endif
|
|
359
|
+
// A live microphone supplies the graph's hardware clock. Do not
|
|
360
|
+
// constrain it with a second wall clock or accumulate timer debt
|
|
361
|
+
// while waiting for a batched ADC/AEC delivery. Output backpressure
|
|
362
|
+
// and the bounded loop still protect the DAC and lower-priority tasks.
|
|
363
|
+
if (self->inputClockActive) next = Clock::now() + quantum;
|
|
364
|
+
else next += quantum;
|
|
365
|
+
// A slow processor must not monopolize this high-priority task with
|
|
366
|
+
// four overdue calls. Retain remaining deadlines for the next wake.
|
|
367
|
+
if (Clock::now() - now >= quantum) break;
|
|
368
|
+
}
|
|
369
|
+
// Output-only graphs retain missed timer deadlines. Capture graphs
|
|
370
|
+
// resume with the next complete hardware quantum on a later wake.
|
|
371
|
+
#ifdef ESP_PLATFORM
|
|
372
|
+
self->reportStats();
|
|
373
|
+
vTaskDelay(1);
|
|
374
|
+
#else
|
|
375
|
+
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
|
376
|
+
#endif
|
|
377
|
+
}
|
|
378
|
+
self->stopNodes();
|
|
379
|
+
self->realm->finish();
|
|
380
|
+
active = nullptr;
|
|
381
|
+
});
|
|
382
|
+
std::unique_lock readyLock(readyMutex);
|
|
383
|
+
if (!readySignal.wait_for(readyLock, std::chrono::seconds(5), [&] { return ready.load(); }))
|
|
384
|
+
throw std::runtime_error("AudioWorklet task did not initialize");
|
|
385
|
+
}
|
|
386
|
+
void invoke(std::function<void()> action) {
|
|
387
|
+
ensureStarted();
|
|
388
|
+
if (active == this) { action(); return; }
|
|
389
|
+
struct Completion { std::mutex mutex; std::condition_variable ready; bool done = false; std::exception_ptr error; };
|
|
390
|
+
auto completion = std::make_shared<Completion>();
|
|
391
|
+
if (!realm->post([completion, action = std::move(action)] {
|
|
392
|
+
try { action(); } catch (...) { completion->error = std::current_exception(); }
|
|
393
|
+
{ std::lock_guard lock(completion->mutex); completion->done = true; }
|
|
394
|
+
completion->ready.notify_one();
|
|
395
|
+
})) throw std::runtime_error("AudioWorklet control queue is full");
|
|
396
|
+
std::unique_lock lock(completion->mutex);
|
|
397
|
+
if (!completion->ready.wait_for(lock, std::chrono::seconds(5), [&] { return completion->done; }))
|
|
398
|
+
throw std::runtime_error("AudioWorklet task did not respond");
|
|
399
|
+
if (completion->error) std::rethrow_exception(completion->error);
|
|
400
|
+
}
|
|
401
|
+
void ensureOutput() {
|
|
402
|
+
if (output) return;
|
|
403
|
+
outputPcm.resize(outputCapacity);
|
|
404
|
+
const std::weak_ptr<ContextState> weak = shared_from_this();
|
|
405
|
+
output = gea::platform::audio::AudioSystem::playPcmStream([weak](std::int16_t* out, std::size_t capacity) {
|
|
406
|
+
const auto state = weak.lock();
|
|
407
|
+
if (!state || state->closed || !state->running) return std::size_t{0};
|
|
408
|
+
std::lock_guard lock(state->outputMutex);
|
|
409
|
+
const auto count = std::min(capacity, state->outputCount);
|
|
410
|
+
#ifdef ESP_PLATFORM
|
|
411
|
+
if (!count) ++state->emptyOutputPulls;
|
|
412
|
+
#endif
|
|
413
|
+
for (std::size_t i = 0; i < count; ++i) {
|
|
414
|
+
out[i] = state->outputPcm[state->outputRead];
|
|
415
|
+
state->outputRead = (state->outputRead + 1) % state->outputPcm.size();
|
|
416
|
+
}
|
|
417
|
+
state->outputCount -= count;
|
|
418
|
+
return count;
|
|
419
|
+
});
|
|
420
|
+
if (!output) throw std::runtime_error("AudioContext output unavailable");
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
std::shared_ptr<ContextState> createContext(double rate) {
|
|
425
|
+
if (!std::isfinite(rate) || rate < 8000 || rate > 48000 || rate != std::floor(rate))
|
|
426
|
+
throw std::invalid_argument("AudioContext sampleRate must be an integer from 8000 to 48000");
|
|
427
|
+
return std::make_shared<ContextState>(static_cast<int>(rate));
|
|
428
|
+
}
|
|
429
|
+
// Report a conservative processing delay from the configured queue capacity.
|
|
430
|
+
// currentTime is a render clock; neither property claims a DAC timestamp.
|
|
431
|
+
double contextBaseLatency(const std::shared_ptr<ContextState>& context) {
|
|
432
|
+
return context ? double(outputCapacity) / 16000 + gea::platform::audio::AudioSystem::processingLatency() : 0;
|
|
433
|
+
}
|
|
434
|
+
double contextTime(const std::shared_ptr<ContextState>& context) {
|
|
435
|
+
// Legacy oscillator-only contexts retain their platform scheduler's clock.
|
|
436
|
+
// A worklet has an independent render clock once its audio realm starts.
|
|
437
|
+
if (context && !context->ready) return gea::platform::audio::AudioSystem::sharedContext().currentTime();
|
|
438
|
+
return context ? double(context->frames.load()) / context->rate : 0;
|
|
439
|
+
}
|
|
440
|
+
std::string contextState(const std::shared_ptr<ContextState>& context) {
|
|
441
|
+
return !context || context->closed ? "closed" : context->running ? "running" : "suspended";
|
|
442
|
+
}
|
|
443
|
+
void resume(const std::shared_ptr<ContextState>& context) {
|
|
444
|
+
if (!context || context->closed) throw std::runtime_error("AudioContext is closed");
|
|
445
|
+
context->invoke([context] { context->running = true; });
|
|
446
|
+
}
|
|
447
|
+
void suspend(const std::shared_ptr<ContextState>& context) {
|
|
448
|
+
if (!context || context->closed) throw std::runtime_error("AudioContext is closed");
|
|
449
|
+
context->invoke([context] {
|
|
450
|
+
context->running = false;
|
|
451
|
+
context->clearOutput();
|
|
452
|
+
for (const auto& node : context->nodes) if (node->reader) node->reader->discardBuffered();
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
void close(const std::shared_ptr<ContextState>& context) {
|
|
456
|
+
if (!context || context->closed) return;
|
|
457
|
+
if (!context->realm) { context->closed = true; return; }
|
|
458
|
+
context->invoke([context] {
|
|
459
|
+
context->closed = true;
|
|
460
|
+
context->running = false;
|
|
461
|
+
context->stopNodes();
|
|
462
|
+
context->clearOutput();
|
|
463
|
+
if (context->output) gea::platform::audio::AudioSystem::stopPcmStream(context->output);
|
|
464
|
+
context->output = 0;
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
void registerModule(const std::string& url, std::function<void()> entry) {
|
|
468
|
+
if (url.empty() || !entry) throw std::invalid_argument("Invalid AudioWorklet module");
|
|
469
|
+
std::lock_guard lock(moduleMutex);
|
|
470
|
+
if (!modules().emplace(url, std::move(entry)).second) throw std::invalid_argument("Duplicate AudioWorklet module URL");
|
|
471
|
+
}
|
|
472
|
+
void registerProcessor(const std::string& name, ProcessorFactory factory) {
|
|
473
|
+
if (!active) throw std::logic_error("registerProcessor must run in an AudioWorklet module");
|
|
474
|
+
if (name.empty() || !factory) throw std::invalid_argument("Invalid AudioWorklet processor");
|
|
475
|
+
if (!active->factories.emplace(name, std::move(factory)).second) throw std::invalid_argument("Duplicate AudioWorklet processor name");
|
|
476
|
+
}
|
|
477
|
+
double sampleRate() { if (!active) throw std::logic_error("Not an AudioWorklet realm"); return active->rate; }
|
|
478
|
+
double currentTime() { return currentFrame() / sampleRate(); }
|
|
479
|
+
double currentFrame() { if (!active) throw std::logic_error("Not an AudioWorklet realm"); return double(active->frames.load()); }
|
|
480
|
+
MessagePort processorPort() {
|
|
481
|
+
if (!active || constructingPort.detached()) throw std::logic_error("AudioWorkletProcessor must be constructed by AudioWorkletNode");
|
|
482
|
+
return constructingPort;
|
|
483
|
+
}
|
|
484
|
+
void flushOutput() {
|
|
485
|
+
if (!active) throw std::logic_error("Output cancellation must run in the audio realm");
|
|
486
|
+
// This message boundary precedes the next process quantum. Clear converted
|
|
487
|
+
// PCM/history, then discard submitted output without suspending capture.
|
|
488
|
+
active->clearOutput();
|
|
489
|
+
gea::platform::audio::AudioSystem::flushPlayback();
|
|
490
|
+
}
|
|
491
|
+
} // namespace gea::host::audio_worklet
|
|
492
|
+
|
|
493
|
+
namespace gea::host {
|
|
494
|
+
AudioWorkletProcessor::AudioWorkletProcessor() : port(audio_worklet::processorPort()) {}
|
|
495
|
+
void AudioWorklet::addModule(const std::string& url) const {
|
|
496
|
+
if (!context_) throw std::logic_error("AudioWorklet has no AudioContext");
|
|
497
|
+
std::function<void()> entry;
|
|
498
|
+
{
|
|
499
|
+
std::lock_guard lock(audio_worklet::moduleMutex);
|
|
500
|
+
const auto found = audio_worklet::modules().find(url);
|
|
501
|
+
if (found == audio_worklet::modules().end()) throw std::invalid_argument("AudioWorklet module was not compiled: " + url);
|
|
502
|
+
entry = found->second;
|
|
503
|
+
}
|
|
504
|
+
const auto context = context_;
|
|
505
|
+
context->invoke([context, url, entry] {
|
|
506
|
+
if (context->loaded.count(url)) return;
|
|
507
|
+
entry();
|
|
508
|
+
context->loaded.insert(url);
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::string& name)
|
|
512
|
+
: AudioWorkletNode(context, name, AudioWorkletNodeOptions{}) {}
|
|
513
|
+
AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::string& name, const AudioWorkletNodeOptions& options) {
|
|
514
|
+
if (options.numberOfInputs > 1 || options.numberOfOutputs != 1 || options.channelCount != 1)
|
|
515
|
+
throw std::invalid_argument("Embedded AudioWorklet supports zero or one mono input and one mono output");
|
|
516
|
+
const auto owner = context.workletContext();
|
|
517
|
+
workers::MessageChannel channel;
|
|
518
|
+
port = channel.port1;
|
|
519
|
+
auto node = std::make_shared<audio_worklet::NodeState>(static_cast<int>(context.sampleRate));
|
|
520
|
+
node->context = owner;
|
|
521
|
+
node->owner = workers::Context::current();
|
|
522
|
+
control_ = std::make_shared<audio_worklet::NodeControl>();
|
|
523
|
+
control_->owner = node->owner;
|
|
524
|
+
node->control = control_;
|
|
525
|
+
node->processorPort = channel.port2.transfer();
|
|
526
|
+
node->numberOfInputs = options.numberOfInputs;
|
|
527
|
+
if (!options.numberOfInputs) node->inputs.clear();
|
|
528
|
+
owner->invoke([owner, node, name] {
|
|
529
|
+
if (owner->nodes.size() >= audio_worklet::maxNodes) throw std::runtime_error("AudioContext node limit exceeded");
|
|
530
|
+
const auto factory = owner->factories.find(name);
|
|
531
|
+
if (factory == owner->factories.end()) throw std::invalid_argument("AudioWorklet processor is not registered: " + name);
|
|
532
|
+
node->processorPort.adopt(owner->realm);
|
|
533
|
+
audio_worklet::constructingPort = node->processorPort;
|
|
534
|
+
try { node->processor = factory->second(); }
|
|
535
|
+
catch (...) { audio_worklet::constructingPort = {}; throw; }
|
|
536
|
+
audio_worklet::constructingPort = {};
|
|
537
|
+
if (!node->processor) throw std::runtime_error("AudioWorklet processor constructor returned null");
|
|
538
|
+
owner->nodes.push_back(node);
|
|
539
|
+
});
|
|
540
|
+
state_ = std::move(node);
|
|
541
|
+
}
|
|
542
|
+
AudioDestinationNode AudioWorkletNode::connect(AudioDestinationNode destination) const {
|
|
543
|
+
if (!state_) throw std::logic_error("Null AudioWorkletNode");
|
|
544
|
+
auto context = state_->context.lock();
|
|
545
|
+
if (!context || context != destination.context) throw std::invalid_argument("Audio nodes belong to different contexts");
|
|
546
|
+
const auto node = state_;
|
|
547
|
+
context->invoke([context, node] { context->ensureOutput(); node->connected = true; });
|
|
548
|
+
return destination;
|
|
549
|
+
}
|
|
550
|
+
AudioDestinationNode AudioWorkletNode::connect(AudioDestinationProperty destination) const { return connect(static_cast<AudioDestinationNode>(destination)); }
|
|
551
|
+
void AudioWorkletNode::disconnect() const {
|
|
552
|
+
if (!state_) return;
|
|
553
|
+
const auto context = state_->context.lock();
|
|
554
|
+
if (!context || context->closed) return;
|
|
555
|
+
const auto node = state_;
|
|
556
|
+
context->invoke([context, node] { node->connected = false; context->clearOutput(); });
|
|
557
|
+
}
|
|
558
|
+
void AudioWorkletNode::setOnProcessorError(std::function<void(const std::string&)> callback) const {
|
|
559
|
+
if (!control_) return;
|
|
560
|
+
if (workers::Context::current() != control_->owner)
|
|
561
|
+
throw std::logic_error("AudioWorkletNode handlers belong to their creating realm");
|
|
562
|
+
control_->error = std::move(callback);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
struct MediaStreamAudioSourceNode::State {
|
|
566
|
+
std::shared_ptr<audio_worklet::ContextState> context;
|
|
567
|
+
MediaStream stream;
|
|
568
|
+
};
|
|
569
|
+
MediaStreamAudioSourceNode::MediaStreamAudioSourceNode(std::shared_ptr<audio_worklet::ContextState> context, MediaStream stream)
|
|
570
|
+
: state_(std::make_shared<State>(State{std::move(context), stream})) {
|
|
571
|
+
if (stream.getAudioTracks().empty()) throw std::invalid_argument("MediaStreamAudioSourceNode needs an audio track");
|
|
572
|
+
}
|
|
573
|
+
AudioWorkletNode MediaStreamAudioSourceNode::connect(AudioWorkletNode destination) const {
|
|
574
|
+
if (!state_ || !destination.state_) throw std::logic_error("Null audio node");
|
|
575
|
+
const auto context = destination.state_->context.lock();
|
|
576
|
+
if (context != state_->context) throw std::invalid_argument("Audio nodes belong to different contexts");
|
|
577
|
+
const auto node = destination.state_;
|
|
578
|
+
const auto source = state_;
|
|
579
|
+
context->invoke([node, source] {
|
|
580
|
+
if (!node->numberOfInputs) throw std::invalid_argument("AudioWorkletNode has no inputs");
|
|
581
|
+
if (node->reader && node->source.lock() != source) throw std::invalid_argument("AudioWorklet mono input already connected");
|
|
582
|
+
const auto tracks = source->stream.getAudioTracks();
|
|
583
|
+
if (tracks.empty() || tracks.front().readyState() == "ended") throw std::invalid_argument("MediaStream has no live audio track");
|
|
584
|
+
if (!node->reader) node->reader = std::make_shared<media::TrackPcmReader>(tracks.front().nativeHandle);
|
|
585
|
+
node->inputTrack = tracks.front();
|
|
586
|
+
node->source = source;
|
|
587
|
+
node->inputs[0] = AudioWorkletChannels{std::vector<float>(audio_worklet::renderQuantum)};
|
|
588
|
+
node->capture.reset();
|
|
589
|
+
node->inputRead = node->inputCount = 0;
|
|
590
|
+
node->captureDropped = 0;
|
|
591
|
+
});
|
|
592
|
+
return destination;
|
|
593
|
+
}
|
|
594
|
+
void MediaStreamAudioSourceNode::disconnect() const {
|
|
595
|
+
if (!state_ || state_->context->closed) return;
|
|
596
|
+
const auto source = state_;
|
|
597
|
+
source->context->invoke([source] {
|
|
598
|
+
for (const auto& node : source->context->nodes) {
|
|
599
|
+
if (node->source.lock() != source) continue;
|
|
600
|
+
node->reader.reset();
|
|
601
|
+
node->inputTrack = {};
|
|
602
|
+
node->captureInputLive = false;
|
|
603
|
+
node->source.reset();
|
|
604
|
+
if (node->numberOfInputs) node->inputs[0].clear();
|
|
605
|
+
node->inputRead = node->inputCount = 0;
|
|
606
|
+
node->captureDropped = 0;
|
|
607
|
+
node->capture.reset();
|
|
608
|
+
}
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
} // namespace gea::host
|
package/host/fetch.cpp
CHANGED
|
@@ -228,6 +228,23 @@ class FetchResponseBuilder {
|
|
|
228
228
|
if (err != ESP_OK) {
|
|
229
229
|
ESP_LOGE(logTag(), "perform failed for %s: %s%s", url_.c_str(), esp_err_to_name(err),
|
|
230
230
|
reuse ? " (reused connection went stale; retrying on a fresh one)" : "");
|
|
231
|
+
// An HTTP rejection is still a Fetch Response. ESP-IDF's automatic
|
|
232
|
+
// auth handler can return NOT_SUPPORTED for a Bearer 401 without a
|
|
233
|
+
// WWW-Authenticate challenge; do not turn that into opaque HTTP 0.
|
|
234
|
+
const int status = esp_http_client_get_status_code(client);
|
|
235
|
+
if (status >= 400) {
|
|
236
|
+
result.status = status;
|
|
237
|
+
readResponseHeaders(result, client);
|
|
238
|
+
if (g_body.size) result.body.assign(g_body.buffer, g_body.buffer + g_body.size);
|
|
239
|
+
// perform() delivers body bytes through HTTP_EVENT_ON_DATA without
|
|
240
|
+
// populating esp_http_client_read()'s cache. Reading that cache after
|
|
241
|
+
// an auth error dereferences raw_data=null with raw_len still set.
|
|
242
|
+
// Preserve the body already delivered to our event handler.
|
|
243
|
+
ESP_LOGW(logTag(), "HTTP rejection status=%d bytes=%u", status,
|
|
244
|
+
static_cast<unsigned>(result.body.size()));
|
|
245
|
+
dropCachedClient();
|
|
246
|
+
return result;
|
|
247
|
+
}
|
|
231
248
|
dropCachedClient();
|
|
232
249
|
if (reuse) {
|
|
233
250
|
// The parked socket died inside the reuse window — retry exactly once
|