Skip to content

MoodRing: room-sensing lighting toy — AnimartrixRing + NoiseRing engines, mood-aware orchestrator #2256

Open

Description

@zackees

AnimartrixRing: replace time-warp-only audio response with a 3-state sound orchestrator

Summary

examples/AnimartrixRing/AnimartrixRing.ino is audio-reactive today, but only in the narrow sense that bass changes FxEngine speed.

That is visible, but it is not compelling on a ring.

The current interaction is effectively:

audio -> vibe.bass -> time warp

instead of:

audio -> classify sound environment -> choose visual behavior -> apply beat/energy/spectrum mapping

Relevant code:

  • examples/AnimartrixRing/AnimartrixRing.ino:139-159
  • examples/AnimartrixRing/AnimartrixRing.ino:197-199
  • src/fl/fx/fx_engine.cpp.hpp:96-145
  • src/fl/audio/audio_processor.h:69-178

Problem

Time warp is a good accent, but it is weak as the entire audio model.

Current shortcomings:

  • the same visual just runs faster or slower
  • silence has no intentional visual state
  • chaotic noise can still look "reactive" without feeling musical
  • beat confidence is not separated from general energy
  • bass dominates while mids, treble, spectrum, and rhythm structure are ignored

On a ring, this reads as "motion intensity" rather than "musical understanding."

Expected behavior

The top-level orchestrator should classify the sound environment into three states:

  1. silence
  2. disorganized_sound
  3. bpm_locked_sound

And each state should use a different visual strategy.

flowchart LR
    A[Audio Input] --> B{Silent?}
    B -- yes --> S[Silence]
    B -- no --> C{Tempo stable and beat confidence high?}
    C -- no --> D[Disorganized Sound]
    C -- yes --> R[BPM Locked Sound]

    S --> S1[Calm ambient visuals]
    D --> D1[Energy and spectrum visuals]
    R --> R1[Beat-synced ring visuals]
Loading

Audio expectations

On beat

  • clear kick or validated beat should produce visible pulse events
  • downbeats should feel larger than ordinary beats
  • beat-locked visuals should not activate without rhythm confidence

On energy

  • loudness should affect density, contrast, and brightness
  • rising energy should feel different from falling energy
  • non-rhythmic sound should still produce interesting visuals without pretending to be on-beat

Why FastLED already supports this

The detector surface is already there:

  • Silence can define the idle state
  • EnergyAnalyzer can drive density and contrast
  • EqualizerDetector can drive spectrum-texture behavior
  • Vibe can provide self-normalizing band accents
  • TempoAnalyzer and MusicalBeat can decide when BPM lock is trustworthy
  • Percussion can separate kick, snare, and hat accents

References:

  • src/fl/audio/detector/silence.h
  • src/fl/audio/detector/equalizer.h
  • src/fl/audio/detector/vibe.h
  • src/fl/audio/detector/musical_beat_detector.h

Proposed redesign

State 1: silence

Use ambient visuals:

  • SLOW_FADE
  • WATER
  • PARAMETRIC_WATER
  • FLUFFY_BLOBS

Behavior:

  • low speed
  • restrained brightness
  • no hard flashes
  • slow palette drift

State 2: disorganized_sound

Use energy and spectrum visuals:

  • RGB_BLOBS5
  • WAVES
  • POLAR_WAVES
  • COMPLEX_KALEIDO

Behavior:

  • bass changes size or radial pressure
  • mids steer hue or rotation
  • treble adds sparkle or edge activity
  • equalizer bins shape sectors or texture
  • time warp is allowed, but secondary

State 3: bpm_locked_sound

Use beat geometry:

  • RINGS
  • CHASING_SPIRALS
  • SPIRALUS
  • CENTER_FIELD

Behavior:

  • kick or validated beat emits ring pulses
  • downbeat changes palette or phase
  • snare adds contrasting flash
  • hi-hat adds fine shimmer
  • BPM sets pulse cadence, not just raw engine speed

Concrete ask

Please redesign AnimartrixRing so that:

  1. it classifies audio into silence, disorganized_sound, and bpm_locked_sound
  2. each class selects different Animartrix visual families
  3. beat, energy, and spectrum map to different visual dimensions
  4. time warp remains available, but stops being the primary behavior
  5. transitions use hysteresis and minimum dwell times so the state machine does not chatter

Example mapping bank

Signal State Visual result
isSilent() silence breathing ambient drift
energy disorganized_sound density and contrast increase
eq.bass disorganized_sound stronger radial expansion
eq.mid disorganized_sound hue travel and rotation bias
eq.treble disorganized_sound sparkle or edge glitter
vibe.bassSpike bpm_locked_sound pulse ring emission
kick bpm_locked_sound thick bright impact
snare bpm_locked_sound secondary color hit
downbeat bpm_locked_sound palette reset or major phase change
measurePhase bpm_locked_sound smooth motion between beats

Acceptance criteria

  • silence looks intentional, not dead
  • random noise does not fake beat sync
  • stable BPM visibly locks the ring into a pulse grammar
  • mids and treble matter, not just bass
  • different songs produce different visual behavior, not just different speed

Context

Related: #2193 is the broader audio reactive enhancement thread.

This issue is narrower: AnimartrixRing specifically needs a stronger top-level orchestration model because "bass -> time warp" is not compelling enough as the core interaction.

