desc:Overstratum Thickener
author: Overstratum Audio

// Overstratum Thickener
// Band-limited density/colour processor with always-on loudness matching.
//
// ---------------------------------------------------------------------------
// THIRD-PARTY CODE
// ---------------------------------------------------------------------------
// The core density/colour processing (pre-filters, colour peak filter incl.
// digital Q correction, compressor/saturation stage and its constants) is
// derived from "JClones_Fattener" of the JClones JSFX collection:
// https://github.com/JClones/JSFXClones
//
// MIT License
//
// Copyright (c) 2026 JClones
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// ---------------------------------------------------------------------------
// PUBLISHED ALGORITHM REFERENCES (no licence obligations, credited for clarity)
// ---------------------------------------------------------------------------
// - Biquad high-pass / peaking EQ: R. Bristow-Johnson, "Audio EQ Cookbook".
// - Loudness measurement: ITU-R BS.1770 K-weighting & short-term loudness.
// - Band crossover: trapezoidal-integrated state variable filter after
//   A. Simper (Cytomic), arranged as Linkwitz-Riley 24 dB/oct 3-way split.

slider1:20.0<0,100,0.1>-Thickening (%)
slider2:50.0<0,100,0.1>-Color (%)
// slider3 (Output Gain) and slider5 (Auto Gain switch) retired: Auto Gain is always active,
// the manual offset is now the relative Band Trim (slider10). Indices left free for project compatibility.
slider4:100.0<0,100,0.1>-Mix (%)
slider6:0<0,1,1{Off,On}>-Delta
slider7:0<0,1,1{Off,On}>-Bypass
slider8:20<20,20000,1:log>-Band Low (Hz)
slider9:20000<20,20000,1:log>-Band High (Hz)
slider10:0<-12,12,0.01>-Band Trim (dB)
slider11:0<0,1,1{Off,On}>-Solo Band

@init
ext_noinit = 1;
gfx_ext_retina = 1;
gfx_clear = -1;

// --- Memory Allocation for FFT & LUFS Ringbuffers ---
// 4096-point FFT for usable low-end resolution (needed for band handles around 100-300 Hz)
dsp_fft_size  = 4096;
dsp_fft_hop   = 1024;            // overlapped analysis (~47 frames/s @ 48 kHz)
dsp_fft_ring  = 20480;           // 4096 entries
dsp_fft_win   = 24576;           // 4096 entries
dsp_fft_buf   = 32768;           // 8192 entries (complex), does not cross a 65536 boundary
disp_main     = 40960;           // 2049 entries
dsp_fft_norm  = 4.0 / dsp_fft_size; // 2/N amplitude norm, +6 dB to keep broadband level as with the former 1024 FFT

// Crossover constants (Linkwitz-Riley 24 dB/oct built from cascaded Butterworth SVFs)
xo_k          = sqrt(2.0);       // 1/Q for Butterworth
xo_min_ratio  = 1.25;            // minimum High/Low ratio (~1/3 octave)
xo_f_min      = 20.0;
xo_f_max      = 20000.0;

// 3-Second Short-Term LUFS Sub-Block Ringbuffers (60 blocks @ 50ms = 3.0s)
lufs_buf_in   = 16384;
lufs_buf_proc = 16512;
lufs_num_blocks = 60;

// --- Safe Math & DSP Helper Functions ---
function dsp_db_to_k(x) local() (
  10.0 ^ (x / 20.0);
);

function dsp_tanh_safe(x) local(cx, e2x) (
  cx = min(max(x, -10.0), 10.0);
  e2x = exp(2.0 * cx);
  (e2x - 1.0) / (e2x + 1.0);
);

function dsp_biquad_reset() local() (
  this.x1 = 0.0; this.x2 = 0.0;
  this.y1 = 0.0; this.y2 = 0.0;
);

function dsp_biquad_proc(x0) local(y0) (
  y0 = x0 * this.a0 + this.x1 * this.a1 + this.x2 * this.a2 + this.y1 * this.b1 + this.y2 * this.b2;
  this.x2 = this.x1; this.x1 = x0;
  this.y2 = this.y1; this.y1 = y0;
  y0;
);

function dsp_biquad_hp(freq_k, q_val) local(omega0, alpha, cos_w, norm) (
  freq_k = min(max(freq_k, 0.0001), 0.49);
  omega0 = freq_k * 2.0 * $pi;
  cos_w = cos(omega0);
  alpha = sin(omega0) / (2.0 * q_val);
  norm = 1.0 / (1.0 + alpha);
  this.a0 = ((1.0 + cos_w) * 0.5) * norm;
  this.a1 = -(1.0 + cos_w) * norm;
  this.a2 = ((1.0 + cos_w) * 0.5) * norm;
  this.b1 = (2.0 * cos_w) * norm;
  this.b2 = -(1.0 - alpha) * norm;
);

function dsp_biquad_peak(freq_k, q_val, lin_gain) local(amp, w0, alpha, cos_w, norm) (
  freq_k = min(max(freq_k, 0.0002), 0.48);
  amp = sqrt(max(lin_gain, 0.0001));
  w0 = freq_k * 2.0 * $pi;
  cos_w = cos(w0);
  alpha = sin(w0) / (2.0 * max(q_val, 0.05));
  norm = 1.0 / (1.0 + alpha / amp);
  this.a0 = (1.0 + alpha * amp) * norm;
  this.a1 = (-2.0 * cos_w) * norm;
  this.a2 = (1.0 - alpha * amp) * norm;
  this.b1 = (2.0 * cos_w) * norm;
  this.b2 = -(1.0 - alpha / amp) * norm;
);

// --- ITU-R BS.1770 K-Weighting Filter Setup ---
function dsp_biquad_k_shelf(sr) local(f0, gain_db, q_val, A, w0, cos_w, sin_w, alpha, two_sqrtA_alpha, a0_inv) (
  f0 = min(1681.974450955533, sr * 0.48);
  gain_db = 3.999843853973347;
  q_val = 0.7071752369554196;
  A = 10.0 ^ (gain_db / 40.0);
  w0 = 2.0 * $pi * f0 / sr;
  cos_w = cos(w0);
  sin_w = sin(w0);
  alpha = sin_w / (2.0 * q_val);
  two_sqrtA_alpha = 2.0 * sqrt(A) * alpha;
  a0_inv = 1.0 / ((A + 1.0) - (A - 1.0) * cos_w + two_sqrtA_alpha);

  this.a0 = (A * ((A + 1.0) + (A - 1.0) * cos_w + two_sqrtA_alpha)) * a0_inv;
  this.a1 = (-2.0 * A * ((A - 1.0) + (A + 1.0) * cos_w)) * a0_inv;
  this.a2 = (A * ((A + 1.0) + (A - 1.0) * cos_w - two_sqrtA_alpha)) * a0_inv;
  this.b1 = (-2.0 * ((A - 1.0) - (A + 1.0) * cos_w)) * a0_inv;
  this.b2 = -((A + 1.0) - (A - 1.0) * cos_w - two_sqrtA_alpha) * a0_inv;
);

function dsp_biquad_k_hp(sr) local(f0, q_val, w0, cos_w, sin_w, alpha, a0_inv) (
  f0 = min(38.13547087602444, sr * 0.48);
  q_val = 0.5003270373238773;
  w0 = 2.0 * $pi * f0 / sr;
  cos_w = cos(w0);
  sin_w = sin(w0);
  alpha = sin_w / (2.0 * q_val);
  a0_inv = 1.0 / (1.0 + alpha);

  this.a0 = ((1.0 + cos_w) * 0.5) * a0_inv;
  this.a1 = -(1.0 + cos_w) * a0_inv;
  this.a2 = ((1.0 + cos_w) * 0.5) * a0_inv;
  this.b1 = (2.0 * cos_w) * a0_inv;
  this.b2 = -(1.0 - alpha) * a0_inv;
);

function kw_ch_init(sr) local() (
  this.shelf.dsp_biquad_k_shelf(sr);
  this.hp.dsp_biquad_k_hp(sr);
);

function kw_ch_reset() local() (
  this.shelf.dsp_biquad_reset();
  this.hp.dsp_biquad_reset();
);

function kw_ch_proc(x) local() (
  this.hp.dsp_biquad_proc(this.shelf.dsp_biquad_proc(x));
);

function lufs_window_clear() local(i) (
  lufs_sub_cnt       = 0;
  lufs_sub_in_acc    = 0.0;
  lufs_sub_proc_acc  = 0.0;
  lufs_sum_in        = 0.0;
  lufs_sum_proc      = 0.0;
  lufs_buf_idx       = 0;
  lufs_filled_blocks = 0;
  ag_lufs_trim_target_db = 0.0;

  i = 0;
  loop(lufs_num_blocks,
    lufs_buf_in[i]   = 0.0;
    lufs_buf_proc[i] = 0.0;
    i += 1;
  );
);

function lufs_engine_init(sr) local() (
  kw_in_l.kw_ch_init(sr);   kw_in_l.kw_ch_reset();
  kw_in_r.kw_ch_init(sr);   kw_in_r.kw_ch_reset();
  kw_proc_l.kw_ch_init(sr); kw_proc_l.kw_ch_reset();
  kw_proc_r.kw_ch_init(sr); kw_proc_r.kw_ch_reset();

  lufs_sub_size = max(floor(sr * 0.05), 64); // 50ms sub-block

  // Stage 1 (Real-Time RMS) time constants
  rms_coeff_fast  = exp(-1.0 / (sr * 0.015)); // 15ms fast acquisition
  rms_coeff_slow  = exp(-1.0 / (sr * 0.350)); // 350ms steady tracking
  rms_track_fast  = exp(-1.0 / (sr * 0.015)); // 15ms fast gain glide
  rms_track_slow  = exp(-1.0 / (sr * 0.250)); // 250ms steady gain glide

  // Stage 2 (LUFS-S Trim) smoothing time constant
  lufs_trim_coeff = exp(-1.0 / (sr * 0.180)); // 180ms smooth LUFS trim

  lufs_window_clear();
);

function dsp_get_digital_q(q_val, freq_k) local(w0, c_val) (
  w0 = freq_k * 2.0 * $pi;
  c_val = cos(w0 * 0.5);
  1.5 * (c_val + 1.0) * c_val / (2.0 * c_val + 1.0) * q_val;
);

function dsp_ch_set_srate(sr) local() (
  this.hp1.dsp_biquad_hp(20.0 / sr, 0.7071);
  this.hp2.dsp_biquad_hp(30.0 / sr, 0.7071);
  this.attack_k = exp(-1.0 / (sr * 0.00269));
  this.release_k = exp(-1.0 / (sr * 0.0329));
);

function dsp_ch_reset() local() (
  this.hp1.dsp_biquad_reset();
  this.hp2.dsp_biquad_reset();
  this.peak3.dsp_biquad_reset();
  this.level_s = 0.0;
);

function dsp_ch_preproc(x) local() (
  this.peak3.dsp_biquad_proc(this.hp2.dsp_biquad_proc(this.hp1.dsp_biquad_proc(x)));
);

function dsp_ch_postproc(x_pp, level_pp) local(k, gr, y, thr, scale) (
  k = level_pp > this.level_s ? this.attack_k : this.release_k;
  this.level_s = (1.0 - k) * level_pp + k * this.level_s;
  gr = (this.level_s > this.threshold) ? pow(this.level_s / this.threshold, this.inv_ratio - 1.0) : 1.0;
  y = x_pp * gr * this.output_gain;
  thr = this.sat_threshold;
  (abs(y) > thr) ? (
    (thr < 0.9999) ? (
      scale = 1.0 - thr;
      y > 0.0 ? (
        y = dsp_tanh_safe((y - thr) / scale) * scale + thr;
      ) : (
        y = -(dsp_tanh_safe((-y - thr) / scale) * scale + thr);
      );
    ) : (
      y = y > 0.0 ? thr : -thr;
    );
  );
  y * this.final_gain;
);

function dsp_ch_set_density(dens) local() (
  this.threshold = dsp_db_to_k(-(dens * 34.0 + 1.0));
  this.output_gain = dsp_db_to_k(dens * 39.0 + 1.0);
  this.inv_ratio = 0.1;
  this.final_gain = dsp_db_to_k(-0.1);
);

