Skip to content

feat(fl/fled): create new fl::Fled bundle subsystem (value + runner + section accessors) under src/fl/fled/ #3311

Open
1 of 1 issue completed

Description

@zackees

🛑 Directive — fl::Fled produces local-state objects; FastLED mutates global state

fl::Fled wraps a binary and returns JSON, blob data, section information, and locally-stateful objects constructed from those sections.

What fl::Fled MAY do:

  • Wrap binary bytes and parse the JSON envelope.
  • Return the raw JSON view and raw section blobs.
  • Construct and return local-state objects: fl::Video (its own frame buffer + timer, PIMPL), fl::ScreenMap (coord LUT value), fl::MultiChannelConfig (passive config). Constructing these does not touch any global registry.

What fl::Fled MUST NOT do:

  • Register controllers (FastLED.addLeds<>(...)).
  • Bind screenmaps to controllers (controller.setScreenMap(...) — that broadcasts via EngineEvents::onCanvasUiSet).
  • Touch the FastLED scheduler / brightness / refresh rate / power limits.
  • Install loader function pointers, fire callbacks, or otherwise reach across into global FastLED state.

FastLED is the mutation nexus. Anything that changes global system state — creating controllers, binding screenmaps, starting playback against the FastLED scheduler, dispatching scripts, registering loaders — goes through FastLED methods. FastLED consumes the local-state objects that fl::Fled produced and wires them into global state.

If anything below this directive contradicts it, the directive wins and the design below must be amended to match.


Summary

Create a new src/fl/fled/ subsystem for the .fled bundle format — a self-describing FastLED deployment unit carrying screenmap + video today, designed to grow into a full "drop one file, sketch self-instantiates" container (hardware config, MicroPython / WASM scripts, playlists, calibration data, … in future releases).

Supersedes the scope of PR #3292 (fl::PatternPlayer), which solved the wrong shape of the problem — it conflated file I/O, format parsing, screenmap extraction, frame timing, and controller binding into a single class. The decisions below were worked out in detail with the maintainer; this issue is the consolidated tracking ticket.

Related: #3310 (doc), #3292 (the catalyzing PR), zackees/ledmapper canonical format spec.


Architectural decisions

Why a new subdir, not under fl/video/

.fled is a bundle, not a video subsystem. Video is one section type. Putting fl::Fled under fl/video/ doesn't scale once additional section types land. Same reasoning as fl/channels/ having its own dir instead of riding fl/system/ or fl/fx/.

Implementation details deliberately left open

The file-by-file layout inside fl/fled/ is the implementer's choice. The decisions captured here are about the API shape and the directory boundary, not the internal file decomposition.

The 2-layer API (post-directive)

// ── Layer 1: passive data + FastLED dispatch ───────────────────────
auto fled = fl::Fled::load(fs, "sketch.fled");   // bundle value (passive)
FastLED.enableWasm();                            // opt-in heavy runtimes (if needed)
FastLED.load(fled);                              // FastLED mutates system state

// ── Layer 2: section accessors (for introspection / custom orchestration) ──
// Accessors return locally-stateful objects. Constructing them touches NO
// global state — no controller registration, no screenmap broadcast, no
// scheduler. The objects can be inspected, or handed to FastLED for
// global binding.
if (auto v  = fled.video())     { /* fl::Video — local state */ }
if (auto sm = fled.screenMap()) { /* fl::ScreenMap — local state */ }
if (auto hw = fled.hardware())  { /* fl::MultiChannelConfig — passive config */ }

fl::Fled is the bundle value. Its accessors return locally-stateful objects (or passive data) with no global side effects. FastLED.load(fled) is the only thing that turns those objects into live system state — it pulls the objects from fled and binds them to controllers, screenmap broadcasts, the scheduler, etc.

FastLED.load() + enable*() — tree-shake-friendly dispatch

The god-object surface for running a bundle:

class CFastLED {
public:
    void load(const fl::Fled& fled);     // reads passive data; mutates system state

    void enableWasm();                    // opt-in: links wasm runtime
    void enableMicroPy();                 // opt-in: links micropython VM
    // ... future enableXxx() per heavy subsystem
};

Tree-shake contract:

Sketch Dispatch table linked? Wasm linked? MicroPy linked?
Legacy (never calls FastLED.load or any enable*) ❌ — fledDispatcher() unreferenced ❌ ❌
Video-only (FastLED.load(fled)) ✅ — small (default-empty fl::function per heavy subsystem) ❌ ❌
Wasm-enabled (FastLED.enableWasm(); FastLED.load(fled);) ✅ ✅ ❌
Both (enableWasm + enableMicroPy + load) ✅ ✅ ✅

The legacy row is the critical guarantee: adding the entire fl::Fled subsystem to FastLED costs zero bytes for sketches that don't use it.

Mechanism:

// fl/fled/fled_dispatch.h
namespace fl::detail {
class FledDispatcher {
public:
    fl::function<void(const Fled&)> wasmLoader;     // default-empty
    fl::function<void(const Fled&)> microPyLoader;  // default-empty
};
// Construct-on-first-use — singleton tree-shakes when no one references it.
FledDispatcher& fledDispatcher();
} // namespace fl::detail

