@geastack/host 0.1.13 → 0.1.15

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 CHANGED
@@ -2,6 +2,7 @@
2
2
  #define GEA_AUDIO_DRIVER_INTERNAL 1
3
3
  #include "audio.h"
4
4
  #include "audio_stream.h"
5
+ #include "audio_oscillator.h"
5
6
 
6
7
  #include <algorithm>
7
8
  #include <atomic>
@@ -20,11 +21,15 @@
20
21
  #include "freertos/task.h"
21
22
  #include "platform/file_cache.h"
22
23
 
24
+ // Optional build-embedded asset registry supplied by the native app pipeline.
25
+ extern "C" bool gea_embedded_asset_lookup(const char*, const unsigned char**, unsigned long*)
26
+ __attribute__((weak));
27
+
23
28
  namespace audio = gea::platform::audio;
24
29
 
25
30
  namespace {
26
31
 
27
- constexpr int kSampleRate = 16000;
32
+ constexpr int kSampleRate = audio::deviceSampleRate;
28
33
  constexpr int kChannels = 2;
29
34
  constexpr int kQueueDepth = 16;
30
35
  // ESP-IDF sizes a task stack in BYTES (`StackType_t` is `uint8_t` on this
@@ -134,29 +139,21 @@ public:
134
139
  void startOscillator(audio::NativeAudioHandle handle, double when) {
135
140
  auto *osc = oscillator(handle);
136
141
  if (!osc) return;
137
- if (when <= 0.0) when = currentTime();
138
- osc->startTime = when;
139
- osc->started = true;
142
+ osc->schedule.start(when, currentTime());
140
143
  }
141
144
 
142
145
  void stopOscillator(audio::NativeAudioHandle handle, double when) {
143
146
  auto *osc = oscillator(handle);
144
147
  if (!osc || !osc->connected) return;
145
148
 
146
- const double now = currentTime();
147
- const double startTime = osc->started ? osc->startTime : now;
148
- if (when <= 0.0) when = now;
149
- if (when < startTime) when = startTime;
150
-
151
- const int durationMs = static_cast<int>((when - startTime) * 1000.0 + 0.5);
152
- const int delayMs = startTime > now ? static_cast<int>((startTime - now) * 1000.0 + 0.5) : 0;
153
- if (durationMs <= 0) return;
149
+ const auto timing = osc->schedule.stop(when, currentTime());
150
+ if (!timing) return;
154
151
 
155
152
  submitTone(Tone{
156
153
  osc->type,
157
154
  osc->frequencyHz,
158
- durationMs,
159
- delayMs,
155
+ timing->durationMs,
156
+ timing->delayMs,
160
157
  });
161
158
  }
162
159
 
@@ -228,8 +225,7 @@ private:
228
225
  audio::OscillatorType type = audio::OscillatorType::Sine;
229
226
  double frequencyHz = 440.0;
230
227
  bool connected = false;
231
- bool started = false;
232
- double startTime = 0.0;
228
+ audio::FiniteOscillatorSchedule schedule;
233
229
  };
234
230
 
235
231
  struct ActiveTone {
@@ -694,7 +690,8 @@ bool playPcmSync(const std::int16_t *samples, std::size_t sampleCount, int sampl
694
690
  const std::size_t frames = std::min<std::size_t>(kPlaybackChunkFrames, frameCount - frame);
695
691
  if (channels == 2) {
696
692
  const std::size_t src = frame * 2;
697
- if (!audio::OutputDriver::write(samples + src, frames * 2, kPlaybackWriteTimeoutMs)) return false;
693
+ std::copy_n(samples + src, frames * 2, stereo.data());
694
+ if (!audio::OutputDriver::write(stereo.data(), frames * 2, kPlaybackWriteTimeoutMs)) return false;
698
695
  } else {
699
696
  for (std::size_t i = 0; i < frames; ++i) {
700
697
  const std::size_t src = (frame + i) * static_cast<std::size_t>(channels);
@@ -708,93 +705,175 @@ bool playPcmSync(const std::int16_t *samples, std::size_t sampleCount, int sampl
708
705
  return true;
709
706
  }
710
707
 
708
+ // Play imported WAV assets without opening a filesystem path or writing into
709
+ // read-only flash. Codec software volume may modify its input buffer.
710
+ bool playEmbeddedWav(const unsigned char* bytes, std::size_t length) {
711
+ if (length < 12 || std::memcmp(bytes, "RIFF", 4) || std::memcmp(bytes + 8, "WAVE", 4)) return false;
712
+ const auto le16 = [](const unsigned char* p) { return unsigned(p[0]) | unsigned(p[1]) << 8; };
713
+ const auto le32 = [](const unsigned char *p) {
714
+ return std::uint32_t(p[0]) | std::uint32_t(p[1]) << 8 | std::uint32_t(p[2]) << 16 |
715
+ std::uint32_t(p[3]) << 24;
716
+ };
717
+ unsigned channels = 0, format = 0, bits = 0;
718
+ std::uint32_t rate = 0;
719
+ const unsigned char *pcm = nullptr;
720
+ std::size_t pcmBytes = 0;
721
+ for (std::size_t offset = 12; offset <= length && length - offset >= 8;) {
722
+ const auto size = le32(bytes + offset + 4);
723
+ const auto payload = offset + 8;
724
+ if (size > length - payload) {
725
+ return false;
726
+ }
727
+ if (!std::memcmp(bytes + offset, "fmt ", 4) && size >= 16) {
728
+ format = le16(bytes + payload);
729
+ channels = le16(bytes + payload + 2);
730
+ rate = le32(bytes + payload + 4);
731
+ bits = le16(bytes + payload + 14);
732
+ } else if (!std::memcmp(bytes + offset, "data", 4)) {
733
+ pcm = bytes + payload;
734
+ pcmBytes = size;
735
+ }
736
+ offset = payload + size + (size & 1u);
737
+ }
738
+ if (!pcm || format != 1 || bits != 16 || channels < 1 || channels > 2 || !rate || pcmBytes == 0 ||
739
+ pcmBytes % (channels * 2)) {
740
+ return false;
741
+ }
742
+ ExclusivePlaybackScope playbackScope;
743
+ if (!audio::OutputDriver::open(static_cast<int>(rate), 2, 16)) {
744
+ return false;
745
+ }
746
+ OutputCloseScope closeOutput{true};
747
+ std::vector<std::int16_t> stereo(kPlaybackChunkFrames * 2);
748
+ const auto frameCount = pcmBytes / (channels * 2);
749
+ for (std::size_t frame = 0; frame < frameCount;) {
750
+ const auto count = std::min<std::size_t>(kPlaybackChunkFrames, frameCount - frame);
751
+ for (std::size_t index = 0; index < count; ++index) {
752
+ const auto *source = pcm + (frame + index) * channels * 2;
753
+ stereo[index * 2] = static_cast<std::int16_t>(le16(source));
754
+ stereo[index * 2 + 1] =
755
+ channels == 1 ? stereo[index * 2] : static_cast<std::int16_t>(le16(source + 2));
756
+ }
757
+ if (!audio::OutputDriver::write(stereo.data(), count * 2, kPlaybackWriteTimeoutMs)) {
758
+ return false;
759
+ }
760
+ frame += count;
761
+ }
762
+ return true;
763
+ }
764
+
711
765
  // Stream a 16-bit PCM WAV from disk to the output driver in bounded chunks.
712
766
  // Playback memory stays ~constant (one small chunk buffer) regardless of file
713
767
  // length. The previous path loaded the ENTIRE file into a std::vector first,
714
768
  // which OOM-crashed on long recordings — a 20-minute 16 kHz mono clip is
715
769
  // ~38 MB, far past available PSRAM. Parses the header (must be PCM 16-bit),
716
770
  // then reads+plays the data chunk incrementally.
717
- bool streamPcm16File(const std::string &path)
718
- {
719
- if (path.empty() || !gea::platform::storage::ensureMounted()) return false;
720
- FILE *file = std::fopen(path.c_str(), "rb");
721
- if (!file) return false;
722
-
723
- bool ok = false;
724
- do {
725
- if (!readTag(file, "RIFF")) break;
726
- (void)readLe32(file);
727
- if (!readTag(file, "WAVE")) break;
728
-
729
- std::uint16_t audioFormat = 0;
730
- std::uint16_t channels = 0;
731
- std::uint32_t sampleRate = 0;
732
- std::uint16_t bitsPerSample = 0;
733
- long dataStart = -1;
734
- std::uint32_t dataSize = 0;
735
-
736
- while (!std::feof(file)) {
737
- char chunkId[4] = {};
738
- if (std::fread(chunkId, 1, sizeof(chunkId), file) != sizeof(chunkId)) break;
739
- const std::uint32_t chunkSize = readLe32(file);
740
- const long payloadStart = std::ftell(file);
741
- if (payloadStart < 0) break;
742
- if (std::memcmp(chunkId, "fmt ", 4) == 0 && chunkSize >= 16) {
743
- audioFormat = readLe16(file);
744
- channels = readLe16(file);
745
- sampleRate = readLe32(file);
746
- (void)readLe32(file);
747
- (void)readLe16(file);
748
- bitsPerSample = readLe16(file);
749
- } else if (std::memcmp(chunkId, "data", 4) == 0 && chunkSize >= 2) {
750
- dataStart = payloadStart;
751
- dataSize = chunkSize;
752
- break; // stream the data chunk below rather than loading it
753
- }
754
- const long next = payloadStart + static_cast<long>(chunkSize) + static_cast<long>(chunkSize & 1u);
755
- if (std::fseek(file, next, SEEK_SET) != 0) break;
756
- }
757
-
758
- if (audioFormat != 1 || bitsPerSample != 16 || dataStart < 0 || dataSize < 2) break;
759
- if (channels == 0) channels = 1;
760
- const int outSampleRate = sampleRate == 0 ? kSampleRate : static_cast<int>(sampleRate);
761
- if (std::fseek(file, dataStart, SEEK_SET) != 0) break;
762
-
763
- ExclusivePlaybackScope playbackScope;
764
- if (!audio::OutputDriver::open(outSampleRate, 2, 16)) break;
765
- OutputCloseScope closeOutput{true};
766
-
767
- const std::size_t ch = static_cast<std::size_t>(channels);
768
- std::size_t framesLeft = dataSize / (sizeof(std::int16_t) * ch);
769
- std::vector<std::int16_t> in(kPlaybackChunkFrames * ch);
770
- std::vector<std::int16_t> stereo(kPlaybackChunkFrames * 2);
771
- bool wrote = true;
772
- while (framesLeft > 0) {
773
- const std::size_t frames = std::min<std::size_t>(kPlaybackChunkFrames, framesLeft);
774
- const std::size_t want = frames * ch;
775
- // WAV PCM is little-endian and the ESP32 is little-endian, so raw int16
776
- // reads need no byte swap.
777
- const std::size_t got = std::fread(in.data(), sizeof(std::int16_t), want, file);
778
- const std::size_t framesGot = got / ch;
779
- if (framesGot == 0) break;
780
- if (channels == 2) {
781
- if (!audio::OutputDriver::write(in.data(), framesGot * 2, kPlaybackWriteTimeoutMs)) { wrote = false; break; }
782
- } else {
783
- for (std::size_t i = 0; i < framesGot; ++i) {
784
- const std::size_t src = i * ch;
785
- stereo[i * 2] = in[src];
786
- stereo[i * 2 + 1] = channels == 1 ? in[src] : in[src + 1];
787
- }
788
- if (!audio::OutputDriver::write(stereo.data(), framesGot * 2, kPlaybackWriteTimeoutMs)) { wrote = false; break; }
789
- }
790
- framesLeft -= framesGot;
791
- if (got < want) break; // short read = EOF
792
- }
793
- ok = wrote;
794
- } while (false);
795
-
796
- std::fclose(file);
797
- return ok;
771
+ bool streamPcm16File(const std::string &path) {
772
+ if (path.empty() || !gea::platform::storage::ensureMounted()) {
773
+ return false;
774
+ }
775
+ FILE *file = std::fopen(path.c_str(), "rb");
776
+ if (!file) {
777
+ return false;
778
+ }
779
+
780
+ bool ok = false;
781
+ do {
782
+ if (!readTag(file, "RIFF")) {
783
+ break;
784
+ }
785
+ (void)readLe32(file);
786
+ if (!readTag(file, "WAVE")) {
787
+ break;
788
+ }
789
+
790
+ std::uint16_t audioFormat = 0;
791
+ std::uint16_t channels = 0;
792
+ std::uint32_t sampleRate = 0;
793
+ std::uint16_t bitsPerSample = 0;
794
+ long dataStart = -1;
795
+ std::uint32_t dataSize = 0;
796
+
797
+ while (!std::feof(file)) {
798
+ char chunkId[4] = {};
799
+ if (std::fread(chunkId, 1, sizeof(chunkId), file) != sizeof(chunkId))
800
+ break;
801
+ const std::uint32_t chunkSize = readLe32(file);
802
+ const long payloadStart = std::ftell(file);
803
+ if (payloadStart < 0)
804
+ break;
805
+ if (std::memcmp(chunkId, "fmt ", 4) == 0 && chunkSize >= 16) {
806
+ audioFormat = readLe16(file);
807
+ channels = readLe16(file);
808
+ sampleRate = readLe32(file);
809
+ (void)readLe32(file);
810
+ (void)readLe16(file);
811
+ bitsPerSample = readLe16(file);
812
+ } else if (std::memcmp(chunkId, "data", 4) == 0 && chunkSize >= 2) {
813
+ dataStart = payloadStart;
814
+ dataSize = chunkSize;
815
+ break; // stream the data chunk below rather than loading it
816
+ }
817
+ const long next =
818
+ payloadStart + static_cast<long>(chunkSize) + static_cast<long>(chunkSize & 1u);
819
+ if (std::fseek(file, next, SEEK_SET) != 0)
820
+ break;
821
+ }
822
+
823
+ if (audioFormat != 1 || bitsPerSample != 16 || dataStart < 0 || dataSize < 2)
824
+ break;
825
+ if (channels == 0)
826
+ channels = 1;
827
+ const int outSampleRate = sampleRate == 0 ? kSampleRate : static_cast<int>(sampleRate);
828
+ if (std::fseek(file, dataStart, SEEK_SET) != 0)
829
+ break;
830
+
831
+ ExclusivePlaybackScope playbackScope;
832
+ if (!audio::OutputDriver::open(outSampleRate, 2, 16))
833
+ break;
834
+ OutputCloseScope closeOutput{true};
835
+
836
+ const std::size_t ch = static_cast<std::size_t>(channels);
837
+ std::size_t framesLeft = dataSize / (sizeof(std::int16_t) * ch);
838
+ std::vector<std::int16_t> in(kPlaybackChunkFrames * ch);
839
+ std::vector<std::int16_t> stereo(kPlaybackChunkFrames * 2);
840
+ bool wrote = true;
841
+ while (framesLeft > 0) {
842
+ const std::size_t frames = std::min<std::size_t>(kPlaybackChunkFrames, framesLeft);
843
+ const std::size_t want = frames * ch;
844
+ // WAV PCM is little-endian and the ESP32 is little-endian, so raw int16
845
+ // reads need no byte swap.
846
+ const std::size_t got = std::fread(in.data(), sizeof(std::int16_t), want, file);
847
+ const std::size_t framesGot = got / ch;
848
+ if (framesGot == 0)
849
+ break;
850
+ if (channels == 2) {
851
+ if (!audio::OutputDriver::write(in.data(), framesGot * 2,
852
+ kPlaybackWriteTimeoutMs)) {
853
+ wrote = false;
854
+ break;
855
+ }
856
+ } else {
857
+ for (std::size_t i = 0; i < framesGot; ++i) {
858
+ const std::size_t src = i * ch;
859
+ stereo[i * 2] = in[src];
860
+ stereo[i * 2 + 1] = channels == 1 ? in[src] : in[src + 1];
861
+ }
862
+ if (!audio::OutputDriver::write(stereo.data(), framesGot * 2,
863
+ kPlaybackWriteTimeoutMs)) {
864
+ wrote = false;
865
+ break;
866
+ }
867
+ }
868
+ framesLeft -= framesGot;
869
+ if (got < want)
870
+ break; // short read = EOF
871
+ }
872
+ ok = wrote;
873
+ } while (false);
874
+
875
+ std::fclose(file);
876
+ return ok;
798
877
  }
799
878
 
800
879
  } // namespace
@@ -876,6 +955,12 @@ void audio::AudioSystem::setVolume(int volumePercent) {
876
955
  bool audio::AudioSystem::playFile(const std::string &path) {
877
956
  // Stream from disk in bounded chunks — never load the whole file (a long
878
957
  // recording is tens of MB and would exhaust PSRAM).
958
+ const unsigned char* embedded = nullptr;
959
+ unsigned long embeddedBytes = 0;
960
+ if (gea_embedded_asset_lookup &&
961
+ gea_embedded_asset_lookup(path.c_str(), &embedded, &embeddedBytes)) {
962
+ return playEmbeddedWav(embedded, embeddedBytes);
963
+ }
879
964
  if (!streamPcm16File(path)) {
880
965
  ESP_LOGW("gea_audio", "Unable to play WAV file: %s", path.c_str());
881
966
  return false;
package/host/audio.cpp CHANGED
@@ -1,5 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #include "audio.h"
3
+ #include "audio_oscillator.h"
3
4
  #include "host/audio_level.h"
4
5
  #include "host/pcm_stream.h"
5
6
  #include "host/websocket.h"
@@ -18,6 +19,7 @@
18
19
  #include <unordered_map>
19
20
  #include <vector>
20
21
  #include <stdexcept>
22
+ #include <limits>
21
23
  #ifdef ESP_PLATFORM
22
24
  #include "esp_log.h"
23
25
  #endif
@@ -77,8 +79,10 @@ namespace gea::host {
77
79
  namespace {
78
80
 
79
81
  std::uint16_t le16(const std::vector<std::uint8_t> &bytes, std::size_t offset) {
80
- if (offset + 2 > bytes.size()) return 0;
81
- return static_cast<std::uint16_t>(bytes[offset] | (static_cast<std::uint16_t>(bytes[offset + 1]) << 8));
82
+ if (offset + 2 > bytes.size())
83
+ return 0;
84
+ return static_cast<std::uint16_t>(
85
+ bytes[offset] | (static_cast<std::uint16_t>(bytes[offset + 1]) << 8));
82
86
  }
83
87
 
84
88
  std::uint32_t le32(const std::vector<std::uint8_t> &bytes, std::size_t offset) {
@@ -135,7 +139,7 @@ AudioBuffer decodePcm16Wav(const std::vector<std::uint8_t> &bytes) {
135
139
  return AudioBuffer(std::move(samples), sampleRate, channels);
136
140
  }
137
141
 
138
- } // namespace
142
+ } // namespace
139
143
 
140
144
  AudioDestinationProperty::operator AudioDestinationNode() const {
141
145
  AudioDestinationNode result(gea::framework::host::AudioHost::context().destination().nativeId());
@@ -209,10 +213,20 @@ void OscillatorNode::connect(double destinationHandle) const {
209
213
  }
210
214
 
211
215
  void OscillatorNode::start(double when) const {
216
+ if (context) {
217
+ clockOffset = gea::framework::host::AudioHost::context().currentTime() - audio_worklet::contextTime(context);
218
+ clockAligned = true;
219
+ if (when > 0) when += clockOffset;
220
+ }
212
221
  gea::framework::host::AudioHost::oscillator(nativeHandle).start(when);
213
222
  }
214
223
 
215
224
  void OscillatorNode::stop(double when) const {
225
+ if (context && when > 0) {
226
+ if (clockAligned) when += clockOffset;
227
+ else when = gea::platform::audio::physicalAudioDeadline(when, audio_worklet::contextTime(context),
228
+ gea::framework::host::AudioHost::context().currentTime());
229
+ }
216
230
  gea::framework::host::AudioHost::oscillator(nativeHandle).stop(when);
217
231
  }
218
232
 
@@ -231,8 +245,13 @@ AudioDestinationNode AudioBufferSourceNode::connect(double destinationHandle) co
231
245
 
232
246
  void AudioBufferSourceNode::start(double when) const {
233
247
  (void)when;
234
- if (!connected || buffer.samples.empty()) return;
235
- gea::platform::audio::AudioSystem::playPcm(buffer.samples.data(), buffer.samples.size(), buffer.sampleRate, buffer.channels);
248
+ if (!connected)
249
+ return;
250
+ const auto &samples = buffer.pcmSamples();
251
+ if (samples.empty())
252
+ return;
253
+ gea::platform::audio::AudioSystem::playPcm(
254
+ samples.data(), samples.size(), buffer.sampleRate, buffer.channels);
236
255
  }
237
256
 
238
257
  void AudioBufferSourceNode::stop(double when) const {
@@ -241,14 +260,17 @@ void AudioBufferSourceNode::stop(double when) const {
241
260
  }
242
261
 
243
262
  OscillatorNode AudioContext::createOscillator() const {
244
- return OscillatorNode(gea::framework::host::AudioHost::context().createOscillator().nativeId());
263
+ OscillatorNode oscillator(gea::framework::host::AudioHost::context().createOscillator().nativeId());
264
+ oscillator.context = state_;
265
+ return oscillator;
245
266
  }
246
267
 
247
268
  AudioBufferSourceNode AudioContext::createBufferSource() const {
248
- return AudioBufferSourceNode{};
269
+ return AudioBufferSourceNode(true);
249
270
  }
250
271
 
251
- AudioBuffer AudioContext::decodeAudioData(const std::vector<std::uint8_t> &bytes) const {
272
+ AudioBuffer
273
+ AudioContext::decodeAudioData(const std::vector<std::uint8_t> &bytes) const {
252
274
  return decodePcm16Wav(bytes);
253
275
  }
254
276
 
@@ -392,7 +414,7 @@ void HTMLAudioElement::setAutoplay(bool enabled) const {
392
414
  if (enabled && state_->source.nativeHandle && state_->paused) (void)play();
393
415
  }
394
416
 
395
- } // namespace gea::host
417
+ } // namespace gea::host
396
418
 
397
419
  namespace gea::host {
398
420
  namespace {
@@ -403,7 +425,9 @@ std::uint32_t pcmNowMs() {
403
425
  }
404
426
 
405
427
  struct PcmAudioStream::State {
406
- explicit State(int rate) : capture(16000, rate), playback(rate, 16000), wireRate(rate) {}
428
+ explicit State(int rate)
429
+ : capture(gea::platform::audio::deviceSampleRate, rate),
430
+ playback(rate, gea::platform::audio::deviceSampleRate), wireRate(rate) {}
407
431
  ~State() { if (output) gea::platform::audio::AudioSystem::stopPcmStream(output); }
408
432
  std::shared_ptr<media::TrackPcmReader> reader;
409
433
  std::mutex captureMutex;
@@ -424,8 +448,8 @@ struct PcmAudioStream::State {
424
448
  };
425
449
 
426
450
  PcmAudioStream PcmAudioStream::create(double sampleRate) {
427
- if (sampleRate != 16000 && sampleRate != 24000 && sampleRate != 48000)
428
- throw std::invalid_argument("PCM sample rate must be 16000, 24000 or 48000");
451
+ if (sampleRate != 16000 && sampleRate != 24000 && sampleRate != 44100 && sampleRate != 48000)
452
+ throw std::invalid_argument("PCM sample rate must be 16000, 24000, 44100 or 48000");
429
453
  PcmAudioStream result;
430
454
  result.state_ = std::make_shared<State>(static_cast<int>(sampleRate));
431
455
  const std::weak_ptr<State> weak = result.state_;
@@ -524,16 +548,15 @@ std::string PcmAudioStream::readBase64() const {
524
548
  const auto started = pcmNowMs();
525
549
  if (!state_) return {};
526
550
  std::lock_guard<std::mutex> lock(state_->captureMutex);
527
- // Match the device/bridge's 20 ms cadence. At 16 kHz, the encoded JSON
528
- // envelope stays below one TCP MSS instead of splitting a 40 ms payload.
529
- constexpr std::size_t captureFrames = 320;
551
+ // Match the capture driver's 20 ms cadence at its configured device rate.
552
+ constexpr std::size_t captureFrames = gea::platform::audio::deviceSampleRate / 50;
530
553
  if (state_->closed || !state_->reader || state_->reader->pendingSamples() < captureFrames) return {};
531
554
  std::int16_t input[captureFrames];
532
555
  const auto count = state_->reader->read(input, captureFrames);
533
556
  const auto readAt = pcmNowMs();
534
- // The native bridge already supplies 16 kHz PCM. Encode the capture block
557
+ // When the network and device clocks match, encode the capture block
535
558
  // directly rather than allocating and visiting a resampler for each sample.
536
- if (state_->wireRate == 16000) return pcm::encode(input, count);
559
+ if (state_->wireRate == gea::platform::audio::deviceSampleRate) return pcm::encode(input, count);
537
560
  std::vector<std::int16_t> wire;
538
561
  wire.reserve(1920);
539
562
  for (std::size_t i = 0; i < count; ++i)
@@ -555,10 +578,10 @@ void PcmAudioStream::writeBase64(const std::string &data) const {
555
578
  const auto decodedAt = pcmNowMs();
556
579
  // Resampling and allocation never hold the real-time mixer's queue mutex.
557
580
  State::Block block;
558
- if (state_->wireRate == 16000) {
581
+ if (state_->wireRate == gea::platform::audio::deviceSampleRate) {
559
582
  block.assign(wire.begin(), wire.end());
560
583
  } else {
561
- block.reserve(wire.size() * 16000 / state_->wireRate + 2);
584
+ block.reserve(wire.size() * gea::platform::audio::deviceSampleRate / state_->wireRate + 2);
562
585
  for (auto sample : wire)
563
586
  state_->playback.push(sample, [&](std::int16_t value) { block.push_back(value); });
564
587
  }
@@ -567,7 +590,7 @@ void PcmAudioStream::writeBase64(const std::string &data) const {
567
590
  std::lock_guard<std::mutex> lock(state_->mutex);
568
591
  // Generated output may run faster than playback. Never silently overwrite
569
592
  // the unplayed tail (MediaStream's live capture ring has different semantics).
570
- if (state_->queuedSamples + block.size() > 16000 * 30)
593
+ if (state_->queuedSamples + block.size() > gea::platform::audio::deviceSampleRate * 30)
571
594
  throw std::runtime_error("PCM playback exceeded 30 second queue limit");
572
595
  if (!block.empty()) {
573
596
  state_->startGate.pushed(pcmNowMs());
@@ -575,7 +598,7 @@ void PcmAudioStream::writeBase64(const std::string &data) const {
575
598
  state_->queue.push_back(std::move(block));
576
599
  }
577
600
  packets = ++state_->receivedPackets;
578
- queuedMs = unsigned(state_->queuedSamples * 1000 / 16000);
601
+ queuedMs = unsigned(state_->queuedSamples * 1000 / gea::platform::audio::deviceSampleRate);
579
602
  }
580
603
  // Console formatting and sinks must never hold the speaker's queue lock.
581
604
  #ifdef ESP_PLATFORM
@@ -614,7 +637,7 @@ void PcmAudioStream::close() const {
614
637
  double PcmAudioStream::queuedMs() const {
615
638
  if (!state_) return 0;
616
639
  std::lock_guard<std::mutex> lock(state_->mutex);
617
- return state_->queuedSamples / 16.0;
640
+ return state_->queuedSamples * 1000.0 / gea::platform::audio::deviceSampleRate;
618
641
  }
619
642
 
620
643
  double PcmAudioStream::playedMs() const {
@@ -624,7 +647,7 @@ double PcmAudioStream::playedMs() const {
624
647
  // This conservative bound never reports queued network data as heard audio.
625
648
  const auto elapsed = static_cast<std::uint32_t>(pcmNowMs() - state_->lastPull);
626
649
  const double inFlight = elapsed >= 122 ? 0 : 122 - elapsed;
627
- return std::max(0.0, state_->pulled / 16.0 - inFlight);
650
+ return std::max(0.0, state_->pulled * 1000.0 / gea::platform::audio::deviceSampleRate - inFlight);
628
651
  }
629
652
 
630
653
  bool PcmAudioStream::drained() const {
@@ -642,7 +665,7 @@ double PcmAudioStream::audioLevel() const { return state_ ? state_->level.read(p
642
665
  double PcmAudioStream::capturePendingMs() const {
643
666
  if (!state_) return 0;
644
667
  std::lock_guard<std::mutex> lock(state_->captureMutex);
645
- return state_->reader ? state_->reader->pendingSamples() / 16.0 : 0;
668
+ return state_->reader ? state_->reader->pendingSamples() * 1000.0 / gea::platform::audio::deviceSampleRate : 0;
646
669
  }
647
670
  double PcmAudioStream::captureDroppedSamples() const {
648
671
  if (!state_) return 0;
@@ -0,0 +1,117 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Compiler-backed typed channel views belong to the app-sensitive host layer.
3
+ #include "gea/embedded.h"
4
+ #define GEA_HOST_DECLARED 1
5
+ #include "gea_runtime.h"
6
+ #include "host/audio.h"
7
+
8
+ #include <algorithm>
9
+ #include <cmath>
10
+ #include <limits>
11
+ #include <stdexcept>
12
+
13
+ namespace gea::host {
14
+
15
+ struct AudioBufferStorage {
16
+ std::vector<gea::Ref<gea::TypedArray<float>>> planes;
17
+ std::vector<std::int16_t> pcm;
18
+ std::size_t length = 0;
19
+ };
20
+
21
+ void AudioBuffer::ensureStorage() const {
22
+ if (storage)
23
+ return;
24
+ if (channels <= 0)
25
+ throw std::out_of_range("AudioBuffer channel count is invalid");
26
+ auto next = std::make_shared<AudioBufferStorage>();
27
+ next->length = samples.size() / static_cast<std::size_t>(channels);
28
+ for (int channel = 0; channel < channels; ++channel) {
29
+ auto plane = gea::makeRef<gea::TypedArray<float>>(next->length);
30
+ for (std::size_t index = 0; index < next->length; ++index)
31
+ plane->data()[index] =
32
+ static_cast<float>(samples[index * channels + channel]) / 32768.0f;
33
+ next->planes.push_back(std::move(plane));
34
+ }
35
+ storage = std::move(next);
36
+ }
37
+
38
+ double AudioBuffer::getLength() const {
39
+ return storage
40
+ ? static_cast<double>(storage->length)
41
+ : (channels > 0 ? static_cast<double>(samples.size() / channels)
42
+ : 0.0);
43
+ }
44
+
45
+ double AudioBuffer::getDuration() const { return getLength() / sampleRate; }
46
+
47
+ double AudioBuffer::getNumberOfChannels() const { return channels; }
48
+
49
+ gea::Ref<gea::TypedArray<float>>
50
+ AudioBuffer::getChannelData(double channel) const {
51
+ if (!std::isfinite(channel) || channel < 0 || std::trunc(channel) >= channels)
52
+ throw std::out_of_range("AudioBuffer channel is out of range");
53
+ ensureStorage();
54
+ return storage->planes[static_cast<std::size_t>(channel)];
55
+ }
56
+
57
+ void AudioBuffer::copyToChannelValues(const float *source, std::size_t count,
58
+ double channel, double offset) const {
59
+ auto plane = getChannelData(channel);
60
+ if (!std::isfinite(offset) || offset < 0 ||
61
+ std::trunc(offset) >= plane->size())
62
+ throw std::out_of_range("AudioBuffer channel offset is out of range");
63
+ const auto first = static_cast<std::size_t>(offset);
64
+ const auto copied = std::min(count, plane->size() - first);
65
+ if (copied)
66
+ std::memmove(plane->data() + first, source, copied * sizeof(float));
67
+ }
68
+
69
+ void AudioBuffer::copyFromChannelValues(float *destination, std::size_t count,
70
+ double channel, double offset) const {
71
+ auto plane = getChannelData(channel);
72
+ if (!std::isfinite(offset) || offset < 0 ||
73
+ std::trunc(offset) >= plane->size())
74
+ throw std::out_of_range("AudioBuffer channel offset is out of range");
75
+ const auto first = static_cast<std::size_t>(offset);
76
+ const auto copied = std::min(count, plane->size() - first);
77
+ if (copied)
78
+ std::memmove(destination, plane->data() + first, copied * sizeof(float));
79
+ }
80
+
81
+ const std::vector<std::int16_t> &AudioBuffer::pcmSamples() const {
82
+ if (!storage)
83
+ return samples;
84
+ storage->pcm.resize(storage->length * channels);
85
+ for (std::size_t index = 0; index < storage->length; ++index) {
86
+ for (int channel = 0; channel < channels; ++channel) {
87
+ const float value = storage->planes[channel]->data()[index];
88
+ const float bounded =
89
+ std::isfinite(value) ? std::clamp(value, -1.0f, 1.0f) : 0.0f;
90
+ const auto sample = std::lround(bounded * 32768.0f);
91
+ storage->pcm[index * channels + channel] =
92
+ static_cast<std::int16_t>(std::clamp(sample, -32768L, 32767L));
93
+ }
94
+ }
95
+ return storage->pcm;
96
+ }
97
+
98
+ AudioBuffer AudioContext::createBuffer(double channelCount, double length,
99
+ double rate) const {
100
+ if (!std::isfinite(channelCount) || channelCount < 1 || channelCount >= 33 ||
101
+ !std::isfinite(length) || length < 1 ||
102
+ length > std::numeric_limits<int>::max() || !std::isfinite(rate) ||
103
+ rate < 8000 || rate > 96000 || std::trunc(rate) != rate)
104
+ throw std::invalid_argument(
105
+ "AudioBuffer dimensions or sample rate are unsupported");
106
+ AudioBuffer buffer;
107
+ buffer.channels = static_cast<int>(channelCount);
108
+ buffer.sampleRate = static_cast<int>(rate);
109
+ buffer.storage = std::make_shared<AudioBufferStorage>();
110
+ buffer.storage->length = static_cast<std::size_t>(length);
111
+ for (int channel = 0; channel < buffer.channels; ++channel)
112
+ buffer.storage->planes.push_back(
113
+ gea::makeRef<gea::TypedArray<float>>(buffer.storage->length));
114
+ return buffer;
115
+ }
116
+
117
+ } // namespace gea::host