# Audio Handling Improvement Advice ## High Impact 1. Prevent heap growth and fragmentation during song changes. - Current behavior allocates new audio source objects for each play request. - Improvement: centralize ownership of playback objects and always stop and release old objects before creating new ones. 2. Separate end-of-track from decode error. - Current behavior treats any failed loop step as a reason to restart playback. - Improvement: classify playback outcomes into Running, Ended, and Error, and only auto-repeat when explicitly enabled. 3. Remove blocking serial work from decoder callbacks. - Current behavior prints ID3 data character-by-character and flushes serial from callback context. - Improvement: keep callback logging minimal, avoid flush in hot paths, and buffer logs where possible. 4. Model real playback state instead of a single software flag. - Current behavior uses one flag for amplifier state and decision flow. - Improvement: expose states such as Idle, Starting, Playing, Stopping, Error, and base transitions on decoder status plus requested state. 5. Validate song input before playback starts. - Current behavior starts playback when filename is non-empty. - Improvement: verify file exists in LittleFS, return reason codes for missing file, invalid path, or decoder start failure. ## Medium Impact 1. Introduce an AudioManager command queue. - Use commands like Play(file), Stop, Pause, SetGain. - This decouples game logic timing from decoder timing and reduces race-like behavior. 2. Register callbacks once during audio initialization. - Avoid repeated callback registration on every play request unless dynamic callback context is required. 3. Make playback policy configurable. - Add options such as RepeatMode, ErrorRetryLimit, and RetryBackoffMs in settings. 4. Add runtime telemetry. - Track counters for starts, stops, open failures, decode errors, and loop overruns. - This improves observability and simplifies field debugging. ## Suggested Implementation Order 1. Add explicit cleanup path for current playback objects. 2. Introduce a playback result enum and stop auto-restart on all errors. 3. Reduce callback logging overhead. 4. Add explicit AudioManager states and update game transitions. 5. Add configuration flags for repeat and retry policy. ## Affected Areas in Code - src/audio.cpp - src/audio.h - src/game.cpp - src/config.cpp and data/settings.json (for new policy options)