talk-rs 0.7.1

Voice dictation for Linux -- record, transcribe, and paste
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//! Shared rendering and DSP utilities for X11 audio overlays.
//!
//! Contains the pixel buffer, ring buffer, FFT, and shape-mask
//! helpers used by both the recording overlay and the visualizer
//! panels.

use crate::error::TalkError;

// ── Constants ────────────────────────────────────────────────────────

/// Per-frame decay multiplier for tracked peaks.
///
/// Peaks jump up instantly (fast attack) but shrink by this factor each
/// frame (slow release).  At 60 fps, 0.998^60 ≈ 0.887, so a transient
/// spike halves in ~6 seconds while sustained speech keeps the peak
/// appropriately high.
pub const PEAK_DECAY: f32 = 0.998;

/// Minimum peak floor to avoid division by near-zero.
pub const PEAK_FLOOR: f32 = 0.0001;

/// Number of audio samples fed into the FFT (must be power of two).
pub const FFT_SIZE: usize = 2048;

/// Lowest frequency shown in the spectrogram (Hz).
pub const FREQ_MIN: f32 = 80.0;

/// Hard upper limit for dynamic frequency scaling (Hz).
pub const FREQ_MAX: f32 = 8000.0;

/// Minimum FFT magnitude to count a bin as "active" for frequency scaling.
pub const FREQ_NOISE_FLOOR: f32 = 0.01;

/// Number of spectrogram columns for the picker waterfall strip.
pub const WATERFALL_COLUMNS: usize = 4096;
/// Number of frequency rows for the picker waterfall strip.
pub const WATERFALL_ROWS: usize = 64;

// ── Ring buffer ──────────────────────────────────────────────────────

// `RingBuffer` was moved to the core `audio` module so the capture
// tee can use it without the `ui` feature.  Re-exported here to keep
// the historical `crate::x11::render_util::RingBuffer` path valid for
// the X11 overlay / visualizer code.
pub use crate::audio::ring_buffer::RingBuffer;

// ── Complex type + radix-2 FFT ──────────────────────────────────────

#[derive(Clone, Copy)]
pub struct Complex {
    pub re: f32,
    pub im: f32,
}

impl Complex {
    pub fn new(re: f32, im: f32) -> Self {
        Self { re, im }
    }

    pub fn magnitude(self) -> f32 {
        (self.re * self.re + self.im * self.im).sqrt()
    }
}

impl std::ops::Add for Complex {
    type Output = Self;
    fn add(self, rhs: Self) -> Self {
        Self::new(self.re + rhs.re, self.im + rhs.im)
    }
}

impl std::ops::Sub for Complex {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self {
        Self::new(self.re - rhs.re, self.im - rhs.im)
    }
}

impl std::ops::Mul for Complex {
    type Output = Self;
    fn mul(self, rhs: Self) -> Self {
        Self::new(
            self.re * rhs.re - self.im * rhs.im,
            self.re * rhs.im + self.im * rhs.re,
        )
    }
}

/// In-place iterative radix-2 Cooley-Tukey FFT.
pub fn fft_in_place(buf: &mut [Complex]) {
    let n = buf.len();
    debug_assert!(n.is_power_of_two());

    // Bit-reversal permutation
    let mut j = 0usize;
    for i in 1..n {
        let mut bit = n >> 1;
        while j & bit != 0 {
            j ^= bit;
            bit >>= 1;
        }
        j ^= bit;
        if i < j {
            buf.swap(i, j);
        }
    }

    // Butterfly stages
    let mut len = 2;
    while len <= n {
        let half = len / 2;
        let angle = -2.0 * std::f32::consts::PI / len as f32;
        let wn = Complex::new(angle.cos(), angle.sin());

        let mut start = 0;
        while start < n {
            let mut w = Complex::new(1.0, 0.0);
            for k in 0..half {
                let u = buf[start + k];
                let v = buf[start + k + half] * w;
                buf[start + k] = u + v;
                buf[start + k + half] = u - v;
                w = w * wn;
            }
            start += len;
        }
        len <<= 1;
    }
}

