@geastack/host 0.1.14 → 0.1.16

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.
@@ -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
@@ -45,7 +45,7 @@ struct NodeControl {
45
45
  };
46
46
 
47
47
  struct NodeState {
48
- explicit NodeState(int rate) : capture(16000, rate) {}
48
+ explicit NodeState(int rate) : capture(gea::platform::audio::deviceSampleRate, rate) {}
49
49
  std::weak_ptr<ContextState> context;
50
50
  std::shared_ptr<AudioWorkletProcessor> processor;
51
51
  MessagePort processorPort;
@@ -63,10 +63,13 @@ struct NodeState {
63
63
  std::uint64_t captureDropped = 0;
64
64
  bool connected = false, alive = true;
65
65
  unsigned numberOfInputs = 1;
66
+ bool processingActive() const {
67
+ return alive && (connected || (outputs.empty() && reader && inputTrack.readyState() == "live"));
68
+ }
66
69
  };
67
70
 
68
71
  struct ContextState : std::enable_shared_from_this<ContextState> {
69
- explicit ContextState(int rate) : rate(rate), playback(rate, 16000) {}
72
+ explicit ContextState(int rate) : rate(rate), playback(rate, gea::platform::audio::deviceSampleRate) {}
70
73
  ~ContextState() {
71
74
  if (output) gea::platform::audio::AudioSystem::stopPcmStream(output);
72
75
  if (realm) realm->stop();
@@ -171,7 +174,7 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
171
174
  // Reserve a whole hardware quantum before process() advances playback
172
175
  // or capture. Codec startup and mixer scheduling may temporarily fill
173
176
  // this queue; yield until the consumer pulls, without dropping samples.
174
- const auto required = (renderQuantum * 16000 + rate - 1) / rate;
177
+ const auto required = (renderQuantum * gea::platform::audio::deviceSampleRate + rate - 1) / rate;
175
178
  std::lock_guard lock(outputMutex);
176
179
  if (required > outputPcm.size() - outputCount) {
177
180
  #ifdef ESP_PLATFORM
@@ -187,7 +190,7 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
187
190
  bool waitingForInput = false;
188
191
  inputClockActive = false;
189
192
  for (const auto& node : nodes) {
190
- if (!node->alive || !node->connected || !node->reader) continue;
193
+ if (!node->processingActive() || !node->reader) continue;
191
194
  node->captureInputLive = node->inputTrack.enabled() && node->inputTrack.readyState() == "live";
192
195
  if (!node->captureInputLive) {
193
196
  // Disabled/ended tracks represent silence, not a stalled device clock.
@@ -218,7 +221,7 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
218
221
  while (node->inputCount < renderQuantum) {
219
222
  std::array<std::int16_t, 128> pcm{};
220
223
  const auto wanted = std::min<std::size_t>(pcm.size(),
221
- ((renderQuantum - node->inputCount) * 16000 + rate - 1) / rate);
224
+ ((renderQuantum - node->inputCount) * gea::platform::audio::deviceSampleRate + rate - 1) / rate);
222
225
  const auto count = node->reader->read(pcm.data(), wanted);
223
226
  if (!count) break;
224
227
  #ifdef ESP_PLATFORM
@@ -241,8 +244,8 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
241
244
  mix.fill(0);
242
245
  bool hasDestination = false;
243
246
  for (const auto& node : nodes) {
244
- if (!node->alive || !node->connected) continue;
245
- hasDestination = true;
247
+ if (!node->processingActive()) continue;
248
+ hasDestination |= node->connected;
246
249
  for (auto& output : node->outputs)
247
250
  for (auto& channel : output) std::fill(channel.begin(), channel.end(), 0.0f);
248
251
  if (node->reader) {
@@ -271,9 +274,11 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
271
274
  processSumUs += processUs;
272
275
  ++processCalls;
273
276
  #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 (!node->outputs.empty()) {
278
+ const auto& channel = node->outputs.at(0).at(0);
279
+ if (channel.size() != renderQuantum) throw std::runtime_error("AudioWorklet changed render quantum geometry");
280
+ for (std::size_t i = 0; i < renderQuantum; ++i) mix[i] += channel[i];
281
+ }
277
282
  if (!keep) node->alive = false;
278
283
  } catch (const std::exception& error) { fail(node, error.what()); }
279
284
  catch (...) { fail(node, "AudioWorklet processor failed"); }
@@ -336,12 +341,14 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
336
341
  { std::lock_guard lock(self->readyMutex); self->ready = true; }
337
342
  self->readySignal.notify_all();
338
343
  const auto quantum = std::chrono::nanoseconds(128000000000LL / self->rate);
344
+ constexpr unsigned maxCatchupQuanta = 4;
345
+ const auto batchBudget = quantum * maxCatchupQuanta;
339
346
  auto next = Clock::now();
340
347
  while (!self->closed && !self->realm->stopped()) {
341
348
  self->realm->runPending(0.5);
342
349
  const auto now = Clock::now();
343
350
  unsigned catchup = 0;
344
- while ((self->inputClockActive || now >= next) && catchup++ < 4) {
351
+ while ((self->inputClockActive || Clock::now() >= next) && catchup++ < maxCatchupQuanta) {
345
352
  #ifdef ESP_PLATFORM
346
353
  const auto renderStart = esp_timer_get_time();
347
354
  const auto framesBefore = self->frames.load();
@@ -362,9 +369,11 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
362
369
  // and the bounded loop still protect the DAC and lower-priority tasks.
363
370
  if (self->inputClockActive) next = Clock::now() + quantum;
364
371
  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;
372
+ // FFT and other block processors alternate expensive and cheap
373
+ // quanta. Amortize the cooperative tick yield across a bounded batch
374
+ // instead of taxing every expensive quantum with another tick.
375
+ // Retain output deadlines if a batch exhausts its work budget.
376
+ if (Clock::now() - now >= batchBudget) break;
368
377
  }
369
378
  // Output-only graphs retain missed timer deadlines. Capture graphs
370
379
  // resume with the next complete hardware quantum on a later wake.
@@ -429,7 +438,7 @@ std::shared_ptr<ContextState> createContext(double rate) {
429
438
  // Report a conservative processing delay from the configured queue capacity.
430
439
  // currentTime is a render clock; neither property claims a DAC timestamp.
431
440
  double contextBaseLatency(const std::shared_ptr<ContextState>& context) {
432
- return context ? double(outputCapacity) / 16000 + gea::platform::audio::AudioSystem::processingLatency() : 0;
441
+ return context ? double(outputCapacity) / gea::platform::audio::deviceSampleRate + gea::platform::audio::AudioSystem::processingLatency() : 0;
433
442
  }
434
443
  double contextTime(const std::shared_ptr<ContextState>& context) {
435
444
  // Legacy oscillator-only contexts retain their platform scheduler's clock.
@@ -511,8 +520,9 @@ void AudioWorklet::addModule(const std::string& url) const {
511
520
  AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::string& name)
512
521
  : AudioWorkletNode(context, name, AudioWorkletNodeOptions{}) {}
513
522
  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");
523
+ if (options.numberOfInputs > 1 || options.numberOfOutputs > 1 || options.channelCount != 1 ||
524
+ (!options.numberOfInputs && !options.numberOfOutputs))
525
+ throw std::invalid_argument("Embedded AudioWorklet requires at least one mono input or output, at most one of each");
516
526
  const auto owner = context.workletContext();
517
527
  workers::MessageChannel channel;
518
528
  port = channel.port1;
@@ -525,6 +535,7 @@ AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::strin
525
535
  node->processorPort = channel.port2.transfer();
526
536
  node->numberOfInputs = options.numberOfInputs;
527
537
  if (!options.numberOfInputs) node->inputs.clear();
538
+ if (!options.numberOfOutputs) node->outputs.clear();
528
539
  owner->invoke([owner, node, name] {
529
540
  if (owner->nodes.size() >= audio_worklet::maxNodes) throw std::runtime_error("AudioContext node limit exceeded");
530
541
  const auto factory = owner->factories.find(name);
@@ -541,6 +552,7 @@ AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::strin
541
552
  }
542
553
  AudioDestinationNode AudioWorkletNode::connect(AudioDestinationNode destination) const {
543
554
  if (!state_) throw std::logic_error("Null AudioWorkletNode");
555
+ if (state_->outputs.empty()) throw std::invalid_argument("AudioWorkletNode has no outputs");
544
556
  auto context = state_->context.lock();
545
557
  if (!context || context != destination.context) throw std::invalid_argument("Audio nodes belong to different contexts");
546
558
  const auto node = state_;
package/host/camera.cpp CHANGED
@@ -2,11 +2,19 @@
2
2
  #include "camera.h"
3
3
  #include "gea/embedded-host.h"
4
4
  #include "ui/camera_element.h"
5
+ #include "host/worker.h"
5
6
 
7
+ #include <cstdint>
8
+ #include <mutex>
6
9
  #include <string>
7
10
 
8
11
  namespace gea::framework::camera {
9
12
 
13
+ namespace {
14
+ std::mutex cameraOwnershipMutex;
15
+ std::uint64_t cameraGeneration = 0;
16
+ }
17
+
10
18
  bool CameraBackend::isAvailable() {
11
19
  return gea::platform::camera::Camera::isAvailable();
12
20
  }
@@ -20,10 +28,31 @@ bool CameraBackend::requestPermission() {
20
28
  }
21
29
 
22
30
  bool CameraBackend::open(const std::string &facing, double preferredWidth, double preferredHeight) {
23
- return gea::platform::camera::Camera::open(facing, static_cast<int>(preferredWidth), static_cast<int>(preferredHeight));
31
+ std::lock_guard guard(cameraOwnershipMutex);
32
+ if (!gea::platform::camera::Camera::open(facing, static_cast<int>(preferredWidth), static_cast<int>(preferredHeight))) return false;
33
+ const auto generation = ++cameraGeneration;
34
+ const auto owner = gea::host::workers::Context::current();
35
+ if (!owner->isMain()) {
36
+ try {
37
+ owner->addCleanup([generation] {
38
+ std::lock_guard cleanupGuard(cameraOwnershipMutex);
39
+ // An old realm must not shut down a camera reopened by its successor.
40
+ if (cameraGeneration != generation) return;
41
+ ++cameraGeneration;
42
+ gea::platform::camera::Camera::close();
43
+ });
44
+ } catch (...) {
45
+ ++cameraGeneration;
46
+ gea::platform::camera::Camera::close();
47
+ throw;
48
+ }
49
+ }
50
+ return true;
24
51
  }
25
52
 
26
53
  void CameraBackend::close() {
54
+ std::lock_guard guard(cameraOwnershipMutex);
55
+ ++cameraGeneration;
27
56
  gea::platform::camera::Camera::close();
28
57
  }
29
58
 
@@ -78,6 +107,10 @@ double CameraBackend::captureMirrored() {
78
107
  return static_cast<double>(gea::platform::camera::Camera::capture(true));
79
108
  }
80
109
 
110
+ std::string CameraBackend::captureFrame() {
111
+ return gea::platform::camera::Camera::captureFrame();
112
+ }
113
+
81
114
  void CameraBackend::setFlash(const std::string &mode) {
82
115
  gea::platform::camera::Camera::setFlash(mode);
83
116
  }
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #include "host/clock.h"
3
+ #include "power.h"
4
+
5
+ #include <cmath>
6
+
7
+ #if defined(__GNUC__)
8
+ #define GEA_WEAK_DEVICE __attribute__((weak))
9
+ #else
10
+ #define GEA_WEAK_DEVICE
11
+ #endif
12
+
13
+ namespace gea::platform::power {
14
+
15
+ GEA_WEAK_DEVICE bool Power::charging() { return false; }
16
+
17
+ GEA_WEAK_DEVICE bool Power::vibrate(double, int) { return false; }
18
+
19
+ } // namespace gea::platform::power
20
+
21
+ namespace gea::platform::clock {
22
+
23
+ GEA_WEAK_DEVICE bool setEpochMs(double timestamp) {
24
+ if (!std::isfinite(timestamp) || timestamp < 0) {
25
+ return false;
26
+ }
27
+ #if defined(_WIN32)
28
+ return false;
29
+ #else
30
+ const auto seconds = static_cast<time_t>(timestamp / 1000);
31
+ timeval now{seconds, static_cast<suseconds_t>((timestamp - seconds * 1000.0) * 1000)};
32
+ return settimeofday(&now, nullptr) == 0;
33
+ #endif
34
+ }
35
+
36
+ } // namespace gea::platform::clock