- Sampler parameter oneShot (Off/On): note-offs don't release its pads; they play their whole slice. Transport stop/pause still releases (SampleVoice:: release), panic kills - Engine in core/ and the Kotlin reference both implement it; the golden Sampler "high" scenario covers it; oneshot_test checks MIDI, song, stop, panic - ONE-SHOT toggle in both apps' Sampler editors; specs and layouts regenerated Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1296 lines
53 KiB
C++
1296 lines
53 KiB
C++
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// Port of AudioEngine.kt, line for line where it makes sound. Kotlin's types are
|
|
// kept (Float -> float, Double -> double); kotlin.math goes through KotlinMath.hpp.
|
|
// Volatile Kotlin references (project, playlist, channelChains) become atomics;
|
|
// replaced playlists / chains are retired and freed by a later main-thread rebuild
|
|
// once the audio thread has finished a block after the swap.
|
|
|
|
#pragma clang fp contract(off)
|
|
|
|
#include "sizzle/Engine.hpp"
|
|
|
|
#include <atomic>
|
|
#include <cmath>
|
|
#include <cstring>
|
|
#include <limits>
|
|
#include <random>
|
|
#include <vector>
|
|
|
|
#include "KotlinMath.hpp"
|
|
#include "engine/ChannelArp.hpp"
|
|
#include "echofield/GrainCloud.hpp"
|
|
#include "frasil/FrasilVoice.hpp"
|
|
#include "model/TimeDivision.hpp"
|
|
#include "sampler/SampleStore.hpp"
|
|
#include "sampler/SampleVoice.hpp"
|
|
#include "sizzle/Effect.hpp"
|
|
#include "sizzle/Model.hpp"
|
|
#include "sizzle/Specs.hpp"
|
|
#include "synth/SynthPatch.hpp"
|
|
#include "synth/SynthVoice.hpp"
|
|
#include "wavetable/WaveVoice.hpp"
|
|
|
|
namespace sizzle::engine {
|
|
|
|
using model::Project;
|
|
using model::ToolboxSlot;
|
|
using sampler::SampleVoice;
|
|
using sampler::VoiceSample;
|
|
using synth::SynthPatch;
|
|
using synth::SynthVoice;
|
|
using echofield::GrainCloud;
|
|
using echofield::GrainPatch;
|
|
|
|
namespace {
|
|
|
|
constexpr int TRACK_COUNT = model::Pattern::TRACK_COUNT;
|
|
constexpr int LANE_COUNT = model::Arrangement::LANE_COUNT;
|
|
|
|
constexpr float MASTER_MAKEUP = 1.5f;
|
|
constexpr float LIM_CEILING = 0.97f;
|
|
constexpr int LIM_LOOKAHEAD = 64;
|
|
constexpr int LIM_HOLD_EXTRA = 8;
|
|
constexpr float LIM_RELEASE = 0.00025f;
|
|
constexpr float LIVE_GAIN = 0.5f;
|
|
constexpr float METER_DECAY = 0.96f;
|
|
constexpr float METER_CLIP_LEVEL = 0.999f;
|
|
constexpr int METER_CLIP_HOLD_BLOCKS = 200;
|
|
constexpr float SOFT_KNEE = 0.6f;
|
|
constexpr float NaNf = std::numeric_limits<float>::quiet_NaN();
|
|
|
|
/** Continuous soft-knee limiter (AudioEngine.softClip). */
|
|
float softClip(float x) {
|
|
const float a = x < 0.f ? -x : x;
|
|
if (a <= SOFT_KNEE) return x;
|
|
const float k = 1.f - SOFT_KNEE;
|
|
const float comp = SOFT_KNEE + k * kt::tanhf_((a - SOFT_KNEE) / k);
|
|
return x < 0.f ? -comp : comp;
|
|
}
|
|
|
|
/** Math.max(float, float) (NaN wins; operands here are non-negative). */
|
|
float jmax(float a, float b) {
|
|
if (a != a) return a;
|
|
return a >= b ? a : b;
|
|
}
|
|
|
|
bool is(const ToolboxSlot *s, const char *type) { return s && s->type == type; }
|
|
bool hasType(const ToolboxSlot *s) { return s && !s->type.empty(); }
|
|
|
|
/** The slot types whose notes a SynthVoice plays with a parsed SynthPatch. */
|
|
bool hasSynthPatch(const ToolboxSlot *s) {
|
|
return is(s, "NES_SYNTH") || is(s, "MORPH_PAD") || is(s, "WAVETABLE");
|
|
}
|
|
|
|
/** Version as Kotlin's Int, widened so -1 can mean "never". */
|
|
int64_t ver(const ToolboxSlot &s) { return (int64_t)(int32_t)s.version; }
|
|
|
|
struct FxUnit {
|
|
ToolboxSlot *slot;
|
|
std::unique_ptr<Effect> effect;
|
|
int slotIndex = -1; // slot->index, kept so viz readers never touch the project
|
|
int64_t lastVersion = -1;
|
|
float lastTempo = NaNf;
|
|
};
|
|
|
|
struct Chains {
|
|
std::vector<FxUnit> ch[TRACK_COUNT];
|
|
};
|
|
|
|
const Sample *storeLookup(void *ctx, const char *id) {
|
|
return static_cast<sampler::SampleStore *>(ctx)->get(id);
|
|
}
|
|
|
|
} // namespace
|
|
|
|
class Engine::Impl {
|
|
public:
|
|
Impl(int sr, sampler::SampleStore *store, const EngineGlobals &g);
|
|
~Impl();
|
|
|
|
const int sampleRate;
|
|
sampler::SampleStore *const store;
|
|
|
|
// Kotlin globals, owned here (declared before the voices that reference them).
|
|
frasil::FrasilClock clock;
|
|
frasil::FrasilSeeds frasilSeeds;
|
|
echofield::GrainSeeds grainSeeds;
|
|
|
|
std::vector<std::unique_ptr<SynthVoice>> seqVoices; // TRACK_COUNT * POLYPHONY
|
|
std::vector<std::unique_ptr<SampleVoice>> sampleVoices; // TRACK_COUNT * POLYPHONY
|
|
int synthAlloc[TRACK_COUNT] = {};
|
|
int sampleAlloc[TRACK_COUNT] = {};
|
|
std::vector<std::unique_ptr<SynthVoice>> liveVoices;
|
|
std::vector<std::unique_ptr<SampleVoice>> auditionSampleVoices;
|
|
std::vector<std::unique_ptr<SynthVoice>> busVoices; // TRACK_COUNT * BUS_POLYPHONY
|
|
std::vector<std::unique_ptr<SampleVoice>> busSampleVoices;
|
|
ChannelArp arps[LANE_COUNT * TRACK_COUNT];
|
|
int lineTriggerGen = 0;
|
|
int trackLastChannel[LANE_COUNT * TRACK_COUNT];
|
|
|
|
// ---- outgoing MIDI
|
|
std::atomic<bool> midiOutEnabled{false};
|
|
int moutRing[256] = {};
|
|
std::atomic<int> moutHead{0};
|
|
std::atomic<int> moutTail{0};
|
|
int moutNote[LANE_COUNT * TRACK_COUNT];
|
|
int moutCh[LANE_COUNT * TRACK_COUNT] = {};
|
|
|
|
// ---- Grain Cloud
|
|
std::vector<std::unique_ptr<GrainCloud>> clouds;
|
|
bool cloudOn[TRACK_COUNT] = {};
|
|
int64_t cloudVer[TRACK_COUNT];
|
|
float cloudTempo[TRACK_COUNT];
|
|
std::unique_ptr<GrainCloud> auditionCloud;
|
|
int64_t auditionCloudVer = -1;
|
|
float auditionCloudTempo = NaNf;
|
|
bool auditionCloudActive = false;
|
|
|
|
// ---- cached synth patches (null in Kotlin == !has)
|
|
SynthPatch synthPatch[TRACK_COUNT];
|
|
bool synthPatchHas[TRACK_COUNT] = {};
|
|
int64_t synthPatchVer[TRACK_COUNT];
|
|
float synthPatchTempo[TRACK_COUNT];
|
|
int auditionSlotIdx = -1;
|
|
SynthPatch auditionPatch;
|
|
bool auditionPatchHas = false;
|
|
int64_t auditionPatchVer = -1;
|
|
float auditionPatchTempo = NaNf;
|
|
|
|
// ---- FX chains (volatile in Kotlin)
|
|
std::atomic<Chains *> channelChains{nullptr};
|
|
float channelSum[TRACK_COUNT] = {};
|
|
|
|
// ---- master limiter
|
|
float limDelayL[LIM_LOOKAHEAD] = {};
|
|
float limDelayR[LIM_LOOKAHEAD] = {};
|
|
int limPos = 0;
|
|
float limGain = 1.f;
|
|
int limHold = 0;
|
|
float limOutL = 0.f, limOutR = 0.f;
|
|
|
|
// ---- meters
|
|
float chBlockPeak[TRACK_COUNT] = {};
|
|
std::atomic<float> chMeter[TRACK_COUNT];
|
|
std::atomic<int> chClipHold[TRACK_COUNT];
|
|
|
|
// ---- per-block active lists
|
|
std::vector<int> actSeq, actSmp, actBus, actBSmp, actLive, actASmp;
|
|
int actSeqN = 0, actSmpN = 0, actBusN = 0, actBSmpN = 0, actLiveN = 0, actASmpN = 0;
|
|
std::vector<int> seqGen, smpGen;
|
|
int blockGen = 0;
|
|
|
|
std::atomic<Project *> project{nullptr};
|
|
std::atomic<bool> playing{false};
|
|
|
|
// ---- position (audio thread; reset from the main thread like the Kotlin)
|
|
double samplesIntoLine = 0.0;
|
|
bool pendingTrigger = true;
|
|
double blockSamplesPerLine = 1.0;
|
|
int currentLine = 0;
|
|
bool arrangementMode = false;
|
|
std::atomic<std::vector<int> *> playlist{nullptr};
|
|
int playlistIndex = 0;
|
|
int lineInBeat = 0;
|
|
int arrPlayLine = 0;
|
|
|
|
// TransportState, packed: line | beat << 31 | playing << 62.
|
|
std::atomic<uint64_t> transportPacked{0};
|
|
|
|
// ---- recording
|
|
MasterSink *sink = nullptr;
|
|
std::atomic<bool> recordArmed{false};
|
|
std::atomic<int> recTailBars{0};
|
|
std::atomic<bool> recCapturing{false};
|
|
std::atomic<bool> extClockRunning{false};
|
|
bool recWasPlaying = false;
|
|
int recTailRemaining = 0;
|
|
|
|
// ---- MIDI LFO
|
|
uint32_t rngState = 0x9E3779B9u;
|
|
double lfoPhase[Project::TOOLBOX_SLOTS] = {};
|
|
double lfoSampleHold[Project::TOOLBOX_SLOTS] = {};
|
|
|
|
// ---- retiring swapped-out chains / playlists (main thread)
|
|
std::atomic<uint64_t> blocksDone{0};
|
|
struct RetiredChains { std::unique_ptr<Chains> p; uint64_t at; };
|
|
struct RetiredList { std::unique_ptr<std::vector<int>> p; uint64_t at; };
|
|
std::vector<RetiredChains> retiredChains;
|
|
std::vector<RetiredList> retiredLists;
|
|
void collectRetired();
|
|
|
|
// ---- effect visualisation (UI thread): readers in flight hold retired chains
|
|
mutable std::atomic<int> vizReaders{0};
|
|
const Effect *vizFor(const Chains *chains, int slotIndex) const;
|
|
|
|
// ---- AudioEngine
|
|
SynthVoice &allocSynthVoice(int bus);
|
|
SampleVoice &allocSampleVoice(int bus);
|
|
void queueSeq(int i) { if (seqGen[i] != blockGen) { seqGen[i] = blockGen; actSeq[actSeqN++] = i; } }
|
|
void queueSmp(int i) { if (smpGen[i] != blockGen) { smpGen[i] = blockGen; actSmp[actSmpN++] = i; } }
|
|
void releaseBus(int bus);
|
|
|
|
void maybeStartRecording();
|
|
void recordSample(Project *proj, float left, float right);
|
|
|
|
void setProject(Project *p);
|
|
void rebuildFxChains();
|
|
void rebuildArrangement();
|
|
void refreshLoopPlaylist();
|
|
std::vector<int> *buildPlaylist(const model::Arrangement &arr);
|
|
|
|
void play(int startBeat);
|
|
void pause();
|
|
void panic();
|
|
void stop();
|
|
void liveNoteOn(int pitch, int velocity);
|
|
void liveNoteOff(int pitch);
|
|
|
|
void fillBlock(float *out, int frames);
|
|
void masterLimit(float inL, float inR);
|
|
void updateFxParams(Project &proj);
|
|
float nextRandomUnit();
|
|
void applyLfos(Project &proj);
|
|
void advanceSequencer(Project &proj);
|
|
void advancePatternLoop(Project &proj);
|
|
void triggerPatternLine(Project &proj, const model::Pattern &pattern, int line);
|
|
void triggerCell(Project &proj, int lane, int track, const model::Cell &cell);
|
|
void releaseTrack(Project &proj, int lane, int track);
|
|
void releaseLane(Project &proj, int lane);
|
|
void releaseTrackVoices(int trackKey);
|
|
void playNote(Project &proj, int bus, int note, int velocity, int ownerTrack = -1);
|
|
bool voiceSample(const ToolboxSlot *slot, int note, VoiceSample &out) const;
|
|
void resetBarArps();
|
|
const ToolboxSlot *channelArpSlot(Project &proj, int track) const;
|
|
void advanceArps(Project &proj);
|
|
int channelTranspose(Project &proj, int track) const;
|
|
void auditionSlotOn(int slotIndex, int midi);
|
|
void auditionSlotOff(int midi);
|
|
void busNoteOn(int midiChannel, int midi, int velocity);
|
|
void busNoteOff(int midiChannel, int midi);
|
|
std::string describeBusTargets(int midiChannel, int midi) const;
|
|
void advanceArrangement(Project &proj);
|
|
void triggerArrangementLine(Project &proj, const model::Arrangement &arr, int beat, int lineInBeat,
|
|
int linesPerBeat);
|
|
static SynthPatch patchForSlot(const ToolboxSlot *slot, float tempoBpm);
|
|
void refreshSynthPatches(Project &proj);
|
|
double samplesPerLine(const Project &proj) const {
|
|
return sampleRate * (60.0 / proj.tempoBpm) / model::info(proj.timeSignature).linesPerBeat;
|
|
}
|
|
void allSeqVoicesOff();
|
|
void emitMidi(int status, int d1, int d2);
|
|
void emitNoteOn(int ch, int note, int vel);
|
|
void emitNoteOff(int ch, int note);
|
|
void allMidiNotesOff();
|
|
int pollMidiOut();
|
|
void publish();
|
|
|
|
static const ToolboxSlot *slotAt(const Project &proj, int idx) {
|
|
return idx >= 0 && idx < Project::TOOLBOX_SLOTS ? &proj.toolbox[idx] : nullptr;
|
|
}
|
|
static ToolboxSlot *slotAt(Project &proj, int idx) {
|
|
return idx >= 0 && idx < Project::TOOLBOX_SLOTS ? &proj.toolbox[idx] : nullptr;
|
|
}
|
|
};
|
|
|
|
// ------------------------------------------------------------------ construction
|
|
|
|
Engine::Impl::Impl(int sr, sampler::SampleStore *st, const EngineGlobals &g) : sampleRate(sr), store(st) {
|
|
clock.seconds = g.clockSeconds;
|
|
frasilSeeds.seeds = g.frasilSeeds;
|
|
grainSeeds.seeds = g.grainSeeds;
|
|
// AudioEngine's field order: every SynthVoice takes the next FrasilVoice seed,
|
|
// every GrainCloud the next cloud seed.
|
|
for (int i = 0; i < TRACK_COUNT * POLYPHONY; ++i)
|
|
seqVoices.push_back(std::make_unique<SynthVoice>(sr, clock, frasilSeeds.next()));
|
|
for (int i = 0; i < TRACK_COUNT * POLYPHONY; ++i) sampleVoices.push_back(std::make_unique<SampleVoice>(sr));
|
|
for (int i = 0; i < LIVE_POLYPHONY; ++i)
|
|
liveVoices.push_back(std::make_unique<SynthVoice>(sr, clock, frasilSeeds.next()));
|
|
for (int i = 0; i < AUDITION_POLYPHONY; ++i) auditionSampleVoices.push_back(std::make_unique<SampleVoice>(sr));
|
|
for (int i = 0; i < TRACK_COUNT * BUS_POLYPHONY; ++i)
|
|
busVoices.push_back(std::make_unique<SynthVoice>(sr, clock, frasilSeeds.next()));
|
|
for (int i = 0; i < TRACK_COUNT * BUS_POLYPHONY; ++i) busSampleVoices.push_back(std::make_unique<SampleVoice>(sr));
|
|
for (int &c : trackLastChannel) c = -1;
|
|
for (int &n : moutNote) n = -1;
|
|
for (int i = 0; i < TRACK_COUNT; ++i) {
|
|
clouds.push_back(std::make_unique<GrainCloud>(sr, grainSeeds.next()));
|
|
cloudVer[i] = -1;
|
|
cloudTempo[i] = NaNf;
|
|
synthPatchVer[i] = -1;
|
|
synthPatchTempo[i] = NaNf;
|
|
chMeter[i].store(0.f);
|
|
chClipHold[i].store(0);
|
|
}
|
|
auditionCloud = std::make_unique<GrainCloud>(sr, grainSeeds.next());
|
|
if (store) {
|
|
for (auto &c : clouds) c->setSampleLookup(&storeLookup, store);
|
|
auditionCloud->setSampleLookup(&storeLookup, store);
|
|
}
|
|
|
|
actSeq.assign(seqVoices.size(), 0);
|
|
actSmp.assign(sampleVoices.size(), 0);
|
|
actBus.assign(busVoices.size(), 0);
|
|
actBSmp.assign(busSampleVoices.size(), 0);
|
|
actLive.assign(liveVoices.size(), 0);
|
|
actASmp.assign(auditionSampleVoices.size(), 0);
|
|
seqGen.assign(seqVoices.size(), 0);
|
|
smpGen.assign(sampleVoices.size(), 0);
|
|
|
|
// Kotlin: DoubleArray { Math.random() * 2 - 1 }.
|
|
std::random_device rd;
|
|
std::uniform_real_distribution<double> uni(0.0, 1.0);
|
|
for (double &v : lfoSampleHold) v = uni(rd) * 2 - 1;
|
|
|
|
channelChains.store(new Chains());
|
|
playlist.store(new std::vector<int>());
|
|
}
|
|
|
|
Engine::Impl::~Impl() {
|
|
delete channelChains.load();
|
|
delete playlist.load();
|
|
}
|
|
|
|
void Engine::Impl::collectRetired() {
|
|
const uint64_t done = blocksDone.load();
|
|
// A viz reader may still be walking a retired chain; keep them all until it's out.
|
|
// (seq_cst: a reader that arrives after this check loads the current chains.)
|
|
if (vizReaders.load() == 0) {
|
|
for (size_t i = 0; i < retiredChains.size();)
|
|
if (done > retiredChains[i].at) retiredChains.erase(retiredChains.begin() + (long)i); else ++i;
|
|
}
|
|
for (size_t i = 0; i < retiredLists.size();)
|
|
if (done > retiredLists[i].at) retiredLists.erase(retiredLists.begin() + (long)i); else ++i;
|
|
}
|
|
|
|
// ------------------------------------------------------------------ voice pools
|
|
|
|
SynthVoice &Engine::Impl::allocSynthVoice(int bus) {
|
|
const int base = bus * POLYPHONY;
|
|
for (int i = 0; i < POLYPHONY; ++i) {
|
|
SynthVoice &v = *seqVoices[base + i];
|
|
if (!v.isActive()) { queueSeq(base + i); return v; }
|
|
}
|
|
const int idx = synthAlloc[bus];
|
|
synthAlloc[bus] = (idx + 1) % POLYPHONY;
|
|
SynthVoice &v = *seqVoices[base + idx];
|
|
v.kill();
|
|
queueSeq(base + idx);
|
|
return v;
|
|
}
|
|
|
|
SampleVoice &Engine::Impl::allocSampleVoice(int bus) {
|
|
const int base = bus * POLYPHONY;
|
|
for (int i = 0; i < POLYPHONY; ++i) {
|
|
SampleVoice &v = *sampleVoices[base + i];
|
|
if (!v.isActive()) { queueSmp(base + i); return v; }
|
|
}
|
|
const int idx = sampleAlloc[bus];
|
|
sampleAlloc[bus] = (idx + 1) % POLYPHONY;
|
|
SampleVoice &v = *sampleVoices[base + idx];
|
|
queueSmp(base + idx);
|
|
return v;
|
|
}
|
|
|
|
void Engine::Impl::releaseBus(int bus) {
|
|
clouds[bus]->releaseSequenced();
|
|
const int base = bus * POLYPHONY;
|
|
for (int i = 0; i < POLYPHONY; ++i) {
|
|
seqVoices[base + i]->noteOff();
|
|
sampleVoices[base + i]->noteOff();
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ recording
|
|
|
|
void Engine::Impl::maybeStartRecording() {
|
|
if (!recordArmed.load()) return;
|
|
if (!sink) return;
|
|
if (sink->isActive()) return;
|
|
if (!sink->begin()) return;
|
|
recTailRemaining = -1;
|
|
recWasPlaying = true;
|
|
recCapturing.store(true);
|
|
}
|
|
|
|
void Engine::Impl::recordSample(Project *proj, float left, float right) {
|
|
const bool nowPlaying = playing.load(std::memory_order_relaxed) || extClockRunning.load(std::memory_order_relaxed);
|
|
if (recWasPlaying && !nowPlaying) {
|
|
recTailRemaining = proj == nullptr ? 0
|
|
: (int)(recTailBars.load(std::memory_order_relaxed) * model::info(proj->timeSignature).linesPerBar()
|
|
* samplesPerLine(*proj));
|
|
}
|
|
recWasPlaying = nowPlaying;
|
|
sink->write(left, right);
|
|
if (!nowPlaying) {
|
|
if (recTailRemaining <= 0) {
|
|
recCapturing.store(false, std::memory_order_relaxed);
|
|
sink->endCapture();
|
|
} else {
|
|
recTailRemaining--;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ song
|
|
|
|
void Engine::Impl::setProject(Project *p) {
|
|
project.store(p);
|
|
rebuildArrangement();
|
|
rebuildFxChains();
|
|
}
|
|
|
|
void Engine::Impl::rebuildFxChains() {
|
|
Project *proj = project.load();
|
|
if (!proj) return;
|
|
collectRetired();
|
|
auto next = std::make_unique<Chains>();
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
|
for (int slotIndex : proj->mixer.channels[ch].fxSlots) {
|
|
if (slotIndex < 0) continue;
|
|
ToolboxSlot *slot = slotAt(*proj, slotIndex);
|
|
if (!slot || slot->type.empty()) continue;
|
|
if (auto fx = Effect::create(slot->type.c_str(), sampleRate)) {
|
|
FxUnit u{slot, std::move(fx), slotIndex};
|
|
next->ch[ch].push_back(std::move(u));
|
|
}
|
|
}
|
|
}
|
|
Chains *old = channelChains.exchange(next.release());
|
|
retiredChains.push_back({std::unique_ptr<Chains>(old), blocksDone.load()});
|
|
}
|
|
|
|
void Engine::Impl::rebuildArrangement() {
|
|
Project *proj = project.load();
|
|
if (!proj) return;
|
|
collectRetired();
|
|
const auto &arr = proj->arrangement;
|
|
bool any = false;
|
|
for (const auto &lane : arr.slots) {
|
|
for (int v : lane) if (v != model::Arrangement::EMPTY) { any = true; break; }
|
|
if (any) break;
|
|
}
|
|
arrangementMode = any;
|
|
std::vector<int> *old = playlist.exchange(buildPlaylist(arr));
|
|
retiredLists.push_back({std::unique_ptr<std::vector<int>>(old), blocksDone.load()});
|
|
playlistIndex = 0;
|
|
lineInBeat = 0;
|
|
arrPlayLine = 0;
|
|
}
|
|
|
|
void Engine::Impl::refreshLoopPlaylist() {
|
|
Project *proj = project.load();
|
|
if (!proj) return;
|
|
if (!arrangementMode) return;
|
|
collectRetired();
|
|
std::vector<int> *old = playlist.exchange(buildPlaylist(proj->arrangement));
|
|
retiredLists.push_back({std::unique_ptr<std::vector<int>>(old), blocksDone.load()});
|
|
}
|
|
|
|
std::vector<int> *Engine::Impl::buildPlaylist(const model::Arrangement &arr) {
|
|
const auto &a = arr.regionA;
|
|
const auto &b = arr.regionB;
|
|
auto *out = new std::vector<int>();
|
|
if (!arr.loopEnabled || (!a.isValid() && !b.isValid())) {
|
|
int end = arr.lastFilledBeat() + 1;
|
|
if (end < 0) end = 0;
|
|
for (int i = 0; i < end; ++i) out->push_back(i);
|
|
return out;
|
|
}
|
|
if (a.isValid()) for (int r = 0; r < a.repeats; ++r) for (int beat = a.start; beat < a.end; ++beat) out->push_back(beat);
|
|
if (b.isValid()) for (int r = 0; r < b.repeats; ++r) for (int beat = b.start; beat < b.end; ++beat) out->push_back(beat);
|
|
return out;
|
|
}
|
|
|
|
// ------------------------------------------------------------------ transport
|
|
|
|
void Engine::Impl::play(int startBeat) {
|
|
rebuildArrangement();
|
|
rebuildFxChains();
|
|
if (startBeat >= 0) {
|
|
if (arrangementMode) {
|
|
const std::vector<int> &list = *playlist.load();
|
|
int seek = -1;
|
|
for (size_t i = 0; i < list.size(); ++i) if (list[i] == startBeat) { seek = (int)i; break; }
|
|
if (seek >= 0) {
|
|
playlistIndex = seek; lineInBeat = 0; arrPlayLine = 0; samplesIntoLine = 0.0;
|
|
}
|
|
} else {
|
|
Project *proj = project.load();
|
|
if (proj) {
|
|
const auto &pat = proj->activePattern();
|
|
currentLine = kt::coerceIn(startBeat * model::info(proj->timeSignature).linesPerBeat, 0, pat.length - 1);
|
|
samplesIntoLine = 0.0;
|
|
}
|
|
}
|
|
}
|
|
pendingTrigger = true;
|
|
playing.store(true);
|
|
maybeStartRecording();
|
|
publish();
|
|
}
|
|
|
|
void Engine::Impl::pause() {
|
|
playing.store(false);
|
|
extClockRunning.store(false);
|
|
allSeqVoicesOff();
|
|
publish();
|
|
}
|
|
|
|
void Engine::Impl::panic() {
|
|
for (auto &c : clouds) c->kill();
|
|
auditionCloud->kill();
|
|
for (auto &v : seqVoices) v->kill();
|
|
for (auto &v : sampleVoices) v->kill();
|
|
for (auto &v : liveVoices) v->kill();
|
|
for (auto &v : auditionSampleVoices) v->kill();
|
|
for (auto &v : busVoices) v->kill();
|
|
for (auto &v : busSampleVoices) v->kill();
|
|
for (auto &a : arps) a.stop();
|
|
for (int &c : trackLastChannel) c = -1;
|
|
allMidiNotesOff();
|
|
}
|
|
|
|
void Engine::Impl::stop() {
|
|
extClockRunning.store(false);
|
|
if (!playing.load() && currentLine == 0 && playlistIndex == 0 && lineInBeat == 0) return;
|
|
const bool wasStopped = !playing.load();
|
|
playing.store(false);
|
|
allSeqVoicesOff();
|
|
if (wasStopped) {
|
|
currentLine = 0; samplesIntoLine = 0.0;
|
|
playlistIndex = 0; lineInBeat = 0;
|
|
arrPlayLine = 0;
|
|
}
|
|
publish();
|
|
}
|
|
|
|
void Engine::Impl::liveNoteOn(int pitch, int velocity) {
|
|
SynthVoice *v = nullptr;
|
|
for (auto &lv : liveVoices) if (!lv->isActive()) { v = lv.get(); break; }
|
|
if (!v) { v = liveVoices[0].get(); v->kill(); }
|
|
v->noteOn(pitch, velocity, SynthPatch::defaults());
|
|
}
|
|
|
|
void Engine::Impl::liveNoteOff(int pitch) {
|
|
SynthVoice *v = nullptr;
|
|
for (auto &lv : liveVoices) if (lv->pitch() == pitch && lv->isGated()) { v = lv.get(); break; }
|
|
if (!v) for (auto &lv : liveVoices) if (lv->isActive() && lv->pitch() == pitch) { v = lv.get(); break; }
|
|
if (v) v->noteOff();
|
|
}
|
|
|
|
// ------------------------------------------------------------------ render
|
|
|
|
void Engine::Impl::fillBlock(float *out, int frames) {
|
|
Project *proj = project.load(std::memory_order_acquire);
|
|
if (store) store->quiescent();
|
|
clock.advance(frames, sampleRate);
|
|
if (proj) {
|
|
applyLfos(*proj);
|
|
updateFxParams(*proj);
|
|
refreshSynthPatches(*proj);
|
|
blockSamplesPerLine = samplesPerLine(*proj);
|
|
}
|
|
const bool anySolo = proj ? proj->mixer.anySolo() : false;
|
|
Chains *chains = channelChains.load(std::memory_order_acquire);
|
|
|
|
blockGen++;
|
|
actSeqN = 0; actSmpN = 0; actBusN = 0; actBSmpN = 0; actLiveN = 0; actASmpN = 0;
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) chBlockPeak[ch] = 0.f;
|
|
for (int i = 0; i < (int)seqVoices.size(); ++i) if (seqVoices[i]->isActive()) { seqGen[i] = blockGen; actSeq[actSeqN++] = i; }
|
|
for (int i = 0; i < (int)sampleVoices.size(); ++i) if (sampleVoices[i]->isActive()) { smpGen[i] = blockGen; actSmp[actSmpN++] = i; }
|
|
for (int i = 0; i < (int)busVoices.size(); ++i) if (busVoices[i]->isActive()) actBus[actBusN++] = i;
|
|
for (int i = 0; i < (int)busSampleVoices.size(); ++i) if (busSampleVoices[i]->isActive()) actBSmp[actBSmpN++] = i;
|
|
for (int i = 0; i < (int)liveVoices.size(); ++i) if (liveVoices[i]->isActive()) actLive[actLiveN++] = i;
|
|
auditionCloudActive = auditionCloud->isActive();
|
|
for (int i = 0; i < (int)auditionSampleVoices.size(); ++i) if (auditionSampleVoices[i]->isActive()) actASmp[actASmpN++] = i;
|
|
|
|
for (int i = 0; i < frames; ++i) {
|
|
if (playing.load(std::memory_order_relaxed) && proj) advanceSequencer(*proj);
|
|
|
|
float mixL = 0.f;
|
|
float mixR = 0.f;
|
|
if (proj) {
|
|
for (float &s : channelSum) s = 0.f;
|
|
for (int k = 0; k < actSeqN; ++k) { const int vi = actSeq[k]; channelSum[vi / POLYPHONY] += seqVoices[vi]->render(); }
|
|
for (int k = 0; k < actSmpN; ++k) { const int vi = actSmp[k]; channelSum[vi / POLYPHONY] += sampleVoices[vi]->render(); }
|
|
for (int k = 0; k < actBusN; ++k) { const int vi = actBus[k]; channelSum[vi / BUS_POLYPHONY] += busVoices[vi]->render(); }
|
|
for (int k = 0; k < actBSmpN; ++k) { const int vi = actBSmp[k]; channelSum[vi / BUS_POLYPHONY] += busSampleVoices[vi]->render(); }
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) if (cloudOn[ch]) channelSum[ch] += clouds[ch]->render();
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
|
const auto &mc = proj->mixer.channels[ch];
|
|
float s = mc.audible(anySolo) ? channelSum[ch] * mc.volume : 0.f;
|
|
for (FxUnit &u : chains->ch[ch]) s = u.effect->process(s);
|
|
if (!std::isfinite(s)) s = 0.f;
|
|
if (mc.limiter) s = softClip(s);
|
|
const float a = s < 0.f ? -s : s;
|
|
if (a > chBlockPeak[ch]) chBlockPeak[ch] = a;
|
|
mixL += s; mixR += s;
|
|
}
|
|
}
|
|
for (int k = 0; k < actLiveN; ++k) { const float v = liveVoices[actLive[k]]->render() * LIVE_GAIN; mixL += v; mixR += v; }
|
|
if (auditionCloudActive) { const float v = auditionCloud->render() * LIVE_GAIN; mixL += v; mixR += v; }
|
|
for (int k = 0; k < actASmpN; ++k) { const float v = auditionSampleVoices[actASmp[k]]->render() * LIVE_GAIN; mixL += v; mixR += v; }
|
|
masterLimit(mixL * MASTER_MAKEUP, mixR * MASTER_MAKEUP);
|
|
const float oL = limOutL;
|
|
const float oR = limOutR;
|
|
out[2 * i] = oL;
|
|
out[2 * i + 1] = oR;
|
|
if (recCapturing.load(std::memory_order_relaxed) && sink) recordSample(proj, oL, oR);
|
|
}
|
|
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
|
const float peak = chBlockPeak[ch];
|
|
const float decayed = chMeter[ch].load(std::memory_order_relaxed) * METER_DECAY;
|
|
chMeter[ch].store(peak > decayed ? peak : decayed, std::memory_order_relaxed);
|
|
if (peak >= METER_CLIP_LEVEL) chClipHold[ch].store(METER_CLIP_HOLD_BLOCKS, std::memory_order_relaxed);
|
|
else if (chClipHold[ch].load(std::memory_order_relaxed) > 0) chClipHold[ch].fetch_sub(1, std::memory_order_relaxed);
|
|
}
|
|
blocksDone.fetch_add(1);
|
|
}
|
|
|
|
void Engine::Impl::masterLimit(float inL, float inR) {
|
|
const float dL = limDelayL[limPos];
|
|
const float dR = limDelayR[limPos];
|
|
limDelayL[limPos] = inL;
|
|
limDelayR[limPos] = inR;
|
|
limPos++; if (limPos >= LIM_LOOKAHEAD) limPos = 0;
|
|
|
|
const float peak = jmax(std::fabs(inL), std::fabs(inR));
|
|
const float target = peak > LIM_CEILING ? LIM_CEILING / peak : 1.f;
|
|
if (target < limGain) { limGain = target; limHold = LIM_LOOKAHEAD + LIM_HOLD_EXTRA; }
|
|
else if (limHold > 0) limHold--;
|
|
else limGain += (1.f - limGain) * LIM_RELEASE;
|
|
|
|
float oL = dL * limGain;
|
|
float oR = dR * limGain;
|
|
if (oL > LIM_CEILING) oL = LIM_CEILING; else if (oL < -LIM_CEILING) oL = -LIM_CEILING;
|
|
if (oR > LIM_CEILING) oR = LIM_CEILING; else if (oR < -LIM_CEILING) oR = -LIM_CEILING;
|
|
limOutL = std::isfinite(oL) ? oL : 0.f;
|
|
limOutR = std::isfinite(oR) ? oR : 0.f;
|
|
}
|
|
|
|
void Engine::Impl::updateFxParams(Project &proj) {
|
|
const float tempo = proj.tempoBpm;
|
|
Chains *chains = channelChains.load(std::memory_order_acquire);
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
|
for (FxUnit &u : chains->ch[ch]) {
|
|
const int64_t v = ver(*u.slot);
|
|
if (v != u.lastVersion || tempo != u.lastTempo) {
|
|
u.effect->update(u.slot->values, tempo);
|
|
u.lastVersion = v;
|
|
u.lastTempo = tempo;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
float Engine::Impl::nextRandomUnit() {
|
|
uint32_t s = rngState;
|
|
s ^= s << 13; s ^= s >> 17; s ^= s << 5;
|
|
rngState = s;
|
|
return (float)s * 2.3283064e-10f;
|
|
}
|
|
|
|
void Engine::Impl::applyLfos(Project &proj) {
|
|
const double secondsPerBeat = 60.0 / proj.tempoBpm;
|
|
const double blockSeconds = (double)BLOCK_FRAMES / sampleRate;
|
|
for (int i = 0; i < Project::TOOLBOX_SLOTS; ++i) {
|
|
ToolboxSlot &lfo = proj.toolbox[i];
|
|
if (lfo.type != "LFO") continue;
|
|
const char *target = lfo.s("target");
|
|
const char *colon = std::strchr(target, ':');
|
|
const int sep = colon ? (int)(colon - target) : -1;
|
|
if (sep <= 0) continue;
|
|
uint32_t tIdx = 0;
|
|
bool validIdx = true;
|
|
for (int ci = 0; ci < sep; ++ci) {
|
|
const char ch = target[ci];
|
|
if (ch < '0' || ch > '9') { validIdx = false; break; }
|
|
tIdx = tIdx * 10u + (uint32_t)(ch - '0');
|
|
}
|
|
if (!validIdx || (int32_t)tIdx == i) continue;
|
|
ToolboxSlot *tSlot = slotAt(proj, (int32_t)tIdx);
|
|
if (!tSlot || tSlot->type.empty()) continue;
|
|
const DeviceSpec *dev = findDevice(tSlot->type.c_str());
|
|
if (!dev) continue;
|
|
const char *key = target + sep + 1;
|
|
const size_t keyLen = std::strlen(key);
|
|
int specIdx = -1;
|
|
for (int pi = 0; pi < dev->paramCount; ++pi) {
|
|
const char *k = dev->params[pi].key;
|
|
if (std::strlen(k) == keyLen && std::memcmp(k, key, keyLen) == 0) { specIdx = pi; break; }
|
|
}
|
|
if (specIdx < 0) continue;
|
|
const ParamSpec &spec = dev->params[specIdx];
|
|
|
|
const auto div = model::fromIndex(kt::toInt(lfo.f("division", 3.f)));
|
|
double period = model::beatFraction(div) * secondsPerBeat;
|
|
if (period < 1e-6) period = 1e-6;
|
|
const double freq = 1.0 / period;
|
|
const double advanced = lfoPhase[i] + freq * blockSeconds;
|
|
if (advanced >= 1.0) lfoSampleHold[i] = nextRandomUnit() * 2.0 - 1.0;
|
|
lfoPhase[i] = std::fmod(advanced, 1.0);
|
|
const double phase = std::fmod(lfoPhase[i] + lfo.f("phase", 0.f), 1.0);
|
|
|
|
const char *wave = lfo.s("wave", "Sine");
|
|
double value;
|
|
if (std::strcmp(wave, "Triangle") == 0) value = 1.0 - 4.0 * std::fabs(phase - 0.5);
|
|
else if (std::strcmp(wave, "Saw") == 0) value = 2.0 * phase - 1.0;
|
|
else if (std::strcmp(wave, "Square") == 0) value = phase < 0.5 ? 1.0 : -1.0;
|
|
else if (std::strcmp(wave, "SampleHold") == 0) value = lfoSampleHold[i];
|
|
else value = std::sin(2 * M_PI * phase);
|
|
const double center = (double)lfo.f("center", spec.def);
|
|
const double half = (spec.max - spec.min) / 2.0;
|
|
const double modulated = kt::coerceIn(center + lfo.f("depth", 0.5f) * value * half,
|
|
(double)spec.min, (double)spec.max);
|
|
tSlot->set(spec.key, (float)modulated);
|
|
}
|
|
}
|
|
|
|
void Engine::Impl::advanceSequencer(Project &proj) {
|
|
if (arrangementMode) advanceArrangement(proj); else advancePatternLoop(proj);
|
|
advanceArps(proj);
|
|
}
|
|
|
|
void Engine::Impl::advancePatternLoop(Project &proj) {
|
|
const model::Pattern &pattern = proj.activePattern();
|
|
const double spl = blockSamplesPerLine;
|
|
|
|
if (pendingTrigger) {
|
|
const int linesPerBar = model::info(proj.timeSignature).linesPerBar();
|
|
if (linesPerBar > 0 && currentLine % linesPerBar == 0) resetBarArps();
|
|
triggerPatternLine(proj, pattern, currentLine);
|
|
pendingTrigger = false;
|
|
}
|
|
samplesIntoLine += 1.0;
|
|
if (samplesIntoLine >= spl) {
|
|
samplesIntoLine -= spl;
|
|
currentLine++;
|
|
if (currentLine >= pattern.length) currentLine = 0;
|
|
pendingTrigger = true;
|
|
publish();
|
|
}
|
|
}
|
|
|
|
void Engine::Impl::triggerPatternLine(Project &proj, const model::Pattern &pattern, int line) {
|
|
lineTriggerGen++;
|
|
for (int t = 0; t < TRACK_COUNT; ++t) {
|
|
const model::Cell &cell = pattern.cell(t, line);
|
|
if (cell.isNoteOff()) triggerCell(proj, 0, t, cell);
|
|
}
|
|
for (int t = 0; t < TRACK_COUNT; ++t) {
|
|
const model::Cell &cell = pattern.cell(t, line);
|
|
if (cell.isPlayable()) triggerCell(proj, 0, t, cell);
|
|
}
|
|
}
|
|
|
|
void Engine::Impl::triggerCell(Project &proj, int lane, int track, const model::Cell &cell) {
|
|
const int trackKey = lane * TRACK_COUNT + track;
|
|
if (cell.isNoteOff()) { releaseTrack(proj, lane, track); return; }
|
|
if (!cell.isPlayable()) return;
|
|
trackLastChannel[trackKey] = cell.channel;
|
|
if (moutNote[trackKey] >= 0) emitNoteOff(moutCh[trackKey], moutNote[trackKey]);
|
|
emitNoteOn(cell.channel, cell.note, cell.velocity);
|
|
moutNote[trackKey] = cell.note; moutCh[trackKey] = cell.channel;
|
|
releaseTrackVoices(trackKey);
|
|
for (int bus = 0; bus < TRACK_COUNT; ++bus) {
|
|
if (proj.mixer.channels[bus].midiChannel != cell.channel) continue;
|
|
ChannelArp &arp = arps[lane * TRACK_COUNT + bus];
|
|
const int velocity = kt::coerceIn(cell.velocity, 0, 127);
|
|
const int note = kt::coerceIn(cell.note + channelTranspose(proj, bus), 0, 127);
|
|
const ToolboxSlot *arpSlot = channelArpSlot(proj, bus);
|
|
if (arpSlot) {
|
|
const int octaves = kt::toInt(arpSlot->f("octaves", 1.f));
|
|
const auto div = model::fromIndex(kt::toInt(arpSlot->f("division", 3.f)));
|
|
const double stepSamples = model::beatFraction(div) * (60.0 / proj.tempoBpm) * sampleRate;
|
|
const char *mode = arpSlot->s("mode", "Up");
|
|
const bool resetBar = std::strcmp(arpSlot->s("resetbar", "Off"), "On") == 0;
|
|
if (arp.active() && arp.genStamp == lineTriggerGen) {
|
|
arp.addNote(note);
|
|
arp.refresh(octaves, mode, stepSamples, resetBar);
|
|
} else if (arp.active()) {
|
|
arp.resetChord(note, velocity, octaves, mode, stepSamples, resetBar);
|
|
arp.genStamp = lineTriggerGen;
|
|
} else {
|
|
arp.startChord(note, velocity, octaves, mode, stepSamples, resetBar);
|
|
arp.genStamp = lineTriggerGen;
|
|
releaseBus(bus);
|
|
playNote(proj, bus, arp.currentNote(), velocity);
|
|
}
|
|
} else {
|
|
arp.stop();
|
|
playNote(proj, bus, note, velocity, trackKey);
|
|
}
|
|
}
|
|
}
|
|
|
|
void Engine::Impl::releaseTrack(Project &proj, int lane, int track) {
|
|
const int trackKey = lane * TRACK_COUNT + track;
|
|
if (moutNote[trackKey] >= 0) { emitNoteOff(moutCh[trackKey], moutNote[trackKey]); moutNote[trackKey] = -1; }
|
|
const int ch = trackLastChannel[trackKey];
|
|
if (ch < 0) return;
|
|
for (int bus = 0; bus < TRACK_COUNT; ++bus) {
|
|
if (proj.mixer.channels[bus].midiChannel != ch) continue;
|
|
arps[lane * TRACK_COUNT + bus].stop();
|
|
releaseBus(bus);
|
|
}
|
|
}
|
|
|
|
void Engine::Impl::releaseLane(Project &proj, int lane) {
|
|
for (int t = 0; t < TRACK_COUNT; ++t) releaseTrack(proj, lane, t);
|
|
}
|
|
|
|
void Engine::Impl::releaseTrackVoices(int trackKey) {
|
|
for (auto &c : clouds) c->releaseOwner(trackKey);
|
|
for (auto &v : seqVoices) if (v->ownerTrack == trackKey && v->isGated()) v->noteOff();
|
|
for (auto &v : sampleVoices) if (v->ownerTrack == trackKey && v->isGated()) v->noteOff();
|
|
}
|
|
|
|
void Engine::Impl::playNote(Project &proj, int bus, int note, int velocity, int ownerTrack) {
|
|
const ToolboxSlot *slot = slotAt(proj, proj.mixer.channels[bus].instrumentSlot);
|
|
VoiceSample vs;
|
|
if (voiceSample(slot, note, vs)) {
|
|
SampleVoice &v = allocSampleVoice(bus);
|
|
v.ownerTrack = ownerTrack;
|
|
v.noteOn(*vs.sample, note, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
|
|
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs);
|
|
v.oneShot = vs.oneShot;
|
|
} else if (!hasType(slot) || is(slot, "SAMPLER")) {
|
|
// Empty bus or a Sampler with an empty pad: silent.
|
|
} else if (is(slot, "GRAIN_CLOUD")) {
|
|
clouds[bus]->noteOn(note, velocity, ownerTrack >= 0 ? ownerTrack : GrainCloud::OWNER_SEQ);
|
|
} else {
|
|
SynthVoice &v = allocSynthVoice(bus);
|
|
v.ownerTrack = ownerTrack;
|
|
if (synthPatchHas[bus]) v.noteOn(note, velocity, synthPatch[bus]);
|
|
else v.noteOn(note, velocity, patchForSlot(slot, proj.tempoBpm));
|
|
}
|
|
}
|
|
|
|
bool Engine::Impl::voiceSample(const ToolboxSlot *slot, int note, VoiceSample &out) const {
|
|
if (!slot || !store || slot->type.empty()) return false;
|
|
return sampler::voiceSample(slot->type.c_str(), slot->values, *store, note, out);
|
|
}
|
|
|
|
void Engine::Impl::resetBarArps() {
|
|
for (auto &a : arps) if (a.active() && a.resetOnBar) a.resetToBar();
|
|
}
|
|
|
|
const ToolboxSlot *Engine::Impl::channelArpSlot(Project &proj, int track) const {
|
|
for (int idx : proj.mixer.channels[track].fxSlots) {
|
|
if (idx < 0) continue;
|
|
const ToolboxSlot *slot = slotAt(proj, idx);
|
|
if (!slot) continue;
|
|
if (is(slot, "ARPEGGIATOR")) return slot;
|
|
}
|
|
return nullptr;
|
|
}
|
|
|
|
void Engine::Impl::advanceArps(Project &proj) {
|
|
for (int i = 0; i < LANE_COUNT * TRACK_COUNT; ++i) {
|
|
ChannelArp &a = arps[i];
|
|
if (!a.active()) continue;
|
|
a.samplesLeft -= 1.0;
|
|
if (a.samplesLeft <= 0.0) {
|
|
if (!a.consumePendingReset()) a.advance();
|
|
const int bus = i % TRACK_COUNT;
|
|
releaseBus(bus);
|
|
playNote(proj, bus, a.currentNote(), a.velocity);
|
|
a.samplesLeft += a.stepSamples;
|
|
}
|
|
}
|
|
}
|
|
|
|
int Engine::Impl::channelTranspose(Project &proj, int track) const {
|
|
int semis = 0;
|
|
for (int idx : proj.mixer.channels[track].fxSlots) {
|
|
if (idx < 0) continue;
|
|
const ToolboxSlot *slot = slotAt(proj, idx);
|
|
if (!slot) continue;
|
|
if (is(slot, "TRANSPOSER"))
|
|
semis += kt::toInt(slot->f("semitones", 0.f)) + kt::toInt(slot->f("octaves", 0.f)) * 12;
|
|
}
|
|
return semis;
|
|
}
|
|
|
|
// ------------------------------------------------------------------ audition
|
|
|
|
void Engine::Impl::auditionSlotOn(int slotIndex, int midi) {
|
|
Project *proj = project.load();
|
|
if (!proj) return;
|
|
const ToolboxSlot *slot = slotAt(*proj, slotIndex);
|
|
VoiceSample vs;
|
|
if (voiceSample(slot, midi, vs)) {
|
|
SampleVoice *v = nullptr;
|
|
for (auto &sv : auditionSampleVoices) if (!sv->isActive()) { v = sv.get(); break; }
|
|
if (!v) { v = auditionSampleVoices[0].get(); v->kill(); }
|
|
v->noteOn(*vs.sample, midi, 110, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
|
|
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs);
|
|
v->oneShot = vs.oneShot;
|
|
return;
|
|
}
|
|
if (is(slot, "SAMPLER")) return;
|
|
if (is(slot, "GRAIN_CLOUD")) {
|
|
if (auditionSlotIdx != slotIndex || ver(*slot) != auditionCloudVer) {
|
|
auditionCloud->setPatch(GrainPatch::from(&slot->values, proj->tempoBpm));
|
|
auditionCloudVer = ver(*slot);
|
|
}
|
|
auditionSlotIdx = slotIndex;
|
|
auditionCloud->noteOn(midi, 110, GrainCloud::OWNER_LIVE);
|
|
return;
|
|
}
|
|
if (hasSynthPatch(slot)) auditionSlotIdx = slotIndex;
|
|
SynthVoice *v = nullptr;
|
|
for (auto &lv : liveVoices) if (!lv->isActive()) { v = lv.get(); break; }
|
|
if (!v) { v = liveVoices[0].get(); v->kill(); }
|
|
v->noteOn(midi, 110, patchForSlot(slot, proj->tempoBpm));
|
|
}
|
|
|
|
void Engine::Impl::auditionSlotOff(int midi) {
|
|
auditionCloud->noteOff(midi);
|
|
SynthVoice *v = nullptr;
|
|
for (auto &lv : liveVoices) if (lv->pitch() == midi && lv->isGated()) { v = lv.get(); break; }
|
|
if (!v) for (auto &lv : liveVoices) if (lv->isActive() && lv->pitch() == midi) { v = lv.get(); break; }
|
|
if (v) v->noteOff();
|
|
SampleVoice *s = nullptr;
|
|
for (auto &sv : auditionSampleVoices) if (sv->pitch == midi && sv->isGated()) { s = sv.get(); break; }
|
|
if (!s) for (auto &sv : auditionSampleVoices) if (sv->isActive() && sv->pitch == midi) { s = sv.get(); break; }
|
|
if (s) s->noteOff();
|
|
}
|
|
|
|
void Engine::Impl::busNoteOn(int midiChannel, int midi, int velocity) {
|
|
Project *proj = project.load();
|
|
if (!proj) return;
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
|
if (proj->mixer.channels[ch].midiChannel != midiChannel) continue;
|
|
const ToolboxSlot *slot = slotAt(*proj, proj->mixer.channels[ch].instrumentSlot);
|
|
if (!hasType(slot)) continue;
|
|
const int base = ch * BUS_POLYPHONY;
|
|
VoiceSample vs;
|
|
if (voiceSample(slot, midi, vs)) {
|
|
SampleVoice *v = nullptr;
|
|
for (int i = 0; i < BUS_POLYPHONY; ++i) if (!busSampleVoices[base + i]->isActive()) { v = busSampleVoices[base + i].get(); break; }
|
|
if (!v) { v = busSampleVoices[base].get(); v->kill(); }
|
|
v->noteOn(*vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
|
|
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs);
|
|
v->oneShot = vs.oneShot;
|
|
} else if (is(slot, "SAMPLER")) {
|
|
} else if (is(slot, "GRAIN_CLOUD")) {
|
|
clouds[ch]->noteOn(midi, velocity, GrainCloud::OWNER_LIVE);
|
|
} else {
|
|
SynthVoice *v = nullptr;
|
|
for (int i = 0; i < BUS_POLYPHONY; ++i) if (!busVoices[base + i]->isActive()) { v = busVoices[base + i].get(); break; }
|
|
if (!v) { v = busVoices[base].get(); v->kill(); }
|
|
if (synthPatchHas[ch]) v->noteOn(midi, velocity, synthPatch[ch]);
|
|
else v->noteOn(midi, velocity, patchForSlot(slot, proj->tempoBpm));
|
|
}
|
|
}
|
|
}
|
|
|
|
std::string Engine::Impl::describeBusTargets(int midiChannel, int midi) const {
|
|
Project *proj = project.load();
|
|
if (!proj) return "no project";
|
|
std::string out;
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
|
if (proj->mixer.channels[ch].midiChannel != midiChannel) continue;
|
|
const ToolboxSlot *slot = slotAt(*proj, proj->mixer.channels[ch].instrumentSlot);
|
|
std::string part = "strip" + std::to_string(ch + 1) + " ";
|
|
VoiceSample vs;
|
|
if (!hasType(slot)) part += "no instrument (silent)";
|
|
else if (is(slot, "SAMPLER")) {
|
|
const int pad = sampler::SamplerPads::padFor(midi);
|
|
part += "SAMPLER pad" + std::to_string(pad + 1) + (voiceSample(slot, midi, vs) ? "" : " empty (silent)");
|
|
} else {
|
|
part += slot->type + (!voiceSample(slot, midi, vs) && is(slot, "SOUNDFONT") ? " no sample" : "");
|
|
}
|
|
if (!out.empty()) out += " | ";
|
|
out += part;
|
|
}
|
|
return out.empty() ? "no strip on channel " + std::to_string(midiChannel) : out;
|
|
}
|
|
|
|
void Engine::Impl::busNoteOff(int midiChannel, int midi) {
|
|
Project *proj = project.load();
|
|
if (!proj) return;
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
|
if (proj->mixer.channels[ch].midiChannel != midiChannel) continue;
|
|
clouds[ch]->noteOff(midi);
|
|
const int base = ch * BUS_POLYPHONY;
|
|
for (int i = 0; i < BUS_POLYPHONY; ++i) {
|
|
if (busVoices[base + i]->isActive() && busVoices[base + i]->pitch() == midi) busVoices[base + i]->noteOff();
|
|
if (busSampleVoices[base + i]->isActive() && busSampleVoices[base + i]->pitch == midi) busSampleVoices[base + i]->noteOff();
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ arrangement
|
|
|
|
void Engine::Impl::advanceArrangement(Project &proj) {
|
|
const model::Arrangement &arr = proj.arrangement;
|
|
const std::vector<int> &list = *playlist.load(std::memory_order_acquire);
|
|
if (list.empty()) { playing.store(false); publish(); return; }
|
|
const int size = (int)list.size();
|
|
const int linesPerBeat = model::info(proj.timeSignature).linesPerBeat;
|
|
const double spl = blockSamplesPerLine;
|
|
const int beat = list[kt::coerceIn(playlistIndex, 0, size - 1)];
|
|
|
|
if (pendingTrigger) {
|
|
const int beatsPerBar = model::info(proj.timeSignature).beatsPerBar;
|
|
if (lineInBeat == 0 && beatsPerBar > 0 && beat % beatsPerBar == 0) resetBarArps();
|
|
triggerArrangementLine(proj, arr, beat, lineInBeat, linesPerBeat);
|
|
pendingTrigger = false;
|
|
}
|
|
|
|
samplesIntoLine += 1.0;
|
|
if (samplesIntoLine >= spl) {
|
|
samplesIntoLine -= spl;
|
|
lineInBeat++;
|
|
if (lineInBeat >= linesPerBeat) {
|
|
lineInBeat = 0;
|
|
playlistIndex++;
|
|
if (playlistIndex >= size) {
|
|
if (arr.loopEnabled) {
|
|
playlistIndex = 0;
|
|
} else {
|
|
playing.store(false); allSeqVoicesOff(); publish(); return;
|
|
}
|
|
}
|
|
}
|
|
pendingTrigger = true;
|
|
publish();
|
|
}
|
|
}
|
|
|
|
void Engine::Impl::triggerArrangementLine(Project &proj, const model::Arrangement &arr, int beat, int lineInBeat_,
|
|
int linesPerBeat) {
|
|
lineTriggerGen++;
|
|
for (int pass = 0; pass <= 1; ++pass) {
|
|
for (int lane = 0; lane < LANE_COUNT; ++lane) {
|
|
if (arr.laneMuted[lane]) continue;
|
|
const int p = arr.patternAt(lane, beat);
|
|
if (p == model::Arrangement::EMPTY) continue;
|
|
if (p == model::Arrangement::NOTE_OFF) {
|
|
if (pass == 0 && lineInBeat_ == 0) releaseLane(proj, lane);
|
|
continue;
|
|
}
|
|
const model::Pattern *pat = proj.pattern(p);
|
|
if (!pat) continue;
|
|
int runStart = beat;
|
|
while (runStart > 0 && arr.hasBlockAt(lane, runStart - 1)) runStart--;
|
|
int blockBeats = pat->length / linesPerBeat;
|
|
if (blockBeats < 1) blockBeats = 1;
|
|
const int patLine = ((beat - runStart) % blockBeats) * linesPerBeat + lineInBeat_;
|
|
if (pass == 0 && p == proj.activePatternId) arrPlayLine = kt::coerceIn(patLine, 0, pat->length - 1);
|
|
if (patLine >= pat->length) continue;
|
|
for (int t = 0; t < TRACK_COUNT; ++t) {
|
|
const model::Cell &cell = pat->cell(t, patLine);
|
|
if (pass == 0) { if (cell.isNoteOff()) triggerCell(proj, lane, t, cell); }
|
|
else { if (cell.isPlayable()) triggerCell(proj, lane, t, cell); }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ patches
|
|
|
|
SynthPatch Engine::Impl::patchForSlot(const ToolboxSlot *slot, float tempoBpm) {
|
|
if (is(slot, "NES_SYNTH")) return SynthPatch::from(&slot->values, tempoBpm);
|
|
if (is(slot, "MORPH_PAD")) return SynthPatch::forPad(frasil::FrasilPatch::from(&slot->values));
|
|
if (is(slot, "WAVETABLE")) return SynthPatch::forWave(wavetable::WavePatch::from(&slot->values, tempoBpm));
|
|
return SynthPatch::defaults();
|
|
}
|
|
|
|
void Engine::Impl::refreshSynthPatches(Project &proj) {
|
|
const float tempo = proj.tempoBpm;
|
|
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
|
const ToolboxSlot *slot = slotAt(proj, proj.mixer.channels[ch].instrumentSlot);
|
|
if (is(slot, "GRAIN_CLOUD")) {
|
|
if (!cloudOn[ch] || ver(*slot) != cloudVer[ch] || tempo != cloudTempo[ch]) {
|
|
clouds[ch]->setPatch(GrainPatch::from(&slot->values, tempo));
|
|
cloudVer[ch] = ver(*slot);
|
|
cloudTempo[ch] = tempo;
|
|
}
|
|
cloudOn[ch] = true;
|
|
} else if (cloudOn[ch]) {
|
|
cloudOn[ch] = false;
|
|
clouds[ch]->kill();
|
|
}
|
|
if (!slot || !hasSynthPatch(slot)) { synthPatchHas[ch] = false; synthPatchVer[ch] = -1; continue; }
|
|
if (!synthPatchHas[ch] || ver(*slot) != synthPatchVer[ch] || tempo != synthPatchTempo[ch]) {
|
|
synthPatch[ch] = patchForSlot(slot, tempo);
|
|
synthPatchHas[ch] = true;
|
|
synthPatchVer[ch] = ver(*slot);
|
|
synthPatchTempo[ch] = tempo;
|
|
}
|
|
const SynthPatch &p = synthPatch[ch];
|
|
const int sbase = ch * POLYPHONY;
|
|
for (int i = 0; i < POLYPHONY; ++i) if (seqVoices[sbase + i]->isActive()) seqVoices[sbase + i]->setPatch(p);
|
|
const int bbase = ch * BUS_POLYPHONY;
|
|
for (int i = 0; i < BUS_POLYPHONY; ++i) if (busVoices[bbase + i]->isActive()) busVoices[bbase + i]->setPatch(p);
|
|
}
|
|
const ToolboxSlot *aslot = slotAt(proj, auditionSlotIdx);
|
|
if (is(aslot, "GRAIN_CLOUD") && (ver(*aslot) != auditionCloudVer || tempo != auditionCloudTempo)) {
|
|
auditionCloud->setPatch(GrainPatch::from(&aslot->values, tempo));
|
|
auditionCloudVer = ver(*aslot);
|
|
auditionCloudTempo = tempo;
|
|
}
|
|
if (aslot && hasSynthPatch(aslot)) {
|
|
if (!auditionPatchHas || ver(*aslot) != auditionPatchVer || tempo != auditionPatchTempo) {
|
|
auditionPatch = patchForSlot(aslot, tempo);
|
|
auditionPatchHas = true;
|
|
auditionPatchVer = ver(*aslot);
|
|
auditionPatchTempo = tempo;
|
|
}
|
|
for (auto &v : liveVoices) if (v->isActive()) v->setPatch(auditionPatch);
|
|
}
|
|
}
|
|
|
|
void Engine::Impl::allSeqVoicesOff() {
|
|
for (auto &c : clouds) c->releaseSequenced();
|
|
for (auto &v : seqVoices) v->noteOff();
|
|
for (auto &v : sampleVoices) v->release(); // a stopped song stops One-shot pads too
|
|
for (auto &a : arps) a.stop();
|
|
allMidiNotesOff();
|
|
}
|
|
|
|
// ------------------------------------------------------------------ outgoing MIDI
|
|
|
|
void Engine::Impl::emitMidi(int status, int d1, int d2) {
|
|
if (!midiOutEnabled.load(std::memory_order_relaxed)) return;
|
|
const int h = moutHead.load(std::memory_order_relaxed);
|
|
const int next = (h + 1) & 255;
|
|
if (next == moutTail.load(std::memory_order_acquire)) return;
|
|
moutRing[h] = (status << 16) | ((d1 & 0x7F) << 8) | (d2 & 0x7F);
|
|
moutHead.store(next, std::memory_order_release);
|
|
}
|
|
|
|
void Engine::Impl::emitNoteOn(int ch, int note, int vel) {
|
|
if (ch < 1) return;
|
|
emitMidi(0x90 | ((ch - 1) & 0x0F), kt::coerceIn(note, 0, 127), kt::coerceIn(vel, 1, 127));
|
|
}
|
|
|
|
void Engine::Impl::emitNoteOff(int ch, int note) {
|
|
if (ch < 1) return;
|
|
emitMidi(0x80 | ((ch - 1) & 0x0F), kt::coerceIn(note, 0, 127), 0);
|
|
}
|
|
|
|
void Engine::Impl::allMidiNotesOff() {
|
|
for (int k = 0; k < LANE_COUNT * TRACK_COUNT; ++k)
|
|
if (moutNote[k] >= 0) { emitNoteOff(moutCh[k], moutNote[k]); moutNote[k] = -1; }
|
|
}
|
|
|
|
int Engine::Impl::pollMidiOut() {
|
|
const int t = moutTail.load(std::memory_order_relaxed);
|
|
if (t == moutHead.load(std::memory_order_acquire)) return -1;
|
|
const int v = moutRing[t];
|
|
moutTail.store((t + 1) & 255, std::memory_order_release);
|
|
return v;
|
|
}
|
|
|
|
void Engine::Impl::publish() {
|
|
Project *proj = project.load(std::memory_order_relaxed);
|
|
const int linesPerBeat = proj ? model::info(proj->timeSignature).linesPerBeat : 4;
|
|
int line, beat;
|
|
if (arrangementMode) {
|
|
const std::vector<int> &list = *playlist.load(std::memory_order_acquire);
|
|
beat = !list.empty() ? list[kt::coerceIn(playlistIndex, 0, (int)list.size() - 1)] : 0;
|
|
line = arrPlayLine;
|
|
} else {
|
|
line = currentLine;
|
|
beat = currentLine / linesPerBeat;
|
|
}
|
|
const uint64_t packed = ((uint64_t)(uint32_t)line & 0x7FFFFFFFu) | (((uint64_t)(uint32_t)beat & 0x7FFFFFFFu) << 31)
|
|
| ((uint64_t)(playing.load(std::memory_order_relaxed) ? 1 : 0) << 62);
|
|
transportPacked.store(packed, std::memory_order_relaxed);
|
|
}
|
|
|
|
// ------------------------------------------------------------------ Engine
|
|
|
|
Engine::Engine(int sampleRate, sampler::SampleStore *store, const EngineGlobals &globals)
|
|
: impl(std::make_unique<Impl>(sampleRate, store, globals)) {}
|
|
Engine::~Engine() = default;
|
|
|
|
int Engine::sampleRate() const { return impl->sampleRate; }
|
|
void Engine::setProject(model::Project *p) { impl->setProject(p); }
|
|
void Engine::rebuildFxChains() { impl->rebuildFxChains(); }
|
|
void Engine::rebuildArrangement() { impl->rebuildArrangement(); }
|
|
void Engine::refreshLoopPlaylist() { impl->refreshLoopPlaylist(); }
|
|
void Engine::play(int startBeat) { impl->play(startBeat); }
|
|
void Engine::pause() { impl->pause(); }
|
|
void Engine::stop() { impl->stop(); }
|
|
void Engine::panic() { impl->panic(); }
|
|
|
|
TransportState Engine::transport() const {
|
|
const uint64_t v = impl->transportPacked.load(std::memory_order_relaxed);
|
|
TransportState t;
|
|
t.currentLine = (int)(v & 0x7FFFFFFFu);
|
|
t.currentBeat = (int)((v >> 31) & 0x7FFFFFFFu);
|
|
t.isPlaying = ((v >> 62) & 1) != 0;
|
|
return t;
|
|
}
|
|
bool Engine::isPlaying() const { return impl->playing.load(); }
|
|
|
|
void Engine::fillBlock(float *out, int frames) { impl->fillBlock(out, frames); }
|
|
|
|
void Engine::liveNoteOn(int pitch, int velocity) { impl->liveNoteOn(pitch, velocity); }
|
|
void Engine::liveNoteOff(int pitch) { impl->liveNoteOff(pitch); }
|
|
void Engine::auditionSlotOn(int slotIndex, int midi) { impl->auditionSlotOn(slotIndex, midi); }
|
|
void Engine::auditionSlotOff(int midi) { impl->auditionSlotOff(midi); }
|
|
void Engine::busNoteOn(int midiChannel, int midi, int velocity) { impl->busNoteOn(midiChannel, midi, velocity); }
|
|
void Engine::busNoteOff(int midiChannel, int midi) { impl->busNoteOff(midiChannel, midi); }
|
|
std::string Engine::describeBusTargets(int midiChannel, int midi) const {
|
|
return impl->describeBusTargets(midiChannel, midi);
|
|
}
|
|
|
|
float Engine::channelMeter(int ch) const {
|
|
return ch >= 0 && ch < TRACK_COUNT ? impl->chMeter[ch].load(std::memory_order_relaxed) : 0.f;
|
|
}
|
|
bool Engine::channelClipped(int ch) const {
|
|
return ch >= 0 && ch < TRACK_COUNT && impl->chClipHold[ch].load(std::memory_order_relaxed) > 0;
|
|
}
|
|
/** AudioEngine.vizFor: the first effect of toolbox [slotIndex] in any channel's chain
|
|
* that publishes a scope, or nullptr. */
|
|
const Effect *Engine::Impl::vizFor(const Chains *chains, int slotIndex) const {
|
|
if (!chains) return nullptr;
|
|
for (const auto &ch : chains->ch)
|
|
for (const FxUnit &u : ch)
|
|
if (u.slotIndex == slotIndex && u.effect->hasScope()) return u.effect.get();
|
|
return nullptr;
|
|
}
|
|
|
|
int Engine::effectScope(int slotIndex, float *out, int capacity) const {
|
|
impl->vizReaders.fetch_add(1);
|
|
const Effect *e = impl->vizFor(impl->channelChains.load(), slotIndex);
|
|
int n = e ? e->copyScope(out, capacity) : -1;
|
|
impl->vizReaders.fetch_sub(1);
|
|
return n;
|
|
}
|
|
|
|
float Engine::effectPlayhead(int slotIndex) const {
|
|
impl->vizReaders.fetch_add(1);
|
|
const Effect *e = impl->vizFor(impl->channelChains.load(), slotIndex);
|
|
float p = e ? e->playhead() : -1.f;
|
|
impl->vizReaders.fetch_sub(1);
|
|
return p;
|
|
}
|
|
|
|
void Engine::setMidiOutEnabled(bool on) { impl->midiOutEnabled.store(on); }
|
|
bool Engine::midiOutEnabled() const { return impl->midiOutEnabled.load(); }
|
|
int Engine::pollMidiOut() { return impl->pollMidiOut(); }
|
|
|
|
void Engine::setMasterSink(MasterSink *sink) { impl->sink = sink; }
|
|
void Engine::setRecordingArm(bool armed, int tailBars) {
|
|
impl->recordArmed.store(armed);
|
|
impl->recTailBars.store(kt::coerceIn(tailBars, 0, 8));
|
|
}
|
|
void Engine::setRecordTailBars(int tailBars) { impl->recTailBars.store(kt::coerceIn(tailBars, 0, 8)); }
|
|
bool Engine::recordArmed() const { return impl->recordArmed.load(); }
|
|
void Engine::externalClockStart() {
|
|
impl->extClockRunning.store(true);
|
|
impl->maybeStartRecording();
|
|
}
|
|
void Engine::externalClockStop() { impl->extClockRunning.store(false); }
|
|
|
|
} // namespace sizzle::engine
|