@geastack/host 0.1.9 → 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.
Files changed (48) hide show
  1. package/audio_runtime.cpp +97 -3
  2. package/host/audio.cpp +395 -10
  3. package/host/audio_worklet.cpp +611 -0
  4. package/host/fetch.cpp +17 -0
  5. package/host/media.cpp +308 -27
  6. package/host/mjpeg.cpp +199 -0
  7. package/host/rtc.cpp +458 -48
  8. package/host/rtc_esp.cpp +897 -75
  9. package/host/rtc_objects.inc +246 -0
  10. package/host/timers.cpp +18 -0
  11. package/host/video.cpp +152 -0
  12. package/host/websocket.cpp +623 -72
  13. package/host/worker.cpp +621 -0
  14. package/include/gea/audio-worklet-runtime.h +165 -0
  15. package/include/gea/base64-runtime.h +26 -0
  16. package/include/gea/embedded-host.h +1 -0
  17. package/include/gea/worker-runtime.h +184 -0
  18. package/include/host/audio.h +94 -6
  19. package/include/host/audio_level.h +37 -0
  20. package/include/host/audio_worklet.h +103 -0
  21. package/include/host/display.h +1 -1
  22. package/include/host/h264_layout.h +170 -0
  23. package/include/host/media.h +67 -0
  24. package/include/host/mjpeg.h +22 -0
  25. package/include/host/mjpeg_parser.h +84 -0
  26. package/include/host/pcm_stream.h +122 -0
  27. package/include/host/rtc.h +38 -20
  28. package/include/host/rtc_h264.h +76 -0
  29. package/include/host/rtc_ice_candidate.h +141 -0
  30. package/include/host/rtc_opus.h +136 -0
  31. package/include/host/rtc_receive_sdp.h +245 -0
  32. package/include/host/rtc_rtp.h +170 -0
  33. package/include/host/rtc_sdp.h +71 -0
  34. package/include/host/rtc_types.h +166 -0
  35. package/include/host/rtc_vp8.h +115 -0
  36. package/include/host/rtc_vp8_capture.h +129 -0
  37. package/include/host/rtc_vp8_decoder.h +169 -0
  38. package/include/host/rtc_vp8_receiver.h +55 -0
  39. package/include/host/timers.h +3 -2
  40. package/include/host/video.h +39 -0
  41. package/include/host/video_color.h +90 -0
  42. package/include/host/video_frame_pool.h +50 -0
  43. package/include/host/video_pixels.h +178 -0
  44. package/include/host/websocket.h +20 -1
  45. package/include/host/websocket_message.h +66 -0
  46. package/include/host/worker.h +131 -0
  47. package/package.json +1 -1
  48. package/services/diagnostics.cpp +120 -19