Activity

  1. zackees commented on Apr 15, 2026

    @zackees
    MemberAuthor

    Field report after reviewing the issue against MilkDrop, Winamp, Shadertoy, and the fragcoord.xyz ecosystem (I could not verify fragcord.xyzl as a real host, so I am assuming that reference meant fragcoord.xyz).

    Executive take

    The issue direction is correct, but the strongest precedent from mature audio-reactive systems is even more specific:

    time-warp-only is almost never the core abstraction.

    The durable pattern is:

    audio transport -> analysis bus -> preset/mapping layer -> visual composition

    The key gap in AnimartrixRing is not missing audio input. It is missing the middle layer that turns audio into multiple visual controls.

    1. What MilkDrop actually does

    MilkDrop is the clearest precedent for the current FastLED Vibe approach.

    Important patterns from the original preset authoring model:

    • MilkDrop exposes bass, mid, treb and also bass_att, mid_att, treb_att.
    • Presets have a programmable mapping layer: per-frame equations, per-vertex equations, custom waves/shapes, and separate WARP vs COMPOSITE shader stages.
    • Presets can carry computed state across stages through q1-q32.
    • The system mixes continuous controls like zoom, rot, warp, dx, dy, decay, gamma, and waveform parameters instead of reducing music to a single scalar.

    Why this matters here:

    • MilkDrop does not treat bass as "just speed".
    • It treats audio bands as a control bus for motion, geometry, color, decay, waveform rendering, and feedback.
    • The *_att variables are especially important because they let the preset distinguish instantaneous energy from smoothed trend. That is how you get punch without noise chatter.

    FastLED already mirrors this idea in Vibe: self-normalized bass/mid/treb plus spike logic based on rising energy. The missed opportunity is that AnimartrixRing only uses that rich signal to call fxEngine.setSpeed(...).

    2. What Winamp got right at the platform level

    The older Winamp visualization interface is simpler than MilkDrop, but it made one architectural decision that still matters:

    • visualization plugins receive waveform and spectrum buffers directly
    • transport is separate from rendering
    • different plugins can build radically different visual grammars on top of the same audio feed

    The vis.h interface exposes both spectrumData[2][576] and waveformData[2][576] for stereo channels. That means the platform did not force plugins into one interpretation of audio. Scope, spectrum analyzer, AVS, and MilkDrop could all coexist because the host handed over broad audio state, not a single beat flag.

    Why this matters here:

    • AnimartrixRing should behave more like a visualization module on top of an analysis bus.
    • FastLED already has this bus in Processor, Equalizer, Vibe, tempo, percussion, silence, etc.
    • The redesign should consume multiple signals and choose a visual grammar per sound class, not just modulate one parameter.

    3. What ShaderToy contributes

    ShaderToy?s contribution is not "better beat detection." It is a better mental model for media-driven shaders:

    • inputs are generic channels (iChannel0..3) with time and resolution metadata
    • shaders can read audio as sampled data, not just callbacks
    • sound can also be an output target via mainSound() returning stereo vec2

    The official ShaderToy input/output docs show that sound sits in the same general interface as textures and buffers: iChannelResolution, iChannelTime, iSampleRate, sampler2D iChannel{i}, and sound shaders output stereo via mainSound().

    The best community technical writeup on ShaderToy audio textures adds the practical detail:

    • audio comes in as a texture-like buffer
    • one row is waveform samples
    • another row is FFT
    • buffering and sync are system-dependent, so na?ve full-wave redraws can drift

    Why this matters here:

    • audio should be thought of as a field that can drive spatial structure, not just a single event source
    • disorganized_sound should likely behave more like ShaderToy audio-texture usage: sample spectrum continuously and map it into sectors, edges, radial pressure, hue, and shimmer
    • bpm_locked_sound can then layer discrete beat grammar on top of that continuous field

    4. What fragcoord.xyz / Fragcolor add

    Assuming the intended reference was fragcoord.xyz, the interesting lesson is not one specific audio algorithm but the authoring environment:

    • the Shadertoy-unofficial ecosystem describes fragcoord.xyz as adding infinite buffers, external textures, custom uniforms with GUI, includes, and stronger debug tooling
    • Fragcolor?s docs expose DSP building blocks like DSP.FFT, which explicitly turns time-domain audio into frequency-domain data

    Why this matters here:

    • mature shader ecosystems win by making the analysis-to-render mapping inspectable and tweakable
    • a ring visualizer benefits from explicit intermediate controls: spectral bins, radial envelopes, trigger lanes, palette lanes, decay lanes
    • the best next step for AnimartrixRing is not only more detectors; it is a better authorable mapping layer between detectors and visuals

    5. Common design patterns across all four systems

    These systems keep converging on the same ideas:

    1. Audio is multi-dimensional.

      • waveform, spectrum, band energy, transients, tempo, and persistence are all used
    2. Continuous and discrete reactions are separated.

      • continuous: motion, hue drift, blur, density, decay
      • discrete: beat pulse, downbeat reset, snare flash, hi-hat sparkle
    3. Visual identity is preserved across songs.

      • the preset does not become a random machine just because input changed
      • the preset has a stable grammar, and audio perturbs that grammar
    4. Feedback/decay layers are central.

      • trails, blur, echo, composite, persistence, accumulation
      • these make beats feel musical instead of binary
    5. There is always an authoring/mapping layer.

      • equations, shaders, uniforms, FFT textures, custom params, state variables

    That is the main precedent backing this issue.

    6. Implications for AnimartrixRing

    This suggests a more precise redesign target than the current issue text alone:

    A. Keep the 3-state orchestrator

    Still the right top level:

    • silence
    • disorganized_sound
    • bpm_locked_sound

    B. Add a visual control bus

    Instead of one scalar (speed), derive a small stable set of control signals, for example:

    • transport_speed
    • radial_pressure
    • rotation_bias
    • palette_drift
    • sparkle_density
    • decay_amount
    • pulse_strength
    • sector_emphasis_low
    • sector_emphasis_mid
    • sector_emphasis_high

    Then let the orchestrator map detectors into that bus per state.

    C. Use MilkDrop-style relative vs attenuated logic

    Concrete recommendation:

    • use vibe.bass - vibe.bass_att style deltas for beat punch
    • use vibe.mid / vibe.treb for continuous texture changes
    • use tempo confidence and musical-beat validation only to permit the BPM-locked grammar

    D. Separate continuous fields from event triggers

    Suggested split:

    • continuous field: equalizer bins + energy + vibe relative levels
    • event layer: kick, validated beat, downbeat, snare, hi-hat

    E. Do not force stock Animartrix to do all the work through time scaling

    At the moment the sketch uses stock Animartrix and samples it onto the ring, but the Animartrix draw path itself is not consuming the richer DrawContext::audio path. That suggests two realistic implementation directions:

    1. keep stock Animartrix selections, but add a ring-side compositor/overlay layer that reacts to beat/spectrum
    2. add custom audio-aware Animartrix viz or factory overrides so the visual itself can respond to the audio bus

    Direction 2 is closer to how MilkDrop actually feels compelling.

    7. Practical recommendations to add to this issue

    I think the issue should implicitly aim for the following deliverables:

    • a SoundClass state machine with hysteresis and dwell time
    • a small intermediate "visual control bus" derived from FastLED audio features
    • at least one continuous spectrum-based mode for disorganized_sound
    • at least one event-driven pulse grammar for bpm_locked_sound
    • either a ring overlay compositor or custom audio-aware Animartrix viz hooks

    If this lands, the result should stop feeling like "the same preset at a different speed" and start feeling like an actual visualizer.

    Sources

    Primary / near-primary:

    Useful community technical references:

    Relevant repo context:

    • src/fl/audio/detector/vibe.h
    • src/fl/audio/README.md
    • examples/AnimartrixRing/AnimartrixRing.ino
  2. zackees commented on Apr 15, 2026

    @zackees
    MemberAuthor

    Concrete implementation plan for AnimartrixRing.ino, based on the field report.

    Scope

    Target: improve examples/AnimartrixRing/AnimartrixRing.ino without requiring a full FastLED audio architecture rewrite.

    The plan is staged so the first pass lands quickly and the later passes deepen the visual language.

    Phase 1: add a sound-class state machine

    Add a small orchestrator layer in the sketch or a helper pair such as:

    • examples/AnimartrixRing/audio_orchestrator.h
    • examples/AnimartrixRing/audio_orchestrator.cpp

    Core types:

    enum class SoundClass {
        Silence,
        DisorganizedSound,
        BpmLockedSound,
    };
    
    struct VisualControlBus {
        float transportSpeed;
        float radialPressure;
        float rotationBias;
        float paletteDrift;
        float sparkleDensity;
        float decayAmount;
        float pulseStrength;
        float lowBand;
        float midBand;
        float highBand;
    };

    Classifier inputs should come from existing Processor APIs:

    • isSilent() / getSilenceDuration()
    • getTempoBPM() / getTempoConfidence()
    • getBeatConfidence()
    • isVibeBassSpike() and spike density over a short window
    • isKick() / isSnare() / isHiHat()
    • getEqBass() / getEqMid() / getEqTreble()
    • getEnergy() / getPeakLevel()

    State logic:

    • enter Silence after sustained silence with hysteresis
    • enter BpmLockedSound only when tempo confidence and beat confidence stay high for a dwell window
    • otherwise use DisorganizedSound
    • use minimum dwell times to prevent rapid state chatter

    Phase 2: replace bass -> speed only with a control bus

    Right now the sketch effectively does:

    • vibe.bass -> fxEngine.setSpeed()

    That should become:

    • audio features -> VisualControlBus
    • SoundClass + VisualControlBus -> visual policy

    Recommended bus derivation:

    • transportSpeed: base speed plus restrained contribution from vibe.bass - vibe.bass_att
    • radialPressure: mostly bass / low EQ
    • rotationBias: mid energy and maybe measure phase if available
    • paletteDrift: mid + treble + tempo
    • sparkleDensity: treble + hi-hat / treble-spike activity
    • decayAmount: inverse of energy in ambient mode, shorter on beat-locked mode
    • pulseStrength: kick / validated beat / downbeat layer

    This is the most important change. It introduces the missing mapping layer that MilkDrop-style systems rely on.

    Phase 3: assign visual families per state

    Recommended stock Animartrix mapping for the first implementation:

    Silence

    Primary candidates:

    • SLOW_FADE
    • WATER
    • PARAMETRIC_WATER
    • FLUFFY_BLOBS

    Policy:

    • low speed
    • low contrast
    • slow palette drift
    • no hard pulse overlay

    DisorganizedSound

    Primary candidates:

    • RGB_BLOBS5
    • WAVES
    • POLAR_WAVES
    • COMPLEX_KALEIDO

    Policy:

    • bass changes pressure/scale
    • mids steer hue/rotation
    • treble adds edge shimmer/sparkle
    • equalizer bands shape sector brightness or overlay accents
    • time warp remains secondary

    BpmLockedSound

    Primary candidates:

    • RINGS
    • CHASING_SPIRALS
    • SPIRALUS
    • CENTER_FIELD

    Policy:

    • beat emits obvious ring pulse
    • kick is primary pulse event
    • snare is a secondary accent
    • hi-hat is fine texture/glitter
    • BPM controls pulse cadence and decay timing

    Phase 4: add a ring-side overlay compositor

    Before writing custom Animartrix viz, add a lightweight post-process overlay on the 1D ring output.

    This can be done entirely in the sketch after fxEngine.draw(...) and before FastLED.show().

    Suggested overlays:

    • expanding pulse ring on kick / validated beat
    • sector emphasis for low/mid/high energy groups
    • transient glitter on treble spikes / hi-hat
    • downbeat palette flash or color inversion pulse

    Why this phase is valuable:

    • it produces obvious beat grammar immediately
    • it does not require modifying core Animartrix internals
    • it lets us prove the control bus before building deeper custom viz

    Phase 5: add custom audio-aware Animartrix hooks if needed

    If stock animation selection + overlay still feels shallow, then use:

    • Animartrix::setVizFactory(...)
    • or Animartrix::setCustomViz(...)

    to build a small number of audio-aware ring-friendly variants.

    Best first candidates:

    • audio-aware RINGS
    • audio-aware CHASING_SPIRALS
    • audio-aware RGB_BLOBS5

    Those should consume the control bus directly rather than inferring everything from ctx.now.

    Concrete file-level change list

    First pass implementation should likely touch:

    • examples/AnimartrixRing/AnimartrixRing.ino
    • optionally examples/AnimartrixRing/audio_reactive.{h,cpp} or replace it with a more explicit orchestrator helper
    • optionally add examples/AnimartrixRing/audio_orchestrator.{h,cpp}
    • optionally add a tiny overlay helper such as examples/AnimartrixRing/ring_overlay.{h,cpp}

    I would avoid touching core src/fl/audio/* or core Animartrix in the first pass unless we prove a missing API.

    Suggested UI controls

    Add a few explicit controls so the behavior is tunable:

    • Enable Audio Orchestrator
    • Silence Hold Ms
    • Beat Lock Threshold
    • Beat Lock Hold Ms
    • Pulse Strength
    • Sparkle Amount
    • Overlay Blend
    • Auto Select Visuals Per State

    That will make the feature much easier to tune in the browser preview.

    Acceptance targets for implementation

    The first implementation should be considered successful if:

    • silence visibly becomes an intentional ambient state
    • noise / speech / random transients stay in DisorganizedSound
    • strong rhythmic music can lock into BpmLockedSound
    • bass, mids, and treble clearly do different things
    • there is at least one visible event-driven layer beyond speed changes

    Recommended order of work

    1. add SoundClass + hysteresis + dwell timing
    2. add VisualControlBus
    3. map detectors into the bus
    4. add state-based animation family selection
    5. add ring overlay pulses/sparkle/sectors
    6. only then decide whether custom Animartrix viz are still needed

    RGB asset

    Assuming "rgb data" meant the current Animartrix RGB_BLOBS* source bundle, I zipped that set here:

    Release page:

    That zip currently contains:

    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs.h
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs.cpp.hpp
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs2.h
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs2.cpp.hpp
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs3.h
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs3.cpp.hpp
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs4.h
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs4.cpp.hpp
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs5.h
    • src/fl/fx/2d/animartrix_detail/viz/rgb_blobs5.cpp.hpp

    If a different RGB asset was intended, say which one and I can swap the bundle.

  3. added
    area: core
    status: triage
    on Apr 16, 2026
  4. zackees commented on Apr 18, 2026

    @zackees
    MemberAuthor

    Expanded design: state machine, control bus, and overlay compositor

    Follow-up to the earlier field report and phased plan. This comment fills in the parts that were still hand-wavy: exact transition rules, the bus derivation formulas, the overlay compositor, the available visual set verified against the actual AnimartrixAnim enum, and a landable PR split.

    All APIs referenced are confirmed against the current tree (src/fl/audio/audio_processor.h, src/fl/audio/detector/vibe.h, src/fl/fx/2d/animartrix.hpp, src/fl/fx/fx_engine.h, examples/AnimartrixRing/AnimartrixRing.ino).


    1. Verified animation set

    AnimartrixAnim only exposes one RGB-blob variant (RGB_BLOBS5) despite the asset zip containing rgb_blobs..rgb_blobs5. The reachable set is:

    RGB_BLOBS5, POLAR_WAVES, SLOW_FADE, SPIRALUS2, SPIRALUS,
    CENTER_FIELD, WAVES, CHASING_SPIRALS, RINGS, COMPLEX_KALEIDO,
    COMPLEX_KALEIDO_2..6, WATER, PARAMETRIC_WATER, FLUFFY_BLOBS
    

    Gotcha to flag in the PR that lands Phase 3: if we want RGB_BLOBS / _2 / _3 / _4 in rotation we have to extend the enum + registry table. Otherwise the disorganized-sound family is {RGB_BLOBS5, WAVES, POLAR_WAVES, COMPLEX_KALEIDO*}.


    2. State machine — precise definition

    enum class SoundClass : u8 {
        Silence,
        DisorganizedSound,
        BpmLockedSound,
    };
    
    struct SoundClassifierConfig {
        // Silence entry / exit
        u32 silenceEnterMs       = 1200;   // must be silent this long to enter
        u32 silenceExitMs        = 120;    // any audio for this long exits
    
        // BPM lock entry / exit (asymmetric — hard to lock, easy to lose)
        float tempoConfEnter     = 0.65f;
        float beatConfEnter      = 0.55f;
        u32   lockEnterMs        = 2500;   // both must hold for this long
        float tempoConfExit      = 0.40f;
        float beatConfExit       = 0.30f;
        u32   lockExitMs         = 800;
    
        // Minimum dwell after any transition (anti-chatter)
        u32 minDwellMs           = 1500;
    };

    Transition diagram (guards evaluated per frame):

                      silenceEnterMs sustained
             ┌────────────────────────────────────┐
             │                                    ▼
       ┌──────────┐  audio > silenceExitMs  ┌──────────────┐
       │ Silence  │◀───────────────────────▶│ Disorganized │
       └──────────┘                         └──────────────┘
                                                  │  ▲
                        tempoConf ≥ enter   &&    │  │  tempoConf < exit OR
                        beatConf  ≥ enter    &&   │  │  beatConf  < exit
                        sustained lockEnterMs     ▼  │  sustained lockExitMs
                                            ┌──────────────┐
                                            │  BpmLocked   │
                                            └──────────────┘
    

    Rules:

    • Silence ↔ BpmLocked is not a legal direct edge — must pass through Disorganized. This keeps the UX coherent (ambient → energized → locked) and avoids a "silent to pulse-grid" jarring cut.
    • minDwellMs applies to every state, including re-entry. Guards the common pattern where tempo confidence oscillates around threshold.
    • On entry to Silence: trigger cross-fade, not hard cut.
    • On entry to BpmLocked: latch current BPM as the dwell target, resist tempo jitter for one measure.

    Driver signals (all already on Processor):

    • isSilent(), getSilenceDuration()
    • getTempoConfidence(), getTempoBPM()
    • getBeatConfidence(), getDownbeatConfidence()
    • getMeasurePhase(), getCurrentBeatNumber()

    3. Visual control bus — derivation

    The bus is the stable authoring surface. State changes which inputs feed which outputs; the consumers (Animartrix family + overlay) only read the bus, never the raw detectors. This is the MilkDrop "q1..q32" analogue — one intermediate layer so visuals don't churn every time the audio pipeline changes.

    struct VisualControlBus {
        // Continuous (smoothed, every frame)
        float transportSpeed;   // [0.1 .. 4.0]  FxEngine::setSpeed
        float radialPressure;   // [0.0 .. 1.0]  inward/outward bias
        float rotationBias;     // [-1.0 .. 1.0] clockwise vs counter
        float paletteDrift;     // [0.0 .. 1.0]  rate of hue travel
        float sparkleDensity;   // [0.0 .. 1.0]  treble-driven shimmer
        float decayAmount;      // [0.0 .. 1.0]  post-process persistence
        float lowBand;          // [0.0 .. 1.0]  smoothed low energy
        float midBand;
        float highBand;
    
        // Event lane (rising-edge flags, consumed-and-cleared per frame)
        float pulseStrength;    // 0 when no pulse, else 0.2..1.0
        bool  pulseIsDownbeat;
        bool  snareAccent;
        bool  hihatTick;
    };

    Derivation formulas (30 Hz target; all inputs from Processor getters):

    // Relative-vs-attenuated delta — the "punch" signal, MilkDrop-style.
    float bassPunch = fl::max(0.0f, p.getVibeBass() - p.getVibeBassAtt());
    float midPunch  = fl::max(0.0f, p.getVibeMid()  - p.getVibeMidAtt());
    float trebPunch = fl::max(0.0f, p.getVibeTreb() - p.getVibeTrebAtt());
    
    // Continuous bands (clip + soft-knee to 0..1)
    bus.lowBand  = softKnee(p.getEqBass());
    bus.midBand  = softKnee(p.getEqMid());
    bus.highBand = softKnee(p.getEqTreble());
    
    // Transport speed: base + bounded bass contribution. Clamped hard so a
    // transient can't fling the engine into unusable speed.
    bus.transportSpeed = clamp(
        baseSpeed + k_speedGain * bassPunch,
        0.1f, 4.0f);
    
    // Radial pressure: weighted bass with slow release
    bus.radialPressure = envFollow(
        0.7f * bus.lowBand + 0.3f * bassPunch,
        attack=15ms, release=220ms);
    
    // Rotation bias: mid drives direction; measure phase adds periodicity in BPM lock
    bus.rotationBias = (bus.midBand - 0.5f) * 2.0f;
    if (state == BpmLocked)
        bus.rotationBias += 0.3f * sinf(2 * PI * p.getMeasurePhase());
    
    // Palette drift: combined mid+treb + small tempo contribution
    bus.paletteDrift = 0.5f * bus.midBand + 0.35f * bus.highBand
                     + 0.15f * (p.getTempoBPM() / 180.0f);
    
    // Sparkle density: treble spikes + hihat ticks
    bus.sparkleDensity = envFollow(
        0.6f * trebPunch + 0.4f * (p.isHiHat() ? 1.0f : 0.0f),
        attack=5ms, release=180ms);
    
    // Decay: high in ambient (long trails), low in BPM lock (crisp beats)
    bus.decayAmount = (state == Silence)      ? 0.85f :
                      (state == BpmLocked)    ? 0.35f : 0.60f;
    
    // Event lane — only populated in BpmLocked; Disorganized uses continuous fields.
    if (state == BpmLocked) {
        if (p.isKick())      { bus.pulseStrength = 1.00f; }
        else if (onValidatedBeat()) { bus.pulseStrength = 0.60f; }
        bus.pulseIsDownbeat = (p.getCurrentBeatNumber() == 1);
        bus.snareAccent     = p.isSnare();
        bus.hihatTick       = p.isHiHat();
    }

    softKnee and envFollow are ~10 lines each; no new dep.


    4. Per-state policy

    Bus signal Silence Disorganized BpmLocked
    transportSpeed 0.25 (fixed) base + 0.8*bassPunch base locked to BPM÷120, 0.4*bassPunch
    radialPressure slow breathing LFO lowBand weighted clamped, driven by pulse event
    paletteDrift 0.05 (fixed) mid+treb weighted step on downbeat, else 0
    sparkleDensity 0 treble-punch driven hihat-driven
    decayAmount 0.85 0.60 0.35
    pulseStrength 0 0 kick/beat event
    Animation family SLOW_FADE, WATER, PARAMETRIC_WATER, FLUFFY_BLOBS RGB_BLOBS5, WAVES, POLAR_WAVES, COMPLEX_KALEIDO RINGS, CHASING_SPIRALS, SPIRALUS, CENTER_FIELD
    Family rotation every 60s every 45s on 4th downbeat of family

    Cross-fade: when Animartrix::fxSet(...) switches (either on family change or on family rotation), blend over 800 ms in ambient / disorganized, snap on downbeat in BpmLocked.


    5. Overlay compositor

    Runs after fxEngine.draw(millis(), leds) and before FastLED.show(). No core changes; purely post-process on the 1D ring.

    struct RingOverlay {
        // Persistence layer — a CRGB shadow buffer that fades each frame.
        // Creates MilkDrop-style trails on top of the Animartrix base layer.
        CRGB trail[NUM_LEDS];
    
        void apply(CRGB* leds, const VisualControlBus& bus, u32 nowMs);
    
    private:
        void compositeTrails(CRGB* leds, float decay);
        void emitPulse(CRGB* leds, float strength, bool downbeat);
        void applySectorEmphasis(CRGB* leds, float lo, float mid, float hi);
        void sprinkleSparkle(CRGB* leds, float density);
    };

    Four lightweight passes:

    1. Trails — trail[i] = scale8(trail[i], 255*(1-decayAmount)) + leds[i]>>2; blend back onto leds. Gives the feedback echo that makes beats feel musical.
    2. Pulse ring — on pulseStrength > 0, paint an expanding Gaussian band that starts at the "12 o'clock" index (configurable origin) and widens k*elapsed pixels. Downbeats use a wider band + palette flip.
    3. Sector emphasis — split ring into three 120° arcs; boost brightness in each by {lowBand, midBand, highBand}*k. Disorganized-only; off in the other two states. Makes the three frequency bands audibly localized on the physical ring.
    4. Sparkle — random indices flipped to palette-white with probability sparkleDensity * dt. Ring-side only; doesn't touch Animartrix internals.

    Each pass is opt-in via UI (see §7) so the user can disable any layer without recompiling.


    6. File-level diff plan

    examples/AnimartrixRing/
      AnimartrixRing.ino                  (EDIT: wire orchestrator + bus + overlay)
      audio_reactive.h / .cpp             (KEEP: legacy path, gated by UI toggle)
      audio_orchestrator.h                (NEW: SoundClass + SoundClassifier)
      audio_orchestrator.cpp              (NEW)
      visual_control_bus.h                (NEW: struct + derivation fn)
      visual_control_bus.cpp              (NEW)
      ring_overlay.h                      (NEW)
      ring_overlay.cpp                    (NEW)
    

    No changes to src/fl/audio/* or src/fl/fx/2d/animartrix* in Phase 1–4. Custom audio-aware vizzes (Phase 5) get their own follow-up issue.


    7. UI schema

    [Orchestrator]
      ☐ Enable Sound Orchestrator         (default off — preserves legacy path)
      [dropdown] Manual Sound Class       (Auto / Silence / Disorganized / BpmLocked)
    
    [State Machine Tuning]
      Silence Enter Ms       500..5000   default 1200
      BPM Lock Enter Ms      500..8000   default 2500
      BPM Lock Tempo Conf    0..1        default 0.65
      BPM Lock Beat  Conf    0..1        default 0.55
      Min Dwell Ms           200..3000   default 1500
    
    [Visual Control Bus]
      Base Speed             0..4        default 1.0
      Bass Punch Gain        0..3        default 1.5
      Palette Drift Gain     0..2        default 1.0
    
    [Overlay]
      ☐ Trails (decay layer)              on
      ☐ Pulse Ring                        on (only active in BpmLocked)
      ☐ Sector Emphasis                   on (only active in Disorganized)
      ☐ Sparkle                           on
      Pulse Origin Offset    0..NUM_LEDS  default 0
      Trail Decay Override   0..1        default -1 (use bus value)
    
    [Debug]
      ☐ Print Sound Class transitions
      ☐ Print Bus every N frames
    

    All controls use existing fl::UICheckbox / fl::UISlider / fl::UIDropdown — no new UI primitives.


    8. Landable PR split

    Each PR is independently mergeable and demonstrably better than master.

    1. PR-A — orchestrator skeleton + UI toggle. SoundClass + classifier + "Manual Sound Class" override. Doesn't yet affect visuals; just prints transitions to Serial. Demo: silence → clap → noise → music — transitions log out.
    2. PR-B — visual control bus + transport speed only. Replace bass→speed with bus.transportSpeed derivation. Behavior equivalent to legacy, but routed through the bus. Demo: flip Enable Orchestrator off/on — visuals identical.
    3. PR-C — per-state animation family + cross-fade. State change → family rotation; hard-cut forbidden. Demo: song start → disorganized family; silence → ambient family.
    4. PR-D — overlay compositor (trails + sparkle). Non-event overlays only. Demo: same anim, visibly more alive.
    5. PR-E — event-driven pulse ring + sector emphasis. The payoff. Demo: metronome / kick-heavy track produces visible ring pulses, mid-heavy track lights the mid sector.
    6. PR-F (optional) — custom audio-aware Animartrix viz. Only if PR-A..E still feel shallow.

    9. Test / validation harness

    The sketch is hard to test end-to-end, but we can verify the classifier and bus in the existing C++ test framework without hardware.

    tests/test_sound_classifier.cpp     → feed canned Processor mock states,
                                          assert expected SoundClass output
                                          over a simulated timeline.
    
    tests/test_visual_control_bus.cpp   → feed canned VibeLevels + Equalizer
                                          reads, assert bus values in range
                                          and track expected monotonicity.
    

    Manual acceptance (matches §8 of the issue body):

    • Dead silence enters Silence within ~1.2 s; output is dim and breathing, not frozen.
    • Whispering / random noise stays in Disorganized — never false-locks.
    • Metronome at 120 BPM locks within ~3 s and stays locked; ring emits visible pulses on the click.
    • Bass-heavy track → strong radial pressure, low sparkle.
    • Treble-heavy track → strong sparkle, minimal radial.
    • Song end → graceful fall through Disorganized → Silence within ~3 s, no jarring cut.

    10. Risks / non-goals

    • Not rewriting Animartrix internals. All audio-awareness lives in the sketch layer; Animartrix stays a time-driven viz.
    • No stereo. Processor is mono today and that's fine for a ring.
    • Tempo-lock latency is real. TempoAnalyzer needs multiple beats to warm up. lockEnterMs=2500 respects this; don't shorten it below ~2 s.
    • Overlay compute budget. ~244 LEDs × 4 passes = negligible on ESP32, but the trail buffer is an extra NUM_LEDS*3 bytes. Document in comments.
    • Legacy path must keep working. Existing users with Enable Vibe Reactive on shouldn't regress. Orchestrator is opt-in until PR-E lands; then it becomes the default with a "Legacy Mode" escape hatch.
  5. zackees commented on Apr 18, 2026

    @zackees
    MemberAuthor

    Progressive WASM + Playwright test plan

    Follow-up to the expanded design. The goal here is concrete: a per-PR test gate so compile and runtime errors surface one at a time as the orchestrator is built up, and each PR is blocked from landing until its gate is green.

    Why this works

    Two existing pieces do almost everything we need:

    1. fastled CLI — fastled examples/AnimartrixRing compiles the sketch to WASM, serves it over HTTP, and prints the port a browser can attach to. Flags we actually use: --just-compile (no browser; Gate C), --serve-dir fastled_js (serve an already-built tree; all later gates), --no-interactive (CI-safe), --debug (instrumentation build).

    2. ci/wasm_audio_drag_drop_test.py — the existing Playwright harness:

      • launches headless Chromium with --autoplay-policy=no-user-gesture-required
      • forces ScriptProcessor (Playwright doesn't drive AudioWorklet)
      • captures all browser console logs + page errors
      • already has example-specific hooks for Vibe:, AnimartrixRing:, BASS SPIKE, etc.
      • supports drag-and-drop MP3 loading, checkbox toggling, stall detection
      • exposes globalThis.fastLEDFrameCount for liveness

    The new work is a thin progressive driver that calls fastled for the compile+serve side and re-uses the Playwright harness for the browser side. No bespoke HTTP server, no custom compile wrapper — the existing tools already cover it.


    1. Gate pyramid — compile errors surface first, then runtime, then behavior

    Each PR graduates through a pyramid of gates. The test harness short-circuits at the first failing gate so the fix loop is tight.

            ╔════════════════════════════════════════╗
     Gate E ║ Event  — kick/beat → observable pulse  ║
            ╠════════════════════════════════════════╣
     Gate V ║ Visual — LED buffer diffs per state    ║
            ╠════════════════════════════════════════╣
     Gate B ║ Bus    — control bus values valid      ║
            ╠════════════════════════════════════════╣
     Gate S ║ State  — SoundClass transitions right  ║
            ╠════════════════════════════════════════╣
     Gate U ║ UI     — new controls rendered in DOM  ║
            ╠════════════════════════════════════════╣
     Gate R ║ Runtime — frames tick, no page errors  ║
            ╠════════════════════════════════════════╣
     Gate C ║ Compile — bash compile wasm builds     ║
            ╚════════════════════════════════════════╝
    

    Each gate is a ~30-150 line Python function. They stack: running a higher gate implicitly runs every gate below it.

    Gate C — Compile

    def gate_compile(example_dir: Path, debug: bool = True) -> GateResult:
        cmd = ["fastled", str(example_dir), "--just-compile", "--no-interactive"]
        if debug:
            cmd.append("--debug")   # enables FL_TEST_INSTRUMENT
        proc = run(cmd, capture_output=True, timeout=600)
        if proc.returncode != 0:
            err = extract_first_error(proc.stderr)
            return Fail(
                gate="compile",
                summary=f"{err.file}:{err.line}: {err.message[:120]}",
                suggestion=suggest_file_to_look_at(err, stage),
                full_log=proc.stderr,
            )
        return Pass(gate="compile")

    extract_first_error parses clang++ output and returns the first error only, with the file path clipped to repo-relative, and all subsequent errors dropped. This is the part that makes "fix compile errors one at a time" actually pleasant: the output is one error, one file, one line — not 2000 lines of cascade.

    The gate caches by source hash: if examples/AnimartrixRing/ hasn't changed since the last green build, skip fastled and reuse fastled_js/. Cuts the inner loop from ~60s to ~2s when iterating Python-side.

    Gate R — Runtime

    Serve the already-built tree with fastled --serve-dir in a background process, parse the printed port, point Playwright at it:

    proc = popen(["fastled", "--serve-dir",
                  str(example_dir / "fastled_js"),
                  "--no-interactive", "--no-https"],
                 stdout=PIPE)
    port = wait_for_port_line(proc)           # parse "serving on http://localhost:PORT"
    page = await browser.new_page()
    await page.goto(f"http://localhost:{port}")

    Then:

    • wait for fastLEDFrameCount > 0 within 10s
    • scrape page.on("pageerror") — zero errors required
    • scrape window._workerErrors — zero required
    • assert setup complete log fired

    Output: per-error stack traces with scripts/wasm_symbolicate.py decode so crashes point at real C++ files, not WASM offsets.

    One fastled --serve-dir process is spun up once per test run and re-used across gates — Playwright just opens fresh pages against the same server. That amortizes the ~2s serve-bootstrap cost.

    Gate U — UI controls rendered

    Reads the DOM and asserts the orchestrator's UI elements exist:

    async def gate_ui(page, expected_controls):
        found = await page.evaluate("""(() => {
            const labels = [...document.querySelectorAll('label')]
                .map(l => l.textContent.trim());
            return labels;
        })()""")
        missing = [c for c in expected_controls if c not in found]
        if missing:
            return Fail(gate="ui", summary=f"Missing UI controls: {missing}")

    This catches silently-removed fl::UISlider declarations, typos in control names, and wiring regressions.

    Gate S — State machine

    Requires the sketch to emit one-line JSON log events in a debug build:

    #if FL_TEST_INSTRUMENT
    printf("FL_TEST: {\"k\":\"state\",\"from\":\"%s\",\"to\":\"%s\",\"ms\":%u}\n",
           stateName(prev), stateName(next), millis());
    #endif

    Playwright collects them:

    state_events = [parse_json(m) for m in all_console_logs if "FL_TEST:" in m]

    Then the gate runs one canned audio fixture at a time and asserts the timeline. Example:

    async def gate_state_bpmlock(page):
        await feed_fixture(page, "metronome_120.wav")
        events = await monitor_for(page, seconds=8)
        classes = [e["to"] for e in events if e["k"] == "state"]
        assert classes[-1] == "BpmLocked", f"expected BpmLocked, got {classes}"
        # Lock must not occur in less than 2s (respect tempo warmup)
        lock_time = next(e["ms"] for e in events if e["to"] == "BpmLocked")
        assert lock_time >= 2000, f"locked too fast: {lock_time}ms"

    Gate B — Control bus

    Same JSON channel, different key:

    #if FL_TEST_INSTRUMENT
    if (frameCount % 30 == 0) {
        printf("FL_TEST: {\"k\":\"bus\",\"lo\":%.3f,\"mi\":%.3f,\"hi\":%.3f,"
               "\"sp\":%.3f,\"rp\":%.3f,\"sd\":%.3f,\"pulse\":%.3f}\n",
               bus.lowBand, bus.midBand, bus.highBand,
               bus.transportSpeed, bus.radialPressure, bus.sparkleDensity,
               bus.pulseStrength);
    }
    #endif

    Gate assertions are boring but effective:

    # No bus value ever leaves its declared range.
    for e in bus_events:
        assert 0.0 <= e["lo"] <= 1.0
        assert 0.1 <= e["sp"] <= 4.0
    # Bus actually responds to audio.
    assert max(e["lo"] for e in bus_events) - min(e["lo"] for e in bus_events) > 0.1
    # Silence clamps pulseStrength to 0.
    silence_events = [e for e in bus_events if state_at(e["ms"]) == "Silence"]
    assert all(e["pulse"] == 0 for e in silence_events)

    Gate V — Visual

    Expose a peek helper in the WASM frontend JS (already the pattern for fastLEDFrameCount):

    globalThis.fastLEDPeekLeds = () => new Uint8Array(Module.HEAPU8.buffer,
                                                       ledsPtr, NUM_LEDS * 3);

    Gate compares the buffer across states:

    async def gate_visual_state_diff(page):
        await feed_fixture(page, "silence.wav")
        await wait_for_state(page, "Silence")
        buf_silence = await page.evaluate("Array.from(fastLEDPeekLeds())")
    
        await feed_fixture(page, "noise.wav")
        await wait_for_state(page, "DisorganizedSound")
        buf_noise = await page.evaluate("Array.from(fastLEDPeekLeds())")
    
        # The two states must produce visibly different output.
        diff = sum(abs(a - b) for a, b in zip(buf_silence, buf_noise))
        assert diff > NUM_LEDS * 10, "state change didn't change visuals"

    No golden-image comparison — just "visuals actually differ." Goldens rot; difference-over-threshold doesn't.

    Gate E — Event-driven pulse

    Needs temporal correlation. Metronome at 120 BPM → a kick every 500ms → pulse should land within ±50ms.

    async def gate_event_pulse_on_kick(page):
        await feed_fixture(page, "metronome_120.wav")
        kick_events = await monitor_events(page, "kick", seconds=10)
        pulse_events = await monitor_events(page, "pulse", seconds=10)
        # For each kick, find a pulse within ±50ms.
        unmatched = 0
        for k in kick_events:
            if not any(abs(p["ms"] - k["ms"]) < 50 for p in pulse_events):
                unmatched += 1
        assert unmatched / len(kick_events) < 0.2, \
            f"{unmatched}/{len(kick_events)} kicks had no pulse within 50ms"

    2. Per-PR gate matrix

    Each PR lands with a test target that calls exactly the gates it should satisfy. Higher PRs subsume lower-PR gates so regressions are caught immediately.

    PR Scope C R U S B V E
    PR-A Orchestrator skeleton + UI ✓ ✓ ✓ ✓
    PR-B Visual control bus ✓ ✓ ✓ ✓ ✓
    PR-C Per-state animation family ✓ ✓ ✓ ✓ ✓ ✓
    PR-D Overlay: trails + sparkle ✓ ✓ ✓ ✓ ✓ ✓
    PR-E Event-driven pulse + sectors ✓ ✓ ✓ ✓ ✓ ✓ ✓
    PR-F Custom audio-aware viz (opt) ✓ ✓ ✓ ✓ ✓ ✓ ✓

    Command surface:

    # Run everything up to and including PR-A's gates
    uv run ci/animartrix_ring/progressive_test.py --stage pr-a
    
    # Same but headed (visible Chromium) — debug mode
    uv run ci/animartrix_ring/progressive_test.py --stage pr-c --headed
    
    # Force rebuild the WASM target even if cache is warm
    uv run ci/animartrix_ring/progressive_test.py --stage pr-b --clean
    
    # Run a single gate in isolation (rare; for drill-down)
    uv run ci/animartrix_ring/progressive_test.py --gate state

    Wire the highest-PR gate as bash test animartrix_ring_e2e in CI. Local dev runs --stage pr-X for whatever they're building.


    3. Deterministic audio fixtures

    No user-supplied MP3. Generate WAVs at test time from Python so the tests are reproducible on any machine:

    ci/animartrix_ring/fixtures/
      generate_fixtures.py         # numpy + soundfile
      silence.wav                  # 6s of zeros (44.1kHz mono)
      noise.wav                    # 6s white noise, RMS 0.15
      metronome_120.wav            # 6s of 100ms kick-shaped clicks @ 120 BPM
      metronome_90.wav             # 6s @ 90 BPM — verify tempo tracking
      sweep.wav                    # 6s 50Hz → 12kHz log sweep — per-band validation
      mixed.wav                    # noise + metronome → disorganized → bpmlocked
      dropout.wav                  # music → silence at 3s — state exit test
    

    generate_fixtures.py is tiny (~60 lines of numpy). These ship with the test; no binary assets in the repo until they're a problem. Output lives under ci/animartrix_ring/fixtures/cache/ and is gitignored; generator runs on first invocation.

    The existing harness's page.route("**/SoundHelix*", handle_soundhelix) pattern intercepts the fetch and serves the generated bytes — same mechanism, different source.

    For fixtures that need precise timing (metronome), the generator puts a synchronized marker channel in the log (FL_TEST: {"k":"fixture","click_at_ms":[500,1000,1500,...]}) that Gate E uses as ground truth.


    4. Instrumentation contract

    The sketch is #if FL_TEST_INSTRUMENT-guarded. The macro is defined only in a debug build produced by fastled examples/AnimartrixRing --just-compile --debug with FL_TEST_INSTRUMENT=1 in the sketch's build defines. Prod / quick builds pay zero cost.

    Stable JSON shape so parsers don't drift:

    FL_TEST: {"k":"state","from":"Silence","to":"Disorganized","ms":3421}
    FL_TEST: {"k":"bus","ms":3450,"lo":0.42,"mi":0.31,"hi":0.18,
              "sp":1.2,"rp":0.55,"sd":0.1,"pulse":0.0}
    FL_TEST: {"k":"event","type":"kick","ms":3500,"strength":0.82}
    FL_TEST: {"k":"event","type":"pulse","ms":3512,"strength":1.0,
              "downbeat":false}
    FL_TEST: {"k":"family","from":"RGB_BLOBS5","to":"RINGS","ms":3600}
    

    One-line JSON is chosen over binary for two reasons: (a) the existing harness already tails console logs, (b) when a test fails the log excerpt is human-readable in the PR comment.


    5. The fix loop

    What this buys when implementing PR-B (the visual control bus):

    $ uv run ci/animartrix_ring/progressive_test.py --stage pr-b
    [1/7] Gate C — Compile .................. FAIL
        visual_control_bus.cpp:42:5: no member named 'softKnee' in namespace 'fl'
        → look at: examples/AnimartrixRing/visual_control_bus.cpp
    

    Fix, re-run:

    $ uv run ci/animartrix_ring/progressive_test.py --stage pr-b
    [1/7] Gate C — Compile ................... PASS (cached)
    [2/7] Gate R — Runtime ................... FAIL
        Page error: TypeError: Cannot read properties of undefined (reading 'bus')
        First error at frame 7. Last logs:
          [log] AnimartrixRing: setup complete
          [error] Uncaught TypeError ...
        → look at: examples/AnimartrixRing/AnimartrixRing.ino line ~175 (loop)
    

    Fix, re-run:

    $ uv run ci/animartrix_ring/progressive_test.py --stage pr-b
    [1/7] Gate C — Compile ................... PASS (cached)
    [2/7] Gate R — Runtime ................... PASS
    [3/7] Gate U — UI controls ............... PASS
    [4/7] Gate S — State machine ............. PASS
    [5/7] Gate B — Control bus ............... FAIL
        bus.lowBand never exceeded 0.05 on noise.wav (expected range > 0.1)
        → possible cause: EQ bands not piped into bus, or softKnee too aggressive
        → look at: examples/AnimartrixRing/visual_control_bus.cpp:derive()
    

    That's the entire dev loop. Each run surfaces one actionable failure with a file pointer. You don't need to read 2000 lines of clang output or a wall of async-stack traces — the gate printed the single sentence that matters.


    6. File layout

    ci/animartrix_ring/
      progressive_test.py           # entry point; selects stage, runs gates
      gates/
        __init__.py
        base.py                     # GateResult, Pass, Fail
        compile.py                  # Gate C
        runtime.py                  # Gate R
        ui.py                       # Gate U
        state.py                    # Gate S
        bus.py                      # Gate B
        visual.py                   # Gate V
        event.py                    # Gate E
      fixtures/
        generate_fixtures.py
        cache/                      # gitignored
      harness.py                    # thin wrapper over wasm_audio_drag_drop_test
      parse.py                      # FL_TEST JSON parser + error extraction
    

    harness.py re-uses ~70% of the existing Playwright code — browser launch, add_init_script audio-worklet disable, console-log routing, and worker-error monitoring. The HTTP server layer is replaced by a fastled --serve-dir subprocess with port auto-discovery. New code is focused on orchestration and JSON parsing, not plumbing.


    7. CI integration

    One job per stage, running in parallel:

    animartrix_ring_progressive:
      strategy:
        matrix:
          stage: [pr-a, pr-b, pr-c, pr-d, pr-e]
      steps:
        - run: uv run ci/animartrix_ring/progressive_test.py --stage ${{ matrix.stage }}

    Until a PR lands, stages beyond its scope are allowed to fail — the matrix job is marked continue-on-error: true for stages above the current HEAD's implemented level. As PRs merge, the gate they satisfy flips to required.

    This creates a forcing function: PR-D's gate includes Gate V, so PR-D cannot merge if its visuals regress per-state behavior. PR-E's gate adds Gate E, so pulse timing is enforced the moment the feature lands, not "someday."


    8. Non-goals

    • Not a replacement for the C++ unit tests in tests/test_sound_classifier.cpp / tests/test_visual_control_bus.cpp. Those run in host builds, are millisecond-fast, and catch pure-logic regressions. This Playwright suite is the end-to-end contract; the C++ tests are the classifier/bus contract.
    • Not a perceptual/UX tester. We're asserting "visuals change between states" and "a pulse happens near a beat," not "the output looks compelling." Perceptual tuning is a human job — this keeps the plumbing honest so human tuning isn't chasing regressions.
    • Not a timing regression tracker. Frame-rate stability is checked loosely (not stalled) but not precisely. If someone doubles the loop cost, this suite won't catch it — that's for bash profile.
  6. zackees commented on Apr 18, 2026

    @zackees
    MemberAuthor

    Product framing: The "Mood Ring" — a lighting toy that senses the room

    Reframing this thread. AnimartrixRing isn't the goal; it's one of two visual engines inside a lighting toy that senses the room it's in and paints a light response to the room's mood. The WASM demo is where patches get composed, and the best ones get promoted to firmware presets on a shippable device.

    The input isn't "music." The input is the room — whatever it sounds like. Music, yes. But also: conversation, silence, laughter, a vacuum cleaner running, a thunderstorm outside, a dog barking, someone cooking. The toy's identity is that it notices what the room is doing and lights back accordingly, not that it drops beats.

    This comment pins down: product scope, engine abstraction, mood→visual mapping, the playground UX, the patch/preset/product promotion flow, and the test additions needed to keep the whole thing honest.


    1. Product vision — one sentence

    A 244-LED ring that listens to the room and lights the room back.

    Input: ambient mic, passively listening. Output: a ring of light whose motion, color, density, and pulse reflect the sound environment the ring is in — not a light show you drive, but a companion that reads the room's mood.

    Concrete rooms it should feel good in:

    • Empty house, no sound → dim ambient breath, slow hue drift. Never dead-looking, never flashy.
    • Dinner, conversation murmur, no music → warm slow noise, low brightness, gentle hue drift — reactive enough that you see the room is "alive."
    • Kids running around, toy sirens, clatter → high-arousal, slightly chaotic disorganized visuals, brighter palette.
    • Tense argument or harsh noise → cool desaturated palette, flicker, lower brightness — mirrors the room's energy without amplifying it.
    • Song comes on with clear beat → ring locks to BPM, emits pulse rings on the kick, sector emphasis on bass/mid/treble.
    • Sudden silence after music → graceful fall through disorganized → silence over ~3 s, not a jarring cut.

    No buttons, no app required, no WiFi required. Optional BLE for patch uploading from a phone.

    The room is the instrument. The toy is the listener.


    2. Input hierarchy — four layers, three already built

      ┌───────────────┐
      │ Mic (I2S/ADC) │   physical input
      └───────┬───────┘
              │
      ┌───────▼───────────────────────────────────┐
      │ fl::audio::Processor                      │   ALREADY EXISTS
      │  - Silence, Energy, Equalizer             │
      │  - Tempo, Beat, Downbeat, Percussion      │
      │  - Vibe (MilkDrop-style normalized bands) │
      │  - MoodAnalyzer (valence, arousal)        │
      └───────┬───────────────────────────────────┘
              │
      ┌───────▼──────────────────────────────────┐
      │ Orchestrator (NEW — this issue)          │
      │  - SoundClass {silence/disorganized/lock}│
      │  - VisualControlBus (10 signals)         │
      │  - Mood-quadrant bias                    │
      └───────┬──────────────────────────────────┘
              │
      ┌───────▼──────────────────────────────────┐
      │ Engine (pluggable, both consume the bus) │
      │  ├─ AnimartrixRing (expressive)          │
      │  └─ NoiseRing     (organic, cheap)       │
      └──────────────────────────────────────────┘
    

    Already shipped: the bottom two layers. MoodAnalyzer gives us valence ∈ [-1,1] and arousal ∈ [0,1] with a 4-quadrant category (calm_positive, calm_negative, energetic_positive, energetic_negative + neutral). That's the product's emotional axis.

    New work: the orchestrator and the engine abstraction. Everything in the prior designs still applies — it just gets a second consumer (NoiseRing) and a new input (Mood).


    3. Two engines behind one bus

    The VisualControlBus from the prior design maps naturally to both the Animartrix FxEngine and fill_2dnoise16 parameters (from examples/NoisePlayground/). That means a single patch format can drive either engine:

    Bus signal AnimartrixRing consumer NoiseRing consumer
    transportSpeed FxEngine::setSpeed time_speed
    radialPressure anim-specific (see PR-F viz) xscale/yscale inverse
    rotationBias via measure-phase overlay x_speed/y_speed delta
    paletteDrift palette crossfade rate hue_time speed
    sparkleDensity overlay-layer sparkle overlay-layer sparkle
    decayAmount trail compositor trail compositor
    lowBand/mid/high sector overlay sector overlay
    pulseStrength expanding ring overlay expanding ring overlay

    The overlay compositor is engine-agnostic — it runs on the 1D ring buffer after the engine writes it. So trails, pulse, sector, sparkle cost one implementation, not two.

    Engine switch policy. The orchestrator picks the engine based on mood quadrant (§4), or honors a manual override in the playground. Cross-fade on switch (~800 ms), not hard cut.


    4. Mood quadrant → visual identity

    The 4-quadrant map turns MoodAnalyzer into a design surface. Each quadrant gets a visual identity — engine choice, palette family, motion character — that's unmistakably different from its neighbors.

                      HIGH AROUSAL
                           │
       ENERGETIC_NEGATIVE  │  ENERGETIC_POSITIVE
       ─────────────────── │ ──────────────────
       engine: Noise       │  engine: Animartrix
       palette: cold sat   │  palette: warm vivid
       motion: high-octave │  motion: RINGS,
         flicker, desat    │    SPIRALUS, pulse
       overlay: sparkle    │  overlay: pulse+sector
                           │
        LOW V  ────────────┼────────────  HIGH V
                           │
       CALM_NEGATIVE       │  CALM_POSITIVE
       ─────────────────── │ ──────────────────
       engine: Animartrix  │  engine: Noise
       palette: cool muted │  palette: warm pastel
       motion: SLOW_FADE,  │  motion: soft drift,
         WATER, low speed  │    slow hue wander
       overlay: trails     │  overlay: trails
                           │
                       LOW AROUSAL
    

    Mood is smoothed with hysteresis already (setMinDuration(ms) on MoodAnalyzer), so this won't flip-flop. A mood transition triggers the same 800 ms cross-fade as an engine switch.

    Important product constraint. Mood bias is a preference, not a hard switch. The SoundClass state machine from the prior design still decides silence vs disorganized vs bpm-locked. Mood only biases which visuals are used for each class. Silence still means silence.


    5. WASM playground — compose, compare, share

    The playground is a web page that:

    • auto-requests mic permission on load
    • renders the ring at 60 fps in a canvas
    • shows a live mood readout (valence/arousal dot moving in the quadrant grid)
    • exposes the full VisualControlBus as sliders, all 10 signals
    • lets the user switch engine (Animartrix / Noise) and animation
    • supports A/B compare: two patches side-by-side, same mic input
    • serializes the entire patch to a URL query param for sharing

    This sits on top of infrastructure that already exists:

    • Mic capture. src/platforms/wasm/compiler/modules/audio/audio_manager.ts already has a mic button wired through getUserMedia + createMediaStreamSource, feeding the same Processor the drag-drop path uses. No new JS. The sketch side just uses audio.audioInput() exactly like AnimartrixRing.ino does today.
    • UI primitives. fl::UISlider, fl::UICheckbox, fl::UIDropdown, fl::UIAudio already render to the browser DOM.
    • Frame preview. globalThis.fastLEDFrameCount and the LED buffer exposure are already in place from the audio-test harness.

    What's new on the playground side is a small set of UI affordances, not a new framework:

    ┌──────────────────────────────────────────────────────────────┐
    │  ⦿ Mic: ACTIVE  [stop]     Source: ⦿ Mic  ○ Fixture  ○ URL  │
    ├──────────────────────────────────────────────────────────────┤
    │  ╭──────────────────╮   Mood:  ENERGETIC_POSITIVE            │
    │  │     RING PREVIEW │   Valence: +0.42 ─────▶               │
    │  │    (244 LEDs)    │   Arousal:  0.71 ▲                    │
    │  │                  │   Class: BpmLocked  BPM: 124 ± 0.8    │
    │  ╰──────────────────╯                                        │
    │  Engine: ⦿ Animartrix ○ Noise   Anim: [RINGS ▼]             │
    ├──────────────────────────────────────────────────────────────┤
    │  ── VISUAL CONTROL BUS (live) ──                             │
    │  transportSpeed    ▇▇▇▇▇▇░░░░  1.42                          │
    │  radialPressure    ▇▇▇░░░░░░░  0.31                          │
    │  sparkleDensity    ▇░░░░░░░░░  0.08                          │
    │  … (7 more)                                                  │
    │                                                              │
    │  ── BUS GAINS (tunable) ──                                   │
    │  [slider: speed gain]   [slider: palette drift gain]  …     │
    │                                                              │
    │  ── OVERLAY ──                                               │
    │  ☑ Trails  ☑ Pulse  ☑ Sector  ☑ Sparkle                     │
    ├──────────────────────────────────────────────────────────────┤
    │  [Save Patch] [Copy Share URL] [Load Patch] [A/B Compare]   │
    │  [Promote to Preset: "warm-party"]                          │
    └──────────────────────────────────────────────────────────────┘
    

    6. Patch / preset / product — three tiers of permanence

      patch      ──┐                       ─ ephemeral, URL-shareable, any
      (JSON)       │                           combination of bus gains,
                   │                           engine choice, overlay flags
                   │
                   ▼   promote to preset
      preset     ──┐                       ─ named patch, lives in
      (C++ hdr)    │                           presets/*.h, ships with
                   │                           firmware
                   │
                   ▼   ship in firmware
      product    ──┘                       ─ device with 4-8 built-in
                                               presets + auto-select by
                                               mood quadrant
    

    Patch schema

    One JSON object, encoded base64 into ?patch=... on the playground URL:

    {
      "v": 1,
      "engine": "animartrix",
      "anim_manual": null,
      "classifier": {
        "silenceEnterMs": 1200,
        "lockEnterMs": 2500,
        "tempoConfEnter": 0.65,
        "minDwellMs": 1500
      },
      "bus_gains": {
        "speedGain": 1.5,
        "paletteDriftGain": 1.0,
        "radialGain": 1.0,
        "sparkleGain": 0.8
      },
      "overlay": {
        "trails": true,
        "pulse": true,
        "sector": true,
        "sparkle": true,
        "pulseOriginOffset": 0
      },
      "mood_bias": {
        "calm_positive":     {"engine": "noise",      "palette": "warm_pastel"},
        "calm_negative":     {"engine": "animartrix", "palette": "cool_muted", "anim_hints": ["WATER","SLOW_FADE"]},
        "energetic_positive":{"engine": "animartrix", "palette": "warm_vivid", "anim_hints": ["RINGS","SPIRALUS"]},
        "energetic_negative":{"engine": "noise",      "palette": "cold_sat"}
      }
    }

    Preset — promotion

    "Promote to preset" button serializes the patch as a constexpr C++ header:

    // presets/warm_party.h  (generated — do not edit)
    namespace fl { namespace mood_ring { namespace presets {
    constexpr Patch warm_party = {
        .engine = Engine::Animartrix,
        .classifier = { .silenceEnterMs=1200, /* ... */ },
        .bus_gains = { .speedGain=1.5f, /* ... */ },
        /* ... */
    };
    }}}

    Then it's code-reviewed and merged like any other C++ change. Presets are hand-curated; the playground is where they're discovered.

    Product — shipping

    Hardware envelope for the "great little product" end of the road:

    • MCU: ESP32-S3 (PSRAM + I2S mic)
    • Mic: INMP441 digital (I2S, simpler than analog)
    • LEDs: WS2812 244 ring (matches example's NUM_LEDS)
    • Power: USB-C PD, ~8 W typical / 14 W peak
    • Config: single button cycles presets; long-press = mood-auto; LED-based confirmation
    • Optional: BLE → phone app uploads a Patch JSON, device stores in NVS, survives reboot
    • No WiFi required. No cloud. Works on a countertop with just USB-C.

    Firmware ships with 4-8 curated presets + an auto preset that uses the mood quadrant to pick from the curated set. The playground is the R&D lab that produces those presets.


    7. Demo showstoppers — what makes the WASM playground memorable

    Ordered by "wow" per line of code:

    1. Instant mic. User lands on URL → mic prompt → within 2 seconds the ring is already responsive. No file upload, no setup. This is the hook.
    2. Live mood dot on the valence/arousal grid. Users see the mood being inferred. Pair with current-quadrant label + confidence bar. Mood-analysis is invisible without this readout.
    3. Engine cross-fade on toggle. Click Animartrix ⇄ Noise — smooth 800 ms blend, not a pop. This sells the "one bus, two engines" abstraction on one click.
    4. Whisper test. User whispers → Silence state → ambient breath. User shouts → Disorganized → energy visual. User plays music → BpmLocked → pulse. One progression, three obviously different behaviors.
    5. A/B compare with shared URL. Open ?patch=...&compare=... → two rings side-by-side, same mic, different patches. Instant demo of patch authoring.
    6. "Save as GIF / video" — record 5 s of the preview and let the user post it. Not core, but social spread is how products get traction.
    7. BPM match to a metronome. Clap a tempo → BPM readout locks to it within ~3 s → pulse overlay fires on each clap. This is the moment skeptics become believers.

    Each of these is a distinct acceptance criterion, and they tie back to specific progressive-test gates (see §8).


    8. Additions to the progressive test plan

    The earlier testing plan (Gates C/R/U/S/B/V/E) covers the orchestrator. The product framing adds three gates:

    Gate M — Mood

    async def gate_mood_quadrants(page):
        # 4 fixtures, one per quadrant, crafted to trip the corresponding mood:
        #   calm_positive.wav      → soft major pads, slow tempo
        #   calm_negative.wav      → slow minor pads, low brightness
        #   energetic_positive.wav → bright metronome + major chord
        #   energetic_negative.wav → dense noise + harsh transients
        for name, expected in FIXTURES:
            await feed_fixture(page, name)
            events = await monitor_events(page, "mood", seconds=8)
            # require at least 3s of sustained expected category
            assert sustained_category(events, expected, min_ms=3000)

    This is the gate that validates MoodAnalyzer is actually distinguishing quadrants in our sketch — not just in its unit tests.

    Gate P — Patch round-trip

    def gate_patch_roundtrip(page):
        patch_in = load_fixture_patch("warm_party.json")
        url = f"http://localhost:{port}?patch={b64encode(patch_in)}"
        page.goto(url)
        patch_out = json.loads(page.evaluate("JSON.stringify(window.currentPatch)"))
        assert patch_in == patch_out

    No runtime behavior check — just that the URL-encoded patch deserializes into the live state identically. Catches schema drift at merge time.

    Gate L — Live mic path

    Chromium supports --use-file-for-fake-audio-capture=<path>. Playwright sets it at browser launch; Chromium's getUserMedia then returns a stream that plays the WAV we generated. This exercises the entire mic pipeline end-to-end without needing a physical mic:

    browser = await p.chromium.launch(
        args=[
            "--autoplay-policy=no-user-gesture-required",
            "--use-fake-ui-for-media-stream",
            "--use-fake-device-for-media-stream",
            f"--use-file-for-fake-audio-capture={fixture_wav_path}",
        ],
    )
    context = await browser.new_context(permissions=["microphone"])
    page = await context.new_page()
    # Click the mic button in the UI; stream flows; rest of the assertions
    # are identical to the drag-drop test path.

    This is the gate that certifies the product's primary input path works in WASM — and by extension, the mic-driven firmware path will too (same Processor, same bus).

    Updated per-PR gate matrix

    PR Scope C R U S B V E M P L
    PR-A Orchestrator skeleton + UI ✓ ✓ ✓ ✓
    PR-B Visual control bus ✓ ✓ ✓ ✓ ✓
    PR-C Per-state animation family ✓ ✓ ✓ ✓ ✓ ✓
    PR-D Overlay compositor ✓ ✓ ✓ ✓ ✓ ✓
    PR-E Event pulse + sector ✓ ✓ ✓ ✓ ✓ ✓ ✓
    PR-F Mood bias + quadrant routing ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓
    PR-G NoiseRing engine + bus adapter ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓
    PR-H Patch schema + URL serialization ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓
    PR-I Mic path + playground UX polish ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓

    Each PR lands one capability, passes its row, and the next PR builds on green.


    9. File layout — what ends up in the tree

    examples/MoodRing/                       ← new, supersedes AnimartrixRing
      MoodRing.ino                           orchestrator + playground wiring
      mood_orchestrator.{h,cpp}              SoundClass + mood bias + patch
      visual_control_bus.{h,cpp}             the bus struct + derivation
      ring_overlay.{h,cpp}                   trails/pulse/sector/sparkle
      engine_animartrix_ring.{h,cpp}         Animartrix adapter (consumes bus)
      engine_noise_ring.{h,cpp}              fill_2dnoise16 adapter (consumes bus)
      patch.{h,cpp}                          JSON ⇄ Patch struct
      presets/
        warm_party.h                         generated from playground
        cool_focus.h
        late_night.h
        … (as many as curated)
    
    examples/AnimartrixRing/                 ← stays as-is; legacy, unchanged
    

    MoodRing is the product sketch; AnimartrixRing stays as the narrow-scope example. That way anyone wanting to understand "just Animartrix on a ring" has the simple version, and the product work happens in its own dir without entangling the example.

    No src/fl/* changes for PR-A through PR-G. PR-H (patch schema) adds a small src/fl/mood_ring/patch.h only if the schema ends up being generally useful beyond this sketch.


    10. Roadmap — playground to product

    Three milestones, tied to the PR plan:

    • M1: "The orchestrator is real." PR-A through PR-E merged. Gate E green. AnimartrixRing behaves as a 3-state mood-aware visualizer. Nothing branded yet.
    • M2: "The playground is real." PR-F through PR-I merged. Gate L green. Mic works in WASM, mood dot is live, engine toggle cross-fades, patches save/load via URL. This is the public-facing demo. Share the URL — users compose patches.
    • M3: "The product is real." 4-8 hand-curated presets promoted from M2's authoring sessions. A reference BOM (ESP32-S3 + INMP441 + 244 WS2812). Firmware ships with the curated preset set and auto-select. Optional BLE for phone patch uploads.

    M2 is the deliverable that makes this issue compelling to other people, not just to us. If a user lands on a URL, grants mic, and within 5 seconds sees a ring visibly responding to the room they're in — that's the shareable artifact. The product follows naturally from the patches that playground produces.


    11. What this doesn't promise

    • Not a music visualizer. Music is one of many things the room might contain. Conversation, silence, ambient noise, and chaos are equal-citizen inputs. Music-sync is a mode, not the identity.
    • Not a MIDI controller. No beat-drop sync to external sources, no DMX in/out, no Ableton Link. The identity is passive room sensing.
    • Not a "dance party light." If the room mode is calm, the toy is calm. It does not perform when there is no audience.
    • Not a perceptual-AI product. MoodAnalyzer is feature-based (spectral centroid + rolloff + flux + energy), not a neural model. That's a feature: runs in real-time on ESP32 with bounded memory, no cloud inference.
    • Not a surveillance device. Local mic → local inference → local light. Audio never leaves the device. No recording, no cloud, no account. Privacy-by-construction.
  7. changed the title [-]AnimartrixRing: replace time-warp-only audio response with a 3-state sound orchestrator[/-] [+]MoodRing: room-sensing lighting toy — AnimartrixRing + NoiseRing engines, mood-aware orchestrator[/+] on Apr 18, 2026
  8. zackees commented on Aug 17, 2026

    @zackees
    MemberAuthor

    Three corrections to this design, now that #3884 and #3886 have landed work against it. Flagging rather than editing in place so the history stays readable.

    1. §9 / §6 target the wrong directory. Both file plans put the orchestrator, control bus and overlay in examples/AnimartrixRing/. As of #3884 that work lives in examples/MoodRing/; AnimartrixRing was reduced to a pure Animartrix-sampling demo with no audio at all.

    This also supersedes §9's "examples/AnimartrixRing/ stays as-is; legacy, unchanged". Per maintainer direction the audio left AnimartrixRing entirely rather than being duplicated across both sketches — the technique demo stays minimal, the product sketch grows.

    2. §6's "audio_reactive.h / .cpp (KEEP: legacy path, gated by UI toggle)" is obsolete. Those files are deleted. #2809 superseded that path with the orchestrator and #3884 removed the dead code. §7's "Enable Sound Orchestrator — default off, preserves legacy path" follows: there is no legacy path, and MoodRing defaults the orchestrator on. A room-sensing toy that boots deaf is not the product.

    3. §1's enum gotcha is stale. It warns that only RGB_BLOBS5 is reachable and that rotating RGB_BLOBS/_2/_3/_4 requires extending the enum plus the registry table. AnimartrixAnim now carries all five (src/fl/fx/2d/animartrix.hpp:33-37), so that work is already done. Worth striking so nobody repeats it.

    Progress against the PR split:

    #3885 carries the detailed design for the #3886 increment, including the derivation formulas and why max(0, vibeBass - vibeBassAtt) is the signal that keeps loudness from faking a beat.

  9. zackees commented on Aug 20, 2026

    @zackees
    MemberAuthor

    Marking this umbrella roadmap deferred after a current-master audit. Merged PRs #2809, #3884, and #3886 delivered the classifier, MoodRing split, VisualControlBus, trails, and pulse rings, but the issue still spans multiple independent product phases: sector/sparkle consumers, mood-quadrant routing, a second NoiseRing engine with cross-fade, serialization/presets, and playground work. This is not one bounded burn-down change; the existing implementation remains usable while those roadmap phases await separate scope.

  10. added
    deferred
    and removed
    status: triage
    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

    area: coredeferred

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions