diff --git a/.github/workflows/ports.yml b/.github/workflows/ports.yml index 5f9ec5f7..9899c9ea 100644 --- a/.github/workflows/ports.yml +++ b/.github/workflows/ports.yml @@ -90,8 +90,11 @@ jobs: - name: the plugin loaded as a host loads it; the editor's picture run: | A=build/juce-plugin/JiantFM_artefacts/Release - xvfb-run -a build/juce-plugin/plugin_check_artefacts/Release/plugin_check "$A/VST3/JIANT FM.vst3" - xvfb-run -a build/juce-plugin/editor_shot_artefacts/Release/editor_shot build/juce-plugin/editor.png + B=build/juce-plugin + xvfb-run -a $B/sysex_check_artefacts/Release/sysex_check + xvfb-run -a $B/sample_check_artefacts/Release/sample_check $B/sample_state.bin + xvfb-run -a $B/plugin_check_artefacts/Release/plugin_check "$A/VST3/JIANT FM.vst3" $B/sample_state.bin + xvfb-run -a $B/editor_shot_artefacts/Release/editor_shot $B/editor.png cd "$A" && zip -qr "$GITHUB_WORKSPACE/JIANT-FM-Linux.zip" "VST3/JIANT FM.vst3" "LV2/JIANT FM.lv2" "Standalone/JIANT FM" - uses: actions/upload-artifact@v4 with: diff --git a/ports/juce-plugin/CMakeLists.txt b/ports/juce-plugin/CMakeLists.txt index 327da525..002b7584 100644 --- a/ports/juce-plugin/CMakeLists.txt +++ b/ports/juce-plugin/CMakeLists.txt @@ -74,7 +74,11 @@ foreach(k RANGE ${JIANT_LAST}) endif() list(APPEND JIANT_CORE_SOURCES "${f}") endforeach() -target_sources(JiantFM PRIVATE Source/JiantProcessor.cpp Source/JiantEditor.cpp ${JIANT_CORE_SOURCES}) +target_sources(JiantFM PRIVATE Source/JiantProcessor.cpp Source/JiantEditor.cpp Source/SamplePanel.cpp Source/JiantLook.cpp + ${JIANT_CORE_SOURCES}) +# the editor's type: DotGothic16 (ASCII, from web/emu/fonts) and IBM Plex Mono, both OFL (fonts/) +juce_add_binary_data(JiantFMFonts SOURCES fonts/DotGothic16-ascii.ttf fonts/IBMPlexMono-SemiBold.ttf) +set_target_properties(JiantFMFonts PROPERTIES POSITION_INDEPENDENT_CODE ON) target_include_directories(JiantFM PRIVATE "${REPO}/ports/core" "${REPO}/build/gen" "${REPO}/firmware/src") target_compile_definitions(JiantFM PRIVATE JIANT_COPIES=${JIANT_COPIES}) # the firmware's C, as the emulator and the host tests build it: no fused multiply-adds, its own warnings off; out of @@ -90,10 +94,10 @@ if(WIN32) target_include_directories(JiantFM PRIVATE "${REPO}/ports/core/compat") endif() target_compile_definitions(JiantFM PUBLIC - JUCE_WEB_BROWSER=0 JUCE_USE_CURL=0 JUCE_VST3_CAN_REPLACE_VST2=0 JUCE_DISPLAY_SPLASH_SCREEN=0 + JUCE_WEB_BROWSER=0 JUCE_USE_CURL=0 JUCE_VST3_CAN_REPLACE_VST2=0 JUCE_DISPLAY_SPLASH_SCREEN=0 JUCE_USE_FLAC=1 JUCE_USE_MP3AUDIOFORMAT=1 JUCE_REPORT_APP_USAGE=0) target_link_libraries(JiantFM - PRIVATE juce::juce_audio_utils + PRIVATE juce::juce_audio_utils JiantFMFonts PUBLIC juce::juce_recommended_config_flags juce::juce_recommended_lto_flags) # the check: the built plugin loaded as a host loads it (tests/plugin_check.cpp); -DJIANT_CHECK=ON @@ -118,4 +122,9 @@ if(JIANT_CHECK AND NOT WIN32) target_sources(sysex_check PRIVATE tests/sysex_check.cpp) target_compile_definitions(sysex_check PRIVATE JUCE_MODAL_LOOPS_PERMITTED=1 JUCE_WEB_BROWSER=0 JUCE_USE_CURL=0) target_link_libraries(sysex_check PRIVATE JiantFM juce::juce_audio_utils PUBLIC juce::juce_recommended_config_flags) + # samples: a file dropped on the editor, SAMPLE playing it, REC, the slots through the state (tests/sample_check.cpp) + juce_add_console_app(sample_check PRODUCT_NAME "sample_check") + target_sources(sample_check PRIVATE tests/sample_check.cpp) + target_compile_definitions(sample_check PRIVATE JUCE_MODAL_LOOPS_PERMITTED=1 JUCE_WEB_BROWSER=0 JUCE_USE_CURL=0) + target_link_libraries(sample_check PRIVATE JiantFM juce::juce_audio_utils PUBLIC juce::juce_recommended_config_flags) endif() diff --git a/ports/juce-plugin/README.md b/ports/juce-plugin/README.md index 7d0a1458..2960ee0c 100644 --- a/ports/juce-plugin/README.md +++ b/ports/juce-plugin/README.md @@ -18,7 +18,8 @@ SHIFT-click holds a button, and the computer keyboard as the emulator's (Z..' an | Web editor | the standalone app answers [the web editor](../../web/editor.html) (its SysEx in, the replies out of the MIDI output chosen in its settings: connect the two through a virtual MIDI cable, e.g. IAC on macOS, loopMIDI on Windows); it shows as "JIANT FM app / plugin" with SAMPLE, GRAIN and DRUM-X's samples. The plugins take the editor's SysEx but have no MIDI output (their buses as before), so a DAW does not pass the replies back | | Sync | **Host** (default): the sequencer follows the host's transport and tempo; **Internal**: its own tempo | | Parameters | Volume (the MASTER knob), Sync | -| Saved | in the host's project: the live section, the songs, the user presets | +| Samples | JIANT's 16 slots (SAMPLE, GRAIN, DRUM-X's sample layer): drop WAV / AIFF / FLAC / MP3 / OGG files anywhere on the window (on a slot of the browser: that slot; elsewhere: the browser's slot, the next ones for several files), or the browser's LOAD and CLEAR. Any rate (resampled to 44.1 kHz), mono or stereo, up to 60 s. REC inside JIANT (SAMPLE / GRAIN) records the master or a track, and the input when the host gives the plugin one (its **Input** bus, off until turned on: a DAW's sidechain; not on AU) | +| Saved | in the host's project: the live section, the songs, the user presets, and every slot's audio embedded (FLAC, lossless, about half the PCM's size: a 60 s stereo slot ~5-7 MB of its 10.6 MB, so a session with 16 full slots can reach ~100 MB; a short one-shot a few KB) with its name and the file it came from. The project carries its samples to another computer; nothing is read from the original files again | | Sample rate | any (the firmware's 44.1 kHz, resampled) | | Power | a computer's CPU: every track its own 8 voices; the firmware's own load governor on the real time ([`ports/README.md`](../README.md)) | | Several per session | up to 8 instances in one DAW session (one process), each a whole JIANT of its own, on its own audio thread if the host gives it one: the core is compiled 8 times, every copy's symbols its own ([`ports/core/jiant_copies.h`](../core/jiant_copies.h)); a 9th stays silent and says so. Memory: ~1 MB of code and ~6.4 MB of zeroed data per copy in the binary, resident only once a copy plays; the sample slots as loaded, the recorder's 60 s spare (21 MB, zeroed until it records) per playing instance | @@ -27,7 +28,7 @@ SHIFT-click holds a button, and the computer keyboard as the emulator's (Z..' an ```sh ports/juce-plugin/build.sh # this computer's formats -> build/juce-plugin/JiantFM_artefacts/Release -ports/juce-plugin/build.sh -DJIANT_CHECK=ON # and the checks: tests/plugin_check.cpp, tests/editor_shot.cpp, tests/sysex_check.cpp +ports/juce-plugin/build.sh -DJIANT_CHECK=ON # and the checks: tests/plugin_check.cpp, editor_shot.cpp, sysex_check.cpp, sample_check.cpp ``` JUCE 9.0.5 is fetched (or `JUCE_DIR=`). macOS: `-G Xcode` (AUv3). iOS: @@ -39,7 +40,10 @@ description, a chord at 44.1, 48 and 96 kHz in blocks of 32 to 1024 frames (it s note-offs, nothing non-finite), the state out and back; then 4 instances at once on 4 threads, each its own sound (no two the same; a note into one sounds there only), each its own state (saved, changed, put back), 8 sounding, the 9th silent, one closed and its JIANT taken by a new one; the editor made. macOS adds Apple's -`auval`. `sysex_check` makes the processor as the standalone app does and sends the web editor's INFO, PRESET and DESC +`auval`. `sample_check` makes the processor and its editor: a WAV dropped on the editor lands in slot 1, SAMPLE plays it, +REC MST records a bar into slot 2 from inside JIANT, the state carries both to a new instance (another JIANT), which +plays them; the state it writes is loaded into the built VST3 by `plugin_check` (as the second argument). +`sysex_check` makes the processor as the standalone app does and sends the web editor's INFO, PRESET and DESC through processBlock: the replies come back in its MIDI (the device as a computer, its big CPU's engines). ## Installing diff --git a/ports/juce-plugin/Source/JiantEditor.cpp b/ports/juce-plugin/Source/JiantEditor.cpp index e2764d1e..a22ef0f9 100644 --- a/ports/juce-plugin/Source/JiantEditor.cpp +++ b/ports/juce-plugin/Source/JiantEditor.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-only // Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) #include "JiantEditor.h" +#include "JiantLook.h" #include "jiant_core.h" #include @@ -85,8 +86,10 @@ int buttonForChar(juce::juce_wchar c) } } // namespace -JiantEditor::JiantEditor(JiantProcessor& p) : AudioProcessorEditor(p), proc_(p) +JiantEditor::JiantEditor(JiantProcessor& p) : AudioProcessorEditor(p), proc_(p), samples_(p) { + addChildComponent(samples_); + samples_.onClose = [this] { samples_.setVisible(false); repaint(); }; float master = proc_.params.getRawParameterValue("volume")->load(); angle_[0] = -135.0f + 270.0f * master / 100.0f; setResizable(true, true); @@ -104,7 +107,22 @@ JiantEditor::~JiantEditor() proc_.post({JiantProcessor::Command::Keys, 0}); } -void JiantEditor::resized() { scale_ = float(getWidth()) / kW; } +void JiantEditor::resized() +{ + scale_ = float(getWidth()) / kW; + samples_.setBounds(juce::Rectangle(kW - 340, 12, 328, kH - 24).transformedBy(juce::AffineTransform::scale(scale_)).toNearestInt()); +} + +bool JiantEditor::isInterestedInFileDrag(const juce::StringArray& files) { return samples_.isInterestedInFileDrag(files); } + +void JiantEditor::filesDropped(const juce::StringArray& files, int x, int y) +{ + samples_.setVisible(true); + if (samples_.getBounds().contains(x, y)) + samples_.filesDropped(files, x - samples_.getX(), y - samples_.getY()); + else + samples_.load(samples_.selected(), files); +} juce::Point JiantEditor::toPanel(juce::Point p) const { return p / scale_; } @@ -208,7 +226,10 @@ void JiantEditor::paint(juce::Graphics& g) } g.setColour(cLabel.withAlpha(0.5f)); g.setFont(juce::FontOptions(11.0f)); - g.drawText("JIANT FM - CPU " + juce::String(proc_.cpuPercent()) + " %", juce::Rectangle(36, 596, 928, 20), + jlook::button(g, samplesButton_, "SAMPLES", samples_.isVisible()); + g.setColour(cLabel.withAlpha(0.5f)); + g.setFont(juce::FontOptions(11.0f)); + g.drawText("JIANT " + juce::String(proc_.copy() + 1) + " OF " + juce::String(JiantProcessor::copies()) + " - CPU " + juce::String(proc_.cpuPercent()) + " %", juce::Rectangle(36, 596, 928, 20), juce::Justification::centredRight); } @@ -274,6 +295,11 @@ void JiantEditor::turn(int knob, int n) void JiantEditor::mouseDown(const juce::MouseEvent& e) { grabKeyboardFocus(); + if (samplesButton_.contains(toPanel(e.position))) { + samples_.setVisible(!samples_.isVisible()); + repaint(); + return; + } Hit h = hitTest(toPanel(e.position)); const int src = e.source.getIndex(); if (h.kind == Knob) diff --git a/ports/juce-plugin/Source/JiantEditor.h b/ports/juce-plugin/Source/JiantEditor.h index 5a5295ae..20095099 100644 --- a/ports/juce-plugin/Source/JiantEditor.h +++ b/ports/juce-plugin/Source/JiantEditor.h @@ -8,10 +8,11 @@ // ALGORITHM). The window scales, its shape kept. #pragma once #include "JiantProcessor.h" +#include "SamplePanel.h" #include #include -class JiantEditor : public juce::AudioProcessorEditor, private juce::Timer +class JiantEditor : public juce::AudioProcessorEditor, public juce::FileDragAndDropTarget, private juce::Timer { public: explicit JiantEditor(JiantProcessor&); @@ -26,6 +27,9 @@ public: bool keyPressed(const juce::KeyPress&) override; bool keyStateChanged(bool isKeyDown) override; void focusLost(FocusChangeType) override; + // audio files dropped anywhere: into the sample browser's slot (on a slot of it: that one) + bool isInterestedInFileDrag(const juce::StringArray& files) override; + void filesDropped(const juce::StringArray& files, int x, int y) override; static constexpr int kW = 1000, kH = 624; // the drawing's own units @@ -52,6 +56,8 @@ private: std::map drags_; float angle_[8] = {}; float scale_ = 1.0f; + SamplePanel samples_; + juce::Rectangle samplesButton_ {36, 594, 110, 24}; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(JiantEditor) }; diff --git a/ports/juce-plugin/Source/JiantLook.cpp b/ports/juce-plugin/Source/JiantLook.cpp new file mode 100644 index 00000000..b12aa468 --- /dev/null +++ b/ports/juce-plugin/Source/JiantLook.cpp @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) +#include "JiantLook.h" +#include "BinaryData.h" + +namespace jlook { + +juce::Typeface::Ptr dotTypeface() +{ + static juce::Typeface::Ptr t = + juce::Typeface::createSystemTypefaceFor(BinaryData::DotGothic16ascii_ttf, BinaryData::DotGothic16ascii_ttfSize); + return t; +} +juce::Typeface::Ptr monoTypeface() +{ + static juce::Typeface::Ptr t = + juce::Typeface::createSystemTypefaceFor(BinaryData::IBMPlexMonoSemiBold_ttf, BinaryData::IBMPlexMonoSemiBold_ttfSize); + return t; +} + +void paintBody(juce::Graphics& g, juce::Rectangle r, float grid) +{ + g.setColour(bg); + g.fillRect(r); + g.setColour(juce::Colour(0x12efe6c8)); + for (float y = r.getY() + grid * 0.5f; y < r.getBottom(); y += grid) + for (float x = r.getX() + grid * 0.5f; x < r.getRight(); x += grid) + g.fillRect(x, y, 1.0f, 1.0f); + juce::ColourGradient heatLine(heat(0), r.getX(), 0, heat(1), r.getRight(), 0, false); + for (int i = 1; i < 5; ++i) + heatLine.addColour(i / 5.0, heat(i / 5.0f)); + g.setGradientFill(heatLine); + g.fillRect(r.getX(), r.getY(), r.getWidth(), 3.0f); +} + +void brackets(juce::Graphics& g, juce::Rectangle r, juce::Colour c, float len, float w) +{ + g.setColour(c); + const float x0 = r.getX(), y0 = r.getY(), x1 = r.getRight(), y1 = r.getBottom(); + g.fillRect(x0, y0, len, w); g.fillRect(x0, y0, w, len); + g.fillRect(x1 - len, y0, len, w); g.fillRect(x1 - w, y0, w, len); + g.fillRect(x0, y1 - w, len, w); g.fillRect(x0, y1 - len, w, len); + g.fillRect(x1 - len, y1 - w, len, w); g.fillRect(x1 - w, y1 - len, w, len); +} + +void ring(juce::Graphics& g, juce::Point c, float radius, float v, juce::Colour arc, bool bipolar, float thick) +{ + const float a0 = -0.75f * juce::MathConstants::pi, a1 = 0.75f * juce::MathConstants::pi; + v = juce::jlimit(0.0f, 1.0f, v); + juce::Path track; + track.addCentredArc(c.x, c.y, radius, radius, 0, a0, a1, true); + g.setColour(line.withAlpha(0.35f)); + g.strokePath(track, juce::PathStrokeType(thick, juce::PathStrokeType::curved, juce::PathStrokeType::rounded)); + const float from = bipolar ? 0.0f : a0, to = a0 + (a1 - a0) * v; + if (std::abs(to - from) > 1e-3f) { + juce::Path val; + val.addCentredArc(c.x, c.y, radius, radius, 0, std::min(from, to), std::max(from, to), true); + g.setColour(arc); + g.strokePath(val, juce::PathStrokeType(thick, juce::PathStrokeType::curved, juce::PathStrokeType::rounded)); + } + // the value's point, cream on the arc's end + const float px = c.x + radius * std::sin(to), py = c.y - radius * std::cos(to); + g.setColour(cream); + g.fillEllipse(px - thick * 0.6f, py - thick * 0.6f, thick * 1.2f, thick * 1.2f); + g.setColour(panel); + g.fillEllipse(c.x - radius + thick * 1.6f, c.y - radius + thick * 1.6f, 2 * (radius - thick * 1.6f), + 2 * (radius - thick * 1.6f)); + g.setColour(line); + g.drawEllipse(c.x - radius + thick * 1.6f, c.y - radius + thick * 1.6f, 2 * (radius - thick * 1.6f), + 2 * (radius - thick * 1.6f), 1.0f); +} + +void button(juce::Graphics& g, juce::Rectangle r, const juce::String& text, bool lit, bool held, juce::Colour on, + float font) +{ + g.setColour(lit ? on.interpolatedWith(bg, 0.82f) : panel); + g.fillRect(r); + g.setColour(held ? cream : lit ? on : on.withAlpha(0.45f)); + g.drawRect(r, held ? 2.0f : 1.25f); + g.setColour(lit ? cream : ink); + g.setFont(dot(font)); + g.drawFittedText(text, r.toNearestInt().reduced(2, 0), juce::Justification::centred, 1, 0.8f); +} + +} // namespace jlook diff --git a/ports/juce-plugin/Source/JiantLook.h b/ports/juce-plugin/Source/JiantLook.h new file mode 100644 index 00000000..26607cd0 --- /dev/null +++ b/ports/juce-plugin/Source/JiantLook.h @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) +// +// JIANT's look for the plugin's editor, as the site's FM-1 panel (web/emu/devices.html) and the firmware's JIANT skin +// draw it: a near-black body with a faint dot grid, thin lines, values as heat (indigo violet pink red orange amber +// cream), what is active in orange, what is selected in violet; DotGothic16 for names, IBM Plex Mono for values (both +// OFL, embedded: ports/juce-plugin/fonts). +#pragma once +#include + +namespace jlook { + +const juce::Colour bg(0xff050409), body(0xff0b0a11), panel(0xff100f17), surf(0xff15141d), line(0x29efe6c8), + lineHi(0x55efe6c8), ink(0xffddd6ea), dim(0xffa39cba), faint(0xff655d78), org(0xffff7a1a), vio(0xffb870ff), + cyan(0xff3fe0e6), grn(0xff8be06a), red(0xffff4b4b), cream(0xfffff3ce), yellow(0xffffe14d); + +// the heat gradient, 0..1 (the site's --heat): the six tracks take its stops +inline juce::Colour heat(float t) +{ + static const juce::uint32 stops[6] = {0xff9d97ff, 0xffd39bff, 0xffff9fd2, 0xffff9a8a, 0xffffc07a, 0xfffff3a8}; + t = juce::jlimit(0.0f, 1.0f, t) * 5.0f; + int i = juce::jmin(4, int(t)); + return juce::Colour(stops[i]).interpolatedWith(juce::Colour(stops[i + 1]), t - float(i)); +} +inline juce::Colour track(int k) { return heat(float(k) / 5.0f); } + +juce::Typeface::Ptr dotTypeface(); +juce::Typeface::Ptr monoTypeface(); +inline juce::FontOptions dot(float h) { return juce::FontOptions(dotTypeface()).withHeight(h); } +inline juce::FontOptions mono(float h) { return juce::FontOptions(monoTypeface()).withHeight(h); } + +// the body: its colour, the dot grid, the heat line along the top +void paintBody(juce::Graphics& g, juce::Rectangle r, float grid = 14.0f); +// HUD corner brackets around r (the site's .stage corners) +void brackets(juce::Graphics& g, juce::Rectangle r, juce::Colour c, float len = 12.0f, float w = 1.5f); +// a ring with its value as an arc (from -135 degrees), the arc in heat or c +void ring(juce::Graphics& g, juce::Point c, float radius, float value01, juce::Colour arc, bool bipolar = false, + float thick = 4.0f); +// a button: dark, a thin edge; lit: orange edge and a warm fill +void button(juce::Graphics& g, juce::Rectangle r, const juce::String& text, bool lit, bool held = false, + juce::Colour on = org, float font = 13.0f); + +} // namespace jlook diff --git a/ports/juce-plugin/Source/JiantProcessor.cpp b/ports/juce-plugin/Source/JiantProcessor.cpp index c90d9ef3..4c83dc28 100644 --- a/ports/juce-plugin/Source/JiantProcessor.cpp +++ b/ports/juce-plugin/Source/JiantProcessor.cpp @@ -12,6 +12,26 @@ namespace { // claimed by a new one starts that one from there, not from the last one's music std::vector g_fresh[JIANT_COPIES]; constexpr uint32_t kStateMagic = 0x504E544Au; // "JNTP": the plugin's state, then the core's +constexpr uint32_t kSampleMagic = 0x4C504D53u; // "SMPL": then the sample slots, each slot's audio whole +constexpr int kFifo = 1 << 15; // (the input's room at the host's rate) +int64_t nowMs() +{ + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); +} +// a slot's audio as its key: frames, channels, name and every sample (FNV-1a 64) +uint64_t pcmKey(const int16_t* l, const int16_t* r, uint32_t frames, uint32_t ch, const char* name) +{ + uint64_t h = 1469598103934665603ull; + auto mix = [&](uint64_t v) { h = (h ^ v) * 1099511628211ull; }; + mix(frames); + mix(ch); + for (const char* c = name; c && *c; ++c) mix(uint8_t(*c)); + for (uint32_t i = 0; i < frames; ++i) { + mix(uint16_t(l[i])); + if (ch > 1) mix(uint16_t(r[i])); + } + return h | 1u; +} } juce::AudioProcessorValueTreeState::ParameterLayout JiantProcessor::layout() @@ -24,10 +44,22 @@ juce::AudioProcessorValueTreeState::ParameterLayout JiantProcessor::layout() return l; } +// stereo out; an input for JIANT's recorder (REC from the input, GRAIN LIVE; a DAW's sidechain), off until the host +// turns it on: not on AU / AUv3, where an instrument with an input is an effect to some hosts +juce::AudioProcessor::BusesProperties JiantProcessor::buses() +{ + auto b = BusesProperties().withOutput("Output", juce::AudioChannelSet::stereo(), true); + auto t = juce::PluginHostType::getPluginLoadedAs(); + if (t != wrapperType_AudioUnit && t != wrapperType_AudioUnitv3) + b = b.withInput("Input", juce::AudioChannelSet::stereo(), false); + return b; +} + JiantProcessor::JiantProcessor() - : AudioProcessor(BusesProperties().withOutput("Output", juce::AudioChannelSet::stereo(), true)), + : AudioProcessor(buses()), params(*this, nullptr, "JIANT", layout()) { + formats_.registerBasicFormats(); uint32_t k = 0; core_ = jiant_copy_claim(&k); owner_ = core_ != nullptr; @@ -49,12 +81,19 @@ JiantProcessor::JiantProcessor() core_->jiant_service(); } publish(); + refreshSlots(); + service_ = std::make_unique(*this); + service_->startTimer(100); } } JiantProcessor::~JiantProcessor() { + service_.reset(); if (owner_) { + for (auto& in : slotIn_) + if (void* o = in.exchange(nullptr)) + core_->jiant_sample_free(static_cast(o)); if (core_->jiant_playing()) core_->jiant_play(0); core_->jiant_buttons(0); @@ -66,7 +105,10 @@ JiantProcessor::~JiantProcessor() bool JiantProcessor::isBusesLayoutSupported(const BusesLayout& layouts) const { const auto& out = layouts.getMainOutputChannelSet(); - return out == juce::AudioChannelSet::stereo() || out == juce::AudioChannelSet::mono(); + if (out != juce::AudioChannelSet::stereo() && out != juce::AudioChannelSet::mono()) + return false; + const auto& in = layouts.getMainInputChannelSet(); + return in.isDisabled() || in == juce::AudioChannelSet::stereo() || in == juce::AudioChannelSet::mono(); } void JiantProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) @@ -77,7 +119,13 @@ void JiantProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) std::fill(std::begin(histL_), std::end(histL_), 0.0f); std::fill(std::begin(histR_), std::end(histR_), 0.0f); bufN_ = bufAt_ = 0; - (void)samplesPerBlock; + const size_t room = size_t(std::max(samplesPerBlock, 0)) + size_t(kFifo); + inL_.assign(room, 0.0f); + inR_.assign(room, 0.0f); + fifoL_.assign(room + size_t(kFifo), 0.0f); + fifoR_.assign(room + size_t(kFifo), 0.0f); + fifoN_ = int(std::ceil(kBuf / step_)) + 4; // (the core renders ahead: its first input is silence) + inPos_ = 0.0; hostPlaying_ = false; lastMaster_ = lastSync_ = -1; } @@ -189,6 +237,17 @@ void JiantProcessor::render(float* l, float* r, int n) for (int i = 0; i < n; ++i) { while (frac_ >= 1.0) { if (bufAt_ >= bufN_) { + if (input_) { // this much of the input, at 44.1 kHz + const double per = 1.0 / step_; + for (int k = 0; k < kBuf; ++k, inPos_ += per) { + int i = int(inPos_); + float f = float(inPos_ - i); + bool in = i + 1 < fifoN_; + coreInL_[k] = in ? fifoL_[size_t(i)] + f * (fifoL_[size_t(i + 1)] - fifoL_[size_t(i)]) : 0.0f; + coreInR_[k] = in ? fifoR_[size_t(i)] + f * (fifoR_[size_t(i + 1)] - fifoR_[size_t(i)]) : 0.0f; + } + core_->jiant_input(coreInL_, coreInR_, kBuf); + } core_->jiant_render(bufL_, bufR_, kBuf); bufN_ = kBuf; bufAt_ = 0; @@ -211,15 +270,35 @@ void JiantProcessor::render(float* l, float* r, int n) void JiantProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBuffer& midi) { juce::ScopedNoDenormals noDenormals; + const int frames = buffer.getNumSamples(); + // the host's input (if it gives one), kept before the buffer becomes the output + const int inCh = getTotalNumInputChannels(); + input_ = owner_ && inCh > 0 && frames <= int(inL_.size()); + if (input_) { + std::memcpy(inL_.data(), buffer.getReadPointer(0), size_t(frames) * sizeof(float)); + std::memcpy(inR_.data(), buffer.getReadPointer(inCh > 1 ? 1 : 0), size_t(frames) * sizeof(float)); + if (resample_) { // onto the input's queue (its rate), what was taken dropped + int drop = std::max(0, std::min(int(inPos_) - 1, fifoN_)); + if (drop) { + std::memmove(fifoL_.data(), fifoL_.data() + drop, size_t(fifoN_ - drop) * sizeof(float)); + std::memmove(fifoR_.data(), fifoR_.data() + drop, size_t(fifoN_ - drop) * sizeof(float)); + fifoN_ -= drop; + inPos_ -= drop; + } + if (fifoN_ + frames <= int(fifoL_.size())) { + std::memcpy(fifoL_.data() + fifoN_, inL_.data(), size_t(frames) * sizeof(float)); + std::memcpy(fifoR_.data() + fifoN_, inR_.data(), size_t(frames) * sizeof(float)); + fifoN_ += frames; + } + } + } buffer.clear(); int idle = 0; if (!owner_ || !busy_.compare_exchange_strong(idle, 1, std::memory_order_acquire)) return; + lastBlockMs_.store(nowMs(), std::memory_order_relaxed); - if (size_t len = pendingLen_.load(std::memory_order_acquire)) { // a session's music, staged by the host - core_->jiant_state_load(pending_.data(), len); - pendingLen_.store(0, std::memory_order_release); - } + handOff(); uint32_t r = qRead_.load(std::memory_order_relaxed), w = qWrite_.load(std::memory_order_acquire); for (; r != w; ++r) { const Command& c = queue_[r % kQueue]; @@ -227,13 +306,13 @@ void JiantProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBu case Command::Buttons: core_->jiant_buttons(c.value); break; case Command::Keys: core_->jiant_keys(c.value); break; case Command::Encoder: core_->jiant_encoder(static_cast(c.enc), c.steps); break; + case Command::Midi: core_->jiant_midi(uint8_t(c.value), uint8_t(c.value >> 8), uint8_t(c.value >> 16)); break; default: break; } } qRead_.store(r, std::memory_order_release); applyParams(); - const int frames = buffer.getNumSamples(); float* outL = buffer.getWritePointer(0); float* outR = buffer.getNumChannels() > 1 ? buffer.getWritePointer(1) : nullptr; int nclk = lastSync_ == 1 ? hostClock(frames) : 0; @@ -258,6 +337,8 @@ void JiantProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBu next = std::min(next, clock_[size_t(ck)].offset); if (next <= at) next = at + 1; + if (input_ && !resample_) // the input as it came, before the frames it goes with + core_->jiant_input(inL_.data() + at, inR_.data() + at, uint32_t(next - at)); render(outL + at, outR ? outR + at : nullptr, next - at); // (mono: the left side) at = next; } @@ -278,13 +359,265 @@ void JiantProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBu } publish(); - if (snapReq_.exchange(false, std::memory_order_acq_rel)) { - snapLen_ = core_->jiant_state_save(snapshot_.data(), snapshot_.size()); - snapDone_.store(true, std::memory_order_release); + if (auto* j = job_.exchange(nullptr, std::memory_order_acq_rel)) { + (*j)(*core_); + jobDone_.store(true, std::memory_order_release); } busy_.store(0, std::memory_order_release); } +// ----------------------------------------------------------------------------------------- the core from elsewhere + +bool JiantProcessor::idleCore() +{ + for (int t = 0; t < 2000; ++t) { + int idle = 0; + if (busy_.compare_exchange_weak(idle, 2, std::memory_order_acquire)) + return true; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return false; +} + +bool JiantProcessor::withCore(const std::function& f) +{ + if (!owner_) + return false; + std::lock_guard one(jobMutex_); + // audio running (a block in the last 100 ms): its thread runs f at the end of its next block + if (nowMs() - lastBlockMs_.load(std::memory_order_relaxed) < 100) { + jobDone_.store(false, std::memory_order_relaxed); + job_.store(&f, std::memory_order_release); + for (int t = 0; t < 300 && !jobDone_.load(std::memory_order_acquire); ++t) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + const std::function* mine = &f; + if (jobDone_.load(std::memory_order_acquire) || !job_.compare_exchange_strong(mine, nullptr)) { + while (!jobDone_.load(std::memory_order_acquire)) // (taken just now: it finishes) + std::this_thread::yield(); + return true; + } + } + if (!idleCore()) // no audio: the core is ours + return false; + handOff(); + f(*core_); + publish(); + busy_.store(0, std::memory_order_release); + return true; +} + +// ---------------------------------------------------------------------------------------------------- samples + +void JiantProcessor::handOff() +{ + for (int k = 0; k < kSlots; ++k) + if (slotIn_[size_t(k)].load(std::memory_order_relaxed)) + if (void* o = slotIn_[size_t(k)].exchange(nullptr, std::memory_order_acq_rel)) + core_->jiant_slot_put(uint32_t(k), static_cast(o)); + if (uint32_t m = clearMask_.exchange(0, std::memory_order_acq_rel)) + for (int k = 0; k < kSlots; ++k) + if ((m >> k) & 1u) + core_->jiant_slot_clear(uint32_t(k)); + uint32_t slot = 0, fr = 0; + recState_.store(core_->jiant_rec_state(&slot, &fr), std::memory_order_relaxed); + recSlot_.store(int(slot), std::memory_order_relaxed); + recFrames_.store(int(fr), std::memory_order_relaxed); +} + +int JiantProcessor::recState(int* slot, int* frames) const +{ + if (slot) + *slot = recSlot_.load(std::memory_order_relaxed); + if (frames) + *frames = recFrames_.load(std::memory_order_relaxed); + return recState_.load(std::memory_order_relaxed); +} + +bool JiantProcessor::handOffPending() const +{ + if (clearMask_.load(std::memory_order_acquire)) + return true; + for (auto& a : slotIn_) + if (a.load(std::memory_order_acquire)) + return true; + return false; +} + +juce::String JiantProcessor::loadSample(int k, const float* l, const float* r, int frames, double rate, + const juce::String& name, const juce::String& file) +{ + if (!owner_) + return "this instance has no JIANT (all " + juce::String(copies()) + " are playing)"; + if (k < 0 || k >= kSlots) + return "no such slot"; + if (!l || frames <= 0 || rate < 1000.0) + return "no audio"; + juce::String n = name.toUpperCase().retainCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_.+#").substring(0, 31); + jiant_sample* o = core_->jiant_sample_make(l, r, uint32_t(frames), uint32_t(std::lround(rate)), n.toRawUTF8()); + if (!o) + return "out of memory"; + clearMask_.fetch_and(~(1u << k), std::memory_order_acq_rel); + if (void* was = slotIn_[size_t(k)].exchange(o, std::memory_order_acq_rel)) // (one not taken yet: never played) + core_->jiant_sample_free(static_cast(was)); + files_[size_t(k)] = file; + service(); + return {}; +} + +juce::String JiantProcessor::loadSample(int k, const juce::File& file) +{ + std::unique_ptr rd(formats_.createReaderFor(file)); + if (!rd) + return "not an audio file JIANT reads: " + file.getFileName(); + if (rd->sampleRate < 1000.0 || rd->lengthInSamples <= 0 || rd->numChannels < 1) + return "no audio in " + file.getFileName(); + // up to 60 s at 44.1 kHz (the slot's most), read at the file's rate + const int64_t most = int64_t(std::ceil(double(JIANT_SLOT_MAX_FRAMES) * rd->sampleRate / JIANT_RATE)) + 64; + const int frames = int(std::min(rd->lengthInSamples, most)); + const int ch = rd->numChannels > 1 ? 2 : 1; + juce::AudioBuffer buf(ch, frames); + if (!rd->read(&buf, 0, frames, 0, true, ch > 1)) + return "could not read " + file.getFileName(); + return loadSample(k, buf.getReadPointer(0), ch > 1 ? buf.getReadPointer(1) : nullptr, frames, rd->sampleRate, + file.getFileNameWithoutExtension(), file.getFullPathName()); +} + +void JiantProcessor::clearSample(int k) +{ + if (!owner_ || k < 0 || k >= kSlots) + return; + if (void* was = slotIn_[size_t(k)].exchange(nullptr, std::memory_order_acq_rel)) + core_->jiant_sample_free(static_cast(was)); + clearMask_.fetch_or(1u << k, std::memory_order_acq_rel); + files_[size_t(k)] = {}; + service(); +} + +// the service timer (message thread) and after each load: with no audio running the hand-offs go in from here; then +// what the slots let go of is freed, the recorder's room kept, the slots read for the browser +void JiantProcessor::service() +{ + if (!owner_) + return; + if (handOffPending() && nowMs() - lastBlockMs_.load(std::memory_order_relaxed) >= 100) + withCore([](const jiant_api&) {}); + std::lock_guard g(serviceMutex_); + core_->jiant_service(); + refreshSlots(); +} + +// (serviceMutex_ held) the slots as the core has them +void JiantProcessor::refreshSlots() +{ + for (int k = 0; k < kSlots; ++k) { + jiant_slot_info_t in; + core_->jiant_slot_info(uint32_t(k), &in); + Slot s; + s.frames = in.frames; + s.channels = in.channels; + s.name = juce::String(in.name); + s.file = in.frames && !in.changed ? files_[size_t(k)] : juce::String(); // (recorded in JIANT: no file has it) + auto& was = slots_[size_t(k)]; + if (s.frames != was.frames || s.channels != was.channels || s.name != was.name || s.file != was.file) { + was = s; + ++slotsSeq_; + } + } +} + +// the slots into the state: "SMPL", 1, the count, then each slot that holds audio: its number, name, file, channels, +// frames, and its audio as FLAC (16 bit, 44.1 kHz: lossless, about half the PCM's size). A slot unchanged since the +// last save reuses that save's FLAC +void JiantProcessor::writeSamples(juce::MemoryOutputStream& out) +{ + std::lock_guard g(serviceMutex_); + struct One { int k; juce::String name; uint32_t ch, frames; const juce::MemoryBlock* flac; }; + std::vector all; + juce::FlacAudioFormat flac; + for (int k = 0; k < kSlots; ++k) { + const jiant_sample* o = core_->jiant_slot_object(uint32_t(k)); // (whole until this thread's next service) + uint32_t frames = 0, ch = 0; + const int16_t* l = core_->jiant_sample_data(o, 0, &frames, &ch); + const int16_t* r = core_->jiant_sample_data(o, 1, nullptr, nullptr); + jiant_slot_info_t in; + core_->jiant_slot_info(uint32_t(k), &in); + if (!l || !frames) + continue; + const uint64_t key = pcmKey(l, r, frames, ch, in.name); + Blob& b = blobs_[size_t(k)]; + if (b.key != key) { + b.flac.reset(); + std::unique_ptr os = std::make_unique(b.flac, false); + auto wr = flac.createWriterFor(os, juce::AudioFormatWriterOptions {} + .withSampleRate(double(JIANT_RATE)) + .withNumChannels(int(ch)) + .withBitsPerSample(16) + .withQualityOptionIndex(5)); + bool ok = wr != nullptr; + std::vector a(4096), c(4096); + for (uint32_t at = 0; ok && at < frames; at += 4096) { + const int n = int(std::min(4096, frames - at)); + for (int i = 0; i < n; ++i) { + a[size_t(i)] = int(l[at + uint32_t(i)]) * 65536; // (JUCE's integers: 32 bit, left justified) + c[size_t(i)] = int(r[at + uint32_t(i)]) * 65536; + } + const int* chans[3] = {a.data(), ch > 1 ? c.data() : nullptr, nullptr}; + ok = wr->write(chans, n); + } + wr.reset(); // (the stream finished) + b.key = ok ? key : 0; + if (!ok) + continue; + } + all.push_back({k, juce::String(in.name), ch, frames, &b.flac}); + } + out.writeInt(int(kSampleMagic)); + out.writeInt(1); + out.writeInt(int(all.size())); + for (auto& one : all) { + out.writeInt(one.k); + out.writeString(one.name); + out.writeString(files_[size_t(one.k)]); + out.writeInt(int(one.ch)); + out.writeInt(int(one.frames)); + out.writeInt(int(one.flac->getSize())); + out.write(one.flac->getData(), one.flac->getSize()); + } +} + +void JiantProcessor::readSamples(juce::MemoryInputStream& in) +{ + uint32_t have = 0; + juce::FlacAudioFormat flac; + if (in.getNumBytesRemaining() >= 12 && uint32_t(in.readInt()) == kSampleMagic && in.readInt() == 1) { + int count = in.readInt(); + for (int i = 0; i < count && i < kSlots && in.getNumBytesRemaining() > 0; ++i) { + int k = in.readInt(); + juce::String name = in.readString(), file = in.readString(); + int ch = in.readInt(), frames = in.readInt(), size = in.readInt(); + if (k < 0 || k >= kSlots || ch < 1 || ch > 2 || frames <= 0 || frames > int(JIANT_SLOT_MAX_FRAMES) || + size <= 0 || size > in.getNumBytesRemaining()) + break; + juce::MemoryBlock blob; + in.readIntoMemoryBlock(blob, size); + std::unique_ptr rd(flac.createReaderFor(new juce::MemoryInputStream(blob, false), true)); + if (!rd) + continue; + juce::AudioBuffer buf(ch, frames); + buf.clear(); + if (!rd->read(&buf, 0, frames, 0, true, ch > 1)) + continue; + // (int16 through float and back: the same samples, made at 44.1 kHz) + if (loadSample(k, buf.getReadPointer(0), ch > 1 ? buf.getReadPointer(1) : nullptr, frames, JIANT_RATE, name, + file).isEmpty()) + have |= 1u << k; + } + } + for (int k = 0; k < kSlots; ++k) // the session's slots only: the others emptied + if (!((have >> k) & 1u) && (slots_[size_t(k)].frames || slotIn_[size_t(k)].load())) + clearSample(k); +} + // ---------------------------------------------------------------------------------------------------- the state void JiantProcessor::getStateInformation(juce::MemoryBlock& dest) @@ -294,27 +627,15 @@ void JiantProcessor::getStateInformation(juce::MemoryBlock& dest) auto xml = params.copyState().createXml(); juce::String text = xml ? xml->toString() : juce::String(); out.writeString(text); - if (!owner_) { - out.writeInt(0); - return; - } - snapDone_.store(false); - snapReq_.store(true, std::memory_order_release); - for (int t = 0; t < 300 && !snapDone_.load(std::memory_order_acquire); ++t) - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - if (!snapDone_.load(std::memory_order_acquire)) { // no audio running: the core is ours to read - snapReq_.store(false); - int idle = 0; - while (!busy_.compare_exchange_weak(idle, 2)) { - idle = 0; - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - snapLen_ = core_->jiant_state_save(snapshot_.data(), snapshot_.size()); - busy_.store(0, std::memory_order_release); - } - size_t len = snapLen_ <= snapshot_.size() ? snapLen_ : 0; + size_t len = 0; + if (owner_) + withCore([&](const jiant_api& c) { len = c.jiant_state_save(snapshot_.data(), snapshot_.size()); }); + if (len > snapshot_.size()) + len = 0; out.writeInt(int(len)); out.write(snapshot_.data(), len); + if (owner_) + writeSamples(out); } void JiantProcessor::setStateInformation(const void* data, int size) @@ -326,13 +647,15 @@ void JiantProcessor::setStateInformation(const void* data, int size) if (xml->hasTagName(params.state.getType())) params.replaceState(juce::ValueTree::fromXml(*xml)); int len = in.readInt(); - if (!owner_ || len <= 0 || len > size) + if (!owner_ || len < 0 || len > in.getNumBytesRemaining()) return; - std::vector blob(static_cast(len)); - if (in.read(blob.data(), len) != len) - return; - pending_ = std::move(blob); // in before the next block (processBlock) - pendingLen_.store(pending_.size(), std::memory_order_release); + if (len > 0) { + std::vector blob(static_cast(len)); + if (in.read(blob.data(), len) != len) + return; + withCore([&](const jiant_api& c) { c.jiant_state_load(blob.data(), blob.size()); }); + } + readSamples(in); } int JiantProcessor::copies() { return JIANT_COPIES; } diff --git a/ports/juce-plugin/Source/JiantProcessor.h b/ports/juce-plugin/Source/JiantProcessor.h index 14872eba..04d1d961 100644 --- a/ports/juce-plugin/Source/JiantProcessor.h +++ b/ports/juce-plugin/Source/JiantProcessor.h @@ -3,18 +3,23 @@ // // JIANT FM as a VST3 / AU / AUv3 / LV2 instrument and a standalone app (JUCE): the whole firmware (ports/core) inside, // its screen and the FM-1's panel in the editor (JiantEditor), MIDI in, the host's transport and tempo as a MIDI clock -// (Sync HOST), the music saved in the host's session. The firmware renders at 44.1 kHz in its own blocks; any other -// rate is resampled. +// (Sync HOST), the music and the sample slots saved in the host's session. The firmware renders at 44.1 kHz in its +// own blocks; any other rate is resampled (the audio input too, for JIANT's recorder). // // Threads: the core belongs to the audio thread. The editor (message thread) sends the panel through a lock-free queue -// and reads back the screen (a seqlock) and the lights (atomics). A state save asks the audio thread for a snapshot -// and waits; with no audio running it takes the core itself (busy_). One device per process (the firmware's state is -// global): each instance claims its own copy of the core -// (ports/core/jiant_copies.h), up to JIANT_COPIES in a process; one more stays silent and says so. +// and reads back the screen (a seqlock) and the lights (atomics). What needs the core from the message thread (a state +// save) runs as a job: the audio thread runs it at the end of a block; with no audio running the message thread takes +// the core itself (busy_). Samples: a file is read and made into a sample object on the message thread, handed to the +// audio thread by pointer (slotIn_), and what the slots let go of is freed by jiant_service on the service timer (the +// message thread), which also reads the slots for the browser and for the state. Each instance claims its own copy of +// the core (ports/core/jiant_copies.h), up to JIANT_COPIES in a process; one more stays silent and says so. #pragma once #include +#include #include #include +#include +#include #include struct jiant_api; @@ -48,7 +53,7 @@ public: void setStateInformation(const void* data, int size) override; // ---- the editor's side (message thread) ---- - struct Command { enum Kind : uint8_t { None, Buttons, Keys, Encoder } kind = None; uint32_t value = 0; uint8_t enc = 0; int32_t steps = 0; }; + struct Command { enum Kind : uint8_t { None, Buttons, Keys, Encoder, Midi } kind = None; uint32_t value = 0; uint8_t enc = 0; int32_t steps = 0; }; void post(const Command& c); // the panel into the device bool owner() const { return owner_; } int copy() const { return copy_; } // this instance's JIANT, 0..copies()-1 (-1: none free) @@ -60,21 +65,50 @@ public: uint32_t dimButtons() const { return dimButtons_.load(std::memory_order_relaxed); } uint32_t dimKeys() const { return dimKeys_.load(std::memory_order_relaxed); } uint32_t cpuPercent() const { return cpu_.load(std::memory_order_relaxed); } + // the core, from the message thread: f runs with the core to itself (on the audio thread at the end of a block, or + // here when no audio runs); false: no core (a silent instance). Blocks for up to a block's time + bool withCore(const std::function& f); + + // ---- samples: JIANT's 16 slots (message thread) ---- + static constexpr int kSlots = 16; + struct Slot { uint32_t frames = 0, channels = 0; juce::String name, file; }; + // a file (WAV, AIFF, FLAC, MP3, OGG; what the format manager reads) into slot (0..15): "" done, else why not. + // The editor's drop and its browser call this, as the tests do + juce::String loadSample(int slot, const juce::File& file); + // PCM into a slot (any rate: resampled), as a file's is + juce::String loadSample(int slot, const float* l, const float* r, int frames, double rate, const juce::String& name, + const juce::String& file = {}); + void clearSample(int slot); + const Slot& slot(int k) const { return slots_[size_t(k)]; } + uint32_t slotsChanged() const { return slotsSeq_; } // counts the changes the browser shows + juce::AudioFormatManager& formats() { return formats_; } + // the recorder: 0 idle, 1 armed, 2 recording; its slot and frames so far + int recState(int* slot = nullptr, int* frames = nullptr) const; + bool hasInput() const { return getTotalNumInputChannels() > 0; } + void service(); // the service timer's work (the tests call it too) juce::AudioProcessorValueTreeState params; private: static juce::AudioProcessorValueTreeState::ParameterLayout layout(); + static BusesProperties buses(); void applyParams(); int hostClock(int frames); // Sync HOST: the clock this block needs, into clock_ void render(float* l, float* r, int n); // n frames at the host's rate static float hermite(const float* y, float x); void publish(); + void handOff(); // (the core's thread) the slots' objects in, the clears + bool handOffPending() const; + bool idleCore(); // no audio running: the core taken here (busy_ 2) + void refreshSlots(); // (service) slots_ from the core + void writeSamples(juce::MemoryOutputStream& out); + void readSamples(juce::MemoryInputStream& in); const jiant_api* core_ = nullptr; // this instance's JIANT (0: all taken, silent) bool owner_ = false; int copy_ = -1; - std::atomic busy_ {0}; // 1 the audio thread is in the core, 2 a save without audio + std::atomic busy_ {0}; // 1 the audio thread is in the core, 2 the message thread + std::atomic lastBlockMs_ {0}; // when processBlock last ran (ms) // editor -> audio: one producer, one consumer static constexpr uint32_t kQueue = 512; @@ -87,13 +121,28 @@ private: std::array screen_ {}; uint32_t screenDraws_ = ~0u; std::atomic ledButtons_ {0}, ledKeys_ {0}, dimButtons_ {0}, dimKeys_ {0}, cpu_ {0}; + std::atomic recState_ {0}, recSlot_ {0}, recFrames_ {0}; + + // a job for the core (withCore) + std::mutex jobMutex_; // one job at a time + std::atomic*> job_ {nullptr}; + std::atomic jobDone_ {false}; // state - std::atomic snapReq_ {false}, snapDone_ {false}; std::vector snapshot_; - size_t snapLen_ = 0; - std::vector pending_; - std::atomic pendingLen_ {0}; + + // samples + juce::AudioFormatManager formats_; + std::array, kSlots> slotIn_ {}; // jiant_sample* made, for the audio thread to put + std::atomic clearMask_ {0}; + std::mutex serviceMutex_; // jiant_service and the slots' reads (any thread but audio) + std::array slots_ {}; + std::array files_ {}; // the file each slot was loaded from (the browser shows it) + uint32_t slotsSeq_ = 0; + struct Blob { uint64_t key = 0; juce::MemoryBlock flac; }; + std::array blobs_ {}; // each slot's audio as last saved (FLAC), by its PCM's hash + struct Service : juce::Timer { JiantProcessor& p; explicit Service(JiantProcessor& q) : p(q) {} void timerCallback() override { p.service(); } }; + std::unique_ptr service_; // parameters as last applied (audio thread) int lastMaster_ = -1, lastSync_ = -1; @@ -109,6 +158,12 @@ private: double step_ = 1.0, frac_ = 0.0; float histL_[4] = {}, histR_[4] = {}, bufL_[kBuf] = {}, bufR_[kBuf] = {}; int bufN_ = 0, bufAt_ = 0; + // the host's input (its rate) for the core (44.1 kHz): this block's, then what the core has not taken yet + std::vector inL_, inR_, fifoL_, fifoR_; + int fifoN_ = 0; + double inPos_ = 0.0; + float coreInL_[kBuf] = {}, coreInR_[kBuf] = {}; + bool input_ = false; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(JiantProcessor) }; diff --git a/ports/juce-plugin/Source/SamplePanel.cpp b/ports/juce-plugin/Source/SamplePanel.cpp new file mode 100644 index 00000000..91d0f063 --- /dev/null +++ b/ports/juce-plugin/Source/SamplePanel.cpp @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) +#include "SamplePanel.h" +#include "JiantLook.h" +#include "jiant_core.h" + +namespace { +constexpr int kHead = 34, kRow = 22, kFoot = 64; +} + +SamplePanel::SamplePanel(JiantProcessor& p) : proc_(p) +{ + setOpaque(true); + startTimerHz(10); +} + +bool SamplePanel::isAudioFile(const juce::String& path) +{ + static const juce::StringArray ext {".wav", ".wave", ".aif", ".aiff", ".aifc", ".flac", ".mp3", ".ogg", ".caf", ".m4a"}; + for (auto& e : ext) + if (path.endsWithIgnoreCase(e)) + return true; + return false; +} + +juce::Rectangle SamplePanel::rowRect(int k) const { return {8, kHead + k * kRow, getWidth() - 16, kRow - 2}; } +juce::Rectangle SamplePanel::loadRect() const { return {8, getHeight() - kFoot + 6, (getWidth() - 24) / 2, 26}; } +juce::Rectangle SamplePanel::clearRect() const +{ + auto l = loadRect(); + return l.withX(l.getRight() + 8); +} +juce::Rectangle SamplePanel::closeRect() const { return {getWidth() - 30, 6, 22, 22}; } + +int SamplePanel::rowAt(juce::Point p) const +{ + for (int k = 0; k < JiantProcessor::kSlots; ++k) + if (rowRect(k).contains(p)) + return k; + return -1; +} + +void SamplePanel::select(int k) +{ + selected_ = juce::jlimit(0, JiantProcessor::kSlots - 1, k); + repaint(); +} + +void SamplePanel::timerCallback() +{ + int slot = 0, frames = 0; + int rec = proc_.recState(&slot, &frames); + int shown = rec ? slot * 1000000 + rec * 100000 + frames / 4410 : -1; + if (proc_.slotsChanged() != seen_ || shown != recShown_) { + seen_ = proc_.slotsChanged(); + recShown_ = shown; + repaint(); + } +} + +void SamplePanel::paint(juce::Graphics& g) +{ + auto r = getLocalBounds().toFloat(); + g.setColour(jlook::body); + g.fillRect(r); + g.setColour(jlook::line); + g.drawRect(r, 1.0f); + jlook::brackets(g, r.reduced(1), jlook::org, 10.0f, 1.5f); + g.setFont(jlook::dot(15.0f)); + g.setColour(jlook::cream); + g.drawText("SAMPLES", 12, 6, getWidth() - 50, 22, juce::Justification::centredLeft); + g.setColour(jlook::dim); + g.setFont(jlook::mono(10.0f)); + g.drawText("16 SLOTS - DROP FILES", 92, 6, getWidth() - 130, 22, juce::Justification::centredLeft); + auto x = closeRect().toFloat().reduced(6); + g.setColour(jlook::ink); + g.drawLine(x.getX(), x.getY(), x.getRight(), x.getBottom(), 1.5f); + g.drawLine(x.getRight(), x.getY(), x.getX(), x.getBottom(), 1.5f); + + int recSlot = 0, recFrames = 0; + const int rec = proc_.recState(&recSlot, &recFrames); + for (int k = 0; k < JiantProcessor::kSlots; ++k) { + const auto& s = proc_.slot(k); + auto rr = rowRect(k).toFloat(); + const bool sel = k == selected_, drop = k == dropRow_; + g.setColour(sel ? jlook::org.withAlpha(0.14f) : (k & 1) ? jlook::surf : jlook::panel); + g.fillRect(rr); + if (sel || drop) { + g.setColour(drop ? jlook::cyan : jlook::org); + g.drawRect(rr, 1.25f); + } + g.setFont(jlook::mono(11.0f)); + g.setColour(s.frames ? jlook::heat(float(k) / 15.0f) : jlook::faint); + g.drawText(juce::String(k + 1).paddedLeft('0', 2), rr.withWidth(26).translated(6, 0), juce::Justification::centredLeft); + juce::String name = s.frames ? s.name : juce::String("-"); + juce::String len; + if (rec && recSlot == k) { + name = rec == 1 ? "REC ARMED" : "REC"; + len = juce::String(recFrames / double(JIANT_RATE), 1) + " s"; + } else if (s.frames) { + len = juce::String(s.frames / double(JIANT_RATE), 2) + " s " + (s.channels > 1 ? "ST" : "MO"); + } + g.setFont(jlook::dot(13.0f)); + g.setColour(rec && recSlot == k ? jlook::red : s.frames ? jlook::ink : jlook::faint); + g.drawText(name, rr.withTrimmedLeft(34).withTrimmedRight(84), juce::Justification::centredLeft, true); + g.setFont(jlook::mono(10.5f)); + g.setColour(jlook::dim); + g.drawText(len, rr.withTrimmedRight(6), juce::Justification::centredRight); + } + // the picked slot's file, LOAD and CLEAR, what last happened + const auto& s = proc_.slot(selected_); + g.setFont(jlook::mono(10.0f)); + g.setColour(status_.isNotEmpty() ? jlook::yellow : jlook::dim); + juce::String info = status_.isNotEmpty() ? status_ + : s.frames ? (s.file.isNotEmpty() ? juce::File(s.file).getFileName() : juce::String("RECORDED IN JIANT")) + : juce::String("SLOT ") + juce::String(selected_ + 1) + " EMPTY"; + g.drawText(info, 10, getHeight() - kFoot + 36, getWidth() - 20, 20, juce::Justification::centredLeft, true); + jlook::button(g, loadRect().toFloat(), "LOAD", false); + jlook::button(g, clearRect().toFloat(), "CLEAR", false, false, jlook::vio); +} + +void SamplePanel::mouseDown(const juce::MouseEvent& e) +{ + const auto p = e.getPosition(); + if (closeRect().contains(p)) { + if (onClose) onClose(); + return; + } + if (loadRect().contains(p)) { + chooseFile(); + return; + } + if (clearRect().contains(p)) { + proc_.clearSample(selected_); + status_ = {}; + repaint(); + return; + } + if (int k = rowAt(p); k >= 0) { + status_ = {}; + select(k); + } +} + +void SamplePanel::mouseDoubleClick(const juce::MouseEvent& e) +{ + if (int k = rowAt(e.getPosition()); k >= 0) { + select(k); + chooseFile(); + } +} + +void SamplePanel::chooseFile() +{ + const int k = selected_; + chooser_ = std::make_unique("A sample for slot " + juce::String(k + 1), juce::File(), + "*.wav;*.aif;*.aiff;*.flac;*.mp3;*.ogg"); + juce::Component::SafePointer self(this); + chooser_->launchAsync(juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, + [self, k](const juce::FileChooser& fc) { + if (self && fc.getResult().existsAsFile()) + self->load(k, juce::StringArray(fc.getResult().getFullPathName())); + }); +} + +juce::String SamplePanel::load(int k, const juce::StringArray& files) +{ + juce::String why; + int loaded = 0; + for (auto& f : files) { + if (k >= JiantProcessor::kSlots) + break; + why = proc_.loadSample(k, juce::File(f)); + if (why.isEmpty()) + ++loaded, ++k; + } + status_ = why.isNotEmpty() ? why : loaded > 1 ? juce::String(loaded) + " FILES LOADED" : juce::String(); + if (loaded) + select(juce::jmin(k - 1, JiantProcessor::kSlots - 1)); + repaint(); + return why; +} + +bool SamplePanel::isInterestedInFileDrag(const juce::StringArray& files) +{ + for (auto& f : files) + if (isAudioFile(f)) + return true; + return false; +} + +void SamplePanel::fileDragMove(const juce::StringArray&, int x, int y) +{ + int k = rowAt({x, y}); + if (k != dropRow_) { + dropRow_ = k; + repaint(); + } +} + +void SamplePanel::fileDragExit(const juce::StringArray&) +{ + dropRow_ = -1; + repaint(); +} + +void SamplePanel::filesDropped(const juce::StringArray& files, int x, int y) +{ + dropRow_ = -1; + int k = rowAt({x, y}); + load(k >= 0 ? k : selected_, files); +} diff --git a/ports/juce-plugin/Source/SamplePanel.h b/ports/juce-plugin/Source/SamplePanel.h new file mode 100644 index 00000000..637710a1 --- /dev/null +++ b/ports/juce-plugin/Source/SamplePanel.h @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) +// +// The sample browser: JIANT's 16 slots (what SAMPLE, GRAIN and DRUM-X's sample layer play), each its name, length and +// channels; pick a slot, LOAD a file into it (WAV, AIFF, FLAC, MP3, OGG), CLEAR it; a file dropped on a slot goes +// there (the editor takes drops anywhere else into the picked slot). What JIANT records (REC in SAMPLE / GRAIN) shows +// here as it lands. All of it the processor's (JiantProcessor::loadSample), saved with the session. +#pragma once +#include "JiantProcessor.h" +#include + +class SamplePanel : public juce::Component, public juce::FileDragAndDropTarget, private juce::Timer +{ +public: + explicit SamplePanel(JiantProcessor&); + void paint(juce::Graphics&) override; + void mouseDown(const juce::MouseEvent&) override; + void mouseDoubleClick(const juce::MouseEvent&) override; + bool isInterestedInFileDrag(const juce::StringArray& files) override; + void filesDropped(const juce::StringArray& files, int x, int y) override; + void fileDragMove(const juce::StringArray&, int x, int y) override; + void fileDragExit(const juce::StringArray&) override; + + int selected() const { return selected_; } + void select(int k); + // files into slots from k on (the editor's drop, the tests): the message of the last, "" all loaded + juce::String load(int k, const juce::StringArray& files); + void chooseFile(); // LOAD: a file chooser for the picked slot + std::function onClose; // (the editor hides it) + static bool isAudioFile(const juce::String& path); + +private: + void timerCallback() override; + int rowAt(juce::Point p) const; + juce::Rectangle rowRect(int k) const; + juce::Rectangle loadRect() const, clearRect() const, closeRect() const; + + JiantProcessor& proc_; + int selected_ = 0, dropRow_ = -1; + uint32_t seen_ = ~0u; + juce::String status_; + std::unique_ptr chooser_; + int recShown_ = -1; +}; diff --git a/ports/juce-plugin/fonts/DotGothic16-ascii.ttf b/ports/juce-plugin/fonts/DotGothic16-ascii.ttf new file mode 100644 index 00000000..dcd826be Binary files /dev/null and b/ports/juce-plugin/fonts/DotGothic16-ascii.ttf differ diff --git a/ports/juce-plugin/fonts/IBMPlexMono-SemiBold.ttf b/ports/juce-plugin/fonts/IBMPlexMono-SemiBold.ttf new file mode 100644 index 00000000..8f8998a1 Binary files /dev/null and b/ports/juce-plugin/fonts/IBMPlexMono-SemiBold.ttf differ diff --git a/ports/juce-plugin/fonts/OFL-DotGothic16.txt b/ports/juce-plugin/fonts/OFL-DotGothic16.txt new file mode 100644 index 00000000..e2837674 --- /dev/null +++ b/ports/juce-plugin/fonts/OFL-DotGothic16.txt @@ -0,0 +1,93 @@ +Copyright 2020 The DotGothic16 Project Authors (https://github.com/fontworks-fonts/DotGothic16/) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/ports/juce-plugin/fonts/OFL-IBMPlexMono.txt b/ports/juce-plugin/fonts/OFL-IBMPlexMono.txt new file mode 100644 index 00000000..c35c4c61 --- /dev/null +++ b/ports/juce-plugin/fonts/OFL-IBMPlexMono.txt @@ -0,0 +1,93 @@ +Copyright © 2017 IBM Corp. with Reserved Font Name "Plex" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/ports/juce-plugin/tests/plugin_check.cpp b/ports/juce-plugin/tests/plugin_check.cpp index e325a0a3..e7d40f92 100644 --- a/ports/juce-plugin/tests/plugin_check.cpp +++ b/ports/juce-plugin/tests/plugin_check.cpp @@ -3,7 +3,7 @@ // The built JIANT FM plugin loaded as a host loads it (JUCE's VST3 / AU hosting): its description, MIDI notes at // 44.1 and 48 kHz in several block sizes (sound, then silence after the note-offs, nothing non-finite), the state // out and back in, several instances at once (each its own JIANT, on its own thread; the 9th silent), the editor made and closed. -// plugin_check "" +// plugin_check "" [a state with samples, from sample_check] #include #include #include @@ -176,7 +176,7 @@ static void severalJiants(juce::AudioPluginFormatManager& fm, const juce::Plugin int main(int argc, char** argv) { juce::ScopedJuceInitialiser_GUI gui; - if (argc < 2) { std::printf("usage: plugin_check \n"); return 2; } + if (argc < 2) { std::printf("usage: plugin_check [state]\n"); return 2; } juce::AudioPluginFormatManager fm; juce::addDefaultFormatsToManager(fm); juce::OwnedArray found; @@ -213,6 +213,33 @@ int main(int argc, char** argv) severalJiants(fm, d, *p); + if (argc > 2 && d.pluginFormatName == "VST3") { // a state with samples (sample_check's) into the built plugin + juce::MemoryBlock st; + juce::File(juce::File::getCurrentWorkingDirectory().getChildFile(argv[2])).loadFileAsData(st); + auto q = fm.createPluginInstance(d, 44100.0, 256, err); + check(q && st.getSize() > 40000, "a session's state with its samples: " + juce::String(int(st.getSize())) + " bytes"); + if (q) { + q->setRateAndBufferSizeDetails(44100.0, 256); + q->prepareToPlay(44100.0, 256); + take(*q, -1, 0, 4096); + // (a VST3 host's state is the component's, in JUCE's hosting wrapped as XML) + juce::XmlElement wrap("VST3PluginState"); + wrap.createNewChildElement("IComponent")->addTextElement(st.toBase64Encoding()); + juce::MemoryBlock wrapped; + juce::AudioProcessor::copyXmlToBinary(wrap, wrapped); + q->setStateInformation(wrapped.getData(), int(wrapped.getSize())); + Out o = take(*q, -1, 60, 44100); + juce::MemoryBlock got, back; + q->getStateInformation(got); + if (auto x = juce::AudioProcessor::getXmlFromBinary(got.getData(), int(got.getSize()))) + if (auto* c = x->getChildByName("IComponent")) + back.fromBase64Encoding(c->getAllSubText()); + check(o.finite && o.peak > 0.02f && back.getSize() + 64 > st.getSize(), + "restored: slot 1 plays in SAMPLE (peak " + juce::String(o.peak, 3) + "), saved again with its audio (" + + juce::String(int(back.getSize())) + " bytes)"); + } + } + if (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr) { std::unique_ptr ed(p->createEditorIfNeeded()); check(ed != nullptr && ed->getWidth() >= 500, "the editor: " + juce::String(ed ? ed->getWidth() : 0) + " x " + diff --git a/ports/juce-plugin/tests/sample_check.cpp b/ports/juce-plugin/tests/sample_check.cpp new file mode 100644 index 00000000..1e19a93c --- /dev/null +++ b/ports/juce-plugin/tests/sample_check.cpp @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) +// Samples in the plugin (the plugin's own processor and editor, as a host makes them): a WAV written here (48 kHz +// stereo, half a second) dropped on the editor as a DAW drops a file (its filesDropped, the browser's slot 1); SAMPLE's +// first preset (the web editor's PRESET, a SysEx) silent with the slot empty, sounding with it loaded; REC MST 1 from +// inside JIANT (SAMPLE's REC) records a bar into the slot; the state out (the slot's audio in it, FLAC), a new instance +// (another JIANT) takes it: the slot back, the same length and name, sounding. The state is written to the file given, +// for plugin_check to load into the built plugin. +// sample_check [state.bin] +#include "../Source/JiantProcessor.h" +#include +#include + +juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter(); + +static int fails; +static void check(bool ok, const juce::String& what) +{ + std::printf(" %s %s\n", ok ? "ok " : "FAIL", what.toRawUTF8()); + fails += !ok; +} + +static float play(JiantProcessor& p, std::initializer_list> sysex, int note, int blocks) +{ + juce::AudioBuffer buf(2, 512); + float peak = 0; + for (int b = 0; b < blocks; ++b) { + juce::MidiBuffer midi; + if (b == 0) + for (auto& sx : sysex) midi.addEvent(sx.data(), int(sx.size()), 0); + if (b == 2 && note) midi.addEvent(juce::MidiMessage::noteOn(1, note, uint8_t(110)), 0); + if (b == blocks - 8 && note) midi.addEvent(juce::MidiMessage::noteOff(1, note), 0); + p.processBlock(buf, midi); + for (int c = 0; c < 2; ++c) + for (int i = 0; i < 512; ++i) peak = std::max(peak, std::abs(buf.getSample(c, i))); + } + return peak; +} +// one block, then the service: what was handed to the audio thread is in, the browser's view read +static void settle(JiantProcessor& p) +{ + juce::AudioBuffer buf(2, 512); + juce::MidiBuffer none; + p.processBlock(buf, none); + p.service(); +} +// SET scope 0 (the selected track), id, value +static std::vector set(int id, int v) +{ + int x = v + 8192; + return {0xF0, 0x7D, 0x46, 0x4C, 3, 0, uint8_t(id), uint8_t(x & 127), uint8_t(x >> 7), 0xF7}; +} + +int main(int argc, char** argv) +{ + juce::ScopedJuceInitialiser_GUI gui; + const std::vector sampleOne {0xF0, 0x7D, 0x46, 0x4C, 8, 4, 0, 0xF7}; // PRESET SAMPLE 0: ONE, slot 1 + std::unique_ptr base(createPluginFilter()); + auto& p = *dynamic_cast(base.get()); + p.setRateAndBufferSizeDetails(44100.0, 512); + p.prepareToPlay(44100.0, 512); + check(p.owner(), "an instance with its JIANT (" + juce::String(p.copy() + 1) + " of " + juce::String(JiantProcessor::copies()) + ")"); + float empty = play(p, {sampleOne}, 60, 40); + check(empty == 0.0f && p.slot(0).frames == 0, "SAMPLE with slot 1 empty: silent"); + + // a WAV, 48 kHz stereo: 0.5 s of 330 Hz (left) and 495 Hz (right), fading + auto dir = juce::File::getSpecialLocation(juce::File::tempDirectory).getChildFile("jiant_sample_check"); + dir.createDirectory(); + auto wav = dir.getChildFile("synth tone.wav"); + { + juce::AudioBuffer b(2, 24000); + for (int i = 0; i < 24000; ++i) { + float env = 0.6f * (1.0f - float(i) / 24000.0f); + b.setSample(0, i, env * std::sin(2.0f * juce::MathConstants::pi * 330.0f * float(i) / 48000.0f)); + b.setSample(1, i, env * std::sin(2.0f * juce::MathConstants::pi * 495.0f * float(i) / 48000.0f)); + } + wav.deleteFile(); + std::unique_ptr os = std::make_unique(wav); + auto w = juce::WavAudioFormat().createWriterFor(os, juce::AudioFormatWriterOptions {}.withSampleRate(48000.0) + .withNumChannels(2).withBitsPerSample(24)); + check(w && w->writeFromAudioSampleBuffer(b, 0, b.getNumSamples()), "a WAV written: " + wav.getFullPathName()); + } + + // dropped on the editor, as a DAW drops a file: into the browser's slot (slot 1) + { + std::unique_ptr ed(p.createEditorIfNeeded()); + auto* target = dynamic_cast(ed.get()); + check(target && target->isInterestedInFileDrag({wav.getFullPathName()}) && + !target->isInterestedInFileDrag({dir.getChildFile("notes.txt").getFullPathName()}), + "the editor takes audio files dropped on it, not others"); + if (target) + target->filesDropped({wav.getFullPathName()}, ed->getWidth() / 2, ed->getHeight() / 2); + p.editorBeingDeleted(ed.get()); + } + settle(p); + const auto s = p.slot(0); + check(s.frames > 22000 && s.frames < 22100 && s.channels == 2 && s.name == "SYNTH TONE" && s.file == wav.getFullPathName(), + "dropped into slot 1: " + s.name + ", " + juce::String(s.frames) + " frames at 44.1 kHz, " + + juce::String(int(s.channels)) + " channels"); + float loud = play(p, {sampleOne}, 60, 60); + check(loud > 0.02f, "SAMPLE plays it (peak " + juce::String(loud, 3) + ")"); + check(p.loadSample(3, dir.getChildFile("nothing.wav")).isNotEmpty(), "a missing file says why: " + + p.loadSample(3, dir.getChildFile("nothing.wav"))); + + // REC MST 1 (SAMPLE's REC, P_LN4 = id 87, value 6), the transport stopped: a bar of JIANT's own output into slot 2 + // (SLOT, E1 = id 115, 1), slot 1 playing + { + play(p, {sampleOne}, 0, 4); + juce::AudioBuffer buf(2, 512); + juce::MidiBuffer midi; + auto rec = set(87, 6); + midi.addEvent(rec.data(), int(rec.size()), 0); + auto slot2 = set(115, 1); + midi.addEvent(slot2.data(), int(slot2.size()), 0); + p.processBlock(buf, midi); + settle(p); + int at = 0, frames = 0; + int st = p.recState(&at, &frames); + auto back = set(115, 0); // (slot 1 sounds into the recording) + play(p, {back}, 0, 1); + float pk = 0; + for (int b = 0; b < 400 && (b < 4 || p.recState()); ++b) { + juce::MidiBuffer m; + if (b % 40 == 1) m.addEvent(juce::MidiMessage::noteOn(1, 60, uint8_t(110)), 0); + if (b % 40 == 30) m.addEvent(juce::MidiMessage::noteOff(1, 60), 0); + p.processBlock(buf, m); + pk = std::max(pk, buf.getMagnitude(0, 512)); + if (b % 20 == 0) p.service(); + } + p.service(); + const auto r = p.slot(1); + check(st == 2 && at == 1 && r.frames > 40000 && r.name.isNotEmpty() && r.file.isEmpty() && pk > 0.01f, + "REC MST 1 from inside JIANT (state " + juce::String(st) + ", slot " + juce::String(at + 1) + "): slot 2 recorded, " + juce::String(r.frames) + " frames (a bar), named " + r.name); + } + + juce::MemoryBlock state; + p.getStateInformation(state); + check(state.getSize() > 22050 * 2, "the state with two slots' audio: " + juce::String(int(state.getSize())) + " bytes"); + if (argc > 1) { + juce::File out = juce::File::getCurrentWorkingDirectory().getChildFile(argv[1]); + out.replaceWithData(state.getData(), state.getSize()); + } + juce::MemoryBlock again; + p.getStateInformation(again); + check(again == state, "saved twice, the same bytes (the FLAC kept)"); + + // a new instance, another JIANT: the state in, the slots back + { + std::unique_ptr other(createPluginFilter()); + auto& q = *dynamic_cast(other.get()); + q.setRateAndBufferSizeDetails(48000.0, 512); + q.prepareToPlay(48000.0, 512); + check(q.owner() && q.copy() != p.copy(), "a second instance, JIANT " + juce::String(q.copy() + 1)); + q.setStateInformation(state.getData(), int(state.getSize())); + settle(q); + const auto a = q.slot(0), b = q.slot(1); + check(a.frames == s.frames && a.channels == 2 && a.name == s.name && a.file == s.file && + b.frames == p.slot(1).frames && b.name == p.slot(1).name, + "its slots back from the state: " + a.name + " " + juce::String(a.frames) + ", " + b.name + " " + + juce::String(b.frames)); + float there = play(q, {}, 60, 60); + check(there > 0.02f, "and SAMPLE plays slot 1 there (peak " + juce::String(there, 3) + ", at 48 kHz)"); + juce::MemoryBlock theirs; + q.getStateInformation(theirs); + q.clearSample(0); + settle(q); + check(q.slot(0).frames == 0 && q.slot(1).frames > 0, "CLEAR empties slot 1, slot 2 kept"); + q.setStateInformation(state.getData(), int(state.getSize())); + settle(q); + check(q.slot(0).frames == s.frames, "and the state brings it back"); + } + dir.deleteRecursively(); + p.releaseResources(); + std::printf(fails ? "juce samples: %d FAILED\n" : "juce samples: all passed\n", fails); + return fails != 0; +}