@@ -0,0 +1,165 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include "gea/worker-runtime.h"
4
+ #include "host/audio.h"
5
+
6
+ namespace gea::runtime::hostaudio {
7
+
8
+ template <typename Action>
9
+ gea::Promise<void> workletPromise(Action action) {
10
+ try { action(); return gea::Promise<void>::settled_value(); }
11
+ catch (...) { return gea::Promise<void>::rejected_with(std::current_exception()); }
12
+ }
13
+ inline gea::host::AudioContext createAudioContext() {
14
+ hostworker::installRealmRuntime();
15
+ return gea::host::AudioContext(16000.0);
16
+ }
17
+ template <typename Options>
18
+ gea::host::AudioContext createAudioContext(const Options& options) {
19
+ hostworker::installRealmRuntime();
20
+ return gea::host::AudioContext(options);
21
+ }
22
+ inline gea::Promise<void> workletAddModule(const gea::host::AudioWorklet& worklet, const std::string& url) {
23
+ hostworker::installRealmRuntime();
24
+ return workletPromise([&] { worklet.addModule(url); });
25
+ }
26
+ inline gea::Promise<void> contextResume(const gea::host::AudioContext& context) {
27
+ hostworker::installRealmRuntime();
28
+ return workletPromise([&] { context.resume(); });
29
+ }
30
+ inline gea::Promise<void> contextSuspend(const gea::host::AudioContext& context) {
31
+ hostworker::installRealmRuntime();
32
+ return workletPromise([&] { context.suspend(); });
33
+ }
34
+ inline gea::Promise<void> contextClose(const gea::host::AudioContext& context) {
35
+ return workletPromise([&] { context.close(); });
36
+ }
37
+ template <typename T>
38
+ double optionNumber(const T& value, double fallback) {
39
+ if constexpr (requires { value.has_value(); *value; }) return value.has_value() ? optionNumber(*value, fallback) : fallback;
40
+ else if constexpr (std::is_convertible_v<T, double>) return static_cast<double>(value);
41
+ else return fallback;
42
+ }
43
+ template <typename Options>
44
+ gea::host::AudioWorkletNodeOptions workletOptions(const Options& options) {
45
+ gea::host::AudioWorkletNodeOptions result;
46
+ if constexpr (requires { options.has_value(); *options; }) {
47
+ if (options.has_value()) return workletOptions(*options);
48
+ } else if constexpr (requires { options.get(); *options; }) {
49
+ if (options.get()) return workletOptions(*options);
50
+ } else {
51
+ auto count = [](double n) {
52
+ if (!std::isfinite(n) || n < 0 || n > 32 || n != std::floor(n))
53
+ throw std::invalid_argument("Invalid AudioWorklet channel count");
54
+ return static_cast<unsigned>(n);
55
+ };
56
+ if constexpr (requires { options.numberOfInputs; }) result.numberOfInputs = count(optionNumber(options.numberOfInputs, 1));
57
+ if constexpr (requires { options.numberOfOutputs; }) result.numberOfOutputs = count(optionNumber(options.numberOfOutputs, 1));
58
+ if constexpr (requires { options.channelCount; }) result.channelCount = count(optionNumber(options.channelCount, 1));
59
+ if constexpr (requires { options.outputChannelCount; }) {
60
+ hostworker::present(options.outputChannelCount, [&](const auto& counts) {
61
+ const auto& values = [&]() -> const auto& { if constexpr (requires { counts->size(); }) return *counts; else return counts; }();
62
+ if (values.size() != result.numberOfOutputs || values.size() != 1 || values.at(0) != 1)
63
+ throw std::invalid_argument("Embedded AudioWorklet requires one mono output");
64
+ });
65
+ }
66
+ }
67
+ return result;
68
+ }
69
+ inline gea::host::AudioWorkletNode createAudioWorkletNode(const gea::host::AudioContext& context, const std::string& name) {
70
+ return gea::host::AudioWorkletNode(context, name);
71
+ }
72
+ template <typename Options>
73
+ gea::host::AudioWorkletNode createAudioWorkletNode(const gea::host::AudioContext& context, const std::string& name, const Options& options) {
74
+ return gea::host::AudioWorkletNode(context, name, workletOptions(options));
75
+ }
76
+ template <typename Handler>
77
+ void setOnProcessorError(const gea::host::AudioWorkletNode& node, const Handler& handler) {
78
+ node.setOnProcessorError({});
79
+ hostworker::present(handler, [&](const auto& fn) {
80
+ node.setOnProcessorError([fn](const std::string& error) { hostworker::deliverError(fn, error); });
81
+ });
82
+ }
83
+
84
+ using WorkletFloat32Array = gea::Ref<gea::TypedArray<float>>;
85
+ using WorkletChannels = gea::Ref<gea::ArrayObject<WorkletFloat32Array>>;
86
+ using WorkletBus = gea::Ref<gea::ArrayObject<WorkletChannels>>;
87
+
88
+ template <typename Function, typename... Args>
89
+ decltype(auto) invokeWorklet(Function& function, Args&&... args) {
90
+ if constexpr (requires { function.call(std::forward<Args>(args)...); })
91
+ return function.call(std::forward<Args>(args)...);
92
+ else return function(std::forward<Args>(args)...);
93
+ }
94
+
95
+ // The compiler supplies the concrete factory and process invocation; generated
96
+ // method spellings and object shapes never enter the hardware host. Float32
97
+ // views persist between quanta. Copying 128 samples crosses the native buffer
98
+ // boundary without allocating a JS array or boxing a sample each time.
99
+ template <typename Processor, typename Process>
100
+ class TypedProcessorAdapter final : public gea::host::AudioWorkletProcessor {
101
+ public:
102
+ TypedProcessorAdapter(Processor processor, Process process)
103
+ : processor_(std::move(processor)), process_(std::move(process)),
104
+ inputs_(gea::makeRef<gea::ArrayObject<WorkletChannels>>()),
105
+ outputs_(gea::makeRef<gea::ArrayObject<WorkletChannels>>()) {}
106
+ bool process(const gea::host::AudioWorkletBus& inputs, gea::host::AudioWorkletBus& outputs,
107
+ const gea::host::AudioWorkletParameters& parameters) override {
108
+ if (!parameters.empty()) throw std::invalid_argument("AudioParam automation is not implemented for this processor");
109
+ prepare(inputs_, inputs, false);
110
+ prepare(outputs_, outputs, true);
111
+ const bool keep = [&] {
112
+ try { return invokeWorklet(process_, processor_, inputs_, outputs_); }
113
+ catch (const gea::Value& error) {
114
+ // A thrown JS value is a genuine dynamic boundary. Preserve its text
115
+ // across the typed/runtime bridge for native logs and processorerror.
116
+ throw std::runtime_error(gea::host::detail::toString(error));
117
+ }
118
+ }();
119
+ for (std::size_t bus = 0; bus < outputs.size(); ++bus)
120
+ for (std::size_t channel = 0; channel < outputs[bus].size(); ++channel) {
121
+ const auto& data = outputs_->at(bus)->at(channel);
122
+ if (data->size() != outputs[bus][channel].size()) throw std::runtime_error("AudioWorklet detached or resized its output buffer");
123
+ std::copy_n(data->data(), data->size(), outputs[bus][channel].data());
124
+ }
125
+ return keep;
126
+ }
127
+ private:
128
+ static void prepare(WorkletBus& target, const gea::host::AudioWorkletBus& native, bool zero) {
129
+ // Geometry changes only at connect/disconnect. A retained input buffer may
130
+ // have been transferred by user code, so replace detached views as well.
131
+ if (target->size() != native.size()) {
132
+ target = gea::makeRef<gea::ArrayObject<WorkletChannels>>();
133
+ for (std::size_t i = 0; i < native.size(); ++i) target->push(gea::makeRef<gea::ArrayObject<WorkletFloat32Array>>());
134
+ }
135
+ for (std::size_t bus = 0; bus < native.size(); ++bus) {
136
+ auto channels = target->at(bus);
137
+ if (channels->size() != native[bus].size()) {
138
+ channels = gea::makeRef<gea::ArrayObject<WorkletFloat32Array>>();
139
+ for (const auto& samples : native[bus]) channels->push(gea::makeRef<gea::TypedArray<float>>(samples.size()));
140
+ target->setElement(static_cast<double>(bus), channels);
141
+ }
142
+ for (std::size_t channel = 0; channel < native[bus].size(); ++channel) {
143
+ auto data = channels->at(channel);
144
+ if (data->size() != native[bus][channel].size()) {
145
+ data = gea::makeRef<gea::TypedArray<float>>(native[bus][channel].size());
146
+ channels->setElement(static_cast<double>(channel), data);
147
+ }
148
+ if (zero) std::fill_n(data->data(), data->size(), 0.0f);
149
+ else std::copy_n(native[bus][channel].data(), data->size(), data->data());
150
+ }
151
+ }
152
+ }
153
+ Processor processor_;
154
+ Process process_;
155
+ WorkletBus inputs_, outputs_;
156
+ };
157
+
158
+ template <typename Factory, typename Process>
159
+ void registerTypedProcessor(const std::string& name, Factory factory, Process process) {
160
+ gea::host::audio_worklet::registerProcessor(name, [factory, process]() mutable {
161
+ using Processor = decltype(invokeWorklet(factory));
162
+ return std::make_shared<TypedProcessorAdapter<Processor, Process>>(invokeWorklet(factory), process);
163
+ });
164
+ }
165
+ } // namespace gea::runtime::hostaudio
@@ -0,0 +1,26 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #ifndef GEA_HOST_DECLARED
4
+ #define GEA_HOST_DECLARED 1
5
+ #include "gea/embedded.h"
6
+ #endif
7
+ #include "gea_runtime.h"
8
+
9
+ namespace gea::runtime::hostbase64 {
10
+ inline std::string encode(const std::string &value) {
11
+ return gea::runtime::base64::encode(value);
12
+ }
13
+ inline std::string encode(const gea::Ref<gea::ArrayBuffer> &value) {
14
+ value->requireAttached();
15
+ return gea::runtime::base64::encodeBytes(value->data(), value->size());
16
+ }
17
+ inline std::string encode(const gea::Ref<gea::TypedArray<std::uint8_t>> &value) {
18
+ return gea::runtime::base64::encodeBytes(value->data(), value->size());
19
+ }
20
+ inline std::string encode(const gea::TypedArray<std::uint8_t> &value) {
21
+ return gea::runtime::base64::encodeBytes(value.data(), value.size());
22
+ }
23
+ inline std::string decode(const std::string &value) {
24
+ return gea::runtime::base64::decode(value);
25
+ }
26
+ } // namespace gea::runtime::hostbase64
@@ -31,6 +31,7 @@
31
31
  #include "host/device_control.h"
