Repository navigation
feat(video): FLED v1 container support + FxSdCard accepts both formats - #3074
Conversation
Closes #3072. PixelStream now detects the 12-byte "FLED" magic at begin() on seekable handles, consumes the header, stashes the embedded screenmap JSON, and shifts frame addressing past the header. Legacy headerless .rgb files keep working — zero behavior change for existing sketches that don't pass FLED-formatted bytes. New accessors on PixelStream / VideoImpl / Video: bool hasEmbeddedScreenMap() const; const fl::string& embeddedScreenMapJson() const; The container spec lives at https://github.com/zackees/ledmapper/blob/main/docs/fled-format.md and the v2 ScreenMap schema (#92) is what ledmapper emits inside the header. ScreenMap::ParseJson already accepted v2, so no change there. FxSdCard.ino is rewritten as a both-format reference: - Tries data/<name>.fled first; if present and well-formed, the embedded screenmap is parsed and used as-is. - Falls back to data/<name>.rgb + data/screenmap.json sidecar pair if no .fled is on the card. The whole pre-existing workflow is preserved for users with legacy data. Sample data converted: data/{video,color_line_bubbles}.fled added alongside the existing .rgb + screenmap.json. The .fled files were produced by data/wrap-fled.mjs (committed for reproducibility), which upgrades the v1 sidecar screenmap to v2 inline. data/readme.txt documents both formats and the regeneration command. Verification: bash test --cpp fx_video → 1/1 pass bash test --cpp screenmap → 1/1 pass bash test --examples FxSdCard → compiles clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughAdds FLED v1 container format support to ChangesFLED v1 Container Format + FxSdCard Example Update
Sequence Diagram(s)sequenceDiagram
participant Setup as FxSdCard setup()
participant Helper as openVideoEitherFormat()
participant Video as fl::Video
participant PS as PixelStream::begin()
participant FS as SD FileSystem
Setup->>Helper: openVideoEitherFormat(fledPath, rgbPath, sidecarPath, &screenMap)
Helper->>Video: video.begin(fledPath, numLeds, fps, pixelBudget)
Video->>PS: begin(handle, bytesPerFrame)
PS->>FS: read 12-byte header
alt FLED magic detected
PS->>FS: read jsonLength + JSON bytes
PS-->>PS: mPayloadOffset = 12+4+jsonLen, mEmbeddedScreenMapJson = json
PS-->>Video: ready with embedded screenmap
Video-->>Helper: opened OK
Helper->>Video: hasEmbeddedScreenMap()
Video-->>Helper: true
Helper->>Video: embeddedScreenMapJson()
Video-->>Helper: JSON string
Helper-->>Setup: video + populated screenMap
else no FLED header / open failed
PS->>FS: seek(0) rewind
PS-->>Video: legacy raw RGB mode
Video-->>Helper: opened (or failed)
Helper->>FS: readScreenMap(sidecarPath, &screenMap)
Helper-->>Setup: video + populated screenMap (or gError set)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@examples/Fx/FxSdCard/FxSdCard.ino`:
- Line 90: Add validation after each ScreenMap is loaded to ensure the resulting
map's LED count matches NUM_LEDS before the map is applied at line 134. At line
90 where ParseJson is called for "strip1", at line 103 where another ParseJson
call occurs, and at lines 121-129 where other maps are loaded, insert checks
that compare the outScreenMap LED count against NUM_LEDS and log an error or
handle the mismatch appropriately (such as exiting setup or logging a warning)
to prevent silent mapping corruption when there is a size mismatch between the
loaded configuration and the expected LED count.
In `@src/fl/video/pixel_stream.cpp.hpp`:
- Around line 54-55: The code performs unchecked offset arithmetic with
kFledHeaderBytes and untrusted jsonLen values without validating for integer
overflow or wraparound, which can bypass validation and seek/read wrong regions.
Add overflow-safe bounds checks before the offset arithmetic comparison in the
condition checking kFledHeaderBytes plus jsonLen against mHandle->size(), and
implement a defensive cap on jsonLen before using it to resize
mEmbeddedScreenMapJson to prevent malicious or corrupted values from causing
issues. Apply the same overflow-safe validation pattern at the other affected
offset arithmetic locations in the file where frame offsets are computed.
In `@src/fl/video/pixel_stream.h`:
- Around line 60-61: The accessor methods hasEmbeddedScreenMap() and
embeddedScreenMapJson() are defined inline in the header file pixel_stream.h,
which violates the repo's coding guidelines that prohibit function definitions
in src/**/*.h files. Move these two method definitions to either a .cpp.hpp or
.impl.hpp file, leaving only the method declarations in the header file. Ensure
the implementation file is properly included where needed to maintain
functionality.
In `@src/fl/video/video_impl.h`:
- Line 59: The header file src/fl/video/video_impl.h uses fl::string as a return
type in the embeddedScreenMapJson() method on line 59, but the header that
defines fl::string is not included. Add `#include` "fl/stl/string.h" to the
include section at the top of the file to make it self-contained and prevent
compile breaks due to include order dependencies.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 67cb6333-fe61-444f-b533-3452a997bf48
📒 Files selected for processing (11)
examples/Fx/FxSdCard/FxSdCard.inoexamples/Fx/FxSdCard/data/color_line_bubbles.fledexamples/Fx/FxSdCard/data/readme.txtexamples/Fx/FxSdCard/data/video.fledexamples/Fx/FxSdCard/data/wrap-fled.mjssrc/fl/fx/video.cpp.hppsrc/fl/fx/video.hsrc/fl/video/pixel_stream.cpp.hppsrc/fl/video/pixel_stream.hsrc/fl/video/video_impl.cpp.hppsrc/fl/video/video_impl.h
- pixel_stream.h: move new accessor definitions out of the header into .cpp.hpp (FastLED layer convention). - pixel_stream.cpp.hpp: cap embedded json_length to kFledMaxJsonBytes (1 MiB) and gate the `kFledHeaderBytes + jsonLen` range check against the file size with a non-overflowing form. Use size_t for the frameNumber * bytesPerFrame product in hasFrame() / readFrameAt() so the offset can't overflow u32 on >1M-frame, large-bytes-per-frame streams. - video_impl.h: add #include "fl/stl/string.h" now that fl::string is on the public API surface. - FxSdCard.ino: validate ScreenMap LED count == NUM_LEDS for both the FLED-embedded and sidecar paths before continuing setup. A silent mismatch otherwise corrupts the LED mapping with no runtime recovery. Verification: fl_fx_video + fl_math_screenmap tests pass, FxSdCard example compiles clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/fl/video/pixel_stream.cpp.hpp (1)
182-183:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winGuard against division by zero in
framesDisplayed().Line 182 was updated to handle
mPayloadOffset, but line 183 still divides bymbytesPerFramewithout checking whether it is zero. Other methods likeframesRemaining()(line 168) already checkif (mbytesPerFrame == 0), showing the code is aware this can occur. IfmbytesPerFrameis zero here, the division triggers undefined behavior (crash).🛡️ Proposed guard
i32 PixelStream::framesDisplayed() const { if (mType == kStreaming) { return -1; } + if (mbytesPerFrame == 0) return 0; fl::size_t pos = mHandle->pos(); if (pos < mPayloadOffset) return 0; return static_cast<i32>((pos - mPayloadOffset) / mbytesPerFrame); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/fl/video/pixel_stream.cpp.hpp` around lines 182 - 183, The framesDisplayed() method divides by mbytesPerFrame on line 183 without guarding against the case where mbytesPerFrame is zero. Add a check immediately after the existing condition on line 182 to return 0 if mbytesPerFrame equals zero, following the same defensive pattern already used in the framesRemaining() method at line 168. This prevents undefined behavior and a potential crash when mbytesPerFrame has not been initialized or is reset to zero.
♻️ Duplicate comments (1)
src/fl/video/pixel_stream.cpp.hpp (1)
137-140:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftMultiplication overflow still possible; past review's guard was not applied.
Lines 137-138 and 149-150 compute
frameNumber * mbytesPerFramewithout checking for overflow first. While switching tosize_tarithmetic reduces the risk on 64-bit platforms, it does not eliminate overflow on 32-bit embedded systems (common for FastLED). The subsequent comparisontarget < total_bytesdoes not reliably catch all overflow cases.Scenario demonstrating false positive:
- 32-bit platform:
SIZE_MAX ≈ 4.3BframeNumber = 1,500,000,000,mbytesPerFrame = 3000frameBytes = 1,500,000,000 * 3000 = 4,500,000,000,000→ wraps to~205,032,704target = 0 + 205,032,704 = 205,032,704- If
total_bytes = 300,000,000, the check returnstrue(frame exists), but the actual frame offset4.5Tis far beyond the file → incorrect seek, corrupted playback.The past review suggested checking overflow before multiplication (e.g.,
if (frameNumber > (SIZE_MAX - mPayloadOffset) / bpf) return false;), but that guard was not applied.🔢 Recommended overflow guard (from past review)
In
hasFrame(lines 137–140):+ const fl::size_t bpf = static_cast<fl::size_t>(mbytesPerFrame); + if (bpf > 0 && frameNumber > ((fl::numeric_limits<fl::size_t>::max)() - mPayloadOffset) / bpf) { + return false; + } fl::size_t frameBytes = static_cast<fl::size_t>(frameNumber) * static_cast<fl::size_t>(mbytesPerFrame);In
readFrameAt(lines 149–151):+ const fl::size_t bpf = static_cast<fl::size_t>(mbytesPerFrame); + if (bpf > 0 && frameNumber > ((fl::numeric_limits<fl::size_t>::max)() - mPayloadOffset) / bpf) { + return false; + } fl::size_t frameBytes = static_cast<fl::size_t>(frameNumber) * static_cast<fl::size_t>(mbytesPerFrame);Also applies to: 149-151
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/fl/video/pixel_stream.cpp.hpp` around lines 137 - 140, The multiplication of frameNumber * mbytesPerFrame in both the hasFrame and readFrameAt methods lacks overflow protection on 32-bit platforms, allowing silent wraparound that produces false positives in frame validation. Add an overflow guard before performing the multiplication: check if frameNumber > (SIZE_MAX - mPayloadOffset) / mbytesPerFrame, and if true, return false immediately to prevent the unsafe multiplication. Apply this same guard to both locations where this calculation occurs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@src/fl/video/pixel_stream.cpp.hpp`:
- Around line 182-183: The framesDisplayed() method divides by mbytesPerFrame on
line 183 without guarding against the case where mbytesPerFrame is zero. Add a
check immediately after the existing condition on line 182 to return 0 if
mbytesPerFrame equals zero, following the same defensive pattern already used in
the framesRemaining() method at line 168. This prevents undefined behavior and a
potential crash when mbytesPerFrame has not been initialized or is reset to
zero.
---
Duplicate comments:
In `@src/fl/video/pixel_stream.cpp.hpp`:
- Around line 137-140: The multiplication of frameNumber * mbytesPerFrame in
both the hasFrame and readFrameAt methods lacks overflow protection on 32-bit
platforms, allowing silent wraparound that produces false positives in frame
validation. Add an overflow guard before performing the multiplication: check if
frameNumber > (SIZE_MAX - mPayloadOffset) / mbytesPerFrame, and if true, return
false immediately to prevent the unsafe multiplication. Apply this same guard to
both locations where this calculation occurs.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 69e40a23-e110-4884-a18e-e2ae8042b3d8
📒 Files selected for processing (4)
examples/Fx/FxSdCard/FxSdCard.inosrc/fl/video/pixel_stream.cpp.hppsrc/fl/video/pixel_stream.hsrc/fl/video/video_impl.h
🚧 Files skipped from review as they are similar to previous changes (3)
- src/fl/video/pixel_stream.h
- src/fl/video/video_impl.h
- examples/Fx/FxSdCard/FxSdCard.ino
Quietens the NoexceptAstChecker — pre-existing master breakage from #3074 (FLED v1 container support). 12 violations across: - src/fl/fx/video.{h,cpp.hpp} — Video::has/embeddedScreenMap* - src/fl/video/pixel_stream.{h,cpp.hpp} — PixelStream::has/embeddedScreenMap* - src/fl/video/video_impl.{h,cpp.hpp} — VideoImpl::has/embeddedScreenMap* All six accessors are simple forwarders / member-field returns; FL_NOEXCEPT is the correct annotation. No behavior change. Surfaced by the stop-hook lint check after meta #3079 closure.
…1 samples (#3100) Closes ledmapper#143 on the FastLED side. (Ledmapper-side emitter + fixture migration shipped in zackees/ledmapper#144.) ScreenMap::toJson / toJsonStr now emit the v2 shape (`{ version: 2, groups, segments: [...] }`) instead of `{ map: { name: {...} } }`. ScreenMap::ParseJson is already bilingual, so: - C++ → JS WASM bridge keeps working (ledmapper reads v2 natively). - Round-trip test (toJson → ParseJson same flat_map) still passes: the parser dispatches on shape, the JSON shape just changed. - Any existing on-disk v1 JSON continues to load via the v1 path — we are not breaking third-party files in the wild. Sample data converted: - examples/Fx/FxSdCard/data/screenmap.json — the legacy sidecar fallback path. The FLED happy path was already embedding v2 since PR #3074; this just makes the .rgb fallback exercise v2 too. - examples/Chromancer/screenmap.json.h — 4-segment inline JSON literal that the sketch feeds to ScreenMap::ParseJson at setup. - examples/Chromancer/output.json — output blob, same 4 segments. Out of scope: - examples/Chromancer/gary_woos_wled_port/gary_woos_wled_ledmap.h uses `{"map": [array of indices]}` which is the WLED ledmap format, not a v1 ScreenMap. Coincidentally shares the "map" key name but the value type is wrong for a screenmap — left untouched. Verification: bash test --cpp screenmap → 1/1 pass bash test --cpp fx_video → 1/1 pass bash test --examples FxSdCard → compiles clean bash test --examples Chromancer → compiles clean Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Closes #3072.
Summary
PixelStreamnow detects the 12-byteFLEDmagic atbegin()on seekable handles, consumes the header, stashes the embedded screenmap JSON, and shifts frame addressing past the header. Legacy headerless.rgbfiles keep working — zero behavior change for sketches that don't pass FLED-formatted bytes.New accessors on
PixelStream/VideoImpl/Video:The container spec lives at https://github.com/zackees/ledmapper/blob/main/docs/fled-format.md (also pasted as a comment on #3072 for cross-repo reference). The embedded JSON uses the v2
ScreenMapschema (#92), whichScreenMap::ParseJsonalready accepts — no parser change needed there.FxSdCard rewrite
examples/Fx/FxSdCard/FxSdCard.inois rewritten as a both-format reference:data/<name>.fledfirst; if present + well-formed, the embedded screenmap is parsed and used directly.data/<name>.rgb+data/screenmap.jsonsidecar pair if no.fledis on the SD card. The whole pre-existing workflow is preserved.A small
openVideoEitherFormat()helper in the sketch wraps that dispatch.Sample data
data/video.fledanddata/color_line_bubbles.fled(each is the existing.rgbpayload wrapped in a 12-byte FLED header + the v2-upgraded screenmap JSON).data/video.rgb,data/color_line_bubbles.rgb, anddata/screenmap.jsonso the legacy code path is also exercised on disk.data/wrap-fled.mjsis the reproducibility script that produced the.fledfiles. It reads a v1 sidecar screenmap, upgrades to v2 inline (addsversion: 2, defaultgroups, segment per strip withpin/group), and concatenates with the raw RGB payload.data/readme.txtdocuments both formats and the regeneration command.Verification
bash test --cpp fx_video→ 1/1 passbash test --cpp screenmap→ 1/1 passbash test --examples FxSdCard→ compiles clean (clang, quick config)Files changed
src/fl/video/pixel_stream.{h,cpp.hpp}— FLED header detection + accessors +mPayloadOffsetfor frame addressing past the headersrc/fl/video/video_impl.{h,cpp.hpp}— proxy accessors to PixelStreamsrc/fl/fx/video.{h,cpp.hpp}— public Video API exposes the same accessorsexamples/Fx/FxSdCard/FxSdCard.ino— both-format dispatchexamples/Fx/FxSdCard/data/{video,color_line_bubbles}.fled— newexamples/Fx/FxSdCard/data/wrap-fled.mjs— reproducibility scriptexamples/Fx/FxSdCard/data/readme.txt— updated🤖 Generated with Claude Code
Summary by CodeRabbit
.fledvideo container format with embedded screen maps.fledplayback with a fallback to legacy.rgb+screenmap.json.rgb+screenmap.jsoninto.fled