From 12816810855883472ecab454f9c0d08d66f0ae52 Mon Sep 17 00:00:00 2001 From: skal Date: Thu, 5 Feb 2026 20:18:28 +0100 Subject: feat(audio): Complete Task #56 - Audio Lifecycle Refactor (All Phases) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SUMMARY ======= Successfully completed comprehensive 4-phase refactor of audio subsystem to eliminate fragile initialization order dependency between synth and tracker. This addresses long-standing architectural fragility where tracker required synth to be initialized first or spectrograms would be cleared. IMPLEMENTATION ============== Phase 1: Design & Prototype - Created AudioEngine class as unified audio subsystem manager - Created SpectrogramResourceManager for lazy resource loading - Manages synth, tracker, and resource lifecycle - Comprehensive test suite (test_audio_engine.cc) Phase 2: Test Migration - Migrated all tracker tests to use AudioEngine - Updated: test_tracker.cc, test_tracker_timing.cc, test_variable_tempo.cc, test_wav_dump.cc - Pattern: Replace synth_init() + tracker_init() with engine.init() - All 20 tests pass (100% pass rate) Phase 3: Production Integration - Fixed pre-existing demo crash (procedural texture loading) - Updated flash_cube_effect.cc and hybrid_3d_effect.cc - Migrated main.cc to use AudioEngine - Replaced tracker_update() calls with engine.update() Phase 4: Cleanup & Documentation - Removed synth_init() call from audio_init() (backwards compatibility) - Added AudioEngine usage guide to HOWTO.md - Added audio initialization protocols to CONTRIBUTING.md - Binary size verification: <500 bytes overhead (acceptable) RESULTS ======= ✅ All 20 tests pass (100% pass rate) ✅ Demo runs successfully with audio and visuals ✅ Initialization order fragility eliminated ✅ Binary size impact minimal (<500 bytes) ✅ Clear documentation for future development ✅ No backwards compatibility issues DOCUMENTATION UPDATES ===================== - Updated TODO.md: Moved Task #56 to "Recently Completed" - Updated PROJECT_CONTEXT.md: Added AudioEngine milestone - Updated HOWTO.md: Added "Audio System" section with usage examples - Updated CONTRIBUTING.md: Added audio initialization protocols CODE FORMATTING =============== Applied clang-format to all source files per project standards. FILES CREATED ============= - src/audio/audio_engine.h (new) - src/audio/audio_engine.cc (new) - src/audio/spectrogram_resource_manager.h (new) - src/audio/spectrogram_resource_manager.cc (new) - src/tests/test_audio_engine.cc (new) KEY FILES MODIFIED ================== - src/main.cc (migrated to AudioEngine) - src/audio/audio.cc (removed backwards compatibility) - All tracker test files (migrated to AudioEngine) - doc/HOWTO.md (added usage guide) - doc/CONTRIBUTING.md (added protocols) - TODO.md (marked complete) - PROJECT_CONTEXT.md (added milestone) TECHNICAL DETAILS ================= AudioEngine Design Philosophy: - Manages initialization order (synth before tracker) - Owns SpectrogramResourceManager for lazy loading - Does NOT wrap every synth API - direct calls remain valid - Provides lifecycle management, not a complete facade What to Use AudioEngine For: - Initialization: engine.init() instead of separate init calls - Updates: engine.update(music_time) instead of tracker_update() - Cleanup: engine.shutdown() for proper teardown - Seeking: engine.seek(time) for timeline navigation (debug only) Direct Synth API Usage (Still Valid): - synth_register_spectrogram() - Register samples - synth_trigger_voice() - Trigger playback - synth_get_output_peak() - Get audio levels - synth_render() - Low-level rendering SIZE IMPACT ANALYSIS ==================== Debug build: 6.2MB Size-optimized build: 5.0MB Stripped build: 5.0MB AudioEngine overhead: <500 bytes (0.01% of total) BACKWARD COMPATIBILITY ====================== No breaking changes. Tests that need low-level control can still call synth_init() directly. AudioEngine is the recommended pattern for production code and tests requiring both synth and tracker. handoff(Claude): Task #56 COMPLETE - All 4 phases finished. Audio initialization is now robust, well-documented, and properly tested. The fragile initialization order dependency has been eliminated. Co-Authored-By: Claude Sonnet 4.5 --- tools/seq_compiler.cc | 173 +++++++++++++++++++++++++++++--------------------- 1 file changed, 102 insertions(+), 71 deletions(-) (limited to 'tools/seq_compiler.cc') diff --git a/tools/seq_compiler.cc b/tools/seq_compiler.cc index 3931e32..062acce 100644 --- a/tools/seq_compiler.cc +++ b/tools/seq_compiler.cc @@ -20,25 +20,29 @@ struct EffectEntry { struct SequenceEntry { std::string start_time; std::string priority; - std::string end_time; // Optional: -1.0f means "no explicit end" - std::string name; // Optional: human-readable name for Gantt charts + std::string end_time; // Optional: -1.0f means "no explicit end" + std::string name; // Optional: human-readable name for Gantt charts std::vector effects; }; std::string trim(const std::string& str) { size_t first = str.find_first_not_of(" \t"); if (std::string::npos == first) - return ""; // String is all whitespace, return empty string + return ""; // String is all whitespace, return empty string size_t last = str.find_last_not_of(" \t"); return str.substr(first, (last - first + 1)); } // Calculate adaptive tick interval based on timeline duration int calculate_tick_interval(float max_time) { - if (max_time <= 5) return 1; - if (max_time <= 40) return 2; - if (max_time <= 100) return 5; - if (max_time <= 200) return 10; + if (max_time <= 5) + return 1; + if (max_time <= 40) + return 2; + if (max_time <= 100) + return 5; + if (max_time <= 200) + return 10; return 20; } @@ -48,7 +52,8 @@ void generate_gantt_chart(const std::string& output_file, float bpm, const std::string& demo_end_time) { std::ofstream out(output_file); if (!out.is_open()) { - std::cerr << "Warning: Could not open Gantt chart output file: " << output_file << "\n"; + std::cerr << "Warning: Could not open Gantt chart output file: " + << output_file << "\n"; return; } @@ -70,7 +75,8 @@ void generate_gantt_chart(const std::string& output_file, const float time_scale = chart_width / max_time; out << "Demo Timeline Gantt Chart\n"; - out << "==============================================================================\n"; + out << "=====================================================================" + "=========\n"; out << "BPM: " << bpm << ", Duration: " << max_time << "s"; if (!demo_end_time.empty()) { out << " (explicit end)"; @@ -84,7 +90,8 @@ void generate_gantt_chart(const std::string& output_file, out << i; int spacing = (i < 10) ? 4 : (i < 100) ? 3 : 2; if (i + tick_interval <= max_time) { - for (int j = 0; j < spacing; ++j) out << " "; + for (int j = 0; j < spacing; ++j) + out << " "; } } out << "\n"; @@ -113,7 +120,7 @@ void generate_gantt_chart(const std::string& output_file, for (size_t seq_idx = 0; seq_idx < sorted_sequences.size(); ++seq_idx) { const auto& seq = sorted_sequences[seq_idx]; float seq_start = std::stof(seq.start_time); - float seq_end = seq_start; // Start at sequence start + float seq_end = seq_start; // Start at sequence start // Check if sequence has explicit end time if (seq.end_time != "-1.0") { @@ -140,8 +147,10 @@ void generate_gantt_chart(const std::string& output_file, int end_col = (int)(seq_end * time_scale); out << " "; for (int i = 0; i < chart_width; ++i) { - if (i >= start_col && i < end_col) out << "█"; - else out << " "; + if (i >= start_col && i < end_col) + out << "█"; + else + out << " "; } out << " (" << seq_start << "-" << seq_end << "s)\n"; @@ -169,7 +178,7 @@ void generate_gantt_chart(const std::string& output_file, if (i >= eff_start_col && i < eff_end_col) { out << "▓"; } else if (i >= start_col && i < end_col) { - out << "·"; // Show sequence background + out << "·"; // Show sequence background } else { out << " "; } @@ -189,7 +198,8 @@ void generate_gantt_chart(const std::string& output_file, } } - out << "==============================================================================\n"; + out << "=====================================================================" + "=========\n"; out << "Legend: █ Sequence ▓ Effect · Sequence background\n"; out << "Priority: Higher numbers render later (on top)\n"; @@ -199,11 +209,12 @@ void generate_gantt_chart(const std::string& output_file, // Generate HTML/SVG Gantt chart for timeline visualization void generate_gantt_html(const std::string& output_file, - const std::vector& sequences, - float bpm, const std::string& demo_end_time) { + const std::vector& sequences, float bpm, + const std::string& demo_end_time) { std::ofstream out(output_file); if (!out.is_open()) { - std::cerr << "Warning: Could not open HTML Gantt output file: " << output_file << "\n"; + std::cerr << "Warning: Could not open HTML Gantt output file: " + << output_file << "\n"; return; } @@ -230,7 +241,7 @@ void generate_gantt_html(const std::string& output_file, // Count total rows needed int total_rows = 0; for (const auto& seq : sequences) { - total_rows += 1 + seq.effects.size(); // 1 for sequence + N for effects + total_rows += 1 + seq.effects.size(); // 1 for sequence + N for effects } const int svg_height = margin_top + total_rows * row_height + 40; @@ -239,18 +250,22 @@ void generate_gantt_html(const std::string& output_file, out << "\n"; out << "Demo Timeline - BPM " << bpm << "\n"; out << "\n\n\n"; @@ -265,7 +280,8 @@ void generate_gantt_html(const std::string& output_file, out << " | Sequences: " << sequences.size() << "\n"; out << "\n\n"; - out << "\n"; + out << "\n"; // Draw time axis with adaptive tick interval const int tick_interval = calculate_tick_interval(max_time); @@ -276,15 +292,14 @@ void generate_gantt_html(const std::string& output_file, for (int t = 0; t <= (int)max_time; t += tick_interval) { int x = margin_left + (int)(t * time_scale); - out << " \n"; + out << " \n"; out << " " << t << "s\n"; + << "\" class=\"axis-label\" text-anchor=\"middle\">" << t + << "s\n"; // Draw vertical time markers - out << " \n"; + out << " \n"; } // Sort sequences by start time for better readability @@ -299,7 +314,7 @@ void generate_gantt_html(const std::string& output_file, for (size_t seq_idx = 0; seq_idx < sorted_sequences.size(); ++seq_idx) { const auto& seq = sorted_sequences[seq_idx]; float seq_start = std::stof(seq.start_time); - float seq_end = seq_start; // Start at sequence start + float seq_end = seq_start; // Start at sequence start if (seq.end_time != "-1.0") { seq_end = seq_start + std::stof(seq.end_time); @@ -314,15 +329,15 @@ void generate_gantt_html(const std::string& output_file, // Draw sequence bar out << " \n"; - out << " \n"; out << " SEQ@" << seq_start << "s"; if (!seq.name.empty()) { out << " \"" << seq.name << "\""; } - out << " [pri=" << seq.priority << "] (" - << seq_start << "-" << seq_end << "s)\n"; + out << " [pri=" << seq.priority << "] (" << seq_start << "-" << seq_end + << "s)\n"; out << " \n"; // Draw sequence label @@ -352,14 +367,15 @@ void generate_gantt_html(const std::string& output_file, out << " \n"; - out << " " << eff.class_name << " [pri=" << eff.priority << "] (" - << eff_start << "-" << eff_end << "s)" + out << " " << eff.class_name << " [pri=" << eff.priority + << "] (" << eff_start << "-" << eff_end << "s)" << (invalid ? " *** INVALID TIME RANGE ***" : "") << "\n"; out << " \n"; out << " " << eff.class_name << " [pri=" << eff.priority << "]" - << (invalid ? " ⚠" : "") << "\n"; + << "\" class=\"label effect\">" << eff.class_name + << " [pri=" << eff.priority << "]" << (invalid ? " ⚠" : "") + << "\n"; y_offset += row_height; } @@ -369,19 +385,26 @@ void generate_gantt_html(const std::string& output_file, out << " \n"; out << " \n"; - y_offset += 10; // Extra spacing after separator + << "\" style=\"stroke:#444444; stroke-width:1; " + "stroke-dasharray:4,2;\"/>\n"; + y_offset += 10; // Extra spacing after separator } } // Legend out << " \n"; - out << " \n"; - out << " Sequence\n"; - out << " \n"; - out << " Effect\n"; - out << " \n"; - out << " Invalid Time Range\n"; + out << " \n"; + out << " Sequence\n"; + out << " \n"; + out << " Effect\n"; + out << " \n"; + out << " Invalid Time Range\n"; out << "\n"; out << "
\n"; @@ -395,7 +418,8 @@ void generate_gantt_html(const std::string& output_file, } // Convert beat notation to time in seconds -// Supports: "64b" or "64" (beats), "32.0s" or "32.0" with decimal point (seconds) +// Supports: "64b" or "64" (beats), "32.0s" or "32.0" with decimal point +// (seconds) std::string convert_to_time(const std::string& value, float bpm) { std::string val = value; bool is_beat = false; @@ -408,7 +432,7 @@ std::string convert_to_time(const std::string& value, float bpm) { // Check for explicit 's' suffix (seconds) else if (!val.empty() && val.back() == 's') { val.pop_back(); - return val; // Already in seconds + return val; // Already in seconds } // If no suffix and no decimal point, assume beats else if (val.find('.') == std::string::npos) { @@ -421,18 +445,25 @@ std::string convert_to_time(const std::string& value, float bpm) { return std::to_string(time); } - return val; // Return as-is (seconds) + return val; // Return as-is (seconds) } int main(int argc, char* argv[]) { if (argc < 2) { - std::cerr << "Usage: " << argv[0] << " [output.cc] [--gantt=] [--gantt-html=]\n"; + std::cerr << "Usage: " << argv[0] + << " [output.cc] [--gantt=] " + "[--gantt-html=]\n"; std::cerr << "Examples:\n"; - std::cerr << " " << argv[0] << " assets/demo.seq src/generated/timeline.cc\n"; + std::cerr << " " << argv[0] + << " assets/demo.seq src/generated/timeline.cc\n"; std::cerr << " " << argv[0] << " assets/demo.seq --gantt=timeline.txt\n"; - std::cerr << " " << argv[0] << " assets/demo.seq --gantt-html=timeline.html\n"; - std::cerr << " " << argv[0] << " assets/demo.seq timeline.cc --gantt=timeline.txt --gantt-html=timeline.html\n"; - std::cerr << "\nIf output.cc is omitted, only validation and Gantt generation are performed.\n"; + std::cerr << " " << argv[0] + << " assets/demo.seq --gantt-html=timeline.html\n"; + std::cerr << " " << argv[0] + << " assets/demo.seq timeline.cc --gantt=timeline.txt " + "--gantt-html=timeline.html\n"; + std::cerr << "\nIf output.cc is omitted, only validation and Gantt " + "generation are performed.\n"; return 1; } @@ -460,8 +491,8 @@ int main(int argc, char* argv[]) { std::vector sequences; SequenceEntry* current_seq = nullptr; - float bpm = 120.0f; // Default BPM - std::string demo_end_time = ""; // Demo end time (optional) + float bpm = 120.0f; // Default BPM + std::string demo_end_time = ""; // Demo end time (optional) std::string line; int line_num = 0; @@ -508,8 +539,8 @@ int main(int argc, char* argv[]) { std::string start_time = convert_to_time(start, bpm); // Check for optional "name" and [end_time] - std::string end_time_str = "-1.0"; // Default: no explicit end - std::string seq_name = ""; // Default: no name + std::string end_time_str = "-1.0"; // Default: no explicit end + std::string seq_name = ""; // Default: no name // Read remaining tokens std::string rest_of_line; @@ -520,17 +551,17 @@ int main(int argc, char* argv[]) { while (rest_ss >> token) { if (token.front() == '"') { // Name in quotes: read until closing quote - std::string name_part = token.substr(1); // Remove opening quote + std::string name_part = token.substr(1); // Remove opening quote if (name_part.back() == '"') { // Complete name in single token - name_part.pop_back(); // Remove closing quote + name_part.pop_back(); // Remove closing quote seq_name = name_part; } else { // Multi-word name: read until closing quote seq_name = name_part; while (rest_ss >> token) { if (token.back() == '"') { - token.pop_back(); // Remove closing quote + token.pop_back(); // Remove closing quote seq_name += " " + token; break; } @@ -542,8 +573,8 @@ int main(int argc, char* argv[]) { std::string time_value = token.substr(1, token.size() - 2); end_time_str = convert_to_time(time_value, bpm); } else { - std::cerr << "Error line " << line_num - << ": Unexpected token '" << token << "'. Expected \"name\" or [end_time]\n"; + std::cerr << "Error line " << line_num << ": Unexpected token '" + << token << "'. Expected \"name\" or [end_time]\n"; return 1; } } @@ -566,7 +597,8 @@ int main(int argc, char* argv[]) { // Validate priority modifier if (priority_mod != "+" && priority_mod != "=" && priority_mod != "-") { std::cerr << "Error line " << line_num - << ": Priority modifier must be '+', '=', or '-', got: " << priority_mod << "\n"; + << ": Priority modifier must be '+', '=', or '-', got: " + << priority_mod << "\n"; return 1; } @@ -585,9 +617,9 @@ int main(int argc, char* argv[]) { // Handle first effect in sequence if (first_in_sequence) { if (priority_mod == "-") { - current_priority = -1; // Background layer + current_priority = -1; // Background layer } else { - current_priority = 0; // Default start (+ or =) + current_priority = 0; // Default start (+ or =) } first_in_sequence = false; } else { @@ -695,9 +727,8 @@ int main(int argc, char* argv[]) { std::cout << "Successfully generated timeline with " << sequences.size() << " sequences.\n"; } else { - std::cout << "Validation successful: " << sequences.size() - << " sequences, " << (demo_end_time.empty() ? "no" : "explicit") - << " end time.\n"; + std::cout << "Validation successful: " << sequences.size() << " sequences, " + << (demo_end_time.empty() ? "no" : "explicit") << " end time.\n"; } // Generate Gantt charts if requested -- cgit v1.2.3