use std::sync::Arc;
use std::sync::mpsc;
use crate::page_ir::{CompiledPage, DeviceRect, DeviceSize, Matrix, PageFeatures};
pub mod contract;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BackendId {
Cpu,
Wgpu,
Other(u32),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OutputFormat {
Rgba8PremultipliedSrgb,
Gray8,
}
impl OutputFormat {
pub fn bytes_per_pixel(self) -> usize {
match self {
OutputFormat::Rgba8PremultipliedSrgb => 4,
OutputFormat::Gray8 => 1,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Background {
White,
Transparent,
Solid(crate::page_ir::Color),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnnotationMode {
None,
StaticAppearances,
}
impl Default for AnnotationMode {
fn default() -> Self {
AnnotationMode::StaticAppearances
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderQuality {
Draft,
Normal,
}
#[derive(Debug, Clone)]
pub struct RenderLimits {
pub max_page_bytes: u64,
pub max_group_depth: u32,
pub cancellation: Option<CancellationToken>,
}
impl Default for RenderLimits {
fn default() -> Self {
Self {
max_page_bytes: 2 << 30,
max_group_depth: 64,
cancellation: None,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct CancellationToken {
cancelled: Arc<std::sync::atomic::AtomicBool>,
linked: Arc<[Arc<std::sync::atomic::AtomicBool>]>,
}
impl CancellationToken {
pub fn new() -> Self {
Self::default()
}
pub fn from_shared(cancelled: Arc<std::sync::atomic::AtomicBool>) -> Self {
Self {
cancelled,
linked: Arc::default(),
}
}
pub fn shared_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
self.cancelled.clone()
}
pub fn linked_with(&self, other: &Self) -> Self {
let mut linked = Vec::new();
for flag in std::iter::once(&self.cancelled)
.chain(self.linked.iter())
.chain(std::iter::once(&other.cancelled))
.chain(other.linked.iter())
{
if !linked.iter().any(|seen| Arc::ptr_eq(seen, flag)) {
linked.push(Arc::clone(flag));
}
}
Self {
cancelled: Arc::default(),
linked: linked.into(),
}
}
pub fn cancel(&self) {
self.cancelled
.store(true, std::sync::atomic::Ordering::Release);
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(std::sync::atomic::Ordering::Acquire)
|| self
.linked
.iter()
.any(|flag| flag.load(std::sync::atomic::Ordering::Acquire))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputResidency {
HostRequired,
BackendPreferred,
}
#[derive(Debug, Clone, Copy)]
pub struct PageTransform {
pub matrix: Matrix,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RenderColorPolicy {
#[default]
Original,
Night {
paper_rgb: [u8; 3],
text_rgb: [u8; 3],
},
WarmPaper {
paper_rgb: [u8; 3],
},
}
impl RenderColorPolicy {
pub fn paper_rgb(self) -> [u8; 3] {
match self {
Self::Original => [255, 255, 255],
Self::Night { paper_rgb, .. } | Self::WarmPaper { paper_rgb } => paper_rgb,
}
}
}
#[derive(Debug, Clone)]
pub struct RenderRequest {
pub page: Arc<CompiledPage>,
pub transform: PageTransform,
pub crop: Option<DeviceRect>,
pub output_size: DeviceSize,
pub output_format: OutputFormat,
pub background: Background,
pub color_policy: RenderColorPolicy,
pub annotations: AnnotationMode,
pub quality: RenderQuality,
pub limits: RenderLimits,
pub residency: OutputResidency,
}
#[derive(Debug, Clone)]
pub struct HostPage {
pub width: u32,
pub height: u32,
pub stride: usize,
pub format: OutputFormat,
pub pixels: Arc<[u8]>,
}
#[derive(Debug, Clone)]
pub struct ResidentPage {
pub backend: BackendId,
pub handle: u64,
pub size: DeviceSize,
pub format: OutputFormat,
}
#[derive(Debug, Clone)]
pub enum RenderedPage {
Host(HostPage),
Resident(ResidentPage),
}
impl RenderedPage {
pub fn as_host(&self) -> Option<&HostPage> {
match self {
RenderedPage::Host(h) => Some(h),
RenderedPage::Resident(_) => None,
}
}
}
#[derive(Debug, Clone)]
pub struct UnsupportedFeature {
pub missing: PageFeatures,
pub detail: &'static str,
}
#[derive(Debug, Clone)]
pub enum SupportLevel {
Native,
Unsupported(UnsupportedFeature),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PostprocessOperations(u16);
impl PostprocessOperations {
pub const CROP: Self = Self(1 << 0);
pub const RESIZE: Self = Self(1 << 1);
pub const CONVERT_TO_GRAY: Self = Self(1 << 2);
pub const APPLY_TONE_CURVE: Self = Self(1 << 3);
pub const OTSU: Self = Self(1 << 4);
pub const SAUVOLA: Self = Self(1 << 5);
pub const FUSE_THRESHOLDS: Self = Self(1 << 6);
pub const DITHER: Self = Self(1 << 7);
pub const PACK_MONOCHROME: Self = Self(1 << 8);
const ALL_BITS: u16 = (1 << 9) - 1;
pub const fn empty() -> Self {
Self(0)
}
pub const fn all() -> Self {
Self(Self::ALL_BITS)
}
pub const fn contains(self, required: Self) -> bool {
self.0 & required.0 == required.0
}
}
impl std::ops::BitOr for PostprocessOperations {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
Self(self.0 | rhs.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PostprocessCapabilities {
pub operations: PostprocessOperations,
pub resident_execution: bool,
}
impl PostprocessCapabilities {
pub const NONE: Self = Self {
operations: PostprocessOperations::empty(),
resident_execution: false,
};
pub const HOST_ALL: Self = Self {
operations: PostprocessOperations::all(),
resident_execution: false,
};
pub fn supports(self, required: PostprocessOperations) -> bool {
self.operations.contains(required)
}
}
impl Default for PostprocessCapabilities {
fn default() -> Self {
Self::NONE
}
}
#[derive(Debug, Clone)]
pub struct BackendCapabilities {
pub formats: Vec<OutputFormat>,
pub max_surface: DeviceSize,
pub features: PageFeatures,
pub resident_surfaces: bool,
pub postprocess: PostprocessCapabilities,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum RenderError {
#[error("page requires unsupported features: {0:?}")]
Unsupported(PageFeatures),
#[error("render limit exceeded: {0}")]
LimitExceeded(&'static str),
#[error("render cancelled")]
Cancelled,
#[error("backend failure: {0}")]
Backend(String),
#[error("GPU unavailable: {0}")]
GpuUnavailable(String),
#[error("GPU device lost")]
GpuDeviceLost,
#[error("GPU out of memory")]
GpuOutOfMemory,
#[error("readback failure: {0}")]
Readback(String),
#[error("result channel disconnected (backend dropped the job)")]
Disconnected,
#[error("backend panicked: {message}")]
Panic { message: String },
}
#[derive(Debug)]
pub struct RenderTicket {
pub job_id: u64,
state: std::cell::RefCell<TicketState>,
}
#[derive(Debug)]
enum TicketState {
Pending(mpsc::Receiver<Result<RenderedPage, RenderError>>),
Ready(Result<RenderedPage, RenderError>),
}
impl RenderTicket {
pub fn new(job_id: u64) -> (Self, mpsc::Sender<Result<RenderedPage, RenderError>>) {
let (tx, rx) = mpsc::channel();
(
Self {
job_id,
state: std::cell::RefCell::new(TicketState::Pending(rx)),
},
tx,
)
}
pub fn wait(self) -> Result<RenderedPage, RenderError> {
match self.state.into_inner() {
TicketState::Pending(receiver) => {
receiver.recv().unwrap_or(Err(RenderError::Disconnected))
}
TicketState::Ready(result) => result,
}
}
pub fn try_wait(&self) -> Option<Result<RenderedPage, RenderError>> {
let mut state = self.state.borrow_mut();
match &*state {
TicketState::Ready(result) => return Some(result.clone()),
TicketState::Pending(receiver) => {
let result = match receiver.try_recv() {
Ok(result) => result,
Err(mpsc::TryRecvError::Empty) => return None,
Err(mpsc::TryRecvError::Disconnected) => Err(RenderError::Disconnected),
};
*state = TicketState::Ready(result.clone());
Some(result)
}
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum SubmitError {
#[error("backend queue is full")]
QueueFull,
#[error("backend is shutting down")]
ShuttingDown,
#[error("request invalid: {0}")]
InvalidRequest(&'static str),
}
pub trait RenderBackend: Send + Sync + std::fmt::Debug {
fn id(&self) -> BackendId;
fn capabilities(&self) -> BackendCapabilities;
fn supports(&self, page: &CompiledPage, request: &RenderRequest) -> SupportLevel;
fn submit(&self, request: RenderRequest) -> Result<RenderTicket, SubmitError>;
fn working_surface_bytes(&self, request: &RenderRequest) -> u64 {
u64::from(request.output_size.width)
.saturating_mul(u64::from(request.output_size.height))
.saturating_mul(4)
}
}
pub fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
if let Some(s) = payload.downcast_ref::<&'static str>() {
(*s).to_owned()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"non-string panic payload".to_owned()
}
}
pub fn submit_caught(
backend: &dyn RenderBackend,
request: RenderRequest,
) -> Result<RenderTicket, SubmitError> {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| backend.submit(request))) {
Ok(outcome) => outcome,
Err(payload) => {
let (ticket, tx) = RenderTicket::new(u64::MAX);
let _ = tx.send(Err(RenderError::Panic {
message: panic_message(payload),
}));
Ok(ticket)
}
}
}
pub fn render_blocking(
backend: &dyn RenderBackend,
request: RenderRequest,
) -> Result<RenderedPage, RenderError> {
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
match backend.submit(request) {
Ok(ticket) => ticket.wait(),
Err(e) => Err(RenderError::Backend(e.to_string())),
}
}));
match outcome {
Ok(result) => result,
Err(payload) => Err(RenderError::Panic {
message: panic_message(payload),
}),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
const fn assert_send_sync<T: Send + Sync>() {}
const _: () = assert_send_sync::<RenderRequest>();
const _: () = assert_send_sync::<HostPage>();
#[test]
fn ticket_roundtrip() {
let (ticket, tx) = RenderTicket::new(7);
assert!(ticket.try_wait().is_none());
let page = HostPage {
width: 1,
height: 1,
stride: 4,
format: OutputFormat::Rgba8PremultipliedSrgb,
pixels: Arc::from([0u8; 4]),
};
tx.send(Ok(RenderedPage::Host(page))).unwrap();
assert!(matches!(ticket.wait(), Ok(RenderedPage::Host(_))));
}
#[test]
fn polling_completion_keeps_the_result_ready_until_wait() {
let (ticket, tx) = RenderTicket::new(9);
assert!(ticket.try_wait().is_none());
tx.send(Err(RenderError::Cancelled)).unwrap();
drop(tx);
for _ in 0..3 {
assert!(matches!(
ticket.try_wait(),
Some(Err(RenderError::Cancelled))
));
}
assert!(matches!(ticket.wait(), Err(RenderError::Cancelled)));
}
#[test]
fn linked_cancellation_observes_both_sources_without_cancelling_parents() {
for cancel_first in [false, true] {
let first = CancellationToken::new();
let second = CancellationToken::new();
let linked = first.linked_with(&second);
assert!(!linked.is_cancelled());
if cancel_first {
first.cancel();
} else {
second.cancel();
}
assert!(linked.is_cancelled());
}
let first = CancellationToken::new();
let second = CancellationToken::new();
first.linked_with(&second).cancel();
assert!(!first.is_cancelled());
assert!(!second.is_cancelled());
let third = CancellationToken::new();
let linked = first.linked_with(&second).linked_with(&third);
second.cancel();
assert!(linked.is_cancelled());
}
#[test]
fn dropped_sender_is_disconnected() {
let (ticket, tx) = RenderTicket::new(1);
drop(tx);
assert!(matches!(ticket.wait(), Err(RenderError::Disconnected)));
}
#[derive(Debug)]
struct PanickingBackend;
impl RenderBackend for PanickingBackend {
fn id(&self) -> BackendId {
BackendId::Other(0xDEAD)
}
fn capabilities(&self) -> BackendCapabilities {
BackendCapabilities {
formats: vec![OutputFormat::Rgba8PremultipliedSrgb],
max_surface: DeviceSize {
width: 1,
height: 1,
},
features: PageFeatures::empty(),
resident_surfaces: false,
postprocess: PostprocessCapabilities::NONE,
}
}
fn supports(&self, _page: &CompiledPage, _request: &RenderRequest) -> SupportLevel {
SupportLevel::Native
}
fn submit(&self, _request: RenderRequest) -> Result<RenderTicket, SubmitError> {
panic!("injected test panic: page 0 poisoned");
}
}
fn dummy_request() -> RenderRequest {
let page = CompiledPage::empty(crate::page_ir::PageBounds {
crop: crate::page_ir::Rect {
x0: 0.0,
y0: 0.0,
x1: 10.0,
y1: 10.0,
},
rotate: 0,
});
RenderRequest {
page: Arc::new(page),
transform: PageTransform {
matrix: Matrix::IDENTITY,
},
crop: None,
output_size: DeviceSize {
width: 4,
height: 4,
},
output_format: OutputFormat::Rgba8PremultipliedSrgb,
background: Background::White,
annotations: AnnotationMode::None,
color_policy: RenderColorPolicy::Original,
quality: RenderQuality::Normal,
limits: RenderLimits::default(),
residency: OutputResidency::HostRequired,
}
}
#[test]
fn injected_panic_becomes_typed_error_in_render_blocking() {
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let result = render_blocking(&PanickingBackend, dummy_request());
std::panic::set_hook(prev);
match result {
Err(RenderError::Panic { message }) => {
assert!(
message.contains("injected test panic"),
"message: {message}"
);
}
other => panic!("expected RenderError::Panic, got {other:?}"),
}
}
#[test]
fn injected_panic_becomes_typed_error_in_submit_caught() {
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let submitted = submit_caught(&PanickingBackend, dummy_request());
std::panic::set_hook(prev);
let ticket = submitted.expect("panic must yield a resolved ticket, not a SubmitError");
match ticket.wait() {
Err(RenderError::Panic { message }) => {
assert!(
message.contains("injected test panic"),
"message: {message}"
);
}
other => panic!("expected RenderError::Panic, got {other:?}"),
}
}
}