Skip to main content

oa/ui/
cv.rs

1//! Legacy CPU reference CV compositing.
2//!
3//! Donor: `oa/ui/cv.h` and `oa/ui/cv.cpp`.
4//!
5//! `CvFrame` remains a diagnostic/reference path for saved images with CPU
6//! bounding-box annotation. It reads back and uploads a complete RGBA frame
7//! and must not be used for realtime playback — use
8//! [`crate::ui::DetectionOverlay`] for completion-safe, GPU-resident boxes
9//! and hinted coverage labels over image/video views.
10//!
11//! ```ignore
12//! let mut frame = CvFrame::default();
13//! frame.w = 1280;
14//! frame.h = 720;
15//! frame.add_bboxes(detections, &CvBboxesConfig { show_labels: true, ..Default::default() });
16//! let annotated = frame.render_on(&runtime)?;
17//! ```
18
19use crate::render::{Texture, texture_from_rgba8_on};
20pub use crate::ui::type_gen::CvBboxesConfig;
21use crate::{Color, Error, Result, Runtime};
22
23/// One normalized-coordinate bounding box with optional label metadata.
24///
25/// Donor: `oa::CvBbox`.
26#[derive(Clone, Debug)]
27pub struct CvBbox {
28	pub x: f32,
29	pub y: f32,
30	pub w: f32,
31	pub h: f32,
32	pub score: f32,
33	pub class_id: i32,
34	pub label: String,
35}
36
37impl Default for CvBbox {
38	fn default() -> Self {
39		Self {
40			x: 0.0,
41			y: 0.0,
42			w: 0.0,
43			h: 0.0,
44			score: 1.0,
45			class_id: 0,
46			label: String::new(),
47		}
48	}
49}
50
51impl Default for CvBboxesConfig {
52	fn default() -> Self {
53		Self {
54			color: Color::error(),
55			line_width: 1.5,
56			alpha: 1.0,
57			label_scale: 1,
58			show_labels: true,
59			show_scores: true,
60		}
61	}
62}
63
64/// One overlay batch: shared config plus its boxes.
65///
66/// Donor: `oa::CvOverlayBboxes` (the only `CvOverlay` kind).
67#[derive(Clone, Debug)]
68pub struct CvOverlay {
69	pub config: CvBboxesConfig,
70	pub boxes: Vec<CvBbox>,
71}
72
73/// Diagnostic frame: borrowed base pixels plus ordered CPU overlays.
74///
75/// `base` borrows a packed RGBA8 texture; `render` reads it back before
76/// compositing. A `None` base composites over a black canvas.
77///
78/// Donor: `oa::CvFrame`.
79#[derive(Default)]
80pub struct CvFrame<'a> {
81	/// Borrowed RGBA8 device image read back during [`Self::render`].
82	pub base: Option<&'a Texture>,
83	pub w: i32,
84	pub h: i32,
85	pub overlays: Vec<CvOverlay>,
86}
87
88impl<'a> CvFrame<'a> {
89	/// Append a bbox overlay batch, drawn after all previous overlays.
90	pub fn add_bboxes(&mut self, boxes: Vec<CvBbox>, config: &CvBboxesConfig) {
91		self.overlays.push(CvOverlay {
92			config: *config,
93			boxes,
94		});
95	}
96
97	/// Drop every overlay.
98	pub fn clear_overlays(&mut self) {
99		self.overlays.clear();
100	}
101
102	pub fn render(&self) -> Result<Texture> {
103		self.render_on(&Runtime::current()?)
104	}
105
106	/// Composite overlays over the borrowed base and upload the result.
107	///
108	/// # Errors
109	///
110	/// Returns an error for a non-positive extent, an undersized or
111	/// unreadable base, or an invalid overlay config or box.
112	pub fn render_on(&self, runtime: &Runtime) -> Result<Texture> {
113		self.render_with_rgba_on(runtime, &[])
114	}
115
116	pub fn render_with_rgba(&self, base_rgba: &[u8]) -> Result<Texture> {
117		self.render_with_rgba_on(&Runtime::current()?, base_rgba)
118	}
119
120	/// Composite overlays over explicit host RGBA8 pixels (or the borrowed
121	/// device base when `base_rgba` is empty).
122	///
123	/// # Errors
124	///
125	/// Returns an error for a non-positive extent, an undersized base, or an
126	/// invalid overlay config or box.
127	pub fn render_with_rgba_on(&self, runtime: &Runtime, base_rgba: &[u8]) -> Result<Texture> {
128		render_frame(self, runtime, base_rgba)
129	}
130}
131
132// ── CPU drawing helpers ──────────────────────────────────────────────────────
133
134fn blend_pixel(dst: &mut [u8], r: u8, g: u8, b: u8, a: u8) {
135	let alpha = f32::from(a) / 255.0;
136	dst[0] = (f32::from(dst[0]) * (1.0 - alpha) + f32::from(r) * alpha) as u8;
137	dst[1] = (f32::from(dst[1]) * (1.0 - alpha) + f32::from(g) * alpha) as u8;
138	dst[2] = (f32::from(dst[2]) * (1.0 - alpha) + f32::from(b) * alpha) as u8;
139	dst[3] = 255;
140}
141
142fn draw_hline(buf: &mut [u8], w: i32, h: i32, x0: i64, x1: i64, y: i64, color: [u8; 4]) {
143	if y < 0 || y >= i64::from(h) {
144		return;
145	}
146	let x0 = x0.max(0);
147	let x1 = x1.min(i64::from(w) - 1);
148	for x in x0..=x1 {
149		let offset = (y as usize * w as usize + x as usize) * 4;
150		blend_pixel(
151			&mut buf[offset..offset + 4],
152			color[0],
153			color[1],
154			color[2],
155			color[3],
156		);
157	}
158}
159
160fn draw_vline(buf: &mut [u8], w: i32, h: i32, x: i64, y0: i64, y1: i64, color: [u8; 4]) {
161	if x < 0 || x >= i64::from(w) {
162		return;
163	}
164	let y0 = y0.max(0);
165	let y1 = y1.min(i64::from(h) - 1);
166	for y in y0..=y1 {
167		let offset = (y as usize * w as usize + x as usize) * 4;
168		blend_pixel(
169			&mut buf[offset..offset + 4],
170			color[0],
171			color[1],
172			color[2],
173			color[3],
174		);
175	}
176}
177
178#[allow(clippy::too_many_arguments)]
179fn draw_rect(
180	buf: &mut [u8],
181	w: i32,
182	h: i32,
183	x: i64,
184	y: i64,
185	rw: i64,
186	rh: i64,
187	thickness: i32,
188	color: [u8; 4],
189) {
190	for t in 0..i64::from(thickness) {
191		draw_hline(buf, w, h, x, x + rw - 1, y + t, color);
192		draw_hline(buf, w, h, x, x + rw - 1, y + rh - 1 - t, color);
193		draw_vline(buf, w, h, x + t, y, y + rh - 1, color);
194		draw_vline(buf, w, h, x + rw - 1 - t, y, y + rh - 1, color);
195	}
196}
197
198#[allow(clippy::too_many_arguments)]
199fn fill_rect(buf: &mut [u8], w: i32, h: i32, x: i64, y: i64, rw: i64, rh: i64, color: [u8; 4]) {
200	let y0 = y.max(0);
201	let y1 = (y + rh).min(i64::from(h));
202	for row in y0..y1 {
203		draw_hline(buf, w, h, x, x + rw - 1, row, color);
204	}
205}
206
207// Compact 5x7 label font: digits, ':', '.', ' ', '%', A-Z.
208const FONT_5X7: [[u8; 7]; 40] = [
209	[
210		0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
211	], // 0
212	[
213		0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
214	], // 1
215	[
216		0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
217	], // 2
218	[
219		0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110,
220	], // 3
221	[
222		0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
223	], // 4
224	[
225		0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
226	], // 5
227	[
228		0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
229	], // 6
230	[
231		0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
232	], // 7
233	[
234		0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
235	], // 8
236	[
237		0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
238	], // 9
239	[
240		0b00000, 0b00100, 0b00000, 0b00000, 0b00100, 0b00000, 0b00000,
241	], // :
242	[
243		0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100,
244	], // .
245	[
246		0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000,
247	], // space
248	[
249		0b11000, 0b11001, 0b00010, 0b00100, 0b01000, 0b10011, 0b00011,
250	], // %
251	[
252		0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
253	], // A
254	[
255		0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110,
256	], // B
257	[
258		0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
259	], // C
260	[
261		0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
262	], // D
263	[
264		0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
265	], // E
266	[
267		0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000,
268	], // F
269	[
270		0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110,
271	], // G
272	[
273		0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
274	], // H
275	[
276		0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
277	], // I
278	[
279		0b00001, 0b00001, 0b00001, 0b00001, 0b10001, 0b10001, 0b01110,
280	], // J
281	[
282		0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001,
283	], // K
284	[
285		0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
286	], // L
287	[
288		0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
289	], // M
290	[
291		0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
292	], // N
293	[
294		0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
295	], // O
296	[
297		0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
298	], // P
299	[
300		0b01110, 0b10001, 0b10001, 0b10101, 0b10001, 0b10010, 0b01101,
301	], // Q
302	[
303		0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
304	], // R
305	[
306		0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
307	], // S
308	[
309		0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
310	], // T
311	[
312		0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
313	], // U
314	[
315		0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
316	], // V
317	[
318		0b10001, 0b10001, 0b10101, 0b10101, 0b10101, 0b10101, 0b01010,
319	], // W
320	[
321		0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
322	], // X
323	[
324		0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
325	], // Y
326	[
327		0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111,
328	], // Z
329];
330
331fn char_index(c: u8) -> usize {
332	if c.is_ascii_digit() {
333		return usize::from(c - b'0');
334	}
335	match c {
336		b':' => 10,
337		b'.' => 11,
338		b' ' => 12,
339		b'%' => 13,
340		_ => {
341			let upper = c.to_ascii_uppercase();
342			if upper.is_ascii_uppercase() {
343				14 + usize::from(upper - b'A')
344			} else {
345				12 // fallback: space
346			}
347		}
348	}
349}
350
351#[allow(clippy::too_many_arguments)]
352fn draw_char(
353	buf: &mut [u8],
354	w: i32,
355	h: i32,
356	x: i64,
357	y: i64,
358	c: u8,
359	scale: i32,
360	r: u8,
361	g: u8,
362	b: u8,
363) {
364	let idx = char_index(c);
365	for (row, bits) in FONT_5X7[idx].iter().enumerate() {
366		for col in 0..5_i64 {
367			if bits & (0b10000_u8 >> col) != 0 {
368				for sy in 0..i64::from(scale) {
369					for sx in 0..i64::from(scale) {
370						let px = x + col * i64::from(scale) + sx;
371						let py = y + row as i64 * i64::from(scale) + sy;
372						if px >= 0 && px < i64::from(w) && py >= 0 && py < i64::from(h) {
373							let offset = (py as usize * w as usize + px as usize) * 4;
374							buf[offset] = r;
375							buf[offset + 1] = g;
376							buf[offset + 2] = b;
377							buf[offset + 3] = 255;
378						}
379					}
380				}
381			}
382		}
383	}
384}
385
386#[allow(clippy::too_many_arguments)]
387fn draw_string(
388	buf: &mut [u8],
389	w: i32,
390	h: i32,
391	x: i64,
392	y: i64,
393	text: &str,
394	scale: i32,
395	color: [u8; 3],
396) {
397	let mut cx = x;
398	for &c in text.as_bytes() {
399		draw_char(buf, w, h, cx, y, c, scale, color[0], color[1], color[2]);
400		cx += 6 * i64::from(scale);
401	}
402}
403
404fn render_frame(frame: &CvFrame<'_>, runtime: &Runtime, base_rgba: &[u8]) -> Result<Texture> {
405	let w = frame.w;
406	let h = frame.h;
407	if w <= 0 || h <= 0 {
408		return Err(Error::invalid_argument("CvFrame: invalid W/H"));
409	}
410	let n_bytes = w as usize * h as usize * 4;
411	let mut pixels = vec![0_u8; n_bytes];
412
413	if !base_rgba.is_empty() && base_rgba.len() < n_bytes {
414		return Err(Error::invalid_argument(
415			"CvFrame::render: host base is smaller than W*H*4",
416		));
417	}
418	if base_rgba.len() >= n_bytes {
419		pixels.copy_from_slice(&base_rgba[..n_bytes]);
420	} else if let Some(base) = frame.base {
421		let readback = base.read_rgba8()?;
422		if readback.len() < n_bytes {
423			return Err(Error::invalid_argument(
424				"CvFrame::render: base is null or smaller than W*H*4",
425			));
426		}
427		pixels.copy_from_slice(&readback[..n_bytes]);
428	} else {
429		// Black canvas fallback — keep alpha=255 so overlays show on it.
430		for index in (3..pixels.len()).step_by(4) {
431			pixels[index] = 255;
432		}
433	}
434
435	for overlay in &frame.overlays {
436		let config = &overlay.config;
437		if !config.alpha.is_finite()
438			|| !(0.0..=1.0).contains(&config.alpha)
439			|| !config.line_width.is_finite()
440			|| !(0.0..=1024.0).contains(&config.line_width)
441			|| config.line_width <= 0.0
442			|| !(1..=16).contains(&config.label_scale)
443			|| ![
444				config.color.r,
445				config.color.g,
446				config.color.b,
447				config.color.a,
448			]
449			.iter()
450			.all(|component| component.is_finite())
451		{
452			return Err(Error::invalid_argument(
453				"CvFrame: invalid bounding-box overlay config",
454			));
455		}
456		let packed = config.color.to_u32();
457		let r = (packed >> 24) as u8;
458		let g = (packed >> 16) as u8;
459		let b = (packed >> 8) as u8;
460		let a = (config.alpha * 255.0) as u8;
461		let thickness = config.line_width.max(1.0) as i32;
462
463		for bbox in &overlay.boxes {
464			let right = f64::from(bbox.x) + f64::from(bbox.w);
465			let bottom = f64::from(bbox.y) + f64::from(bbox.h);
466			let min_coordinate = f64::from(i32::MIN);
467			let max_coordinate = f64::from(i32::MAX);
468			if !bbox.x.is_finite()
469				|| !bbox.y.is_finite()
470				|| !bbox.w.is_finite()
471				|| !bbox.h.is_finite()
472				|| !bbox.score.is_finite()
473				|| bbox.w <= 0.0
474				|| bbox.h <= 0.0
475				|| f64::from(bbox.x) < min_coordinate
476				|| f64::from(bbox.y) < min_coordinate
477				|| f64::from(bbox.w) > max_coordinate
478				|| f64::from(bbox.h) > max_coordinate
479				|| right > max_coordinate
480				|| bottom > max_coordinate
481			{
482				return Err(Error::invalid_argument("CvFrame: invalid bounding box"));
483			}
484			let bx = i64::from(bbox.x as i32);
485			let by = i64::from(bbox.y as i32);
486			let bw = i64::from(bbox.w as i32);
487			let bh = i64::from(bbox.h as i32);
488			if bw <= 0 || bh <= 0 {
489				return Err(Error::invalid_argument(
490					"CvFrame: bounding box has no whole-pixel extent",
491				));
492			}
493			draw_rect(&mut pixels, w, h, bx, by, bw, bh, thickness, [r, g, b, a]);
494
495			if config.show_labels || config.show_scores {
496				let percent = bbox.score * 100.0;
497				let label_text = if bbox.label.is_empty() {
498					"obj"
499				} else {
500					&bbox.label
501				};
502				let text = match (config.show_labels, config.show_scores) {
503					(true, true) => format!("{label_text} {percent:.0}%"),
504					(true, false) => label_text.to_string(),
505					(false, true) => format!("{percent:.0}%"),
506					(false, false) => String::new(),
507				};
508				let label_scale = config.label_scale.max(1);
509				let label_width = text.len() as i64 * 6 * i64::from(label_scale) + 4;
510				let label_height = 7 * i64::from(label_scale) + 4;
511				let lx = bx + 2;
512				let mut ly = by - label_height;
513				if ly < 0 {
514					ly = by + 2;
515				}
516				fill_rect(
517					&mut pixels,
518					w,
519					h,
520					lx - 2,
521					ly - 2,
522					label_width,
523					label_height,
524					[0, 0, 0, 192],
525				);
526				draw_string(&mut pixels, w, h, lx, ly, &text, label_scale, [r, g, b]);
527			}
528		}
529	}
530
531	texture_from_rgba8_on(runtime, &pixels, w as usize, h as usize)
532}