/// Apply Hann window and compute FFT magnitude spectrum (positive
/// frequencies only).
pub fn compute_spectrum(samples: &[f32]) -> Vec<f32> {
    let n = samples.len();
    let mut buf: Vec<Complex> = samples
        .iter()
        .enumerate()
        .map(|(i, &s)| {
            let w = 0.5 * (1.0 - (2.0 * std::f32::consts::PI * i as f32 / n as f32).cos());
            Complex::new(s * w, 0.0)
        })
        .collect();

    fft_in_place(&mut buf);

    buf[..n / 2].iter().map(|c| c.magnitude()).collect()
}

// ── Pixel buffer ─────────────────────────────────────────────────────

pub struct PixelBuffer {
    pub data: Vec<u8>,
    pub width: usize,
    pub height: usize,
}

impl PixelBuffer {
    pub fn new(width: usize, height: usize) -> Self {
        Self {
            data: vec![0u8; width * height * 4],
            width,
            height,
        }
    }

    pub fn clear(&mut self, color: [u8; 4]) {
        for pixel in self.data.chunks_exact_mut(4) {
            pixel.copy_from_slice(&color);
        }
    }

    pub fn set_pixel(&mut self, x: usize, y: usize, color: [u8; 4]) {
        if x < self.width && y < self.height {
            let off = (y * self.width + x) * 4;
            self.data[off..off + 4].copy_from_slice(&color);
        }
    }

    /// Alpha-blend `color` over the existing pixel at (x, y) using
    /// the given `opacity` (0.0–1.0).  Sibling to [`Self::set_pixel`]
    /// for the case where a phase or overlay element wants to be
    /// dimmer than full opacity without compositing through a
    /// glyph alpha mask.
    ///
    /// At `opacity == 1.0` this is identical to `set_pixel`; at
    /// `opacity == 0.0` the pixel is left unchanged.  The alpha
    /// channel of `color` is ignored — the BGRA channels are
    /// blended into the existing background using the supplied
    /// scalar opacity.
    pub fn blend_pixel(&mut self, x: usize, y: usize, color: [u8; 4], opacity: f32) {
        if x >= self.width || y >= self.height {
            return;
        }
        let a = opacity.clamp(0.0, 1.0);
        if a <= f32::EPSILON {
            return;
        }
        let off = (y * self.width + x) * 4;
        for (c, &fg_val) in color.iter().enumerate().take(3) {
            let bg_val = self.data[off + c] as f32;
            self.data[off + c] = (bg_val + (fg_val as f32 - bg_val) * a) as u8;
        }
        // Leave the alpha channel as the background's; the X11
        // overlay window has its own opacity treatment and we
        // never want a transparent hole in the badge.
    }

    /// Fill the buffer with `fg` inside a rounded rectangle that spans
    /// the full buffer.  Pixels outside the rounded corners are left
    /// transparent (all zeroes) so the window shape mask clips them.
    pub fn clear_rounded(&mut self, fg: [u8; 4], radius: usize) {
        let w = self.width;
        let h = self.height;
        let r = radius.min(w / 2).min(h / 2);
        let r2 = (r * r) as i64;

        // Start fully transparent.
        for b in self.data.iter_mut() {
            *b = 0;
        }

        for y in 0..h {
            for x in 0..w {
                let inside = if x < r && y < r {
                    // top-left corner
                    let dx = r as i64 - x as i64;
                    let dy = r as i64 - y as i64;
                    dx * dx + dy * dy <= r2
                } else if x >= w - r && y < r {
                    // top-right corner
                    let dx = x as i64 - (w - r - 1) as i64;
                    let dy = r as i64 - y as i64;
                    dx * dx + dy * dy <= r2
                } else if x < r && y >= h - r {
                    // bottom-left corner
                    let dx = r as i64 - x as i64;
                    let dy = y as i64 - (h - r - 1) as i64;
                    dx * dx + dy * dy <= r2
                } else if x >= w - r && y >= h - r {
                    // bottom-right corner
                    let dx = x as i64 - (w - r - 1) as i64;
                    let dy = y as i64 - (h - r - 1) as i64;
                    dx * dx + dy * dy <= r2
                } else {
                    true
                };

                if inside {
                    let off = (y * w + x) * 4;
                    self.data[off..off + 4].copy_from_slice(&fg);
                }
            }
        }
    }

