Skip to main content

qualia_vision/
overlay.rs

1//! Detection overlay — draw boxes onto caller-owned pixel buffers (desktop/renderer path).
2//!
3//! Pure Rust, no GPU required. Coordinates use the same normalized u16 boxes as `Detection`.
4
5use crate::types::{Detection, VisionError};
6
7/// Convert a detection box to CSS percentages (left, top, width, height) in 0…100.
8#[inline]
9pub fn box_css_percent(det: &Detection) -> (f32, f32, f32, f32) {
10    let x0 = det.x_min_u16 as f32 / 65535.0 * 100.0;
11    let y0 = det.y_min_u16 as f32 / 65535.0 * 100.0;
12    let x1 = det.x_max_u16 as f32 / 65535.0 * 100.0;
13    let y1 = det.y_max_u16 as f32 / 65535.0 * 100.0;
14    (x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
15}
16
17/// Pixel bounds (inclusive min, exclusive max) for a detection on an image of size w×h.
18#[inline]
19pub fn box_pixel_bounds(det: &Detection, w: u32, h: u32) -> (u32, u32, u32, u32) {
20    let x0 = ((det.x_min_u16 as u64 * w as u64) / 65535) as u32;
21    let y0 = ((det.y_min_u16 as u64 * h as u64) / 65535) as u32;
22    let x1 = ((det.x_max_u16 as u64 * w as u64) / 65535) as u32;
23    let y1 = ((det.y_max_u16 as u64 * h as u64) / 65535) as u32;
24    let x1 = x1.max(x0.saturating_add(1)).min(w);
25    let y1 = y1.max(y0.saturating_add(1)).min(h);
26    (x0.min(w), y0.min(h), x1, y1)
27}
28
29/// Draw axis-aligned box outlines onto an RGBA8 buffer (stride = w * 4).
30/// `thickness` in pixels (clamped 1…8). Returns number of boxes drawn.
31pub fn draw_boxes_rgba8(
32    width: u32,
33    height: u32,
34    rgba: &mut [u8],
35    detections: &[Detection],
36    n: usize,
37    color: [u8; 4],
38    thickness: u32,
39) -> Result<usize, VisionError> {
40    let need = (width as usize)
41        .saturating_mul(height as usize)
42        .saturating_mul(4);
43    if rgba.len() < need || width == 0 || height == 0 {
44        return Err(VisionError::OutputBufferTooSmall);
45    }
46    let t = thickness.clamp(1, 8);
47    let n = n.min(detections.len());
48    let mut drawn = 0usize;
49    for det in detections.iter().take(n) {
50        if det.class_hash == 0 && det.score_u16 == 0 {
51            continue;
52        }
53        let (x0, y0, x1, y1) = box_pixel_bounds(det, width, height);
54        stroke_rect_rgba8(width, height, rgba, x0, y0, x1, y1, color, t);
55        drawn += 1;
56    }
57    Ok(drawn)
58}
59
60/// Copy RGB8 source into RGBA8 (alpha=255), then draw boxes.
61pub fn compose_rgb_overlay_rgba8(
62    width: u32,
63    height: u32,
64    rgb: &[u8],
65    detections: &[Detection],
66    n: usize,
67    color: [u8; 4],
68    thickness: u32,
69    out_rgba: &mut [u8],
70) -> Result<usize, VisionError> {
71    let px = (width as usize).saturating_mul(height as usize);
72    if rgb.len() < px * 3 || out_rgba.len() < px * 4 {
73        return Err(VisionError::OutputBufferTooSmall);
74    }
75    for i in 0..px {
76        out_rgba[i * 4] = rgb[i * 3];
77        out_rgba[i * 4 + 1] = rgb[i * 3 + 1];
78        out_rgba[i * 4 + 2] = rgb[i * 3 + 2];
79        out_rgba[i * 4 + 3] = 255;
80    }
81    draw_boxes_rgba8(width, height, out_rgba, detections, n, color, thickness)
82}
83
84fn stroke_rect_rgba8(
85    w: u32,
86    h: u32,
87    rgba: &mut [u8],
88    x0: u32,
89    y0: u32,
90    x1: u32,
91    y1: u32,
92    color: [u8; 4],
93    t: u32,
94) {
95    // Horizontal edges
96    for dy in 0..t {
97        let yt = y0.saturating_add(dy).min(h.saturating_sub(1));
98        let yb = y1
99            .saturating_sub(1)
100            .saturating_sub(dy)
101            .min(h.saturating_sub(1));
102        for x in x0..x1 {
103            put_rgba(w, rgba, x, yt, color);
104            put_rgba(w, rgba, x, yb, color);
105        }
106    }
107    // Vertical edges
108    for dx in 0..t {
109        let xl = x0.saturating_add(dx).min(w.saturating_sub(1));
110        let xr = x1
111            .saturating_sub(1)
112            .saturating_sub(dx)
113            .min(w.saturating_sub(1));
114        for y in y0..y1 {
115            put_rgba(w, rgba, xl, y, color);
116            put_rgba(w, rgba, xr, y, color);
117        }
118    }
119}
120
121#[inline]
122fn put_rgba(w: u32, rgba: &mut [u8], x: u32, y: u32, color: [u8; 4]) {
123    let i = ((y as usize) * (w as usize) + (x as usize)) * 4;
124    if i + 3 < rgba.len() {
125        rgba[i] = color[0];
126        rgba[i + 1] = color[1];
127        rgba[i + 2] = color[2];
128        rgba[i + 3] = color[3];
129    }
130}
131
132/// Encode RGBA8 as a minimal uncompressed 32-bit BMP into `out`.
133/// Returns bytes written. Need ≥ 54 + w*h*4.
134pub fn encode_bmp_rgba8(
135    width: u32,
136    height: u32,
137    rgba: &[u8],
138    out: &mut [u8],
139) -> Result<usize, VisionError> {
140    let px = (width as usize).saturating_mul(height as usize);
141    let data_len = px * 4;
142    let file_len = 54 + data_len;
143    if rgba.len() < data_len || out.len() < file_len || width == 0 || height == 0 {
144        return Err(VisionError::OutputBufferTooSmall);
145    }
146    // BITMAPFILEHEADER
147    out[0] = b'B';
148    out[1] = b'M';
149    write_u32_le(&mut out[2..6], file_len as u32);
150    write_u32_le(&mut out[6..10], 0);
151    write_u32_le(&mut out[10..14], 54);
152    // BITMAPINFOHEADER
153    write_u32_le(&mut out[14..18], 40);
154    write_i32_le(&mut out[18..22], width as i32);
155    // Negative height = top-down rows (matches our buffer order).
156    write_i32_le(&mut out[22..26], -(height as i32));
157    write_u16_le(&mut out[26..28], 1);
158    write_u16_le(&mut out[28..30], 32);
159    write_u32_le(&mut out[30..34], 0);
160    write_u32_le(&mut out[34..38], data_len as u32);
161    write_u32_le(&mut out[38..42], 2835);
162    write_u32_le(&mut out[42..46], 2835);
163    write_u32_le(&mut out[46..50], 0);
164    write_u32_le(&mut out[50..54], 0);
165    // BGRA pixel order for BMP
166    for i in 0..px {
167        let s = i * 4;
168        let d = 54 + i * 4;
169        out[d] = rgba[s + 2];
170        out[d + 1] = rgba[s + 1];
171        out[d + 2] = rgba[s];
172        out[d + 3] = rgba[s + 3];
173    }
174    Ok(file_len)
175}
176
177#[inline]
178fn write_u16_le(dst: &mut [u8], v: u16) {
179    dst[0] = (v & 0xFF) as u8;
180    dst[1] = (v >> 8) as u8;
181}
182
183#[inline]
184fn write_u32_le(dst: &mut [u8], v: u32) {
185    dst[0] = (v & 0xFF) as u8;
186    dst[1] = ((v >> 8) & 0xFF) as u8;
187    dst[2] = ((v >> 16) & 0xFF) as u8;
188    dst[3] = ((v >> 24) & 0xFF) as u8;
189}
190
191#[inline]
192fn write_i32_le(dst: &mut [u8], v: i32) {
193    write_u32_le(dst, v as u32);
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::types::Detection;
200
201    #[test]
202    fn css_percent_full_frame() {
203        let d = Detection {
204            x_min_u16: 0,
205            y_min_u16: 0,
206            x_max_u16: 65535,
207            y_max_u16: 65535,
208            ..Detection::empty()
209        };
210        let (l, t, w, h) = box_css_percent(&d);
211        assert!((l - 0.0).abs() < 0.01);
212        assert!((t - 0.0).abs() < 0.01);
213        assert!((w - 100.0).abs() < 0.1);
214        assert!((h - 100.0).abs() < 0.1);
215    }
216
217    #[test]
218    fn draw_box_changes_pixels() {
219        let w = 8u32;
220        let h = 8u32;
221        let mut rgba = vec![0u8; (w * h * 4) as usize];
222        let mut d = Detection::empty();
223        d.class_hash = 1;
224        d.score_u16 = 1000;
225        d.x_min_u16 = 0;
226        d.y_min_u16 = 0;
227        d.x_max_u16 = 32768;
228        d.y_max_u16 = 32768;
229        let n = draw_boxes_rgba8(w, h, &mut rgba, &[d], 1, [255, 0, 0, 255], 1).unwrap();
230        assert_eq!(n, 1);
231        assert!(rgba.iter().any(|&b| b == 255));
232    }
233
234    #[test]
235    fn bmp_roundtrip_size() {
236        let w = 4u32;
237        let h = 4u32;
238        let rgba = vec![128u8; (w * h * 4) as usize];
239        let mut out = vec![0u8; 54 + (w * h * 4) as usize];
240        let n = encode_bmp_rgba8(w, h, &rgba, &mut out).unwrap();
241        assert_eq!(n, 54 + 64);
242        assert_eq!(&out[0..2], b"BM");
243    }
244}