use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use flate2::write::GzEncoder;
use flate2::Compression;
use rayon::prelude::*;
use serde_json::json;
use super::render::{
decode_frame_grayscale_values, decode_frame_texture_rgb_values, resolve_default_window,
resolve_grayscale_invert,
};
use super::types::RenderError;
use super::volume::{resample_volume, Interpolation, Volume};
#[derive(Debug)]
pub enum TextureExportError {
Io(io::Error),
Render(RenderError),
SampleCountMismatch {
expected: usize,
found: usize,
},
InvalidDimensions,
FrameDimensionMismatch {
expected: (u32, u32),
found: (u32, u32),
},
}
impl fmt::Display for TextureExportError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(error) => write!(formatter, "failed to pack texture export: {error}"),
Self::Render(error) => write!(formatter, "failed to decode frame for texture export: {error}"),
Self::SampleCountMismatch { expected, found } => write!(
formatter,
"texture export sample count ({found}) does not match its declared dimensions ({expected} expected)"
),
Self::InvalidDimensions => write!(formatter, "texture export dimensions must all be non-zero"),
Self::FrameDimensionMismatch { expected, found } => write!(
formatter,
"frame stack texture export requires every frame to share the same dimensions \
({}x{} expected, found {}x{})",
expected.0, expected.1, found.0, found.1
),
}
}
}
impl Error for TextureExportError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Io(error) => Some(error),
Self::Render(error) => Some(error),
_ => None,
}
}
}
impl From<io::Error> for TextureExportError {
fn from(value: io::Error) -> Self {
Self::Io(value)
}
}
impl From<RenderError> for TextureExportError {
fn from(value: RenderError) -> Self {
Self::Render(value)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SampleFormat {
Uint16,
Int16,
Rgb8,
}
impl SampleFormat {
pub fn as_str(self) -> &'static str {
match self {
Self::Uint16 => "uint16",
Self::Int16 => "int16",
Self::Rgb8 => "rgb8",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContentKind {
Volume,
Image2D,
FrameStack,
}
impl ContentKind {
fn as_str(self) -> &'static str {
match self {
Self::Volume => "volume",
Self::Image2D => "image2d",
Self::FrameStack => "framestack",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TextureCompression {
None,
Gzip,
}
impl TextureCompression {
fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Gzip => "gzip",
}
}
}
#[derive(Clone, Debug)]
pub struct TextureMeta {
pub content_kind: ContentKind,
pub sample_format: SampleFormat,
pub compression: TextureCompression,
pub lossless: bool,
pub width: u32,
pub height: u32,
pub depth: u32,
pub rescale_slope: f64,
pub rescale_intercept: f64,
pub row_spacing_mm: f64,
pub col_spacing_mm: f64,
pub slice_spacing_mm: f64,
pub origin: [f64; 3],
pub row_dir: [f64; 3],
pub col_dir: [f64; 3],
pub normal_dir: [f64; 3],
pub default_window_center: Option<f64>,
pub default_window_width: Option<f64>,
pub invert: bool,
pub layer_default_windows: Vec<(f64, f64)>,
pub layer_invert: Vec<bool>,
pub native_dims: (u32, u32, u32),
pub downsampled: bool,
pub payload_bytes_raw: u64,
pub payload_bytes_stored: u64,
}
impl TextureMeta {
pub fn to_json(&self) -> serde_json::Value {
json!({
"formatVersion": 1,
"contentKind": self.content_kind.as_str(),
"sampleFormat": self.sample_format.as_str(),
"compression": self.compression.as_str(),
"lossless": self.lossless,
"width": self.width,
"height": self.height,
"depth": self.depth,
"rescaleSlope": self.rescale_slope,
"rescaleIntercept": self.rescale_intercept,
"rowSpacingMm": self.row_spacing_mm,
"colSpacingMm": self.col_spacing_mm,
"sliceSpacingMm": self.slice_spacing_mm,
"origin": self.origin,
"rowDir": self.row_dir,
"colDir": self.col_dir,
"normalDir": self.normal_dir,
"defaultWindowCenter": self.default_window_center,
"defaultWindowWidth": self.default_window_width,
"invert": self.invert,
"layerWindowCenters": self.layer_default_windows.iter().map(|(center, _)| *center).collect::<Vec<_>>(),
"layerWindowWidths": self.layer_default_windows.iter().map(|(_, width)| *width).collect::<Vec<_>>(),
"layerInvert": self.layer_invert,
"nativeDims": [self.native_dims.0, self.native_dims.1, self.native_dims.2],
"downsampled": self.downsampled,
"payloadBytesRaw": self.payload_bytes_raw,
"payloadBytesStored": self.payload_bytes_stored,
})
}
}
pub struct PackedTexture {
pub meta: TextureMeta,
pub payload: Vec<u8>,
}
impl fmt::Debug for PackedTexture {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PackedTexture")
.field("meta", &self.meta)
.field("payload_len", &self.payload.len())
.finish()
}
}
fn gzip_bytes(bytes: &[u8]) -> Result<Vec<u8>, TextureExportError> {
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
encoder.write_all(bytes)?;
Ok(encoder.finish()?)
}
pub fn quantize_samples(raw: &[f32]) -> (Vec<u8>, SampleFormat, f64, f64, bool) {
quantize_with_stats(raw, &sample_stats(raw))
}
#[derive(Clone, Copy, Debug)]
struct SampleStats {
min: f64,
max: f64,
all_integral: bool,
}
const PAR_CHUNK_SAMPLES: usize = 1 << 16;
fn sample_stats(raw: &[f32]) -> SampleStats {
sample_stats_parts(&[raw])
}
fn sample_stats_parts(parts: &[&[f32]]) -> SampleStats {
let identity = || SampleStats {
min: f64::INFINITY,
max: f64::NEG_INFINITY,
all_integral: true,
};
parts
.par_iter()
.flat_map(|part| part.par_chunks(PAR_CHUNK_SAMPLES))
.map(|chunk| {
let mut stats = identity();
for &sample in chunk {
let value = sample as f64;
stats.min = stats.min.min(value);
stats.max = stats.max.max(value);
if stats.all_integral && (value - value.round()).abs() > 1e-4 {
stats.all_integral = false;
}
}
stats
})
.reduce(identity, |a, b| SampleStats {
min: a.min.min(b.min),
max: a.max.max(b.max),
all_integral: a.all_integral && b.all_integral,
})
}
fn encode_u16_le_parts(parts: &[&[f32]], encode: impl Fn(f32) -> [u8; 2] + Sync) -> Vec<u8> {
let total: usize = parts.iter().map(|part| part.len()).sum();
let mut bytes = vec![0u8; total * 2];
let mut rest: &mut [u8] = &mut bytes;
for part in parts {
let (out, tail) = rest.split_at_mut(part.len() * 2);
rest = tail;
out.par_chunks_mut(PAR_CHUNK_SAMPLES * 2)
.zip(part.par_chunks(PAR_CHUNK_SAMPLES))
.for_each(|(out, samples)| {
for (dst, &sample) in out.chunks_exact_mut(2).zip(samples) {
dst.copy_from_slice(&encode(sample));
}
});
}
bytes
}
fn quantize_with_stats(
raw: &[f32],
stats: &SampleStats,
) -> (Vec<u8>, SampleFormat, f64, f64, bool) {
quantize_parts_with_stats(&[raw], stats)
}
fn quantize_parts_with_stats(
parts: &[&[f32]],
stats: &SampleStats,
) -> (Vec<u8>, SampleFormat, f64, f64, bool) {
if parts.iter().all(|part| part.is_empty()) {
return (Vec::new(), SampleFormat::Int16, 1.0, 0.0, true);
}
let SampleStats {
min,
max,
all_integral,
} = *stats;
if all_integral && min >= 0.0 && max <= u16::MAX as f64 {
let bytes = encode_u16_le_parts(parts, |sample| (sample.round() as u16).to_le_bytes());
return (bytes, SampleFormat::Uint16, 1.0, 0.0, true);
}
if all_integral && min >= i16::MIN as f64 && max <= i16::MAX as f64 {
let bytes = encode_u16_le_parts(parts, |sample| (sample.round() as i16).to_le_bytes());
return (bytes, SampleFormat::Int16, 1.0, 0.0, true);
}
if all_integral && max - min <= u16::MAX as f64 {
let intercept = min.round();
let bytes = encode_u16_le_parts(parts, |sample| {
((sample as f64 - intercept).round() as u16).to_le_bytes()
});
return (bytes, SampleFormat::Uint16, 1.0, intercept, true);
}
let range = (max - min).max(1e-6);
let slope = range / 65535.0;
let intercept = min;
let bytes = encode_u16_le_parts(parts, |sample| {
let scaled = ((sample as f64 - intercept) / slope)
.round()
.clamp(0.0, 65535.0);
(scaled as u16).to_le_bytes()
});
(bytes, SampleFormat::Uint16, slope, intercept, false)
}
fn window_from_stats(stats: &SampleStats) -> (f64, f64) {
let SampleStats { min, max, .. } = *stats;
if !min.is_finite() || !max.is_finite() {
return (0.0, 1.0);
}
((min + max) / 2.0, (max - min).max(1.0))
}
fn apply_compression(
quantized: Vec<u8>,
compression: TextureCompression,
) -> Result<(Vec<u8>, u64), TextureExportError> {
let payload_bytes_raw = quantized.len() as u64;
let payload = match compression {
TextureCompression::None => quantized,
TextureCompression::Gzip => gzip_bytes(&quantized)?,
};
Ok((payload, payload_bytes_raw))
}
pub fn pack_volume_texture(
volume: &Volume,
target_max_dim: Option<u32>,
default_window: Option<(f64, f64)>,
compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
let native_dims = (volume.cols, volume.rows, volume.num_slices);
if native_dims.0 == 0 || native_dims.1 == 0 || native_dims.2 == 0 {
return Err(TextureExportError::InvalidDimensions);
}
let native_max = native_dims.0.max(native_dims.1).max(native_dims.2);
let (raw, dims, downsampled): (Cow<[f32]>, (u32, u32, u32), bool) = match target_max_dim {
Some(max_dim) if native_max > max_dim.max(1) => {
let scale = max_dim.max(1) as f64 / native_max as f64;
let target_cols = ((native_dims.0 as f64 * scale).round() as u32).max(1);
let target_rows = ((native_dims.1 as f64 * scale).round() as u32).max(1);
let target_slices = ((native_dims.2 as f64 * scale).round() as u32).max(1);
let resampled = resample_volume(
volume,
target_cols,
target_rows,
target_slices,
Interpolation::Trilinear,
);
(
Cow::Owned(resampled),
(target_cols, target_rows, target_slices),
true,
)
}
_ if volume.has_irregular_spacing() => {
let resampled = resample_volume(
volume,
native_dims.0,
native_dims.1,
native_dims.2,
Interpolation::Trilinear,
);
(Cow::Owned(resampled), native_dims, false)
}
_ => (Cow::Borrowed(volume.samples.as_slice()), native_dims, false),
};
let expected = dims.0 as usize * dims.1 as usize * dims.2 as usize;
if raw.len() != expected {
return Err(TextureExportError::SampleCountMismatch {
expected,
found: raw.len(),
});
}
let stats = sample_stats(&raw);
let (quantized, sample_format, rescale_slope, rescale_intercept, lossless) =
quantize_with_stats(&raw, &stats);
let default_window = default_window.or_else(|| Some(window_from_stats(&stats)));
let (payload, payload_bytes_raw) = apply_compression(quantized, compression)?;
let payload_bytes_stored = payload.len() as u64;
let axis_scale = |native: u32, exported: u32| -> f64 {
if exported > 1 && native > 1 {
(native - 1) as f64 / (exported - 1) as f64
} else {
native as f64 / exported as f64
}
};
let col_scale = axis_scale(native_dims.0, dims.0);
let row_scale = axis_scale(native_dims.1, dims.1);
let slice_nominal_spacing = volume.nominal_slice_spacing_mm();
let slice_scale = axis_scale(native_dims.2, dims.2);
let meta = TextureMeta {
content_kind: ContentKind::Volume,
sample_format,
compression,
lossless,
width: dims.0,
height: dims.1,
depth: dims.2,
rescale_slope,
rescale_intercept,
row_spacing_mm: volume.row_spacing_mm * row_scale,
col_spacing_mm: volume.col_spacing_mm * col_scale,
slice_spacing_mm: slice_nominal_spacing * slice_scale,
origin: volume.origin,
row_dir: volume.row_vector,
col_dir: volume.col_vector,
normal_dir: volume.slice_normal,
default_window_center: default_window.map(|(center, _)| center),
default_window_width: default_window.map(|(_, width)| width),
invert: false,
layer_default_windows: Vec::new(),
layer_invert: Vec::new(),
native_dims,
downsampled,
payload_bytes_raw,
payload_bytes_stored,
};
Ok(PackedTexture { meta, payload })
}
pub fn resample_frame_2d(
values: &[f32],
width: u32,
height: u32,
target_max_dim: u32,
) -> (Vec<f32>, u32, u32) {
let native_max = width.max(height);
if native_max == 0 || native_max <= target_max_dim.max(1) {
return (values.to_vec(), width, height);
}
let scale = target_max_dim.max(1) as f64 / native_max as f64;
let target_width = ((width as f64 * scale).round() as u32).max(1);
let target_height = ((height as f64 * scale).round() as u32).max(1);
let col_scale = if target_width > 1 {
(width as f64 - 1.0) / (target_width as f64 - 1.0)
} else {
0.0
};
let row_scale = if target_height > 1 {
(height as f64 - 1.0) / (target_height as f64 - 1.0)
} else {
0.0
};
let sample_at = |x_f: f64, y_f: f64| -> f32 {
let x0 = x_f.floor().clamp(0.0, (width - 1) as f64) as usize;
let y0 = y_f.floor().clamp(0.0, (height - 1) as f64) as usize;
let x1 = (x0 + 1).min(width as usize - 1);
let y1 = (y0 + 1).min(height as usize - 1);
let tx = x_f - x0 as f64;
let ty = y_f - y0 as f64;
let get = |x: usize, y: usize| values[y * width as usize + x] as f64;
let top = get(x0, y0) * (1.0 - tx) + get(x1, y0) * tx;
let bottom = get(x0, y1) * (1.0 - tx) + get(x1, y1) * tx;
(top * (1.0 - ty) + bottom * ty) as f32
};
let mut out = vec![0f32; target_width as usize * target_height as usize];
for target_row in 0..target_height {
let y_f = if target_height > 1 {
target_row as f64 * row_scale
} else {
(height as f64 - 1.0) / 2.0
};
for target_col in 0..target_width {
let x_f = if target_width > 1 {
target_col as f64 * col_scale
} else {
(width as f64 - 1.0) / 2.0
};
out[target_row as usize * target_width as usize + target_col as usize] =
sample_at(x_f, y_f);
}
}
(out, target_width, target_height)
}
pub fn pack_frame_texture(
values: &[f32],
width: u32,
height: u32,
default_window: Option<(f64, f64)>,
target_max_dim: Option<u32>,
compression: TextureCompression,
invert: bool,
) -> Result<PackedTexture, TextureExportError> {
if width == 0 || height == 0 {
return Err(TextureExportError::InvalidDimensions);
}
let expected = width as usize * height as usize;
if values.len() != expected {
return Err(TextureExportError::SampleCountMismatch {
expected,
found: values.len(),
});
}
let native_dims = (width, height, 1);
let (raw, out_width, out_height, downsampled) = match target_max_dim {
Some(max_dim) if width.max(height) > max_dim.max(1) => {
let (resampled, w, h) = resample_frame_2d(values, width, height, max_dim);
(Cow::Owned(resampled), w, h, true)
}
_ => (Cow::Borrowed(values), width, height, false),
};
let stats = sample_stats(&raw);
let (quantized, sample_format, rescale_slope, rescale_intercept, lossless) =
quantize_with_stats(&raw, &stats);
let default_window = default_window.or_else(|| Some(window_from_stats(&stats)));
let (payload, payload_bytes_raw) = apply_compression(quantized, compression)?;
let payload_bytes_stored = payload.len() as u64;
let meta = TextureMeta {
content_kind: ContentKind::Image2D,
sample_format,
compression,
lossless,
width: out_width,
height: out_height,
depth: 1,
rescale_slope,
rescale_intercept,
row_spacing_mm: 1.0,
col_spacing_mm: 1.0,
slice_spacing_mm: 0.0,
origin: [0.0, 0.0, 0.0],
row_dir: [1.0, 0.0, 0.0],
col_dir: [0.0, 1.0, 0.0],
normal_dir: [0.0, 0.0, 1.0],
default_window_center: default_window.map(|(center, _)| center),
default_window_width: default_window.map(|(_, width)| width),
invert,
layer_default_windows: Vec::new(),
layer_invert: Vec::new(),
native_dims,
downsampled,
payload_bytes_raw,
payload_bytes_stored,
};
Ok(PackedTexture { meta, payload })
}
pub fn pack_dicom_frame_texture(
object: &dcmnorm_object::DefaultDicomObject,
frame_index: usize,
target_max_dim: Option<u32>,
default_window: Option<(f64, f64)>,
compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
let default_window = default_window.or_else(|| {
let (center, width) = resolve_default_window(object, frame_index);
center.zip(width)
});
let (metadata, values) = decode_frame_grayscale_values(object, frame_index)?;
let invert = resolve_grayscale_invert(object, &metadata.photometric_interpretation);
let raw: Vec<f32> = values.into_iter().map(|value| value as f32).collect();
pack_frame_texture(
&raw,
metadata.cols as u32,
metadata.rows as u32,
default_window,
target_max_dim,
compression,
invert,
)
}
#[derive(Clone, Debug)]
pub struct DecodedFrame {
pub values: Vec<f32>,
pub width: u32,
pub height: u32,
}
pub fn pack_frame_stack_texture(
frames: &[DecodedFrame],
default_window: Option<(f64, f64)>,
compression: TextureCompression,
invert: bool,
) -> Result<PackedTexture, TextureExportError> {
let Some(first) = frames.first() else {
return Err(TextureExportError::InvalidDimensions);
};
let (width, height) = (first.width, first.height);
if width == 0 || height == 0 {
return Err(TextureExportError::InvalidDimensions);
}
let expected_per_frame = width as usize * height as usize;
let mut parts: Vec<&[f32]> = Vec::with_capacity(frames.len());
for frame in frames {
if frame.width != width || frame.height != height {
return Err(TextureExportError::FrameDimensionMismatch {
expected: (width, height),
found: (frame.width, frame.height),
});
}
if frame.values.len() != expected_per_frame {
return Err(TextureExportError::SampleCountMismatch {
expected: expected_per_frame,
found: frame.values.len(),
});
}
parts.push(&frame.values);
}
let depth = frames.len() as u32;
let native_dims = (width, height, depth);
let stats = sample_stats_parts(&parts);
let (quantized, sample_format, rescale_slope, rescale_intercept, lossless) =
quantize_parts_with_stats(&parts, &stats);
let default_window = default_window.or_else(|| Some(window_from_stats(&stats)));
let (payload, payload_bytes_raw) = apply_compression(quantized, compression)?;
let payload_bytes_stored = payload.len() as u64;
let meta = TextureMeta {
content_kind: ContentKind::FrameStack,
sample_format,
compression,
lossless,
width,
height,
depth,
rescale_slope,
rescale_intercept,
row_spacing_mm: 1.0,
col_spacing_mm: 1.0,
slice_spacing_mm: 0.0,
origin: [0.0, 0.0, 0.0],
row_dir: [1.0, 0.0, 0.0],
col_dir: [0.0, 1.0, 0.0],
normal_dir: [0.0, 0.0, 1.0],
default_window_center: default_window.map(|(center, _)| center),
default_window_width: default_window.map(|(_, width)| width),
invert,
layer_default_windows: Vec::new(),
layer_invert: Vec::new(),
native_dims,
downsampled: false,
payload_bytes_raw,
payload_bytes_stored,
};
Ok(PackedTexture { meta, payload })
}
pub fn pack_dicom_frame_stack_texture(
sources: &[(&dcmnorm_object::DefaultDicomObject, usize)],
default_window: Option<(f64, f64)>,
compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
let default_window = default_window.or_else(|| {
let (object, frame_index) = sources.first()?;
let (center, width) = resolve_default_window(object, *frame_index);
center.zip(width)
});
let mut invert = false;
let mut layer_invert = Vec::with_capacity(sources.len());
let mut decoded = Vec::with_capacity(sources.len());
for (index, (object, frame_index)) in sources.iter().enumerate() {
let (metadata, values) = decode_frame_grayscale_values(object, *frame_index)?;
if index == 0 {
invert = resolve_grayscale_invert(object, &metadata.photometric_interpretation);
}
let raw: Vec<f32> = values.into_iter().map(|value| value as f32).collect();
decoded.push(DecodedFrame {
values: raw,
width: metadata.cols as u32,
height: metadata.rows as u32,
});
layer_invert.push(resolve_grayscale_invert(
object,
&metadata.photometric_interpretation,
));
}
let mut object_min_max: Vec<(*const dcmnorm_object::DefaultDicomObject, (f64, f64))> =
Vec::new();
let mut layer_default_windows = Vec::with_capacity(sources.len());
for (object, frame_index) in sources {
let (center, width) = resolve_default_window(object, *frame_index);
let window = match center.zip(width) {
Some(window) => window,
None => {
let key: *const dcmnorm_object::DefaultDicomObject = *object;
match object_min_max.iter().find(|(cached, _)| *cached == key) {
Some((_, window)) => *window,
None => {
let object_frames: Vec<&[f32]> = sources
.iter()
.zip(decoded.iter())
.filter(|((other, _), _)| std::ptr::eq(*other, *object))
.map(|(_, frame)| frame.values.as_slice())
.collect();
let window = window_from_stats(&sample_stats_parts(&object_frames));
object_min_max.push((key, window));
window
}
}
}
};
layer_default_windows.push(window);
}
let mut packed = pack_frame_stack_texture(&decoded, default_window, compression, invert)?;
packed.meta.layer_default_windows = layer_default_windows;
packed.meta.layer_invert = layer_invert;
Ok(packed)
}
pub fn resample_rgb_frame_2d(
rgb: &[u8],
width: u32,
height: u32,
target_max_dim: u32,
) -> (Vec<u8>, u32, u32) {
let native_max = width.max(height);
if native_max == 0 || native_max <= target_max_dim.max(1) {
return (rgb.to_vec(), width, height);
}
let scale = target_max_dim.max(1) as f64 / native_max as f64;
let target_width = ((width as f64 * scale).round() as u32).max(1);
let target_height = ((height as f64 * scale).round() as u32).max(1);
let col_scale = if target_width > 1 {
(width as f64 - 1.0) / (target_width as f64 - 1.0)
} else {
0.0
};
let row_scale = if target_height > 1 {
(height as f64 - 1.0) / (target_height as f64 - 1.0)
} else {
0.0
};
let sample_at = |channel: usize, x_f: f64, y_f: f64| -> f64 {
let x0 = x_f.floor().clamp(0.0, (width - 1) as f64) as usize;
let y0 = y_f.floor().clamp(0.0, (height - 1) as f64) as usize;
let x1 = (x0 + 1).min(width as usize - 1);
let y1 = (y0 + 1).min(height as usize - 1);
let tx = x_f - x0 as f64;
let ty = y_f - y0 as f64;
let get = |x: usize, y: usize| rgb[(y * width as usize + x) * 3 + channel] as f64;
let top = get(x0, y0) * (1.0 - tx) + get(x1, y0) * tx;
let bottom = get(x0, y1) * (1.0 - tx) + get(x1, y1) * tx;
top * (1.0 - ty) + bottom * ty
};
let mut out = vec![0u8; target_width as usize * target_height as usize * 3];
for target_row in 0..target_height {
let y_f = if target_height > 1 {
target_row as f64 * row_scale
} else {
(height as f64 - 1.0) / 2.0
};
for target_col in 0..target_width {
let x_f = if target_width > 1 {
target_col as f64 * col_scale
} else {
(width as f64 - 1.0) / 2.0
};
let out_index = (target_row as usize * target_width as usize + target_col as usize) * 3;
for channel in 0..3 {
out[out_index + channel] =
sample_at(channel, x_f, y_f).round().clamp(0.0, 255.0) as u8;
}
}
}
(out, target_width, target_height)
}
pub fn pack_rgb_frame_texture(
rgb: &[u8],
width: u32,
height: u32,
target_max_dim: Option<u32>,
compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
if width == 0 || height == 0 {
return Err(TextureExportError::InvalidDimensions);
}
let expected = width as usize * height as usize * 3;
if rgb.len() != expected {
return Err(TextureExportError::SampleCountMismatch {
expected,
found: rgb.len(),
});
}
let native_dims = (width, height, 1);
let (quantized, out_width, out_height, downsampled) = match target_max_dim {
Some(max_dim) if width.max(height) > max_dim.max(1) => {
let (resampled, w, h) = resample_rgb_frame_2d(rgb, width, height, max_dim);
(resampled, w, h, true)
}
_ => (rgb.to_vec(), width, height, false),
};
let (payload, payload_bytes_raw) = apply_compression(quantized, compression)?;
let payload_bytes_stored = payload.len() as u64;
let meta = TextureMeta {
content_kind: ContentKind::Image2D,
sample_format: SampleFormat::Rgb8,
compression,
lossless: true,
width: out_width,
height: out_height,
depth: 1,
rescale_slope: 1.0,
rescale_intercept: 0.0,
row_spacing_mm: 1.0,
col_spacing_mm: 1.0,
slice_spacing_mm: 0.0,
origin: [0.0, 0.0, 0.0],
row_dir: [1.0, 0.0, 0.0],
col_dir: [0.0, 1.0, 0.0],
normal_dir: [0.0, 0.0, 1.0],
default_window_center: None,
default_window_width: None,
invert: false,
layer_default_windows: Vec::new(),
layer_invert: Vec::new(),
native_dims,
downsampled,
payload_bytes_raw,
payload_bytes_stored,
};
Ok(PackedTexture { meta, payload })
}
pub fn pack_dicom_rgb_frame_texture(
object: &dcmnorm_object::DefaultDicomObject,
frame_index: usize,
target_max_dim: Option<u32>,
compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
let (metadata, rgb) = decode_frame_texture_rgb_values(object, frame_index)?;
pack_rgb_frame_texture(
&rgb,
metadata.cols as u32,
metadata.rows as u32,
target_max_dim,
compression,
)
}
#[derive(Clone, Debug)]
pub struct DecodedRgbFrame {
pub bytes: Vec<u8>,
pub width: u32,
pub height: u32,
}
pub fn pack_rgb_frame_stack_texture(
frames: &[DecodedRgbFrame],
compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
let Some(first) = frames.first() else {
return Err(TextureExportError::InvalidDimensions);
};
let (width, height) = (first.width, first.height);
if width == 0 || height == 0 {
return Err(TextureExportError::InvalidDimensions);
}
let expected_per_frame = width as usize * height as usize * 3;
let mut concatenated = Vec::with_capacity(expected_per_frame * frames.len());
for frame in frames {
if frame.width != width || frame.height != height {
return Err(TextureExportError::FrameDimensionMismatch {
expected: (width, height),
found: (frame.width, frame.height),
});
}
if frame.bytes.len() != expected_per_frame {
return Err(TextureExportError::SampleCountMismatch {
expected: expected_per_frame,
found: frame.bytes.len(),
});
}
concatenated.extend_from_slice(&frame.bytes);
}
let depth = frames.len() as u32;
let native_dims = (width, height, depth);
let (payload, payload_bytes_raw) = apply_compression(concatenated, compression)?;
let payload_bytes_stored = payload.len() as u64;
let meta = TextureMeta {
content_kind: ContentKind::FrameStack,
sample_format: SampleFormat::Rgb8,
compression,
lossless: true,
width,
height,
depth,
rescale_slope: 1.0,
rescale_intercept: 0.0,
row_spacing_mm: 1.0,
col_spacing_mm: 1.0,
slice_spacing_mm: 0.0,
origin: [0.0, 0.0, 0.0],
row_dir: [1.0, 0.0, 0.0],
col_dir: [0.0, 1.0, 0.0],
normal_dir: [0.0, 0.0, 1.0],
default_window_center: None,
default_window_width: None,
invert: false,
layer_default_windows: Vec::new(),
layer_invert: Vec::new(),
native_dims,
downsampled: false,
payload_bytes_raw,
payload_bytes_stored,
};
Ok(PackedTexture { meta, payload })
}
pub fn pack_dicom_rgb_frame_stack_texture(
sources: &[(&dcmnorm_object::DefaultDicomObject, usize)],
compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
let mut decoded = Vec::with_capacity(sources.len());
for (object, frame_index) in sources.iter() {
let (metadata, bytes) = decode_frame_texture_rgb_values(object, *frame_index)?;
decoded.push(DecodedRgbFrame {
bytes,
width: metadata.cols as u32,
height: metadata.rows as u32,
});
}
pack_rgb_frame_stack_texture(&decoded, compression)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dicom_io::volume::Volume;
fn axis_aligned_test_volume(cols: u32, rows: u32, num_slices: u32) -> Volume {
let plane = (rows * cols) as usize;
let mut samples = vec![0f32; plane * num_slices as usize];
for (index, sample) in samples.iter_mut().enumerate() {
*sample = index as f32 - 1024.0; }
Volume {
samples,
rows,
cols,
num_slices,
origin: [10.0, -20.0, 30.0],
row_vector: [1.0, 0.0, 0.0],
col_vector: [0.0, 1.0, 0.0],
slice_normal: [0.0, 0.0, 1.0],
col_spacing_mm: 0.5,
row_spacing_mm: 0.6,
slice_zs: (0..num_slices).map(|index| index as f64 * 2.0).collect(),
modality: None,
frame_of_reference_uid: None,
series_instance_uid: None,
study_instance_uid: None,
gantry_tilt_deg: 0.0,
desheared: false,
}
}
#[test]
fn quantize_samples_of_integer_values_is_exact_and_lossless() {
let raw = vec![-1024.0f32, 0.0, 1500.0, 3071.0];
let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
assert_eq!(format, SampleFormat::Int16);
assert_eq!(slope, 1.0);
assert_eq!(intercept, 0.0);
assert!(lossless);
assert_eq!(bytes.len(), raw.len() * 2);
for (index, &expected) in raw.iter().enumerate() {
let value = i16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap());
assert_eq!(value as f32, expected);
}
}
#[test]
fn quantize_samples_of_fractional_values_falls_back_to_bounded_error_uint16() {
let raw = vec![0.0f32, 0.25, 0.5, 1.0];
let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
assert_eq!(format, SampleFormat::Uint16);
assert!(!lossless);
assert_eq!(bytes.len(), raw.len() * 2);
for (index, &expected) in raw.iter().enumerate() {
let quantized = u16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap());
let reconstructed = quantized as f64 * slope + intercept;
assert!((reconstructed - expected as f64).abs() <= 0.5 * slope + 1e-9);
}
}
#[test]
fn quantize_samples_of_unsigned_16_bit_integer_values_is_exact_uint16() {
let raw = vec![1000.0f32, 28876.0, 56990.0, 65535.0];
let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
assert_eq!(format, SampleFormat::Uint16);
assert_eq!(slope, 1.0);
assert_eq!(intercept, 0.0);
assert!(lossless);
for (index, &expected) in raw.iter().enumerate() {
let stored = u16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap());
assert_eq!(stored as f64 * slope + intercept, expected as f64);
}
}
#[test]
fn quantize_samples_of_unsigned_12_bit_values_is_uint16_not_int16() {
let raw = vec![0.0f32, 1.0, 2048.0, 4095.0];
let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
assert_eq!(format, SampleFormat::Uint16);
assert_eq!((slope, intercept, lossless), (1.0, 0.0, true));
for (index, &expected) in raw.iter().enumerate() {
assert_eq!(
u16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap()) as f32,
expected
);
}
}
#[test]
fn quantize_samples_of_signed_values_wider_than_i16_is_exact_offset_uint16() {
let raw = vec![-1000.0f32, 0.0, 40000.0, 64535.0];
let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
assert_eq!(format, SampleFormat::Uint16);
assert_eq!(slope, 1.0);
assert_eq!(intercept, -1000.0);
assert!(lossless);
for (index, &expected) in raw.iter().enumerate() {
let stored = u16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap());
assert_eq!(stored as f64 * slope + intercept, expected as f64);
}
}
#[test]
fn quantize_samples_of_out_of_i16_range_values_falls_back_to_bounded_error_uint16() {
let raw = vec![-40000.0f32, 0.0, 40000.0];
let (_, format, _, _, lossless) = quantize_samples(&raw);
assert_eq!(format, SampleFormat::Uint16);
assert!(!lossless);
}
#[test]
fn pack_volume_texture_without_downsampling_round_trips_exactly() {
let volume = axis_aligned_test_volume(4, 4, 4);
let packed = pack_volume_texture(&volume, None, None, TextureCompression::None).unwrap();
assert!(packed.meta.lossless);
assert!(!packed.meta.downsampled);
assert_eq!(
(packed.meta.width, packed.meta.height, packed.meta.depth),
(4, 4, 4)
);
assert_eq!(packed.meta.native_dims, (4, 4, 4));
assert_eq!(packed.payload.len(), volume.samples.len() * 2);
for (index, &expected) in volume.samples.iter().enumerate() {
let value =
i16::from_le_bytes(packed.payload[index * 2..index * 2 + 2].try_into().unwrap());
assert_eq!(value as f32, expected);
}
}
#[test]
fn pack_volume_texture_downsamples_to_fit_target_max_dim() {
let volume = axis_aligned_test_volume(8, 8, 8);
let packed = pack_volume_texture(&volume, Some(4), None, TextureCompression::None).unwrap();
assert!(packed.meta.downsampled);
assert!(packed.meta.width <= 4 && packed.meta.height <= 4 && packed.meta.depth <= 4);
assert_eq!(packed.meta.native_dims, (8, 8, 8));
assert!(packed.meta.col_spacing_mm > volume.col_spacing_mm);
assert!(packed.meta.row_spacing_mm > volume.row_spacing_mm);
}
#[test]
fn pack_volume_texture_below_target_max_dim_is_a_no_op() {
let volume = axis_aligned_test_volume(4, 4, 4);
let packed =
pack_volume_texture(&volume, Some(64), None, TextureCompression::None).unwrap();
assert!(!packed.meta.downsampled);
assert_eq!(
(packed.meta.width, packed.meta.height, packed.meta.depth),
(4, 4, 4)
);
}
#[test]
fn pack_volume_texture_gzip_round_trips_to_the_uncompressed_payload() {
let volume = axis_aligned_test_volume(4, 4, 4);
let plain = pack_volume_texture(&volume, None, None, TextureCompression::None).unwrap();
let gzipped = pack_volume_texture(&volume, None, None, TextureCompression::Gzip).unwrap();
assert_eq!(gzipped.meta.payload_bytes_raw, plain.payload.len() as u64);
assert_eq!(
gzipped.meta.payload_bytes_stored,
gzipped.payload.len() as u64
);
let mut decoder = flate2::read::GzDecoder::new(&gzipped.payload[..]);
let mut decompressed = Vec::new();
std::io::Read::read_to_end(&mut decoder, &mut decompressed).unwrap();
assert_eq!(decompressed, plain.payload);
}
#[test]
fn pack_volume_texture_carries_default_window_through_to_meta() {
let volume = axis_aligned_test_volume(2, 2, 2);
let packed =
pack_volume_texture(&volume, None, Some((40.0, 400.0)), TextureCompression::None)
.unwrap();
assert_eq!(packed.meta.default_window_center, Some(40.0));
assert_eq!(packed.meta.default_window_width, Some(400.0));
}
#[test]
fn resample_frame_2d_is_a_no_op_when_already_within_target() {
let values: Vec<f32> = (0..16).map(|value| value as f32).collect();
let (out, w, h) = resample_frame_2d(&values, 4, 4, 8);
assert_eq!((w, h), (4, 4));
assert_eq!(out, values);
}
#[test]
fn resample_frame_2d_downsamples_a_linear_ramp_correctly() {
let width = 8u32;
let height = 8u32;
let mut values = vec![0f32; (width * height) as usize];
for row in 0..height {
for col in 0..width {
values[(row * width + col) as usize] = col as f32;
}
}
let (out, out_w, out_h) = resample_frame_2d(&values, width, height, 4);
assert_eq!((out_w, out_h), (4, 4));
let expected_cols = [0.0f32, 7.0 / 3.0, 14.0 / 3.0, 7.0];
for row in 0..out_h {
for col in 0..out_w {
let value = out[(row * out_w + col) as usize];
assert!(
(value - expected_cols[col as usize]).abs() < 1e-4,
"row={row} col={col} value={value} expected={}",
expected_cols[col as usize]
);
}
}
}
#[test]
fn pack_frame_texture_rejects_a_sample_count_mismatch() {
let error =
pack_frame_texture(&[0.0; 3], 2, 2, None, None, TextureCompression::None, false)
.unwrap_err();
assert!(matches!(
error,
TextureExportError::SampleCountMismatch {
expected: 4,
found: 3
}
));
}
#[test]
fn pack_frame_texture_downsamples_and_round_trips_within_tolerance() {
let width = 8u32;
let height = 8u32;
let values: Vec<f32> = (0..width * height).map(|index| index as f32).collect();
let packed = pack_frame_texture(
&values,
width,
height,
None,
Some(4),
TextureCompression::None,
false,
)
.unwrap();
assert!(packed.meta.downsampled);
assert_eq!(packed.meta.depth, 1);
assert_eq!(packed.meta.native_dims, (8, 8, 1));
assert!(packed.meta.width <= 4 && packed.meta.height <= 4);
}
#[test]
fn pack_frame_texture_without_a_default_window_falls_back_to_min_max_span() {
let width = 4u32;
let height = 4u32;
let values: Vec<f32> = (0..width * height).map(|index| index as f32).collect();
let packed = pack_frame_texture(
&values,
width,
height,
None,
None,
TextureCompression::None,
true,
)
.unwrap();
assert_eq!(packed.meta.default_window_center, Some(7.5));
assert_eq!(packed.meta.default_window_width, Some(15.0));
}
#[test]
fn pack_volume_texture_without_a_default_window_falls_back_to_min_max_span() {
let volume = axis_aligned_test_volume(2, 2, 2);
let packed = pack_volume_texture(&volume, None, None, TextureCompression::None).unwrap();
assert_eq!(
packed.meta.default_window_center,
Some((-1024.0 + -1017.0) / 2.0)
);
assert_eq!(packed.meta.default_window_width, Some(7.0));
}
#[test]
fn texture_meta_to_json_round_trips_expected_fields() {
let volume = axis_aligned_test_volume(2, 2, 2);
let packed =
pack_volume_texture(&volume, None, Some((40.0, 400.0)), TextureCompression::Gzip)
.unwrap();
let json = packed.meta.to_json();
assert_eq!(json["formatVersion"], 1);
assert_eq!(json["contentKind"], "volume");
assert_eq!(json["compression"], "gzip");
assert_eq!(json["width"], 2);
assert_eq!(json["defaultWindowCenter"], 40.0);
assert_eq!(json["defaultWindowWidth"], 400.0);
assert_eq!(json["nativeDims"], serde_json::json!([2, 2, 2]));
}
fn ramp_frame(width: u32, height: u32, base: f32) -> DecodedFrame {
let values = (0..width * height)
.map(|index| base + index as f32)
.collect();
DecodedFrame {
values,
width,
height,
}
}
#[test]
fn pack_frame_stack_texture_concatenates_layers_in_source_order() {
let frames = vec![
ramp_frame(2, 2, 0.0),
ramp_frame(2, 2, 100.0),
ramp_frame(2, 2, 200.0),
];
let packed =
pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap();
assert_eq!(packed.meta.content_kind, ContentKind::FrameStack);
assert_eq!(
(packed.meta.width, packed.meta.height, packed.meta.depth),
(2, 2, 3)
);
assert_eq!(packed.meta.native_dims, (2, 2, 3));
assert!(!packed.meta.downsampled);
assert!(packed.meta.lossless);
let layer1_offset = 1 * 4 * 2; let value = i16::from_le_bytes(
packed.payload[layer1_offset..layer1_offset + 2]
.try_into()
.unwrap(),
);
assert_eq!(value, 100);
}
#[test]
fn pack_frame_stack_texture_never_carries_physical_geometry() {
let frames = vec![ramp_frame(2, 2, 0.0), ramp_frame(2, 2, 1.0)];
let packed =
pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap();
assert_eq!(packed.meta.origin, [0.0, 0.0, 0.0]);
assert_eq!(packed.meta.slice_spacing_mm, 0.0);
assert_eq!(packed.meta.row_dir, [1.0, 0.0, 0.0]);
assert_eq!(packed.meta.col_dir, [0.0, 1.0, 0.0]);
}
#[test]
fn pack_frame_stack_texture_rejects_mismatched_frame_dimensions() {
let frames = vec![ramp_frame(2, 2, 0.0), ramp_frame(3, 2, 0.0)];
let error =
pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap_err();
assert!(matches!(
error,
TextureExportError::FrameDimensionMismatch {
expected: (2, 2),
found: (3, 2)
}
));
}
#[test]
fn pack_frame_stack_texture_rejects_an_empty_stack() {
let error =
pack_frame_stack_texture(&[], None, TextureCompression::None, false).unwrap_err();
assert!(matches!(error, TextureExportError::InvalidDimensions));
}
#[test]
fn pack_frame_stack_texture_never_downsamples_even_when_large() {
let frames = vec![ramp_frame(16, 16, 0.0)];
let packed =
pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap();
assert_eq!((packed.meta.width, packed.meta.height), (16, 16));
assert!(!packed.meta.downsampled);
}
#[test]
fn pack_frame_stack_texture_default_window_spans_the_whole_stack_not_just_one_layer() {
let frames = vec![
ramp_frame(2, 2, 0.0),
ramp_frame(2, 2, 100.0),
ramp_frame(2, 2, 200.0),
];
let packed =
pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap();
assert_eq!(packed.meta.default_window_center, Some((0.0 + 203.0) / 2.0));
assert_eq!(packed.meta.default_window_width, Some(203.0));
}
fn fixture(name: &str) -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("test/files")
.join(name)
}
fn rgb_ramp(width: u32, height: u32, base: u8) -> DecodedRgbFrame {
let bytes = (0..width * height * 3)
.map(|index| base.wrapping_add((index % 251) as u8))
.collect();
DecodedRgbFrame {
bytes,
width,
height,
}
}
#[test]
fn pack_rgb_frame_texture_is_unconditionally_lossless_and_rgb8() {
let rgb = vec![10u8, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; let packed = pack_rgb_frame_texture(&rgb, 2, 2, None, TextureCompression::None).unwrap();
assert_eq!(packed.meta.sample_format, SampleFormat::Rgb8);
assert!(packed.meta.lossless);
assert_eq!(
(packed.meta.width, packed.meta.height, packed.meta.depth),
(2, 2, 1)
);
assert_eq!(packed.payload, rgb);
assert_eq!(
packed.meta.default_window_center, None,
"color has no window/level concept"
);
assert!(
!packed.meta.invert,
"color has no MONOCHROME1 invert concept"
);
}
#[test]
fn pack_rgb_frame_texture_rejects_wrong_byte_count() {
let error =
pack_rgb_frame_texture(&[1, 2, 3], 2, 2, None, TextureCompression::None).unwrap_err();
assert!(matches!(
error,
TextureExportError::SampleCountMismatch {
expected: 12,
found: 3
}
));
}
#[test]
fn pack_rgb_frame_texture_rejects_zero_dimensions() {
let error = pack_rgb_frame_texture(&[], 0, 4, None, TextureCompression::None).unwrap_err();
assert!(matches!(error, TextureExportError::InvalidDimensions));
}
#[test]
fn pack_rgb_frame_texture_downsamples_when_over_target_max_dim() {
let rgb = vec![128u8; 16 * 16 * 3];
let packed =
pack_rgb_frame_texture(&rgb, 16, 16, Some(8), TextureCompression::None).unwrap();
assert!(packed.meta.downsampled);
assert_eq!((packed.meta.width, packed.meta.height), (8, 8));
assert_eq!(packed.meta.native_dims, (16, 16, 1));
assert_eq!(packed.payload.len(), 8 * 8 * 3);
}
#[test]
fn pack_rgb_frame_stack_texture_concatenates_layers_in_source_order() {
let frames = vec![rgb_ramp(2, 2, 0), rgb_ramp(2, 2, 100), rgb_ramp(2, 2, 200)];
let packed = pack_rgb_frame_stack_texture(&frames, TextureCompression::None).unwrap();
assert_eq!(packed.meta.content_kind, ContentKind::FrameStack);
assert_eq!(packed.meta.sample_format, SampleFormat::Rgb8);
assert_eq!(
(packed.meta.width, packed.meta.height, packed.meta.depth),
(2, 2, 3)
);
assert!(packed.meta.lossless);
let bytes_per_layer = 2 * 2 * 3;
assert_eq!(&packed.payload[0..bytes_per_layer], &frames[0].bytes[..]);
assert_eq!(
&packed.payload[bytes_per_layer..bytes_per_layer * 2],
&frames[1].bytes[..]
);
}
#[test]
fn pack_rgb_frame_stack_texture_rejects_mismatched_frame_dimensions() {
let frames = vec![rgb_ramp(2, 2, 0), rgb_ramp(3, 2, 0)];
let error = pack_rgb_frame_stack_texture(&frames, TextureCompression::None).unwrap_err();
assert!(matches!(
error,
TextureExportError::FrameDimensionMismatch {
expected: (2, 2),
found: (3, 2)
}
));
}
#[test]
fn pack_rgb_frame_stack_texture_rejects_an_empty_stack() {
let error = pack_rgb_frame_stack_texture(&[], TextureCompression::None).unwrap_err();
assert!(matches!(error, TextureExportError::InvalidDimensions));
}
#[test]
fn pack_dicom_rgb_frame_texture_packs_a_real_uncompressed_rgb_fixture() {
let object = crate::dicom_io::read_dicom_file(fixture("rgb_interleaved.dcm"))
.expect("fixture should be readable");
let packed =
pack_dicom_rgb_frame_texture(&object, 0, None, TextureCompression::None).unwrap();
assert_eq!(packed.meta.sample_format, SampleFormat::Rgb8);
assert!(packed.meta.lossless);
assert_eq!(
packed.payload.len(),
packed.meta.width as usize * packed.meta.height as usize * 3
);
}
#[test]
fn pack_dicom_rgb_frame_stack_texture_packs_two_real_instances() {
let planar = crate::dicom_io::read_dicom_file(fixture("rgb_planar.dcm"))
.expect("fixture should be readable");
let interleaved = crate::dicom_io::read_dicom_file(fixture("rgb_interleaved.dcm"))
.expect("fixture should be readable");
let sources: Vec<(&dcmnorm_object::DefaultDicomObject, usize)> =
vec![(&planar, 0), (&interleaved, 0)];
let packed =
pack_dicom_rgb_frame_stack_texture(&sources, TextureCompression::None).unwrap();
assert_eq!(packed.meta.depth, 2);
assert_eq!(packed.meta.sample_format, SampleFormat::Rgb8);
}
}