use std::fmt;
use crate::dataset::DataSet;
use crate::dictionary::tags;
use crate::endian::Endian;
use crate::error::{Error, Result};
use crate::file::DicomFile;
use crate::transfer_syntax::TransferSyntax;
use crate::value::Value;
use crate::vr::Vr;
const RLE_LOSSLESS: &str = "1.2.840.10008.1.2.5";
#[cfg(feature = "pixel-j2k")]
mod j2k;
#[cfg(feature = "pixel-jpeg")]
mod jpeg;
mod jpeg_lossless;
#[cfg(feature = "pixel-jpegls")]
mod jpegls;
#[cfg(feature = "pixel-jxl")]
mod jxl;
mod lut;
mod rle;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PixelRepresentation {
Unsigned,
Signed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanarConfiguration {
None,
Interleaved,
Planar,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PhotometricInterpretation {
Monochrome1,
Monochrome2,
PaletteColor,
Rgb,
YbrFull,
YbrFull422,
YbrPartial422,
YbrPartial420,
YbrIct,
YbrRct,
Hsv,
Argb,
Cmyk,
Unknown(String),
}
impl PhotometricInterpretation {
fn from_dicom(text: &str) -> Self {
match text.trim() {
"MONOCHROME1" => Self::Monochrome1,
"MONOCHROME2" => Self::Monochrome2,
"PALETTE COLOR" => Self::PaletteColor,
"RGB" => Self::Rgb,
"YBR_FULL" => Self::YbrFull,
"YBR_FULL_422" => Self::YbrFull422,
"YBR_PARTIAL_422" => Self::YbrPartial422,
"YBR_PARTIAL_420" => Self::YbrPartial420,
"YBR_ICT" => Self::YbrIct,
"YBR_RCT" => Self::YbrRct,
"HSV" => Self::Hsv,
"ARGB" => Self::Argb,
"CMYK" => Self::Cmyk,
other => Self::Unknown(other.to_owned()),
}
}
}
impl fmt::Display for PhotometricInterpretation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Monochrome1 => f.write_str("MONOCHROME1"),
Self::Monochrome2 => f.write_str("MONOCHROME2"),
Self::PaletteColor => f.write_str("PALETTE COLOR"),
Self::Rgb => f.write_str("RGB"),
Self::YbrFull => f.write_str("YBR_FULL"),
Self::YbrFull422 => f.write_str("YBR_FULL_422"),
Self::YbrPartial422 => f.write_str("YBR_PARTIAL_422"),
Self::YbrPartial420 => f.write_str("YBR_PARTIAL_420"),
Self::YbrIct => f.write_str("YBR_ICT"),
Self::YbrRct => f.write_str("YBR_RCT"),
Self::Hsv => f.write_str("HSV"),
Self::Argb => f.write_str("ARGB"),
Self::Cmyk => f.write_str("CMYK"),
Self::Unknown(text) => f.write_str(text),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PixelDescriptor {
pub rows: u16,
pub columns: u16,
pub samples_per_pixel: u16,
pub bits_allocated: u16,
pub bits_stored: u16,
pub high_bit: u16,
pub pixel_representation: PixelRepresentation,
pub planar_configuration: PlanarConfiguration,
pub photometric: PhotometricInterpretation,
pub number_of_frames: u32,
}
impl PixelDescriptor {
pub fn from_dataset(set: &DataSet) -> Result<Self> {
let rows = set.u16(tags::ROWS)?;
let columns = set.u16(tags::COLUMNS)?;
let samples_per_pixel = set.u16(tags::SAMPLES_PER_PIXEL)?;
let bits_allocated = set.u16(tags::BITS_ALLOCATED)?;
let bits_stored = set.u16(tags::BITS_STORED)?;
let high_bit = set.u16(tags::HIGH_BIT)?;
let pixel_representation = match set.u16(tags::PIXEL_REPRESENTATION)? {
0 => PixelRepresentation::Unsigned,
1 => PixelRepresentation::Signed,
value => {
return Err(Error::InvalidPixelData(format!(
"invalid Pixel Representation: {value}"
)));
}
};
let planar_configuration = if samples_per_pixel == 1 {
PlanarConfiguration::None
} else if set.contains(tags::PLANAR_CONFIGURATION) {
match set.u16(tags::PLANAR_CONFIGURATION)? {
0 => PlanarConfiguration::Interleaved,
1 => PlanarConfiguration::Planar,
value => {
return Err(Error::InvalidPixelData(format!(
"invalid Planar Configuration: {value}"
)));
}
}
} else {
PlanarConfiguration::Interleaved
};
let photometric_text = set.string(tags::PHOTOMETRIC_INTERPRETATION)?;
let photometric = PhotometricInterpretation::from_dicom(&photometric_text);
let number_of_frames = match set.get(tags::NUMBER_OF_FRAMES) {
Some(element) => {
let text = element.string()?.trim();
text.parse::<u32>().map_err(|_| {
Error::InvalidPixelData(format!("invalid Number of Frames: {text:?}"))
})?
}
None => 1,
};
if rows == 0 || columns == 0 {
return Err(Error::InvalidPixelData(
"Rows and Columns must be non-zero".to_owned(),
));
}
if samples_per_pixel == 0 || samples_per_pixel > 4 {
return Err(Error::InvalidPixelData(format!(
"invalid Samples per Pixel: {samples_per_pixel}"
)));
}
if bits_allocated == 0 || bits_allocated > 32 {
return Err(Error::InvalidPixelData(format!(
"invalid Bits Allocated: {bits_allocated}"
)));
}
if bits_stored == 0 || bits_stored > bits_allocated {
return Err(Error::InvalidPixelData(format!(
"invalid Bits Stored: {bits_stored} for Bits Allocated {bits_allocated}"
)));
}
if high_bit >= bits_allocated {
return Err(Error::InvalidPixelData(format!(
"invalid High Bit: {high_bit} for Bits Allocated {bits_allocated}"
)));
}
if number_of_frames == 0 {
return Err(Error::InvalidPixelData(
"Number of Frames must be non-zero".to_owned(),
));
}
Ok(Self {
rows,
columns,
samples_per_pixel,
bits_allocated,
bits_stored,
high_bit,
pixel_representation,
planar_configuration,
photometric,
number_of_frames,
})
}
pub fn bytes_per_sample(&self) -> usize {
usize::from(self.bits_allocated).div_ceil(8)
}
pub fn frame_size(&self) -> usize {
let pixels = usize::from(self.rows)
* usize::from(self.columns)
* usize::from(self.samples_per_pixel);
if self.bits_allocated < 8 {
pixels.div_ceil(8)
} else {
pixels * self.bytes_per_sample()
}
}
}
impl DataSet {
pub fn pixel_descriptor(&self) -> Result<PixelDescriptor> {
PixelDescriptor::from_dataset(self)
}
pub fn encapsulated_frames(&self) -> Result<Vec<Vec<u8>>> {
let element = self.element(tags::PIXEL_DATA)?;
let Some(fragments) = element.value.as_fragments() else {
return Err(Error::InvalidPixelData(
"Pixel Data is not encapsulated".to_owned(),
));
};
if fragments.is_empty() {
return Ok(Vec::new());
}
let basic_offset_table = &fragments[0];
if basic_offset_table.is_empty() {
return self.frameless_encapsulated_frames(&fragments[1..]);
}
if basic_offset_table.len() % 4 != 0 {
return Err(Error::InvalidPixelData(format!(
"Basic Offset Table length {} is not a multiple of 4",
basic_offset_table.len()
)));
}
let offsets: Vec<usize> = basic_offset_table
.chunks_exact(4)
.map(|chunk| u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) as usize)
.collect();
let fragments = &fragments[1..];
let final_index = offsets.len() - 1;
let mut frames = Vec::new();
let mut frame = Vec::new();
let mut current = 0usize;
let mut stream_offset = 0usize;
for fragment in fragments {
if current == final_index {
frame.extend_from_slice(fragment);
stream_offset += fragment.len() + 8;
continue;
}
if stream_offset < offsets[current + 1] {
frame.extend_from_slice(fragment);
} else {
frames.push(std::mem::take(&mut frame));
current += 1;
frame = fragment.clone();
}
stream_offset += fragment.len() + 8;
}
if !frame.is_empty() || frames.is_empty() {
frames.push(frame);
}
Ok(frames)
}
fn frameless_encapsulated_frames(&self, fragments: &[Vec<u8>]) -> Result<Vec<Vec<u8>>> {
if fragments.is_empty() {
return Ok(Vec::new());
}
let number_of_frames = match self.get(tags::NUMBER_OF_FRAMES) {
Some(element) => {
let text = element.string()?.trim();
text.parse::<u32>().map_err(|_| {
Error::InvalidPixelData(format!("invalid Number of Frames: {text:?}"))
})?
}
None => 1,
}
.max(1) as usize;
if fragments.len() == 1 || number_of_frames == 1 {
return Ok(vec![fragments.concat()]);
}
if fragments.len() == number_of_frames {
return Ok(fragments.to_vec());
}
if fragments.len() < number_of_frames {
return Err(Error::InvalidPixelData(format!(
"encapsulated Pixel Data has {} fragments for {number_of_frames} frames",
fragments.len()
)));
}
let mut frames = Vec::new();
let mut frame = Vec::new();
for fragment in fragments {
frame.extend_from_slice(fragment);
let tail = &fragment[fragment.len().saturating_sub(10)..];
if tail.windows(2).any(|pair| pair == [0xFF, 0xD9]) {
frames.push(std::mem::take(&mut frame));
}
}
if !frame.is_empty() {
frames.push(frame);
}
Ok(frames)
}
}
impl DicomFile {
pub fn pixel_descriptor(&self) -> Result<PixelDescriptor> {
self.dataset.pixel_descriptor()
}
pub fn pixel_frames(&self) -> Result<Vec<Vec<u8>>> {
let syntax = self.transfer_syntax()?;
let descriptor = self.dataset.pixel_descriptor()?;
if syntax.is_encapsulated() {
return self.dataset.encapsulated_frames();
}
let element = self.dataset.element(tags::PIXEL_DATA)?;
let Some(bytes) = element.value.as_bytes() else {
return Err(Error::InvalidPixelData(
"Pixel Data is not a byte value".to_owned(),
));
};
let frame_size = descriptor.frame_size();
if frame_size == 0 {
return Err(Error::InvalidPixelData("frame size is zero".to_owned()));
}
let expected = frame_size
.checked_mul(descriptor.number_of_frames as usize)
.ok_or_else(|| Error::InvalidPixelData("pixel data size overflows".to_owned()))?;
if bytes.len() < expected {
return Err(Error::InvalidPixelData(format!(
"Pixel Data has {} bytes, {expected} required for {} frame(s)",
bytes.len(),
descriptor.number_of_frames
)));
}
Ok((0..descriptor.number_of_frames as usize)
.map(|index| bytes[index * frame_size..(index + 1) * frame_size].to_vec())
.collect())
}
pub fn decode_frame(&self, index: usize) -> Result<Vec<u8>> {
let descriptor = self.dataset.pixel_descriptor()?;
let syntax = self.transfer_syntax()?;
let frames = self.pixel_frames()?;
let frame = frames.get(index).ok_or_else(|| {
Error::InvalidPixelData(format!(
"frame index {index} out of range (have {})",
frames.len()
))
})?;
decode_frame_bytes(syntax, &descriptor, frame)
}
pub fn decode_pixel_data(&self) -> Result<Vec<Vec<u8>>> {
let descriptor = self.dataset.pixel_descriptor()?;
let syntax = self.transfer_syntax()?;
self.pixel_frames()?
.iter()
.map(|frame| decode_frame_bytes(syntax, &descriptor, frame))
.collect()
}
pub fn compress_rle(&mut self) -> Result<()> {
let descriptor = self.dataset.pixel_descriptor()?;
let syntax = self.transfer_syntax()?;
if syntax.is_encapsulated() {
return Err(Error::InvalidPixelData(
"Pixel Data is already encapsulated".to_owned(),
));
}
let frames = self.pixel_frames()?;
let mut encoded = Vec::with_capacity(frames.len());
for frame in &frames {
encoded.push(rle::encode(frame, &descriptor)?);
}
self.set_encapsulated(encoded, RLE_LOSSLESS)
}
fn set_encapsulated(&mut self, frames: Vec<Vec<u8>>, uid: &str) -> Result<()> {
let value = crate::encaps::encapsulate(&frames, 1, true)?;
let fragments: Vec<Vec<u8>> = crate::encaps::generate_fragments(&value, Endian::Little)?
.into_iter()
.map(|fragment| fragment.to_vec())
.collect();
self.dataset
.set(tags::PIXEL_DATA, Vr::Ob, Value::Fragments(fragments));
self.meta
.set(tags::TRANSFER_SYNTAX_UID, Vr::Ui, Value::from_str(uid));
Ok(())
}
}
#[cfg(feature = "pixel-jpeg")]
impl DicomFile {
pub fn compress_jpeg(&mut self, quality: u8) -> Result<()> {
use jpeg_encoder::{ColorType, Encoder};
let descriptor = self.dataset.pixel_descriptor()?;
if self.transfer_syntax()?.is_encapsulated() {
return Err(Error::InvalidPixelData(
"Pixel Data is already encapsulated".to_owned(),
));
}
if descriptor.bits_allocated != 8 {
return Err(Error::InvalidPixelData(
"baseline JPEG writes 8-bit samples only".to_owned(),
));
}
let colour = descriptor.samples_per_pixel == 3;
let color = match descriptor.samples_per_pixel {
1 => ColorType::Luma,
3 => ColorType::Rgb,
samples => {
return Err(Error::InvalidPixelData(format!(
"baseline JPEG needs one or three samples, this image has {samples}"
)))
}
};
let frames = self.pixel_frames()?;
let mut encoded = Vec::with_capacity(frames.len());
for frame in &frames {
let mut out = Vec::new();
Encoder::new(&mut out, quality)
.encode(frame, descriptor.columns, descriptor.rows, color)
.map_err(|err| Error::InvalidPixelData(format!("JPEG encoder: {err}")))?;
encoded.push(out);
}
self.set_encapsulated(encoded, "1.2.840.10008.1.2.4.50")?;
if colour {
self.dataset
.set_string(tags::PHOTOMETRIC_INTERPRETATION, Vr::Cs, "YBR_FULL_422");
}
Ok(())
}
}
#[cfg(feature = "pixel-jpegls")]
impl DicomFile {
pub fn compress_jpegls(&mut self) -> Result<()> {
use charls::{CharLS, FrameInfo, InterleaveMode};
let descriptor = self.dataset.pixel_descriptor()?;
if self.transfer_syntax()?.is_encapsulated() {
return Err(Error::InvalidPixelData(
"Pixel Data is already encapsulated".to_owned(),
));
}
if !matches!(descriptor.bits_allocated, 8 | 16) {
return Err(Error::InvalidPixelData(
"JPEG-LS writes 8- and 16-bit samples".to_owned(),
));
}
if !matches!(descriptor.samples_per_pixel, 1 | 3) {
return Err(Error::InvalidPixelData(
"JPEG-LS needs one or three samples".to_owned(),
));
}
let frames = self.pixel_frames()?;
let mut encoded = Vec::with_capacity(frames.len());
for frame in &frames {
let mut encoder = CharLS::default();
if descriptor.samples_per_pixel > 1 {
encoder
.set_interleave_mode(InterleaveMode::Sample)
.map_err(|err| Error::InvalidPixelData(format!("JPEG-LS encoder: {err}")))?;
}
let compressed = encoder
.encode(
FrameInfo {
width: u32::from(descriptor.columns),
height: u32::from(descriptor.rows),
bits_per_sample: i32::from(descriptor.bits_allocated),
component_count: i32::from(descriptor.samples_per_pixel),
},
0,
frame,
)
.map_err(|err| Error::InvalidPixelData(format!("JPEG-LS encoder: {err}")))?;
encoded.push(compressed);
}
self.set_encapsulated(encoded, "1.2.840.10008.1.2.4.80")
}
}
#[cfg(feature = "pixel-j2k")]
impl DicomFile {
pub fn compress_j2k(&mut self) -> Result<()> {
use jpeg2k::{ColorSpace, CoreImage, CoreImageComp, EncodeParameters, Image};
let descriptor = self.dataset.pixel_descriptor()?;
if self.transfer_syntax()?.is_encapsulated() {
return Err(Error::InvalidPixelData(
"Pixel Data is already encapsulated".to_owned(),
));
}
if !matches!(descriptor.bits_allocated, 8 | 16) {
return Err(Error::InvalidPixelData(
"JPEG 2000 writes 8- and 16-bit samples".to_owned(),
));
}
let samples = usize::from(descriptor.samples_per_pixel);
let bytes_per_sample = descriptor.bytes_per_sample();
let pixel_count = usize::from(descriptor.rows) * usize::from(descriptor.columns);
let signed = descriptor.pixel_representation == PixelRepresentation::Signed;
let planar = descriptor.planar_configuration == PlanarConfiguration::Planar;
let mut resolutions = 1u32;
while resolutions < 6
&& (1u32 << resolutions) <= u32::from(descriptor.columns.min(descriptor.rows))
{
resolutions += 1;
}
let frames = self.pixel_frames()?;
let mut encoded = Vec::with_capacity(frames.len());
for frame in &frames {
let comps = (0..samples)
.map(|sample| {
let data = (0..pixel_count)
.map(|pixel| {
let index = if planar {
(sample * pixel_count + pixel) * bytes_per_sample
} else {
(pixel * samples + sample) * bytes_per_sample
};
match (bytes_per_sample, signed) {
(1, false) => i32::from(frame[index]),
(1, true) => i32::from(frame[index] as i8),
(_, false) => {
i32::from(u16::from_le_bytes([frame[index], frame[index + 1]]))
}
(_, true) => {
i32::from(i16::from_le_bytes([frame[index], frame[index + 1]]))
}
}
})
.collect();
CoreImageComp {
dx: 1,
dy: 1,
w: u32::from(descriptor.columns),
h: u32::from(descriptor.rows),
x0: 0,
y0: 0,
prec: u32::from(descriptor.bits_stored),
bpp: u32::from(descriptor.bits_allocated),
sgnd: u32::from(signed),
resno_decoded: 0,
factor: 0,
alpha: 0,
data,
}
})
.collect();
let image = Image::from_core_image(CoreImage {
x0: 0,
y0: 0,
x1: u32::from(descriptor.columns),
y1: u32::from(descriptor.rows),
numcomps: u32::from(descriptor.samples_per_pixel),
color_space: if samples >= 3 {
ColorSpace::Srgb
} else {
ColorSpace::Gray
},
comps,
icc_profile_buf: Vec::new(),
icc_profile_is_cielab: false,
});
encoded.push(
image
.encode(EncodeParameters::new().num_resolutions(resolutions))
.map_err(|err| Error::InvalidPixelData(format!("JPEG 2000 encoder: {err}")))?,
);
}
self.set_encapsulated(encoded, "1.2.840.10008.1.2.4.90")
}
}
#[cfg(feature = "pixel-jxl")]
impl DicomFile {
pub fn compress_jxl(&mut self) -> Result<()> {
use zune_core::bit_depth::BitDepth;
use zune_core::colorspace::ColorSpace;
use zune_core::options::EncoderOptions;
use zune_jpegxl::JxlSimpleEncoder;
let descriptor = self.dataset.pixel_descriptor()?;
if self.transfer_syntax()?.is_encapsulated() {
return Err(Error::InvalidPixelData(
"Pixel Data is already encapsulated".to_owned(),
));
}
let (space, depth) = match (descriptor.samples_per_pixel, descriptor.bits_allocated) {
(1, 8) => (ColorSpace::Luma, BitDepth::Eight),
(3, 8) => (ColorSpace::RGB, BitDepth::Eight),
(1, 16) => (ColorSpace::Luma, BitDepth::Sixteen),
(3, 16) => (ColorSpace::RGB, BitDepth::Sixteen),
(samples, bits) => {
return Err(Error::InvalidPixelData(format!(
"JPEG XL writes 8- and 16-bit gray or colour, this image has {samples} \
sample(s) of {bits} bits"
)))
}
};
let width = usize::from(descriptor.columns);
let height = usize::from(descriptor.rows);
let frame_len = width
* usize::from(descriptor.samples_per_pixel)
* height
* (usize::from(descriptor.bits_allocated) / 8);
let frames = self.pixel_frames()?;
let mut encoded = Vec::with_capacity(frames.len());
for frame in &frames {
let samples = frame.get(..frame_len).ok_or_else(|| {
Error::InvalidPixelData(format!(
"frame holds {} bytes, JPEG XL needs {frame_len}",
frame.len()
))
})?;
let mut codestream = Vec::new();
JxlSimpleEncoder::new(samples, EncoderOptions::new(width, height, space, depth))
.encode(&mut codestream)
.map_err(|err| Error::InvalidPixelData(format!("JPEG XL encoder: {err}")))?;
encoded.push(codestream);
}
self.set_encapsulated(encoded, "1.2.840.10008.1.2.4.110")
}
}
fn decode_frame_bytes(
syntax: TransferSyntax,
descriptor: &PixelDescriptor,
frame: &[u8],
) -> Result<Vec<u8>> {
if let TransferSyntax::Encapsulated(uid) = syntax {
if uid == "1.2.840.10008.1.2.5" {
return rle::decode(frame, descriptor);
}
if is_jpeg_lossless_uid(uid) {
return jpeg_lossless::decode(frame, descriptor);
}
#[cfg(feature = "pixel-jpeg")]
if is_jpeg_uid(uid) {
return jpeg::decode(frame, descriptor);
}
#[cfg(feature = "pixel-jpegls")]
if is_jpegls_uid(uid) {
return jpegls::decode(frame, descriptor);
}
#[cfg(feature = "pixel-j2k")]
if is_j2k_uid(uid) {
return j2k::decode(frame, descriptor);
}
#[cfg(feature = "pixel-jxl")]
if is_jxl_uid(uid) {
return jxl::decode(frame, descriptor);
}
return Err(Error::UnsupportedPixelData(format!(
"transfer syntax {uid}"
)));
}
Ok(frame.to_vec())
}
fn is_jpeg_lossless_uid(uid: &str) -> bool {
matches!(uid, "1.2.840.10008.1.2.4.57" | "1.2.840.10008.1.2.4.70")
}
#[cfg(feature = "pixel-jpeg")]
fn is_jpeg_uid(uid: &str) -> bool {
matches!(
uid,
"1.2.840.10008.1.2.4.50"
| "1.2.840.10008.1.2.4.51"
| "1.2.840.10008.1.2.4.52"
| "1.2.840.10008.1.2.4.53"
| "1.2.840.10008.1.2.4.54"
)
}
#[cfg(feature = "pixel-jpegls")]
fn is_jpegls_uid(uid: &str) -> bool {
matches!(uid, "1.2.840.10008.1.2.4.80" | "1.2.840.10008.1.2.4.81")
}
#[cfg(feature = "pixel-jxl")]
fn is_jxl_uid(uid: &str) -> bool {
matches!(
uid,
"1.2.840.10008.1.2.4.110" | "1.2.840.10008.1.2.4.111" | "1.2.840.10008.1.2.4.112"
)
}
#[cfg(feature = "pixel-j2k")]
fn is_j2k_uid(uid: &str) -> bool {
matches!(
uid,
"1.2.840.10008.1.2.4.90"
| "1.2.840.10008.1.2.4.91"
| "1.2.840.10008.1.2.4.201"
| "1.2.840.10008.1.2.4.202"
| "1.2.840.10008.1.2.4.203"
| "1.2.840.10008.1.2.4.204"
)
}