diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c2efc75..464bbd67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,18 @@ the project file format or the controls. longer, 1,615 bytes; older builds read it). A scene or a lock made on a PERC track that was once a synth, and a user sound saved from one, can carry old bytes into the page: set NSE to 0 and save again. +- **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 + 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 5e22b49b..2a2bb88a 100644 --- a/app/app.hpp +++ b/app/app.hpp @@ -43,6 +43,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 @@ -956,6 +957,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 @@ -1356,6 +1359,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/commands.hpp b/app/commands.hpp index 202bab28..e6867428 100644 --- a/app/commands.hpp +++ b/app/commands.hpp @@ -501,6 +501,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 @@ -807,6 +811,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 66433c1e..5f186f42 100644 --- a/app/engine.cpp +++ b/app/engine.cpp @@ -2877,6 +2877,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 @@ -4287,6 +4300,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 @@ -5346,6 +5361,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 df5c05bf..08911d3d 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 @@ -420,6 +421,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); @@ -670,6 +681,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 598e81b4..2af88dcc 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"; @@ -291,6 +293,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); @@ -1903,6 +1910,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. @@ -4446,6 +4454,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. @@ -4587,6 +4772,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 15df65a8..04350c8e 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. @@ -1073,6 +1106,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 cd86d0c5..e4aa2db3 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 @@ -389,6 +537,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 c492bba2..007a7e4f 100644 --- a/app/ui_perfmix.hpp +++ b/app/ui_perfmix.hpp @@ -17,7 +17,8 @@ // the file actions after them; then SET, the settings. The screen keys jump between the two // (LEFT: SAVE, RIGHT: CLICK), so no row is more than a few presses from where the list // opens. The selected track's rows are in GRID's track menu (app/ui_trackmenu.hpp). - enum class MenuItem : uint8_t { save, gen_all, jam, arr, arr_undo, save_as, open, kits, fresh, + enum class MenuItem : uint8_t { save, gen_all, jam, arr, catch_take, stems, + arr_undo, save_as, open, kits, fresh, reload, clear, demo, click, count_in, rec_mode, quantize, autofill, glide, transpose, loop_len, chain, song, prog_out, tempo_guard, @@ -53,6 +54,8 @@ 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::stems: return "STEMS"; case MenuItem::arr_undo: return "ARR UNDO"; default: return "?"; } @@ -126,6 +129,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; } @@ -146,10 +153,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 ------------------------------- @@ -243,6 +253,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; } @@ -964,12 +1017,19 @@ 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; 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/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 080d61ba..38fad52b 100644 --- a/core/help.cpp +++ b/core/help.cpp @@ -490,6 +490,28 @@ constexpr Text kKeysLayout = {"KEYS LAYOUT:", { "SAVED WITH PROJECT", }}; +// 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", +}}; + +// 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: A VALUE TURN IS", @@ -996,6 +1018,8 @@ 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++] = &kStems; list[listed++] = &kTempoGuard; list[listed++] = &kKeysLayout; break; 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 ed9c3dd0..c262968c 100644 --- a/docs/BUDGET.md +++ b/docs/BUDGET.md @@ -463,6 +463,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 W130). + ### 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 c41c201a..6adc2f9a 100644 --- a/docs/CHEATSHEET.md +++ b/docs/CHEATSHEET.md @@ -212,13 +212,14 @@ 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):** DO: SAVE, GEN ALL, JAM REC, ARR REC, ARR UNDO, SAVE AS, OPEN PROJECT, +**FUNC menu (FUNC+HOME):** DO: SAVE, GEN ALL, 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), ARR UNDO, SAVE AS, OPEN PROJECT, KITS, NEW PROJECT, RELOAD PROJECT, CLEAR PATTERN, LOAD DEMO. SET: CLICK, COUNT-IN, REC MODE, QUANTIZE, AUTO-FILL, FX GLIDE, TRANSPOSE (SCALE or SEMI), LOOP LEN, CHAIN, CHAIN END, PROG CHG OUT, TEMPO GUARD (ON: VALUE's turn is ENERGY and its tap shows the tempo; saved), KEYS LAYOUT (PIANO or SCALE: the pads as the key's degrees, chords on a chord track's lower pads; saved). It always opens on SAVE: DOWN once is GEN ALL (GENERATE on every unmuted track, each of its own TYPE, one undo level; OK -again for another), twice JAM REC, three times ARR REC. The right screen key jumps to SET (CLICK), +again for another), twice JAM REC, three times ARR REC, four CATCH, five STEMS. The right screen key jumps to SET (CLICK), the left one back to SAVE. 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 setting row (OK steps it too), CLR or FUNC+HOME close it. **Track menu (hold OK in GRID):** diff --git a/docs/CONTROLS.md b/docs/CONTROLS.md index 4d9c0526..6704e7da 100644 --- a/docs/CONTROLS.md +++ b/docs/CONTROLS.md @@ -196,14 +196,16 @@ the setting rows used to sit between SAVE and the file rows.) | GEN ALL | GENERATE on every unmuted track at once, each of its own TYPE, with the track menu's DENSITY, RANGE, LEAP and WHAT: a whole idea from one press. One undo level (FUNC + CLR takes every track back at once); the menu stays open, so OK again is the next idea. A lane playing another pattern's part (LAUNCH) is passed over. `GEN ALL: ALL MUTED` when nothing would be written. The second row: FUNC + HOME, DOWN | `GEN ALL 7 TRACKS` | | 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, 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 three times, 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. FUNC + HOME, DOWN four times, OK. 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`); FUNC + HOME, DOWN five times, OK; 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` | | ARR UNDO | swaps the chain the last ARR REC take replaced back in (`ARR UNDONE`); OK again brings the take back (`ARR REDONE`), unless the take captured launched lanes: then the undo also empties the slots it captured into and is final. `NO ARR TO UNDO` with none, or during a take | | | SAVE AS | PROJECTS page with the name entry open | | | OPEN PROJECT | PROJECTS page; OK twice there opens | | | KITS | the kit browser | | | NEW PROJECT | OK twice within 2 s: a new, empty project (the factory sounds, every pan centred, no steps, scenes or macros) | | | RELOAD PROJECT | OK twice within 2 s: read the project back from the card | | -| CLEAR PATTERN | OK twice within 2 s: every track's trigs and locks gone, one undo level (FUNC + CLR). FUNC + HOME, DOWN ten times | | -| LOAD DEMO | OK twice within 2 s: the factory demo project (the boot beat), under a new name. FUNC + HOME, DOWN eleven times | | +| CLEAR PATTERN | OK twice within 2 s: every track's trigs and locks gone, one undo level (FUNC + CLR). FUNC + HOME, DOWN twelve times | | +| LOAD DEMO | OK twice within 2 s: the factory demo project (the boot beat), under a new name. FUNC + HOME, DOWN thirteen times | | | 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 2fe00da4..9342f4c1 100644 --- a/docs/DESIGN_NOTES.md +++ b/docs/DESIGN_NOTES.md @@ -916,3 +916,55 @@ the result and leaves the detail where it was. brings its drive back down, so a hard CLP spends the headroom PSH made. Hence CLP climbs slowest. Measured on one beat; a sparse or a sustained mix moves differently, which is what OWN is for. + +## 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(). + +## 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 e90bc138..fd82a220 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -258,6 +258,8 @@ 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 | ○ (W130), 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 | ○ (W129), 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 | | LOUD (MIXER CLIP, knob C): PSH, CLP, MNO and GLU on one tuned curve | Unreleased | ○ (W128), E (scenario_loud.sh) | Stores nothing: read back from the four bytes, `OWN` when one was turned by hand. Curve measured on A01 only (host render) | | KEYS LAYOUT (FUNC menu): SCALE puts the key's degrees on the pads, triads on a chord track's lower pads | Unreleased | ○ (W127), E (scenario_keyslayout.sh) | PIANO by default; saved with the project (one byte on the end of PROJECT.BIN's MIDI section). The emulator has no pads, so the notes are host-tested | | TEMPO GUARD (FUNC menu): VALUE's plain turn is ENERGY (review 2026-11-30, proposal 10) and its tap shows the tempo; both 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 | diff --git a/docs/MANUAL.md b/docs/MANUAL.md index c12236a9..a1bfc6ae 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -1525,7 +1525,7 @@ To hear it, set CHAIN END to SONG, turn CHAIN on and press PLAY from stop: the j its patterns, mutes, scenes, breakdowns, key changes and tempo changes, quantized to whole passes. Edit any entry on the CHAIN page or in its SECTION view. A morph swept by hand is written as the side it ended a pass nearer to; set RIDE or BACK on the entry for a sweep. **ARR UNDO** (the FUNC menu, -under ARR REC) swaps the chain from before the take back in (`ARR UNDONE`), and OK again brings +under STEMS) swaps the chain from before the take back in (`ARR UNDONE`), and OK again brings the take back (`ARR REDONE`). It keeps one chain until the next take or until a project is opened. After a take that wrote launched tracks into slots, ARR UNDO also empties those slots, so the jam leaves nothing behind in the bank; a slot you have edited since, or one playing at that @@ -1585,6 +1585,32 @@ 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. +**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 four +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`. + +**STEMS records every track apart, for mixing on a computer.** **STEMS** (FUNC menu, under CATCH: +FUNC + HOME, DOWN five 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, the first row of its SET part, with COUNT-IN below

