diff --git a/README.md b/README.md index bd977a9..dcadd7d 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,21 @@ pedalboard of five pedals — Boost and Chorus before the amp, Flanger, Delay an A settings page behind the "Captures, MIDI, Settings" button, top right, carrying the capture loaders, a trim per channel, the MIDI-learn rows and the output section. +**A green lamp beside the Input dial** tells you whether the capture is hearing a level like the +one it was trained on. It lights while your playing peaks between −6 and 0 dBFS at the capture's +input, which is the top of NAM's training signal: turn Input up until your hardest playing lights it. +If it goes dark when you dig in, you are past full scale and the capture is hearing more than it +was ever shown. It reads after the Input dial and, with *Calibrate Input* on, after the +calibration, so it works the same for captures that state their recording level and captures that +do not. The Boost and Chorus pedals do not count towards it; in NAMp Rack, plug-ins you host before +the amp do. + +**The knobs.** Drag up or down to turn one, or use the mouse wheel. Hold **Shift** or **Ctrl** +(**Command** on a Mac) for ten times finer control. **Double-click** a knob or a channel trim to +return it to its default. Click the number under Threshold, Bass, Middle, Treble, Input or Output +to **type a value**: Enter or Tab sets it, Escape leaves it alone, and either `2.5` or `2,5` works. +The same applies to the amp in NAMp Rack. + **You load your own captures.** Nothing ships in the bundle. Point each loader at a folder of `.nam` files or at a single one; the folder's name becomes the channel's name, and you can type over it. diff --git a/VERSION b/VERSION index a918a2a..faef31a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.6.0 +0.7.0 diff --git a/core/channelrack.cpp b/core/channelrack.cpp index d1c5d36..d9f9433 100644 --- a/core/channelrack.cpp +++ b/core/channelrack.cpp @@ -355,6 +355,11 @@ double ChannelRack::activeIndexNorm() const return mEngine[mFading ? mTo : mFrom].activeIndexNorm(); } +double ChannelRack::soundingInputGain() const +{ + return mEngine[soundingChannel()].dominantInputGain(); +} + bool ChannelRack::playable() const { return mEngine[mFrom].playable(); diff --git a/core/channelrack.h b/core/channelrack.h index 618de6a..3b10c56 100644 --- a/core/channelrack.h +++ b/core/channelrack.h @@ -136,6 +136,11 @@ class ChannelRack : public NativeBlockProcessor } // Normalized index of the capture sounding in that channel. double activeIndexNorm() const; + // The input calibration gain of that capture, for the input-level lamp: 1.0 unless Calibrate + // is on and the capture states its input level, and 0 when the sounding channel has no model + // bound. Read from the channel soundingChannel() names, so the lamp and the channel LEDs + // always describe the same capture. Audio thread only: both ends of a fade belong to it. + double soundingInputGain() const; bool playable() const; // Fraction of all four banks that is built and primed. One number rather than four, because // what the editor shows is one progress line. diff --git a/core/crossfadeengine.cpp b/core/crossfadeengine.cpp index 34916ff..a488f02 100644 --- a/core/crossfadeengine.cpp +++ b/core/crossfadeengine.cpp @@ -230,9 +230,14 @@ bool CrossfadeEngine::hasInputLevel() const return mA.bound() && mBank && mBank->entries[mA.index].hasInputLevel; } -double CrossfadeEngine::inputLevelDbu() const +// B is the upper neighbour of A and carries weight mPos - A, so it dominates once mPos rounds to +// it. std::round takes the half away from zero, as activeIndexNorm() does, so the two always agree +// on which capture is sounding. +double CrossfadeEngine::dominantInputGain() const { - return hasInputLevel() ? mBank->entries[mA.index].inputLevelDbu : 0.0; + if (mB.bound() && std::round(mPos) >= static_cast(mB.index)) + return mB.inputGain; + return mA.bound() ? mA.inputGain : 0.0; } //------------------------------------------------------------------------ diff --git a/core/crossfadeengine.h b/core/crossfadeengine.h index fa1f203..aacd136 100644 --- a/core/crossfadeengine.h +++ b/core/crossfadeengine.h @@ -83,9 +83,13 @@ class CrossfadeEngine : public NativeBlockProcessor // NativeBlockProcessor. void processNative(NAM_SAMPLE **in, NAM_SAMPLE **out, int numFrames) override; - // RT, for the processor's input-calibration stage and its editor feedback. + // Whether the capture on branch A states the level it was made at. For the tools' reports. bool hasInputLevel() const; - double inputLevelDbu() const; + // RT. The input calibration gain of the branch carrying the larger weight: A, or B once the + // dial crossfade has reached the halfway point, the same choice activeIndexNorm() makes. What + // the input-level lamp multiplies the model input by. 0 when no model is bound, so an empty + // or still-building channel never lights it. + double dominantInputGain() const; int entryCount() const { return mBank ? mBank->count : 0; diff --git a/core/inputlevellamp.h b/core/inputlevellamp.h new file mode 100644 index 0000000..bf66951 --- /dev/null +++ b/core/inputlevellamp.h @@ -0,0 +1,109 @@ +// InputLevelLamp — whether the level the sounding capture hears is the level it was trained on. +// +// The green lamp beside the Input knob. It answers one question, and it is a question about the +// MODEL INPUT, not about the interface: the signal after the Input knob and after the sounding +// capture's own input calibration. That gain is exactly 1.0 when Calibrate is off or when the +// capture states no input_level_dbu, so a capture without metadata is judged by the same rule as +// one with it, and nothing is guessed on its behalf. With Calibrate on, it is still the model +// input that is judged: calibration is a gain on that input, so the lamp follows it rather than +// having a second rule for that mode. +// +// The rule is a window on the block's sample peak: +// +// * LIT when the peak is above -6.0 dBFS and at most 0.0 dBFS. The bottom edge is the one +// measured on ML Sound Lab's Amped, whose input LED is off for a -6.0 dBFS peak and on for a +// -5.9 dBFS one, and which reads peak rather than RMS (a burst with the same peak and 10 dB +// less RMS still lights it). It agrees within 2 dB with the NAM training signal itself, the +// same material in the trainer's v2 and v3 inputs: over 300 ms windows, 90% of its peaks are +// at or below -7.8 dBFS. The top edge is that signal's loudest sample, -0.3 dBFS, rounded to +// full scale: above it the capture is hearing a level it was never shown. +// * OFF below the window, once the hold has run out, so a played phrase reads as a steady light +// rather than flickering between notes. +// * OFF above the window at once, and held off for the same hold. The second half is not +// decoration: a hot pick attack decays back through the window within milliseconds, and +// without the hold the lamp would relight before any editor repaint could show it was ever +// dark. Too hot would then be indistinguishable from just right, which is the one thing the +// lamp exists to tell apart. Amped never does this; its LED stays lit to +12 dBFS. +// * OFF at once when no capture is hearing anything (gain 0), so an empty channel, or one still +// building, never shows a light left over from the capture before it. +// +// The hold is a choice, not a measurement. Amped holds full brightness for about 0.2 s and then +// fades over about 2 s; this lamp has two states, so one hold stands in for both. +// +// Real-time contract: process() allocates nothing, takes no lock and calls nothing; the state is +// plain members owned by the audio thread. reset() is called from setupProcessing(), when the +// audio thread is not running. + +#pragma once + +#include +#include + +namespace Rations +{ + +//------------------------------------------------------------------------ +class InputLevelLamp +{ +public: + // The window, as sample peaks in dBFS at the model input. Lit means kLitAboveDb < peak <= + // kLitAtMostDb. See the top of this file for where each number comes from. + static constexpr double kLitAboveDb = -6.0; + static constexpr double kLitAtMostDb = 0.0; + // How long a peak in the window keeps the lamp lit, and a peak above it keeps the lamp dark. + static constexpr double kHoldSeconds = 1.0; + + // Non-RT. The hold is counted in samples, so it has to know the rate it is counting at. + void reset(double sampleRate) + { + mHoldSamples = static_cast(std::llround(kHoldSeconds * sampleRate)); + mLitLeft = 0; + mHotLeft = 0; + } + + // RT. One block of the signal the sounding capture is fed, before its input calibration, and + // that calibration's gain. A gain of 0 means no capture is hearing it. + void process(const double *x, int numFrames, double gain) + { + if (!(gain > 0.0)) { + mLitLeft = 0; + mHotLeft = 0; + return; + } + // A NaN sample loses every comparison and so is ignored rather than propagated; an + // infinite one reads as hot, which is the right answer for it. + double peak = 0.0; + for (int i = 0; i < numFrames; ++i) + peak = std::max(peak, std::fabs(x[i])); + peak *= gain; + + // Count down by this block first, then let this block restart whichever hold it earned, + // so a peak at the end of a block holds for the full time from there. + const long long elapsed = numFrames > 0 ? numFrames : 0; + mLitLeft = std::max(0LL, mLitLeft - elapsed); + mHotLeft = std::max(0LL, mHotLeft - elapsed); + if (peak > mHotAbove) { + mHotLeft = mHoldSamples; + mLitLeft = 0; + } else if (peak > mLitAbove && mHotLeft == 0) { + mLitLeft = mHoldSamples; + } + } + + bool lit() const + { + return mLitLeft > 0 && mHotLeft == 0; + } + +private: + // The window's edges as linear peaks. std::pow is not constexpr, so they are worked out once, + // at construction, from the dB constants above rather than written out as bare numbers. + double mLitAbove = std::pow(10.0, kLitAboveDb / 20.0); + double mHotAbove = std::pow(10.0, kLitAtMostDb / 20.0); + + long long mHoldSamples = 0; + long long mLitLeft = 0; + long long mHotLeft = 0; +}; + +} // namespace Rations diff --git a/core/platform/plugview.h b/core/platform/plugview.h index 5392146..8b731db 100644 --- a/core/platform/plugview.h +++ b/core/platform/plugview.h @@ -1,9 +1,10 @@ // The platform seam: which IPlugView base the editor is built on. // // RationsEditorView is written against ONE protected hook set — onAttached, -// onRemoved, onDraw(cairo_t*), onMouseDown/Up/Move/Leave/Wheel, onTick, -// isResizable, constrainSize, onResized, invalidate, isWindowOpen — and knows -// nothing about the windowing system underneath it. Each platform base +// onRemoved, onDraw(cairo_t*), onMouseDown/Up/Move/Leave/Wheel (carrying a +// PointerMod mask from platform/pointermods.h and, on a press, a double-click +// flag), onTick, isResizable, constrainSize, onResized, invalidate, +// isWindowOpen — and knows nothing about the windowing system underneath it. Each platform base // implements that hook set over its own native window, and this header picks // one. Nothing else in the plug-in includes a platform header. // diff --git a/core/platform/pointermods.h b/core/platform/pointermods.h new file mode 100644 index 0000000..77222ea --- /dev/null +++ b/core/platform/pointermods.h @@ -0,0 +1,24 @@ +// Modifier keys held during a pointer event, as the editor sees them on every platform. +// +// Each window class translates its own platform's state into this mask — X's ShiftMask and +// ControlMask, Win32's MK_SHIFT and MK_CONTROL, AppKit's Shift and Command — so the editor's +// gestures are written once and cannot learn which platform they are on. Only the two keys a +// fine-adjust gesture needs are carried: the original plug-in's knobs treat either as "fine" +// (iPlug2's IKnobControlBase::IsFineControl, `mod.C || mod.S`). +// +// kPointerControl is the COMMAND key on macOS, not Control, and that is upstream's mapping rather +// than a choice made here: iPlug2's IGraphicsMac_view.mm builds its IMouseMod with `C` taken from +// NSCommandKeyMask. It is also the only mapping that works there, because a Control-click is a +// right-click on that platform (see macplugview.mm) and so cannot also be a fine left-drag. + +#pragma once + +namespace Steinberg +{ + +enum PointerMod : unsigned { + kPointerShift = 1u << 0, + kPointerControl = 1u << 1, +}; + +} // namespace Steinberg diff --git a/core/platform/win32plugview.cpp b/core/platform/win32plugview.cpp index 00be47b..aadd8e6 100644 --- a/core/platform/win32plugview.cpp +++ b/core/platform/win32plugview.cpp @@ -31,6 +31,24 @@ constexpr int kButtonLeft = 1; constexpr int kButtonMiddle = 2; constexpr int kButtonRight = 3; +// The X11 view's double-click rule and its two numbers, repeated rather than read from +// GetDoubleClickTime: that is the desktop's preference on this platform and has no counterpart on +// the other, and one gesture behaving two ways is the thing CS_DBLCLKS is left off to avoid. +constexpr DWORD kDoubleClickMs = 400; +constexpr int kDoubleClickSlop = 4; + +// MK_SHIFT / MK_CONTROL, the key state every mouse message carries (in the whole of wParam, or in +// its low word for WM_MOUSEWHEEL), as the editor's PointerMod mask. +unsigned pointerMods(WPARAM keys) +{ + unsigned mods = 0; + if (keys & MK_SHIFT) + mods |= kPointerShift; + if (keys & MK_CONTROL) + mods |= kPointerControl; + return mods; +} + // One trace summary line per ~1 s, and the threshold above which a repaint is // interesting enough to log on its own (i.e. the editor was quiet and then // something woke it up). @@ -76,8 +94,11 @@ HINSTANCE thisModule() // // CS_DBLCLKS is deliberately NOT set. With it, the second click of a pair // arrives as WM_LBUTTONDBLCLK instead of WM_LBUTTONDOWN, and the editor would -// simply lose that click. X11 delivers two ordinary presses; this keeps the two -// platforms behaving the same. CS_HREDRAW | CS_VREDRAW invalidate the whole +// simply lose that click. X11 delivers two ordinary presses, and both views +// derive the double-click themselves from those presses by one rule and two +// shared numbers (see pressButton), so the gesture is the same on both +// platforms rather than one rule here and another there. CS_HREDRAW | +// CS_VREDRAW invalidate the whole // window on a size change, so a resize can never leave a stale edge. // `proc` is passed in rather than named here because the window procedure is a // private member of Win32PlugView; openWindow() supplies it. @@ -393,13 +414,13 @@ LRESULT Win32PlugView::wndProc(UINT msg, WPARAM wParam, LPARAM lParam) return 0; case WM_LBUTTONDOWN: - pressButton(kButtonLeft, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + pressButton(kButtonLeft, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), wParam); return 0; case WM_MBUTTONDOWN: - pressButton(kButtonMiddle, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + pressButton(kButtonMiddle, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), wParam); return 0; case WM_RBUTTONDOWN: - pressButton(kButtonRight, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + pressButton(kButtonRight, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), wParam); return 0; case WM_LBUTTONUP: @@ -422,7 +443,7 @@ LRESULT Win32PlugView::wndProc(UINT msg, WPARAM wParam, LPARAM lParam) // Already coalesced by the system — a WM_MOUSEMOVE is only // generated when the queue has none pending, so the X11 side's // explicit motion compression has no counterpart here. - onMouseMove(mLastMouseX, mLastMouseY); + onMouseMove(mLastMouseX, mLastMouseY, pointerMods(wParam)); return 0; case WM_MOUSELEAVE: @@ -436,14 +457,17 @@ LRESULT Win32PlugView::wndProc(UINT msg, WPARAM wParam, LPARAM lParam) POINT pt{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)}; ScreenToClient(mWindow, &pt); + // The key state is the low word here, where every other mouse message carries it as + // the whole of wParam: the high word is the wheel delta. + const unsigned mods = pointerMods(GET_KEYSTATE_WPARAM(wParam)); mWheelRemainder += GET_WHEEL_DELTA_WPARAM(wParam); while (mWheelRemainder >= WHEEL_DELTA) { mWheelRemainder -= WHEEL_DELTA; - onMouseWheel(pt.x, pt.y, 1); + onMouseWheel(pt.x, pt.y, 1, mods); } while (mWheelRemainder <= -WHEEL_DELTA) { mWheelRemainder += WHEEL_DELTA; - onMouseWheel(pt.x, pt.y, -1); + onMouseWheel(pt.x, pt.y, -1, mods); } return 0; } @@ -518,14 +542,31 @@ LRESULT Win32PlugView::wndProc(UINT msg, WPARAM wParam, LPARAM lParam) // pointer crosses our window's edge the drag stops receiving WM_MOUSEMOVE and // the knob freezes. Capture is taken on the first button down and released only // when the last one comes up. -void Win32PlugView::pressButton(int button, int x, int y) +// +// The double-click is the X11 view's rule, derived from two ordinary presses: the same button +// within kDoubleClickMs and kDoubleClickSlop pixels of the first, and a pair consumed so a third +// press starts a new one. GetMessageTime is that message's own timestamp in milliseconds since the +// system started, and Microsoft's documentation for it says to take the difference of two such +// times ignoring overflow, as unsigned integers — which is what the DWORD subtraction does across +// the 49-day wrap. +void Win32PlugView::pressButton(int button, int x, int y, WPARAM keys) { mLastMouseX = x; mLastMouseY = y; if (mButtonsDown == 0) SetCapture(mWindow); mButtonsDown |= 1u << button; - onMouseDown(x, y, button); + + const DWORD now = static_cast(GetMessageTime()); + const bool doubleClick = button == mLastPressButton && + static_cast(now - mLastPressTime) <= kDoubleClickMs && + std::abs(x - mLastPressX) <= kDoubleClickSlop && + std::abs(y - mLastPressY) <= kDoubleClickSlop; + mLastPressButton = doubleClick ? 0 : button; + mLastPressTime = now; + mLastPressX = x; + mLastPressY = y; + onMouseDown(x, y, button, pointerMods(keys), doubleClick); } void Win32PlugView::releaseButton(int button, int x, int y) diff --git a/core/platform/win32plugview.h b/core/platform/win32plugview.h index e0a5930..b2e22db 100644 --- a/core/platform/win32plugview.h +++ b/core/platform/win32plugview.h @@ -61,6 +61,7 @@ #include "public.sdk/source/vst/vsteditcontroller.h" #include "pluginterfaces/gui/iplugview.h" #include "pluginterfaces/gui/iplugviewcontentscalesupport.h" +#include "platform/pointermods.h" #include @@ -127,25 +128,28 @@ class Win32PlugView : public Vst::EditorView, public IPlugViewContentScaleSuppor // 3 = right) on this platform too: the numbering is part of the hook // contract that both platform bases honour, so the editor above never has // to know which one it is running on. Wheel steps arrive as delta +1 (up) - // or -1 (down). - virtual void onMouseDown(int x, int y, int button) + // or -1 (down). `mods` is a PointerMod mask (platform/pointermods.h), and + // `doubleClick` is set on the second press of a pair — derived here rather + // than taken from WM_LBUTTONDBLCLK, for the reason given at + // windowClassName() in the .cpp. + virtual void onMouseDown(int x, int y, int button, unsigned mods, bool doubleClick) { - (void)x, (void)y, (void)button; + (void)x, (void)y, (void)button, (void)mods, (void)doubleClick; } virtual void onMouseUp(int x, int y, int button) { (void)x, (void)y, (void)button; } - virtual void onMouseMove(int x, int y) + virtual void onMouseMove(int x, int y, unsigned mods) { - (void)x, (void)y; + (void)x, (void)y, (void)mods; } virtual void onMouseLeave() { } - virtual void onMouseWheel(int x, int y, int delta) + virtual void onMouseWheel(int x, int y, int delta, unsigned mods) { - (void)x, (void)y, (void)delta; + (void)x, (void)y, (void)delta, (void)mods; } // Keyboard, taken from the PLATFORM window rather than handed in by the host. Return true @@ -235,7 +239,7 @@ class Win32PlugView : public Vst::EditorView, public IPlugViewContentScaleSuppor void redraw(); void blit(HDC dc); - void pressButton(int button, int x, int y); + void pressButton(int button, int x, int y, WPARAM keys); void releaseButton(int button, int x, int y); void releaseAllButtons(); // capture lost: end every drag that is open void armMouseLeave(); @@ -279,6 +283,12 @@ class Win32PlugView : public Vst::EditorView, public IPlugViewContentScaleSuppor unsigned mButtonsDown = 0; int mLastMouseX = 0; int mLastMouseY = 0; + // The last press, for double-click detection: the same rule and the same two numbers as the + // X11 view, timed on the message's own clock (GetMessageTime) rather than on a fresh read of + // the system's, so a busy message queue cannot turn one click into two. + int mLastPressButton = 0; + DWORD mLastPressTime = 0; + int mLastPressX = 0, mLastPressY = 0; bool mTrackingLeave = false; // WM_MOUSEWHEEL deltas are a multiple of WHEEL_DELTA on an ordinary mouse // but smaller on a high-resolution one, so they accumulate into notches. diff --git a/core/platform/x11plugview.cpp b/core/platform/x11plugview.cpp index 726561f..f928c1a 100644 --- a/core/platform/x11plugview.cpp +++ b/core/platform/x11plugview.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -43,6 +44,23 @@ constexpr int kMapFallbackTicks = 6; // ~200 ms at 33 ms constexpr unsigned long kSummaryTicks = 30; constexpr unsigned long kQuietRedrawTicks = 15; +// Two presses of one button count as a double-click when the second follows within this many +// milliseconds and this many pixels of the first. X itself defines no double-click, so these are +// this editor's own choice rather than a value read from the desktop's settings — and the Win32 +// view uses the same two numbers, so the gesture feels the same on both. +constexpr unsigned long kDoubleClickMs = 400; +constexpr int kDoubleClickSlop = 4; + +unsigned pointerMods(unsigned int state) +{ + unsigned mods = 0; + if (state & ShiftMask) + mods |= kPointerShift; + if (state & ControlMask) + mods |= kPointerControl; + return mods; +} + //------------------------------------------------------------------------ // One X keysym to one VirtualKeyCodes value (pluginterfaces/base/keycodes.h), or 0 for a key // that has no virtual code and is therefore carried by its character instead. Only the keys a @@ -798,15 +816,29 @@ void X11PlugView::drainEvents() mDirty = true; break; - case ButtonPress: - if (event.xbutton.button == kWheelUp || event.xbutton.button == kWheelDown) { - onMouseWheel(event.xbutton.x, event.xbutton.y, - event.xbutton.button == kWheelUp ? 1 : -1); - } else { - onMouseDown(event.xbutton.x, event.xbutton.y, - static_cast(event.xbutton.button)); + case ButtonPress: { + const XButtonEvent &b = event.xbutton; + if (b.button == kWheelUp || b.button == kWheelDown) { + onMouseWheel(b.x, b.y, b.button == kWheelUp ? 1 : -1, pointerMods(b.state)); + break; } + // The server clock is a 32-bit CARD32 carried in an unsigned long, so the + // difference is taken in 32 bits to stay right across its wrap. + const bool doubleClick = + b.button == mLastPressButton && + static_cast(b.time - mLastPressTime) <= kDoubleClickMs && + std::abs(b.x - mLastPressX) <= kDoubleClickSlop && + std::abs(b.y - mLastPressY) <= kDoubleClickSlop; + // A double-click consumes its pair, so a third press starts a new one instead of + // reading as a second double-click. + mLastPressButton = doubleClick ? 0 : b.button; + mLastPressTime = b.time; + mLastPressX = b.x; + mLastPressY = b.y; + onMouseDown(b.x, b.y, static_cast(b.button), pointerMods(b.state), + doubleClick); break; + } case ButtonRelease: if (event.xbutton.button != kWheelUp && event.xbutton.button != kWheelDown) @@ -825,7 +857,7 @@ void X11PlugView::drainEvents() break; XNextEvent(mDisplay, &latest); } - onMouseMove(latest.xmotion.x, latest.xmotion.y); + onMouseMove(latest.xmotion.x, latest.xmotion.y, pointerMods(latest.xmotion.state)); break; } diff --git a/core/platform/x11plugview.h b/core/platform/x11plugview.h index 8b8c2a7..45f68ac 100644 --- a/core/platform/x11plugview.h +++ b/core/platform/x11plugview.h @@ -42,6 +42,7 @@ #include "public.sdk/source/vst/vsteditcontroller.h" #include "pluginterfaces/gui/iplugview.h" +#include "platform/pointermods.h" #include @@ -98,25 +99,29 @@ class X11PlugView : public Vst::EditorView, public Linux::IEventHandler, public virtual void onDraw(cairo_t *cr) = 0; // Pointer input. Buttons are X button numbers (1 = left, 2 = middle, - // 3 = right). Wheel steps arrive as delta +1 (up) or -1 (down). - virtual void onMouseDown(int x, int y, int button) + // 3 = right). Wheel steps arrive as delta +1 (up) or -1 (down). `mods` is + // a PointerMod mask (platform/pointermods.h). `doubleClick` is set on the + // second press of the same button, close in time and place to the first: + // X has no double-click event of its own, so it is derived here once + // rather than by every editor. + virtual void onMouseDown(int x, int y, int button, unsigned mods, bool doubleClick) { - (void)x, (void)y, (void)button; + (void)x, (void)y, (void)button, (void)mods, (void)doubleClick; } virtual void onMouseUp(int x, int y, int button) { (void)x, (void)y, (void)button; } - virtual void onMouseMove(int x, int y) + virtual void onMouseMove(int x, int y, unsigned mods) { - (void)x, (void)y; + (void)x, (void)y, (void)mods; } virtual void onMouseLeave() { } - virtual void onMouseWheel(int x, int y, int delta) + virtual void onMouseWheel(int x, int y, int delta, unsigned mods) { - (void)x, (void)y, (void)delta; + (void)x, (void)y, (void)delta, (void)mods; } // Keyboard, taken from the PLATFORM window rather than handed in by the host. Return true @@ -240,6 +245,13 @@ class X11PlugView : public Vst::EditorView, public Linux::IEventHandler, public bool mMapped = false; int mTicksUnmapped = 0; + // The last left/middle/right press, for double-click detection. Time is the X server's + // millisecond clock from the event itself, never the local clock, so a slow round trip cannot + // turn one click into two. + unsigned int mLastPressButton = 0; + unsigned long mLastPressTime = 0; + int mLastPressX = 0, mLastPressY = 0; + // Keyboard focus, held only while a text field is open. mPrevFocus is whatever had the focus // when we took it, so it can be given back rather than left wherever we put it. bool mKeyFocus = false; diff --git a/core/tools/rations_lampcheck.cpp b/core/tools/rations_lampcheck.cpp new file mode 100644 index 0000000..b58fe06 --- /dev/null +++ b/core/tools/rations_lampcheck.cpp @@ -0,0 +1,827 @@ +// rations_lampcheck — the offline proof of the input-level lamp. +// +// The lamp beside the Input knob is lit when the peak the sounding capture hears sits in a window +// at the top of what NAM captures are trained on (inputlevellamp.h has the rule and where each +// number comes from). Two things have to be right for it to mean anything, and this tool asserts +// both rather than reading them off the code: +// +// 1. THE DETECTOR. The window's edges, the hold, the hot hold, the empty-channel reset and the +// sample-rate dependence of the hold, driven with exact synthetic peaks. No captures needed. +// 2. THE GAIN IT IS GIVEN. The lamp judges the model INPUT, so it is told the input calibration +// gain of the capture that is sounding. That gain is checked against the level each file +// states, read through the capture parser rather than through the engine: exactly 1.0 with +// Calibrate off and for a capture stating no level, exactly the calibration offset for one +// that does, the dominant capture's and never a blend of two while the dial crossfades +// between captures stating different levels, and 0 when nothing is bound. Then once more +// through the shipped ChannelRack, across a channel switch. +// 3. THE PLUG-IN. The built bundle, loaded the way a host loads it and played exact sine tones, +// with the lamp read back out of the output parameter queue, kInputLevelOkId, which is all +// the editor ever sees of it. This is where the tap point is proved: that the Input knob is +// in the peak, that Calibrate moves the edge by exactly what the capture states and a capture +// stating nothing moves it by nothing, that an instance with nothing loaded stays dark, and, +// in rations, that the PRE Boost is not counted. +// +// Usage: rations_lampcheck --bank --plain --bundle [--block N] +// --bank a folder holding two neighbouring captures (in the bank's own order) that state +// different input_level_dbu +// --plain one capture that states no input_level_dbu +// --bundle the built amp bundle + +// The SDK's headers come first, and that is not taste. pluginterfaces/base/fstrdefs.h defines +// stricmp and strnicmp unconditionally, while the WDL headers under the resampler define them only +// if nobody has; the other order is a macro-redefinition warning in every translation unit that +// has both. +#include "public.sdk/source/vst/hosting/hostclasses.h" +#include "public.sdk/source/vst/hosting/module.h" +#include "public.sdk/source/vst/hosting/parameterchanges.h" +#include "public.sdk/source/vst/hosting/plugprovider.h" +#include "pluginterfaces/vst/ivstaudioprocessor.h" +#include "pluginterfaces/vst/ivstcomponent.h" + +#include "rationsids.h" +#include "toolcaptures.h" + +#include "capturesource.h" +#include "channelrack.h" +#include "crossfadeengine.h" +#include "engineconfig.h" +#include "inputlevellamp.h" +#include "modelbank.h" + +// The rations product has a built-in PRE pedalboard and the rack does not; the Boost check in the +// plug-in section runs only where there is a Boost to check. +#if __has_include("pedals/boost.h") +#define RATIONS_LAMPCHECK_HAS_BOOST 1 +#else +#define RATIONS_LAMPCHECK_HAS_BOOST 0 +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +namespace fs = std::filesystem; +using Rations::InputLevelLamp; + +constexpr double kNativeRate = Rations::kNativeSampleRate; +constexpr int kOutputModeNormalized = 1; +// The interface level calibration works against, as the settings page's value box holds it. +constexpr double kCalLevelDbu = 12.0; + +int gFailures = 0; + +bool check(bool condition, const char *what, const char *detail = nullptr) +{ + if (condition) + printf(" ok %s\n", what); + else if (detail) + printf(" FAIL %s (%s)\n", what, detail); + else + printf(" FAIL %s\n", what); + if (!condition) + ++gFailures; + return condition; +} + +double dbToGain(double db) +{ + return std::pow(10.0, db / 20.0); +} + +bool closeTo(double a, double b) +{ + return std::fabs(a - b) <= 1e-12 * std::max(1.0, std::fabs(b)); +} + +struct Options { + std::string bank; + std::string plain; + std::string bundle; + int block = 128; +}; + +bool parseArgs(int argc, char **argv, Options &opt) +{ + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--bank" && i + 1 < argc) + opt.bank = argv[++i]; + else if (a == "--plain" && i + 1 < argc) + opt.plain = argv[++i]; + else if (a == "--bundle" && i + 1 < argc) + opt.bundle = argv[++i]; + else if (a == "--block" && i + 1 < argc) + opt.block = std::atoi(argv[++i]); + else + return false; + } + return !opt.bank.empty() && !opt.plain.empty() && !opt.bundle.empty() && opt.block > 0 && + opt.block <= 4096; +} + +// --- 1. the detector -------------------------------------------------------------------------- + +// One block of a constant magnitude: the exact peak, with no question of whether a sample landed +// on a crest. +void feed(InputLevelLamp &lamp, double peak, int n, double gain = 1.0) +{ + std::vector x(static_cast(n), peak); + lamp.process(x.data(), n, gain); +} + +// How many samples of silence after one in-window block the lamp stays lit for. +long long litFor(double rate, int block) +{ + InputLevelLamp lamp; + lamp.reset(rate); + feed(lamp, dbToGain(-3.0), block); + long long samples = 0; + while (lamp.lit() && samples < static_cast(rate * 10.0)) { + feed(lamp, 0.0, block); + samples += block; + } + return samples; +} + +void checkDetector(int block) +{ + printf("--- 1. the detector ---\n"); + const double below = dbToGain(InputLevelLamp::kLitAboveDb); + const double top = dbToGain(InputLevelLamp::kLitAtMostDb); + + auto litAfterOne = [&](double peak, double gain = 1.0) { + InputLevelLamp lamp; + lamp.reset(kNativeRate); + feed(lamp, peak, block, gain); + return lamp.lit(); + }; + check(!litAfterOne(dbToGain(-7.0)), "-7 dBFS is too quiet: off"); + check(!litAfterOne(below), "exactly -6.0 dBFS is still too quiet: off (Amped's edge)"); + check(litAfterOne(below * 1.0001), "just above -6.0 dBFS: lit"); + check(litAfterOne(dbToGain(-5.0)), "-5 dBFS: lit"); + check(litAfterOne(top), "exactly 0.0 dBFS: lit (the top edge is inclusive)"); + check(!litAfterOne(top * 1.0001), "just above 0.0 dBFS is too hot: off"); + check(!litAfterOne(dbToGain(1.0)), "+1 dBFS: off"); + + { + // A sine whose crest lands on a sample, so its peak is its amplitude. + std::vector x(static_cast(block)); + for (int i = 0; i < block; ++i) + x[static_cast(i)] = dbToGain(-5.0) * std::sin(2.0 * M_PI * i / 32.0); + InputLevelLamp lamp; + lamp.reset(kNativeRate); + lamp.process(x.data(), block, 1.0); + check(lamp.lit(), "a -5 dBFS sine lights it, not only a constant"); + } + + check(litAfterOne(dbToGain(-8.0), dbToGain(3.0)), + "the gain is part of the peak: -8 dBFS under +3 dB of calibration is lit"); + check(!litAfterOne(dbToGain(-8.0), dbToGain(1.0)), "... and under +1 dB is not"); + check(!litAfterOne(dbToGain(-3.0), 0.0), "gain 0 (no capture hearing it) is off"); + + { + const long long hold = std::llround(InputLevelLamp::kHoldSeconds * kNativeRate); + const long long held = litFor(kNativeRate, block); + char detail[96]; + snprintf(detail, sizeof detail, "lit for %lld samples of silence, hold is %lld", held, + hold); + check(held >= hold && held < hold + block, + "the hold keeps it lit through silence for the hold time, to the block", detail); + const long long held44 = litFor(44100.0, block), held96 = litFor(96000.0, block); + snprintf(detail, sizeof detail, "%lld at 44.1 kHz, %lld at 96 kHz", held44, held96); + check(held44 >= 44100 && held44 < 44100 + block && held96 >= 96000 && + held96 < 96000 + block, + "the hold is counted at the rate reset() was given", detail); + } + + { + InputLevelLamp lamp; + lamp.reset(kNativeRate); + feed(lamp, dbToGain(-3.0), block); + feed(lamp, dbToGain(2.0), block); + check(!lamp.lit(), "a hot block takes a lit lamp off at once"); + const long long hold = std::llround(InputLevelLamp::kHoldSeconds * kNativeRate); + long long dark = 0; + bool stayedDark = true; + while (dark < hold - block) { + feed(lamp, dbToGain(-3.0), block); + dark += block; + stayedDark = stayedDark && !lamp.lit(); + } + check(stayedDark, "... and in-window playing does not relight it inside the hot hold"); + int blocksToRelight = 0; + while (!lamp.lit() && blocksToRelight < 4) { + feed(lamp, dbToGain(-3.0), block); + ++blocksToRelight; + } + check(lamp.lit() && blocksToRelight <= 2, "... and relights once the hot hold is over"); + } + + { + InputLevelLamp lamp; + lamp.reset(kNativeRate); + feed(lamp, dbToGain(-3.0), block); + feed(lamp, dbToGain(-3.0), block, 0.0); + check(!lamp.lit(), "gain 0 takes a lit lamp off at once, without waiting for the hold"); + } + + { + std::vector x(static_cast(block), dbToGain(-3.0)); + x[5] = std::numeric_limits::quiet_NaN(); + InputLevelLamp lamp; + lamp.reset(kNativeRate); + lamp.process(x.data(), block, 1.0); + check(lamp.lit(), "a NaN sample is ignored, not propagated"); + x[5] = std::numeric_limits::infinity(); + lamp.process(x.data(), block, 1.0); + check(!lamp.lit(), "an infinite sample reads as hot"); + } +} + +// --- 2. the gain the lamp is given -------------------------------------------------------------- + +// The input level each capture states, in the bank's own order, read through the capture parser +// and not through the engine. NaN for a capture that states none. +std::vector statedLevels(const std::string &dir) +{ + std::vector files; + std::error_code ec; + for (fs::directory_iterator it(dir, ec), end; it != end && !ec; it.increment(ec)) + if (it->is_regular_file(ec) && it->path().extension() == ".nam") + files.push_back(it->path()); + std::sort(files.begin(), files.end(), [](const fs::path &a, const fs::path &b) { + return Rations::captureFilenameLess(a.filename().string(), b.filename().string()); + }); + std::vector levels; + for (const fs::path &f : files) { + Rations::CaptureSource source; + std::string error; + if (!Rations::loadCaptureSource(f, source, error)) { + fprintf(stderr, "rations_lampcheck: %s: %s\n", f.string().c_str(), error.c_str()); + levels.push_back(std::numeric_limits::quiet_NaN()); + continue; + } + // The largest variant, which is the one Slim 1.0 builds. + const auto &level = source.submodels.back().metadata.input_level; + levels.push_back(level ? *level : std::numeric_limits::quiet_NaN()); + } + return levels; +} + +// The stated level goes through a float on its way to the engine: the DSP core keeps a model's +// input level in a float member (nam::DSP::Level, in NAM/dsp.h), so 16.3 dBu reaches the gain as +// the nearest float to it, about 1e-7 dB away. The engine's gain is what actually scales the model +// input, so it is the right number for the lamp too; the expectation rounds the same way, which is +// what lets the comparison stay at 1e-12 instead of being loosened to hide the float. +double expectedGain(double level, bool calibrate) +{ + if (!calibrate || std::isnan(level)) + return 1.0; + return dbToGain(kCalLevelDbu - static_cast(static_cast(level))); +} + +bool waitForBank(Rations::ModelBank &loader) +{ + for (int i = 0; i < 1200 && loader.progress() < 1.0f; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + return loader.progress() >= 1.0f; +} + +struct Engine { + Rations::ModelBank loader; + Rations::CrossfadeEngine engine; + std::vector in, out; + + explicit Engine(int block) : in(static_cast(block)), out(static_cast(block)) + { + for (int i = 0; i < block; ++i) + in[static_cast(i)] = 0.1 * std::sin(2.0 * M_PI * 110.0 * i / kNativeRate); + engine.setLoader(&loader); + engine.prepare(block, kNativeRate); + loader.start(); + } + ~Engine() + { + loader.stop(); + Rations::ModelBank::destroyBank(engine.releaseBank()); + } + void run(double pos) + { + engine.pollBank(); + engine.setPositionNorm(pos); + NAM_SAMPLE *ip = in.data(), *op = out.data(); + engine.processNative(&ip, &op, static_cast(in.size())); + } + // Long enough for the slew to arrive and the detent to settle. + void settle(double pos) + { + for (int i = 0; i < static_cast(kNativeRate) / static_cast(in.size()); ++i) + run(pos); + } +}; + +void checkEngine(const Options &opt) +{ + printf("--- 2. the gain the lamp is given: one channel ---\n"); + const std::vector levels = statedLevels(opt.bank); + const int count = static_cast(levels.size()); + + // Two neighbours whose gains differ with Calibrate on: the crossing the dial test needs. + int pair = -1; + for (int i = 0; i + 1 < count && pair < 0; ++i) + if (!closeTo(expectedGain(levels[i], true), expectedGain(levels[i + 1], true))) + pair = i; + if (!check(count >= 2 && pair >= 0, + "the bank has neighbouring captures stating different input levels")) { + return; + } + printf(" captures %d and %d state %.3f and %.3f dBu, against %.1f dBu\n", pair, pair + 1, + levels[pair], levels[pair + 1], kCalLevelDbu); + + { + Engine e(opt.block); + e.run(0.0); + check(e.engine.dominantInputGain() == 0.0, "an engine with no capture assigned gives 0"); + + e.engine.setOutputMode(kOutputModeNormalized, kCalLevelDbu, true); + e.loader.loadDirectory(opt.bank, 1.0, Rations::engine::kChunk); + // Whatever blocks run before the first entry is built must give 0; how many there are is + // up to the worker, so it is reported rather than required. + int building = 0; + bool zeroWhileBuilding = true; + while (!e.engine.playable() && building < 100000) { + e.run(0.0); + if (!e.engine.playable()) { + ++building; + zeroWhileBuilding = zeroWhileBuilding && e.engine.dominantInputGain() == 0.0; + } + } + char detail[64]; + snprintf(detail, sizeof detail, "%d blocks ran before the first capture was built", + building); + check(zeroWhileBuilding, "a channel still building gives 0", detail); + printf(" measured: %s\n", detail); + if (!check(waitForBank(e.loader), "the bank builds")) + return; + + const double norm = 1.0 / static_cast(count - 1); + bool restOn = true, restOff = true; + for (int i = 0; i < count; ++i) { + e.engine.setOutputMode(kOutputModeNormalized, kCalLevelDbu, true); + e.settle(i * norm); + const double got = e.engine.dominantInputGain(); + const double want = expectedGain(levels[i], true); + if (!closeTo(got, want)) + printf( + " capture %d (index %.0f sounding): gain %.17g, its level asks %.17g\n", + i, e.engine.activeIndexNorm() * (count - 1), got, want); + restOn = restOn && closeTo(got, want); + e.engine.setOutputMode(kOutputModeNormalized, kCalLevelDbu, false); + e.run(i * norm); + restOff = restOff && e.engine.dominantInputGain() == 1.0; + } + check(restOff, "Calibrate off: every capture gives exactly 1.0"); + check(restOn, "Calibrate on: every capture gives the offset its own stated level asks for"); + + e.engine.setOutputMode(kOutputModeNormalized, kCalLevelDbu, true); + e.settle(pair * norm); + const double at12 = e.engine.dominantInputGain(); + e.engine.setOutputMode(kOutputModeNormalized, kCalLevelDbu + 3.0, true); + e.run(pair * norm); + const double at15 = e.engine.dominantInputGain(); + check(!std::isnan(levels[pair]) ? closeTo(at15 / at12, dbToGain(3.0)) : at15 == at12, + "moving the interface level by 3 dB moves the gain by exactly 3 dB"); + + // The dial swept slowly across the pair and back, so the crossfade spends many blocks with + // both captures bound. At every block the gain must be the one the sounding capture asks + // for: the same capture activeIndexNorm() names, and never a blend of the two. + e.engine.setOutputMode(kOutputModeNormalized, kCalLevelDbu, true); + e.settle(pair * norm); + const double gLow = expectedGain(levels[pair], true); + const double gHigh = expectedGain(levels[pair + 1], true); + const int steps = 2 * static_cast(kNativeRate) / opt.block; + bool agrees = true, sawLow = false, sawHigh = false, sawBoth = false; + for (int pass = 0; pass < 2; ++pass) { + for (int s = 0; s <= steps; ++s) { + const double t = static_cast(s) / steps; + const double pos = (pair + (pass == 0 ? t : 1.0 - t)) * norm; + e.run(pos); + const int sounding = + static_cast(std::lround(e.engine.activeIndexNorm() * (count - 1))); + const double g = e.engine.dominantInputGain(); + agrees = agrees && closeTo(g, expectedGain(levels[sounding], true)); + if (e.engine.boundBranches() == 2) { + sawBoth = true; + sawLow = sawLow || closeTo(g, gLow); + sawHigh = sawHigh || closeTo(g, gHigh); + } + } + } + check(sawBoth && sawLow && sawHigh, + "the sweep crossed the pair with both captures bound, and saw each one's gain"); + check(agrees, "every block gives the gain of the capture activeIndexNorm() names"); + } + + { + Engine e(opt.block); + e.engine.setOutputMode(kOutputModeNormalized, kCalLevelDbu, true); + e.loader.loadFile(opt.plain, 1.0, Rations::engine::kChunk); + if (check(waitForBank(e.loader), "the plain capture builds")) { + e.settle(0.0); + check(e.engine.dominantInputGain() == 1.0, + "Calibrate on, a capture stating no level: exactly 1.0, nothing guessed"); + } + } +} + +void checkRack(const Options &opt) +{ + printf("--- 3. the gain the lamp is given: the rack ---\n"); + const std::vector levels = statedLevels(opt.bank); + if (levels.empty()) + return; + const double g0 = expectedGain(levels[0], true); + + Rations::ChannelRack rack; + rack.prepare(opt.block, kNativeRate); + rack.setOutputMode(kOutputModeNormalized, kCalLevelDbu, true); + rack.start(); + + std::vector in(static_cast(opt.block)), out(in.size()); + for (int i = 0; i < opt.block; ++i) + in[static_cast(i)] = 0.1 * std::sin(2.0 * M_PI * 110.0 * i / kNativeRate); + auto run = [&](Rations::Channel want) { + rack.pollBanks(); + for (int c = 0; c < Rations::kChannelCount; ++c) + rack.setPositionNorm(static_cast(c), 0.0); + rack.requestChannel(want); + NAM_SAMPLE *ip = in.data(), *op = out.data(); + rack.processNative(&ip, &op, opt.block); + }; + // Run until the rack sounds `want`, checking the lamp's gain at every block from the first + // one in which it does. + auto switchTo = [&](Rations::Channel want, double expected) { + bool arrived = false, right = true; + for (int b = 0; b < 2000; ++b) { + run(want); + if (rack.soundingChannel() == want) { + arrived = true; + right = right && closeTo(rack.soundingInputGain(), expected); + } + } + return arrived && right; + }; + + run(Rations::kChannelClean); + check(rack.soundingInputGain() == 0.0, "a rack with nothing loaded gives 0"); + + rack.loadChannel(Rations::kChannelClean, opt.bank, true, 1.0, Rations::engine::kChunk); + rack.loadChannel(Rations::kChannelCrunch, opt.plain, false, 1.0, Rations::engine::kChunk); + for (int i = 0; i < 1200 && rack.progress() < 1.0f; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + if (check(rack.progress() >= 1.0f, "both channels build")) { + check(switchTo(Rations::kChannelClean, g0), + "sounding the bank: the gain of its first capture's stated level"); + check(switchTo(Rations::kChannelCrunch, 1.0), + "switched to the plain capture: 1.0 from the block the switch sounds it"); + check(switchTo(Rations::kChannelClean, g0), "and back: the bank's gain again"); + } + + rack.stop(); + rack.releaseBanks(); +} + +// --- 4. the plug-in +// ------------------------------------------------------------------------------- + +using namespace Steinberg; + +constexpr double kHostRate = 48000.0; + +double gainNorm(double db) +{ + return (db - Rations::ranges::kGainMin) / + (Rations::ranges::kGainMax - Rations::ranges::kGainMin); +} + +double calNorm(double dbu) +{ + return (dbu - Rations::ranges::kCalMin) / (Rations::ranges::kCalMax - Rations::ranges::kCalMin); +} + +// Everything a run pins, every block, so no test inherits a setting from the one before. +struct Controls { + double inputDb = 0.0; + bool calibrate = false; + double calDbu = kCalLevelDbu; + Rations::Channel channel = Rations::kChannelClean; + bool boostSilent = false; // rations only: the PRE Boost engaged with its Level at zero +}; + +// What one run saw, block by block. +struct Run { + std::vector lamp; // kInputLevelOkId; -1 for a block that did not write it + double progress = 0.0; // kBankProgressId at the last block + double channel = -1.0; // kActiveChannelId at the last block + double outPeak = 0.0; // the plug-in's own output, for the Boost check +}; + +struct Plugin { + Vst::IAudioProcessor *processor = nullptr; + int block = 128; + + // `seconds` of a sine at `peakDb` dBFS whose crest lands on a sample, so the block peak IS the + // amplitude; or silence when peakDb is NaN. + Run play(double seconds, double peakDb, const Controls &c) + { + const int n = block; + const double amp = std::isnan(peakDb) ? 0.0 : dbToGain(peakDb); + std::vector in(static_cast(n)), outL(in.size()), outR(in.size()); + float *inPtrs[1] = {in.data()}; + float *outPtrs[2] = {outL.data(), outR.data()}; + Vst::AudioBusBuffers inBus = {}; + inBus.numChannels = 1; + inBus.channelBuffers32 = inPtrs; + Vst::AudioBusBuffers outBus = {}; + outBus.numChannels = 2; + outBus.channelBuffers32 = outPtrs; + Vst::ParameterChanges changes; + changes.setMaxParameters(16); + Vst::ParameterChanges outChanges; + outChanges.setMaxParameters(64); + Vst::ProcessData data = {}; + data.processMode = Vst::kOffline; + data.symbolicSampleSize = Vst::kSample32; + data.numInputs = 1; + data.numOutputs = 1; + data.inputs = &inBus; + data.outputs = &outBus; + data.numSamples = n; + data.inputParameterChanges = &changes; + data.outputParameterChanges = &outChanges; + + Run r; + const int blocks = static_cast(seconds * kHostRate) / n; + for (int b = 0; b < blocks; ++b) { + for (int i = 0; i < n; ++i) + in[static_cast(i)] = + static_cast(amp * std::sin(2.0 * M_PI * (b * n + i) / 32.0)); + changes.clearQueue(); + auto set = [&](Vst::ParamID id, double v) { + int32 qi = 0, pi = 0; + if (auto *q = changes.addParameterData(id, qi)) + q->addPoint(0, v, pi); + }; + set(Rations::kBypassId, 0.0); + set(Rations::kNoiseGateOnId, 0.0); + set(Rations::kInputGainId, gainNorm(c.inputDb)); + set(Rations::kCalibrateInputId, c.calibrate ? 1.0 : 0.0); + set(Rations::kInputCalLevelId, calNorm(c.calDbu)); + set(Rations::kChannelId, Rations::normFromChannel(c.channel)); + set(Rations::kCleanGainId, 0.0); // the bank's first capture +#if RATIONS_LAMPCHECK_HAS_BOOST + set(Rations::kBoostOnId, c.boostSilent ? 1.0 : 0.0); + set(Rations::kBoostLevelId, c.boostSilent ? 0.0 : 0.5); +#endif + outChanges.clearQueue(); + processor->process(data); + + double lamp = -1.0; + for (int32 q = 0; q < outChanges.getParameterCount(); ++q) { + Vst::IParamValueQueue *queue = outChanges.getParameterData(q); + int32 offset = 0; + Vst::ParamValue v = 0.0; + if (!queue || queue->getPointCount() <= 0 || + queue->getPoint(queue->getPointCount() - 1, offset, v) != kResultTrue) + continue; + if (queue->getParameterId() == Rations::kInputLevelOkId) + lamp = v; + else if (queue->getParameterId() == Rations::kBankProgressId) + r.progress = v; + else if (queue->getParameterId() == Rations::kActiveChannelId) + r.channel = v; + } + r.lamp.push_back(lamp); + for (int i = 0; i < n; ++i) + r.outPeak = std::max(r.outPeak, std::fabs(static_cast(outL[i]))); + } + return r; + } + + Run silence(double seconds, const Controls &c) + { + return play(seconds, std::numeric_limits::quiet_NaN(), c); + } + + // Enough silence for any hold, lit or hot, to have run out. + void clear(const Controls &c) + { + silence(InputLevelLamp::kHoldSeconds + 0.2, c); + } + + // Until the plug-in says it is sounding `c.channel`. + bool reach(const Controls &c) + { + for (int i = 0; i < 200; ++i) + if (silence(0.05, c).channel == Rations::normFromChannel(c.channel)) + return true; + return false; + } +}; + +bool allEqual(const Run &r, double v) +{ + return !r.lamp.empty() && + std::all_of(r.lamp.begin(), r.lamp.end(), [v](double x) { return x == v; }); +} + +// What the rule says for a peak at the model input, for the cases below that are worked out from +// a capture's stated level rather than written in. +bool windowSays(double peakDb) +{ + return peakDb > InputLevelLamp::kLitAboveDb && peakDb <= InputLevelLamp::kLitAtMostDb; +} + +// How long, in seconds, a run held its first value before changing to `to`. +double secondsUntil(const Run &r, double to, int block) +{ + const auto at = std::find(r.lamp.begin(), r.lamp.end(), to) - r.lamp.begin(); + return static_cast(at) * block / kHostRate; +} + +void checkPlugin(const Options &opt) +{ + printf("--- 4. the plug-in ---\n"); + Vst::HostApplication host; + Vst::PluginContextFactory::instance().setPluginContext(&host); + std::string error; + auto module = VST3::Hosting::Module::create(opt.bundle, error); + if (!check(module != nullptr, "the bundle loads", error.c_str())) + return; + auto factory = module->getFactory(); + IPtr provider; + for (auto &classInfo : factory.classInfos()) { + if (classInfo.category() != kVstAudioEffectClass) + continue; + provider = owned(new Vst::PlugProvider(factory, classInfo, true)); + if (provider->initialize()) + break; + provider = nullptr; + } + if (!check(provider != nullptr, "the bundle offers an audio effect")) + return; + Vst::IComponent *component = provider->getComponent(); + FUnknownPtr processor(component); + if (!check(component && processor, "the plug-in provides a processor")) + return; + + Vst::ProcessSetup setup = {}; + setup.processMode = Vst::kOffline; + setup.symbolicSampleSize = Vst::kSample32; + setup.maxSamplesPerBlock = opt.block; + setup.sampleRate = kHostRate; + if (!check(processor->setupProcessing(setup) == kResultOk, "the process setup is accepted")) + return; + component->setActive(true); + processor->setProcessing(true); + + Plugin plug; + plug.processor = processor; + plug.block = opt.block; + const Controls c; + const double tick = 2.0 * opt.block / kHostRate; // how closely a hold can be timed here + char detail[128]; + + check(allEqual(plug.play(0.5, -3.0, c), 0.0), + "nothing loaded: a -3 dBFS input leaves the lamp dark, because no capture hears it"); + + const std::vector levels = statedLevels(opt.bank); + const bool bankStates = !levels.empty() && !std::isnan(levels[0]); + double progress = 0.0; + if (check(bankStates, "the bank's first capture states an input level")) { + RationsTools::sendCaptureLoad(host, component, Rations::kChannelClean, opt.bank, true); + RationsTools::sendCaptureLoad(host, component, Rations::kChannelCrunch, opt.plain, false); + for (int i = 0; i < 1200 && progress < 1.0; ++i) { + progress = plug.silence(0.05, c).progress; + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + } + if (bankStates && check(progress >= 1.0, "both channels build inside the plug-in")) { + // The window, through the whole processor. + plug.clear(c); + check(allEqual(plug.play(0.5, -7.0, c), 0.0), "-7 dBFS: dark for the whole run"); + check(allEqual(plug.play(0.3, -5.0, c), 1.0), "-5 dBFS: lit from the first block"); + check(allEqual(plug.play(0.3, 1.0, c), 0.0), "+1 dBFS: dark from the first block"); + + Run r = plug.play(1.5, -5.0, c); + double held = secondsUntil(r, 1.0, opt.block); + snprintf(detail, sizeof detail, "dark for %.3f s of -5 dBFS after the hot peak", held); + check(std::fabs(held - InputLevelLamp::kHoldSeconds) <= tick && r.lamp.back() == 1.0, + "back in the window after a hot peak: dark for the hold, then lit", detail); + printf(" measured: %s\n", detail); + r = plug.silence(1.5, c); + held = secondsUntil(r, 0.0, opt.block); + snprintf(detail, sizeof detail, "lit for %.3f s of silence", held); + check(std::fabs(held - InputLevelLamp::kHoldSeconds) <= tick && r.lamp.back() == 0.0, + "silence after playing: lit for the hold, then dark", detail); + printf(" measured: %s\n", detail); + + // The Input knob is in the peak. + plug.clear(c); + check(allEqual(plug.play(0.3, -11.0, c), 0.0), + "-11 dBFS with the Input knob at 0 dB: dark"); + Controls up = c; + up.inputDb = 6.0; + check(allEqual(plug.play(0.3, -11.0, up), 1.0), + "... and with the Input knob at +6 dB: lit, so the knob is in the peak it reads"); + + // Calibrate moves the edge by exactly what the capture states. + const double shift = kCalLevelDbu - static_cast(static_cast(levels[0])); + printf(" the first capture states %.3f dBu, so Calibrate scales the model input " + "by %+.3f dB\n", + levels[0], shift); + Controls cal = c; + cal.calibrate = true; + plug.clear(cal); + check(allEqual(plug.play(0.3, -3.0 - shift, cal), 1.0), + "Calibrate on: an input that the shift brings to -3 dBFS is lit"); + plug.clear(cal); + check(allEqual(plug.play(0.3, -3.0, cal), windowSays(-3.0 + shift) ? 1.0 : 0.0), + "Calibrate on: a -3 dBFS input is judged at -3 dBFS plus the shift"); + Controls calMoved = cal; + calMoved.calDbu = kCalLevelDbu + 4.0; + plug.clear(calMoved); + check(allEqual(plug.play(0.3, -3.0 - shift - 4.0, calMoved), 1.0), + "moving the interface level 4 dB moves the edge 4 dB with it"); + + // A capture stating no level is not shifted. + Controls plain = cal; + plain.channel = Rations::kChannelCrunch; + if (check(plug.reach(plain), "the switch to the plain capture arrives")) { + plug.clear(plain); + check(allEqual(plug.play(0.3, -3.0, plain), 1.0), + "Calibrate on, a capture stating no level: -3 dBFS is lit, unshifted"); + plug.clear(plain); + const double moved = -3.0 - shift; // lit under the bank's shift + check(allEqual(plug.play(0.3, moved, plain), windowSays(moved) ? 1.0 : 0.0), + "... and the bank's shift is not applied to it"); + } + +#if RATIONS_LAMPCHECK_HAS_BOOST + // The PRE Boost is not counted. With its Level at zero the model hears silence, and the + // lamp, which reads ahead of the pedals, still says what the guitar is doing. + if (check(plug.reach(c), "back on the bank")) { + Controls boost = c; + boost.boostSilent = true; + plug.clear(c); + const Run open = plug.play(0.5, -3.0, c); + plug.clear(boost); + const Run boosted = plug.play(0.5, -3.0, boost); + snprintf(detail, sizeof detail, "output peak %.5f with the Boost at zero, %.5f without", + boosted.outPeak, open.outPeak); + check(boosted.outPeak < 0.01 * open.outPeak, "the Boost at Level 0 silences the amp", + detail); + check(allEqual(boosted, 1.0), + "... and the lamp stays lit at -3 dBFS: it reads ahead of the PRE pedals"); + } +#endif + } + + processor->setProcessing(false); + component->setActive(false); +} + +} // namespace + +int main(int argc, char **argv) +{ + Options opt; + if (!parseArgs(argc, argv, opt)) { + fprintf(stderr, + "usage: rations_lampcheck --bank --plain --bundle \n" + " [--block N]\n" + " --bank a folder with two neighbouring captures stating different\n" + " input_level_dbu\n" + " --plain a capture stating no input_level_dbu\n" + " --bundle the built amp bundle\n"); + return 2; + } + + checkDetector(opt.block); + checkEngine(opt); + checkRack(opt); + checkPlugin(opt); + + printf("\n%s\n", gFailures == 0 ? "rations_lampcheck: PASSED" : "rations_lampcheck: FAILED"); + return gFailures == 0 ? 0 : 1; +} diff --git a/core/typednumber.h b/core/typednumber.h new file mode 100644 index 0000000..eb0fa44 --- /dev/null +++ b/core/typednumber.h @@ -0,0 +1,60 @@ +// typednumber.h — read a number a user typed into one of the editor's value fields. +// +// NOT strtod, and not sscanf("%lf"): both follow LC_NUMERIC, and that is the HOST's locale rather +// than ours — a host that calls setlocale(LC_ALL, "") under a locale which writes 2,5 makes +// strtod("-3.5") stop at the point and return -3. The same defect was found and fixed in this +// editor's grandparent for the same field. And not std::from_chars, which ignores the locale and +// would otherwise be the answer: its floating-point overloads need libc++ 20, the macOS build's +// toolchain is older than that, and whether a given AppleClang carries them cannot be checked from +// the machine this is developed on. What a value field accepts is so narrow that a parser for it is +// shorter than the argument about which library function to trust. +// +// The grammar is the whole of what the fields admit (acceptsTextChar): an optional sign, digits, +// and at most one decimal mark, which may be '.' or ',' so that either habit works. Like strtod it +// reads the longest prefix that is a number and ignores the rest, so "1-2" is 1; unlike strtod it +// requires a digit, so "-", "." or an emptied field is not a number and leaves the value alone. +// +// There is no exponent and no "inf"/"nan", so the result is always finite — which matters, because +// the editor is built with -ffast-math and an isfinite() test there would fold to true. The value +// is formed as one integer divided by one power of ten, both exact for the eight characters a field +// holds, so the single division is the only rounding and "7.5" is exactly 7.5. + +#pragma once + +#include + +namespace Rations +{ + +inline bool parseTypedNumber(const std::string &text, double &out) +{ + size_t i = 0; + const size_t n = text.size(); + bool negative = false; + if (i < n && (text[i] == '+' || text[i] == '-')) + negative = (text[i++] == '-'); + + double mantissa = 0.0; + double scale = 1.0; + int digits = 0; + bool seenMark = false; + for (; i < n; ++i) { + const char ch = text[i]; + if (ch >= '0' && ch <= '9') { + mantissa = mantissa * 10.0 + static_cast(ch - '0'); + if (seenMark) + scale *= 10.0; + ++digits; + } else if ((ch == '.' || ch == ',') && !seenMark) { + seenMark = true; + } else { + break; + } + } + if (digits == 0) + return false; + out = (negative ? -mantissa : mantissa) / scale; + return true; +} + +} // namespace Rations diff --git a/products/rack/CMakeLists.txt b/products/rack/CMakeLists.txt index 8985850..9d29c7b 100644 --- a/products/rack/CMakeLists.txt +++ b/products/rack/CMakeLists.txt @@ -603,6 +603,8 @@ set(NAMP_IMG_FILES img/namp-badge.png img/dial.png img/led_on.png + # The input-level lamp, lit. Generated from led-on-base.png by gui/make_assets.sh. + img/led_green_on.png img/led_off.png img/switch_up_ring.png img/switch_down_ring.png @@ -1051,8 +1053,9 @@ if(NAMPRACK_BUILD_TOOLS) target_compile_features(rations_fadecheck PRIVATE cxx_std_20) target_compile_options(rations_fadecheck PRIVATE -Wall) - # The channel-switch proof and the race gate: the same engine sources, driven differently. - foreach(_tool rations_switchcheck rations_racecheck) + # The channel-switch proof, the race gate and the input-level lamp's proof: the same engine + # sources, driven differently. + foreach(_tool rations_switchcheck rations_racecheck rations_lampcheck) namp_source(_tool_src tools/${_tool}.cpp) add_executable(${_tool} ${_tool_src} @@ -1071,6 +1074,16 @@ if(NAMPRACK_BUILD_TOOLS) target_compile_features(${_tool} PRIVATE cxx_std_20) target_compile_options(${_tool} PRIVATE -Wall) endforeach() + # The lamp's proof ends by driving the BUILT BUNDLE, because the tap point and the output + # parameter are facts about the plug-in a host loads, so it carries the module loader too. + target_sources(rations_lampcheck PRIVATE + ${NAMPRACK_MODULE_LOADER} + ${VST3_SDK_DIR}/public.sdk/source/vst/hosting/plugprovider.cpp + ${VST3_SDK_DIR}/public.sdk/samples/vst-hosting/editorhost/source/usediids.cpp) + target_link_libraries(rations_lampcheck PRIVATE sdk_hosting) + if(NAMPRACK_BUILD_VST3_BUNDLE) + add_dependencies(rations_lampcheck NampRackAmp) + endif() # The allocation gate. Deliberately links NO graphics at all — it is measuring allocations on diff --git a/products/rack/gui/make_assets.sh b/products/rack/gui/make_assets.sh index 09d65db..8e6edf8 100755 --- a/products/rack/gui/make_assets.sh +++ b/products/rack/gui/make_assets.sh @@ -106,6 +106,33 @@ need "$ART_DIR/led-off-base.png" magick "$ART_DIR/led-on-base.png" -strip -depth 8 "PNG32:$OUT_DIR/led_on.png" magick "$ART_DIR/led-off-base.png" -strip -depth 8 "PNG32:$OUT_DIR/led_off.png" +# ---- led_green_on.png: the input-level lamp, lit --------------------------- +# The red LED recoloured to ACCENT rather than drawn again, so the two lamps +# share one shape, rim and size. The red LED's green and blue are a fixed tenth +# of its red everywhere, so the RED channel alone carries all of its shading: +# it is levelled so the brightest opaque red becomes 1 (that maximum is measured +# here, not written in, because a hard-coded 234 would quietly mis-tint a +# re-exported source), turned back into colour (a separated channel is a +# greyscale image, and colourising one leaves it grey), multiplied by ACCENT, +# and given the source's own alpha back. The centre therefore lands on ACCENT +# exactly, and the check below says so. The white point is passed as a PERCENTAGE because -level reads a bare +# number in QuantumRange units, which is 65535 on a Q16 build. The lamp's off +# state is led_off.png, shared with the channel LEDs. +RED_MAX_PCT="$(magick "$ART_DIR/led-on-base.png" \ + \( +clone -alpha extract -threshold 50% \) -alpha off \ + -compose multiply -composite -channel R -separate -format "%[fx:maxima*100]" info:)" +magick "$ART_DIR/led-on-base.png" \ + \( +clone -alpha off -channel R -separate +channel -level "0,${RED_MAX_PCT}%" \ + -colorspace sRGB \ + \( +clone -fill "$ACCENT" -colorize 100 \) -compose multiply -composite \) \ + +swap -compose copyalpha -composite \ + -strip -depth 8 "PNG32:$OUT_DIR/led_green_on.png" +green_centre="$(magick "$OUT_DIR/led_green_on.png" -format "%[hex:p{64,64}]" info:)" +if [ "#${green_centre:0:6}" != "$ACCENT" ]; then + echo "make_assets: led_green_on.png's centre is #${green_centre}, not ACCENT $ACCENT." >&2 + exit 1 +fi + # ---- generated art -------------------------------------------------------- ./make_knob.sh ./make_switch.sh diff --git a/products/rack/resources/img/led_green_on.png b/products/rack/resources/img/led_green_on.png new file mode 100644 index 0000000..39ceac9 Binary files /dev/null and b/products/rack/resources/img/led_green_on.png differ diff --git a/products/rack/src/geometry.h b/products/rack/src/geometry.h index 90eb42f..b3b6e5c 100644 --- a/products/rack/src/geometry.h +++ b/products/rack/src/geometry.h @@ -517,6 +517,10 @@ constexpr int kLedR = 9; constexpr int kToggleToLedGap = 6; constexpr int kLedCY = kToggleCY + kToggleH / 2 + kToggleToLedGap + kLedR; // 292 constexpr int kLedCount = 4; +// Which lamp an LED is when lit. Red is every LED the panel had before the input-level lamp, which +// is the one green: led_green_on.png, the red art recoloured to kAccent by gui/make_assets.sh. Both +// share led_off.png, so an unlit lamp does not say which colour it would be. +enum class LedColor { Red, Green }; // The gaps are named rather than folded into literal centres so the arithmetic // is checkable and so a part that grows fails the static_asserts below instead @@ -934,6 +938,30 @@ constexpr KnobSpec kIoKnobs[2] = { {kOutputGainId, kSideCXR, kIoKnobCY, kIoKnobR, "Output", "dB"}, }; +// The input-level lamp: green when the peak the sounding capture hears is in the +// window inputlevellamp.h describes. To the right of the Input dial, at the +// dial's own height, which is the author's choice between two rendered +// candidates (the other was beside the Input legend, where Amped puts its LED): +// the lamp sits next to the control that fixes it. The utility row's size, not +// the channel lamps': it is an indicator, set while a rig is put together, like +// BYPASS. Nothing else is in this band between the dial and the first channel. +constexpr int kInputLampR = kTopLedR; +constexpr int kInputLampGap = 8; // from the dial's edge to the lamp's +constexpr int kInputLampCX = kSideCXL + kIoKnobR + kInputLampGap + kInputLampR; // 134 +constexpr int kInputLampCY = kIoKnobCY; // 275 +static_assert(kInputLampCX - kInputLampR > kSideCXL + kIoKnobR, + "the input-level lamp is drawn on the Input dial"); +static_assert(kInputLampCY - kInputLampR > kIoLabelBaselineY + kIoLabelSize / 4, + "the input-level lamp has come up onto the Input legend"); +static_assert(kInputLampCY + kInputLampR < kIoValueBaselineY - kKnobValueSize, + "the input-level lamp has come down onto the Input value row"); +static_assert(kInputLampCX + kInputLampR + 8 < kToggles[0].cx - kToggleHitW / 2, + "the input-level lamp has reached the first channel switch's click area"); +static_assert(kInputLampCX + kInputLampR + 8 < kKnobs[0].cx - kKnobR, + "the input-level lamp has reached the first channel dial"); +static_assert(kInputLampCY + kInputLampR < kFaceB - 8, + "the input-level lamp has reached the faceplate's edge"); + // --- Page buttons, bottom-centre-right of the faceplate --------------------- // ButtonSpec and kPageButtonH are declared further up, with the settings button: // that one is drawn in the same style but has to be declared before the Slim @@ -995,6 +1023,63 @@ constexpr ButtonSpec kPageButtons[kPageButtonCount] = { static_assert(kLedCY == kPageButtonY + kPageButtonH / 2, "the channel lamps no longer line up with the page buttons"); +// --- Typed values: the six readouts are also where a value is entered -------- +// Clicking a dial's value row opens a text field over it, seeded with the +// value and selected, which is the parent plug-in's IVKnobControl built with +// valueIsEditable and is the second way to reach those six controls, never the +// only one (whether keys reach an embedded view at all is the host's business). +// The four channel dials have no value row — their band is the bat switches' — +// and what they would offer to type is a capture name, so they are not here. +// +// The box is the CLICK target and the field drawn while editing, one rect for +// both so the two cannot drift. It hangs off the readout's own baseline, 13 +// above and 6 below, so the text does not move as the field opens; 64 wide is +// room for "-100.0" at kKnobValueSize with the caret, and stops 30 units short +// of the next column at the 94-unit pitch. +struct ValueField { + Steinberg::Vst::ParamID id; + int x, y, w, h; +}; +constexpr int kValueFieldW = 64; +constexpr int kValueFieldAscent = 13; +constexpr int kValueFieldDescent = 6; +constexpr ValueField valueField(const KnobSpec &k, int baselineY) +{ + return {k.id, k.cx - kValueFieldW / 2, baselineY - kValueFieldAscent, kValueFieldW, + kValueFieldAscent + kValueFieldDescent}; +} +constexpr int kValueFieldCount = 6; +constexpr ValueField kValueFields[kValueFieldCount] = { + valueField(kKnobs[4], kKnobCY + kKnobValueDY), // Threshold + valueField(kKnobs[5], kKnobCY + kKnobValueDY), // Bass + valueField(kKnobs[6], kKnobCY + kKnobValueDY), // Middle + valueField(kKnobs[7], kKnobCY + kKnobValueDY), // Treble + valueField(kIoKnobs[0], kIoValueBaselineY), // Input + valueField(kIoKnobs[1], kIoValueBaselineY), // Output +}; +// A dial is hit-tested as its own circle, so a box that reached up into one +// would take a drag's first click away from it. +static_assert(kValueFields[0].y > kKnobCY + kKnobR, "a value field reaches up into its dial"); +static_assert(kValueFields[4].y > kIoKnobCY + kIoKnobR, + "the Input/Output value fields reach up into their dials"); +static_assert(kValueFieldW < kKnobPitch, "two neighbouring value fields touch"); +// Below the four head readouts is the page button row, which spans Bass to +// Treble; the Threshold field's left-hand neighbour is the last channel +// switch's (generous) click target. +static_assert(kValueFields[0].y + kValueFields[0].h < kPageButtonY, + "the value fields have come down onto the page buttons"); +static_assert(kValueFields[0].x > kToggles[kToggleCount - 1].cx + kToggleHitW / 2, + "the Threshold value field reaches into the last channel switch's click area"); +// The Input field's neighbour is the first channel switch; the Output field's +// is the end of the page button row, which shares its band. +static_assert(kValueFields[4].x + kValueFieldW < kToggles[0].cx - kToggleHitW / 2, + "the Input value field reaches into the first channel switch's click area"); +static_assert(kValueFields[5].x > + kPageButtons[kPageButtonCount - 1].x + kPageButtons[kPageButtonCount - 1].w, + "the Output value field reaches into the page buttons"); +static_assert(kValueFields[4].y + kValueFields[4].h < kFaceB, + "the Input/Output value fields have reached the faceplate's edge"); + // --- The status strip, under the faceplate ---------------------------------- // WHAT THE STRIP IS FOR: the one thing a player could not see without leaving // this page — which capture each of the four banks is on. diff --git a/products/rack/src/rationscontroller.cpp b/products/rack/src/rationscontroller.cpp index 4974c93..4ce6436 100644 --- a/products/rack/src/rationscontroller.cpp +++ b/products/rack/src/rationscontroller.cpp @@ -183,6 +183,10 @@ tresult PLUGIN_API RationsController::initialize(FUnknown *context) parameters.addParameter(STR16("Active Channel"), nullptr, 0, 0.0, Vst::ParameterInfo::kIsReadOnly | Vst::ParameterInfo::kIsHidden, kActiveChannelId); + // The input-level lamp, 0 or 1, hence one step. + parameters.addParameter(STR16("Input Level OK"), nullptr, 1, 0.0, + Vst::ParameterInfo::kIsReadOnly | Vst::ParameterInfo::kIsHidden, + kInputLevelOkId); // --- the unit, and the ORDER rule that comes with it --------------------------------- // diff --git a/products/rack/src/rationsids.h b/products/rack/src/rationsids.h index 2bb9f76..247140e 100644 --- a/products/rack/src/rationsids.h +++ b/products/rack/src/rationsids.h @@ -166,6 +166,10 @@ enum ParamIDs : Steinberg::Vst::ParamID { // capture is still being built is held rather than faked, and the panel LEDs read this so a // lamp never lights over a channel the audio has not reached yet. kActiveChannelId = 204, + // The input-level lamp beside the Input knob: 1 when the peak the sounding capture hears is in + // the window inputlevellamp.h describes, else 0. Like kActiveChannelId it is an answer from the + // audio thread, and the editor only draws it. + kInputLevelOkId = 205, // The MIDI-mapped parameter block: 1000 + cc for CC 0 .. 127, and 1128 for Program Change. // These exist because a footswitch's messages do not arrive as MIDI at all - they arrive as @@ -185,6 +189,16 @@ enum ParamIDs : Steinberg::Vst::ParamID { kMidiProgramChangeId = 1128, }; +// Every hidden read-only parameter the processor writes on every block, in one list. The +// processor writes them by walking this list and each standalone backend reserves its output +// queue against the count, so adding a value moves both together. +inline constexpr Steinberg::Vst::ParamID kFeedbackIds[] = { + kInputMeterId, kOutputMeterId, kBankProgressId, + kActiveIndexId, kActiveChannelId, kInputLevelOkId, +}; +inline constexpr int kFeedbackCount = + static_cast(sizeof(kFeedbackIds) / sizeof(kFeedbackIds[0])); + // Units. The root unit is everything a player touches; the MIDI unit holds the 129 parameters // that exist only so that CC and Program Change have somewhere to arrive, and exists so a host // can fold them away instead of listing them beside Bass and Treble. diff --git a/products/rack/src/rationsprocessor.cpp b/products/rack/src/rationsprocessor.cpp index 46ecdc7..9a8c421 100644 --- a/products/rack/src/rationsprocessor.cpp +++ b/products/rack/src/rationsprocessor.cpp @@ -235,6 +235,8 @@ tresult PLUGIN_API RationsProcessor::setupProcessing(ProcessSetup &setup) // section has to be said again here rather than assumed to have survived. publishOutputMode(); + mInputLamp.reset(mSampleRate); + // Bypass ramp length in samples, at least one sample so the step is finite. const double rampSamples = std::max(1.0, engine::kBypassRampMs * 0.001 * mSampleRate); mBypassStep = 1.0 / rampSamples; @@ -282,6 +284,8 @@ tresult PLUGIN_API RationsProcessor::setActive(TBool state) mToneStack.Process(warm, 1, static_cast(n)); // Come up dry and ramp in, rather than opening on a half-built bank. mBypassMix = 1.0; + // And with the lamp dark, rather than holding a light from before the deactivation. + mInputLamp.reset(mSampleRate); } else { // Anything the audio thread retired is unreachable from it now; free it here. for (int slot = 0; slot < kIrSlotCount; ++slot) @@ -657,15 +661,25 @@ tresult PLUGIN_API RationsProcessor::process(ProcessData &data) inPeak = std::max(inPeak, std::fabs(static_cast(in[i]))); outPeak = std::max(outPeak, std::fabs(static_cast(outL[i]))); } - writeOutputPoint(data.outputParameterChanges, kInputMeterId, peakToMeterNorm(inPeak), 0); - writeOutputPoint(data.outputParameterChanges, kOutputMeterId, peakToMeterNorm(outPeak), 0); - writeOutputPoint(data.outputParameterChanges, kBankProgressId, mRack.progress(), 0); - writeOutputPoint(data.outputParameterChanges, kActiveIndexId, mRack.activeIndexNorm(), 0); - // Which channel is SOUNDING, which is not always the one kChannelId asks for: a switch - // whose target capture is still being built is held, and the editor's LED must not light - // over a channel that is not there yet. The parameter is the request; this is the answer. - writeOutputPoint(data.outputParameterChanges, kActiveChannelId, - normFromChannel(mRack.soundingChannel()), 0); + // In kFeedbackIds' order, and written by walking that list, because the list is also what + // every standalone reserves its output queue against. The size check makes a value added + // here without its id, or an id without its value, a compile error. + const double feedback[] = { + peakToMeterNorm(inPeak), + peakToMeterNorm(outPeak), + mRack.progress(), + mRack.activeIndexNorm(), + // Which channel is SOUNDING, which is not always the one kChannelId asks for: a switch + // whose target capture is still being built is held, and the editor's LED must not + // light over a channel that is not there yet. The parameter is the request; this is + // the answer. + normFromChannel(mRack.soundingChannel()), + mInputLamp.lit() ? 1.0 : 0.0, + }; + static_assert(sizeof(feedback) / sizeof(feedback[0]) == kFeedbackCount, + "one feedback value per entry of kFeedbackIds"); + for (int f = 0; f < kFeedbackCount; ++f) + writeOutputPoint(data.outputParameterChanges, kFeedbackIds[f], feedback[f], 0); } return kResultOk; @@ -689,6 +703,19 @@ void RationsProcessor::applyDsp(const float *in, float *outL, float *outR, int32 mWorkBufInput[static_cast(i)] = x * inputGain; } + // 1a. The input-level lamp, fed the model input as the Input knob leaves it, times the + // sounding capture's own input calibration: exactly the signal that capture's model will be + // fed. Anything a host runs before this plug-in, a hosted boost in the rack's own pre chain + // included, is already in it, and so is counted. Rations taps at the same point, which in that + // product is before its built-in PRE pedals, so its Boost is not counted; that is where each + // product's pedals sit, not a choice made here. + // + // At 48 kHz this is the native-rate signal sample for sample, because the resampler is a + // call-through. At any other rate it is the host-rate signal, and its peak can differ from the + // native-rate one by whatever inter-sample peak the resampler reconstructs - not measured, and + // the reason the lamp reads here anyway: the native-rate signal exists only inside the rack. + mInputLamp.process(mWorkBufInput.data(), numSamples, mRack.soundingInputGain()); + // 2. Noise-gate trigger (level detection; returns the gated signal). DSP_SAMPLE **processingInput = &mWorkPtrInput; if (ngOn) { diff --git a/products/rack/src/rationsprocessor.h b/products/rack/src/rationsprocessor.h index 3673f08..9b66edc 100644 --- a/products/rack/src/rationsprocessor.h +++ b/products/rack/src/rationsprocessor.h @@ -32,6 +32,7 @@ #include "public.sdk/source/vst/vstaudioeffect.h" #include "channelrack.h" +#include "inputlevellamp.h" #include "irblend.h" #include "midilearn.h" #include "nativeresampler.h" @@ -193,6 +194,9 @@ class RationsProcessor : public Steinberg::Vst::AudioEffect // Four banks, four crossfade engines, one input ring and the switch between them. The single // native-rate block processor the shared resampler drives. ChannelRack mRack; + // The input-level lamp's detector. Audio thread only, apart from reset() in setupProcessing + // and setActive, when the audio thread is not running. + InputLevelLamp mInputLamp; // Two IR slots. Slot A alone is the normal case and takes exactly the path it took before the // second slot existed - one Process call, no mixing, the blend not consulted - so a user who diff --git a/products/rack/src/rationsview.cpp b/products/rack/src/rationsview.cpp index ffb8071..97ca349 100644 --- a/products/rack/src/rationsview.cpp +++ b/products/rack/src/rationsview.cpp @@ -17,6 +17,7 @@ #include "rationsids.h" #include "gfx/widgets.h" #include "platform/respath.h" +#include "typednumber.h" #include "pluginterfaces/base/keycodes.h" #include "pluginterfaces/base/ustring.h" @@ -64,9 +65,25 @@ void drawCaret(Canvas &c, const Rect &box, float caretX) c.strokeLine(caretX, box.y + 4.0f, caretX, box.bottom() - 4.0f); } -// Pixels of vertical drag for a dial's full range, in LOGICAL units — so the feel is the same at -// every window size. -constexpr float kKnobDragRange = 200.0f; +// Drag and wheel gearing, from the original plug-in's knobs (iPlug2's IKnobControlBase). A drag +// covers the full range in DEFAULT_GEARING (4.0) heights of the knob's drag bounds; upstream takes +// those bounds from the control's own rect, and the head dial's face diameter stands in for it +// here — for EVERY dial, so the small pedal knobs are not geared coarser than the big ones. In +// LOGICAL units, so the feel is the same at every window size. Holding Shift or Ctrl (Command on a +// Mac, see platform/pointermods.h) makes a drag ten times finer and a wheel notch a tenth of its +// usual 1%: upstream's IsFineControl is `mod.C || mod.S`, and its wheel steps are 0.01 and 0.001. +constexpr float kDragGearing = 4.0f; +constexpr float kKnobDragRange = kDragGearing * 2.0f * geo::kKnobR; // 224 +constexpr float kFineDragFactor = 10.0f; +constexpr double kWheelStep = 0.01, kFineWheelStep = 0.001; +// The trims and the dBu box keep their own round-number notches (kLevelWheelDb, kCalWheelDb), and +// fine is a tenth of those too. +constexpr double kFineWheelDivisor = 10.0; + +bool isFine(unsigned mods) +{ + return (mods & (Steinberg::kPointerShift | Steinberg::kPointerControl)) != 0; +} // The dial is the one layer that is rotated after being scaled, so rotation resamples it a second // time. Caching it at exactly its on-screen size loses visible contrast in the thin gold pointer; @@ -641,6 +658,11 @@ void RationsEditorView::composeHead(Canvas &c) drawMeter(c, geo::kOutputMeter, mOutDisp, mOutPeak); for (int i = 0; i < 2; ++i) drawKnob(c, geo::kIoKnobs[i], true); + // Read from the parameter rather than from the cached copy ParamChanged keeps, so a page that + // is drawn before the first report still shows the controller's value. + drawLed(c, static_cast(geo::kInputLampCX), static_cast(geo::kInputLampCY), + paramValue(kInputLevelOkId) > 0.5, static_cast(geo::kInputLampR), + geo::LedColor::Green); for (const geo::ButtonSpec &b : geo::kPageButtons) drawButton(c, b); @@ -1213,29 +1235,17 @@ void RationsEditorView::drawOutputSection(Canvas &c) c.setPenSize(1.0f); c.strokeRoundRect(value, 4.0f); - const std::string text = editing ? mEditText : calValueText(); c.setFont(Font::Body); c.setFontSize(geo::kMidiRowTextSize); // Centred in both states, so the box does not jolt as the field opens under the pointer. - const float textW = c.stringWidth(text.c_str()); - const float textX = value.centerX() - textW * 0.5f; const float textBase = value.centerY() + geo::kMidiRowTextSize * 0.36f; - if (editSelected()) { - // The seed, drawn SELECTED — which is the field saying, before anything is typed, that - // typing will replace it rather than append to it. Without this the rule is still the - // right one and the user has no way to know it until they have got a wrong answer. - const Rect sel(textX - 2.0f, value.y + 4.0f, textW + 4.0f, value.h - 8.0f); - c.setColor(geo::kAccent, 210); - c.fillRoundRect(sel, 2.0f); - c.setColor(0x0C0B0A); - } else { - c.setColor(editing ? geo::kAccentBright : geo::kTextColor); - } - c.drawString(text.c_str(), textX, textBase); - if (editing && !editSelected()) { - const std::string before = text.substr(0, std::min(mEditCaret, text.size())); - drawCaret(c, value, textX + c.stringWidth(before.c_str())); + if (editing) { + drawFieldText(c, value, textBase); + return; } + const std::string text = calValueText(); + c.setColor(geo::kTextColor); + c.drawString(text.c_str(), value.centerX() - c.stringWidth(text.c_str()) * 0.5f, textBase); } //------------------------------------------------------------------------ @@ -1269,7 +1279,7 @@ geo::ButtonSpec RationsEditorView::midiButton(int row, bool clear) const } //------------------------------------------------------------------------ -bool RationsEditorView::handleSettingsClick(float x, float y) +bool RationsEditorView::handleSettingsClick(float x, float y, bool doubleClick) { if (!mController) return false; @@ -1350,7 +1360,10 @@ bool RationsEditorView::handleSettingsClick(float x, float y) // inside the row it starts makes no difference, and a 12 px thumb is not something to // make anyone aim at. if (levelRowRect(i).contains(x, y)) { - startDrag(kChannelLevelId[i], x, y, true); + if (doubleClick) + resetParam(kChannelLevelId[i]); + else + startDrag(kChannelLevelId[i], x, y, true); invalidate(); return true; } @@ -1468,6 +1481,24 @@ void RationsEditorView::drawKnob(Canvas &c, const geo::KnobSpec &k, bool enabled // Dim when idle, accent while this dial is being dragged. The row does not appear and // disappear — a value that came and went would make the panel twitch under the hand — it only // changes colour, which says "live" without moving anything. + // Open for typing: the readout's own box becomes the field, in the dBu box's style, with the + // text on the readout's own baseline so nothing shifts as it opens. + if (editingValue(k.id)) { + for (const geo::ValueField &f : geo::kValueFields) { + if (f.id != k.id) + continue; + const Rect box = valueFieldRect(f); + c.setColor(0x000000, 200); + c.fillRoundRect(box, 4.0f); + c.setColor(geo::kAccent, 220); + c.setPenSize(1.0f); + c.strokeRoundRect(box, 4.0f); + c.setFont(Font::Body); + c.setFontSize(geo::kKnobValueSize); + drawFieldText(c, box, valueY); + } + return; + } if (readout.empty()) return; c.setFont(Font::Body); @@ -1545,14 +1576,17 @@ void RationsEditorView::drawToggle(Canvas &c, const geo::ToggleSpec &t, bool on) } //------------------------------------------------------------------------ -void RationsEditorView::drawLed(Canvas &c, float cx, float cy, bool lit, float r) +void RationsEditorView::drawLed(Canvas &c, float cx, float cy, bool lit, float r, + geo::LedColor color) { const Rect dest(cx - r, cy - r, 2.0f * r, 2.0f * r); const int px = static_cast(std::lround(2.0 * r * mScale)); - if (cairo_surface_t *led = mImages.getScaled(lit ? "led_on" : "led_off", px, px)) { + const bool green = color == geo::LedColor::Green; + if (cairo_surface_t *led = + mImages.getScaled(!lit ? "led_off" : (green ? "led_green_on" : "led_on"), px, px)) { c.drawImage(led, dest); } else { - c.setColor(lit ? geo::kPeakColor : 0x141414); + c.setColor(!lit ? 0x141414 : (green ? geo::kAccent : geo::kPeakColor)); c.fillEllipse(dest); } } @@ -1926,15 +1960,37 @@ void RationsEditorView::nudgeParam(Vst::ParamID id, double delta) invalidate(); } +// The double-click's reset. Slim needs one more step than every other control: it is published on +// the knob's RELEASE (see kMsgSetSlim), and a double-click has no release of its own to wait for — +// the first click's has already been and gone, with nothing moved. So it is published here, and +// only when the value actually changed, because an unmoved Slim would cost every bank a rebuild. +void RationsEditorView::resetParam(Vst::ParamID id) +{ + if (!mController) + return; + const Vst::Parameter *p = mController->getParameterObject(id); + if (!p) + return; + const double norm = p->getInfo().defaultNormalizedValue; + const bool moved = paramValue(id) != norm; + editParam(id, norm); + if (id == kSlimId && moved) { + mController->applySlim(); + mSlimDirty = false; + } + invalidate(); +} + void RationsEditorView::startDrag(Vst::ParamID id, float x, float y, bool horizontal) { if (!mController) return; mDragParam = id; - mDragStartX = x; - mDragStartY = y; + mDragLastX = x; + mDragLastY = y; mDragHorizontal = horizontal; mDragStartNorm = paramValue(id); + mDragNorm = mDragStartNorm; mController->beginEdit(id); // No explicit pointer grab is needed here: X delivers an implicit grab to the window that saw // the ButtonPress for as long as the button is held, and the Win32 view calls SetCapture for @@ -1943,27 +1999,40 @@ void RationsEditorView::startDrag(Vst::ParamID id, float x, float y, bool horizo //------------------------------------------------------------------------ // One wheel click. On a channel dial that is one capture, so the wheel lands on real captures -// rather than between them — the same resting places the dial's own auto-detent glides to. -double RationsEditorView::wheelStep(Vst::ParamID id) const +// rather than between them — the same resting places the dial's own auto-detent glides to, which +// is also why fine control does not apply there: a tenth of a capture is a position the detent +// would glide straight back off. +double RationsEditorView::wheelStep(Vst::ParamID id, bool fine) const { for (int c = 0; c < kChannelCount; ++c) if (id == kChannelGainId[c] && mEntryCount[c] > 1) return 1.0 / static_cast(mEntryCount[c] - 1); - return 0.05; + return fine ? kFineWheelStep : kWheelStep; } //------------------------------------------------------------------------ -void RationsEditorView::onMouseDown(int x, int y, int button) +void RationsEditorView::onMouseDown(int x, int y, int button, unsigned /*mods*/, bool doubleClick) { // Physical pixels in, logical units out: this is the only place the page transform is undone, // and everything below hit-tests against geometry.h directly. const float fx = static_cast((x - mOffX) / mScale); const float fy = static_cast((y - mOffY) / mScale); - // Right-click resets a channel trim to exactly 0 dB. The one gesture this editor answers on a - // button other than the left, and it is here rather than on a double-click because neither - // window class delivers double-clicks: the X11 view sees two ordinary presses and the Win32 - // one deliberately does not set CS_DBLCLKS, so that the two platforms behave the same. + // An open dial readout is closed by a press anywhere else, and closed by KEEPING what was + // typed — the setup page's rule for its own fields, applied before anything below can act on + // the press. A press inside it leaves it open, caret and all. The head page does not scroll, + // so its fields are tested in window-logical coordinates as they are drawn. + if (mEditField == TextField::KnobValue) { + for (const geo::ValueField &f : geo::kValueFields) { + if (f.id == mEditParam && valueFieldRect(f).contains(fx, fy)) + return; + } + commitTextEdit(); + } + + // Right-click resets a channel trim to exactly 0 dB. It predates the double-click, which every + // platform base now reports and which resets the trims too; the right button keeps doing what + // it did, because a gesture a user has learned is not one to take away. if (button == 3) { // The Slim overlay closes on a right-click ANYWHERE, which is the gesture the author asked // for and is tested before everything else so it cannot be swallowed by a control under @@ -2003,7 +2072,10 @@ void RationsEditorView::onMouseDown(int x, int y, int button) // underneath the dim can be clicked through. if (mSlimOpen) { if (hitCircle(fx, fy, geo::kSlimKnobCX, geo::kSlimKnobCY, geo::kSlimKnobR)) { - startDrag(kSlimId, fx, fy); + if (doubleClick) + resetParam(kSlimId); + else + startDrag(kSlimId, fx, fy); invalidate(); } else { closeSlim(); @@ -2037,7 +2109,7 @@ void RationsEditorView::onMouseDown(int x, int y, int button) switch (mPage) { case geo::Page::Head: - handleHeadClick(fx, fy); + handleHeadClick(fx, fy, doubleClick); return; case geo::Page::Setup: // The scrollbar is chrome, so it is hit-tested in window coordinates and gets first @@ -2053,18 +2125,18 @@ void RationsEditorView::onMouseDown(int x, int y, int button) // latched, because a drag started in here is measured against it for its whole life. if (geo::inSetupSettingsColumn(fx)) { mFrameX = static_cast(geo::kSetupSetColX); - handleSettingsClick(fx - mFrameX, contentY(fy)); + handleSettingsClick(fx - mFrameX, contentY(fy), doubleClick); } else { mFrameX = static_cast(geo::kSetupCabColX); mFrameCabinet = true; - handleCabinetClick(fx - mFrameX, columnContentY(fx, fy)); + handleCabinetClick(fx - mFrameX, columnContentY(fx, fy), doubleClick); } return; } } //------------------------------------------------------------------------ -bool RationsEditorView::handleHeadClick(float x, float y) +bool RationsEditorView::handleHeadClick(float x, float y, bool doubleClick) { // Slim opens an overlay rather than a page: it is one knob, and a page for one knob would be a // window change and a back button to reach something most users set once. Tested against the @@ -2087,10 +2159,17 @@ bool RationsEditorView::handleHeadClick(float x, float y) } } + // A dial is dragged, double-clicked back to its default, or — for the six with a value row — + // typed into by clicking that row: the three ways the original plug-in's knobs offer. The + // first press of a double-click has already begun and ended a drag that went nowhere, which + // is harmless: an edit gesture with no performEdit in it changes nothing. for (int i = 0; i < geo::kKnobCount; ++i) { const geo::KnobSpec &k = geo::kKnobs[i]; if (hitCircle(x, y, k.cx, k.cy, k.r)) { - startDrag(k.id, x, y); + if (doubleClick) + resetParam(k.id); + else + startDrag(k.id, x, y); invalidate(); // the readout appears return true; } @@ -2098,11 +2177,21 @@ bool RationsEditorView::handleHeadClick(float x, float y) for (int i = 0; i < 2; ++i) { const geo::KnobSpec &k = geo::kIoKnobs[i]; if (hitCircle(x, y, k.cx, k.cy, k.r)) { - startDrag(k.id, x, y); + if (doubleClick) + resetParam(k.id); + else + startDrag(k.id, x, y); invalidate(); return true; } } + for (const geo::ValueField &f : geo::kValueFields) { + if (valueFieldRect(f).contains(x, y)) { + if (!editingValue(f.id)) + beginTextEdit(TextField::KnobValue, -1, f.id); + return true; + } + } for (int i = 0; i < geo::kToggleCount; ++i) { const geo::ToggleSpec &t = geo::kToggles[i]; @@ -2137,10 +2226,13 @@ bool RationsEditorView::handleHeadClick(float x, float y) } //------------------------------------------------------------------------ -bool RationsEditorView::handleCabinetClick(float x, float y) +bool RationsEditorView::handleCabinetClick(float x, float y, bool doubleClick) { if (blendActive() && hitCircle(x, y, geo::kBlendCX, geo::kBlendCY, geo::kBlendHitR)) { - startDrag(kIrBlendId, x, y); + if (doubleClick) + resetParam(kIrBlendId); + else + startDrag(kIrBlendId, x, y); invalidate(); return true; } @@ -2187,7 +2279,7 @@ bool RationsEditorView::handleIrRowClick(int slot, float x, float y) } //------------------------------------------------------------------------ -void RationsEditorView::onMouseMove(int x, int y) +void RationsEditorView::onMouseMove(int x, int y, unsigned mods) { const float fx = static_cast((x - mOffX) / mScale); const float fy = static_cast((y - mOffY) / mScale); @@ -2215,19 +2307,32 @@ void RationsEditorView::onMouseMove(int x, int y) if (!mDragParam || !mController) return; + // Accumulated from the last position, as the original plug-in's knobs do, so pressing or + // releasing Shift mid-drag changes the gearing from that point on instead of making the + // control jump. The accumulator is clamped as it goes, so overshooting an end costs no travel + // on the way back. + const bool fine = isFine(mods); + const float gear = fine ? kFineDragFactor : 1.0f; double norm; if (mDragHorizontal) { // Relative, never absolute: a slider that jumped to wherever it was clicked would let a // mis-click throw a channel's level by the whole range, and this control's whole job is // small corrections. The drag also snaps to exactly 0 dB near the centre, because a trim - // has to be returnable to its default by hand. - norm = clampNorm(mDragStartNorm + (mMouseX - mDragStartX) / geo::kLevelDragRange); + // has to be returnable to its default by hand — but NOT under fine control, whose whole + // point is a value like +0.1 dB that the snap zone (±0.28 dB) would otherwise swallow. + // The snap is applied to what is published, never to the accumulator, so a coarse drag + // that passes through the centre is not held there. + mDragNorm = clampNorm(mDragNorm + (mMouseX - mDragLastX) / (geo::kLevelDragRange * gear)); + norm = mDragNorm; const double centre = 0.5; - if (std::fabs(norm - centre) * geo::kLevelDragRange < geo::kLevelCentreSnap) + if (!fine && std::fabs(norm - centre) * geo::kLevelDragRange < geo::kLevelCentreSnap) norm = centre; } else { - norm = clampNorm(mDragStartNorm + (mDragStartY - mMouseY) / kKnobDragRange); + mDragNorm = clampNorm(mDragNorm + (mDragLastY - mMouseY) / (kKnobDragRange * gear)); + norm = mDragNorm; } + mDragLastX = mMouseX; + mDragLastY = mMouseY; // A Slim drag that actually moved is what makes the release worth publishing. A click on the // knob that goes nowhere leaves mSlimDirty false and costs no rebuild. if (mDragParam == kSlimId && norm != mDragStartNorm) @@ -2262,14 +2367,16 @@ void RationsEditorView::onMouseUp(int /*x*/, int /*y*/, int button) //------------------------------------------------------------------------ // Wheel adjusts whatever is under the cursor (wheel up = increase). -void RationsEditorView::onMouseWheel(int x, int y, int delta) +void RationsEditorView::onMouseWheel(int x, int y, int delta, unsigned mods) { const float fx = static_cast((x - mOffX) / mScale); const float fy = static_cast((y - mOffY) / mScale); + const bool fine = isFine(mods); + const double step = delta * (fine ? kFineWheelStep : kWheelStep); if (mSlimOpen) { if (hitCircle(fx, fy, geo::kSlimKnobCX, geo::kSlimKnobCY, geo::kSlimKnobR)) { - nudgeParam(kSlimId, delta * 0.05); + nudgeParam(kSlimId, step); mSlimDirty = true; } return; @@ -2306,7 +2413,7 @@ void RationsEditorView::onMouseWheel(int x, int y, int delta) if (!geo::inSetupSettingsColumn(fx)) { const float bx = fx - static_cast(geo::kSetupCabColX); if (blendActive() && hitCircle(bx, cy, geo::kBlendCX, geo::kBlendCY, geo::kBlendHitR)) - nudgeParam(kIrBlendId, delta * 0.05); + nudgeParam(kIrBlendId, step); return; } const float cx = fx - static_cast(geo::kSetupSetColX); @@ -2315,16 +2422,19 @@ void RationsEditorView::onMouseWheel(int x, int y, int delta) // to repeat on the other three channels. for (int i = 0; i < geo::kLevelRowCount; ++i) { if (levelRowRect(i).contains(cx, cy)) { + const double db = geo::kLevelWheelDb / (fine ? kFineWheelDivisor : 1.0); nudgeParam(kChannelLevelId[i], - delta * geo::kLevelWheelDb / (ranges::kLevelMax - ranges::kLevelMin)); + delta * db / (ranges::kLevelMax - ranges::kLevelMin)); return; } } // The interface calibration level, in whole decibels: an interface's stated level is a // round number, and this is how a user lands on theirs without aiming a drag at it. - if (calValueRect().contains(cx, cy)) { - nudgeParam(kInputCalLevelId, - delta * geo::kCalWheelDb / (ranges::kCalMax - ranges::kCalMin)); + // Not while the box is open for typing: the wheel would move the value underneath a field + // that is about to overwrite it, and the box would show neither. + if (calValueRect().contains(cx, cy) && mEditField != TextField::CalLevel) { + const double db = geo::kCalWheelDb / (fine ? kFineWheelDivisor : 1.0); + nudgeParam(kInputCalLevelId, delta * db / (ranges::kCalMax - ranges::kCalMin)); return; } return; @@ -2333,15 +2443,18 @@ void RationsEditorView::onMouseWheel(int x, int y, int delta) return; for (int i = 0; i < geo::kKnobCount; ++i) { const geo::KnobSpec &k = geo::kKnobs[i]; + // A dial whose readout is open for typing ignores the wheel, as the dBu box does. if (hitCircle(fx, fy, k.cx, k.cy, k.r)) { - nudgeParam(k.id, delta * wheelStep(k.id)); + if (!editingValue(k.id)) + nudgeParam(k.id, delta * wheelStep(k.id, fine)); return; } } for (int i = 0; i < 2; ++i) { const geo::KnobSpec &k = geo::kIoKnobs[i]; if (hitCircle(fx, fy, k.cx, k.cy, k.r)) { - nudgeParam(k.id, delta * 0.05); + if (!editingValue(k.id)) + nudgeParam(k.id, step); return; } } @@ -2471,20 +2584,71 @@ std::string RationsEditorView::calEditSeed() const return dbu; } -void RationsEditorView::beginTextEdit(TextField field, int channel) +// A dial's readout without its unit: exactly the number the row shows, so opening the field moves +// nothing but the highlight. paramText is the controller's own formatting of the plain value, and +// commitTextEdit reads a plain value back, so the seed round-trips. +std::string RationsEditorView::valueEditSeed(Vst::ParamID id) const +{ + return paramText(id); +} + +Rect RationsEditorView::valueFieldRect(const geo::ValueField &f) +{ + return Rect(static_cast(f.x), static_cast(f.y), static_cast(f.w), + static_cast(f.h)); +} + +// The text of the open field: centred in its box, either the whole of it highlighted (just +// opened — typing replaces it) or a caret. Shared by the dBu box and the dial readouts, so the two +// cannot come to disagree about what a selected field looks like. +void RationsEditorView::drawFieldText(Canvas &c, const Rect &box, float baseline) +{ + const float textW = c.stringWidth(mEditText.c_str()); + const float textX = box.centerX() - textW * 0.5f; + if (editSelected()) { + // The seed, drawn SELECTED — which is the field saying, before anything is typed, that + // typing will replace it rather than append to it. Without this the rule is still the + // right one and the user has no way to know it until they have got a wrong answer. + const Rect sel(textX - 2.0f, box.y + 4.0f, textW + 4.0f, box.h - 8.0f); + c.setColor(geo::kAccent, 210); + c.fillRoundRect(sel, 2.0f); + c.setColor(0x0C0B0A); + } else { + c.setColor(geo::kAccentBright); + } + c.drawString(mEditText.c_str(), textX, baseline); + if (!editSelected()) { + const std::string before = mEditText.substr(0, std::min(mEditCaret, mEditText.size())); + drawCaret(c, box, textX + c.stringWidth(before.c_str())); + } +} + +void RationsEditorView::beginTextEdit(TextField field, int channel, Vst::ParamID param) { if (!mController || field == TextField::NoField) return; if (field == TextField::ChannelName && (channel < 0 || channel >= kChannelCount)) return; + if (field == TextField::KnobValue && param == 0) + return; + // One field at a time: opening a second one closes the first, keeping what it held. + commitTextEdit(); mEditField = field; mEditChannel = channel; + mEditParam = field == TextField::KnobValue ? param : 0; // A name is seeded with the name currently SHOWN, not with the override, so a user adjusting - // the folder's name starts from it rather than from an empty field. A level is seeded with the - // level currently set, for the same reason: both are edits to something, not entries from - // nothing. - mEditText = field == TextField::ChannelName ? mController->channelName(channel) : calEditSeed(); + // the folder's name starts from it rather than from an empty field. A level or a dial's value + // is seeded with what is currently set, for the same reason: all three are edits to something, + // not entries from nothing. + if (field == TextField::ChannelName) + mEditText = mController->channelName(channel); + else if (field == TextField::CalLevel) + mEditText = calEditSeed(); + else + mEditText = valueEditSeed(param); + if (field != TextField::ChannelName && mEditText.size() > geo::kCalEditMaxChars) + mEditText.resize(geo::kCalEditMaxChars); mEditCaret = mEditText.size(); // A LEVEL opens with its seed selected, so the first character typed replaces it. That is what // a value field is for: the number is read off an interface's spec sheet and entered whole, @@ -2495,7 +2659,7 @@ void RationsEditorView::beginTextEdit(TextField field, int channel) // A NAME does not, and that is the same argument reaching the other answer: a channel's name // is seeded with what the folder is called precisely so it can be ADJUSTED (D14), and select- // on-open would put a keystroke between the user and the text they asked to start from. - mEditSelectAll = field == TextField::CalLevel; + mEditSelectAll = field != TextField::ChannelName; // Take the keyboard for exactly as long as this field is open, and no longer. Every exit from // a field — commit, cancel, a click elsewhere, a page change — runs through commitTextEdit() // or cancelTextEdit(), so there is no path that leaves it held. @@ -2509,9 +2673,11 @@ void RationsEditorView::commitTextEdit() return; const TextField field = mEditField; const int channel = mEditChannel; + const Vst::ParamID param = mEditParam; const std::string text = mEditText; mEditField = TextField::NoField; mEditChannel = -1; + mEditParam = 0; mEditText.clear(); mEditCaret = 0; mEditSelectAll = false; @@ -2533,25 +2699,37 @@ void RationsEditorView::commitTextEdit() // a number invented out of a partial one — "-" on its own, or an emptied field, is a user // part-way through an edit and not a request for -60 dBu. // - // strtod rather than std::stod: this runs on the host's UI thread inside a click, and a - // throw out of here would cross the SDK's C ABI. + // parseTypedNumber rather than strtod, which follows the HOST's LC_NUMERIC and under a + // locale that writes 2,5 reads "-3.5" as -3 — see typednumber.h, which also says why it is + // not std::from_chars. It throws nothing, so nothing can cross the SDK's C ABI from here. // // There is deliberately no std::isfinite guard: this translation unit is built with // -ffast-math, under which that call folds to a constant true (D26, where exactly such a // guard had been compiled out of every build since it was written). It is not needed - // either. acceptsTextChar admits only [0-9.+-], so there is no exponent and no "nan" to + // either. acceptsTextChar admits only [0-9.,+-], so there is no exponent and no "nan" to // type, and kCalEditMaxChars caps the field at eight characters — the largest magnitude // that can be entered is 99999999, which is finite, and std::clamp takes it to +60. - const char *begin = text.c_str(); - char *end = nullptr; - const double db = std::strtod(begin, &end); - if (end != begin) { + double db = 0.0; + if (parseTypedNumber(text, db)) { // Clamped rather than refused: a user who types 100 wants the loudest this offers, and // the box redraws at +60.0 dBu to say what they got. const double clamped = std::clamp(db, ranges::kCalMin, ranges::kCalMax); editParam(kInputCalLevelId, (clamped - ranges::kCalMin) / (ranges::kCalMax - ranges::kCalMin)); } + } else if (mController && field == TextField::KnobValue) { + // A dial's value, in the units its readout shows — the parameter's PLAIN value, which for + // all six is a straight line over its range (each is a RangeParameter), so toNormalized is + // exact. The same rules as the dBu box: what will not parse leaves the parameter alone, + // and what is out of range is clamped, so the readout redraws at the limit and says what + // was taken. + double plain = 0.0; + const Vst::Parameter *p = mController->getParameterObject(param); + if (p && parseTypedNumber(text, plain)) { + const double lo = p->toPlain(0.0), hi = p->toPlain(1.0); + plain = std::clamp(plain, std::min(lo, hi), std::max(lo, hi)); + editParam(param, p->toNormalized(plain)); + } } invalidate(); } @@ -2560,6 +2738,7 @@ void RationsEditorView::cancelTextEdit() { mEditField = TextField::NoField; mEditChannel = -1; + mEditParam = 0; mEditText.clear(); mEditCaret = 0; mEditSelectAll = false; @@ -2567,11 +2746,6 @@ void RationsEditorView::cancelTextEdit() invalidate(); } -// What may be typed into the field that is open. A name takes any printable ASCII; a level takes -// only the characters a decimal number is written with, so a field whose whole purpose is to be -// parsed cannot be filled with something that will not parse. The check is on the CHARACTER and -// not on the resulting string: rejecting "-" because "-" is not yet a number would make a negative -// level untypeable, which is the shape of interface level most users have. // Drop the selection, optionally taking the text with it. One place rather than the six the key // handler would otherwise set two fields in, because a selection left set after the text under it // has changed would highlight characters the user did not select. @@ -2586,11 +2760,17 @@ void RationsEditorView::clearSelection(bool erase) } } +// What may be typed into the field that is open. A name takes any printable ASCII; a level or a +// dial's value takes only the characters a decimal number is written with, so a field whose whole +// purpose is to be parsed cannot be filled with something that will not parse. The check is on the +// CHARACTER and not on the resulting string: rejecting "-" because "-" is not yet a number would +// make a negative level untypeable, which is the shape of interface level most users have. Both +// decimal marks are taken, because a user whose desktop writes 2,5 will type it that way. bool RationsEditorView::acceptsTextChar(char ch) const { - if (mEditField != TextField::CalLevel) + if (mEditField == TextField::ChannelName) return true; - return (ch >= '0' && ch <= '9') || ch == '.' || ch == '-' || ch == '+'; + return (ch >= '0' && ch <= '9') || ch == '.' || ch == ',' || ch == '-' || ch == '+'; } // One key. Returns whether it was consumed, which is the whole contract: the SDK warns that @@ -2602,8 +2782,11 @@ bool RationsEditorView::handleTextKey(char16 key, int16 keyCode, int16 modifiers return false; switch (keyCode) { + // Tab commits as well, as it does in the original plug-in's fields and in most others: it + // is what a hand that is about to move on presses. case Steinberg::KEY_RETURN: case Steinberg::KEY_ENTER: + case Steinberg::KEY_TAB: commitTextEdit(); return true; case Steinberg::KEY_ESCAPE: @@ -2700,8 +2883,9 @@ bool RationsEditorView::handleTextKey(char16 key, int16 keyCode, int16 modifiers // The first character typed into a selected field replaces the whole of it. if (mEditSelectAll) clearSelection(/*erase=*/true); + // A dial's value is a number of the same shape as the dBu level, so it takes the same cap. const size_t limit = - mEditField == TextField::CalLevel ? geo::kCalEditMaxChars : kRenameMaxChars; + mEditField == TextField::ChannelName ? kRenameMaxChars : geo::kCalEditMaxChars; if (mEditText.size() >= limit) return true; // consumed, but the field is full mEditText.insert(mEditCaret, 1, static_cast(ch)); @@ -2834,6 +3018,16 @@ void RationsEditorView::ParamChanged(Vst::ParamID id, Vst::ParamValue value) invalidate(); return; } + case kInputLevelOkId: { + // Reported every block, and it changes a few times a phrase at most, so it repaints + // only when it changes rather than on every report the way the default below does. + const bool lit = value > 0.5; + if (lit != mInputLampLit) { + mInputLampLit = lit; + invalidate(); + } + return; + } case kActiveIndexId: { const int c = activeChannel(); const int index = mEntryCount[c] > 1 diff --git a/products/rack/src/rationsview.h b/products/rack/src/rationsview.h index 022847e..0404b83 100644 --- a/products/rack/src/rationsview.h +++ b/products/rack/src/rationsview.h @@ -88,10 +88,10 @@ class RationsEditorView : public Steinberg::NativePlugView void onAttached() SMTG_OVERRIDE; void onRemoved() SMTG_OVERRIDE; void onDraw(cairo_t *cr) SMTG_OVERRIDE; - void onMouseDown(int x, int y, int button) SMTG_OVERRIDE; + void onMouseDown(int x, int y, int button, unsigned mods, bool doubleClick) SMTG_OVERRIDE; void onMouseUp(int x, int y, int button) SMTG_OVERRIDE; - void onMouseMove(int x, int y) SMTG_OVERRIDE; - void onMouseWheel(int x, int y, int delta) SMTG_OVERRIDE; + void onMouseMove(int x, int y, unsigned mods) SMTG_OVERRIDE; + void onMouseWheel(int x, int y, int delta, unsigned mods) SMTG_OVERRIDE; void onTick() SMTG_OVERRIDE; bool isResizable() const SMTG_OVERRIDE @@ -160,7 +160,8 @@ class RationsEditorView : public Steinberg::NativePlugView // passes the head's own kLedR today; it was the pedalboard's smaller status LEDs that needed // the argument, and the channel lamps and the utility row would each need it again the moment // anything on this panel wants a lamp at another size. - void drawLed(Canvas &c, float cx, float cy, bool lit, float r = static_cast(geo::kLedR)); + void drawLed(Canvas &c, float cx, float cy, bool lit, float r = static_cast(geo::kLedR), + geo::LedColor color = geo::LedColor::Red); // The status strip under the faceplate: the four banks with the capture each dial is on. // Caps-dependent, so it is composed every frame; the band it sits on and its dividers are // static. There is no pedal row here — this product has no pedalboard. @@ -175,9 +176,14 @@ class RationsEditorView : public Steinberg::NativePlugView void editParam(Steinberg::Vst::ParamID id, double norm); void nudgeParam(Steinberg::Vst::ParamID id, double delta); void startDrag(Steinberg::Vst::ParamID id, float x, float y, bool horizontal = false); - bool handleHeadClick(float x, float y); - bool handleCabinetClick(float x, float y); - bool handleSettingsClick(float x, float y); + // Return a control to its parameter's own default — the double-click on a dial or a slider, + // as on the original plug-in (IControl::OnMouseDblClick -> SetValueToDefault). + void resetParam(Steinberg::Vst::ParamID id); + // `doubleClick` reaches only the handlers that have something a double-click resets; every + // switch ignores it, so two clicks on a toggle are still two toggles. + bool handleHeadClick(float x, float y, bool doubleClick); + bool handleCabinetClick(float x, float y, bool doubleClick); + bool handleSettingsClick(float x, float y, bool doubleClick); bool handleIrRowClick(int slot, float x, float y); // Load the previous (-1) or next (+1) IR in slot `slot`'s own folder. void stepIr(int slot, int dir); @@ -191,8 +197,9 @@ class RationsEditorView : public Steinberg::NativePlugView void boundCaptureBrowser(); // --- typed input ------------------------------------------------------------------------- - // Two fields take typed input — a channel's name and the interface calibration level — and - // they share one field, one caret, one focus grab and one key handler. That is not tidiness: + // Three kinds of field take typed input — a channel's name, the interface calibration level and + // the six dial readouts — and they share one field, one caret, one focus grab and one key + // handler. That is not tidiness: // the field holds the host's keyboard focus while it is open (RULES §4), so two independent // fields would be two things that can each forget to hand it back, and a state where both // believe they have it. One field cannot be open twice. @@ -204,8 +211,9 @@ class RationsEditorView : public Steinberg::NativePlugView NoField, ChannelName, // mEditChannel says which of the four CalLevel, // the interface level in dBu, kInputCalLevelId + KnobValue, // one of the six dial readouts, geo::kValueFields; mEditParam says which }; - void beginTextEdit(TextField field, int channel = -1); + void beginTextEdit(TextField field, int channel = -1, Steinberg::Vst::ParamID param = 0); // Ends the edit by KEEPING what was typed, which is what every exit but Escape does. A value // that will not parse is the one case that cannot be kept, and leaves its parameter alone. void commitTextEdit(); @@ -225,6 +233,10 @@ class RationsEditorView : public Steinberg::NativePlugView { return mEditField == TextField::ChannelName && mEditChannel == channel; } + bool editingValue(Steinberg::Vst::ParamID id) const + { + return mEditField == TextField::KnobValue && mEditParam == id; + } // Returns true when the key was consumed, which is exactly what onKeyDown must report to the // host: a wrong "yes" swallows the host's own key commands, and the transport is one of them. bool handleTextKey(Steinberg::char16 key, Steinberg::int16 keyCode, Steinberg::int16 modifiers); @@ -238,6 +250,13 @@ class RationsEditorView : public Steinberg::NativePlugView // for editing ("12.0") — the unit is not typed, so it is not offered to be deleted. std::string calValueText() const; std::string calEditSeed() const; + // A dial readout's field: where it is, and its seed — the readout without its unit. + static Rect valueFieldRect(const geo::ValueField &f); + std::string valueEditSeed(Steinberg::Vst::ParamID id) const; + // The text of an open field, with its selection or its caret, inside `box` on `baseline`. The + // font is set by the caller; the dBu box and the dial readouts both draw through this, so the + // two fields look and behave as one. + void drawFieldText(Canvas &c, const Rect &box, float baseline); void pollCaps(); // Ask the processor what the learn table now says, while a row is waiting to be taught. void pollMidi(); @@ -255,7 +274,7 @@ class RationsEditorView : public Steinberg::NativePlugView std::string knobReadout(const geo::KnobSpec &k) const; // One wheel click. On a channel dial that is one capture, so the wheel lands on real captures // rather than between them. - double wheelStep(Steinberg::Vst::ParamID id) const; + double wheelStep(Steinberg::Vst::ParamID id, bool fine) const; // Index of the capture sounding in channel `c`, falling back to that dial's position before // the processor has reported one. int captureIndex(int c) const; @@ -378,7 +397,8 @@ class RationsEditorView : public Steinberg::NativePlugView // The one open text field, if any, and what is in it. The text is held here rather than // pushed at its destination on every keystroke so that Escape has something to go back to. TextField mEditField = TextField::NoField; - int mEditChannel = -1; // meaningful only for TextField::ChannelName + int mEditChannel = -1; // meaningful only for TextField::ChannelName + Steinberg::Vst::ParamID mEditParam = 0; // meaningful only for TextField::KnobValue std::string mEditText; size_t mEditCaret = 0; // The whole seed is selected until the first key lands on it. One flag rather than an anchor @@ -393,12 +413,17 @@ class RationsEditorView : public Steinberg::NativePlugView // rebuilds every capture in every bank — see kMsgSetSlim. bool mSlimOpen = false; bool mSlimDirty = false; - float mDragStartY = 0; + // The drag ACCUMULATES from the last pointer position rather than measuring from the first, + // which is what lets Shift or Ctrl change its gearing mid-drag without the control jumping. + // mDragNorm is the editor's own running value and is never re-read from the parameter during + // the drag, so a host that echoes a write back late cannot pull it backwards. mDragStartNorm is + // kept only to tell a drag that moved from a click that did not. + float mDragLastX = 0, mDragLastY = 0; + double mDragNorm = 0; double mDragStartNorm = 0; // A knob is dragged vertically and a level slider horizontally, so the drag carries which // axis it is on rather than the hit test having to leave a knob's coordinate in a Y field. bool mDragHorizontal = false; - float mDragStartX = 0; float mMouseX = 0, mMouseY = 0; // The coordinate frame the press that is being held was hit-tested in. The setup page hands @@ -420,6 +445,8 @@ class RationsEditorView : public Steinberg::NativePlugView int mEntryCount[kChannelCount] = {0, 0, 0, 0}; std::vector mCaptureNames[kChannelCount]; int mActiveIndex = -1; // capture sounding in the ACTIVE channel; -1 = not reported yet + // The input-level lamp as last reported, kept only to tell a change from a repeat. + bool mInputLampLit = false; float mBankProgress = 0.0f; // Capability polling. The capture names are produced by the processor's worker threads, so diff --git a/products/rack/standalone/asiobackend.cpp b/products/rack/standalone/asiobackend.cpp index f09216f..cde1d96 100644 --- a/products/rack/standalone/asiobackend.cpp +++ b/products/rack/standalone/asiobackend.cpp @@ -52,7 +52,7 @@ namespace // The queue and event sizes, and the reasoning behind each, are the JACK backend's; they are the // same numbers because they answer the same question about the same plug-in. constexpr int32 kMaxInputParameters = 64; -constexpr int32 kMaxOutputParameters = 8; +constexpr int32 kMaxOutputParameters = AudioBackend::kFeedbackSlots; constexpr int32 kMaxEvents = 256; constexpr int kMidiStatusMask = 0xf0; diff --git a/products/rack/standalone/jackclient.cpp b/products/rack/standalone/jackclient.cpp index a66f549..d5be768 100644 --- a/products/rack/standalone/jackclient.cpp +++ b/products/rack/standalone/jackclient.cpp @@ -3,6 +3,9 @@ #include "jackclient.h" +#include "midilearn.h" +#include "rationsids.h" + #include "host/hostapp.h" #include "host/rtdenormal.h" @@ -32,9 +35,18 @@ namespace // its vector when addParameterData runs out of reserved queues // (public.sdk/source/vst/hosting/parameterchanges.cpp), which on this thread is a malloc. One // block can carry every knob the editor touched plus a burst of CC, so the input side is sized for -// far more than a person can produce and the output side for the five the plug-in publishes. +// far more than a person can produce. +// +// The output side is sized to the feedback slots it drains into, because that is the most distinct +// parameters this host can do anything with. It used to be 8, sized for "the five the plug-in +// publishes", which forgot the MIDI echoes: the amp also reports every parameter its learn table +// moved, one queue per distinct id. Each queue holds one point however often it is written, +// because addPoint replaces a point at the same sample offset and the amp writes them all at 0. constexpr int32 kMaxInputParameters = 64; -constexpr int32 kMaxOutputParameters = 8; +constexpr int32 kMaxOutputParameters = AudioBackend::kFeedbackSlots; +// The amp's own worst case: every feedback value plus an echo from every learn row at once. +static_assert(kFeedbackCount + kMidiLearnRowCount <= kMaxOutputParameters, + "a block in which every MIDI row fires would outgrow the output queue"); // One block of MIDI. A footswitch sends one message; this is sized for a controller sweeping a // whole bank of them, and anything past it is dropped rather than grown into. diff --git a/products/rack/standalone/wasapibackend.cpp b/products/rack/standalone/wasapibackend.cpp index e3e18cd..de04906 100644 --- a/products/rack/standalone/wasapibackend.cpp +++ b/products/rack/standalone/wasapibackend.cpp @@ -52,7 +52,7 @@ namespace // The same figures, for the same reasons, as the other two backends'. See jackclient.cpp. constexpr int32 kMaxInputParameters = 64; -constexpr int32 kMaxOutputParameters = 8; +constexpr int32 kMaxOutputParameters = AudioBackend::kFeedbackSlots; constexpr int32 kMaxEvents = 256; constexpr int kMidiStatusMask = 0xf0; diff --git a/products/rack/tools/panelrender.cpp b/products/rack/tools/panelrender.cpp index 5cc6eda..75e612d 100644 --- a/products/rack/tools/panelrender.cpp +++ b/products/rack/tools/panelrender.cpp @@ -63,6 +63,7 @@ const char *const kRequiredImages[] = { "cabinet", "dial", "led_on", + "led_green_on", "led_off", "switch_up_ring", "switch_down_ring", @@ -141,13 +142,14 @@ void drawToggle(Canvas &c, ImageCache &images, const geo::ToggleSpec &t, bool on //------------------------------------------------------------------------ void drawLed(Canvas &c, ImageCache &images, float cx, float cy, bool lit, - float r = static_cast(geo::kLedR)) + float r = static_cast(geo::kLedR), geo::LedColor color = geo::LedColor::Red) { const Rect dest(cx - r, cy - r, 2.0f * r, 2.0f * r); - if (cairo_surface_t *led = images.get(lit ? "led_on" : "led_off")) { + const bool green = color == geo::LedColor::Green; + if (cairo_surface_t *led = images.get(!lit ? "led_off" : (green ? "led_green_on" : "led_on"))) { c.drawImage(led, dest); } else { - c.setColor(lit ? 0xE02020 : 0x141414); + c.setColor(!lit ? 0x141414 : (green ? geo::kAccent : 0xE02020)); c.fillEllipse(dest); } } @@ -397,6 +399,9 @@ void renderHead(Canvas &c, ImageCache &images, SvgCache &icons) static_cast(geo::kIoKnobs[i].cx), static_cast(geo::kIoValueBaselineY)); } + // The input-level lamp, lit: the demo input meter above it is playing. + drawLed(c, images, static_cast(geo::kInputLampCX), static_cast(geo::kInputLampCY), + true, static_cast(geo::kInputLampR), geo::LedColor::Green); for (const geo::ButtonSpec &b : geo::kPageButtons) drawButton(c, b); @@ -850,6 +855,22 @@ bool auditHitBoxes() static_cast(geo::kStripColX0 + (i + 1) * geo::kStripColW), static_cast(geo::kStripCaptureY + geo::kStripCaptureDescent)}); + // The six dial readouts are click targets too, since clicking one opens it for typing. They + // share the bottom band with the switches and the page buttons, and the Input field sits + // beside the input meter's column, so they are exactly what this audit is for. Labelled by + // the dial's own legend, from the same table the editor hit-tests. + for (const geo::ValueField &f : geo::kValueFields) { + const char *what = "value field"; + for (const geo::KnobSpec &k : geo::kKnobs) + if (k.id == f.id) + what = k.label; + for (const geo::KnobSpec &k : geo::kIoKnobs) + if (k.id == f.id) + what = k.label; + boxes.push_back({what, static_cast(f.x), static_cast(f.y), + static_cast(f.x + f.w), static_cast(f.y + f.h)}); + } + // The two level meters are not clickable, but a control drawn on top of one is a control // drawn on top of the thing it is supposed to sit beside, so they are in the check as // obstacles. diff --git a/products/rack/tools/rations_midicheck.cpp b/products/rack/tools/rations_midicheck.cpp index 9a65678..82c290c 100644 --- a/products/rack/tools/rations_midicheck.cpp +++ b/products/rack/tools/rations_midicheck.cpp @@ -193,6 +193,10 @@ struct Block { // general form, because what a footswitch row echoes is a value it COMPUTED and the whole // point is to check which one. std::vector> echoes; + // How much of the output queue the block used: queues claimed, and the most points any one of + // them held. A host has to reserve both before the audio thread runs. + int outQueues = 0; + int maxPoints = 0; }; // What the plug-in said it did to one parameter this block, if it said anything. @@ -263,6 +267,12 @@ struct Harness { b.echoes.clear(); processor->process(data); + b.outQueues = outParamChanges.getParameterCount(); + b.maxPoints = 0; + for (int32 i = 0; i < b.outQueues; ++i) + if (Vst::IParamValueQueue *q = outParamChanges.getParameterData(i)) + b.maxPoints = std::max(b.maxPoints, static_cast(q->getPointCount())); + // The plug-in reporting a parameter it changed by itself, and the hidden read-only // parameter that says which channel is actually SOUNDING - the request and the answer, // which are not the same thing while a switch is being held. @@ -1253,6 +1263,57 @@ int main(int argc, char **argv) } } + // --- 8. every row in one block ------------------------------------------------------------- + // + // A host reserves its output queue before the audio thread runs, because addParameterData + // grows it with `new` once the reserve is used up (public.sdk/source/vst/hosting/ + // parameterchanges.cpp). What this plug-in can put in it in one block is every feedback value + // plus an echo of every parameter its learn table moved, so that is measured here: every row + // taught its own CC, and every CC pressed at once. The standalones assert the same bound at + // compile time; this is the half that says the plug-in really stays inside it. They used to + // reserve 8, which a footswitch burst outgrew. + printf("every row in one block\n"); + { + constexpr int kFirstCc = 90; + for (int row = 0; row < kMidiLearnRowCount; ++row) { + sendMessage(hostContext, component, kMsgMidiLearn, &row); + Block teach; + teach.params.push_back(cc(kFirstCc + row, 127)); + rig.run(teach); + } + Block release; + for (int row = 0; row < kMidiLearnRowCount; ++row) + release.params.push_back(cc(kFirstCc + row, 0)); + rig.run(release); + Block all; + for (int row = 0; row < kMidiLearnRowCount; ++row) + all.params.push_back(cc(kFirstCc + row, 127)); + rig.run(all); + + // Rows can share a target - every channel row sets kChannelId - and the queue holds one + // entry per DISTINCT id, so that is what the count is compared with. + std::vector targets; + for (const MidiLearnTarget &row : kMidiLearnRows) + if (std::find(targets.begin(), targets.end(), row.param) == targets.end()) + targets.push_back(row.param); + bool everyTarget = true; + for (Vst::ParamID id : targets) { + double v = 0.0; + everyTarget = everyTarget && echoOf(all, id, v); + } + check(everyTarget, "every row fires in the same block"); + + char detail[96]; + snprintf(detail, sizeof detail, "%d queues for %d feedback values and %d moved parameters", + all.outQueues, kFeedbackCount, static_cast(targets.size())); + check(all.outQueues == kFeedbackCount + static_cast(targets.size()), + "one output queue per feedback value and per moved parameter", detail); + check(all.outQueues <= kFeedbackCount + kMidiLearnRowCount, + "... which is inside the reserve the standalones make", detail); + check(all.maxPoints == 1, "every output queue holds a single point"); + printf(" measured: %s\n", detail); + } + processor->setProcessing(false); component->setActive(false); diff --git a/products/rack/tools/rations_rtcheck.cpp b/products/rack/tools/rations_rtcheck.cpp index c3d1d8f..d1f6c95 100644 --- a/products/rack/tools/rations_rtcheck.cpp +++ b/products/rack/tools/rations_rtcheck.cpp @@ -19,7 +19,8 @@ // burst is still the audio thread: it feeds the incoming channel out of the input ring inside // the same process() call, so every rule that applies to the steady state applies to it. This // is also where a ring read, a fade buffer or a chunk stage that was sized wrong would show -// up, because those only run during a switch. +// up, because those only run during a switch. The input-level lamp runs in the same loop, +// fed the gain soundingInputGain() reads across the switch, as the processor feeds it. // 5. The cabinet stage with both IR slots filled and the blend dial sweeping. AudioDSPTools // sizes an ImpulseResponse's history and output buffers on its FIRST Process call, which for // an IR loaded mid-session would be a malloc on the audio thread. The plug-in avoids that by @@ -34,6 +35,7 @@ #include "channelrack.h" #include "crossfadeengine.h" #include "engineconfig.h" +#include "inputlevellamp.h" #include "irblend.h" #include "midilearn.h" #include "modelbank.h" @@ -201,6 +203,9 @@ int main(int argc, char **argv) return 1; } + Rations::InputLevelLamp lamp; + lamp.reset(Rations::kNativeSampleRate); + // The stomp period is deliberately shorter than a whole switch takes, so some requests // land mid-catch-up and some mid-fade. Both are the paths that only exist here. auto drive = [&](int blocks) { @@ -220,15 +225,17 @@ int main(int argc, char **argv) 0.25 + 0.5 * std::fabs(std::fmod(t, 2.0) - 1.0)); rack.setLevel(Rations::kChannelOd1, 4.0 - 3.0 * std::fabs(std::fmod(t, 2.0) - 1.0)); rack.requestChannel(want); + lamp.process(in.data(), kBlock, rack.soundingInputGain()); rack.processNative(&ip, &op, kBlock); } }; drive(8); // warm anything lazily sized before the count starts - printf("counting channel rack, stomping between two channels, trims moving\n"); + printf("counting channel rack, stomping between two channels, trims moving, lamp " + "running\n"); allocation_tracking::run_allocation_test_no_allocations( nullptr, [&] { drive(200); }, nullptr, - "channel rack, stomping between two channels, trims moving"); + "channel rack, stomping between two channels, trims moving, lamp running"); rack.stop(); rack.releaseBanks(); diff --git a/products/rations/CMakeLists.txt b/products/rations/CMakeLists.txt index 707beb7..c3e2436 100644 --- a/products/rations/CMakeLists.txt +++ b/products/rations/CMakeLists.txt @@ -503,6 +503,8 @@ set(NAMP_IMG_FILES img/cabinet.png img/dial.png img/led_on.png + # The input-level lamp, lit. Generated from led-on-base.png by gui/make_assets.sh. + img/led_green_on.png img/led_off.png img/switch_up_ring.png img/switch_down_ring.png @@ -1087,6 +1089,34 @@ namp_link_whole_dsp(rations_switchcheck) target_compile_features(rations_switchcheck PRIVATE cxx_std_20) target_compile_options(rations_switchcheck PRIVATE -Wall) +# --------------------------------------------------------------------------- +# rations_lampcheck — the offline proof of the input-level lamp: the detector's +# window and holds, and the calibration gain it is handed, checked against the +# level each capture states, through one engine and through the shipped +# ChannelRack across a channel switch. Its last section drives the BUILT +# BUNDLE, because the tap point and the output parameter are facts about the +# plug-in a host loads, so it carries the module loader as well as the engine. +# --------------------------------------------------------------------------- +add_executable(rations_lampcheck + ${NAMP_CORE_DIR}/tools/rations_lampcheck.cpp + ${RATIONS_MODULE_LOADER} + ${VST3_SDK_DIR}/public.sdk/source/vst/hosting/plugprovider.cpp + ${VST3_SDK_DIR}/public.sdk/samples/vst-hosting/editorhost/source/usediids.cpp + ${NAMP_CORE_DIR}/capturesource.cpp + ${NAMP_CORE_DIR}/modelbank.cpp + ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp + ${NAMP_CORE_DIR}/channelrack.cpp + ${NAMP_CORE_DIR}/platform/respath.cpp + ${NAMP_CORE_DIR}/gfx/resourcestore.cpp +) +target_include_directories(rations_lampcheck PRIVATE ${NAMP_PRODUCT_DIR}/src ${NAMP_CORE_INCLUDES} ${VST3_SDK_DIR}) +namp_link_whole_dsp(rations_lampcheck) +target_link_libraries(rations_lampcheck PRIVATE sdk_hosting ${RATIONS_MODULE_LOADER_LIBS}) +target_compile_features(rations_lampcheck PRIVATE cxx_std_20) +target_compile_options(rations_lampcheck PRIVATE -Wall) +add_dependencies(rations_lampcheck Rations) + # --------------------------------------------------------------------------- # rations_racecheck - the ThreadSanitizer gate for the prime worker. # diff --git a/products/rations/docs/macos-testing.md b/products/rations/docs/macos-testing.md index bf26b0e..7f786d9 100644 --- a/products/rations/docs/macos-testing.md +++ b/products/rations/docs/macos-testing.md @@ -123,6 +123,16 @@ than a person with a pedal. needed explicit work; on macOS it should be free, and this confirms it.) - [ ] Right-click a control: it should return to its default. **Control-click should do the same thing**, because that is the Mac gesture for it. +- [ ] **Double-click a knob** (Bass, say): it should jump back to its default + (5.0 for Bass). A third quick click should not do it again. +- [ ] Drag a knob while holding **Shift**, then while holding **Command**: either + one should make it move about ten times more slowly. (Not Control — on a + Mac, Control-click is a right-click.) The mouse wheel or a two-finger + scroll over a knob should also step ten times finer with Shift held. +- [ ] **Click the number under Bass** (or Threshold, Middle, Treble, Input, + Output). It should turn into a box with the number highlighted. Type + `7.5` and press Return: the knob should move to 7.5. Try `7,5` too — it + should do the same. Escape should leave the value as it was. - [ ] All four page buttons work, and the window **changes shape** each time without changing apparent size. - [ ] Resize the window by dragging its corner. The panel should scale with it diff --git a/products/rations/gui/make_assets.sh b/products/rations/gui/make_assets.sh index 09d65db..8e6edf8 100755 --- a/products/rations/gui/make_assets.sh +++ b/products/rations/gui/make_assets.sh @@ -106,6 +106,33 @@ need "$ART_DIR/led-off-base.png" magick "$ART_DIR/led-on-base.png" -strip -depth 8 "PNG32:$OUT_DIR/led_on.png" magick "$ART_DIR/led-off-base.png" -strip -depth 8 "PNG32:$OUT_DIR/led_off.png" +# ---- led_green_on.png: the input-level lamp, lit --------------------------- +# The red LED recoloured to ACCENT rather than drawn again, so the two lamps +# share one shape, rim and size. The red LED's green and blue are a fixed tenth +# of its red everywhere, so the RED channel alone carries all of its shading: +# it is levelled so the brightest opaque red becomes 1 (that maximum is measured +# here, not written in, because a hard-coded 234 would quietly mis-tint a +# re-exported source), turned back into colour (a separated channel is a +# greyscale image, and colourising one leaves it grey), multiplied by ACCENT, +# and given the source's own alpha back. The centre therefore lands on ACCENT +# exactly, and the check below says so. The white point is passed as a PERCENTAGE because -level reads a bare +# number in QuantumRange units, which is 65535 on a Q16 build. The lamp's off +# state is led_off.png, shared with the channel LEDs. +RED_MAX_PCT="$(magick "$ART_DIR/led-on-base.png" \ + \( +clone -alpha extract -threshold 50% \) -alpha off \ + -compose multiply -composite -channel R -separate -format "%[fx:maxima*100]" info:)" +magick "$ART_DIR/led-on-base.png" \ + \( +clone -alpha off -channel R -separate +channel -level "0,${RED_MAX_PCT}%" \ + -colorspace sRGB \ + \( +clone -fill "$ACCENT" -colorize 100 \) -compose multiply -composite \) \ + +swap -compose copyalpha -composite \ + -strip -depth 8 "PNG32:$OUT_DIR/led_green_on.png" +green_centre="$(magick "$OUT_DIR/led_green_on.png" -format "%[hex:p{64,64}]" info:)" +if [ "#${green_centre:0:6}" != "$ACCENT" ]; then + echo "make_assets: led_green_on.png's centre is #${green_centre}, not ACCENT $ACCENT." >&2 + exit 1 +fi + # ---- generated art -------------------------------------------------------- ./make_knob.sh ./make_switch.sh diff --git a/products/rations/lv2/rationslv2.h b/products/rations/lv2/rationslv2.h index 931a750..7f330b4 100644 --- a/products/rations/lv2/rationslv2.h +++ b/products/rations/lv2/rationslv2.h @@ -204,16 +204,11 @@ inline constexpr Steinberg::Vst::ParamID kFixedControlIds[] = { inline constexpr int kFixedControlCount = static_cast(sizeof(kFixedControlIds) / sizeof(kFixedControlIds[0])); -// The feedback block, as control OUTPUT ports. Every one of these needs a ui:portNotification -// block in the TTL or it never reaches the UI: the UI extension says a host calls port_event() -// for control port INPUTS by default, so without those declarations the meters, the bank progress -// bar and the capture readout are permanently dead while the plug-in builds, loads and otherwise -// works perfectly. -inline constexpr Steinberg::Vst::ParamID kFeedbackIds[] = { - kInputMeterId, kOutputMeterId, kBankProgressId, kActiveIndexId, kActiveChannelId, -}; -inline constexpr int kFeedbackCount = - static_cast(sizeof(kFeedbackIds) / sizeof(kFeedbackIds[0])); +// The feedback block, as control OUTPUT ports: one per entry of kFeedbackIds (rationsids.h), in +// that list's order. Every one of these needs a ui:portNotification block in the TTL or it never +// reaches the UI: the UI extension says a host calls port_event() for control port INPUTS by +// default, so without those declarations the meters, the bank progress bar and the capture readout +// are permanently dead while the plug-in builds, loads and otherwise works perfectly. inline constexpr int kControlInCount = kFixedControlCount + kPedalParamCount; @@ -224,6 +219,36 @@ inline constexpr std::uint32_t kPortFeedbackFirst = kPortControlFirst + kControl inline constexpr std::uint32_t kPortLatency = kPortFeedbackFirst + kFeedbackCount; inline constexpr std::uint32_t kPortCount = kPortLatency + 1; +// What each feedback port is called, in kFeedbackIds' order. Kept here, beside the port layout, so +// that the TTL generator writes from it and rations_lv2check reads the installed bundle back +// against the same table. +// +// `optional` marks a port added after the bundle first shipped, and it is not a free choice. LV2's +// versioning rules (the lv2:minorVersion documentation in the LV2 core specification) let a new +// port be added under the same plug-in URI only "if and only if" it is lv2:connectionOptional and +// the minor version is incremented, and they require that increment too whenever an existing +// port's index moves, as the latency port's does each time this block grows. A host may then leave +// such a port unconnected (lv2.h: connect_port() must be called before run() "unless that port is +// lv2:connectionOptional"); the wrapper writes a feedback port only when it was connected, so +// that costs nothing. The minor-version half of the rule is met by the release that first carries +// the port, not by this table: kLv2MinorVersion above follows the project's VERSION file. +struct FeedbackPort { + const char *symbol; + const char *name; + bool optional; +}; +inline constexpr FeedbackPort kFeedbackPorts[] = { + {"input_meter", "Input Meter", false}, + {"output_meter", "Output Meter", false}, + {"bank_progress", "Bank Progress", false}, + {"active_capture", "Active Capture", false}, + {"active_channel", "Active Channel", false}, + // Added in the release after 0.6.0, for the input-level lamp. + {"input_level_ok", "Input Level OK", true}, +}; +static_assert(sizeof(kFeedbackPorts) / sizeof(kFeedbackPorts[0]) == kFeedbackCount, + "one LV2 symbol and name per entry of kFeedbackIds"); + // The ParamID a control-input port carries. Out of range returns 0, which is not a ParamID this // plug-in uses. inline constexpr Steinberg::Vst::ParamID controlPortParam(int index) diff --git a/products/rations/resources/img/led_green_on.png b/products/rations/resources/img/led_green_on.png new file mode 100644 index 0000000..39ceac9 Binary files /dev/null and b/products/rations/resources/img/led_green_on.png differ diff --git a/products/rations/scripts/editor-drive.c b/products/rations/scripts/editor-drive.c index 91bc47e..71a3334 100644 --- a/products/rations/scripts/editor-drive.c +++ b/products/rations/scripts/editor-drive.c @@ -64,6 +64,17 @@ static void wheel(int clicks) } } +// Hold or release Shift around a pointer gesture: the editor's fine control. Shift rather than +// Ctrl because both are fine control on this platform and Shift is the one a window manager is +// least likely to have bound to a pointer gesture of its own. +static void holdShift(int down) +{ + const KeyCode code = XKeysymToKeycode(display, XK_Shift_L); + XTestFakeKeyEvent(display, code, down ? True : False, CurrentTime); + XFlush(display); + usleep(30000); +} + // Resize the host's TOP-LEVEL window, which is what makes the host call the plug-in's // checkSizeConstraint and then onSize. Resizing the plug-in's own child window directly would // change some pixels and tell the plug-in nothing, so the editor would never re-lay-out and the @@ -149,10 +160,12 @@ static void typeString(const char *text) int main(int argc, char **argv) { if (argc < 4) { - fprintf(stderr, "usage: editor-drive [dx dy]\n" - " editor-drive wheel \n" - " editor-drive resize \n" - " editor-drive \n"); + fprintf(stderr, + "usage: editor-drive [dx dy]\n" + " editor-drive \n" + " editor-drive focus -\n" + " editor-drive resize \n" + " editor-drive \n"); return 2; } display = XOpenDisplay(NULL); @@ -162,11 +175,35 @@ int main(int argc, char **argv) } window = (Window)strtoul(argv[2], NULL, 0); + // Who holds the X input focus right now. A field takes it while open and must hand it back + // when it closes, and the only way to see that it did is to ask the server. + if (strcmp(argv[1], "focus") == 0) { + Window focus = None; + int revert = 0; + XGetInputFocus(display, &focus, &revert); + printf("0x%lx\n", (unsigned long)focus); + XCloseDisplay(display); + return 0; + } if (strcmp(argv[1], "type") == 0) { typeString(argv[3]); XCloseDisplay(display); return 0; } + // `press` is `key` WITHOUT the focus move: it leaves the input focus wherever the editor put + // it, which is the only way to test that the editor hands the focus back by itself. `key` + // moves it first because it predates the editor taking the focus on its own. + if (strcmp(argv[1], "press") == 0) { + const KeySym sym = XStringToKeysym(argv[3]); + if (sym == NoSymbol) { + fprintf(stderr, "editor-drive: unknown keysym '%s'\n", argv[3]); + XCloseDisplay(display); + return 2; + } + pressKeysym(sym); + XCloseDisplay(display); + return 0; + } if (strcmp(argv[1], "key") == 0) { XSetInputFocus(display, window, RevertToParent, CurrentTime); XFlush(display); @@ -201,15 +238,20 @@ int main(int argc, char **argv) const int x = atoi(argv[3]); const int y = atoi(argv[4]); - if (strcmp(argv[1], "wheel") == 0) { + if (strcmp(argv[1], "wheel") == 0 || strcmp(argv[1], "swheel") == 0) { if (argc < 6) { fprintf(stderr, "editor-drive: wheel needs a click count\n"); XCloseDisplay(display); return 2; } + const int shifted = argv[1][0] == 's'; moveTo(x, y); usleep(50000); + if (shifted) + holdShift(1); wheel(atoi(argv[5])); + if (shifted) + holdShift(0); XCloseDisplay(display); return 0; } @@ -221,19 +263,34 @@ int main(int argc, char **argv) moveTo(x, y); button(1, 1); button(0, 1); - } else if (strcmp(argv[1], "drag") == 0 && argc >= 7) { + } else if (strcmp(argv[1], "dclick") == 0) { + // Two presses 80 ms apart at one spot: well inside the editor's 400 ms, and slow enough + // that each is a separate event on the server's clock rather than one burst. + moveTo(x, y); + button(1, 1); + button(0, 1); + usleep(80000); + button(1, 1); + button(0, 1); + } else if ((strcmp(argv[1], "drag") == 0 || strcmp(argv[1], "sdrag") == 0) && argc >= 7) { // Twenty steps with a real pause between them, because the editor coalesces motion and // repaints on a timer: a drag delivered as one jump exercises the hit test and nothing // else, and would not show a readout that is only drawn while the button is held. + // sdrag holds Shift for the whole gesture, which is the editor's fine control. const int dx = atoi(argv[5]); const int dy = atoi(argv[6]); + const int shifted = argv[1][0] == 's'; moveTo(x, y); + if (shifted) + holdShift(1); button(1, 1); for (int i = 1; i <= 20; ++i) { moveTo(x + dx * i / 20, y + dy * i / 20); usleep(60000); } button(0, 1); + if (shifted) + holdShift(0); } else { fprintf(stderr, "editor-drive: unknown command '%s'\n", argv[1]); XCloseDisplay(display); diff --git a/products/rations/scripts/editor-drive.sh b/products/rations/scripts/editor-drive.sh index aa04663..a9627c0 100755 --- a/products/rations/scripts/editor-drive.sh +++ b/products/rations/scripts/editor-drive.sh @@ -52,6 +52,9 @@ # scripts/editor-drive.sh click 251 226 shot out.png # scripts/editor-drive.sh rclick 320 200 shot out.png # the second button # scripts/editor-drive.sh drag 251 226 0 -70 shot out.png # photographed mid-drag +# scripts/editor-drive.sh sdrag 251 226 0 -70 shot out.png # the same, with Shift held (fine) +# scripts/editor-drive.sh dclick 721 203 shot out.png # double-click: reset to default +# scripts/editor-drive.sh swheel 721 203 3 focus # fine wheel; who has the focus # scripts/editor-drive.sh click 140 110 type "JCM800" key Return shot out.png # scripts/editor-drive.sh --size 640x460 click 320 200 shot cab.png # scripts/editor-drive.sh click 886 106 resize 640 420 shot short.png # the settings page, @@ -148,19 +151,29 @@ while [ "$#" -gt 0 ]; do echo " rclick $2,$3" sleep 1 shift 3 ;; - drag) + dclick) + # A double-click: the reset gesture on a dial, a slider or a pedal knob. + "$poke" dclick "$window" "$2" "$3" + echo " dclick $2,$3" + sleep 1 + shift 3 ;; + focus) + # Print who holds the X input focus: an open field takes it and must give it back. + echo " focus $("$poke" focus "$window" -) (editor window $window)" + shift 1 ;; + drag|sdrag) # Photograph from here while the drag runs in the background: the readout exists only - # for as long as the button is down. - "$poke" drag "$window" "$2" "$3" "$4" "$5" & + # for as long as the button is down. sdrag holds Shift throughout, for fine control. + "$poke" "$1" "$window" "$2" "$3" "$4" "$5" & drag_pid=$! sleep 1 if [ "${6:-}" = "shot" ]; then import -window "$window" "$7" - echo " drag $2,$3 by $4,$5 -> $7 (mid-drag)" + echo " $1 $2,$3 by $4,$5 -> $7 (mid-drag)" wait "$drag_pid" 2>/dev/null shift 7 else - echo " drag $2,$3 by $4,$5" + echo " $1 $2,$3 by $4,$5" wait "$drag_pid" 2>/dev/null shift 5 fi ;; @@ -169,14 +182,16 @@ while [ "$#" -gt 0 ]; do echo " type '$2'" sleep 1 shift 2 ;; - key) - "$poke" key "$window" "$2" - echo " key $2" + key|press) + # `press` leaves the input focus alone; `key` moves it to the window first. Use press + # when what is being tested is who holds the focus afterwards. + "$poke" "$1" "$window" "$2" + echo " $1 $2" sleep 1 shift 2 ;; - wheel) - "$poke" wheel "$window" "$2" "$3" "$4" - echo " wheel $2,$3 x$4" + wheel|swheel) + "$poke" "$1" "$window" "$2" "$3" "$4" + echo " $1 $2,$3 x$4" sleep 1 shift 4 ;; resize) diff --git a/products/rations/src/geometry.h b/products/rations/src/geometry.h index 2a8bbe8..439ffbc 100644 --- a/products/rations/src/geometry.h +++ b/products/rations/src/geometry.h @@ -441,6 +441,10 @@ constexpr int kLedR = 9; constexpr int kToggleToLedGap = 6; constexpr int kLedCY = kToggleCY + kToggleH / 2 + kToggleToLedGap + kLedR; // 292 constexpr int kLedCount = 4; +// Which lamp an LED is when lit. Red is every LED the panel had before the input-level lamp, which +// is the one green: led_green_on.png, the red art recoloured to kAccent by gui/make_assets.sh. Both +// share led_off.png, so an unlit lamp does not say which colour it would be. +enum class LedColor { Red, Green }; // The gaps are named rather than folded into literal centres so the arithmetic // is checkable and so a part that grows fails the static_asserts below instead @@ -863,6 +867,30 @@ constexpr KnobSpec kIoKnobs[2] = { {kOutputGainId, kSideCXR, kIoKnobCY, kIoKnobR, "Output", "dB"}, }; +// The input-level lamp: green when the peak the sounding capture hears is in the +// window inputlevellamp.h describes. To the right of the Input dial, at the +// dial's own height, which is the author's choice between two rendered +// candidates (the other was beside the Input legend, where Amped puts its LED): +// the lamp sits next to the control that fixes it. The utility row's size, not +// the channel lamps': it is an indicator, set while a rig is put together, like +// BYPASS. Nothing else is in this band between the dial and the first channel. +constexpr int kInputLampR = kTopLedR; +constexpr int kInputLampGap = 8; // from the dial's edge to the lamp's +constexpr int kInputLampCX = kSideCXL + kIoKnobR + kInputLampGap + kInputLampR; // 134 +constexpr int kInputLampCY = kIoKnobCY; // 275 +static_assert(kInputLampCX - kInputLampR > kSideCXL + kIoKnobR, + "the input-level lamp is drawn on the Input dial"); +static_assert(kInputLampCY - kInputLampR > kIoLabelBaselineY + kIoLabelSize / 4, + "the input-level lamp has come up onto the Input legend"); +static_assert(kInputLampCY + kInputLampR < kIoValueBaselineY - kKnobValueSize, + "the input-level lamp has come down onto the Input value row"); +static_assert(kInputLampCX + kInputLampR + 8 < kToggles[0].cx - kToggleHitW / 2, + "the input-level lamp has reached the first channel switch's click area"); +static_assert(kInputLampCX + kInputLampR + 8 < kKnobs[0].cx - kKnobR, + "the input-level lamp has reached the first channel dial"); +static_assert(kInputLampCY + kInputLampR < kFaceB - 8, + "the input-level lamp has reached the faceplate's edge"); + // --- Page buttons, bottom-centre-right of the faceplate --------------------- // ButtonSpec and kPageButtonH are declared further up, with the settings button: // that one is drawn in the same style but has to be declared before the Slim @@ -903,6 +931,63 @@ constexpr ButtonSpec kPageButtons[kPageButtonCount] = { static_assert(kLedCY == kPageButtonY + kPageButtonH / 2, "the channel lamps no longer line up with the page buttons"); +// --- Typed values: the six readouts are also where a value is entered -------- +// Clicking a dial's value row opens a text field over it, seeded with the +// value and selected, which is the parent plug-in's IVKnobControl built with +// valueIsEditable and is the second way to reach those six controls, never the +// only one (whether keys reach an embedded view at all is the host's business). +// The four channel dials have no value row — their band is the bat switches' — +// and what they would offer to type is a capture name, so they are not here. +// +// The box is the CLICK target and the field drawn while editing, one rect for +// both so the two cannot drift. It hangs off the readout's own baseline, 13 +// above and 6 below, so the text does not move as the field opens; 64 wide is +// room for "-100.0" at kKnobValueSize with the caret, and stops 30 units short +// of the next column at the 94-unit pitch. +struct ValueField { + Steinberg::Vst::ParamID id; + int x, y, w, h; +}; +constexpr int kValueFieldW = 64; +constexpr int kValueFieldAscent = 13; +constexpr int kValueFieldDescent = 6; +constexpr ValueField valueField(const KnobSpec &k, int baselineY) +{ + return {k.id, k.cx - kValueFieldW / 2, baselineY - kValueFieldAscent, kValueFieldW, + kValueFieldAscent + kValueFieldDescent}; +} +constexpr int kValueFieldCount = 6; +constexpr ValueField kValueFields[kValueFieldCount] = { + valueField(kKnobs[4], kKnobCY + kKnobValueDY), // Threshold + valueField(kKnobs[5], kKnobCY + kKnobValueDY), // Bass + valueField(kKnobs[6], kKnobCY + kKnobValueDY), // Middle + valueField(kKnobs[7], kKnobCY + kKnobValueDY), // Treble + valueField(kIoKnobs[0], kIoValueBaselineY), // Input + valueField(kIoKnobs[1], kIoValueBaselineY), // Output +}; +// A dial is hit-tested as its own circle, so a box that reached up into one +// would take a drag's first click away from it. +static_assert(kValueFields[0].y > kKnobCY + kKnobR, "a value field reaches up into its dial"); +static_assert(kValueFields[4].y > kIoKnobCY + kIoKnobR, + "the Input/Output value fields reach up into their dials"); +static_assert(kValueFieldW < kKnobPitch, "two neighbouring value fields touch"); +// Below the four head readouts is the page button row, which spans Bass to +// Treble; the Threshold field's left-hand neighbour is the last channel +// switch's (generous) click target. +static_assert(kValueFields[0].y + kValueFields[0].h < kPageButtonY, + "the value fields have come down onto the page buttons"); +static_assert(kValueFields[0].x > kToggles[kToggleCount - 1].cx + kToggleHitW / 2, + "the Threshold value field reaches into the last channel switch's click area"); +// The Input field's neighbour is the first channel switch; the Output field's +// is the end of the page button row, which shares its band. +static_assert(kValueFields[4].x + kValueFieldW < kToggles[0].cx - kToggleHitW / 2, + "the Input value field reaches into the first channel switch's click area"); +static_assert(kValueFields[5].x > + kPageButtons[kPageButtonCount - 1].x + kPageButtons[kPageButtonCount - 1].w, + "the Output value field reaches into the page buttons"); +static_assert(kValueFields[4].y + kValueFields[4].h < kFaceB, + "the Input/Output value fields have reached the faceplate's edge"); + // --- The status strip, under the faceplate ---------------------------------- // WHAT THE STRIP IS FOR: the two things a player could not see without leaving // this page. Which capture each of the four banks is on, and which pedals are diff --git a/products/rations/src/platform/macplugview.h b/products/rations/src/platform/macplugview.h index 33edebd..1d3c31e 100644 --- a/products/rations/src/platform/macplugview.h +++ b/products/rations/src/platform/macplugview.h @@ -88,6 +88,7 @@ #include "public.sdk/source/vst/vsteditcontroller.h" #include "pluginterfaces/gui/iplugview.h" +#include "platform/pointermods.h" #include @@ -126,11 +127,11 @@ class MacPlugView : public Vst::EditorView // the subclass contract and nothing in src/ outside this pair calls them. void macTick(); void macDraw(void *cgContext); - void macMouseDown(double x, double y, int button); + void macMouseDown(double x, double y, int button, unsigned mods, bool doubleClick); void macMouseUp(double x, double y, int button); - void macMouseMove(double x, double y); + void macMouseMove(double x, double y, unsigned mods); void macMouseLeave(); - void macMouseWheel(double x, double y, double deltaY); + void macMouseWheel(double x, double y, double deltaY, unsigned mods); bool macKeyDown(char16 key, int16 keyCode, int16 modifiers); void macFocusLost(); void macFrameChanged(double pointW, double pointH); @@ -155,25 +156,28 @@ class MacPlugView : public Vst::EditorView // Buttons are X button numbers (1 = left, 2 = middle, 3 = right) on this // platform too: the numbering is part of the hook contract that all three // platform bases honour, so the editor above never has to know which one it - // is running on. Wheel steps arrive as delta +1 (up) or -1 (down). - virtual void onMouseDown(int x, int y, int button) + // is running on. Wheel steps arrive as delta +1 (up) or -1 (down). `mods` is + // a PointerMod mask (platform/pointermods.h), and `doubleClick` is set on the + // second press of a pair — AppKit counts clicks itself, so this one is read + // from the event rather than derived as the other two derive theirs. + virtual void onMouseDown(int x, int y, int button, unsigned mods, bool doubleClick) { - (void)x, (void)y, (void)button; + (void)x, (void)y, (void)button, (void)mods, (void)doubleClick; } virtual void onMouseUp(int x, int y, int button) { (void)x, (void)y, (void)button; } - virtual void onMouseMove(int x, int y) + virtual void onMouseMove(int x, int y, unsigned mods) { - (void)x, (void)y; + (void)x, (void)y, (void)mods; } virtual void onMouseLeave() { } - virtual void onMouseWheel(int x, int y, int delta) + virtual void onMouseWheel(int x, int y, int delta, unsigned mods) { - (void)x, (void)y, (void)delta; + (void)x, (void)y, (void)delta, (void)mods; } // Keyboard, taken from the PLATFORM view rather than handed in by the host. Return true if diff --git a/products/rations/src/platform/macplugview.mm b/products/rations/src/platform/macplugview.mm index 1708fdd..0472b16 100644 --- a/products/rations/src/platform/macplugview.mm +++ b/products/rations/src/platform/macplugview.mm @@ -106,6 +106,32 @@ return mods; } +//------------------------------------------------------------------------ +// The pointer's fine-adjust keys, as the editor's PointerMod mask. Shift is Shift; the second +// key is COMMAND, which is iPlug2's own mapping for its mouse modifiers here (IGraphicsMac_view.mm, +// -getMouseLeft:, builds IMouseMod's `C` from NSCommandKeyMask) and the only one that can work: +// Control turns a left click into a right one (see -mouseDown:), so it cannot also mean "fine". +static unsigned pointerModsFromFlags(NSEventModifierFlags flags) +{ + unsigned mods = 0; + if (flags & NSEventModifierFlagShift) + mods |= Steinberg::kPointerShift; + if (flags & NSEventModifierFlagCommand) + mods |= Steinberg::kPointerControl; + return mods; +} + +//------------------------------------------------------------------------ +// AppKit counts clicks itself, so a double-click is read rather than derived: VSTGUI's own +// NSViewFrame::onMouseDown passes [theEvent clickCount] straight through. It is taken as every +// EVEN count rather than exactly 2, which pairs presses the way the X11 and Win32 views do — a +// third press starts a new pair, and the fourth completes it. +static bool isDoubleClick(NSEvent *event) +{ + const NSInteger count = [event clickCount]; + return count >= 2 && (count % 2) == 0; +} + //------------------------------------------------------------------------ // The Objective-C view. // @@ -274,14 +300,15 @@ - (void)mouseDown:(NSEvent *)event const NSPoint p = [self localPoint:event]; mLeftIsRight = ([event modifierFlags] & NSEventModifierFlagControl) ? YES : NO; if (mOwner) - mOwner->macMouseDown(p.x, p.y, mLeftIsRight ? kButtonRight : kButtonLeft); + mOwner->macMouseDown(p.x, p.y, mLeftIsRight ? kButtonRight : kButtonLeft, + pointerModsFromFlags([event modifierFlags]), isDoubleClick(event)); } - (void)mouseDragged:(NSEvent *)event { const NSPoint p = [self localPoint:event]; if (mOwner) - mOwner->macMouseMove(p.x, p.y); + mOwner->macMouseMove(p.x, p.y, pointerModsFromFlags([event modifierFlags])); } - (void)mouseUp:(NSEvent *)event @@ -297,14 +324,15 @@ - (void)rightMouseDown:(NSEvent *)event { const NSPoint p = [self localPoint:event]; if (mOwner) - mOwner->macMouseDown(p.x, p.y, kButtonRight); + mOwner->macMouseDown(p.x, p.y, kButtonRight, pointerModsFromFlags([event modifierFlags]), + isDoubleClick(event)); } - (void)rightMouseDragged:(NSEvent *)event { const NSPoint p = [self localPoint:event]; if (mOwner) - mOwner->macMouseMove(p.x, p.y); + mOwner->macMouseMove(p.x, p.y, pointerModsFromFlags([event modifierFlags])); } - (void)rightMouseUp:(NSEvent *)event @@ -318,14 +346,15 @@ - (void)otherMouseDown:(NSEvent *)event { const NSPoint p = [self localPoint:event]; if (mOwner) - mOwner->macMouseDown(p.x, p.y, kButtonMiddle); + mOwner->macMouseDown(p.x, p.y, kButtonMiddle, pointerModsFromFlags([event modifierFlags]), + isDoubleClick(event)); } - (void)otherMouseDragged:(NSEvent *)event { const NSPoint p = [self localPoint:event]; if (mOwner) - mOwner->macMouseMove(p.x, p.y); + mOwner->macMouseMove(p.x, p.y, pointerModsFromFlags([event modifierFlags])); } - (void)otherMouseUp:(NSEvent *)event @@ -344,7 +373,7 @@ - (void)mouseMoved:(NSEvent *)event { const NSPoint p = [self localPoint:event]; if (mOwner) - mOwner->macMouseMove(p.x, p.y); + mOwner->macMouseMove(p.x, p.y, pointerModsFromFlags([event modifierFlags])); } - (void)mouseExited:(NSEvent *)event @@ -363,7 +392,7 @@ - (void)scrollWheel:(NSEvent *)event { const NSPoint p = [self localPoint:event]; if (mOwner) - mOwner->macMouseWheel(p.x, p.y, [event deltaY]); + mOwner->macMouseWheel(p.x, p.y, [event deltaY], pointerModsFromFlags([event modifierFlags])); } //------------------------------------------------------------------------ @@ -967,9 +996,9 @@ - (void)viewDidChangeBackingProperties //------------------------------------------------------------------------ // AppKit hands over points; the hook set is in device pixels. This is the third // of the four conversion sites named at the top of macplugview.h. -void MacPlugView::macMouseDown(double x, double y, int button) +void MacPlugView::macMouseDown(double x, double y, int button, unsigned mods, bool doubleClick) { - onMouseDown(toPixels(x), toPixels(y), button); + onMouseDown(toPixels(x), toPixels(y), button, mods, doubleClick); } void MacPlugView::macMouseUp(double x, double y, int button) @@ -977,9 +1006,9 @@ - (void)viewDidChangeBackingProperties onMouseUp(toPixels(x), toPixels(y), button); } -void MacPlugView::macMouseMove(double x, double y) +void MacPlugView::macMouseMove(double x, double y, unsigned mods) { - onMouseMove(toPixels(x), toPixels(y)); + onMouseMove(toPixels(x), toPixels(y), mods); } void MacPlugView::macMouseLeave() @@ -988,7 +1017,7 @@ - (void)viewDidChangeBackingProperties } //------------------------------------------------------------------------ -void MacPlugView::macMouseWheel(double x, double y, double deltaY) +void MacPlugView::macMouseWheel(double x, double y, double deltaY, unsigned mods) { NAMpRationsPlugView *view = nativeView(mView); if (!view) @@ -998,11 +1027,11 @@ - (void)viewDidChangeBackingProperties const int py = toPixels(y); while (view->mWheelAccum >= 1.0) { view->mWheelAccum -= 1.0; - onMouseWheel(px, py, 1); + onMouseWheel(px, py, 1, mods); } while (view->mWheelAccum <= -1.0) { view->mWheelAccum += 1.0; - onMouseWheel(px, py, -1); + onMouseWheel(px, py, -1, mods); } } diff --git a/products/rations/src/rationscontroller.cpp b/products/rations/src/rationscontroller.cpp index 42b8b76..43d9161 100644 --- a/products/rations/src/rationscontroller.cpp +++ b/products/rations/src/rationscontroller.cpp @@ -229,6 +229,10 @@ tresult PLUGIN_API RationsController::initialize(FUnknown *context) parameters.addParameter(STR16("Active Channel"), nullptr, 0, 0.0, Vst::ParameterInfo::kIsReadOnly | Vst::ParameterInfo::kIsHidden, kActiveChannelId); + // The input-level lamp, 0 or 1, hence one step. + parameters.addParameter(STR16("Input Level OK"), nullptr, 1, 0.0, + Vst::ParameterInfo::kIsReadOnly | Vst::ParameterInfo::kIsHidden, + kInputLevelOkId); // --- the units, and their ORDER is load-bearing -------------------------------------- // diff --git a/products/rations/src/rationsids.h b/products/rations/src/rationsids.h index b76de2a..2d69a34 100644 --- a/products/rations/src/rationsids.h +++ b/products/rations/src/rationsids.h @@ -208,6 +208,10 @@ enum ParamIDs : Steinberg::Vst::ParamID { // capture is still being built is held rather than faked, and the panel LEDs read this so a // lamp never lights over a channel the audio has not reached yet. kActiveChannelId = 204, + // The input-level lamp beside the Input knob: 1 when the peak the sounding capture hears is in + // the window inputlevellamp.h describes, else 0. Like kActiveChannelId it is an answer from the + // audio thread, and the editor only draws it. + kInputLevelOkId = 205, // The MIDI-mapped parameter block: 1000 + cc for CC 0 .. 127, and 1128 for Program Change. // These exist because a footswitch's messages do not arrive as MIDI at all - they arrive as @@ -227,6 +231,17 @@ enum ParamIDs : Steinberg::Vst::ParamID { kMidiProgramChangeId = 1128, }; +// Every hidden read-only parameter the processor writes on every block, in one list. The +// processor writes them by walking this list, the LV2 wrapper makes one control output port per +// entry, in this order, and each standalone reserves its output queue against the count. One list +// is what makes adding a value move all three together. +inline constexpr Steinberg::Vst::ParamID kFeedbackIds[] = { + kInputMeterId, kOutputMeterId, kBankProgressId, + kActiveIndexId, kActiveChannelId, kInputLevelOkId, +}; +inline constexpr int kFeedbackCount = + static_cast(sizeof(kFeedbackIds) / sizeof(kFeedbackIds[0])); + // Units. The root unit is everything a player touches; the MIDI unit holds the 129 parameters // that exist only so that CC and Program Change have somewhere to arrive, and exists so a host // can fold them away instead of listing them beside Bass and Treble. diff --git a/products/rations/src/rationsprocessor.cpp b/products/rations/src/rationsprocessor.cpp index 35061c6..faf96a6 100644 --- a/products/rations/src/rationsprocessor.cpp +++ b/products/rations/src/rationsprocessor.cpp @@ -240,6 +240,8 @@ tresult PLUGIN_API RationsProcessor::setupProcessing(ProcessSetup &setup) // section has to be said again here rather than assumed to have survived. publishOutputMode(); + mInputLamp.reset(mSampleRate); + // Bypass ramp length in samples, at least one sample so the step is finite. const double rampSamples = std::max(1.0, engine::kBypassRampMs * 0.001 * mSampleRate); mBypassStep = 1.0 / rampSamples; @@ -298,6 +300,8 @@ tresult PLUGIN_API RationsProcessor::setActive(TBool state) mPedals.reset(); // Come up dry and ramp in, rather than opening on a half-built bank. mBypassMix = 1.0; + // And with the lamp dark, rather than holding a light from before the deactivation. + mInputLamp.reset(mSampleRate); } else { // Anything the audio thread retired is unreachable from it now; free it here. for (int slot = 0; slot < kIrSlotCount; ++slot) @@ -697,15 +701,25 @@ tresult PLUGIN_API RationsProcessor::process(ProcessData &data) inPeak = std::max(inPeak, std::fabs(static_cast(in[i]))); outPeak = std::max(outPeak, std::fabs(static_cast(outL[i]))); } - writeOutputPoint(data.outputParameterChanges, kInputMeterId, peakToMeterNorm(inPeak), 0); - writeOutputPoint(data.outputParameterChanges, kOutputMeterId, peakToMeterNorm(outPeak), 0); - writeOutputPoint(data.outputParameterChanges, kBankProgressId, mRack.progress(), 0); - writeOutputPoint(data.outputParameterChanges, kActiveIndexId, mRack.activeIndexNorm(), 0); - // Which channel is SOUNDING, which is not always the one kChannelId asks for: a switch - // whose target capture is still being built is held, and the editor's LED must not light - // over a channel that is not there yet. The parameter is the request; this is the answer. - writeOutputPoint(data.outputParameterChanges, kActiveChannelId, - normFromChannel(mRack.soundingChannel()), 0); + // In kFeedbackIds' order, and written by walking that list, because the list is also what + // every standalone reserves its output queue against. The size check makes a value added + // here without its id, or an id without its value, a compile error. + const double feedback[] = { + peakToMeterNorm(inPeak), + peakToMeterNorm(outPeak), + mRack.progress(), + mRack.activeIndexNorm(), + // Which channel is SOUNDING, which is not always the one kChannelId asks for: a switch + // whose target capture is still being built is held, and the editor's LED must not + // light over a channel that is not there yet. The parameter is the request; this is + // the answer. + normFromChannel(mRack.soundingChannel()), + mInputLamp.lit() ? 1.0 : 0.0, + }; + static_assert(sizeof(feedback) / sizeof(feedback[0]) == kFeedbackCount, + "one feedback value per entry of kFeedbackIds"); + for (int f = 0; f < kFeedbackCount; ++f) + writeOutputPoint(data.outputParameterChanges, kFeedbackIds[f], feedback[f], 0); } return kResultOk; @@ -729,6 +743,20 @@ void RationsProcessor::applyDsp(const float *in, float *outL, float *outR, int32 mWorkBufInput[static_cast(i)] = x * inputGain; } + // 1a. The input-level lamp, fed the model input as the Input knob leaves it, times the + // sounding capture's own input calibration: exactly the signal that capture's model will be + // fed, apart from the stages below that change it on purpose. Tapped HERE, before the gate's + // trigger and before the PRE pedals, so a Boost (a deliberate drive into the amp) does not + // switch off the lamp that is there to check the gain staging under it. In the rack the same + // tap counts a hosted boost, because hosted plug-ins run before the amp's Input knob; that is + // where each product's pedals sit, not a choice made here. + // + // At 48 kHz this is the native-rate signal sample for sample, because the resampler is a + // call-through. At any other rate it is the host-rate signal, and its peak can differ from the + // native-rate one by whatever inter-sample peak the resampler reconstructs - not measured, and + // the reason the lamp reads here anyway: the native-rate signal exists only inside the rack. + mInputLamp.process(mWorkBufInput.data(), numSamples, mRack.soundingInputGain()); + // 2. Noise-gate trigger (level detection; returns the gated signal). DSP_SAMPLE **processingInput = &mWorkPtrInput; if (ngOn) { diff --git a/products/rations/src/rationsprocessor.h b/products/rations/src/rationsprocessor.h index 2557ca7..38d83d9 100644 --- a/products/rations/src/rationsprocessor.h +++ b/products/rations/src/rationsprocessor.h @@ -32,6 +32,7 @@ #include "public.sdk/source/vst/vstaudioeffect.h" #include "channelrack.h" +#include "inputlevellamp.h" #include "irblend.h" #include "midilearn.h" #include "nativeresampler.h" @@ -188,6 +189,9 @@ class RationsProcessor : public Steinberg::Vst::AudioEffect // Four banks, four crossfade engines, one input ring and the switch between them. The single // native-rate block processor the shared resampler drives. ChannelRack mRack; + // The input-level lamp's detector. Audio thread only, apart from reset() in setupProcessing + // and setActive, when the audio thread is not running. + InputLevelLamp mInputLamp; // Two IR slots. Slot A alone is the normal case and takes exactly the path it took before the // second slot existed - one Process call, no mixing, the blend not consulted - so a user who diff --git a/products/rations/src/rationsview.cpp b/products/rations/src/rationsview.cpp index 1b04c8a..51a79c0 100644 --- a/products/rations/src/rationsview.cpp +++ b/products/rations/src/rationsview.cpp @@ -17,6 +17,7 @@ #include "rationsids.h" #include "gfx/widgets.h" #include "platform/respath.h" +#include "typednumber.h" #include "pluginterfaces/base/keycodes.h" #include "pluginterfaces/base/ustring.h" @@ -64,9 +65,25 @@ void drawCaret(Canvas &c, const Rect &box, float caretX) c.strokeLine(caretX, box.y + 4.0f, caretX, box.bottom() - 4.0f); } -// Pixels of vertical drag for a dial's full range, in LOGICAL units — so the feel is the same at -// every window size. -constexpr float kKnobDragRange = 200.0f; +// Drag and wheel gearing, from the original plug-in's knobs (iPlug2's IKnobControlBase). A drag +// covers the full range in DEFAULT_GEARING (4.0) heights of the knob's drag bounds; upstream takes +// those bounds from the control's own rect, and the head dial's face diameter stands in for it +// here — for EVERY dial, so the small pedal knobs are not geared coarser than the big ones. In +// LOGICAL units, so the feel is the same at every window size. Holding Shift or Ctrl (Command on a +// Mac, see platform/pointermods.h) makes a drag ten times finer and a wheel notch a tenth of its +// usual 1%: upstream's IsFineControl is `mod.C || mod.S`, and its wheel steps are 0.01 and 0.001. +constexpr float kDragGearing = 4.0f; +constexpr float kKnobDragRange = kDragGearing * 2.0f * geo::kKnobR; // 224 +constexpr float kFineDragFactor = 10.0f; +constexpr double kWheelStep = 0.01, kFineWheelStep = 0.001; +// The trims and the dBu box keep their own round-number notches (kLevelWheelDb, kCalWheelDb), and +// fine is a tenth of those too. +constexpr double kFineWheelDivisor = 10.0; + +bool isFine(unsigned mods) +{ + return (mods & (Steinberg::kPointerShift | Steinberg::kPointerControl)) != 0; +} // The dial is the one layer that is rotated after being scaled, so rotation resamples it a second // time. Caching it at exactly its on-screen size loses visible contrast in the thin gold pointer; @@ -598,6 +615,11 @@ void RationsEditorView::composeHead(Canvas &c) drawMeter(c, geo::kOutputMeter, mOutDisp, mOutPeak); for (int i = 0; i < 2; ++i) drawKnob(c, geo::kIoKnobs[i], true); + // Read from the parameter rather than from the cached copy ParamChanged keeps, so a page that + // is drawn before the first report still shows the controller's value. + drawLed(c, static_cast(geo::kInputLampCX), static_cast(geo::kInputLampCY), + paramValue(kInputLevelOkId) > 0.5, static_cast(geo::kInputLampR), + geo::LedColor::Green); for (const geo::ButtonSpec &b : geo::kPageButtons) drawButton(c, b); @@ -1366,29 +1388,17 @@ void RationsEditorView::drawOutputSection(Canvas &c) c.setPenSize(1.0f); c.strokeRoundRect(value, 4.0f); - const std::string text = editing ? mEditText : calValueText(); c.setFont(Font::Body); c.setFontSize(geo::kMidiRowTextSize); // Centred in both states, so the box does not jolt as the field opens under the pointer. - const float textW = c.stringWidth(text.c_str()); - const float textX = value.centerX() - textW * 0.5f; const float textBase = value.centerY() + geo::kMidiRowTextSize * 0.36f; - if (editSelected()) { - // The seed, drawn SELECTED — which is the field saying, before anything is typed, that - // typing will replace it rather than append to it. Without this the rule is still the - // right one and the user has no way to know it until they have got a wrong answer. - const Rect sel(textX - 2.0f, value.y + 4.0f, textW + 4.0f, value.h - 8.0f); - c.setColor(geo::kAccent, 210); - c.fillRoundRect(sel, 2.0f); - c.setColor(0x0C0B0A); - } else { - c.setColor(editing ? geo::kAccentBright : geo::kTextColor); - } - c.drawString(text.c_str(), textX, textBase); - if (editing && !editSelected()) { - const std::string before = text.substr(0, std::min(mEditCaret, text.size())); - drawCaret(c, value, textX + c.stringWidth(before.c_str())); + if (editing) { + drawFieldText(c, value, textBase); + return; } + const std::string text = calValueText(); + c.setColor(geo::kTextColor); + c.drawString(text.c_str(), value.centerX() - c.stringWidth(text.c_str()) * 0.5f, textBase); } //------------------------------------------------------------------------ @@ -1422,7 +1432,7 @@ geo::ButtonSpec RationsEditorView::midiButton(int row, bool clear) const } //------------------------------------------------------------------------ -bool RationsEditorView::handleSettingsClick(float x, float y) +bool RationsEditorView::handleSettingsClick(float x, float y, bool doubleClick) { if (!mController) return false; @@ -1503,7 +1513,10 @@ bool RationsEditorView::handleSettingsClick(float x, float y) // inside the row it starts makes no difference, and a 12 px thumb is not something to // make anyone aim at. if (levelRowRect(i).contains(x, y)) { - startDrag(kChannelLevelId[i], x, y, true); + if (doubleClick) + resetParam(kChannelLevelId[i]); + else + startDrag(kChannelLevelId[i], x, y, true); invalidate(); return true; } @@ -1621,6 +1634,24 @@ void RationsEditorView::drawKnob(Canvas &c, const geo::KnobSpec &k, bool enabled // Dim when idle, accent while this dial is being dragged. The row does not appear and // disappear — a value that came and went would make the panel twitch under the hand — it only // changes colour, which says "live" without moving anything. + // Open for typing: the readout's own box becomes the field, in the dBu box's style, with the + // text on the readout's own baseline so nothing shifts as it opens. + if (editingValue(k.id)) { + for (const geo::ValueField &f : geo::kValueFields) { + if (f.id != k.id) + continue; + const Rect box = valueFieldRect(f); + c.setColor(0x000000, 200); + c.fillRoundRect(box, 4.0f); + c.setColor(geo::kAccent, 220); + c.setPenSize(1.0f); + c.strokeRoundRect(box, 4.0f); + c.setFont(Font::Body); + c.setFontSize(geo::kKnobValueSize); + drawFieldText(c, box, valueY); + } + return; + } if (readout.empty()) return; c.setFont(Font::Body); @@ -1698,14 +1729,17 @@ void RationsEditorView::drawToggle(Canvas &c, const geo::ToggleSpec &t, bool on) } //------------------------------------------------------------------------ -void RationsEditorView::drawLed(Canvas &c, float cx, float cy, bool lit, float r) +void RationsEditorView::drawLed(Canvas &c, float cx, float cy, bool lit, float r, + geo::LedColor color) { const Rect dest(cx - r, cy - r, 2.0f * r, 2.0f * r); const int px = static_cast(std::lround(2.0 * r * mScale)); - if (cairo_surface_t *led = mImages.getScaled(lit ? "led_on" : "led_off", px, px)) { + const bool green = color == geo::LedColor::Green; + if (cairo_surface_t *led = + mImages.getScaled(!lit ? "led_off" : (green ? "led_green_on" : "led_on"), px, px)) { c.drawImage(led, dest); } else { - c.setColor(lit ? geo::kPeakColor : 0x141414); + c.setColor(!lit ? 0x141414 : (green ? geo::kAccent : geo::kPeakColor)); c.fillEllipse(dest); } } @@ -2079,15 +2113,37 @@ void RationsEditorView::nudgeParam(Vst::ParamID id, double delta) invalidate(); } +// The double-click's reset. Slim needs one more step than every other control: it is published on +// the knob's RELEASE (see kMsgSetSlim), and a double-click has no release of its own to wait for — +// the first click's has already been and gone, with nothing moved. So it is published here, and +// only when the value actually changed, because an unmoved Slim would cost every bank a rebuild. +void RationsEditorView::resetParam(Vst::ParamID id) +{ + if (!mController) + return; + const Vst::Parameter *p = mController->getParameterObject(id); + if (!p) + return; + const double norm = p->getInfo().defaultNormalizedValue; + const bool moved = paramValue(id) != norm; + editParam(id, norm); + if (id == kSlimId && moved) { + mController->applySlim(); + mSlimDirty = false; + } + invalidate(); +} + void RationsEditorView::startDrag(Vst::ParamID id, float x, float y, bool horizontal) { if (!mController) return; mDragParam = id; - mDragStartX = x; - mDragStartY = y; + mDragLastX = x; + mDragLastY = y; mDragHorizontal = horizontal; mDragStartNorm = paramValue(id); + mDragNorm = mDragStartNorm; mController->beginEdit(id); // No explicit pointer grab is needed here: X delivers an implicit grab to the window that saw // the ButtonPress for as long as the button is held, and the Win32 view calls SetCapture for @@ -2096,13 +2152,15 @@ void RationsEditorView::startDrag(Vst::ParamID id, float x, float y, bool horizo //------------------------------------------------------------------------ // One wheel click. On a channel dial that is one capture, so the wheel lands on real captures -// rather than between them — the same resting places the dial's own auto-detent glides to. -double RationsEditorView::wheelStep(Vst::ParamID id) const +// rather than between them — the same resting places the dial's own auto-detent glides to, which +// is also why fine control does not apply there: a tenth of a capture is a position the detent +// would glide straight back off. +double RationsEditorView::wheelStep(Vst::ParamID id, bool fine) const { for (int c = 0; c < kChannelCount; ++c) if (id == kChannelGainId[c] && mEntryCount[c] > 1) return 1.0 / static_cast(mEntryCount[c] - 1); - return 0.05; + return fine ? kFineWheelStep : kWheelStep; } //------------------------------------------------------------------------ @@ -2143,17 +2201,29 @@ static Rect pedalSwitchRect(int pedal) } //------------------------------------------------------------------------ -void RationsEditorView::onMouseDown(int x, int y, int button) +void RationsEditorView::onMouseDown(int x, int y, int button, unsigned /*mods*/, bool doubleClick) { // Physical pixels in, logical units out: this is the only place the page transform is undone, // and everything below hit-tests against geometry.h directly. const float fx = static_cast((x - mOffX) / mScale); const float fy = static_cast((y - mOffY) / mScale); - // Right-click resets a channel trim to exactly 0 dB. The one gesture this editor answers on a - // button other than the left, and it is here rather than on a double-click because neither - // window class delivers double-clicks: the X11 view sees two ordinary presses and the Win32 - // one deliberately does not set CS_DBLCLKS, so that the two platforms behave the same. + // An open dial readout is closed by a press anywhere else, and closed by KEEPING what was + // typed — the settings page's rule for its own fields, applied before anything below can act + // on the press. A press inside it leaves it open, caret and all. The head page does not + // scroll, so its fields are tested in window-logical coordinates as they are drawn. + if (mEditField == TextField::KnobValue) { + for (const geo::ValueField &f : geo::kValueFields) { + if (f.id == mEditParam && valueFieldRect(f).contains(fx, fy)) + return; + } + commitTextEdit(); + } + + // Right-click resets a channel trim to exactly 0 dB, and steps a pedal's list backwards. It + // predates the double-click, which every platform base now reports and which resets the trims + // too; the right button keeps doing what it did, because a gesture a user has learned is not + // one to take away. if (button == 3) { // The Slim overlay closes on a right-click ANYWHERE, which is the gesture the author asked // for and is tested before everything else so it cannot be swallowed by a control under @@ -2203,7 +2273,10 @@ void RationsEditorView::onMouseDown(int x, int y, int button) // underneath the dim can be clicked through. if (mSlimOpen) { if (hitCircle(fx, fy, geo::kSlimKnobCX, geo::kSlimKnobCY, geo::kSlimKnobR)) { - startDrag(kSlimId, fx, fy); + if (doubleClick) + resetParam(kSlimId); + else + startDrag(kSlimId, fx, fy); invalidate(); } else { closeSlim(); @@ -2237,10 +2310,10 @@ void RationsEditorView::onMouseDown(int x, int y, int button) switch (mPage) { case geo::Page::Head: - handleHeadClick(fx, fy); + handleHeadClick(fx, fy, doubleClick); return; case geo::Page::Cabinet: - handleCabinetClick(fx, fy); + handleCabinetClick(fx, fy, doubleClick); return; case geo::Page::Settings: // The scrollbar is chrome, so it is hit-tested in window coordinates and gets first @@ -2251,16 +2324,16 @@ void RationsEditorView::onMouseDown(int x, int y, int button) return; if (fy < static_cast(geo::kPageContentTop)) return; - handleSettingsClick(fx, contentY(fy)); + handleSettingsClick(fx, contentY(fy), doubleClick); return; case geo::Page::Pedalboard: - handlePedalboardClick(fx, fy); + handlePedalboardClick(fx, fy, doubleClick); return; } } //------------------------------------------------------------------------ -bool RationsEditorView::handleHeadClick(float x, float y) +bool RationsEditorView::handleHeadClick(float x, float y, bool doubleClick) { if (buttonRect(geo::kSettingsButton).contains(x, y)) { setPage(geo::kSettingsButton.target); @@ -2287,10 +2360,17 @@ bool RationsEditorView::handleHeadClick(float x, float y) } } + // A dial is dragged, double-clicked back to its default, or — for the six with a value row — + // typed into by clicking that row: the three ways the original plug-in's knobs offer. The + // first press of a double-click has already begun and ended a drag that went nowhere, which + // is harmless: an edit gesture with no performEdit in it changes nothing. for (int i = 0; i < geo::kKnobCount; ++i) { const geo::KnobSpec &k = geo::kKnobs[i]; if (hitCircle(x, y, k.cx, k.cy, k.r)) { - startDrag(k.id, x, y); + if (doubleClick) + resetParam(k.id); + else + startDrag(k.id, x, y); invalidate(); // the readout appears return true; } @@ -2298,11 +2378,21 @@ bool RationsEditorView::handleHeadClick(float x, float y) for (int i = 0; i < 2; ++i) { const geo::KnobSpec &k = geo::kIoKnobs[i]; if (hitCircle(x, y, k.cx, k.cy, k.r)) { - startDrag(k.id, x, y); + if (doubleClick) + resetParam(k.id); + else + startDrag(k.id, x, y); invalidate(); return true; } } + for (const geo::ValueField &f : geo::kValueFields) { + if (valueFieldRect(f).contains(x, y)) { + if (!editingValue(f.id)) + beginTextEdit(TextField::KnobValue, -1, f.id); + return true; + } + } for (int i = 0; i < geo::kToggleCount; ++i) { const geo::ToggleSpec &t = geo::kToggles[i]; @@ -2350,10 +2440,13 @@ bool RationsEditorView::handleHeadClick(float x, float y) } //------------------------------------------------------------------------ -bool RationsEditorView::handleCabinetClick(float x, float y) +bool RationsEditorView::handleCabinetClick(float x, float y, bool doubleClick) { if (blendActive() && hitCircle(x, y, geo::kBlendCX, geo::kBlendCY, geo::kBlendHitR)) { - startDrag(kIrBlendId, x, y); + if (doubleClick) + resetParam(kIrBlendId); + else + startDrag(kIrBlendId, x, y); invalidate(); return true; } @@ -2383,7 +2476,7 @@ void RationsEditorView::cycleList(const PedalParamSpec &spec, int dir) // A pedal that is switched OFF is still fully editable. That is not an oversight: a player dials // a delay in and then stomps it, and the alternative - refusing clicks until the LED is lit - // would mean the only way to set a pedal up is to hear it first. -bool RationsEditorView::handlePedalboardClick(float x, float y) +bool RationsEditorView::handlePedalboardClick(float x, float y, bool doubleClick) { for (int i = 0; i < geo::kPedalCount; ++i) { for (int k = 0, nk = pedalKnobCount(i); k < nk; ++k) { @@ -2391,7 +2484,11 @@ bool RationsEditorView::handlePedalboardClick(float x, float y) if (!hitCircle(x, y, static_cast(pt.x), static_cast(pt.y), static_cast(geo::kPedalKnobHitR))) continue; - startDrag(kPedalParams[pedalKnobParam(i, k)].id, x, y); + const Vst::ParamID id = kPedalParams[pedalKnobParam(i, k)].id; + if (doubleClick) + resetParam(id); + else + startDrag(id, x, y); invalidate(); return true; } @@ -2458,7 +2555,7 @@ bool RationsEditorView::handleIrRowClick(int slot, float x, float y) } //------------------------------------------------------------------------ -void RationsEditorView::onMouseMove(int x, int y) +void RationsEditorView::onMouseMove(int x, int y, unsigned mods) { mMouseX = static_cast((x - mOffX) / mScale); // In PAGE coordinates, like every rect it is tested against. A drag reads deltas, and those @@ -2480,19 +2577,32 @@ void RationsEditorView::onMouseMove(int x, int y) if (!mDragParam || !mController) return; + // Accumulated from the last position, as the original plug-in's knobs do, so pressing or + // releasing Shift mid-drag changes the gearing from that point on instead of making the + // control jump. The accumulator is clamped as it goes, so overshooting an end costs no travel + // on the way back. + const bool fine = isFine(mods); + const float gear = fine ? kFineDragFactor : 1.0f; double norm; if (mDragHorizontal) { // Relative, never absolute: a slider that jumped to wherever it was clicked would let a // mis-click throw a channel's level by the whole range, and this control's whole job is // small corrections. The drag also snaps to exactly 0 dB near the centre, because a trim - // has to be returnable to its default by hand. - norm = clampNorm(mDragStartNorm + (mMouseX - mDragStartX) / geo::kLevelDragRange); + // has to be returnable to its default by hand — but NOT under fine control, whose whole + // point is a value like +0.1 dB that the snap zone (±0.28 dB) would otherwise swallow. + // The snap is applied to what is published, never to the accumulator, so a coarse drag + // that passes through the centre is not held there. + mDragNorm = clampNorm(mDragNorm + (mMouseX - mDragLastX) / (geo::kLevelDragRange * gear)); + norm = mDragNorm; const double centre = 0.5; - if (std::fabs(norm - centre) * geo::kLevelDragRange < geo::kLevelCentreSnap) + if (!fine && std::fabs(norm - centre) * geo::kLevelDragRange < geo::kLevelCentreSnap) norm = centre; } else { - norm = clampNorm(mDragStartNorm + (mDragStartY - mMouseY) / kKnobDragRange); + mDragNorm = clampNorm(mDragNorm + (mDragLastY - mMouseY) / (kKnobDragRange * gear)); + norm = mDragNorm; } + mDragLastX = mMouseX; + mDragLastY = mMouseY; // A Slim drag that actually moved is what makes the release worth publishing. A click on the // knob that goes nowhere leaves mSlimDirty false and costs no rebuild. if (mDragParam == kSlimId && norm != mDragStartNorm) @@ -2527,14 +2637,16 @@ void RationsEditorView::onMouseUp(int /*x*/, int /*y*/, int button) //------------------------------------------------------------------------ // Wheel adjusts whatever is under the cursor (wheel up = increase). -void RationsEditorView::onMouseWheel(int x, int y, int delta) +void RationsEditorView::onMouseWheel(int x, int y, int delta, unsigned mods) { const float fx = static_cast((x - mOffX) / mScale); const float fy = static_cast((y - mOffY) / mScale); + const bool fine = isFine(mods); + const double step = delta * (fine ? kFineWheelStep : kWheelStep); if (mSlimOpen) { if (hitCircle(fx, fy, geo::kSlimKnobCX, geo::kSlimKnobCY, geo::kSlimKnobR)) { - nudgeParam(kSlimId, delta * 0.05); + nudgeParam(kSlimId, step); mSlimDirty = true; } return; @@ -2546,7 +2658,7 @@ void RationsEditorView::onMouseWheel(int x, int y, int delta) } if (mPage == geo::Page::Cabinet) { if (blendActive() && hitCircle(fx, fy, geo::kBlendCX, geo::kBlendCY, geo::kBlendHitR)) - nudgeParam(kIrBlendId, delta * 0.05); + nudgeParam(kIrBlendId, step); return; } if (mPage == geo::Page::Settings) { @@ -2577,16 +2689,19 @@ void RationsEditorView::onMouseWheel(int x, int y, int delta) // to repeat on the other three channels. for (int i = 0; i < geo::kLevelRowCount; ++i) { if (levelRowRect(i).contains(fx, cy)) { + const double db = geo::kLevelWheelDb / (fine ? kFineWheelDivisor : 1.0); nudgeParam(kChannelLevelId[i], - delta * geo::kLevelWheelDb / (ranges::kLevelMax - ranges::kLevelMin)); + delta * db / (ranges::kLevelMax - ranges::kLevelMin)); return; } } // The interface calibration level, in whole decibels: an interface's stated level is a // round number, and this is how a user lands on theirs without aiming a drag at it. - if (calValueRect().contains(fx, cy)) { - nudgeParam(kInputCalLevelId, - delta * geo::kCalWheelDb / (ranges::kCalMax - ranges::kCalMin)); + // Not while the box is open for typing: the wheel would move the value underneath a field + // that is about to overwrite it, and the box would show neither. + if (calValueRect().contains(fx, cy) && mEditField != TextField::CalLevel) { + const double db = geo::kCalWheelDb / (fine ? kFineWheelDivisor : 1.0); + nudgeParam(kInputCalLevelId, delta * db / (ranges::kCalMax - ranges::kCalMin)); return; } return; @@ -2601,7 +2716,7 @@ void RationsEditorView::onMouseWheel(int x, int y, int delta) if (!hitCircle(fx, fy, static_cast(pt.x), static_cast(pt.y), static_cast(geo::kPedalKnobHitR))) continue; - nudgeParam(kPedalParams[pedalKnobParam(i, k)].id, delta * 0.05); + nudgeParam(kPedalParams[pedalKnobParam(i, k)].id, step); return; } for (int m = 0, nm = pedalMiniCount(i); m < nm; ++m) { @@ -2609,8 +2724,9 @@ void RationsEditorView::onMouseWheel(int x, int y, int delta) continue; const PedalParamSpec &spec = kPedalParams[pedalMiniParam(i, m)]; // A list steps by whole entries: landing between two sync divisions is not a - // state the parameter has, and a 0.05 nudge on a twelve-entry list would skip - // some of them and repeat others. + // state the parameter has, and a fractional nudge on a twelve-entry list would + // skip some of them and repeat others. Fine control does not apply, for the same + // reason. if (spec.kind == PedalParamKind::List) cycleList(spec, delta > 0 ? 1 : -1); return; @@ -2622,15 +2738,18 @@ void RationsEditorView::onMouseWheel(int x, int y, int delta) return; for (int i = 0; i < geo::kKnobCount; ++i) { const geo::KnobSpec &k = geo::kKnobs[i]; + // A dial whose readout is open for typing ignores the wheel, as the dBu box does. if (hitCircle(fx, fy, k.cx, k.cy, k.r)) { - nudgeParam(k.id, delta * wheelStep(k.id)); + if (!editingValue(k.id)) + nudgeParam(k.id, delta * wheelStep(k.id, fine)); return; } } for (int i = 0; i < 2; ++i) { const geo::KnobSpec &k = geo::kIoKnobs[i]; if (hitCircle(fx, fy, k.cx, k.cy, k.r)) { - nudgeParam(k.id, delta * 0.05); + if (!editingValue(k.id)) + nudgeParam(k.id, step); return; } } @@ -2760,20 +2879,71 @@ std::string RationsEditorView::calEditSeed() const return dbu; } -void RationsEditorView::beginTextEdit(TextField field, int channel) +// A dial's readout without its unit: exactly the number the row shows, so opening the field moves +// nothing but the highlight. paramText is the controller's own formatting of the plain value, and +// commitTextEdit reads a plain value back, so the seed round-trips. +std::string RationsEditorView::valueEditSeed(Vst::ParamID id) const +{ + return paramText(id); +} + +Rect RationsEditorView::valueFieldRect(const geo::ValueField &f) +{ + return Rect(static_cast(f.x), static_cast(f.y), static_cast(f.w), + static_cast(f.h)); +} + +// The text of the open field: centred in its box, either the whole of it highlighted (just +// opened — typing replaces it) or a caret. Shared by the dBu box and the dial readouts, so the two +// cannot come to disagree about what a selected field looks like. +void RationsEditorView::drawFieldText(Canvas &c, const Rect &box, float baseline) +{ + const float textW = c.stringWidth(mEditText.c_str()); + const float textX = box.centerX() - textW * 0.5f; + if (editSelected()) { + // The seed, drawn SELECTED — which is the field saying, before anything is typed, that + // typing will replace it rather than append to it. Without this the rule is still the + // right one and the user has no way to know it until they have got a wrong answer. + const Rect sel(textX - 2.0f, box.y + 4.0f, textW + 4.0f, box.h - 8.0f); + c.setColor(geo::kAccent, 210); + c.fillRoundRect(sel, 2.0f); + c.setColor(0x0C0B0A); + } else { + c.setColor(geo::kAccentBright); + } + c.drawString(mEditText.c_str(), textX, baseline); + if (!editSelected()) { + const std::string before = mEditText.substr(0, std::min(mEditCaret, mEditText.size())); + drawCaret(c, box, textX + c.stringWidth(before.c_str())); + } +} + +void RationsEditorView::beginTextEdit(TextField field, int channel, Vst::ParamID param) { if (!mController || field == TextField::NoField) return; if (field == TextField::ChannelName && (channel < 0 || channel >= kChannelCount)) return; + if (field == TextField::KnobValue && param == 0) + return; + // One field at a time: opening a second one closes the first, keeping what it held. + commitTextEdit(); mEditField = field; mEditChannel = channel; + mEditParam = field == TextField::KnobValue ? param : 0; // A name is seeded with the name currently SHOWN, not with the override, so a user adjusting - // the folder's name starts from it rather than from an empty field. A level is seeded with the - // level currently set, for the same reason: both are edits to something, not entries from - // nothing. - mEditText = field == TextField::ChannelName ? mController->channelName(channel) : calEditSeed(); + // the folder's name starts from it rather than from an empty field. A level or a dial's value + // is seeded with what is currently set, for the same reason: all three are edits to something, + // not entries from nothing. + if (field == TextField::ChannelName) + mEditText = mController->channelName(channel); + else if (field == TextField::CalLevel) + mEditText = calEditSeed(); + else + mEditText = valueEditSeed(param); + if (field != TextField::ChannelName && mEditText.size() > geo::kCalEditMaxChars) + mEditText.resize(geo::kCalEditMaxChars); mEditCaret = mEditText.size(); // A LEVEL opens with its seed selected, so the first character typed replaces it. That is what // a value field is for: the number is read off an interface's spec sheet and entered whole, @@ -2784,7 +2954,7 @@ void RationsEditorView::beginTextEdit(TextField field, int channel) // A NAME does not, and that is the same argument reaching the other answer: a channel's name // is seeded with what the folder is called precisely so it can be ADJUSTED (D14), and select- // on-open would put a keystroke between the user and the text they asked to start from. - mEditSelectAll = field == TextField::CalLevel; + mEditSelectAll = field != TextField::ChannelName; // Take the keyboard for exactly as long as this field is open, and no longer. Every exit from // a field — commit, cancel, a click elsewhere, a page change — runs through commitTextEdit() // or cancelTextEdit(), so there is no path that leaves it held. @@ -2798,9 +2968,11 @@ void RationsEditorView::commitTextEdit() return; const TextField field = mEditField; const int channel = mEditChannel; + const Vst::ParamID param = mEditParam; const std::string text = mEditText; mEditField = TextField::NoField; mEditChannel = -1; + mEditParam = 0; mEditText.clear(); mEditCaret = 0; mEditSelectAll = false; @@ -2822,25 +2994,37 @@ void RationsEditorView::commitTextEdit() // a number invented out of a partial one — "-" on its own, or an emptied field, is a user // part-way through an edit and not a request for -60 dBu. // - // strtod rather than std::stod: this runs on the host's UI thread inside a click, and a - // throw out of here would cross the SDK's C ABI. + // parseTypedNumber rather than strtod, which follows the HOST's LC_NUMERIC and under a + // locale that writes 2,5 reads "-3.5" as -3 — see typednumber.h, which also says why it is + // not std::from_chars. It throws nothing, so nothing can cross the SDK's C ABI from here. // // There is deliberately no std::isfinite guard: this translation unit is built with // -ffast-math, under which that call folds to a constant true (D26, where exactly such a // guard had been compiled out of every build since it was written). It is not needed - // either. acceptsTextChar admits only [0-9.+-], so there is no exponent and no "nan" to + // either. acceptsTextChar admits only [0-9.,+-], so there is no exponent and no "nan" to // type, and kCalEditMaxChars caps the field at eight characters — the largest magnitude // that can be entered is 99999999, which is finite, and std::clamp takes it to +60. - const char *begin = text.c_str(); - char *end = nullptr; - const double db = std::strtod(begin, &end); - if (end != begin) { + double db = 0.0; + if (parseTypedNumber(text, db)) { // Clamped rather than refused: a user who types 100 wants the loudest this offers, and // the box redraws at +60.0 dBu to say what they got. const double clamped = std::clamp(db, ranges::kCalMin, ranges::kCalMax); editParam(kInputCalLevelId, (clamped - ranges::kCalMin) / (ranges::kCalMax - ranges::kCalMin)); } + } else if (mController && field == TextField::KnobValue) { + // A dial's value, in the units its readout shows — the parameter's PLAIN value, which for + // all six is a straight line over its range (each is a RangeParameter), so toNormalized is + // exact. The same rules as the dBu box: what will not parse leaves the parameter alone, + // and what is out of range is clamped, so the readout redraws at the limit and says what + // was taken. + double plain = 0.0; + const Vst::Parameter *p = mController->getParameterObject(param); + if (p && parseTypedNumber(text, plain)) { + const double lo = p->toPlain(0.0), hi = p->toPlain(1.0); + plain = std::clamp(plain, std::min(lo, hi), std::max(lo, hi)); + editParam(param, p->toNormalized(plain)); + } } invalidate(); } @@ -2849,6 +3033,7 @@ void RationsEditorView::cancelTextEdit() { mEditField = TextField::NoField; mEditChannel = -1; + mEditParam = 0; mEditText.clear(); mEditCaret = 0; mEditSelectAll = false; @@ -2856,11 +3041,6 @@ void RationsEditorView::cancelTextEdit() invalidate(); } -// What may be typed into the field that is open. A name takes any printable ASCII; a level takes -// only the characters a decimal number is written with, so a field whose whole purpose is to be -// parsed cannot be filled with something that will not parse. The check is on the CHARACTER and -// not on the resulting string: rejecting "-" because "-" is not yet a number would make a negative -// level untypeable, which is the shape of interface level most users have. // Drop the selection, optionally taking the text with it. One place rather than the six the key // handler would otherwise set two fields in, because a selection left set after the text under it // has changed would highlight characters the user did not select. @@ -2875,11 +3055,17 @@ void RationsEditorView::clearSelection(bool erase) } } +// What may be typed into the field that is open. A name takes any printable ASCII; a level or a +// dial's value takes only the characters a decimal number is written with, so a field whose whole +// purpose is to be parsed cannot be filled with something that will not parse. The check is on the +// CHARACTER and not on the resulting string: rejecting "-" because "-" is not yet a number would +// make a negative level untypeable, which is the shape of interface level most users have. Both +// decimal marks are taken, because a user whose desktop writes 2,5 will type it that way. bool RationsEditorView::acceptsTextChar(char ch) const { - if (mEditField != TextField::CalLevel) + if (mEditField == TextField::ChannelName) return true; - return (ch >= '0' && ch <= '9') || ch == '.' || ch == '-' || ch == '+'; + return (ch >= '0' && ch <= '9') || ch == '.' || ch == ',' || ch == '-' || ch == '+'; } // One key. Returns whether it was consumed, which is the whole contract: the SDK warns that @@ -2891,8 +3077,11 @@ bool RationsEditorView::handleTextKey(char16 key, int16 keyCode, int16 modifiers return false; switch (keyCode) { + // Tab commits as well, as it does in the original plug-in's fields and in most others: it + // is what a hand that is about to move on presses. case Steinberg::KEY_RETURN: case Steinberg::KEY_ENTER: + case Steinberg::KEY_TAB: commitTextEdit(); return true; case Steinberg::KEY_ESCAPE: @@ -2989,8 +3178,9 @@ bool RationsEditorView::handleTextKey(char16 key, int16 keyCode, int16 modifiers // The first character typed into a selected field replaces the whole of it. if (mEditSelectAll) clearSelection(/*erase=*/true); + // A dial's value is a number of the same shape as the dBu level, so it takes the same cap. const size_t limit = - mEditField == TextField::CalLevel ? geo::kCalEditMaxChars : kRenameMaxChars; + mEditField == TextField::ChannelName ? kRenameMaxChars : geo::kCalEditMaxChars; if (mEditText.size() >= limit) return true; // consumed, but the field is full mEditText.insert(mEditCaret, 1, static_cast(ch)); @@ -3123,6 +3313,16 @@ void RationsEditorView::ParamChanged(Vst::ParamID id, Vst::ParamValue value) invalidate(); return; } + case kInputLevelOkId: { + // Reported every block, and it changes a few times a phrase at most, so it repaints + // only when it changes rather than on every report the way the default below does. + const bool lit = value > 0.5; + if (lit != mInputLampLit) { + mInputLampLit = lit; + invalidate(); + } + return; + } case kActiveIndexId: { const int c = activeChannel(); const int index = mEntryCount[c] > 1 diff --git a/products/rations/src/rationsview.h b/products/rations/src/rationsview.h index 1fcb42f..5346087 100644 --- a/products/rations/src/rationsview.h +++ b/products/rations/src/rationsview.h @@ -88,10 +88,10 @@ class RationsEditorView : public Steinberg::NativePlugView void onAttached() SMTG_OVERRIDE; void onRemoved() SMTG_OVERRIDE; void onDraw(cairo_t *cr) SMTG_OVERRIDE; - void onMouseDown(int x, int y, int button) SMTG_OVERRIDE; + void onMouseDown(int x, int y, int button, unsigned mods, bool doubleClick) SMTG_OVERRIDE; void onMouseUp(int x, int y, int button) SMTG_OVERRIDE; - void onMouseMove(int x, int y) SMTG_OVERRIDE; - void onMouseWheel(int x, int y, int delta) SMTG_OVERRIDE; + void onMouseMove(int x, int y, unsigned mods) SMTG_OVERRIDE; + void onMouseWheel(int x, int y, int delta, unsigned mods) SMTG_OVERRIDE; void onTick() SMTG_OVERRIDE; bool isResizable() const SMTG_OVERRIDE @@ -161,7 +161,8 @@ class RationsEditorView : public Steinberg::NativePlugView // The LED's radius is a parameter because the pedalboard's are smaller than the head's: a // pedal's status LED is 10 units across against the amp's 18, which is the proportion the two // have on the real objects. - void drawLed(Canvas &c, float cx, float cy, bool lit, float r = static_cast(geo::kLedR)); + void drawLed(Canvas &c, float cx, float cy, bool lit, float r = static_cast(geo::kLedR), + geo::LedColor color = geo::LedColor::Red); // One pedal's face: its knobs, its mini controls, its LED, its footswitch and its name. The // enclosure itself is static and is composited by drawPedalboardStatic. void drawPedal(Canvas &c, int pedal); @@ -180,13 +181,18 @@ class RationsEditorView : public Steinberg::NativePlugView void editParam(Steinberg::Vst::ParamID id, double norm); void nudgeParam(Steinberg::Vst::ParamID id, double delta); void startDrag(Steinberg::Vst::ParamID id, float x, float y, bool horizontal = false); + // Return a control to its parameter's own default — the double-click on a dial, a slider or a + // pedal knob, as on the original plug-in (IControl::OnMouseDblClick -> SetValueToDefault). + void resetParam(Steinberg::Vst::ParamID id); // Step a list parameter by one, wrapping. The Delay's Sync division is the only one today; // it is a click rather than a drag because twelve values over a 62-unit box is not a drag. void cycleList(const PedalParamSpec &spec, int dir); - bool handleHeadClick(float x, float y); - bool handleCabinetClick(float x, float y); - bool handlePedalboardClick(float x, float y); - bool handleSettingsClick(float x, float y); + // `doubleClick` reaches only the pages that have something a double-click resets; every + // switch on them ignores it, so two clicks on a toggle are still two toggles. + bool handleHeadClick(float x, float y, bool doubleClick); + bool handleCabinetClick(float x, float y, bool doubleClick); + bool handlePedalboardClick(float x, float y, bool doubleClick); + bool handleSettingsClick(float x, float y, bool doubleClick); bool handleIrRowClick(int slot, float x, float y); // Load the previous (-1) or next (+1) IR in slot `slot`'s own folder. void stepIr(int slot, int dir); @@ -200,8 +206,9 @@ class RationsEditorView : public Steinberg::NativePlugView void boundCaptureBrowser(); // --- typed input ------------------------------------------------------------------------- - // Two fields take typed input — a channel's name and the interface calibration level — and - // they share one field, one caret, one focus grab and one key handler. That is not tidiness: + // Three kinds of field take typed input — a channel's name, the interface calibration level and + // the six dial readouts — and they share one field, one caret, one focus grab and one key + // handler. That is not tidiness: // the field holds the host's keyboard focus while it is open (RULES §4), so two independent // fields would be two things that can each forget to hand it back, and a state where both // believe they have it. One field cannot be open twice. @@ -213,8 +220,9 @@ class RationsEditorView : public Steinberg::NativePlugView NoField, ChannelName, // mEditChannel says which of the four CalLevel, // the interface level in dBu, kInputCalLevelId + KnobValue, // one of the six dial readouts, geo::kValueFields; mEditParam says which }; - void beginTextEdit(TextField field, int channel = -1); + void beginTextEdit(TextField field, int channel = -1, Steinberg::Vst::ParamID param = 0); // Ends the edit by KEEPING what was typed, which is what every exit but Escape does. A value // that will not parse is the one case that cannot be kept, and leaves its parameter alone. void commitTextEdit(); @@ -234,6 +242,10 @@ class RationsEditorView : public Steinberg::NativePlugView { return mEditField == TextField::ChannelName && mEditChannel == channel; } + bool editingValue(Steinberg::Vst::ParamID id) const + { + return mEditField == TextField::KnobValue && mEditParam == id; + } // Returns true when the key was consumed, which is exactly what onKeyDown must report to the // host: a wrong "yes" swallows the host's own key commands, and the transport is one of them. bool handleTextKey(Steinberg::char16 key, Steinberg::int16 keyCode, Steinberg::int16 modifiers); @@ -247,6 +259,13 @@ class RationsEditorView : public Steinberg::NativePlugView // for editing ("12.0") — the unit is not typed, so it is not offered to be deleted. std::string calValueText() const; std::string calEditSeed() const; + // A dial readout's field: where it is, and its seed — the readout without its unit. + static Rect valueFieldRect(const geo::ValueField &f); + std::string valueEditSeed(Steinberg::Vst::ParamID id) const; + // The text of an open field, with its selection or its caret, inside `box` on `baseline`. The + // font is set by the caller; the dBu box and the dial readouts both draw through this, so the + // two fields look and behave as one. + void drawFieldText(Canvas &c, const Rect &box, float baseline); void pollCaps(); // Ask the processor what the learn table now says, while a row is waiting to be taught. void pollMidi(); @@ -264,7 +283,7 @@ class RationsEditorView : public Steinberg::NativePlugView std::string knobReadout(const geo::KnobSpec &k) const; // One wheel click. On a channel dial that is one capture, so the wheel lands on real captures // rather than between them. - double wheelStep(Steinberg::Vst::ParamID id) const; + double wheelStep(Steinberg::Vst::ParamID id, bool fine) const; // Index of the capture sounding in channel `c`, falling back to that dial's position before // the processor has reported one. int captureIndex(int c) const; @@ -367,7 +386,8 @@ class RationsEditorView : public Steinberg::NativePlugView // The one open text field, if any, and what is in it. The text is held here rather than // pushed at its destination on every keystroke so that Escape has something to go back to. TextField mEditField = TextField::NoField; - int mEditChannel = -1; // meaningful only for TextField::ChannelName + int mEditChannel = -1; // meaningful only for TextField::ChannelName + Steinberg::Vst::ParamID mEditParam = 0; // meaningful only for TextField::KnobValue std::string mEditText; size_t mEditCaret = 0; // The whole seed is selected until the first key lands on it. One flag rather than an anchor @@ -382,12 +402,17 @@ class RationsEditorView : public Steinberg::NativePlugView // rebuilds every capture in every bank — see kMsgSetSlim. bool mSlimOpen = false; bool mSlimDirty = false; - float mDragStartY = 0; + // The drag ACCUMULATES from the last pointer position rather than measuring from the first, + // which is what lets Shift or Ctrl change its gearing mid-drag without the control jumping. + // mDragNorm is the editor's own running value and is never re-read from the parameter during + // the drag, so a host that echoes a write back late (LV2, see D29) cannot pull it backwards. + // mDragStartNorm is kept only to tell a drag that moved from a click that did not. + float mDragLastX = 0, mDragLastY = 0; + double mDragNorm = 0; double mDragStartNorm = 0; // A knob is dragged vertically and a level slider horizontally, so the drag carries which // axis it is on rather than the hit test having to leave a knob's coordinate in a Y field. bool mDragHorizontal = false; - float mDragStartX = 0; float mMouseX = 0, mMouseY = 0; // Meter display state: fast attack from ParamChanged, exponential release in onTick, plus a @@ -400,6 +425,8 @@ class RationsEditorView : public Steinberg::NativePlugView int mEntryCount[kChannelCount] = {0, 0, 0, 0}; std::vector mCaptureNames[kChannelCount]; int mActiveIndex = -1; // capture sounding in the ACTIVE channel; -1 = not reported yet + // The input-level lamp as last reported, kept only to tell a change from a repeat. + bool mInputLampLit = false; float mBankProgress = 0.0f; // Capability polling. The capture names are produced by the processor's worker threads, so diff --git a/products/rations/standalone/jackclient.cpp b/products/rations/standalone/jackclient.cpp index bf5a9a7..01d7808 100644 --- a/products/rations/standalone/jackclient.cpp +++ b/products/rations/standalone/jackclient.cpp @@ -2,6 +2,9 @@ #include "jackclient.h" +#include "midilearn.h" +#include "rationsids.h" + #include "pluginterfaces/vst/ivstcomponent.h" #include "pluginterfaces/vst/ivstevents.h" @@ -25,9 +28,19 @@ namespace // its vector when addParameterData runs out of reserved queues // (public.sdk/source/vst/hosting/parameterchanges.cpp), which on this thread is a malloc. One // block can carry every knob the editor touched plus a burst of CC, so the input side is sized for -// far more than a person can produce and the output side for the five the plug-in publishes. +// far more than a person can produce. +// +// The output side is sized to the feedback slots it drains into, because that is the most distinct +// parameters this host can do anything with. It used to be 8, sized for "the five the plug-in +// publishes", and that missed the MIDI echoes: the plug-in also reports every parameter its learn +// table moved, one queue per distinct id, so a MIDI burst landing in one block wanted 5 + 6 and the +// sixth echo was a malloc on this thread. Each queue holds one point however often it is written, +// because addPoint replaces a point at the same sample offset and the plug-in writes them all at 0. constexpr int32 kMaxInputParameters = 64; -constexpr int32 kMaxOutputParameters = 8; +constexpr int32 kMaxOutputParameters = JackClient::kFeedbackSlots; +// The plug-in's own worst case: every feedback value plus an echo from every learn row at once. +static_assert(kFeedbackCount + kMidiLearnRowCount <= kMaxOutputParameters, + "a block in which every MIDI row fires would outgrow the output queue"); // One block of MIDI. A footswitch sends one message; this is sized for a controller sweeping a // bank of pedals, and anything past it is dropped rather than grown into. diff --git a/products/rations/tools/macstub/Cocoa/Cocoa.h b/products/rations/tools/macstub/Cocoa/Cocoa.h index 87e2ee9..b748130 100644 --- a/products/rations/tools/macstub/Cocoa/Cocoa.h +++ b/products/rations/tools/macstub/Cocoa/Cocoa.h @@ -132,6 +132,7 @@ enum { @interface NSEvent : NSObject - (NSPoint)locationInWindow; - (NSEventModifierFlags)modifierFlags; +- (NSInteger)clickCount; - (CGFloat)deltaY; - (NSString *)characters; - (NSString *)charactersIgnoringModifiers; diff --git a/products/rations/tools/macstub/seamcheck.mm b/products/rations/tools/macstub/seamcheck.mm index 26ccc82..04dbc8d 100644 --- a/products/rations/tools/macstub/seamcheck.mm +++ b/products/rations/tools/macstub/seamcheck.mm @@ -24,21 +24,21 @@ void onDraw(cairo_t *cr) SMTG_OVERRIDE { (void)cr; } - void onMouseDown(int x, int y, int button) SMTG_OVERRIDE + void onMouseDown(int x, int y, int button, unsigned mods, bool doubleClick) SMTG_OVERRIDE { - (void)x, (void)y, (void)button; + (void)x, (void)y, (void)button, (void)mods, (void)doubleClick; } void onMouseUp(int x, int y, int button) SMTG_OVERRIDE { (void)x, (void)y, (void)button; } - void onMouseMove(int x, int y) SMTG_OVERRIDE + void onMouseMove(int x, int y, unsigned mods) SMTG_OVERRIDE { - (void)x, (void)y; + (void)x, (void)y, (void)mods; } - void onMouseWheel(int x, int y, int delta) SMTG_OVERRIDE + void onMouseWheel(int x, int y, int delta, unsigned mods) SMTG_OVERRIDE { - (void)x, (void)y, (void)delta; + (void)x, (void)y, (void)delta, (void)mods; } void onTick() SMTG_OVERRIDE { diff --git a/products/rations/tools/panelrender.cpp b/products/rations/tools/panelrender.cpp index 82f6038..da0b68d 100644 --- a/products/rations/tools/panelrender.cpp +++ b/products/rations/tools/panelrender.cpp @@ -64,6 +64,7 @@ const char *const kRequiredImages[] = { "cabinet", "dial", "led_on", + "led_green_on", "led_off", "switch_up_ring", "switch_down_ring", @@ -151,13 +152,14 @@ void drawToggle(Canvas &c, ImageCache &images, const geo::ToggleSpec &t, bool on //------------------------------------------------------------------------ void drawLed(Canvas &c, ImageCache &images, float cx, float cy, bool lit, - float r = static_cast(geo::kLedR)) + float r = static_cast(geo::kLedR), geo::LedColor color = geo::LedColor::Red) { const Rect dest(cx - r, cy - r, 2.0f * r, 2.0f * r); - if (cairo_surface_t *led = images.get(lit ? "led_on" : "led_off")) { + const bool green = color == geo::LedColor::Green; + if (cairo_surface_t *led = images.get(!lit ? "led_off" : (green ? "led_green_on" : "led_on"))) { c.drawImage(led, dest); } else { - c.setColor(lit ? 0xE02020 : 0x141414); + c.setColor(!lit ? 0x141414 : (green ? geo::kAccent : 0xE02020)); c.fillEllipse(dest); } } @@ -428,6 +430,9 @@ void renderHead(Canvas &c, ImageCache &images, SvgCache &icons) static_cast(geo::kIoKnobs[i].cx), static_cast(geo::kIoValueBaselineY)); } + // The input-level lamp, lit: the demo input meter above it is playing. + drawLed(c, images, static_cast(geo::kInputLampCX), static_cast(geo::kInputLampCY), + true, static_cast(geo::kInputLampR), geo::LedColor::Green); for (const geo::ButtonSpec &b : geo::kPageButtons) drawButton(c, b); @@ -1021,6 +1026,22 @@ bool auditHitBoxes() static_cast(geo::kStripColX0 + (i + 1) * geo::kStripColW), static_cast(geo::kStripCaptureY + geo::kStripCaptureDescent)}); + // The six dial readouts are click targets too, since clicking one opens it for typing. They + // share the bottom band with the switches and the page buttons, and the Input field sits + // beside the input meter's column, so they are exactly what this audit is for. Labelled by + // the dial's own legend, from the same table the editor hit-tests. + for (const geo::ValueField &f : geo::kValueFields) { + const char *what = "value field"; + for (const geo::KnobSpec &k : geo::kKnobs) + if (k.id == f.id) + what = k.label; + for (const geo::KnobSpec &k : geo::kIoKnobs) + if (k.id == f.id) + what = k.label; + boxes.push_back({what, static_cast(f.x), static_cast(f.y), + static_cast(f.x + f.w), static_cast(f.y + f.h)}); + } + // The two level meters are not clickable, but a control drawn on top of one is a control // drawn on top of the thing it is supposed to sit beside, so they are in the check as // obstacles. diff --git a/products/rations/tools/rations_lv2check.cpp b/products/rations/tools/rations_lv2check.cpp index 4494508..5bbb294 100644 --- a/products/rations/tools/rations_lv2check.cpp +++ b/products/rations/tools/rations_lv2check.cpp @@ -211,6 +211,7 @@ void checkPorts(LilvWorld *world, const LilvPlugin *plugin) LilvNode *classControl = lilv_new_uri(world, LV2_CORE__ControlPort); LilvNode *classAtom = lilv_new_uri(world, LV2_ATOM__AtomPort); LilvNode *classInput = lilv_new_uri(world, LV2_CORE__InputPort); + LilvNode *optional = lilv_new_uri(world, LV2_CORE__connectionOptional); const uint32_t count = lilv_plugin_get_num_ports(plugin); checkf(count == kPortCount, "the bundle declares %u ports; the code expects %u", count, @@ -263,8 +264,22 @@ void checkPorts(LilvWorld *world, const LilvPlugin *plugin) // The feedback block and the latency port. checkf(lilv_port_is_a(plugin, port, classControl), "port %u should be a control port", i); checkf(!isInput, "port %u should be an output", i); + if (i >= kPortFeedbackFirst && i < kPortLatency) { + // By symbol as well as by index, because a symbol is what a host's saved state keys + // on, and connectionOptional exactly where the table says, because a port added after + // the bundle shipped is allowed under the same URI only with it. + const FeedbackPort &want = kFeedbackPorts[i - kPortFeedbackFirst]; + const LilvNode *symbol = lilv_port_get_symbol(plugin, port); + const char *got = symbol ? lilv_node_as_string(symbol) : ""; + checkf(std::strcmp(got, want.symbol) == 0, "port %u is \"%s\"; the code says \"%s\"", i, + got, want.symbol); + checkf(lilv_port_has_property(plugin, port, optional) == want.optional, + "port %u (%s) %s lv2:connectionOptional", i, want.symbol, + want.optional ? "must be" : "must not be"); + } } + lilv_node_free(optional); lilv_node_free(classInput); lilv_node_free(classAtom); lilv_node_free(classControl); @@ -1085,8 +1100,13 @@ void checkInstantiate(LilvWorld *world, const LilvPlugin *plugin) lilv_instance_connect_port(instance, kPortControlFirst + i, &gPortValues[kPortControlFirst + i]); } - for (uint32_t i = kPortFeedbackFirst; i < kPortCount; ++i) - lilv_instance_connect_port(instance, i, &gPortValues[i]); + // Every feedback port except the connection-optional ones, which are explicitly left + // unconnected, as a host is entitled to. The 32 blocks below are then the proof that the + // wrapper writes only the ports it was given. + for (uint32_t i = kPortFeedbackFirst; i < kPortCount; ++i) { + const bool optional = i < kPortLatency && kFeedbackPorts[i - kPortFeedbackFirst].optional; + lilv_instance_connect_port(instance, i, optional ? nullptr : &gPortValues[i]); + } lilv_instance_activate(instance); for (int block = 0; block < 32; ++block) { diff --git a/products/rations/tools/rations_midicheck.cpp b/products/rations/tools/rations_midicheck.cpp index 9b229b1..2ea80ca 100644 --- a/products/rations/tools/rations_midicheck.cpp +++ b/products/rations/tools/rations_midicheck.cpp @@ -193,6 +193,10 @@ struct Block { // general form, because what a footswitch row echoes is a value it COMPUTED and the whole // point is to check which one. std::vector> echoes; + // How much of the output queue the block used: queues claimed, and the most points any one of + // them held. A host has to reserve both before the audio thread runs. + int outQueues = 0; + int maxPoints = 0; }; // What the plug-in said it did to one parameter this block, if it said anything. @@ -263,6 +267,12 @@ struct Harness { b.echoes.clear(); processor->process(data); + b.outQueues = outParamChanges.getParameterCount(); + b.maxPoints = 0; + for (int32 i = 0; i < b.outQueues; ++i) + if (Vst::IParamValueQueue *q = outParamChanges.getParameterData(i)) + b.maxPoints = std::max(b.maxPoints, static_cast(q->getPointCount())); + // The plug-in reporting a parameter it changed by itself, and the hidden read-only // parameter that says which channel is actually SOUNDING - the request and the answer, // which are not the same thing while a switch is being held. @@ -1431,6 +1441,57 @@ int main(int argc, char **argv) } } + // --- 8. every row in one block ------------------------------------------------------------- + // + // A host reserves its output queue before the audio thread runs, because addParameterData + // grows it with `new` once the reserve is used up (public.sdk/source/vst/hosting/ + // parameterchanges.cpp). What this plug-in can put in it in one block is every feedback value + // plus an echo of every parameter its learn table moved, so that is measured here: every row + // taught its own CC, and every CC pressed at once. The standalones assert the same bound at + // compile time; this is the half that says the plug-in really stays inside it. They used to + // reserve 8, which a footswitch burst outgrew. + printf("every row in one block\n"); + { + constexpr int kFirstCc = 90; + for (int row = 0; row < kMidiLearnRowCount; ++row) { + sendMessage(hostContext, component, kMsgMidiLearn, &row); + Block teach; + teach.params.push_back(cc(kFirstCc + row, 127)); + rig.run(teach); + } + Block release; + for (int row = 0; row < kMidiLearnRowCount; ++row) + release.params.push_back(cc(kFirstCc + row, 0)); + rig.run(release); + Block all; + for (int row = 0; row < kMidiLearnRowCount; ++row) + all.params.push_back(cc(kFirstCc + row, 127)); + rig.run(all); + + // Rows can share a target - every channel row sets kChannelId - and the queue holds one + // entry per DISTINCT id, so that is what the count is compared with. + std::vector targets; + for (const MidiLearnTarget &row : kMidiLearnRows) + if (std::find(targets.begin(), targets.end(), row.param) == targets.end()) + targets.push_back(row.param); + bool everyTarget = true; + for (Vst::ParamID id : targets) { + double v = 0.0; + everyTarget = everyTarget && echoOf(all, id, v); + } + check(everyTarget, "every row fires in the same block"); + + char detail[96]; + snprintf(detail, sizeof detail, "%d queues for %d feedback values and %d moved parameters", + all.outQueues, kFeedbackCount, static_cast(targets.size())); + check(all.outQueues == kFeedbackCount + static_cast(targets.size()), + "one output queue per feedback value and per moved parameter", detail); + check(all.outQueues <= kFeedbackCount + kMidiLearnRowCount, + "... which is inside the reserve the standalones make", detail); + check(all.maxPoints == 1, "every output queue holds a single point"); + printf(" measured: %s\n", detail); + } + processor->setProcessing(false); component->setActive(false); diff --git a/products/rations/tools/rations_rtcheck.cpp b/products/rations/tools/rations_rtcheck.cpp index 6da3390..181aeb2 100644 --- a/products/rations/tools/rations_rtcheck.cpp +++ b/products/rations/tools/rations_rtcheck.cpp @@ -19,7 +19,8 @@ // burst is still the audio thread: it feeds the incoming channel out of the input ring inside // the same process() call, so every rule that applies to the steady state applies to it. This // is also where a ring read, a fade buffer or a chunk stage that was sized wrong would show -// up, because those only run during a switch. +// up, because those only run during a switch. The input-level lamp runs in the same loop, +// fed the gain soundingInputGain() reads across the switch, as the processor feeds it. // 5. The cabinet stage with both IR slots filled and the blend dial sweeping. AudioDSPTools // sizes an ImpulseResponse's history and output buffers on its FIRST Process call, which for // an IR loaded mid-session would be a malloc on the audio thread. The plug-in avoids that by @@ -34,6 +35,7 @@ #include "channelrack.h" #include "crossfadeengine.h" #include "engineconfig.h" +#include "inputlevellamp.h" #include "irblend.h" #include "midilearn.h" #include "modelbank.h" @@ -202,6 +204,9 @@ int main(int argc, char **argv) return 1; } + Rations::InputLevelLamp lamp; + lamp.reset(Rations::kNativeSampleRate); + // The stomp period is deliberately shorter than a whole switch takes, so some requests // land mid-catch-up and some mid-fade. Both are the paths that only exist here. auto drive = [&](int blocks) { @@ -221,15 +226,17 @@ int main(int argc, char **argv) 0.25 + 0.5 * std::fabs(std::fmod(t, 2.0) - 1.0)); rack.setLevel(Rations::kChannelOd1, 4.0 - 3.0 * std::fabs(std::fmod(t, 2.0) - 1.0)); rack.requestChannel(want); + lamp.process(in.data(), kBlock, rack.soundingInputGain()); rack.processNative(&ip, &op, kBlock); } }; drive(8); // warm anything lazily sized before the count starts - printf("counting channel rack, stomping between two channels, trims moving\n"); + printf("counting channel rack, stomping between two channels, trims moving, lamp " + "running\n"); allocation_tracking::run_allocation_test_no_allocations( nullptr, [&] { drive(200); }, nullptr, - "channel rack, stomping between two channels, trims moving"); + "channel rack, stomping between two channels, trims moving, lamp running"); rack.stop(); rack.releaseBanks(); diff --git a/products/rations/tools/rations_ttlgen.cpp b/products/rations/tools/rations_ttlgen.cpp index c57f720..90976d9 100644 --- a/products/rations/tools/rations_ttlgen.cpp +++ b/products/rations/tools/rations_ttlgen.cpp @@ -481,19 +481,14 @@ bool writePluginTtl(const std::string &path, const std::vector &ports) fprintf(f, " , "); } - static const char *kFeedbackNames[kFeedbackCount] = { - "Input Meter", "Output Meter", "Bank Progress", "Active Capture", "Active Channel", - }; - static const char *kFeedbackSymbols[kFeedbackCount] = { - "input_meter", "output_meter", "bank_progress", "active_capture", "active_channel", - }; for (int i = 0; i < kFeedbackCount; ++i) { + const FeedbackPort &port = kFeedbackPorts[i]; fprintf(f, "[\n\t\ta lv2:OutputPort ,\n\t\t\tlv2:ControlPort ;\n\t\tlv2:index %u ;\n" - "\t\tlv2:symbol \"%s\" ;\n\t\tlv2:name \"%s\" ;\n" + "\t\tlv2:symbol \"%s\" ;\n\t\tlv2:name \"%s\" ;\n%s" "\t\tlv2:default 0.0 ;\n\t\tlv2:minimum 0.0 ;\n\t\tlv2:maximum 1.0\n\t] , ", - kPortFeedbackFirst + static_cast(i), kFeedbackSymbols[i], - kFeedbackNames[i]); + kPortFeedbackFirst + static_cast(i), port.symbol, port.name, + port.optional ? "\t\tlv2:portProperty lv2:connectionOptional ;\n" : ""); } // Latency. The VST3 build reports it through getLatencySamples(); LV2's way of saying the same