@geastack/host 0.1.21 → 0.1.23

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/host/gpio.cpp CHANGED
@@ -3,6 +3,11 @@
3
3
 
4
4
  #include "gea/embedded-host.h"
5
5
 
6
+ #include <chrono>
7
+ #include <cstdint>
8
+ #include <functional>
9
+ #include <utility>
10
+
6
11
  namespace gea::framework::gpio {
7
12
 
8
13
  namespace {
@@ -31,6 +36,136 @@ bool GpioBackend::write(double pin, bool level)
31
36
 
32
37
  bool GpioBackend::read(double pin) { return gea::platform::gpio::Gpio::read(toPin(pin)); }
33
38
 
39
+ namespace {
40
+
41
+ using Platform = gea::platform::gpio::Gpio;
42
+
43
+ // Open pins. A slot is also the pin's bit in Platform::takeEdges().
44
+ constexpr int kMaxOpen = 32;
45
+
46
+ struct OpenPin {
47
+ bool used = false;
48
+ int pin = -1;
49
+ int mode = 0;
50
+ int edges = 0;
51
+ // Interrupt-driven, or polled every pollMs (0 = each frame).
52
+ bool interrupt = false;
53
+ int pollMs = 0;
54
+ std::int64_t nextPollMs = 0;
55
+ // The last level the app thread saw, for polled edge detection.
56
+ bool level = false;
57
+ std::function<void()> onEdge;
58
+ };
59
+
60
+ OpenPin gOpen[kMaxOpen];
61
+
62
+ std::int64_t nowMs()
63
+ {
64
+ using Clock = std::chrono::steady_clock;
65
+ return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now().time_since_epoch()).count();
66
+ }
67
+
68
+ bool isOutput(int mode) { return mode == Platform::Output || mode == Platform::OutputOpenDrain; }
69
+
70
+ OpenPin *lookup(double handle)
71
+ {
72
+ const int slot = static_cast<int>(handle);
73
+ if (slot < 0 || slot >= kMaxOpen || !gOpen[slot].used) return nullptr;
74
+ return &gOpen[slot];
75
+ }
76
+
77
+ void deliverEdges()
78
+ {
79
+ const unsigned fired = Platform::takeEdges();
80
+ const std::int64_t now = nowMs();
81
+ for (int slot = 0; slot < kMaxOpen; ++slot) {
82
+ OpenPin &open = gOpen[slot];
83
+ if (!open.used || !open.edges) continue;
84
+ bool due = false;
85
+ if (open.interrupt) {
86
+ due = fired & (1u << slot);
87
+ // An interrupt shared with another driver fires on both edges, and
88
+ // a bouncing contact can end on either: a one-edge pin reports only
89
+ // when it settled on that edge's level.
90
+ if (due && open.edges != (Platform::kRising | Platform::kFalling))
91
+ due = Platform::read(open.pin) == (open.edges == Platform::kRising);
92
+ } else if (now >= open.nextPollMs) {
93
+ open.nextPollMs = now + open.pollMs;
94
+ const bool level = Platform::read(open.pin);
95
+ if (level != open.level) {
96
+ due = (open.edges & (level ? Platform::kRising : Platform::kFalling)) != 0;
97
+ open.level = level;
98
+ }
99
+ }
100
+ if (!due) continue;
101
+ // The callback may close this pin (or open another into this slot);
102
+ // run a copy so its captures outlive the call.
103
+ auto onEdge = open.onEdge;
104
+ if (onEdge) onEdge();
105
+ }
106
+ }
107
+
108
+ } // namespace
109
+
110
+ double GpioBackend::open(double pinValue, double modeValue, double edgesValue, double pollMsValue,
111
+ std::function<void()> onEdge)
112
+ {
113
+ const int pin = toPin(pinValue);
114
+ const int mode = toPin(modeValue);
115
+ const int edges = toPin(edgesValue) & (Platform::kRising | Platform::kFalling);
116
+ const int pollMs = toPin(pollMsValue);
117
+ if (edges && isOutput(mode)) return -1;
118
+ int slot = -1;
119
+ for (int i = 0; i < kMaxOpen; ++i) {
120
+ if (gOpen[i].used && gOpen[i].pin == pin) return -1;
121
+ if (!gOpen[i].used && slot < 0) slot = i;
122
+ }
123
+ if (slot < 0 || !Platform::configure(pin, mode)) return -1;
124
+
125
+ OpenPin &open = gOpen[slot];
126
+ open = OpenPin{};
127
+ open.used = true;
128
+ open.pin = pin;
129
+ open.mode = mode;
130
+ open.edges = edges;
131
+ open.level = isOutput(mode) ? false : Platform::read(pin);
132
+ if (edges) {
133
+ open.onEdge = std::move(onEdge);
134
+ // Interrupts unless the app asked to poll; polling also stands in for
135
+ // a platform or pin with no edge interrupt.
136
+ open.interrupt = pollMs <= 0 && Platform::watch(pin, edges, slot);
137
+ open.pollMs = pollMs > 0 ? pollMs : 0;
138
+ gea::host::gpio::pendingCallbacks = deliverEdges;
139
+ }
140
+ return slot;
141
+ }
142
+
143
+ double GpioBackend::get(double handle)
144
+ {
145
+ const OpenPin *open = lookup(handle);
146
+ return open && Platform::read(open->pin) ? 1 : 0;
147
+ }
148
+
149
+ bool GpioBackend::set(double handle, double level)
150
+ {
151
+ const OpenPin *open = lookup(handle);
152
+ if (!open || !isOutput(open->mode)) return false;
153
+ return Platform::write(open->pin, level != 0);
154
+ }
155
+
156
+ void GpioBackend::close(double handle)
157
+ {
158
+ OpenPin *open = lookup(handle);
159
+ if (!open) return;
160
+ if (open->interrupt) Platform::unwatch(open->pin);
161
+ // Destroying the callback releases its captures; when close() runs inside
162
+ // that callback, deliverEdges holds the copy that is executing.
163
+ auto released = std::move(open->onEdge);
164
+ *open = OpenPin{};
165
+ }
166
+
167
+ void GpioBackend::runCallbacks() { deliverEdges(); }
168
+
34
169
  bool AddressableLedBackend::set(double pin, double r, double g, double b)
35
170
  {
36
171
  return gea::platform::gpio::AddressableLed::set(toPin(pin), toPin(r), toPin(g), toPin(b));
@@ -0,0 +1,35 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ //
3
+ // GpioBackend for targets with no GPIO driver (desktop, mobile, the
4
+ // simulator). Every call reports that the board did nothing, so `new Gpio()`
5
+ // and `new Digital()` throw and the static calls return false, and an app
6
+ // written for a board still links and runs here.
7
+ //
8
+ // ESP32 builds compile host/gpio.cpp over targets/esp32/gpio.cpp instead, and
9
+ // this file to nothing: both come from gea_sources.mjs there.
10
+ #ifndef ESP_PLATFORM
11
+
12
+ #include "host/backends.h"
13
+
14
+ namespace gea::framework::gpio {
15
+
16
+ bool GpioBackend::configureOutput(double) { return false; }
17
+ bool GpioBackend::configureInput(double, bool) { return false; }
18
+ bool GpioBackend::write(double, bool) { return false; }
19
+ bool GpioBackend::read(double) { return false; }
20
+ double GpioBackend::open(double, double, double, double, std::function<void()>) { return -1; }
21
+ double GpioBackend::get(double) { return 0; }
22
+ bool GpioBackend::set(double, double) { return false; }
23
+ void GpioBackend::close(double) {}
24
+ void GpioBackend::runCallbacks() {}
25
+
26
+ bool AddressableLedBackend::set(double, double, double, double) { return false; }
27
+ bool AddressableLedBackend::off(double) { return false; }
28
+ bool AddressableLedBackend::attach(double, double) { return false; }
29
+ bool AddressableLedBackend::setPixel(double, double, double, double) { return false; }
30
+ bool AddressableLedBackend::show() { return false; }
31
+ void AddressableLedBackend::detach() {}
32
+
33
+ } // namespace gea::framework::gpio
34
+
35
+ #endif
package/host/media.cpp CHANGED
@@ -20,6 +20,7 @@
20
20
  #include <vector>
21
21
 
22
22
  #include "platform/file_cache.h"
23
+ #include "platform/internal_stack.h"
23
24
 
24
25
  #ifdef ESP_PLATFORM
25
26
  #include "esp_log.h"
@@ -241,7 +242,7 @@ bool patchWavHeader(FILE *file, std::uint32_t dataBytes) {
241
242
  return std::fflush(file) == 0;
242
243
  }
243
244
 
244
- double writeWavFile(const std::string &path, const std::vector<std::int16_t> &samples, int sampleRate, int channels) {
245
+ double writeWavFileOnInternalStack(const std::string &path, const std::vector<std::int16_t> &samples, int sampleRate, int channels) {
245
246
  if (path.empty()) return 0.0;
246
247
  gea::platform::storage::ensureMounted();
247
248
  makeParentDirs(path);
@@ -286,6 +287,13 @@ double writeWavFile(const std::string &path, const std::vector<std::int16_t> &sa
286
287
  return static_cast<double>(44u + actualDataBytes);
287
288
  }
288
289
 
290
+ double writeWavFile(const std::string &path, const std::vector<std::int16_t> &samples, int sampleRate, int channels) {
291
+ double result{};
292
+ gea::platform::onInternalStack([&] { result = writeWavFileOnInternalStack(path, samples, sampleRate, channels); });
293
+ return result;
294
+ }
295
+
296
+
289
297
  bool recordingPathAssigned(const std::string &path) {
290
298
  for (const auto &entry : recorderTable()) {
291
299
  if (entry.second.path == path) return true;
@@ -325,7 +333,7 @@ std::FILE *openRecorderOutput(RecorderState &recorder, NativeMediaRecorderHandle
325
333
  }
326
334
  }
327
335
 
328
- bool openRecorderFile(RecorderState &recorder, NativeMediaRecorderHandle handle) {
336
+ bool openRecorderFileOnInternalStack(RecorderState &recorder, NativeMediaRecorderHandle handle) {
329
337
  if (recorder.path.empty()) return false;
330
338
  gea::platform::storage::ensureMounted();
331
339
  makeParentDirs(recorder.path);
@@ -343,13 +351,25 @@ bool openRecorderFile(RecorderState &recorder, NativeMediaRecorderHandle handle)
343
351
  return true;
344
352
  }
345
353
 
346
- void closeRecorderFile(RecorderState &recorder) {
354
+ bool openRecorderFile(RecorderState &recorder, NativeMediaRecorderHandle handle) {
355
+ bool result{};
356
+ gea::platform::onInternalStack([&] { result = openRecorderFileOnInternalStack(recorder, handle); });
357
+ return result;
358
+ }
359
+
360
+
361
+ void closeRecorderFileOnInternalStack(RecorderState &recorder) {
347
362
  if (!recorder.file) return;
348
363
  std::fclose(recorder.file);
349
364
  recorder.file = nullptr;
350
365
  }
351
366
 
352
- bool flushRecorderPcm(RecorderState &recorder) {
367
+ void closeRecorderFile(RecorderState &recorder) {
368
+ gea::platform::onInternalStack([&] { closeRecorderFileOnInternalStack(recorder); });
369
+ }
370
+
371
+
372
+ bool flushRecorderPcmOnInternalStack(RecorderState &recorder) {
353
373
  if (!recorder.file || recorder.pcm.empty() || recorder.writeFailed) return !recorder.writeFailed;
354
374
  std::size_t writtenSamples = 0;
355
375
  while (writtenSamples < recorder.pcm.size()) {
@@ -376,13 +396,20 @@ bool flushRecorderPcm(RecorderState &recorder) {
376
396
  return true;
377
397
  }
378
398
 
399
+ bool flushRecorderPcm(RecorderState &recorder) {
400
+ bool result{};
401
+ gea::platform::onInternalStack([&] { result = flushRecorderPcmOnInternalStack(recorder); });
402
+ return result;
403
+ }
404
+
405
+
379
406
  void appendRecorderPcm(RecorderState &recorder, const std::int16_t *samples, std::size_t count) {
380
407
  if (!recorder.file || recorder.writeFailed || !samples || count == 0) return;
381
408
  recorder.pcm.insert(recorder.pcm.end(), samples, samples + count);
382
409
  if (recorder.pcm.size() >= kRecorderFlushSamples) flushRecorderPcm(recorder);
383
410
  }
384
411
 
385
- double finalizeRecorderFile(RecorderState &recorder) {
412
+ double finalizeRecorderFileOnInternalStack(RecorderState &recorder) {
386
413
  flushRecorderPcm(recorder);
387
414
  std::vector<std::int16_t>().swap(recorder.pcm); // the entry outlives the recording; free its staging
388
415
  if (!recorder.file) return 0.0;
@@ -405,7 +432,14 @@ double finalizeRecorderFile(RecorderState &recorder) {
405
432
  return static_cast<double>(44u + dataBytes);
406
433
  }
407
434
 
408
- std::vector<std::uint8_t> readFileBytes(const std::string &path) {
435
+ double finalizeRecorderFile(RecorderState &recorder) {
436
+ double result{};
437
+ gea::platform::onInternalStack([&] { result = finalizeRecorderFileOnInternalStack(recorder); });
438
+ return result;
439
+ }
440
+
441
+
442
+ std::vector<std::uint8_t> readFileBytesOnInternalStack(const std::string &path) {
409
443
  if (path.empty()) return {};
410
444
  gea::platform::storage::ensureMounted();
411
445
  FILE *file = std::fopen(path.c_str(), "rb");
@@ -424,6 +458,13 @@ std::vector<std::uint8_t> readFileBytes(const std::string &path) {
424
458
  return out;
425
459
  }
426
460
 
461
+ std::vector<std::uint8_t> readFileBytes(const std::string &path) {
462
+ std::vector<std::uint8_t> result{};
463
+ gea::platform::onInternalStack([&] { result = readFileBytesOnInternalStack(path); });
464
+ return result;
465
+ }
466
+
467
+
427
468
  } // namespace
428
469
 
429
470
  namespace media {
@@ -1,5 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // Linux desktop provider: link a WebSocket-enabled libcurl >= 7.86.
2
+ // Linux desktop provider: link libcurl >= 7.86. Without ws/wss in the linked
3
+ // libcurl (Debian 12's 7.88.1) it still builds, and connections fail at runtime.
3
4
  #if defined(__linux__) || defined(GEA_TEST_CURL_WEBSOCKET)
4
5
  #include "host/websocket_platform.h"
5
6
  #include <atomic>
@@ -16,7 +17,7 @@
16
17
  #include <sys/socket.h>
17
18
  #endif
18
19
  #if LIBCURL_VERSION_NUM < 0x075600
19
- #error "Desktop WebSocket requires libcurl >= 7.86 with ws/wss enabled"
20
+ #error "Desktop WebSocket requires libcurl >= 7.86"
20
21
  #endif
21
22
  namespace gea::host::websocket::curl_transport {
22
23
  using Clock = std::chrono::steady_clock;
@@ -332,7 +333,12 @@ void State::run() {
332
333
  }
333
334
  char buffer[16384];
334
335
  std::size_t received = 0;
336
+ #if LIBCURL_VERSION_NUM >= 0x080200
335
337
  const curl_ws_frame *meta = nullptr;
338
+ #else
339
+ // curl_ws_recv took a non-const frame pointer until 8.2.0.
340
+ curl_ws_frame *meta = nullptr;
341
+ #endif
336
342
  const auto rc =
337
343
  curl_ws_recv(c.easy, buffer, sizeof(buffer), &received, &meta);
338
344
  if (rc == CURLE_OK && meta) {
@@ -21,7 +21,9 @@
21
21
  #include "host/image.h"
22
22
  #include "host/tile_loader.h"
23
23
  #include "host/memory.h"
24
+ #include "host/simd.h"
24
25
  #include "host/input.h"
26
+ #include "host/buttons.h"
25
27
  #include "host/gpio.h"
26
28
  #include "host/uart.h"
27
29
  #include "host/esp_now.h"
@@ -2,6 +2,7 @@
2
2
  #pragma once
3
3
 
4
4
  #include <cstdint>
5
+ #include <functional>
5
6
  #include <string>
6
7
  #include <vector>
7
8
 
@@ -468,6 +469,23 @@ public:
468
469
  static bool configureInput(double pin, bool pull_up);
469
470
  static bool write(double pin, bool level);
470
471
  static bool read(double pin);
472
+
473
+ // An open pin: the one backend under both TS classes, `Gpio` and the
474
+ // ECMA-419 `Digital`. `mode` is a platform::gpio::Gpio::Mode, `edges` a
475
+ // kRising | kFalling mask (0 for none). With edges, `onEdge` runs on the app
476
+ // thread, once per frame that saw one or more edges. Edges come from the
477
+ // pin's interrupt; the pin is polled instead every `pollMs` (each frame for
478
+ // 0) when the app asks for polling with pollMs > 0, or when the platform has
479
+ // no interrupt for the pin. Returns the handle, or -1 when the pin is not
480
+ // usable, is already open, or the mode is not supported.
481
+ static double open(double pin, double mode, double edges, double pollMs, std::function<void()> onEdge);
482
+ // 0 or 1; 0 for a closed handle.
483
+ static double get(double handle);
484
+ static bool set(double handle, double level);
485
+ static void close(double handle);
486
+ // Delivers pending edges. Application::frame calls it through
487
+ // gea::host::gpio::runCallbacks().
488
+ static void runCallbacks();
471
489
  };
472
490
 
473
491
  // A WS2812/NeoPixel strand on one pin — the "onboard LED" of most modern ESP32
@@ -0,0 +1,27 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ #include <string>
5
+
6
+ #include <input.h>
7
+
8
+ namespace gea::host {
9
+
10
+ // The board's named physical buttons, for app code. Presses themselves arrive
11
+ // as keydown/keyup events whose `code` is the button's name; this lists the
12
+ // names a board has, so an app can show or bind them before the first press.
13
+ // Plain reads of a table filled at boot, safe from any task.
14
+ struct ButtonsFacade {
15
+ double count() const { return static_cast<double>(gea::framework::input::buttonCount()); }
16
+ std::string code(double index) const { return gea::framework::input::buttonCode(static_cast<int>(index)); }
17
+ std::string key(double index) const { return gea::framework::input::buttonKey(static_cast<int>(index)); }
18
+ double pin(double index) const { return gea::framework::input::buttonPin(static_cast<int>(index)); }
19
+ bool pressed(const std::string &code) const
20
+ {
21
+ return gea::framework::input::buttonPressed(gea::framework::input::findButton(code.c_str()));
22
+ }
23
+ };
24
+
25
+ inline constexpr ButtonsFacade Buttons{};
26
+
27
+ } // namespace gea::host
@@ -3,6 +3,9 @@
3
3
 
4
4
  #include "backends.h"
5
5
 
6
+ #include <functional>
7
+ #include <utility>
8
+
6
9
  namespace gea::host {
7
10
 
8
11
  struct GpioFacade {
@@ -13,6 +16,15 @@ struct GpioFacade {
13
16
  }
14
17
  bool write(double pin, bool level) const { return gea::framework::gpio::GpioBackend::write(pin, level); }
15
18
  bool read(double pin) const { return gea::framework::gpio::GpioBackend::read(pin); }
19
+
20
+ // The handle API under the TS `Gpio` and `Digital` classes (runtime/gpio.ts).
21
+ double open(double pin, double mode, double edges, double pollMs, std::function<void()> onEdge) const
22
+ {
23
+ return gea::framework::gpio::GpioBackend::open(pin, mode, edges, pollMs, std::move(onEdge));
24
+ }
25
+ double get(double handle) const { return gea::framework::gpio::GpioBackend::get(handle); }
26
+ bool set(double handle, double level) const { return gea::framework::gpio::GpioBackend::set(handle, level); }
27
+ void close(double handle) const { gea::framework::gpio::GpioBackend::close(handle); }
16
28
  };
17
29
 
18
30
  struct LedFacade {
@@ -34,3 +46,17 @@ inline constexpr GpioFacade Gpio{};
34
46
  inline constexpr LedFacade Led{};
35
47
 
36
48
  } // namespace gea::host
49
+
50
+ namespace gea::host::gpio {
51
+
52
+ // Set by the first GpioBackend::open, so a program that never opens a pin
53
+ // (and a platform with no GPIO backend) links none of it.
54
+ inline void (*pendingCallbacks)() = nullptr;
55
+
56
+ // Application::frame: run the edge callbacks of open pins.
57
+ inline void runCallbacks()
58
+ {
59
+ if (pendingCallbacks) pendingCallbacks();
60
+ }
61
+
62
+ } // namespace gea::host::gpio
@@ -3,6 +3,13 @@
3
3
 
4
4
  #include "backends.h"
5
5
 
6
+ #include <cstddef>
7
+
8
+ // A platform with fast on-chip RAM next to a large slow one (ESP32-S3: SRAM
9
+ // and PSRAM) defines these; elsewhere they are absent and the calls do nothing.
10
+ extern "C" void gea_memory_begin_internal(std::size_t bytes) __attribute__((weak));
11
+ extern "C" void gea_memory_end_internal() __attribute__((weak));
12
+
6
13
  namespace gea::host {
7
14
 
8
15
  struct MemoryFacade {
@@ -37,6 +44,14 @@ struct MemoryFacade {
37
44
  double allocationPsramBytes() const { return gea::framework::memory::MemoryBackend::allocationPsramBytes(); }
38
45
  double allocationSramPeakBytes() const { return gea::framework::memory::MemoryBackend::allocationSramPeakBytes(); }
39
46
  double allocationPsramPeakBytes() const { return gea::framework::memory::MemoryBackend::allocationPsramPeakBytes(); }
47
+ // Allocations this task makes until endInternal() prefer on-chip RAM; `bytes`
48
+ // says how much to make room for (the display may yield staging buffers).
49
+ void beginInternal(double bytes) const {
50
+ if (gea_memory_begin_internal) gea_memory_begin_internal(bytes > 0 ? static_cast<std::size_t>(bytes) : 0);
51
+ }
52
+ void endInternal() const {
53
+ if (gea_memory_end_internal) gea_memory_end_internal();
54
+ }
40
55
  };
41
56
 
42
57
  inline constexpr MemoryFacade Memory{};
@@ -0,0 +1,191 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ #include <cstddef>
5
+ #include <cstdint>
6
+
7
+ // ESP32-S3 PIE (Processor Instruction Extensions) vector kernels for per-frame
8
+ // byte-grid effects. Every other target compiles the scalar loop, which is also
9
+ // the reference the vector path must match bit for bit.
10
+ #if defined(__XTENSA__) && __has_include("sdkconfig.h")
11
+ #include "sdkconfig.h"
12
+ #endif
13
+ #if defined(CONFIG_IDF_TARGET_ESP32S3)
14
+ #define GEA_HOST_SIMD_PIE 1
15
+ #include "freertos/FreeRTOS.h"
16
+ #else
17
+ #define GEA_HOST_SIMD_PIE 0
18
+ #endif
19
+
20
+ namespace gea::host::simd {
21
+
22
+ inline constexpr int kMaxWindows = 8;
23
+
24
+ inline void sumWindowsRowScalar(std::uint8_t *dst, const std::uint8_t *const *rows, int windows, int count, int multiplier,
25
+ int shift) {
26
+ for (int x = 0; x < count; ++x) {
27
+ int sum = 0;
28
+ for (int k = 0; k < windows; ++k) sum += rows[k][x];
29
+ const int value = (sum * multiplier) >> shift;
30
+ dst[x] = static_cast<std::uint8_t>(value < 255 ? value : 255);
31
+ }
32
+ }
33
+
34
+ #if GEA_HOST_SIMD_PIE
35
+ // 16 cells per group: each window's 16 source bytes come from two aligned
36
+ // loads joined by EE.SRC.Q (sources sit at any byte offset), are widened to
37
+ // u16 by zipping with zero and accumulated with saturating s16 adds. The sum
38
+ // is then scaled by `multiplier >> SAR`, clamped to 255 and narrowed back by
39
+ // keeping the low bytes. `dst` must be 16-byte aligned; each source read
40
+ // reaches up to 31 bytes past its group's start.
41
+ //
42
+ // q registers have been seen corrupted by a mid-kernel preemption (rgb_panel's
43
+ // blend kernel), so the block runs with this core's interrupts masked; a row is
44
+ // a few microseconds.
45
+ inline void sumWindowsGroupsPie(std::uint8_t *dst, const std::uint8_t **rows, int windows, int groups, int multiplier, int shift) {
46
+ alignas(16) std::uint16_t constants[2] = {static_cast<std::uint16_t>(multiplier), 255};
47
+ const std::uint16_t *limit = constants + 1;
48
+ int column = 0;
49
+ const std::uint8_t **cursor;
50
+ const std::uint8_t *source;
51
+ int remaining;
52
+ const UBaseType_t interrupts = portSET_INTERRUPT_MASK_FROM_ISR();
53
+ asm volatile(
54
+ "wsr.sar %[shift]\n"
55
+ "ee.vldbc.16 q6, %[constants]\n"
56
+ "ee.vldbc.16 q7, %[limit]\n"
57
+ "loopnez %[groups], 3f\n"
58
+ "ee.zero.q q4\n"
59
+ "ee.zero.q q5\n"
60
+ "mov %[cursor], %[rows]\n"
61
+ "mov %[remaining], %[windows]\n"
62
+ "2:\n"
63
+ "l32i %[source], %[cursor], 0\n"
64
+ "add %[source], %[source], %[column]\n"
65
+ "ee.ld.128.usar.ip q0, %[source], 16\n"
66
+ "ee.ld.128.usar.ip q1, %[source], 0\n"
67
+ "ee.src.q q2, q0, q1\n"
68
+ "ee.zero.q q3\n"
69
+ "ee.vzip.8 q2, q3\n"
70
+ "ee.vadds.s16 q4, q4, q2\n"
71
+ "ee.vadds.s16 q5, q5, q3\n"
72
+ "addi %[cursor], %[cursor], 4\n"
73
+ "addi %[remaining], %[remaining], -1\n"
74
+ "bnez %[remaining], 2b\n"
75
+ "ee.vmul.s16 q4, q4, q6\n"
76
+ "ee.vmul.s16 q5, q5, q6\n"
77
+ "ee.vmin.s16 q4, q4, q7\n"
78
+ "ee.vmin.s16 q5, q5, q7\n"
79
+ "ee.vunzip.8 q4, q5\n"
80
+ "ee.vst.128.ip q4, %[dst], 16\n"
81
+ "addi %[column], %[column], 16\n"
82
+ "3:\n"
83
+ : [dst] "+&r"(dst), [column] "+&r"(column), [cursor] "=&r"(cursor), [source] "=&r"(source), [remaining] "=&r"(remaining)
84
+ : [rows] "r"(rows), [windows] "r"(windows), [groups] "r"(groups), [shift] "r"(shift), [constants] "r"(constants),
85
+ [limit] "r"(limit)
86
+ : "memory");
87
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(interrupts);
88
+ }
89
+ #endif
90
+
91
+ // Whether start + (rows - 1) * stride + width <= length, without overflowing.
92
+ inline bool spanFits(std::size_t start, std::size_t stride, int rows, int width, std::size_t length) {
93
+ if (start > length) return false;
94
+ std::size_t room = length - start;
95
+ if (static_cast<std::size_t>(width) > room) return false;
96
+ room -= static_cast<std::size_t>(width);
97
+ const std::size_t steps = static_cast<std::size_t>(rows - 1);
98
+ return steps == 0 || stride == 0 || steps <= room / stride;
99
+ }
100
+
101
+ // dst[dstStart + r*dstStride + x] =
102
+ // min(255, ((Σ_k src[offsets[k] + r*srcStride + x]) * multiplier) >> shift)
103
+ // for r in [0, rows), x in [0, width). Any read or write outside the arrays
104
+ // makes the whole call a no-op rather than a partial write.
105
+ inline void sumWindowsU8(std::uint8_t *dst, std::size_t dstLength, int dstStart, int dstStride, const std::uint8_t *src,
106
+ std::size_t srcLength, const std::int32_t *offsets, std::size_t offsetsLength, int windows, int srcStride,
107
+ int width, int rows, int multiplier, int shift) {
108
+ if (!dst || !src || !offsets || windows <= 0 || windows > kMaxWindows || static_cast<std::size_t>(windows) > offsetsLength) return;
109
+ if (width <= 0 || rows <= 0 || multiplier < 0 || shift < 0 || shift > 30 || dstStart < 0 || dstStride < 0 || srcStride < 0) return;
110
+ if (!spanFits(static_cast<std::size_t>(dstStart), static_cast<std::size_t>(dstStride), rows, width, dstLength)) return;
111
+ for (int k = 0; k < windows; ++k) {
112
+ if (offsets[k] < 0 || !spanFits(static_cast<std::size_t>(offsets[k]), static_cast<std::size_t>(srcStride), rows, width, srcLength)) return;
113
+ }
114
+ #if GEA_HOST_SIMD_PIE
115
+ // Sums stay in s16 lanes and the scaled value must not overflow one before
116
+ // the clamp; outside that range the scalar loop is exact.
117
+ const bool vector = multiplier <= 32767 && ((windows * 255 * multiplier) >> shift) <= 32767;
118
+ #endif
119
+ const std::uint8_t *rowSources[kMaxWindows];
120
+ for (int r = 0; r < rows; ++r) {
121
+ std::uint8_t *out = dst + dstStart + static_cast<std::ptrdiff_t>(r) * dstStride;
122
+ for (int k = 0; k < windows; ++k) rowSources[k] = src + offsets[k] + static_cast<std::ptrdiff_t>(r) * srcStride;
123
+ int count = width;
124
+ #if GEA_HOST_SIMD_PIE
125
+ if (vector && count >= 32) {
126
+ const int head = static_cast<int>((16 - (reinterpret_cast<std::uintptr_t>(out) & 15u)) & 15u);
127
+ sumWindowsRowScalar(out, rowSources, windows, head, multiplier, shift);
128
+ out += head;
129
+ count -= head;
130
+ for (int k = 0; k < windows; ++k) rowSources[k] += head;
131
+ int groups = count >> 4;
132
+ // The last group's loads reach 31 bytes past its start; keep them inside
133
+ // every source array by leaving trailing groups to the scalar tail.
134
+ std::ptrdiff_t slack = static_cast<std::ptrdiff_t>(srcLength);
135
+ for (int k = 0; k < windows; ++k) {
136
+ const std::ptrdiff_t room = static_cast<std::ptrdiff_t>(srcLength) - (rowSources[k] - src);
137
+ if (room < slack) slack = room;
138
+ }
139
+ while (groups > 0 && static_cast<std::ptrdiff_t>(groups - 1) * 16 + 32 > slack) --groups;
140
+ if (groups > 0) {
141
+ sumWindowsGroupsPie(out, rowSources, windows, groups, multiplier, shift);
142
+ out += groups * 16;
143
+ count -= groups * 16;
144
+ for (int k = 0; k < windows; ++k) rowSources[k] += groups * 16;
145
+ }
146
+ }
147
+ #endif
148
+ sumWindowsRowScalar(out, rowSources, windows, count, multiplier, shift);
149
+ }
150
+ }
151
+
152
+ } // namespace gea::host::simd
153
+
154
+ namespace gea::host {
155
+
156
+ namespace simd {
157
+ // The program's typed array, whether the call site passes the array view
158
+ // itself or a handle to one; null for an absent handle.
159
+ template <typename Array>
160
+ auto *viewOf(const Array &array) {
161
+ if constexpr (requires { array.data(); array.size(); }) {
162
+ return &const_cast<Array &>(array);
163
+ } else {
164
+ return array ? &*array : nullptr;
165
+ }
166
+ }
167
+ } // namespace simd
168
+
169
+ struct SimdFacade {
170
+ // Typed-array arguments are bound by reference to the program's own views:
171
+ // no copy, and no dependency here on the runtime that defines them. A view
172
+ // is a window onto shared bytes, so writing through it is the JS semantics.
173
+ template <typename Dst, typename Src, typename Offsets>
174
+ void sumWindowsU8(const Dst &dstArray, double dstStart, double dstStride, const Src &srcArray, const Offsets &offsetsArray,
175
+ double windows, double srcStride, double width, double rows, double multiplier, double shift) const {
176
+ auto *dst = simd::viewOf(dstArray);
177
+ auto *src = simd::viewOf(srcArray);
178
+ auto *offsets = simd::viewOf(offsetsArray);
179
+ if (!dst || !src || !offsets) return;
180
+ static_assert(sizeof(*dst->data()) == 1 && sizeof(*src->data()) == 1 && sizeof(*offsets->data()) == 4);
181
+ simd::sumWindowsU8(reinterpret_cast<std::uint8_t *>(dst->data()), dst->size(), static_cast<int>(dstStart),
182
+ static_cast<int>(dstStride), reinterpret_cast<const std::uint8_t *>(src->data()), src->size(),
183
+ reinterpret_cast<const std::int32_t *>(offsets->data()), offsets->size(), static_cast<int>(windows),
184
+ static_cast<int>(srcStride), static_cast<int>(width), static_cast<int>(rows), static_cast<int>(multiplier),
185
+ static_cast<int>(shift));
186
+ }
187
+ };
188
+
189
+ inline constexpr SimdFacade Simd{};
190
+
191
+ } // namespace gea::host
package/input.cpp CHANGED
@@ -2,6 +2,7 @@
2
2
  #include "input.h"
3
3
 
4
4
  #include <atomic>
5
+ #include <cstring>
5
6
 
6
7
  namespace gea::framework::input {
7
8
 
@@ -20,6 +21,42 @@ constexpr unsigned kKeyQueueSize = 8;
20
21
  std::atomic_uint g_key_queue[kKeyQueueSize]{};
21
22
  std::atomic<unsigned> g_key_write{0};
22
23
  std::atomic<unsigned> g_key_read{0};
24
+ // The registered button behind each slot's key, as id + 1 (0 = a bare key
25
+ // code). Written before the slot's code is published, read after it is taken.
26
+ std::atomic_int g_key_button[kKeyQueueSize]{};
27
+
28
+ // Board button table. Entries are only ever appended, each one fully written
29
+ // before the count that exposes it is published, so readers need no lock.
30
+ struct ButtonEntry {
31
+ const char *code = "";
32
+ const char *key = "";
33
+ int keyCode = 0;
34
+ int pin = -1;
35
+ };
36
+ ButtonEntry g_buttons[kMaxButtons];
37
+ std::atomic_bool g_button_pressed[kMaxButtons]{};
38
+ std::atomic_int g_button_count{0};
39
+ std::atomic_flag g_button_register_lock = ATOMIC_FLAG_INIT;
40
+
41
+ // A button with no key alias still needs a nonzero ticket in the queue (zero
42
+ // marks an unpublished slot). The dispatcher reports the button's own
43
+ // keyCode, 0, not this.
44
+ constexpr int kUnaliasedButtonTicket = 0xFFFF;
45
+
46
+ bool validButton(int id) {
47
+ return id >= 0 && id < g_button_count.load(std::memory_order_acquire);
48
+ }
49
+
50
+ void queueKeyFor(int keyCode, bool pressed, int button) {
51
+ if (keyCode <= 0)
52
+ return;
53
+ const unsigned slot =
54
+ g_key_write.fetch_add(1, std::memory_order_acq_rel) % kKeyQueueSize;
55
+ g_key_button[slot].store(button + 1, std::memory_order_relaxed);
56
+ g_key_queue[slot].store((static_cast<unsigned>(keyCode) << 1) |
57
+ unsigned(pressed),
58
+ std::memory_order_release);
59
+ }
23
60
 
24
61
  } // namespace
25
62
 
@@ -41,19 +78,60 @@ int consumeRotaryDelta() {
41
78
  return g_rotary_delta.exchange(0, std::memory_order_acq_rel);
42
79
  }
43
80
 
44
- void queueKey(int keyCode, bool pressed) {
45
- if (keyCode <= 0)
81
+ void queueKeyDown(int keyCode) { queueKeyFor(keyCode, true, -1); }
82
+
83
+ void queueKeyUp(int keyCode) { queueKeyFor(keyCode, false, -1); }
84
+
85
+ int registerButton(const char *code, const char *key, int keyCode, int pin) {
86
+ if (!code || !*code)
87
+ return -1;
88
+ while (g_button_register_lock.test_and_set(std::memory_order_acquire)) {
89
+ }
90
+ int id = findButton(code);
91
+ if (id < 0) {
92
+ const int count = g_button_count.load(std::memory_order_relaxed);
93
+ if (count < kMaxButtons) {
94
+ g_buttons[count] = {code, key ? key : "", keyCode > 0 ? keyCode : 0, pin >= 0 ? pin : -1};
95
+ g_button_pressed[count].store(false, std::memory_order_relaxed);
96
+ g_button_count.store(count + 1, std::memory_order_release);
97
+ id = count;
98
+ }
99
+ }
100
+ g_button_register_lock.clear(std::memory_order_release);
101
+ return id;
102
+ }
103
+
104
+ void queueButton(int id, bool pressed) {
105
+ if (!validButton(id))
46
106
  return;
47
- const unsigned slot =
48
- g_key_write.fetch_add(1, std::memory_order_acq_rel) % kKeyQueueSize;
49
- g_key_queue[slot].store((static_cast<unsigned>(keyCode) << 1) |
50
- unsigned(pressed),
51
- std::memory_order_release);
107
+ g_button_pressed[id].store(pressed, std::memory_order_release);
108
+ const int keyCode = g_buttons[id].keyCode;
109
+ queueKeyFor(keyCode > 0 ? keyCode : kUnaliasedButtonTicket, pressed, id);
52
110
  }
53
111
 
54
- void queueKeyDown(int keyCode) { queueKey(keyCode, true); }
112
+ int buttonCount() { return g_button_count.load(std::memory_order_acquire); }
55
113
 
56
- void queueKeyUp(int keyCode) { queueKey(keyCode, false); }
114
+ const char *buttonCode(int id) { return validButton(id) ? g_buttons[id].code : ""; }
115
+
116
+ const char *buttonKey(int id) { return validButton(id) ? g_buttons[id].key : ""; }
117
+
118
+ int buttonKeyCode(int id) { return validButton(id) ? g_buttons[id].keyCode : 0; }
119
+
120
+ int buttonPin(int id) { return validButton(id) ? g_buttons[id].pin : -1; }
121
+
122
+ int findButton(const char *code) {
123
+ if (!code)
124
+ return -1;
125
+ const int count = buttonCount();
126
+ for (int id = 0; id < count; ++id)
127
+ if (std::strcmp(g_buttons[id].code, code) == 0)
128
+ return id;
129
+ return -1;
130
+ }
131
+
132
+ bool buttonPressed(int id) {
133
+ return validButton(id) && g_button_pressed[id].load(std::memory_order_acquire);
134
+ }
57
135
 
58
136
  bool consumeKeyEvent(HardwareKeyEvent &event) {
59
137
  const unsigned write = g_key_write.load(std::memory_order_acquire);
@@ -73,8 +151,12 @@ bool consumeKeyEvent(HardwareKeyEvent &event) {
73
151
  // Zero key codes never reserve a ticket in queueKeyDown().
74
152
  if (code == 0)
75
153
  return false;
154
+ const int button =
155
+ g_key_button[slot].load(std::memory_order_relaxed) - 1;
76
156
  g_key_read.store(read + 1, std::memory_order_release);
77
- event = {static_cast<int>(code >> 1), (code & 1) != 0};
157
+ event = {static_cast<int>(code >> 1), (code & 1) != 0, button};
158
+ if (button >= 0)
159
+ event.keyCode = buttonKeyCode(button);
78
160
  return true;
79
161
  }
80
162
  return false;
@@ -83,7 +165,7 @@ bool consumeKeyEvent(HardwareKeyEvent &event) {
83
165
  int consumeKeyDown() {
84
166
  HardwareKeyEvent event{};
85
167
  while (consumeKeyEvent(event)) {
86
- if (event.pressed)
168
+ if (event.pressed && event.keyCode > 0)
87
169
  return event.keyCode;
88
170
  }
89
171
  return 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/host",
3
- "version": "0.1.21",
3
+ "version": "0.1.23",
4
4
  "description": "GeaStack host bindings and platform service sources.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {