@geastack/host 0.1.11 → 0.1.13

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
  }
@@ -94,49 +108,91 @@ struct MjpegStream::State {
94
108
  config.output_type = GEA_EMBEDDED_PIXEL_PANEL_ENDIAN ?
95
109
  JPEG_PIXEL_FORMAT_RGB565_BE : JPEG_PIXEL_FORMAT_RGB565_LE;
96
110
  jpeg_dec_handle_t decoder = nullptr;
97
- if (jpeg_dec_open(&config, &decoder) != JPEG_ERR_OK)
98
- throw std::runtime_error("MJPEG SIMD decoder allocation failed");
99
111
  struct Cleanup {
100
- jpeg_dec_handle_t decoder;
101
- ~Cleanup() { jpeg_dec_close(decoder); }
112
+ jpeg_dec_handle_t& decoder;
113
+ ~Cleanup() { if (decoder) jpeg_dec_close(decoder); }
102
114
  } cleanup{decoder};
103
115
  media::VideoFramePool frames;
116
+ #ifdef GEA_HAS_MULTIPART_H264
117
+ rtc::h264::Decoder h264Decoder;
118
+ #endif
104
119
  const auto track = source.getVideoTracks().front().nativeHandle;
105
- unsigned decoded = 0;
106
- 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;
107
123
  while (running) {
108
124
  xSemaphoreTake(wake, pdMS_TO_TICKS(100));
109
125
  if (!running) break;
110
126
  std::optional<JpegPacket> packet;
111
- { 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
+ }
112
135
  if (!packet) continue;
113
136
  const auto started = esp_timer_get_time();
114
- jpeg_dec_io_t io{};
115
- io.inbuf = packet->bytes.data();
116
- io.inbuf_len = int(packet->bytes.size());
117
- jpeg_dec_header_info_t header{};
118
- if (jpeg_dec_parse_header(decoder, &io, &header) != JPEG_ERR_OK ||
119
- !header.width || !header.height || header.width > 512 || header.height > 512)
120
- throw std::runtime_error("MJPEG rejected JPEG dimensions/header");
121
- int outputBytes = 0;
122
- if (jpeg_dec_get_outbuf_len(decoder, &outputBytes) != JPEG_ERR_OK ||
123
- outputBytes != int(size_t(header.width) * header.height * sizeof(uint16_t)))
124
- throw std::runtime_error("MJPEG unexpected decoder output size");
125
- auto frame = frames.acquire(header.width, header.height);
126
- if (!frame) continue;
127
- io.outbuf = reinterpret_cast<uint8_t*>(frame->rgb565.data());
128
- if (jpeg_dec_process(decoder, &io) != JPEG_ERR_OK || io.out_size != outputBytes)
129
- throw std::runtime_error("MJPEG JPEG decode failed");
130
- frame->panelEndian = bool(GEA_EMBEDDED_PIXEL_PANEL_ENDIAN);
131
- frame->timestampMs = packet->timestampMs;
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
141
+ auto frame = std::move(packet->rawFrame);
142
+ if (frame) {
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
156
+ } else {
157
+ // RGB565 never instantiates a JPEG decoder or a second pixel buffer.
158
+ if (!decoder && jpeg_dec_open(&config, &decoder) != JPEG_ERR_OK)
159
+ throw std::runtime_error("MJPEG SIMD decoder allocation failed");
160
+ jpeg_dec_io_t io{};
161
+ io.inbuf = packet->bytes.data();
162
+ io.inbuf_len = int(packet->bytes.size());
163
+ jpeg_dec_header_info_t header{};
164
+ if (jpeg_dec_parse_header(decoder, &io, &header) != JPEG_ERR_OK ||
165
+ !header.width || !header.height || header.width > 512 || header.height > 512)
166
+ throw std::runtime_error("MJPEG rejected JPEG dimensions/header");
167
+ int outputBytes = 0;
168
+ if (jpeg_dec_get_outbuf_len(decoder, &outputBytes) != JPEG_ERR_OK ||
169
+ outputBytes != int(size_t(header.width) * header.height * sizeof(uint16_t)))
170
+ throw std::runtime_error("MJPEG unexpected decoder output size");
171
+ frame = frames.acquire(header.width, header.height);
172
+ if (!frame) continue;
173
+ io.outbuf = reinterpret_cast<uint8_t*>(frame->rgb565.data());
174
+ if (jpeg_dec_process(decoder, &io) != JPEG_ERR_OK || io.out_size != outputBytes)
175
+ throw std::runtime_error("MJPEG JPEG decode failed");
176
+ frame->panelEndian = bool(GEA_EMBEDDED_PIXEL_PANEL_ENDIAN);
177
+ frame->timestampMs = packet->timestampMs;
178
+ }
132
179
  if (!running) break;
133
180
  media::publish_video_frame(track, std::move(frame));
134
181
  ++decoded;
135
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
136
188
  const auto now = esp_timer_get_time();
137
189
  if (now - report >= 2000000) {
138
- ESP_LOGI("gea_mjpeg", "decoded=%u received=%u replaced=%u decode_us=%lld",
139
- decoded, received.load(), replaced.load(), (long long)(totalDecode / decoded));
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));
140
196
  report = now;
141
197
  }