**CLICK and COUNT-IN** (FUNC menu, the first two rows of its SET part). CLICK `ON` clicks every beat while the transport runs, a diff --git a/docs/UNIT_CHECKLIST.md b/docs/UNIT_CHECKLIST.md index 04eee1dd..85565058 100644 --- a/docs/UNIT_CHECKLIST.md +++ b/docs/UNIT_CHECKLIST.md @@ -3812,3 +3812,22 @@ the key A minor (PROJECT page, B to A, C to MINOR), PLAY. - While LUD turns, EQ's D (PSH), CLIP's A and B, DRUMS's C move with it. Turn CLP on its own: LUD reads `OWN`. Turn LUD one detent: all four are back on the curve. `____` - SAVE, RELOAD PROJECT: LUD reads what it read before the save. `____` +**W129. 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). `____` + +**W130. STEMS: every track to the card (5 min).** Load the demo (FUNC menu, LOAD DEMO), stopped. +- FUNC + HOME, DOWN five 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/chain.png b/docs/screens/chain.png index 59ebdb55..cd55a775 100644 Binary files a/docs/screens/chain.png and b/docs/screens/chain.png differ diff --git a/docs/screens/edit.png b/docs/screens/edit.png index 77aed2de..5f7977ae 100644 Binary files a/docs/screens/edit.png and b/docs/screens/edit.png differ diff --git a/docs/screens/edit_amp.png b/docs/screens/edit_amp.png index ecaf37fc..27d24da6 100644 Binary files a/docs/screens/edit_amp.png and b/docs/screens/edit_amp.png differ diff --git a/docs/screens/edit_arp.png b/docs/screens/edit_arp.png index db9e25bc..ab666224 100644 Binary files a/docs/screens/edit_arp.png and b/docs/screens/edit_arp.png differ diff --git a/docs/screens/edit_asr.png b/docs/screens/edit_asr.png index b9870e02..6496d037 100644 Binary files a/docs/screens/edit_asr.png and b/docs/screens/edit_asr.png differ diff --git a/docs/screens/edit_fltr.png b/docs/screens/edit_fltr.png index 3dac2231..d45d73eb 100644 Binary files a/docs/screens/edit_fltr.png and b/docs/screens/edit_fltr.png differ diff --git a/docs/screens/edit_grain.png b/docs/screens/edit_grain.png index 62754e06..10815b80 100644 Binary files a/docs/screens/edit_grain.png and b/docs/screens/edit_grain.png differ diff --git a/docs/screens/edit_lfo.png b/docs/screens/edit_lfo.png index 127b81ad..b1597eee 100644 Binary files a/docs/screens/edit_lfo.png and b/docs/screens/edit_lfo.png differ diff --git a/docs/screens/edit_scan.png b/docs/screens/edit_scan.png index 13a70a6c..7b726e5f 100644 Binary files a/docs/screens/edit_scan.png and b/docs/screens/edit_scan.png differ diff --git a/docs/screens/edit_vfltr.png b/docs/screens/edit_vfltr.png index cae4e0ba..9a80b94e 100644 Binary files a/docs/screens/edit_vfltr.png and b/docs/screens/edit_vfltr.png differ diff --git a/docs/screens/edit_wave.png b/docs/screens/edit_wave.png index d35301a8..1c22c989 100644 Binary files a/docs/screens/edit_wave.png and b/docs/screens/edit_wave.png differ diff --git a/docs/screens/edit_wave_amp.png b/docs/screens/edit_wave_amp.png index adf2bfdb..e6870c66 100644 Binary files a/docs/screens/edit_wave_amp.png and b/docs/screens/edit_wave_amp.png differ diff --git a/docs/screens/help_keys.png b/docs/screens/help_keys.png index e8839c96..dfdc7caa 100644 Binary files a/docs/screens/help_keys.png and b/docs/screens/help_keys.png differ diff --git a/docs/screens/keys.png b/docs/screens/keys.png index 070b9e5e..ea9ec544 100644 Binary files a/docs/screens/keys.png and b/docs/screens/keys.png differ diff --git a/docs/screens/kit.png b/docs/screens/kit.png index dd0021ea..1eb3ff37 100644 Binary files a/docs/screens/kit.png and b/docs/screens/kit.png differ diff --git a/docs/screens/machine.png b/docs/screens/machine.png index c07e3c2a..f9ecdfa8 100644 Binary files a/docs/screens/machine.png and b/docs/screens/machine.png differ diff --git a/docs/screens/menu.png b/docs/screens/menu.png index 1e04e021..1a9f75ac 100644 Binary files a/docs/screens/menu.png and b/docs/screens/menu.png differ diff --git a/docs/screens/mixer_dck.png b/docs/screens/mixer_dck.png index 7dd8d323..532dda42 100644 Binary files a/docs/screens/mixer_dck.png and b/docs/screens/mixer_dck.png differ diff --git a/docs/screens/mixer_dly.png b/docs/screens/mixer_dly.png index 0d7f012a..a55821af 100644 Binary files a/docs/screens/mixer_dly.png and b/docs/screens/mixer_dly.png differ diff --git a/docs/screens/mixer_eq.png b/docs/screens/mixer_eq.png index 7f7b175e..553d24c3 100644 Binary files a/docs/screens/mixer_eq.png and b/docs/screens/mixer_eq.png differ diff --git a/docs/screens/mixer_in.png b/docs/screens/mixer_in.png index 3db8f6b6..61668f1a 100644 Binary files a/docs/screens/mixer_in.png and b/docs/screens/mixer_in.png differ diff --git a/docs/screens/mixer_mst.png b/docs/screens/mixer_mst.png index 07491267..fcf5fc34 100644 Binary files a/docs/screens/mixer_mst.png and b/docs/screens/mixer_mst.png differ diff --git a/docs/screens/mutate.png b/docs/screens/mutate.png index a307c1a5..0ac3b942 100644 Binary files a/docs/screens/mutate.png and b/docs/screens/mutate.png differ diff --git a/docs/screens/overview.png b/docs/screens/overview.png index 0ce3c4bc..4777e84f 100644 Binary files a/docs/screens/overview.png and b/docs/screens/overview.png differ diff --git a/docs/screens/pattern.png b/docs/screens/pattern.png index ca1ae929..faf9bef2 100644 Binary files a/docs/screens/pattern.png and b/docs/screens/pattern.png differ diff --git a/docs/screens/perform.png b/docs/screens/perform.png index 5ff622fb..5515e301 100644 Binary files a/docs/screens/perform.png and b/docs/screens/perform.png differ diff --git a/docs/screens/prep.png b/docs/screens/prep.png index 3b4a7698..13cd256a 100644 Binary files a/docs/screens/prep.png and b/docs/screens/prep.png differ diff --git a/docs/screens/prep_slice.png b/docs/screens/prep_slice.png index e4a92126..67febb82 100644 Binary files a/docs/screens/prep_slice.png and b/docs/screens/prep_slice.png differ diff --git a/docs/screens/prep_write.png b/docs/screens/prep_write.png index 800a4c0e..08f6ecec 100644 Binary files a/docs/screens/prep_write.png and b/docs/screens/prep_write.png differ diff --git a/docs/screens/project.png b/docs/screens/project.png index 3bfd47f3..835ef54e 100644 Binary files a/docs/screens/project.png and b/docs/screens/project.png differ diff --git a/docs/screens/projects.png b/docs/screens/projects.png index 06109c67..17c8fb73 100644 Binary files a/docs/screens/projects.png and b/docs/screens/projects.png differ diff --git a/docs/screens/resample.png b/docs/screens/resample.png index 55b8aa1b..7a8894d9 100644 Binary files a/docs/screens/resample.png and b/docs/screens/resample.png differ diff --git a/docs/screens/resample_auto.png b/docs/screens/resample_auto.png index 58cdbc39..6c8c7308 100644 Binary files a/docs/screens/resample_auto.png and b/docs/screens/resample_auto.png differ diff --git a/docs/screens/samples.png b/docs/screens/samples.png index d347100a..37065cc4 100644 Binary files a/docs/screens/samples.png and b/docs/screens/samples.png differ diff --git a/docs/screens/scene.png b/docs/screens/scene.png index 8406da1b..2dbe9322 100644 Binary files a/docs/screens/scene.png and b/docs/screens/scene.png differ diff --git a/docs/screens/section.png b/docs/screens/section.png index 1ab281f1..3c631a5e 100644 Binary files a/docs/screens/section.png and b/docs/screens/section.png differ diff --git a/docs/screens/setup.png b/docs/screens/setup.png index 14f6df13..45527d71 100644 Binary files a/docs/screens/setup.png and b/docs/screens/setup.png differ diff --git a/docs/screens/sounds.png b/docs/screens/sounds.png index b1db1dcb..6b27e73f 100644 Binary files a/docs/screens/sounds.png and b/docs/screens/sounds.png differ diff --git a/docs/screens/step.png b/docs/screens/step.png index 5a3a0b12..bb3a6d2f 100644 Binary files a/docs/screens/step.png and b/docs/screens/step.png differ diff --git a/docs/screens/zones.png b/docs/screens/zones.png index f13b9a18..d2445720 100644 Binary files a/docs/screens/zones.png and b/docs/screens/zones.png differ diff --git a/dsp/buses.cpp b/dsp/buses.cpp index cb38998b..98d6ca80 100644 --- a/dsp/buses.cpp +++ b/dsp/buses.cpp @@ -854,6 +854,12 @@ void Mixer::begin_block(int frames) { enaga_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_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/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 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_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_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 4a20cc48..e334b430 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 @@ -647,6 +648,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"}, @@ -5517,6 +5520,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 feeceb49..8374096b 100644 --- a/tests/test_ui.cpp +++ b/tests/test_ui.cpp @@ -454,7 +454,8 @@ void open_keys() { } // The FUNC menu's rows, in order (app/ui_perfmix.hpp, MenuItem). -enum MenuRow : int { kMenuSave, kMenuGenAll, kMenuJam, kMenuArr, kMenuArrUndo, kMenuSaveAs, +enum MenuRow : int { kMenuSave, kMenuGenAll, kMenuJam, kMenuArr, kMenuCatch, kMenuStems, + kMenuArrUndo, kMenuSaveAs, kMenuOpen, kMenuKits, kMenuNew, kMenuReload, kMenuClear, kMenuDemo, kMenuClick, kMenuCountIn, kMenuRecMode, kMenuQuantize, kMenuAutofill, kMenuGlide, kMenuTranspose, kMenuLoopLen, kMenuChain, kMenuSong, @@ -10519,6 +10520,76 @@ TEST(ui_keys_scale_layout_plays_the_key_and_chords_on_a_poly_track) { CHECK(!app_engine().project().settings.keys_scale); } +// 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(); @@ -15277,6 +15348,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()