A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
Video thumbnails made on the GPU; shaders compiled once per process
gelenmedyacee869509758
diff --git a/crates/rf-app/examples/thumb_probe/main.rs b/crates/rf-app/examples/thumb_probe/main.rsindex cce2b6de..54f7c771 100644--- a/crates/rf-app/examples/thumb_probe/main.rs+++ b/crates/rf-app/examples/thumb_probe/main.rs@@ -40,7 +40,7 @@ fn main() {}#[cfg(windows)]-const KINDS: [&str; 13] = ["cache", "forced", "factory", "embedded", "wic", "full", "video", "stream", "psd", "dc-1", "dc-16", "dc-skip", "inflate"];+const KINDS: [&str; 14] = ["cache", "forced", "factory", "embedded", "wic", "full", "video", "stream", "psd", "dc-1", "dc-16", "dc-skip", "inflate", "video-gpu"];#[cfg(windows)]fn probe_folder(dir: &std::path::Path, size: u32, per: usize) {@@ -94,6 +94,7 @@ fn probe_folder(dir: &std::path::Path, size: u32, per: usize) {});if k == Kind::Video {time(6, &mut || video(p));+ time(13, &mut || video_gpu(p, size));} else if k == Kind::Psd {time(8, &mut || rf_win::psd_thumb::thumbnail(p, size).is_some());} else {@@ -158,7 +159,7 @@ fn probe_folder(dir: &std::path::Path, size: u32, per: usize) {Kind::Raw => embedded(p, size),Kind::Png => png_stream(p, size),Kind::Psd => rf_win::psd_thumb::thumbnail(p, size).is_some(),- Kind::Video => video(p),+ Kind::Video => video_gpu(p, size),};}});@@ -567,12 +568,58 @@ fn inflate_only(p: &std::path::Path) -> bool {d.decompress_vec(&z, &mut out, flate2::FlushDecompress::Finish).is_ok() && out.len() == raw}+/// rustdecoder's first frame made a thumbnail on the GPU (converted, averaged down by mipmaps), only that read back. The+/// converter (its shaders compiled once) is kept per thread, as the app would keep one.+#[cfg(windows)]+fn video_gpu(p: &std::path::Path, size: u32) -> bool {+ use rustdecoder::present::{Colorimetry, Converter, Params, Source};+ thread_local! {+ static CONV: std::cell::RefCell<Option<(usize, Converter)>> = const { std::cell::RefCell::new(None) };+ }+ let t = std::time::Instant::now();+ let Ok(mut dec) = rustdecoder::VideoDecoder::open(p) else { return false };+ let opened = t.elapsed().as_secs_f64() * 1000.0;+ let Ok(Some(frame)) = dec.next_frame() else { return false };+ let decoded = t.elapsed().as_secs_f64() * 1000.0;+ let info = dec.info().clone();+ let params = Params { colour: Colorimetry::from_vui(&info.vui, info.width, info.height), rotation: info.rotation, flip: false };+ let gpu = dec.gpu();+ let key = windows::core::Interface::as_raw(&gpu.device) as usize;+ let r = CONV.with(|c| {+ let mut c = c.borrow_mut();+ if c.as_ref().is_none_or(|(k, _)| *k != key) {+ *c = Converter::new(&gpu.device, &gpu.context).ok().map(|v| (key, v));+ }+ let conv = &mut c.as_mut()?.1;+ let made = t.elapsed().as_secs_f64() * 1000.0;+ let r = conv.thumbnail(&Source::from_frame(&frame), ¶ms, size).ok();+ Some((made, r))+ });+ let Some((made, Some((w, h, px)))) = r else { return false };+ if std::env::var("PROBE_PHASES").is_ok() {+ eprintln!(" video-gpu: open {opened:.1} ms, first frame {:.1} ms, converter {:.1} ms, thumbnail {:.1} ms ({w}x{h})", decoded - opened, made - decoded, t.elapsed().as_secs_f64() * 1000.0 - made);+ }+ if let Ok(dir) = std::env::var("PROBE_SAVE") {+ let rgb: Vec<u8> = px.chunks_exact(4).flat_map(|b| [b[2], b[1], b[0]]).collect();+ let name = p.file_stem().unwrap().to_string_lossy().to_string();+ let _ = image::RgbImage::from_raw(w, h, rgb).map(|i| i.save(format!("{dir}/{name}-gpu.png")));+ }+ true+}+/// rustdecoder's first frame, read back from the GPU.#[cfg(windows)]fn video(p: &std::path::Path) -> bool {+ let t = std::time::Instant::now();let Ok(mut dec) = rustdecoder::VideoDecoder::open(p) else { return false };+ let opened = t.elapsed().as_secs_f64() * 1000.0;let Ok(Some(frame)) = dec.next_frame() else { return false };- dec.read_back(&frame).is_ok()+ let decoded = t.elapsed().as_secs_f64() * 1000.0;+ let ok = dec.read_back(&frame).is_ok();+ if std::env::var("PROBE_PHASES").is_ok() {+ eprintln!(" video: open {opened:.1} ms, first frame {:.1} ms, read back {:.1} ms", decoded - opened, t.elapsed().as_secs_f64() * 1000.0 - decoded);+ }+ ok}#[cfg(not(windows))]diff --git a/crates/rustdecoder/src/present.rs b/crates/rustdecoder/src/present.rsindex 67833959..072ca869 100644--- a/crates/rustdecoder/src/present.rs+++ b/crates/rustdecoder/src/present.rs@@ -338,14 +338,28 @@ pub struct Converter {gpu_samples: u64,staging: Option<(ID3D11Texture2D, u32, u32)>,deinterlace: bool,+ /// The last thumbnail's textures, kept for the next one of the same size (see `thumbnail`).+ thumb: Option<ThumbTextures>,+}++/// What a thumbnail of one size is made in: the converted picture with its mipmaps, and the staging copy of the last level.+struct ThumbTextures {+ size: (u32, u32, u32),+ target: Target,+ srv: Option<ID3D11ShaderResourceView>,+ staging: ID3D11Texture2D,}impl Converter {/// A converter on the device the pictures are decoded on.pub fn new(device: &ID3D11Device, context: &ID3D11DeviceContext) -> Result<Self> {- let vs_code = compile(s!("vs"), s!("vs_5_0"))?;- let ps_code = compile(s!("ps"), s!("ps_5_0"))?;- let ps_planar_code = compile(s!("ps_planar"), s!("ps_5_0"))?;+ // compiled once per process (about 35 ms): every video's device makes its converter from the same code+ static CODE: std::sync::OnceLock<std::result::Result<[Vec<u8>; 3], String>> = std::sync::OnceLock::new();+ let code = CODE.get_or_init(|| {+ let all = || -> Result<[Vec<u8>; 3]> { Ok([compile(s!("vs"), s!("vs_5_0"))?, compile(s!("ps"), s!("ps_5_0"))?, compile(s!("ps_planar"), s!("ps_5_0"))?]) };+ all().map_err(|e| e.to_string())+ });+ let [vs_code, ps_code, ps_planar_code] = code.as_ref().map_err(|e| Error::Gpu(e.clone()))?;unsafe {let mut ps_planar = None;gpu("CreatePixelShader (planar)", device.CreatePixelShader(&ps_planar_code, None, Some(&mut ps_planar)))?;@@ -393,6 +407,7 @@ impl Converter {gpu_samples: 0,staging: None,deinterlace: false,+ thumb: None,})}}@@ -627,6 +642,90 @@ impl Converter {if self.gpu_samples == 0 { (0.0, 0) } else { (self.gpu_ns / self.gpu_samples as f64 / 1e6, self.gpu_samples) }}+ /// The picture as a thumbnail, its long side at most `max_side` (never enlarged): BGRA8, top-down rows, `(width, height,+ /// bytes)`. Waits for the GPU.+ ///+ /// Only the thumbnail crosses to the CPU (a 256 px one is 256 KB; reading back a 4K frame was 12-24 MB and most of the+ /// time). The frame is converted at the thumbnail's size times a power of two, no more than twice smaller than the frame+ /// (so the bilinear sampler does not skip pixels), and the GPU's mipmaps average it down from there by halves.+ pub fn thumbnail(&mut self, src: &Source, params: &Params, max_side: u32) -> Result<(u32, u32, Vec<u8>)> {+ let (w, h) = rotated_size(src.width, src.height, params.rotation);+ let (tw, th) = fit(w, h, max_side.max(1), max_side.max(1));+ let (tw, th) = (tw.max(1), th.max(1));+ let mut levels = 0u32;+ // the smallest power of two that brings the converted size to at least half the frame's+ while levels < 6 && (tw << levels) * 2 < w {+ levels += 1;+ }+ let (bw, bh) = (tw << levels, th << levels);+ unsafe {+ if self.thumb.as_ref().is_none_or(|t| t.size != (tw, th, levels)) {+ self.thumb = Some(self.thumb_textures(tw, th, levels)?);+ }+ let t = self.thumb.as_ref().unwrap();+ let (target, srv, staging) = (Target { texture: t.target.texture.clone(), rtv: t.target.rtv.clone(), width: bw, height: bh }, t.srv.clone(), t.staging.clone());+ self.convert(src, params, &target)?;+ if let Some(srv) = &srv {+ self.context.GenerateMips(srv);+ }+ self.context.CopySubresourceRegion(&staging, 0, 0, 0, 0, &target.texture, levels, None);+ let mut m = D3D11_MAPPED_SUBRESOURCE::default();+ gpu("Map", self.context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut m)))?;+ let mut out = Vec::with_capacity((tw * th * 4) as usize);+ for row in 0..th as usize {+ out.extend_from_slice(std::slice::from_raw_parts((m.pData as *const u8).add(row * m.RowPitch as usize), tw as usize * 4));+ }+ self.context.Unmap(&staging, 0);+ Ok((tw, th, out))+ }+ }++ fn thumb_textures(&self, tw: u32, th: u32, levels: u32) -> Result<ThumbTextures> {+ let (bw, bh) = (tw << levels, th << levels);+ unsafe {+ let d = D3D11_TEXTURE2D_DESC {+ Width: bw,+ Height: bh,+ MipLevels: levels + 1,+ ArraySize: 1,+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32,+ MiscFlags: if levels > 0 { D3D11_RESOURCE_MISC_GENERATE_MIPS.0 as u32 } else { 0 },+ ..Default::default()+ };+ let mut t = None;+ gpu("CreateTexture2D (thumbnail)", self.device.CreateTexture2D(&d, None, Some(&mut t)))?;+ let texture = t.ok_or(Error::Gpu("no texture".into()))?;+ let mut rtv = None;+ gpu("CreateRenderTargetView", self.device.CreateRenderTargetView(&texture, None, Some(&mut rtv)))?;+ let mut srv = None;+ if levels > 0 {+ gpu("CreateShaderResourceView (thumbnail)", self.device.CreateShaderResourceView(&texture, None, Some(&mut srv)))?;+ }+ let sd = D3D11_TEXTURE2D_DESC {+ Width: tw,+ Height: th,+ MipLevels: 1,+ ArraySize: 1,+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },+ Usage: D3D11_USAGE_STAGING,+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,+ ..Default::default()+ };+ let mut st = None;+ gpu("CreateTexture2D (thumbnail staging)", self.device.CreateTexture2D(&sd, None, Some(&mut st)))?;+ Ok(ThumbTextures {+ size: (tw, th, levels),+ target: Target { texture, rtv: rtv.ok_or(Error::Gpu("no view".into()))?, width: bw, height: bh },+ srv,+ staging: st.ok_or(Error::Gpu("no texture".into()))?,+ })+ }+ }+/// Copies a target to the CPU as RGBA bytes, row after row (for tests). Waits for the GPU.pub fn read_rgba(&mut self, t: &Target) -> Result<Vec<u8>> {unsafe {