@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.
- 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 +205 -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 +189 -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 +23 -0
- package/include/host/mjpeg_parser.h +126 -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
package/audio_runtime.cpp
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
#define GEA_AUDIO_DRIVER_INTERNAL 1
|
|
3
3
|
#include "audio.h"
|
|
4
|
+
#include "audio_stream.h"
|
|
4
5
|
|
|
5
6
|
#include <algorithm>
|
|
6
7
|
#include <atomic>
|
|
@@ -36,6 +37,11 @@ constexpr int kQueueDepth = 16;
|
|
|
36
37
|
// the 2.06 AMOLED rebooted every 3 seconds). The task logs its high-water
|
|
37
38
|
// mark once after the driver opens so the next reader sizes it from a number.
|
|
38
39
|
constexpr int kTaskStackBytes = 8192;
|
|
40
|
+
// PCM feeding has a hardware deadline. The AMOLED UI runs at priority 23;
|
|
41
|
+
// letting it preempt this task produced 142 ms writes for 32 ms chunks even
|
|
42
|
+
// with PCM available, exceeding the 90 ms DMA ring. Mixing is bounded and
|
|
43
|
+
// the I2S write blocks for pacing, so audio can safely preempt rendering.
|
|
44
|
+
constexpr UBaseType_t kTaskPriority = configMAX_PRIORITIES - 1;
|
|
39
45
|
constexpr int kChunkSamples = 512;
|
|
40
46
|
constexpr int kAmplitude = 5200;
|
|
41
47
|
constexpr int kMaxOscillators = 8;
|
|
@@ -176,17 +182,45 @@ public:
|
|
|
176
182
|
}
|
|
177
183
|
|
|
178
184
|
void stopPlayback() {
|
|
185
|
+
streams_.clear();
|
|
179
186
|
clearTones();
|
|
180
187
|
driverOpen_.store(false, std::memory_order_release);
|
|
181
188
|
audio::OutputDriver::close();
|
|
182
189
|
}
|
|
183
190
|
|
|
191
|
+
std::uint64_t playPcmStream(audio::PcmStreamMixer::Pull pull) {
|
|
192
|
+
#if GEA_EMBEDDED_AUDIO_DISABLED
|
|
193
|
+
return 0;
|
|
194
|
+
#else
|
|
195
|
+
ensureTask();
|
|
196
|
+
if (!audioTask_ || !toneQueue_) return 0;
|
|
197
|
+
// Half-duplex capture can close the speaker between replies. Revalidate
|
|
198
|
+
// its hardware state when the first playback source attaches again.
|
|
199
|
+
if (!streams_.active()) driverOpen_.store(false, std::memory_order_release);
|
|
200
|
+
auto handle = streams_.add(std::move(pull));
|
|
201
|
+
// Wake a task waiting for a tone without manufacturing an audible note.
|
|
202
|
+
Tone wake;
|
|
203
|
+
wake.wakeOnly = true;
|
|
204
|
+
xQueueSend(toneQueue_, &wake, 0);
|
|
205
|
+
return handle;
|
|
206
|
+
#endif
|
|
207
|
+
}
|
|
208
|
+
void flushPlayback() {
|
|
209
|
+
// The sole output consumer cancels DMA before its next pull. A write
|
|
210
|
+
// already in progress finishes BEFORE that cancellation. Never wait for
|
|
211
|
+
// a driver/mixer lock on the microphone's audio-worklet thread.
|
|
212
|
+
flushPending_.store(true, std::memory_order_release);
|
|
213
|
+
}
|
|
214
|
+
void stopPcmStream(std::uint64_t handle) { streams_.remove(handle); }
|
|
215
|
+
bool pcmStreamSettled(std::uint64_t handle) { return streams_.settled(handle); }
|
|
216
|
+
|
|
184
217
|
private:
|
|
185
218
|
struct Tone {
|
|
186
219
|
audio::OscillatorType type = audio::OscillatorType::Sine;
|
|
187
220
|
double frequencyHz = 440.0;
|
|
188
221
|
int durationMs = 0;
|
|
189
222
|
int delayMs = 0;
|
|
223
|
+
bool wakeOnly = false;
|
|
190
224
|
};
|
|
191
225
|
|
|
192
226
|
struct OscillatorState {
|
|
@@ -316,6 +350,7 @@ private:
|
|
|
316
350
|
}
|
|
317
351
|
|
|
318
352
|
void addActiveTone(Tone tone) {
|
|
353
|
+
if (tone.wakeOnly) return;
|
|
319
354
|
normalizeTone(tone);
|
|
320
355
|
|
|
321
356
|
const int totalSamples = (kSampleRate * tone.durationMs) / 1000;
|
|
@@ -383,8 +418,13 @@ private:
|
|
|
383
418
|
Tone tone;
|
|
384
419
|
std::int16_t pcm[kChunkSamples * kChannels];
|
|
385
420
|
int idleChunks = 0;
|
|
421
|
+
int64_t previousWriteEnd = 0, cadenceStart = 0, maxSupplyGap = 0, maxWriteUs = 0;
|
|
422
|
+
std::size_t cadenceFrames = 0, emptyPulls = 0;
|
|
386
423
|
|
|
387
424
|
while (true) {
|
|
425
|
+
if (flushPending_.exchange(false, std::memory_order_acq_rel) &&
|
|
426
|
+
driverOpen_.load(std::memory_order_acquire) && !audio::OutputDriver::flush())
|
|
427
|
+
ESP_LOGW(kTag, "Unable to discard speaker DMA samples");
|
|
388
428
|
if (exclusivePlayback_.load(std::memory_order_acquire)) {
|
|
389
429
|
clearTones();
|
|
390
430
|
idleChunks = 0;
|
|
@@ -397,7 +437,10 @@ private:
|
|
|
397
437
|
idleChunks = 0;
|
|
398
438
|
}
|
|
399
439
|
|
|
400
|
-
|
|
440
|
+
const bool streaming = streams_.active();
|
|
441
|
+
if (!hasActiveTones() && !streaming) {
|
|
442
|
+
previousWriteEnd = cadenceStart = maxSupplyGap = maxWriteUs = 0;
|
|
443
|
+
cadenceFrames = emptyPulls = 0;
|
|
401
444
|
if (!driverOpen_.load(std::memory_order_acquire)) {
|
|
402
445
|
if (xQueueReceive(toneQueue_, &tone, portMAX_DELAY) == pdTRUE) {
|
|
403
446
|
addActiveTone(tone);
|
|
@@ -426,6 +469,8 @@ private:
|
|
|
426
469
|
}
|
|
427
470
|
}
|
|
428
471
|
|
|
472
|
+
// Open before consuming PCM, so codec initialization cannot discard
|
|
473
|
+
// the first packet of a reply when capture is still relinquishing I2S.
|
|
429
474
|
if (!driverOpen_.load(std::memory_order_acquire)) {
|
|
430
475
|
if (!audio::OutputDriver::open(kSampleRate, kChannels, 16)) {
|
|
431
476
|
vTaskDelay(pdMS_TO_TICKS(50));
|
|
@@ -441,9 +486,37 @@ private:
|
|
|
441
486
|
}
|
|
442
487
|
}
|
|
443
488
|
|
|
489
|
+
const bool tones = hasActiveTones();
|
|
444
490
|
renderChunk(pcm, kChunkSamples);
|
|
445
|
-
|
|
491
|
+
const auto streamFrames = streams_.mix(pcm, kChunkSamples);
|
|
492
|
+
const auto outputFrames = tones ? std::size_t(kChunkSamples) : streamFrames;
|
|
493
|
+
if (outputFrames == 0) {
|
|
494
|
+
++emptyPulls;
|
|
495
|
+
// Empty between RTP packets means wait for data, never end a stream.
|
|
496
|
+
vTaskDelay(pdMS_TO_TICKS(5));
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const int64_t writeStart = esp_timer_get_time();
|
|
501
|
+
if (!cadenceStart) cadenceStart = writeStart;
|
|
502
|
+
if (previousWriteEnd) maxSupplyGap = std::max(maxSupplyGap, writeStart - previousWriteEnd);
|
|
503
|
+
const bool wrote = audio::OutputDriver::write(pcm, outputFrames * kChannels, kWriteTimeoutMs);
|
|
504
|
+
previousWriteEnd = esp_timer_get_time();
|
|
505
|
+
maxWriteUs = std::max(maxWriteUs, previousWriteEnd - writeStart);
|
|
506
|
+
cadenceFrames += outputFrames;
|
|
507
|
+
if (streaming && previousWriteEnd - cadenceStart >= 2000000) {
|
|
508
|
+
ESP_LOGI(kTag, "PCM cadence span_ms=%lld frames=%u empty_pulls=%u max_supply_gap_ms=%lld max_write_ms=%lld",
|
|
509
|
+
static_cast<long long>((previousWriteEnd - cadenceStart) / 1000),
|
|
510
|
+
static_cast<unsigned>(cadenceFrames), static_cast<unsigned>(emptyPulls),
|
|
511
|
+
static_cast<long long>(maxSupplyGap / 1000), static_cast<long long>(maxWriteUs / 1000));
|
|
512
|
+
cadenceStart = previousWriteEnd;
|
|
513
|
+
cadenceFrames = emptyPulls = 0;
|
|
514
|
+
maxSupplyGap = maxWriteUs = 0;
|
|
515
|
+
}
|
|
516
|
+
streams_.didWrite(wrote);
|
|
517
|
+
if (!wrote) {
|
|
446
518
|
ESP_LOGW(kTag, "PCM write failed");
|
|
519
|
+
driverOpen_.store(false, std::memory_order_release);
|
|
447
520
|
vTaskDelay(pdMS_TO_TICKS(10));
|
|
448
521
|
}
|
|
449
522
|
}
|
|
@@ -484,7 +557,7 @@ private:
|
|
|
484
557
|
"gea_audio",
|
|
485
558
|
kTaskStackBytes,
|
|
486
559
|
this,
|
|
487
|
-
|
|
560
|
+
kTaskPriority,
|
|
488
561
|
audioTaskStack_,
|
|
489
562
|
&audioTaskStorage_);
|
|
490
563
|
#if GEA_AUDIO_DEBUG_TIMING
|
|
@@ -543,6 +616,7 @@ private:
|
|
|
543
616
|
static constexpr const char *kTag = "gea_audio";
|
|
544
617
|
|
|
545
618
|
QueueHandle_t toneQueue_ = nullptr;
|
|
619
|
+
audio::PcmStreamMixer streams_;
|
|
546
620
|
TaskHandle_t audioTask_ = nullptr;
|
|
547
621
|
OscillatorState oscillators_[kMaxOscillators]{};
|
|
548
622
|
ActiveTone activeTones_[kMaxActiveTones]{};
|
|
@@ -553,6 +627,7 @@ private:
|
|
|
553
627
|
StaticTask_t audioTaskStorage_{};
|
|
554
628
|
StackType_t audioTaskStack_[kTaskStackBytes]{};
|
|
555
629
|
std::atomic<bool> exclusivePlayback_{false};
|
|
630
|
+
std::atomic<bool> flushPending_{false};
|
|
556
631
|
std::atomic<bool> driverOpen_{false};
|
|
557
632
|
bool audioTaskFailureLogged_ = false;
|
|
558
633
|
bool stackReported_ = false;
|
|
@@ -776,6 +851,12 @@ audio::OscillatorNode audio::AudioContext::createOscillator() const {
|
|
|
776
851
|
return audio::OscillatorNode(AudioEngine::instance().createOscillator());
|
|
777
852
|
}
|
|
778
853
|
|
|
854
|
+
// Drivers without a latency estimate retain the standard unknown value, zero.
|
|
855
|
+
__attribute__((weak)) double audio::OutputDriver::outputLatency(int) { return 0; }
|
|
856
|
+
__attribute__((weak)) bool audio::OutputDriver::flush() { return false; }
|
|
857
|
+
double audio::AudioSystem::processingLatency() { return double(kChunkSamples) / kSampleRate; }
|
|
858
|
+
double audio::AudioSystem::outputLatency() { return audio::OutputDriver::outputLatency(kSampleRate); }
|
|
859
|
+
|
|
779
860
|
audio::AudioContext audio::AudioSystem::sharedContext() {
|
|
780
861
|
return audio::AudioContext{};
|
|
781
862
|
}
|
|
@@ -805,3 +886,16 @@ bool audio::AudioSystem::playPcm(const std::int16_t *samples, std::size_t sample
|
|
|
805
886
|
void audio::AudioSystem::stopPlayback() {
|
|
806
887
|
AudioEngine::instance().stopPlayback();
|
|
807
888
|
}
|
|
889
|
+
void audio::AudioSystem::flushPlayback() {
|
|
890
|
+
AudioEngine::instance().flushPlayback();
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
std::uint64_t audio::AudioSystem::playPcmStream(audio::PcmStreamMixer::Pull pull) {
|
|
894
|
+
return AudioEngine::instance().playPcmStream(std::move(pull));
|
|
895
|
+
}
|
|
896
|
+
void audio::AudioSystem::stopPcmStream(std::uint64_t stream) {
|
|
897
|
+
AudioEngine::instance().stopPcmStream(stream);
|
|
898
|
+
}
|
|
899
|
+
bool audio::AudioSystem::pcmStreamSettled(std::uint64_t stream) {
|
|
900
|
+
return AudioEngine::instance().pcmStreamSettled(stream);
|
|
901
|
+
}
|
package/host/audio.cpp
CHANGED
|
@@ -1,13 +1,36 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
#include "audio.h"
|
|
3
|
+
#include "host/audio_level.h"
|
|
4
|
+
#include "host/pcm_stream.h"
|
|
5
|
+
#include "host/websocket.h"
|
|
6
|
+
#include <deque>
|
|
7
|
+
#include <mutex>
|
|
8
|
+
#include <chrono>
|
|
3
9
|
#include "gea/embedded-host.h"
|
|
4
10
|
#include "ui/document.h" // host/audio.cpp HTMLAudioElement bridge (entangled — moves to elements)
|
|
5
11
|
|
|
12
|
+
#include <atomic>
|
|
13
|
+
#include <cmath>
|
|
6
14
|
#include <cstddef>
|
|
7
15
|
#include <cstdint>
|
|
8
16
|
#include <cstring>
|
|
9
17
|
#include <utility>
|
|
18
|
+
#include <unordered_map>
|
|
10
19
|
#include <vector>
|
|
20
|
+
#include <stdexcept>
|
|
21
|
+
#ifdef ESP_PLATFORM
|
|
22
|
+
#include "esp_log.h"
|
|
23
|
+
#endif
|
|
24
|
+
|
|
25
|
+
// Platforms without the streaming output engine reject attachment. The ESP
|
|
26
|
+
// audio runtime supplies the strong definitions through its existing task.
|
|
27
|
+
namespace gea::platform::audio {
|
|
28
|
+
__attribute__((weak)) std::uint64_t AudioSystem::playPcmStream(std::function<std::size_t(std::int16_t*, std::size_t)>) { return 0; }
|
|
29
|
+
__attribute__((weak)) void AudioSystem::stopPcmStream(std::uint64_t) {}
|
|
30
|
+
__attribute__((weak)) bool AudioSystem::pcmStreamSettled(std::uint64_t) { return false; }
|
|
31
|
+
__attribute__((weak)) double AudioSystem::processingLatency() { return 0; }
|
|
32
|
+
__attribute__((weak)) double AudioSystem::outputLatency() { return 0; }
|
|
33
|
+
}
|
|
11
34
|
|
|
12
35
|
namespace gea::framework::host {
|
|
13
36
|
|
|
@@ -115,7 +138,9 @@ AudioBuffer decodePcm16Wav(const std::vector<std::uint8_t> &bytes) {
|
|
|
115
138
|
} // namespace
|
|
116
139
|
|
|
117
140
|
AudioDestinationProperty::operator AudioDestinationNode() const {
|
|
118
|
-
|
|
141
|
+
AudioDestinationNode result(gea::framework::host::AudioHost::context().destination().nativeId());
|
|
142
|
+
result.context = context;
|
|
143
|
+
return result;
|
|
119
144
|
}
|
|
120
145
|
|
|
121
146
|
AudioDestinationProperty::operator double() const {
|
|
@@ -123,9 +148,23 @@ AudioDestinationProperty::operator double() const {
|
|
|
123
148
|
}
|
|
124
149
|
|
|
125
150
|
AudioContextCurrentTimeProperty::operator double() const {
|
|
151
|
+
if (context) return audio_worklet::contextTime(context);
|
|
126
152
|
return gea::framework::host::AudioHost::context().currentTime();
|
|
127
153
|
}
|
|
128
154
|
|
|
155
|
+
AudioContext::AudioContext(double rate)
|
|
156
|
+
: state_(audio_worklet::createContext(rate)), sampleRate(rate),
|
|
157
|
+
destination{state_}, currentTime{state_}, audioWorklet(state_) {}
|
|
158
|
+
double AudioContext::baseLatency() const { return audio_worklet::contextBaseLatency(state_); }
|
|
159
|
+
double AudioContext::outputLatency() const { return gea::platform::audio::AudioSystem::outputLatency(); }
|
|
160
|
+
std::string AudioContext::state() const { return audio_worklet::contextState(state_); }
|
|
161
|
+
void AudioContext::resume() const { audio_worklet::resume(state_); }
|
|
162
|
+
void AudioContext::suspend() const { audio_worklet::suspend(state_); }
|
|
163
|
+
void AudioContext::close() const { audio_worklet::close(state_); }
|
|
164
|
+
MediaStreamAudioSourceNode AudioContext::createMediaStreamSource(MediaStream stream) const {
|
|
165
|
+
return MediaStreamAudioSourceNode(state_, stream);
|
|
166
|
+
}
|
|
167
|
+
|
|
129
168
|
const AudioParamValueProperty &AudioParamValueProperty::operator=(double frequency_hz) const {
|
|
130
169
|
gea::framework::host::AudioHost::oscillator(oscillatorHandle).frequency.setValue(frequency_hz);
|
|
131
170
|
return *this;
|
|
@@ -213,28 +252,374 @@ AudioBuffer AudioContext::decodeAudioData(const std::vector<std::uint8_t> &bytes
|
|
|
213
252
|
return decodePcm16Wav(bytes);
|
|
214
253
|
}
|
|
215
254
|
|
|
216
|
-
HTMLAudioElement::
|
|
255
|
+
struct HTMLAudioElement::State {
|
|
256
|
+
static std::unordered_map<int, std::weak_ptr<State>>& registry() {
|
|
257
|
+
static std::unordered_map<int, std::weak_ptr<State>> states;
|
|
258
|
+
return states;
|
|
259
|
+
}
|
|
260
|
+
int nodeId = -1;
|
|
261
|
+
std::string src;
|
|
262
|
+
MediaStream source;
|
|
263
|
+
std::uint64_t output = 0;
|
|
264
|
+
std::shared_ptr<media::TrackPcmReader> reader;
|
|
265
|
+
std::shared_ptr<AudioLevelMeter> level = std::make_shared<AudioLevelMeter>();
|
|
266
|
+
bool autoplay = false, paused = true, freshSource = true, draining = false;
|
|
267
|
+
~State() { if (output) gea::platform::audio::AudioSystem::stopPcmStream(output); }
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
HTMLAudioElement HTMLAudioElement::create() {
|
|
271
|
+
HTMLAudioElement result;
|
|
272
|
+
result.state_ = std::make_shared<State>();
|
|
273
|
+
return result;
|
|
274
|
+
}
|
|
275
|
+
HTMLAudioElement HTMLAudioElement::create(const std::string& src) { return HTMLAudioElement(src); }
|
|
276
|
+
|
|
277
|
+
HTMLAudioElement::HTMLAudioElement(const char *src) : HTMLAudioElement(std::string(src ? src : "")) {}
|
|
217
278
|
|
|
218
|
-
HTMLAudioElement::HTMLAudioElement(const std::string &src) :
|
|
279
|
+
HTMLAudioElement::HTMLAudioElement(const std::string &src) : state_(std::make_shared<State>()) { state_->src = src; }
|
|
219
280
|
|
|
220
|
-
HTMLAudioElement::HTMLAudioElement(const gea::embedded::ui::NodeHandle &node)
|
|
281
|
+
HTMLAudioElement::HTMLAudioElement(const gea::embedded::ui::NodeHandle &node) {
|
|
282
|
+
if (!node.valid()) return;
|
|
283
|
+
auto& entry = State::registry()[node.id()];
|
|
284
|
+
state_ = entry.lock();
|
|
285
|
+
if (!state_) {
|
|
286
|
+
state_ = std::make_shared<State>();
|
|
287
|
+
state_->nodeId = node.id();
|
|
288
|
+
entry = state_;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
221
291
|
|
|
222
292
|
std::string HTMLAudioElement::src() const {
|
|
223
|
-
if (
|
|
224
|
-
return
|
|
293
|
+
if (!state_) return {};
|
|
294
|
+
if (state_->nodeId >= 0) return std::string(gea::embedded::ui::NodeHandle(state_->nodeId).getAttribute("src"));
|
|
295
|
+
return state_->src;
|
|
225
296
|
}
|
|
226
297
|
|
|
227
298
|
void HTMLAudioElement::setSrc(const std::string &src) {
|
|
228
|
-
if (
|
|
229
|
-
|
|
299
|
+
if (!state_) throw std::logic_error("null HTMLAudioElement");
|
|
300
|
+
if (state_->nodeId >= 0) gea::embedded::ui::NodeHandle(state_->nodeId).setAttribute("src", src.c_str());
|
|
301
|
+
state_->src = src;
|
|
230
302
|
}
|
|
231
303
|
|
|
232
304
|
bool HTMLAudioElement::play() const {
|
|
233
|
-
|
|
305
|
+
if (!state_) return false;
|
|
306
|
+
if (state_->draining) pause();
|
|
307
|
+
if (state_->output) return true;
|
|
308
|
+
if (state_->source.nativeHandle) {
|
|
309
|
+
const auto tracks = state_->source.getAudioTracks();
|
|
310
|
+
if (tracks.empty() || tracks.front().readyState() == "ended") return false;
|
|
311
|
+
auto reader = state_->reader;
|
|
312
|
+
if (!reader) reader = std::make_shared<media::TrackPcmReader>(tracks.front().nativeHandle, state_->freshSource);
|
|
313
|
+
state_->reader = reader;
|
|
314
|
+
auto level = state_->level;
|
|
315
|
+
state_->output = gea::platform::audio::AudioSystem::playPcmStream(
|
|
316
|
+
[reader, level](std::int16_t* samples, std::size_t count) {
|
|
317
|
+
const auto read = reader->read(samples, count);
|
|
318
|
+
const auto now = std::chrono::steady_clock::now().time_since_epoch();
|
|
319
|
+
level->update(samples, read, static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(now).count()));
|
|
320
|
+
return read;
|
|
321
|
+
});
|
|
322
|
+
if (!state_->output) { state_->reader.reset(); return false; }
|
|
323
|
+
state_->freshSource = false;
|
|
324
|
+
state_->paused = false;
|
|
325
|
+
return true;
|
|
326
|
+
}
|
|
327
|
+
const bool ok = gea::platform::audio::AudioSystem::playFile(src());
|
|
328
|
+
state_->paused = !ok;
|
|
329
|
+
return ok;
|
|
234
330
|
}
|
|
235
331
|
|
|
236
332
|
void HTMLAudioElement::pause() const {
|
|
237
|
-
|
|
333
|
+
if (!state_) return;
|
|
334
|
+
state_->draining = false;
|
|
335
|
+
if (state_->output) {
|
|
336
|
+
#ifdef ESP_PLATFORM
|
|
337
|
+
ESP_LOGI("gea::host::audio", "pause: queued samples=%u dropped=%u",
|
|
338
|
+
static_cast<unsigned>(state_->reader ? state_->reader->pendingSamples() : 0),
|
|
339
|
+
static_cast<unsigned>(state_->reader ? state_->reader->droppedSamples() : 0));
|
|
340
|
+
#endif
|
|
341
|
+
gea::platform::audio::AudioSystem::stopPcmStream(state_->output);
|
|
342
|
+
state_->output = 0;
|
|
343
|
+
} else if (!state_->paused && !state_->source.nativeHandle) gea::platform::audio::AudioSystem::stopPlayback();
|
|
344
|
+
// Discard the cancelled reply at the interruption boundary, not when
|
|
345
|
+
// play() later resumes: new RTP can precede its SCTP response event.
|
|
346
|
+
if (state_->reader) state_->reader->discardBuffered();
|
|
347
|
+
state_->level->reset();
|
|
348
|
+
state_->paused = true;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
void HTMLAudioElement::clearBufferedAudio() const {
|
|
352
|
+
if (!state_) return;
|
|
353
|
+
if (state_->reader) state_->reader->discardBuffered();
|
|
354
|
+
state_->draining = false;
|
|
355
|
+
state_->level->reset();
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
double HTMLAudioElement::audioLevel() const {
|
|
359
|
+
if (!state_ || state_->paused) return 0;
|
|
360
|
+
const auto now = std::chrono::steady_clock::now().time_since_epoch();
|
|
361
|
+
return state_->level->read(static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(now).count()));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
void HTMLAudioElement::beginDrain() const {
|
|
365
|
+
if (!state_ || !state_->reader || state_->draining) return;
|
|
366
|
+
state_->draining = true;
|
|
367
|
+
state_->reader->beginDrain();
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
bool HTMLAudioElement::drained() const {
|
|
371
|
+
if (!state_ || state_->paused) return true;
|
|
372
|
+
return state_->draining && state_->reader && state_->reader->pendingSamples() == 0 &&
|
|
373
|
+
gea::platform::audio::AudioSystem::pcmStreamSettled(state_->output);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
MediaStream HTMLAudioElement::srcObject() const { return state_ ? state_->source : MediaStream{}; }
|
|
377
|
+
void HTMLAudioElement::setSrcObject(MediaStream stream) const {
|
|
378
|
+
if (!state_) throw std::logic_error("null HTMLAudioElement");
|
|
379
|
+
if (stream.nativeHandle == state_->source.nativeHandle) return;
|
|
380
|
+
const bool resume = !state_->paused || state_->autoplay;
|
|
381
|
+
pause();
|
|
382
|
+
state_->reader.reset();
|
|
383
|
+
state_->source = stream;
|
|
384
|
+
state_->freshSource = true;
|
|
385
|
+
if (stream.nativeHandle && resume) (void)play();
|
|
386
|
+
}
|
|
387
|
+
bool HTMLAudioElement::autoplay() const { return state_ && state_->autoplay; }
|
|
388
|
+
bool HTMLAudioElement::paused() const { return !state_ || state_->paused; }
|
|
389
|
+
void HTMLAudioElement::setAutoplay(bool enabled) const {
|
|
390
|
+
if (!state_) throw std::logic_error("null HTMLAudioElement");
|
|
391
|
+
state_->autoplay = enabled;
|
|
392
|
+
if (enabled && state_->source.nativeHandle && state_->paused) (void)play();
|
|
238
393
|
}
|
|
239
394
|
|
|
240
395
|
} // namespace gea::host
|
|
396
|
+
|
|
397
|
+
namespace gea::host {
|
|
398
|
+
namespace {
|
|
399
|
+
std::uint32_t pcmNowMs() {
|
|
400
|
+
return static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
401
|
+
std::chrono::steady_clock::now().time_since_epoch()).count());
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
struct PcmAudioStream::State {
|
|
406
|
+
explicit State(int rate) : capture(16000, rate), playback(rate, 16000), wireRate(rate) {}
|
|
407
|
+
~State() { if (output) gea::platform::audio::AudioSystem::stopPcmStream(output); }
|
|
408
|
+
std::shared_ptr<media::TrackPcmReader> reader;
|
|
409
|
+
std::mutex captureMutex;
|
|
410
|
+
std::atomic<std::uint32_t> capturePackets{0};
|
|
411
|
+
unsigned receivedPackets = 0;
|
|
412
|
+
pcm::Resampler capture, playback;
|
|
413
|
+
int wireRate;
|
|
414
|
+
std::mutex mutex;
|
|
415
|
+
std::mutex playbackInputMutex;
|
|
416
|
+
using Block = std::vector<std::int16_t, pcm::QueueAllocator<std::int16_t>>;
|
|
417
|
+
std::deque<Block> queue;
|
|
418
|
+
std::size_t queuedSamples = 0, readOffset = 0;
|
|
419
|
+
AudioLevelMeter level;
|
|
420
|
+
std::uint64_t output = 0, pulled = 0;
|
|
421
|
+
std::uint32_t lastPull = 0;
|
|
422
|
+
std::atomic<bool> closed{false};
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
PcmAudioStream PcmAudioStream::create(double sampleRate) {
|
|
426
|
+
if (sampleRate != 16000 && sampleRate != 24000 && sampleRate != 48000)
|
|
427
|
+
throw std::invalid_argument("PCM sample rate must be 16000, 24000 or 48000");
|
|
428
|
+
PcmAudioStream result;
|
|
429
|
+
result.state_ = std::make_shared<State>(static_cast<int>(sampleRate));
|
|
430
|
+
const std::weak_ptr<State> weak = result.state_;
|
|
431
|
+
result.state_->output = gea::platform::audio::AudioSystem::playPcmStream(
|
|
432
|
+
[weak](std::int16_t *out, std::size_t capacity) {
|
|
433
|
+
const auto state = weak.lock();
|
|
434
|
+
if (!state) return std::size_t{0};
|
|
435
|
+
std::lock_guard<std::mutex> lock(state->mutex);
|
|
436
|
+
const auto count = std::min(capacity, state->queuedSamples);
|
|
437
|
+
std::size_t copied = 0;
|
|
438
|
+
while (copied < count) {
|
|
439
|
+
const auto &block = state->queue.front();
|
|
440
|
+
const auto n = std::min(count - copied, block.size() - state->readOffset);
|
|
441
|
+
std::copy_n(block.data() + state->readOffset, n, out + copied);
|
|
442
|
+
state->readOffset += n;
|
|
443
|
+
copied += n;
|
|
444
|
+
if (state->readOffset == block.size()) {
|
|
445
|
+
state->queue.pop_front();
|
|
446
|
+
state->readOffset = 0;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
state->queuedSamples -= count;
|
|
450
|
+
if (count) {
|
|
451
|
+
state->pulled += count;
|
|
452
|
+
state->lastPull = pcmNowMs();
|
|
453
|
+
state->level.update(out, count, state->lastPull);
|
|
454
|
+
}
|
|
455
|
+
return count;
|
|
456
|
+
});
|
|
457
|
+
if (!result.state_->output) throw std::runtime_error("PCM output unavailable");
|
|
458
|
+
return result;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
void PcmAudioStream::setInput(MediaStream stream) const {
|
|
462
|
+
if (!state_) throw std::logic_error("Closed PCM stream");
|
|
463
|
+
std::lock_guard<std::mutex> lock(state_->captureMutex);
|
|
464
|
+
if (state_->closed) throw std::logic_error("Closed PCM stream");
|
|
465
|
+
const auto tracks = stream.getAudioTracks();
|
|
466
|
+
if (tracks.empty()) throw std::invalid_argument("PCM input needs an audio track");
|
|
467
|
+
state_->reader = std::make_shared<media::TrackPcmReader>(tracks.front().nativeHandle);
|
|
468
|
+
state_->capture.reset();
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
void PcmAudioStream::pipeTo(WebSocket socket, const std::string &prefix, const std::string &suffix) const {
|
|
472
|
+
if (!state_ || state_->closed) throw std::logic_error("Closed PCM stream");
|
|
473
|
+
const std::weak_ptr<State> weak = state_;
|
|
474
|
+
websocket::setTextProducer(socket.nativeHandle, [weak, prefix, suffix]() -> std::string {
|
|
475
|
+
PcmAudioStream stream;
|
|
476
|
+
stream.state_ = weak.lock();
|
|
477
|
+
if (!stream.state_ || stream.state_->closed) return {};
|
|
478
|
+
if (stream.captureDroppedSamples() > 0)
|
|
479
|
+
throw std::runtime_error("Microphone capture overflowed during native upload");
|
|
480
|
+
auto pcm = stream.readBase64();
|
|
481
|
+
if (pcm.empty() || stream.state_->closed) return {};
|
|
482
|
+
// Base64 has no JSON quote/backslash characters; framing needs no JSON
|
|
483
|
+
// serializer. The provider-specific envelope is supplied by TypeScript.
|
|
484
|
+
std::string packet;
|
|
485
|
+
packet.reserve(prefix.size() + pcm.size() + suffix.size());
|
|
486
|
+
packet.append(prefix).append(pcm).append(suffix);
|
|
487
|
+
const auto sent = ++stream.state_->capturePackets;
|
|
488
|
+
#ifdef ESP_PLATFORM
|
|
489
|
+
if (sent % 50 == 0) ESP_LOGI("gea_pcm", "native capture packets=%u pending_ms=%u dropped=%u",
|
|
490
|
+
unsigned(sent), unsigned(stream.capturePendingMs()), unsigned(stream.captureDroppedSamples()));
|
|
491
|
+
#endif
|
|
492
|
+
return packet;
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
void PcmAudioStream::receiveFrom(WebSocket socket, const std::string& prefix, const std::string& suffix) const {
|
|
497
|
+
if (!state_ || state_->closed) throw std::logic_error("Closed PCM stream");
|
|
498
|
+
const std::weak_ptr<State> weak = state_;
|
|
499
|
+
websocket::setTextConsumer(socket.nativeHandle, [weak, prefix, suffix](const std::string& message) {
|
|
500
|
+
if (message.size() < prefix.size() + suffix.size() ||
|
|
501
|
+
!message.starts_with(prefix) || !message.ends_with(suffix)) return false;
|
|
502
|
+
PcmAudioStream stream;
|
|
503
|
+
stream.state_ = weak.lock();
|
|
504
|
+
if (!stream.state_ || stream.state_->closed) return true;
|
|
505
|
+
const auto size = message.size() - prefix.size() - suffix.size();
|
|
506
|
+
if (size > 4096) throw std::runtime_error("PCM packet exceeded native receive bound");
|
|
507
|
+
stream.writeBase64(message.substr(prefix.size(), size));
|
|
508
|
+
return true;
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
std::string PcmAudioStream::readBase64() const {
|
|
513
|
+
const auto started = pcmNowMs();
|
|
514
|
+
if (!state_) return {};
|
|
515
|
+
std::lock_guard<std::mutex> lock(state_->captureMutex);
|
|
516
|
+
if (state_->closed || !state_->reader || state_->reader->pendingSamples() < 640) return {};
|
|
517
|
+
std::int16_t input[640];
|
|
518
|
+
const auto count = state_->reader->read(input, 640);
|
|
519
|
+
const auto readAt = pcmNowMs();
|
|
520
|
+
std::vector<std::int16_t> wire;
|
|
521
|
+
wire.reserve(1920);
|
|
522
|
+
for (std::size_t i = 0; i < count; ++i)
|
|
523
|
+
state_->capture.push(input[i], [&](std::int16_t sample) { wire.push_back(sample); });
|
|
524
|
+
const auto resampledAt = pcmNowMs();
|
|
525
|
+
auto encoded = pcm::encode(wire);
|
|
526
|
+
#ifdef ESP_PLATFORM
|
|
527
|
+
if (pcmNowMs() - started > 15) ESP_LOGW("gea_pcm", "capture read_ms=%u resample_ms=%u encode_ms=%u", readAt-started, resampledAt-readAt, pcmNowMs()-resampledAt);
|
|
528
|
+
#endif
|
|
529
|
+
return encoded;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
void PcmAudioStream::writeBase64(const std::string &data) const {
|
|
533
|
+
if (!state_) return;
|
|
534
|
+
std::lock_guard inputLock(state_->playbackInputMutex);
|
|
535
|
+
if (state_->closed) return;
|
|
536
|
+
const auto started = pcmNowMs();
|
|
537
|
+
const auto wire = pcm::decode(data);
|
|
538
|
+
const auto decodedAt = pcmNowMs();
|
|
539
|
+
// Resampling and allocation never hold the real-time mixer's queue mutex.
|
|
540
|
+
State::Block block;
|
|
541
|
+
block.reserve(wire.size() * 16000 / state_->wireRate + 2);
|
|
542
|
+
for (auto sample : wire)
|
|
543
|
+
state_->playback.push(sample, [&](std::int16_t value) { block.push_back(value); });
|
|
544
|
+
std::lock_guard<std::mutex> lock(state_->mutex);
|
|
545
|
+
// Generated output may run faster than playback. Never silently overwrite
|
|
546
|
+
// the unplayed tail (MediaStream's live capture ring has different semantics).
|
|
547
|
+
if (state_->queuedSamples + block.size() > 16000 * 30)
|
|
548
|
+
throw std::runtime_error("PCM playback exceeded 30 second queue limit");
|
|
549
|
+
if (!block.empty()) {
|
|
550
|
+
state_->queuedSamples += block.size();
|
|
551
|
+
state_->queue.push_back(std::move(block));
|
|
552
|
+
}
|
|
553
|
+
#ifdef ESP_PLATFORM
|
|
554
|
+
if (++state_->receivedPackets == 1 || state_->receivedPackets % 100 == 0)
|
|
555
|
+
ESP_LOGI("gea_pcm", "native receive packets=%u queued_ms=%u", state_->receivedPackets,
|
|
556
|
+
unsigned(state_->queuedSamples * 1000 / 16000));
|
|
557
|
+
if (pcmNowMs()-started > 15) ESP_LOGW("gea_pcm", "playback samples=%u decode_ms=%u resample_queue_ms=%u", unsigned(wire.size()), decodedAt-started, pcmNowMs()-decodedAt);
|
|
558
|
+
#endif
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
void PcmAudioStream::resetPlayback(bool interrupted) const {
|
|
562
|
+
if (!state_) return;
|
|
563
|
+
std::lock_guard inputLock(state_->playbackInputMutex);
|
|
564
|
+
std::lock_guard<std::mutex> lock(state_->mutex);
|
|
565
|
+
state_->queue.clear();
|
|
566
|
+
state_->queuedSamples = state_->readOffset = 0;
|
|
567
|
+
state_->playback.reset();
|
|
568
|
+
state_->pulled = 0;
|
|
569
|
+
state_->lastPull = 0;
|
|
570
|
+
state_->level.reset();
|
|
571
|
+
if (interrupted) gea::platform::audio::AudioSystem::flushPlayback();
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
void PcmAudioStream::close() const {
|
|
575
|
+
if (!state_ || state_->closed.exchange(true)) return;
|
|
576
|
+
if (state_->output) gea::platform::audio::AudioSystem::stopPcmStream(state_->output);
|
|
577
|
+
state_->output = 0;
|
|
578
|
+
gea::platform::audio::AudioSystem::flushPlayback();
|
|
579
|
+
{
|
|
580
|
+
std::lock_guard<std::mutex> lock(state_->captureMutex);
|
|
581
|
+
state_->reader.reset();
|
|
582
|
+
}
|
|
583
|
+
resetPlayback();
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
double PcmAudioStream::queuedMs() const {
|
|
587
|
+
if (!state_) return 0;
|
|
588
|
+
std::lock_guard<std::mutex> lock(state_->mutex);
|
|
589
|
+
return state_->queuedSamples / 16.0;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
double PcmAudioStream::playedMs() const {
|
|
593
|
+
if (!state_) return 0;
|
|
594
|
+
std::lock_guard<std::mutex> lock(state_->mutex);
|
|
595
|
+
// Pulling submits up to 32ms to the mixer, ahead of up to 90ms of I2S DMA.
|
|
596
|
+
// This conservative bound never reports queued network data as heard audio.
|
|
597
|
+
const auto elapsed = static_cast<std::uint32_t>(pcmNowMs() - state_->lastPull);
|
|
598
|
+
const double inFlight = elapsed >= 122 ? 0 : 122 - elapsed;
|
|
599
|
+
return std::max(0.0, state_->pulled / 16.0 - inFlight);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
bool PcmAudioStream::drained() const {
|
|
603
|
+
if (!state_ || state_->closed) return true;
|
|
604
|
+
bool empty;
|
|
605
|
+
{
|
|
606
|
+
std::lock_guard<std::mutex> lock(state_->mutex);
|
|
607
|
+
empty = state_->queue.empty() && (!state_->pulled ||
|
|
608
|
+
static_cast<std::uint32_t>(pcmNowMs() - state_->lastPull) >= 122);
|
|
609
|
+
}
|
|
610
|
+
return empty && gea::platform::audio::AudioSystem::pcmStreamSettled(state_->output);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
double PcmAudioStream::audioLevel() const { return state_ ? state_->level.read(pcmNowMs()) : 0; }
|
|
614
|
+
double PcmAudioStream::capturePendingMs() const {
|
|
615
|
+
if (!state_) return 0;
|
|
616
|
+
std::lock_guard<std::mutex> lock(state_->captureMutex);
|
|
617
|
+
return state_->reader ? state_->reader->pendingSamples() / 16.0 : 0;
|
|
618
|
+
}
|
|
619
|
+
double PcmAudioStream::captureDroppedSamples() const {
|
|
620
|
+
if (!state_) return 0;
|
|
621
|
+
std::lock_guard<std::mutex> lock(state_->captureMutex);
|
|
622
|
+
return state_->reader ? state_->reader->droppedSamples() : 0;
|
|
623
|
+
}
|
|
624
|
+
double PcmAudioStream::capturePackets() const { return state_ ? state_->capturePackets.load() : 0; }
|
|
625
|
+
} // namespace gea::host
|