function dsp_ch_set_color(col, sr) local(gain_db, freq_hz, fk) (
  gain_db = col * 8.0;
  freq_hz = pow(col, 3.219) * 6680.0 + 40.0;
  freq_hz = min(freq_hz, sr * 0.5 - 120.0);
  fk = freq_hz / sr;
  this.peak3.dsp_biquad_peak(fk, dsp_get_digital_q(0.71, fk), dsp_db_to_k(gain_db));
  this.sat_threshold = min(0.1 * col + 0.9, 0.9995);
);

// --- Band Crossover (zero-latency, magnitude-flat LR4 3-way split) ---
// Topology: x -> LR4 @ f1 -> [LOW | REST]; REST -> LR4 @ f2 -> [MID | HIGH]; LOW -> 2nd-order allpass @ f2.
// LOW + MID + HIGH sums to an allpass (flat magnitude), only MID is processed.
function svf_reset() local() (
  this.ic1 = 0.0; this.ic2 = 0.0;
  this.lp = 0.0; this.bp = 0.0; this.hp = 0.0;
);

// Cytomic/Simper TPT state variable filter (modulation-safe for smooth handle dragging)
function svf_proc(v0, a1, a2, a3) local(v1, v2, v3) (
  v3 = v0 - this.ic2;
  v1 = a1 * this.ic1 + a2 * v3;
  v2 = this.ic2 + a2 * this.ic1 + a3 * v3;
  this.ic1 = 2.0 * v1 - this.ic1;
  this.ic2 = 2.0 * v2 - this.ic2;
  this.bp = v1;
  this.lp = v2;
  this.hp = v0 - xo_k * v1 - v2;
);

function xo_ch_reset() local() (
  this.s1a.svf_reset(); this.s1l.svf_reset(); this.s1h.svf_reset();
  this.s2a.svf_reset(); this.s2l.svf_reset(); this.s2h.svf_reset();
  this.ap.svf_reset();
  this.lo = 0.0; this.mid = 0.0; this.hi = 0.0;
);

function xo_ch_proc(x) local(l, r1, m, ap_out) (
  // Split 1 (Low Cut of processing band)
  this.s1a.svf_proc(x, xo1_a1, xo1_a2, xo1_a3);
  this.s1l.svf_proc(this.s1a.lp, xo1_a1, xo1_a2, xo1_a3);
  this.s1h.svf_proc(this.s1a.hp, xo1_a1, xo1_a2, xo1_a3);
  l  = xo_lo_w * this.s1l.lp;
  r1 = xo_lo_w * this.s1h.hp + (1.0 - xo_lo_w) * x;

  // Split 2 (High Cut of processing band)
  this.s2a.svf_proc(r1, xo2_a1, xo2_a2, xo2_a3);
  this.s2l.svf_proc(this.s2a.lp, xo2_a1, xo2_a2, xo2_a3);
  this.s2h.svf_proc(this.s2a.hp, xo2_a1, xo2_a2, xo2_a3);
  m = xo_hi_w * this.s2l.lp + (1.0 - xo_hi_w) * r1;
  this.hi = xo_hi_w * this.s2h.hp;

  // Phase-align LOW band with the f2 split
  this.ap.svf_proc(l, xo2_a1, xo2_a2, xo2_a3);
  ap_out = l - 2.0 * xo_k * this.ap.bp;
  this.lo  = xo_hi_w * ap_out + (1.0 - xo_hi_w) * l;
  this.mid = m;
);

function xo_update_targets(sr) local(f1, f2, fmax) (
  fmax = sr * 0.45;
  xo_lo_on = slider8 > xo_f_min + 0.5 ? 1 : 0;
  // A high split at/above the usable Nyquist range is pointless -> treat as off
  xo_hi_on = slider9 < min(xo_f_max - 0.5, fmax) ? 1 : 0;
  f1 = min(max(slider8, xo_f_min), fmax / xo_min_ratio);
  f2 = min(max(slider9, f1 * xo_min_ratio), fmax);
  dsp_band_lo_hz = f1;
  dsp_band_hi_hz = f2;
  xo_g1_t = tan($pi * f1 / sr);
  xo_g2_t = tan($pi * f2 / sr);
  xo_lo_w_t = xo_lo_on;
  xo_hi_w_t = xo_hi_on;
  xo_snap ? (
    xo_g1 = xo_g1_t; xo_g2 = xo_g2_t;
    xo_lo_w = xo_lo_w_t; xo_hi_w = xo_hi_w_t;
    xo_snap = 0;
  );
);

function dsp_update_params() local(sr) (
  sr = srate > 0 ? srate : 44100.0;
  dsp_density_norm = slider1 / 100.0;
  dsp_color_norm   = slider2 / 100.0;
  dsp_trim_db      = slider10;
  dsp_mix_target   = slider4 / 100.0;
  dsp_delta_on     = slider6 >= 0.5 ? 1 : 0;
  dsp_bypass_on    = slider7 >= 0.5 ? 1 : 0;
  dsp_solo_on      = slider11 >= 0.5 ? 1 : 0;
  dsp_rest_g_t     = dsp_solo_on ? 0.0 : 1.0;   // level of the untouched outside bands

  // Enforce mutual exclusion: Bypass has strict priority over Delta
  dsp_bypass_on ? (
    dsp_delta_on = 0;
  );

  dsp_color_freq_hz = min(pow(dsp_color_norm, 3.219) * 6680.0 + 40.0, sr * 0.5 - 120.0);
  dsp_color_gain_db = dsp_color_norm * 8.0;

  dsp_left.dsp_ch_set_density(dsp_density_norm);
  dsp_right.dsp_ch_set_density(dsp_density_norm);
  dsp_left.dsp_ch_set_color(dsp_color_norm, sr);
  dsp_right.dsp_ch_set_color(dsp_color_norm, sr);

  xo_update_targets(sr);
);

function dsp_set_srate_consts(sr) local() (
  dsp_left.dsp_ch_set_srate(sr);
  dsp_right.dsp_ch_set_srate(sr);
  dsp_smooth_coeff    = exp(-1.0 / (sr * 0.005)); // 5ms parameter smoothing
  dsp_gr_smooth_coeff = exp(-1.0 / (sr * 0.010)); // 10ms GR smoothing
  dsp_meter_decay     = exp(-1.0 / (sr * 0.045)); // peak meter release (sample-rate independent)
  dsp_solo_coeff      = exp(-1.0 / (sr * 0.010)); // 10ms solo fade
  xo_g_coeff          = exp(-1.0 / (sr * 0.020)); // 20ms crossover frequency glide
  xo_w_coeff          = exp(-1.0 / (sr * 0.015)); // 15ms split on/off crossfade
  xo_l.xo_ch_reset();
  xo_r.xo_ch_reset();
  xo_snap = 1;
  lufs_engine_init(sr);
);

// --- One-Time Initialization ---
!dsp_init_done ? (
  dsp_left.dsp_ch_reset();
  dsp_right.dsp_ch_reset();
  // Use the real sample rate (former max(srate, 44100) detuned all filters below 44.1 kHz
  // and made @block re-initialise once after load)
  dsp_sample_rate = srate > 0 ? srate : 44100.0;
  dsp_set_srate_consts(dsp_sample_rate);

  // Initial static estimate before the very first audio sample arrives
  ag_rms_db_target       = -(slider1 * 0.35);
  ag_rms_db_state        = ag_rms_db_target;
  ag_lufs_trim_target_db = 0.0;
  ag_lufs_trim_state_db  = 0.0;
  dsp_auto_gain_db       = ag_rms_db_state;

  rms_is_seeded   = 0;
  ag_fast_samples = floor(dsp_sample_rate * 0.200);
  silence_counter = 0;

  dsp_ag_lin_state   = dsp_db_to_k(dsp_auto_gain_db);
  dsp_trim_db        = slider10;
  dsp_applied_db     = dsp_auto_gain_db + dsp_trim_db;
  dsp_gain_lin_state = dsp_db_to_k(dsp_applied_db);
  dsp_mix_state      = slider4 / 100.0;
  dsp_rest_g         = slider11 >= 0.5 ? 0.0 : 1.0;
  dsp_rest_g_t       = dsp_rest_g;
  dsp_meter_gr_out   = 0.0;
  dsp_meter_gr_db    = 0.0;
  lufs_valid_gate    = 0;
  input_lufs         = -100.0;
  processed_lufs     = -100.0;

  ui_smooth_in_db  = -60.0;
  ui_smooth_out_db = -60.0;
  ui_smooth_gr_db  = 0.0;
  ui_txt_in_db     = -60.0;
  ui_txt_out_db    = -60.0;
  ui_txt_gr_db     = 0.0;

  dsp_init_i = 0;
  loop(dsp_fft_size,
    dsp_fft_win[dsp_init_i] = 0.5 * (1.0 - cos(2.0 * $pi * dsp_init_i / dsp_fft_size)); // periodic Hann
    dsp_fft_ring[dsp_init_i] = 0.0;
    dsp_init_i += 1;
  );
  dsp_fft_pos = 0;
  dsp_fft_hop_cnt = 0;
  dsp_init_i = 0;
  loop(dsp_fft_size * 0.5 + 1,
    disp_main[dsp_init_i] = 0.00001;
    dsp_init_i += 1;
  );

  dsp_prev_s1 = slider1;
  dsp_prev_s2 = slider2;
  dsp_prev_s4 = slider4;
  dsp_prev_s6 = slider6;
  dsp_prev_s7 = slider7;
  dsp_prev_s8 = slider8;
  dsp_prev_s9 = slider9;
  param_dirty = 1;
  dsp_init_done = 1;
);

@slider
// Trigger fast Stage-1 RMS acquisition & clear stale 3s LUFS history if sound parameters change
(abs(slider1 - dsp_prev_s1) > 0.001 || abs(slider2 - dsp_prev_s2) > 0.001 || abs(slider4 - dsp_prev_s4) > 0.001 ||
 abs(slider8 - dsp_prev_s8) > 0.001 || abs(slider9 - dsp_prev_s9) > 0.001) ? (
  ag_param_changed = 1;
  dsp_prev_s1 = slider1;
  dsp_prev_s2 = slider2;
  dsp_prev_s4 = slider4;
  dsp_prev_s8 = slider8;
  dsp_prev_s9 = slider9;
);


// Enforce mutual exclusion between Bypass (slider7) and Delta (slider6)
(slider7 >= 0.5 && dsp_prev_s7 < 0.5) ? (
  slider6 != 0 ? (
    slider6 = 0;
    slider_automate(32);
  );
) : (slider6 >= 0.5 && dsp_prev_s6 < 0.5) ? (
  slider7 != 0 ? (
    slider7 = 0;
    slider_automate(64);
  );
);
(slider7 >= 0.5 && slider6 >= 0.5) ? (
  slider6 = 0;
  slider_automate(32);
);
dsp_prev_s6 = slider6;
dsp_prev_s7 = slider7;
param_dirty = 1;

@block
(srate != dsp_sample_rate && srate > 0) ? (
  dsp_sample_rate = srate;
  dsp_set_srate_consts(dsp_sample_rate);
  param_dirty = 1;
);

// Detect REAPER transport Play start: trigger fast RMS lock-on for immediate startup stability
is_playing = (play_state & 1);
(is_playing && !dsp_was_playing) ? (
  ag_fast_samples = floor(dsp_sample_rate * 0.200);
  !rms_is_seeded ? (
    rms_need_seed = 1;
  );
);
dsp_was_playing = is_playing;

// Handle processing parameter changes (Density, Color, Mix)
ag_param_changed ? (
  ag_fast_samples = floor(dsp_sample_rate * 0.200);
  lufs_window_clear();
  !is_playing ? (
    rms_need_seed = 1;
  );
  ag_param_changed = 0;
);

param_dirty ? (
  dsp_update_params();
  param_dirty = 0;
);