    pub fn fill_rect(&mut self, x: usize, y: usize, w: usize, h: usize, color: [u8; 4]) {
        for dy in 0..h {
            for dx in 0..w {
                self.set_pixel(x + dx, y + dy, color);
            }
        }
    }
}

// ── DSP helpers ──────────────────────────────────────────────────────

/// Compute the root-mean-square of a slice of samples.
pub fn rms(samples: &[f32]) -> f32 {
    if samples.is_empty() {
        return 0.0;
    }
    let sum_sq: f32 = samples.iter().map(|s| s * s).sum();
    (sum_sq / samples.len() as f32).sqrt()
}

/// Map a 0–1 normalized value to a heat-map BGRA colour (premultiplied
/// alpha).
///
/// The gradient goes: transparent → blue → cyan → green → yellow → red.
/// Alpha tracks `brightness` so quiet areas fade to transparent
/// (suitable for waterfall overlays on a dark badge).
pub fn heat_map_color(norm: f32, brightness: f32) -> [u8; 4] {
    let norm = norm.clamp(0.0, 1.0);
    let alpha = (brightness * 255.0).clamp(0.0, 255.0) as u8;
    if alpha == 0 {
        return [0, 0, 0, 0];
    }

    // Piecewise-linear RGB gradient (0.0–1.0 range).
    let (r, g, b) = if norm < 0.2 {
        let t = norm / 0.2;
        (0.0, 0.0, t)
    } else if norm < 0.4 {
        let t = (norm - 0.2) / 0.2;
        (0.0, t, 1.0)
    } else if norm < 0.6 {
        let t = (norm - 0.4) / 0.2;
        (0.0, 1.0, 1.0 - t)
    } else if norm < 0.8 {
        let t = (norm - 0.6) / 0.2;
        (t, 1.0, 0.0)
    } else {
        let t = (norm - 0.8) / 0.2;
        (1.0, 1.0 - t, 0.0)
    };

    // Premultiply by alpha (= brightness).
    let af = brightness;
    [
        (b * af * 255.0) as u8,
        (g * af * 255.0) as u8,
        (r * af * 255.0) as u8,
        alpha,
    ]
}

/// Map a 0–1 normalized level to an opaque BGRA bar colour.
///
/// The gradient goes: green (low) → yellow (mid) → red (high).
/// Returns fully opaque pixels suitable for amplitude / spectrum bars.
pub fn level_color(norm: f32) -> [u8; 4] {
    let norm = norm.clamp(0.0, 1.0);
    let (r, g) = if norm < 0.5 {
        let t = norm / 0.5;
        (t, 1.0)
    } else {
        let t = (norm - 0.5) / 0.5;
        (1.0, 1.0 - t)
    };
    // BGRA, fully opaque, blue channel is always 0.
    [0, (g * 255.0) as u8, (r * 255.0) as u8, 0xFF]
}

/// Linearly interpolate between two BGRA colours by factor `t` (0–1).
pub fn lerp_color(a: [u8; 4], b: [u8; 4], t: f32) -> [u8; 4] {
    let t = t.clamp(0.0, 1.0);
    [
        (a[0] as f32 + (b[0] as f32 - a[0] as f32) * t) as u8,
        (a[1] as f32 + (b[1] as f32 - a[1] as f32) * t) as u8,
        (a[2] as f32 + (b[2] as f32 - a[2] as f32) * t) as u8,
        0xFF,
    ]
}

// ── Theme detection ──────────────────────────────────────────────────

/// Detect whether the desktop theme is dark.
///
/// Uses the `dark-light` crate (freedesktop portal via D-Bus) with a
/// fallback to the `GTK_THEME` environment variable.  Returns `true`
/// for dark themes (use white foreground), `false` for light themes
/// (use black foreground).  Defaults to dark when detection fails.
pub fn detect_is_dark_theme() -> bool {
    match dark_light::detect() {
        Ok(dark_light::Mode::Light) => {
            log::debug!("theme detection: light (via dark-light)");
            false
        }
        Ok(dark_light::Mode::Dark) => {
            log::debug!("theme detection: dark (via dark-light)");
            true
        }
        _ => {
            // Fallback: check GTK_THEME for "dark" substring.
            if let Ok(theme) = std::env::var("GTK_THEME") {
                let lower = theme.to_ascii_lowercase();
                if lower.contains("dark") {
                    log::debug!("theme detection: dark (GTK_THEME={:?})", theme);
                    return true;
                }
                if lower.contains("light") {
                    log::debug!("theme detection: light (GTK_THEME={:?})", theme);
                    return false;
                }
            }
            log::debug!("theme detection: defaulting to dark");
            true
        }
    }
}

/// Return the BGRA foreground and background colours for monochrome
/// visualiser mode based on theme detection.
///
/// - Dark theme → white foreground on black background.
/// - Light theme → black foreground on white background.
pub fn monochrome_palette() -> ([u8; 4], [u8; 4]) {
    if detect_is_dark_theme() {
        // fg = white, bg = black
        ([0xFF, 0xFF, 0xFF, 0xFF], [0x00, 0x00, 0x00, 0xFF])
    } else {
        // fg = black, bg = white
        ([0x00, 0x00, 0x00, 0xFF], [0xFF, 0xFF, 0xFF, 0xFF])
    }
}

// ── X11 shape helpers ────────────────────────────────────────────────

/// Create a 1-bit pixmap with a rounded rectangle and apply it as the
/// window's bounding shape so corners are truly transparent.
pub fn apply_rounded_shape(
    conn: &impl x11rb::connection::Connection,
    win: u32,
    w: u16,
    h: u16,
    radius: usize,
) -> Result<(), TalkError> {
    use x11rb::protocol::shape;
    use x11rb::protocol::xproto::*;

    let pixmap: Pixmap = conn
        .generate_id()
        .map_err(|e| TalkError::Config(format!("X11 id: {}", e)))?;
    conn.create_pixmap(1, pixmap, win, w, h)
        .map_err(|e| TalkError::Config(format!("X11 create pixmap: {}", e)))?;

    let gc: Gcontext = conn
        .generate_id()
        .map_err(|e| TalkError::Config(format!("X11 id: {}", e)))?;
    conn.create_gc(gc, pixmap, &CreateGCAux::new().foreground(0))
        .map_err(|e| TalkError::Config(format!("X11 gc: {}", e)))?;

    // Clear to 0 (fully transparent).
    conn.poly_fill_rectangle(
        pixmap,
        gc,
        &[Rectangle {
            x: 0,
            y: 0,
            width: w,
            height: h,
        }],
    )
    .map_err(|e| TalkError::Config(format!("X11 fill: {}", e)))?;

    // Draw the rounded rectangle in foreground = 1 (opaque).
    conn.change_gc(gc, &ChangeGCAux::new().foreground(1))
        .map_err(|e| TalkError::Config(format!("X11 change gc: {}", e)))?;

    let r = (radius as u16).min(w / 2).min(h / 2);
    let d = r * 2;

    // Centre rectangle (full width minus corners).
    conn.poly_fill_rectangle(
        pixmap,
        gc,
        &[
            // Horizontal band spanning full width, excluding top/bottom
            // corner rows.
            Rectangle {
                x: 0,
                y: r as i16,
                width: w,
                height: h - d,
            },
            // Top band between corners.
            Rectangle {
                x: r as i16,
                y: 0,
                width: w - d,
                height: r,
            },
            // Bottom band between corners.
            Rectangle {
                x: r as i16,
                y: (h - r) as i16,
                width: w - d,
                height: r,
            },
        ],
    )
    .map_err(|e| TalkError::Config(format!("X11 fill: {}", e)))?;

    // Four corner arcs (angles in 64ths of a degree).
    conn.poly_fill_arc(
        pixmap,
        gc,
        &[
            // top-left
            x11rb::protocol::xproto::Arc {
                x: 0,
                y: 0,
                width: d,
                height: d,
                angle1: 90 * 64,
                angle2: 90 * 64,
            },
            // top-right
            x11rb::protocol::xproto::Arc {
                x: (w - d) as i16,
                y: 0,
                width: d,
                height: d,
                angle1: 0,
                angle2: 90 * 64,
            },
            // bottom-left
            x11rb::protocol::xproto::Arc {
                x: 0,
                y: (h - d) as i16,
                width: d,
                height: d,
                angle1: 180 * 64,
                angle2: 90 * 64,
            },
            // bottom-right
            x11rb::protocol::xproto::Arc {
                x: (w - d) as i16,
                y: (h - d) as i16,
                width: d,
                height: d,
                angle1: 270 * 64,
                angle2: 90 * 64,
            },
        ],
    )
    .map_err(|e| TalkError::Config(format!("X11 fill arc: {}", e)))?;

    // Apply as bounding shape.
    shape::mask(conn, shape::SO::SET, shape::SK::BOUNDING, win, 0, 0, pixmap)
        .map_err(|e| TalkError::Config(format!("X11 shape mask: {}", e)))?;

    conn.free_gc(gc)
        .map_err(|e| TalkError::Config(format!("X11 free gc: {}", e)))?;
    conn.free_pixmap(pixmap)
        .map_err(|e| TalkError::Config(format!("X11 free pixmap: {}", e)))?;

    Ok(())
}

