1use std::sync::Arc;
4
5use crate::{
6 errors::{ErrorContext, OperationEffect, OperationFailure, OperationPhase},
7 operation,
8 style::OpaqueColor,
9 Error, Result,
10};
11
12use super::{ExportRegion, PngSizing};
13
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum PixelFormat {
18 #[default]
20 Rgba8,
21 Rgb8,
23 PremultipliedRgba8,
25 PremultipliedBgra8,
27}
28
29impl PixelFormat {
30 pub const fn channels(self) -> usize {
32 match self {
33 Self::Rgb8 => 3,
34 Self::Rgba8 | Self::PremultipliedRgba8 | Self::PremultipliedBgra8 => 4,
35 }
36 }
37
38 pub const fn name(self) -> &'static str {
40 match self {
41 Self::Rgba8 => "rgba8",
42 Self::Rgb8 => "rgb8",
43 Self::PremultipliedRgba8 => "premultiplied_rgba8",
44 Self::PremultipliedBgra8 => "premultiplied_bgra8",
45 }
46 }
47}
48
49impl std::str::FromStr for PixelFormat {
50 type Err = Error;
51
52 fn from_str(value: &str) -> Result<Self> {
53 match value {
54 "rgba8" => Ok(Self::Rgba8),
55 "rgb8" => Ok(Self::Rgb8),
56 "premultiplied_rgba8" => Ok(Self::PremultipliedRgba8),
57 "premultiplied_bgra8" => Ok(Self::PremultipliedBgra8),
58 _ => Err(Error::Data(
59 format!("unknown pixel format {value:?}").into(),
60 )),
61 }
62 }
63}
64
65#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
67pub enum RowOrder {
68 #[default]
70 TopDown,
71 BottomUp,
73}
74
75impl RowOrder {
76 pub const fn name(self) -> &'static str {
78 match self {
79 Self::TopDown => "top_down",
80 Self::BottomUp => "bottom_up",
81 }
82 }
83}
84
85impl std::str::FromStr for RowOrder {
86 type Err = Error;
87 fn from_str(value: &str) -> Result<Self> {
88 match value {
89 "top_down" => Ok(Self::TopDown),
90 "bottom_up" => Ok(Self::BottomUp),
91 _ => Err(Error::Data(
92 format!("unknown pixel row order {value:?}").into(),
93 )),
94 }
95 }
96}
97
98#[derive(Debug, Clone, Default, PartialEq)]
100#[must_use]
101pub struct PixelOptions {
102 pub(crate) sizing: Option<PngSizing>,
103 pub(crate) format: Option<PixelFormat>,
104 pub(crate) row_order: Option<RowOrder>,
105 pub(crate) matte: Option<OpaqueColor>,
106 pub(crate) region: ExportRegion,
107 pub(crate) transparent: bool,
108}
109
110impl PixelOptions {
111 pub const fn sizing(mut self, sizing: PngSizing) -> Self {
114 self.sizing = Some(sizing);
115 self
116 }
117
118 pub const fn pixel_format(mut self, format: PixelFormat) -> Self {
120 self.format = Some(format);
121 self
122 }
123
124 pub const fn row_order(mut self, order: RowOrder) -> Self {
126 self.row_order = Some(order);
127 self
128 }
129
130 pub const fn matte(mut self, color: OpaqueColor) -> Self {
132 self.matte = Some(color);
133 self
134 }
135
136 pub fn region(mut self, region: ExportRegion) -> Self {
138 self.region = region;
139 self
140 }
141
142 pub const fn transparent(mut self, transparent: bool) -> Self {
144 self.transparent = transparent;
145 self
146 }
147
148 pub(crate) fn for_target(mut self, target: &PixelTarget<'_>) -> Result<Self> {
149 if self.format.is_some_and(|format| format != target.format)
150 || self.row_order.is_some_and(|order| order != target.order)
151 {
152 return Err(Error::Data(
153 "pixel options do not match the target representation".into(),
154 ));
155 }
156 self.format = Some(target.format);
157 self.row_order = Some(target.order);
158 Ok(self)
159 }
160}
161
162#[derive(Debug, Clone)]
164pub struct PixelBuffer {
165 bytes: Arc<Vec<u8>>,
166 width: u32,
167 height: u32,
168 format: PixelFormat,
169 order: RowOrder,
170 dpi: Option<f64>,
171}
172
173impl PixelBuffer {
174 pub(crate) fn new(
175 bytes: Vec<u8>,
176 width: u32,
177 height: u32,
178 format: PixelFormat,
179 order: RowOrder,
180 dpi: Option<f64>,
181 ) -> Self {
182 Self {
183 bytes: Arc::new(bytes),
184 width,
185 height,
186 format,
187 order,
188 dpi,
189 }
190 }
191 pub const fn width(&self) -> u32 {
193 self.width
194 }
195 pub const fn height(&self) -> u32 {
197 self.height
198 }
199 pub fn stride(&self) -> usize {
201 self.width as usize * self.format.channels()
202 }
203 pub const fn pixel_format(&self) -> PixelFormat {
205 self.format
206 }
207 pub const fn row_order(&self) -> RowOrder {
209 self.order
210 }
211 pub const fn dpi(&self) -> Option<f64> {
213 self.dpi
214 }
215 pub const fn color_space(&self) -> &'static str {
217 "srgb"
218 }
219 pub fn as_bytes(&self) -> &[u8] {
221 &self.bytes
222 }
223
224 pub(crate) fn straight_rgba(&self) -> Result<std::borrow::Cow<'_, [u8]>> {
227 if self.format == PixelFormat::Rgba8 && self.order == RowOrder::TopDown {
228 return Ok(std::borrow::Cow::Borrowed(&self.bytes));
229 }
230 let mut bytes = Vec::new();
231 let len = self.width as usize * self.height as usize * 4;
232 bytes
233 .try_reserve_exact(len)
234 .map_err(|error| Error::Render(format!("pixel asset reservation: {error}").into()))?;
235 let stride = self.stride();
236 for row in 0..self.height as usize {
237 operation::checkpoint()?;
238 let row = match self.order {
239 RowOrder::TopDown => row,
240 RowOrder::BottomUp => self.height as usize - 1 - row,
241 };
242 for sample in
243 self.bytes[row * stride..(row + 1) * stride].chunks_exact(self.format.channels())
244 {
245 match self.format {
246 PixelFormat::Rgb8 => {
247 bytes.extend_from_slice(&[sample[0], sample[1], sample[2], 255]);
248 }
249 PixelFormat::Rgba8 => bytes.extend_from_slice(sample),
250 PixelFormat::PremultipliedRgba8 | PixelFormat::PremultipliedBgra8 => {
251 let alpha = sample[3];
252 let component = |value: u8| {
253 if alpha == 0 {
254 0
255 } else {
256 let numerator = u32::from(value) * 255;
257 let divisor = u32::from(alpha);
258 let quotient = numerator / divisor;
259 let remainder = numerator % divisor;
260 let up = remainder * 2 > divisor
261 || (remainder * 2 == divisor && quotient % 2 == 1);
262 u8::try_from((quotient + u32::from(up)).min(255))
263 .expect("byte sample")
264 }
265 };
266 let (red, blue) = if self.format == PixelFormat::PremultipliedRgba8 {
267 (sample[0], sample[2])
268 } else {
269 (sample[2], sample[0])
270 };
271 bytes.extend_from_slice(&[
272 component(red),
273 component(sample[1]),
274 component(blue),
275 alpha,
276 ]);
277 }
278 }
279 }
280 }
281 Ok(std::borrow::Cow::Owned(bytes))
282 }
283}
284
285type RowWriter<'a> = dyn FnMut(u32, &[u8], &mut bool) -> Result<()> + 'a;
286
287enum Storage<'a> {
288 Borrowed {
289 bytes: &'a mut [u8],
290 stride: usize,
291 reverse: bool,
292 },
293 Rows(&'a mut RowWriter<'a>),
294}
295
296pub struct PixelTarget<'a> {
299 width: u32,
300 height: u32,
301 format: PixelFormat,
302 order: RowOrder,
303 storage: Storage<'a>,
304}
305
306impl<'a> PixelTarget<'a> {
307 pub fn rgba8(bytes: &'a mut [u8], width: u32, height: u32, stride: isize) -> Result<Self> {
309 Self::new(
310 bytes,
311 width,
312 height,
313 stride,
314 PixelFormat::Rgba8,
315 RowOrder::TopDown,
316 )
317 }
318
319 pub fn new(
322 bytes: &'a mut [u8],
323 width: u32,
324 height: u32,
325 stride: isize,
326 format: PixelFormat,
327 order: RowOrder,
328 ) -> Result<Self> {
329 let row_bytes = row_bytes(width, height, format)?;
330 let pitch = stride.unsigned_abs();
331 let required = pitch
332 .checked_mul(height as usize - 1)
333 .and_then(|offset| offset.checked_add(row_bytes));
334 if pitch < row_bytes || required.is_none_or(|required| required > bytes.len()) {
335 return Err(Error::Data(
336 "pixel target stride or storage does not contain the active rows".into(),
337 ));
338 }
339 Ok(Self {
340 width,
341 height,
342 format,
343 order,
344 storage: Storage::Borrowed {
345 bytes,
346 stride: pitch,
347 reverse: stride < 0,
348 },
349 })
350 }
351
352 #[doc(hidden)]
357 pub fn host_rows(
358 width: u32,
359 height: u32,
360 format: PixelFormat,
361 order: RowOrder,
362 writer: &'a mut RowWriter<'a>,
363 ) -> Result<Self> {
364 row_bytes(width, height, format)?;
365 Ok(Self {
366 width,
367 height,
368 format,
369 order,
370 storage: Storage::Rows(writer),
371 })
372 }
373
374 pub(crate) fn dimensions(&self) -> (u32, u32) {
375 (self.width, self.height)
376 }
377
378 pub(crate) fn copy(mut self, pixels: &PixelBuffer) -> Result<()> {
379 if self.dimensions() != (pixels.width, pixels.height)
380 || self.format != pixels.format
381 || self.order != pixels.order
382 {
383 return Err(Error::Data(
384 "pixel target does not match the requested sampling or representation".into(),
385 ));
386 }
387 let mut started = false;
388 let result = (|| {
389 for (row, samples) in pixels.bytes.chunks_exact(pixels.stride()).enumerate() {
390 operation::checkpoint()?;
391 match &mut self.storage {
392 Storage::Borrowed {
393 bytes,
394 stride,
395 reverse,
396 } => {
397 let row = if *reverse {
398 self.height as usize - 1 - row
399 } else {
400 row
401 };
402 let offset = row * *stride;
403 started = true;
404 bytes[offset..offset + samples.len()].copy_from_slice(samples);
405 }
406 Storage::Rows(write) => {
407 let mut attempted = false;
408 let result = operation::external(|| {
409 write(
410 u32::try_from(row).expect("admitted pixel row"),
411 samples,
412 &mut attempted,
413 )
414 });
415 started |= attempted || result.is_ok();
416 result?;
417 }
418 }
419 }
420 Ok(())
421 })();
422 result.map_err(|cause| {
423 if started {
424 Error::Operation(Box::new(OperationFailure::new(
425 OperationPhase::Write,
426 ErrorContext::new().with_operation(OperationPhase::Write),
427 OperationEffect::PixelTargetIndeterminate,
428 cause,
429 )))
430 } else {
431 cause
432 }
433 })
434 }
435}
436
437fn row_bytes(width: u32, height: u32, format: PixelFormat) -> Result<usize> {
438 if width == 0 || height == 0 {
439 return Err(Error::Data(
440 "pixel target dimensions must be positive".into(),
441 ));
442 }
443 (width as usize)
444 .checked_mul(format.channels())
445 .ok_or_else(|| Error::Data("pixel row storage size overflows".into()))
446}