From 4ce19d4bbab38a9abbd4310ff1b1152029a25b10 Mon Sep 17 00:00:00 2001 From: red77290 <23342613+red77290@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:00:23 +0000 Subject: [PATCH 1/3] fix(overlay,sync): enforce zero-retained FighterEngine lifecycle and <45ms esp32dev wheel sync --- CHANGELOG.md | 10 ++ docs/adr/0004-overlay-architecture.md | 13 +- src/api/WebUI.h | 2 +- src/core/BuildInfo.h | 6 +- src/core/Core0Lifecycle.h | 1 + src/core/DisplayRuntime.cpp | 31 ++-- src/core/DisplayRuntime.h | 1 + src/core/OverlayManager.h | 182 ++++++++++++++++--- src/core/RotationManager.cpp | 11 ++ src/engines/FighterEngine.cpp | 245 +++++++++++++++++++------- src/engines/FighterEngine.h | 31 +++- src/engines/FrontendSyncEngine.cpp | 43 +++-- src/engines/GifEngine.cpp | 16 +- test/native/test_native_core.cpp | 74 +++++++- test/test_core/test_core.cpp | 21 ++- 15 files changed, 540 insertions(+), 147 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83a85748..f9f27144 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to the **ArcadeMatrix (ESP32)** firmware, WebUI, and tooling The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed +- **Zero Retained `FighterEngine` Memory Between Fights, Across Rotation & During FrontendSync (`ESP32` & `ESP32-S3` — `ADR-0004`)**: + - **Eliminated `Clock + Fighters -> GIFs` Rotation Lock-Up & FrontendSync PNG Starvation on `esp32dev`**: `OverlayManager` now destroys `FighterEngine` completely via `Core0LifecycleDispatcher` after each fight (`0 B` retained during the inter-fight cooldown), across every rotation slot switch, deactivation, and FrontendSync preemption (`0 B` retained heap/PSRAM when inactive on both `esp32dev` and `ESP32-S3`), and `RotationManager::switchToModule()` / `evictAllActiveEnginesForMemory()` synchronously wait for Core 0 reclamation *before* evaluating HUB75 DMA depth or allocating `AnimatedGIF` (`22.6 KB` contiguous). + - **Strictly Rotation-Scoped Overlays, SMP-Safe Worker Handshake & Live Heap Admission Gate**: Removed `FighterEngine` activation from FrontendSync (`MQTT` / `MARQUEE`), moved `FighterEngine::loadRoster()` and post-fight `freeFighter()` off Core 1 onto Core 0 (`FgtLoader` / `Core0Lifecycle`), added a single-notify `signalLoaderStopOnce()` handshake, made `s_lastInstance` atomic, preserved `idle_fighter_interval` across ephemeral evictions in a rollover-safe `4 B` `.bss` timestamp, and gated `OverlayManager` instantiation on live free internal SRAM / PSRAM headroom. + - **Decoder-First `GifEngine::activate()` & Safe `8-bit` PNG Heap Floor**: `GifEngine::activate()` now allocates `AnimatedGIF` (`22.6 KB`) before spawning `gif_preload` (`4 KB` stack on `!hasPsram`), and `GifEngine::refineDynamicRequirements()` reserves a `~30 KB` total SRAM floor so `128x32` stays at `8-bit` with zero DMA teardowns while constrained geometries step down cleanly instead of starving `LitePngDecoder` or LwIP TCP RX. +- **Restored `< 45 ms` Live Intermediate Marquee Logos During `100 ms/step` Wheel Navigation on `esp32dev` (`FrontendSyncEngine`)**: + - Eliminated the redundant `35 ms` Tier-2 network settle delay on local-SD `!hasPsram` targets, tightened non-PSRAM Tier-1 burst coalescing to `15 ms`, reduced `SyncShowcaseWkr` wake polling to `2 ms` slices, and added stripped `title` stems to `binarySearchCatalogForGameJob()` (`O(log N)` exact lookup for Console titles). + ## [4.3.8] - 2026-12-01 ### Fixed diff --git a/docs/adr/0004-overlay-architecture.md b/docs/adr/0004-overlay-architecture.md index c4601041..16688b77 100644 --- a/docs/adr/0004-overlay-architecture.md +++ b/docs/adr/0004-overlay-architecture.md @@ -14,16 +14,15 @@ In early firmware iterations, the M.U.G.E.N `FighterEngine` was treated as a sel - `DisplayArbiter`: Selects the primary display source (e.g. `MQTT` > `VISUALIZER` > `MARQUEE` > `GIF` > `ROTATION`). - `EngineRegistry`: Contains only primary selectable display sources (`clock`, `date`, `weather`, `gifs`, `crypto`, `stock`, `audiovisualizer`, `decibelMeter`, `temp`, `message`, `google_cast`, `spotify`, `system_info`, `music_player`, `dashboard`, `gnews`, `marquee`, `mqttdata`). - `OverlayManager`: Manages transverse overlays (`FighterEngine`). -2. **User-Driven Per-Rotation Configuration:** - - Overlays are enabled per rotation slot via `"overlays": { "fighter": true }` (migrated from legacy `"fighter_overlay"`). - - Combined with global master switch: `isActive = global_enabled && rotation_entry.overlays.fighter`. - - Zero engine-specific exceptions: `GIF + Fighter` is completely supported. +2. **User-Driven Per-Rotation Configuration & Engine Gating:** + - Overlays are enabled per rotation slot via `"overlays": { "fighter": true }` (migrated from legacy `"fighter_overlay"`), combined with the global master switch: `isActive = global_enabled && rotation_entry.overlays.fighter`. + - Full-frame media engines (`GifEngine`, `allowsOverlay() == false`) and non-rotation priority sessions (`FrontendSync` `MQTT` / `MARQUEE` / `GIF` / `INGAME_SHOWCASE`, `VISUALIZER`, `WEBUI_SYNC`) suppress overlays completely. 3. **Additive Invariant:** - Overlays compose additively over existing framebuffers and must never call `matrix.clear()`. -4. **Heap Preservation on ESP32:** - - `OverlayManager` lazily instantiates `FighterEngine` on first demand and preserves the instance in heap across rotation cycles. +4. **Zero Retained Memory When Inactive or Between Fights (ESP32 & ESP32-S3):** + - `OverlayManager` instantiates `FighterEngine` strictly on demand after the active rotation engine is admitted, cooldown has elapsed, and heap headroom is verified, and destroys the entire `FighterEngine` instance via `Core0LifecycleDispatcher` after each fight (holding `0 B` during inter-fight cooldown), across every rotation slot switch, deactivation, or FrontendSync preemption — reclaiming 100% of worker stacks, rosters, and sprite buffers before the incoming engine evaluates pipeline depth or allocates decoders. ## Consequences - Clean, extensible layering architecture where overlays are independent of primary engine types. - Zero visual flicker through additive compositing. -- Zero heap fragmentation on ESP32. +- Zero residual overlay SRAM or PSRAM footprint during `GifEngine` playlists and `FrontendSync` marquee sessions. diff --git a/src/api/WebUI.h b/src/api/WebUI.h index 580cefc4..874c1978 100644 --- a/src/api/WebUI.h +++ b/src/api/WebUI.h @@ -3,7 +3,7 @@ const size_t WebUI_html_len = 147298; const char WebUI_html_etag[] = "57c256b84c692a71"; const uint8_t WebUI_html[] PROGMEM = { - 0x1f, 0x8b, 0x08, 0x00, 0x53, 0x1d, 0x0f, 0x6b, 0x02, 0xff, 0xec, 0xbd, + 0x1f, 0x8b, 0x08, 0x00, 0x36, 0x40, 0x10, 0x6b, 0x02, 0xff, 0xec, 0xbd, 0x6b, 0x77, 0x23, 0xdb, 0x75, 0x20, 0xf6, 0x5d, 0xbf, 0xe2, 0x08, 0x37, 0xba, 0x04, 0x2c, 0x00, 0x04, 0xc0, 0x47, 0xb3, 0xc1, 0x4b, 0xca, 0x6c, 0xb2, 0x5f, 0x56, 0xb3, 0x9b, 0x6e, 0xb2, 0x75, 0xad, 0xf1, 0x78, 0x41, diff --git a/src/core/BuildInfo.h b/src/core/BuildInfo.h index e311c305..114671df 100644 --- a/src/core/BuildInfo.h +++ b/src/core/BuildInfo.h @@ -1,10 +1,10 @@ #pragma once #ifndef FIRMWARE_VERSION -#define FIRMWARE_VERSION "4.3.7" +#define FIRMWARE_VERSION "4.3.8" #endif #ifndef BUILD_GIT_COMMIT -#define BUILD_GIT_COMMIT "0b702a1" +#define BUILD_GIT_COMMIT "db37089" #endif #ifndef BUILD_TIMESTAMP -#define BUILD_TIMESTAMP "2026-12-01 19:17:20 UTC" +#define BUILD_TIMESTAMP "2026-12-01 20:31:21 UTC" #endif diff --git a/src/core/Core0Lifecycle.h b/src/core/Core0Lifecycle.h index a52b59c0..106ad581 100644 --- a/src/core/Core0Lifecycle.h +++ b/src/core/Core0Lifecycle.h @@ -66,6 +66,7 @@ class Core0LifecycleDispatcher { size_t getQuarantineCount() const { return _quarantineCount; } bool hasPending() const { return _activeRetirements.load(std::memory_order_acquire) > 0 || !_retireQueue.isEmpty(); } + bool hasWorkerTask() const { return _lifecycleTaskHandle != nullptr; } private: Core0LifecycleDispatcher() = default; diff --git a/src/core/DisplayRuntime.cpp b/src/core/DisplayRuntime.cpp index a77811bf..ede23f94 100644 --- a/src/core/DisplayRuntime.cpp +++ b/src/core/DisplayRuntime.cpp @@ -176,6 +176,12 @@ void DisplayRuntime::purgeRotationPreemptionEntries() { } } +void DisplayRuntime::evictOverlaysForMemory() { + if (m_overlayManager) { + m_overlayManager->evictForMemory(); + } +} + void DisplayRuntime::transitionSession(const DisplayDecision& decision) { // PHASE 1: Resolve target engine IEngine* targetEngine = resolveEngine(decision.engineHandle, decision.sourceId); @@ -294,6 +300,7 @@ void DisplayRuntime::transitionSession(const DisplayDecision& decision) { // if (oldEngine && !sameEngine) { oldEngine->pause(); } + evictOverlaysForMemory(); if (m_rotationManager && m_rotationManager->getActiveEngineCount() > 0) { m_rotationManager->evictAllActiveEnginesForMemory(); } @@ -332,6 +339,9 @@ void DisplayRuntime::transitionSession(const DisplayDecision& decision) { // // CASE 4: REPLACE const bool isInternalRotationSwitch = (decision.sourceId == DisplaySourceId::ROTATION && m_session.sourceId == DisplaySourceId::ROTATION); + if (decision.sourceId != DisplaySourceId::ROTATION) { + evictOverlaysForMemory(); + } if (evictManagedRotation) { m_rotationManager->evictAllActiveEnginesForMemory(); oldEngine = nullptr; @@ -436,19 +446,18 @@ FrameRenderResult DisplayRuntime::render(const DisplayDecision& decision, AppEng result.nextDueInMs = activeEngine->nextFrameDueInMs(); } - // Render Overlays (Fighter etc.) if enabled by decision and active rotation slot - if (m_overlayManager && decision.allowsOverlay && (!activeEngine || activeEngine->allowsOverlay())) { - OverlayConfig activeOverlayConfig; - if (decision.sourceId == DisplaySourceId::ROTATION && m_rotationManager) { - activeOverlayConfig = m_rotationManager->getCurrentOverlays(); - } else if (decision.sourceId == DisplaySourceId::MQTT || decision.sourceId == DisplaySourceId::MARQUEE) { - activeOverlayConfig.fighter = FighterOverride::Enabled; - } - m_overlayManager->configure(activeOverlayConfig); + // Transverse overlays (FighterEngine) are strictly scoped to ROTATION slots whose primary + // engine permits overlays (never active on FrontendSync MQTT/MARQUEE/GIF or GifEngine playlists). + if (m_overlayManager && + decision.sourceId == DisplaySourceId::ROTATION && + m_rotationManager != nullptr && + decision.allowsOverlay && + (!activeEngine || activeEngine->allowsOverlay())) { + m_overlayManager->configure(m_rotationManager->getCurrentOverlays()); m_overlayManager->update(); m_overlayManager->render(); - // An active overlay draws over the engine's frame; a dirty-pixel engine must repaint under it. - if (m_overlayManager->isActive()) matrixEngine.markExternalDraw(); + // An active combat pass draws over the engine's frame; a dirty-pixel engine must repaint under it. + if (m_overlayManager->isRenderingCombat()) matrixEngine.markExternalDraw(); } else if (m_overlayManager) { m_overlayManager->deactivate(); } diff --git a/src/core/DisplayRuntime.h b/src/core/DisplayRuntime.h index 47daa3d7..5def1e4c 100644 --- a/src/core/DisplayRuntime.h +++ b/src/core/DisplayRuntime.h @@ -110,6 +110,7 @@ class DisplayRuntime { */ void purgeEngineReferences(IEngine* engine, const char* instanceId); void purgeRotationPreemptionEntries(); + void evictOverlaysForMemory(); /** * @brief Reset the Adafruit_GFX text state (font, size, wrap) shared through the panel object. diff --git a/src/core/OverlayManager.h b/src/core/OverlayManager.h index 780ebb81..fcdd897a 100644 --- a/src/core/OverlayManager.h +++ b/src/core/OverlayManager.h @@ -2,12 +2,18 @@ #include #include +#include +#if defined(ESP32) +#include +#include +#endif #include "../../include/core/EngineContract.h" #include "../hal/BuildCapabilities.h" #include "ConfigLoader.h" #include "Core0Lifecycle.h" #include "NetworkBudget.h" #include "../engines/FighterEngine.h" +#include "../engines/WebUiSyncEngine.h" #include "Logger.h" using ActiveFighterOverlay = FighterEngine; @@ -19,12 +25,15 @@ using ActiveFighterOverlay = FighterEngine; * CONTRACT: * - Overlay rendering MUST be additive onto existing framebuffers. * - Overlay rendering MUST NOT call matrix->clear() or replace the base display. - * - FighterEngine is lazily instantiated on first demand and preserved in heap to prevent fragmentation. + * - Zero retained memory when inactive or between fights: `FighterEngine` is instantiated on demand + * ONLY when rotation allows overlays, cooldown has elapsed, and sufficient heap headroom is available, + * and is completely destroyed via `Core0LifecycleDispatcher` after each fight, on every slot eviction, + * deactivation, or FrontendSync preemption. */ class OverlayManager : public IDisplayGeometryAware { public: OverlayManager() = default; - ~OverlayManager() { deactivate(); } + ~OverlayManager() { evictForMemory(); } void initialize(EngineContext* context, ConfigLoader* config) { _context = context; @@ -38,26 +47,41 @@ class OverlayManager : public IDisplayGeometryAware { } /** - * @brief Configures which overlays should be active for the current display pass. - * @param overlays Requested overlay switches from the current rotation slot (or empty when preempted). + * @brief Configures which overlays should be active for the current rotation pass. + * @param overlays Requested overlay switches from the current rotation slot. */ void configure(const OverlayConfig& overlays) { if (!_config) { - _fighterActive = false; + retireFighterOverlay(false); return; } // Global master switch + per-rotation entry tri-state switch (ADR-0004): - // PSRAM targets cache `/fighters_64` (or `/fighters_32`) in PSRAM; non-PSRAM targets (`esp32dev`) + // PSRAM targets cache `/fighters_64` (or `/fighters_32`) in PSRAM; non-PSRAM targets // stream scanline-cropped `/fighters_32` sprites on Core 0 with zero Core 1 SD I/O or heap churn. ConfigSnapshotGuard guard = _config->acquireSnapshot(); bool globalEnabled = guard->system.idle_fighter_enabled; bool shouldBeActive = globalEnabled && (overlays.fighter != FighterOverride::Disabled); + if (NetworkBudget::isOtaUpdateActive()) { + shouldBeActive = false; + } if (shouldBeActive) { + if (_fighterOverlay && _fighterOverlay->shouldRetireForCooldown()) { + retireFighterOverlay(false); + return; + } if (!_fighterOverlay) { - LOGI("OverlayManager", "Lazy-instantiating FighterEngine overlay..."); - _fighterOverlay = std::unique_ptr(new ActiveFighterOverlay()); + if (!canAdmitFighterOverlay(guard->system.idle_fighter_interval)) { + _fighterActive = false; + return; + } + LOGI("OverlayManager", "Instantiating ephemeral FighterEngine overlay..."); + _fighterOverlay = std::unique_ptr(new (std::nothrow) ActiveFighterOverlay()); + if (!_fighterOverlay) { + _fighterActive = false; + return; + } if (_context) { _fighterOverlay->initialize(_context, nullptr); } @@ -67,15 +91,7 @@ class OverlayManager : public IDisplayGeometryAware { _fighterActive = true; } } else { - if (_fighterActive && _fighterOverlay) { - _fighterOverlay->deactivate(); - _fighterActive = false; - } - if (!globalEnabled && _fighterOverlay) { - LOGI("OverlayManager", "Retiring FighterEngine overlay for Core 0 lifecycle destruction..."); - _fighterOverlay->setResourceState(EngineResourceState::CORE1_RELEASED); - Core0LifecycleDispatcher::instance().retire(std::move(_fighterOverlay)); - } + retireFighterOverlay(false); } } @@ -92,14 +108,14 @@ class OverlayManager : public IDisplayGeometryAware { } void deactivate() { - if (_fighterActive && _fighterOverlay) { - _fighterOverlay->deactivate(); - _fighterActive = false; - } - if (_fighterOverlay && (!_context || !_context->hasPsram()) && NetworkBudget::isOtaUpdateActive()) { - _fighterOverlay->setResourceState(EngineResourceState::CORE1_RELEASED); - Core0LifecycleDispatcher::instance().retire(std::move(_fighterOverlay)); - } + retireFighterOverlay(false); + } + + /** + * @brief Synchronously reclaims 100% of overlay memory before incoming engine pipeline evaluation or activation. + */ + void evictForMemory() { + retireFighterOverlay(true); } void onConfigChanged() { @@ -108,12 +124,126 @@ class OverlayManager : public IDisplayGeometryAware { } } - bool isActive() const { return _fighterActive && _fighterOverlay && _fighterOverlay->isActive(); } + bool isActive() const { return _fighterActive && _fighterOverlay != nullptr; } + bool isRenderingCombat() const { return _fighterActive && _fighterOverlay && _fighterOverlay->isActive(); } bool hasInstantiatedFighter() const { return _fighterOverlay != nullptr; } private: + bool canAdmitFighterOverlay(int configuredIntervalSec) { + if (!_context) { + return true; // Unit-test headless context + } +#if defined(ESP32) && !defined(UNIT_TEST) + if (NetworkBudget::isOtaUpdateActive() || + WebUiSyncEngine::isRequested() || + WebUiSyncEngine::isReadyForServing() || + Core0LifecycleDispatcher::instance().hasPending()) { + return false; + } + + const uint32_t now = millis(); + const uint32_t cooldownEnd = FighterEngine::peekNextFightCooldownEndMs(); + const uint32_t maxIntervalMs = static_cast(configuredIntervalSec > 1 ? configuredIntervalSec : 1) * 1000U; + if (cooldownEnd != 0U) { + const int32_t remMs = static_cast(cooldownEnd - now); + if (remMs > 0) { + if (static_cast(remMs) > maxIntervalMs) { + FighterEngine::clampNextFightCooldownEndMs(now + maxIntervalMs); + } + return false; // Zero RAM footprint while waiting between fights + } + } + + if (_nextAdmissionProbeMs != 0U && static_cast(now - _nextAdmissionProbeMs) < 0) { + return false; + } + + const size_t freeInternal = esp_get_free_internal_heap_size(); + const size_t largestInternal = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + bool fits = false; + if (_context->hasPsram()) { + const size_t freePsram = heap_caps_get_free_size(MALLOC_CAP_SPIRAM); + fits = (freeInternal >= 28672U) && (largestInternal >= 12288U) && (freePsram >= (1024U * 1024U)); + } else { + const DisplayGeometry geom = _context->getGeometry(); + const size_t w = geom.width > 0 ? static_cast(geom.width) : 128U; + const size_t h = geom.height > 0 ? static_cast(geom.height) : 32U; + const size_t planeBytes = w * h * sizeof(uint16_t); + fits = (freeInternal >= (planeBytes * 2U + 30720U)) && (largestInternal >= 12288U); + } + + if (!fits) { + _nextAdmissionProbeMs = (now + 1000U == 0U) ? 1U : (now + 1000U); + if (!_loggedAdmissionSkip) { + _loggedAdmissionSkip = true; + LOGW("OverlayManager", "Skipping FighterEngine overlay: insufficient memory headroom (freeInt=%u, maxBlk=%u)", + (unsigned)freeInternal, (unsigned)largestInternal); + } + return false; + } + _loggedAdmissionSkip = false; + _nextAdmissionProbeMs = 0U; +#else + (void)configuredIntervalSec; +#endif + return true; + } + + void retireFighterOverlay(bool waitForReclamation) { + _nextAdmissionProbeMs = 0U; + if (_fighterActive && _fighterOverlay) { + _fighterOverlay->deactivate(); + } + _fighterActive = false; + + bool queuedAny = false; + if (_fighterOverlay) { + _fighterOverlay->setResourceState(EngineResourceState::CORE1_RELEASED); + std::unique_ptr basePtr(std::move(_fighterOverlay)); + if (Core0LifecycleDispatcher::instance().retire(std::move(basePtr))) { + queuedAny = true; + } else if (!Core0LifecycleDispatcher::instance().hasWorkerTask()) { + Core0LifecycleDispatcher::instance().processRetirements(); + (void)Core0LifecycleDispatcher::instance().retire(std::move(basePtr)); + queuedAny = true; + } else if (waitForReclamation) { +#if defined(ESP32) && !defined(UNIT_TEST) + uint32_t drainStart = millis(); + while (Core0LifecycleDispatcher::instance().hasPending() && (millis() - drainStart) < 300U) { + esp_task_wdt_reset(); + vTaskDelay(pdMS_TO_TICKS(5)); + } +#endif + if (Core0LifecycleDispatcher::instance().retire(std::move(basePtr))) { + queuedAny = true; + } + } + } + + if (!Core0LifecycleDispatcher::instance().hasWorkerTask()) { + if (queuedAny || Core0LifecycleDispatcher::instance().hasPending()) { + Core0LifecycleDispatcher::instance().processRetirements(); + } + return; + } + +#if defined(ESP32) && !defined(UNIT_TEST) + if (waitForReclamation && (queuedAny || Core0LifecycleDispatcher::instance().hasPending())) { + const uint32_t waitStart = millis(); + while (Core0LifecycleDispatcher::instance().hasPending() && (millis() - waitStart) < 850U) { + esp_task_wdt_reset(); + vTaskDelay(pdMS_TO_TICKS(5)); + } + } +#else + (void)waitForReclamation; +#endif + } + EngineContext* _context = nullptr; ConfigLoader* _config = nullptr; std::unique_ptr _fighterOverlay; bool _fighterActive = false; + bool _loggedAdmissionSkip = false; + uint32_t _nextAdmissionProbeMs = 0U; }; diff --git a/src/core/RotationManager.cpp b/src/core/RotationManager.cpp index 731fa0ec..7eb11891 100644 --- a/src/core/RotationManager.cpp +++ b/src/core/RotationManager.cpp @@ -239,6 +239,7 @@ void RotationManager::evictAllActiveEnginesForMemory() { m_missingClears = 0; if (m_displayRuntime) { m_displayRuntime->purgeRotationPreemptionEntries(); + m_displayRuntime->evictOverlaysForMemory(); } #if defined(ESP32) && !defined(UNIT_TEST) if (retiredAny) { @@ -334,6 +335,9 @@ void RotationManager::switchToModule(int index) { LOGI("RotationManager", "switchToModule(index=%d), total rotation entries: %d", index, (int)guard->rotation.size()); if (guard->rotation.empty()) { LOGW("RotationManager", "switchToModule: rotation is empty!"); + if (m_displayRuntime) { + m_displayRuntime->evictOverlaysForMemory(); + } if (currentActiveInstanceId[0] != '\0') { IEngine* oldEngine = findActiveEngine(currentActiveInstanceId); if (oldEngine) { @@ -371,6 +375,13 @@ void RotationManager::switchToModule(int index) { const bool switchingInstance = (currentActiveInstanceId[0] == '\0') || (strcmp(currentActiveInstanceId, newInstanceId) != 0); + // Destroy any active transverse overlay (e.g. FighterEngine) FIRST across every slot switch + // so 100% of its SRAM/PSRAM (task stack, roster, sprite planes) is reclaimed BEFORE the incoming + // engine evaluates HUB75 DMA depth or allocates its decoders (e.g. 22.6 KB AnimatedGIF). + if (switchingInstance && m_displayRuntime) { + m_displayRuntime->evictOverlaysForMemory(); + } + // Deactivate (or retire on non-PSRAM if large stateless Showcase object) old engine if (currentActiveInstanceId[0] != '\0' && strcmp(currentActiveInstanceId, newInstanceId) != 0) { char outgoingId[32]{0}; diff --git a/src/engines/FighterEngine.cpp b/src/engines/FighterEngine.cpp index 7bfc2c4b..ab9d6b7b 100644 --- a/src/engines/FighterEngine.cpp +++ b/src/engines/FighterEngine.cpp @@ -27,19 +27,28 @@ FighterEngine::FighterEngine() : matrix(nullptr) { } EngineError FighterEngine::initialize(EngineContext* context, const EngineConfig* config) { + (void)config; matrix = context ? (context->getSurface() ? static_cast(context->getSurface()) : static_cast(context->getMatrix())) : nullptr; m_hasPsram = context ? context->hasPsram() : false; - s_lastInstance = this; - initialize(); + retryDelayEnd = s_nextFightCooldownEndMs.load(std::memory_order_acquire); + s_lastInstance.store(this, std::memory_order_release); + // Keep Core 1 100% free of SD I/O and roster heap allocations: `loadRoster()` runs on Core 0 inside `FgtLoader`. return EngineError::OK; } void FighterEngine::activate() { - startLoaderTaskIfNeeded(); - startFight(); + retryDelayEnd = s_nextFightCooldownEndMs.load(std::memory_order_acquire); + s_lastInstance.store(this, std::memory_order_release); +#if !defined(UNIT_TEST) + if (matrix != nullptr) { + startLoaderTaskIfNeeded(); + startFight(); + } +#endif } void FighterEngine::update(EngineContext* context) { + (void)context; loop(); } @@ -50,56 +59,85 @@ void FighterEngine::render(EngineContext* context) { draw(); } +void FighterEngine::signalLoaderStopOnce() { + if (!m_shutdownSignaled.exchange(true, std::memory_order_acq_rel)) { + m_taskShouldExit = true; + if (loaderTaskHandle) { + xTaskNotifyGive(loaderTaskHandle); + } + m_shutdownNotified.store(true, std::memory_order_release); + } else { + m_taskShouldExit = true; + } +} + void FighterEngine::deactivate() { // Non-blocking state-only transition on Core 1: zero allocation, zero mutex. - // Keep FgtLoader parked across rotation switches (preventing stack heap churn), - // while advancing m_fightEpoch to even so Core 0 immediately releases stream planes & SD files. + // Clear `s_lastInstance` before `OverlayManager` hands ownership to `Core0LifecycleDispatcher` + // so `/api/fighter/status` never dereferences a retiring instance. + FighterEngine* expected = this; + s_lastInstance.compare_exchange_strong(expected, nullptr, std::memory_order_acq_rel); active = false; endFightEpochOnCore1(); + signalLoaderStopOnce(); } void FighterEngine::onConfigChanged(const EngineConfig* engineConfig) { + (void)engineConfig; // Config now comes from global config.system } bool FighterEngine::shutdownForDestruction() { + FighterEngine* expected = this; + s_lastInstance.compare_exchange_strong(expected, nullptr, std::memory_order_acq_rel); active = false; endFightEpochOnCore1(); + signalLoaderStopOnce(); // 1. Core 0 cooperative worker task shutdown if (loaderTaskHandle) { - m_taskShouldExit = true; - xTaskNotifyGive(loaderTaskHandle); uint32_t start = millis(); - while (!m_loaderStopped.load(std::memory_order_acquire) && (millis() - start < 300)) { - vTaskDelay(pdMS_TO_TICKS(10)); + while (!m_loaderStopped.load(std::memory_order_acquire) && (millis() - start < 800U)) { +#if defined(ESP32) && !defined(UNIT_TEST) + esp_task_wdt_reset(); +#endif + vTaskDelay(pdMS_TO_TICKS(5)); } if (!m_loaderStopped.load(std::memory_order_acquire)) { - LOGE("FighterEngine", "CRITICAL: FgtLoader task failed to stop within 300ms!"); - m_lastNote = "CRITICAL: FgtLoader task failed to stop within 300ms!"; + LOGE("FighterEngine", "CRITICAL: FgtLoader task failed to stop within 800ms!"); + m_lastNote = "CRITICAL: FgtLoader task failed to stop within 800ms!"; return false; // Quarantined: do not delete object, no UAF } + vTaskDelay(1); + loaderTaskHandle = nullptr; } - // 2. Safe resource cleanup on Core 0 (closes SD file handles and frees frame buffers) - if (s_lastInstance == this) { - s_lastInstance = nullptr; - } + // 2. Safe 100% resource cleanup on Core 0 (closes SD file handles, frees stream planes, roster, and all fighter buffers) stop(); + freeFighter(nextP1); + freeFighter(nextP2); + if (m_roster) { + if (esp_ptr_external_ram(m_roster)) { + heap_caps_free(m_roster); + } else { + free(m_roster); + } + m_roster = nullptr; + } + numAvailableFighters = 0; return true; } FighterEngine::~FighterEngine() { active = false; endFightEpochOnCore1(); - if (s_lastInstance == this) { - s_lastInstance = nullptr; - } - if (loaderTaskHandle && !m_loaderStopped.load(std::memory_order_acquire)) { - m_taskShouldExit = true; - xTaskNotifyGive(loaderTaskHandle); + FighterEngine* expected = this; + s_lastInstance.compare_exchange_strong(expected, nullptr, std::memory_order_acq_rel); + signalLoaderStopOnce(); + if (loaderTaskHandle) { while (!m_loaderStopped.load(std::memory_order_acquire)) { - vTaskDelay(pdMS_TO_TICKS(10)); + vTaskDelay(pdMS_TO_TICKS(5)); } + vTaskDelay(1); loaderTaskHandle = nullptr; } releaseStreamResourcesOnCore0(); @@ -154,6 +192,7 @@ String FighterEngine::getFightersDir() { } void FighterEngine::loadRoster() { + if (m_taskShouldExit) return; if (m_roster) { if (esp_ptr_external_ram(m_roster)) heap_caps_free(m_roster); else free(m_roster); @@ -161,18 +200,21 @@ void FighterEngine::loadRoster() { } numAvailableFighters = 0; String indexPath = getFightersDir() + "/index.txt"; + if (m_taskShouldExit) return; - SdLockGuard guard(pdMS_TO_TICKS(3000)); + SdLockGuard guard(pdMS_TO_TICKS(1500)); if (!guard) { LOGW("FighterEngine", "Could not acquire sdMutex to load roster."); m_lastNote = "Could not acquire sdMutex to load roster."; return; } + if (m_taskShouldExit) return; FsFile f = sd.open(indexPath.c_str(), FILE_OPEN_READ); if (!f) { LOGW("FighterEngine", "No index.txt found or failed to open at %s!", indexPath.c_str()); m_lastNote = "No index.txt found at"; + m_rosterLoaded.store(true, std::memory_order_release); return; } @@ -181,6 +223,7 @@ void FighterEngine::loadRoster() { LOGW("FighterEngine", "Invalid index.txt size: %u", (unsigned)fileSize); m_lastNote = "Invalid index.txt size"; f.close(); + m_rosterLoaded.store(true, std::memory_order_release); return; } @@ -204,6 +247,12 @@ void FighterEngine::loadRoster() { f.close(); guard.unlock(); // SD access complete in ~15ms! + if (m_taskShouldExit) { + if (esp_ptr_external_ram(rawBuf)) heap_caps_free(rawBuf); + else free(rawBuf); + return; + } + if (bytesRead != fileSize) { LOGE("FighterEngine", "Short read on index.txt: %u of %u bytes.", (unsigned)bytesRead, (unsigned)fileSize); m_lastNote = "Short read on index.txt"; @@ -279,6 +328,7 @@ void FighterEngine::loadRoster() { numAvailableFighters = 0; } } + m_rosterLoaded.store(true, std::memory_order_release); LOGI("FighterEngine", "Loaded %d fighters (Fast PSRAM Roster: %u bytes %s)", numAvailableFighters, (unsigned)(numAvailableFighters * sizeof(FighterMeta)), @@ -541,22 +591,25 @@ void FighterEngine::freeFighter(FighterPlayer& p) { } void FighterEngine::startLoaderTaskIfNeeded() { - if (loaderTaskHandle) return; - if (numAvailableFighters < 2) return; + if (loaderTaskHandle || m_taskShouldExit) return; + if (m_rosterLoaded.load(std::memory_order_acquire) && numAvailableFighters < 2) return; - m_taskShouldExit = false; + m_shutdownSignaled.store(false, std::memory_order_release); + m_shutdownNotified.store(false, std::memory_order_release); m_loaderStopped.store(false, std::memory_order_release); const size_t stackSize = m_hasPsram ? 16384 : 6144; if (xTaskCreatePinnedToCore(loaderTaskFunc, "FgtLoader", stackSize, this, 1, &loaderTaskHandle, 0) != pdPASS) { LOGE("FighterEngine", "Failed to spawn preload worker task."); m_lastNote = "Failed to spawn preload worker task."; loaderTaskHandle = nullptr; + m_loaderStopped.store(true, std::memory_order_release); } } void FighterEngine::triggerBackgroundPreload() { - if (millis() < retryDelayEnd) return; - if (isNextReady.load(std::memory_order_acquire) || isPreloading || numAvailableFighters < 2) return; + if (m_taskShouldExit || (retryDelayEnd != 0U && static_cast(retryDelayEnd - millis()) > 0)) return; + if (isNextReady.load(std::memory_order_acquire) || isPreloading) return; + if (m_rosterLoaded.load(std::memory_order_acquire) && numAvailableFighters < 2) return; startLoaderTaskIfNeeded(); if (!loaderTaskHandle) return; // Worker failed to start; nothing to notify. @@ -861,7 +914,36 @@ void FighterEngine::loaderTaskFunc(void* param) { FighterEngine* self = (FighterEngine*)param; uint32_t lastComposedSeq = 0U; uint32_t lastComposedEpoch = 0U; + if (!self->m_taskShouldExit && !self->m_rosterLoaded.load(std::memory_order_acquire)) { + self->loadRoster(); + } + if (!self->m_taskShouldExit && + self->m_rosterLoaded.load(std::memory_order_acquire) && + self->numAvailableFighters < 2) { + self->isPreloading = false; + uint32_t nextTry = millis() + 30000U; + if (nextTry == 0U) nextTry = 1U; + s_nextFightCooldownEndMs.store(nextTry, std::memory_order_release); + self->m_readyForEphemeralRetire.store(true, std::memory_order_release); + } while (!self->m_taskShouldExit) { + if (!self->m_rosterLoaded.load(std::memory_order_acquire)) { + self->loadRoster(); + if (self->m_taskShouldExit) break; + if (self->m_rosterLoaded.load(std::memory_order_acquire) && self->numAvailableFighters < 2) { + self->isPreloading = false; + uint32_t nextTry = millis() + 30000U; + if (nextTry == 0U) nextTry = 1U; + s_nextFightCooldownEndMs.store(nextTry, std::memory_order_release); + self->m_readyForEphemeralRetire.store(true, std::memory_order_release); + } + } + if (self->isPreloading && !self->m_taskShouldExit && + self->numAvailableFighters >= 2 && + (!self->m_hasPsram ? ((self->m_fightEpoch.load(std::memory_order_acquire) & 1U) == 0U) : true)) { + self->runBackgroundPreload(); + if (self->m_taskShouldExit) break; + } const bool streamActive = !self->m_hasPsram && ((self->m_fightEpoch.load(std::memory_order_acquire) & 1U) != 0U); const TickType_t waitTicks = streamActive ? pdMS_TO_TICKS(15) : portMAX_DELAY; @@ -871,7 +953,8 @@ void FighterEngine::loaderTaskFunc(void* param) { if (!self->m_hasPsram) { if (NetworkBudget::isOtaUpdateActive()) { self->releaseStreamResourcesOnCore0(); - break; + self->m_readyForEphemeralRetire.store(true, std::memory_order_release); + continue; } const uint32_t ep = self->m_fightEpoch.load(std::memory_order_acquire); if ((ep & 1U) != 0U) { @@ -883,20 +966,24 @@ void FighterEngine::loaderTaskFunc(void* param) { } } - if (self->isPreloading) { + if (self->isPreloading && self->numAvailableFighters >= 2) { self->runBackgroundPreload(); } } + self->isPreloading = false; if (!self->m_hasPsram) { self->releaseStreamResourcesOnCore0(); } - self->loaderTaskHandle = nullptr; + while (!self->m_shutdownNotified.load(std::memory_order_acquire)) { + vTaskDelay(1); + } + // Last touch of `self`: once `m_loaderStopped` is released, Core 0 lifecycle may delete `self`. self->m_loaderStopped.store(true, std::memory_order_release); vTaskDelete(NULL); } void FighterEngine::runBackgroundPreload() { - if (m_taskShouldExit || millis() < retryDelayEnd) { + if (m_taskShouldExit || (retryDelayEnd != 0U && static_cast(retryDelayEnd - millis()) > 0)) { isPreloading = false; return; } @@ -943,7 +1030,9 @@ void FighterEngine::runBackgroundPreload() { return false; } bool res = loadFighterAnim(anim, path.c_str()); - vTaskDelay(pdMS_TO_TICKS(10)); // Yield SD bus and CPU to Core 1 rendering + if (!m_taskShouldExit) { + vTaskDelay(pdMS_TO_TICKS(10)); // Yield SD bus and CPU to Core 1 rendering + } return res; }; @@ -1076,8 +1165,20 @@ void FighterEngine::runBackgroundPreload() { } loadAnimThreadSafe(nextP2.animFall, dir + "/" + nextP2.name + "/fall.fgt"); + if (m_taskShouldExit) { + freeFighter(nextP1); + freeFighter(nextP2); + break; + } computeStandBounds(nextP1); - computeStandBounds(nextP2); + if (!m_taskShouldExit) { + computeStandBounds(nextP2); + } + if (m_taskShouldExit) { + freeFighter(nextP1); + freeFighter(nextP2); + break; + } isNextReady.store(true, std::memory_order_release); LOGI("FighterEngine", "Background preload completed on Core 0: %s (front:%d, back:%d) vs %s (front:%d, back:%d)", nextP1.name.c_str(), nextP1.frontExtent, nextP1.backExtent, @@ -1087,17 +1188,24 @@ void FighterEngine::runBackgroundPreload() { } if (!matchFoundAndLoaded) { - LOGW("FighterEngine", "Preload exhausted all 4 pairing attempts (missing animations on SD). Retrying in 10s..."); - m_lastNote = "Preload exhausted all 4 pairing attempts (missing animations on SD). Retrying in 10s..."; + if (!m_taskShouldExit) { + LOGW("FighterEngine", "Preload exhausted all 4 pairing attempts (missing animations on SD). Retrying in 10s..."); + m_lastNote = "Preload exhausted all 4 pairing attempts (missing animations on SD). Retrying in 10s..."; + uint32_t nextTry = millis() + 10000U; + if (nextTry == 0U) nextTry = 1U; + retryDelayEnd = nextTry; + s_nextFightCooldownEndMs.store(nextTry, std::memory_order_release); + m_readyForEphemeralRetire.store(true, std::memory_order_release); + } freeFighter(nextP1); freeFighter(nextP2); - retryDelayEnd = millis() + 10000; } isPreloading = false; } void FighterEngine::computeStandBounds(FighterPlayer& p) { + if (m_taskShouldExit) return; int h = p.height > 0 ? p.height : 32; p.frontExtent = max(6, (h * 35) / 100); p.backExtent = max(6, (h * 25) / 100); @@ -1129,16 +1237,16 @@ void FighterEngine::computeStandBounds(FighterPlayer& p) { #endif { String path = anim.filepath; - if (path.length() > 0) { - SdLockGuard guard(pdMS_TO_TICKS(1500)); - if (guard && sd.exists(path.c_str())) { + if (path.length() > 0 && !m_taskShouldExit) { + SdLockGuard guard(pdMS_TO_TICKS(500)); + if (guard && !m_taskShouldExit && sd.exists(path.c_str())) { FsFile f = sd.open(path.c_str(), FILE_OPEN_READ); if (f) { f.seek(anim.pixelsOffset); int minX = anim.width; int maxX = -1; uint8_t lineBuf[512]; - for (int y = 0; y < anim.height; y++) { + for (int y = 0; y < anim.height && !m_taskShouldExit; y++) { int toRead = min((int)sizeof(lineBuf), (int)(anim.width * 2)); int n = f.read(lineBuf, toRead); for (int x = 0; x < n / 2; x++) { @@ -1286,13 +1394,12 @@ void FighterEngine::onDisplayGeometryChanged(const DisplayGeometry& geometry) { } void FighterEngine::startFight() { - if (millis() < retryDelayEnd) return; - if (numAvailableFighters < 2) return; + if (m_taskShouldExit || m_readyForEphemeralRetire.load(std::memory_order_acquire)) return; + if (retryDelayEnd != 0U && static_cast(retryDelayEnd - millis()) > 0) return; + if (m_rosterLoaded.load(std::memory_order_acquire) && numAvailableFighters < 2) return; if (isNextReady.load(std::memory_order_acquire)) { endFightEpochOnCore1(); - freeFighter(p1); - freeFighter(p2); movePlayer(p1, nextP1); movePlayer(p2, nextP2); @@ -1377,7 +1484,28 @@ void FighterEngine::setPlayerState(FighterPlayer& p, FighterState newState) { } bool FighterEngine::loop() { - if (millis() < retryDelayEnd) return true; + if (m_readyForEphemeralRetire.load(std::memory_order_acquire)) return true; + const uint32_t nowEarly = millis(); + extern ConfigLoader config; + uint32_t speed = 100; + uint32_t intervalMs = 60000U; + { + ConfigSnapshotGuard guard = config.acquireSnapshot(); + uint32_t cfgSpeed = guard.get().system.idle_fighter_speed; + if (cfgSpeed >= 25 && cfgSpeed <= 200) speed = cfgSpeed; + int cfgIntervalSec = guard.get().system.idle_fighter_interval; + if (cfgIntervalSec < 1) cfgIntervalSec = 1; + intervalMs = static_cast(cfgIntervalSec) * 1000U; + } + if (retryDelayEnd != 0U) { + if (static_cast(retryDelayEnd - nowEarly) > static_cast(intervalMs)) { + uint32_t clamped = nowEarly + intervalMs; + if (clamped == 0U) clamped = 1U; + retryDelayEnd = clamped; + s_nextFightCooldownEndMs.store(clamped, std::memory_order_release); + } + if (static_cast(retryDelayEnd - nowEarly) > 0) return true; + } if (millis() < hitStopUntilMillis) return true; @@ -1387,13 +1515,6 @@ bool FighterEngine::loop() { } uint32_t now = millis(); - extern ConfigLoader config; - uint32_t speed = 100; - { - ConfigSnapshotGuard guard = config.acquireSnapshot(); - uint32_t cfgSpeed = guard.get().system.idle_fighter_speed; - if (cfgSpeed >= 25 && cfgSpeed <= 200) speed = cfgSpeed; - } // Update frames FgtAnimation* anim1 = nullptr; @@ -1574,12 +1695,11 @@ bool FighterEngine::loop() { if (fightEndTime > 0 && now - fightEndTime > 1200) { active = false; endFightEpochOnCore1(); - freeFighter(p1); - freeFighter(p2); - extern ConfigLoader config; - ConfigSnapshotGuard guard = config.acquireSnapshot(); - retryDelayEnd = now + (guard->system.idle_fighter_interval * 1000); - triggerBackgroundPreload(); + uint32_t nextEnd = now + intervalMs; + if (nextEnd == 0U) nextEnd = 1U; + retryDelayEnd = nextEnd; + s_nextFightCooldownEndMs.store(nextEnd, std::memory_order_release); + m_readyForEphemeralRetire.store(true, std::memory_order_release); return true; } @@ -1757,10 +1877,11 @@ void FighterEngine::draw() { } -FighterEngine* FighterEngine::s_lastInstance = nullptr; +std::atomic FighterEngine::s_lastInstance{nullptr}; +std::atomic FighterEngine::s_nextFightCooldownEndMs{0U}; String FighterEngine::debugStatusJson() { - FighterEngine* f = s_lastInstance; + FighterEngine* f = s_lastInstance.load(std::memory_order_acquire); String j = "{"; if (!f) { j += "\"instantiated\":false}"; return j; } uint32_t now = millis(); diff --git a/src/engines/FighterEngine.h b/src/engines/FighterEngine.h index 46f5c393..77ac09a8 100644 --- a/src/engines/FighterEngine.h +++ b/src/engines/FighterEngine.h @@ -143,8 +143,22 @@ class FighterEngine : public IEngine { */ bool isActive() const { return active; } + bool shouldRetireForCooldown() const { + return m_readyForEphemeralRetire.load(std::memory_order_acquire); + } + + static uint32_t peekNextFightCooldownEndMs() { + return s_nextFightCooldownEndMs.load(std::memory_order_acquire); + } + + static void clampNextFightCooldownEndMs(uint32_t clampedEndMs) { + const uint32_t safeEnd = (clampedEndMs == 0U) ? 1U : clampedEndMs; + s_nextFightCooldownEndMs.store(safeEnd, std::memory_order_release); + } + private: - static FighterEngine* s_lastInstance; ///< most recently initialised overlay, for debugStatusJson() + static std::atomic s_lastInstance; ///< active live overlay instance, cleared atomically before retirement + static std::atomic s_nextFightCooldownEndMs; ///< 4-byte .bss timestamp preserving idle_fighter_interval across ephemeral evictions const char* m_lastNote = nullptr; ///< last warning/error this engine logged (zero-allocation string literal) Adafruit_GFX* matrix; ///< Display surface/matrix instance @@ -155,20 +169,21 @@ class FighterEngine : public IEngine { // Background Preloader & Non-PSRAM Scanline Streamer (Core 0 FreeRTOS task). // - // The loader task is created ONCE and kept alive for the engine's whole - // lifetime (mirrors GoogleCastEngine's CastPoll / DashboardDataProvider's - // DashFetch: a single long-lived worker parked on a task notification, - // never torn down and recreated). On non-PSRAM targets (`esp32dev`), the same - // Core 0 worker also streams visible cropped `/fighters_32` scanlines into a - // compact double-buffered RGB565 overlay plane during active ~4s fights, - // keeping Core 1 100% free of SD I/O, mutexes, and heap allocations. + // FighterEngine is strictly ephemeral: OverlayManager destroys the entire instance + // (freeing 100% of task stack, roster, and sprite buffers on both ESP32 and ESP32-S3) + // after each fight (during cooldown), across every rotation switch, and on FrontendSync. FighterPlayer nextP1; FighterPlayer nextP2; std::atomic isNextReady{false}; + std::atomic m_rosterLoaded{false}; + std::atomic m_readyForEphemeralRetire{false}; + std::atomic m_shutdownSignaled{false}; + std::atomic m_shutdownNotified{false}; volatile bool isPreloading = false; volatile bool m_taskShouldExit = false; std::atomic m_loaderStopped{false}; TaskHandle_t loaderTaskHandle = nullptr; + void signalLoaderStopOnce(); struct StreamPlayerCmd { char filepath[64]; diff --git a/src/engines/FrontendSyncEngine.cpp b/src/engines/FrontendSyncEngine.cpp index 2531618b..34e0cccb 100644 --- a/src/engines/FrontendSyncEngine.cpp +++ b/src/engines/FrontendSyncEngine.cpp @@ -1690,9 +1690,13 @@ bool FrontendSyncEngine::loop() { pendingPayload.indexOf("\"status\":\"stopped\"") != -1 || pendingPayload.indexOf("\"status\": \"stopped\"") != -1); const unsigned long nowMs = millis(); - const unsigned long debounceMs = (!hasReceivedAnyEvent || isPlayingOrStopped) ? 0UL : 40UL; + const bool hasPsram = hardwareHAL.capabilities().hasPsram; + const unsigned long debounceMs = (!hasReceivedAnyEvent || isPlayingOrStopped) + ? 0UL + : (hasPsram ? 40UL : 15UL); + const unsigned long maxCoalesceMs = hasPsram ? 80UL : 35UL; if ((nowMs - pendingEventTime) >= debounceMs || - (nowMs - m_pendingBatchStartMs) >= 80UL) { + (nowMs - m_pendingBatchStartMs) >= maxCoalesceMs) { hasPendingEvent = false; uint32_t reqId = currentRequestId; handleGameEvent(pendingPayload, reqId); @@ -2855,7 +2859,7 @@ void FrontendSyncEngine::showcaseWorkerLoop() { } } - for (int slice = 0; slice < 4; ++slice) { + for (int slice = 0; slice < 20; ++slice) { if (m_workerStopRequested.load(std::memory_order_acquire)) { break; } @@ -2863,7 +2867,7 @@ void FrontendSyncEngine::showcaseWorkerLoop() { lastWorkerBusyMs = millis() == 0U ? 1U : millis(); break; } - vTaskDelay(pdMS_TO_TICKS(10)); + vTaskDelay(pdMS_TO_TICKS(2)); } } @@ -3125,11 +3129,9 @@ void FrontendSyncEngine::scheduleOrDispatchArtJob( bool immediate ) { const bool hasPsram = hardwareHAL.capabilities().hasPsram; - // Immediate dispatch on game launch ("playing"). - // During wheel browsing, wait 35 ms after the 40 ms Tier-1 debounce (75 ms total) on local-SD - // `esp32dev` (140 ms on HTTPS PSRAM boards) so 100 ms/step navigation renders live logos while - // turbo wheel spinning coalesces cleanly. - if (immediate) { + // Immediate dispatch on game launch ("playing") or on local-SD non-PSRAM boards (`esp32dev`, 0 HTTPS/TLS). + // On PSRAM boards, wait 140 ms during rapid wheel browsing before firing remote HTTPS GETs. + if (immediate || !hasPsram) { m_hasPendingNetArt = false; dispatchAsyncArtJob(primaryFolder, secondaryFolder, query, title, localStem, reqId, negHash, isSystem); return; @@ -3144,7 +3146,7 @@ void FrontendSyncEngine::scheduleOrDispatchArtJob( m_pendingNetArtJob.negHash = negHash; m_pendingNetArtJob.isSystem = isSystem; m_pendingNetArtJob.active = true; - m_pendingNetArtDueMs = millis() + (hasPsram ? 140U : 35U); + m_pendingNetArtDueMs = millis() + 140U; m_hasPendingNetArt = true; } @@ -4172,7 +4174,16 @@ bool FrontendSyncEngine::binarySearchCatalogForGameJob( #if defined(ESP32) && !defined(UNIT_TEST) if (!catalogPath || catalogPath[0] == '\0' || job.isSystem) return false; - const char* stems[3] = { + char cleanTitleStripped[128] = ""; + if (job.title[0] != '\0') { + engines::PixelcadeArtResolver::stripRomOrArtExtensionAndTags( + job.title, + cleanTitleStripped, + sizeof(cleanTitleStripped) + ); + } + + const char* stems[4] = { job.localStem[0] != '\0' ? job.localStem : nullptr, (cleanGameStripped && cleanGameStripped[0] != '\0' && strcmp(cleanGameStripped, job.localStem) != 0) ? cleanGameStripped @@ -4181,6 +4192,12 @@ bool FrontendSyncEngine::binarySearchCatalogForGameJob( strcmp(job.query, job.localStem) != 0 && (!cleanGameStripped || strcmp(job.query, cleanGameStripped) != 0)) ? job.query + : nullptr, + (cleanTitleStripped[0] != '\0' && + strcmp(cleanTitleStripped, job.localStem) != 0 && + (!cleanGameStripped || strcmp(cleanTitleStripped, cleanGameStripped) != 0) && + strcmp(cleanTitleStripped, job.query) != 0) + ? cleanTitleStripped : nullptr }; const char* exts[2] = { ".png", ".gif" }; @@ -4204,7 +4221,7 @@ bool FrontendSyncEngine::binarySearchCatalogForGameJob( } slice{reinterpret_cast(m_cachedCatalogPsram), static_cast(m_cachedCatalogLen)}; for (size_t ei = 0U; ei < 2U; ++ei) { - for (size_t si = 0U; si < 3U; ++si) { + for (size_t si = 0U; si < 4U; ++si) { const char* st = stems[si]; if (!st || st[0] == '\0') continue; char cand[160]; @@ -4249,7 +4266,7 @@ bool FrontendSyncEngine::binarySearchCatalogForGameJob( bool found = false; for (size_t ei = 0U; ei < 2U && !found; ++ei) { - for (size_t si = 0U; si < 3U && !found; ++si) { + for (size_t si = 0U; si < 4U && !found; ++si) { const char* st = stems[si]; if (!st || st[0] == '\0') continue; if (m_workerStopRequested.load(std::memory_order_acquire) || diff --git a/src/engines/GifEngine.cpp b/src/engines/GifEngine.cpp index 3d9dd127..0426be35 100644 --- a/src/engines/GifEngine.cpp +++ b/src/engines/GifEngine.cpp @@ -313,9 +313,11 @@ void GifEngine::activate() { instance = this; if (refreshSingleFileOnSurface()) return; - startPreloadTask(); + // Allocate the 22.6 KB contiguous `AnimatedGIF` decoder and any rotated canvas buffer FIRST + // so the `gif_preload` FreeRTOS task stack never fragments the largest free internal SRAM block. ensureGifDecoder(); ensureCanvasBuffer(); + startPreloadTask(); if (matrix) { allocateShadows(matrix->width() * matrix->height()); } @@ -658,11 +660,12 @@ void GifEngine::refineDynamicRequirements(EngineRequirements& reqs) const { // Single static PNG marquee (`playGif("*.png")` with `playlistMode == false`): // `LitePngDecoder` has already decoded the image into the surface canvas and freed // 100% of its working pages, and `AnimatedGIF` (~22.6 KB) is never allocated. - // Refining heap thresholds prevents pointless 8/6-bit <-> 4-bit HUB75 DMA teardowns - // on every game navigation step on non-PSRAM `esp32dev`. + // Reserve ~18 KB engine headroom (plus 12 KB OS floor = ~30 KB free SRAM) so `128x32` (~75 KB free) + // stays at 8-bit with zero DMA teardowns, while extreme low-RAM configurations step down cleanly + // so the next `LitePngDecoder` pass and LwIP TCP RX never starve. if (isPlaying && !playlistMode && isPng) { - reqs.minFreeInternalHeapBytes = 4096; - reqs.internalContiguousBytes = 4096; + reqs.minFreeInternalHeapBytes = 18432; + reqs.internalContiguousBytes = 10240; } } @@ -895,7 +898,8 @@ void GifEngine::startPreloadTask() { } m_stopPreload.store(false, std::memory_order_release); m_preloadExited.store(false, std::memory_order_release); - if (xTaskCreatePinnedToCore(preloadTaskEntry, "gif_preload", 8192, this, 1, &m_preloadTask, 0) != pdPASS) { + const uint32_t preloadStackBytes = m_hasPsram ? 8192U : 4096U; + if (xTaskCreatePinnedToCore(preloadTaskEntry, "gif_preload", preloadStackBytes, this, 1, &m_preloadTask, 0) != pdPASS) { m_preloadTask = nullptr; m_preloadExited.store(true, std::memory_order_release); LOGW("GifEngine", "Failed to start gif_preload task on Core 0"); diff --git a/test/native/test_native_core.cpp b/test/native/test_native_core.cpp index 81014942..154bdba7 100644 --- a/test/native/test_native_core.cpp +++ b/test/native/test_native_core.cpp @@ -5416,7 +5416,7 @@ void test_pixelcade_binary_search_sorted_catalog_and_esp32dev_sync_worker_handof // 2. Structural guards on FrontendSyncEngine.cpp for esp32dev zero-stall sync & CAS worker handoff const std::string syncCpp = readRepoFileForNativeTest("src/engines/FrontendSyncEngine.cpp"); - TEST_ASSERT_TRUE(syncCpp.find("if (immediate || !hasPsram)") == std::string::npos); + TEST_ASSERT_TRUE(syncCpp.find("if (immediate || !hasPsram)") != std::string::npos); TEST_ASSERT_TRUE(syncCpp.find("NON_PSRAM_WORKER_IDLE_MS = 15000U") != std::string::npos); TEST_ASSERT_TRUE(syncCpp.find("m_workerExited.compare_exchange_strong") != std::string::npos); TEST_ASSERT_TRUE(syncCpp.find("binarySearchCatalogForGameJob") != std::string::npos); @@ -5522,6 +5522,77 @@ void test_static_png_marquee_zero_teardown_and_zero_map_oom_on_esp32dev() { TEST_ASSERT_TRUE(dispCpp.find("targetEngine->refineDynamicRequirements(reqs)") != std::string::npos); } +void test_ephemeral_fighter_overlay_zero_retained_ram_and_fast_wheel_sync(void) { + // 1. Low-heap safety floor on static PNG marquees: healthy `128x32` (~75 KB free) stays at 8-bit, + // whereas a starved heap (22 KB free < 30 KB floor) steps down to 4-bit so LitePngDecoder + LwIP never fail! + EngineRequirements starvReqs; + starvReqs.minFreeInternalHeapBytes = 18432; + starvReqs.internalContiguousBytes = 10240; + const uint8_t steppedDepth = PipelineSelectionPolicy::resolveTargetDepth( + /*configuredDepth=*/0, + /*dynamicDepth=*/true, + /*totalWidth=*/128, + /*height=*/32, + /*hasPsram=*/false, + starvReqs, + /*currentDepth=*/8, + /*largestBlock=*/11000U, + /*freeInternal=*/22000U, + /*freeDma=*/18000U, + /*isDoubleBuffered=*/false, + /*hasCanvas=*/true + ); + TEST_ASSERT_EQUAL_UINT8(4U, steppedDepth); + + // 2. Structural & ordering invariants across OverlayManager, DisplayRuntime, RotationManager, FighterEngine, GifEngine & FrontendSyncEngine + const std::string overlayHdr = readRepoFileForNativeTest("src/core/OverlayManager.h"); + const std::string dispCpp = readRepoFileForNativeTest("src/core/DisplayRuntime.cpp"); + const std::string rotCpp = readRepoFileForNativeTest("src/core/RotationManager.cpp"); + const std::string fighterCpp = readRepoFileForNativeTest("src/engines/FighterEngine.cpp"); + const std::string gifCpp = readRepoFileForNativeTest("src/engines/GifEngine.cpp"); + const std::string syncCpp = readRepoFileForNativeTest("src/engines/FrontendSyncEngine.cpp"); + + // OverlayManager always retires FighterEngine when disabled/deactivated/evicted/between-fights (both PSRAM & non-PSRAM) and gates admission by heap + TEST_ASSERT_TRUE(overlayHdr.find("void evictForMemory()") != std::string::npos); + TEST_ASSERT_TRUE(overlayHdr.find("canAdmitFighterOverlay(") != std::string::npos); + TEST_ASSERT_TRUE(overlayHdr.find("shouldRetireForCooldown()") != std::string::npos); + TEST_ASSERT_TRUE(overlayHdr.find("retireFighterOverlay(true)") != std::string::npos); + TEST_ASSERT_TRUE(overlayHdr.find("if (!globalEnabled && _fighterOverlay)") == std::string::npos); + TEST_ASSERT_TRUE(fighterCpp.find("void FighterEngine::signalLoaderStopOnce()") != std::string::npos); + TEST_ASSERT_TRUE(fighterCpp.find("m_readyForEphemeralRetire.store(true") != std::string::npos); + + // DisplayRuntime never enables FighterEngine on FrontendSync (`MQTT` / `MARQUEE`) and evicts overlays before priority sessions + TEST_ASSERT_TRUE(dispCpp.find("decision.sourceId == DisplaySourceId::MQTT || decision.sourceId == DisplaySourceId::MARQUEE") == std::string::npos); + TEST_ASSERT_TRUE(dispCpp.find("decision.sourceId == DisplaySourceId::ROTATION") != std::string::npos); + TEST_ASSERT_TRUE(dispCpp.find("evictOverlaysForMemory();") != std::string::npos); + + // RotationManager::switchToModule() evicts overlays BEFORE `maybeReconfigurePipelineFor` and `newEngine->activate()` + const size_t evictPos = rotCpp.find("if (switchingInstance && m_displayRuntime)"); + const size_t getOrCreatePos = rotCpp.find("IEngine* newEngine = getOrCreateEngine(newInstanceId);", evictPos); + TEST_ASSERT_TRUE(evictPos != std::string::npos); + TEST_ASSERT_TRUE(getOrCreatePos != std::string::npos && evictPos < getOrCreatePos); + + // FighterEngine loads `index.txt` on Core 0 (`loaderTaskFunc`), not in `initialize(EngineContext*, ...)` on Core 1 + const size_t initCtxPos = fighterCpp.find("EngineError FighterEngine::initialize(EngineContext*"); + const size_t activatePos = fighterCpp.find("void FighterEngine::activate()", initCtxPos); + TEST_ASSERT_TRUE(initCtxPos != std::string::npos && activatePos != std::string::npos); + const std::string initBody = fighterCpp.substr(initCtxPos, activatePos - initCtxPos); + TEST_ASSERT_TRUE(initBody.find("initialize();") == std::string::npos); + TEST_ASSERT_TRUE(initBody.find("\n loadRoster();") == std::string::npos); + + // GifEngine::activate() allocates `ensureGifDecoder()` (22.6 KB contiguous) BEFORE `startPreloadTask()` + const size_t gifActPos = gifCpp.find("void GifEngine::activate()"); + const size_t gifDecPos = gifCpp.find("ensureGifDecoder();", gifActPos); + const size_t gifPrePos = gifCpp.find("startPreloadTask();", gifActPos); + TEST_ASSERT_TRUE(gifActPos != std::string::npos && gifDecPos != std::string::npos && gifPrePos != std::string::npos); + TEST_ASSERT_TRUE(gifDecPos < gifPrePos); + TEST_ASSERT_TRUE(gifCpp.find("const uint32_t preloadStackBytes = m_hasPsram ? 8192U : 4096U;") != std::string::npos); + + // FrontendSyncEngine dispatches `!hasPsram` local-SD jobs without Tier-2 delay and wakes worker within <= 2 ms + TEST_ASSERT_TRUE(syncCpp.find("if (immediate || !hasPsram)") != std::string::npos); + TEST_ASSERT_TRUE(syncCpp.find("vTaskDelay(pdMS_TO_TICKS(2));") != std::string::npos); +} + // ========================================================================= // Main Runner (Unity Execution) // ========================================================================= @@ -5638,6 +5709,7 @@ int main(int argc, char** argv) { RUN_TEST(test_esp32dev_dual_ota_4mb_partition_and_bluetooth_exclusion_guard); RUN_TEST(test_pixelcade_binary_search_sorted_catalog_and_esp32dev_sync_worker_handoff); RUN_TEST(test_static_png_marquee_zero_teardown_and_zero_map_oom_on_esp32dev); + RUN_TEST(test_ephemeral_fighter_overlay_zero_retained_ram_and_fast_wheel_sync); return UNITY_END(); } diff --git a/test/test_core/test_core.cpp b/test/test_core/test_core.cpp index db080991..50344690 100644 --- a/test/test_core/test_core.cpp +++ b/test/test_core/test_core.cpp @@ -885,7 +885,7 @@ void test_rotation_overlay_combinations(void) { } /** - * @brief Tests lazy allocation and heap preservation of overlay instances to prevent heap fragmentation. + * @brief Tests on-demand allocation and complete eviction of overlay instances when disabled (zero retained memory). */ void test_overlay_manager_lifecycle_and_heap_preservation(void) { ConfigLoader cfg; @@ -895,24 +895,24 @@ void test_overlay_manager_lifecycle_and_heap_preservation(void) { overlay.initialize(nullptr, &cfg); TEST_ASSERT_FALSE(overlay.hasInstantiatedFighter()); - // First time ON -> lazy allocation + // First time ON -> on-demand allocation overlay.configure(OverlayConfig{true}); TEST_ASSERT_TRUE(overlay.isActive()); TEST_ASSERT_TRUE(overlay.hasInstantiatedFighter()); - // Switch to OFF -> inactive but instance PRESERVED in heap (prevents fragmentation) + // Switch to OFF -> inactive and instance completely evicted from heap (zero retained RAM) overlay.configure(OverlayConfig{false}); TEST_ASSERT_FALSE(overlay.isActive()); - TEST_ASSERT_TRUE(overlay.hasInstantiatedFighter()); + TEST_ASSERT_FALSE(overlay.hasInstantiatedFighter()); - // Switch back to ON -> re-activates without re-allocating + // Switch back to ON -> cleanly re-instantiates on demand overlay.configure(OverlayConfig{true}); TEST_ASSERT_TRUE(overlay.isActive()); TEST_ASSERT_TRUE(overlay.hasInstantiatedFighter()); } /** - * @brief Tests overlay suppression when priority sources (Marquee / Alert) preempt baseline rotation. + * @brief Tests overlay eviction when priority sources (Marquee / Alert) preempt baseline rotation. */ void test_overlay_preemption_by_arbiter(void) { ConfigLoader cfg; @@ -924,14 +924,17 @@ void test_overlay_preemption_by_arbiter(void) { // 1. Rotation active with Fighter ON overlay.configure(OverlayConfig{true}); TEST_ASSERT_TRUE(overlay.isActive()); + TEST_ASSERT_TRUE(overlay.hasInstantiatedFighter()); - // 2. Preempted by priority source (Arbiter selects MARQUEE/MQTT -> passes empty OverlayConfig{}) - overlay.configure(OverlayConfig{}); + // 2. Preempted by priority source -> deactivate() evicts FighterEngine completely + overlay.deactivate(); TEST_ASSERT_FALSE(overlay.isActive()); + TEST_ASSERT_FALSE(overlay.hasInstantiatedFighter()); - // 3. Resumed back to Rotation with Fighter ON + // 3. Resumed back to Rotation with Fighter ON -> re-instantiates cleanly overlay.configure(OverlayConfig{true}); TEST_ASSERT_TRUE(overlay.isActive()); + TEST_ASSERT_TRUE(overlay.hasInstantiatedFighter()); } /** From 107736390fd90232e75985b9f11807b852ebbb3b Mon Sep 17 00:00:00 2001 From: red77290 <23342613+red77290@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:06:45 +0000 Subject: [PATCH 2/3] fix(overlay): guard TWDT reset by task registration status on ESP-IDF 4.4 --- src/api/WebUI.h | 2 +- src/core/BuildInfo.h | 6 +++--- src/core/OverlayManager.h | 8 ++++++-- src/engines/FighterEngine.cpp | 3 --- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/api/WebUI.h b/src/api/WebUI.h index 874c1978..f1604763 100644 --- a/src/api/WebUI.h +++ b/src/api/WebUI.h @@ -3,7 +3,7 @@ const size_t WebUI_html_len = 147298; const char WebUI_html_etag[] = "57c256b84c692a71"; const uint8_t WebUI_html[] PROGMEM = { - 0x1f, 0x8b, 0x08, 0x00, 0x36, 0x40, 0x10, 0x6b, 0x02, 0xff, 0xec, 0xbd, + 0x1f, 0x8b, 0x08, 0x00, 0xb9, 0x41, 0x10, 0x6b, 0x02, 0xff, 0xec, 0xbd, 0x6b, 0x77, 0x23, 0xdb, 0x75, 0x20, 0xf6, 0x5d, 0xbf, 0xe2, 0x08, 0x37, 0xba, 0x04, 0x2c, 0x00, 0x04, 0xc0, 0x47, 0xb3, 0xc1, 0x4b, 0xca, 0x6c, 0xb2, 0x5f, 0x56, 0xb3, 0x9b, 0x6e, 0xb2, 0x75, 0xad, 0xf1, 0x78, 0x41, diff --git a/src/core/BuildInfo.h b/src/core/BuildInfo.h index 114671df..013abbbf 100644 --- a/src/core/BuildInfo.h +++ b/src/core/BuildInfo.h @@ -1,10 +1,10 @@ #pragma once #ifndef FIRMWARE_VERSION -#define FIRMWARE_VERSION "4.3.8" +#define FIRMWARE_VERSION "4.3.9-beta1" #endif #ifndef BUILD_GIT_COMMIT -#define BUILD_GIT_COMMIT "db37089" +#define BUILD_GIT_COMMIT "4ce19d4" #endif #ifndef BUILD_TIMESTAMP -#define BUILD_TIMESTAMP "2026-12-01 20:31:21 UTC" +#define BUILD_TIMESTAMP "2026-12-02 16:00:23 UTC" #endif diff --git a/src/core/OverlayManager.h b/src/core/OverlayManager.h index fcdd897a..36b2bd9b 100644 --- a/src/core/OverlayManager.h +++ b/src/core/OverlayManager.h @@ -210,7 +210,9 @@ class OverlayManager : public IDisplayGeometryAware { #if defined(ESP32) && !defined(UNIT_TEST) uint32_t drainStart = millis(); while (Core0LifecycleDispatcher::instance().hasPending() && (millis() - drainStart) < 300U) { - esp_task_wdt_reset(); + if (esp_task_wdt_status(NULL) == ESP_OK) { + esp_task_wdt_reset(); + } vTaskDelay(pdMS_TO_TICKS(5)); } #endif @@ -231,7 +233,9 @@ class OverlayManager : public IDisplayGeometryAware { if (waitForReclamation && (queuedAny || Core0LifecycleDispatcher::instance().hasPending())) { const uint32_t waitStart = millis(); while (Core0LifecycleDispatcher::instance().hasPending() && (millis() - waitStart) < 850U) { - esp_task_wdt_reset(); + if (esp_task_wdt_status(NULL) == ESP_OK) { + esp_task_wdt_reset(); + } vTaskDelay(pdMS_TO_TICKS(5)); } } diff --git a/src/engines/FighterEngine.cpp b/src/engines/FighterEngine.cpp index ab9d6b7b..9e4b8c74 100644 --- a/src/engines/FighterEngine.cpp +++ b/src/engines/FighterEngine.cpp @@ -97,9 +97,6 @@ bool FighterEngine::shutdownForDestruction() { if (loaderTaskHandle) { uint32_t start = millis(); while (!m_loaderStopped.load(std::memory_order_acquire) && (millis() - start < 800U)) { -#if defined(ESP32) && !defined(UNIT_TEST) - esp_task_wdt_reset(); -#endif vTaskDelay(pdMS_TO_TICKS(5)); } if (!m_loaderStopped.load(std::memory_order_acquire)) { From 1335d8d044dbf0e8905e34cd4565a5b5d7642b67 Mon Sep 17 00:00:00 2001 From: red77290 <23342613+red77290@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:27:39 +0000 Subject: [PATCH 3/3] docs(release): prepare changelog and webinstaller feed for v4.3.9 --- CHANGELOG.md | 4 ++- src/api/WebUI.h | 2 +- src/core/BuildInfo.h | 6 ++-- webinstaller/changelog/posts.json | 49 ++++++++++++++++++++++++++++++- webinstaller/index.html | 48 +++++++++++++++++++++++++++++- 5 files changed, 102 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f9f27144..f852d5bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to the **ArcadeMatrix (ESP32)** firmware, WebUI, and tooling The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [4.3.9] - 2026-12-02 ### Fixed - **Zero Retained `FighterEngine` Memory Between Fights, Across Rotation & During FrontendSync (`ESP32` & `ESP32-S3` — `ADR-0004`)**: @@ -13,6 +13,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - **Decoder-First `GifEngine::activate()` & Safe `8-bit` PNG Heap Floor**: `GifEngine::activate()` now allocates `AnimatedGIF` (`22.6 KB`) before spawning `gif_preload` (`4 KB` stack on `!hasPsram`), and `GifEngine::refineDynamicRequirements()` reserves a `~30 KB` total SRAM floor so `128x32` stays at `8-bit` with zero DMA teardowns while constrained geometries step down cleanly instead of starving `LitePngDecoder` or LwIP TCP RX. - **Restored `< 45 ms` Live Intermediate Marquee Logos During `100 ms/step` Wheel Navigation on `esp32dev` (`FrontendSyncEngine`)**: - Eliminated the redundant `35 ms` Tier-2 network settle delay on local-SD `!hasPsram` targets, tightened non-PSRAM Tier-1 burst coalescing to `15 ms`, reduced `SyncShowcaseWkr` wake polling to `2 ms` slices, and added stripped `title` stems to `binarySearchCatalogForGameJob()` (`O(log N)` exact lookup for Console titles). +- **M.U.G.E.N Extractor Palette Fidelity & Non-Body Helper Filtering (`tools/mugen_extractor/mugen_extractor.py`)**: + - Decoded reversed Elecbyte `.act` palette tables (`255..0` index convention), chained `SFFv1` shared palettes across sprite groups so character colors never corrupt on secondary frames, and filtered detached helper/projectile sprites when computing character bounding boxes. ## [4.3.8] - 2026-12-01 diff --git a/src/api/WebUI.h b/src/api/WebUI.h index f1604763..efbc1d16 100644 --- a/src/api/WebUI.h +++ b/src/api/WebUI.h @@ -3,7 +3,7 @@ const size_t WebUI_html_len = 147298; const char WebUI_html_etag[] = "57c256b84c692a71"; const uint8_t WebUI_html[] PROGMEM = { - 0x1f, 0x8b, 0x08, 0x00, 0xb9, 0x41, 0x10, 0x6b, 0x02, 0xff, 0xec, 0xbd, + 0x1f, 0x8b, 0x08, 0x00, 0x9f, 0x54, 0x10, 0x6b, 0x02, 0xff, 0xec, 0xbd, 0x6b, 0x77, 0x23, 0xdb, 0x75, 0x20, 0xf6, 0x5d, 0xbf, 0xe2, 0x08, 0x37, 0xba, 0x04, 0x2c, 0x00, 0x04, 0xc0, 0x47, 0xb3, 0xc1, 0x4b, 0xca, 0x6c, 0xb2, 0x5f, 0x56, 0xb3, 0x9b, 0x6e, 0xb2, 0x75, 0xad, 0xf1, 0x78, 0x41, diff --git a/src/core/BuildInfo.h b/src/core/BuildInfo.h index 013abbbf..c2075c60 100644 --- a/src/core/BuildInfo.h +++ b/src/core/BuildInfo.h @@ -1,10 +1,10 @@ #pragma once #ifndef FIRMWARE_VERSION -#define FIRMWARE_VERSION "4.3.9-beta1" +#define FIRMWARE_VERSION "4.3.9-beta1-dev" #endif #ifndef BUILD_GIT_COMMIT -#define BUILD_GIT_COMMIT "4ce19d4" +#define BUILD_GIT_COMMIT "f965e94" #endif #ifndef BUILD_TIMESTAMP -#define BUILD_TIMESTAMP "2026-12-02 16:00:23 UTC" +#define BUILD_TIMESTAMP "2026-12-02 17:23:44 UTC" #endif diff --git a/webinstaller/changelog/posts.json b/webinstaller/changelog/posts.json index 966d03b8..de39598a 100644 --- a/webinstaller/changelog/posts.json +++ b/webinstaller/changelog/posts.json @@ -1,7 +1,54 @@ { "project": "esp32", - "latest_version": "v4.3.8", + "latest_version": "v4.3.9", "posts": [ + { + "version": "v4.3.9", + "date": "2026-12-02", + "channel": "stable", + "tags": ["FIX", "PERF"], + "media": "changelog/media/agenda-sync-preview.svg", + "release_url": "https://github.com/red77290/ArcadeMatrix/releases/tag/v4.3.9", + "title": { + "en": "Zero-Retained Fighter Overlay (ESP32 & ESP32-S3), Clock -> GIFs Fix & < 45 ms Console Wheel Sync", + "fr": "Overlay Fighters Zéro-RAM au Repos (ESP32 & ESP32-S3), Rotation Horloge -> GIFs & Synchro < 45 ms", + "es": "Overlay Fighters Cero-RAM en Reposo (ESP32 y ESP32-S3), Rotación Reloj -> GIFs y Sincro < 45 ms" + }, + "summary": { + "en": "Makes FighterEngine strictly ephemeral across both Classic ESP32 (esp32dev) and ESP32-S3 (0 bytes retained between fights, across rotation switches, and during Recalbox/Batocera sync), fixes Clock + Fighters -> GIFs rotation lock-ups and PNG marquee starvation on esp32dev, restores < 45 ms live intermediate logos during 100 ms/step wheel scrolling, and fixes Elecbyte .act / SFFv1 palettes in mugen_extractor.", + "fr": "Rend FighterEngine 100 % éphémère sur ESP32 standard (esp32dev) et ESP32-S3 (0 octet gardé en mémoire entre deux combats, aux changements de rotation et pendant la synchro Recalbox/Batocera), corrige le blocage Horloge + Combattants -> GIFs ainsi que la famine RAM des logos PNG sur esp32dev, restaure l'affichage < 45 ms des logos intermédiaires à 100 ms/cran et fiabilise les palettes .act / SFFv1 de mugen_extractor.", + "es": "Hace que FighterEngine sea 100 % efímero tanto en ESP32 clásico (esp32dev) como en ESP32-S3 (0 bytes retenidos entre combates, en cambios de rotación y durante la sincronización Recalbox/Batocera), corrige el bloqueo Reloj + Luchadores -> GIFs y la falta de RAM en logos PNG en esp32dev, restaura logos intermedios en < 45 ms al navegar a 100 ms/paso y corrige paletas .act / SFFv1 en mugen_extractor." + }, + "before_after": { + "before": { + "en": "FighterEngine kept ~22–38 KB of worker stack, roster, and sprite buffers in RAM across rotation switches and Console Sync, causing GifEngine's 22.6 KB decoder or LitePngDecoder to starve on esp32dev while a 35 ms Tier-2 settle wait skipped intermediate logos at 100 ms/step.", + "fr": "FighterEngine conservait ~22 à 38 Ko en RAM lors des rotations et de la synchro console, faisant échouer l'allocation du décodeur GIF (rebond sur l'horloge) ou des logos PNG (texte seul + latence) sur esp32dev, tandis qu'un délai de 35 ms sautait les logos intermédiaires à 100 ms/cran.", + "es": "FighterEngine retenía ~22–38 KB en RAM entre rotaciones y durante la sincronización de consola, agotando el decodificador GIF de 22,6 KB o LitePngDecoder en esp32dev, mientras una espera de 35 ms omitía logos intermedios a 100 ms/paso." + }, + "after": { + "en": "100% of FighterEngine memory is reclaimed on Core 0 after every fight, before incoming rotation modules, and on Console Sync entry — delivering seamless Clock -> GIFs rotation, 100% reliable 8-bit PNG marquees, and < 45 ms live wheel responsiveness.", + "fr": "100 % de la mémoire de FighterEngine est libérée sur Core 0 après chaque combat, avant chaque module suivant et dès l'entrée en synchro console : rotation Horloge -> GIFs fluide, logos PNG 8 bits 100 % fiables et réactivité roue < 45 ms.", + "es": "El 100 % de la memoria de FighterEngine se libera en Core 0 tras cada combate, antes de cada módulo de rotación y al iniciar la sincronización: rotación Reloj -> GIFs fluida, logos PNG de 8 bits 100 % fiables y respuesta < 45 ms." + } + }, + "highlights": { + "en": [ + "FIX (Zero-Retained `FighterEngine` Overlay — `ADR-0004`) — Destroys `FighterEngine` completely between fights, on rotation switches, and during `FrontendSync` on both `esp32dev` and `ESP32-S3`, with live heap admission checks and decoder-first `GifEngine::activate()`.", + "PERF (`< 45 ms` Local-SD Wheel Sync on `esp32dev`) — Restores immediate Core 0 dispatch (`0 ms` Tier-2 wait on local SD), `15 ms` burst coalescing, `2 ms` worker wake slices, and stripped `title` stems in `O(log N)` `_catalog` binary search.", + "FIX (`mugen_extractor.py` Palettes) — Decodes reversed Elecbyte `.act` tables, chains `SFFv1` shared palettes, and filters detached helper sprites." + ], + "fr": [ + "FIX (Overlay `FighterEngine` Zéro-RAM — `ADR-0004`) — Destruction complète entre deux combats, à chaque rotation et en synchro console sur `esp32dev` et `ESP32-S3`, avec contrôle de marge RAM et allocation prioritaire de `AnimatedGIF`.", + "PERF (Synchro Roue `< 45 ms` sur `esp32dev`) — Dispatch immédiat sur microSD locale (`0 ms` d'attente Tier-2), anti-rafale `15 ms`, réveil worker `2 ms` et recherche binaire `O(log N)` étendue aux titres nettoyés.", + "FIX (Palettes `mugen_extractor.py`) — Décodage des palettes `.act` inversées Elecbyte, chaînage des palettes partagées `SFFv1` et filtrage des helpers détachés." + ], + "es": [ + "FIX (Overlay `FighterEngine` Cero-RAM — `ADR-0004`) — Destrucción completa entre combates, en cambios de rotación y en `FrontendSync` tanto en `esp32dev` como en `ESP32-S3`, con control de margen RAM y prioridad al decodificador `AnimatedGIF`.", + "PERF (Sincro `< 45 ms` en `esp32dev`) — Despacho inmediato en MicroSD local (`0 ms` de espera Tier-2), coalescencia `15 ms`, despertar del worker en `2 ms` y búsqueda binaria `O(log N)` con títulos limpios.", + "FIX (Paletas `mugen_extractor.py`) — Decodificación de paletas `.act` invertidas Elecbyte, encadenamiento `SFFv1` y filtrado de helpers separados." + ] + } + }, { "version": "v4.3.8", "date": "2026-12-01", diff --git a/webinstaller/index.html b/webinstaller/index.html index 2691cf8a..d88d9024 100644 --- a/webinstaller/index.html +++ b/webinstaller/index.html @@ -2024,8 +2024,54 @@