// ── Font / glyph utilities ───────────────────────────────────────────

/// Well-known system font paths, tried in order.  CJK-capable fonts
/// come first so Chinese / Japanese / Korean text renders correctly.
pub const FONT_SEARCH_PATHS: &[&str] = &[
    // CJK-capable (Noto Sans CJK covers Latin + CJK + most scripts)
    "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc",
    // Droid fallback (broad Unicode coverage including CJK)
    "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
    // Latin-only fallbacks
    "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
    "/usr/share/fonts/TTF/DejaVuSans.ttf",
    "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
];

/// Load a system TrueType font for text rendering.
///
/// Searches well-known paths; returns `None` if no font is found.
/// `scale` sets the default rasterisation size (e.g. 30.0 for the
/// text panel, 24.0 for the badge).
pub fn load_system_font(scale: f32) -> Option<fontdue::Font> {
    for path in FONT_SEARCH_PATHS {
        if let Ok(data) = std::fs::read(path) {
            let settings = fontdue::FontSettings {
                collection_index: 0,
                scale,
                load_substitutions: true,
            };
            match fontdue::Font::from_bytes(data, settings) {
                Ok(font) => {
                    log::debug!("loaded font from {}", path);
                    return Some(font);
                }
                Err(e) => {
                    log::warn!("failed to parse font {}: {}", path, e);
                }
            }
        }
    }
    log::warn!("no system font found");
    None
}

/// Rasterise glyphs and return `(glyph_data, total_advance_width)`.
pub fn rasterise_glyphs(
    text: &str,
    font: &fontdue::Font,
    font_size: f32,
) -> (Vec<(fontdue::Metrics, Vec<u8>)>, usize) {
    let mut glyphs: Vec<(fontdue::Metrics, Vec<u8>)> = Vec::new();
    let mut total_w: usize = 0;
    for ch in text.chars() {
        let (metrics, bitmap) = font.rasterize(ch, font_size);
        total_w += metrics.advance_width as usize;
        glyphs.push((metrics, bitmap));
    }
    (glyphs, total_w)
}

/// Blit pre-rasterised glyphs into the pixel buffer at `start_x`,
/// vertically centred, clipped to buffer bounds.  `opacity` (0.0–1.0)
/// scales the per-glyph coverage alpha for smooth fade-out.
pub fn blit_glyphs(
    pb: &mut PixelBuffer,
    glyphs: &[(fontdue::Metrics, Vec<u8>)],
    start_x: i32,
    color: [u8; 4],
    opacity: f32,
) {
    let h = pb.height;
    let w = pb.width;
    let baseline = (h as i32 * 3) / 4;
    let mut cursor_x = start_x;

    for (metrics, bitmap) in glyphs {
        blit_glyph_at(
            pb, metrics, bitmap, cursor_x, baseline, w, h, color, opacity,
        );
        cursor_x += metrics.advance_width as i32;
    }
}