142
198
  vTaskDelay(1); // Keep raster and CPU1 idle work progressing under sustained video.
@@ -174,8 +230,17 @@ MjpegStream::MjpegStream(const std::string& url) {
174
230
  for (const bool decode : {false, true}) {
175
231
  auto* owner = new std::shared_ptr<State>(state_);
176
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;
177
242
  if (xTaskCreatePinnedToCoreWithCaps(entry, decode ? "gea_mjpeg_dec" : "gea_mjpeg_rx",
178
- 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,
179
244
  MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS) {
180
245
  delete owner;
181
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});
@@ -83,10 +83,11 @@ void present(const T &value, Fn &&fn) {
83
83
  else if constexpr (requires { T::arity; value.index(); }) visit(value, [&](const auto &item) { present(item, fn); });
84
84
  else fn(value);
85
85
  }
86
- struct TransferList {
87
- std::vector<gea::Ref<gea::ArrayBuffer>> buffers;
86
+ template <typename Buffer> struct BufferTransferList {
87
+ std::vector<gea::Ref<Buffer>> buffers;
88
88
  std::vector<native::MessagePort> ports;
89
89
  };
90
+ using TransferList = BufferTransferList<gea::ArrayBuffer>;
90
91
  template <typename List>
91
92
  TransferList transfers(const List &input) {
92
93
  TransferList result;
@@ -111,8 +112,12 @@ TransferList transfers(const List &input) {
111
112
  else inspect(input);
112
113
  return result;
113
114
  }
114
- template <typename Data>
115
- native::MessageData cloneData(const Data &data, TransferList &list) {
115
+ // Keep buffer operations dependent on the instantiated bridge. Older compiler
116
+ // runtimes have no detachment API, but must still be able to include the host
117
+ // declarations in applications that do not use workers. An actual worker bridge
118
+ // still requires the real detachment API; no copy or no-op substitutes for it.
119
+ template <typename Data, typename Buffer>
120
+ native::MessageData cloneData(const Data &data, BufferTransferList<Buffer> &list) {
116
121
  native::MessageData result;
117
122
  visit(data, [&](const auto &value) {
118
123
  using T = std::decay_t<decltype(value)>;
@@ -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;
@@ -5,7 +5,8 @@
5
5
  #include <string>
6
6
 
7
7
  namespace gea::host::video {
8
- // Network and JPEG decoding stay in native workers. The UI receives only the
8
+ // Network and optional JPEG decoding stay in native workers. Multipart RGB565
9
+ // writes directly into pooled pixels. The UI receives only the
9
10
  // newest immutable RGB565 frame through the same media sink as WebRTC.
10
11
  class MjpegStream {
11
12
  public:
@@ -1,6 +1,8 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #pragma once
3
- #include "host/video_pixels.h"
3
+ #include "host/video_frame_pool.h"
4
+ #include "host/h264_layout.h"
5
+ #include <bit>
4
6
  #include <charconv>
5
7
  #include <functional>
6
8
  #include <span>
@@ -10,28 +12,71 @@
10
12
 
11
13
  namespace gea::host::video {
12
14
  using JpegBytes = std::vector<uint8_t, media::VideoAllocator<uint8_t>>;
13
- struct JpegPacket { JpegBytes bytes; uint32_t timestampMs = 0; };
15
+ struct JpegPacket {
16
+ JpegBytes bytes;
17
+ uint32_t timestampMs = 0;
18
+ bool h264 = false;
19
+ bool h264Keyframe = false;
20
+ bool resetDecoder = false;
21
+ // Raw transport writes directly into the final pooled pixel allocation.
22
+ std::shared_ptr<media::VideoFrame> rawFrame;
23
+ };
14
24
 
15
25
  // Length-delimited multipart parsing survives arbitrary TCP fragmentation.
16
26
  // Never search the JPEG body for boundaries or allocate from untrusted sizes.
17
27
  class MjpegParser {
18
28
  public:
19
29
  bool push(std::span<const uint8_t> bytes, const std::function<void(JpegPacket)>& emit) {
20
- for (const auto byte : bytes) {
30
+ while (!bytes.empty()) {
21
31
  if (remaining_) {
22
- packet_.bytes.push_back(byte);
23
- if (!--remaining_) {
24
- const auto& jpeg = packet_.bytes;
25
- if (jpeg.size() < 4 || jpeg[0] != 0xff || jpeg[1] != 0xd8 ||
26
- jpeg[jpeg.size() - 2] != 0xff || jpeg.back() != 0xd9) return false;
27
- emit(std::move(packet_));
32
+ const auto count = std::min(remaining_, bytes.size());
33
+ if (format_ == Format::Jpeg || format_ == Format::H264) {
34
+ packet_.bytes.insert(packet_.bytes.end(), bytes.begin(), bytes.begin() + count);
35
+ } else if (packet_.rawFrame) {
36
+ std::memcpy(reinterpret_cast<uint8_t*>(packet_.rawFrame->rgb565.data()) + length_ - remaining_,
37
+ bytes.data(), count);
38
+ }
39
+ bytes = bytes.subspan(count);
40
+ remaining_ -= count;
41
+ if (!remaining_) {
42
+ if (format_ == Format::Jpeg) {
43
+ const auto& jpeg = packet_.bytes;
44
+ if (jpeg.size() < 4 || jpeg[0] != 0xff || jpeg[1] != 0xd8 ||
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;
67
+ }
68
+ // Exhausted pool means a slow sink: consume/drop this whole picture,
69
+ // never overwrite a published buffer or grow a frame backlog.
70
+ if (format_ == Format::Jpeg || format_ == Format::H264 || packet_.rawFrame) emit(std::move(packet_));
28
71
  packet_ = {};
29
- length_ = 0;
30
- contentType_ = false;
72
+ length_ = width_ = height_ = 0;
73
+ format_ = Format::None;
31
74
  inHeaders_ = false;
32
75
  }
33
76
  continue;
34
77
  }
78
+ const auto byte = bytes.front();
79
+ bytes = bytes.subspan(1);
35
80
  if (line_.size() >= 1024 || ++headerBytes_ > 2048) return false;
36
81
  line_ += char(byte);
37
82
  if (byte != '\n') continue;
@@ -39,8 +84,20 @@ class MjpegParser {
39
84
  line_.resize(line_.size() - 2);
40
85
  if (line_.empty()) {
41
86
  if (inHeaders_) {
42
- if (!length_ || !contentType_) return false;
43
- packet_.bytes.reserve(length_);
87
+ if (!length_ || format_ == Format::None) 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;
91
+ packet_.bytes.reserve(length_);
92
+ } else {
93
+ if (!width_ || !height_ || length_ != size_t(width_) * height_ * 2) return false;
94
+ packet_.rawFrame = frames_.acquire(width_, height_);
95
+ if (packet_.rawFrame) {
96
+ packet_.rawFrame->timestampMs = packet_.timestampMs;
97
+ packet_.rawFrame->panelEndian = (format_ == Format::Rgb565Be) !=
98
+ (std::endian::native == std::endian::big);
99
+ }
100
+ }
44
101
  remaining_ = length_;
45
102
  headerBytes_ = 0;
46
103
  }
@@ -58,17 +115,25 @@ class MjpegParser {
58
115
  for (auto& c : name) if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
59
116
  auto value = std::string_view(line_).substr(colon + 1);
60
117
  while (!value.empty() && value.front() == ' ') value.remove_prefix(1);
61
- if (name == "content-length" || name == "x-timestamp-ms") {
118
+ if (name == "content-length" || name == "x-timestamp-ms" || name == "x-width" || name == "x-height") {
62
119
  uint32_t number = 0;
63
120
  const auto parsed = std::from_chars(value.data(), value.data() + value.size(), number);
64
121
  if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size()) return false;
65
122
  if (name == "content-length") {
66
- if (length_ || number < 4 || number > 65536) return false;
123
+ if (length_ || number < 4 || number > 512 * 512 * 2) return false;
67
124
  length_ = number;
125
+ } else if (name == "x-width" || name == "x-height") {
126
+ auto& dimension = name == "x-width" ? width_ : height_;
127
+ if (dimension || !number || number > 512) return false;
128
+ dimension = number;
68
129
  } else packet_.timestampMs = number;
69
130
  } else if (name == "content-type") {
70
- if (contentType_ || value != "image/jpeg") return false;
71
- contentType_ = true;
131
+ if (format_ != Format::None) return false;
132
+ if (value == "image/jpeg") format_ = Format::Jpeg;
133
+ else if (value == "video/h264") format_ = Format::H264;
134
+ else if (value == "application/x-rgb565-be") format_ = Format::Rgb565Be;
135
+ else if (value == "application/x-rgb565-le") format_ = Format::Rgb565Le;
136
+ else return false;
72
137
  }
73
138
  }
74
139
  line_.clear();
@@ -76,9 +141,15 @@ class MjpegParser {
76
141
  return true;
77
142
  }
78
143
  private:
144
+ enum class Format { None, Jpeg, H264, Rgb565Le, Rgb565Be };
79
145
  std::string line_, boundary_;
80
146
  JpegPacket packet_;
147
+ media::VideoFramePool frames_;
148
+ rtc::h264::Metadata h264Metadata_;
149
+ bool h264HasIdr_ = false;
150
+ uint32_t width_ = 0, height_ = 0;
81
151
  size_t remaining_ = 0, length_ = 0, headerBytes_ = 0;
82
- bool inHeaders_ = false, contentType_ = false;
152
+ bool inHeaders_ = false;
153
+ Format format_ = Format::None;
83
154
  };
84
155
  } // namespace gea::host::video
@@ -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,7 +164,14 @@ 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
+ #else
173
+ return static_cast<std::uint16_t*>(::aligned_alloc(16, (bytes + 15) & ~std::size_t(15)));
174
+ #endif
158
175
  #endif
159
176
  }
160
177
  static void release(std::uint16_t* pointer) noexcept {
@@ -172,7 +189,7 @@ class VideoPixels {
172
189
 
173
190
  inline VideoPixels videoPixelsForOverwrite(std::size_t count) {
174
191
  VideoPixels pixels;
175
- if (!pixels.tryResizeForOverwrite(count)) throw std::bad_alloc();
192
+ if (!pixels.tryResizeForOverwrite(count)) videoAllocationFailed();
176
193
  return pixels;
177
194
  }
178
195
  } // namespace gea::host::media
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/host",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "GeaStack host bindings and platform service sources.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {