use dcmnorm_dictionary::{tags, uids};
use dcmnorm_object::{DefaultDicomObject, InMemDicomObject};
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;
use super::region::Region;
use super::render::{
draw_bounding_boxes, encode_rendered_frame, icc_profile_to_srgb_transform, maybe_pad_frame,
maybe_resize_frame, render_dicom_frame, render_dicom_frame_pixels, resolve_grayscale_invert,
rgb_to_luma, scale_by_ratio, scale_to_max_dimension, IccTransform, RenderFrameOutput,
RenderOutputFormat, RenderPipelineOptions, RenderedFramePixels,
};
use super::types::RenderError;
pub const DEFAULT_WSI_MAX_OUTPUT_PIXELS: u64 = 100_000_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WsiDimensionOrganization {
TiledFull,
TiledSparse,
}
impl WsiDimensionOrganization {
pub fn as_str(&self) -> &'static str {
match self {
Self::TiledFull => "TILED_FULL",
Self::TiledSparse => "TILED_SPARSE",
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct WsiLevelInfo {
pub index: usize,
pub input_index: usize,
pub total_columns: u32,
pub total_rows: u32,
pub tile_columns: u32,
pub tile_rows: u32,
pub number_of_frames: usize,
pub dimension_organization: WsiDimensionOrganization,
pub focal_planes: usize,
pub optical_paths: usize,
pub samples_per_pixel: u16,
pub photometric_interpretation: String,
pub transfer_syntax_uid: String,
pub image_type: Vec<String>,
pub sop_instance_uid: Option<String>,
pub series_instance_uid: Option<String>,
pub pixel_spacing_mm: Option<[f64; 2]>,
pub downsample: f64,
}
#[derive(Clone, Debug)]
pub struct WsiRenderOptions {
pub render: RenderPipelineOptions,
pub background_color: [u8; 3],
pub level: Option<usize>,
pub focal_plane_index: usize,
pub optical_path_index: usize,
pub max_output_pixels: u64,
}
impl Default for WsiRenderOptions {
fn default() -> Self {
Self {
render: RenderPipelineOptions::default(),
background_color: [255, 255, 255],
level: None,
focal_plane_index: 0,
optical_path_index: 0,
max_output_pixels: DEFAULT_WSI_MAX_OUTPUT_PIXELS,
}
}
}
#[derive(Clone, Debug)]
pub struct WsiRenderOutput {
pub frame: RenderFrameOutput,
pub level: WsiLevelInfo,
pub region: Region,
pub level_region: Region,
pub tiles_decoded: usize,
}
pub fn is_whole_slide_object(object: &DefaultDicomObject) -> bool {
let sop_class = object
.get(tags::SOP_CLASS_UID)
.and_then(|element| element.to_str().ok())
.map(|value| value.trim_end_matches(['\0', ' ']).to_owned())
.unwrap_or_else(|| {
object
.meta()
.media_storage_sop_class_uid()
.trim_end_matches(['\0', ' '])
.to_owned()
});
sop_class == uids::VL_WHOLE_SLIDE_MICROSCOPY_IMAGE_STORAGE
}
pub fn describe_wsi(objects: &[&DefaultDicomObject]) -> Result<Vec<WsiLevelInfo>, RenderError> {
build_pyramid(objects)
}
pub fn render_wsi(
objects: &[&DefaultDicomObject],
output_format: RenderOutputFormat,
options: &WsiRenderOptions,
) -> Result<WsiRenderOutput, RenderError> {
let levels = build_pyramid(objects)?;
let plan = plan_render(&levels, options)?;
let object = objects[plan.level.input_index];
render_planned(object, plan, output_format, options)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn describe_wsi_files<P: AsRef<std::path::Path>>(
paths: &[P],
) -> Result<Vec<WsiLevelInfo>, RenderError> {
let headers = read_headers(paths)?;
let refs: Vec<&DefaultDicomObject> = headers.iter().collect();
build_pyramid(&refs)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn render_wsi_files<P: AsRef<std::path::Path>>(
paths: &[P],
output_format: RenderOutputFormat,
options: &WsiRenderOptions,
) -> Result<WsiRenderOutput, RenderError> {
let headers = read_headers(paths)?;
let refs: Vec<&DefaultDicomObject> = headers.iter().collect();
let levels = build_pyramid(&refs)?;
let plan = plan_render(&levels, options)?;
let path = paths[plan.level.input_index].as_ref();
let object = super::io::read_dicom_file(path)
.map_err(|error| RenderError::WholeSlide(format!("reading {}: {error}", path.display())))?;
render_planned(&object, plan, output_format, options)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn is_whole_slide_file(path: impl AsRef<std::path::Path>) -> bool {
read_header(path.as_ref())
.map(|object| is_whole_slide_object(&object))
.unwrap_or(false)
}
#[cfg(not(target_arch = "wasm32"))]
fn read_header(path: &std::path::Path) -> Result<DefaultDicomObject, RenderError> {
dcmnorm_object::OpenFileOptions::new()
.read_preamble(dcmnorm_object::ReadPreamble::Always)
.read_until(dcmnorm_core::Tag(0x7FDF, 0xFFFF))
.open_file(path)
.map_err(|error| RenderError::WholeSlide(format!("reading {}: {error}", path.display())))
}
#[cfg(not(target_arch = "wasm32"))]
fn read_headers<P: AsRef<std::path::Path>>(
paths: &[P],
) -> Result<Vec<DefaultDicomObject>, RenderError> {
paths
.iter()
.map(|path| read_header(path.as_ref()))
.collect()
}
fn wsi_error(message: impl Into<String>) -> RenderError {
RenderError::WholeSlide(message.into())
}
fn text(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<String> {
object
.get(tag)
.and_then(|element| element.to_str().ok())
.map(|value| value.trim_end_matches(['\0', ' ']).trim().to_owned())
.filter(|value| !value.is_empty())
}
fn uint(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<u64> {
object.get(tag).and_then(|element| {
element.to_int::<u64>().ok().or_else(|| {
element
.to_str()
.ok()
.and_then(|value| value.split('\\').next()?.trim().parse::<u64>().ok())
})
})
}
fn float(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<f64> {
object.get(tag).and_then(|element| {
element.to_float64().ok().or_else(|| {
element
.to_str()
.ok()
.and_then(|value| value.split('\\').next()?.trim().parse::<f64>().ok())
})
})
}
fn first_item(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<&InMemDicomObject> {
object.get(tag)?.value().items()?.first()
}
fn items(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> &[InMemDicomObject] {
object
.get(tag)
.and_then(|element| element.value().items())
.unwrap_or(&[])
}
fn optical_path_identifiers(object: &InMemDicomObject) -> Vec<String> {
items(object, tags::OPTICAL_PATH_SEQUENCE)
.iter()
.map(|item| text(item, tags::OPTICAL_PATH_IDENTIFIER).unwrap_or_default())
.collect()
}
fn frame_optical_path(object: &InMemDicomObject, frame_index: usize) -> Option<String> {
let lookup = |group: &InMemDicomObject| {
first_item(group, tags::OPTICAL_PATH_IDENTIFICATION_SEQUENCE)
.and_then(|item| text(item, tags::OPTICAL_PATH_IDENTIFIER))
};
items(object, tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE)
.get(frame_index)
.and_then(lookup)
.or_else(|| first_item(object, tags::SHARED_FUNCTIONAL_GROUPS_SEQUENCE).and_then(lookup))
}
fn sparse_position(item: &InMemDicomObject) -> Option<(i64, i64, Option<f64>)> {
let position = first_item(item, tags::PLANE_POSITION_SLIDE_SEQUENCE)?;
let column = position
.get(tags::COLUMN_POSITION_IN_TOTAL_IMAGE_PIXEL_MATRIX)?
.to_int::<i64>()
.ok()?;
let row = position
.get(tags::ROW_POSITION_IN_TOTAL_IMAGE_PIXEL_MATRIX)?
.to_int::<i64>()
.ok()?;
let z = float(position, tags::Z_OFFSET_IN_SLIDE_COORDINATE_SYSTEM);
Some((column - 1, row - 1, z))
}
fn z_key(z: Option<f64>) -> i64 {
z.map(|value| (value * 1e6).round() as i64).unwrap_or(0)
}
fn sorted_focal_planes(object: &InMemDicomObject) -> Vec<i64> {
let mut keys: Vec<i64> = items(object, tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE)
.iter()
.filter_map(sparse_position)
.map(|(_, _, z)| z_key(z))
.collect();
keys.sort_unstable();
keys.dedup();
if keys.is_empty() {
keys.push(0);
}
keys
}
fn dimension_organization(object: &InMemDicomObject) -> WsiDimensionOrganization {
match text(object, tags::DIMENSION_ORGANIZATION_TYPE).as_deref() {
Some("TILED_SPARSE") => WsiDimensionOrganization::TiledSparse,
Some("TILED_FULL") => WsiDimensionOrganization::TiledFull,
_ => {
let has_positions = items(object, tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE)
.first()
.and_then(sparse_position)
.is_some();
if has_positions {
WsiDimensionOrganization::TiledSparse
} else {
WsiDimensionOrganization::TiledFull
}
}
}
}
fn level_info(
object: &DefaultDicomObject,
input_index: usize,
) -> Result<WsiLevelInfo, RenderError> {
let sop_instance_uid = text(object, tags::SOP_INSTANCE_UID);
let name = sop_instance_uid
.clone()
.unwrap_or_else(|| format!("input {input_index}"));
let tile_columns = uint(object, tags::COLUMNS)
.ok_or_else(|| wsi_error(format!("{name} has no Columns")))? as u32;
let tile_rows =
uint(object, tags::ROWS).ok_or_else(|| wsi_error(format!("{name} has no Rows")))? as u32;
let number_of_frames = usize::try_from(uint(object, tags::NUMBER_OF_FRAMES).unwrap_or(1))
.map_err(|_| {
wsi_error(format!(
"{name} has more frames than this platform can index"
))
})?;
let total_columns = uint(object, tags::TOTAL_PIXEL_MATRIX_COLUMNS)
.map(|value| value as u32)
.unwrap_or(tile_columns);
let total_rows = uint(object, tags::TOTAL_PIXEL_MATRIX_ROWS)
.map(|value| value as u32)
.unwrap_or(tile_rows);
if tile_columns == 0 || tile_rows == 0 || total_columns == 0 || total_rows == 0 {
return Err(wsi_error(format!(
"{name} has an empty tile or total pixel matrix"
)));
}
let organization = dimension_organization(object);
let focal_planes = match organization {
WsiDimensionOrganization::TiledFull => uint(object, tags::TOTAL_PIXEL_MATRIX_FOCAL_PLANES)
.unwrap_or(1)
.max(1) as usize,
WsiDimensionOrganization::TiledSparse => sorted_focal_planes(object).len(),
};
let optical_paths = uint(object, tags::NUMBER_OF_OPTICAL_PATHS)
.map(|value| value as usize)
.unwrap_or_else(|| optical_path_identifiers(object).len())
.max(1);
let pixel_spacing_mm = first_item(object, tags::SHARED_FUNCTIONAL_GROUPS_SEQUENCE)
.and_then(|group| first_item(group, tags::PIXEL_MEASURES_SEQUENCE))
.and_then(|measures| text(measures, tags::PIXEL_SPACING))
.and_then(|value| {
let parts: Vec<f64> = value
.split('\\')
.filter_map(|part| part.trim().parse::<f64>().ok())
.collect();
(parts.len() == 2).then(|| [parts[0], parts[1]])
});
Ok(WsiLevelInfo {
index: 0,
input_index,
total_columns,
total_rows,
tile_columns,
tile_rows,
number_of_frames,
dimension_organization: organization,
focal_planes,
optical_paths,
samples_per_pixel: uint(object, tags::SAMPLES_PER_PIXEL).unwrap_or(1) as u16,
photometric_interpretation: text(object, tags::PHOTOMETRIC_INTERPRETATION)
.unwrap_or_else(|| "MONOCHROME2".to_owned()),
transfer_syntax_uid: object
.meta()
.transfer_syntax()
.trim_end_matches(['\0', ' '])
.to_owned(),
image_type: text(object, tags::IMAGE_TYPE)
.map(|value| value.split('\\').map(|v| v.trim().to_owned()).collect())
.unwrap_or_default(),
sop_instance_uid,
series_instance_uid: text(object, tags::SERIES_INSTANCE_UID),
pixel_spacing_mm,
downsample: 1.0,
})
}
fn build_pyramid(objects: &[&DefaultDicomObject]) -> Result<Vec<WsiLevelInfo>, RenderError> {
if objects.is_empty() {
return Err(wsi_error("no input instances"));
}
let mut levels = Vec::with_capacity(objects.len());
for (input_index, object) in objects.iter().enumerate() {
levels.push(level_info(object, input_index)?);
}
if levels.len() > 1 {
let series = levels[0].series_instance_uid.clone();
if levels
.iter()
.any(|level| level.series_instance_uid != series)
{
return Err(wsi_error(
"the inputs belong to different series; pass the levels of one pyramid",
));
}
levels.retain(|level| {
!matches!(
level.image_type.get(2).map(String::as_str),
Some("LABEL") | Some("OVERVIEW")
)
});
if levels.is_empty() {
return Err(wsi_error(
"none of the inputs is a pyramid level (all are LABEL/OVERVIEW images)",
));
}
}
levels.sort_by_key(|level| std::cmp::Reverse((level.total_columns, level.total_rows)));
levels.dedup_by(|b, a| a.total_columns == b.total_columns && a.total_rows == b.total_rows);
let base_columns = f64::from(levels[0].total_columns);
for (index, level) in levels.iter_mut().enumerate() {
level.index = index;
level.downsample = base_columns / f64::from(level.total_columns);
}
Ok(levels)
}
struct RenderPlan {
level: WsiLevelInfo,
base_region: Region,
level_region: Region,
output: (u32, u32),
decimation: (u32, u32),
}
fn requested_output(
width: u32,
height: u32,
options: &RenderPipelineOptions,
) -> Result<Option<(u32, u32)>, RenderError> {
match (
options.output_width,
options.output_height,
options.scale_max_size,
) {
(None, None, None) => Ok(None),
(Some(w), Some(h), None) => Ok(Some((w, h))),
(Some(w), None, None) => Ok(Some((w, scale_by_ratio(height, width, w)))),
(None, Some(h), None) => Ok(Some((scale_by_ratio(width, height, h), h))),
(None, None, Some(max)) => Ok(Some(scale_to_max_dimension(width, height, max))),
_ => Err(wsi_error(
"scale_max_size can't be combined with output_width/output_height",
)),
}
}
fn plan_render(
levels: &[WsiLevelInfo],
options: &WsiRenderOptions,
) -> Result<RenderPlan, RenderError> {
let base = &levels[0];
let full = Region::new(0, 0, base.total_columns, base.total_rows);
let base_region = options
.render
.region
.unwrap_or(full)
.clamp_to(u64::from(base.total_columns), u64::from(base.total_rows))?;
let target = requested_output(base_region.width, base_region.height, &options.render)?;
if let Some((width, height)) = target {
if width == 0 || height == 0 {
return Err(wsi_error("output width/height must be greater than zero"));
}
}
let level = match options.level {
Some(index) => levels.get(index).ok_or_else(|| {
wsi_error(format!(
"level {index} is out of range; the pyramid has {} level(s)",
levels.len()
))
})?,
None => match target {
Some((width, height)) => levels
.iter()
.rev()
.find(|level| {
let columns = f64::from(base_region.width) * f64::from(level.total_columns)
/ f64::from(base.total_columns);
let rows = f64::from(base_region.height) * f64::from(level.total_rows)
/ f64::from(base.total_rows);
columns + 1.0 + 1e-9 >= f64::from(width)
&& rows + 1.0 + 1e-9 >= f64::from(height)
})
.unwrap_or(base),
None => base,
},
};
let fx = f64::from(base.total_columns) / f64::from(level.total_columns);
let fy = f64::from(base.total_rows) / f64::from(level.total_rows);
let left = (base_region.x as f64 / fx).floor() as i64;
let top = (base_region.y as f64 / fy).floor() as i64;
let right = ((base_region.right() as f64 / fx).ceil() as i64)
.clamp(left + 1, i64::from(level.total_columns));
let bottom = ((base_region.bottom() as f64 / fy).ceil() as i64)
.clamp(top + 1, i64::from(level.total_rows));
let level_region = Region::new(left, top, (right - left) as u32, (bottom - top) as u32);
let output = target.unwrap_or((level_region.width, level_region.height));
let final_size = match options.render.scale_max_size {
Some(max_dim) if options.render.pad => {
let side = max_dim.max(output.0).max(output.1);
(side, side)
}
_ => output,
};
let pixels = u64::from(final_size.0) * u64::from(final_size.1);
if final_size.0 > u32::from(u16::MAX)
|| final_size.1 > u32::from(u16::MAX)
|| pixels > options.max_output_pixels
{
let padded = if final_size == output {
String::new()
} else {
format!(" ({}x{} before padding)", output.0, output.1)
};
return Err(wsi_error(format!(
"the stitched output would be {}x{} pixels{padded}, over the limit ({} pixels, 65535 per side); \
request a smaller region or a downsampled output (output_width/output_height/scale_max_size)",
final_size.0, final_size.1, options.max_output_pixels
)));
}
let max_side = u32::from(u16::MAX);
let axis = |region_side: u32, output_side: u32| {
let k = if target.is_some() {
(region_side / output_side).max(1)
} else {
1
};
k.max(region_side.div_ceil(max_side))
};
let decimation = (
axis(level_region.width, output.0),
axis(level_region.height, output.1),
);
Ok(RenderPlan {
level: level.clone(),
base_region,
level_region,
output,
decimation,
})
}
fn tile_positions(
object: &DefaultDicomObject,
level: &WsiLevelInfo,
options: &WsiRenderOptions,
region: Region,
) -> Result<Vec<(usize, i64, i64)>, RenderError> {
let tile_w = i64::from(level.tile_columns);
let tile_h = i64::from(level.tile_rows);
let right = region.right().min(i64::from(level.total_columns));
let bottom = region.bottom().min(i64::from(level.total_rows));
let intersects = |column: i64, row: i64| {
column < right && column + tile_w > region.x && row < bottom && row + tile_h > region.y
};
if options.focal_plane_index >= level.focal_planes {
return Err(wsi_error(format!(
"focal plane {} is out of range; the level has {} focal plane(s)",
options.focal_plane_index, level.focal_planes
)));
}
if options.optical_path_index >= level.optical_paths {
return Err(wsi_error(format!(
"optical path {} is out of range; the level has {} optical path(s)",
options.optical_path_index, level.optical_paths
)));
}
match level.dimension_organization {
WsiDimensionOrganization::TiledFull => {
let tiles_x = u64::from(level.total_columns.div_ceil(level.tile_columns));
let tiles_y = u64::from(level.total_rows.div_ceil(level.tile_rows));
let overflow = || wsi_error("TILED_FULL frame offsets overflow");
let per_plane = tiles_x.checked_mul(tiles_y).ok_or_else(overflow)?;
let plane = (options.optical_path_index as u64)
.checked_mul(level.focal_planes as u64)
.and_then(|value| value.checked_add(options.focal_plane_index as u64))
.ok_or_else(overflow)?;
let first = plane.checked_mul(per_plane).ok_or_else(overflow)?;
let last = first.checked_add(per_plane).ok_or_else(overflow)?;
if last > level.number_of_frames as u64 {
return Err(wsi_error(format!(
"TILED_FULL level {}x{} with {}x{} tiles needs {} frames for focal plane {} / optical path {}, but NumberOfFrames is {}",
level.total_columns,
level.total_rows,
level.tile_columns,
level.tile_rows,
last,
options.focal_plane_index,
options.optical_path_index,
level.number_of_frames
)));
}
if right <= region.x || bottom <= region.y {
return Ok(Vec::new());
}
let tx_range = (region.x / tile_w) as u64..(right as u64).div_ceil(tile_w as u64);
let ty_range = (region.y / tile_h) as u64..(bottom as u64).div_ceil(tile_h as u64);
let mut positions = Vec::new();
for ty in ty_range {
for tx in tx_range.clone() {
positions.push((
(first + ty * tiles_x + tx) as usize,
(tx * u64::from(level.tile_columns)) as i64,
(ty * u64::from(level.tile_rows)) as i64,
));
}
}
Ok(positions)
}
WsiDimensionOrganization::TiledSparse => {
let per_frame = items(object, tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE);
if per_frame.len() < level.number_of_frames {
return Err(wsi_error(format!(
"TILED_SPARSE level has {} frames but only {} PerFrameFunctionalGroupsSequence items",
level.number_of_frames,
per_frame.len()
)));
}
let planes = sorted_focal_planes(object);
let plane_key = planes[options.focal_plane_index];
let path_ids = optical_path_identifiers(object);
let wanted_path = if level.optical_paths > 1 || path_ids.len() > 1 {
let wanted = path_ids
.get(options.optical_path_index)
.filter(|id| !id.is_empty())
.ok_or_else(|| {
wsi_error(format!(
"optical path {} has no OpticalPathSequence item with an OpticalPathIdentifier",
options.optical_path_index
))
})?;
Some(wanted.as_str())
} else {
None
};
let mut positions = Vec::new();
for (frame_index, item) in per_frame.iter().take(level.number_of_frames).enumerate() {
let (column, row, z) = sparse_position(item).ok_or_else(|| {
wsi_error(format!(
"TILED_SPARSE frame {frame_index} has no PlanePositionSlideSequence column/row position"
))
})?;
if let Some(wanted) = wanted_path {
let actual = frame_optical_path(object, frame_index).ok_or_else(|| {
wsi_error(format!(
"TILED_SPARSE frame {frame_index} has no OpticalPathIdentificationSequence identifier, \
so it can't be assigned to one of the slide's {} optical paths",
level.optical_paths.max(path_ids.len())
))
})?;
if actual != wanted {
continue;
}
}
if z_key(z) != plane_key || !intersects(column, row) {
continue;
}
positions.push((frame_index, column, row));
}
Ok(positions)
}
}
}
struct MonochromeMapping {
center: Option<f64>,
width: Option<f64>,
bits_stored: u32,
invert: bool,
}
impl MonochromeMapping {
fn map(&self, value: f64) -> u8 {
let mapped = match (self.center, self.width) {
(Some(center), Some(width)) if width > 0.0 => {
let lower = center - 0.5 - (width - 1.0) / 2.0;
let upper = center - 0.5 + (width - 1.0) / 2.0;
if value <= lower {
0.0
} else if value > upper {
255.0
} else {
((value - (center - 0.5)) / (width - 1.0).max(1.0) + 0.5) * 255.0
}
}
_ if self.bits_stored <= 8 => value,
_ => value * 255.0 / ((1u64 << self.bits_stored.min(32)) - 1) as f64,
};
let byte = mapped.round().clamp(0.0, 255.0) as u8;
if self.invert {
255 - byte
} else {
byte
}
}
}
struct TileIcc {
frame_profile: bool,
path_transform: Option<IccTransform>,
}
impl TileIcc {
fn new(object: &DefaultDicomObject, options: &WsiRenderOptions) -> Self {
if !options.render.apply_icc_profile {
return Self {
frame_profile: false,
path_transform: None,
};
}
let path_profile = items(object, tags::OPTICAL_PATH_SEQUENCE)
.get(options.optical_path_index)
.and_then(|item| item.get(tags::ICC_PROFILE))
.and_then(|element| element.to_bytes().ok())
.filter(|bytes| !bytes.is_empty());
match path_profile {
Some(bytes) => Self {
frame_profile: false,
path_transform: icc_profile_to_srgb_transform(&bytes),
},
None => Self {
frame_profile: true,
path_transform: None,
},
}
}
}
struct DecodedTile {
column: i64,
row: i64,
width: u32,
height: u32,
samples_per_pixel: u16,
bytes: Vec<u8>,
}
fn decode_tile(
object: &DefaultDicomObject,
frame_index: usize,
column: i64,
row: i64,
mono: Option<&MonochromeMapping>,
icc: &TileIcc,
) -> Result<DecodedTile, RenderError> {
let tile_options = RenderPipelineOptions {
frame_index,
apply_icc_profile: icc.frame_profile,
show_overlays: false,
..Default::default()
};
let Some(mapping) = mono else {
let mut frame = render_dicom_frame_pixels(object, &tile_options)?;
if let Some(transform) = &icc.path_transform {
if frame.samples_per_pixel == 3 && frame.bytes.len().is_multiple_of(3) {
let _ = transform.transform(&mut frame.bytes);
}
}
return Ok(DecodedTile {
column,
row,
width: u32::from(frame.width),
height: u32::from(frame.height),
samples_per_pixel: frame.samples_per_pixel,
bytes: frame.bytes,
});
};
let raw = render_dicom_frame(object, RenderOutputFormat::Raw, &tile_options)?;
let signed = object
.get(tags::PIXEL_REPRESENTATION)
.and_then(|element| element.to_int::<u16>().ok())
.unwrap_or(0)
== 1;
let bytes = match raw.bits_allocated {
8 => raw
.bytes
.iter()
.map(|&value| {
let value = if signed {
f64::from(value as i8)
} else {
f64::from(value)
};
mapping.map(value)
})
.collect(),
16 => raw
.bytes
.chunks_exact(2)
.map(|pair| {
let word = u16::from_le_bytes([pair[0], pair[1]]);
let value = if signed {
f64::from(word as i16)
} else {
f64::from(word)
};
mapping.map(value)
})
.collect(),
other => return Err(RenderError::UnsupportedBitsAllocated(other)),
};
Ok(DecodedTile {
column,
row,
width: u32::from(raw.width),
height: u32::from(raw.height),
samples_per_pixel: 1,
bytes,
})
}
struct Canvas {
region: Region,
kx: u32,
ky: u32,
width: u32,
height: u32,
samples: usize,
background: [u8; 3],
direct: Vec<u8>,
sums: Vec<u64>,
counts: Vec<u64>,
}
impl Canvas {
fn new(region: Region, (kx, ky): (u32, u32), samples: usize, background: [u8; 3]) -> Self {
let width = region.width.div_ceil(kx);
let height = region.height.div_ceil(ky);
let pixels = width as usize * height as usize;
let background = if samples == 1 {
[rgb_to_luma(background); 3]
} else {
background
};
let (direct, sums, counts) = if kx == 1 && ky == 1 {
let mut direct = Vec::with_capacity(pixels * samples);
for _ in 0..pixels {
direct.extend_from_slice(&background[..samples]);
}
(direct, Vec::new(), Vec::new())
} else {
(Vec::new(), vec![0u64; pixels * samples], vec![0u64; pixels])
};
Self {
region,
kx,
ky,
width,
height,
samples,
background,
direct,
sums,
counts,
}
}
fn add(&mut self, tile: &DecodedTile, matrix_w: i64, matrix_h: i64) {
let x0 = tile.column.max(self.region.x);
let x1 = (tile.column + i64::from(tile.width))
.min(self.region.right())
.min(matrix_w);
let y0 = tile.row.max(self.region.y);
let y1 = (tile.row + i64::from(tile.height))
.min(self.region.bottom())
.min(matrix_h);
if x1 <= x0 || y1 <= y0 {
return;
}
let samples = self.samples;
let tile_stride = tile.width as usize * samples;
if self.kx == 1 && self.ky == 1 {
let row_len = (x1 - x0) as usize * samples;
for gy in y0..y1 {
let src =
(gy - tile.row) as usize * tile_stride + (x0 - tile.column) as usize * samples;
let dst = ((gy - self.region.y) as usize * self.width as usize
+ (x0 - self.region.x) as usize)
* samples;
self.direct[dst..dst + row_len].copy_from_slice(&tile.bytes[src..src + row_len]);
}
return;
}
let kx = i64::from(self.kx);
let ky = i64::from(self.ky);
for gy in y0..y1 {
let dy = ((gy - self.region.y) / ky) as usize;
let src_row = (gy - tile.row) as usize * tile_stride;
for gx in x0..x1 {
let dx = ((gx - self.region.x) / kx) as usize;
let pixel = dy * self.width as usize + dx;
let src = src_row + (gx - tile.column) as usize * samples;
for sample in 0..samples {
self.sums[pixel * samples + sample] += u64::from(tile.bytes[src + sample]);
}
self.counts[pixel] += 1;
}
}
}
fn finish(self) -> RenderedFramePixels {
let samples = self.samples;
let bytes = if self.kx == 1 && self.ky == 1 {
self.direct
} else {
let (kx, ky) = (self.kx, self.ky);
let mut bytes =
Vec::with_capacity(self.width as usize * self.height as usize * samples);
for dy in 0..self.height {
let rows = ky.min(self.region.height - dy * ky);
for dx in 0..self.width {
let columns = kx.min(self.region.width - dx * kx);
let expected = u128::from(rows) * u128::from(columns);
let pixel = dy as usize * self.width as usize + dx as usize;
let count = u128::from(self.counts[pixel]);
let missing = expected.saturating_sub(count);
let total = count.max(expected).max(1);
for sample in 0..samples {
let sum = u128::from(self.sums[pixel * samples + sample])
+ missing * u128::from(self.background[sample]);
bytes.push(((sum + total / 2) / total) as u8);
}
}
}
bytes
};
RenderedFramePixels {
width: self.width as u16,
height: self.height as u16,
samples_per_pixel: samples as u16,
bytes,
}
}
}
fn render_planned(
object: &DefaultDicomObject,
plan: RenderPlan,
output_format: RenderOutputFormat,
options: &WsiRenderOptions,
) -> Result<WsiRenderOutput, RenderError> {
let level = &plan.level;
let region = plan.level_region;
let monochrome = level.photometric_interpretation.starts_with("MONOCHROME");
let supported = if monochrome {
level.samples_per_pixel == 1
} else {
matches!(level.samples_per_pixel, 1 | 3)
};
if !supported {
return Err(wsi_error(format!(
"SamplesPerPixel {} is not supported for a {} whole slide image",
level.samples_per_pixel, level.photometric_interpretation
)));
}
let wanted = tile_positions(object, level, options, region)?;
let matrix_w = i64::from(level.total_columns);
let matrix_h = i64::from(level.total_rows);
let mono = monochrome.then(|| {
let bits_stored = uint(object, tags::BITS_STORED)
.or_else(|| uint(object, tags::BITS_ALLOCATED))
.unwrap_or(8) as u32;
let (center, width) = match (options.render.window_center, options.render.window_width) {
(Some(center), Some(width)) => (Some(center), Some(width)),
_ => super::render::resolve_default_window(object, 0),
};
MonochromeMapping {
center,
width,
bits_stored,
invert: resolve_grayscale_invert(object, &level.photometric_interpretation),
}
});
let icc = TileIcc::new(object, options);
let decode = |&(frame_index, column, row): &(usize, i64, i64)| {
decode_tile(object, frame_index, column, row, mono.as_ref(), &icc)
};
let mut canvas: Option<Canvas> = None;
let mut fold = |tile: Result<DecodedTile, RenderError>| -> Result<(), RenderError> {
let tile = tile?;
let canvas = canvas.get_or_insert_with(|| {
let samples = if mono.is_some() {
1
} else {
usize::from(tile.samples_per_pixel)
};
Canvas::new(region, plan.decimation, samples, options.background_color)
});
if usize::from(tile.samples_per_pixel) != canvas.samples {
return Err(wsi_error("tiles decode to different sample counts"));
}
canvas.add(&tile, matrix_w, matrix_h);
Ok(())
};
#[cfg(not(target_arch = "wasm32"))]
{
let batch = rayon::current_num_threads().max(1) * 4;
for chunk in wanted.chunks(batch) {
let decoded: Vec<Result<DecodedTile, RenderError>> =
chunk.par_iter().map(decode).collect();
for tile in decoded {
fold(tile)?;
}
}
}
#[cfg(target_arch = "wasm32")]
for position in &wanted {
fold(decode(position))?;
}
let tiles_decoded = wanted.len();
let canvas = canvas.unwrap_or_else(|| {
let samples = if mono.is_some() { 1 } else { 3 };
Canvas::new(region, plan.decimation, samples, options.background_color)
});
let stitched = canvas.finish();
let resize_options = RenderPipelineOptions {
output_width: Some(plan.output.0),
output_height: Some(plan.output.1),
..Default::default()
};
let mut frame = maybe_resize_frame(stitched, &resize_options);
draw_bounding_boxes(&mut frame, &options.render);
let frame = maybe_pad_frame(frame, &options.render);
let encoded = encode_rendered_frame(&frame, output_format, options.render.jpeg_quality)?;
Ok(WsiRenderOutput {
frame: encoded,
level: plan.level,
region: plan.base_region,
level_region: plan.level_region,
tiles_decoded,
})
}