/// Blit a single rasterised glyph at `cursor_x` with the given colour.
/// `opacity` (0.0–1.0) is multiplied into the glyph coverage alpha.
#[allow(clippy::too_many_arguments)]
pub fn blit_glyph_at(
    pb: &mut PixelBuffer,
    metrics: &fontdue::Metrics,
    bitmap: &[u8],
    cursor_x: i32,
    baseline: i32,
    buf_w: usize,
    buf_h: usize,
    color: [u8; 4],
    opacity: f32,
) {
    let gx = cursor_x + metrics.xmin;
    let gy = baseline - metrics.height as i32 - metrics.ymin;

    for row in 0..metrics.height {
        for col in 0..metrics.width {
            let alpha = bitmap[row * metrics.width + col];
            if alpha == 0 {
                continue;
            }
            let px = gx + col as i32;
            let py = gy + row as i32;
            if px >= 0 && (px as usize) < buf_w && py >= 0 && (py as usize) < buf_h {
                let off = (py as usize * buf_w + px as usize) * 4;
                let a = alpha as f32 / 255.0 * opacity;
                for (c, &fg_val) in color.iter().enumerate().take(3) {
                    let bg_val = pb.data[off + c] as f32;
                    pb.data[off + c] = (bg_val + (fg_val as f32 - bg_val) * a) as u8;
                }
            }
        }
    }
}

// ── Spectrogram helpers ──────────────────────────────────────────────

/// Map FFT magnitude bins to a fixed-height spectrogram column using
/// logarithmic frequency spacing.
///
/// Returns a `Vec<f32>` of length `num_rows`, where index 0 is the
/// lowest frequency (bottom of spectrogram) and the last index is
/// the highest (top).
pub fn map_spectrum_to_column(
    magnitudes: &[f32],
    num_rows: usize,
    sample_rate: u32,
    freq_max: f32,
) -> Vec<f32> {
    let n_bins = magnitudes.len();
    if n_bins == 0 || num_rows == 0 {
        return vec![0.0; num_rows];
    }

    let nyquist = sample_rate as f32 / 2.0;
    let f_max = freq_max.min(nyquist);
    let log_min = FREQ_MIN.ln();
    let log_max = f_max.ln();

    // Pre-compute the fractional bin index for each row centre.
    let bin_centers: Vec<f32> = (0..num_rows)
        .map(|row| {
            let t = if num_rows > 1 {
                row as f32 / (num_rows - 1) as f32
            } else {
                0.5
            };
            let freq = (log_min + t * (log_max - log_min)).exp();
            (freq / nyquist * n_bins as f32).clamp(0.0, (n_bins - 1) as f32)
        })
        .collect();

    let mut column = Vec::with_capacity(num_rows);

    for row in 0..num_rows {
        // Each row covers the band from the midpoint to its previous
        // neighbour up to the midpoint to its next neighbour.
        let lo = if row == 0 {
            bin_centers[0]
        } else {
            (bin_centers[row - 1] + bin_centers[row]) * 0.5
        };
        let hi = if row + 1 >= num_rows {
            bin_centers[num_rows - 1]
        } else {
            (bin_centers[row] + bin_centers[row + 1]) * 0.5
        };

        let bin_start = (lo.floor() as usize).min(n_bins - 1);
        let bin_end = ((hi.ceil() as usize) + 1).min(n_bins);
        // Guarantee at least one bin.
        let bin_end = bin_end.max(bin_start + 1);

        // Use peak (max) within the bin range — matches how real-time
        // spectrum analysers work and avoids visual holes between harmonics.
        let peak_val: f32 = magnitudes[bin_start..bin_end]
            .iter()
            .copied()
            .fold(0.0f32, f32::max);

        column.push(peak_val);
    }

    column
}

