Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(desktop-gpui): build the app crate unoptimized in dev and keep hot loops in cap-gpui-kernels
LukeParkerDevd917486a63f6
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lockindex 635d63bb1..ecfb0d213 100644--- a/apps/desktop-gpui/Cargo.lock+++ b/apps/desktop-gpui/Cargo.lock@@ -1537,6 +1537,7 @@ dependencies = ["cap-editor","cap-enc-ffmpeg","cap-export",+ "cap-gpui-kernels","cap-media-info","cap-project","cap-recording",@@ -1562,7 +1563,6 @@ dependencies = ["jpeg-decoder","kameo","libc",- "md-5","objc2 0.5.2","objc2-app-kit 0.2.2","objc2-foundation 0.2.2",@@ -1747,6 +1747,16 @@ dependencies = ["workspace-hack",]+[[package]]+name = "cap-gpui-kernels"+version = "0.1.0"+dependencies = [+ "cap-audio",+ "cap-project",+ "image 0.25.10",+ "md-5",+]+[[package]]name = "cap-media"version = "0.1.0"diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.tomlindex de7f91841..a498de6df 100644--- a/apps/desktop-gpui/Cargo.toml+++ b/apps/desktop-gpui/Cargo.toml@@ -5,7 +5,7 @@# wgpu-hal, tao) that only exist for the Tauri app.[workspace]resolver = "2"-members = ["."]+members = [".", "kernels"][package]name = "cap-desktop-gpui"@@ -33,6 +33,7 @@ osx_url_schemes = ["cap-desktop"][dependencies]cap-audio = { path = "../../crates/audio" }+cap-gpui-kernels = { path = "kernels" }# gpui — the wingleeio/zed fork Comet ships. The pinned rev carries f596cde# ("destination alpha on transparent windows: Porter-Duff OVER, not additive"),# which our transparent rounded main-window shell depends on.@@ -116,7 +117,6 @@ smallvec = "1"unicode-segmentation = "1"# spawn_blocking for finalize; the runtime itself comes from gpui_tokio.tokio = { version = "1", features = ["rt", "time"] }-md-5 = "0.10"# The same crate `tauri_plugin_global_shortcut` wraps, at the Tauri app's pin:# store bindings are W3C `KeyboardEvent.code` strings and this owns the# platform mapping (Carbon RegisterEventHotKey on macOS).@@ -257,22 +257,22 @@ gpui_tokio = { path = "../../../zed-cap/crates/gpui_tokio" }# build deps at opt-level 2 and keep the app crate itself at 0.opt-level = 0# Incremental caches for this dep tree run to gigabytes on a disk that has-# already been filled to zero once; the app crate is small enough that full-# recompiles cost seconds.+# already been filled to zero once; a full app-crate recompile at opt-level 0+# costs about a minute, and `dev.sh` opts back in for its own loop.incremental = false[profile.dev.package."*"]opt-level = 2+# Full debug info for every dependency made a 1 GB Windows PDB that every+# relink rewrote; line tables keep file:line backtraces through dependencies.+debug = "line-tables-only"-# ...and the app crate too, since the editor landed. `frame_image` un-pads and-# BGRA-swaps a 1080x702 frame per displayed frame, which is 3MB of per-pixel-# work on this side of the seam: at opt-level 0 it measures **30.1ms** and the-# preview is convert-bound at 33fps with 45% of the renderer's frames dropped;-# at opt-level 2 it is **0.92ms**, and playback holds 59.9fps with zero drops.-# A dev build that cannot show the editor at its real speed is a dev build that-# will get the wrong answer out of every later editor unit. Costs ~7s a build.-[profile.dev.package.cap-desktop-gpui]-opt-level = 2+# The app crate stays at opt-level 0; its per-frame pixel and sample loops live+# in `cap-gpui-kernels` instead. `frame_image` alone measures 42.7ms per frame+# unoptimized against 1.0ms here, and optimizing the whole app crate instead+# turns a one-line edit into a 6-minute rebuild.+[profile.dev.package.cap-gpui-kernels]+opt-level = 3[profile.release]lto = "thin"diff --git a/apps/desktop-gpui/README.md b/apps/desktop-gpui/README.mdindex 00cbc2a14..86b84671a 100644--- a/apps/desktop-gpui/README.md+++ b/apps/desktop-gpui/README.md@@ -16,12 +16,19 @@ cargo run`RUST_LOG=cap_gpui=debug cargo run` for logs — note the filter is `cap_gpui`(the binary), not `cap_desktop_gpui` (the package).-The first build takes a few minutes and about 8 GB of `target/`: gpui pulls its-own revisions of the wgpu and font stacks. Rebuilds after that are seconds —-the dependencies build at `opt-level = 2` and so, since the editor landed, does-the app crate: the editor's per-frame pixel conversion is 30ms unoptimised and-0.92ms optimised, which is the difference between a 33fps preview and a 60fps-one (see the editor's measurements below).+The first build takes about 11 minutes and 6.4 GB of `target/`: gpui pulls its+own revisions of the wgpu and font stacks. After that, an edit rebuilds only+the app crate, which stays at `opt-level = 0`: about 75s with `cargo build` and+35s in the dev loop below. Dependencies build at `opt-level = 2` with line-table+debug info.++Loops over pixels or samples live in `kernels/` (`cap-gpui-kernels`,+`opt-level = 3`): unoptimised, the editor's frame conversion alone costs 42.7ms+a frame against 1.0ms, a 23fps preview instead of a 60fps one. That includes+generic dependency calls over large data — `imageops::resize`, image encoders,+`serde_json::from_reader`, `md5` — because a generic compiles into the crate+that instantiates it, at that crate's opt-level. Put the call in `kernels/`+behind a plain-slice function and call that from the app.### The dev loop@@ -49,8 +56,8 @@ doubles as that handshake — `dev.sh` will not kill the app while it reads`"recording":true`).The loop exports `CARGO_INCREMENTAL=1`, overriding this profile's-`incremental = false` for its own builds only: a warm rebuild drops from ~41s-to ~3s for a metadata-only change and ~23s for an edit to a 4k-line module.+`incremental = false` for its own builds only: a one-line edit to the app crate+rebuilds in about 35s instead of 75s.The costs are the ones the profile comment warns about, scoped down: a few GBof `target/debug/incremental` (delete it to reclaim), and a one-off app-craterebuild when switching between `./dev.sh` and a plain `cargo build`, whose@@ -1315,9 +1322,10 @@ crate at `opt-level = 0` the same conversion measures **30.1ms**, the pumpbecomes convert-bound at 33 fps and the bounded channel drops **45 %** of therenderer's frames (`playback fps=33.0 frames=523 dropped=423 …convert_avg=30149us`). Nothing about the architecture changes — it is a-3MB-per-frame per-pixel loop compiled without optimisation. `Cargo.toml` now-carries `[profile.dev.package.cap-desktop-gpui] opt-level = 2` so a dev build-shows the editor at its real speed; it costs about seven seconds a build.+3MB-per-frame per-pixel loop compiled without optimisation. The loop now lives+in `kernels/` (`cap_gpui_kernels::frame::unpad_rgba_to_bgra`), built at+`opt-level = 3`, so a dev build shows the editor at its real speed while the+app crate itself stays unoptimised (see [Running it](#running-it)).Reliability, same binary:diff --git a/apps/desktop-gpui/dev.sh b/apps/desktop-gpui/dev.shindex 49aa48d64..5dffb08f5 100755--- a/apps/desktop-gpui/dev.sh+++ b/apps/desktop-gpui/dev.sh@@ -10,7 +10,7 @@ STATE_FILE="$PWD/target/dev-restore.json"BIN="$PWD/target/debug/cap-gpui"BUILD=cargo-WATCH_PATHS=(src assets Cargo.toml ../desktop/src-tauri/sounds)+WATCH_PATHS=(src kernels/src assets Cargo.toml ../desktop/src-tauri/sounds)[ -d resources ] && WATCH_PATHS+=(resources)for crate in camera scap-targets recording timestamp utils project rendering editor export; do[ -d "../../crates/$crate/src" ] && WATCH_PATHS+=("../../crates/$crate/src")diff --git a/apps/desktop-gpui/kernels/Cargo.toml b/apps/desktop-gpui/kernels/Cargo.tomlnew file mode 100644index 000000000..83da91fd8--- /dev/null+++ b/apps/desktop-gpui/kernels/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "cap-gpui-kernels"+version = "0.1.0"+edition = "2024"+license = "AGPL-3.0"+publish = false++[dependencies]+cap-audio = { path = "../../../crates/audio" }+cap-project = { path = "../../../crates/project" }+image = { version = "0.25.1", default-features = false, features = ["jpeg", "png", "webp"] }+md-5 = "0.10"diff --git a/apps/desktop-gpui/kernels/src/codec.rs b/apps/desktop-gpui/kernels/src/codec.rsnew file mode 100644index 000000000..1e5d3e3ef--- /dev/null+++ b/apps/desktop-gpui/kernels/src/codec.rs@@ -0,0 +1,218 @@+use std::path::Path;++use ::md5::{Digest as _, Md5};+use image::ImageEncoder as _;++pub fn md5(bytes: &[u8]) -> [u8; 16] {+ let digest = Md5::digest(bytes);+ let mut output = [0; 16];+ output.copy_from_slice(&digest);+ output+}++pub fn parse_cursor_events(bytes: &[u8]) -> Result<cap_project::CursorEvents, String> {+ cap_project::CursorEvents::load_from_reader(bytes)+}++pub fn rgba_to_rgb(rgba: &[u8]) -> Vec<u8> {+ rgba.chunks_exact(4)+ .flat_map(|px| [px[0], px[1], px[2]])+ .collect()+}++pub fn encode_png_rgba(rgba: &[u8], width: u32, height: u32) -> image::ImageResult<Vec<u8>> {+ let mut png = std::io::Cursor::new(Vec::new());+ image::codecs::png::PngEncoder::new(&mut png).write_image(+ rgba,+ width,+ height,+ image::ExtendedColorType::Rgba8,+ )?;+ Ok(png.into_inner())+}++pub fn write_png_file(+ file: std::fs::File,+ data: &[u8],+ width: u32,+ height: u32,+ color: image::ExtendedColorType,+ compression: image::codecs::png::CompressionType,+ filter: image::codecs::png::FilterType,+) -> image::ImageResult<()> {+ let encoder = image::codecs::png::PngEncoder::new_with_quality(+ std::io::BufWriter::new(file),+ compression,+ filter,+ );+ encoder.write_image(data, width, height, color)+}++pub fn encode_jpeg_rgb(+ rgb: &[u8],+ width: u32,+ height: u32,+ quality: u8,+) -> image::ImageResult<Vec<u8>> {+ let mut buffer = Vec::new();+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buffer, quality).encode(+ rgb,+ width,+ height,+ image::ExtendedColorType::Rgb8,+ )?;+ Ok(buffer)+}++pub fn encode_jpeg_rgba_as_rgb(+ rgba: &image::RgbaImage,+ quality: u8,+) -> image::ImageResult<Vec<u8>> {+ use image::buffer::ConvertBuffer as _;+ let rgb: image::RgbImage = rgba.convert();+ let mut encoded = Vec::new();+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut encoded, quality).encode_image(&rgb)?;+ Ok(encoded)+}++pub fn save_rgb_image(+ rgb: &image::RgbImage,+ path: &Path,+ format: image::ImageFormat,+) -> image::ImageResult<()> {+ rgb.save_with_format(path, format)+}++pub fn open_image(path: &Path) -> image::ImageResult<image::DynamicImage> {+ image::open(path)+}++pub fn decode_image_file(path: &Path) -> Result<image::DynamicImage, String> {+ image::ImageReader::open(path)+ .map_err(|e| format!("Failed to open image: {e}"))?+ .with_guessed_format()+ .map_err(|e| format!("Failed to detect image format: {e}"))?+ .decode()+ .map_err(|e| format!("Failed to decode image: {e}"))+}++pub fn inspect_overlay_image(encoded: &[u8]) -> Result<(&'static str, u32, u32), String> {+ use image::ImageDecoder as _;+ let mut reader = image::ImageReader::new(std::io::Cursor::new(encoded))+ .with_guessed_format()+ .map_err(|error| error.to_string())?;+ let extension = match reader.format() {+ Some(image::ImageFormat::Png) => "png",+ Some(image::ImageFormat::Jpeg) => "jpg",+ Some(image::ImageFormat::WebP) => "webp",+ Some(image::ImageFormat::Gif) => "gif",+ Some(image::ImageFormat::Bmp) => "bmp",+ _ => return Err("Choose a PNG, JPEG, WebP, GIF or BMP image".into()),+ };+ let mut limits = image::Limits::default();+ limits.max_alloc = Some(128 * 1024 * 1024);+ limits.max_image_width = Some(32_768);+ limits.max_image_height = Some(32_768);+ reader.limits(limits);+ let mut decoder = reader.into_decoder().map_err(|error| {+ format!("Cannot decode image (maximum 32,768 pixels per side): {error}")+ })?;+ let (source_width, source_height) = decoder.dimensions();+ if source_width == 0+ || source_height == 0+ || u64::from(source_width) * u64::from(source_height) > 16_777_216+ || decoder.total_bytes() > 128 * 1024 * 1024+ {+ return Err("Images must have at most 16,777,216 pixels (32,768 per side) and decode to at most 128 MiB".into());+ }+ let orientation = decoder.orientation().map_err(|error| error.to_string())?;+ let mut decoded = image::DynamicImage::from_decoder(decoder)+ .map_err(|error| format!("Cannot decode image: {error}"))?;+ decoded.apply_orientation(orientation);+ Ok((extension, decoded.width(), decoded.height()))+}++pub fn decode_jpeg_to_bgra(bytes: &[u8]) -> Option<image::RgbaImage> {+ let decoded = image::load_from_memory_with_format(bytes, image::ImageFormat::Jpeg).ok()?;+ let mut rgba = decoded.into_rgba8();+ crate::frame::swap_red_blue(&mut rgba);+ Some(rgba)+}++pub fn compress_image_jpeg(path: &Path) -> Result<Vec<u8>, String> {+ let img = image::ImageReader::open(path)+ .map_err(|error| format!("Failed to open image: {error}"))?+ .decode()+ .map_err(|error| format!("Failed to decode image: {error}"))?;+ let resized = img.resize(+ img.width() / 2,+ img.height() / 2,+ image::imageops::FilterType::Nearest,+ );+ let mut buffer = Vec::new();+ let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buffer, 30);+ encoder+ .encode(+ resized.as_bytes(),+ resized.width(),+ resized.height(),+ resized.color().into(),+ )+ .map_err(|error| format!("Failed to compress image: {error}"))?;+ Ok(buffer)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn md5_matches_the_reference_digest() {+ assert_eq!(+ md5(b""),+ [+ 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8,+ 0x42, 0x7e+ ]+ );+ }++ #[test]+ fn rgba_to_rgb_drops_alpha() {+ assert_eq!(+ rgba_to_rgb(&[1, 2, 3, 4, 5, 6, 7, 8]),+ vec![1, 2, 3, 5, 6, 7]+ );+ }++ #[test]+ fn png_round_trips_rgba() {+ let rgba = [10, 20, 30, 40, 50, 60, 70, 255];+ let png = encode_png_rgba(&rgba, 2, 1).unwrap();+ let decoded = image::load_from_memory(&png).unwrap().to_rgba8();+ assert_eq!(decoded.as_raw(), &rgba);+ }++ #[test]+ fn jpeg_paths_agree_on_the_same_pixels() {+ let rgba = image::RgbaImage::from_fn(9, 7, |x, y| {+ image::Rgba([(x * 20) as u8, (y * 30) as u8, 90, 128])+ });+ let from_slice = encode_jpeg_rgb(&rgba_to_rgb(rgba.as_raw()), 9, 7, 80).unwrap();+ let from_image = encode_jpeg_rgba_as_rgb(&rgba, 80).unwrap();+ assert_eq!(from_slice, from_image);+ let bgra = decode_jpeg_to_bgra(&from_slice).unwrap();+ assert_eq!(bgra.dimensions(), (9, 7));+ }++ #[test]+ fn parses_cursor_events_and_reports_errors() {+ let events = parse_cursor_events(br#"{"clicks":[],"moves":[]}"#).unwrap();+ assert!(events.clicks.is_empty() && events.moves.is_empty());+ assert!(+ parse_cursor_events(b"{")+ .unwrap_err()+ .starts_with("Failed to parse cursor data: ")+ );+ }+}diff --git a/apps/desktop-gpui/kernels/src/frame.rs b/apps/desktop-gpui/kernels/src/frame.rsnew file mode 100644index 000000000..e22ddb6a1--- /dev/null+++ b/apps/desktop-gpui/kernels/src/frame.rs@@ -0,0 +1,135 @@+pub fn unpad_rows(data: &[u8], row_bytes: usize, stride: usize, rows: usize) -> Option<Vec<u8>> {+ if stride == 0 {+ return None;+ }+ let mut tight = Vec::with_capacity(row_bytes * rows);+ for row in data.chunks(stride).take(rows) {+ tight.extend_from_slice(row.get(..row_bytes)?);+ }+ Some(tight)+}++pub fn unpad_rgba_to_bgra(+ data: &[u8],+ width: usize,+ stride: usize,+ rows: usize,+) -> Option<Vec<u8>> {+ let mut tight = unpad_rows(data, width * 4, stride, rows)?;+ swap_red_blue(&mut tight);+ Some(tight)+}++pub fn swap_red_blue(pixels: &mut [u8]) {+ for pixel in pixels.chunks_exact_mut(4) {+ pixel.swap(0, 2);+ }+}++pub fn swap_red_blue_into(source: &[u8], target: &mut Vec<u8>) {+ target.clear();+ target.extend_from_slice(source);+ swap_red_blue(target);+}++pub fn copy_rows(+ data: &[u8],+ row_bytes: usize,+ stride: usize,+ rows: usize,+ mirrored: bool,+) -> Option<Vec<u8>> {+ if stride < row_bytes || data.len() < rows.checked_mul(stride)? {+ return None;+ }+ let mut pixels = vec![0; rows.checked_mul(row_bytes)?];+ for (row, output) in pixels.chunks_exact_mut(row_bytes.max(1)).enumerate() {+ let input = &data[row * stride..row * stride + row_bytes];+ if mirrored {+ for (target, source) in output.chunks_exact_mut(4).zip(input.chunks_exact(4).rev()) {+ target.copy_from_slice(source);+ }+ } else {+ output.copy_from_slice(input);+ }+ }+ Some(pixels)+}++pub fn downsample_nearest(+ data: &[u8],+ width: usize,+ height: usize,+ stride: usize,+ target_width: u32,+ target_height: u32,+) -> Vec<u8> {+ let target_width = target_width as usize;+ let target_height = target_height as usize;+ let mut pixels = Vec::with_capacity(target_width * target_height * 4);+ for y in 0..target_height {+ let row = &data[y * height / target_height * stride..];+ for x in 0..target_width {+ let offset = x * width / target_width * 4;+ pixels.extend_from_slice(&row[offset..offset + 4]);+ }+ }+ pixels+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn downsamples_with_nearest_source_pixels() {+ let source: Vec<u8> = (0..4u8)+ .flat_map(|y| (0..4u8).flat_map(move |x| [x, y, 0, 255]))+ .collect();+ assert_eq!(+ downsample_nearest(&source, 4, 4, 16, 2, 2),+ vec![0, 0, 0, 255, 2, 0, 0, 255, 0, 2, 0, 255, 2, 2, 0, 255]+ );+ }++ const PADDED: [u8; 20] = [+ 1, 2, 3, 4, 5, 6, 7, 8, 99, 99, //+ 9, 10, 11, 12, 13, 14, 15, 16, 99, 99,+ ];++ #[test]+ fn unpads_rows_and_swaps_red_and_blue() {+ assert_eq!(+ unpad_rgba_to_bgra(&PADDED, 2, 10, 2).unwrap(),+ vec![3, 2, 1, 4, 7, 6, 5, 8, 11, 10, 9, 12, 15, 14, 13, 16]+ );+ assert_eq!(unpad_rows(&PADDED, 8, 10, 1).unwrap(), PADDED[..8].to_vec());+ }++ #[test]+ fn rejects_short_rows_and_zero_stride() {+ assert_eq!(unpad_rgba_to_bgra(&[0; 12], 4, 12, 1), None);+ assert_eq!(unpad_rgba_to_bgra(&[0; 16], 4, 0, 1), None);+ }++ #[test]+ fn copies_rows_and_mirrors_each_row() {+ assert_eq!(+ copy_rows(&PADDED, 8, 10, 2, false).unwrap(),+ vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]+ );+ assert_eq!(+ copy_rows(&PADDED, 8, 10, 2, true).unwrap(),+ vec![5, 6, 7, 8, 1, 2, 3, 4, 13, 14, 15, 16, 9, 10, 11, 12]+ );+ assert_eq!(copy_rows(&PADDED, 8, 6, 2, false), None);+ assert_eq!(copy_rows(&PADDED, 8, 10, 3, false), None);+ }++ #[test]+ fn swaps_into_a_reused_buffer() {+ let mut target = vec![0; 99];+ swap_red_blue_into(&[1, 2, 3, 4], &mut target);+ assert_eq!(target, vec![3, 2, 1, 4]);+ }+}diff --git a/apps/desktop-gpui/kernels/src/lib.rs b/apps/desktop-gpui/kernels/src/lib.rsnew file mode 100644index 000000000..f35b4f5ed--- /dev/null+++ b/apps/desktop-gpui/kernels/src/lib.rs@@ -0,0 +1,6 @@+pub mod codec;+pub mod frame;+pub mod screenshot;+pub mod texture;+pub mod thumbnail;+pub mod waveform;diff --git a/apps/desktop-gpui/kernels/src/screenshot.rs b/apps/desktop-gpui/kernels/src/screenshot.rsnew file mode 100644index 000000000..f66551271--- /dev/null+++ b/apps/desktop-gpui/kernels/src/screenshot.rs@@ -0,0 +1,282 @@+pub fn is_opaque(rgba: &[u8]) -> bool {+ const ALPHA_MASK: u128 = 0xff000000ff000000ff000000ff000000;+ let mut blocks = rgba.chunks_exact(16);+ blocks+ .by_ref()+ .all(|block| u128::from_le_bytes(block.try_into().unwrap()) & ALPHA_MASK == ALPHA_MASK)+ && blocks+ .remainder()+ .iter()+ .skip(3)+ .step_by(4)+ .all(|&alpha| alpha == 255)+}++pub fn has_translucent_pixel(rgba: &[u8]) -> bool {+ rgba.iter().skip(3).step_by(4).any(|&alpha| alpha != 255)+}++pub fn flatten_onto_white(rgba: &[u8]) -> Vec<u8> {+ let mut rgba = rgba.to_vec();+ for pixel in rgba.chunks_exact_mut(4) {+ let alpha = u32::from(pixel[3]);+ for channel in &mut pixel[..3] {+ *channel = ((u32::from(*channel) * alpha + 255 * (255 - alpha) + 127) / 255) as u8;+ }+ pixel[3] = 255;+ }+ rgba+}++fn blend_pixel_over(dst: &mut [u8], src: [u8; 4]) {+ if src[3] == 0 {+ return;+ }+ if src[3] == 255 {+ dst.copy_from_slice(&src);+ return;+ }+ let sa = f32::from(src[3]) / 255.;+ let da = f32::from(dst[3]) / 255.;+ let oa = sa + da * (1. - sa);+ if oa <= 0. {+ dst.fill(0);+ return;+ }+ for channel in 0..3 {+ let s = f32::from(src[channel]);+ let d = f32::from(dst[channel]);+ dst[channel] = ((s * sa + d * da * (1. - sa)) / oa).round().clamp(0., 255.) as u8;+ }+ dst[3] = (oa * 255.).round() as u8;+}++pub fn blit_over(canvas: &mut [u8], size: (u32, u32), region: &image::RgbaImage, at: (u32, u32)) {+ let stride = size.0 as usize * 4;+ for (row_index, row) in region.rows().enumerate() {+ let y = at.1 as usize + row_index;+ if y >= size.1 as usize {+ break;+ }+ for (column_index, pixel) in row.enumerate() {+ let x = at.0 as usize + column_index;+ if x >= size.0 as usize {+ break;+ }+ let start = y * stride + x * 4;+ blend_pixel_over(&mut canvas[start..start + 4], pixel.0);+ }+ }+}++pub fn blit_over_offset(+ dst: &mut [u8],+ dst_size: (u32, u32),+ src: &[u8],+ src_size: (u32, u32),+ offset: (i64, i64),+) {+ let dst_stride = dst_size.0 as usize * 4;+ let src_stride = src_size.0 as usize * 4;+ for src_y in 0..src_size.1 as i64 {+ let dst_y = src_y + offset.1;+ if dst_y < 0 || dst_y >= i64::from(dst_size.1) {+ continue;+ }+ for src_x in 0..src_size.0 as i64 {+ let dst_x = src_x + offset.0;+ if dst_x < 0 || dst_x >= i64::from(dst_size.0) {+ continue;+ }+ let src_start = src_y as usize * src_stride + src_x as usize * 4;+ let dst_start = dst_y as usize * dst_stride + dst_x as usize * 4;+ let pixel = [+ src[src_start],+ src[src_start + 1],+ src[src_start + 2],+ src[src_start + 3],+ ];+ blend_pixel_over(&mut dst[dst_start..dst_start + 4], pixel);+ }+ }+}++pub fn premultiply(rgba: &mut [u8]) {+ for pixel in rgba.chunks_exact_mut(4) {+ let alpha = u16::from(pixel[3]);+ if alpha == 255 {+ continue;+ }+ for channel in &mut pixel[..3] {+ *channel = ((u16::from(*channel) * alpha + 127) / 255) as u8;+ }+ }+}++pub fn demultiply(rgba: &mut [u8]) {+ for pixel in rgba.chunks_exact_mut(4) {+ let alpha = u32::from(pixel[3]);+ if alpha == 255 || alpha == 0 {+ continue;+ }+ for channel in &mut pixel[..3] {+ let value = (u32::from(*channel) * 255 + alpha / 2) / alpha;+ *channel = value.min(255) as u8;+ }+ }+}++pub fn blend_rect_premultiplied(+ data: &mut [u8],+ size: (u32, u32),+ at: (f64, f64),+ rect: (u32, u32),+ color: [u8; 4],+) {+ let alpha = f32::from(color[3]) / 255.;+ if alpha <= 0. {+ return;+ }+ let src = [+ (f32::from(color[0]) * alpha).round() as u8,+ (f32::from(color[1]) * alpha).round() as u8,+ (f32::from(color[2]) * alpha).round() as u8,+ color[3],+ ];+ let inverse = 1. - alpha;+ let stride = size.0 as usize * 4;+ let x0 = at.0.round() as i64;+ let y0 = at.1.round() as i64;+ for row in 0..i64::from(rect.1) {+ let y = y0 + row;+ if y < 0 || y >= i64::from(size.1) {+ continue;+ }+ for column in 0..i64::from(rect.0) {+ let x = x0 + column;+ if x < 0 || x >= i64::from(size.0) {+ continue;+ }+ let start = y as usize * stride + x as usize * 4;+ for channel in 0..4 {+ let d = f32::from(data[start + channel]);+ data[start + channel] =+ (f32::from(src[channel]) + d * inverse).round().min(255.) as u8;+ }+ }+ }+}++pub fn mask_filter(+ rgba: &[u8],+ frame_width: u32,+ frame_height: u32,+ region: (u32, u32, u32, u32),+ pixelate: bool,+ level: f64,+) -> Option<image::RgbaImage> {+ if frame_width == 0 || frame_height == 0 {+ return None;+ }+ let stride = frame_width as usize * 4;+ if rgba.len() < stride * frame_height as usize {+ return None;+ }++ let (x0, y0, width, height) = region;+ let mut copied = Vec::with_capacity(width as usize * height as usize * 4);+ for row in 0..height {+ let start = (y0 + row) as usize * stride + x0 as usize * 4;+ copied.extend_from_slice(&rgba[start..start + width as usize * 4]);+ }+ let source = image::RgbaImage::from_raw(width, height, copied)?;++ let processed = if pixelate {+ let block = (level.round() as u32).max(2);+ let small = image::imageops::resize(+ &source,+ (width / block).max(1),+ (height / block).max(1),+ image::imageops::FilterType::Nearest,+ );+ image::imageops::resize(&small, width, height, image::imageops::FilterType::Nearest)+ } else {+ let factor = ((level / 4.).round() as u32).max(2);+ let small = image::imageops::resize(+ &source,+ (width / factor).max(1),+ (height / factor).max(1),+ image::imageops::FilterType::Triangle,+ );+ image::imageops::resize(&small, width, height, image::imageops::FilterType::Triangle)+ };++ Some(processed)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn reference_flatten(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {+ let mut out = vec![255; rgba.len()];+ blit_over_offset(&mut out, (width, height), rgba, (width, height), (0, 0));+ out+ }++ #[test]+ fn white_flatten_matches_source_over_for_every_channel_and_alpha() {+ let rgba: Vec<u8> = (0..=255u8)+ .flat_map(|alpha| {+ (0..=255u8).flat_map(move |channel| {+ [channel, 255 - channel, channel.wrapping_mul(17), alpha]+ })+ })+ .collect();+ assert_eq!(+ flatten_onto_white(&rgba),+ reference_flatten(&rgba, 256, 256)+ );+ }++ #[test]+ fn opacity_check_matches_individual_alpha_bytes_at_block_boundaries() {+ for length in 0..130 {+ let opaque = vec![255; length];+ assert!(is_opaque(&opaque));+ assert!(!has_translucent_pixel(&opaque));+ for changed_byte in 0..length {+ let mut rgba = opaque.clone();+ rgba[changed_byte] = 127;+ let expected = rgba.iter().skip(3).step_by(4).all(|&alpha| alpha == 255);+ assert_eq!(is_opaque(&rgba), expected);+ assert_eq!(has_translucent_pixel(&rgba), !expected);+ }+ }+ }++ #[test]+ fn flattening_an_opaque_canvas_is_the_identity() {+ let rgba = vec![10, 20, 30, 255, 40, 50, 60, 255];+ assert_eq!(flatten_onto_white(&rgba), rgba);+ }++ #[test]+ fn premultiply_roundtrip_is_exact_for_opaque_pixels() {+ let mut rgba = vec![13, 200, 91, 255, 1, 2, 3, 0];+ premultiply(&mut rgba);+ demultiply(&mut rgba);+ assert_eq!(rgba, vec![13, 200, 91, 255, 0, 0, 0, 0]);+ }++ #[test]+ fn mask_filter_returns_the_region_size_and_rejects_short_frames() {+ let rgba: Vec<u8> = (0..16u32 * 12 * 4).map(|value| value as u8).collect();+ for pixelate in [false, true] {+ let filtered = mask_filter(&rgba, 16, 12, (2, 3, 9, 7), pixelate, 8.).unwrap();+ assert_eq!(filtered.dimensions(), (9, 7));+ }+ assert!(mask_filter(&rgba[..10], 16, 12, (0, 0, 1, 1), true, 8.).is_none());+ assert!(mask_filter(&rgba, 0, 12, (0, 0, 1, 1), true, 8.).is_none());+ }+}diff --git a/apps/desktop-gpui/kernels/src/texture.rs b/apps/desktop-gpui/kernels/src/texture.rsnew file mode 100644index 000000000..2949e5923--- /dev/null+++ b/apps/desktop-gpui/kernels/src/texture.rs@@ -0,0 +1,272 @@+pub fn noise_texture_bgra(width: u32, height: u32, base_frequency: f32) -> image::RgbaImage {+ let mut rgba = image::RgbaImage::new(width.max(1), height.max(1));+ for (x, y, pixel) in rgba.enumerate_pixels_mut() {+ let value = fractal_noise(x as f32 * base_frequency, y as f32 * base_frequency, 0);+ let alpha = fractal_noise(x as f32 * base_frequency, y as f32 * base_frequency, 7);+ let level = (value.clamp(0., 1.) * 255.) as u8;+ *pixel = image::Rgba([level, level, level, (alpha.clamp(0., 1.) * 255.) as u8]);+ }+ rgba+}++fn fractal_noise(x: f32, y: f32, seed: u32) -> f32 {+ fractal_noise_octaves(x, y, seed, 4)+}++pub fn fractal_noise_octaves(x: f32, y: f32, seed: u32, octaves: u32) -> f32 {+ let (mut value, mut amplitude, mut total, mut frequency) = (0., 1., 0., 1.);+ for octave in 0..octaves {+ value += amplitude * value_noise(x * frequency, y * frequency, seed + octave);+ total += amplitude;+ amplitude *= 0.5;+ frequency *= 2.;+ }+ value / total+}++fn value_noise(x: f32, y: f32, seed: u32) -> f32 {+ let (x0, y0) = (x.floor(), y.floor());+ let (fx, fy) = (x - x0, y - y0);+ let (sx, sy) = (fx * fx * (3. - 2. * fx), fy * fy * (3. - 2. * fy));+ let (x0, y0) = (x0 as i32, y0 as i32);+ let corner = |dx: i32, dy: i32| lattice(x0 + dx, y0 + dy, seed);+ let top = corner(0, 0) + sx * (corner(1, 0) - corner(0, 0));+ let bottom = corner(0, 1) + sx * (corner(1, 1) - corner(0, 1));+ top + sy * (bottom - top)+}++fn lattice(x: i32, y: i32, seed: u32) -> f32 {+ let mut hash = (x as u32)+ .wrapping_mul(374_761_393)+ .wrapping_add((y as u32).wrapping_mul(668_265_263))+ .wrapping_add(seed.wrapping_mul(2_246_822_519));+ hash = (hash ^ (hash >> 13)).wrapping_mul(1_274_126_177);+ f32::from((hash ^ (hash >> 16)) as u16) / 65_535.+}++#[derive(Debug, Clone, Copy, PartialEq)]+pub enum Filter {+ Contrast(f32),+ Saturate(f32),+ Grayscale(f32),+ Brightness(f32),+ Sepia(f32),+ HueRotate(f32),+}++#[derive(Debug, Clone, Copy)]+pub struct Overlay {+ pub angle: f32,+ pub from: [f32; 4],+ pub to: [f32; 4],+}++pub const SCENE_ANGLE: f32 = 160.;+pub const SCENE_STOPS: [(f32, [f32; 3]); 4] = [+ (+ 0.00,+ [0x60 as f32 / 255., 0xa5 as f32 / 255., 0xfa as f32 / 255.],+ ),+ (+ 0.35,+ [0xe2 as f32 / 255., 0xe8 as f32 / 255., 0xf0 as f32 / 255.],+ ),+ (+ 0.62,+ [0xfb as f32 / 255., 0x92 as f32 / 255., 0x3c as f32 / 255.],+ ),+ (+ 1.00,+ [0x1e as f32 / 255., 0x29 as f32 / 255., 0x3b as f32 / 255.],+ ),+];++pub fn gradient_position(x: f32, y: f32, width: f32, height: f32, angle: f32) -> f32 {+ let radians = angle.to_radians();+ let (sin, cos) = (radians.sin(), radians.cos());+ let length = (width * sin).abs() + (height * cos).abs();+ if length <= 0. {+ return 0.;+ }+ let (dx, dy) = (x - width / 2., y - height / 2.);+ (0.5 + (dx * sin - dy * cos) / length).clamp(0., 1.)+}++pub fn gradient_color(position: f32, stops: &[(f32, [f32; 3])]) -> [f32; 3] {+ let mut previous = stops[0];+ for stop in stops {+ if position <= stop.0 {+ if stop.0 <= previous.0 {+ return stop.1;+ }+ let t = (position - previous.0) / (stop.0 - previous.0);+ return [+ previous.1[0] + t * (stop.1[0] - previous.1[0]),+ previous.1[1] + t * (stop.1[1] - previous.1[1]),+ previous.1[2] + t * (stop.1[2] - previous.1[2]),+ ];+ }+ previous = *stop;+ }+ previous.1+}++pub fn apply_filter(color: [f32; 3], filter: Filter) -> [f32; 3] {+ let clamp = |value: f32| value.clamp(0., 1.);+ let [r, g, b] = color;+ let out = match filter {+ Filter::Brightness(amount) => [r * amount, g * amount, b * amount],+ Filter::Contrast(amount) => [+ (r - 0.5) * amount + 0.5,+ (g - 0.5) * amount + 0.5,+ (b - 0.5) * amount + 0.5,+ ],+ Filter::Saturate(amount) | Filter::Grayscale(amount) => {+ let amount = if matches!(filter, Filter::Grayscale(_)) {+ 1. - amount+ } else {+ amount+ };+ [+ (0.213 + 0.787 * amount) * r+ + (0.715 - 0.715 * amount) * g+ + (0.072 - 0.072 * amount) * b,+ (0.213 - 0.213 * amount) * r+ + (0.715 + 0.285 * amount) * g+ + (0.072 - 0.072 * amount) * b,+ (0.213 - 0.213 * amount) * r+ + (0.715 - 0.715 * amount) * g+ + (0.072 + 0.928 * amount) * b,+ ]+ }+ Filter::Sepia(amount) => {+ let lerp = |identity: f32, sepia: f32| identity + amount * (sepia - identity);+ [+ lerp(1., 0.393) * r + lerp(0., 0.769) * g + lerp(0., 0.189) * b,+ lerp(0., 0.349) * r + lerp(1., 0.686) * g + lerp(0., 0.168) * b,+ lerp(0., 0.272) * r + lerp(0., 0.534) * g + lerp(1., 0.131) * b,+ ]+ }+ Filter::HueRotate(degrees) => {+ let radians = degrees.to_radians();+ let (sin, cos) = (radians.sin(), radians.cos());+ [+ (0.213 + cos * 0.787 - sin * 0.213) * r+ + (0.715 - cos * 0.715 - sin * 0.715) * g+ + (0.072 - cos * 0.072 + sin * 0.928) * b,+ (0.213 - cos * 0.213 + sin * 0.143) * r+ + (0.715 + cos * 0.285 + sin * 0.140) * g+ + (0.072 - cos * 0.072 - sin * 0.283) * b,+ (0.213 - cos * 0.213 - sin * 0.787) * r+ + (0.715 - cos * 0.715 + sin * 0.715) * g+ + (0.072 + cos * 0.928 + sin * 0.072) * b,+ ]+ }+ };+ [clamp(out[0]), clamp(out[1]), clamp(out[2])]+}++pub fn apply_filters(color: [f32; 3], filters: &[Filter]) -> [f32; 3] {+ filters+ .iter()+ .fold(color, |color, filter| apply_filter(color, *filter))+}++pub fn overlay_blend(backdrop: f32, source: f32) -> f32 {+ if backdrop <= 0.5 {+ 2. * backdrop * source+ } else {+ 1. - 2. * (1. - backdrop) * (1. - source)+ }+}++pub fn composite_overlay(backdrop: [f32; 3], source: [f32; 4]) -> [f32; 3] {+ let alpha = source[3];+ [+ alpha * overlay_blend(backdrop[0], source[0]) + (1. - alpha) * backdrop[0],+ alpha * overlay_blend(backdrop[1], source[1]) + (1. - alpha) * backdrop[1],+ alpha * overlay_blend(backdrop[2], source[2]) + (1. - alpha) * backdrop[2],+ ]+}++pub fn vignette_alpha(x: f32, y: f32, width: f32, height: f32, vignette: f32) -> f32 {+ if vignette <= 0. {+ return 0.;+ }+ let (rx, ry) = (+ width / 2. * std::f32::consts::SQRT_2,+ height / 2. * std::f32::consts::SQRT_2,+ );+ let (dx, dy) = ((x - width / 2.) / rx, (y - height / 2.) / ry);+ let distance = (dx * dx + dy * dy).sqrt();+ let peak = ((vignette * 0.75) * 1000.).round() / 1000.;+ (((distance - 0.4) / 0.6).clamp(0., 1.)) * peak+}++pub fn preset_preview_bgra(+ filter: &[Filter],+ overlay: Option<Overlay>,+ vignette: f32,+ grain: f32,+ width: u32,+ height: u32,+) -> image::RgbaImage {+ let (w, h) = (width.max(1), height.max(1));+ let (wf, hf) = (w as f32, h as f32);+ let mut rgba = image::RgbaImage::new(w, h);+ let grain_opacity = (grain * 1.2).min(1.);++ for (x, y, pixel) in rgba.enumerate_pixels_mut() {+ let (xf, yf) = (x as f32 + 0.5, y as f32 + 0.5);+ let scene = gradient_color(gradient_position(xf, yf, wf, hf, SCENE_ANGLE), &SCENE_STOPS);+ let mut color = apply_filters(scene, filter);++ if let Some(overlay) = overlay {+ let position = gradient_position(xf, yf, wf, hf, overlay.angle);+ let source = [+ overlay.from[0] + position * (overlay.to[0] - overlay.from[0]),+ overlay.from[1] + position * (overlay.to[1] - overlay.from[1]),+ overlay.from[2] + position * (overlay.to[2] - overlay.from[2]),+ overlay.from[3] + position * (overlay.to[3] - overlay.from[3]),+ ];+ color = composite_overlay(color, source);+ }++ let shade = 1. - vignette_alpha(xf, yf, wf, hf, vignette);+ color = [color[0] * shade, color[1] * shade, color[2] * shade];++ if grain_opacity > 0. {+ let level = fractal_noise_octaves(xf * 0.9 / 2., yf * 0.9 / 2., 11, 2).clamp(0., 1.);+ color = composite_overlay(color, [level, level, level, grain_opacity]);+ }++ let byte = |value: f32| (value.clamp(0., 1.) * 255.).round() as u8;+ *pixel = image::Rgba([byte(color[2]), byte(color[1]), byte(color[0]), 255]);+ }++ rgba+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn noise_texture_has_the_requested_size_and_grey_channels() {+ let texture = noise_texture_bgra(13, 0, 0.9);+ assert_eq!(texture.dimensions(), (13, 1));+ for pixel in texture.pixels() {+ assert_eq!(pixel.0[0], pixel.0[1]);+ assert_eq!(pixel.0[1], pixel.0[2]);+ }+ }++ #[test]+ fn preset_preview_is_opaque_bgra_at_the_requested_size() {+ let preview = preset_preview_bgra(&[Filter::Grayscale(1.)], None, 0.32, 0.35, 21, 9);+ assert_eq!(preview.dimensions(), (21, 9));+ for pixel in preview.pixels() {+ assert_eq!(pixel.0[3], 255);+ }+ }+}diff --git a/apps/desktop-gpui/kernels/src/thumbnail.rs b/apps/desktop-gpui/kernels/src/thumbnail.rsnew file mode 100644index 000000000..b564601ad--- /dev/null+++ b/apps/desktop-gpui/kernels/src/thumbnail.rs@@ -0,0 +1,41 @@+use image::RgbaImage;++pub fn fit_centered(image: &RgbaImage, target_width: u32, target_height: u32) -> RgbaImage {+ let width = image.width();+ let height = image.height();++ if width == target_width && height == target_height {+ return image.clone();+ }++ if width == 0 || height == 0 {+ return RgbaImage::from_pixel(target_width, target_height, image::Rgba([0, 0, 0, 0]));+ }++ let scale = (target_width as f32 / width as f32)+ .min(target_height as f32 / height as f32)+ .max(f32::MIN_POSITIVE);++ let scaled_width = (width as f32 * scale)+ .round()+ .clamp(1.0, target_width as f32) as u32;+ let scaled_height = (height as f32 * scale)+ .round()+ .clamp(1.0, target_height as f32) as u32;++ let resized = image::imageops::resize(+ image,+ scaled_width.max(1),+ scaled_height.max(1),+ image::imageops::FilterType::Lanczos3,+ );++ let mut canvas = RgbaImage::from_pixel(target_width, target_height, image::Rgba([0, 0, 0, 0]));++ let offset_x = (target_width - scaled_width) / 2;+ let offset_y = (target_height - scaled_height) / 2;++ image::imageops::overlay(&mut canvas, &resized, offset_x as i64, offset_y as i64);++ canvas+}diff --git a/apps/desktop-gpui/kernels/src/waveform.rs b/apps/desktop-gpui/kernels/src/waveform.rsnew file mode 100644index 000000000..73b862fc8--- /dev/null+++ b/apps/desktop-gpui/kernels/src/waveform.rs@@ -0,0 +1,3 @@+pub fn peaks(blocks: &[&[f32]], channels: u16) -> Vec<f32> {+ cap_audio::waveform_peaks(blocks.iter().flat_map(|block| block.iter()), channels)+}diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rsindex 539e0dbff..8dfff17bd 100644--- a/apps/desktop-gpui/src/app_windows.rs+++ b/apps/desktop-gpui/src/app_windows.rs@@ -5351,7 +5351,7 @@ fn load_editor_waveforms(.map(|audio| {Arc::new(match audio {Some(audio) => editor_timeline::waveform_peaks(- audio.sample_slices().flatten(),+ &audio.sample_slices().collect::<Vec<_>>(),audio.channels(),),None => Vec::new(),diff --git a/apps/desktop-gpui/src/camera_blur_portable.rs b/apps/desktop-gpui/src/camera_blur_portable.rsindex 735eebb74..0247ef09a 100644--- a/apps/desktop-gpui/src/camera_blur_portable.rs+++ b/apps/desktop-gpui/src/camera_blur_portable.rs@@ -130,12 +130,7 @@ impl PortableCameraBlur {}self.ensure_resources(width, height)?;- self.rgba.clear();- self.rgba.reserve(expected_bytes);- for pixel in bgra.chunks_exact(4) {- self.rgba- .extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]);- }+ cap_gpui_kernels::frame::swap_red_blue_into(bgra, &mut self.rgba);let source = self.source.as_ref().context("camera blur source missing")?;self.queue.write_texture(@@ -210,18 +205,17 @@ impl PortableCameraBlur {.context("camera blur GPU readback channel")?.map_err(|error| anyhow!("camera blur GPU readback: {error}"))?;- let mut pixels = Vec::with_capacity(expected_bytes);- {+ let pixels = {let mapped = readback.slice(..).get_mapped_range();- let padded = self.padded_bytes_per_row as usize;- let row = row_bytes as usize;- for source in mapped.chunks_exact(padded).take(height as usize) {- for pixel in source[..row].chunks_exact(4) {- pixels.extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]);- }- }- }+ cap_gpui_kernels::frame::unpad_rgba_to_bgra(+ &mapped,+ width as usize,+ self.padded_bytes_per_row as usize,+ height as usize,+ )+ };readback.unmap();+ let pixels = pixels.context("camera blur readback rows")?;let image = image::RgbaImage::from_raw(width, height, pixels).context("camera blur output image")?;diff --git a/apps/desktop-gpui/src/camera_window.rs b/apps/desktop-gpui/src/camera_window.rsindex 59240b712..73f41ae2a 100644--- a/apps/desktop-gpui/src/camera_window.rs+++ b/apps/desktop-gpui/src/camera_window.rs@@ -895,14 +895,17 @@ pub(crate) fn snapshot_preview(let scale = (960. / width as f64).min(540. / height as f64).min(1.);let target_width = (width as f64 * scale).round().max(1.) as u32;let target_height = (height as f64 * scale).round().max(1.) as u32;- let image = image::RgbaImage::from_fn(target_width, target_height, |x, y| {- let source_x = x as usize * width / target_width as usize;- let source_y = y as usize * height / target_height as usize;- let offset = source_y * stride + source_x * 4;- let pixel = unsafe { std::slice::from_raw_parts(base.add(offset), 4) };- // RenderImage consumes BGRA bytes even though image::Frame wraps RgbaImage.- image::Rgba([pixel[0], pixel[1], pixel[2], pixel[3]])- });+ let data = unsafe { std::slice::from_raw_parts(base, required_bytes) };+ // RenderImage consumes BGRA bytes even though image::Frame wraps RgbaImage.+ let pixels = cap_gpui_kernels::frame::downsample_nearest(+ data,+ width,+ height,+ stride,+ target_width,+ target_height,+ );+ let image = image::RgbaImage::from_raw(target_width, target_height, pixels)?;Some(Arc::new(gpui::RenderImage::new(smallvec::smallvec![image::Frame::new(image)])))diff --git a/apps/desktop-gpui/src/editor_color.rs b/apps/desktop-gpui/src/editor_color.rsindex 13393aee3..a3948bee9 100644--- a/apps/desktop-gpui/src/editor_color.rs+++ b/apps/desktop-gpui/src/editor_color.rs@@ -37,6 +37,7 @@use std::sync::Arc;+pub use cap_gpui_kernels::texture::{Filter, Overlay};use cap_project::{ColorCorrection, ProjectConfiguration};use gpui::{AnyElement, Context, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement,@@ -100,27 +101,6 @@ pub const IDENTITY: GradeValues = GradeValues {grain: 0.,};-/// One CSS shorthand filter function. The chain per preset is the source's-/// `preview.filter` string, parsed here into its terms once and for all.-#[derive(Debug, Clone, Copy, PartialEq)]-pub enum Filter {- Contrast(f32),- Saturate(f32),- Grayscale(f32),- Brightness(f32),- Sepia(f32),- HueRotate(f32),-}--/// `preview.overlay` -- a two-stop `linear-gradient` in rgba, painted at-/// `mix-blend-mode: overlay`.-#[derive(Debug, Clone, Copy)]-pub struct Overlay {- pub angle: f32,- pub from: [f32; 4],- pub to: [f32; 4],-}-pub struct ColorPreset {pub id: &'static str,pub label: &'static str,@@ -425,225 +405,22 @@ impl GradeSlider {// The preview, computed// ----------------------------------------------------------------------------/// `COLOR_PREVIEW_SCENE`: `linear-gradient(160deg, #60a5fa 0%, #e2e8f0 35%,-/// #fb923c 62%, #1e293b 100%)` (`colorCorrection.ts:53-54`).-const SCENE_ANGLE: f32 = 160.;-const SCENE_STOPS: [(f32, [f32; 3]); 4] = [- (- 0.00,- [0x60 as f32 / 255., 0xa5 as f32 / 255., 0xfa as f32 / 255.],- ),- (- 0.35,- [0xe2 as f32 / 255., 0xe8 as f32 / 255., 0xf0 as f32 / 255.],- ),- (- 0.62,- [0xfb as f32 / 255., 0x92 as f32 / 255., 0x3c as f32 / 255.],- ),- (- 1.00,- [0x1e as f32 / 255., 0x29 as f32 / 255., 0x3b as f32 / 255.],- ),-];-/// The tile: `aspect-video` inside a `grid-cols-3 gap-2` in the sidebar's/// 382px content column, each button `p-1.5` with a 1px border. Generated at/// 2x so it is sharp on a Retina panel.pub const PREVIEW_WIDTH: u32 = 216;pub const PREVIEW_HEIGHT: u32 = 122;-/// Where a pixel sits along a CSS gradient line, in `[0, 1]`.-///-/// The line runs through the box centre at `angle` clockwise from "to top", so-/// its direction in screen coordinates (y down) is `(sin a, -cos a)`, and its-/// length is `|w sin a| + |h cos a|` -- the projection of the box onto it.-pub fn gradient_position(x: f32, y: f32, width: f32, height: f32, angle: f32) -> f32 {- let radians = angle.to_radians();- let (sin, cos) = (radians.sin(), radians.cos());- let length = (width * sin).abs() + (height * cos).abs();- if length <= 0. {- return 0.;- }- let (dx, dy) = (x - width / 2., y - height / 2.);- (0.5 + (dx * sin - dy * cos) / length).clamp(0., 1.)-}--/// Linear interpolation between stops, in sRGB -- the default interpolation-/// space for a CSS gradient with no `in <space>` clause.-fn gradient_color(position: f32, stops: &[(f32, [f32; 3])]) -> [f32; 3] {- let mut previous = stops[0];- for stop in stops {- if position <= stop.0 {- if stop.0 <= previous.0 {- return stop.1;- }- let t = (position - previous.0) / (stop.0 - previous.0);- return [- previous.1[0] + t * (stop.1[0] - previous.1[0]),- previous.1[1] + t * (stop.1[1] - previous.1[1]),- previous.1[2] + t * (stop.1[2] - previous.1[2]),- ];- }- previous = *stop;- }- previous.1-}--/// One CSS filter function, in sRGB.-///-/// The Filter Effects spec defines the shorthand functions as SVG filter-/// primitives with `color-interpolation-filters: sRGB`, so no linearisation-/// happens -- which is why `brightness(1.1)` is a plain multiply here.-/// Intermediate results clamp, as a browser's 8-bit filter chain does.-pub fn apply_filter(color: [f32; 3], filter: Filter) -> [f32; 3] {- let clamp = |value: f32| value.clamp(0., 1.);- let [r, g, b] = color;- let out = match filter {- Filter::Brightness(amount) => [r * amount, g * amount, b * amount],- Filter::Contrast(amount) => [- (r - 0.5) * amount + 0.5,- (g - 0.5) * amount + 0.5,- (b - 0.5) * amount + 0.5,- ],- // `grayscale(a)` is defined as the saturate matrix at `1 - a`.- Filter::Saturate(amount) | Filter::Grayscale(amount) => {- let amount = if matches!(filter, Filter::Grayscale(_)) {- 1. - amount- } else {- amount- };- [- (0.213 + 0.787 * amount) * r- + (0.715 - 0.715 * amount) * g- + (0.072 - 0.072 * amount) * b,- (0.213 - 0.213 * amount) * r- + (0.715 + 0.285 * amount) * g- + (0.072 - 0.072 * amount) * b,- (0.213 - 0.213 * amount) * r- + (0.715 - 0.715 * amount) * g- + (0.072 + 0.928 * amount) * b,- ]- }- // The sepia matrix, lerped against the identity by `amount`.- Filter::Sepia(amount) => {- let lerp = |identity: f32, sepia: f32| identity + amount * (sepia - identity);- [- lerp(1., 0.393) * r + lerp(0., 0.769) * g + lerp(0., 0.189) * b,- lerp(0., 0.349) * r + lerp(1., 0.686) * g + lerp(0., 0.168) * b,- lerp(0., 0.272) * r + lerp(0., 0.534) * g + lerp(1., 0.131) * b,- ]- }- Filter::HueRotate(degrees) => {- let radians = degrees.to_radians();- let (sin, cos) = (radians.sin(), radians.cos());- [- (0.213 + cos * 0.787 - sin * 0.213) * r- + (0.715 - cos * 0.715 - sin * 0.715) * g- + (0.072 - cos * 0.072 + sin * 0.928) * b,- (0.213 - cos * 0.213 + sin * 0.143) * r- + (0.715 + cos * 0.285 + sin * 0.140) * g- + (0.072 - cos * 0.072 - sin * 0.283) * b,- (0.213 - cos * 0.213 - sin * 0.787) * r- + (0.715 - cos * 0.715 + sin * 0.715) * g- + (0.072 + cos * 0.928 + sin * 0.072) * b,- ]- }- };- [clamp(out[0]), clamp(out[1]), clamp(out[2])]-}--pub fn apply_filters(color: [f32; 3], filters: &[Filter]) -> [f32; 3] {- filters- .iter()- .fold(color, |color, filter| apply_filter(color, *filter))-}--/// `mix-blend-mode: overlay` -- `HardLight(Cs, Cb)` with the operands swapped,-/// which is the Compositing spec's definition.-pub fn overlay_blend(backdrop: f32, source: f32) -> f32 {- if backdrop <= 0.5 {- 2. * backdrop * source- } else {- 1. - 2. * (1. - backdrop) * (1. - source)- }-}--/// Source-over of a blended layer whose own alpha is `alpha`, over an opaque-/// backdrop: `Co = a * B(Cb, Cs) + (1 - a) * Cb`.-fn composite_overlay(backdrop: [f32; 3], source: [f32; 4]) -> [f32; 3] {- let alpha = source[3];- [- alpha * overlay_blend(backdrop[0], source[0]) + (1. - alpha) * backdrop[0],- alpha * overlay_blend(backdrop[1], source[1]) + (1. - alpha) * backdrop[1],- alpha * overlay_blend(backdrop[2], source[2]) + (1. - alpha) * backdrop[2],- ]-}--/// `radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,v*0.75)-/// 100%)` (`ColorCorrectionSection.tsx:57-63`).-///-/// The default radial size is `farthest-corner`, and for an `ellipse at center`-/// that is the farthest-side ellipse scaled to pass through the corner, i.e.-/// both radii multiplied by sqrt(2).-pub fn vignette_alpha(x: f32, y: f32, width: f32, height: f32, vignette: f32) -> f32 {- if vignette <= 0. {- return 0.;- }- let (rx, ry) = (- width / 2. * std::f32::consts::SQRT_2,- height / 2. * std::f32::consts::SQRT_2,- );- let (dx, dy) = ((x - width / 2.) / rx, (y - height / 2.) / ry);- let distance = (dx * dx + dy * dy).sqrt();- // `toFixed(3)` on the stop's alpha, as the source writes it.- let peak = ((vignette * 0.75) * 1000.).round() / 1000.;- (((distance - 0.4) / 0.6).clamp(0., 1.)) * peak-}-/// One preset tile, rasterised.pub fn preset_preview(preset: &ColorPreset, width: u32, height: u32) -> Arc<RenderImage> {- let (w, h) = (width.max(1), height.max(1));- let (wf, hf) = (w as f32, h as f32);- let mut rgba = image::RgbaImage::new(w, h);- // `opacity: Math.min(1, grain * 1.2)` over a 64px tile at- // `baseFrequency 0.9`, `numOctaves 2` -- the source's `COLOR_PREVIEW_GRAIN`.- let grain_opacity = (preset.values.grain * 1.2).min(1.);-- for (x, y, pixel) in rgba.enumerate_pixels_mut() {- let (xf, yf) = (x as f32 + 0.5, y as f32 + 0.5);- let scene = gradient_color(gradient_position(xf, yf, wf, hf, SCENE_ANGLE), &SCENE_STOPS);- let mut color = apply_filters(scene, preset.filter);-- if let Some(overlay) = preset.overlay {- let position = gradient_position(xf, yf, wf, hf, overlay.angle);- let source = [- overlay.from[0] + position * (overlay.to[0] - overlay.from[0]),- overlay.from[1] + position * (overlay.to[1] - overlay.from[1]),- overlay.from[2] + position * (overlay.to[2] - overlay.from[2]),- overlay.from[3] + position * (overlay.to[3] - overlay.from[3]),- ];- color = composite_overlay(color, source);- }-- let shade = 1. - vignette_alpha(xf, yf, wf, hf, preset.values.vignette);- color = [color[0] * shade, color[1] * shade, color[2] * shade];-- if grain_opacity > 0. {- // The tile repeats every 64 device pixels in CSS; the preview is- // generated at 2x, so the tile is 128 pixels wide here.- let level =- crate::editor_sidebar::fractal_noise_octaves(xf * 0.9 / 2., yf * 0.9 / 2., 11, 2)- .clamp(0., 1.);- let grain = [level, level, level, grain_opacity];- color = composite_overlay(color, grain);- }-- let byte = |value: f32| (value.clamp(0., 1.) * 255.).round() as u8;- // BGRA, gpui's atlas order.- *pixel = image::Rgba([byte(color[2]), byte(color[1]), byte(color[0]), 255]);- }-+ let rgba = cap_gpui_kernels::texture::preset_preview_bgra(+ preset.filter,+ preset.overlay,+ preset.values.vignette,+ preset.values.grain,+ width,+ height,+ );Arc::new(RenderImage::new(smallvec::smallvec![image::Frame::new(rgba)]))@@ -897,6 +674,10 @@ impl EditorWindow {#[cfg(test)]mod tests {use super::*;+ use cap_gpui_kernels::texture::{+ SCENE_ANGLE, SCENE_STOPS, apply_filter, apply_filters, composite_overlay, gradient_color,+ gradient_position, overlay_blend, vignette_alpha,+ };#[test]fn the_catalogue_matches_the_source() {diff --git a/apps/desktop-gpui/src/editor_crop.rs b/apps/desktop-gpui/src/editor_crop.rsindex d888d3353..412b8f20c 100644--- a/apps/desktop-gpui/src/editor_crop.rs+++ b/apps/desktop-gpui/src/editor_crop.rs@@ -2311,9 +2311,7 @@ async fn decode_display_frame(};// gpui's `RenderImage` is BGRA behind an `RgbaImage`, which is the same// swap `editor_window::frame_image` does for the player's frames.- for pixel in rgba.chunks_exact_mut(4) {- pixel.swap(0, 2);- }+ cap_gpui_kernels::frame::swap_red_blue(&mut rgba);let buffer = image::RgbaImage::from_raw(width, height, rgba)?;Some(Arc::new(RenderImage::new(smallvec::smallvec![image::Frame::new(buffer)diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rsindex 5b3b44f97..4a05063ed 100644--- a/apps/desktop-gpui/src/editor_export.rs+++ b/apps/desktop-gpui/src/editor_export.rs@@ -432,11 +432,7 @@ fn format_estimate_range(range: [f64; 2], time: bool) -> String {}fn decode_jpeg_bytes(bytes: &[u8]) -> Option<Arc<RenderImage>> {- let decoded = image::load_from_memory_with_format(bytes, image::ImageFormat::Jpeg).ok()?;- let mut rgba = decoded.into_rgba8();- for pixel in rgba.chunks_exact_mut(4) {- pixel.swap(0, 2);- }+ let rgba = cap_gpui_kernels::codec::decode_jpeg_to_bgra(bytes)?;Some(Arc::new(RenderImage::new(smallvec::smallvec![image::Frame::new(rgba)])))diff --git a/apps/desktop-gpui/src/editor_preparing.rs b/apps/desktop-gpui/src/editor_preparing.rsindex 63641cf9d..15eeec23a 100644--- a/apps/desktop-gpui/src/editor_preparing.rs+++ b/apps/desktop-gpui/src/editor_preparing.rs@@ -709,7 +709,7 @@ fn adapt(is_live: || !*control.cancelled.borrow() && sources.live().is_some(),remaining: cursor_budget,});- let cursor = CursorEvents::load_from_reader(&mut reader)?;+ let cursor = read_cursor_events(&mut reader)?;cursor_budget = reader.get_ref().remaining;cursor} else {@@ -759,6 +759,14 @@ fn adapt())}+fn read_cursor_events(reader: &mut impl Read) -> Result<CursorEvents, String> {+ let mut bytes = Vec::new();+ reader+ .read_to_end(&mut bytes)+ .map_err(|error| format!("Failed to parse cursor data: {error}"))?;+ cap_gpui_kernels::codec::parse_cursor_events(&bytes)+}+struct CheckedCursorReader<R, F> {reader: R,is_live: F,@@ -853,7 +861,7 @@ mod tests {is_live: || true,remaining,};- let result = CursorEvents::load_from_reader(BufReader::new(reader));+ let result = read_cursor_events(&mut BufReader::new(reader));assert_eq!(result.is_ok(), remaining == bytes.len() as u64);}}diff --git a/apps/desktop-gpui/src/editor_sidebar.rs b/apps/desktop-gpui/src/editor_sidebar.rsindex 339dea45a..73afc538e 100644--- a/apps/desktop-gpui/src/editor_sidebar.rs+++ b/apps/desktop-gpui/src/editor_sidebar.rs@@ -590,60 +590,12 @@ pub fn noise_opacity(intensity: f32) -> f32 {/// `noise_scale` itself (`layers/background.rs:251-299`), so the player shows/// the real thing.fn noise_texture(width: u32, height: u32, base_frequency: f32) -> Arc<RenderImage> {- let mut rgba = image::RgbaImage::new(width.max(1), height.max(1));- for (x, y, pixel) in rgba.enumerate_pixels_mut() {- let value = fractal_noise(x as f32 * base_frequency, y as f32 * base_frequency, 0);- let alpha = fractal_noise(x as f32 * base_frequency, y as f32 * base_frequency, 7);- let level = (value.clamp(0., 1.) * 255.) as u8;- // BGRA, gpui's atlas order.- *pixel = image::Rgba([level, level, level, (alpha.clamp(0., 1.) * 255.) as u8]);- }+ let rgba = cap_gpui_kernels::texture::noise_texture_bgra(width, height, base_frequency);Arc::new(RenderImage::new(smallvec::smallvec![image::Frame::new(rgba)]))}-/// Four octaves, each twice the frequency and half the amplitude -- what-/// `numOctaves="4"` means.-fn fractal_noise(x: f32, y: f32, seed: u32) -> f32 {- fractal_noise_octaves(x, y, seed, 4)-}--/// The same, at whatever `numOctaves` the call site's `feTurbulence` declares.-/// The colour-grade previews' grain is `numOctaves="2"`-/// (`colorCorrection.ts:56`).-pub(crate) fn fractal_noise_octaves(x: f32, y: f32, seed: u32, octaves: u32) -> f32 {- let (mut value, mut amplitude, mut total, mut frequency) = (0., 1., 0., 1.);- for octave in 0..octaves {- value += amplitude * value_noise(x * frequency, y * frequency, seed + octave);- total += amplitude;- amplitude *= 0.5;- frequency *= 2.;- }- value / total-}--fn value_noise(x: f32, y: f32, seed: u32) -> f32 {- let (x0, y0) = (x.floor(), y.floor());- let (fx, fy) = (x - x0, y - y0);- // Smoothstep, as the spec's interpolant is smooth rather than linear.- let (sx, sy) = (fx * fx * (3. - 2. * fx), fy * fy * (3. - 2. * fy));- let (x0, y0) = (x0 as i32, y0 as i32);- let corner = |dx: i32, dy: i32| lattice(x0 + dx, y0 + dy, seed);- let top = corner(0, 0) + sx * (corner(1, 0) - corner(0, 0));- let bottom = corner(0, 1) + sx * (corner(1, 1) - corner(0, 1));- top + sy * (bottom - top)-}--fn lattice(x: i32, y: i32, seed: u32) -> f32 {- let mut hash = (x as u32)- .wrapping_mul(374_761_393)- .wrapping_add((y as u32).wrapping_mul(668_265_263))- .wrapping_add(seed.wrapping_mul(2_246_822_519));- hash = (hash ^ (hash >> 13)).wrapping_mul(1_274_126_177);- f32::from((hash ^ (hash >> 16)) as u16) / 65_535.-}-// ---------------------------------------------------------------------------// State// ---------------------------------------------------------------------------@@ -2024,8 +1976,8 @@ fn write_desktop_background_snapshot(source: &Path, output: &Path) -> Result<(),return Ok(());}- let decoded =- image::open(source).map_err(|err| format!("failed to decode desktop background: {err}"))?;+ let decoded = cap_gpui_kernels::codec::open_image(source)+ .map_err(|err| format!("failed to decode desktop background: {err}"))?;let decoded = if decoded.width() > DESKTOP_BACKGROUND_MAX_DIMENSION|| decoded.height() > DESKTOP_BACKGROUND_MAX_DIMENSION{@@ -2037,9 +1989,7 @@ fn write_desktop_background_snapshot(source: &Path, output: &Path) -> Result<(),} else {decoded};- decoded- .to_rgb8()- .save_with_format(output, image::ImageFormat::Jpeg)+ cap_gpui_kernels::codec::save_rgb_image(&decoded.to_rgb8(), output, image::ImageFormat::Jpeg).map_err(|err| format!("failed to save desktop background: {err}"))}diff --git a/apps/desktop-gpui/src/editor_timeline.rs b/apps/desktop-gpui/src/editor_timeline.rsindex 987bb776e..2313271d7 100644--- a/apps/desktop-gpui/src/editor_timeline.rs+++ b/apps/desktop-gpui/src/editor_timeline.rs@@ -512,8 +512,8 @@ fn visible_box(start: f64, end: f64, transform: Transform, secs_per_pixel: f64)// Waveform peaks// ----------------------------------------------------------------------------pub fn waveform_peaks<'a>(samples: impl IntoIterator<Item = &'a f32>, channels: u16) -> Vec<f32> {- cap_editor::waveform_peaks(samples.into_iter(), channels)+pub fn waveform_peaks(blocks: &[&[f32]], channels: u16) -> Vec<f32> {+ cap_gpui_kernels::waveform::peaks(blocks, channels)}/// `WAVEFORM_MIN_DB` / `WAVEFORM_SAMPLE_STEP` / `WAVEFORM_MUTE_DB`@@ -4408,18 +4408,18 @@ mod tests {fn peak_extraction_is_one_value_per_hundred_milliseconds() {// Two chunks of full-scale mono at the crate's own sample rate.let samples = vec![1.0f32; AUDIO_SAMPLE_RATE / 5];- let peaks = waveform_peaks(&samples, 1);+ let peaks = waveform_peaks(&[&samples], 1);assert_eq!(peaks.len(), 2);// 20 * log10(1.0) = 0 dBFS.assert!(peaks.iter().all(|value| value.abs() < 1e-4), "{peaks:?}");// Stereo halves the chunk count for the same sample buffer: the chunk// is `CHUNK_SIZE * channels` wide.- assert_eq!(waveform_peaks(&samples, 2).len(), 1);+ assert_eq!(waveform_peaks(&[&samples], 2).len(), 1);// Digital silence is pinned to -60 rather than -inf.let silent = vec![0.0f32; AUDIO_SAMPLE_RATE / 10];- assert_eq!(waveform_peaks(&silent, 1), vec![-60.0]);+ assert_eq!(waveform_peaks(&[&silent], 1), vec![-60.0]);// An empty track is an empty table, not a panic.assert!(waveform_peaks(&[], 1).is_empty());diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rsindex 5cbec1e49..955bab7a3 100644--- a/apps/desktop-gpui/src/editor_window.rs+++ b/apps/desktop-gpui/src/editor_window.rs@@ -561,17 +561,12 @@ fn recorded_cursor_family(studio: &StudioRecordingMeta) -> Option<CursorFamily>/// (`frame_pipeline.rs:809-827`) and gpui's atlas expects BGRA, the same/// swap `library::decode_thumbnail` does after decoding a thumbnail.pub fn frame_image(frame: &RenderedFrame) -> Option<Arc<RenderImage>> {- let row_bytes = frame.width as usize * 4;- let mut tight = Vec::with_capacity(row_bytes * frame.height as usize);- for row in frame.data.chunks(frame.padded_bytes_per_row as usize) {- if row.len() < row_bytes {- return None;- }- tight.extend_from_slice(&row[..row_bytes]);- }- for pixel in tight.chunks_exact_mut(4) {- pixel.swap(0, 2);- }+ let tight = cap_gpui_kernels::frame::unpad_rgba_to_bgra(+ &frame.data,+ frame.width as usize,+ frame.padded_bytes_per_row as usize,+ frame.height as usize,+ )?;let buffer = image::RgbaImage::from_raw(frame.width, frame.height, tight)?;Some(Arc::new(RenderImage::new(smallvec::smallvec![image::Frame::new(buffer)diff --git a/apps/desktop-gpui/src/feeds.rs b/apps/desktop-gpui/src/feeds.rsindex c8be1a017..8e0b8d9de 100644--- a/apps/desktop-gpui/src/feeds.rs+++ b/apps/desktop-gpui/src/feeds.rs@@ -1426,27 +1426,13 @@ pub(crate) fn camera_preview_image(let width = width as usize;let height = height as usize;- let row_bytes = width.checked_mul(4)?;- let stride = source.stride(0);- if stride < row_bytes {- return None;- }- let input = source.data(0);- if input.len() < height.checked_mul(stride)? {- return None;- }- let mut pixels = vec![0; height.checked_mul(row_bytes)?];- for (row, output) in pixels.chunks_exact_mut(row_bytes).enumerate() {- let input = &input[row * stride..row * stride + row_bytes];- if mirrored {- for (destination, source) in output.chunks_exact_mut(4).zip(input.chunks_exact(4).rev())- {- destination.copy_from_slice(source);- }- } else {- output.copy_from_slice(input);- }- }+ let pixels = cap_gpui_kernels::frame::copy_rows(+ source.data(0),+ width.checked_mul(4)?,+ source.stride(0),+ height,+ mirrored,+ )?;let image = image::RgbaImage::from_raw(width as u32, height as u32, pixels)?;let image = Arc::new(gpui::RenderImage::new(smallvec::smallvec![image::Frame::new(image)diff --git a/apps/desktop-gpui/src/import.rs b/apps/desktop-gpui/src/import.rsindex 46c37db83..9b97f0444 100644--- a/apps/desktop-gpui/src/import.rs+++ b/apps/desktop-gpui/src/import.rs@@ -1776,12 +1776,7 @@ fn decode_image_rgba(source_path: &Path) -> Result<(u32, u32, Vec<u8>), String>}fn decode_image_with_image_crate(source_path: &Path) -> Result<(u32, u32, Vec<u8>), String> {- let image = image::ImageReader::open(source_path)- .map_err(|e| format!("Failed to open image: {e}"))?- .with_guessed_format()- .map_err(|e| format!("Failed to detect image format: {e}"))?- .decode()- .map_err(|e| format!("Failed to decode image: {e}"))?;+ let image = cap_gpui_kernels::codec::decode_image_file(source_path)?;let (width, height) = (image.width(), image.height());check_image_dimensions(width, height)?;@@ -1868,13 +1863,16 @@ fn decode_image_with_ffmpeg(source_path: &Path) -> Result<(u32, u32, Vec<u8>), Sfn write_png(path: &Path, width: u32, height: u32, rgba: &[u8]) -> Result<(), String> {let file = std::fs::File::create(path).map_err(|e| format!("Failed to create imported image file: {e}"))?;- let encoder = image::codecs::png::PngEncoder::new_with_quality(- std::io::BufWriter::new(file),+ cap_gpui_kernels::codec::write_png_file(+ file,+ rgba,+ width,+ height,+ image::ColorType::Rgba8.into(),image::codecs::png::CompressionType::Default,image::codecs::png::FilterType::Adaptive,- );- image::ImageEncoder::write_image(encoder, rgba, width, height, image::ColorType::Rgba8.into())- .map_err(|e| format!("Failed to encode imported image: {e}"))+ )+ .map_err(|e| format!("Failed to encode imported image: {e}"))}#[cfg(test)]@@ -2093,7 +2091,6 @@ pub(crate) fn import_editor_image(project_path: &Path,source: &Path,) -> Result<ImportedEditorImage, String> {- use image::ImageDecoder;use std::{hash::BuildHasher,io::{Read, Write},@@ -2114,39 +2111,7 @@ pub(crate) fn import_editor_image(if encoded.len() as u64 > MAX_BYTES {return Err("Image files must be 64 MiB or smaller".into());}- let mut reader = image::ImageReader::new(std::io::Cursor::new(&encoded))- .with_guessed_format()- .map_err(|error| error.to_string())?;- let extension = match reader.format() {- Some(image::ImageFormat::Png) => "png",- Some(image::ImageFormat::Jpeg) => "jpg",- Some(image::ImageFormat::WebP) => "webp",- Some(image::ImageFormat::Gif) => "gif",- Some(image::ImageFormat::Bmp) => "bmp",- _ => return Err("Choose a PNG, JPEG, WebP, GIF or BMP image".into()),- };- let mut limits = image::Limits::default();- limits.max_alloc = Some(128 * 1024 * 1024);- limits.max_image_width = Some(32_768);- limits.max_image_height = Some(32_768);- reader.limits(limits);- let mut decoder = reader.into_decoder().map_err(|error| {- format!("Cannot decode image (maximum 32,768 pixels per side): {error}")- })?;- let (source_width, source_height) = decoder.dimensions();- if source_width == 0- || source_height == 0- || u64::from(source_width) * u64::from(source_height) > 16_777_216- || decoder.total_bytes() > 128 * 1024 * 1024- {- return Err("Images must have at most 16,777,216 pixels (32,768 per side) and decode to at most 128 MiB".into());- }- let orientation = decoder.orientation().map_err(|error| error.to_string())?;- let mut decoded = image::DynamicImage::from_decoder(decoder)- .map_err(|error| format!("Cannot decode image: {error}"))?;- decoded.apply_orientation(orientation);- let (width, height) = (decoded.width(), decoded.height());- drop(decoded);+ let (extension, width, height) = cap_gpui_kernels::codec::inspect_overlay_image(&encoded)?;let mut bytes = [0u8; 16];for chunk in bytes.chunks_exact_mut(8) {chunk.copy_from_slice(diff --git a/apps/desktop-gpui/src/library.rs b/apps/desktop-gpui/src/library.rsindex 73697da9d..7a4154baf 100644--- a/apps/desktop-gpui/src/library.rs+++ b/apps/desktop-gpui/src/library.rs@@ -29,7 +29,6 @@ use cap_project::{};use cap_recording::{recovery::RecoveryManager, upload_resume::UploadLock};use gpui::RenderImage;-use image::buffer::ConvertBuffer as _;/// `RECENT_MEDIA_LIMIT` in `new-main/index.tsx:129`.pub const RECENT_MEDIA_LIMIT: usize = 9;@@ -992,14 +991,11 @@ impl CacheSlot {if std::fs::create_dir_all(&self.dir).is_err() {return;}- let rgb: image::RgbImage = rgba.convert();- let mut encoded = Vec::new();- if image::codecs::jpeg::JpegEncoder::new_with_quality(&mut encoded, THUMBNAIL_JPEG_QUALITY)- .encode_image(&rgb)- .is_err()- {+ let Ok(encoded) =+ cap_gpui_kernels::codec::encode_jpeg_rgba_as_rgb(rgba, THUMBNAIL_JPEG_QUALITY)+ else {return;- }+ };let file = self.file();// The prefix keeps two same-mtime slots (wallpapers installed in one// copy) from interleaving writes into one tmp file.@@ -1047,9 +1043,7 @@ impl CacheSlot {/// gpui's atlas takes BGRA; `image`'s RgbaImage is just the container (the/// same swap gpui's own asset loader does after decoding).pub fn rgba_to_render_image(mut rgba: image::RgbaImage) -> Arc<RenderImage> {- for pixel in rgba.chunks_exact_mut(4) {- pixel.swap(0, 2);- }+ cap_gpui_kernels::frame::swap_red_blue(&mut rgba);Arc::new(RenderImage::new(smallvec::smallvec![image::Frame::new(rgba)]))@@ -1190,8 +1184,7 @@ pub fn create_screenshot(if let Some(parent) = output.parent() {std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;}- return image- .save_with_format(output, image::ImageFormat::Jpeg)+ return cap_gpui_kernels::codec::save_rgb_image(&image, output, image::ImageFormat::Jpeg).map_err(|e| e.to_string());}diff --git a/apps/desktop-gpui/src/screenshot.rs b/apps/desktop-gpui/src/screenshot.rsindex c19cb8e4e..b01af4894 100644--- a/apps/desktop-gpui/src/screenshot.rs+++ b/apps/desktop-gpui/src/screenshot.rs@@ -150,13 +150,16 @@ async fn write_png(path: PathBuf, image: image::DynamicImage) -> anyhow::Result<let file =std::fs::File::create(&path).with_context(|| format!("creating {}", path.display()))?;- let encoder = image::codecs::png::PngEncoder::new_with_quality(- std::io::BufWriter::new(file),+ cap_gpui_kernels::codec::write_png_file(+ file,+ &data,+ width,+ height,+ color_type.into(),compression,image::codecs::png::FilterType::Adaptive,- );- image::ImageEncoder::write_image(encoder, &data, width, height, color_type.into())- .context("encoding the screenshot PNG")+ )+ .context("encoding the screenshot PNG")}).await.context("the PNG encode task died")?diff --git a/apps/desktop-gpui/src/screenshot_annotations.rs b/apps/desktop-gpui/src/screenshot_annotations.rsindex 228652944..30118d7e5 100644--- a/apps/desktop-gpui/src/screenshot_annotations.rs+++ b/apps/desktop-gpui/src/screenshot_annotations.rs@@ -3986,40 +3986,18 @@ pub(crate) fn masked_region_image(return None;}- let (x0, y0, width, height) = mask_region(mask, rect, (frame_width, frame_height))?;-- let mut region = Vec::with_capacity(width as usize * height as usize * 4);- for row in 0..height {- let start = (y0 + row) as usize * stride + x0 as usize * 4;- region.extend_from_slice(&rgba[start..start + width as usize * 4]);- }- let source = image::RgbaImage::from_raw(width, height, region)?;-+ let region = mask_region(mask, rect, (frame_width, frame_height))?;let level = mask.mask_level.unwrap_or(MASK_FALLBACK_LEVEL).max(1.);- let processed = if mask.mask_type == Some(MaskType::Pixelate) {- // `blockSize = Math.max(2, Math.round(level))`, nearest both ways.- let block = (level.round() as u32).max(2);- let small = image::imageops::resize(- &source,- (width / block).max(1),- (height / block).max(1),- image::imageops::FilterType::Nearest,- );- image::imageops::resize(&small, width, height, image::imageops::FilterType::Nearest)- } else {- // `blurRegion`: `scale = Math.max(2, Math.round(level / 4))`, with- // smoothing on both passes.- let factor = ((level / 4.).round() as u32).max(2);- let small = image::imageops::resize(- &source,- (width / factor).max(1),- (height / factor).max(1),- image::imageops::FilterType::Triangle,- );- image::imageops::resize(&small, width, height, image::imageops::FilterType::Triangle)- };-- Some((x0, y0, processed))+ let processed = cap_gpui_kernels::screenshot::mask_filter(+ rgba,+ frame_width,+ frame_height,+ region,+ mask.mask_type == Some(MaskType::Pixelate),+ level,+ )?;++ Some((region.0, region.1, processed))}/// One mask's region in whole frame pixels: its own rect, clipped to thediff --git a/apps/desktop-gpui/src/screenshot_crop.rs b/apps/desktop-gpui/src/screenshot_crop.rsindex a789563dc..4e45a960a 100644--- a/apps/desktop-gpui/src/screenshot_crop.rs+++ b/apps/desktop-gpui/src/screenshot_crop.rs@@ -1122,7 +1122,7 @@ impl ScreenshotEditorWindow {/// can be up to 768 logical (1536 physical) pixels wide and the load path/// already refused anything past `MAX_DIMENSION`.fn decode_crop_image(path: Option<&Path>) -> Option<Arc<RenderImage>> {- let decoded = image::open(path?).ok()?;+ let decoded = cap_gpui_kernels::codec::open_image(path?).ok()?;Some(crate::library::rgba_to_render_image(decoded.into_rgba8()))}diff --git a/apps/desktop-gpui/src/screenshot_editor.rs b/apps/desktop-gpui/src/screenshot_editor.rsindex 223d67da6..3fcacd3c9 100644--- a/apps/desktop-gpui/src/screenshot_editor.rs+++ b/apps/desktop-gpui/src/screenshot_editor.rs@@ -391,12 +391,9 @@ async fn render_export_rgba(frame.height));}- let rgba: Vec<u8> = frame- .data- .chunks(padded)- .take(frame.height as usize)- .flat_map(|row| row[..row_bytes].iter().copied())- .collect();+ let rgba =+ cap_gpui_kernels::frame::unpad_rows(&frame.data, row_bytes, padded, frame.height as usize)+ .ok_or_else(|| "Invalid export buffer rows".to_string())?;// What the preview renders this config at: `get_base_size`, then the// uniforms' own alignment -- `get_output_size` at scale 1. That is what@@ -4688,22 +4685,14 @@ fn decode_preview_image(path: &Path) -> Option<Arc<RenderImage>> {/// copied once and the swap runs over a clone, so the padded GPU buffer is/// walked a single time.fn frame_buffers(frame: &RenderedFrame) -> Option<(Arc<Vec<u8>>, Arc<RenderImage>)> {- let row_bytes = frame.width as usize * 4;- let mut rgba = Vec::with_capacity(row_bytes * frame.height as usize);- for row in frame- .data- .chunks(frame.padded_bytes_per_row as usize)- .take(frame.height as usize)- {- if row.len() < row_bytes {- return None;- }- rgba.extend_from_slice(&row[..row_bytes]);- }+ let rgba = cap_gpui_kernels::frame::unpad_rows(+ &frame.data,+ frame.width as usize * 4,+ frame.padded_bytes_per_row as usize,+ frame.height as usize,+ )?;let mut bgra = rgba.clone();- for pixel in bgra.chunks_exact_mut(4) {- pixel.swap(0, 2);- }+ cap_gpui_kernels::frame::swap_red_blue(&mut bgra);let buffer = image::RgbaImage::from_raw(frame.width, frame.height, bgra)?;Some((Arc::new(rgba),diff --git a/apps/desktop-gpui/src/screenshot_export.rs b/apps/desktop-gpui/src/screenshot_export.rsindex 8d30ab6b4..4720daddb 100644--- a/apps/desktop-gpui/src/screenshot_export.rs+++ b/apps/desktop-gpui/src/screenshot_export.rs@@ -20,6 +20,7 @@use std::sync::{Mutex, OnceLock};+use cap_gpui_kernels::{codec, screenshot as pixels};use cap_project::{Annotation, AnnotationType, ProjectConfiguration};use crate::screenshot_annotations::{self as annotations, Rect};@@ -133,7 +134,7 @@ pub fn composite(raw: &RawFrame, config: &ProjectConfiguration) -> Composited {let height = raw.height.max(1);if config.annotations.is_empty()&& raw.rgba.len() == width as usize * height as usize * 4- && is_opaque(&raw.rgba)+ && pixels::is_opaque(&raw.rgba){return Composited {rgba: raw.rgba.clone(),@@ -163,7 +164,7 @@ pub fn composite(raw: &RawFrame, config: &ProjectConfiguration) -> Composited {if let Some((x0, y0, region)) =annotations::masked_region_image(&raw.rgba, (width, height), mask, full){- blit_over(&mut canvas, (width, height), ®ion, (x0, y0));+ pixels::blit_over(&mut canvas, (width, height), ®ion, (x0, y0));}}@@ -178,7 +179,7 @@ pub fn composite(raw: &RawFrame, config: &ProjectConfiguration) -> Composited {(-bounds.min_x).round() as i64,(-bounds.min_y).round() as i64,);- blit_over_offset(+ pixels::blit_over_offset(&mut out,(bounds.width, bounds.height),&canvas,@@ -204,39 +205,13 @@ pub fn needs_transparency(out: &Composited, config: &ProjectConfiguration) -> boif !has_no_visible_background(&config.background.source) {return false;}- out.rgba- .iter()- .skip(3)- .step_by(4)- .any(|&alpha| alpha != 255)-}--fn is_opaque(rgba: &[u8]) -> bool {- const ALPHA_MASK: u128 = 0xff000000ff000000ff000000ff000000;- let mut blocks = rgba.chunks_exact(16);- blocks- .by_ref()- .all(|block| u128::from_le_bytes(block.try_into().unwrap()) & ALPHA_MASK == ALPHA_MASK)- && blocks- .remainder()- .iter()- .skip(3)- .step_by(4)- .all(|&alpha| alpha == 255)+ pixels::has_translucent_pixel(&out.rgba)}/// `withWhiteBackground` (`useScreenshotExport.ts:18-28`).pub fn flatten_onto_white(out: &Composited) -> Composited {- let mut rgba = out.rgba.clone();- for pixel in rgba.chunks_exact_mut(4) {- let alpha = u32::from(pixel[3]);- for channel in &mut pixel[..3] {- *channel = ((u32::from(*channel) * alpha + 255 * (255 - alpha) + 127) / 255) as u8;- }- pixel[3] = 255;- }Composited {- rgba,+ rgba: pixels::flatten_onto_white(&out.rgba),width: out.width,height: out.height,}@@ -246,12 +221,8 @@ pub fn flatten_onto_white(out: &Composited) -> Composited {/// frame straight to PNG" path, still callable through/// `screenshot_editor::render_export_png`.pub fn encode_rgba_png(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>, String> {- use image::ImageEncoder as _;- let mut png = std::io::Cursor::new(Vec::new());- image::codecs::png::PngEncoder::new(&mut png)- .write_image(rgba, width, height, image::ExtendedColorType::Rgba8)- .map_err(|e| format!("Failed to encode screenshot export: {e}"))?;- Ok(png.into_inner())+ codec::encode_png_rgba(rgba, width, height)+ .map_err(|e| format!("Failed to encode screenshot export: {e}"))}fn encode_png(out: &Composited) -> Result<Vec<u8>, String> {@@ -263,21 +234,9 @@ fn encode_png(out: &Composited) -> Result<Vec<u8>, String> {/// flatten here is the same belt the browser's own encode wears.fn encode_jpeg(out: &Composited) -> Result<Vec<u8>, String> {let flat = flatten_onto_white(out);- let rgb: Vec<u8> = flat- .rgba- .chunks_exact(4)- .flat_map(|px| [px[0], px[1], px[2]])- .collect();- let mut buffer = Vec::new();- image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buffer, 90)- .encode(- &rgb,- flat.width,- flat.height,- image::ExtendedColorType::Rgb8,- )- .map_err(|e| format!("Failed to encode screenshot export: {e}"))?;- Ok(buffer)+ let rgb = codec::rgba_to_rgb(&flat.rgba);+ codec::encode_jpeg_rgb(&rgb, flat.width, flat.height, 90)+ .map_err(|e| format!("Failed to encode screenshot export: {e}"))}/// An encoded export, tagged with the content type the upload sends.@@ -317,7 +276,7 @@ pub fn encode_for_share(/// Copy: always PNG, composited over white when transparency is not needed/// (`:183-198` -- `withWhiteBackground` only on the clipboard path).pub fn encode_for_copy(out: &Composited, config: &ProjectConfiguration) -> Result<Vec<u8>, String> {- if has_no_visible_background(&config.background.source) || is_opaque(&out.rgba) {+ if has_no_visible_background(&config.background.source) || pixels::is_opaque(&out.rgba) {encode_png(out)} else {encode_png(&flatten_onto_white(out))@@ -379,115 +338,6 @@ pub fn content_hash(config: &ProjectConfiguration) -> Result<String, String> {Ok(format!("sha256:{hex}"))}-// ----------------------------------------------------------------------------// Pixel plumbing-// -----------------------------------------------------------------------------/// Straight-alpha source-over of one pixel -- what `drawImage` does.-fn blend_pixel_over(dst: &mut [u8], src: [u8; 4]) {- if src[3] == 0 {- return;- }- if src[3] == 255 {- dst.copy_from_slice(&src);- return;- }- let sa = f32::from(src[3]) / 255.;- let da = f32::from(dst[3]) / 255.;- let oa = sa + da * (1. - sa);- if oa <= 0. {- dst.fill(0);- return;- }- for channel in 0..3 {- let s = f32::from(src[channel]);- let d = f32::from(dst[channel]);- dst[channel] = ((s * sa + d * da * (1. - sa)) / oa).round().clamp(0., 255.) as u8;- }- dst[3] = (oa * 255.).round() as u8;-}--/// Source-over blit of a filtered mask region into the working canvas.-fn blit_over(canvas: &mut [u8], size: (u32, u32), region: &image::RgbaImage, at: (u32, u32)) {- let stride = size.0 as usize * 4;- for (row_index, row) in region.rows().enumerate() {- let y = at.1 as usize + row_index;- if y >= size.1 as usize {- break;- }- for (column_index, pixel) in row.enumerate() {- let x = at.0 as usize + column_index;- if x >= size.0 as usize {- break;- }- let start = y * stride + x * 4;- blend_pixel_over(&mut canvas[start..start + 4], pixel.0);- }- }-}--/// Source-over blit of one straight-alpha buffer into another at a (possibly-/// negative) offset, clipping to the destination.-fn blit_over_offset(- dst: &mut [u8],- dst_size: (u32, u32),- src: &[u8],- src_size: (u32, u32),- offset: (i64, i64),-) {- let dst_stride = dst_size.0 as usize * 4;- let src_stride = src_size.0 as usize * 4;- for src_y in 0..src_size.1 as i64 {- let dst_y = src_y + offset.1;- if dst_y < 0 || dst_y >= i64::from(dst_size.1) {- continue;- }- for src_x in 0..src_size.0 as i64 {- let dst_x = src_x + offset.0;- if dst_x < 0 || dst_x >= i64::from(dst_size.0) {- continue;- }- let src_start = src_y as usize * src_stride + src_x as usize * 4;- let dst_start = dst_y as usize * dst_stride + dst_x as usize * 4;- let pixel = [- src[src_start],- src[src_start + 1],- src[src_start + 2],- src[src_start + 3],- ];- blend_pixel_over(&mut dst[dst_start..dst_start + 4], pixel);- }- }-}--/// `(c * a + 127) / 255` rounding both ways -- the standard integer-/// premultiply pair. tiny-skia's pixmaps are premultiplied, our canvases are-/// straight, so the draw pass converts in and back out.-fn premultiply(rgba: &mut [u8]) {- for pixel in rgba.chunks_exact_mut(4) {- let alpha = u16::from(pixel[3]);- if alpha == 255 {- continue;- }- for channel in &mut pixel[..3] {- *channel = ((u16::from(*channel) * alpha + 127) / 255) as u8;- }- }-}--fn demultiply(rgba: &mut [u8]) {- for pixel in rgba.chunks_exact_mut(4) {- let alpha = u32::from(pixel[3]);- if alpha == 255 || alpha == 0 {- continue;- }- for channel in &mut pixel[..3] {- let value = (u32::from(*channel) * 255 + alpha / 2) / alpha;- *channel = value.min(255) as u8;- }- }-}-// ---------------------------------------------------------------------------// The shape draw (`drawAnnotations`, `screenshotExport.ts:42-121`)// ---------------------------------------------------------------------------@@ -531,7 +381,7 @@ fn skia_stroke(width: f64, round: bool) -> tiny_skia::Stroke {/// order -- rect, ellipse, arrow, freehand with tiny-skia, text with/// cosmic-text, each under its own `globalAlpha`.fn draw_annotations_onto(canvas: &mut [u8], width: u32, height: u32, scaled: &[Annotation]) {- premultiply(canvas);+ pixels::premultiply(canvas);if let Some(mut pixmap) = tiny_skia::PixmapMut::from_bytes(canvas, width, height) {for annotation in scaled {if annotation.annotation_type == AnnotationType::Mask {@@ -540,7 +390,7 @@ fn draw_annotations_onto(canvas: &mut [u8], width: u32, height: u32, scaled: &[Adraw_one(&mut pixmap, annotation);}}- demultiply(canvas);+ pixels::demultiply(canvas);}fn draw_one(pixmap: &mut tiny_skia::PixmapMut<'_>, annotation: &Annotation) {@@ -762,59 +612,16 @@ fn draw_text(pixmap: &mut tiny_skia::PixmapMut<'_>, annotation: &Annotation) {let (canvas_width, canvas_height) = (pixmap.width(), pixmap.height());let data = pixmap.data_mut();buffer.draw(font_system, swash_cache, color, |x, y, w, h, pixel| {- blend_rect_premultiplied(+ pixels::blend_rect_premultiplied(data,(canvas_width, canvas_height),(origin_x + f64::from(x), origin_y + f64::from(y)),(w, h),- pixel,+ [pixel.r(), pixel.g(), pixel.b(), pixel.a()],);});}-/// Premultiplied source-over of one glyph-coverage rect (cosmic-text hands-/// back the coverage folded into the colour's alpha).-fn blend_rect_premultiplied(- data: &mut [u8],- size: (u32, u32),- at: (f64, f64),- rect: (u32, u32),- color: cosmic_text::Color,-) {- let alpha = f32::from(color.a()) / 255.;- if alpha <= 0. {- return;- }- let src = [- (f32::from(color.r()) * alpha).round() as u8,- (f32::from(color.g()) * alpha).round() as u8,- (f32::from(color.b()) * alpha).round() as u8,- color.a(),- ];- let inverse = 1. - alpha;- let stride = size.0 as usize * 4;- let x0 = at.0.round() as i64;- let y0 = at.1.round() as i64;- for row in 0..i64::from(rect.1) {- let y = y0 + row;- if y < 0 || y >= i64::from(size.1) {- continue;- }- for column in 0..i64::from(rect.0) {- let x = x0 + column;- if x < 0 || x >= i64::from(size.0) {- continue;- }- let start = y as usize * stride + x as usize * 4;- for channel in 0..4 {- let d = f32::from(data[start + channel]);- data[start + channel] =- (f32::from(src[channel]) + d * inverse).round().min(255.) as u8;- }- }- }-}-#[cfg(test)]mod tests {use super::*;@@ -995,7 +802,7 @@ mod tests {fn reference_flatten(out: &Composited) -> Composited {let mut rgba = vec![255; out.rgba.len()];- blit_over_offset(+ pixels::blit_over_offset(&mut rgba,(out.width, out.height),&out.rgba,@@ -1021,7 +828,7 @@ mod tests {if !has_no_visible_background(&config.background.source) {rgba.fill(255);}- blit_over_offset(&mut rgba, (width, height), &canvas, (width, height), (0, 0));+ pixels::blit_over_offset(&mut rgba, (width, height), &canvas, (width, height), (0, 0));Composited {rgba,width,@@ -1029,39 +836,6 @@ mod tests {}}- #[test]- fn white_flatten_matches_source_over_for_every_channel_and_alpha() {- let rgba = (0..=255u8)- .flat_map(|alpha| {- (0..=255u8).flat_map(move |channel| {- [channel, 255 - channel, channel.wrapping_mul(17), alpha]- })- })- .collect();- let out = Composited {- rgba,- width: 256,- height: 256,- };- assert_eq!(flatten_onto_white(&out).rgba, reference_flatten(&out).rgba);- }-- #[test]- fn opacity_check_matches_individual_alpha_bytes_at_block_boundaries() {- for length in 0..130 {- let opaque = vec![255; length];- assert!(is_opaque(&opaque));- for changed_byte in 0..length {- let mut rgba = opaque.clone();- rgba[changed_byte] = 127;- assert_eq!(- is_opaque(&rgba),- rgba.iter().skip(3).step_by(4).all(|&alpha| alpha == 255),- );- }- }- }-#[test]fn unannotated_composite_and_copy_preserve_all_alpha_values() {for opaque in [false, true] {@@ -1150,7 +924,7 @@ mod tests {let baseline_ms = start.elapsed().as_secs_f64() * 1000.0;let start = Instant::now();let result = composite(black_box(&raw), &config);- let result = if is_opaque(&result.rgba) {+ let result = if pixels::is_opaque(&result.rgba) {result} else {flatten_onto_white(&result)@@ -1173,17 +947,6 @@ mod tests {}}- /// `withWhiteBackground` leaves an opaque canvas untouched.- #[test]- fn flattening_an_opaque_canvas_is_the_identity() {- let out = Composited {- rgba: vec![10, 20, 30, 255, 40, 50, 60, 255],- width: 2,- height: 1,- };- assert_eq!(flatten_onto_white(&out).rgba, out.rgba);- }-/// A composite with no annotations is the frame itself over the white/// output canvas, and an annotation past the edge pads the output --/// matching the source, the part outside the frame is clipped by the@@ -1217,14 +980,4 @@ mod tests {let margin = 9 * 4;assert_eq!(&out.rgba[margin..margin + 4], &[255, 255, 255, 255]);}-- /// Premultiply/demultiply round-trips opaque pixels exactly; a fully- /// transparent pixel's colour is unrecoverable by definition and zeroes.- #[test]- fn premultiply_roundtrip_is_exact_for_opaque_pixels() {- let mut rgba = vec![13, 200, 91, 255, 1, 2, 3, 0];- premultiply(&mut rgba);- demultiply(&mut rgba);- assert_eq!(rgba, vec![13, 200, 91, 255, 0, 0, 0, 0]);- }}diff --git a/apps/desktop-gpui/src/target_thumbnails.rs b/apps/desktop-gpui/src/target_thumbnails.rsindex c553c37df..f3d4b1696 100644--- a/apps/desktop-gpui/src/target_thumbnails.rs+++ b/apps/desktop-gpui/src/target_thumbnails.rs@@ -439,44 +439,7 @@ pub fn fitted_capture_size(source: Option<(f64, f64)>) -> (usize, usize) {/// `normalize_thumbnail_dimensions` (`thumbnails/mod.rs:44-87`), verbatim.pub fn normalize_thumbnail_dimensions(image: &RgbaImage) -> RgbaImage {- let width = image.width();- let height = image.height();-- if width == THUMBNAIL_WIDTH && height == THUMBNAIL_HEIGHT {- return image.clone();- }-- if width == 0 || height == 0 {- return RgbaImage::from_pixel(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, image::Rgba([0, 0, 0, 0]));- }-- let scale = (THUMBNAIL_WIDTH as f32 / width as f32)- .min(THUMBNAIL_HEIGHT as f32 / height as f32)- .max(f32::MIN_POSITIVE);-- let scaled_width = (width as f32 * scale)- .round()- .clamp(1.0, THUMBNAIL_WIDTH as f32) as u32;- let scaled_height = (height as f32 * scale)- .round()- .clamp(1.0, THUMBNAIL_HEIGHT as f32) as u32;-- let resized = image::imageops::resize(- image,- scaled_width.max(1),- scaled_height.max(1),- image::imageops::FilterType::Lanczos3,- );-- let mut canvas =- RgbaImage::from_pixel(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, image::Rgba([0, 0, 0, 0]));-- let offset_x = (THUMBNAIL_WIDTH - scaled_width) / 2;- let offset_y = (THUMBNAIL_HEIGHT - scaled_height) / 2;-- image::imageops::overlay(&mut canvas, &resized, offset_x as i64, offset_y as i64);-- canvas+ cap_gpui_kernels::thumbnail::fit_centered(image, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)}/// Run a capture sweep somewhere it is allowed to be non-`Send`.diff --git a/apps/desktop-gpui/src/upload.rs b/apps/desktop-gpui/src/upload.rsindex aa01ca627..ceb845ba3 100644--- a/apps/desktop-gpui/src/upload.rs+++ b/apps/desktop-gpui/src/upload.rs@@ -2153,26 +2153,7 @@ async fn upload_screenshot_bytes(}fn compress_image(path: &Path) -> Result<Vec<u8>, AuthApiError> {- let img = image::ImageReader::open(path)- .map_err(|error| AuthApiError::Other(format!("Failed to open image: {error}")))?- .decode()- .map_err(|error| AuthApiError::Other(format!("Failed to decode image: {error}")))?;- let resized = img.resize(- img.width() / 2,- img.height() / 2,- image::imageops::FilterType::Nearest,- );- let mut buffer = Vec::new();- let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buffer, 30);- encoder- .encode(- resized.as_bytes(),- resized.width(),- resized.height(),- resized.color().into(),- )- .map_err(|error| AuthApiError::Other(format!("Failed to compress image: {error}")))?;- Ok(buffer)+ cap_gpui_kernels::codec::compress_image_jpeg(path).map_err(AuthApiError::Other)}fn build_video_meta(path: &Path) -> Result<VideoMeta, String> {@@ -2215,8 +2196,7 @@ fn chunk_size_for(file_size: u64) -> u64 {}fn md5_base64(bytes: &[u8]) -> String {- use md5::{Digest, Md5};- let digest = Md5::digest(bytes);+ let digest = cap_gpui_kernels::codec::md5(bytes);base64::Engine::encode(&base64::engine::general_purpose::STANDARD, digest)}