use std::sync::Arc;
use crate::{
errors::{ErrorContext, OperationEffect, OperationFailure, OperationPhase},
operation,
style::OpaqueColor,
Error, Result,
};
use super::{ExportRegion, PngSizing};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PixelFormat {
#[default]
Rgba8,
Rgb8,
PremultipliedRgba8,
PremultipliedBgra8,
}
impl PixelFormat {
pub const fn channels(self) -> usize {
match self {
Self::Rgb8 => 3,
Self::Rgba8 | Self::PremultipliedRgba8 | Self::PremultipliedBgra8 => 4,
}
}
pub const fn name(self) -> &'static str {
match self {
Self::Rgba8 => "rgba8",
Self::Rgb8 => "rgb8",
Self::PremultipliedRgba8 => "premultiplied_rgba8",
Self::PremultipliedBgra8 => "premultiplied_bgra8",
}
}
}
impl std::str::FromStr for PixelFormat {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
match value {
"rgba8" => Ok(Self::Rgba8),
"rgb8" => Ok(Self::Rgb8),
"premultiplied_rgba8" => Ok(Self::PremultipliedRgba8),
"premultiplied_bgra8" => Ok(Self::PremultipliedBgra8),
_ => Err(Error::Data(
format!("unknown pixel format {value:?}").into(),
)),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RowOrder {
#[default]
TopDown,
BottomUp,
}
impl RowOrder {
pub const fn name(self) -> &'static str {
match self {
Self::TopDown => "top_down",
Self::BottomUp => "bottom_up",
}
}
}
impl std::str::FromStr for RowOrder {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
match value {
"top_down" => Ok(Self::TopDown),
"bottom_up" => Ok(Self::BottomUp),
_ => Err(Error::Data(
format!("unknown pixel row order {value:?}").into(),
)),
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
#[must_use]
pub struct PixelOptions {
pub(crate) sizing: Option<PngSizing>,
pub(crate) format: Option<PixelFormat>,
pub(crate) row_order: Option<RowOrder>,
pub(crate) matte: Option<OpaqueColor>,
pub(crate) region: ExportRegion,
pub(crate) transparent: bool,
}
impl PixelOptions {
pub const fn sizing(mut self, sizing: PngSizing) -> Self {
self.sizing = Some(sizing);
self
}
pub const fn pixel_format(mut self, format: PixelFormat) -> Self {
self.format = Some(format);
self
}
pub const fn row_order(mut self, order: RowOrder) -> Self {
self.row_order = Some(order);
self
}
pub const fn matte(mut self, color: OpaqueColor) -> Self {
self.matte = Some(color);
self
}
pub fn region(mut self, region: ExportRegion) -> Self {
self.region = region;
self
}
pub const fn transparent(mut self, transparent: bool) -> Self {
self.transparent = transparent;
self
}
pub(crate) fn for_target(mut self, target: &PixelTarget<'_>) -> Result<Self> {
if self.format.is_some_and(|format| format != target.format)
|| self.row_order.is_some_and(|order| order != target.order)
{
return Err(Error::Data(
"pixel options do not match the target representation".into(),
));
}
self.format = Some(target.format);
self.row_order = Some(target.order);
Ok(self)
}
}
#[derive(Debug, Clone)]
pub struct PixelBuffer {
bytes: Arc<Vec<u8>>,
width: u32,
height: u32,
format: PixelFormat,
order: RowOrder,
dpi: Option<f64>,
}
impl PixelBuffer {
pub(crate) fn new(
bytes: Vec<u8>,
width: u32,
height: u32,
format: PixelFormat,
order: RowOrder,
dpi: Option<f64>,
) -> Self {
Self {
bytes: Arc::new(bytes),
width,
height,
format,
order,
dpi,
}
}
pub const fn width(&self) -> u32 {
self.width
}
pub const fn height(&self) -> u32 {
self.height
}
pub fn stride(&self) -> usize {
self.width as usize * self.format.channels()
}
pub const fn pixel_format(&self) -> PixelFormat {
self.format
}
pub const fn row_order(&self) -> RowOrder {
self.order
}
pub const fn dpi(&self) -> Option<f64> {
self.dpi
}
pub const fn color_space(&self) -> &'static str {
"srgb"
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub(crate) fn straight_rgba(&self) -> Result<std::borrow::Cow<'_, [u8]>> {
if self.format == PixelFormat::Rgba8 && self.order == RowOrder::TopDown {
return Ok(std::borrow::Cow::Borrowed(&self.bytes));
}
let mut bytes = Vec::new();
let len = self.width as usize * self.height as usize * 4;
bytes
.try_reserve_exact(len)
.map_err(|error| Error::Render(format!("pixel asset reservation: {error}").into()))?;
let stride = self.stride();
for row in 0..self.height as usize {
operation::checkpoint()?;
let row = match self.order {
RowOrder::TopDown => row,
RowOrder::BottomUp => self.height as usize - 1 - row,
};
for sample in
self.bytes[row * stride..(row + 1) * stride].chunks_exact(self.format.channels())
{
match self.format {
PixelFormat::Rgb8 => {
bytes.extend_from_slice(&[sample[0], sample[1], sample[2], 255]);
}
PixelFormat::Rgba8 => bytes.extend_from_slice(sample),
PixelFormat::PremultipliedRgba8 | PixelFormat::PremultipliedBgra8 => {
let alpha = sample[3];
let component = |value: u8| {
if alpha == 0 {
0
} else {
let numerator = u32::from(value) * 255;
let divisor = u32::from(alpha);
let quotient = numerator / divisor;
let remainder = numerator % divisor;
let up = remainder * 2 > divisor
|| (remainder * 2 == divisor && quotient % 2 == 1);
u8::try_from((quotient + u32::from(up)).min(255))
.expect("byte sample")
}
};
let (red, blue) = if self.format == PixelFormat::PremultipliedRgba8 {
(sample[0], sample[2])
} else {
(sample[2], sample[0])
};
bytes.extend_from_slice(&[
component(red),
component(sample[1]),
component(blue),
alpha,
]);
}
}
}
}
Ok(std::borrow::Cow::Owned(bytes))
}
}
type RowWriter<'a> = dyn FnMut(u32, &[u8], &mut bool) -> Result<()> + 'a;
enum Storage<'a> {
Borrowed {
bytes: &'a mut [u8],
stride: usize,
reverse: bool,
},
Rows(&'a mut RowWriter<'a>),
}
pub struct PixelTarget<'a> {
width: u32,
height: u32,
format: PixelFormat,
order: RowOrder,
storage: Storage<'a>,
}
impl<'a> PixelTarget<'a> {
pub fn rgba8(bytes: &'a mut [u8], width: u32, height: u32, stride: isize) -> Result<Self> {
Self::new(
bytes,
width,
height,
stride,
PixelFormat::Rgba8,
RowOrder::TopDown,
)
}
pub fn new(
bytes: &'a mut [u8],
width: u32,
height: u32,
stride: isize,
format: PixelFormat,
order: RowOrder,
) -> Result<Self> {
let row_bytes = row_bytes(width, height, format)?;
let pitch = stride.unsigned_abs();
let required = pitch
.checked_mul(height as usize - 1)
.and_then(|offset| offset.checked_add(row_bytes));
if pitch < row_bytes || required.is_none_or(|required| required > bytes.len()) {
return Err(Error::Data(
"pixel target stride or storage does not contain the active rows".into(),
));
}
Ok(Self {
width,
height,
format,
order,
storage: Storage::Borrowed {
bytes,
stride: pitch,
reverse: stride < 0,
},
})
}
#[doc(hidden)]
pub fn host_rows(
width: u32,
height: u32,
format: PixelFormat,
order: RowOrder,
writer: &'a mut RowWriter<'a>,
) -> Result<Self> {
row_bytes(width, height, format)?;
Ok(Self {
width,
height,
format,
order,
storage: Storage::Rows(writer),
})
}
pub(crate) fn dimensions(&self) -> (u32, u32) {
(self.width, self.height)
}
pub(crate) fn copy(mut self, pixels: &PixelBuffer) -> Result<()> {
if self.dimensions() != (pixels.width, pixels.height)
|| self.format != pixels.format
|| self.order != pixels.order
{
return Err(Error::Data(
"pixel target does not match the requested sampling or representation".into(),
));
}
let mut started = false;
let result = (|| {
for (row, samples) in pixels.bytes.chunks_exact(pixels.stride()).enumerate() {
operation::checkpoint()?;
match &mut self.storage {
Storage::Borrowed {
bytes,
stride,
reverse,
} => {
let row = if *reverse {
self.height as usize - 1 - row
} else {
row
};
let offset = row * *stride;
started = true;
bytes[offset..offset + samples.len()].copy_from_slice(samples);
}
Storage::Rows(write) => {
let mut attempted = false;
let result = operation::external(|| {
write(
u32::try_from(row).expect("admitted pixel row"),
samples,
&mut attempted,
)
});
started |= attempted || result.is_ok();
result?;
}
}
}
Ok(())
})();
result.map_err(|cause| {
if started {
Error::Operation(Box::new(OperationFailure::new(
OperationPhase::Write,
ErrorContext::new().with_operation(OperationPhase::Write),
OperationEffect::PixelTargetIndeterminate,
cause,
)))
} else {
cause
}
})
}
}
fn row_bytes(width: u32, height: u32, format: PixelFormat) -> Result<usize> {
if width == 0 || height == 0 {
return Err(Error::Data(
"pixel target dimensions must be positive".into(),
));
}
(width as usize)
.checked_mul(format.channels())
.ok_or_else(|| Error::Data("pixel row storage size overflows".into()))
}