// src/FastLED_load.cpp.hpp — always linked when FastLED.load is called.
// Reads passive data from fled, constructs live runtime objects, mutates state.
void CFastLED::load(const fl::Fled& fled) {
    // Always-cheap GLOBAL-mutating subsystems. fled supplies the objects;
    // FastLED performs the mutation.
    if (auto mc = fled.channels()) {                                  // creates controllers
        for (const auto& cfg : mc->mChannels) FastLED.add(*cfg);
    }
    if (auto sm = fled.screenMap())  detail::bindScreenMap(*sm);     // broadcasts via EngineEvents

    // NOTE: no video dispatch here. Video is local state; the user is
    // responsible for retrieving fled.video() and drawing it in loop().
    // See "No loadVideo" rationale above.

    // Heavy subsystems via fl::function dispatch:
    if (auto script = fled.script()) {
        auto& d = fl::detail::fledDispatcher();
        if (script->kind() == ScriptKind::Wasm) {
            if (d.wasmLoader) d.wasmLoader(fled);
            else FL_ERROR("Wasm script detected in .fled bundle but the wasm "
                          "runtime is not linked. Call FastLED.enableWasm() in "
                          "setup() to enable it.");
        } else if (script->kind() == ScriptKind::MicroPy) {
            if (d.microPyLoader) d.microPyLoader(fled);
            else FL_ERROR("MicroPython script detected in .fled bundle but the "
                          "VM is not linked. Call FastLED.enableMicroPy() in "
                          "setup() to enable it.");
        }
    }
}

// src/FastLED_enableWasm.cpp.hpp — separate TU, links wasm runtime
#include "fl/fled/fled_wasm_host.h"
void CFastLED::enableWasm() {
    fl::detail::fledDispatcher().wasmLoader = &fl::FledWasmHost::run;
}

Setup-time ordering invariant: FastLED.enable*() must be called in setup() before any FastLED.load() that might encounter the corresponding section type. Enabling after a load won't retroactively dispatch.

Builder deferred: A fluent variant — FastLED.configure().enableWasm().load(fled) — may be added as syntactic sugar later. Not part of v1.

Relationship to existing types — fled returns them; only their globally-mutating methods are off-limits to fled

