rosier 0.5.0

A fast picture and video viewer for large folders
//! Minimal binding to the system libjpeg-turbo (TurboJPEG 2.x API).
//!
//! The point is scaled decoding: libjpeg-turbo can skip most of the IDCT work
//! and emit 1/2, 1/4 or 1/8 sized output directly, which is far cheaper than
//! decoding a 12 MP photo at full size and shrinking it afterwards. It also
//! encodes the cached thumbnails, several times faster than the image crate.

use std::ffi::{CStr, c_char, c_int, c_uchar, c_ulong, c_void};

use anyhow::{Result, bail};

type TjHandle = *mut c_void;

const TJPF_BGRA: c_int = 8;
const TJFLAG_FASTDCT: c_int = 2048;

// The system libturbojpeg by default; with `vendored-turbojpeg` (CI and the
// release builds) turbojpeg-sys builds libjpeg-turbo 3.x, which still exports
// these TurboJPEG 2.x functions, and links it statically.
#[cfg(feature = "vendored-turbojpeg")]
use turbojpeg_sys as _;

#[cfg_attr(not(feature = "vendored-turbojpeg"), link(name = "turbojpeg"))]
unsafe extern "C" {
    fn tjInitDecompress() -> TjHandle;
    fn tjDecompressHeader3(
        handle: TjHandle,
        jpeg_buf: *const c_uchar,
        jpeg_size: c_ulong,
        width: *mut c_int,
        height: *mut c_int,
        jpeg_subsamp: *mut c_int,
        jpeg_colorspace: *mut c_int,
    ) -> c_int;
    fn tjDecompress2(
        handle: TjHandle,
        jpeg_buf: *const c_uchar,
        jpeg_size: c_ulong,
        dst_buf: *mut c_uchar,
        width: c_int,
        pitch: c_int,
        height: c_int,
        pixel_format: c_int,
        flags: c_int,
    ) -> c_int;
    fn tjInitCompress() -> TjHandle;
    fn tjCompress2(
        handle: TjHandle,
        src_buf: *const c_uchar,
        width: c_int,
        pitch: c_int,
        height: c_int,
        pixel_format: c_int,
        jpeg_buf: *mut *mut c_uchar,
        jpeg_size: *mut c_ulong,
        jpeg_subsamp: c_int,
        jpeg_qual: c_int,
        flags: c_int,
    ) -> c_int;
    fn tjFree(buffer: *mut c_uchar);
    fn tjDestroy(handle: TjHandle) -> c_int;
    fn tjGetErrorStr2(handle: TjHandle) -> *const c_char;
    fn tjGetErrorCode(handle: TjHandle) -> c_int;
}

const TJERR_WARNING: c_int = 0;
const TJSAMP_420: c_int = 2;

struct Handle(TjHandle);

impl Drop for Handle {
    fn drop(&mut self) {
        unsafe { tjDestroy(self.0) };
    }
}

impl Handle {
    fn error(&self) -> String {
        unsafe { CStr::from_ptr(tjGetErrorStr2(self.0)) }.to_string_lossy().into_owned()
    }
}

/// A decoded image in BGRA order (what gpui uploads as a texture).
#[derive(Clone)]
pub struct Bgra {
    pub width: u32,
    pub height: u32,
    pub pixels: Vec<u8>,
}

/// Returns the JPEG's full-size dimensions without decoding pixels.
pub fn dimensions(data: &[u8]) -> Result<(u32, u32)> {
    let h = Handle(unsafe { tjInitDecompress() });
    if h.0.is_null() {
        bail!("tjInitDecompress failed");
    }
    let (mut w, mut ht, mut ss, mut cs) = (0, 0, 0, 0);
    let rc =
        unsafe { tjDecompressHeader3(h.0, data.as_ptr(), data.len() as c_ulong, &mut w, &mut ht, &mut ss, &mut cs) };
    if rc != 0 {
        bail!("jpeg header: {}", h.error());
    }
    Ok((w as u32, ht as u32))
}

/// Decodes `data` at the smallest libjpeg-turbo scale (n/8) whose longer side
/// is still at least `min_long_side`, so the caller only does a small final
/// resize. Pass `u32::MAX` to decode at full size.
pub fn decode_scaled(data: &[u8], min_long_side: u32) -> Result<Bgra> {
    let h = Handle(unsafe { tjInitDecompress() });
    if h.0.is_null() {
        bail!("tjInitDecompress failed");
    }
    let (mut w, mut ht, mut ss, mut cs) = (0, 0, 0, 0);
    let rc =
        unsafe { tjDecompressHeader3(h.0, data.as_ptr(), data.len() as c_ulong, &mut w, &mut ht, &mut ss, &mut cs) };
    if rc != 0 {
        bail!("jpeg header: {}", h.error());
    }
    let long = w.max(ht) as u32;
    // libjpeg-turbo supports n/8 for n in 1..=8 when shrinking.
    let num = (1..=8).find(|n| (long * n).div_ceil(8) >= min_long_side).unwrap_or(8) as c_int;
    let sw = (w * num + 7) / 8;
    let sh = (ht * num + 7) / 8;
    let pitch = sw * 4;
    let mut pixels = vec![0u8; (pitch * sh) as usize];
    let rc = unsafe {
        tjDecompress2(
            h.0,
            data.as_ptr(),
            data.len() as c_ulong,
            pixels.as_mut_ptr(),
            sw,
            pitch,
            sh,
            TJPF_BGRA,
            TJFLAG_FASTDCT,
        )
    };
    // A non-fatal warning (e.g. a truncated file) still yields usable pixels.
    if rc != 0 && unsafe { tjGetErrorCode(h.0) } != TJERR_WARNING {
        bail!("jpeg decode: {}", h.error());
    }
    Ok(Bgra { width: sw as u32, height: sh as u32, pixels })
}

/// Encodes BGRA pixels as a JPEG of `quality` (1 to 100), 4:2:0.
pub fn encode(b: &Bgra, quality: u8) -> Result<Vec<u8>> {
    if b.pixels.len() < (b.width as usize) * (b.height as usize) * 4 {
        bail!("jpeg encode: buffer smaller than {}x{}", b.width, b.height);
    }
    let h = Handle(unsafe { tjInitCompress() });
    if h.0.is_null() {
        bail!("tjInitCompress failed");
    }
    let mut buf: *mut c_uchar = std::ptr::null_mut();
    let mut size: c_ulong = 0;
    // SAFETY: the source holds width * height BGRA pixels (checked above);
    // libjpeg-turbo allocates `buf`, which is freed below with tjFree.
    let rc = unsafe {
        tjCompress2(
            h.0,
            b.pixels.as_ptr(),
            b.width as c_int,
            (b.width * 4) as c_int,
            b.height as c_int,
            TJPF_BGRA,
            &mut buf,
            &mut size,
            TJSAMP_420,
            quality.clamp(1, 100) as c_int,
            TJFLAG_FASTDCT,
        )
    };
    let out = (!buf.is_null()).then(|| unsafe { std::slice::from_raw_parts(buf, size as usize) }.to_vec());
    unsafe { tjFree(buf) };
    if rc != 0 {
        bail!("jpeg encode: {}", h.error());
    }
    out.ok_or_else(|| anyhow::anyhow!("jpeg encode: no output"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encodes_and_decodes_at_scale() {
        // Left half dark, right half light.
        let (w, h) = (64u32, 32u32);
        let mut pixels = Vec::new();
        for _ in 0..h {
            for x in 0..w {
                let v = if x < w / 2 { 20 } else { 230 };
                pixels.extend_from_slice(&[v, v, v, 255]);
            }
        }
        let jpeg = encode(&Bgra { width: w, height: h, pixels }, 90).unwrap();
        assert_eq!(dimensions(&jpeg).unwrap(), (64, 32));
        let full = decode_scaled(&jpeg, u32::MAX).unwrap();
        assert_eq!((full.width, full.height), (64, 32));
        assert!(full.pixels[0] < 60 && full.pixels[(w as usize - 1) * 4] > 190);
        // A quarter is the smallest n/8 scale at least 16 px long.
        let quarter = decode_scaled(&jpeg, 16).unwrap();
        assert_eq!((quarter.width, quarter.height), (16, 8));
    }

    #[test]
    fn rejects_bad_input() {
        assert!(dimensions(b"not a jpeg").is_err());
        assert!(decode_scaled(b"not a jpeg", 10).is_err());
        assert!(encode(&Bgra { width: 4, height: 4, pixels: vec![0; 8] }, 80).is_err());
    }
}