/// Generate waterfall spectrogram columns from PCM i16 audio.
///
/// Computes `WATERFALL_COLUMNS` evenly-spaced FFT windows across the
/// entire audio, maps each to `WATERFALL_ROWS` frequency bins, and
/// returns the column data plus the global peak magnitude.
///
/// The caller can render these columns at any display width by
/// mapping column indices to pixel columns.
pub fn generate_waterfall_columns(samples: &[i16], sample_rate: u32) -> (Vec<Vec<f32>>, f32) {
    // Convert i16 samples to f32, padding to at least FFT_SIZE.
    let padded: Vec<f32> = if samples.len() < FFT_SIZE {
        let mut buf = Vec::with_capacity(FFT_SIZE);
        for &s in samples {
            buf.push(s as f32 / 32768.0);
        }
        buf.resize(FFT_SIZE, 0.0);
        buf
    } else {
        samples.iter().map(|&s| s as f32 / 32768.0).collect()
    };

    let num_columns = if padded.len() <= FFT_SIZE {
        1
    } else {
        WATERFALL_COLUMNS
    };

    let hop = padded.len().saturating_sub(FFT_SIZE) / (num_columns.max(2) - 1).max(1);

    let mut columns = Vec::with_capacity(num_columns);
    let mut global_peak: f32 = 0.0;

    for col in 0..num_columns {
        let start = (col * hop).min(padded.len().saturating_sub(FFT_SIZE));
        let window = &padded[start..start + FFT_SIZE];

        let magnitudes = compute_spectrum(window);

        let frame_peak = magnitudes.iter().copied().fold(0.0f32, f32::max);
        if frame_peak > global_peak {
            global_peak = frame_peak;
        }

        let column = map_spectrum_to_column(&magnitudes, WATERFALL_ROWS, sample_rate, FREQ_MAX);
        columns.push(column);
    }

    // If the audio was shorter than FFT_SIZE, replicate the single
    // column to fill WATERFALL_COLUMNS.
    if columns.len() == 1 && WATERFALL_COLUMNS > 1 {
        let single = columns[0].clone();
        columns.resize(WATERFALL_COLUMNS, single);
    }

    (columns, global_peak)
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── FFT ──────────────────────────────────────────────────────────

    #[test]
    fn fft_dc_signal() {
        // A constant signal should have all energy in bin 0.
        let mut buf: Vec<Complex> = (0..16).map(|_| Complex::new(1.0, 0.0)).collect();
        fft_in_place(&mut buf);

        let dc = buf[0].magnitude();
        let rest_max = buf[1..]
            .iter()
            .map(|c| c.magnitude())
            .fold(0.0f32, f32::max);

        assert!(
            dc > rest_max * 100.0,
            "DC bin should dominate: dc={}, rest_max={}",
            dc,
            rest_max
        );
    }

    #[test]
    fn fft_sine_peak() {
        // 4 Hz sine in a 16-sample buffer at 16 Hz sample rate →
        // energy should be concentrated in bin 4.
        let n = 16usize;
        let freq = 4.0;
        let mut buf: Vec<Complex> = (0..n)
            .map(|i| {
                let t = i as f32 / n as f32;
                Complex::new((2.0 * std::f32::consts::PI * freq * t).sin(), 0.0)
            })
            .collect();
        fft_in_place(&mut buf);

        let peak_bin = buf[..n / 2]
            .iter()
            .enumerate()
            .max_by(|a, b| a.1.magnitude().partial_cmp(&b.1.magnitude()).unwrap())
            .map(|(i, _)| i)
            .unwrap();

        assert_eq!(peak_bin, 4);
    }

    #[test]
    fn compute_spectrum_returns_half_length() {
        let samples = vec![0.0f32; 256];
        let mags = compute_spectrum(&samples);
        assert_eq!(mags.len(), 128);
    }

    // ── Pixel buffer ─────────────────────────────────────────────────

    #[test]
    fn pixel_buffer_clear() {
        let mut pb = PixelBuffer::new(4, 4);
        pb.clear([0xFF, 0x00, 0x00, 0xFF]);
        // Every pixel should be the clear color
        for chunk in pb.data.chunks_exact(4) {
            assert_eq!(chunk, &[0xFF, 0x00, 0x00, 0xFF]);
        }
    }

    #[test]
    fn pixel_buffer_set_pixel_bounds() {
        let mut pb = PixelBuffer::new(4, 4);
        pb.clear([0; 4]);
        pb.set_pixel(3, 3, [1, 2, 3, 4]);
        let off = (3 * 4 + 3) * 4;
        assert_eq!(&pb.data[off..off + 4], &[1, 2, 3, 4]);

        // Out of bounds — should not panic
        pb.set_pixel(10, 10, [0xFF; 4]);
    }

    // ── RMS helper ────────────────────────────────────────────────────

    #[test]
    fn rms_of_silence_is_zero() {
        assert!((rms(&[0.0; 100])).abs() < f32::EPSILON);
    }

    #[test]
    fn rms_of_constant_is_value() {
        let val = 0.5f32;
        let samples = vec![val; 200];
        assert!((rms(&samples) - val).abs() < 1e-6);
    }

    #[test]
    fn rms_empty_is_zero() {
        assert!((rms(&[])).abs() < f32::EPSILON);
    }

    // ── PixelBuffer::blend_pixel ──────────────────────────────────

    /// Spec: at opacity 1.0, `blend_pixel` matches `set_pixel` for
    /// the BGR channels (alpha is intentionally not overwritten).
    #[test]
    fn blend_pixel_at_full_opacity_overwrites_bgr() {
        let mut pb = PixelBuffer::new(2, 2);
        pb.set_pixel(0, 0, [10, 20, 30, 40]); // background
        pb.blend_pixel(0, 0, [200, 100, 50, 0], 1.0);
        let off = 0;
        assert_eq!(pb.data[off], 200);
        assert_eq!(pb.data[off + 1], 100);
        assert_eq!(pb.data[off + 2], 50);
        // Alpha channel intentionally preserved.
        assert_eq!(pb.data[off + 3], 40);
    }

    /// Spec: at opacity 0.0, the pixel is unchanged.
    #[test]
    fn blend_pixel_at_zero_opacity_is_noop() {
        let mut pb = PixelBuffer::new(2, 2);
        pb.set_pixel(0, 0, [10, 20, 30, 40]);
        pb.blend_pixel(0, 0, [200, 100, 50, 0], 0.0);
        assert_eq!(&pb.data[0..4], &[10, 20, 30, 40]);
    }

    /// Spec: at opacity 0.5 the resulting BGR channels are halfway
    /// between background and foreground.
    #[test]
    fn blend_pixel_at_half_opacity_averages_bgr() {
        let mut pb = PixelBuffer::new(2, 2);
        pb.set_pixel(0, 0, [0, 0, 0, 0]); // black background
        pb.blend_pixel(0, 0, [100, 200, 50, 0], 0.5);
        // 0 + (100-0)*0.5 = 50, etc.
        assert_eq!(pb.data[0], 50);
        assert_eq!(pb.data[1], 100);
        assert_eq!(pb.data[2], 25);
    }

    /// Spec: out-of-bounds coordinates do not panic.
    #[test]
    fn blend_pixel_out_of_bounds_is_noop() {
        let mut pb = PixelBuffer::new(2, 2);
        pb.blend_pixel(5, 5, [255, 255, 255, 255], 1.0);
        // No panic, no change to in-bounds pixels.
        for b in &pb.data {
            assert_eq!(*b, 0);
        }
    }

    /// Spec: opacity values outside [0.0, 1.0] are clamped (do not
    /// produce wraparound or panics).
    #[test]
    fn blend_pixel_clamps_opacity() {
        let mut pb = PixelBuffer::new(2, 2);
        pb.set_pixel(0, 0, [0, 0, 0, 0]);
        pb.blend_pixel(0, 0, [100, 200, 50, 0], 2.0); // > 1.0
                                                      // Clamped to 1.0 → identical to full overwrite.
        assert_eq!(pb.data[0], 100);
        assert_eq!(pb.data[1], 200);
        assert_eq!(pb.data[2], 50);
    }
}