32
32
  #include "input.h"
33
33
  #include "host/audio.h"
34
+ #include "host/video.h"
34
35
  #include "host/display.h"
35
36
  #include "host/navigator.h"
36
37
  #include "host/camera.h"
@@ -0,0 +1,184 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #ifndef GEA_HOST_DECLARED
4
+ #define GEA_HOST_DECLARED 1
5
+ #include "gea/embedded.h"
6
+ #endif
7
+ #include "gea_runtime.h"
8
+ #include "host/worker.h"
9
+ #include <unordered_set>
10
+
11
+ namespace gea::runtime::hostworker {
12
+ namespace native = gea::host::workers;
13
+
14
+ template <typename T> struct EventFactory {
15
+ static T make() { return {}; }
16
+ static T &fields(T &event) { return event; }
17
+ };
18
+ template <typename T> struct EventFactory<gea::Ref<T>> {
19
+ static gea::Ref<T> make() { return gea::makeRef<T>(); }
20
+ static T &fields(gea::Ref<T> &event) { return *event; }
21
+ };
22
+ template <typename Target, typename Head, typename... Tail>
23
+ constexpr std::size_t armIndex() {
24
+ if constexpr (std::is_same_v<Target, Head>) return 0;
25
+ else { static_assert(sizeof...(Tail) > 0, "Event field cannot hold this message payload"); return 1 + armIndex<Target, Tail...>(); }
26
+ }
27
+ template <typename Slot, typename T> void assign(Slot &slot, const T &value) { slot = value; }
28
+ template <typename... Arms, typename T>
29
+ void assign(gea::TaggedUnion<Arms...> &slot, const T &value) {
30
+ slot = gea::TaggedUnion<Arms...>::template ofArm<armIndex<T, Arms...>()>(value);
31
+ }
32
+
33
+ inline void installRealmRuntime() {
34
+ static const bool installed = [] {
35
+ native::setRealmRunner([](std::function<void()> run) {
36
+ #if defined(GEA_RUNTIME_REALMS) && GEA_RUNTIME_REALMS
37
+ gea::detail::RuntimeRealm realm;
38
+ gea::detail::RuntimeRealmScope scope(realm);
39
+ native::Context::current()->setPump([] { gea::detail::drainPromiseJobs(); });
40
+ run();
41
+ realm.clear();
42
+ #else
43
+ throw std::runtime_error("Workers require GEA_RUNTIME_REALMS=1");
44
+ #endif
45
+ });
46
+ return true;
47
+ }();
48
+ (void)installed;
49
+ }
50
+ inline native::Worker createWorker(const std::string &url) {
51
+ installRealmRuntime();
52
+ return native::Worker::create(url);
53
+ }
54
+ template <typename T, typename Fn> void present(const T &value, Fn &&fn);
55
+ template <typename Options>
56
+ native::Worker createWorker(const std::string &url, const Options &options) {
57
+ if constexpr (requires { options->type; }) {
58
+ if (options) return createWorker(url, *options);
59
+ } else if constexpr (requires { options.type; }) {
60
+ bool provided = true;
61
+ if constexpr (requires { options.gea_present_type; }) provided = options.gea_present_type;
62
+ if (provided) present(options.type, [](const auto &type) {
63
+ if (type != "module") throw std::runtime_error("Only module workers are supported");
64
+ });
65
+ }
66
+ return createWorker(url);
67
+ }
68
+
69
+ // These adapters keep compiler handles on their creating task. Only owned byte
70
+ // vectors and native port handles enter the inter-task queue.
71
+ template <typename T, typename Fn>
72
+ void visit(const T &value, Fn &&fn) {
73
+ if constexpr (requires { T::arity; value.index(); }) {
74
+ [&]<std::size_t... I>(std::index_sequence<I...>) {
75
+ ((value.index() == I ? (visit(value.template get<I>(), fn), 0) : 0), ...);
76
+ }(std::make_index_sequence<T::arity>{});
77
+ } else fn(value);
78
+ }
79
+ template <typename T, typename Fn>
80
+ void present(const T &value, Fn &&fn) {
81
+ if constexpr (std::is_same_v<T, std::nullptr_t> || std::is_same_v<T, gea::Undefined>) return;
82
+ else if constexpr (requires { value.has_value(); *value; }) { if (value.has_value()) present(*value, fn); }
83
+ else if constexpr (requires { T::arity; value.index(); }) visit(value, [&](const auto &item) { present(item, fn); });
84
+ else fn(value);
85
+ }
86
+ struct TransferList {
87
+ std::vector<gea::Ref<gea::ArrayBuffer>> buffers;
88
+ std::vector<native::MessagePort> ports;
89
+ };
90
+ template <typename List>
91
+ TransferList transfers(const List &input) {
92
+ TransferList result;
93
+ std::unordered_set<const void *> seen;
94
+ auto inspect = [&](const auto &array) {
95
+ for (std::size_t i = 0; i < array.size(); ++i) visit(array.at(i), [&](const auto &entry) {
96
+ using T = std::decay_t<decltype(entry)>;
97
+ if constexpr (std::is_same_v<T, gea::Ref<gea::ArrayBuffer>>) {
98
+ if (!entry || entry->detached() || !seen.insert(entry.operator->()).second)
99
+ throw std::runtime_error("DataCloneError: invalid ArrayBuffer transfer list");
100
+ result.buffers.push_back(entry);
101
+ } else if constexpr (std::is_same_v<T, native::MessagePort>) {
102
+ if (entry.detached() || !seen.insert(entry.identity()).second)
103
+ throw std::runtime_error("DataCloneError: invalid MessagePort transfer list");
104
+ result.ports.push_back(entry);
105
+ } else {
106
+ static_assert(std::is_same_v<T, void>, "Unsupported transferable type");
107
+ }
108
+ });
109
+ };
110
+ if constexpr (requires { input->size(); }) inspect(*input);
111
+ else inspect(input);
112
+ return result;
113
+ }
114
+ template <typename Data>
115
+ native::MessageData cloneData(const Data &data, TransferList &list) {
116
+ native::MessageData result;
117
+ visit(data, [&](const auto &value) {
118
+ using T = std::decay_t<decltype(value)>;
119
+ if constexpr (std::is_convertible_v<T, std::string>) result = std::string(value);
120
+ else if constexpr (std::is_same_v<T, gea::Ref<gea::ArrayBuffer>>) {
121
+ if (!value || value->detached()) throw std::runtime_error("DataCloneError: detached ArrayBuffer");
122
+ const bool transfer = std::any_of(list.buffers.begin(), list.buffers.end(),
123
+ [&](const auto &candidate) { return candidate.operator->() == value.operator->(); });
124
+ if (transfer) result = value->detachBytes();
125
+ else result = native::MessageData::Bytes(value->begin(), value->end());
126
+ } else static_assert(std::is_same_v<T, void>, "Only string and ArrayBuffer messages are implemented");
127
+ });
128
+ for (const auto &buffer : list.buffers) if (!buffer->detached()) buffer->detachBytes();
129
+ return result;
130
+ }
131
+ template <typename Owner, typename Data>
132
+ void postMessage(const Owner &owner, const Data &data) {
133
+ TransferList list;
134
+ owner.postMessage(cloneData(data, list));
135
+ }
136
+ template <typename Owner, typename Data, typename List>
137
+ void postMessage(const Owner &owner, const Data &data, const List &transfer) {
138
+ auto list = transfers(transfer);
139
+ owner.validateTransfers(list.ports);
140
+ owner.postMessage(cloneData(data, list), list.ports);
141
+ }
142
+ template <typename R, typename E>
143
+ void deliver(const gea::CallableObject<R(E)> &handler, native::MessageEvent &message) {
144
+ E event = EventFactory<E>::make();
145
+ auto &fields = EventFactory<E>::fields(event);
146
+ if (std::holds_alternative<std::string>(message.data.value)) {
147
+ assign(fields.data, std::get<std::string>(message.data.value));
148
+ } else {
149
+ assign(fields.data, gea::makeRef<gea::ArrayBuffer>(
150
+ std::move(std::get<native::MessageData::Bytes>(message.data.value))));
151
+ }
152
+ if constexpr (requires { fields.ports; }) {
153
+ auto ports = gea::makeRef<gea::ArrayObject<native::MessagePort>>();
154
+ for (const auto &port : message.ports) ports->push(port);
155
+ assign(fields.ports, ports);
156
+ }
157
+ handler.call(event);
158
+ }
159
+ template <typename R>
160
+ void deliver(const gea::CallableObject<R()> &handler, native::MessageEvent &) { handler.call(); }
161
+ template <typename Owner, typename Handler>
162
+ void setOnMessage(const Owner &owner, const Handler &handler) {
163
+ owner.setOnMessage({});
164
+ present(handler, [&](const auto &fn) {
165
+ owner.setOnMessage([fn](native::MessageEvent &message) { deliver(fn, message); });
166
+ });
167
+ }
168
+ template <typename R, typename E>
169
+ void deliverError(const gea::CallableObject<R(E)> &handler, const std::string &message) {
170
+ E event = EventFactory<E>::make();
171
+ if constexpr (requires { EventFactory<E>::fields(event).message; })
172
+ assign(EventFactory<E>::fields(event).message, message);
173
+ handler.call(event);
174
+ }
175
+ template <typename R>
176
+ void deliverError(const gea::CallableObject<R()> &handler, const std::string &) { handler.call(); }
177
+ template <typename Handler>
178
+ void setOnError(const native::Worker &worker, const Handler &handler) {
179
+ worker.setOnError({});
180
+ present(handler, [&](const auto &fn) {
181
+ worker.setOnError([fn](const std::string &message) { deliverError(fn, message); });
182
+ });
183
+ }
184
+ } // namespace gea::runtime::hostworker
@@ -3,6 +3,9 @@
3
3
 