// Process FFT in @block when ringbuffer is ready
dsp_fft_ready ? (
  dsp_fft_ready = 0;
  // Unwrap circular ring (oldest sample first = current write position)
  dsp_bi = 0;
  dsp_ri = dsp_fft_pos;
  loop(dsp_fft_size,
    dsp_fft_buf[dsp_bi * 2]     = dsp_fft_ring[dsp_ri] * dsp_fft_win[dsp_bi];
    dsp_fft_buf[dsp_bi * 2 + 1] = 0.0;
    dsp_bi += 1;
    dsp_ri += 1;
    dsp_ri >= dsp_fft_size ? dsp_ri = 0;
  );
  fft(dsp_fft_buf, dsp_fft_size);
  fft_permute(dsp_fft_buf, dsp_fft_size);

  dsp_bi = 1;
  dsp_half = dsp_fft_size * 0.5;
  dsp_inv_n = dsp_fft_norm;
  loop(dsp_half,
    dsp_re = dsp_fft_buf[dsp_bi * 2];
    dsp_im = dsp_fft_buf[dsp_bi * 2 + 1];
    dsp_mag = sqrt(dsp_re * dsp_re + dsp_im * dsp_im) * dsp_inv_n;
    disp_main[dsp_bi] = disp_main[dsp_bi] * 0.72 + dsp_mag * 0.28;
    dsp_bi += 1;
  );
  disp_main[0] = disp_main[1] * 0.92;
);

@sample
// =========================================================================
// 1. CAPTURE ORIGINAL REFERENCE INPUT (Before any processing)
// =========================================================================
in_orig_l = spl0;
in_orig_r = spl1;

// Input Peak Metering
dsp_in_peak_inst = max(abs(in_orig_l), abs(in_orig_r));
dsp_meter_in = dsp_in_peak_inst > dsp_meter_in ? dsp_in_peak_inst : dsp_meter_in * dsp_meter_decay;

// =========================================================================
// 1b. BAND SPLIT (only the MID band between Low/High handle gets processed)
// =========================================================================
xo_g1   = xo_g1   * xo_g_coeff + xo_g1_t   * (1.0 - xo_g_coeff);
xo_g2   = xo_g2   * xo_g_coeff + xo_g2_t   * (1.0 - xo_g_coeff);
xo_lo_w = xo_lo_w * xo_w_coeff + xo_lo_w_t * (1.0 - xo_w_coeff);
xo_hi_w = xo_hi_w * xo_w_coeff + xo_hi_w_t * (1.0 - xo_w_coeff);
xo_lo_w < 0.00001 ? ( xo_lo_w = 0.0; ) : xo_lo_w > 0.99999 ? ( xo_lo_w = 1.0; );
xo_hi_w < 0.00001 ? ( xo_hi_w = 0.0; ) : xo_hi_w > 0.99999 ? ( xo_hi_w = 1.0; );

xo1_a1 = 1.0 / (1.0 + xo_g1 * (xo_g1 + xo_k)); xo1_a2 = xo_g1 * xo1_a1; xo1_a3 = xo_g1 * xo1_a2;
xo2_a1 = 1.0 / (1.0 + xo_g2 * (xo_g2 + xo_k)); xo2_a2 = xo_g2 * xo2_a1; xo2_a3 = xo_g2 * xo2_a2;

xo_l.xo_ch_proc(in_orig_l);
xo_r.xo_ch_proc(in_orig_r);

band_in_l = xo_l.mid;
band_in_r = xo_r.mid;
// Untouched outside bands (magnitude-flat, phase-aligned)
band_rest_l = xo_l.lo + xo_l.hi;
band_rest_r = xo_r.lo + xo_r.hi;

dsp_bin_peak_inst = max(abs(band_in_l), abs(band_in_r));
dsp_meter_bin = dsp_bin_peak_inst > dsp_meter_bin ? dsp_bin_peak_inst : dsp_meter_bin * dsp_meter_decay;

// =========================================================================
// 2. CORE PROCESSING CHAIN (Density, Color, Dry/Wet Mix) - on the band only
// =========================================================================
dsp_pp0 = dsp_left.dsp_ch_preproc(band_in_l);
dsp_pp1 = dsp_right.dsp_ch_preproc(band_in_r);
dsp_det_lvl = max(abs(dsp_pp0), abs(dsp_pp1));

dsp_wet_l = dsp_left.dsp_ch_postproc(dsp_pp0, dsp_det_lvl);
dsp_wet_r = dsp_right.dsp_ch_postproc(dsp_pp1, dsp_det_lvl);

// Smooth Dry/Wet Mix (Pre-AutoGain / Pre-OutputGain)
dsp_mix_state = dsp_mix_state * dsp_smooth_coeff + dsp_mix_target * (1.0 - dsp_smooth_coeff);
proc_pre_ag_l = band_in_l * (1.0 - dsp_mix_state) + dsp_wet_l * dsp_mix_state;
proc_pre_ag_r = band_in_r * (1.0 - dsp_mix_state) + dsp_wet_r * dsp_mix_state;

// =========================================================================
// 3. TWO-STAGE HYBRID AUTO-GAIN ENGINE (Zero-Latency Pre-RMS + 3s LUFS-S)
// =========================================================================

// --- STAGE 1: Real-Time Broadband RMS Pre-Matcher ---
inst_e_in   = band_in_l * band_in_l + band_in_r * band_in_r;
inst_e_proc = proc_pre_ag_l * proc_pre_ag_l + proc_pre_ag_r * proc_pre_ag_r;

// Check if instantaneous signal is above the -70 dBFS silence threshold
(inst_e_in > 0.0000001 && inst_e_proc > 0.0000001 && !dsp_bypass_on) ? (
  // If waking up after > 0.5s of silence, enable fast RMS acquisition
  silence_counter > (dsp_sample_rate * 0.5) ? (
    ag_fast_samples = floor(dsp_sample_rate * 0.150);
  );
  silence_counter = 0;

  // Instant seed on the very first active sample to eliminate startup gain jumps
  (!rms_is_seeded || rms_need_seed) ? (
    rms_env_in       = inst_e_in;
    rms_env_proc     = inst_e_proc;
    ag_rms_db_target = min(max(10.0 * log10(rms_env_in / rms_env_proc), -24.0), 24.0);
    ag_rms_db_state  = ag_rms_db_target;
    dsp_auto_gain_db = min(max(ag_rms_db_state + ag_lufs_trim_state_db, -24.0), 24.0);
    dsp_ag_lin_state = dsp_db_to_k(dsp_auto_gain_db);
    dsp_gain_lin_state = dsp_db_to_k(dsp_auto_gain_db + dsp_trim_db);
    rms_is_seeded = 1;
    rms_need_seed = 0;
  ) : (
    cur_rms_coeff = (ag_fast_samples > 0) ? rms_coeff_fast : rms_coeff_slow;
    rms_env_in    = rms_env_in   * cur_rms_coeff + inst_e_in   * (1.0 - cur_rms_coeff);
    rms_env_proc  = rms_env_proc * cur_rms_coeff + inst_e_proc * (1.0 - cur_rms_coeff);

    (rms_env_in > 0.0000001 && rms_env_proc > 0.0000001) ? (
      ag_rms_db_target = min(max(10.0 * log10(rms_env_in / rms_env_proc), -24.0), 24.0);
    );
  );

  cur_track_coeff = (ag_fast_samples > 0) ? rms_track_fast : rms_track_slow;
  ag_rms_db_state = ag_rms_db_state * cur_track_coeff + ag_rms_db_target * (1.0 - cur_track_coeff);

  ag_fast_samples > 0 ? (
    ag_fast_samples -= 1;
  );
) : (
  silence_counter += 1;
);

// --- STAGE 2: ITU-R BS.1770 3-Second Short-Term LUFS Fine Calibration ---
kw_in_s_l   = kw_in_l.kw_ch_proc(band_in_l);
kw_in_s_r   = kw_in_r.kw_ch_proc(band_in_r);
kw_proc_s_l = kw_proc_l.kw_ch_proc(proc_pre_ag_l);
kw_proc_s_r = kw_proc_r.kw_ch_proc(proc_pre_ag_r);

lufs_sub_in_acc   += (kw_in_s_l * kw_in_s_l + kw_in_s_r * kw_in_s_r);
lufs_sub_proc_acc += (kw_proc_s_l * kw_proc_s_l + kw_proc_s_r * kw_proc_s_r);
lufs_sub_cnt += 1;

lufs_sub_cnt >= lufs_sub_size ? (
  mean_sub_in   = lufs_sub_in_acc / lufs_sub_size;
  mean_sub_proc = lufs_sub_proc_acc / lufs_sub_size;

  // Only advance the 3s LUFS ringbuffer when active audio is present (Gate > -70 LUFS)
  sub_in_lufs   = (mean_sub_in   > 0.0000000001) ? (-0.691 + 10.0 * log10(mean_sub_in))   : -100.0;
  sub_proc_lufs = (mean_sub_proc > 0.0000000001) ? (-0.691 + 10.0 * log10(mean_sub_proc)) : -100.0;

  (!dsp_bypass_on && sub_in_lufs > -70.0 && sub_proc_lufs > -70.0) ? (
    lufs_valid_gate = 1;

    lufs_sum_in   += mean_sub_in   - lufs_buf_in[lufs_buf_idx];
    lufs_sum_proc += mean_sub_proc - lufs_buf_proc[lufs_buf_idx];
    lufs_sum_in   = max(0.0, lufs_sum_in);
    lufs_sum_proc = max(0.0, lufs_sum_proc);

    lufs_buf_in[lufs_buf_idx]   = mean_sub_in;
    lufs_buf_proc[lufs_buf_idx] = mean_sub_proc;

    lufs_buf_idx += 1;
    lufs_buf_idx >= lufs_num_blocks ? lufs_buf_idx = 0;

    lufs_filled_blocks < lufs_num_blocks ? (
      lufs_filled_blocks += 1;
    );

    mean_win_in   = lufs_sum_in / lufs_filled_blocks;
    mean_win_proc = lufs_sum_proc / lufs_filled_blocks;

    input_lufs     = (mean_win_in   > 0.0000000001) ? (-0.691 + 10.0 * log10(mean_win_in))   : -100.0;
    processed_lufs = (mean_win_proc > 0.0000000001) ? (-0.691 + 10.0 * log10(mean_win_proc)) : -100.0;

    // Total BS.1770 LUFS-S correction required
    lufs_total_corr_db = min(max(input_lufs - processed_lufs, -24.0), 24.0);

    // Confidence weight (0.0 -> 1.0 as the 3-second window fills up)
    lufs_conf = lufs_filled_blocks / lufs_num_blocks;

    // Stage 2 computes the exact K-weighted residual trim on top of Stage 1 (RMS)
    ag_lufs_trim_target_db = lufs_conf * (lufs_total_corr_db - ag_rms_db_state);
  ) : (
    lufs_valid_gate = 0;
    // Hold last valid LUFS trim during silence or bypass
  );

  lufs_sub_cnt      = 0;
  lufs_sub_in_acc   = 0.0;
  lufs_sub_proc_acc = 0.0;
);

// Smooth Stage 2 residual trim and combine Stage 1 (RMS) + Stage 2 (LUFS Trim)
ag_lufs_trim_state_db = ag_lufs_trim_state_db * lufs_trim_coeff + ag_lufs_trim_target_db * (1.0 - lufs_trim_coeff);
dsp_auto_gain_db      = min(max(ag_rms_db_state + ag_lufs_trim_state_db, -24.0), 24.0);

// =========================================================================
// 4. GAIN REDUCTION MEASUREMENT (Raw Input vs. Output incl. Internal AG & Mix)
// =========================================================================
dsp_ag_lin_target = dsp_db_to_k(dsp_auto_gain_db);
dsp_ag_lin_state  = dsp_ag_lin_state * dsp_smooth_coeff + dsp_ag_lin_target * (1.0 - dsp_smooth_coeff);

// Internal reference output for GR (always includes Dry/Wet Mix and Auto-Gain)
gr_out_l = proc_pre_ag_l * dsp_ag_lin_state;
gr_out_r = proc_pre_ag_r * dsp_ag_lin_state;

dsp_gr_out_peak_inst = max(abs(gr_out_l), abs(gr_out_r));
dsp_meter_gr_out = dsp_gr_out_peak_inst > dsp_meter_gr_out ? dsp_gr_out_peak_inst : dsp_meter_gr_out * dsp_meter_decay;

// GR compares the band input with the band output (outside bands are untouched)
(dsp_meter_bin > 0.001778 && dsp_meter_gr_out > 0.00001) ? (
  dsp_gr_db_inst = max(0.0, 20.0 * log10(dsp_meter_bin / dsp_meter_gr_out));
) : (
  dsp_gr_db_inst = 0.0;
);
dsp_meter_gr_db = dsp_meter_gr_db * dsp_gr_smooth_coeff + dsp_gr_db_inst * (1.0 - dsp_gr_smooth_coeff);

// =========================================================================
// 5. APPLY AUDIBLE BAND GAIN (always-on loudness match + relative Band Trim)
// =========================================================================
dsp_applied_db      = dsp_auto_gain_db + dsp_trim_db;
dsp_target_gain_lin = dsp_db_to_k(dsp_applied_db);
dsp_gain_lin_state  = dsp_gain_lin_state * dsp_smooth_coeff + dsp_target_gain_lin * (1.0 - dsp_smooth_coeff);

// Gain compensates the processed band only, outside bands stay at unity
proc_band_l  = proc_pre_ag_l * dsp_gain_lin_state;
proc_band_r  = proc_pre_ag_r * dsp_gain_lin_state;
// SOLO: fade the outside bands out (10 ms, click-free)
dsp_rest_g = dsp_rest_g * dsp_solo_coeff + dsp_rest_g_t * (1.0 - dsp_solo_coeff);
dsp_rest_g < 0.00001 ? ( dsp_rest_g = 0.0; ) : dsp_rest_g > 0.99999 ? ( dsp_rest_g = 1.0; );

proc_final_l = band_rest_l * dsp_rest_g + proc_band_l;
proc_final_r = band_rest_r * dsp_rest_g + proc_band_r;

// =========================================================================
// 6. FINAL OUTPUT ROUTING (Priority: 1. BYPASS -> 2. DELTA -> 3. NORMAL)
//    SOLO acts inside each mode: Bypass+Solo = raw band, Delta is band-only anyway
// =========================================================================
dsp_bypass_on ? (
  dsp_rest_g >= 1.0 ? (
    // True Signal Bypass: Bit-transparent routing of original input
    out_final_l = in_orig_l;
    out_final_r = in_orig_r;
  ) : (
    // Bypass + Solo: unprocessed band for A/B against the processed solo band
    out_final_l = band_in_l + band_rest_l * dsp_rest_g;
    out_final_r = band_in_r + band_rest_r * dsp_rest_g;
  );
) : dsp_delta_on ? (
  // Delta Monitoring: Exact difference between processed and unprocessed band
  // (= processed output minus phase-matched crossover reconstruction of the input -> nulls perfectly)
  out_final_l = proc_band_l - band_in_l;
  out_final_r = proc_band_r - band_in_r;
) : (
  // Normal Processed Output
  out_final_l = proc_final_l;
  out_final_r = proc_final_r;
);

spl0 = out_final_l;
spl1 = out_final_r;

// Output Peak Metering & FFT Monitor
dsp_out_peak_inst = max(abs(spl0), abs(spl1));
dsp_meter_out = dsp_out_peak_inst > dsp_meter_out ? dsp_out_peak_inst : dsp_meter_out * dsp_meter_decay;

// Continuous circular capture, analysed every dsp_fft_hop samples (75% overlap)
dsp_fft_ring[dsp_fft_pos] = 0.5 * (spl0 + spl1);
dsp_fft_pos += 1;
dsp_fft_pos >= dsp_fft_size ? dsp_fft_pos = 0;
dsp_fft_hop_cnt += 1;
dsp_fft_hop_cnt >= dsp_fft_hop ? (
  dsp_fft_hop_cnt = 0;
  dsp_fft_ready = 1;
);


@gfx 760 564
gfx_clear = -1;

ui_base_w = 760;
ui_base_h = 564;

gfx_getimgdim(1, ui_img_w, ui_img_h);
(ui_img_w != ui_base_w || ui_img_h != ui_base_h) ? (
  gfx_setimgdim(1, ui_base_w, ui_base_h);
);

ui_scale = min(gfx_w / ui_base_w, gfx_h / ui_base_h);
ui_scale = max(ui_scale, 0.25);
ui_off_x = floor((gfx_w - ui_base_w * ui_scale) * 0.5);
ui_off_y = floor((gfx_h - ui_base_h * ui_scale) * 0.5);

ui_mx = (mouse_x - ui_off_x) / ui_scale;
ui_my = (mouse_y - ui_off_y) / ui_scale;
ui_mouse_down = (mouse_cap & 1) && !(ui_last_cap & 1);

ui_mouse_down ? (
  // Double-click only counts when both clicks hit (nearly) the same spot
  ((time_precise() - ui_last_click_t) < 0.30 && abs(ui_mx - ui_last_click_x) < 6 && abs(ui_my - ui_last_click_y) < 6) ? (
    ui_is_dbl = 1;
    ui_last_click_t = 0;
  ) : (
    ui_is_dbl = 0;
    ui_last_click_t = time_precise();
    ui_last_click_x = ui_mx;
    ui_last_click_y = ui_my;
  );
) : (
  ui_is_dbl = 0;
);

gfx_dest = 1;

function ui_draw_bevel_box(x, y, w, h, r_bg, g_bg, b_bg, inverted) local(r_tl, g_tl, b_tl, r_br, g_br, b_br) (
  gfx_set(r_bg, g_bg, b_bg, 1.0);
  gfx_rect(x, y, w, h, 1);
  inverted ? (
    r_tl = 0.07; g_tl = 0.07; b_tl = 0.06;
    r_br = 0.26; g_br = 0.26; b_br = 0.24;
  ) : (
    r_tl = 0.26; g_tl = 0.26; b_tl = 0.24;
    r_br = 0.07; g_br = 0.07; b_br = 0.06;
  );
  gfx_set(r_tl, g_tl, b_tl, 1.0);
  gfx_line(x, y, x + w - 1, y);
  gfx_line(x, y, x, y + h - 1);
  gfx_set(r_br, g_br, b_br, 1.0);
  gfx_line(x, y + h - 1, x + w - 1, y + h - 1);
  gfx_line(x + w - 1, y, x + w - 1, y + h - 1);
);

function ui_draw_screw(cx, cy, rad) local(dx, dy) (
  gfx_set(0.06, 0.06, 0.05, 1.0);
  gfx_circle(cx, cy, rad + 1, 1, 1);
  gfx_set(0.26, 0.25, 0.23, 1.0);
  gfx_circle(cx, cy, rad, 0, 1);
  gfx_set(0.13, 0.13, 0.12, 1.0);
  gfx_circle(cx, cy, rad - 1, 1, 1);
  dx = rad * 0.55;
  dy = rad * 0.55;
  gfx_set(0.05, 0.05, 0.04, 1.0);
  gfx_line(cx - dx, cy - dy, cx + dx, cy + dy);
  gfx_set(0.28, 0.27, 0.25, 0.7);
  gfx_line(cx - dx, cy - dy + 1, cx + dx, cy + dy + 1);
);

function ui_draw_knob(id, cx, cy, rad, val, vmin, vmax, vdef, title_str, unit_str, is_disabled, disp_val, tip_id)
  local(ang_min, ang_max, i, n_ticks, t_norm, t_ang, is_maj, r1, r2, tx1, ty1, tx2, ty2,
        is_hov, new_val, fine, disp_norm, p_ang, px1, py1, px2, py2, box_w, box_h, box_x, box_y, tw, th)
(
  ang_min = 0.75 * $pi;
  ang_max = 2.25 * $pi;

  is_hov = (sqrt(sqr(ui_mx - cx) + sqr(ui_my - cy)) <= rad + 14) ||
           (ui_mx >= cx - 58 && ui_mx <= cx + 58 && ui_my >= cy + rad + 12 && ui_my <= cy + rad + 42);
  is_hov ? ( ui_hover_tip = tip_id; );

  new_val = val;

  !is_disabled ? (
    (ui_mouse_down && ui_drag_id == 0 && is_hov) ? (
      ui_is_dbl ? (
        new_val = vdef;
        ui_drag_id = 0;
        ui_dbl_changed = id;
      ) : (
        ui_drag_id = id;
        ui_drag_start_y = ui_my;
        ui_drag_start_val = val;
      );
    );

    (ui_drag_id == id && (mouse_cap & 1)) ? (
      fine = (mouse_cap & 4) ? 0.2 : 1.0;
      new_val = ui_drag_start_val - (ui_my - ui_drag_start_y) * (vmax - vmin) / 180.0 * fine;
      new_val = min(max(new_val, vmin), vmax);
      ui_drag_start_y = ui_my;
      ui_drag_start_val = new_val;
    );
  );

  n_ticks = 20;
  i = 0;
  loop(n_ticks + 1,
    t_norm = i / n_ticks;
    t_ang = ang_min + t_norm * (ang_max - ang_min);
    is_maj = (i % 5) == 0;
    r1 = rad + 4;
    r2 = rad + (is_maj ? 11 : 7);
    tx1 = cx + cos(t_ang) * r1;
    ty1 = cy + sin(t_ang) * r1;
    tx2 = cx + cos(t_ang) * r2;
    ty2 = cy + sin(t_ang) * r2;

    disp_norm = (min(max(disp_val, vmin), vmax) - vmin) / (vmax - vmin);
    (t_norm <= disp_norm + 0.001) ? (
      is_disabled ? gfx_set(0.55, 0.48, 0.35, 0.75) : gfx_set(0.88, 0.72, 0.38, 0.95);
    ) : (
      gfx_set(0.32, 0.31, 0.28, 0.85);
    );
    gfx_line(tx1, ty1, tx2, ty2);
    is_maj ? gfx_line(tx1 + 1, ty1, tx2 + 1, ty2);
    i += 1;
  );

  gfx_set(0.06, 0.06, 0.05, 0.85);
  gfx_circle(cx + 3, cy + 4, rad, 1, 1);

  gfx_set(0.22, 0.20, 0.18, 1.0);
  gfx_circle(cx, cy, rad, 1, 1);
  gfx_set(0.30, 0.28, 0.25, 1.0);
  gfx_circle(cx, cy, rad, 0, 1);

  i = 0;
  loop(24,
    t_ang = i * (2.0 * $pi / 24.0);
    tx1 = cx + cos(t_ang) * (rad - 3);
    ty1 = cy + sin(t_ang) * (rad - 3);
    tx2 = cx + cos(t_ang) * rad;
    ty2 = cy + sin(t_ang) * rad;
    gfx_set(0.10, 0.10, 0.09, 0.9);
    gfx_line(tx1, ty1, tx2, ty2);
    i += 1;
  );

  gfx_set(0.12, 0.12, 0.11, 1.0);
  gfx_circle(cx, cy, rad - 5, 1, 1);
  gfx_set(0.25, 0.24, 0.22, 1.0);
  gfx_circle(cx, cy, rad - 5, 0, 1);

  gfx_set(is_disabled ? 0.22 : 0.29, is_disabled ? 0.22 : 0.28, is_disabled ? 0.21 : 0.26, 1.0);
  gfx_circle(cx, cy, rad - 15, 1, 1);
  gfx_set(0.42, 0.40, 0.37, 0.9);
  gfx_circle(cx, cy, rad - 15, 0, 1);

  disp_norm = (min(max(disp_val, vmin), vmax) - vmin) / (vmax - vmin);
  p_ang = ang_min + disp_norm * (ang_max - ang_min);
  px1 = cx + cos(p_ang) * 6;
  py1 = cy + sin(p_ang) * 6;
  px2 = cx + cos(p_ang) * (rad - 6);
  py2 = cy + sin(p_ang) * (rad - 6);

  gfx_set(0.05, 0.05, 0.04, 0.8);
  gfx_line(px1 + 1, py1 + 1, px2 + 1, py2 + 1);
  is_disabled ? gfx_set(0.75, 0.65, 0.45, 0.75) : gfx_set(0.92, 0.86, 0.72, 1.0);
  gfx_line(px1, py1, px2, py2);
  gfx_line(px1 + 1, py1, px2 + 1, py2);

  box_w = 122;
  box_h = 26;
  box_x = cx - box_w * 0.5;
  box_y = cy + rad + 15;
  ui_draw_bevel_box(box_x, box_y, box_w, box_h, 0.12, 0.12, 0.11, 1);

  gfx_setfont(2, "Arial", 12, 'b');
  is_disabled ? (
    sprintf(#ui_knob_str, "%s: %+.1f (AG)", title_str, disp_val);
    gfx_set(0.76, 0.68, 0.48, 0.9);
  ) : (
    vmin < 0 ? (
      sprintf(#ui_knob_str, "%s: %+.1f %s", title_str, disp_val, unit_str);
    ) : (
      sprintf(#ui_knob_str, "%s: %.1f %s", title_str, disp_val, unit_str);
    );
    gfx_set(0.84, 0.81, 0.74, 0.95);
  );
  gfx_measurestr(#ui_knob_str, tw, th);
  gfx_x = cx - tw * 0.5;
  gfx_y = box_y + (box_h - th) * 0.5;
  gfx_drawstr(#ui_knob_str);

  new_val;
);

function ui_draw_vmeter(x, y, w, h, title_str, bar_db_val, txt_db_val, db_min, db_max, is_gr, tip_id)
  local(tw, th, well_y, well_h, n_segs, gap, seg_h, norm_val, i, seg_norm, sy, is_lit, r_c, g_c, b_c, ro_y, ro_h, is_hov)
(
  is_hov = (ui_mx >= x && ui_mx <= x + w && ui_my >= y && ui_my <= y + h);
  is_hov ? ( ui_hover_tip = tip_id; );

  ui_draw_bevel_box(x, y, w, h, 0.13, 0.12, 0.10, 1);

  gfx_setfont(3, "Arial", 11, 'b');
  gfx_set(0.75, 0.72, 0.65, 0.95);
  gfx_measurestr(title_str, tw, th);
  gfx_x = x + (w - tw) * 0.5;
  gfx_y = y + 5;
  gfx_drawstr(title_str);

  well_y = y + 22;
  ro_h = 20;
  ro_y = y + h - ro_h - 4;
  well_h = ro_y - well_y - 5;

  n_segs = 18;
  gap = 2;
  seg_h = floor((well_h - (n_segs - 1) * gap) / n_segs);

  norm_val = (min(max(bar_db_val, db_min), db_max) - db_min) / (db_max - db_min);

  i = 0;
  loop(n_segs,
    seg_norm = (i + 0.5) / n_segs;
    sy = well_y + (n_segs - 1 - i) * (seg_h + gap);
    is_lit = norm_val >= (i / n_segs) && (bar_db_val > db_min + 0.2);

    is_lit ? (
      is_gr ? (
        seg_norm > 0.65 ? ( r_c = 0.86; g_c = 0.32; b_c = 0.18; )
        : ( r_c = 0.92; g_c = 0.62; b_c = 0.22; );
      ) : (
        seg_norm > 0.85 ? ( r_c = 0.86; g_c = 0.32; b_c = 0.18; )
        : seg_norm > 0.65 ? ( r_c = 0.88; g_c = 0.68; b_c = 0.26; )
        : ( r_c = 0.55; g_c = 0.68; b_c = 0.36; );
      );
    ) : (
      r_c = 0.20; g_c = 0.19; b_c = 0.17;
    );

    gfx_set(r_c, g_c, b_c, 1.0);
    gfx_rect(x + 8, sy, w - 16, seg_h, 1);
    i += 1;
  );

  ui_draw_bevel_box(x + 4, ro_y, w - 8, ro_h, 0.09, 0.09, 0.08, 1);
  gfx_setfont(3, "Arial", 11, 'b');
  gfx_set(0.84, 0.80, 0.70, 0.95);
  is_gr ? (
    sprintf(#ui_m_str, "-%.1f", max(txt_db_val, 0.0));
  ) : (
    txt_db_val <= -55.0 ? strcpy(#ui_m_str, "-inf") : sprintf(#ui_m_str, "%+.1f", txt_db_val);
  );
  gfx_measurestr(#ui_m_str, tw, th);
  gfx_x = x + (w - tw) * 0.5;
  gfx_y = ro_y + (ro_h - th) * 0.5;
  gfx_drawstr(#ui_m_str);
);

// Read-only Auto Gain display (Auto Gain is always on). state: 0 = locked, 1 = adapting, 2 = holding
function ui_draw_ag_display(x, y, w, h, gain_db, state, tip_id)
  local(is_hov, jx, jy, tw, th)
(
  is_hov = (ui_mx >= x && ui_mx <= x + w && ui_my >= y && ui_my <= y + h);
  is_hov ? ( ui_hover_tip = tip_id; );

  ui_draw_bevel_box(x - 2, y - 2, w + 4, h + 4, 0.09, 0.09, 0.08, 1);
  ui_draw_bevel_box(x, y, w, h, 0.08, 0.08, 0.07, 1);

  jx = x + 13;
  jy = y + h * 0.5;
  gfx_set(0.04, 0.04, 0.03, 1.0);
  gfx_circle(jx, jy, 5, 1, 1);
  state == 0 ? (
    gfx_set(0.88, 0.68, 0.24, 0.28); gfx_circle(jx, jy, 7, 1, 1);
    gfx_set(0.90, 0.72, 0.28, 1.0);
  ) : state == 1 ? (
    gfx_set(0.95, 0.52, 0.18, 0.35); gfx_circle(jx, jy, 8, 1, 1);
    gfx_set(0.96, 0.56, 0.20, 1.0);
  ) : (
    gfx_set(0.30, 0.27, 0.22, 1.0);
  );
  gfx_circle(jx, jy, 4, 1, 1);
  state < 2 ? ( gfx_set(1.0, 0.92, 0.80, 0.8); gfx_circle(jx - 1, jy - 1, 1.5, 1, 1); );

  gfx_setfont(3, "Arial", 11, 'b');
  gfx_set(0.62, 0.59, 0.53, 0.95);
  gfx_measurestr("AUTO GAIN", tw, th);
  gfx_x = x + 24;
  gfx_y = y + (h - th) * 0.5;
  gfx_drawstr("AUTO GAIN");

  gfx_setfont(2, "Arial", 13, 'b');
  sprintf(#ui_ag_val, "%+.1f dB", gain_db);
  gfx_measurestr(#ui_ag_val, tw, th);
  state == 2 ? gfx_set(0.60, 0.55, 0.45, 0.9) : gfx_set(0.95, 0.82, 0.52, 1.0);
  gfx_x = x + w - 10 - tw;
  gfx_y = y + (h - th) * 0.5;
  gfx_drawstr(#ui_ag_val);
);

// led_mode: 0 = Gold, 1 = Orange (Delta), 2 = Red (Bypass)
function ui_draw_push_switch(x, y, w, h, label_str, is_active, led_mode, tip_id)
  local(is_hov, clicked, tw, th, jx, jy)
(
  is_hov = (ui_mx >= x && ui_mx <= x + w && ui_my >= y && ui_my <= y + h);
  is_hov ? ( ui_hover_tip = tip_id; );
  clicked = (ui_mouse_down && ui_drag_id == 0 && is_hov);

  ui_draw_bevel_box(x - 2, y - 2, w + 4, h + 4, 0.09, 0.09, 0.08, 1);

  is_active ? (
    ui_draw_bevel_box(x, y, w, h, 0.22, 0.21, 0.19, 0);
  ) : (
    ui_draw_bevel_box(x, y, w, h, 0.16, 0.16, 0.15, 0);
  );

  jx = x + 13;
  jy = y + h * 0.5;
  gfx_set(0.06, 0.06, 0.05, 1.0);
  gfx_circle(jx, jy, 5, 1, 1);

  is_active ? (
    led_mode == 2 ? (
      gfx_set(0.95, 0.24, 0.20, 0.35);
      gfx_circle(jx, jy, 8, 1, 1);
      gfx_set(0.96, 0.28, 0.22, 1.0);
    ) : led_mode == 1 ? (
      gfx_set(0.95, 0.52, 0.18, 0.35);
      gfx_circle(jx, jy, 8, 1, 1);
      gfx_set(0.96, 0.56, 0.20, 1.0);
    ) : (
      gfx_set(0.88, 0.68, 0.24, 0.28);
      gfx_circle(jx, jy, 7, 1, 1);
      gfx_set(0.90, 0.72, 0.28, 1.0);
    );
    gfx_circle(jx, jy, 4, 1, 1);
    gfx_set(1.0, 0.92, 0.80, 0.8);
    gfx_circle(jx - 1, jy - 1, 1.5, 1, 1);
  ) : (
    gfx_set(0.24, 0.22, 0.20, 1.0);
    gfx_circle(jx, jy, 4, 1, 1);
  );

  gfx_setfont(2, "Arial", 12, 'b');
  is_active ? gfx_set(0.92, 0.89, 0.81, 1.0) : gfx_set(0.55, 0.53, 0.48, 0.9);
  gfx_measurestr(label_str, tw, th);
  gfx_x = x + 22 + (w - 26 - tw) * 0.5;
  gfx_y = y + (h - th) * 0.5;
  gfx_drawstr(label_str);

  clicked;
);

function ui_draw_hslider(id, x, y, w, h, val, vmin, vmax, vdef, title_str, tip_id)
  local(is_hov, new_val, track_x, track_w, track_y, i, tx, norm_val, cap_x, cap_w, cap_h, tw, th, fine)
(
  is_hov = (ui_mx >= x && ui_mx <= x + w && ui_my >= y - 6 && ui_my <= y + h + 6);
  is_hov ? ( ui_hover_tip = tip_id; );

  new_val = val;
  (ui_mouse_down && ui_drag_id == 0 && is_hov) ? (
    ui_is_dbl ? (
      new_val = vdef;
      ui_drag_id = 0;
    ) : (
      ui_drag_id = id;
      ui_drag_start_x = ui_mx;
      ui_drag_start_val = val;
    );
  );

  (ui_drag_id == id && (mouse_cap & 1)) ? (
    fine = (mouse_cap & 4) ? 0.2 : 1.0;
    new_val = ui_drag_start_val + (ui_mx - ui_drag_start_x) * (vmax - vmin) / (w - 30) * fine;
    new_val = min(max(new_val, vmin), vmax);
    ui_drag_start_x = ui_mx;
    ui_drag_start_val = new_val;
  );

  gfx_setfont(3, "Arial", 11, 'b');
  gfx_set(0.78, 0.75, 0.68, 0.95);
  sprintf(#ui_sl_str, "%s: %.1f %%", title_str, new_val);
  gfx_measurestr(#ui_sl_str, tw, th);
  gfx_x = x + (w - tw) * 0.5;
  gfx_y = y - 15;
  gfx_drawstr(#ui_sl_str);

  track_x = x + 12;
  track_w = w - 24;
  track_y = y + h * 0.5;

  i = 0;
  loop(11,
    tx = track_x + (i / 10.0) * track_w;
    gfx_set(0.32, 0.31, 0.28, 0.8);
    gfx_line(tx, track_y - 9, tx, track_y + 9);
    i += 1;
  );

  gfx_set(0.07, 0.07, 0.06, 1.0);
  gfx_rect(track_x, track_y - 3, track_w, 6, 1);
  gfx_set(0.26, 0.26, 0.24, 1.0);
  gfx_line(track_x, track_y + 3, track_x + track_w, track_y + 3);

  norm_val = (new_val - vmin) / (vmax - vmin);
  cap_w = 18;
  cap_h = 20;
  cap_x = track_x + norm_val * track_w - cap_w * 0.5;
  ui_draw_bevel_box(cap_x, track_y - cap_h * 0.5, cap_w, cap_h, 0.24, 0.23, 0.21, 0);

  gfx_set(0.92, 0.86, 0.72, 1.0);
  gfx_line(cap_x + cap_w * 0.5, track_y - cap_h * 0.5 + 3, cap_x + cap_w * 0.5, track_y + cap_h * 0.5 - 3);

  new_val;
);

// =========================================================================
// BAND CONTROL (shared by spectrum handles and the multi-function range slider)
// Normalised position n: 0 = 20 Hz, 1 = 20 kHz (log scale, identical to the spectrum x-axis)
// =========================================================================
function ui_f_to_n(f) local() ( log(min(max(f, 20.0), 20000.0) / 20.0) / log(1000.0); );
function ui_n_to_f(n) local() ( 20.0 * exp(min(max(n, 0.0), 1.0) * log(1000.0)); );

function ui_fmt_hz(str, f) local() (
  f < 1000.0 ? sprintf(str, "%.0f Hz", f)
  : f < 10000.0 ? sprintf(str, "%.2f kHz", f / 1000.0)
  : sprintf(str, "%.1f kHz", f / 1000.0);
);

function ui_band_snap() local() (
  // Pull to the edges -> split switched off (20 Hz = no low split, 20 kHz = no high split)
  ui_band_lo_n < 0.004 ? ( ui_band_lo_n = 0.0; );
  ui_band_hi_n > 0.996 ? ( ui_band_hi_n = 1.0; );
);

function ui_band_set_width(lo0, hi0, wd) local(ctr) (
  ctr = (lo0 + hi0) * 0.5;
  wd = min(max(wd, ui_band_gap), 1.0);
  ui_band_lo_n = ctr - wd * 0.5;
  ui_band_hi_n = ctr + wd * 0.5;
  ui_band_lo_n < 0.0 ? ( ui_band_hi_n -= ui_band_lo_n; ui_band_lo_n = 0.0; );
  ui_band_hi_n > 1.0 ? ( ui_band_lo_n -= ui_band_hi_n - 1.0; ui_band_hi_n = 1.0; );
  ui_band_lo_n = max(ui_band_lo_n, 0.0);
);

// Left-drag: Low/High handle or whole band (move), Shift+drag on band = width,
// Ctrl = fine, double-click handle = reset that edge, double-click band = full range
function ui_band_interact(id_base, x0, w, hit_lo, hit_hi, hit_mid)
  local(lo_x, hi_x, fine, mode, dn, d, lo_prev, hi_prev)
(
  lo_x = x0 + ui_band_lo_n * w;
  hi_x = x0 + ui_band_hi_n * w;
  (hit_lo && hit_hi) ? (
    // Overlapping grab zones: pick the nearer handle (ties -> by side of the band)
    abs(ui_mx - lo_x) < abs(ui_mx - hi_x) ? ( hit_hi = 0; )
    : abs(ui_mx - lo_x) > abs(ui_mx - hi_x) ? ( hit_lo = 0; )
    : ui_mx < (lo_x + hi_x) * 0.5 ? ( hit_hi = 0; ) : ( hit_lo = 0; );
  );

  (ui_mouse_down && ui_drag_id == 0 && (hit_lo || hit_hi || hit_mid)) ? (
    ui_is_dbl ? (
      hit_lo ? ( ui_band_lo_n = 0.0; )
      : hit_hi ? ( ui_band_hi_n = 1.0; )
      : ( ui_band_lo_n = 0.0; ui_band_hi_n = 1.0; );
      ui_band_changed = 1;
    ) : (
      ui_drag_id = id_base + (hit_lo ? 1 : hit_hi ? 2 : 3);
      ui_bd_start_x = ui_mx;
      ui_bd_lo0 = ui_band_lo_n;
      ui_bd_hi0 = ui_band_hi_n;
      ui_bd_fine = (mouse_cap & 4) ? 0.2 : 1.0;
      ui_bd_mode = (mouse_cap & 8) ? 1 : 0;
    );
  );

  ((mouse_cap & 1) && ui_drag_id > id_base && ui_drag_id <= id_base + 3) ? (
    lo_prev = ui_band_lo_n;
    hi_prev = ui_band_hi_n;
    fine = (mouse_cap & 4) ? 0.2 : 1.0;
    mode = (mouse_cap & 8) ? 1 : 0;
    // Re-anchor when Ctrl/Shift change mid-drag (no jumps)
    (fine != ui_bd_fine || mode != ui_bd_mode) ? (
      ui_bd_start_x = ui_mx;
      ui_bd_lo0 = ui_band_lo_n;
      ui_bd_hi0 = ui_band_hi_n;
      ui_bd_fine = fine;
      ui_bd_mode = mode;
    );
    dn = (ui_mx - ui_bd_start_x) / w * fine;

    ui_drag_id == id_base + 1 ? (
      ui_band_lo_n = min(max(ui_bd_lo0 + dn, 0.0), ui_band_hi_n - ui_band_gap);
    ) : ui_drag_id == id_base + 2 ? (
      ui_band_hi_n = max(min(ui_bd_hi0 + dn, 1.0), ui_band_lo_n + ui_band_gap);
    ) : (
      mode ? (
        ui_band_set_width(ui_bd_lo0, ui_bd_hi0, (ui_bd_hi0 - ui_bd_lo0) + 2.0 * dn);
      ) : (
        d = min(max(dn, -ui_bd_lo0), 1.0 - ui_bd_hi0);
        ui_band_lo_n = ui_bd_lo0 + d;
        ui_band_hi_n = ui_bd_hi0 + d;
      );
    );
    ui_band_snap();
    (ui_band_lo_n != lo_prev || ui_band_hi_n != hi_prev) ? ( ui_band_changed = 1; );
  );
);

// Mouse wheel over band controls: widen (up) / narrow (down) around the band centre
function ui_band_wheel(is_hov) local(d) (
  (is_hov && mouse_wheel != 0 && ui_drag_id == 0) ? (
    d = (mouse_wheel / 120.0) * 0.02 * ((mouse_cap & 4) ? 0.25 : 1.0);
    ui_band_set_width(ui_band_lo_n, ui_band_hi_n, (ui_band_hi_n - ui_band_lo_n) + 2.0 * d);
    ui_band_snap();
    ui_band_changed = 1;
    mouse_wheel = 0;
  );
);

function ui_draw_band_tab(hx, ty, is_on, is_hot) local(tx) (
  tx = min(max(hx - 6, ui_in_x), ui_in_x + ui_in_w - 12);
  gfx_set(0.05, 0.05, 0.04, 0.8);
  gfx_rect(tx + 1, ty + 1, 12, 14, 1);
  is_hot ? gfx_set(1.0, 0.82, 0.45, 1.0)
  : is_on ? gfx_set(0.88, 0.68, 0.30, 1.0)
  : gfx_set(0.42, 0.40, 0.36, 1.0);
  gfx_rect(tx, ty, 12, 14, 1);
  gfx_set(0.10, 0.09, 0.08, 0.9);
  gfx_line(tx + 4, ty + 4, tx + 4, ty + 10);
  gfx_line(tx + 7, ty + 4, tx + 7, ty + 10);
);

// Range slider cap (clamped inside the row; the gold line marks the exact position)
function ui_draw_band_cap(hx, is_on, is_hot) local(cx) (
  cx = min(max(hx - 7, ui_in_x - 2), ui_in_x + ui_in_w - 12);
  ui_draw_bevel_box(cx, ui_bs_ty - 9, 14, 18, is_hot ? 0.30 : 0.24, is_hot ? 0.28 : 0.23, is_hot ? 0.25 : 0.21, 0);
  is_on || is_hot ? gfx_set(0.95, 0.80, 0.50, 1.0) : gfx_set(0.55, 0.53, 0.48, 1.0);
  gfx_line(min(max(hx, cx + 2), cx + 11), ui_bs_ty - 6, min(max(hx, cx + 2), cx + 11), ui_bs_ty + 6);
);

ui_band_gap = log(xo_min_ratio) / log(1000.0);
ui_hover_tip = 0;
ui_dbl_changed = 0;

gfx_set(0.11, 0.11, 0.10, 1.0);
gfx_rect(0, 0, ui_base_w, ui_base_h, 1);
ui_draw_bevel_box(12, 12, ui_base_w - 24, ui_base_h - 24, 0.17, 0.17, 0.16, 0);

ui_draw_screw(28, 28, 7);
ui_draw_screw(ui_base_w - 28, 28, 7);
ui_draw_screw(28, ui_base_h - 28, 7);
ui_draw_screw(ui_base_w - 28, ui_base_h - 28, 7);

ui_badge_w = 340;
ui_badge_h = 38;
ui_badge_x = (ui_base_w - ui_badge_w) * 0.5;
ui_badge_y = 20;
ui_draw_bevel_box(ui_badge_x, ui_badge_y, ui_badge_w, ui_badge_h, 0.12, 0.12, 0.11, 1);

gfx_setfont(1, "Arial", 16, 'b');
gfx_set(0.78, 0.75, 0.68, 1.0);
strcpy(#ui_title, "T H I C K E N E R");
gfx_measurestr(#ui_title, ui_tw, ui_th);
gfx_x = (ui_base_w - ui_tw) * 0.5;
gfx_y = ui_badge_y + 4;
gfx_drawstr(#ui_title);

gfx_setfont(3, "Arial", 10, 'b');
gfx_set(0.55, 0.53, 0.48, 0.95);
strcpy(#ui_sub, "O V E R S T R A T U M   A U D I O");
gfx_measurestr(#ui_sub, ui_tw, ui_th);
gfx_x = (ui_base_w - ui_tw) * 0.5;
gfx_y = ui_badge_y + 22;
gfx_drawstr(#ui_sub);

ui_mon_x = 34;
ui_mon_y = 66;
ui_mon_w = ui_base_w - 68;
ui_mon_h = 122;

(ui_mx >= ui_mon_x && ui_mx <= ui_mon_x + ui_mon_w && ui_my >= ui_mon_y && ui_my <= ui_mon_y + ui_mon_h) ? (
  ui_hover_tip = 7;
);

ui_draw_bevel_box(ui_mon_x, ui_mon_y, ui_mon_w, ui_mon_h, 0.13, 0.12, 0.10, 1);

ui_in_x = ui_mon_x + 2;
ui_in_y = ui_mon_y + 2;
ui_in_w = ui_mon_w - 4;
ui_in_h = ui_mon_h - 4;

// --- Band control interaction (handled before drawing, so graph & slider show the same frame) ---
ui_band_lo_n = ui_f_to_n(slider8);
ui_band_hi_n = ui_f_to_n(slider9);
ui_band_changed = 0;

ui_bs_x  = 34;               // range slider row (track uses the same x-mapping as the spectrum)
ui_bs_y  = 196;
ui_bs_w  = ui_base_w - 68;
ui_bs_h  = 42;
ui_bs_ty = ui_bs_y + 30;     // track centre line

// Spectrum handles: grab the line anywhere (+-7 px) or the tabs on top; top strip between tabs = move band
ui_lo_x = ui_in_x + ui_band_lo_n * ui_in_w;
ui_hi_x = ui_in_x + ui_band_hi_n * ui_in_w;
ui_in_graph = ui_mx >= ui_in_x - 6 && ui_mx <= ui_in_x + ui_in_w + 6 && ui_my >= ui_in_y && ui_my <= ui_in_y + ui_in_h;
ui_g_hit_lo  = ui_in_graph && abs(ui_mx - max(ui_lo_x, ui_in_x + 6)) <= 7;
ui_g_hit_hi  = ui_in_graph && abs(ui_mx - min(ui_hi_x, ui_in_x + ui_in_w - 6)) <= 7;
ui_g_hit_mid = ui_in_graph && ui_my <= ui_in_y + 18 && ui_mx > ui_lo_x + 7 && ui_mx < ui_hi_x - 7;
(ui_g_hit_lo || ui_g_hit_hi || ui_g_hit_mid) ? ( ui_hover_tip = 12; );
ui_band_interact(30, ui_in_x, ui_in_w, ui_g_hit_lo, ui_g_hit_hi, ui_g_hit_mid);

// Range slider: caps = edges, bar between = move (Shift = width), click beside caps = jump edge there
ui_lo_x = ui_in_x + ui_band_lo_n * ui_in_w;
ui_hi_x = ui_in_x + ui_band_hi_n * ui_in_w;
ui_in_row = ui_mx >= ui_bs_x && ui_mx <= ui_bs_x + ui_bs_w && ui_my >= ui_bs_y && ui_my <= ui_bs_y + ui_bs_h;
ui_s_hit_lo  = ui_in_row && ui_my >= ui_bs_ty - 12 && abs(ui_mx - max(ui_lo_x, ui_in_x + 5)) <= 8;
ui_s_hit_hi  = ui_in_row && ui_my >= ui_bs_ty - 12 && abs(ui_mx - min(ui_hi_x, ui_in_x + ui_in_w - 5)) <= 8;
ui_s_hit_mid = ui_in_row && ui_my >= ui_bs_ty - 12 && ui_mx > ui_lo_x + 8 && ui_mx < ui_hi_x - 8;
ui_in_row ? ( ui_hover_tip = 13; );
(ui_mouse_down && !ui_is_dbl && ui_drag_id == 0 && ui_in_row && ui_my >= ui_bs_ty - 12 && !ui_s_hit_lo && !ui_s_hit_hi && !ui_s_hit_mid) ? (
  ui_mx < ui_lo_x ? (
    ui_band_lo_n = min((ui_mx - ui_in_x) / ui_in_w, ui_band_hi_n - ui_band_gap);
    ui_band_lo_n = max(ui_band_lo_n, 0.0);
    ui_s_hit_lo = 1;
  ) : (
    ui_band_hi_n = max((ui_mx - ui_in_x) / ui_in_w, ui_band_lo_n + ui_band_gap);
    ui_band_hi_n = min(ui_band_hi_n, 1.0);
    ui_s_hit_hi = 1;
  );
  ui_band_snap();
  ui_band_changed = 1;
);
ui_band_interact(40, ui_in_x, ui_in_w, ui_s_hit_lo, ui_s_hit_hi, ui_s_hit_mid);

ui_band_wheel(ui_in_graph || ui_in_row);

ui_band_changed ? (
  slider8 = ui_band_lo_n <= 0.0 ? xo_f_min : ui_n_to_f(ui_band_lo_n);
  slider9 = ui_band_hi_n >= 1.0 ? xo_f_max : ui_n_to_f(ui_band_hi_n);
  slider_automate(128 + 256);
  dsp_prev_s8 = slider8;
  dsp_prev_s9 = slider9;
  ag_param_changed = 1;
  param_dirty = 1;
);

ui_band_lo_on = slider8 > xo_f_min + 0.5;
ui_band_hi_on = slider9 < xo_f_max - 0.5;
ui_band_lo_f  = max(slider8, xo_f_min);
ui_band_hi_f  = max(slider9, ui_band_lo_f * xo_min_ratio);
ui_lo_x = ui_in_x + ui_band_lo_n * ui_in_w;
ui_hi_x = ui_in_x + ui_band_hi_n * ui_in_w;
ui_lo_hot = ui_drag_id == 31 || ui_drag_id == 41 || (ui_drag_id == 0 && (ui_g_hit_lo || ui_s_hit_lo));
ui_hi_hot = ui_drag_id == 32 || ui_drag_id == 42 || (ui_drag_id == 0 && (ui_g_hit_hi || ui_s_hit_hi));
ui_mid_hot = ui_drag_id == 33 || ui_drag_id == 43 || (ui_drag_id == 0 && (ui_g_hit_mid || ui_s_hit_mid));

gfx_set(0.24, 0.23, 0.20, 0.6);
gfx_line(ui_in_x, ui_in_y + ui_in_h * 0.35, ui_in_x + ui_in_w, ui_in_y + ui_in_h * 0.35);
gfx_line(ui_in_x, ui_in_y + ui_in_h * 0.70, ui_in_x + ui_in_w, ui_in_y + ui_in_h * 0.70);

gfx_setfont(3, "Arial", 10);
ui_f_idx = 0;
loop(3,
  ui_grid_f = ui_f_idx == 0 ? 100.0 : (ui_f_idx == 1 ? 1000.0 : 10000.0);
  ui_gx = ui_in_x + (log(ui_grid_f / 20.0) / log(1000.0)) * ui_in_w;
  gfx_set(0.24, 0.23, 0.20, 0.6);
  gfx_line(ui_gx, ui_in_y, ui_gx, ui_in_y + ui_in_h);
  gfx_set(0.48, 0.46, 0.40, 0.85);
  gfx_x = ui_gx + 4;
  gfx_y = ui_in_y + ui_in_h - 13;
  ui_f_idx == 0 ? gfx_drawstr("100 Hz") : (ui_f_idx == 1 ? gfx_drawstr("1 kHz") : gfx_drawstr("10 kHz"));
  ui_f_idx += 1;
);

ui_dx = 0;
ui_sr = srate > 0 ? srate : 44100.0;
ui_half_n = dsp_fft_size * 0.5;
ui_col_f = max(dsp_color_freq_hz, 40.0);
ui_dens_norm = slider1 / 100.0;
ui_col_norm  = slider2 / 100.0;
ui_cur_gr = min(max(dsp_meter_gr_db, 0.0), 24.0);

while (ui_dx <= ui_in_w) (
  ui_freq = 20.0 * exp((ui_dx / ui_in_w) * log(1000.0));
  ui_fbin = ui_freq * dsp_fft_size / ui_sr;
  ui_b0 = min(max(floor(ui_fbin), 0), ui_half_n);
  ui_b1 = min(ui_b0 + 1, ui_half_n);
  ui_frac = 0.5 - 0.5 * cos((ui_fbin - floor(ui_fbin)) * $pi);

  ui_mag = disp_main[ui_b0] + ui_frac * (disp_main[ui_b1] - disp_main[ui_b0]);
  // Upper range: several bins per 2px column -> show their peak instead of a random sample
  ui_bn = min(floor(20.0 * exp(((ui_dx + 2) / ui_in_w) * log(1000.0)) * dsp_fft_size / ui_sr), ui_half_n);
  ui_bk = ui_b1 + 1;
  while (ui_bk <= ui_bn) (
    ui_mag = max(ui_mag, disp_main[ui_bk]);
    ui_bk += 1;
  );
  ui_mag *= sqrt(ui_freq / 1000.0);
  ui_spec_db = 20.0 * log10(max(ui_mag, 0.000001));
  ui_spec_norm = min(max((ui_spec_db + 66.0) / 66.0, 0.0), 1.0);
  ui_sy = ui_in_y + ui_in_h - ui_spec_norm * (ui_in_h - 6);

  gfx_set(0.55, 0.68, 0.36, 0.16);
  gfx_line(ui_in_x + ui_dx, ui_sy, ui_in_x + ui_dx, ui_in_y + ui_in_h);
  (ui_dx + 1 <= ui_in_w) ? (
    gfx_line(ui_in_x + ui_dx + 1, ui_sy, ui_in_x + ui_dx + 1, ui_in_y + ui_in_h);
  );

  ui_oct_dist = log(ui_freq / ui_col_f) / log(2.0);
  ui_bell_shape = exp(-0.85 * ui_oct_dist * ui_oct_dist);
  ui_bulge_db = ui_dens_norm * (11.0 + ui_col_norm * 9.0) * ui_bell_shape;
  ui_dyn_drop = (ui_dens_norm * 2.2) + ui_bulge_db + (ui_cur_gr * 0.40 * (0.35 + 0.65 * ui_bell_shape));
  // Processing only acts inside the band (LR4 magnitude response of the crossover)
  ui_band_wt = (ui_band_lo_on ? 1.0 / (1.0 + sqr(sqr(ui_band_lo_f / ui_freq))) : 1.0) *
               (ui_band_hi_on ? 1.0 / (1.0 + sqr(sqr(ui_freq / ui_band_hi_f))) : 1.0);
  ui_dyn_drop *= ui_band_wt;
  ui_gy = ui_in_y + min(max(ui_dyn_drop / 26.0, 0.015), 0.92) * ui_in_h;

  gfx_set(0.86, 0.36, 0.18, 0.24);
  gfx_line(ui_in_x + ui_dx, ui_in_y, ui_in_x + ui_dx, ui_gy);
  (ui_dx + 1 <= ui_in_w) ? (
    gfx_line(ui_in_x + ui_dx + 1, ui_in_y, ui_in_x + ui_dx + 1, ui_gy);
  );

  ui_dx > 0 ? (
    gfx_set(0.76, 0.84, 0.48, 0.90);
    gfx_line(ui_in_x + ui_dx - 2, ui_prev_sy, ui_in_x + ui_dx, ui_sy);

    gfx_set(0.95, 0.56, 0.24, 0.95);
    gfx_line(ui_in_x + ui_dx - 2, ui_prev_gy, ui_in_x + ui_dx, ui_gy);
    gfx_line(ui_in_x + ui_dx - 2, ui_prev_gy + 1, ui_in_x + ui_dx, ui_gy + 1);
  );

  ui_prev_sy = ui_sy;
  ui_prev_gy = ui_gy;
  ui_dx += 2;
);

// --- Band overlay: dim untouched ranges, handle lines + tabs + labels ---
ui_band_lo_on ? (
  gfx_set(0.04, 0.04, 0.03, 0.45);
  gfx_rect(ui_in_x, ui_in_y, ui_lo_x - ui_in_x, ui_in_h, 1);
);
ui_band_hi_on ? (
  gfx_set(0.04, 0.04, 0.03, 0.45);
  gfx_rect(ui_hi_x, ui_in_y, ui_in_x + ui_in_w - ui_hi_x, ui_in_h, 1);
);
gfx_set(0.88, 0.72, 0.38, ui_mid_hot ? 0.22 : 0.10);
gfx_rect(ui_lo_x, ui_in_y, ui_hi_x - ui_lo_x, 16, 1);

ui_band_lo_on || ui_lo_hot ? (
  gfx_set(0.92, 0.72, 0.32, ui_lo_hot ? 0.95 : 0.65);
  gfx_line(ui_lo_x, ui_in_y, ui_lo_x, ui_in_y + ui_in_h - 1);
);
ui_band_hi_on || ui_hi_hot ? (
  gfx_set(0.92, 0.72, 0.32, ui_hi_hot ? 0.95 : 0.65);
  gfx_line(ui_hi_x, ui_in_y, ui_hi_x, ui_in_y + ui_in_h - 1);
);
ui_draw_band_tab(ui_lo_x, ui_in_y + 1, ui_band_lo_on, ui_lo_hot);
ui_draw_band_tab(ui_hi_x, ui_in_y + 1, ui_band_hi_on, ui_hi_hot);

gfx_setfont(3, "Arial", 10, 'b');
ui_band_lo_on ? (
  ui_fmt_hz(#ui_flo, ui_band_lo_f);
  gfx_measurestr(#ui_flo, ui_tw, ui_th);
  gfx_set(0.95, 0.82, 0.55, 0.95);
  gfx_x = ui_lo_x + 9;
  gfx_y = ui_in_y + 3;
  gfx_drawstr(#ui_flo);
);
ui_band_hi_on ? (
  ui_fmt_hz(#ui_fhi, ui_band_hi_f);
  gfx_measurestr(#ui_fhi, ui_tw, ui_th);
  gfx_set(0.95, 0.82, 0.55, 0.95);
  gfx_x = ui_hi_x - 9 - ui_tw;
  gfx_y = ui_in_y + 3;
  gfx_drawstr(#ui_fhi);
);

// Status Badge inside Spectrum Monitor when BYPASS or DELTA is active
(dsp_bypass_on || dsp_delta_on || dsp_solo_on) ? (
  gfx_setfont(2, "Arial", 11, 'b');
  dsp_bypass_on ? (
    dsp_solo_on ? strcpy(#ui_mode_str, "BYPASS + SOLO (RAW BAND)") : strcpy(#ui_mode_str, "BYPASS ACTIVE (RAW INPUT)");
    gfx_set(0.96, 0.30, 0.24, 0.95);
  ) : dsp_delta_on ? (
    strcpy(#ui_mode_str, "DELTA MONITOR (PROCESSED - INPUT)");
    gfx_set(0.96, 0.58, 0.22, 0.95);
  ) : (
    strcpy(#ui_mode_str, "SOLO BAND (PROCESSED)");
    gfx_set(0.95, 0.80, 0.40, 0.95);
  );
  gfx_measurestr(#ui_mode_str, ui_tw, ui_th);
  gfx_x = ui_in_x + ui_in_w - ui_tw - 8;
  gfx_y = ui_in_y + 22; // below the band handle tabs
  gfx_drawstr(#ui_mode_str);
);

// --- Multi-function band range slider (aligned 1:1 with the spectrum frequency axis) ---
ui_draw_bevel_box(ui_bs_x, ui_bs_y, ui_bs_w, ui_bs_h, 0.13, 0.12, 0.10, 1);

gfx_setfont(3, "Arial", 11, 'b');
gfx_set(0.75, 0.72, 0.65, 0.95);
gfx_x = ui_bs_x + 10;
gfx_y = ui_bs_y + 5;
gfx_drawstr("PROCESSING BAND");

(!ui_band_lo_on && !ui_band_hi_on) ? (
  strcpy(#ui_band_str, "FULL RANGE");
) : (
  ui_fmt_hz(#ui_flo, ui_band_lo_on ? ui_band_lo_f : xo_f_min);
  ui_fmt_hz(#ui_fhi, ui_band_hi_on ? ui_band_hi_f : xo_f_max);
  sprintf(#ui_band_str, "%s  -  %s", #ui_flo, #ui_fhi);
);
gfx_measurestr(#ui_band_str, ui_tw, ui_th);
gfx_set(0.92, 0.80, 0.52, 1.0);
gfx_x = ui_bs_x + ui_bs_w - 10 - ui_tw;
gfx_y = ui_bs_y + 5;
gfx_drawstr(#ui_band_str);

// Grid ticks (100 Hz / 1 kHz / 10 kHz) like the spectrum
ui_f_idx = 0;
loop(3,
  ui_grid_f = ui_f_idx == 0 ? 100.0 : (ui_f_idx == 1 ? 1000.0 : 10000.0);
  ui_gx = ui_in_x + (log(ui_grid_f / 20.0) / log(1000.0)) * ui_in_w;
  gfx_set(0.32, 0.31, 0.28, 0.8);
  gfx_line(ui_gx, ui_bs_ty - 8, ui_gx, ui_bs_ty + 8);
  ui_f_idx += 1;
);

// Groove
gfx_set(0.07, 0.07, 0.06, 1.0);
gfx_rect(ui_in_x, ui_bs_ty - 3, ui_in_w, 6, 1);
gfx_set(0.26, 0.26, 0.24, 1.0);
gfx_line(ui_in_x, ui_bs_ty + 3, ui_in_x + ui_in_w, ui_bs_ty + 3);

// Active band bar
gfx_set(0.88, 0.62, 0.24, ui_mid_hot ? 1.0 : 0.80);
gfx_rect(ui_lo_x, ui_bs_ty - 2, ui_hi_x - ui_lo_x, 4, 1);

// Caps
ui_draw_band_cap(ui_lo_x, ui_band_lo_on, ui_lo_hot);
ui_draw_band_cap(ui_hi_x, ui_band_hi_on, ui_hi_hot);

ui_in_db_raw  = 20.0 * log10(max(dsp_meter_in, 0.00001));
ui_out_db_raw = 20.0 * log10(max(dsp_meter_out, 0.00001));
ui_gr_db_raw  = dsp_bypass_on ? 0.0 : dsp_meter_gr_db;

ui_smooth_in_db  = ui_in_db_raw  < -55.0 ? (ui_smooth_in_db  * 0.85 - 60.0 * 0.15) : (ui_smooth_in_db  * 0.92 + ui_in_db_raw  * 0.08);
ui_smooth_out_db = ui_out_db_raw < -55.0 ? (ui_smooth_out_db * 0.85 - 60.0 * 0.15) : (ui_smooth_out_db * 0.92 + ui_out_db_raw * 0.08);
ui_smooth_gr_db  = ui_in_db_raw  < -55.0 ? (ui_smooth_gr_db  * 0.85)              : (ui_smooth_gr_db  * 0.92 + ui_gr_db_raw  * 0.08);

(time_precise() - ui_last_txt_upd) >= 0.12 ? (
  ui_txt_in_db  = ui_smooth_in_db;
  ui_txt_out_db = ui_smooth_out_db;
  ui_txt_gr_db  = ui_smooth_gr_db;
  ui_last_txt_upd = time_precise();
);

ui_draw_vmeter(34, 246, 54, 206, "IN (dB)", ui_in_db_raw, ui_txt_in_db, -48.0, 6.0, 0, 8);
ui_draw_vmeter(ui_base_w - 150, 246, 54, 206, "GR (dB)",  ui_gr_db_raw,  ui_txt_gr_db,  0.0, 24.0, 1, 9);
ui_draw_vmeter(ui_base_w - 88,  246, 54, 206, "OUT (dB)", ui_out_db_raw, ui_txt_out_db, -48.0, 6.0, 0, 10);

ui_val_dens   = slider1;
ui_val_col    = slider2;
ui_val_trim   = slider10;
ui_val_mix    = slider4;
ui_delta_on   = (slider6 >= 0.5) && (slider7 < 0.5);
ui_bypass_on  = slider7 >= 0.5;
ui_solo_on    = slider11 >= 0.5;

ui_knob_y = 326;
ui_knob_r = 50;

ui_val_dens = ui_draw_knob(1, 188, ui_knob_y, ui_knob_r, ui_val_dens, 0.0, 100.0, 20.0,  "THICKENING", "%",  0, ui_val_dens,  1);
ui_val_col  = ui_draw_knob(2, 348, ui_knob_y, ui_knob_r, ui_val_col,  0.0, 100.0, 50.0,  "COLOR",   "%",  0, ui_val_col,   2);
ui_val_trim = ui_draw_knob(3, 508, ui_knob_y, ui_knob_r, ui_val_trim, -12.0, 12.0, 0.0,   "TRIM",    "dB", 0, ui_val_trim,  3);

ui_deck_y = 466;
ui_deck_h = 56;
ui_draw_bevel_box(34, ui_deck_y, ui_base_w - 68, ui_deck_h, 0.14, 0.14, 0.13, 1);

// --- Bottom Deck: AUTO GAIN readout | DELTA | SOLO | BYPASS | DRY/WET MIX ---
// LED: gold = locked (3s LUFS window valid), orange = adapting (fast RMS stage), dark = holding (bypass)
ui_ag_state = dsp_bypass_on ? 2 : (lufs_valid_gate && ag_fast_samples == 0) ? 0 : 1;
ui_draw_ag_display(48, ui_deck_y + 13, 168, 30, dsp_auto_gain_db, ui_ag_state, 5);

ui_ClickDelta = ui_draw_push_switch(226, ui_deck_y + 13, 74, 30, "DELTA", ui_delta_on, 1, 6);
ui_ClickDelta ? (
  ui_new_delta = ui_delta_on ? 0 : 1;
  slider6 = ui_new_delta;
  slider_automate(32);
  (ui_new_delta && slider7 >= 0.5) ? (
    slider7 = 0;
    slider_automate(64);
  );
  dsp_prev_s6 = slider6;
  dsp_prev_s7 = slider7;
  param_dirty = 1;
);

ui_ClickSolo = ui_draw_push_switch(308, ui_deck_y + 13, 74, 30, "SOLO", ui_solo_on, 0, 14);
ui_ClickSolo ? (
  slider11 = ui_solo_on ? 0 : 1;
  slider_automate(1024);
  param_dirty = 1;
);

ui_ClickBypass = ui_draw_push_switch(390, ui_deck_y + 13, 84, 30, "BYPASS", ui_bypass_on, 2, 11);
ui_ClickBypass ? (
  ui_new_byp = ui_bypass_on ? 0 : 1;
  slider7 = ui_new_byp;
  slider_automate(64);
  (ui_new_byp && slider6 >= 0.5) ? (
    slider6 = 0;
    slider_automate(32);
  );
  dsp_prev_s6 = slider6;
  dsp_prev_s7 = slider7;
  param_dirty = 1;
);

ui_val_mix = ui_draw_hslider(4, 488, ui_deck_y + 24, 220, 22, ui_val_mix, 0.0, 100.0, 100.0, "DRY / WET MIX", 4);

ui_val_dens != slider1 ? (
  slider1 = ui_val_dens;
  slider_automate(1);
  ag_param_changed = 1;
  dsp_prev_s1 = slider1;
  param_dirty = 1;
);
ui_val_col != slider2 ? (
  slider2 = ui_val_col;
  slider_automate(2);
  ag_param_changed = 1;
  dsp_prev_s2 = slider2;
  param_dirty = 1;
);
ui_val_trim != slider10 ? (
  slider10 = ui_val_trim;
  slider_automate(512);
  param_dirty = 1;
);
ui_val_mix != slider4 ? (
  slider4 = ui_val_mix;
  slider_automate(8);
  ag_param_changed = 1;
  dsp_prev_s4 = slider4;
  param_dirty = 1;
);

!(mouse_cap & 1) ? (
  ui_drag_id = 0;
);
mouse_wheel = 0; // consume wheel events not used by the band controls

ui_hover_tip == 1 ? strcpy(#ui_tip, "THICKENING: Push this up to make your sound fuller, louder, and punchier (Double-click to reset).")
: ui_hover_tip == 2 ? strcpy(#ui_tip, "COLOR: Adds harmonic warmth and shifts the tone from deep low-end weight to bright upper presence.")
: ui_hover_tip == 3 ? strcpy(#ui_tip, "TRIM: Level offset of the processed band on top of Auto Gain (0 dB = loudness-matched). Outside bands stay at unity.")
: ui_hover_tip == 4 ? strcpy(#ui_tip, "DRY / WET MIX: Blends the original clean signal with the processed sound for parallel thickness.")
: ui_hover_tip == 5 ? strcpy(#ui_tip, "AUTO GAIN (always on): Band loudness match, fast RMS + 3s BS.1770 LUFS-S. LED gold = locked, orange = adapting.")
: ui_hover_tip == 6 ? strcpy(#ui_tip, "DELTA: Outputs the exact difference (Processed - Input) of the band, including Auto Gain and Trim.")
: ui_hover_tip == 7 ? strcpy(#ui_tip, "SPECTRUM & DYNAMICS: Green = output spectrum; Amber = active tone & compression. Dimmed areas are untouched.")
: ui_hover_tip == 8 ? strcpy(#ui_tip, "IN (dB): Shows the incoming peak audio level before processing.")
: ui_hover_tip == 9 ? strcpy(#ui_tip, "GR (dB): Peak reduction of the processed band, input vs. loudness-matched output (incl. Auto Gain & Dry/Wet).")
: ui_hover_tip == 10 ? strcpy(#ui_tip, "OUT (dB): Shows the final monitored output peak level leaving the plugin.")
: ui_hover_tip == 11 ? strcpy(#ui_tip, "BYPASS: True signal bypass (raw input), disables Delta. With SOLO on you hear the unprocessed band for A/B.")
: ui_hover_tip == 14 ? strcpy(#ui_tip, "SOLO: Listen to the processing band only. Combine with BYPASS to compare it with the unprocessed band.")
: ui_hover_tip == 12 ? strcpy(#ui_tip, "BAND HANDLES: Drag edges, drag top strip to move band, wheel = width, Ctrl = fine, double-click = reset edge.")
: ui_hover_tip == 13 ? strcpy(#ui_tip, "BAND: Drag caps/bar, click beside a cap to jump, Shift+drag bar or wheel = width, double-click bar = full range.")
: strcpy(#ui_tip, "Hover over any control for help. Hold Ctrl while dragging for fine adjustments, or double-click a knob to reset.");

gfx_setfont(4, "Arial", 11);
gfx_set(0.52, 0.50, 0.45, 1.0);
gfx_measurestr(#ui_tip, ui_tw, ui_th);
gfx_x = (ui_base_w - ui_tw) * 0.5;
gfx_y = ui_base_h - 28;
gfx_drawstr(#ui_tip);

gfx_dest = -1;
gfx_set(0.07, 0.07, 0.06, 1.0);
(ui_off_x > 0) ? (
  gfx_rect(0, 0, ui_off_x, gfx_h, 1);
  gfx_rect(ui_off_x + ui_base_w * ui_scale, 0, gfx_w, gfx_h, 1);
);
(ui_off_y > 0) ? (
  gfx_rect(0, 0, gfx_w, ui_off_y, 1);
  gfx_rect(0, ui_off_y + ui_base_h * ui_scale, gfx_w, gfx_h, 1);
);

gfx_set(1.0, 1.0, 1.0, 1.0);
gfx_blit(1, 1.0, 0.0, 0, 0, ui_base_w, ui_base_h, ui_off_x, ui_off_y, ui_base_w * ui_scale, ui_base_h * ui_scale);

ui_last_cap = mouse_cap;