@geastack/host 0.1.12 → 0.1.14

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
@@ -487,7 +487,11 @@ private:
487
487
  }
488
488
 
489
489
  const bool tones = hasActiveTones();
490
- renderChunk(pcm, kChunkSamples);
490
+ // Streaming speech has no oscillator voices to render. Avoid walking
491
+ // every tone slot for every sample, including the empty pulls between
492
+ // incoming packets, in this highest-priority task.
493
+ if (tones) renderChunk(pcm, kChunkSamples);
494
+ else std::memset(pcm, 0, sizeof(pcm));
491
495
  const auto streamFrames = streams_.mix(pcm, kChunkSamples);
492
496
  const auto outputFrames = tones ? std::size_t(kChunkSamples) : streamFrames;
493
497
  if (outputFrames == 0) {
package/host/audio.cpp CHANGED
@@ -417,6 +417,7 @@ struct PcmAudioStream::State {
417
417
  std::deque<Block> queue;
418
418
  std::size_t queuedSamples = 0, readOffset = 0;
419
419
  AudioLevelMeter level;
420
+ pcm::PlaybackStartGate startGate;
420
421
  std::uint64_t output = 0, pulled = 0;
421
422
  std::uint32_t lastPull = 0;
422
423
  std::atomic<bool> closed{false};
@@ -433,6 +434,7 @@ PcmAudioStream PcmAudioStream::create(double sampleRate) {
433
434
  const auto state = weak.lock();
434
435
  if (!state) return std::size_t{0};
435
436
  std::lock_guard<std::mutex> lock(state->mutex);
437
+ if (!state->startGate.ready(state->queuedSamples, pcmNowMs())) return std::size_t{0};
436
438
  const auto count = std::min(capacity, state->queuedSamples);
437
439
  std::size_t copied = 0;
438
440
  while (copied < count) {
@@ -493,8 +495,17 @@ void PcmAudioStream::pipeTo(WebSocket socket, const std::string &prefix, const s
493
495
  });
494
496
  }
495
497
 
496
- void PcmAudioStream::receiveFrom(WebSocket socket, const std::string& prefix, const std::string& suffix) const {
498
+ void PcmAudioStream::receiveFrom(WebSocket socket, const std::string& prefix, const std::string& suffix, double startupMs) const {
499
+ if (!std::isfinite(startupMs) || startupMs < 0 || startupMs > 10000)
500
+ throw std::invalid_argument("PCM startup delay must be between 0 and 10000 ms");
497
501
  if (!state_ || state_->closed) throw std::logic_error("Closed PCM stream");
502
+ {
503
+ std::lock_guard<std::mutex> lock(state_->mutex);
504
+ // Keep the startup clock across turns. A sender that coordinates both
505
+ // media streams can opt out instead of stacking a second audio-only wait.
506
+ state_->startGate.enable(static_cast<std::uint32_t>(startupMs));
507
+ if (state_->queuedSamples) state_->startGate.pushed(pcmNowMs());
508
+ }
498
509
  const std::weak_ptr<State> weak = state_;
499
510
  websocket::setTextConsumer(socket.nativeHandle, [weak, prefix, suffix](const std::string& message) {
500
511
  if (message.size() < prefix.size() + suffix.size() ||
@@ -513,10 +524,16 @@ std::string PcmAudioStream::readBase64() const {
513
524
  const auto started = pcmNowMs();
514
525
  if (!state_) return {};
515
526
  std::lock_guard<std::mutex> lock(state_->captureMutex);
516
- if (state_->closed || !state_->reader || state_->reader->pendingSamples() < 640) return {};
517
- std::int16_t input[640];
518
- const auto count = state_->reader->read(input, 640);
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;
530
+ if (state_->closed || !state_->reader || state_->reader->pendingSamples() < captureFrames) return {};
531
+ std::int16_t input[captureFrames];
532
+ const auto count = state_->reader->read(input, captureFrames);
519
533
  const auto readAt = pcmNowMs();
534
+ // The native bridge already supplies 16 kHz PCM. Encode the capture block
535
+ // directly rather than allocating and visiting a resampler for each sample.
536
+ if (state_->wireRate == 16000) return pcm::encode(input, count);
520
537
  std::vector<std::int16_t> wire;
521
538
  wire.reserve(1920);
522
539
  for (std::size_t i = 0; i < count; ++i)
@@ -538,22 +555,32 @@ void PcmAudioStream::writeBase64(const std::string &data) const {
538
555
  const auto decodedAt = pcmNowMs();
539
556
  // Resampling and allocation never hold the real-time mixer's queue mutex.
540
557
  State::Block block;
541
- block.reserve(wire.size() * 16000 / state_->wireRate + 2);
542
- for (auto sample : wire)
543
- state_->playback.push(sample, [&](std::int16_t value) { block.push_back(value); });
544
- std::lock_guard<std::mutex> lock(state_->mutex);
545
- // Generated output may run faster than playback. Never silently overwrite
546
- // the unplayed tail (MediaStream's live capture ring has different semantics).
547
- if (state_->queuedSamples + block.size() > 16000 * 30)
548
- throw std::runtime_error("PCM playback exceeded 30 second queue limit");
549
- if (!block.empty()) {
550
- state_->queuedSamples += block.size();
551
- state_->queue.push_back(std::move(block));
558
+ if (state_->wireRate == 16000) {
559
+ block.assign(wire.begin(), wire.end());
560
+ } else {
561
+ block.reserve(wire.size() * 16000 / state_->wireRate + 2);
562
+ for (auto sample : wire)
563
+ state_->playback.push(sample, [&](std::int16_t value) { block.push_back(value); });
564
+ }
565
+ unsigned packets, queuedMs;
566
+ {
567
+ std::lock_guard<std::mutex> lock(state_->mutex);
568
+ // Generated output may run faster than playback. Never silently overwrite
569
+ // the unplayed tail (MediaStream's live capture ring has different semantics).
570
+ if (state_->queuedSamples + block.size() > 16000 * 30)
571
+ throw std::runtime_error("PCM playback exceeded 30 second queue limit");
572
+ if (!block.empty()) {
573
+ state_->startGate.pushed(pcmNowMs());
574
+ state_->queuedSamples += block.size();
575
+ state_->queue.push_back(std::move(block));
576
+ }
577
+ packets = ++state_->receivedPackets;
578
+ queuedMs = unsigned(state_->queuedSamples * 1000 / 16000);
552
579
  }
580
+ // Console formatting and sinks must never hold the speaker's queue lock.
553
581
  #ifdef ESP_PLATFORM
554
- if (++state_->receivedPackets == 1 || state_->receivedPackets % 100 == 0)
555
- ESP_LOGI("gea_pcm", "native receive packets=%u queued_ms=%u", state_->receivedPackets,
556
- unsigned(state_->queuedSamples * 1000 / 16000));
582
+ if (packets == 1 || packets % 100 == 0)
583
+ ESP_LOGI("gea_pcm", "native receive packets=%u queued_ms=%u", packets, queuedMs);
557
584
  if (pcmNowMs()-started > 15) ESP_LOGW("gea_pcm", "playback samples=%u decode_ms=%u resample_queue_ms=%u", unsigned(wire.size()), decodedAt-started, pcmNowMs()-decodedAt);
558
585
  #endif
559
586
  }
@@ -565,6 +592,7 @@ void PcmAudioStream::resetPlayback(bool interrupted) const {
565
592
  state_->queue.clear();
566
593
  state_->queuedSamples = state_->readOffset = 0;
567
594
  state_->playback.reset();
595
+ state_->startGate.reset();
568
596
  state_->pulled = 0;
569
597
  state_->lastPull = 0;
570
598
  state_->level.reset();
package/host/image.cpp CHANGED
@@ -323,6 +323,7 @@ GeaEmbeddedImage ImageService::make(double id) const {
323
323
  return handle;
324
324
  }
325
325
 
326
+ bool GeaEmbeddedImage::decode() const { return store().currentPixels(id) != nullptr; }
326
327
  void GeaEmbeddedImage::play() const { store().setPlaying(id, true); }
327
328
  void GeaEmbeddedImage::pause() const { store().setPlaying(id, false); }
328
329
  void GeaEmbeddedImage::seek(int frame) const { store().seek(id, frame); }
package/host/mjpeg.cpp CHANGED
@@ -1,6 +1,7 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #include "host/mjpeg.h"
3
3
  #include "host/mjpeg_parser.h"
4
+ #include "host/h264_packet_queue.h"
4
5
  #include "host/video_frame_pool.h"
5
6
  #include "pixel.h"
6
7
  #include <atomic>
@@ -16,6 +17,10 @@ extern "C" void gea_mjpeg_link_bindings() {}
16
17
  #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED) && __has_include("esp_jpeg_dec.h")
17
18
  #include "esp_http_client.h"
18
19
  #include "esp_jpeg_dec.h"
20
+ #if __has_include("esp_h264_dec_sw.h")
21
+ #include "host/rtc_h264.h"
22
+ #define GEA_HAS_MULTIPART_H264 1
23
+ #endif
19
24
  #include "esp_log.h"
20
25
  #include "esp_timer.h"
21
26
  #include "freertos/FreeRTOS.h"
@@ -43,26 +48,32 @@ struct MjpegStream::State {
43
48
  SemaphoreHandle_t wake = nullptr;
44
49
  std::mutex mutex;
45
50
  std::optional<JpegPacket> newest;
51
+ H264PacketQueue h264Packets;
46
52
  std::atomic<unsigned> received{0}, replaced{0};
47
53
 
48
54
  void receive() {
49
55
  esp_http_client_config_t config{};
50
56
  config.url = url.c_str();
51
- config.timeout_ms = 1000;
57
+ // Initial ARP/TCP setup can exceed one second on a newly booted station.
58
+ // The steady-state read timeout is shortened after the connection opens.
59
+ config.timeout_ms = 5000;
52
60
  config.buffer_size = 4096;
53
61
  config.disable_auto_redirect = true;
54
62
  #if GEA_EMBEDDED_ENABLE_HTTPS
55
63
  config.crt_bundle_attach = esp_crt_bundle_attach;
56
64
  #endif
57
65
  auto client = esp_http_client_init(&config);
58
- if (!client) throw std::runtime_error("MJPEG HTTP allocation failed");
66
+ if (!client) { ESP_LOGE("gea_mjpeg", "MJPEG HTTP allocation failed"); return; }
59
67
  struct Cleanup {
60
68
  esp_http_client_handle_t client;
61
69
  ~Cleanup() { esp_http_client_cleanup(client); }
62
70
  } cleanup{client};
63
71
  if (esp_http_client_open(client, 0) != ESP_OK ||
64
- esp_http_client_fetch_headers(client) < 0 || esp_http_client_get_status_code(client) != 200)
65
- throw std::runtime_error("MJPEG HTTP connection rejected");
72
+ esp_http_client_fetch_headers(client) < 0 || esp_http_client_get_status_code(client) != 200) {
73
+ ESP_LOGE("gea_mjpeg", "MJPEG HTTP connection rejected");
74
+ return;
75
+ }
76
+ esp_http_client_set_timeout_ms(client, 1000);
66
77
  MjpegParser parser;
67
78
  std::array<uint8_t, 4096> bytes{};
68
79
  auto lastData = esp_timer_get_time();
@@ -72,18 +83,21 @@ struct MjpegStream::State {
72
83
  if (!running) break;
73
84
  if (size == -ESP_ERR_HTTP_EAGAIN && esp_timer_get_time() - lastData <
74
85
  (receivedData ? 15000000 : 150000000)) continue;
75
- if (size <= 0) throw std::runtime_error("MJPEG HTTP stream ended");
86
+ if (size <= 0) { ESP_LOGE("gea_mjpeg", "MJPEG HTTP stream ended"); return; }
76
87
  lastData = esp_timer_get_time();
77
88
  receivedData = true;
78
89
  if (!parser.push(std::span(bytes.data(), size_t(size)), [&](JpegPacket packet) {
79
90
  {
80
91
  std::lock_guard lock(mutex);
81
- if (newest) ++replaced;
82
- newest = std::move(packet);
92
+ if (packet.h264) replaced += h264Packets.push(std::move(packet));
93
+ else {
94
+ if (newest) ++replaced;
95
+ newest = std::move(packet);
96
+ }
83
97
  ++received;
84
98
  }
85
99
  xSemaphoreGive(wake);
86
- })) throw std::runtime_error("MJPEG malformed or oversized multipart frame");
100
+ })) { ESP_LOGE("gea_mjpeg", "MJPEG malformed or oversized multipart frame"); return; }
87
101
  // Receiving owns no decode/display work and cannot build a frame queue.
88
102
  taskYIELD();
89
103
  }
@@ -99,19 +113,46 @@ struct MjpegStream::State {
99
113
  ~Cleanup() { if (decoder) jpeg_dec_close(decoder); }
100
114
  } cleanup{decoder};
101
115
  media::VideoFramePool frames;
116
+ #ifdef GEA_HAS_MULTIPART_H264
117
+ rtc::h264::Decoder h264Decoder;
118
+ #endif
102
119
  const auto track = source.getVideoTracks().front().nativeHandle;
103
- unsigned decoded = 0, raw = 0;
104
- int64_t report = esp_timer_get_time(), totalDecode = 0;
120
+ unsigned decoded = 0, raw = 0, h264 = 0;
121
+ int64_t report = esp_timer_get_time(), totalDecode = 0, h264DecodeUs = 0, h264ConvertUs = 0;
122
+ uint64_t workerCpuUs = 0;
105
123
  while (running) {
106
124
  xSemaphoreTake(wake, pdMS_TO_TICKS(100));
107
125
  if (!running) break;
108
126
  std::optional<JpegPacket> packet;
109
- { std::lock_guard lock(mutex); packet.swap(newest); }
127
+ {
128
+ std::lock_guard lock(mutex);
129
+ packet = h264Packets.pop();
130
+ if (!packet) packet.swap(newest);
131
+ // A binary semaphore must keep draining an existing reference queue
132
+ // even if upstream pauses before sending another packet.
133
+ if (!h264Packets.empty()) xSemaphoreGive(wake);
134
+ }
110
135
  if (!packet) continue;
111
136
  const auto started = esp_timer_get_time();
137
+ #if CONFIG_FREERTOS_USE_TRACE_FACILITY && CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS && CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER
138
+ TaskStatus_t cpuBefore{};
139
+ vTaskGetInfo(nullptr, &cpuBefore, pdFALSE, eRunning);
140
+ #endif
112
141
  auto frame = std::move(packet->rawFrame);
113
142
  if (frame) {
114
143
  ++raw;
144
+ } else if (packet->h264) {
145
+ #ifdef GEA_HAS_MULTIPART_H264
146
+ if (packet->resetDecoder) h264Decoder.reset();
147
+ frame = h264Decoder.decode(packet->bytes.data(), packet->bytes.size(), packet->timestampMs);
148
+ if (!frame) throw std::runtime_error("H264 access unit decode failed");
149
+ h264DecodeUs += h264Decoder.lastDecodeUs();
150
+ h264ConvertUs += h264Decoder.lastConvertUs();
151
+ ++h264;
152
+ if (h264 == 1) ESP_LOGI("gea_h264", "simd_input_aligned=%d", h264Decoder.simdAligned());
153
+ #else
154
+ throw std::runtime_error("Native H264 decoder is not linked on this target");
155
+ #endif
115
156
  } else {
116
157
  // RGB565 never instantiates a JPEG decoder or a second pixel buffer.
117
158
  if (!decoder && jpeg_dec_open(&config, &decoder) != JPEG_ERR_OK)
@@ -139,10 +180,19 @@ struct MjpegStream::State {
139
180
  media::publish_video_frame(track, std::move(frame));
140
181
  ++decoded;
141
182
  totalDecode += esp_timer_get_time() - started;
183
+ #if CONFIG_FREERTOS_USE_TRACE_FACILITY && CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS && CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER
184
+ TaskStatus_t cpuAfter{};
185
+ vTaskGetInfo(nullptr, &cpuAfter, pdFALSE, eRunning);
186
+ workerCpuUs += cpuAfter.ulRunTimeCounter - cpuBefore.ulRunTimeCounter;
187
+ #endif
142
188
  const auto now = esp_timer_get_time();
143
189
  if (now - report >= 2000000) {
144
- ESP_LOGI("gea_mjpeg", "decoded=%u received=%u replaced=%u decode_us=%lld raw=%u",
145
- decoded, received.load(), replaced.load(), (long long)(totalDecode / decoded), raw);
190
+ ESP_LOGI("gea_mjpeg", "decoded=%u received=%u replaced=%u decode_us=%lld raw=%u h264=%u worker_cpu_us=%llu",
191
+ decoded, received.load(), replaced.load(), (long long)(totalDecode / decoded), raw, h264,
192
+ (unsigned long long)(workerCpuUs / decoded));
193
+ if (h264) ESP_LOGI("gea_h264", "decode_us=%lld convert_us=%lld worker_cpu_us=%llu",
194
+ (long long)(h264DecodeUs / h264), (long long)(h264ConvertUs / h264),
195
+ (unsigned long long)(workerCpuUs / decoded));
146
196
  report = now;
147
197
  }
148
198
  vTaskDelay(1); // Keep raster and CPU1 idle work progressing under sustained video.
@@ -180,8 +230,17 @@ MjpegStream::MjpegStream(const std::string& url) {
180
230
  for (const bool decode : {false, true}) {
181
231
  auto* owner = new std::shared_ptr<State>(state_);
182
232
  const auto entry = decode ? State::worker<true> : State::worker<false>;
233
+ // Drain TCP promptly so rendering cannot close its small receive window.
234
+ // JPEG decoding shares the UI's background priority. Audio stays above
235
+ // both, and the receive worker blocks when no network data is available.
236
+ // Full-image RGB565 JPEG decoding is integer/SIMD work. The codec's
237
+ // floating-point block-count helper is not used or linked on this path.
238
+ // Let FreeRTOS use the spare cycles on either core: fixed CPU0 competes
239
+ // with capture/Wi-Fi, while fixed CPU1 competes with UI/response receive.
240
+ // Audio remains higher priority; reception and rendering stay independent.
241
+ const BaseType_t decodeCore = configNUMBER_OF_CORES > 1 ? tskNO_AFFINITY : 0;
183
242
  if (xTaskCreatePinnedToCoreWithCaps(entry, decode ? "gea_mjpeg_dec" : "gea_mjpeg_rx",
184
- decode ? 64 * 1024 : 16 * 1024, owner, decode ? 4 : 7, nullptr, 1,
243
+ decode ? 64 * 1024 : 16 * 1024, owner, decode ? 3 : 4, nullptr, decode ? decodeCore : 1,
185
244
  MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS) {
186
245
  delete owner;
187
246
  stop();
package/host/video.cpp CHANGED
@@ -7,12 +7,15 @@
7
7
  #include "pixel.h"
8
8
  #include <stdexcept>
9
9
  #include <unordered_map>
10
+ #include <chrono>
10
11
 
11
12
  namespace gea::host {
12
13
  struct HTMLVideoElement::State {
13
14
  int node = -1, image = -1;
14
15
  uint32_t width = 0, height = 0;
15
16
  uint64_t sequence = 0;
17
+ uint32_t selected = 0, maxGapMs = 0;
18
+ std::chrono::steady_clock::time_point selectedAt{};
16
19
  MediaStream source;
17
20
  std::string url;
18
21
  std::unique_ptr<video::MjpegStream> mjpeg;
@@ -72,6 +75,8 @@ void HTMLVideoElement::setSrcObject(MediaStream stream) const {
72
75
  state_->url.clear();
73
76
  state_->source = stream;
74
77
  state_->sequence = 0;
78
+ state_->selected = state_->maxGapMs = 0;
79
+ state_->selectedAt = {};
75
80
  state_->width = state_->height = 0;
76
81
  state_->playing = false;
77
82
  // Detaching/replacing a stream releases its presentation buffer immediately.
@@ -139,6 +144,11 @@ void HTMLVideoElement::presentFrames() {
139
144
  state->image = image;
140
145
  state->presentedFrame = borrowed ? frame : nullptr;
141
146
  state->sequence = frame->sequence;
147
+ const auto now = std::chrono::steady_clock::now();
148
+ if (state->selected) state->maxGapMs = std::max(state->maxGapMs,
149
+ uint32_t(std::chrono::duration_cast<std::chrono::milliseconds>(now - state->selectedAt).count()));
150
+ state->selectedAt = now;
151
+ ++state->selected;
142
152
  state->width = frame->width;
143
153
  state->height = frame->height;
144
154
  if (!state->playing) {
@@ -148,5 +158,19 @@ void HTMLVideoElement::presentFrames() {
148
158
  }
149
159
  }
150
160
  }
161
+ VideoPresentationStats HTMLVideoElement::presentationStats() {
162
+ VideoPresentationStats result;
163
+ for (const auto& [id, weak] : State::registry()) {
164
+ const auto state = weak.lock();
165
+ if (!state || state->paused) continue;
166
+ const auto tracks = state->source.getVideoTracks();
167
+ if (tracks.empty()) continue;
168
+ const auto latest = media::latest_video_frame(tracks.front().nativeHandle);
169
+ if (latest) result.decoded += uint32_t(latest->sequence);
170
+ result.selected += state->selected;
171
+ result.maxGapMs = std::max(result.maxGapMs, state->maxGapMs);
172
+ }
173
+ return result;
174
+ }
151
175
  namespace video { void presentFrames() { HTMLVideoElement::presentFrames(); } }
152
176
  } // namespace gea::host
@@ -115,7 +115,9 @@ __attribute__((weak)) void platform_set_producer(NativeWebSocketHandle, TextProd
115
115
  #endif
116
116
 
117
117
  void setTextProducer(NativeWebSocketHandle handle, TextProducer producer) {
118
- if (producer) workers::Context::current()->prioritizeAudio();
118
+ // The producer runs exclusively on the native socket sender, whose priority
119
+ // platform_set_producer raises for audio. Promoting the caller's realm here
120
+ // also promotes the UI that attached it and starves background video decode.
119
121
  platform_set_producer(handle, std::move(producer));
120
122
  }
121
123
 
@@ -501,6 +503,13 @@ void handleWsEvent(void *arg, esp_event_base_t, int32_t event_id, void *data) {
501
503
  }
502
504
  }
503
505
  if (hasMessage) {
506
+ // Native PCM receive is as time-critical as its sender. Leaving the
507
+ // SDK RX task at priority 5 while PCM TX runs at 23 can prevent RX
508
+ // from draining the socket during a capture burst and close its TCP
509
+ // window. Only native sinks opt in; ordinary JS sockets stay at the
510
+ // SDK's default priority. This callback runs on the RX task itself.
511
+ if (consumer && uxTaskPriorityGet(nullptr) != configMAX_PRIORITIES - 2)
512
+ vTaskPrioritySet(nullptr, configMAX_PRIORITIES - 2);
504
513
  try {
505
514
  if (!consumer || !consumer(complete))
506
515
  enqueue(PendingEvent{handle, EventKind::Message, std::move(complete), 0});
@@ -212,7 +212,7 @@ class PcmAudioStream {
212
212
  static PcmAudioStream create(double sampleRate);
213
213
  void setInput(MediaStream stream) const;
214
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;
215
+ void receiveFrom(WebSocket socket, const std::string &prefix, const std::string &suffix, double startupMs = 200) const;
216
216
  std::string readBase64() const;
217
217
  void writeBase64(const std::string &data) const;
218
218
  void resetPlayback(bool interrupted = false) const;
@@ -0,0 +1,38 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+ #include "host/mjpeg_parser.h"
4
+ #include <deque>
5
+ #include <optional>
6
+
7
+ namespace gea::host::video {
8
+ // Keep references in order. On overload, abandon the entire reference chain
9
+ // and restart at the next IDR; never retain an unbounded latency backlog.
10
+ class H264PacketQueue {
11
+ public:
12
+ unsigned push(JpegPacket packet) {
13
+ unsigned dropped = 0;
14
+ if (packets_.size() == 3) {
15
+ dropped = unsigned(packets_.size());
16
+ packets_.clear();
17
+ needKeyframe_ = true;
18
+ }
19
+ if (needKeyframe_) {
20
+ if (!packet.h264Keyframe) return dropped + 1;
21
+ packet.resetDecoder = true;
22
+ needKeyframe_ = false;
23
+ }
24
+ packets_.push_back(std::move(packet));
25
+ return dropped;
26
+ }
27
+ std::optional<JpegPacket> pop() {
28
+ if (packets_.empty()) return {};
29
+ auto packet = std::move(packets_.front());
30
+ packets_.pop_front();
31
+ return packet;
32
+ }
33
+ bool empty() const { return packets_.empty(); }
34
+ private:
35
+ std::deque<JpegPacket> packets_;
36
+ bool needKeyframe_ = true;
37
+ };
38
+ } // namespace gea::host::video
@@ -22,6 +22,7 @@ struct GeaEmbeddedImage {
22
22
  int frameCount = 0;
23
23
  bool isAnimated = false;
24
24
 
25
+ bool decode() const;
25
26
  void play() const;
26
27
  void pause() const;
27
28
  void seek(int frame) const;
@@ -1,6 +1,7 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #pragma once
3
3
  #include "host/video_frame_pool.h"
4
+ #include "host/h264_layout.h"
4
5
  #include <bit>
5
6
  #include <charconv>
6
7
  #include <functional>
@@ -14,6 +15,9 @@ using JpegBytes = std::vector<uint8_t, media::VideoAllocator<uint8_t>>;
14
15
  struct JpegPacket {
15
16
  JpegBytes bytes;
16
17
  uint32_t timestampMs = 0;
18
+ bool h264 = false;
19
+ bool h264Keyframe = false;
20
+ bool resetDecoder = false;
17
21
  // Raw transport writes directly into the final pooled pixel allocation.
18
22
  std::shared_ptr<media::VideoFrame> rawFrame;
19
23
  };
@@ -26,7 +30,7 @@ class MjpegParser {
26
30
  while (!bytes.empty()) {
27
31
  if (remaining_) {
28
32
  const auto count = std::min(remaining_, bytes.size());
29
- if (format_ == Format::Jpeg) {
33
+ if (format_ == Format::Jpeg || format_ == Format::H264) {
30
34
  packet_.bytes.insert(packet_.bytes.end(), bytes.begin(), bytes.begin() + count);
31
35
  } else if (packet_.rawFrame) {
32
36
  std::memcpy(reinterpret_cast<uint8_t*>(packet_.rawFrame->rgb565.data()) + length_ - remaining_,
@@ -39,10 +43,31 @@ class MjpegParser {
39
43
  const auto& jpeg = packet_.bytes;
40
44
  if (jpeg.size() < 4 || jpeg[0] != 0xff || jpeg[1] != 0xd8 ||
41
45
  jpeg[jpeg.size() - 2] != 0xff || jpeg.back() != 0xd9) return false;
46
+ } else if (format_ == Format::H264) {
47
+ const auto& bytes = packet_.bytes;
48
+ if (!rtc::h264::inspectAccessUnit(bytes.data(), bytes.size(), h264Metadata_) ||
49
+ h264Metadata_.visibleWidth != int(width_) || h264Metadata_.visibleHeight != int(height_)) return false;
50
+ unsigned prefix = 0;
51
+ bool sps = false, pps = false, idr = false, predictive = false;
52
+ for (size_t start = rtc::h264::startCode(bytes.data(), bytes.size(), 0, prefix);
53
+ start < bytes.size();) {
54
+ const auto nal = start + prefix;
55
+ if (nal >= bytes.size()) return false;
56
+ const auto type = bytes[nal] & 31;
57
+ predictive |= type == 1;
58
+ sps |= type == 7; pps |= type == 8; idr |= type == 5;
59
+ start = rtc::h264::startCode(bytes.data(), bytes.size(), nal, prefix);
60
+ }
61
+ if (idr) {
62
+ if (!sps || !pps) return false;
63
+ h264HasIdr_ = true;
64
+ } else if (!h264HasIdr_ || !predictive) return false;
65
+ packet_.h264 = true;
66
+ packet_.h264Keyframe = idr;
42
67
  }
43
68
  // Exhausted pool means a slow sink: consume/drop this whole picture,
44
69
  // never overwrite a published buffer or grow a frame backlog.
45
- if (format_ == Format::Jpeg || packet_.rawFrame) emit(std::move(packet_));
70
+ if (format_ == Format::Jpeg || format_ == Format::H264 || packet_.rawFrame) emit(std::move(packet_));
46
71
  packet_ = {};
47
72
  length_ = width_ = height_ = 0;
48
73
  format_ = Format::None;
@@ -60,8 +85,9 @@ class MjpegParser {
60
85
  if (line_.empty()) {
61
86
  if (inHeaders_) {
62
87
  if (!length_ || format_ == Format::None) return false;
63
- if (format_ == Format::Jpeg) {
64
- if (length_ > 65536) return false;
88
+ if (format_ == Format::Jpeg || format_ == Format::H264) {
89
+ if (length_ > (format_ == Format::Jpeg ? 65536 : 262144)) return false;
90
+ if (format_ == Format::H264 && (!width_ || !height_)) return false;
65
91
  packet_.bytes.reserve(length_);
66
92
  } else {
67
93
  if (!width_ || !height_ || length_ != size_t(width_) * height_ * 2) return false;
@@ -104,6 +130,7 @@ class MjpegParser {
104
130
  } else if (name == "content-type") {
105
131
  if (format_ != Format::None) return false;
106
132
  if (value == "image/jpeg") format_ = Format::Jpeg;
133
+ else if (value == "video/h264") format_ = Format::H264;
107
134
  else if (value == "application/x-rgb565-be") format_ = Format::Rgb565Be;
108
135
  else if (value == "application/x-rgb565-le") format_ = Format::Rgb565Le;
109
136
  else return false;
@@ -114,10 +141,12 @@ class MjpegParser {
114
141
  return true;
115
142
  }
116
143
  private:
117
- enum class Format { None, Jpeg, Rgb565Le, Rgb565Be };
144
+ enum class Format { None, Jpeg, H264, Rgb565Le, Rgb565Be };
118
145
  std::string line_, boundary_;
119
146
  JpegPacket packet_;
120
147
  media::VideoFramePool frames_;
148
+ rtc::h264::Metadata h264Metadata_;
149
+ bool h264HasIdr_ = false;
121
150
  uint32_t width_ = 0, height_ = 0;
122
151
  size_t remaining_ = 0, length_ = 0, headerBytes_ = 0;
123
152
  bool inHeaders_ = false;
@@ -2,6 +2,7 @@
2
2
  #pragma once
3
3
 
4
4
  #include <algorithm>
5
+ #include <array>
5
6
  #include <cstdint>
6
7
  #include <stdexcept>
7
8
  #include <string>
@@ -43,6 +44,30 @@ struct QueueAllocator {
43
44
  };
44
45
 
45
46
 
47
+ // Native network PCM needs a small startup reservoir before DMA consumes it.
48
+ // This is a one-time gate, never a minimum queue retained during playback:
49
+ // short tails are released after the bounded wait and no sample is discarded.
50
+ class PlaybackStartGate {
51
+ public:
52
+ void enable(std::uint32_t delayMs) { delayMs_ = delayMs; reset(); }
53
+ void pushed(std::uint32_t nowMs) {
54
+ if (!received_) { firstPacketMs_ = nowMs; received_ = true; }
55
+ }
56
+ bool ready(std::size_t queuedSamples, std::uint32_t nowMs) {
57
+ if (!delayMs_ || started_) return true;
58
+ if (!queuedSamples) return false;
59
+ // A TCP burst is not a realtime cadence: even a large first batch must
60
+ // wait for the arrival timeline to establish its lead over playback.
61
+ if (!received_ || std::uint32_t(nowMs - firstPacketMs_) < delayMs_) return false;
62
+ started_ = true;
63
+ return true;
64
+ }
65
+ void reset() { received_ = started_ = false; firstPacketMs_ = 0; }
66
+ private:
67
+ std::uint32_t delayMs_ = 0, firstPacketMs_ = 0;
68
+ bool received_ = false, started_ = false;
69
+ };
70
+
46
71
  // Causal linear conversion: preserve fractional position across every network
47
72
  // chunk. Input/output are signed mono PCM, never independently resampled frames.
48
73
  class Resampler {
@@ -55,6 +80,12 @@ class Resampler {
55
80
  }
56
81
  template <typename Write>
57
82
  void push(std::int16_t sample, Write write) {
83
+ if (input_ == output_) {
84
+ previous_ = sample;
85
+ started_ = true;
86
+ write(sample);
87
+ return;
88
+ }
58
89
  if (!started_) { previous_ = sample; started_ = true; }
59
90
  phase_ += output_;
60
91
  while (phase_ >= input_) {
@@ -76,47 +107,66 @@ class Resampler {
76
107
  bool started_ = false;
77
108
  };
78
109
 
79
- inline std::string encode(const std::vector<std::int16_t>& pcm) {
110
+ inline std::string encode(const std::int16_t* pcm, std::size_t samples) {
80
111
  constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
81
- std::string result;
82
- result.reserve((pcm.size() * 2 + 2) / 3 * 4);
83
- std::uint32_t bits = 0;
84
- int available = 0;
85
- for (auto sample : pcm) {
86
- for (int shift : {0, 8}) {
87
- bits = (bits << 8) | ((static_cast<std::uint16_t>(sample) >> shift) & 255);
88
- available += 8;
89
- while (available >= 6) { available -= 6; result += alphabet[(bits >> available) & 63]; }
90
- }
112
+ const auto bytes = samples * 2;
113
+ // Size once: appending every base64 character repeatedly reads/writes the
114
+ // string metadata in PSRAM on the realtime network worker.
115
+ std::string result((bytes + 2) / 3 * 4, '=');
116
+ const auto byte = [&](size_t index) {
117
+ return (static_cast<std::uint16_t>(pcm[index / 2]) >> ((index % 2) * 8)) & 255u;
118
+ };
119
+ for (size_t input = 0, output = 0; input < bytes; input += 3, output += 4) {
120
+ const auto first = byte(input);
121
+ const auto second = input + 1 < bytes ? byte(input + 1) : 0;
122
+ const auto third = input + 2 < bytes ? byte(input + 2) : 0;
123
+ result[output] = alphabet[first >> 2];
124
+ result[output + 1] = alphabet[((first & 3) << 4) | (second >> 4)];
125
+ if (input + 1 < bytes) result[output + 2] = alphabet[((second & 15) << 2) | (third >> 6)];
126
+ if (input + 2 < bytes) result[output + 3] = alphabet[third & 63];
91
127
  }
92
- if (available) result += alphabet[(bits << (6 - available)) & 63];
93
- while (result.size() % 4) result += '=';
94
128
  return result;
95
129
  }
96
130
 
131
+ inline std::string encode(const std::vector<std::int16_t>& pcm) {
132
+ return encode(pcm.data(), pcm.size());
133
+ }
134
+
97
135
  inline std::vector<std::int16_t> decode(const std::string& encoded) {
98
136
  if (encoded.size() % 4 || encoded.size() > 1024 * 1024)
99
137
  throw std::invalid_argument("Invalid PCM base64 length");
100
- std::vector<std::int16_t> result;
101
- result.reserve(encoded.size() / 4 * 3 / 2);
102
- std::uint32_t bits = 0;
103
- int available = 0, low = -1, padding = 0;
104
- for (unsigned char c : encoded) {
105
- if (c == '=') { if (++padding > 2) throw std::invalid_argument("Invalid base64 padding"); continue; }
106
- const int value = c >= 'A' && c <= 'Z' ? c - 'A' : c >= 'a' && c <= 'z' ? c - 'a' + 26 :
107
- c >= '0' && c <= '9' ? c - '0' + 52 : c == '+' ? 62 : c == '/' ? 63 : -1;
108
- if (value < 0 || padding) throw std::invalid_argument("Invalid PCM base64");
109
- bits = (bits << 6) | value;
110
- available += 6;
111
- if (available >= 8) {
112
- available -= 8;
113
- const int byte = (bits >> available) & 255;
114
- if (low < 0) low = byte;
115
- else { result.push_back(static_cast<std::int16_t>(low | (byte << 8))); low = -1; }
116
- }
138
+ if (encoded.empty()) return {};
139
+ static constexpr auto values = [] {
140
+ std::array<std::int8_t, 256> table{};
141
+ table.fill(-1);
142
+ constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
143
+ for (int index = 0; index < 64; ++index) table[static_cast<unsigned char>(alphabet[index])] = index;
144
+ return table;
145
+ }();
146
+ const size_t padding = (encoded.back() == '=') + (encoded[encoded.size() - 2] == '=');
147
+ const size_t bytes = encoded.size() / 4 * 3 - padding;
148
+ if (bytes % 2) throw std::invalid_argument("Incomplete PCM sample");
149
+ std::vector<std::int16_t> result(bytes / 2);
150
+ size_t output = 0;
151
+ int low = -1;
152
+ const auto write = [&](unsigned byte) {
153
+ if (low < 0) low = byte;
154
+ else { result[output++] = static_cast<std::int16_t>(low | (byte << 8)); low = -1; }
155
+ };
156
+ for (size_t input = 0; input < encoded.size(); input += 4) {
157
+ const bool last = input + 4 == encoded.size();
158
+ const auto first = values[static_cast<unsigned char>(encoded[input])];
159
+ const auto second = values[static_cast<unsigned char>(encoded[input + 1])];
160
+ const auto third = last && padding == 2 ? 0 : values[static_cast<unsigned char>(encoded[input + 2])];
161
+ const auto fourth = last && padding ? 0 : values[static_cast<unsigned char>(encoded[input + 3])];
162
+ if (first < 0 || second < 0 || third < 0 || fourth < 0 ||
163
+ (last && padding == 2 && (second & 15)) ||
164
+ (last && padding == 1 && (third & 3)))
165
+ throw std::invalid_argument("Invalid PCM base64");
166
+ write((first << 2) | (second >> 4));
167
+ if (!last || padding < 2) write(((second & 15) << 4) | (third >> 2));
168
+ if (!last || !padding) write(((third & 3) << 6) | fourth);
117
169
  }
118
- if (low >= 0 || available != padding * 2 || (available && (bits & ((1u << available) - 1))))
119
- throw std::invalid_argument("Incomplete PCM sample or invalid base64 padding");
120
170
  return result;
121
171
  }
122
172
  } // namespace gea::host::pcm
@@ -2,7 +2,11 @@
2
2
  #pragma once
3
3
  #include "host/h264_layout.h"
4
4
  #include "host/media.h"
5
+ #include "host/video_frame_pool.h"
6
+ #include "host/video_color.h"
7
+ #include "pixel.h"
5
8
  #include "esp_h264_dec_sw.h"
9
+ #include "esp_timer.h"
6
10
  #include <memory>
7
11
  #include <limits>
8
12
 
@@ -16,6 +20,10 @@ class Decoder {
16
20
  Decoder& operator=(const Decoder&) = delete;
17
21
  ~Decoder() { reset(); }
18
22
 
23
+ int64_t lastDecodeUs() const { return decodeUs_; }
24
+ int64_t lastConvertUs() const { return convertUs_; }
25
+ bool simdAligned() const { return simdAligned_; }
26
+
19
27
  void reset() {
20
28
  if (decoder_) { esp_h264_dec_close(decoder_); esp_h264_dec_del(decoder_); }
21
29
  decoder_ = nullptr;
@@ -23,7 +31,8 @@ class Decoder {
23
31
  metadata_ = {};
24
32
  }
25
33
 
26
- std::unique_ptr<media::VideoFrame> decode(const uint8_t* bytes, size_t length, uint32_t timestamp) {
34
+ std::shared_ptr<media::VideoFrame> decode(const uint8_t* bytes, size_t length, uint32_t timestamp) {
35
+ decodeUs_ = convertUs_ = 0;
27
36
  if (!length || length > std::numeric_limits<uint32_t>::max() ||
28
37
  !inspectAccessUnit(bytes, length, metadata_) || !open()) {
29
38
  reset(); return nullptr;
@@ -31,11 +40,13 @@ class Decoder {
31
40
  esp_h264_dec_in_frame_t input{};
32
41
  input.raw_data.buffer = const_cast<uint8_t*>(bytes);
33
42
  input.raw_data.len = static_cast<uint32_t>(length);
34
- std::unique_ptr<media::VideoFrame> latest;
43
+ std::shared_ptr<media::VideoFrame> latest;
35
44
  while (input.raw_data.len) {
36
45
  input.consume = 0;
37
46
  esp_h264_dec_out_frame_t decoded{};
47
+ const auto decodeStarted = esp_timer_get_time();
38
48
  const auto rc = esp_h264_dec_process(decoder_, &input, &decoded);
49
+ decodeUs_ += esp_timer_get_time() - decodeStarted;
39
50
  if (rc != ESP_H264_ERR_OK || !input.consume || input.consume > input.raw_data.len) {
40
51
  reset(); return nullptr;
41
52
  }
@@ -46,12 +57,30 @@ class Decoder {
46
57
  resolution.width != metadata_.width || resolution.height != metadata_.height || decoded.out_size != expected) {
47
58
  reset(); return nullptr;
48
59
  }
49
- latest = std::make_unique<media::VideoFrame>();
50
- latest->width = metadata_.visibleWidth;
51
- latest->height = metadata_.visibleHeight;
52
- latest->timestampMs = timestamp;
53
- latest->rgb565.resize(size_t(latest->width) * latest->height);
54
- convertI420(decoded.outbuf, metadata_, latest->rgb565.data());
60
+ latest = frames_.acquire(metadata_.visibleWidth, metadata_.visibleHeight);
61
+ if (latest) {
62
+ const auto convertStarted = esp_timer_get_time();
63
+ simdAligned_ = !(uintptr_t(decoded.outbuf) & 7) &&
64
+ !(uintptr_t(latest->rgb565.data()) & 7) && !(metadata_.width & 7) &&
65
+ !(metadata_.visibleWidth & 3) && !metadata_.top && !metadata_.left &&
66
+ !metadata_.fullRange && !metadata_.bt709;
67
+ latest->timestampMs = timestamp;
68
+ latest->panelEndian = bool(GEA_EMBEDDED_PIXEL_PANEL_ENDIAN);
69
+ if (!metadata_.fullRange && !metadata_.bt709) {
70
+ // The server emits limited-range BT.601. Reuse the S3 PIE kernel
71
+ // directly into the pooled panel buffer, without scalar conversion.
72
+ const auto* u = decoded.outbuf + metadata_.width * metadata_.height;
73
+ const auto* v = u + metadata_.width * metadata_.height / 4;
74
+ media::i420ToRgb565(decoded.outbuf + metadata_.top * metadata_.width + metadata_.left,
75
+ metadata_.width, u + metadata_.top / 2 * (metadata_.width / 2) + metadata_.left / 2,
76
+ metadata_.width / 2, v + metadata_.top / 2 * (metadata_.width / 2) + metadata_.left / 2,
77
+ metadata_.width / 2, latest->width, latest->height, latest->rgb565.data(), latest->panelEndian);
78
+ } else {
79
+ convertI420(decoded.outbuf, metadata_, latest->rgb565.data());
80
+ if (latest->panelEndian) media::rgb565SwapBytes(latest->rgb565.data(), latest->rgb565.size());
81
+ }
82
+ convertUs_ += esp_timer_get_time() - convertStarted;
83
+ }
55
84
  }
56
85
  input.raw_data.buffer += input.consume;
57
86
  input.raw_data.len -= input.consume;
@@ -72,5 +101,8 @@ class Decoder {
72
101
  esp_h264_dec_handle_t decoder_ = nullptr;
73
102
  esp_h264_dec_param_sw_handle_t parameters_ = nullptr;
74
103
  Metadata metadata_;
104
+ media::VideoFramePool frames_;
105
+ int64_t decodeUs_ = 0, convertUs_ = 0;
106
+ bool simdAligned_ = false;
75
107
  };
76
108
  } // namespace gea::host::rtc::h264
@@ -4,6 +4,7 @@
4
4
  #include <algorithm>
5
5
  #include <array>
6
6
  #include <charconv>
7
+ #include <cstdint>
7
8
  #include <optional>
8
9
  #include <string>
9
10
  #include <string_view>
@@ -6,6 +6,7 @@
6
6
  #include <optional>
7
7
  #include <span>
8
8
  #include <cstring>
9
+ #include <vector>
9
10
  #include "host/video_pixels.h"
10
11
 
11
12
  namespace gea::host::rtc::rtp {
@@ -6,6 +6,9 @@
6
6
 
7
7
  namespace gea::embedded::ui { class NodeHandle; }
8
8
  namespace gea::host {
9
+ struct VideoPresentationStats {
10
+ uint32_t decoded = 0, selected = 0, maxGapMs = 0;
11
+ };
9
12
  class HTMLVideoElement {
10
13
  public:
11
14
  HTMLVideoElement() = default;
@@ -30,6 +33,7 @@ class HTMLVideoElement {
30
33
  bool operator==(const HTMLVideoElement& other) const { return state_ == other.state_; }
31
34
  explicit operator bool() const { return static_cast<bool>(state_); }
32
35
  static void presentFrames();
36
+ static VideoPresentationStats presentationStats();
33
37
  private:
34
38
  void setOnPlayingHandler(std::function<void()> callback) const;
35
39
  struct State;
@@ -17,6 +17,16 @@
17
17
  namespace gea::host::media {
18
18
  class VideoFramePool;
19
19
 
20
+ // Allocation failure is an exception where the target has them. An exception-free
21
+ // target (the Pebble watch builds with -fno-exceptions) cannot throw, so it aborts.
22
+ [[noreturn]] inline void videoAllocationFailed() {
23
+ #if defined(__cpp_exceptions) || defined(__EXCEPTIONS)
24
+ throw std::bad_alloc();
25
+ #else
26
+ std::abort();
27
+ #endif
28
+ }
29
+
20
30
  // Packet containers retain the standard allocator contract. Large decoded
21
31
  // pictures below have an explicit non-throwing allocation boundary instead.
22
32
  struct VideoOverwriteTag {};
@@ -36,7 +46,7 @@ struct VideoAllocator {
36
46
  ::new (static_cast<void*>(pointer)) U(std::forward<Args>(args)...);
37
47
  }
38
48
  T* allocate(std::size_t count) {
39
- if (count > std::numeric_limits<std::size_t>::max() / sizeof(T)) throw std::bad_alloc();
49
+ if (count > std::numeric_limits<std::size_t>::max() / sizeof(T)) videoAllocationFailed();
40
50
  #ifdef ESP_PLATFORM
41
51
  constexpr std::size_t alignment = alignof(T) > 16 ? alignof(T) : 16;
42
52
  void* result = heap_caps_aligned_alloc(alignment, count * sizeof(T),
@@ -44,7 +54,7 @@ struct VideoAllocator {
44
54
  #else
45
55
  void* result = std::malloc(count * sizeof(T));
46
56
  #endif
47
- if (!result && count) throw std::bad_alloc();
57
+ if (!result && count) videoAllocationFailed();
48
58
  return static_cast<T*>(result);
49
59
  }
50
60
  void deallocate(T* pointer, std::size_t) noexcept {
@@ -65,7 +75,7 @@ class VideoPixels {
65
75
  VideoPixels() = default;
66
76
  explicit VideoPixels(std::size_t count) { resize(count); }
67
77
  VideoPixels(const VideoPixels& other) {
68
- if (!tryResizeForOverwrite(other.size_)) throw std::bad_alloc();
78
+ if (!tryResizeForOverwrite(other.size_)) videoAllocationFailed();
69
79
  if (size_) std::memcpy(pixels_, other.pixels_, size_ * sizeof(*pixels_));
70
80
  }
71
81
  VideoPixels(VideoPixels&& other) noexcept { swap(other); }
@@ -97,7 +107,7 @@ class VideoPixels {
97
107
  const auto previousSize = size_;
98
108
  if (count > capacity_) {
99
109
  auto* replacement = allocate(count);
100
- if (!replacement) throw std::bad_alloc();
110
+ if (!replacement) videoAllocationFailed();
101
111
  if (previousSize) std::memcpy(replacement, pixels_, previousSize * sizeof(*pixels_));
102
112
  releaseAllocation();
103
113
  pixels_ = replacement;
@@ -108,7 +118,7 @@ class VideoPixels {
108
118
  }
109
119
 
110
120
  void assign(std::size_t count, std::uint16_t value) {
111
- if (!tryResizeForOverwrite(count)) throw std::bad_alloc();
121
+ if (!tryResizeForOverwrite(count)) videoAllocationFailed();
112
122
  if (count) std::fill_n(pixels_, count, value);
113
123
  }
114
124
  void pop_back() { if (size_) --size_; }
@@ -154,12 +164,25 @@ class VideoPixels {
154
164
  #else
155
165
  // Round up without overflowing: aligned_alloc requires a multiple of 16.
156
166
  if (bytes > std::numeric_limits<std::size_t>::max() - 15) return nullptr;
157
- return static_cast<std::uint16_t*>(std::aligned_alloc(16, (bytes + 15) & ~std::size_t(15)));
167
+ #if defined(__ANDROID__)
168
+ // Bionic declares aligned_alloc only from API 28; posix_memalign exists at every level.
169
+ void* result = nullptr;
170
+ if (posix_memalign(&result, 16, (bytes + 15) & ~std::size_t(15)) != 0) return nullptr;
171
+ return static_cast<std::uint16_t*>(result);
172
+ #elif defined(_WIN32)
173
+ // The MSVC CRT has no aligned_alloc: its aligned blocks come from
174
+ // _aligned_malloc and must go back through _aligned_free (see release).
175
+ return static_cast<std::uint16_t*>(_aligned_malloc((bytes + 15) & ~std::size_t(15), 16));
176
+ #else
177
+ return static_cast<std::uint16_t*>(::aligned_alloc(16, (bytes + 15) & ~std::size_t(15)));
178
+ #endif
158
179
  #endif
159
180
  }
160
181
  static void release(std::uint16_t* pointer) noexcept {
161
182
  #ifdef ESP_PLATFORM
162
183
  heap_caps_free(pointer);
184
+ #elif defined(_WIN32)
185
+ _aligned_free(pointer);
163
186
  #else
164
187
  std::free(pointer);
165
188
  #endif
@@ -172,7 +195,7 @@ class VideoPixels {
172
195
 
173
196
  inline VideoPixels videoPixelsForOverwrite(std::size_t count) {
174
197
  VideoPixels pixels;
175
- if (!pixels.tryResizeForOverwrite(count)) throw std::bad_alloc();
198
+ if (!pixels.tryResizeForOverwrite(count)) videoAllocationFailed();
176
199
  return pixels;
177
200
  }
178
201
  } // namespace gea::host::media
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/host",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "GeaStack host bindings and platform service sources.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {