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;
#[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()
}
}
#[derive(Clone)]
pub struct Bgra {
pub width: u32,
pub height: u32,
pub pixels: Vec<u8>,
}
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))
}
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;
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,
)
};
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 })
}
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;
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() {
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);
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());
}
}