4
4
  #include <audio.h>
5
5
  #include "backends.h"
6
+ #include "host/media.h"
7
+ #include "host/audio_worklet.h"
8
+ #include <memory>
6
9
 
7
10
  #include <cstdint>
8
11
  #include <cstring>
@@ -30,20 +33,23 @@ inline double oscillator_type_from_name(const char *type) {
30
33
 
31
34
  struct AudioDestinationNode {
32
35
  NativeAudioHandle nativeHandle = 0;
36
+ std::shared_ptr<audio_worklet::ContextState> context;
33
37
 
34
- constexpr AudioDestinationNode() = default;
35
- explicit constexpr AudioDestinationNode(NativeAudioHandle destination) : nativeHandle(destination) {}
36
- explicit constexpr AudioDestinationNode(double destination) : nativeHandle(static_cast<NativeAudioHandle>(destination)) {}
38
+ AudioDestinationNode() = default;
39
+ explicit AudioDestinationNode(NativeAudioHandle destination) : nativeHandle(destination) {}
40
+ explicit AudioDestinationNode(double destination) : nativeHandle(static_cast<NativeAudioHandle>(destination)) {}
37
41
 
38
42
  constexpr operator double() const { return static_cast<double>(nativeHandle); }
39
43
  };
40
44
 
41
45
  struct AudioDestinationProperty {
46
+ std::shared_ptr<audio_worklet::ContextState> context;
42
47
  operator AudioDestinationNode() const;
43
48
  operator double() const;
44
49
  };
45
50
 
46
51
  struct AudioContextCurrentTimeProperty {
52
+ std::shared_ptr<audio_worklet::ContextState> context;
47
53
  operator double() const;
48
54
  };
49
55
 
@@ -122,17 +128,54 @@ struct AudioBufferSourceNode {
122
128
  };
123
129
 
124
130
  struct AudioContext {
131
+ private:
132
+ std::shared_ptr<audio_worklet::ContextState> state_;
133
+ public:
134
+ // The default native carrier represents a missing/undefined JS handle.
135
+ // Actual construction is performed by createAudioContext or the rate ctor.
136
+ AudioContext() = default;
137
+ explicit AudioContext(double rate);
138
+ explicit operator bool() const { return static_cast<bool>(state_); }
139
+ bool operator==(std::nullptr_t) const { return !state_; }
140
+ template <typename Options>
141
+ explicit AudioContext(const Options& options) : AudioContext(sampleRateOption(options)) {}
142
+ double sampleRate = 16000;
125
143
  AudioDestinationProperty destination;
126
144
  AudioContextCurrentTimeProperty currentTime;
145
+ AudioWorklet audioWorklet;
146
+
147
+ std::string state() const;
148
+ double baseLatency() const;
149
+ double outputLatency() const;
150
+ void resume() const;
151
+ void suspend() const;
152
+ void close() const;
153
+ MediaStreamAudioSourceNode createMediaStreamSource(MediaStream stream) const;
154
+ const std::shared_ptr<audio_worklet::ContextState>& workletContext() const { return state_; }
127
155
 
128
156
  OscillatorNode createOscillator() const;
129
157
  AudioBufferSourceNode createBufferSource() const;
130
158
  AudioBuffer decodeAudioData(const std::vector<std::uint8_t> &bytes) const;
159
+ private:
160
+ template <typename Options>
161
+ static double sampleRateOption(const Options& options) {
162
+ if constexpr (requires { options.has_value(); *options; })
163
+ return options.has_value() ? sampleRateOption(*options) : 16000;
164
+ else if constexpr (requires { options.get(); *options; })
165
+ return options.get() ? sampleRateOption(*options) : 16000;
166
+ else if constexpr (requires { options.sampleRate; })
167
+ return sampleRateOption(options.sampleRate);
168
+ else if constexpr (requires { static_cast<double>(options); })
169
+ return static_cast<double>(options);
170
+ else return 16000;
171
+ }
131
172
  };
132
173
 
133
174
  class HTMLAudioElement {
134
175
  public:
135
176
  HTMLAudioElement() = default;
177
+ static HTMLAudioElement create();
178
+ static HTMLAudioElement create(const std::string &src);
136
179
  explicit HTMLAudioElement(const char *src);
137
180
  explicit HTMLAudioElement(const std::string &src);
138
181
  explicit HTMLAudioElement(const gea::embedded::ui::NodeHandle &node);
@@ -141,10 +184,52 @@ class HTMLAudioElement {
141
184
  void setSrc(const std::string &src);
142
185
  bool play() const;
143
186
  void pause() const;
187
+ void beginDrain() const;
188
+ void clearBufferedAudio() const;
189
+ bool drained() const;
190
+ double audioLevel() const;
191
+ MediaStream srcObject() const;
192
+ void setSrcObject(MediaStream stream) const;
193
+ void setSrcObject(std::nullptr_t) const { setSrcObject(MediaStream{}); }
194
+ bool autoplay() const;
195
+ void setAutoplay(bool enabled) const;
196
+ bool paused() const;
197
+ explicit operator bool() const { return static_cast<bool>(state_); }
198
+ bool operator==(std::nullptr_t) const { return !state_; }
199
+ bool operator==(const HTMLAudioElement& other) const { return state_ == other.state_; }
144
200
 
145
201
  private:
146
- int nodeId_ = -1;
147
- std::string src_;
202
+ struct State;
203
+ std::shared_ptr<State> state_;
204
+ };
205
+
206
+ // Streaming mono PCM transport independent of any speech provider. Wire PCM
207
+ // uses sampleRate; capture/playback use the device's 16 kHz audio clock.
208
+ class WebSocket;
209
+ class PcmAudioStream {
210
+ public:
211
+ PcmAudioStream() = default;
212
+ static PcmAudioStream create(double sampleRate);
213
+ void setInput(MediaStream stream) const;
214
+ void pipeTo(WebSocket socket, const std::string &prefix, const std::string &suffix) const;
215
+ void receiveFrom(WebSocket socket, const std::string &prefix, const std::string &suffix) const;
216
+ std::string readBase64() const;
217
+ void writeBase64(const std::string &data) const;
218
+ void resetPlayback(bool interrupted = false) const;
219
+ void close() const;
220
+ double queuedMs() const;
221
+ double playedMs() const;
222
+ double capturePendingMs() const;
223
+ double captureDroppedSamples() const;
224
+ double capturePackets() const;
225
+ double audioLevel() const;
226
+ bool drained() const;
227
+ explicit operator bool() const { return static_cast<bool>(state_); }
228
+ bool operator==(std::nullptr_t) const { return !state_; }
229
+ bool operator==(const PcmAudioStream &other) const { return state_ == other.state_; }
230
+ private:
231
+ struct State;
232
+ std::shared_ptr<State> state_;
148
233
  };
149
234
 
150
235
  struct AudioFacade {
@@ -152,7 +237,10 @@ struct AudioFacade {
152
237
  void setVolume(double volume) const { gea::framework::audio::AudioBackend::setVolume(volume); }
153
238
  };
154
239
 
155
- inline constexpr AudioContext audioContext{};
240
+ inline const AudioContext& sharedAudioContext() {
241
+ static const AudioContext context(16000.0);
242
+ return context;
243
+ }
156
244
  inline constexpr AudioFacade Audio{};
157
245
 
158
246
  } // namespace gea::host
@@ -0,0 +1,37 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ #include <atomic>
5
+ #include <cmath>
6
+ #include <cstddef>
7
+ #include <cstdint>
8
+
9
+ namespace gea::host {
10
+
11
+ // Display telemetry only: an empty pull is a scheduling/network gap, not a
12
+ // silent PCM block. Never use this meter to end playback or gate the mic.
13
+ class AudioLevelMeter {
14
+ public:
15
+ void update(const std::int16_t* samples, std::size_t count, std::uint32_t nowMs) {
16
+ if (!count) return;
17
+ std::uint64_t energy = 0;
18
+ for (std::size_t i = 0; i < count; ++i)
19
+ energy += std::int64_t(samples[i]) * samples[i];
20
+ level_.store(static_cast<unsigned>(std::sqrt(double(energy) / count)), std::memory_order_relaxed);
21
+ updatedMs_.store(nowMs, std::memory_order_release);
22
+ }
23
+
24
+ double read(std::uint32_t nowMs) const {
25
+ // Expire stale telemetry if transport stops delivering even silent PCM.
26
+ // This changes no audio buffering, playback, or turn detection.
27
+ if (std::int32_t(nowMs - updatedMs_.load(std::memory_order_acquire)) > 250) return 0;
28
+ return level_.load(std::memory_order_relaxed) / 32768.0;
29
+ }
30
+
31
+ void reset() { level_.store(0, std::memory_order_relaxed); }
32
+
33
+ private:
34
+ std::atomic<unsigned> level_{0};
35
+ std::atomic<std::uint32_t> updatedMs_{0};
36
+ };
37
+ }
@@ -0,0 +1,103 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ #include "host/media.h"
5
+ #include "host/worker.h"
6
+ #include <functional>
7
+ #include <memory>
8
+ #include <string>
9
+ #include <unordered_map>
10
+ #include <vector>
11
+
12
+ namespace gea::host {
13
+ using workers::MessagePort;
14
+ struct AudioContext;
15
+ struct AudioDestinationNode;
16
+ struct AudioDestinationProperty;
17
+ class AudioWorkletNode;
18
+
19
+ using AudioWorkletChannels = std::vector<std::vector<float>>;
20
+ using AudioWorkletBus = std::vector<AudioWorkletChannels>;
21
+ using AudioWorkletParameters = std::unordered_map<std::string, std::vector<float>>;
22
+
23
+ namespace audio_worklet {
24
+ struct ContextState;
25
+ struct NodeState;
26
+ struct NodeControl;
27
+ constexpr std::size_t renderQuantum = 128;
28
+ std::shared_ptr<ContextState> createContext(double sampleRate);
29
+ double contextBaseLatency(const std::shared_ptr<ContextState>& context);
30
+ double contextTime(const std::shared_ptr<ContextState>&);
31
+ std::string contextState(const std::shared_ptr<ContextState>&);
32
+ void resume(const std::shared_ptr<ContextState>&);
33
+ void suspend(const std::shared_ptr<ContextState>&);
34
+ void close(const std::shared_ptr<ContextState>&);
35
+ // Module entries and processor factories are generated C++; no JS evaluator.
36
+ void registerModule(const std::string& url, std::function<void()> entry);
37
+ double sampleRate();
38
+ double currentTime();
39
+ double currentFrame();
40
+ workers::MessagePort processorPort();
41
+ void flushOutput();
42
+ }
43
+
44
+ class AudioWorkletProcessor {
45
+ public:
46
+ AudioWorkletProcessor();
47
+ virtual ~AudioWorkletProcessor() = default;
48
+ workers::MessagePort port;
49
+ virtual bool process(const AudioWorkletBus& inputs, AudioWorkletBus& outputs,
50
+ const AudioWorkletParameters& parameters) { return false; }
51
+ };
52
+
53
+ namespace audio_worklet {
54
+ using ProcessorFactory = std::function<std::shared_ptr<AudioWorkletProcessor>()>;
55
+ void registerProcessor(const std::string& name, ProcessorFactory factory);
56
+ }
57
+
58
+ class AudioWorklet {
59
+ public:
60
+ AudioWorklet() = default;
61
+ explicit AudioWorklet(std::shared_ptr<audio_worklet::ContextState> context) : context_(std::move(context)) {}
62
+ void addModule(const std::string& url) const;
63
+ private:
64
+ std::shared_ptr<audio_worklet::ContextState> context_;
65
+ };
66
+
67
+ struct AudioWorkletNodeOptions {
68
+ unsigned numberOfInputs = 1;
69
+ unsigned numberOfOutputs = 1;
70
+ unsigned channelCount = 1;
71
+ };
72
+
73
+ class AudioWorkletNode {
74
+ public:
75
+ AudioWorkletNode() = default;
76
+ AudioWorkletNode(const AudioContext& context, const std::string& name);
77
+ AudioWorkletNode(const AudioContext& context, const std::string& name, const AudioWorkletNodeOptions& options);
78
+ workers::MessagePort port;
79
+ AudioDestinationNode connect(AudioDestinationNode destination) const;
80
+ AudioDestinationNode connect(AudioDestinationProperty destination) const;
81
+ void disconnect() const;
82
+ void setOnProcessorError(std::function<void(const std::string&)> callback) const;
83
+ explicit operator bool() const { return static_cast<bool>(state_); }
84
+ bool operator==(std::nullptr_t) const { return !state_; }
85
+ private:
86
+ std::shared_ptr<audio_worklet::NodeState> state_;
87
+ std::shared_ptr<audio_worklet::NodeControl> control_;
88
+ friend class MediaStreamAudioSourceNode;
89
+ };
90
+
91
+ class MediaStreamAudioSourceNode {
92
+ public:
93
+ MediaStreamAudioSourceNode() = default;
94
+ explicit operator bool() const { return static_cast<bool>(state_); }
95
+ bool operator==(std::nullptr_t) const { return !state_; }
96
+ MediaStreamAudioSourceNode(std::shared_ptr<audio_worklet::ContextState> context, MediaStream stream);
97
+ AudioWorkletNode connect(AudioWorkletNode destination) const;
98
+ void disconnect() const;
99
+ private:
100
+ struct State;
101
+ std::shared_ptr<State> state_;
102
+ };
103
+ } // namespace gea::host