From c4b1a4c879f8fd822e397925751b6c18df8ef6d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 15:14:13 +0000 Subject: [PATCH 1/3] CATCH: the FUNC menu row that writes what was played with REC off With REC off, record_note stamps every pad, KEYS and MIDI note into a ring per track (core/catchring.hpp). CATCH replays the last pass and the one before through quantize_hit, as a take would have written them (micro-timing, LEN from the hold, chords, REC MODE), every track at once, one undo level, at most 96 notes a press. START empties the ring; notes from another pattern origin are never caught. Host tests, scenario_catch, W116, docs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Tw2EaEK2oaJWJMdGQTNLPf --- CHANGELOG.md | 5 ++ app/app.hpp | 3 + app/ui_lights.hpp | 150 ++++++++++++++++++++++++++++++++++++++- app/ui_perfmix.hpp | 7 +- core/catchring.cpp | 81 +++++++++++++++++++++ core/catchring.hpp | 77 ++++++++++++++++++++ core/help.cpp | 12 ++++ docs/CHEATSHEET.md | 4 +- docs/CONTROLS.md | 1 + docs/DESIGN_NOTES.md | 24 +++++++ docs/FEATURES.md | 1 + docs/MANUAL.md | 17 ++++- docs/UNIT_CHECKLIST.md | 9 +++ tests/scenario_catch.sh | 122 +++++++++++++++++++++++++++++++ tests/test_catchring.cpp | 82 +++++++++++++++++++++ tests/test_ui.cpp | 72 ++++++++++++++++++- 16 files changed, 659 insertions(+), 8 deletions(-) create mode 100644 core/catchring.cpp create mode 100644 core/catchring.hpp create mode 100755 tests/scenario_catch.sh create mode 100644 tests/test_catchring.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cb17ed3..392fbd4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ the project file format or the controls. ### Added +- **CATCH.** A FUNC menu row under ARR REC. With REC off, the pads, KEYS and MIDI IN are still + stamped and kept; CATCH writes the last pass and the one before into the pattern, exactly as + REC would have (QUANTIZE, micro-timing, LEN, chords, REC MODE), every track played at once, as + one undo level (`CATCH T7 12 NOTES`). At most 96 notes a press. Nothing is saved: the notes + are kept from PLAY until they are caught. - **OPN: open hats from the step's length.** HAT's CYM page has a fourth knob, OPN. Above 0, a step longer than one step plays open with OPN as its decay, and the next hit on the track cuts it, so an open hat needs no locks. A roll's hits and ENERGY's ghosts stay closed. GENERATE's diff --git a/app/app.hpp b/app/app.hpp index f8b29830..df3b26fb 100644 --- a/app/app.hpp +++ b/app/app.hpp @@ -42,6 +42,7 @@ #include "paint.hpp" // the drawing kit: lines, arcs, the small font, afterglow #include "spectrum.hpp" // the output's spectrum for MIXER's master pages #include "record.hpp" // live recording's stamping and quantizing, used from here only +#include "catchring.hpp" // CATCH: notes played with REC off, kept for one press #include "sounds.hpp" // SOUNDS: the factory sounds for one track #include "usersounds.hpp" // and your own, saved on the card #include "arppresets.hpp" // ARPS: the factory arps for one track @@ -1327,6 +1328,8 @@ class Strata : public enaga::App { }; static constexpr int kRecHolds = 16; RecHold rec_holds_[kRecHolds] = {}; + // CATCH's notes, played with REC off (core/catchring.hpp). + CatchRing catch_; int rec_hold_next_ = 0; // On a chord track, the pass each step was last recorded in, plus 1 (0: not this take). // A note landing on a step already recorded in its own pass is another note of the chord diff --git a/app/ui_lights.hpp b/app/ui_lights.hpp index 3b2b3787..01f3d24f 100644 --- a/app/ui_lights.hpp +++ b/app/ui_lights.hpp @@ -93,7 +93,7 @@ // pad's release gives the roll its LEN, on any machine. void record_note(int track, uint8_t note, uint8_t velocity, bool held = true, uint8_t roll = 0) { - if (!rec_) return; + // REC off: the note is stamped all the same and kept for CATCH (core/catchring.hpp). const enaga::clock::State clock = enaga::clock::state(); if (!clock.running) return; // nothing to record onto // A count-in is the player's lead-in, not the pattern: nothing records until it ends -- @@ -135,6 +135,21 @@ now.fraction = clock.fraction; } const Stamp hit = stamp_back(now, kPadLatencyMs, clock.tempo); + if (!rec_) { + CatchHit caught; + caught.hit = hit; + caught.down = now; + caught.down.tick = now.tick + origin; + caught.origin = origin; + caught.note = note; + caught.velocity = velocity; + caught.roll = roll; + // Measured where a take measures it: a held key on a machine that plays LEN (the + // drums below SAMPLE do not), or a roll on any machine. + caught.held = held && (roll != 0 || engine_.machine_id(track) >= uint8_t(MachineId::sample)); + catch_.add(track, caught); + return; + } // quantize_hit finds the time SLOT the hit belongs to; under REV, PING or RND the note // goes to the step that plays in that slot on that pass, so it plays back where it was @@ -191,6 +206,137 @@ slot->down.tick = now.tick + origin; } + // A caught note's key came up (REC off): its hold becomes the LEN CATCH will give it, measured + // as record_note_up measures a recorded one. + void catch_note_up(int track, uint8_t note) { + Stamp down; + if (!catch_.find_held(track, note, down)) return; + const enaga::clock::State clock = enaga::clock::state(); + if (!clock.running) return; + const uint32_t lead = count_in_lead(); + Stamp up; + up.tick = clock.position > lead ? clock.position - lead : 0u; + up.fraction = clock.fraction; + const TrackPattern &source = engine_.pattern().tracks[track]; + TrackTiming timing; + timing.length = source.length; + timing.speed = Speed(source.speed); + catch_.set_length(track, note, held_length_index(down, up, timing)); + } + + // CATCH (FUNC menu): what was played with REC off over the last pass and the one before, + // written into the pattern as a take would have written it -- the same quantize, steps, + // micro-timing, chords and LEN. Every track with notes in its window, one undo level. The + // ring is emptied after, so a second CATCH does not write the same notes twice. + void catch_played() { + const enaga::clock::State clock = enaga::clock::state(); + if (!clock.running) { + notice_logged("CATCH: PLAY FIRST"); + return; + } + const uint32_t lead = count_in_lead(); + const uint32_t origin = engine_.status().pattern_origin.load(std::memory_order_relaxed); + if (clock.position < lead + origin) { + notice_logged("CATCH: NOTHING PLAYED"); + return; + } + const uint32_t now = clock.position - lead - origin; + const Pattern &pattern = engine_.pattern(); + TrackTiming timings[kTracks]; + for (int track = 0; track < kTracks; track++) { + const TrackPattern &source = pattern.tracks[track]; + TrackTiming &timing = timings[track]; + timing.length = source.length; + timing.speed = Speed(source.speed); + timing.swing = source.swing == kSwingInherit ? pattern.swing : source.swing; + timing.play = live_play_mode(source.play, engine_.live_rnd_unit(), + engine_.live_rnd_armed(), track); + timing.play_seed = play_seed(pattern.seed, track); + } + // The command ring holds 256 (app/commands.hpp) and a caught note posts two at most, so + // one press writes kCatchMostNotes. Over that, only the pass playing is caught; and + // what still does not fit, the last notes of it, is left out and the notice says CUT. + static CatchHit hits[kCatchHits]; // UI context only; too big for the stack + bool two_passes = true; + int total = 0; + for (int track = 0; track < kTracks; track++) { + const uint32_t from = catch_window_start(now, uint32_t(timings[track].loop_ticks())); + total += catch_.window(track, origin, from, now, hits, kCatchHits); + } + if (total > kCatchMostNotes) two_passes = false; + int notes = 0, tracks = 0, last_track = 0; + bool marked = false, cut = false; + for (int track = 0; track < kTracks && !cut; track++) { + const TrackTiming &timing = timings[track]; + const uint32_t loop = uint32_t(timing.loop_ticks()); + const uint32_t from = two_passes ? catch_window_start(now, loop) + : (loop == 0 ? 0u : now - now % loop); + const int count = catch_.window(track, origin, from, now, hits, kCatchHits); + if (count == 0) continue; + if (!marked) { + mark(GestureKind::record, track, 0); + marked = true; + } + // A step's first caught note replaces what it held (or joins it under REC MODE + // ADD), and the notes after it on that step join, as one pass of a take does. + uint64_t written = 0; + for (int i = 0; i < count; i++) { + if (notes >= kCatchMostNotes) { + cut = true; + break; + } + const CatchHit &h = hits[i]; + Landing landing = quantize_hit(h.hit, timing, quantize()); + landing.step = play_step(int(landing.step), landing.loop, timing); + const uint64_t bit = uint64_t(1) << (landing.step & 63u); + Command command; + command.cmd = Cmd::record_hit; + command.track = uint8_t(track); + command.step = landing.step; + command.a = h.note; + command.b = h.velocity; + command.c = uint8_t(landing.micro); + command.e = h.roll; + command.d = uint8_t(RecWrite::note); + if (records_chords(track)) { + command.d = uint8_t((written & bit) != 0 || rec_add() ? RecWrite::join : RecWrite::replace); + } + written |= bit; + post_command(command); + if (h.has_length) { + Command length; + length.cmd = Cmd::record_length; + length.track = uint8_t(track); + length.step = landing.step; + length.a = h.note; + length.b = h.length; + post_command(length); + } + notes++; + } + tracks++; + last_track = track; + } + if (notes == 0) { + notice_logged("CATCH: NOTHING PLAYED"); + return; + } + end_gesture(); + catch_.clear(); + char *out = notice_buffer_; + append(out, "CATCH "); + if (tracks == 1) { + append(out, "T"); + append_number(out, uint32_t(last_track + 1)); + append(out, " "); + } + append_number(out, uint32_t(notes)); + append(out, notes == 1 ? " NOTE" : " NOTES"); + if (cut) append(out, " CUT"); + *out = 0; + notice_logged(notice_buffer_); + } + // The machines whose steps play several notes: the POLY three, and MID, which sends a // chord to the synth it drives. Only these gather a chord played into one step. bool records_chords(int track) const { @@ -203,6 +349,7 @@ // (core/record.hpp, held_length_index), becomes the step's LEN. Nothing if it was not // recorded, if REC went off in between or the clock stopped -- there is nothing to measure. void record_note_up(int track, uint8_t note) { + if (!rec_) catch_note_up(track, note); RecHold *hold = nullptr; for (RecHold &h : rec_holds_) { if (h.track == track && h.note == note) hold = &h; @@ -240,6 +387,7 @@ if (what == ENAGA_TRANSPORT_START || what == ENAGA_TRANSPORT_LOCATE) { stop_armed_ = false; clear_rec_passes(); // the pass count starts again: old marks would match + catch_.clear(); // and CATCH's ticks: the last run's would read as this one's } // A song position pointer at MIDI IN: Enaga located its clock (only while stopped), and // the CONTINUE that follows plays from there. The engine puts the pattern, or the chain diff --git a/app/ui_perfmix.hpp b/app/ui_perfmix.hpp index 80173d70..ee9d24e9 100644 --- a/app/ui_perfmix.hpp +++ b/app/ui_perfmix.hpp @@ -16,7 +16,7 @@ // first, the file actions at the bottom, and GEN ALL last of all, which the wrap makes one // UP from SAVE (FUNC + HOME, UP, OK) without moving JAM REC and ARR REC off their DOWNs. The selected track's rows (SPEED, PLAY, FREEZE, // RELOAD SAMPLE) are in GRID's track menu (app/ui_trackmenu.hpp). - enum class MenuItem : uint8_t { save, jam, arr, click, count_in, rec_mode, quantize, + enum class MenuItem : uint8_t { save, jam, arr, catch_take, click, count_in, rec_mode, quantize, autofill, glide, transpose, loop_len, chain, song, arr_undo, prog_out, tempo_guard, save_as, open, kits, fresh, reload, clear, demo, gen_all, count }; @@ -48,6 +48,7 @@ case MenuItem::demo: return "LOAD DEMO"; case MenuItem::jam: return "JAM REC"; case MenuItem::arr: return "ARR REC"; + case MenuItem::catch_take: return "CATCH"; case MenuItem::arr_undo: return "ARR UNDO"; default: return "?"; } @@ -937,6 +938,10 @@ case MenuItem::gen_all: gen_all(); break; + case MenuItem::catch_take: + // The menu stays open, as on GEN ALL: CLR closes it, FUNC + CLR undoes the catch. + catch_played(); + break; case MenuItem::kits: open_kits(); break; diff --git a/core/catchring.cpp b/core/catchring.cpp new file mode 100644 index 00000000..1d901f6c --- /dev/null +++ b/core/catchring.cpp @@ -0,0 +1,81 @@ +#include "catchring.hpp" + +namespace strata { + +void CatchRing::clear() { + for (int t = 0; t < kCatchTracks; t++) clear_track(t); +} + +void CatchRing::clear_track(int track) { + if (track < 0 || track >= kCatchTracks) return; + tracks_[track].next = 0; + tracks_[track].count = 0; +} + +void CatchRing::add(int track, const CatchHit &hit) { + if (track < 0 || track >= kCatchTracks) return; + Track &t = tracks_[track]; + t.hits[t.next] = hit; + t.next = uint16_t(t.next + 1 >= kCatchHits ? 0 : t.next + 1); + if (t.count < kCatchHits) t.count++; +} + +const CatchHit &CatchRing::at(const Track &t, int age) const { + int index = int(t.next) - 1 - age; + if (index < 0) index += kCatchHits; + return t.hits[index]; +} + +int CatchRing::latest_held(int track, uint8_t note) const { + if (track < 0 || track >= kCatchTracks) return -1; + const Track &t = tracks_[track]; + for (int age = 0; age < t.count; age++) { + const CatchHit &h = at(t, age); + if (h.note != note) continue; + // The newest press of this note: still waiting for its key, or already measured. + return h.held && !h.has_length ? age : -1; + } + return -1; +} + +bool CatchRing::find_held(int track, uint8_t note, Stamp &down) const { + const int age = latest_held(track, note); + if (age < 0) return false; + down = at(tracks_[track], age).down; + return true; +} + +void CatchRing::set_length(int track, uint8_t note, uint8_t length_index) { + const int age = latest_held(track, note); + if (age < 0) return; + Track &t = tracks_[track]; + int index = int(t.next) - 1 - age; + if (index < 0) index += kCatchHits; + t.hits[index].length = length_index; + t.hits[index].has_length = true; +} + +int CatchRing::window(int track, uint32_t origin, uint32_t from, uint32_t to, CatchHit *out, + int max) const { + if (track < 0 || track >= kCatchTracks) return 0; + const Track &t = tracks_[track]; + int n = 0; + for (int age = t.count - 1; age >= 0 && n < max; age--) { + const CatchHit &h = at(t, age); + if (h.origin != origin || h.hit.tick < from || h.hit.tick > to) continue; + out[n++] = h; + } + return n; +} + +int CatchRing::count(int track) const { + return track < 0 || track >= kCatchTracks ? 0 : tracks_[track].count; +} + +uint32_t catch_window_start(uint32_t now, uint32_t loop_ticks) { + if (loop_ticks == 0) return 0; + const uint32_t pass_start = now - now % loop_ticks; + return pass_start >= loop_ticks ? pass_start - loop_ticks : 0; +} + +} // namespace strata diff --git a/core/catchring.hpp b/core/catchring.hpp new file mode 100644 index 00000000..422fd85f --- /dev/null +++ b/core/catchring.hpp @@ -0,0 +1,77 @@ +// CATCH: what was played on the pads, KEYS or MIDI IN while REC was off, kept so one press can +// write it into the pattern afterwards (the second review's proposal 12, option A, Roland +// 2026-11-30). The classic retrospective record: play, and when it was good, keep it. +// +// The UI stamps every note it would have recorded (app/ui_lights.hpp, record_note) and, with REC +// off, hands the stamp here instead of to the engine. A ring per track holds the last +// kCatchHits; CATCH then takes the ones from the start of the pass before the current one to +// now (catch_window_start) and posts them exactly as a live take would have: the same +// quantize, the same step, the same micro-timing, the same LEN from the key's hold. +// +// Stamps are the pattern's own ticks (the clock less a count-in, less where the pattern +// started), with that origin kept beside each hit: a hit from before a pattern switch or a +// chain entry belongs to another pattern and is never caught into this one. +// +// Fixed arrays, no allocation: 8 tracks x 256 hits x 32 bytes is 64 KiB, part of the app. +#pragma once + +#include "record.hpp" + +#include + +namespace strata { + +constexpr int kCatchHits = 256; // per track: two passes of 64 steps with chords to spare +constexpr int kCatchTracks = 8; +// The most notes one CATCH writes: each posts a hit and a LEN, and the command ring is 256. +constexpr int kCatchMostNotes = 96; + +struct CatchHit { + Stamp hit; // where it was played, the pad latency taken off (stamp_back) + Stamp down; // the raw press, on the clock less the count-in: the hold's start + uint32_t origin = 0; // the pattern's origin when it was played + uint8_t note = 0; + uint8_t velocity = 0; + uint8_t roll = 0; // a NOTE RPT roll's ratchet byte, 0 for a plain hit + uint8_t length = 0; // held_length_index once the key came up, if `held` + bool held = false; // the note has a key-up to wait for, which gives it a LEN + bool has_length = false; +}; + +class CatchRing { +public: + void clear(); + void clear_track(int track); + + // A note played with REC off. The oldest hit of the track gives way when the ring is full. + void add(int track, const CatchHit &hit); + + // The key of the latest caught `note` on `track` that is still held came up: its LEN. + // Returns the hit's down stamp through `down` so the caller can measure; false if none. + bool find_held(int track, uint8_t note, Stamp &down) const; + void set_length(int track, uint8_t note, uint8_t length_index); + + // The track's hits on `origin` at or after tick `from` (and not after `to`), oldest first, + // into `out` (at most `max`). Returns how many. + int window(int track, uint32_t origin, uint32_t from, uint32_t to, CatchHit *out, int max) const; + + int count(int track) const; + +private: + struct Track { + CatchHit hits[kCatchHits]; + uint16_t next = 0; // where the next hit goes + uint16_t count = 0; // how many are held, up to kCatchHits + }; + Track tracks_[kCatchTracks]; + + const CatchHit &at(const Track &t, int age) const; // 0 = the newest + int latest_held(int track, uint8_t note) const; // its age, or -1 +}; + +// Where CATCH starts on a track whose loop is `loop_ticks` long, at pattern tick `now`: the start +// of the pass before the one playing, so a whole loop is caught even just after the wrap. 0 in +// the first two passes. +uint32_t catch_window_start(uint32_t now, uint32_t loop_ticks); + +} // namespace strata diff --git a/core/help.cpp b/core/help.cpp index 8d72c7ef..e29b9ff6 100644 --- a/core/help.cpp +++ b/core/help.cpp @@ -478,6 +478,17 @@ constexpr Text kMenu = {"FUNC MENU:", { "FUNC+REC TWICE JAM", }}; +// CATCH, the FUNC menu's row that keeps what was played with REC off (core/catchring.hpp). +constexpr Text kCatch = {"CATCH:", { + "REC OFF: PADS KEYS", + "AND MIDI ARE KEPT", + "OK WRITES THE LAST", + "TWO PASSES AS REC", + "EVERY TRACK PLAYED", + "FUNC+CLR UNDOES IT", + "96 NOTES AT MOST", +}}; + // TEMPO GUARD, the FUNC menu's row that keeps VALUE off the tempo during a set. constexpr Text kTempoGuard = {"TEMPO GUARD:", { "ON: VALUE TURN OR TAP", @@ -953,6 +964,7 @@ bool own_page(const HelpPlace &place, int page, char title[kHelpChars + 1], list[listed++] = &kMenu; list[listed++] = &kGenAll; list[listed++] = &kArrRec; + list[listed++] = &kCatch; list[listed++] = &kTempoGuard; break; case HelpScreen::prep: diff --git a/docs/CHEATSHEET.md b/docs/CHEATSHEET.md index 1eb7c007..82d47c23 100644 --- a/docs/CHEATSHEET.md +++ b/docs/CHEATSHEET.md @@ -212,11 +212,11 @@ RELOAD PROJECT, NEW PROJECT and LOAD DEMO are in the FUNC menu (FUNC+HOME), the the track menu (hold OK in GRID); the last three throw away unsaved work, so each needs OK twice within 2 s (OK AGAIN: RELOAD, OK AGAIN: NEW, OK AGAIN: DEMO). NEW is empty; LOAD DEMO is the factory demo a first start plays. -**FUNC menu (FUNC+HOME):** SAVE, JAM REC, ARR REC, CLICK, COUNT-IN, REC MODE, QUANTIZE, AUTO-FILL, +**FUNC menu (FUNC+HOME):** SAVE, JAM REC, ARR REC, CATCH (what you played with REC off, the last two passes, into the pattern), CLICK, COUNT-IN, REC MODE, QUANTIZE, AUTO-FILL, FX GLIDE, TRANSPOSE (SCALE or SEMI), LOOP LEN, CHAIN, CHAIN END, ARR UNDO, PROG CHG OUT, TEMPO GUARD (ON: VALUE's turn and tap leave the tempo; saved), SAVE AS, OPEN PROJECT, KITS, NEW PROJECT, RELOAD PROJECT, CLEAR PATTERN, LOAD DEMO, GEN ALL. It always opens on SAVE: -DOWN once is JAM REC, twice ARR REC, three times CLICK; the list wraps, so +DOWN once is JAM REC, twice ARR REC, three times CATCH, four CLICK; the list wraps, so UP once is GEN ALL (GENERATE on every unmuted track, each of its own TYPE, one undo level; OK again for another), twice LOAD DEMO, three times CLEAR PATTERN. UP/DOWN or A scroll, OK runs the row (NEW, RELOAD, CLEAR PATTERN and LOAD DEMO need OK twice), LEFT/RIGHT or B change a diff --git a/docs/CONTROLS.md b/docs/CONTROLS.md index 14734e9f..1137db2f 100644 --- a/docs/CONTROLS.md +++ b/docs/CONTROLS.md @@ -176,6 +176,7 @@ FUNC + EDIT twice is KIT. | SAVE | saves the project, closes the menu | | | JAM REC | starts recording the finished master to `/RECORD/JAM_.WAV` and closes the menu (`JAM REC JAM 3`); OK again stops it (`JAM STOPPING`, then `SAVED JAM 3` once the file is closed). FUNC + HOME, DOWN, OK. FUNC + REC on RESAMPLE does the same and stays on RESAMPLE, whose last line shows the time and `FUNC+REC: STOP JAM` (`JAM OFF` when none runs) | `OFF`, or how long it has run, `4:07`, `1:02:33` | | ARR REC | starts a take (`ARR REC ON`, or `ARR: PRESS PLAY` with the transport stopped) and closes the menu; OK again ends it (`ARR 23 SECTIONS`). FUNC + HOME, DOWN, DOWN, OK. See ARR REC below | `OFF`, `ON`, or `ON 7`: the sections written so far | +| CATCH | writes what was played with REC off over the last pass and the one before into the pattern, as REC would have (QUANTIZE, LEN, chords, REC MODE), every track at once, one undo level (`CATCH T7 12 NOTES`; `CATCH: NOTHING PLAYED`, `CATCH: PLAY FIRST`). At most 96 notes (`CUT`). The menu stays open. Second review, proposal 12 option A (Roland, 2026-11-30); a FUNC menu row first because FUNC + REC is RESAMPLE and JAM | | | CLICK | | the metronome, `ON` / `OFF`: a click on every beat while the transport runs, higher on a bar's first. Not saved | | COUNT-IN | | `OFF`, `1 BAR`, `2 BAR`: a PLAY from stop with REC on clicks that many bars first (`COUNT-IN 4` .. `1`), then the pattern starts on step 1. Internal clock only. Not saved | | REC MODE | | `REPLACE` (default) / `ADD`: what a note recorded onto a chord track's step does. REPLACE: the first note of a pass on a step takes it over (its notes and chord type go), the rest of that pass's notes join it. ADD: every note joins the step's notes. Saved with the project | diff --git a/docs/DESIGN_NOTES.md b/docs/DESIGN_NOTES.md index 314fd69b..6081cb1b 100644 --- a/docs/DESIGN_NOTES.md +++ b/docs/DESIGN_NOTES.md @@ -740,3 +740,27 @@ rest are on the backlog with what each needs first. Measured and left alone: free-running oscillator phases on VA POLY (a stab's level then varies 1.7 dB from hit to hit), oversampling anywhere, and anti-aliasing the insert chain's DRV and the drum bus clip (their fold-over is at -40 dB or lower). + +## CATCH + +The second review's proposal 12, option A (Roland, 2026-11-30): keep what was played without +REC, and write it with one press. + +- **The same stamp as REC.** record_note (app/ui_lights.hpp) stamps every pad, KEYS and MIDI + note whether REC is on or not; with REC off the stamp goes into a ring per track + (core/catchring.hpp) instead of the engine. CATCH replays the ring through the same + quantize_hit and play_step, so a caught note lands exactly where a take would have put it, + with the same micro-timing, LEN (from the key's hold), chord joins and REC MODE. +- **The last pass and the one before.** catch_window_start: from the start of the pass before + the one playing, per track (polymeter: each track's own loop). Just after a wrap the pass + playing is nearly empty, so the one before is what was meant. +- **Origins.** Every hit keeps the pattern's origin; a pattern change or chain entry moves it, + so notes played into another pattern are never caught into this one. START empties the ring, + since ticks restart from 0 there. +- **96 notes a press.** A note posts a record_hit and a record_length, and the command ring + holds 256 (app/commands.hpp). Over 96 only the pass playing is caught, and past that the + notes are left out and the notice says `CUT`. +- **A menu row first.** FUNC + REC is RESAMPLE, and FUNC + REC again there is JAM REC; a + gesture on REC itself (held, or twice) can come once CATCH has been played with. The row sits + under ARR REC, three DOWNs from SAVE. +- **Memory.** 256 hits a track, 32 bytes each: 64 KiB in the app object, nothing at init(). diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 2fe52e5d..33186ff2 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -247,6 +247,7 @@ FM4 and GRAIN machines. | --- | --- | --- | --- | | Follows the unit's clock: internal, MIDI clock, SYNC IN; refuses tempo/transport under external clock | v0.1.0 | ○ (M7) | STRATA cannot set CLOCK SRC (Enaga has no setter). SYNC polarity not selectable (Enaga) | | Tap tempo on VALUE, nudge on FUNC + push VALUE + turn | v0.6.0 | ○ (W72, W80) | Internal clock only; nothing set until three taps agree within 25%; the nudge is 4% for 250 ms a detent | +| CATCH (FUNC menu): what was played with REC off over the last two passes, written as a take | Unreleased | ○ (W116), E (scenario_catch.sh) | Live only, emptied at PLAY and once caught; 256 notes kept a track, 96 written a press (the command ring); notes from before a pattern change are not caught | | TEMPO GUARD (FUNC menu): VALUE's plain turn and tap show the tempo and leave it | Unreleased | ○ (W99), E (scenario_tempoguard.sh) | Off by default; saved with the project (one byte on the end of PROJECT.BIN's MIDI section). Nudge, VariSpeed, swing and section BPMs still play | | **Song tempo kept apart from the project's**: a section's BPM plays without becoming the saved tempo; ARR REC writes BPM only where the tempo changed (and the take's start tempo on its first entry); VariSpeed held back near 300 BPM says so and returns at a slower tempo | v0.6.0 | ○ (W80), E (scenario_sections.sh, scenario_arrrec.sh) | The clock no longer jumps back for a moment after a section BPM, a VALUE turn or a tap | | MIDI OUT per track (OFF/1-16): steps, chords, ratchets, arp, note repeat, pads, KEYS, MIDI IN | v0.1.0 | ○ (8d) | **On Enaga 0.2.0 (v0.1.0-v0.3.1):** with USB connected to a computer not reading, DIN out stalls; unplug USB. Fixed in Enaga 0.3.0, which `main` needs | diff --git a/docs/MANUAL.md b/docs/MANUAL.md index d95ad8c6..964502ec 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -1520,9 +1520,20 @@ can be built up one pass at a time. The edit line says `REC+` under ADD. Transpo MUTATE's note moves and turning NOTE move the whole chord. VA MONO, WAVE MONO, SAMPLE, GRAIN and the drums keep one note a step: the last one played. -