Existing FastLED types are reused directly — no new wrapper types. fl::Fled constructs and returns them; the constraint is that constructing them must not touch global state (which is already true for these types — they're locally-stateful values).

Section fl::Fled accessor returns Locality of construction Global mutation (FastLED's job)
Video fl::shared_ptr<fl::Video> Local — PIMPL'd frame buffer + timer Hook into FastLED scheduler (start playback)
Screenmap fl::shared_ptr<fl::ScreenMap> Local — coord LUT value controller.setScreenMap(*sm) (broadcasts via EngineEvents::onCanvasUiSet)
Channels fl::shared_ptr<fl::MultiChannelConfig> Local — vector<ChannelConfigPtr>, passive FastLED.add(*cfg) per channel
Script fl::shared_ptr<fl::FledScript> Local — bytecode + kind enum, passive Install loader, invoke runtime

The objects are usable for introspection without involving FastLED at all (Scenario 7). Touching their globally-mutating methods (the rightmost column) is FastLED's job — sketches that do it explicitly (Scenario 4) are doing the mutation themselves, not having fled do it for them.


Public API surface (v1)

// fl/fled/fled.h — uses only forward decls for section types
#pragma once
#include "fl/stl/span.h"
#include "fl/stl/vector.h"
#include "fl/stl/shared_ptr.h"
#include "fl/stl/u8.h"

namespace fl {

class FileSystem;          // fwd
class Video;               // fwd  (existing locally-stateful PIMPL type, fl/fx/video.h)
class ScreenMap;           // fwd  (existing locally-stateful value type, fl/math/screenmap.h)
class MultiChannelConfig;  // fwd  (existing channels-API type at fl/channels/config.h:366)
class FledScript;          // fwd  (passive data wrapper — only fled-specific new type)
class FledImpl;            // fwd  (internal PIMPL)

class Fled {
public:
    // ── Load factories — ownership-explicit, NO T*/size pairs ──────────────

    // Read from a file via the FileSystem abstraction. Allocates + owns.
    static Fled load(FileSystem& fs, const char* path);

    // Static / PROGMEM bundle. ZERO COPY — caller asserts span lifetime.
    static Fled loadFromStatic(fl::span<const fl::u8> bytes);

    // Heap-owned buffer transferred in by move.
    static Fled loadFromVector(fl::vector<fl::u8>&& bytes);

    // ── Raw access — the lowest-level surface ──────────────────────────────

    // Parsed JSON envelope. Read-only view; mutating it does not affect the
    // bundle. Useful for tools / inspectors that want to walk the envelope
    // without going through typed section accessors.
    const fl::Json& json() const;

    // Raw section bytes by name. Returns nullptr if the section is absent.
    // The returned pointer is valid for the lifetime of this Fled instance.
    fl::shared_ptr<const fl::u8> blob(const char* sectionName,
                                      fl::size* outLen) const;

    // ── Typed accessors — return locally-stateful objects or passive data ──
    // Constructing the returned objects touches NO global state — no controller
    // registration, no EngineEvents broadcasts, no scheduler hook-in.
    // FastLED.load(fled) is the only thing that wires them into global state.
    fl::shared_ptr<Video>              video()    const;   // fl::Video — local PIMPL state
    fl::shared_ptr<ScreenMap>          screenMap() const;  // fl::ScreenMap — local value
    fl::shared_ptr<MultiChannelConfig> channels() const;   // existing channels-API type
    fl::shared_ptr<FledScript>         script()   const;   // passive: bytecode + kind

    // ── Introspection ──────────────────────────────────────────────────────
    fl::u8   version()      const;
    fl::size sectionCount() const;

    // Default-constructible to null state; cheap to copy (PIMPL).
    Fled();
    explicit operator bool() const;

private:
    fl::shared_ptr<FledImpl> mImpl;   // single hidden indirection
};

} // namespace fl
// fl/channels/config.h — ALREADY EXISTS. fled does NOT define a new wrapper.
// fl::MultiChannelConfig (line 366) is the canonical multi-strip config type;
// it holds fl::vector<ChannelConfigPtr>. Each fl::ChannelConfig (line 163)
// carries chipset variant + LEDs span + color order + ChannelOptions
// (correction, temperature, dither, rgbw) + ScreenMap + optional name.
// The bundle's JSON "channels" key deserializes directly into MultiChannelConfig.

// fl/fled/fled_script.h — the only new fled-specific section type (v2 prep)
namespace fl {
enum class ScriptKind : fl::u8 { Wasm, MicroPy };
struct FledScript {
    ScriptKind                   kind;
    fl::shared_ptr<const fl::u8> bytes;
    fl::size                     length;
};
}

// Video and ScreenMap stay in their existing locations (fl/fx/video.h,
// fl/math/screenmap.h). fled returns them directly via shared_ptr.
// Constructing them does not touch global FastLED state.
// file_system.h — one-line addition for bidirectional factory
namespace fl {
class FileSystem {
public:
    // ... existing API ...
    Fled loadFled(const char* path);   // sugar for Fled::load(*this, path)
};
}
// CFastLED additions — the god-object surface for mutating global state from a bundle
class CFastLED {
public:
    // ... existing FastLED API ...

    // ── Full load — does every GLOBAL mutation: channels + screenmap + script dispatch ──
    // Does NOT include video — Video is local state; user retrieves it via
    // fled.video() and drives it from loop(). See "No loadVideo" rationale below.
    void load(const fl::Fled& fled);

    // ── Granular per-section loads — for sketches that want partial application ──
    // Each takes the bundle and performs ONLY that section's global mutations.
    // load() is the composition of these (plus the script dispatch).
    // Each method lives in its own TU and tree-shakes independently.
    void loadChannels(const fl::Fled& fled);    // calls FastLED.add(*cfg) for each in MultiChannelConfig
    void loadScreenMap(const fl::Fled& fled);   // broadcasts via EngineEvents

    // ── Heavy-runtime opt-ins (own TU, only link when named) ─────────────
    void enableWasm();                  // opt-in: links wasm runtime
    void enableMicroPy();               // opt-in: links micropython VM
};

No loadVideo — video is local state, drawn from loop()

A FastLED.loadVideo(fled) method was considered and rejected. fl::Video is local-state — frame buffer, internal timer, PIMPL impl. It has no global side effects. There is no FastLED scheduler that auto-draws videos. Drawing is the user's responsibility:

fl::shared_ptr<fl::Video> v;
void setup() {
    auto fled = fl::Fled::load(fs, "sketch.fled");
    FastLED.load(fled);     // channels + screenmap (global mutations)
    v = fled.video();       // local: caller owns the playback timer
}
void loop() {
    if (v) v->draw(fl::millis(), leds);
    FastLED.show();
}

This is consistent with every other FastLED sketch — loop() is where frames get drawn. A loadVideo method would have to invent a new "auto-frame-callback" mechanism on FastLED to do its job, which is scope creep and doesn't fit the "FastLED mutates global state" framing (a video reference held for later drawing isn't a global mutation, it's deferred local-state usage).

Scripted bundles (wasm/mpy) are different — enableWasm() installs a per-frame hook that calls into the script's loop(). That hook IS a global mutation (it changes what runs each show cycle). Video has no equivalent mechanism, by design.

That's the entire v1 public surface. No FledRunner. No fl::Fled::run() sugar. No builder. No live runtime objects returned from fl::Fled.


Design rationale

Byte-buffer ownership — three explicit factories, no T*/size pairs

Factory Memory source Copy? Owns?
load(fs, path) FileSystem read Yes — allocates internally Yes
loadFromStatic(span) PROGMEM / .rodata / linker blob No — zero copy No (non-owning view)
loadFromVector(vec&&) Caller-built heap buffer No — moves the vector Yes (after move)

Rules:

  • T*, size_t pairs are forbidden. Span is the contract for borrowed memory; vector<T>&& is the contract for transferred memory. Matches FastLED's existing fl::span convention.
  • No implicit-copy "safe default" factory. Rejected — it hides allocation cost. The three named factories make the cost explicit at the call site.
  • shared_ptr<const u8> for the byte buffer was considered and rejected. Shared ownership of bundle bytes is a rare use case.

Section accessor return types — uniform fl::shared_ptr<T>

The rule: every section accessor returns fl::shared_ptr<T>. nullptr means the bundle has no section of that type. The T is whatever existing type is natural for the section's payload — fl::Video for video, fl::ScreenMap for screenmap — provided that constructing T does not touch global state. Where no suitable existing type exists, fled defines a passive data wrapper (MultiChannelConfig, FledScript).

Uniformity across all sections + same-shape introspection for tools. The per-access cost (one shared_ptr increment + indirection) is negligible.

Fled is itself PIMPL-wrapped

fl::shared_ptr<FledImpl> lives in exactly one place — inside Fled's mImpl. User code never types shared_ptr of FledImpl. Forward decls keep the include graph light.

Bidirectional factories — both spellings, one impl

Two factory directions for every relationship. Each is a one-line forwarder to the other; pick whichever reads better at the call site.

Bundle load (Fled ↔ FileSystem):

auto fled = fl::Fled::load(fs, "sketch.fled");   // canonical
auto fled = fs.loadFled("sketch.fled");          // sugar — internally calls Fled::load(*this, path)

Section produce (Fled ↔ section type):

auto v = fled.video();                           // fled-side accessor
auto v = fl::Video::fromFled(fled);              // Video-side factory — internally `return fled.video();`

auto sm = fled.screenMap();
auto sm = fl::ScreenMap::fromFled(fled);

auto chs = fled.channels();
auto chs = fl::MultiChannelConfig::fromFled(fled);

The fromFled(...) factories live on each section type (fl::Video::fromFled in fl/fx/video.h, fl::ScreenMap::fromFled in fl/math/screenmap.h, fl::MultiChannelConfig::fromFled in fl/channels/config.h). Each implementation is a one-line forwarder to the fled-side accessor — same return type, same data, just a different call-site spelling.

No new wrapper types, no separate code paths — the bidirectional symmetry is purely ergonomic.


v1 vs v2 scope

v1 (this issue's deliverable):

  • fl::Fled value with the three factories + raw json() / blob(...) accessors + typed accessors (video, screenMap, hardware, script)
  • fl::Fled::video() returns fl::shared_ptr<fl::Video>; fl::Fled::screenMap() returns fl::shared_ptr<fl::ScreenMap>; fl::Fled::channels() returns fl::shared_ptr<fl::MultiChannelConfig> — all existing types, constructed by fled with no global side effects, NO fled-side wrappers
  • New passive data type in fl/fled/: FledScript only (the one type that doesn't have an existing equivalent)
  • CFastLED::load(fled) — reads the objects fled produced, performs global mutations (addLeds<>, setScreenMap, scheduler hook-in, script dispatch)
  • CFastLED::enableWasm() + CFastLED::enableMicroPy() — opt-in heavy runtime linkage
  • fl::detail::FledDispatcher singleton — tree-shakes when no one calls FastLED.load or any enable*
  • Channel-API types fl::MultiChannelConfig and fl::ChannelConfig (with its ChannelOptions, ClocklessChipset/SpiChipsetConfig variants) ALREADY EXIST at src/fl/channels/config.h. fled uses them as-is; no new types invented (see embedded MultiChannelConfig-from-fled comment below for JSON deserialization mapping)
  • fs.loadFled() sugar on FileSystem
  • FLED_FORMAT.md relocated from fl/video/ to fl/fled/
  • Audit of fl::Video and fl::ScreenMap constructors to verify zero global side effects (if any are found, fix before fled uses them)
  • One updated example replacing the FxSdCard.ino boilerplate dance
  • PR feat(video): add fl::PatternPlayer high-level mapped video file player #3292's pattern_player.* files retired or deprecated

v2 (separate follow-up issues — NOT prescribed here):

  • Script-host implementations (fl::FledWasmHost, fl::FledMicroPyHost) — internal only, surfaced via FastLED.enableWasm() / FastLED.enableMicroPy()
  • FledPlaylist, FledCalibration, additional section types
  • Fluent builder (FastLED.configure().enableWasm().load(fled))

If a sketch needs override behavior, the v1 granular methods (FastLED.loadChannels, FastLED.loadScreenMap, FastLED.loadVideo) already cover the "load just this part, do the rest manually" case. No FledLoadOpts struct needed.


Dependency: unified fl::FileSystem

fl::FileSystem today only has beginSd(cs_pin). Bundle API needs:

auto fs = fl::FileSystem::sd(CHIP_SELECT_PIN);        // current
auto fs = fl::FileSystem::littleFs();                 // ESP32 / RP2040 flash
auto fs = fl::FileSystem::littleFs("/fled");          // mount-point override
auto fs = fl::FileSystem::wasm();                     // browser virtual FS
auto fs = fl::FileSystem::host();                     // host tests / desktop

v1 dependency. Closes the "future work" note at src/fl/asset/asset.h:157.


Acceptance scenarios

Every scenario where state mutation happens goes through FastLED. fl::Fled is touched only for passive reads.

Scenario 1 — Video bundle (load + draw)

fl::shared_ptr<fl::Video> v;

void setup() {
    auto fled = fl::Fled::load(fs, "sketch.fled");
    FastLED.load(fled);    // global mutations: channels + screenmap
    v = fled.video();      // local: keep the video reference for the loop
}

void loop() {
    if (v) v->draw(fl::millis(), leds);
    FastLED.show();
}

FastLED.load() handles the global setup (controllers + screenmap broadcast); the user drives video playback from loop() like any other FastLED sketch. There is no FastLED.loadVideo() because video has no global mutation to perform.

Scenario 2 — LittleFS on ESP32 (no SD card)

fl::shared_ptr<fl::Video> v;

void setup() {
    auto fs = fl::FileSystem::littleFs();
    auto fled = fl::Fled::load(fs, "/sketch.fled");
    FastLED.load(fled);
    v = fled.video();
}

void loop() {
    if (v) v->draw(fl::millis(), leds);
    FastLED.show();
}

Scenario 3 — Bundle embedded in firmware (no FS at all, zero copy)

extern const fl::u8 kSketchFled[] FL_PROGMEM;
extern const fl::size kSketchFledSize;

fl::shared_ptr<fl::Video> v;

void setup() {
    auto fled = fl::Fled::loadFromStatic({kSketchFled, kSketchFledSize});
    FastLED.load(fled);
    v = fled.video();
}

void loop() {
    if (v) v->draw(fl::millis(), leds);
    FastLED.show();
}

Scenario 4 — Two videos sharing one screenmap (custom orchestration)

auto fled1 = fl::Fled::load(fs, "cam_a.fled");
auto fled2 = fl::Fled::load(fs, "cam_b.fled");

// fled hands us locally-stateful objects (no global mutation yet):
auto sm = fled1.screenMap();   // shared_ptr<fl::ScreenMap> — local value
auto v1 = fled1.video();       // shared_ptr<fl::Video>     — local PIMPL state
auto v2 = fled2.video();

// The sketch then explicitly performs the global mutations:
//   addLeds<>() registers a controller with FastLED's global controller list;
//   setScreenMap(*sm) broadcasts via EngineEvents::onCanvasUiSet.
// Both are FastLED-side mutations triggered by the sketch — not by fled.
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS).setScreenMap(*sm);

void loop() {
    auto& v = whichVideo.value() ? v2 : v1;
    v->draw(fl::millis(), leds);
    FastLED.show();
}

Note: this sketch does fine-grained orchestration that FastLED.load(fled) doesn't try to support. fled.screenMap() and fled.video() return locally-stateful objects — fled never touched global state. The sketch then performs the global mutations explicitly via addLeds<> + setScreenMap.

Scenario 5 — Wasm script bundle (script drives the loop)

void setup() {
    FastLED.enableWasm();
    FastLED.load(fl::Fled::load(fs, "sketch.fled"));
    // No `v = fled.video()` here — the bundled wasm sketch handles drawing.
}
void loop() {
    FastLED.show();
    // The wasm runtime's per-frame hook (installed by enableWasm + dispatched
    // during load) runs the script's loop, which draws frames into the LED
    // buffer before FastLED.show() flushes them.
}

Scripted bundles ARE the "drop one file, it runs" case — enableWasm() installs a per-frame hook that runs the script's loop() automatically. Plain video bundles aren't; they require the user's loop() to drive v->draw().

Scenario 6 — WiFi / OTA delivery (heap vector move-in)

fl::vector<fl::u8> buf;
http.GET("https://art.example/today.fled", &buf);
auto fled = fl::Fled::loadFromVector(fl::move(buf));
FastLED.load(fled);
// If the bundle has video, the sketch must retain fled.video() and draw it
// in loop(). If the bundle has a script section (and the runtime is enabled),
// no extra work — the script's loop runs via the per-frame hook.

Scenario 7 — Pure introspection (no playback, no global mutation)

auto fled = fl::Fled::load(fs, "sketch.fled");
Serial.printf("FLED v%d  sections=%zu\n", fled.version(), fled.sectionCount());
if (auto sm = fled.screenMap()) Serial.printf("screenmap: %zu LEDs\n", sm->getLength());
if (auto v  = fled.video())     Serial.printf("video: %zu frames @ %.1f fps\n",
                                              v->frameCount(), v->fps());
// No FastLED calls. fled returns objects; we read their accessors. Zero global state changed.

Scenario 8 — FileSystem::loadFled() sugar (bidirectional)

fl::shared_ptr<fl::Video> v;
void setup() {
    auto fs = fl::FileSystem::littleFs();
    auto fled = fs.loadFled("/sketch.fled");   // equivalent to Fled::load(fs, ...)
    FastLED.load(fled);
    v = fled.video();
}
void loop() {
    if (v) v->draw(fl::millis(), leds);
    FastLED.show();
}

Scenario 9 — Forgot to enable but bundle wants wasm

void setup() {
    FastLED.load(fl::Fled::load(fs, "sketch.fled"));   // bundle has wasm; no enableWasm()
}

Runtime output:

[FL_ERROR] Wasm script detected in .fled bundle but the wasm runtime is
not linked into this firmware. Call FastLED.enableWasm() in setup() to
enable it.

Scenario 10 — Tool: raw JSON envelope walk

auto fled = fl::Fled::load(fs, "sketch.fled");
const auto& j = fled.json();
for (auto& [key, val] : j.items()) {
    Serial.printf("section: %s\n", key.c_str());
}
// Raw JSON access for inspectors / transcoders that want to walk the
// envelope without going through typed accessors.

Migration

File Action
src/fl/video/pattern_player.h / .cpp.hpp (PR #3292) Retire; the frame-timing logic moves into fl/fled/ (exact filename TBD)
src/fl/video/_build.cpp.hpp Drop the pattern_player.cpp.hpp include
examples/PatternPlayer/PatternPlayer.ino Rewrite using FastLED.load(fl::Fled::load(...)); rename appropriately
examples/Fx/FxSdCard/FxSdCard.ino Rewrite using fl::Fled::load() + fled.video() + fled.screenMap() + FastLED.load() — removes ~60 lines of openVideoEitherFormat + validateScreenMapSize boilerplate
src/fl/video/FLED_FORMAT.md (#3310) Move to src/fl/fled/FLED_FORMAT.md
src/fl/video/video_impl.h, src/fl/fx/video.h Stay put. fl::Video is what fled.video() returns directly. Verify its constructor has no global side effects. Add static shared_ptr<Video> fromFled(const Fled&) factory (one-line forwarder).
src/fl/math/screenmap.h Stay put. fl::ScreenMap is what fled.screenMap() returns directly. Verify its constructor has no global side effects. Add static shared_ptr<ScreenMap> fromFled(const Fled&) factory (one-line forwarder).
src/fl/channels/config.h Already has fl::MultiChannelConfig (line 366) and fl::ChannelConfig (line 163). Add static shared_ptr<MultiChannelConfig> MultiChannelConfig::fromFled(const Fled&) one-line forwarder. Add JSON serializer (toJson/fromJson) if not already present.
src/FastLED.h / src/FastLED.cpp (split TUs) Add load(const fl::Fled&), loadChannels(const fl::Fled&), loadScreenMap(const fl::Fled&), loadVideo(const fl::Fled&), enableWasm(), enableMicroPy() to CFastLED. Each load*() and enable*() lives in its own TU.
src/fl/system/file_system.h Extend with littleFs() / wasm() / host() factories plus loadFled(path) sugar.
CLAUDE.md directory map Add row for src/fl/fled/
agents/docs/fled-format.md (or section in cpp-standards.md per #3310) Brief summary pointing at src/fl/fled/README.md + FLED_FORMAT.md

Coordination


Suggested implementation order

  1. Unify fl::FileSystem factories + add loadFled(path) sugar — the v1 dependency.
  2. Stand up src/fl/fled/ with the fl::Fled value + passive data wrappers (FledVideoData, FledScreenMapData, MultiChannelConfig). File decomposition is implementer's choice.
  3. Add fled.json() / fled.blob(...) raw accessors and the typed passive-data accessors.
  4. Add fl::Video::fromData(...) and fl::ScreenMap::fromData(...) factories on the existing runtime types.
  5. Add fl::detail::FledDispatcher singleton and CFastLED::load(fled) — it reads passive data, calls the bridge factories, mutates system state.
  6. Add CFastLED::enableWasm() and CFastLED::enableMicroPy() in their own TUs.
  7. Relocate FLED_FORMAT.md; rewrite the two affected example sketches.
  8. Open separate v2 follow-up issues for script-host implementations, additional section types, runtime overrides, and the fluent-builder sugar.

Labels

area:fl/fled, area:video, breaking-change, tracking, epic

Sub-issues

Sub-issues

1 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. zackees commented on Jun 20, 2026

    @zackees
    MemberAuthor

    Channels-from-fled design (using existing fl::MultiChannelConfig from fl/channels/config.h, no new types) is embedded as an in-thread comment further down on this issue. Originally filed as #3315 and retired in favor of consolidating the bundle design in one place.

  2. zackees commented on Jun 20, 2026

    @zackees
    MemberAuthor

    Channels-from-fled — use existing fl::MultiChannelConfig, no new types

    Originally filed as #3315 with a heavy invented schema (HardwareConfig, StripConfig, GlobalConfig, Chipset enum, ColorOrder enum, RgbwMode enum, ...). All of that is dead. The Channels API already has the canonical types — fled uses them as-is.

    The existing channels-API surface fled uses

    At src/fl/channels/config.h:

    • fl::ChannelConfig (line 163) — single channel config: chipset variant (ClocklessChipset or SpiChipsetConfig), fl::span<CRGB> LEDs, EOrder rgb order, ChannelOptions (correction, temperature, dither, rgbw, affinity), fl::ScreenMap, optional name.
    • fl::MultiChannelConfig (line 366) — vector<ChannelConfigPtr>. Canonical multi-strip config bag.
    • fl::ChannelOptions — per-channel correction / temperature / dither / rgbw / affinity. Already factored.
    • fl::ClocklessChipset / fl::SpiChipsetConfig — chipset-specific config carried in a variant inside ChannelConfig.

    No new types. The bundle's "channels" JSON key deserializes directly into fl::MultiChannelConfig. The JSON serializer for these types lives in fl/channels/ (add it if not already present); fled just calls into it.

    Section accessor

    class Fled {
    public:
        fl::shared_ptr<fl::MultiChannelConfig> channels() const;   // returns existing type
    };
    
    // Symmetric factory (one-line forwarder in fl/channels/config.h):
    namespace fl {
    class MultiChannelConfig {
    public:
        static fl::shared_ptr<MultiChannelConfig> fromFled(const Fled& fled) {
            return fled.channels();
        }
    };
    }

    Runner integration

    FastLED.loadChannels(fled) is the global-mutation entry point. It reads the MultiChannelConfig and calls FastLED.add(*cfg) per channel — that's the existing channels-API call site for "register this channel with FastLED":

    void CFastLED::loadChannels(const fl::Fled& fled) {
        auto mc = fled.channels();
        if (!mc) return;
        for (const auto& cfg : mc->mChannels) {
            FastLED.add(*cfg);   // existing channels-API entrypoint
        }
    }

    That's the entire integration. No applyHardware(), no detail:: helpers, no for-each-strip-with-correction-and-temperature-and-rgbw branching — the existing FastLED.add(cfg) path already handles all of that because ChannelConfig already carries it.

    Global FastLED config (brightness, max power, etc.) — out of v1 scope

    fl::MultiChannelConfig is per-channel only. Brightness, setMaxPowerInMilliWatts, setMaxRefreshRate, dither — these are FastLED-wide settings that don't currently have a consolidated config type in fl/channels/. v1 does NOT invent one; sketches that need non-default global settings call the existing setters explicitly:

    void setup() {
        auto fled = fl::Fled::load(fs, "sketch.fled");
        FastLED.load(fled);
        FastLED.setBrightness(96);     // manual; bundle does not carry brightness
        FastLED.setMaxPowerInMilliWatts(5000);
    }

    If real demand emerges for a bundle-side global config, the natural follow-up is to add a fl::GlobalConfig (or similar) to fl/channels/, surface it on MultiChannelConfig (extension) OR as a separate fled.globals() accessor, and add JSON support. Not v1.

    On-disk JSON representation

    The bundle's JSON envelope's "channels" key holds an array of channel configs that deserialize into MultiChannelConfig. Exact JSON shape mirrors ChannelConfig field-by-field. Authoritative spec lives in ledmapper's docs/fled-format.md alongside the existing map and video.fps blocks.

    Example envelope (illustrative — the canonical field names are whatever the ChannelConfig JSON serializer produces):

    {
      "channels": [
        {
          "name": "front",
          "chipset": { "kind": "clockless", "pin": 2, "timing": "WS2812B_800KHZ" },
          "ledCount": 1024,
          "rgbOrder": "GRB",
          "options": {
            "correction": "TypicalLEDStrip",
            "temperature": "TypicalLEDStripTemperature"
          },
          "screenMapName": "front_matrix"
        },
        {
          "name": "ring",
          "chipset": { "kind": "spi", "dataPin": 4, "clockPin": 5, "hz": 8000000 },
          "ledCount": 60,
          "rgbOrder": "BGR",
          "screenMapName": "ring"
        }
      ]
    }

    The actual field names + chipset variant encoding fall out of the JSON (de)serializer for fl::ChannelConfig — they're not new design here, they're whatever shape the channels-API team picks for that serializer.

    Coordination with the canonical format spec

    The JSON shape for channels should land in ledmapper's docs/fled-format.md alongside the existing map and video.fps blocks. The serializer/deserializer lives in fl/channels/ (the same TU that owns ChannelConfig and MultiChannelConfig).

    Cross-link:

    Acceptance criteria (folded into umbrella v1)

    • fl::MultiChannelConfig::fromFled(const Fled&) static factory added (one-line forwarder to fled.channels()).
    • fl::Fled::channels() returns fl::shared_ptr<fl::MultiChannelConfig> (nullptr if no channels section).
    • CFastLED::loadChannels(const fl::Fled&) iterates mc->mChannels and calls FastLED.add(*cfg) per channel.
    • CFastLED::load(const fl::Fled&) composes loadChannels + loadScreenMap + script dispatch.
    • JSON (de)serializer for fl::MultiChannelConfig / fl::ChannelConfig lands in fl/channels/ (extend existing or add if absent).
    • At least one example sketch loads a .fled file with a channels section via FastLED.load(fled) end-to-end.
    • Coordinated update to ledmapper's docs/fled-format.md adding the "channels" envelope key.
    • NO new HardwareConfig / StripConfig / Chipset enum / ColorOrder enum / RgbwMode enum / ColorCorrection struct / ColorTemperature struct / CustomClocklessTiming struct types in fl/channels/. The existing channels-API surface covers all of these.
  3. zackees commented on Jun 20, 2026

    @zackees
    MemberAuthor

    Filed #3322 as a hard dependency on the channels/screenmap bridge.

    The proposal: type pin as fl::ArduinoPin (numeric int or symbolic "D0"/"A2"/"LED_BUILTIN") and use it as the implicit join key between fl::ScreenMap segments and fl::MultiChannelConfig channels. Without that bridge, fl::Fled::load(fled) here has to fall back to ordinal matching between the two arrays — which silently shears on any reorder and undermines the "drop one file, sketch self-instantiates" promise of the bundle format.

    Two specific gaps #3322 closes:

    1. screenmap.cpp.hpp already documents "pin": <int|str> (lines 104, 384) but the parser drops it — no read path, no field on ScreenMap, no accessor. A user writes "pin": "D0" today and it silently disappears.
    2. ChannelConfig::pin is int, so even if (1) were fixed there's no shared type to match against.

    The ArduinoPin value preserves the symbolic form across round-trips (good for WASM / studio), with opt-in .resolve() on target. Backwards compatible via implicit int ctor so existing addLeds<>(5, ...) call sites keep compiling unchanged.

  4. zackees commented on Jun 20, 2026

    @zackees
    MemberAuthor

    v1 implementation shipped (5 PRs)

    Five PRs landed end-to-end implementing the v1 subset of this issue:

    PR Scope
    #3323 fl::Fled PIMPL value + 3 load factories + raw json() / blob() accessors
    #3326 Typed section accessors (video() / screenMap() / channels() / script()) + fl::FledScript passive type
    #3327 FileSystem::sd(int) factory + FileSystem::loadFled(path) sugar
    #3328 Bidirectional fromFled factories on fl::Video / fl::ScreenMap / fl::MultiChannelConfig
    #3330 CFastLED::load / loadChannels / loadScreenMap

    Working today

    • fl::Fled::load(fs, path) / loadFromStatic(span) / loadFromVector(vec&&) parse .fled v1 bundles with strict header validation
    • fled.json() returns the parsed envelope; fled.blob("frame_payload", &n) returns the post-JSON bytes via aliasing shared_ptr
    • fled.screenMap() returns a real fl::ScreenMap parsed from the envelope's "map" key
    • fl::ScreenMap::fromFled(fled) works as a bidirectional spelling of the above
    • FileSystem::sd(cs_pin).loadFled("sketch.fled") is the canonical bundle-load idiom

    Stubbed (API surface only; bodies are follow-ups)

    • Fled::video() returns nullptr — needs a fl::Video::fromBytes integration in fl/fx/video.h
    • Fled::channels() returns nullptr — needs a JSON deserializer for fl::MultiChannelConfig in fl/channels/
    • Fled::script() returns nullptr — v1 bundles do not carry script sections
    • CFastLED::loadScreenMap(fled) emits FL_WARN_F — the controller-binding policy (all controllers vs first / default vs a controller-less EngineEvents API) is unresolved

    Out of scope for v1 (design-only)

    Per follow-up direction during implementation:

    • CFastLED::enableWasm() / enableMicroPy() — not shipped. The wasm host and MicroPython VM themselves remain a v2 concern; without them the public enable methods would only install no-op handlers, which would mislead users into believing the runtimes were available.
    • fl::detail::FledDispatcher singleton — initially built into PR5 but removed in c3ccacc2c once the enable methods were de-scoped. With nothing to install loaders, the dispatcher was dead code.
    • FxSdCard.ino migration — blocked by the Fled::video() and loadScreenMap() stubs; a migration today would degrade the example.
    • FileSystem::littleFs() / wasm() / host() static factories — each requires a working backend that is a much larger lift than the "sugar" framing of this issue; filed for follow-up.

    Follow-ups to file separately

    1. fl::Video::fromBytes(...) factory + Fled::video() body — unblocks the FxSdCard migration.
    2. JSON (de)serializer for fl::MultiChannelConfig + Fled::channels() body — unblocks bundle-driven multi-strip config.
    3. loadScreenMap() binding policy decision + body.
    4. FileSystem::littleFs/wasm/host backends.
    5. Wasm host + MicroPython VM runtime hosts (longer-horizon v2).

    🤖 Authored with Claude Code

  5. zackees commented on Aug 20, 2026

    @zackees
    MemberAuthor

    Deferred under the active bug-burn-down policy after reconciling the issue body, the five original PRs, and the later scope-reset PR #3334 with current master.

    What is complete:

    Why this umbrella is not complete today:

    Restart criteria:

    1. Resolve feat(screenmap/channels): bridge ScreenMap and ChannelConfig via typed ArduinoPin (number | string) #3322 or choose a different stable screenmap/channel join key.
    2. Amend this issue to the post-refactor(fl/fled): focus on header/json/blob/objects + FledBuilder + full FLED_FORMAT.md spec coverage (#3311) #3334 scope, with the removed runner/video/script/backend items either explicitly canceled or split into bounded children.
    3. Specify and land the ChannelConfig/MultiChannelConfig JSON schema in FastLED and the canonical ledmapper spec.
    4. Replace the Fled::channels() null stub with a tested real deserializer.
    5. Remove deferred only after that narrowed acceptance is authoritative.

    The issue remains open as the umbrella record and is excluded from the actionable queue while labeled deferred.

  6. added
    deferred
    on Aug 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    deferred

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions