dspk-app-core 0.0.10

DSP App core: the workbench for any multichannel signal (open, view, process, write) and the plugin interface the domain plugins (electrophysiology: dspk-app-synapse) extend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Waveform rasterizer for the plot area.
//!
//! Draws only the plot itself (traces or heatmap, grid, spike ticks, scale bar); all text
//! (channel labels, time axis, readouts), the playhead and the cursor are elements the view lays
//! out around and over the image.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use dspk_ops::math::percentile;
use dspk_core::SignalUnit;
use dspk_view::{min_max_decimate_into, Envelope, SignalBackend, View};

use crate::ui::plot::canvas::{Canvas, Frame};
use crate::ui::plot::ticks::nice_step;
use crate::ui::theme::palette::Palette;
use crate::data::recording::SpikeEventStore;

/// Voltage that fills `LANE_FILL` of a lane's half-height at gain 1x when a view is not
/// auto-scaled (80 µV: a large extracellular spike).
pub const NOMINAL_VOLTS: f64 = 80e-6;
/// The same for signals that are not voltages (no natural size: auto-scale is the useful mode).
pub const NOMINAL_OTHER: f32 = 1.0;
/// Fraction of the lane half-height used by the nominal amplitude.
const LANE_FILL: f32 = 0.84;

/// Time-module view kinds: how the plot area visualizes channels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum TimeViewKind {
    /// One trace per lane for the visible channel page.
    #[default]
    Traces,
    /// All channels as rows, color = peak |amplitude| per screen column.
    Heatmap,
    /// Spike times as ticks, one row per unit (a plugin's sorting), coloured by unit.
    Raster,
}

/// How traces are coloured.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum ColorBy {
    /// A colour per channel (cycling).
    #[default]
    Channel,
    /// One colour for every trace.
    Single,
    /// Each column by its amplitude (the heat map's colours).
    Amplitude,
}

impl ColorBy {
    pub const ALL: [ColorBy; 3] = [ColorBy::Channel, ColorBy::Single, ColorBy::Amplitude];

    pub fn name(self) -> &'static str {
        match self {
            ColorBy::Channel => "By channel",
            ColorBy::Single => "One colour",
            ColorBy::Amplitude => "By amplitude",
        }
    }
}

/// Everything needed to draw one frame of one view. Sendable to the worker thread.
#[derive(Clone)]
pub struct RenderRequest {
    /// The signal shown: asked for the envelope of the visible window (zoomed out from its
    /// pyramid, zoomed in from the samples).
    pub signal: Arc<dyn SignalBackend>,
    pub events: Arc<SpikeEventStore>,
    /// Physical pixel size of the plot area.
    pub width: u32,
    pub height: u32,
    /// Display scale factor (physical px per logical px); sets line and marker thickness.
    pub scale: f32,
    pub mode: TimeViewKind,
    /// Channels to draw, top to bottom (traces: the lanes on screen; heatmap: every row).
    pub channels: Vec<usize>,
    pub window_start_sec: f64,
    pub window_sec: f64,
    /// Session time of the source's first sample (sources can start at different times).
    pub start_time_sec: f64,
    pub amplitude_scale: f32,
    /// Amplitude (signal unit) filling a lane when not auto-scaled ([`nominal_amplitude`]).
    pub nominal: f32,
    /// Fit the amplitude to the visible data (else `nominal` fills a lane).
    pub auto_scale: bool,
    /// Subtract each channel's offset over the window (center of its interquartile range).
    pub remove_dc: bool,
    /// Scale of the previous frame: kept while the data still fits it, so views do not jump.
    pub scale_hint: f32,
    /// Times of vertical grid lines (the time-axis ticks).
    pub grid_times: Vec<f64>,
    /// Draw the amplitude scale bar (traces).
    pub scale_bar: bool,
    /// Sorted spikes to mark in a cluster color: (color, [(time_sec, channel)]).
    pub highlights: Vec<(crate::ui::plot::canvas::Pixel, Vec<(f64, usize)>)>,
    /// A plugin's marks over the traces (e.g. spikes coloured by unit over their template's
    /// extent, the traces faint).
    pub overlay: Option<Arc<crate::plugin::TraceOverlay>>,
    /// Raster rows (one per unit) for [`TimeViewKind::Raster`].
    pub raster: Option<Arc<crate::plugin::Raster>>,
    pub color_by: ColorBy,
    pub palette: Palette,
}

thread_local! {
    /// Scratch buffers of the worker thread, reused across frames.
    static RENDERER: std::cell::RefCell<WaveformRenderer> = std::cell::RefCell::new(WaveformRenderer::default());
}

/// Renders `req` with this thread's reusable renderer (call from a work thread): the frame and
/// the amplitude scale it was drawn with, and whether every column was available. Zoomed-out
/// windows draw from the signal's pyramid as far as it is built (the rest stays empty until its
/// builder reaches it: draw again on progress while incomplete); `None` when a newer frame for
/// the view cancelled this one.
pub fn render_on_worker(req: &RenderRequest, cancel: &AtomicBool) -> Option<(Frame, f32, bool)> {
    if cancel.load(Ordering::Relaxed) {
        return None;
    }
    Some(RENDERER.with(|r| {
        let mut r = r.borrow_mut();
        let (frame, scale) = r.render_scaled(req);
        (frame, scale, r.complete)
    }))
}

/// Visible sample range of `req`'s source and the pixel columns `x0..x1` it covers (sources can
/// start later or end earlier than the window); `None` when nothing is visible.
fn visible(req: &RenderRequest) -> Option<(usize, usize, usize, usize)> {
    let info = req.signal.info();
    let samples = info.samples as usize;
    if samples == 0 || info.channel_count() == 0 || req.window_sec <= 0.0 {
        return None;
    }
    let sr = info.sample_rate_hz();
    let s0 = (req.window_start_sec - req.start_time_sec) * sr;
    let s1 = s0 + req.window_sec * sr;
    let (a, b) = (s0.max(0.0), s1.min(samples as f64));
    let w_px = req.width.max(1) as f64;
    let (x0, x1) = if b > a { (((a - s0) / (s1 - s0) * w_px).round() as usize, ((b - s0) / (s1 - s0) * w_px).round() as usize) } else { (0, 0) };
    let (start, end) = (a.round() as usize, (b.round() as usize).max(a.round() as usize));
    Some((start, end, x0, x1.min(req.width.max(1) as usize)))
}

/// Nominal amplitude of a signal in `unit`: [`NOMINAL_VOLTS`] in that unit for voltages, else
/// [`NOMINAL_OTHER`].
pub fn nominal_amplitude(unit: &SignalUnit) -> f32 {
    let volts_per_unit = match unit {
        SignalUnit::Volt => 1.0,
        SignalUnit::Millivolt => 1e-3,
        SignalUnit::Microvolt => 1e-6,
        _ => return NOMINAL_OTHER,
    };
    (NOMINAL_VOLTS / volts_per_unit) as f32
}

/// Pixels per unit for a lane of `lane_h` pixels, where `nominal` units fill `LANE_FILL` of
/// the half-lane at gain 1.
pub fn px_per_unit(lane_h: f32, amplitude_scale: f32, nominal: f32) -> f32 {
    lane_h * 0.5 * LANE_FILL * amplitude_scale / nominal.max(f32::MIN_POSITIVE)
}

/// Scale bar value (1-2-5 series) about 45% of a lane tall, for `k` pixels per unit.
pub fn scale_bar_value(lane_h: f32, k: f32) -> f32 {
    if k <= 0.0 || lane_h <= 0.0 {
        return 0.0;
    }
    nice_step((0.45 * lane_h / k) as f64) as f32
}

/// Auto-scale: the previous scale while the visible amplitude stays within 50–125 % of it,
/// else the new amplitude.
fn choose_scale(amplitude: f32, hint: f32, nominal: f32) -> f32 {
    if amplitude.is_nan() || amplitude <= 0.0 || !amplitude.is_finite() {
        return if hint > 0.0 { hint } else { nominal };
    }
    if hint > 0.0 && amplitude >= 0.5 * hint && amplitude <= 1.25 * hint { hint } else { amplitude }
}

/// One row per unit, each spike a tick in its unit's colour; rows fill the height.
fn draw_raster(canvas: &mut Canvas, req: &RenderRequest) {
    let Some(r) = &req.raster else { return };
    let n = r.rows.len();
    if n == 0 {
        return;
    }
    let row_h = canvas.height as f32 / n as f32;
    let w = canvas.width as f64;
    let tick = (row_h * 0.8).max(1.0);
    for (i, row) in r.rows.iter().enumerate() {
        let top = i as f32 * row_h + (row_h - tick) * 0.5;
        for &t in &row.times {
            let x = ((t - req.window_start_sec) / req.window_sec * w) as f32;
            if x >= 0.0 && x < w as f32 {
                canvas.rect(x, top, x + req.scale.max(1.0), top + tick, row.color, 1.0);
            }
        }
    }
}

/// Opacity of traces under an overlay (the marks are drawn opaque over them).
const DIM_ALPHA: f32 = 0.35;

/// The vertical span of column `x` of an envelope row (`[min, max]` per column) around `center`
/// at `k` pixels per unit, joined to the previous column so steep edges stay connected; `None`
/// where the row has no data.
fn column_span(row: &[[f32; 2]], x: usize, center: f32, k: f32, (lo, hi): (f32, f32)) -> Option<(f32, f32)> {
    let [mn, mx] = *row.get(x)?;
    if !mn.is_finite() {
        return None;
    }
    let (mut a, mut b) = ((center - mx * k).clamp(lo, hi), (center - mn * k).clamp(lo, hi));
    if let Some(&[pmn, pmx]) = x.checked_sub(1).and_then(|p| row.get(p)) {
        if pmn.is_finite() {
            let (pa, pb) = ((center - pmx * k).clamp(lo, hi), (center - pmn * k).clamp(lo, hi));
            a = a.min(pb);
            b = b.max(pa);
        }
    }
    Some((a, b))
}

/// Rasterizer with reusable scratch buffers (no per-frame allocations besides the image).
#[derive(Default)]
pub struct WaveformRenderer {
    /// `[min, max]` per (row, pixel column), row-major.
    env: Vec<[f32; 2]>,
    /// Whether each requested row is a real channel.
    valid: Vec<bool>,
    /// Channels actually read, and the row each one fills.
    read_channels: Vec<usize>,
    read_rows: Vec<usize>,
    /// The signal's answer for the read channels (its buffer reused across frames).
    answer: Option<Envelope>,
    /// Whether the last frame had every column it needed (false while the pyramid builds).
    complete: bool,
    heat: Vec<f32>,
    /// Scratch for medians and percentiles.
    stats: Vec<f32>,
}

impl WaveformRenderer {
    #[cfg(test)]
    pub fn render(&mut self, req: &RenderRequest) -> Frame {
        self.render_scaled(req).0
    }

    /// Renders and returns the amplitude scale used (units filling a lane at gain 1). Zoomed out,
    /// columns come from the signal's pyramid (pages not built yet draw empty).
    pub fn render_scaled(&mut self, req: &RenderRequest) -> (Frame, f32) {
        let signal = req.signal.as_ref();
        let width = req.width.max(1);
        let height = req.height.max(1);
        let mut pixel_buffer = Frame::new(width, height);
        let mut canvas = pixel_buffer.canvas();
        canvas.pixels.fill(req.palette.background);

        let Some((start, end, x0, x1)) = visible(req) else {
            return (pixel_buffer, req.scale_hint.max(0.0));
        };

        // Time grid aligned with the axis ticks
        let w = canvas.width as f64;
        for &t in &req.grid_times {
            let x = ((t - req.window_start_sec) / req.window_sec * w).round();
            if x >= 0.0 && x < w {
                canvas.vline(x as usize, 0, canvas.height, req.palette.grid);
            }
        }
        // A raster reads no samples: spike times only
        if req.mode == TimeViewKind::Raster {
            self.complete = true;
            draw_raster(&mut canvas, req);
            return (pixel_buffer, req.scale_hint.max(0.0));
        }

        self.envelope(signal, &req.channels, start, end, x1.saturating_sub(x0));
        self.place_columns(req.channels.len(), x0, x1, canvas.width);
        let scale = self.adjust(req, canvas.width);
        let has_samples = end > start;
        match req.mode {
            TimeViewKind::Traces => self.draw_traces(&mut canvas, &req.events, req, has_samples, scale),
            TimeViewKind::Heatmap => self.draw_heatmap(&mut canvas, req, has_samples, scale),
            TimeViewKind::Raster => {}
        }

        (pixel_buffer, scale)
    }

    /// Spreads `cols`-wide envelope rows into `width`-wide rows starting at column `x0`; columns
    /// the source does not cover become NaN (drawn empty).
    fn place_columns(&mut self, rows: usize, x0: usize, x1: usize, width: usize) {
        let cols = x1.saturating_sub(x0);
        if cols == width {
            return;
        }
        let mut full = vec![[f32::NAN, f32::NAN]; rows * width];
        if cols > 0 {
            for r in 0..rows {
                full[r * width + x0..r * width + x1].copy_from_slice(&self.env[r * cols..(r + 1) * cols]);
            }
        }
        self.env = full;
    }

    /// Removes each row's offset (when asked: the midpoint of the 25th and 75th percentiles of
    /// its column midpoints — robust to spikes and unbiased for two-level signals) and returns
    /// the amplitude scale: the 99th percentile of |value| over the visible rows (auto-scale),
    /// else the request's nominal amplitude.
    fn adjust(&mut self, req: &RenderRequest, width: usize) -> f32 {
        let rows = req.channels.len();
        if req.remove_dc {
            for r in (0..rows).filter(|&r| self.valid[r]) {
                let row = &mut self.env[r * width..(r + 1) * width];
                self.stats.clear();
                self.stats.extend(row.iter().filter(|v| v[0].is_finite()).map(|v| 0.5 * (v[0] + v[1])));
                let (Some(q1), Some(q3)) = (percentile(&mut self.stats, 25.0), percentile(&mut self.stats, 75.0)) else { continue };
                let offset = 0.5 * (q1 + q3);
                for v in row.iter_mut() {
                    v[0] -= offset;
                    v[1] -= offset;
                }
            }
        }
        if !req.auto_scale {
            return req.nominal;
        }
        self.stats.clear();
        for r in (0..rows).filter(|&r| self.valid[r]) {
            self.stats.extend(self.env[r * width..(r + 1) * width].iter().filter(|v| v[0].is_finite()).map(|v| v[0].abs().max(v[1].abs())));
        }
        choose_scale(percentile(&mut self.stats, 99.0).unwrap_or(0.0), req.scale_hint, req.nominal)
    }

    /// Fills `env` with the `[min, max]` of every requested row per pixel column over
    /// `start..end`, as the signal answers the view (zoomed out from its pyramid, else from the
    /// samples, streamed in bounded blocks). A window of fewer samples than columns comes back as
    /// samples and is spread over the columns. Every sample of the window lands in a column, so no
    /// peak is dropped. Rows of channels the signal lacks, and every row when it cannot answer,
    /// stay NaN (drawn empty).
    fn envelope(&mut self, signal: &dyn SignalBackend, rows: &[usize], start: usize, end: usize, width: usize) {
        let total = signal.info().channel_count();
        self.complete = true;
        self.env.clear();
        self.env.resize(rows.len() * width, [f32::NAN, f32::NAN]);
        self.valid.clear();
        self.valid.extend(rows.iter().map(|&c| c < total));
        self.read_channels.clear();
        self.read_rows.clear();
        for (r, &c) in rows.iter().enumerate().filter(|&(_, &c)| c < total) {
            self.read_channels.push(c);
            self.read_rows.push(r);
        }
        if self.read_channels.is_empty() || end <= start || width == 0 {
            return;
        }
        let view = View { channels: self.read_channels.clone(), start: start as u64, end: end as u64, width };
        let answer = self.answer.get_or_insert_with(|| Envelope::Samples(Vec::new()));
        if let Err(e) = signal.view(&view, answer) {
            tracing::warn!("cannot draw samples {start}..{end}: {e}");
            return;
        }
        match answer {
            Envelope::Columns { values, complete } => {
                self.complete = *complete;
                for (k, &r) in self.read_rows.iter().enumerate() {
                    self.env[r * width..(r + 1) * width].copy_from_slice(&values[k * width..(k + 1) * width]);
                }
            }
            Envelope::Samples(samples) => {
                let n = end - start;
                for (k, &r) in self.read_rows.iter().enumerate() {
                    min_max_decimate_into(&samples[k * n..(k + 1) * n], &mut self.env[r * width..(r + 1) * width]);
                }
            }
        }
    }

    fn draw_traces(&mut self, canvas: &mut Canvas, events: &SpikeEventStore, req: &RenderRequest, has_samples: bool, scale: f32) {
        let num_channels = req.channels.len();
        if num_channels == 0 {
            return;
        }

        let lane_h = canvas.height as f32 / num_channels as f32;
        let k = px_per_unit(lane_h, req.amplitude_scale, scale);
        let thickness = req.scale.max(1.0);
        let t_end = req.window_start_sec + req.window_sec;

        let w = canvas.width;
        for lane in 0..num_channels {
            let ch = req.channels[lane];
            if !self.valid[lane] {
                continue;
            }
            let color = req.palette.channel(ch);
            let center = (lane as f32 + 0.5) * lane_h;

            // Dashed baseline
            let by = center.round() as usize;
            for x in (0..canvas.width).filter(|x| x % 4 != 0) {
                canvas.set(x, by, req.palette.baseline);
            }

            // Spikes of selected clusters: colored band + thick tick
            for (color, spikes) in &req.highlights {
                for &(t, sch) in spikes {
                    if sch != ch || t < req.window_start_sec || t > t_end {
                        continue;
                    }
                    let x = ((t - req.window_start_sec) / req.window_sec * canvas.width as f64) as f32;
                    let top = lane as f32 * lane_h;
                    canvas.rect(x - 2.0 * req.scale, top, x + 2.0 * req.scale, top + lane_h, *color, 0.16);
                    canvas.rect(x - thickness, top + 1.0, x + thickness, top + 1.0 + 10.0 * req.scale, *color, 1.0);
                }
            }

            // Spike ticks: faint full-lane line + solid tick at the lane top
            for &t in events.in_window(ch, req.window_start_sec, t_end) {
                let x = ((t - req.window_start_sec) / req.window_sec * canvas.width as f64) as usize;
                let top = (lane as f32 * lane_h) as usize;
                let bottom = ((lane + 1) as f32 * lane_h) as usize;
                canvas.vline_alpha(x, top, bottom, req.palette.marker, 0.18);
                let tick = (6.0 * req.scale) as usize;
                for dx in 0..(thickness as usize).max(1) {
                    canvas.vline(x + dx, top + 1, top + 1 + tick, req.palette.marker);
                }
            }

            if !has_samples {
                continue;
            }

            // Anti-aliased min/max envelope, joined to the previous column for continuity; faint
            // under an overlay, whose marks redraw their columns in their unit's colour
            let row = &self.env[lane * w..(lane + 1) * w];
            let clip = (0.0, canvas.height as f32 - 1.0);
            let dim = req.overlay.as_ref().is_some_and(|o| o.dim);
            let color = match req.color_by {
                ColorBy::Single => req.palette.text,
                _ => color,
            };
            for x in 0..w {
                if let Some((a, b)) = column_span(row, x, center, k, clip) {
                    if dim {
                        canvas.span_aa_alpha(x, a - thickness * 0.5, b + thickness * 0.5, req.palette.text, DIM_ALPHA);
                    } else if req.color_by == ColorBy::Amplitude {
                        // Peak |amplitude| of the column against the lane's scale
                        let [mn, mx] = row[x];
                        let v = (mn.abs().max(mx.abs()) * k / (lane_h * 0.5)).min(1.0);
                        canvas.span_aa(x, a - thickness * 0.5, b + thickness * 0.5, req.palette.heat(0.25 + 0.75 * v));
                    } else {
                        canvas.span_aa(x, a - thickness * 0.5, b + thickness * 0.5, color);
                    }
                }
            }
            if let Some(o) = &req.overlay {
                let px_per_sec = w as f64 / req.window_sec;
                for m in &o.marks {
                    let Some(unit) = o.units.get(m.unit as usize) else { continue };
                    if unit.channels.binary_search(&ch).is_err() {
                        continue;
                    }
                    let x0 = ((m.start_sec - req.window_start_sec) * px_per_sec).floor().max(0.0) as usize;
                    let x1 = (((m.end_sec - req.window_start_sec) * px_per_sec).ceil().max(0.0) as usize).min(w.saturating_sub(1));
                    for x in x0..=x1 {
                        if let Some((a, b)) = column_span(row, x, center, k, clip) {
                            canvas.span_aa(x, a - thickness * 0.5, b + thickness * 0.5, unit.color);
                        }
                    }
                }
            }
        }

        // Amplitude scale bar in the bottom-right corner of the last lane
        let bar = if req.scale_bar { scale_bar_value(lane_h, k) } else { 0.0 };
        if bar > 0.0 {
            let bar_h = bar * k;
            let x = canvas.width.saturating_sub((12.0 * req.scale) as usize);
            let bottom = canvas.height as f32 - 6.0 * req.scale;
            let top = (bottom - bar_h).max(0.0);
            for dx in 0..(thickness as usize).max(1) {
                canvas.vline(x + dx, top as usize, bottom as usize, req.palette.text);
            }
        }
    }