The FUNC menu on CLICK, with ARR REC above and COUNT-IN below

- -**CLICK and COUNT-IN** (FUNC menu, the two rows under ARR REC). CLICK `ON` clicks every beat while the transport runs, a +**CATCH keeps what you played without REC.** With REC off, every pad hit, KEYS note and MIDI note +is still stamped and kept, per track. **CATCH** (FUNC menu, under ARR REC: FUNC + HOME, DOWN three +times, OK) writes the last pass and the one before it into the pattern, exactly as REC would have +written them: QUANTIZE, micro-timing, LEN from the hold, chords note for note, REC MODE. Every +track you played on is caught at once (`CATCH T7 12 NOTES`, or `CATCH 20 NOTES` over several +tracks), as one undo level, and the menu stays open. What was caught is gone from the store, so +a second CATCH says `CATCH: NOTHING PLAYED`; notes from before a PLAY, a pattern change or a +chain entry are never caught into the pattern playing. One CATCH writes at most 96 notes: past +that only the pass playing is caught, and what still does not fit is left out (`CUT`). With the +transport stopped it says `CATCH: PLAY FIRST`. + +

The FUNC menu on CLICK, with CATCH above and COUNT-IN below

+ +**CLICK and COUNT-IN** (FUNC menu, the two rows under CATCH). CLICK `ON` clicks every beat while the transport runs, a higher click on each bar's first beat. COUNT-IN `1 BAR` or `2 BAR` makes a PLAY from stop with REC on click that many bars first (the notice counts `COUNT-IN 4` .. `1`), whether CLICK is on or not; the pattern then starts on step 1 on the next beat, and nothing is recorded during the clicks diff --git a/docs/UNIT_CHECKLIST.md b/docs/UNIT_CHECKLIST.md index aea97356..80bffb2b 100644 --- a/docs/UNIT_CHECKLIST.md +++ b/docs/UNIT_CHECKLIST.md @@ -3683,3 +3683,12 @@ hat track's OPN at about 60 (W111). `W14: MAX 61.2`. --- + +**W116. CATCH: keep what was played without REC (4 min).** A01 playing, REC off, track 7 (VA +POLY) selected, KEYS (HOME twice). +- Play a two-bar line on the pads, some notes held. Nothing is written (GRID shows no new + steps). FUNC + HOME, DOWN to CATCH, OK: `CATCH T7 NOTES`, and the line plays back where + it was played, the held notes as long as they were held. `____` +- OK again: `CATCH: NOTHING PLAYED`. CLR, FUNC + CLR: the line is gone, the pattern as before. `____` +- Play on two tracks (UP/DOWN between them), then CATCH: `CATCH NOTES`, both written. STOP, + PLAY, CATCH at once: `CATCH: NOTHING PLAYED` (the notes before PLAY are not this run's). `____` diff --git a/tests/scenario_catch.sh b/tests/scenario_catch.sh new file mode 100755 index 00000000..aa19e45c --- /dev/null +++ b/tests/scenario_catch.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# CATCH in the emulator (FUNC menu; docs/CONTROLS.md, "The FUNC menu"): the row run with the +# transport stopped, then with the beat running and nothing played. +# +# What it proves is what the host cannot: the row draws and runs on the C674x, and CATCH's walk +# over eight tracks' rings with the beat playing costs no overrun or stall. The emulator has no +# pads and no MIDI IN, so it plays nothing to catch: what CATCH writes is host-tested +# (tests/test_ui.cpp, ui_catch_writes_what_was_played_with_rec_off; tests/test_catchring.cpp). +# +# Observable through Enaga's log (notice_logged): `CATCH: PLAY FIRST` before PLAY, then +# `CATCH: NOTHING PLAYED` while it plays; `run int` from the transport. +# +# Keys (third_party/enaga/include/enaga/abi.h): F5 = 22 (PLAY), F1 = 19, F4 = 27 (HOME), DOWN = 25, +# OK = 23, CLR = 30. The row is found by name (tools/menu_rows.py), so a row added to the menu +# does not move it. The first press comes late (tests/scenario_m1.sh). +set -euo pipefail + +cd "$(dirname "$0")/.." +# shellcheck source=tools/env.sh +source tools/env.sh + +if [ "${1:-}" != "" ]; then + echo "error: unknown argument: $1" >&2 + exit 2 +fi + +if [ ! -f "$ENAGA_EMULATOR/cpu.py" ]; then + echo "SKIP: no emulator at $ENAGA_EMULATOR" >&2 + exit 0 +fi + +strata_require_toolchain +strata_link_emulator_toolchain +tools/build.sh > /dev/null + +STAGE="$ENAGA_BUILD/stage/STRATA" +mkdir -p "$ENAGA_BUILD" +LOG="$ENAGA_BUILD/scenario_catch.log" + +downs=$(python3 -B tools/menu_rows.py app/ui_perfmix.hpp MenuItem catch_take) +step=40000000 + +keys=() +at=300000000 +# FUNC + HOME, DOWN to CATCH, OK, CLR: stopped. +open_row() { + keys+=(--key "19@$at" --key "27@$((at + 5000000))") + at=$((at + 80000000)) + for ((i = 0; i < downs; i++)); do + keys+=(--key "25@$at") + at=$((at + step)) + done +} +open_row +keys+=(--key "23@$at"); at=$((at + step)) +keys+=(--key "30@$at"); at=$((at + step)) +# PLAY, a bar, then the same while the beat runs. +keys+=(--key "22@$at"); at=$((at + 700000000)) +open_row +keys+=(--key "23@$at"); at=$((at + step)) +keys+=(--key "30@$at"); at=$((at + step)) +CYCLES=$((at + 200000000)) + +echo "running the emulator for $CYCLES cycles: CATCH stopped, then playing ..." +python3 -B tools/enaga_cached.py emulate "$STAGE" --cycles "$CYCLES" "${keys[@]}" \ + > "$LOG" 2>&1 || { + echo "FAIL: emulate.py exited non-zero" >&2 + tail -30 "$LOG" >&2 + exit 1 +} + +rc=0 +python3 - "$LOG" <<'PY' || rc=$? +import json, re, sys + +CYCLES_PER_BLOCK = 496_000 + +text = open(sys.argv[1]).read() +match = re.search(r'^\{.*?^\}', text, re.S | re.M) +if not match: + print(" FAIL no JSON report in the emulator output") + sys.exit(1) +report = json.loads(match.group(0)) + +failures = [] + +def check(ok, label, detail=""): + print(f" {'ok ' if ok else 'FAIL'} {label}{' ' + detail if detail else ''}") + if not ok: + failures.append(label) + +log = report.get("log", []) + +check(report.get("app_status") == "APP RUNNING", "app is running", + f'status={report.get("app_status")!r}') +check(not report.get("crash_reason"), "no crash", f'reason={report.get("crash_reason")!r}') +check("run int" in log, "the transport started", f"log={log}") +check("CATCH: PLAY FIRST" in log, "CATCH with the transport stopped asks for PLAY", f"log={log}") +check("CATCH: NOTHING PLAYED" in log, "CATCH while playing found nothing to catch", f"log={log}") + +blocks = report.get("audio_blocks", 0) +check(blocks > 1000, "audio ran throughout", f"blocks={blocks}") +check(report.get("audio_overruns", -1) == 0, "no audio overruns", + f'overruns={report.get("audio_overruns")}') + +peak = report.get("audio_cycles_peak", 0) +percent = 100.0 * peak / CYCLES_PER_BLOCK +check(percent > 5.0, "the beat was sounding", f"{percent:.2f}% peak") +check(percent < 60.0, "load is inside the target", f"{percent:.2f}% peak") + +print() +print(f"emulator peak load: {percent:.2f}% ({peak} of {CYCLES_PER_BLOCK} cycles, {blocks} blocks)") + +sys.exit(1 if failures else 0) +PY + +echo +if [ "$rc" -ne 0 ]; then + echo "SCENARIO FAILED; full log: $LOG" >&2 + exit 1 +fi +echo "SCENARIO OK (log: $LOG)" diff --git a/tests/test_catchring.cpp b/tests/test_catchring.cpp new file mode 100644 index 00000000..fbf5d889 --- /dev/null +++ b/tests/test_catchring.cpp @@ -0,0 +1,82 @@ +// CATCH's ring (core/catchring.hpp): the window it takes, the LEN a key-up gives, and the +// oldest hit giving way. The gesture is in tests/test_ui.cpp (ui_catch_writes_what_was_played_with_rec_off). +#include "check.hpp" + +#include "catchring.hpp" + +using namespace strata; + +namespace { + +CatchHit hit_at(uint32_t tick, uint8_t note, uint32_t origin = 0, bool held = false) { + CatchHit h; + h.hit.tick = tick; + h.down.tick = tick; + h.origin = origin; + h.note = note; + h.velocity = 100; + h.held = held; + return h; +} + +CatchRing g_ring; +CatchHit g_out[kCatchHits]; + +} // namespace + +TEST(catch_window_starts_a_pass_before_the_one_playing) { + CHECK_EQ(catch_window_start(0, 384), 0u); + CHECK_EQ(catch_window_start(383, 384), 0u); + CHECK_EQ(catch_window_start(384, 384), 0u); // pass 2: from the first + CHECK_EQ(catch_window_start(800, 384), 384u); // pass 3: from pass 2 + CHECK_EQ(catch_window_start(1152, 384), 768u); + CHECK_EQ(catch_window_start(500, 0), 0u); +} + +TEST(catch_window_keeps_its_origin_and_ticks_oldest_first) { + g_ring.clear(); + g_ring.add(2, hit_at(10, 60)); + g_ring.add(2, hit_at(400, 62)); + g_ring.add(2, hit_at(500, 64, 7)); // another pattern's + g_ring.add(2, hit_at(900, 65)); + g_ring.add(3, hit_at(450, 70)); + const int n = g_ring.window(2, 0, 384, 1000, g_out, kCatchHits); + CHECK_EQ(n, 2); + CHECK_EQ(int(g_out[0].note), 62); + CHECK_EQ(int(g_out[1].note), 65); + CHECK_EQ(g_ring.window(2, 0, 0, 100, g_out, kCatchHits), 1); + CHECK_EQ(g_ring.window(2, 0, 0, 1000, g_out, 1), 1); // `max` holds + CHECK_EQ(g_ring.window(9, 0, 0, 1000, g_out, kCatchHits), 0); // no such track +} + +TEST(catch_a_key_up_gives_its_latest_press_a_length_once) { + g_ring.clear(); + g_ring.add(0, hit_at(0, 60, 0, true)); + g_ring.add(0, hit_at(96, 60, 0, true)); + Stamp down; + CHECK(g_ring.find_held(0, 60, down)); + CHECK_EQ(down.tick, 96u); // the newest press of the note + g_ring.set_length(0, 60, 12); + CHECK(!g_ring.find_held(0, 60, down)); // measured: no second key-up + CHECK(!g_ring.find_held(0, 61, down)); + const int n = g_ring.window(0, 0, 0, 1000, g_out, kCatchHits); + CHECK_EQ(n, 2); + CHECK(!g_out[0].has_length); + CHECK(g_out[1].has_length); + CHECK_EQ(int(g_out[1].length), 12); + // A drum hit has no key-up to wait for. + g_ring.add(1, hit_at(0, 36)); + CHECK(!g_ring.find_held(1, 36, down)); +} + +TEST(catch_a_full_ring_lets_the_oldest_go) { + g_ring.clear(); + for (int i = 0; i < kCatchHits + 10; i++) g_ring.add(4, hit_at(uint32_t(i), uint8_t(i & 127))); + CHECK_EQ(g_ring.count(4), kCatchHits); + const int n = g_ring.window(4, 0, 0, 100000, g_out, kCatchHits); + CHECK_EQ(n, kCatchHits); + CHECK_EQ(g_out[0].hit.tick, 10u); + CHECK_EQ(g_out[n - 1].hit.tick, uint32_t(kCatchHits + 9)); + g_ring.clear_track(4); + CHECK_EQ(g_ring.count(4), 0); +} diff --git a/tests/test_ui.cpp b/tests/test_ui.cpp index 002570b0..cdb084d1 100644 --- a/tests/test_ui.cpp +++ b/tests/test_ui.cpp @@ -448,7 +448,7 @@ void open_keys() { } // The FUNC menu's rows, in order (app/ui_perfmix.hpp, MenuItem). -enum MenuRow : int { kMenuSave, kMenuJam, kMenuArr, kMenuClick, kMenuCountIn, kMenuRecMode, +enum MenuRow : int { kMenuSave, kMenuJam, kMenuArr, kMenuCatch, kMenuClick, kMenuCountIn, kMenuRecMode, kMenuQuantize, kMenuAutofill, kMenuGlide, kMenuTranspose, kMenuLoopLen, kMenuChain, kMenuSong, kMenuArrUndo, kMenuProgOut, kMenuTempoGuard, kMenuSaveAs, kMenuOpen, @@ -10283,6 +10283,76 @@ TEST(ui_keys_plays_the_pads_as_a_piano) { pump(2); } +// CATCH (FUNC menu; core/catchring.hpp): KEYS pads played with REC off write nothing, and CATCH +// then writes them as a take would have, with the hold's LEN; one undo level takes it back, and +// a second CATCH finds nothing, since the first emptied the ring. +TEST(ui_catch_writes_what_was_played_with_rec_off) { + Strata &app = fresh(); + key(ENAGA_KEY_F8); + for (int i = 0; i < 6; i++) key(ENAGA_KEY_DOWN); // track 7, VA POLY + CHECK_EQ(UiProbe::selected(app), 6); + open_keys(); + FakeHost &host = FakeHost::the(); + host.set_running(true); + host.set_position(96); // step 5 (index 4) + CHECK(!UiProbe::rec(app)); + + const int first = UiProbe::pad_note(app, 4); + const int second = UiProbe::pad_note(app, 8); + app.on_pad_press(4, 90); + pump(2); + host.set_position(96 + 4 * 24); // held four steps + app.on_pad_release(4); + pump(2); + host.set_position(96 + 8 * 24); // step 13 (index 12), a quick tap + app.on_pad_press(8, 70); + app.on_pad_release(8); + pump(2); + for (int s = 0; s < kStepsPerTrack; s++) CHECK(!trig_at(6, s)); // REC was off + + host.set_position(96 + 10 * 24); + menu_run(kMenuCatch); + pump(2); + CHECK_EQ(UiProbe::notice(app), "CATCH T7 2 NOTES"); + CHECK(trig_at(6, 4)); + CHECK_EQ(int(step_of(6, 4).note), first); + CHECK_EQ(int(step_of(6, 4).velocity), 90); + CHECK_EQ(int(step_of(6, 4).length), 12); // the four-step hold + CHECK(trig_at(6, 12)); + CHECK_EQ(int(step_of(6, 12).note), second); + CHECK_EQ(int(step_of(6, 12).velocity), 70); + int trigs = 0; + for (int s = 0; s < kStepsPerTrack; s++) trigs += trig_at(6, s) ? 1 : 0; + CHECK_EQ(trigs, 2); + + // Caught once: the ring is empty. + key(ENAGA_KEY_OK); + pump(2); + CHECK_EQ(UiProbe::notice(app), "CATCH: NOTHING PLAYED"); + key(ENAGA_KEY_CLR); + + // One undo level takes the whole catch back. + shift_key(ENAGA_KEY_CLR); + pump(2); + for (int s = 0; s < kStepsPerTrack; s++) CHECK(!trig_at(6, s)); + + // A note from before a restart is not this run's: START empties the ring. + app.on_pad_press(4, 90); + app.on_pad_release(4); + pump(2); + app.on_transport(ENAGA_TRANSPORT_START, 0); + menu_run(kMenuCatch); + pump(2); + CHECK_EQ(UiProbe::notice(app), "CATCH: NOTHING PLAYED"); + key(ENAGA_KEY_CLR); + + // Stopped: nothing to catch onto. + host.set_running(false); + menu_run(kMenuCatch); + CHECK_EQ(UiProbe::notice(app), "CATCH: PLAY FIRST"); + key(ENAGA_KEY_CLR); +} + TEST(ui_keys_pads_record_at_their_own_velocity) { Strata &app = fresh(); open_keys(); From e0a9bd2cb637dad4d3462c565f49188c2168b4fc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 16:01:27 +0000 Subject: [PATCH 2/3] STEMS: every track and the send returns to the card in one pass The second review's proposal 12, option A. A FUNC menu row under CATCH: OK starts the stems (and the transport, from stopped), STOP or OK again ends them. /RECORD/STEMS_.WAV holds the eight tracks as 16 channels of 16 bits, after inserts, fader and pan; STEMS__FX.WAV the returns. The mixer adds each chain into its own stem plane (Mixer::set_stems), audio() queues the planes in a StemRing (core/stemring.hpp), and the main context packs them (strata_stem_pack16) for two wav::Writers. tools/split_stems.py makes eight stereo WAVs. Host tests, scenario_stems (59.90% GCC-only against 56.47% for the beat alone), W117, docs, BUDGET. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Tw2EaEK2oaJWJMdGQTNLPf --- CHANGELOG.md | 7 ++ app/app.hpp | 2 + app/commands.hpp | 6 ++ app/engine.cpp | 26 ++++++ app/engine.hpp | 17 ++++ app/storage.cpp | 186 ++++++++++++++++++++++++++++++++++++++++ app/storage.hpp | 59 +++++++++++++ app/ui_lights.hpp | 13 +++ app/ui_perfmix.hpp | 60 ++++++++++++- core/help.cpp | 12 +++ core/stemring.hpp | 84 ++++++++++++++++++ docs/BUDGET.md | 19 ++++ docs/CHEATSHEET.md | 4 +- docs/CONTROLS.md | 1 + docs/DESIGN_NOTES.md | 28 ++++++ docs/FEATURES.md | 1 + docs/MANUAL.md | 21 ++++- docs/UNIT_CHECKLIST.md | 11 +++ docs/screens/menu.png | Bin 7132 -> 6961 bytes dsp/buses.cpp | 44 +++++++++- dsp/buses.hpp | 27 ++++++ dsp/masterloops.h | 10 +++ dsp/masterloops.ti.c | 21 +++++ tests/scenario_stems.sh | 126 +++++++++++++++++++++++++++ tests/test_memory.cpp | 11 ++- tests/test_stemring.cpp | 66 ++++++++++++++ tests/test_storage.cpp | 155 +++++++++++++++++++++++++++++++++ tests/test_ui.cpp | 86 ++++++++++++++++++- tools/split_stems.py | 85 ++++++++++++++++++ 29 files changed, 1174 insertions(+), 14 deletions(-) create mode 100644 core/stemring.hpp create mode 100755 tests/scenario_stems.sh create mode 100644 tests/test_stemring.cpp create mode 100755 tools/split_stems.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 392fbd4d..169fc7a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ the project file format or the controls. ### Added +- **STEMS.** A FUNC menu row under CATCH. OK records every track and the send returns to the + card at once, for mixing on a computer: `/RECORD/STEMS_.WAV` holds the eight tracks as 16 + channels of 16 bits (after each track's inserts, fader and pan; before the drum bus and the + master), `/RECORD/STEMS__FX.WAV` the delay, reverb and chorus returns in stereo 16-bit. + From a stopped transport the row starts the music too, and STOP ends the pass (`SAVED STEMS + 3`). `tools/split_stems.py` turns the 16-channel file into eight stereo WAVs. A JAM REC can + run at the same time. - **CATCH.** A FUNC menu row under ARR REC. With REC off, the pads, KEYS and MIDI IN are still stamped and kept; CATCH writes the last pass and the one before into the pattern, exactly as REC would have (QUANTIZE, micro-timing, LEN, chords, REC MODE), every track played at once, as diff --git a/app/app.hpp b/app/app.hpp index df3b26fb..03bbefdc 100644 --- a/app/app.hpp +++ b/app/app.hpp @@ -938,6 +938,8 @@ class Strata : public enaga::App { uint16_t project_steps_ = 0; uint32_t jam_lost_seen_ = 0; // JAM REC's dropped frames last said uint32_t jam_lost_ms_ = 0; + uint32_t stems_lost_seen_ = 0; + bool stems_saw_run_ = false; // STEMS: the transport has run since the stems started char notice_buffer_[24] = {}; // notice() keeps the pointer, so dynamic text // needs somewhere of its own to live diff --git a/app/commands.hpp b/app/commands.hpp index d9f43703..1e67bb16 100644 --- a/app/commands.hpp +++ b/app/commands.hpp @@ -487,6 +487,10 @@ enum class Cmd : uint8_t { // project file. jam_start, jam_stop, + // STEMS, the same protocol for two files (app/storage.hpp, "stems"): every track's stem and + // the returns, from Mixer's stem planes; Status::stems_epoch moves once writing has stopped. + stems_start, + stems_stop, // One field of one zone's sound (core/zones.hpp, ZoneField), from ZONES in the track menu: // step: the zone, a: the field, u: the value as the record holds it. The record in the kit is @@ -797,6 +801,8 @@ struct Status { // JAM REC. Bumped (with release) by every Cmd::jam_stop once the audio side has stopped // writing the jam's stream, so the card side may close it the moment it sees the change. std::atomic jam_epoch{0}; + // STEMS, the same as jam_epoch for Cmd::stems_stop. + std::atomic stems_epoch{0}; // Where a SAMPLE or GRAIN track is in its sample, for EDIT's waveform (core/overview.hpp, // WaveView): the window or the grain bracket, the slice starts, and up to eight playheads or diff --git a/app/engine.cpp b/app/engine.cpp index 6a02d3c9..e58177a0 100644 --- a/app/engine.cpp +++ b/app/engine.cpp @@ -2789,6 +2789,19 @@ bool Engine::apply_samples(const Command &command, int track, int) { jam_on_ = true; break; + case Cmd::stems_start: + stems_on_ = true; + mixer_.set_stems(true); + break; + + case Cmd::stems_stop: + // As jam_stop: stop writing, then say so. + stems_on_ = false; + mixer_.set_stems(false); + stems_epoch_ = uint8_t(stems_epoch_ + 1u); + status_.stems_epoch.store(stems_epoch_, std::memory_order_release); + break; + case Cmd::jam_stop: // Stop writing FIRST, then say so: the card side closes the file the moment it sees // the epoch move. Bumped even when nothing was being written, so a stop the card side @@ -4174,6 +4187,8 @@ namespace { constexpr float kInverseCount[kArpMaxRatchet + 1] = {1.0f, 1.0f, 0.5f, 1.0f / 3.0f, 0.25f}; // A block's length as a reciprocal: how many blocks a spacing holds. constexpr float kInverseBlock = 1.0f / float(ENAGA_BLOCK_FRAMES); +static_assert(StemRing::kFrames == ENAGA_BLOCK_FRAMES, "a stem slot holds one block"); +static_assert(StemRing::kPlanes == 2 * Mixer::kStems, "the stems ring carries every stem"); } // namespace @@ -5232,6 +5247,17 @@ void Engine::process(const float *in, float *out, uint32_t frames) { // ones that fit are kept. if (jam_on_) jam_.write(out, frames); + // STEMS: the mixer's stem planes into the ring (core/stemring.hpp); the main context packs + // them into the two files. A full ring drops the block and counts it. + if (stems_on_) { + const float *planes[StemRing::kPlanes]; + for (int s = 0; s <= kTracks; s++) { + planes[2 * s] = mixer_.stem(s, 0); + planes[2 * s + 1] = mixer_.stem(s, 1); + } + stems_ring_.push(planes, int(frames)); + } + // The input's level, every block, for the RESAMPLE screen's meter: one pass of the master's // own peak loop over the interleaved buffer (L and R alike, so one plane of 2n samples). if (in != nullptr) { diff --git a/app/engine.hpp b/app/engine.hpp index cebd4ffd..677b6fa7 100644 --- a/app/engine.hpp +++ b/app/engine.hpp @@ -23,6 +23,7 @@ #include "buses.hpp" #include "capture.hpp" // resampling's take buffer #include "frozen.hpp" // freeze: a track playing a loop of itself +#include "stemring.hpp" // STEMS: the stem planes to the main context #include "grain.hpp" // GRAIN, reachable at last: a track can host any machine #include "commands.hpp" #include "cpuguard.hpp" // sheds POLY voices and grains when the block nears its budget @@ -417,6 +418,16 @@ class Engine { // For tests: is the audio side writing it? bool jam_attached() const { return jam_on_; } + // STEMS' two files (app/storage.hpp, "stems"): the eight tracks as one 16-channel file, T1's + // left and right first, and the send returns as a stereo one. Written in audio() from the + // mixer's stem planes while Cmd::stems_start is in force, as the jam's is. + enaga::wav::Writer &stems_writer() { return stems_; } + enaga::wav::Writer &stems_returns_writer() { return stems_returns_; } + const enaga::wav::Writer &stems_writer() const { return stems_; } + const enaga::wav::Writer &stems_returns_writer() const { return stems_returns_; } + bool stems_attached() const { return stems_on_; } + StemRing &stems_ring() { return stems_ring_; } + private: void apply_commands(); void apply(const Command &command); @@ -656,6 +667,12 @@ class Engine { enaga::wav::Writer jam_; bool jam_on_ = false; // writing every block into jam_ uint8_t jam_epoch_ = 0; // what Status::jam_epoch holds + enaga::wav::Writer stems_; + enaga::wav::Writer stems_returns_; + bool stems_on_ = false; + uint8_t stems_epoch_ = 0; + StemRing stems_ring_; // audio() to the main context, which writes the files + // The hat choke is a pair, and the pair is tracks 3 and 4 of the DEFAULT kit. Machine // switching makes that an assumption rather than a fact, so it is re-derived on every diff --git a/app/storage.cpp b/app/storage.cpp index 339ccc16..8fbd9622 100644 --- a/app/storage.cpp +++ b/app/storage.cpp @@ -3,6 +3,7 @@ #include "factory.hpp" #include "zones.hpp" +#include "masterloops.h" // strata_stem_pack16 #include "engine.hpp" @@ -25,6 +26,7 @@ constexpr const char *kKeyNewSeq = "NEWSEQ"; constexpr const char *kKeyTakeSeq = "TAKESEQ"; // JAM REC's files the same way: /RECORD/JAM_.WAV. constexpr const char *kKeyJamSeq = "JAMSEQ"; +constexpr const char *kKeyStemsSeq = "STEMSEQ"; constexpr const char *kDefaultName = "DEFAULT"; @@ -288,6 +290,11 @@ bool Storage::init(Engine &engine) { if (audition_head_ == nullptr || audition_ring_ == nullptr) return false; jam_ring_ = new uint8_t[kJamRingBytes]; if (jam_ring_ == nullptr) return false; + stems_ring_ = new uint8_t[kStemsRingBytes]; + stems_returns_ring_ = new uint8_t[kStemsReturnsRingBytes]; + stems_slots_ = new float[kStemsBlocks * uint32_t(StemRing::kSlotFloats)]; + if (stems_ring_ == nullptr || stems_returns_ring_ == nullptr || stems_slots_ == nullptr) return false; + engine_->stems_ring().attach(stems_slots_, kStemsBlocks); pool_.init(kSampleBudgetDefaultMib << 20); engine_->set_sample_region(region_, kRegionBytes); @@ -1891,6 +1898,7 @@ void Storage::service() { service_audition(); // And JAM REC: a full card or a stop must not wait behind a job either. service_jam(); + service_stems(); // Freeze next, whatever job runs and with or without a card: it is RAM only, and a loop // whose slot is waiting to be given back should not wait behind a save. @@ -4306,6 +4314,183 @@ void Storage::close_jam_for_shutdown() { close_jam(); } +// --- stems ----------------------------------------------------------------------- +// +// app/storage.hpp, "stems", has the layout; the protocol is the jam's. + +bool Storage::request_stems_start() { + if (stems_state_ == JamState::recording) return true; + if (stems_state_ == JamState::closing) { + stems_message_ = "STEMS BUSY"; + return false; + } + if (!card_usable_) { + stems_message_ = "NO CARD"; + return false; + } + const int32_t next = settings_.get(kKeyStemsSeq, 0) + 1; + { + char *out = stems_name_; + const char *end = stems_name_ + sizeof stems_name_ - 1; + append_text(out, "STEMS_", end); + append_number(out, uint32_t(next), end); + append_text(out, ".WAV", end); + *out = '\0'; + } + { + char *out = stems_path_; + const char *end = stems_path_ + sizeof stems_path_ - 1; + append_text(out, "/RECORD/", end); + append_text(out, stems_name_, end); + *out = '\0'; + } + { + char *out = stems_returns_path_; + const char *end = stems_returns_path_ + sizeof stems_returns_path_ - 1; + append_text(out, "/RECORD/STEMS_", end); + append_number(out, uint32_t(next), end); + append_text(out, "_FX.WAV", end); + *out = '\0'; + } + enaga::wav::Format tracks{}; + tracks.encoding = enaga::wav::pcm; + tracks.channels = uint16_t(2 * kTracks); + tracks.rate = uint32_t(ENAGA_SAMPLE_RATE); + tracks.bits = 16; + enaga::wav::Format returns = tracks; + returns.channels = 2; + returns.bits = 16; + enaga::wav::Writer &a = engine_->stems_writer(); + enaga::wav::Writer &b = engine_->stems_returns_writer(); + int32_t created = a.create(stems_path_, tracks, stems_ring_, kStemsRingBytes); + if (created >= 0) created = b.create(stems_returns_path_, returns, stems_returns_ring_, kStemsReturnsRingBytes); + if (created < 0) { + a.close(); + b.close(); + // A half-made pair is no use: neither is kept. + enaga::files::remove(stems_path_); + enaga::files::remove(stems_returns_path_); + char *out = stems_text_; + const char *end = stems_text_ + sizeof stems_text_ - 1; + append_text(out, "STEMS: ", end); + append_text(out, created == enaga::wav::not_wav ? "BAD FORMAT" : enaga::files::error_name(created), end); + *out = '\0'; + stems_message_ = stems_text_; + stems_name_[0] = '\0'; + return false; + } + settings_.set(kKeyStemsSeq, next); + settings_.save(); + stems_epoch_ = engine_->status().stems_epoch.load(std::memory_order_acquire); + stems_frames_ = 0; + stems_stop_reason_ = nullptr; + engine_->stems_ring().clear(); // the producer is idle until stems_start lands + post(Cmd::stems_start); + stems_state_ = JamState::recording; + return true; +} + +void Storage::request_stems_stop() { + if (stems_state_ == JamState::recording) stop_stems(nullptr); +} + +uint32_t Storage::stems_lost_frames() const { + const uint32_t a = engine_->stems_writer().frames_lost(); + const uint32_t b = engine_->stems_returns_writer().frames_lost(); + return (a > b ? a : b) + engine_->stems_ring().lost(); +} + +// What audio() has queued, packed into 16-bit frames and handed to the two Writers. A Writer +// whose ring is full drops what does not fit and counts it (frames_lost). +void Storage::drain_stems() { + StemRing &ring = engine_->stems_ring(); + enaga::wav::Writer &a = engine_->stems_writer(); + enaga::wav::Writer &b = engine_->stems_returns_writer(); + int frames = 0; + for (const float *slot = ring.front(frames); slot != nullptr; slot = ring.front(frames)) { + constexpr int kF = StemRing::kFrames; + for (int t = 0; t < kTracks; t++) + strata_stem_pack16(stems_pcm_ + 2 * t, slot + (2 * t) * kF, slot + (2 * t + 1) * kF, + 2 * kTracks, frames); + a.write_bytes(stems_pcm_, uint32_t(frames) * 2u * 2u * kTracks); + strata_stem_pack16(stems_pcm_, slot + (2 * kTracks) * kF, slot + (2 * kTracks + 1) * kF, 2, + frames); + b.write_bytes(stems_pcm_, uint32_t(frames) * 2u * 2u); + ring.pop(); + } +} + +void Storage::stop_stems(const char *why) { + stems_stop_reason_ = why; + post(Cmd::stems_stop); + stems_state_ = JamState::closing; +} + +void Storage::close_stems() { + enaga::wav::Writer &a = engine_->stems_writer(); + enaga::wav::Writer &b = engine_->stems_returns_writer(); + stems_frames_ = a.frames(); + const uint32_t lost = stems_lost_frames(); + const int32_t closed_a = a.close(); + const int32_t closed_b = b.close(); + const int32_t closed = closed_a < 0 ? closed_a : closed_b; + stems_state_ = JamState::idle; + char *out = stems_text_; + const char *end = stems_text_ + sizeof stems_text_ - 1; + if (stems_stop_reason_ != nullptr) { + append_text(out, stems_stop_reason_, end); + } else if (closed < 0) { + append_text(out, "STEMS: ", end); + append_text(out, enaga::files::error_name(closed), end); + } else if (lost > 0) { + // The card fell behind: the files are there, with gaps. Said rather than SAVED. + append_text(out, "STEMS: CARD TOO SLOW", end); + } else { + append_text(out, "SAVED ", end); + for (const char *c = stems_name_; *c != '\0' && *c != '.' && out < end; c++) { + *out++ = *c == '_' ? ' ' : *c; + } + } + *out = '\0'; + stems_message_ = stems_text_; +} + +void Storage::service_stems() { + switch (stems_state_) { + case JamState::idle: + return; + case JamState::closing: { + // Once audio() has stopped (the epoch moved), what it queued goes in, then the close. + const uint8_t now = engine_->status().stems_epoch.load(std::memory_order_acquire); + drain_stems(); + if (now != stems_epoch_) { + drain_stems(); + close_stems(); + } + return; + } + case JamState::recording: { + drain_stems(); + enaga::wav::Writer &a = engine_->stems_writer(); + stems_frames_ = a.frames(); + const enaga::files::Stream::Status sa = a.status(); + const enaga::files::Stream::Status sb = engine_->stems_returns_writer().status(); + const int32_t state = sa.state < 0 ? sa.state : sb.state; + if (state < 0) { + stop_stems(state == ENAGA_FILE_FULL ? "CARD FULL: STEMS SAVED" : "CARD ERROR: STEMS CUT"); + } else if (sa.position >= stems_limit_) { + stop_stems("STEMS: FILE FULL"); + } + return; + } + } +} + +void Storage::close_stems_for_shutdown() { + if (stems_state_ == JamState::idle) return; + close_stems(); +} + // --- streaming ---------------------------------------------------------------- // // app/storage.hpp, "streaming: a file too big for the pool", has the protocol. @@ -4447,6 +4632,7 @@ void Storage::save_for_shutdown() { // this file that waits. // The jam first: without its header the file says it holds nothing. close_jam_for_shutdown(); + close_stems_for_shutdown(); if (!card_usable_) return; // Nor while a project load is half done: RAM is part the project being read and part the one // before (on_card says more), and both are whole on the card. An autosave of the mix would diff --git a/app/storage.hpp b/app/storage.hpp index ee624936..cb50fe8b 100644 --- a/app/storage.hpp +++ b/app/storage.hpp @@ -62,6 +62,7 @@ #include "prep.hpp" #include "project.hpp" #include "samplepool.hpp" +#include "stemring.hpp" #include "usersounds.hpp" #include @@ -408,6 +409,38 @@ class Storage { static constexpr uint32_t kJamMaxBytes = 4000000000u; void set_jam_limit(uint32_t bytes) { jam_limit_ = bytes; } + // --- stems: STEMS, the FUNC menu's row under JAM REC's group --- + // + // The second review's proposal 12, option A (Roland, 2026-11-30): one pass of the song, + // every track to the card at once, for mixing elsewhere. Enaga opens at most 8 streams, and + // sample streaming and JAM REC take some, so the eight tracks go into ONE file of 16 + // channels (T1 left, T1 right, T2 left ...) at 16 bits, which is 32 bytes a frame, the most + // a wav::Writer takes; the send returns into a second, stereo at 16 bits. Each track's stem is + // what it adds to the mix: after its insert chain, fader and pan, before the drum bus and the + // master (Mixer::set_stems). tools/split_stems.py turns the first file into eight stereo WAVs. + // + // /RECORD/STEMS_.WAV 16 channels, 1.5 MB/s + // /RECORD/STEMS__FX.WAV the delay, reverb and chorus returns, 192 KB/s + // + // The jam's protocol, with one step between: create both, post Cmd::stems_start; audio() + // queues the planes (core/stemring.hpp) and service_stems packs and writes them; on a stop + // post Cmd::stems_stop, and once Status::stems_epoch has moved write what is left and close. A card that + // cannot keep up drops frames and counts them (stems_lost_frames); the closing message says. + bool request_stems_start(); + void request_stems_stop(); + bool stems_running() const { return stems_state_ != JamState::idle; } + bool stems_recording() const { return stems_state_ == JamState::recording; } + uint32_t stems_seconds() const { return stems_frames_ / uint32_t(ENAGA_SAMPLE_RATE); } + uint32_t stems_lost_frames() const; + const char *stems_name() const { return stems_name_; } + const char *take_stems_message() { + const char *m = stems_message_; + stems_message_ = nullptr; + return m; + } + void close_stems_for_shutdown(); + void set_stems_limit(uint32_t bytes) { stems_limit_ = bytes; } + // --- streaming (below, "streaming: a file too big for the pool") --- // Does this track play a streamed file? For the screen's sample line and for tests. @@ -1037,6 +1070,32 @@ class Storage { static constexpr uint32_t kJamRingBytes = 1u << 20; uint8_t *jam_ring_ = nullptr; + // --- stems --- + void service_stems(); + void stop_stems(const char *why); + void close_stems(); + JamState stems_state_ = JamState::idle; + uint8_t stems_epoch_ = 0; + uint32_t stems_frames_ = 0; + uint32_t stems_limit_ = kJamMaxBytes; + const char *stems_stop_reason_ = nullptr; + const char *stems_message_ = nullptr; + char stems_name_[24] = {}; + char stems_path_[40] = {}; + char stems_returns_path_[44] = {}; + char stems_text_[32] = {}; + // The Writers' rings, 1.4 s of each file for the card's slow moments, and before them the + // planes audio() queues (core/stemring.hpp), 0.68 s for the main loop's. Taken in init(), + // like the jam's. + static constexpr uint32_t kStemsRingBytes = 2u << 20; + static constexpr uint32_t kStemsReturnsRingBytes = 256u << 10; + static constexpr uint32_t kStemsBlocks = 512; + uint8_t *stems_ring_ = nullptr; + uint8_t *stems_returns_ring_ = nullptr; + float *stems_slots_ = nullptr; + int16_t stems_pcm_[2 * kTracks * StemRing::kFrames] = {}; // a block of the tracks' file + void drain_stems(); + // --- streaming: a file too big for the pool --- // // Roland's call (2026-11-22), after chunked loading: a file the pool cannot hold is STREAMED diff --git a/app/ui_lights.hpp b/app/ui_lights.hpp index 01f3d24f..a9834efe 100644 --- a/app/ui_lights.hpp +++ b/app/ui_lights.hpp @@ -536,6 +536,19 @@ // JAM REC: why a start was refused, why a jam stopped on its own, or SAVED once its file // is closed. Logged, for tests/scenario_jamrec.sh and a unit log. if (const char *jam = storage_.take_jam_message()) notice_logged(jam); + // STEMS: the same, and a STOP of the transport ends a pass. + service_stems_ui(); + if (const char *stems = storage_.take_stems_message()) notice_logged(stems); + if (storage_.stems_running()) { + const uint32_t lost = storage_.stems_lost_frames(); + if (lost != stems_lost_seen_ && uint32_t(last_ms_ - jam_lost_ms_) >= 1000u) { + stems_lost_seen_ = lost; + jam_lost_ms_ = last_ms_; + notice_logged("STEMS: CARD TOO SLOW"); + } + } else { + stems_lost_seen_ = 0; + } // What a SAVE AS (or a save of a collected project) did with the samples, once saved. if (const char *collected = storage_.take_collect_message()) notice(collected); // PREP's WRITE: WROTE KICK-E1.WAV, or why not. diff --git a/app/ui_perfmix.hpp b/app/ui_perfmix.hpp index ee9d24e9..314c3264 100644 --- a/app/ui_perfmix.hpp +++ b/app/ui_perfmix.hpp @@ -16,7 +16,7 @@ // first, the file actions at the bottom, and GEN ALL last of all, which the wrap makes one // UP from SAVE (FUNC + HOME, UP, OK) without moving JAM REC and ARR REC off their DOWNs. The selected track's rows (SPEED, PLAY, FREEZE, // RELOAD SAMPLE) are in GRID's track menu (app/ui_trackmenu.hpp). - enum class MenuItem : uint8_t { save, jam, arr, catch_take, click, count_in, rec_mode, quantize, + enum class MenuItem : uint8_t { save, jam, arr, catch_take, stems, click, count_in, rec_mode, quantize, autofill, glide, transpose, loop_len, chain, song, arr_undo, prog_out, tempo_guard, save_as, open, kits, fresh, reload, clear, demo, gen_all, count }; @@ -49,6 +49,7 @@ case MenuItem::jam: return "JAM REC"; case MenuItem::arr: return "ARR REC"; case MenuItem::catch_take: return "CATCH"; + case MenuItem::stems: return "STEMS"; case MenuItem::arr_undo: return "ARR UNDO"; default: return "?"; } @@ -119,6 +120,10 @@ if (storage_.jam_running()) append_clock(out, storage_.jam_seconds()); else append(out, "OFF"); break; + case MenuItem::stems: + if (storage_.stems_running()) append_clock(out, storage_.stems_seconds()); + else append(out, "OFF"); + break; default: break; } @@ -139,10 +144,13 @@ append_padded(out, secs, 2); } - // JAM REC's mark, the top bar's dot and the REC key's blink: lit for 600 ms of each second + // JAM REC's mark (and STEMS'), the top bar's dot and the REC key's blink: lit for 600 ms of each second // while the jam records, steady while its file is being closed, dark otherwise. bool jam_mark_on() const { - return storage_.jam_running() && (!storage_.jam_recording() || last_ms_ % 1000u < 600u); + const bool on = storage_.jam_running() || storage_.stems_running(); + const bool steady = (storage_.jam_running() && !storage_.jam_recording()) || + (storage_.stems_running() && !storage_.stems_recording()); + return on && (steady || last_ms_ % 1000u < 600u); } // --- ARR REC (core/arrrec.hpp): the jam written into the chain ------------------------------- @@ -236,6 +244,49 @@ notice_logged(notice_buffer_); } + // STEMS, from the menu's row: every track to the card at once (app/storage.hpp, "stems"), or + // stop. From a stopped transport the row starts it too, as PLAY does, so one OK records a + // pass; a STOP ends the stems as well (service_stems_ui). The menu closes on a start, as + // JAM REC's does. + void toggle_stems() { + if (storage_.stems_running()) { + storage_.request_stems_stop(); + notice_logged("STEMS STOPPING"); + return; + } + if (!storage_.request_stems_start()) return; // the reason comes as a stems message + stems_saw_run_ = enaga::clock::running(); + if (!stems_saw_run_) { + // Refused under an outside clock: the stems wait for it, and its STOP ends them. + clock_refused_ = !enaga::clock::start(); + if (!clock_refused_) { + stop_armed_ = false; + post(Cmd::play); + } + } + close_menu(false); + char *out = notice_buffer_; + const char *name = storage_.stems_name(); + for (; *name != '\0' && *name != '.'; name++) *out++ = *name == '_' ? ' ' : *name; // no _ in the font + *out = 0; + notice_logged(notice_buffer_); + } + + // Once the transport has run with stems recording, its STOP ends them: the take is the pass. + void service_stems_ui() { + if (!storage_.stems_recording()) { + stems_saw_run_ = false; + return; + } + const bool running = enaga::clock::running(); + if (running) { + stems_saw_run_ = true; + } else if (stems_saw_run_) { + stems_saw_run_ = false; + storage_.request_stems_stop(); + } + } + bool frozen(int track) const { return (engine_.status().frozen.load(std::memory_order_relaxed) >> track & 1u) != 0; } @@ -948,6 +999,9 @@ case MenuItem::jam: toggle_jam(true); break; + case MenuItem::stems: + toggle_stems(); + break; case MenuItem::arr_undo: // One level, both ways: the audio side says which (service_arr). post(Cmd::arr_undo); diff --git a/core/help.cpp b/core/help.cpp index e29b9ff6..9d8ffc09 100644 --- a/core/help.cpp +++ b/core/help.cpp @@ -489,6 +489,17 @@ constexpr Text kCatch = {"CATCH:", { "96 NOTES AT MOST", }}; +// STEMS, the FUNC menu's row under CATCH (app/storage.hpp, "stems"). +constexpr Text kStems = {"STEMS:", { + "OK EVERY TRACK AND", + "THE FX RETURNS TO", + "/RECORD AT ONCE", + "STOPPED: PLAYS TOO", + "STOP OR OK ENDS IT", + "SPLIT ON A COMPUTER", + "TOOLS/SPLIT STEMS.PY", +}}; + // TEMPO GUARD, the FUNC menu's row that keeps VALUE off the tempo during a set. constexpr Text kTempoGuard = {"TEMPO GUARD:", { "ON: VALUE TURN OR TAP", @@ -965,6 +976,7 @@ bool own_page(const HelpPlace &place, int page, char title[kHelpChars + 1], list[listed++] = &kGenAll; list[listed++] = &kArrRec; list[listed++] = &kCatch; + list[listed++] = &kStems; list[listed++] = &kTempoGuard; break; case HelpScreen::prep: diff --git a/core/stemring.hpp b/core/stemring.hpp new file mode 100644 index 00000000..2ca6cb69 --- /dev/null +++ b/core/stemring.hpp @@ -0,0 +1,84 @@ +// STEMS (app/storage.hpp, "stems"): the stem planes from audio() to the main context, a block a +// slot. audio() only copies the mixer's eighteen planes in; the main context turns them into +// 16-bit frames (strata_stem_pack16) and hands them to the two wav::Writers. Packing eighteen +// channels a block in audio() cost about 8 points of load GCC-only, and the Writers' own copy +// 4 more (docs/BUDGET.md); here they are main-loop time, which a take does not need to be +// on time for, only to keep up with on average. +// +// Single producer (audio()), single consumer (the main context), through two atomics: the +// producer writes a slot and then publishes head_, the consumer reads a slot and then publishes +// tail_. A full ring drops the block whole and counts its frames (lost()). +// +// The slots are the caller's, allocated in init(): blocks() slots of kSlotFloats floats. +#pragma once + +#include +#include + +namespace strata { + +class StemRing { +public: + static constexpr int kPlanes = 18; // eight tracks' L and R, then the returns' L and R + static constexpr int kFrames = 64; // a block at most + static constexpr int kSlotFloats = kPlanes * kFrames + 1; // the last: the block's frames + + // `blocks` a power of two. Main context, with no producer running. + void attach(float *slots, uint32_t blocks) { + slots_ = slots; + mask_ = blocks - 1u; + clear(); + } + // Empties the ring and its count. Main context, with no producer running. + void clear() { + head_.store(0, std::memory_order_relaxed); + tail_.store(0, std::memory_order_relaxed); + lost_.store(0, std::memory_order_relaxed); + } + bool attached() const { return slots_ != nullptr; } + + // audio(): one block of `frames` (1..kFrames) from planes[0..kPlanes-1]. False when full. + bool push(const float *const *planes, int frames) { + if (slots_ == nullptr || frames <= 0 || frames > kFrames) return false; + const uint32_t head = head_.load(std::memory_order_relaxed); + const uint32_t tail = tail_.load(std::memory_order_acquire); + if (head - tail > mask_) { + lost_.store(lost_.load(std::memory_order_relaxed) + uint32_t(frames), std::memory_order_relaxed); + return false; + } + float *slot = slots_ + (head & mask_) * uint32_t(kSlotFloats); + for (int p = 0; p < kPlanes; p++) { + const float *from = planes[p]; + float *to = slot + p * kFrames; + for (int i = 0; i < frames; i++) to[i] = from[i]; + } + slot[kPlanes * kFrames] = float(frames); + head_.store(head + 1u, std::memory_order_release); + return true; + } + + // Main context: the oldest block's planes (plane p at front + p * kFrames) and its frames, + // or nullptr when empty. pop() lets the producer have the slot back. + const float *front(int &frames) const { + const uint32_t tail = tail_.load(std::memory_order_relaxed); + if (slots_ == nullptr || head_.load(std::memory_order_acquire) == tail) return nullptr; + const float *slot = slots_ + (tail & mask_) * uint32_t(kSlotFloats); + frames = int(slot[kPlanes * kFrames]); + return slot; + } + void pop() { tail_.store(tail_.load(std::memory_order_relaxed) + 1u, std::memory_order_release); } + + uint32_t lost() const { return lost_.load(std::memory_order_relaxed); } + uint32_t queued() const { + return head_.load(std::memory_order_acquire) - tail_.load(std::memory_order_relaxed); + } + +private: + float *slots_ = nullptr; + uint32_t mask_ = 0; + std::atomic head_{0}; + std::atomic tail_{0}; + std::atomic lost_{0}; // written by the producer only +}; + +} // namespace strata diff --git a/docs/BUDGET.md b/docs/BUDGET.md index d93e4e8a..0fceba28 100644 --- a/docs/BUDGET.md +++ b/docs/BUDGET.md @@ -367,6 +367,25 @@ Peaks, so the difference carries about half a point of the run-to-run spread. No (that is `scenario_energy`, below). The card's write speed beside four sample streams is a unit question (UNIT_CHECKLIST W63). Image with cl6x: payload 1,655,768 bytes, bss 1,670,384. +### STEMS (2026-11-30, emulator, Enaga v0.4.0, GCC-only) + +STEMS records every track's stem and the send returns (docs/DESIGN_NOTES.md, "STEMS"). In +audio() it costs two adds a track a block in the mixer and a copy of eighteen planes into a ring; +the 16-bit packing and the Writers' copies are main-loop time. `scenario_stems` starts the +default beat and the stems together from the FUNC menu and records about four seconds; `m1` +is the beat alone, the same build. A first version that packed in audio() peaked at 70.74% +(70.7 with ring writes, 66.8 without them, 58.4 with only the mixer's part), which is why the +packing moved out. + +| | cl6x | GCC-only | +| --- | --- | --- | +| default beat (`m1`) | owed | 56.47% | +| default beat with JAM REC running (`jamrec`) | owed | 58.94% (+2.47) | +| default beat with STEMS running (`stems`) | owed | **59.90%** (+3.43) | + +The cl6x figures come from Roland's PC. The card's speed for 1.7 MB/s beside sample streams is +a unit question (UNIT_CHECKLIST W117). + ### ENERGY at +64 (2026-11-28, emulator, Enaga v0.4.0) ENERGY adds notes only above rest: ghosts on empty steps (hats most, perc, snare and samples, diff --git a/docs/CHEATSHEET.md b/docs/CHEATSHEET.md index 82d47c23..845f0d9e 100644 --- a/docs/CHEATSHEET.md +++ b/docs/CHEATSHEET.md @@ -212,11 +212,11 @@ RELOAD PROJECT, NEW PROJECT and LOAD DEMO are in the FUNC menu (FUNC+HOME), the the track menu (hold OK in GRID); the last three throw away unsaved work, so each needs OK twice within 2 s (OK AGAIN: RELOAD, OK AGAIN: NEW, OK AGAIN: DEMO). NEW is empty; LOAD DEMO is the factory demo a first start plays. -**FUNC menu (FUNC+HOME):** SAVE, JAM REC, ARR REC, CATCH (what you played with REC off, the last two passes, into the pattern), CLICK, COUNT-IN, REC MODE, QUANTIZE, AUTO-FILL, +**FUNC menu (FUNC+HOME):** SAVE, JAM REC, ARR REC, CATCH (what you played with REC off, the last two passes, into the pattern), STEMS (every track to the card at once; STOP ends it), CLICK, COUNT-IN, REC MODE, QUANTIZE, AUTO-FILL, FX GLIDE, TRANSPOSE (SCALE or SEMI), LOOP LEN, CHAIN, CHAIN END, ARR UNDO, PROG CHG OUT, TEMPO GUARD (ON: VALUE's turn and tap leave the tempo; saved), SAVE AS, OPEN PROJECT, KITS, NEW PROJECT, RELOAD PROJECT, CLEAR PATTERN, LOAD DEMO, GEN ALL. It always opens on SAVE: -DOWN once is JAM REC, twice ARR REC, three times CATCH, four CLICK; the list wraps, so +DOWN once is JAM REC, twice ARR REC, three times CATCH, four STEMS, five CLICK; the list wraps, so UP once is GEN ALL (GENERATE on every unmuted track, each of its own TYPE, one undo level; OK again for another), twice LOAD DEMO, three times CLEAR PATTERN. UP/DOWN or A scroll, OK runs the row (NEW, RELOAD, CLEAR PATTERN and LOAD DEMO need OK twice), LEFT/RIGHT or B change a diff --git a/docs/CONTROLS.md b/docs/CONTROLS.md index 1137db2f..78f03a79 100644 --- a/docs/CONTROLS.md +++ b/docs/CONTROLS.md @@ -177,6 +177,7 @@ FUNC + EDIT twice is KIT. | JAM REC | starts recording the finished master to `/RECORD/JAM_.WAV` and closes the menu (`JAM REC JAM 3`); OK again stops it (`JAM STOPPING`, then `SAVED JAM 3` once the file is closed). FUNC + HOME, DOWN, OK. FUNC + REC on RESAMPLE does the same and stays on RESAMPLE, whose last line shows the time and `FUNC+REC: STOP JAM` (`JAM OFF` when none runs) | `OFF`, or how long it has run, `4:07`, `1:02:33` | | ARR REC | starts a take (`ARR REC ON`, or `ARR: PRESS PLAY` with the transport stopped) and closes the menu; OK again ends it (`ARR 23 SECTIONS`). FUNC + HOME, DOWN, DOWN, OK. See ARR REC below | `OFF`, `ON`, or `ON 7`: the sections written so far | | CATCH | writes what was played with REC off over the last pass and the one before into the pattern, as REC would have (QUANTIZE, LEN, chords, REC MODE), every track at once, one undo level (`CATCH T7 12 NOTES`; `CATCH: NOTHING PLAYED`, `CATCH: PLAY FIRST`). At most 96 notes (`CUT`). The menu stays open. Second review, proposal 12 option A (Roland, 2026-11-30); a FUNC menu row first because FUNC + REC is RESAMPLE and JAM | | +| STEMS | starts recording every track to `/RECORD/STEMS_.WAV` (16 channels) and the send returns to `STEMS__FX.WAV`, and closes the menu (`STEMS 3`); from a stopped transport it starts the transport too. OK again (`STEMS STOPPING`) or STOP ends it (`SAVED STEMS 3`). The REC dot blinks as for JAM REC. Second review, proposal 12 option A (Roland, 2026-11-30) | `OFF`, or how long it has run, `4:07` | | CLICK | | the metronome, `ON` / `OFF`: a click on every beat while the transport runs, higher on a bar's first. Not saved | | COUNT-IN | | `OFF`, `1 BAR`, `2 BAR`: a PLAY from stop with REC on clicks that many bars first (`COUNT-IN 4` .. `1`), then the pattern starts on step 1. Internal clock only. Not saved | | REC MODE | | `REPLACE` (default) / `ADD`: what a note recorded onto a chord track's step does. REPLACE: the first note of a pass on a step takes it over (its notes and chord type go), the rest of that pass's notes join it. ADD: every note joins the step's notes. Saved with the project | diff --git a/docs/DESIGN_NOTES.md b/docs/DESIGN_NOTES.md index 6081cb1b..b812c08f 100644 --- a/docs/DESIGN_NOTES.md +++ b/docs/DESIGN_NOTES.md @@ -764,3 +764,31 @@ REC, and write it with one press. gesture on REC itself (held, or twice) can come once CATCH has been played with. The row sits under ARR REC, three DOWNs from SAVE. - **Memory.** 256 hits a track, 32 bytes each: 64 KiB in the app object, nothing at init(). + +## STEMS + +The second review's proposal 12, option A (Roland, 2026-11-30): one pass, every track and the +send returns to the card, for mixing elsewhere. + +- **One 16-channel file, not eight.** Enaga opens at most 8 files and 8 streams, sample + streaming and JAM REC take some, and a wav::Writer frame is at most 32 bytes: eight stereo + tracks fit as 16 channels of 16 bits, exactly 32. The returns go in a second, stereo 16-bit + file. tools/split_stems.py makes the eight stereo WAVs on a computer. +- **Where a stem is taken.** Mixer::add_any (dsp/buses.cpp): with stems on, a track's chain adds + into a cleared pair, which joins both the track's stem and the bus it was going to, so the mix + is unchanged. That is after the inserts, fader and pan, before the drum bus: a drum track's + stem does not have the bus's compression. The returns' stem is the mix after the sends minus + the mix before them (every step between only adds), so the nine stems sum to what master() + gets, less the drum bus's change. +- **Cost, and why the packing is not in audio().** With stems on, a track's chain adds into its + own stem plane and finish_block adds the plane to its bus: two adds a track a block. audio() + then copies the eighteen planes into a ring (core/stemring.hpp), and the main context packs + them into 16-bit frames (strata_stem_pack16, dsp/masterloops.ti.c) for Writer::write_bytes. + Packing in audio() cost about 8 points of load GCC-only and the Writers' copy 4 more (the + default beat went from 56% to 70.7% in scenario_stems); queued, the same take peaks at 59.9% + GCC-only. The ring holds 0.68 s for the main loop's slow moments, the Writers' rings 1.4 s + each for the card's; 1.7 MB/s to the card. Both returns and tracks are 16-bit. +- **A pass.** From a stopped transport the row starts it, and STOP ends the stems + (service_stems_ui), so one OK and one STOP make a take. Under an outside clock the start is + refused, the stems wait for it, and its STOP ends them. The protocol is JAM REC's: create both, + post the start, write in audio(), post the stop, and close once Status::stems_epoch has moved. diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 33186ff2..66579c24 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -247,6 +247,7 @@ FM4 and GRAIN machines. | --- | --- | --- | --- | | Follows the unit's clock: internal, MIDI clock, SYNC IN; refuses tempo/transport under external clock | v0.1.0 | ○ (M7) | STRATA cannot set CLOCK SRC (Enaga has no setter). SYNC polarity not selectable (Enaga) | | Tap tempo on VALUE, nudge on FUNC + push VALUE + turn | v0.6.0 | ○ (W72, W80) | Internal clock only; nothing set until three taps agree within 25%; the nudge is 4% for 250 ms a detent | +| STEMS (FUNC menu): every track and the send returns to the card in one pass | Unreleased | ○ (W117), E (scenario_stems.sh) | One 16-channel 16-bit file for the tracks (Enaga's stream limit; tools/split_stems.py splits it) and a stereo 16-bit one for the returns; 1.7 MB/s to the card, frames the card misses are counted and said. Tracks on the drum bus are recorded before it | | CATCH (FUNC menu): what was played with REC off over the last two passes, written as a take | Unreleased | ○ (W116), E (scenario_catch.sh) | Live only, emptied at PLAY and once caught; 256 notes kept a track, 96 written a press (the command ring); notes from before a pattern change are not caught | | TEMPO GUARD (FUNC menu): VALUE's plain turn and tap show the tempo and leave it | Unreleased | ○ (W99), E (scenario_tempoguard.sh) | Off by default; saved with the project (one byte on the end of PROJECT.BIN's MIDI section). Nudge, VariSpeed, swing and section BPMs still play | | **Song tempo kept apart from the project's**: a section's BPM plays without becoming the saved tempo; ARR REC writes BPM only where the tempo changed (and the take's start tempo on its first entry); VariSpeed held back near 300 BPM says so and returns at a slower tempo | v0.6.0 | ○ (W80), E (scenario_sections.sh, scenario_arrrec.sh) | The clock no longer jumps back for a moment after a section BPM, a VALUE turn or a tap | diff --git a/docs/MANUAL.md b/docs/MANUAL.md index 964502ec..c58566e8 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -1531,9 +1531,24 @@ chain entry are never caught into the pattern playing. One CATCH writes at most that only the pass playing is caught, and what still does not fit is left out (`CUT`). With the transport stopped it says `CATCH: PLAY FIRST`. -

The FUNC menu on CLICK, with CATCH above and COUNT-IN below

- -**CLICK and COUNT-IN** (FUNC menu, the two rows under CATCH). CLICK `ON` clicks every beat while the transport runs, a +**STEMS records every track apart, for mixing on a computer.** **STEMS** (FUNC menu, under CATCH: +FUNC + HOME, DOWN four times, OK) writes two files to `/RECORD` at once and closes the menu +(`STEMS 3`): `STEMS_3.WAV` holds the eight tracks, each what it adds to the mix after its inserts, +fader and pan, as 16 channels (track 1 left, track 1 right, track 2 left and so on, 16-bit), and +`STEMS_3_FX.WAV` holds the delay, reverb and chorus returns in stereo (16-bit). All of them added +together at unity are the mix before the drum bus and the master, so the master's EQ and +compression are left to the computer. From a stopped transport STEMS starts it too, so one OK +records a pass from where PLAY would start; STOP ends the stems, and so does OK on the row again +(`STEMS STOPPING`). Once the files are closed it says `SAVED STEMS 3`. The row shows how long it +has run, and the top bar's REC dot blinks as for JAM REC, which can run at the same time. +On a computer, `python3 tools/split_stems.py STEMS_3.WAV` writes `STEMS_3_T1.WAV` to +`STEMS_3_T8.WAV` beside it (`--skip-silent` leaves out empty tracks). The two files take about +1.7 MB a second; a card too slow for that says `STEMS: CARD TOO SLOW`, and the files then have +gaps. + +

The FUNC menu on CLICK, with STEMS above and COUNT-IN below

+ +**CLICK and COUNT-IN** (FUNC menu, the two rows under STEMS). CLICK `ON` clicks every beat while the transport runs, a higher click on each bar's first beat. COUNT-IN `1 BAR` or `2 BAR` makes a PLAY from stop with REC on click that many bars first (the notice counts `COUNT-IN 4` .. `1`), whether CLICK is on or not; the pattern then starts on step 1 on the next beat, and nothing is recorded during the clicks diff --git a/docs/UNIT_CHECKLIST.md b/docs/UNIT_CHECKLIST.md index 80bffb2b..8444ef11 100644 --- a/docs/UNIT_CHECKLIST.md +++ b/docs/UNIT_CHECKLIST.md @@ -3692,3 +3692,14 @@ POLY) selected, KEYS (HOME twice). - OK again: `CATCH: NOTHING PLAYED`. CLR, FUNC + CLR: the line is gone, the pattern as before. `____` - Play on two tracks (UP/DOWN between them), then CATCH: `CATCH NOTES`, both written. STOP, PLAY, CATCH at once: `CATCH: NOTHING PLAYED` (the notes before PLAY are not this run's). `____` + +**W117. STEMS: every track to the card (5 min).** Load the demo (FUNC menu, LOAD DEMO), stopped. +- FUNC + HOME, DOWN four times to STEMS, OK: `STEMS `, the menu closes, the demo starts and + the REC dot blinks. Let it play a minute, then STOP: `SAVED STEMS `, and no `CARD TOO + SLOW` on the way. `____` +- The load meter while stems record: write the worst `CPU` seen against W14's. `____` +- On a computer, `python3 tools/split_stems.py --skip-silent STEMS_.WAV`: each track sounds + alone, `STEMS__FX.WAV` has the delay and reverb, and all nine at unity in a DAW sound like + the demo before the master. `____` +- PLAY, STEMS, OK on the row again: `STEMS STOPPING` then `SAVED STEMS `, the music plays + on. Start JAM REC and STEMS together, stop both: both files whole. `____` diff --git a/docs/screens/menu.png b/docs/screens/menu.png index 658df61f892af2fe05272aea809f0442f1a7f7a8..8a161bc43f6507df72ab9710acb57355a0dc7e27 100644 GIT binary patch literal 6961 zcmb7J3p|@=-|ncTbZcr}rY-W8jo-prbZwmytHq%!ZH*Asl8W*vZKsM7;mf)@tZBWb z+EkIZbf`o`Gpq<%Sy(CSoT5%|i#a4@$N?$7`+0(C_wM`N?UV^Bq>$i82;047`K`AO9sfmeVtaY2_E+1#y6<*@^x^%(nSAqa(JP+WpG5x4 z>4%^0*4p-lm-6I;sCnJMJyGrU`xLngZP^tHy9=*=cXia$*7n_?IuJ>O^uo_I`4(V7AmRYkYY9^Ly4Rrn%8uYR>wNxWpR*lJ@_vej;d&T9Dn+z5P zm}#reImdi1Cp!t0ctJ(|ISoD8&&I<#pS#Eoh`jveMMoGvSWPc@q-(9uv^sO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ga_clear(drum_l_, frames_); enaga_clear(drum_r_, frames_); } + if (stems_on_) { + for (int s = 0; s < kStems; s++) { + enaga_clear(stems_[s][0], frames_); + enaga_clear(stems_[s][1], frames_); + } + } // One duck envelope for the whole mixer; false means idle, and then no chain touches it. duck_active_ = duck_.render(duck_curve_, frames_); } @@ -872,8 +878,17 @@ void Mixer::add_any(int track, float *mono, float *right, float *tap, bool tail) if (track < 0 || track >= kTracks || frames_ <= 0) return; // A drum track's dry sound goes to the drum bus while it is on; its sends stay its own. const bool to_bus = drum_on_ && (drum_tracks_ >> track & 1u) != 0; - add_through(chains_[track], mono, right, tap, to_bus ? drum_l_ : mix_l_, - to_bus ? drum_r_ : mix_r_, tail); + float *dry_l = to_bus ? drum_l_ : mix_l_; + float *dry_r = to_bus ? drum_r_ : mix_r_; + if (!stems_on_) { + add_through(chains_[track], mono, right, tap, dry_l, dry_r, tail); + return; + } + // STEMS: the chain adds into the track's stem, cleared at begin_block, and finish_block adds + // each stem to the bus it was going to, so the mix is what it is with stems off. + add_through(chains_[track], mono, right, tap, stems_[track][0], stems_[track][1], tail); + stems_added_ |= uint8_t(1u << track); + if (to_bus) stems_to_bus_ |= uint8_t(1u << track); } void Mixer::add_tail(int track, float *silence) { add_any(track, silence, nullptr, nullptr, true); } @@ -928,8 +943,28 @@ void Mixer::finish_block(float *out, int frames) { const int n = frames_; // --- the drum bus, into the mix before the returns join it ------------------------------- + // STEMS: the tracks' stems into the buses they were going to, before the drum bus works. + if (stems_on_ && n > 0) { + for (int t = 0; t < kTracks; t++) { + if ((stems_added_ >> t & 1u) == 0) continue; + const bool bus = (stems_to_bus_ >> t & 1u) != 0; + enaga_add(bus ? drum_l_ : mix_l_, stems_[t][0], n); + enaga_add(bus ? drum_r_ : mix_r_, stems_[t][1], n); + } + } + stems_added_ = 0; + stems_to_bus_ = 0; + if (drum_on_ && n > 0) drum_bus(n); + // STEMS: the returns' stem starts as the mix before them, negated; it becomes their sum below. + if (stems_on_ && n > 0) { + enaga_clear(stems_[kStemReturns][0], n); + enaga_clear(stems_[kStemReturns][1], n); + enaga_mix(stems_[kStemReturns][0], mix_l_, n, -1.0f); + enaga_mix(stems_[kStemReturns][1], mix_r_, n, -1.0f); + } + // --- send A: the delay ------------------------------------------------------------------- // A freeze keeps the delay running whatever its tail says, and while held cuts its feed. const bool freezing = freeze_.active(); @@ -1064,6 +1099,11 @@ void Mixer::finish_block(float *out, int frames) { strata_duck_mix(mix_r_, wet_r_, duck_curve_, reverb_duck_, n); } + if (stems_on_ && n > 0) { + enaga_mix(stems_[kStemReturns][0], mix_l_, n, 1.0f); + enaga_mix(stems_[kStemReturns][1], mix_r_, n, 1.0f); + } + // --- master ------------------------------------------------------------------------------ if (n > 0) master(n); diff --git a/dsp/buses.hpp b/dsp/buses.hpp index eaafc7c3..9c066512 100644 --- a/dsp/buses.hpp +++ b/dsp/buses.hpp @@ -359,6 +359,29 @@ class Mixer { // The three sends, the master chain, and the interleaved L R L R result for audio(). void finish_block(float *out, int frames); + // STEMS (the second review's proposal 12, option A): while on, every track's dry sound after + // its insert chain, fader and pan -- what it adds to the mix, before the drum bus and the + // master -- is also kept in a plane pair of its own, and the three send returns together in + // a ninth (kStemReturns): the mix after the returns less the mix before them, so the nine + // add up to what the master is fed. Off, nothing is kept and nothing costs. + static constexpr int kStemReturns = kTracks; + static constexpr int kStems = kTracks + 1; + // Cleared on the way on, so a stem never starts with what an earlier take left in it, + // whichever side of begin_block this lands on. + void set_stems(bool on) { + if (on && !stems_on_) { + for (int s = 0; s < kStems; s++) + for (int side = 0; side < 2; side++) + for (int i = 0; i < kMaxFrames; i++) stems_[s][side][i] = 0.0f; + } + stems_on_ = on; + stems_added_ = 0; + stems_to_bus_ = 0; + } + bool stems_on() const { return stems_on_; } + // Stem `stem`'s left (side 0) or right (side 1) plane for the block finish_block made. + const float *stem(int stem, int side) const { return stems_[stem][side]; } + // Introspection for the UI and the tests. float compressor_gain() const { return compressor_gain_; } float peak() const { return peak_; } @@ -463,6 +486,10 @@ class Mixer { float mix_l_[kMaxFrames] = {}; float mix_r_[kMaxFrames] = {}; + bool stems_on_ = false; + float stems_[kStems][2][kMaxFrames] = {}; + uint8_t stems_added_ = 0; // the tracks that added to their stems this block + uint8_t stems_to_bus_ = 0; // ... and of those, the ones going to the drum bus float send_a_[kMaxFrames] = {}; float send_a_right_[kMaxFrames] = {}; float send_b_[kMaxFrames] = {}; diff --git a/dsp/masterloops.h b/dsp/masterloops.h index c7c70141..bc4b44a9 100644 --- a/dsp/masterloops.h +++ b/dsp/masterloops.h @@ -13,6 +13,8 @@ #ifndef STRATA_MASTERLOOPS_H #define STRATA_MASTERLOOPS_H +#include + #ifdef __cplusplus extern "C" { #endif @@ -50,6 +52,14 @@ void strata_kill_eq(float *left, float *right, int n, float *state_l, float *sta /* The planes into audio()'s interleaved L R L R buffer, and silence in any frames past n. */ void strata_interleave(float *out, const float *left, const float *right, int n, int frames); +/* STEMS (app/storage.hpp, "stems"): one track's planes into the 16-channel file's frames as + * 16-bit PCM, little-endian as both the C674x and the host store an int16: out[i * stride] is + * left[i], out[i * stride + 1] right[i]. Rounded to nearest (ties to even), clamped to + * +-1 full scale (32768 a unit, as Enaga's wav::Writer), NaN as 0. Branch-free. Done here rather + * than through Writer::write, whose per-sample conversion costs several times more on 16 + * channels a block. */ +void strata_stem_pack16(int16_t *out, const float *left, const float *right, int stride, int n); + /* dst[i] += src[i] * (1 - depth * duck[i]): a return ducked by the sidechain curve (0 open, * 1 fully down), as the reverb's RDK uses it (dsp/buses.cpp). */ void strata_duck_mix(float *dst, const float *src, const float *duck, float depth, int n); diff --git a/dsp/masterloops.ti.c b/dsp/masterloops.ti.c index 31386af4..9f9befac 100644 --- a/dsp/masterloops.ti.c +++ b/dsp/masterloops.ti.c @@ -48,6 +48,27 @@ void strata_master_limit(float *restrict left, float *restrict right, int n, flo } } +/* A float clamped to the int16 range, plus 1.5 * 2^23, holds its nearest integer (ties to even) + * in the low bits of its mantissa: rounding and conversion in one add, with no float-to-int + * conversion and no branch. NaN is made 0 first. */ +static inline int16_t strata_pcm16(float x) { + union { float f; uint32_t u; } bits; + float y = (x == x ? x : 0.0f) * 32768.0f; + y = y > 32767.0f ? 32767.0f : y; + y = y < -32768.0f ? -32768.0f : y; + bits.f = y + 12582912.0f; + return (int16_t)(uint16_t)(bits.u & 0xFFFFu); +} + +void strata_stem_pack16(int16_t *restrict out, const float *restrict left, + const float *restrict right, int stride, int n) { + int i; + for (i = 0; i < n; i++) { + out[i * stride] = strata_pcm16(left[i]); + out[i * stride + 1] = strata_pcm16(right[i]); + } +} + void strata_interleave(float *restrict out, const float *restrict left, const float *restrict right, int n, int frames) { int i; diff --git a/tests/scenario_stems.sh b/tests/scenario_stems.sh new file mode 100755 index 00000000..5777f257 --- /dev/null +++ b/tests/scenario_stems.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# STEMS in the emulator (FUNC menu; docs/CONTROLS.md, "The FUNC menu"): from a stopped +# transport, the row starts the stems and the beat together (`STEMS `, `run int`), the beat +# records for about four seconds through two of Enaga's real recording streams (16 channels and +# the returns' stereo), and STOP ends the pass: `SAVED STEMS ` once both files are closed. No +# `STEMS: CARD TOO SLOW` on the way, and the load with the stems' extra mixing and the +# 16-channel interleave in audio() is inside the target. +# +# What the files hold, numbering, a JAM REC alongside and the menu row's clock are +# tests/test_storage.cpp's and tests/test_ui.cpp's (storage_stems_*, ui_stems_*): the emulator +# cannot hand the files back. +# +# Keys (third_party/enaga/include/enaga/abi.h): F1 = 19, F4 = 27 (FUNC + HOME: the menu), DOWN = 25, +# OK = 23, F6 = 29 (STOP). The row is found by name (tools/menu_rows.py). The first press comes +# late (tests/scenario_m1.sh). A 32 MiB card: a pass is about 7 MB, more than the default 4. +set -euo pipefail + +cd "$(dirname "$0")/.." +# shellcheck source=tools/env.sh +source tools/env.sh + +if [ "${1:-}" != "" ]; then + echo "error: unknown argument: $1" >&2 + exit 2 +fi + +if [ ! -f "$ENAGA_EMULATOR/cpu.py" ]; then + echo "SKIP: no emulator at $ENAGA_EMULATOR" >&2 + exit 0 +fi + +strata_require_toolchain +strata_link_emulator_toolchain +tools/build.sh > /dev/null + +STAGE="$ENAGA_BUILD/stage/STRATA" +mkdir -p "$ENAGA_BUILD" +LOG="$ENAGA_BUILD/scenario_stems.log" + +downs=$(python3 -B tools/menu_rows.py app/ui_perfmix.hpp MenuItem stems) +step=40000000 + +keys=() +at=300000000 +# FUNC + HOME, DOWN to STEMS, OK: the stems and the transport start. +keys+=(--key "19@$at" --key "27@$((at + 5000000))") +at=$((at + 80000000)) +for ((i = 0; i < downs; i++)); do + keys+=(--key "25@$at") + at=$((at + step)) +done +keys+=(--key "23@$at"); at=$((at + 1500000000)) +# About four seconds of the beat, then STOP. +keys+=(--key "29@$at"); at=$((at + 300000000)) +CYCLES=$((at + 100000000)) + +echo "running the emulator for $CYCLES cycles: STEMS for a pass ..." +python3 -B tools/enaga_cached.py emulate "$STAGE" --cycles "$CYCLES" --card-mib 32 "${keys[@]}" \ + > "$LOG" 2>&1 || { + echo "FAIL: emulate.py exited non-zero" >&2 + tail -30 "$LOG" >&2 + exit 1 +} + +rc=0 +python3 - "$LOG" <<'PY' || rc=$? +import json, os, re, sys + +CYCLES_PER_BLOCK = 496_000 + +text = open(sys.argv[1]).read() +match = re.search(r'^\{.*?^\}', text, re.S | re.M) +if not match: + print(" FAIL no JSON report in the emulator output") + sys.exit(1) +report = json.loads(match.group(0)) + +failures = [] + +def check(ok, label, detail=""): + print(f" {'ok ' if ok else 'FAIL'} {label}{' ' + detail if detail else ''}") + if not ok: + failures.append(label) + +log = report.get("log", []) + +check(report.get("app_status") == "APP RUNNING", "app is running", + f'status={report.get("app_status")!r}') +check(not report.get("crash_reason"), "no crash", f'reason={report.get("crash_reason")!r}') +def first(prefix): + for i, line in enumerate(log): + if line.startswith(prefix): + return i + return -1 + +check(first("STEMS ") >= 0, "the row started the stems", f"log={log}") +check("run int" in log, "the transport started with them", f"log={log}") +check(first("SAVED STEMS ") > first("STEMS "), "STOP ended them and both files closed", f"log={log}") +check(first("STEMS:") < 0, "the card kept up and nothing failed", f"log={log}") +check(first("CARD") < 0, "no card trouble", f"log={log}") + +blocks = report.get("audio_blocks", 0) +check(blocks > 1000, "audio ran throughout", f"blocks={blocks}") +check(report.get("audio_overruns", -1) == 0, "no audio overruns", + f'overruns={report.get("audio_overruns")}') + +peak = report.get("audio_cycles_peak", 0) +percent = 100.0 * peak / CYCLES_PER_BLOCK +check(percent > 5.0, "the beat was sounding", f"{percent:.2f}% peak") +gcc_only = os.environ.get("ENAGA_TI_CGT") == "none" +target = 70.0 if gcc_only else 60.0 +check(percent < target, f"load is under {target:.0f}% ({'GCC-only' if gcc_only else 'cl6x'})", + f"{percent:.2f}% peak") + +print() +print(f"emulator peak load: {percent:.2f}% ({peak} of {CYCLES_PER_BLOCK} cycles, {blocks} blocks)") + +sys.exit(1 if failures else 0) +PY + +echo +if [ "$rc" -ne 0 ]; then + echo "SCENARIO FAILED; full log: $LOG" >&2 + exit 1 +fi +echo "SCENARIO OK (log: $LOG)" diff --git a/tests/test_memory.cpp b/tests/test_memory.cpp index 62eb1022..4b375c24 100644 --- a/tests/test_memory.cpp +++ b/tests/test_memory.cpp @@ -20,6 +20,7 @@ // As Enaga's runtime does it (third_party/enaga/runtime/runtime.cpp, heap_alloc): an 8-byte // header, rounded up to 8, at least 16. Allocation happens once, in init(), and nothing is // freed, so a first-fit list never fragments and the sum is the whole story. +#include "stemring.hpp" #include "check.hpp" #include "fakehost.hpp" @@ -178,6 +179,10 @@ TEST(memory_init_is_what_the_budget_says) { const uint64_t audition = 32u * 1024u + 256u * 1024u; // JAM REC (app/storage.hpp, "jam recording"): its recording stream's ring, 1 MiB. const uint64_t jam = 1u * kMiB; + // STEMS (app/storage.hpp, "stems"): the tracks' 16-channel stream ring, 2 MiB (1.4 s at + // 1.5 MB/s), the send returns' stereo ring, 256 KiB, and 512 blocks of the planes audio() + // queues for the main context (core/stemring.hpp), 2.25 MiB. + const uint64_t stems = 2u * kMiB + 256u * 1024u + 512u * uint64_t(StemRing::kSlotFloats) * 4u; // app/engine: the beat-repeat ring (stereo float) and the resample take (stereo int16 plus // a WAV header, dsp/capture.hpp). @@ -214,7 +219,7 @@ TEST(memory_init_is_what_the_budget_says) { for (int t = 0; t < kTracks; t++) chain_lines += g_engine.mixer().chain(t).line_bytes(); CHECK(chain_lines >= uint64_t(kTracks) * 0.66 * 48000.0 * 4.0); - const uint64_t itemised = region + raw + src + file + rings + audition + jam + repeat + capture + freeze + tape + + const uint64_t itemised = region + raw + src + file + rings + audition + jam + stems + repeat + capture + freeze + tape + long_delay + hall + waves + locks + chain_lines; CHECK(f.requested >= itemised); @@ -222,13 +227,13 @@ TEST(memory_init_is_what_the_budget_says) { // them at 2 MiB, which is the bound here. const uint64_t buses = f.requested - itemised; std::printf(" region %.2f, loader staging %.2f, file %.2f, stream rings %.2f, repeat %.2f, " - "audition %.2f, jam %.2f, capture %.2f, freeze %.2f, tape stop %.2f, long delay %.2f, " + "audition %.2f, jam %.2f, stems %.2f, capture %.2f, freeze %.2f, tape stop %.2f, long delay %.2f, " "hall %.2f, " "wavetables %.2f, locks %.2f, chain lines %.2f, delay+reverb %.2f MiB\n", double(region) / double(kMiB), double(raw + src) / double(kMiB), double(file) / double(kMiB), double(rings) / double(kMiB), double(repeat) / double(kMiB), double(audition) / double(kMiB), - double(jam) / double(kMiB), double(capture) / double(kMiB), + double(jam) / double(kMiB), double(stems) / double(kMiB), double(capture) / double(kMiB), double(freeze) / double(kMiB), double(tape) / double(kMiB), double(long_delay) / double(kMiB), double(hall) / double(kMiB), double(waves) / double(kMiB), double(locks) / double(kMiB), diff --git a/tests/test_stemring.cpp b/tests/test_stemring.cpp new file mode 100644 index 00000000..6c32bcce --- /dev/null +++ b/tests/test_stemring.cpp @@ -0,0 +1,66 @@ +// core/stemring.hpp: STEMS' planes from audio() to the main context. +#include "check.hpp" +#include "stemring.hpp" + +using namespace strata; + +namespace { + +float g_slots[4 * StemRing::kSlotFloats]; +float g_planes[StemRing::kPlanes][StemRing::kFrames]; + +const float *const *planes_of(float base) { + static const float *pointers[StemRing::kPlanes]; + for (int p = 0; p < StemRing::kPlanes; p++) { + for (int i = 0; i < StemRing::kFrames; i++) g_planes[p][i] = base + float(p * 100 + i); + pointers[p] = g_planes[p]; + } + return pointers; +} + +} // namespace + +TEST(stemring_carries_blocks_in_order_with_their_frames) { + StemRing ring; + int frames = 0; + CHECK(ring.front(frames) == nullptr); // nothing attached + CHECK(!ring.push(planes_of(0.0f), 64)); + ring.attach(g_slots, 4); + CHECK(ring.front(frames) == nullptr); + CHECK(ring.push(planes_of(0.0f), 64)); + CHECK(ring.push(planes_of(10000.0f), 32)); + CHECK_EQ(ring.queued(), 2u); + const float *slot = ring.front(frames); + CHECK(slot != nullptr); + CHECK_EQ(frames, 64); + CHECK_EQ(slot[0], 0.0f); + CHECK_EQ(slot[17 * StemRing::kFrames + 63], 1763.0f); // plane 17, frame 63 + ring.pop(); + slot = ring.front(frames); + CHECK_EQ(frames, 32); + CHECK_EQ(slot[5 * StemRing::kFrames + 31], 10531.0f); + ring.pop(); + CHECK(ring.front(frames) == nullptr); + CHECK_EQ(ring.lost(), 0u); + CHECK(!ring.push(planes_of(0.0f), 0)); // no frames, or more than a block + CHECK(!ring.push(planes_of(0.0f), 65)); +} + +TEST(stemring_full_drops_a_block_whole_and_counts_its_frames) { + StemRing ring; + ring.attach(g_slots, 4); + for (int b = 0; b < 4; b++) CHECK(ring.push(planes_of(float(b)), 64)); + CHECK(!ring.push(planes_of(9.0f), 48)); + CHECK_EQ(ring.lost(), 48u); + int frames = 0; + CHECK_EQ(ring.front(frames)[0], 0.0f); // the oldest is kept, not overwritten + ring.pop(); + CHECK(ring.push(planes_of(5.0f), 64)); // and the slot comes back + for (int b = 1; b <= 4; b++) { + CHECK_EQ(ring.front(frames)[0], float(b == 4 ? 5 : b)); + ring.pop(); + } + ring.clear(); + CHECK_EQ(ring.lost(), 0u); + CHECK_EQ(ring.queued(), 0u); +} diff --git a/tests/test_storage.cpp b/tests/test_storage.cpp index 53099275..c8f40cf3 100644 --- a/tests/test_storage.cpp +++ b/tests/test_storage.cpp @@ -50,6 +50,7 @@ #include "serialize.hpp" #include "collect.hpp" #include "zones.hpp" +#include "masterloops.h" #include #include @@ -643,6 +644,8 @@ const Expect kTable[] = { // JAM REC writes /RECORD/JAM_.WAV, which is no project file. {Cmd::jam_start, 0u, "jam_start"}, {Cmd::jam_stop, 0u, "jam_stop"}, + {Cmd::stems_start, 0u, "stems_start"}, + {Cmd::stems_stop, 0u, "stems_stop"}, // GEN writes steps, and HOME puts them back: the bank. EVOLVE's settings are PROJECT.BIN's // (core/project.hpp), and HOME stops EVOLVE too. {Cmd::generate, kDirtyBank, "generate"}, @@ -5513,6 +5516,158 @@ TEST(storage_a_jam_never_hears_the_audition_or_the_click) { host.remove_file("/SAMPLES/AUD.WAV"); } +// --- STEMS: every track to the card at once (app/storage.hpp, "stems") ----------------------- + +namespace { + +bool pump_until_stems_closed(int limit = 50) { + for (int i = 0; i < limit && storage().stems_running(); i++) pump(); + return !storage().stems_running(); +} + +// A 16-bit little-endian sample at `p`, as a float of full scale 1. +float stem_sample(const uint8_t *p) { + return float(int16_t(uint16_t(p[0]) | uint16_t(p[1]) << 8)) / 32768.0f; +} + +} // namespace + +// The packer: to nearest, ties to even, clamped at full scale, NaN as silence, at its stride. +TEST(storage_stem_pack16_rounds_clamps_and_strides) { + const float left[6] = {0.0f, 1.5f / 32768.0f, -0.6f / 32768.0f, 2.0f, -2.0f, std::nanf("")}; + const float right[6] = {1.0f, -1.0f, 1000.0f / 32768.0f, -1000.4f / 32768.0f, 0.25f, 0.0f}; + int16_t out[6 * 4]; + for (int16_t &v : out) v = 77; + strata_stem_pack16(out + 2, left, right, 4, 6); + const int16_t want_l[6] = {0, 2, -1, 32767, -32768, 0}; + const int16_t want_r[6] = {32767, -32768, 1000, -1000, 8192, 0}; + for (int i = 0; i < 6; i++) { + CHECK_EQ(int(out[4 * i + 2]), int(want_l[i])); + CHECK_EQ(int(out[4 * i + 3]), int(want_r[i])); + CHECK_EQ(int(out[4 * i]), 77); // the other track's pair untouched + CHECK_EQ(int(out[4 * i + 1]), 77); + } +} + +TEST(storage_stems_write_each_track_to_its_own_channel_pair_and_the_returns_beside) { + clean(); + FakeHost &host = FakeHost::the(); + const bool dirty = storage().dirty(); + CHECK(storage().request_stems_start()); + CHECK(storage().stems_recording()); + CHECK(std::strncmp(storage().stems_name(), "STEMS_", 6) == 0); + char path[64], fx_path[64]; + std::snprintf(path, sizeof path, "/RECORD/%s", storage().stems_name()); + std::snprintf(fx_path, sizeof fx_path, "%.*s_FX.WAV", int(std::strlen(path) - 4), path); + pump(); + CHECK(engine().stems_attached()); + CHECK_EQ(host.streams_open(), 2); // the tracks' file and the returns' + + // A kick on track 1 and a delay send on it, so track 1's pair and the returns carry sound + // and every other track's pair is silent. + strata::test::put_trig(0, 0); + strata::test::post(Cmd::set_param, 0, 0, uint8_t(page_first(Page::fx) + 2), 100); + host.set_running(true); + float peak = 0.0f; + for (int b = 0; b < 200; b++) { + if (b == 0) host.deliver_tick(0, 0); + peak = std::fmax(peak, pump()); + } + CHECK(peak > 0.05f); + CHECK_EQ(storage().stems_lost_frames(), 0u); + + storage().request_stems_stop(); + CHECK(storage().stems_running()); // closing + CHECK(!storage().stems_recording()); + CHECK(pump_until_stems_closed()); + CHECK(!engine().stems_attached()); + CHECK_EQ(host.streams_open(), 0); + const char *message = storage().take_stems_message(); + CHECK(message != nullptr && std::strncmp(message, "SAVED STEMS ", 12) == 0); + + // The tracks: 16 channels of 16 bits, T1 L R, T2 L R ... + static uint8_t file[4u << 20]; + int32_t read = host.read_prefix(path, file, sizeof file); + CHECK_EQ(read, host.file_bytes(path)); + enaga::wav::Format format{}; + CHECK(enaga::wav::parse(file, uint32_t(read), format)); + CHECK_EQ(int(format.channels), 2 * kTracks); + CHECK_EQ(int(format.bits), 16); + CHECK_EQ(format.rate, 48000u); + const uint32_t frame_bytes = 2u * 2u * kTracks; + CHECK_EQ(format.data_bytes % frame_bytes, 0u); + CHECK_EQ(format.data_bytes / frame_bytes, engine().stems_writer().frames()); + float loudest[2 * kTracks] = {}; + for (uint32_t at = format.data_offset; at + frame_bytes <= format.data_offset + format.data_bytes; at += frame_bytes) { + for (int c = 0; c < 2 * kTracks; c++) + loudest[c] = std::fmax(loudest[c], std::fabs(stem_sample(file + at + 2u * uint32_t(c)))); + } + CHECK(loudest[0] > 0.05f); + CHECK(loudest[1] > 0.05f); + for (int c = 2; c < 2 * kTracks; c++) CHECK(loudest[c] < 1e-3f); + + // The returns: stereo 16-bit, as long as the tracks, with the delay in it. + read = host.read_prefix(fx_path, file, sizeof file); + CHECK_EQ(read, host.file_bytes(fx_path)); + CHECK(enaga::wav::parse(file, uint32_t(read), format)); + CHECK_EQ(int(format.channels), 2); + CHECK_EQ(int(format.bits), 16); + CHECK_EQ(format.data_bytes / 4u, engine().stems_writer().frames()); + float wet = 0.0f; + for (uint32_t at = format.data_offset; at + 2u <= format.data_offset + format.data_bytes; at += 2u) + wet = std::fmax(wet, std::fabs(stem_sample(file + at))); + CHECK(wet > 1e-3f); + + CHECK_EQ(storage().dirty(), dirty); // not a project file + host.set_running(false); + strata::test::post(Cmd::set_param, 0, 0, uint8_t(page_first(Page::fx) + 2), 0); + host.remove_file(path); + host.remove_file(fx_path); +} + +TEST(storage_stems_and_a_jam_record_together_and_stems_number_on) { + clean(); + FakeHost &host = FakeHost::the(); + CHECK(storage().request_stems_start()); + char first[24]; + std::snprintf(first, sizeof first, "%s", storage().stems_name()); + CHECK(storage().request_stems_start()); // a second start while one records: the same + CHECK(std::strcmp(storage().stems_name(), first) == 0); + CHECK(storage().request_jam_start()); + pump(5); + CHECK_EQ(host.streams_open(), 3); + CHECK(engine().jam_attached()); + CHECK(engine().stems_attached()); + storage().request_stems_stop(); + CHECK(!storage().request_stems_start()); // still closing + CHECK(std::strcmp(storage().take_stems_message(), "STEMS BUSY") == 0); + CHECK(pump_until_stems_closed()); + storage().take_stems_message(); + CHECK(storage().jam_recording()); // the jam goes on + storage().request_jam_stop(); + CHECK(pump_until_jam_closed()); + storage().take_jam_message(); + CHECK(storage().request_stems_start()); + CHECK(std::strcmp(storage().stems_name(), first) != 0); + char second[24]; + std::snprintf(second, sizeof second, "%s", storage().stems_name()); + pump(5); + storage().request_stems_stop(); + CHECK(pump_until_stems_closed()); + storage().take_stems_message(); + const char *names[] = {first, second}; + for (const char *name : names) { + char path[64]; + std::snprintf(path, sizeof path, "/RECORD/%s", name); + CHECK(host.has_file(path)); + host.remove_file(path); + std::snprintf(path, sizeof path, "/RECORD/%.*s_FX.WAV", int(std::strlen(name) - 4), name); + CHECK(host.has_file(path)); + host.remove_file(path); + } + host.remove_file(jam_path()); +} + TEST(storage_jams_are_numbered_and_never_replace_each_other) { clean(); FakeHost &host = FakeHost::the(); diff --git a/tests/test_ui.cpp b/tests/test_ui.cpp index cdb084d1..aca5d560 100644 --- a/tests/test_ui.cpp +++ b/tests/test_ui.cpp @@ -448,7 +448,7 @@ void open_keys() { } // The FUNC menu's rows, in order (app/ui_perfmix.hpp, MenuItem). -enum MenuRow : int { kMenuSave, kMenuJam, kMenuArr, kMenuCatch, kMenuClick, kMenuCountIn, kMenuRecMode, +enum MenuRow : int { kMenuSave, kMenuJam, kMenuArr, kMenuCatch, kMenuStems, kMenuClick, kMenuCountIn, kMenuRecMode, kMenuQuantize, kMenuAutofill, kMenuGlide, kMenuTranspose, kMenuLoopLen, kMenuChain, kMenuSong, kMenuArrUndo, kMenuProgOut, kMenuTempoGuard, kMenuSaveAs, kMenuOpen, @@ -14951,6 +14951,90 @@ TEST(ui_hold_ok_in_keys_opens_the_track_menu) { CHECK(!screen_has(app, "OK: RUN")); } +// STEMS (app/storage.hpp, "stems"): the FUNC menu's row under CATCH. From a stopped transport +// OK starts the stems and the transport together and closes the menu; the top bar's dot blinks +// as for a jam; the row counts the time; STOP ends the pass and the stems are saved. +TEST(ui_stems_one_ok_records_a_pass_and_stop_ends_it) { + Strata &app = fresh(); + FakeHost &host = FakeHost::the(); + host.set_running(false); + pump(2); + menu_to(kMenuStems); + CHECK(screen_has(app, "STEMS")); + CHECK(screen_has(app, "OFF")); + key(ENAGA_KEY_OK); + pump(2); + CHECK(app_storage().stems_recording()); + CHECK(host.running()); // the transport started with it + CHECK_EQ(UiProbe::mode(app), int(Mode::grid)); // closed, as JAM REC's start + CHECK(std::strncmp(UiProbe::notice(app), "STEMS ", 6) == 0); + check_layout(app, "STEMS started"); + char name[24]; + std::snprintf(name, sizeof name, "%s", app_storage().stems_name()); + enaga::Canvas canvas(g_pixels); + int lit = 0; + for (int i = 0; i < 1000; i++) { + pump(); + app.draw(canvas); + lit += pixel_at(76, 3) == 15 ? 1 : 0; + } + CHECK(lit >= 595 && lit <= 605); + menu_to(kMenuStems); + CHECK(screen_has(app, "0:01")); + check_layout(app, "STEMS row running"); + key(ENAGA_KEY_CLR); + pump(2); + + key(ENAGA_KEY_F6); // STOP: the pass is over + bool saved = false; + for (int i = 0; i < 20 && !saved; i++) { + pump(); + saved = std::strncmp(UiProbe::notice(app), "SAVED STEMS ", 12) == 0; + } + CHECK(saved); + CHECK(!app_storage().stems_running()); + char path[64]; + std::snprintf(path, sizeof path, "/RECORD/%s", name); + CHECK(host.file_bytes(path) > 44 + 1000 * 64 * 32); + host.remove_file(path); + std::snprintf(path, sizeof path, "/RECORD/%.*s_FX.WAV", int(std::strlen(name) - 4), name); + CHECK(host.has_file(path)); + host.remove_file(path); + host.set_running(false); + pump(2); +} + +// While the transport runs, OK starts the stems where the song is, and OK again stops them. +TEST(ui_stems_ok_again_stops_them_with_the_transport_running) { + Strata &app = fresh(); + FakeHost &host = FakeHost::the(); + host.set_running(true); + menu_to(kMenuStems); + key(ENAGA_KEY_OK); + pump(20); + CHECK(app_storage().stems_recording()); + menu_to(kMenuStems); + key(ENAGA_KEY_OK); + CHECK_EQ(UiProbe::notice(app), "STEMS STOPPING"); + bool saved = false; + for (int i = 0; i < 20 && !saved; i++) { + pump(); + saved = std::strncmp(UiProbe::notice(app), "SAVED STEMS ", 12) == 0; + } + CHECK(saved); + CHECK(host.running()); // the music goes on + key(ENAGA_KEY_CLR); + char name[24]; + std::snprintf(name, sizeof name, "%s", app_storage().stems_name()); + char path[64]; + std::snprintf(path, sizeof path, "/RECORD/%s", name); + host.remove_file(path); + std::snprintf(path, sizeof path, "/RECORD/%.*s_FX.WAV", int(std::strlen(name) - 4), name); + host.remove_file(path); + host.set_running(false); + pump(2); +} + TEST(ui_jam_rec_without_a_card_says_why) { Strata &app = fresh(); FakeHost &host = FakeHost::the(); diff --git a/tools/split_stems.py b/tools/split_stems.py new file mode 100755 index 00000000..fed9d562 --- /dev/null +++ b/tools/split_stems.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Split a STEMS recording into one stereo WAV a track. + +STEMS (the FUNC menu's row) writes every track into one 16-channel 16-bit WAV, T1 left, T1 right, +T2 left ... T8 right, because the SmplTrek's file layer opens few streams at once +(app/storage.hpp, "stems"). This turns it into eight stereo WAVs beside it: + + python3 tools/split_stems.py STEMS_3.WAV -> STEMS_3_T1.WAV ... STEMS_3_T8.WAV + python3 tools/split_stems.py --skip-silent STEMS_3.WAV + python3 tools/split_stems.py -o OUTDIR STEMS_*.WAV + +STEMS_3_FX.WAV, the delay, reverb and chorus returns, is a stereo WAV already: it needs no split. +All nine together, at unity, are the mix before the drum bus and the master. +Standard library only. +""" +import argparse +import array +import os +import sys +import wave + +TRACKS = 8 +assert array.array("I").itemsize == 4, "a 32-bit word holds one stereo pair" +CHUNK = 48000 # frames read at a time + + +def split(path, out_dir, skip_silent): + with wave.open(path, "rb") as src: + channels, width, rate = src.getnchannels(), src.getsampwidth(), src.getframerate() + if channels != 2 * TRACKS or width != 2: + sys.exit("%s: %d channels of %d bits, not a STEMS file (16 channels of 16 bits)" + % (path, channels, 8 * width)) + base = os.path.splitext(os.path.basename(path))[0] + names = [os.path.join(out_dir, "%s_T%d.WAV" % (base, t + 1)) for t in range(TRACKS)] + outs = [] + for name in names: + w = wave.open(name, "wb") + w.setnchannels(2) + w.setsampwidth(2) + w.setframerate(rate) + outs.append(w) + peak = [0] * TRACKS + frame = 2 * TRACKS * 2 + while True: + data = src.readframes(CHUNK) + if not data: + break + # One 32-bit word is one track's stereo pair of 16-bit samples, so every eighth word + # is a track's: a stride, with no per-sample work and no byte order to mind. + words = array.array("I") + words.frombytes(data[:len(data) // frame * frame]) + for t in range(TRACKS): + pair = words[t::TRACKS] + outs[t].writeframes(pair.tobytes()) + if skip_silent and peak[t] == 0 and any(pair): + peak[t] = 1 + for w in outs: + w.close() + written = [] + for t, name in enumerate(names): + if skip_silent and peak[t] == 0: + os.remove(name) + else: + written.append(name) + return written + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("files", nargs="+", help="STEMS_.WAV files") + parser.add_argument("-o", "--out", help="folder for the stereo WAVs (default: beside each file)") + parser.add_argument("--skip-silent", action="store_true", help="leave out tracks that are all zero") + args = parser.parse_args() + for path in args.files: + if path.upper().endswith("_FX.WAV"): + print("%s: the returns, stereo already" % path) + continue + out_dir = args.out or os.path.dirname(os.path.abspath(path)) + os.makedirs(out_dir, exist_ok=True) + for name in split(path, out_dir, args.skip_silent): + print(name) + + +if __name__ == "__main__": + main() From 82d2c54ed7e0dc0a4c5368095ea3a3d75e44b309 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:22:21 +0000 Subject: [PATCH 3/3] JAM REC scenario: walk to the row by name #312 put GEN ALL one DOWN from SAVE, and the scenario's single DOWN ran GEN ALL instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Tw2EaEK2oaJWJMdGQTNLPf --- tests/scenario_jamrec.sh | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/tests/scenario_jamrec.sh b/tests/scenario_jamrec.sh index 7bd90e15..2ee39443 100755 --- a/tests/scenario_jamrec.sh +++ b/tests/scenario_jamrec.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# JAM REC in the emulator: PLAY starts the default beat, the FUNC menu's second row (one DOWN -# from SAVE) starts a jam (`JAM REC JAM ` in the log), the beat records for about four seconds +# JAM REC in the emulator: PLAY starts the default beat, the FUNC menu's JAM REC row (found by +# name, tools/menu_rows.py) starts a jam (`JAM REC JAM ` in the log), the beat records for about four seconds # through Enaga's real recording stream, and the same row stops it: `JAM STOPPING`, then # `SAVED JAM ` once the file is closed with its header. No `JAM: CARD TOO SLOW` on the way, # and the load with the jam's 24-bit conversion in audio() is inside the target. @@ -42,10 +42,20 @@ mkdir -p "$ENAGA_BUILD" LOG="$ENAGA_BUILD/scenario_jamrec.log" echo "running the emulator for $CYCLES cycles: PLAY, JAM REC on, four seconds, JAM REC off ..." -python3 -B tools/enaga_cached.py emulate "$STAGE" --cycles "$CYCLES" \ - --key 22@300000000 \ - --key 19@400000000 --key 27@405000000 --key 25@460000000 --key 23@520000000 \ - --key 19@2000000000 --key 27@2005000000 --key 25@2060000000 --key 23@2120000000 \ +# DOWN from SAVE to JAM REC, counted from the menu's own order, so a row added above it does not +# move the walk off it. +downs=$(python3 -B tools/menu_rows.py app/ui_perfmix.hpp MenuItem jam) +keys=(--key 22@300000000) +for start in 400000000 2000000000; do + keys+=(--key "19@$start" --key "27@$((start + 5000000))") + at=$((start + 60000000)) + for ((i = 0; i < downs; i++)); do + keys+=(--key "25@$at") + at=$((at + 40000000)) + done + keys+=(--key "23@$((at + 20000000))") +done +python3 -B tools/enaga_cached.py emulate "$STAGE" --cycles "$CYCLES" "${keys[@]}" \ > "$LOG" 2>&1 || { echo "FAIL: emulate.py exited non-zero" >&2 tail -30 "$LOG" >&2