1use std::io;
4
5pub const MAX_SURFACE_PIXELS: usize = 1280 * 720;
8const MAX_SURFACE_SIDE: usize = 65_535;
12const MAX_BLEND_PRODUCT: u16 = 255 * 255;
13const BLEND_LOOKUP_TABLE_SIDE: usize = 256;
14const BLEND_LOOKUP_TABLE_SIDE_U16: u16 = 256;
15#[cfg(test)]
16const BLEND_LOOKUP_TABLE_LEN: usize = BLEND_LOOKUP_TABLE_SIDE * BLEND_LOOKUP_TABLE_SIDE;
17#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
18const SPAN_NEON_PIXELS: usize = 16;
19
20macro_rules! blend_lookup_table {
21 ($($inverse_alpha:literal),* $(,)?) => {
22 [$(build_blend_lookup_row($inverse_alpha)),*]
23 };
24}
25
26static BLEND_PRODUCT_BY_255_ROUNDED: [[u8; BLEND_LOOKUP_TABLE_SIDE]; BLEND_LOOKUP_TABLE_SIDE] = blend_lookup_table!(
27 0, 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,
28 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
29 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
30 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
31 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
32 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
33 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154,
34 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173,
35 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192,
36 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211,
37 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230,
38 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249,
39 250, 251, 252, 253, 254, 255
40);
41
42const fn build_blend_lookup_row(inverse_alpha: u16) -> [u8; BLEND_LOOKUP_TABLE_SIDE] {
43 let mut row = [0; BLEND_LOOKUP_TABLE_SIDE];
44 let mut index = 0;
45 let mut destination = 0;
46 while destination < BLEND_LOOKUP_TABLE_SIDE_U16 {
47 row[index] = divide_blend_product_by_255_rounded(destination * inverse_alpha);
48 index += 1;
49 destination += 1;
50 }
51 row
52}
53
54fn blend_lookup_entry(destination: u8, inverse_alpha: u8) -> u8 {
55 BLEND_PRODUCT_BY_255_ROUNDED[usize::from(inverse_alpha)][usize::from(destination)]
56}
57
58#[derive(Debug, Default)]
59pub struct SoftwareSurface {
61 pub width: usize,
63 pub height: usize,
65 pub pixels: Vec<u8>,
67}
68
69impl SoftwareSurface {
70 pub(crate) fn resize(&mut self, width: usize, height: usize) -> io::Result<bool> {
71 let pixels = width
72 .checked_mul(height)
73 .ok_or_else(|| io::Error::other("software surface pixel count overflow"))?;
74 if pixels > MAX_SURFACE_PIXELS {
75 return Err(io::Error::other(format!(
76 "software surface pixel budget exceeded: {pixels} > {MAX_SURFACE_PIXELS}"
77 )));
78 }
79 if width > MAX_SURFACE_SIDE || height > MAX_SURFACE_SIDE {
80 return Err(io::Error::other(format!(
81 "software surface {width}x{height} is longer than {MAX_SURFACE_SIDE} pixels on a side"
82 )));
83 }
84 let bytes = pixels
85 .checked_mul(4)
86 .ok_or_else(|| io::Error::other("software surface byte count overflow"))?;
87 if self.width != width || self.height != height || self.pixels.len() != bytes {
88 self.pixels.resize(bytes, 0);
89 self.width = width;
90 self.height = height;
91 return Ok(true);
92 }
93 Ok(false)
94 }
95
96 pub(crate) fn clear(&mut self, color: [u8; 4]) {
97 for pixel in self.pixels.as_chunks_mut::<4>().0 {
98 pixel.copy_from_slice(&color);
99 }
100 }
101
102 pub(crate) fn blend_pixel(&mut self, x: usize, y: usize, color: [u8; 4]) {
103 let offset = (y * self.width + x) * 4;
104 alpha_blend(&mut self.pixels[offset..offset + 4], color);
105 }
106
107 pub(crate) const fn row_offset(&self, y: usize) -> usize {
108 y * self.width * 4
109 }
110
111 pub(crate) fn write_opaque_pixel_at_offset(&mut self, offset: usize, color: [u8; 4]) {
112 self.pixels[offset..offset + 4].copy_from_slice(&color);
113 }
114
115 pub(crate) fn blend_translucent_pixel_at_offset(&mut self, offset: usize, color: [u8; 4]) {
116 blend_translucent_premultiplied_over_opaque_destination(
117 &mut self.pixels[offset..offset + 4],
118 color,
119 );
120 }
121
122 pub(crate) fn blend_constant_color_span_at_offset(
123 &mut self,
124 offset: usize,
125 len: usize,
126 color: [u8; 4],
127 ) {
128 match color[3] {
129 0 => {}
130 u8::MAX => self.write_opaque_span_at_offset(offset, len, color),
131 _ => self.blend_translucent_span_at_offset(offset, len, color),
132 }
133 }
134
135 fn write_opaque_span_at_offset(&mut self, offset: usize, len: usize, color: [u8; 4]) {
136 let end = offset + len * 4;
137 for pixel in self.pixels[offset..end].as_chunks_mut::<4>().0 {
138 pixel.copy_from_slice(&color);
139 }
140 }
141
142 fn blend_translucent_span_at_offset(&mut self, offset: usize, len: usize, color: [u8; 4]) {
143 let end = offset + len * 4;
144 blend_constant_premultiplied_span_rgba(&mut self.pixels[offset..end], color);
145 }
146
147 pub(crate) fn blend_span(&mut self, y: usize, start_x: usize, end_x: usize, color: [u8; 4]) {
148 if color[3] == 0 {
149 return;
150 }
151
152 let start = (y * self.width + start_x) * 4;
153 let end = (y * self.width + end_x) * 4;
154
155 if color[3] == u8::MAX {
156 for pixel in self.pixels[start..end].as_chunks_mut::<4>().0 {
157 pixel.copy_from_slice(&color);
158 }
159 return;
160 }
161
162 blend_constant_premultiplied_span_rgba(&mut self.pixels[start..end], color);
163 }
164}
165
166fn blend_constant_premultiplied_span_rgba(span: &mut [u8], source: [u8; 4]) {
167 #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
168 {
169 let vector_bytes = span.len() / (SPAN_NEON_PIXELS * 4) * (SPAN_NEON_PIXELS * 4);
170 let (vector_span, tail) = span.split_at_mut(vector_bytes);
171
172 unsafe { blend_constant_premultiplied_span_rgba_neon(vector_span, source) };
175 blend_constant_premultiplied_span_rgba_scalar(tail, source);
176 }
177
178 #[cfg(not(all(target_arch = "aarch64", target_endian = "little")))]
179 blend_constant_premultiplied_span_rgba_scalar(span, source);
180}
181
182fn blend_constant_premultiplied_span_rgba_scalar(span: &mut [u8], source: [u8; 4]) {
183 let inverse_alpha = u8::MAX - source[3];
184 for pixel in span.as_chunks_mut::<4>().0 {
185 blend_translucent_premultiplied_over_opaque_destination_with_inverse_alpha(
186 pixel,
187 source,
188 inverse_alpha,
189 );
190 }
191}
192
193#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
194unsafe fn blend_constant_premultiplied_span_rgba_neon(span: &mut [u8], source: [u8; 4]) {
195 use core::arch::aarch64::{
196 uint8x8_t, uint8x16_t, uint8x16x4_t, uint16x8_t, vaddq_u16, vcombine_u8, vdup_n_u8,
197 vdupq_n_u8, vdupq_n_u16, vget_high_u8, vget_low_u8, vld4q_u8, vmovn_u16, vmull_u8,
198 vqaddq_u8, vshrq_n_u16, vst4q_u8,
199 };
200
201 unsafe fn divide_product(product: uint16x8_t) -> uint8x8_t {
202 let biased = unsafe { vaddq_u16(product, vdupq_n_u16(128)) };
203 let correction = unsafe { vshrq_n_u16(biased, 8) };
204 let quotient = unsafe { vshrq_n_u16(vaddq_u16(biased, correction), 8) };
205 unsafe { vmovn_u16(quotient) }
206 }
207
208 unsafe fn blend_channel(
209 destination: uint8x16_t,
210 source: uint8x16_t,
211 inverse_alpha: uint8x8_t,
212 ) -> uint8x16_t {
213 let low_product = unsafe { vmull_u8(vget_low_u8(destination), inverse_alpha) };
214 let high_product = unsafe { vmull_u8(vget_high_u8(destination), inverse_alpha) };
215 let blend =
216 unsafe { vcombine_u8(divide_product(low_product), divide_product(high_product)) };
217 unsafe { vqaddq_u8(source, blend) }
218 }
219
220 debug_assert_eq!(span.len() % (SPAN_NEON_PIXELS * 4), 0);
221
222 let inverse_alpha = unsafe { vdup_n_u8(u8::MAX - source[3]) };
223 let red = unsafe { vdupq_n_u8(source[0]) };
224 let green = unsafe { vdupq_n_u8(source[1]) };
225 let blue = unsafe { vdupq_n_u8(source[2]) };
226 let alpha = unsafe { vdupq_n_u8(u8::MAX) };
227
228 for pixel_block in span.as_chunks_mut::<{ SPAN_NEON_PIXELS * 4 }>().0 {
229 let destination = unsafe { vld4q_u8(pixel_block.as_ptr()) };
230 let blended = uint8x16x4_t(
231 unsafe { blend_channel(destination.0, red, inverse_alpha) },
232 unsafe { blend_channel(destination.1, green, inverse_alpha) },
233 unsafe { blend_channel(destination.2, blue, inverse_alpha) },
234 alpha,
235 );
236 unsafe { vst4q_u8(pixel_block.as_mut_ptr(), blended) };
237 }
238}
239
240fn alpha_blend(destination: &mut [u8], source: [u8; 4]) {
241 match source[3] {
242 0 => return,
243 u8::MAX => {
244 destination.copy_from_slice(&source);
245 return;
246 }
247 _ => {}
248 }
249
250 let inverse_alpha = u8::MAX - source[3];
251 destination[0] = blend_premultiplied_channel(source[0], destination[0], inverse_alpha);
255 destination[1] = blend_premultiplied_channel(source[1], destination[1], inverse_alpha);
256 destination[2] = blend_premultiplied_channel(source[2], destination[2], inverse_alpha);
257 destination[3] = u8::MAX;
258}
259
260fn blend_translucent_premultiplied_over_opaque_destination(
261 destination: &mut [u8],
262 source: [u8; 4],
263) {
264 let inverse_alpha = u8::MAX - source[3];
265 blend_translucent_premultiplied_over_opaque_destination_with_inverse_alpha(
266 destination,
267 source,
268 inverse_alpha,
269 );
270}
271
272fn blend_translucent_premultiplied_over_opaque_destination_with_inverse_alpha(
273 destination: &mut [u8],
274 source: [u8; 4],
275 inverse_alpha: u8,
276) {
277 destination[0] = blend_premultiplied_channel(source[0], destination[0], inverse_alpha);
278 destination[1] = blend_premultiplied_channel(source[1], destination[1], inverse_alpha);
279 destination[2] = blend_premultiplied_channel(source[2], destination[2], inverse_alpha);
280 destination[3] = u8::MAX;
281}
282
283fn blend_premultiplied_channel(source: u8, destination: u8, inverse_alpha: u8) -> u8 {
284 let blend = blend_lookup_entry(destination, inverse_alpha);
285 u8::try_from(u16::from(source) + u16::from(blend)).unwrap_or(u8::MAX)
286}
287
288const fn divide_blend_product_by_255_rounded(product: u16) -> u8 {
289 debug_assert!(product <= MAX_BLEND_PRODUCT);
290 let biased = product + 128;
291 let quotient = (biased + (biased >> 8)) >> 8;
292 debug_assert!(quotient <= 255);
293 quotient.to_le_bytes()[0]
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 #[test]
301 fn rounded_divide_by_255_matches_reference_for_blend_products() {
302 for destination in u8::MIN..=u8::MAX {
303 for inverse_alpha in u8::MIN..=u8::MAX {
304 let product = u16::from(destination) * u16::from(inverse_alpha);
305 let reference = (product + 127) / 255;
306
307 assert_eq!(
308 u16::from(divide_blend_product_by_255_rounded(product)),
309 reference
310 );
311 }
312 }
313 }
314
315 #[test]
316 fn blend_lookup_table_matches_reference_for_all_entries() {
317 assert_eq!(BLEND_PRODUCT_BY_255_ROUNDED.len(), 256);
318 assert_eq!(BLEND_PRODUCT_BY_255_ROUNDED[0].len(), 256);
319 assert_eq!(
320 BLEND_PRODUCT_BY_255_ROUNDED.len() * BLEND_PRODUCT_BY_255_ROUNDED[0].len(),
321 BLEND_LOOKUP_TABLE_LEN
322 );
323
324 for inverse_alpha in u8::MIN..=u8::MAX {
325 for destination in u8::MIN..=u8::MAX {
326 let product = u16::from(destination) * u16::from(inverse_alpha);
327 let reference = u8::try_from((product + 127) / 255).expect("blend product");
328
329 assert_eq!(blend_lookup_entry(destination, inverse_alpha), reference);
330 }
331 }
332 }
333
334 #[test]
335 fn alpha_blend_skips_transparent_source() {
336 let mut destination = [11, 22, 33, 255];
337
338 alpha_blend(&mut destination, [255, 0, 0, 0]);
339
340 assert_eq!(destination, [11, 22, 33, 255]);
341 }
342
343 #[test]
344 fn alpha_blend_overwrites_with_opaque_source() {
345 let mut destination = [11, 22, 33, 255];
346
347 alpha_blend(&mut destination, [44, 55, 66, 255]);
348
349 assert_eq!(destination, [44, 55, 66, 255]);
350 }
351
352 #[test]
353 fn alpha_blend_places_premultiplied_half_alpha_over_opaque_destination() {
354 let mut destination = [0, 0, 255, 255];
355
356 alpha_blend(&mut destination, [128, 0, 0, 128]);
357
358 assert_eq!(destination, [128, 0, 127, 255]);
359 }
360
361 #[test]
362 fn blend_span_skips_transparent_source() {
363 let mut surface = SoftwareSurface::default();
364 surface.resize(4, 1).expect("surface");
365 surface
366 .pixels
367 .copy_from_slice(&[1, 2, 3, 255, 4, 5, 6, 255, 7, 8, 9, 255, 10, 11, 12, 255]);
368
369 surface.blend_span(0, 1, 3, [200, 100, 50, 0]);
370
371 assert_eq!(
372 surface.pixels,
373 [1, 2, 3, 255, 4, 5, 6, 255, 7, 8, 9, 255, 10, 11, 12, 255]
374 );
375 }
376
377 #[test]
378 fn blend_span_overwrites_opaque_source_over_multiple_pixels() {
379 let mut surface = SoftwareSurface::default();
380 surface.resize(4, 1).expect("surface");
381 surface
382 .pixels
383 .copy_from_slice(&[1, 2, 3, 255, 4, 5, 6, 255, 7, 8, 9, 255, 10, 11, 12, 255]);
384
385 surface.blend_span(0, 1, 3, [44, 55, 66, 255]);
386
387 assert_eq!(
388 surface.pixels,
389 [
390 1, 2, 3, 255, 44, 55, 66, 255, 44, 55, 66, 255, 10, 11, 12, 255
391 ]
392 );
393 }
394
395 #[test]
396 fn blend_span_matches_alpha_blend_for_translucent_source() {
397 let color = [100, 25, 0, 128];
398 let mut surface = SoftwareSurface::default();
399 surface.resize(4, 1).expect("surface");
400 surface.pixels.copy_from_slice(&[
401 1, 2, 3, 255, 20, 40, 60, 255, 70, 80, 90, 255, 10, 11, 12, 255,
402 ]);
403 let mut expected = surface.pixels.clone();
404
405 for pixel in expected[4..12].as_chunks_mut::<4>().0 {
406 alpha_blend(pixel, color);
407 }
408 surface.blend_span(0, 1, 3, color);
409
410 assert_eq!(surface.pixels, expected);
411 }
412
413 #[test]
414 fn constant_premultiplied_span_matches_explicit_scalar_reference() {
415 for width in [0, 1, 3, 7, 8, 15, 16, 17, 31, 32, 33] {
416 for alpha in [1_u8, 2, 63, 127, 128, 191, 254] {
417 for source_rgb in [
418 [0, 0, 0],
419 [1, 0, alpha],
420 [alpha / 2, alpha.saturating_sub(1), alpha],
421 [alpha, alpha, alpha],
422 [254, 255, 1],
423 [255, 255, 255],
424 ] {
425 for pattern_seed in [0, 17, 251] {
426 let source = [source_rgb[0], source_rgb[1], source_rgb[2], alpha];
427 let mut by_span = patterned_pixels(width, pattern_seed);
428 let mut expected = by_span.clone();
429
430 blend_constant_premultiplied_span_rgba(&mut by_span, source);
431 blend_constant_premultiplied_span_rgba_reference(&mut expected, source);
432
433 assert_eq!(by_span, expected, "width {width}, source {source:?}");
434 }
435 }
436 }
437 }
438 }
439
440 #[test]
441 fn offset_opaque_write_matches_blend_pixel_for_opaque_source() {
442 let color = [44, 55, 66, 255];
443 let mut by_offset = SoftwareSurface::default();
444 by_offset.resize(3, 2).expect("surface");
445 by_offset.clear([1, 2, 3, 255]);
446 let mut by_blend = SoftwareSurface::default();
447 by_blend.resize(3, 2).expect("surface");
448 by_blend.clear([1, 2, 3, 255]);
449
450 by_offset.write_opaque_pixel_at_offset(by_offset.row_offset(1) + 2 * 4, color);
451 by_blend.blend_pixel(2, 1, color);
452
453 assert_eq!(by_offset.pixels, by_blend.pixels);
454 }
455
456 #[test]
457 fn offset_translucent_blend_matches_alpha_blend_for_translucent_source() {
458 let color = [100, 25, 0, 128];
459 let mut by_offset = SoftwareSurface::default();
460 by_offset.resize(3, 2).expect("surface");
461 by_offset.clear([20, 40, 60, 255]);
462 let mut by_blend = SoftwareSurface::default();
463 by_blend.resize(3, 2).expect("surface");
464 by_blend.clear([20, 40, 60, 255]);
465
466 by_offset.blend_translucent_pixel_at_offset(by_offset.row_offset(1) + 4, color);
467 by_blend.blend_pixel(1, 1, color);
468
469 assert_eq!(by_offset.pixels, by_blend.pixels);
470 }
471
472 #[test]
473 fn offset_span_skips_transparent_source_like_repeated_pixel_blend() {
474 assert_offset_span_matches_repeated_pixel_blend([100, 25, 0, 0], 2, 3);
475 }
476
477 #[test]
478 fn offset_span_overwrites_opaque_source_like_repeated_pixel_write() {
479 assert_offset_span_matches_repeated_pixel_blend([44, 55, 66, 255], 2, 3);
480 }
481
482 #[test]
483 fn offset_span_blends_translucent_source_like_repeated_pixel_blend() {
484 assert_offset_span_matches_repeated_pixel_blend([100, 25, 0, 128], 2, 3);
485 }
486
487 fn assert_offset_span_matches_repeated_pixel_blend(color: [u8; 4], start_x: usize, len: usize) {
488 let mut by_span = SoftwareSurface::default();
489 by_span.resize(6, 2).expect("surface");
490 by_span.clear([20, 40, 60, 255]);
491 let mut by_pixel = SoftwareSurface::default();
492 by_pixel.resize(6, 2).expect("surface");
493 by_pixel.clear([20, 40, 60, 255]);
494 let offset = by_span.row_offset(1) + start_x * 4;
495
496 by_span.blend_constant_color_span_at_offset(offset, len, color);
497 let mut pixel_offset = offset;
498 for _ in 0..len {
499 match color[3] {
500 0 => {}
501 u8::MAX => by_pixel.write_opaque_pixel_at_offset(pixel_offset, color),
502 _ => by_pixel.blend_translucent_pixel_at_offset(pixel_offset, color),
503 }
504 pixel_offset += 4;
505 }
506
507 assert_eq!(by_span.pixels, by_pixel.pixels);
508 }
509
510 fn patterned_pixels(width: usize, seed: u8) -> Vec<u8> {
511 let mut pixels = Vec::with_capacity(width * 4);
512 for index in 0..width {
513 let offset = u8::try_from(index).expect("test width fits in u8");
514 pixels.extend_from_slice(&[
515 seed.wrapping_add(offset.wrapping_mul(3)),
516 seed.wrapping_add(offset.wrapping_mul(5)),
517 seed.wrapping_add(offset.wrapping_mul(7)),
518 u8::MAX,
519 ]);
520 }
521 pixels
522 }
523
524 fn blend_constant_premultiplied_span_rgba_reference(span: &mut [u8], source: [u8; 4]) {
525 let inverse_alpha = u16::from(u8::MAX - source[3]);
526 for pixel in span.as_chunks_mut::<4>().0 {
527 for channel in 0..3 {
528 let product = u16::from(pixel[channel]) * inverse_alpha;
529 let blend = (product + 127) / 255;
530 pixel[channel] =
531 u8::try_from(u16::from(source[channel]) + blend).unwrap_or(u8::MAX);
532 }
533 pixel[3] = u8::MAX;
534 }
535 }
536
537 #[test]
538 fn transparent_source_matches_skipped_offset_write() {
539 let mut by_offset = SoftwareSurface::default();
540 by_offset.resize(3, 2).expect("surface");
541 by_offset.clear([20, 40, 60, 255]);
542 let mut by_blend = SoftwareSurface::default();
543 by_blend.resize(3, 2).expect("surface");
544 by_blend.clear([20, 40, 60, 255]);
545
546 by_blend.blend_pixel(1, 1, [100, 25, 0, 0]);
547
548 assert_eq!(by_offset.pixels, by_blend.pixels);
549 }
550
551 #[test]
552 fn software_surface_accepts_hd_handheld_framebuffer() {
553 let mut surface = SoftwareSurface::default();
554
555 surface.resize(1280, 720).expect("HD handheld surface");
556
557 assert_eq!(surface.width, 1280);
558 assert_eq!(surface.height, 720);
559 assert_eq!(surface.pixels.len(), MAX_SURFACE_PIXELS * 4);
560 }
561
562 #[test]
563 fn software_surface_rejects_pixel_budget_overflow() {
564 let mut surface = SoftwareSurface::default();
565
566 let error = surface
567 .resize(MAX_SURFACE_PIXELS + 1, 1)
568 .expect_err("oversized surface");
569
570 assert_eq!(
571 error.to_string(),
572 format!(
573 "software surface pixel budget exceeded: {} > {MAX_SURFACE_PIXELS}",
574 MAX_SURFACE_PIXELS + 1
575 )
576 );
577 }
578}