    fn draw_heatmap(&mut self, canvas: &mut Canvas, req: &RenderRequest, has_samples: bool, scale: f32) {
        let channels = req.channels.len();
        let (w, h) = (canvas.width, canvas.height);
        if !has_samples || channels == 0 {
            return;
        }

        // Peak |amplitude| per (row, column), normalized by the gain-scaled nominal range
        self.heat.resize(channels * w, 0.0);
        let norm = req.amplitude_scale / (scale * 1.5);
        for r in 0..channels {
            let row = &mut self.heat[r * w..(r + 1) * w];
            if !self.valid[r] {
                row.fill(0.0);
                continue;
            }
            for (v, &[mn, mx]) in row.iter_mut().zip(&self.env[r * w..(r + 1) * w]) {
                // Squared for contrast: background noise stays dark, spikes stand out
                let a = if mn.is_finite() { (mn.abs().max(mx.abs()) * norm).min(1.0) } else { 0.0 };
                *v = a * a;
            }
        }

        // Each pixel row shows the max over the channels it covers
        for y in 0..h {
            let c0 = y * channels / h;
            let c1 = ((y + 1) * channels / h).max(c0 + 1).min(channels);
            for x in 0..w {
                let mut v = 0.0f32;
                for ch in c0..c1 {
                    v = v.max(self.heat[ch * w + x]);
                }
                canvas.set(x, y, req.palette.heat(v));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::recording::Dataset;

    /// Request for `mode` over `ds`: traces show the first 4 channels, heatmap every channel.
    fn request(ds: Dataset, mode: TimeViewKind) -> RenderRequest {
        let events = Arc::new(SpikeEventStore::detect(ds.signal().as_ref()));
        let channels = match mode {
            TimeViewKind::Traces => (0..4.min(ds.total_channels)).collect(),
            TimeViewKind::Heatmap | TimeViewKind::Raster => (0..ds.total_channels).collect(),
        };
        RenderRequest {
            signal: ds.signal().clone(),
            events,
            width: 800,
            height: 400,
            scale: 1.0,
            mode,
            channels,
            window_start_sec: 0.0,
            window_sec: 0.100,
            start_time_sec: 0.0,
            amplitude_scale: 1.0,
            nominal: nominal_amplitude(&SignalUnit::Microvolt),
            auto_scale: false,
            remove_dc: false,
            scale_hint: 0.0,
            grid_times: vec![0.05],
            scale_bar: true,
            highlights: vec![(crate::ui::plot::canvas::Pixel::rgb(255, 0, 0), vec![(0.05, 0)])],
            overlay: None,
            raster: None,
            color_by: ColorBy::default(),
            palette: Palette::DARK,
        }
    }

    #[test]
    fn test_renderer_output_dimensions_and_trace_pixels() {
        let mut r = WaveformRenderer::default();
        for mode in [TimeViewKind::Traces, TimeViewKind::Heatmap] {
            let req = request(Dataset::generate_synthetic(8, 30_000.0, 0.5), mode);
            let buf = r.render(&req);
            assert_eq!((buf.width, buf.height), (800, 400));
            // Something other than background was drawn
            assert!(buf.pixels().iter().any(|p| *p != Palette::DARK.background));
        }
    }

    #[test]
    fn test_out_of_range_channels_are_skipped() {
        let mut req = request(Dataset::generate_synthetic(2, 10_000.0, 0.2), TimeViewKind::Traces);
        req.channels = vec![0, 99];
        let mut r = WaveformRenderer::default();
        assert_eq!(r.render(&req).width, 800);
        req.mode = TimeViewKind::Heatmap;
        assert_eq!(r.render(&req).width, 800);
    }

    /// One channel: a 1000 µV offset plus a ±100 µV square wave (100 Hz at 10 kHz).
    fn offset_square() -> Dataset {
        let data: Vec<f32> = (0..10_000).map(|s| 1000.0 + if (s / 50) % 2 == 0 { 100.0 } else { -100.0 }).collect();
        Dataset::from_samples("sq", data, 1, 10_000.0)
    }

    #[test]
    fn test_auto_scale_dc_and_hysteresis() {
        let mut r = WaveformRenderer::default();
        let base = RenderRequest { channels: vec![0], window_sec: 0.5, auto_scale: true, ..request(offset_square(), TimeViewKind::Traces) };
        // Without DC removal the offset dominates the scale
        let (_, with_dc) = r.render_scaled(&base);
        assert!((with_dc - 1100.0).abs() < 1.0, "{with_dc}");
        // Offset removed: only the ±100 swing remains
        let (_, no_dc) = r.render_scaled(&RenderRequest { remove_dc: true, ..base.clone() });
        assert!((no_dc - 100.0).abs() < 1.0, "{no_dc}");
        // A previous scale within 50–125 % of the data is kept (no jumping while scrolling)
        let (_, kept) = r.render_scaled(&RenderRequest { remove_dc: true, scale_hint: 110.0, ..base.clone() });
        assert_eq!(kept, 110.0);
        let (_, replaced) = r.render_scaled(&RenderRequest { remove_dc: true, scale_hint: 1000.0, ..base.clone() });
        assert!((replaced - 100.0).abs() < 1.0);
        // Not auto-scaled: the nominal range
        let (_, fixed) = r.render_scaled(&RenderRequest { auto_scale: false, ..base });
        assert_eq!(fixed, nominal_amplitude(&SignalUnit::Microvolt));
    }

    #[test]
    fn test_source_starting_inside_the_window_draws_only_its_part() {
        let mut ds = Dataset::generate_synthetic(1, 1000.0, 1.0);
        ds.start_time_sec = 1.0;
        let req = RenderRequest {
            channels: vec![0],
            window_start_sec: 0.0,
            window_sec: 2.0,
            start_time_sec: 1.0,
            grid_times: Vec::new(),
            events: Arc::new(SpikeEventStore::default()),
            highlights: Vec::new(),
            overlay: None,
            raster: None,
            color_by: ColorBy::default(),
            ..request(ds, TimeViewKind::Traces)
        };
        let buf = WaveformRenderer::default().render(&req);
        let (w, h) = (buf.width as usize, buf.height as usize);
        let px = buf.pixels();
        let drawn = |x0: usize, x1: usize| (0..h).any(|y| (x0..x1).any(|x| px[y * w + x] != Palette::DARK.background && px[y * w + x] != Palette::DARK.baseline));
        assert!(!drawn(0, w / 2 - 2), "no data before the source starts");
        assert!(drawn(w / 2 + 2, w - 20), "data after it starts");
    }

    /// In-memory source that reports a storage chunk size and records every read range.
    struct Chunked {
        inner: dspk_core::MemoryRecording,
        chunk: u64,
        reads: Arc<std::sync::Mutex<Vec<std::ops::Range<u64>>>>,
    }

    impl dspk_core::RecordingSource for Chunked {
        fn info(&self) -> &dspk_core::RecordingInfo {
            self.inner.info()
        }
        fn chunk_samples(&self) -> Option<u64> {
            Some(self.chunk)
        }
        fn read(&self, channels: &[usize], samples: std::ops::Range<u64>, out: &mut [f32]) -> dspk_core::DspResult<()> {
            self.reads.lock().unwrap().push(samples.clone());
            self.inner.read(channels, samples, out)
        }
    }

    #[test]
    fn test_raw_windows_are_exact_and_read_each_chunk_once() {
        // Zoomed in below the pyramid's base: the envelope comes from the samples
        let (nch, total, width) = (3usize, 10_000usize, 37usize);
        let data: Vec<f32> = (0..nch * total).map(|i| ((i * 7919) % 1013) as f32 - 500.0).collect();
        let reads = Arc::new(std::sync::Mutex::new(Vec::new()));
        let inner = dspk_core::MemoryRecording::new("chunked", data.clone(), nch, 1000.0).unwrap();
        let src = Chunked { inner, chunk: 300, reads: reads.clone() };
        let ds = Dataset::local(Arc::new(src), None).unwrap();
        let (start, end) = (1_234usize, 9_876usize);
        assert!(((end - start) / width) < dspk_view::MEMORY_BASE as usize, "a raw window");

        let mut r = WaveformRenderer::default();
        let rows = [2usize, 0];
        r.envelope(ds.signal().as_ref(), &rows, start, end, width);

        let n = end - start;
        for (k, &ch) in rows.iter().enumerate() {
            for x in 0..width {
                let (c0, c1) = (start + x * n / width, start + (x + 1) * n / width);
                let col = &data[ch * total + c0..ch * total + c1];
                let exact = col.iter().fold([f32::INFINITY, f32::NEG_INFINITY], |[a, b], &v| [a.min(v), b.max(v)]);
                assert_eq!(r.env[k * width + x], exact, "row {k} column {x}");
            }
        }
        let reads = reads.lock().unwrap();
        assert_eq!(reads.first().unwrap().start, start as u64);
        assert_eq!(reads.last().unwrap().end, end as u64);
        for w in reads.windows(2) {
            assert_eq!(w[0].end, w[1].start, "contiguous, no sample read twice");
            assert_eq!(w[0].end % 300, 0, "blocks end on chunk boundaries");
        }
    }

    /// Per-frame render cost on the local datasets. Run with:
    /// `cargo test -p dspk-app --release bench_render -- --ignored --nocapture`
    #[test]
    #[ignore]
    fn bench_render() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../playground/datasets");
        let cases = [
            ("mearec_32ch_10s.bin", TimeViewKind::Traces, 0.1),
            ("mearec_32ch_10s.bin", TimeViewKind::Traces, 1.0),
            ("mearec_32ch_10s.bin", TimeViewKind::Heatmap, 1.0),
            ("mock_signal_384ch.bin", TimeViewKind::Traces, 1.0),
            ("mock_signal_384ch.bin", TimeViewKind::Heatmap, 1.0),
        ];
        for (file, mode, window_sec) in cases {
            let Ok(sources) = crate::data::recording::SourceSet::open(&root.join(file)) else {
                println!("skip {file} (not found)");
                continue;
            };
            let ds = Dataset::new(sources.default_dataset().signal().clone(), None);
            let mut r = WaveformRenderer::default();
            let mut req = RenderRequest { width: 1136, height: 550, window_sec, ..request(ds, mode) };
            if mode == TimeViewKind::Traces {
                req.channels = (0..8).collect();
            }
            r.render(&req); // warm-up
            let n = 20;
            let t0 = std::time::Instant::now();
            for _ in 0..n {
                std::hint::black_box(r.render(&req));
            }
            let ms = t0.elapsed().as_secs_f64() * 1000.0 / n as f64;
            println!("{file:24} {mode:?} {window_sec:>4}s  {ms:6.2} ms/frame");
        }
    }
}