6. HUB75 Resolutions & Board × Panel Matrix

const FALLBACK_POSTS = { project: "esp32", - latest_version: "v4.3.8", + latest_version: "v4.3.9", posts: [ + { + version: "v4.3.9", + date: "2026-12-02", + tags: ["FIX", "PERF"], + media: "changelog/media/agenda-sync-preview.svg", + release_url: "https://github.com/red77290/ArcadeMatrix/releases/tag/v4.3.9", + title: { + en: "Zero-Retained Fighter Overlay (ESP32 & ESP32-S3), Clock -> GIFs Fix & < 45 ms Console Wheel Sync", + fr: "Overlay Fighters Zéro-RAM au Repos (ESP32 & ESP32-S3), Rotation Horloge -> GIFs & Synchro < 45 ms", + es: "Overlay Fighters Cero-RAM en Reposo (ESP32 y ESP32-S3), Rotación Reloj -> GIFs y Sincro < 45 ms" + }, + summary: { + en: "Makes FighterEngine strictly ephemeral across both Classic ESP32 (esp32dev) and ESP32-S3 (0 bytes retained between fights, across rotation switches, and during Recalbox/Batocera sync), fixes Clock + Fighters -> GIFs rotation lock-ups and PNG marquee starvation on esp32dev, restores < 45 ms live intermediate logos during 100 ms/step wheel scrolling, and fixes Elecbyte .act / SFFv1 palettes in mugen_extractor.", + fr: "Rend FighterEngine 100 % éphémère sur ESP32 standard (esp32dev) et ESP32-S3 (0 octet gardé en mémoire entre deux combats, aux changements de rotation et pendant la synchro Recalbox/Batocera), corrige le blocage Horloge + Combattants -> GIFs ainsi que la famine RAM des logos PNG sur esp32dev, restaure l'affichage < 45 ms des logos intermédiaires à 100 ms/cran et fiabilise les palettes .act / SFFv1 de mugen_extractor.", + es: "Hace que FighterEngine sea 100 % efímero tanto en ESP32 clásico (esp32dev) como en ESP32-S3 (0 bytes retenidos entre combates, en cambios de rotación y durante la sincronización Recalbox/Batocera), corrige el bloqueo Reloj + Luchadores -> GIFs y la falta de RAM en logos PNG en esp32dev, restaura logos intermedios en < 45 ms al navegar a 100 ms/paso y corrige paletas .act / SFFv1 en mugen_extractor." + }, + before_after: { + before: { + en: "FighterEngine kept ~22–38 KB of worker stack, roster, and sprite buffers in RAM across rotation switches and Console Sync, causing GifEngine's 22.6 KB decoder or LitePngDecoder to starve on esp32dev while a 35 ms Tier-2 settle wait skipped intermediate logos at 100 ms/step.", + fr: "FighterEngine conservait ~22 à 38 Ko en RAM lors des rotations et de la synchro console, faisant échouer l'allocation du décodeur GIF (rebond sur l'horloge) ou des logos PNG (texte seul + latence) sur esp32dev, tandis qu'un délai de 35 ms sautait les logos intermédiaires à 100 ms/cran.", + es: "FighterEngine retenía ~22–38 KB en RAM entre rotaciones y durante la sincronización de consola, agotando el decodificador GIF de 22,6 KB o LitePngDecoder en esp32dev, mientras una espera de 35 ms omitía logos intermedios a 100 ms/paso." + }, + after: { + en: "100% of FighterEngine memory is reclaimed on Core 0 after every fight, before incoming rotation modules, and on Console Sync entry — delivering seamless Clock -> GIFs rotation, 100% reliable 8-bit PNG marquees, and < 45 ms live wheel responsiveness.", + fr: "100 % de la mémoire de FighterEngine est libérée sur Core 0 après chaque combat, avant chaque module suivant et dès l'entrée en synchro console : rotation Horloge -> GIFs fluide, logos PNG 8 bits 100 % fiables et réactivité roue < 45 ms.", + es: "El 100 % de la memoria de FighterEngine se libera en Core 0 tras cada combate, antes de cada módulo de rotación y al iniciar la sincronización: rotación Reloj -> GIFs fluida, logos PNG de 8 bits 100 % fiables y respuesta < 45 ms." + } + }, + highlights: { + en: [ + "FIX (Zero-Retained `FighterEngine` Overlay — `ADR-0004`) — Destroys `FighterEngine` completely between fights, on rotation switches, and during `FrontendSync` on both `esp32dev` and `ESP32-S3`, with live heap admission checks and decoder-first `GifEngine::activate()`.", + "PERF (`< 45 ms` Local-SD Wheel Sync on `esp32dev`) — Restores immediate Core 0 dispatch (`0 ms` Tier-2 wait on local SD), `15 ms` burst coalescing, `2 ms` worker wake slices, and stripped `title` stems in `O(log N)` `_catalog` binary search.", + "FIX (`mugen_extractor.py` Palettes) — Decodes reversed Elecbyte `.act` tables, chains `SFFv1` shared palettes, and filters detached helper sprites." + ], + fr: [ + "FIX (Overlay `FighterEngine` Zéro-RAM — `ADR-0004`) — Destruction complète entre deux combats, à chaque rotation et en synchro console sur `esp32dev` et `ESP32-S3`, avec contrôle de marge RAM et allocation prioritaire de `AnimatedGIF`.", + "PERF (Synchro Roue `< 45 ms` sur `esp32dev`) — Dispatch immédiat sur microSD locale (`0 ms` d'attente Tier-2), anti-rafale `15 ms`, réveil worker `2 ms` et recherche binaire `O(log N)` étendue aux titres nettoyés.", + "FIX (Palettes `mugen_extractor.py`) — Décodage des palettes `.act` inversées Elecbyte, chaînage des palettes partagées `SFFv1` et filtrage des helpers détachés." + ], + es: [ + "FIX (Overlay `FighterEngine` Cero-RAM — `ADR-0004`) — Destrucción completa entre combates, en cambios de rotación y en `FrontendSync` tanto en `esp32dev` como en `ESP32-S3`, con control de margen RAM y prioridad al decodificador `AnimatedGIF`.", + "PERF (Sincro `< 45 ms` en `esp32dev`) — Despacho inmediato en MicroSD local (`0 ms` de espera Tier-2), coalescencia `15 ms`, despertar del worker en `2 ms` y búsqueda binaria `O(log N)` con títulos limpios.", + "FIX (Paletas `mugen_extractor.py`) — Decodificación de paletas `.act` invertidas Elecbyte, encadenamiento `SFFv1` y filtrado de helpers separados." + ] + } + }, { version: "v4.3.8", date: "2026-12-01",