mod chroma;
mod fixed;
mod kernel;
mod source;
use alloc::vec::Vec;
use crate::error::{Error, Result};
use crate::hevc::{ChromaFormat, Frame};
use crate::image::{Image, PixelLayout, check_pixels};
use crate::parallel;
use crate::props::colr::Nclx;
use fixed::{AlphaScale, Coeffs};
use kernel::Mode;
pub(crate) use source::Source;
const DEPTHS: core::ops::RangeInclusive<u8> = 8..=16;
pub fn convert(
frame: &Frame,
alpha: Option<&Frame>,
nclx: Nclx,
layout: PixelLayout,
max_pixels: u64,
threads: Option<usize>,
) -> Result<Image> {
frame.validate()?;
convert_source(
&Source::Frame(frame),
alpha,
nclx,
layout,
max_pixels,
threads,
)
}
pub(crate) fn convert_source(
src: &Source<'_>,
alpha: Option<&Frame>,
nclx: Nclx,
layout: PixelLayout,
max_pixels: u64,
threads: Option<usize>,
) -> Result<Image> {
depth_ok(src.bit_depth())?;
let (w, h) = (src.width(), src.height());
check_pixels(w, h, max_pixels)?;
let mut image = Image::zeroed(w, h, layout, max_pixels)?;
let wide = layout.bytes_per_channel() == 2;
let coeffs = Coeffs::new(nclx, src.bit_depth(), wide);
let mode = if src.chroma() == ChromaFormat::Monochrome || layout.is_gray() {
Mode::Luma
} else if nclx.matrix.is_identity() {
Mode::Identity
} else {
Mode::Matrix
};
run(src, &coeffs, mode, &mut image, threads);
if let Some(a) = alpha.filter(|_| layout.has_alpha()) {
depth_ok(a.bit_depth)?;
let scale = AlphaScale::new(a.bit_depth, coeffs.max_out);
kernel::alpha(
&mut image.data,
a,
w as usize,
h as usize,
layout.bytes_per_pixel(),
&scale,
);
}
Ok(image)
}
fn depth_ok(depth: u8) -> Result<()> {
if DEPTHS.contains(&depth) {
return Ok(());
}
Err(Error::Unsupported("sample bit depth is outside 8 to 16"))
}
fn run(src: &Source<'_>, c: &Coeffs, mode: Mode, image: &mut Image, threads: Option<usize>) {
let out = &mut image.data;
match image.layout {
PixelLayout::Gray8 => bands::<1, false, false>(src, c, mode, out, threads),
PixelLayout::Rgb8 => bands::<3, false, false>(src, c, mode, out, threads),
PixelLayout::Bgr8 => bands::<3, true, false>(src, c, mode, out, threads),
PixelLayout::Rgba8 => bands::<4, false, false>(src, c, mode, out, threads),
PixelLayout::Bgra8 => bands::<4, true, false>(src, c, mode, out, threads),
PixelLayout::Rgb16 => bands::<6, false, true>(src, c, mode, out, threads),
PixelLayout::Rgba16 => bands::<8, false, true>(src, c, mode, out, threads),
}
}
const ROWS_PER_BAND: usize = 16;
const PARALLEL_FLOOR_PIXELS: u64 = 768 * 768;
fn bands<const N: usize, const BGR: bool, const WIDE: bool>(
src: &Source<'_>,
c: &Coeffs,
mode: Mode,
out: &mut [u8],
threads: Option<usize>,
) {
let w = src.width() as usize;
let scratch_len = kernel::scratch_len(src, mode);
let small = u64::from(src.width()) * u64::from(src.height()) < PARALLEL_FLOOR_PIXELS;
let threads = if small { Some(1) } else { threads };
parallel::for_each_band(out, w * N, ROWS_PER_BAND, threads, |y0, dst| {
let mut scratch: Vec<u16> = alloc::vec![0u16; scratch_len];
kernel::planes::<N, BGR, WIDE>(src, c, mode, &mut scratch, dst, y0);
});
}