#[test]
fn writes_flat_json_with_source_uri_mode_for_pixeldata_bulkdatauri() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let object = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_source(&object, &source).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let pixel = &value["PixelData"];
let uri = pixel.get("BulkDataURI").and_then(|v| v.as_str()).unwrap();
assert!(
uri.contains("offset=") && uri.contains("length="),
"PixelData BulkDataURI must include offset and length, got: {}",
uri
);
assert!(
!uri.contains("tag="),
"PixelData BulkDataURI must not fallback to tag-based URI, got: {}",
uri
);
}
#[test]
fn deflated_transfer_syntax_falls_back_to_inline_binary_for_bulk_data() {
let source = fixture_bytes(fixture_path("deflated.dcm"));
let object = read_dicom_bytes(&source).unwrap();
assert_eq!(
object.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.1.99"
);
let json = write_dicom_json_with_source(&object, &source).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let pixel = &value["PixelData"];
assert!(
pixel.get("BulkDataURI").is_none(),
"a deflated dataset has no valid file-byte-offset for BulkDataURI"
);
let inline = pixel["InlineBinary"]
.as_str()
.expect("PixelData should fall back to InlineBinary");
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
let decoded = BASE64_STANDARD.decode(inline).unwrap();
let expected = object
.element(dcmnorm_dictionary::tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.to_vec();
assert_eq!(
decoded, expected,
"InlineBinary must still carry the real pixel data, not garbage"
);
}
#[test]
fn writes_flat_json_with_source_uri_mode_for_large_meta_without_part10_header() {
let source = fixture_bytes(repo_root_path("nometa.dcm"));
let object = read_dicom_bytes(&source).unwrap();
use dcmnorm_core::value::PrimitiveValue;
use dcmnorm_core::DataElement;
use dcmnorm_dictionary::tags;
let big_bytes = vec![0xAB; 64];
let mut object = object;
object.put(DataElement::new(
tags::IMPLEMENTATION_VERSION_NAME,
dcmnorm_core::VR::SH,
PrimitiveValue::from(big_bytes.clone()),
));
let json = write_dicom_json_with_source(&object, &source).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let meta = &value["ImplementationVersionName"];
assert!(
meta.get("BulkDataURI").is_none(),
"non-bulk meta should not emit offsetless BulkDataURI"
);
}
#[test]
fn writes_flat_json_with_source_uri_mode_for_nometa_pixeldata_uses_offset_length() {
let source = fixture_bytes(repo_root_path("nometa.dcm"));
let object = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_source(&object, &source).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let uri = value["PixelData"]["BulkDataURI"].as_str().unwrap();
assert!(uri.contains("offset="), "missing offset in URI: {uri}");
assert!(uri.contains("length="), "missing length in URI: {uri}");
assert!(!uri.contains("tag="), "unexpected tag-based URI: {uri}");
}
#[test]
fn writes_flat_json_with_source_uri_mode_for_nested_bulk_value() {
let mut source = fixture_bytes(fixture_path("dx.dcm"));
let nested_payload = vec![0x5A; 64];
append_nested_icc_profile_sequence(&mut source, &nested_payload);
let object = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_source(&object, &source).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let icc = &value["OpticalPathSequence"][0]["ICCProfile"];
let uri = icc["BulkDataURI"]
.as_str()
.expect("nested ICCProfile should emit BulkDataURI");
assert!(uri.contains("offset="), "missing offset in URI: {uri}");
assert!(uri.contains("length="), "missing length in URI: {uri}");
assert!(
icc["InlineBinary"].is_null(),
"nested ICCProfile should not fallback to InlineBinary"
);
}
#[test]
fn writes_flat_json_with_source_uri_mode_for_large_nested_bulk_value() {
let mut source = fixture_bytes(fixture_path("dx.dcm"));
let nested_payload: Vec<u8> = (0..150_000u32).map(|i| (i % 251) as u8).collect();
append_nested_icc_profile_sequence(&mut source, &nested_payload);
let object = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_source(&object, &source).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let icc = &value["OpticalPathSequence"][0]["ICCProfile"];
assert!(
icc["InlineBinary"].is_null(),
"large nested ICCProfile should not fallback to InlineBinary"
);
let uri = icc["BulkDataURI"]
.as_str()
.expect("large nested ICCProfile should emit BulkDataURI");
let (offset, length) = parse_offset_length(uri);
assert_eq!(&source[offset..offset + length], nested_payload.as_slice());
let (pixel_offset, pixel_length) =
parse_offset_length(value["PixelData"]["BulkDataURI"].as_str().unwrap());
assert!(pixel_offset + pixel_length <= source.len());
}
#[test]
fn writes_flat_json_with_source_uri_mode_for_wsi_nested_icc_profile() {
let source = fixture_bytes(fixture_path("wsi.dcm"));
let object = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_source(&object, &source).unwrap();
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let icc = &value["OpticalPathSequence"][0]["ICCProfile"];
assert!(
icc["InlineBinary"].is_null(),
"wsi ICCProfile fell back to InlineBinary"
);
let (offset, length) = parse_offset_length(icc["BulkDataURI"].as_str().unwrap());
assert!(
length > 64 * 1024,
"expected a large ICC profile, got {length} bytes"
);
assert_eq!(&source[offset + 36..offset + 40], b"acsp");
}
fn parse_offset_length(uri: &str) -> (usize, usize) {
let param = |name: &str| -> usize {
uri.split(['?', '&'])
.find_map(|kv| kv.strip_prefix(name)?.strip_prefix('='))
.unwrap_or_else(|| panic!("missing {name} in URI: {uri}"))
.parse()
.unwrap()
};
(param("offset"), param("length"))
}
#[test]
fn reads_element_with_nonstandard_ambiguous_vr_shorthand_as_unsigned_short() {
let mut source = fixture_bytes(fixture_path("dx.dcm"));
let tag = Tag(0x0028, 0x0107); append_explicit_vr_header(&mut source, tag, *b"xs", 2);
source.extend_from_slice(&4017u16.to_le_bytes());
let object = read_dicom_bytes(&source).unwrap();
let element = object.element(tag).unwrap();
assert_eq!(element.header().vr(), VR::US);
assert_eq!(element.to_int::<u16>().unwrap(), 4017);
}
#[test]
fn reads_element_with_nonstandard_ambiguous_vr_shorthand_ox_as_other_word() {
let mut source = fixture_bytes(fixture_path("dx.dcm"));
let tag = Tag(0x0028, 0x9999); let payload = [0xAB, 0xCD, 0xEF, 0x01];
append_explicit_vr_header(&mut source, tag, *b"ox", payload.len() as u32);
source.extend_from_slice(&payload);
let object = read_dicom_bytes(&source).unwrap();
let element = object.element(tag).unwrap();
assert_eq!(element.header().vr(), VR::OW);
}
fn append_nested_icc_profile_sequence(bytes: &mut Vec<u8>, payload: &[u8]) {
let sequence_tag = Tag(0x0048, 0x0105); let icc_profile_tag = Tag(0x0028, 0x2000);
append_explicit_vr_header(bytes, sequence_tag, *b"SQ", u32::MAX);
append_item_header(bytes, u32::MAX);
append_explicit_vr_header(bytes, icc_profile_tag, *b"OB", payload.len() as u32);
bytes.extend_from_slice(payload);
append_item_delimitation(bytes);
append_sequence_delimitation(bytes);
}
fn append_explicit_vr_header(bytes: &mut Vec<u8>, tag: Tag, vr: [u8; 2], len: u32) {
bytes.extend_from_slice(&tag.group().to_le_bytes());
bytes.extend_from_slice(&tag.element().to_le_bytes());
bytes.extend_from_slice(&vr);
if uses_32_bit_vr_length(vr) {
bytes.extend_from_slice(&[0, 0]);
bytes.extend_from_slice(&len.to_le_bytes());
} else {
bytes.extend_from_slice(&(len as u16).to_le_bytes());
}
}
fn append_item_header(bytes: &mut Vec<u8>, len: u32) {
bytes.extend_from_slice(&0xFFFEu16.to_le_bytes());
bytes.extend_from_slice(&0xE000u16.to_le_bytes());
bytes.extend_from_slice(&len.to_le_bytes());
}
fn append_item_delimitation(bytes: &mut Vec<u8>) {
bytes.extend_from_slice(&0xFFFEu16.to_le_bytes());
bytes.extend_from_slice(&0xE00Du16.to_le_bytes());
bytes.extend_from_slice(&0u32.to_le_bytes());
}
fn append_sequence_delimitation(bytes: &mut Vec<u8>) {
bytes.extend_from_slice(&0xFFFEu16.to_le_bytes());
bytes.extend_from_slice(&0xE0DDu16.to_le_bytes());
bytes.extend_from_slice(&0u32.to_le_bytes());
}
fn uses_32_bit_vr_length(vr: [u8; 2]) -> bool {
matches!(
&vr,
b"OB"
| b"OD"
| b"OF"
| b"OL"
| b"OV"
| b"OW"
| b"SQ"
| b"UC"
| b"UR"
| b"UT"
| b"UN"
| b"ox"
)
}
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use dcmnorm_core::{dicom_value, DataElement, PrimitiveValue, Tag, VR};
use dcmnorm_dictionary::tags;
use dcmnorm_dictionary::uids;
use dcmnorm_object::InMemDicomObject;
use serde_json::Value as JsonValue;
use super::dimse::build_move_identifier;
use super::{
build_volume, detect_jpeg2000_backend_from_search_path, dicom_file_to_json, echo_scu, find_scu,
kakadu_ffi_enabled, list_transfer_syntax_support, move_scu, pack_dicom_frame_stack_texture,
pack_dicom_frame_texture, parse_attribute_override, probe_dicom_file_for_sop_class_uid,
read_dicom_bytes, read_dicom_file, read_dicom_file_deferring_bulk_data,
read_dicom_file_for_frame, read_dicom_json, read_dicom_json_full,
read_dicom_json_full_with_source, read_dicom_json_with_options, read_dicom_json_with_source,
redact_dicom_pixels_to_transfer_syntax, reformat_plane, remove_attribute,
render_all_dicom_video_frames, render_dicom_frame, set_attribute, start_scp, store_scu,
transcode_dcmnorm_object, transcode_dicom_bytes, write_dataset_as_dicom_file,
write_dicom_bytes, write_dicom_file, write_dicom_json, write_dicom_json_full,
write_dicom_json_full_with_source, write_dicom_json_with_options, write_dicom_json_with_source,
BoundingBox, BoxLength, CancelMode, CancelSignal, ContentKind, DicomJsonBulkDataMode,
DicomJsonFormat, DicomJsonKeyStyle, DicomJsonReadOptions, DicomJsonWriteOptions, DimseError,
DimseLogger, EchoScuOptions, FindScuOptions, Interpolation, Jpeg2000Backend, MoveScuOptions,
PlaneParams, QueryRetrieveLevel, RenderError, RenderOutputFormat, RenderPipelineOptions,
ScpHandlers, ScpOptions, SlabProjection, StoreScuOptions, TextureCompression,
TextureExportError, VolumeError,
};
#[test]
fn set_attribute_writes_media_storage_sop_class_uid_to_meta_not_dataset() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let mut object = read_dicom_bytes(&source).unwrap();
let (tag, vr, value) =
parse_attribute_override("MediaStorageSOPClassUID=1.2.840.10008.5.1.4.1.1.7").unwrap();
set_attribute(&mut object, tag, vr, value).unwrap();
assert_eq!(
object.meta().media_storage_sop_class_uid,
"1.2.840.10008.5.1.4.1.1.7",
"set_attribute should update the real File Meta Information group"
);
assert!(
object.element(tags::MEDIA_STORAGE_SOP_CLASS_UID).is_err(),
"MediaStorageSOPClassUID must not also leak into the dataset"
);
}
#[test]
fn set_attribute_writes_media_storage_sop_instance_uid_to_meta() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let mut object = read_dicom_bytes(&source).unwrap();
let (tag, vr, value) =
parse_attribute_override("MediaStorageSOPInstanceUID=1.2.840.10008.114051.1.2.3.4.5")
.unwrap();
set_attribute(&mut object, tag, vr, value).unwrap();
assert_eq!(
object.meta().media_storage_sop_instance_uid,
"1.2.840.10008.114051.1.2.3.4.5"
);
assert!(object
.element(tags::MEDIA_STORAGE_SOP_INSTANCE_UID)
.is_err());
}
#[test]
fn set_attribute_rejects_unsettable_meta_elements() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let mut object = read_dicom_bytes(&source).unwrap();
let original_transfer_syntax = object.meta().transfer_syntax.clone();
let (tag, vr, value) =
parse_attribute_override("TransferSyntaxUID=1.2.840.10008.1.2.1").unwrap();
let result = set_attribute(&mut object, tag, vr, value);
assert!(result.is_err());
assert_eq!(object.meta().transfer_syntax, original_transfer_syntax);
}
#[test]
fn set_attribute_still_writes_dataset_elements() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let mut object = read_dicom_bytes(&source).unwrap();
let (tag, vr, value) = parse_attribute_override("PatientName=DOE^JOHN").unwrap();
set_attribute(&mut object, tag, vr, value).unwrap();
assert_eq!(
object
.element(tags::PATIENT_NAME)
.unwrap()
.to_str()
.unwrap(),
"DOE^JOHN"
);
}
#[test]
fn remove_attribute_clears_media_storage_sop_instance_uid() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let mut object = read_dicom_bytes(&source).unwrap();
assert!(!object.meta().media_storage_sop_instance_uid.is_empty());
let was_present = remove_attribute(&mut object, tags::MEDIA_STORAGE_SOP_INSTANCE_UID);
assert!(was_present, "the tag was present before removal");
assert!(
object.meta().media_storage_sop_instance_uid.is_empty(),
"remove_attribute should clear the real File Meta Information field"
);
}
#[test]
fn remove_attribute_on_absent_meta_field_reports_not_present() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let mut object = read_dicom_bytes(&source).unwrap();
remove_attribute(&mut object, tags::MEDIA_STORAGE_SOP_INSTANCE_UID);
let was_present_second_time =
remove_attribute(&mut object, tags::MEDIA_STORAGE_SOP_INSTANCE_UID);
assert!(!was_present_second_time);
}
#[test]
fn remove_attribute_still_removes_dataset_elements() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let mut object = read_dicom_bytes(&source).unwrap();
assert!(object.element(tags::PATIENT_NAME).is_ok());
let was_present = remove_attribute(&mut object, tags::PATIENT_NAME);
assert!(was_present);
assert!(object.element(tags::PATIENT_NAME).is_err());
}
const PRIVATE_TAG: Tag = Tag(0x0013, 0x1010);
const EXPLICIT_VR_BIG_ENDIAN_UID: &str = "1.2.840.10008.1.2.2";
const JPEG_2000_IMAGE_COMPRESSION_UID: &str = "1.2.840.10008.1.2.4.91";
#[test]
fn transcodes_rle_ybr_full_preserving_photometric_interpretation() {
let Some(path) = optional_repo_fixture_path("test.dcm") else {
return;
};
let source = read_dicom_file(path).unwrap();
let transcoded = transcode_dcmnorm_object(&source, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
let photometric = transcoded
.element(tags::PHOTOMETRIC_INTERPRETATION)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
assert_eq!(photometric, "YBR_FULL");
let planar = transcoded
.element(tags::PLANAR_CONFIGURATION)
.unwrap()
.uint16()
.unwrap();
assert_eq!(planar, 0);
}
#[test]
fn renders_rle_ybr_full_without_pink_cast() {
let Some(path) = optional_repo_fixture_path("test.dcm") else {
return;
};
let source = read_dicom_file(path).unwrap();
let rendered = render_dicom_frame(
&source,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
let image = image::load_from_memory(&rendered.bytes).unwrap().to_rgb8();
let first = image.get_pixel(0, 0).0;
assert!(first[0] <= 5, "expected low red channel, got {}", first[0]);
assert!(
first[1] <= 5,
"expected low green channel, got {}",
first[1]
);
assert!(first[2] <= 5, "expected low blue channel, got {}", first[2]);
}
#[test]
fn reads_dicom_file_fixture() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
assert_eq!(
object.element(tags::MODALITY).unwrap().to_str().unwrap(),
"DX"
);
assert!(object.element(tags::PIXEL_DATA).is_ok());
}
#[test]
fn reads_dicom_file_without_part10_header() {
let object = read_dicom_file(repo_root_path("nometa.dcm")).unwrap();
assert_eq!(
object.element(tags::MODALITY).unwrap().to_str().unwrap(),
"DX"
);
}
#[test]
fn probes_dicom_file_with_part10_header() {
let is_valid = probe_dicom_file_for_sop_class_uid(fixture_path("dx.dcm")).unwrap();
assert!(is_valid);
}
#[test]
fn probes_deflated_dicom_file() {
let is_valid = probe_dicom_file_for_sop_class_uid(fixture_path("deflated.dcm")).unwrap();
assert!(is_valid);
assert!(super::check_dicom_bytes(include_bytes!(
"../../test/files/deflated.dcm"
)));
}
#[test]
fn probes_dicom_file_without_part10_header() {
let is_valid = probe_dicom_file_for_sop_class_uid(repo_root_path("nometa.dcm")).unwrap();
assert!(is_valid);
}
#[test]
fn probe_rejects_non_dicom_file() {
let is_valid = probe_dicom_file_for_sop_class_uid(fixture_path("notdicom.txt")).unwrap();
assert!(!is_valid);
}
#[test]
fn probe_rejects_directory_path() {
let is_valid = probe_dicom_file_for_sop_class_uid(fixture_path(""))
.expect("directory metadata should be readable");
assert!(!is_valid);
}
#[test]
fn remove_private_tags_removes_all_private_tags() {
let mut object = read_dicom_bytes(include_bytes!("../../test/files/dx.dcm")).unwrap();
let private_tag = Tag(0x0013, 0x1010);
object.put(DataElement::new(
private_tag,
VR::LO,
PrimitiveValue::from("PRIVATE"),
));
let standard_tag = tags::PATIENT_NAME;
object.put(DataElement::new(
standard_tag,
VR::PN,
PrimitiveValue::from("John^Doe"),
));
super::remove_private_tags_inplace(&mut object);
assert!(
object.element(private_tag).is_err(),
"private tag was not removed"
);
assert_eq!(
object.element(standard_tag).unwrap().to_str().unwrap(),
"John^Doe"
);
}
#[test]
fn writes_dicom_file_fixture_round_trip() {
let mut original = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let output_path = temp_file_path("dicom-file-roundtrip");
write_dicom_file(&mut original, &output_path).unwrap();
let roundtrip = read_dicom_file(&output_path).unwrap();
assert_core_fields_match(&original, &roundtrip);
fs::remove_file(output_path).unwrap();
}
#[test]
fn reads_dicom_bytes_fixture() {
let bytes = fixture_bytes(fixture_path("dx.dcm"));
let object = read_dicom_bytes(&bytes).unwrap();
assert_eq!(
object.element(tags::MODALITY).unwrap().to_str().unwrap(),
"DX"
);
assert!(object.element(tags::PIXEL_DATA).is_ok());
}
#[test]
fn writes_dicom_bytes_fixture_round_trip() {
let mut original = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let bytes = write_dicom_bytes(&mut original).unwrap();
let roundtrip = read_dicom_bytes(&bytes).unwrap();
assert_core_fields_match(&original, &roundtrip);
}
#[test]
fn writes_dicom_file_with_explicit_length_nested_sequences_stays_readable() {
let mut object = read_dicom_file(fixture_path("sr.dcm")).unwrap();
object.put_str(tags::PATIENT_NAME, dcmnorm_core::VR::PN, "TEST");
let bytes = write_dicom_bytes(&mut object).unwrap();
let roundtrip = read_dicom_bytes(&bytes).unwrap();
assert_eq!(
roundtrip
.element(tags::PATIENT_NAME)
.unwrap()
.to_str()
.unwrap(),
"TEST"
);
assert_eq!(
roundtrip
.element(tags::CONTENT_SEQUENCE)
.unwrap()
.items()
.unwrap()
.len(),
1
);
}
#[test]
fn writes_flat_json_with_inline_binary_by_default() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let json_text = write_dicom_json(&object).unwrap();
let json: JsonValue = serde_json::from_str(&json_text).unwrap();
assert_eq!(json["Modality"], JsonValue::String("DX".to_owned()));
assert!(json["PixelData"]["InlineBinary"].is_string());
assert_eq!(json["00131010"]["vr"], JsonValue::String("LO".to_owned()));
assert!(json["00131010"]["Value"].is_string());
let roundtrip = read_dicom_json(&json_text).unwrap();
assert_core_fields_match(&object, &roundtrip);
assert_eq!(roundtrip.element(PRIVATE_TAG).unwrap().vr(), VR::LO);
}
#[test]
fn writes_flat_json_keys_as_hex_when_requested() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let json_text = write_dicom_json_with_options(
&object,
DicomJsonWriteOptions {
key_style: DicomJsonKeyStyle::Hex,
..DicomJsonWriteOptions::default()
},
)
.unwrap();
let json: JsonValue = serde_json::from_str(&json_text).unwrap();
assert_eq!(json["00080060"], JsonValue::String("DX".to_owned()));
assert_eq!(json["00131010"]["vr"], JsonValue::String("LO".to_owned()));
assert_eq!(
json["00020010"],
JsonValue::String("1.2.840.10008.1.2.1".to_owned())
);
let roundtrip = read_dicom_json(&json_text).unwrap();
assert_core_fields_match(&object, &roundtrip);
assert_eq!(
roundtrip.meta().transfer_syntax(),
object.meta().transfer_syntax()
);
}
#[test]
fn writes_and_reads_flat_json_with_bulk_data_uri() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let original = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_source(&original, &source).unwrap();
let value: JsonValue = serde_json::from_str(&json).unwrap();
assert!(value["FileMetaInformationVersion"]["InlineBinary"].is_string());
assert!(value["FileMetaInformationVersion"]["BulkDataURI"].is_null());
let pixel_uri = value["PixelData"]["BulkDataURI"].as_str().unwrap();
assert!(pixel_uri.contains("offset="));
assert!(pixel_uri.contains("length="));
let roundtrip = read_dicom_json_with_source(&json, &source).unwrap();
assert_core_fields_match(&original, &roundtrip);
assert_eq!(
original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.len(),
roundtrip
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.len(),
);
}
#[test]
fn reads_flat_json_with_file_bulk_data_uri_without_source() {
let source_path = fixture_path("dx.dcm");
let source = fixture_bytes(source_path.clone());
let original = read_dicom_bytes(&source).unwrap();
let canonical = source_path.canonicalize().unwrap();
let uri_base = format!(
"file://{}",
canonical
.to_string_lossy()
.replace('%', "%25")
.replace(' ', "%20")
);
let json = write_dicom_json_with_options(
&original,
DicomJsonWriteOptions {
bulk_data_mode: DicomJsonBulkDataMode::Uri,
bulk_data_source: Some(&source),
bulk_data_uri_base: Some(uri_base.as_str()),
..DicomJsonWriteOptions::default()
},
)
.unwrap();
let roundtrip = read_dicom_json(&json).unwrap();
assert_core_fields_match(&original, &roundtrip);
assert_eq!(
original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.len(),
roundtrip
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.len(),
);
}
fn icc_bytes(object: &dcmnorm_object::DefaultDicomObject) -> Vec<u8> {
let sequence_tag = Tag(0x0048, 0x0105); let icc_profile_tag = Tag(0x0028, 0x2000);
let dcmnorm_core::value::Value::Sequence(sequence) =
object.element(sequence_tag).unwrap().value()
else {
panic!("OpticalPathSequence did not decode as a sequence");
};
sequence.items()[0]
.element(icc_profile_tag)
.unwrap()
.to_bytes()
.unwrap()
.into_owned()
}
#[test]
fn reads_json_with_bulk_data_source_and_separate_file_bulk_data_uri_together() {
let mut source = fixture_bytes(fixture_path("dx.dcm"));
let nested_payload = vec![0x5A; 64];
append_nested_icc_profile_sequence(&mut source, &nested_payload);
let original = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_options(
&original,
DicomJsonWriteOptions {
bulk_data_mode: DicomJsonBulkDataMode::Uri,
bulk_data_source: Some(&source),
..DicomJsonWriteOptions::default()
},
)
.unwrap();
let icc_path = temp_file_path("dcmnorm-test-icc-separate-source");
fs::write(&icc_path, &nested_payload).unwrap();
let mut value: JsonValue = serde_json::from_str(&json).unwrap();
value["OpticalPathSequence"][0]["ICCProfile"] = serde_json::json!({
"BulkDataURI": format!(
"file://{}?offset=0&length={}",
icc_path.canonicalize().unwrap().to_string_lossy(),
nested_payload.len(),
)
});
let modified_json = serde_json::to_string(&value).unwrap();
let roundtrip = read_dicom_json_with_options(
&modified_json,
DicomJsonReadOptions {
format: DicomJsonFormat::Flat,
bulk_data_source: Some(&source),
},
);
fs::remove_file(&icc_path).ok();
let roundtrip = roundtrip.unwrap();
assert_eq!(
original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.into_owned(),
roundtrip
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.into_owned(),
);
assert_eq!(icc_bytes(&roundtrip), nested_payload);
}
#[test]
fn reads_json_with_two_independent_file_bulk_data_uris() {
let mut source = fixture_bytes(fixture_path("dx.dcm"));
let nested_payload = vec![0x5A; 64];
append_nested_icc_profile_sequence(&mut source, &nested_payload);
let original = read_dicom_bytes(&source).unwrap();
let pixel_data = original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.into_owned();
let pixel_path = temp_file_path("dcmnorm-test-pixeldata-separate-source");
let icc_path = temp_file_path("dcmnorm-test-icc-separate-source-2");
fs::write(&pixel_path, &pixel_data).unwrap();
fs::write(&icc_path, &nested_payload).unwrap();
let json = write_dicom_json_with_options(
&original,
DicomJsonWriteOptions {
bulk_data_mode: DicomJsonBulkDataMode::InlineBinary,
..DicomJsonWriteOptions::default()
},
)
.unwrap();
let mut value: JsonValue = serde_json::from_str(&json).unwrap();
value["PixelData"] = serde_json::json!({
"BulkDataURI": format!(
"file://{}?offset=0&length={}",
pixel_path.canonicalize().unwrap().to_string_lossy(),
pixel_data.len(),
)
});
value["OpticalPathSequence"][0]["ICCProfile"] = serde_json::json!({
"BulkDataURI": format!(
"file://{}?offset=0&length={}",
icc_path.canonicalize().unwrap().to_string_lossy(),
nested_payload.len(),
)
});
let modified_json = serde_json::to_string(&value).unwrap();
let roundtrip = read_dicom_json_with_options(
&modified_json,
DicomJsonReadOptions {
format: DicomJsonFormat::Flat,
bulk_data_source: None,
},
);
fs::remove_file(&pixel_path).ok();
fs::remove_file(&icc_path).ok();
let roundtrip = roundtrip.unwrap();
assert_eq!(
roundtrip
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.into_owned(),
pixel_data,
);
assert_eq!(icc_bytes(&roundtrip), nested_payload);
}
#[test]
fn writes_flat_json_with_source_for_file_without_part10_header() {
let source = fixture_bytes(repo_root_path("nometa.dcm"));
let object = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_source(&object, &source).unwrap();
let value: JsonValue = serde_json::from_str(&json).unwrap();
assert!(value["FileMetaInformationVersion"]["InlineBinary"].is_string());
assert_eq!(
value["Modality"],
JsonValue::String(
object
.element(tags::MODALITY)
.unwrap()
.to_str()
.unwrap()
.to_string()
)
);
}
#[test]
fn writes_and_reads_flat_json_with_bulk_data_uri_for_ct() {
let source = fixture_bytes(fixture_path("ct.dcm"));
let original = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_with_source(&original, &source).unwrap();
let mut roundtrip = read_dicom_json_with_source(&json, &source).unwrap();
let bytes = write_dicom_bytes(&mut roundtrip).unwrap();
let rewritten = read_dicom_bytes(&bytes).unwrap();
assert_eq!(
roundtrip.meta().transfer_syntax(),
original.meta().transfer_syntax()
);
assert_eq!(
rewritten
.element(tags::PIXEL_DATA)
.unwrap()
.fragments()
.unwrap()
.len(),
original
.element(tags::PIXEL_DATA)
.unwrap()
.fragments()
.unwrap()
.len(),
);
assert_eq!(
rewritten
.element(tags::REQUEST_ATTRIBUTES_SEQUENCE)
.unwrap()
.items()
.unwrap()
.len(),
original
.element(tags::REQUEST_ATTRIBUTES_SEQUENCE)
.unwrap()
.items()
.unwrap()
.len(),
);
}
#[test]
fn writes_and_reads_full_json_with_inline_binary() {
let original = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let json = write_dicom_json_full(&original).unwrap();
let value: JsonValue = serde_json::from_str(&json).unwrap();
assert_eq!(value["00080060"]["vr"], JsonValue::String("CS".to_owned()));
assert_eq!(
value["00080060"]["Keyword"],
JsonValue::String("Modality".to_owned())
);
assert!(value["7FE00010"]["InlineBinary"].is_string());
assert_eq!(value["7FE00010"]["VM"], JsonValue::Number(1.into()));
let roundtrip = read_dicom_json_full(&json).unwrap();
assert_core_fields_match(&original, &roundtrip);
}
#[test]
fn writes_and_reads_full_json_with_bulk_data_uri() {
let source = fixture_bytes(fixture_path("ct.dcm"));
let original = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_full_with_source(&original, &source).unwrap();
let value: JsonValue = serde_json::from_str(&json).unwrap();
assert!(value["00020001"]["InlineBinary"].is_string());
assert!(value["00020001"]["BulkDataURI"].is_null());
let pixel_uri = value["7FE00010"]["BulkDataURI"].as_str().unwrap();
assert!(pixel_uri.contains("offset="));
assert!(pixel_uri.contains("length="));
assert_eq!(
value["7FE00010"]["Keyword"],
JsonValue::String("PixelData".to_owned())
);
let roundtrip = read_dicom_json_full_with_source(&json, &source).unwrap();
assert_eq!(
original.element(tags::MODALITY).unwrap().to_str().unwrap(),
roundtrip.element(tags::MODALITY).unwrap().to_str().unwrap(),
);
assert_eq!(
original
.element(tags::PIXEL_DATA)
.unwrap()
.fragments()
.unwrap()
.len(),
roundtrip
.element(tags::PIXEL_DATA)
.unwrap()
.fragments()
.unwrap()
.len(),
);
assert_eq!(
original.meta().transfer_syntax(),
roundtrip.meta().transfer_syntax()
);
}
#[test]
fn writes_full_json_with_source_uri_mode_for_nested_bulk_value() {
let mut source = fixture_bytes(fixture_path("dx.dcm"));
let nested_payload = vec![0x5A; 64];
append_nested_icc_profile_sequence(&mut source, &nested_payload);
let object = read_dicom_bytes(&source).unwrap();
let json = write_dicom_json_full_with_source(&object, &source).unwrap();
let value: JsonValue = serde_json::from_str(&json).unwrap();
let icc = &value["00480105"]["Value"][0]["00282000"];
let uri = icc["BulkDataURI"]
.as_str()
.expect("nested ICCProfile should emit BulkDataURI in standard JSON too");
assert!(uri.contains("offset="), "missing offset in URI: {uri}");
assert!(uri.contains("length="), "missing length in URI: {uri}");
assert!(
icc["InlineBinary"].is_null(),
"nested ICCProfile should not fallback to InlineBinary"
);
let roundtrip = read_dicom_json_full_with_source(&json, &source).unwrap();
let optical_path = roundtrip
.element(Tag(0x0048, 0x0105))
.unwrap()
.items()
.unwrap();
let icc_profile = optical_path[0].element(Tag(0x0028, 0x2000)).unwrap();
assert_eq!(icc_profile.to_bytes().unwrap().into_owned(), nested_payload);
}
#[test]
fn writes_and_reads_full_json_pn_with_ideographic_and_phonetic() {
let mut object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
object.put(DataElement::new(
tags::PATIENT_NAME,
VR::PN,
PrimitiveValue::from("Yamada^Tarou=山田^太郎=やまだ^たろう"),
));
let json = write_dicom_json_full(&object).unwrap();
let value: JsonValue = serde_json::from_str(&json).unwrap();
let name = &value["00100010"]["Value"][0];
assert_eq!(
name["Alphabetic"],
JsonValue::String("Yamada^Tarou".to_owned())
);
assert_eq!(
name["Ideographic"],
JsonValue::String("山田^太郎".to_owned())
);
assert_eq!(
name["Phonetic"],
JsonValue::String("やまだ^たろう".to_owned())
);
let roundtrip = read_dicom_json_full(&json).unwrap();
assert_eq!(
roundtrip
.element(tags::PATIENT_NAME)
.unwrap()
.to_str()
.unwrap(),
"Yamada^Tarou=山田^太郎=やまだ^たろう"
);
}
#[test]
fn writes_and_reads_full_json_numeric_nan_and_infinity() {
let mut object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
object.put(DataElement::new(
Tag(0x0018, 0x9432), VR::FD,
PrimitiveValue::from([f64::NAN, f64::INFINITY, f64::NEG_INFINITY]),
));
let json = write_dicom_json_full(&object).unwrap();
let value: JsonValue = serde_json::from_str(&json).unwrap();
let values = value["00189432"]["Value"].as_array().unwrap();
assert_eq!(values[0], JsonValue::String("NaN".to_owned()));
assert_eq!(values[1], JsonValue::String("inf".to_owned()));
assert_eq!(values[2], JsonValue::String("-inf".to_owned()));
let roundtrip = read_dicom_json_full(&json).unwrap();
let restored = roundtrip
.element(Tag(0x0018, 0x9432))
.unwrap()
.to_multi_float64()
.unwrap();
assert!(restored[0].is_nan());
assert_eq!(restored[1], f64::INFINITY);
assert_eq!(restored[2], f64::NEG_INFINITY);
}
#[test]
fn writes_and_reads_full_json_large_integer_falls_back_to_string() {
let mut object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let large_value = 876_543_245_678u64;
object.put(DataElement::new(
Tag(0x0028, 0x9422), VR::UV,
PrimitiveValue::U64(vec![large_value].into()),
));
let json = write_dicom_json_full(&object).unwrap();
let value: JsonValue = serde_json::from_str(&json).unwrap();
assert_eq!(
value["00289422"]["Value"][0],
JsonValue::String(large_value.to_string())
);
let roundtrip = read_dicom_json_full(&json).unwrap();
assert_eq!(
roundtrip
.element(Tag(0x0028, 0x9422))
.unwrap()
.to_multi_int::<u64>()
.unwrap()[0],
large_value
);
}
#[test]
fn transcodes_native_dataset_to_big_endian() {
let original = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let mut transcoded = transcode_dcmnorm_object(&original, EXPLICIT_VR_BIG_ENDIAN_UID).unwrap();
let bytes = write_dicom_bytes(&mut transcoded).unwrap();
let roundtrip = read_dicom_bytes(&bytes).unwrap();
assert_eq!(
roundtrip.meta().transfer_syntax(),
EXPLICIT_VR_BIG_ENDIAN_UID
);
assert_dataset_fields_match(&original, &roundtrip);
assert_eq!(
original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.len(),
roundtrip
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.len(),
);
}
#[test]
fn transcodes_native_dataset_to_encapsulated_uncompressed_and_back() {
let original = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let encapsulated = transcode_dcmnorm_object(
&original,
uids::ENCAPSULATED_UNCOMPRESSED_EXPLICIT_VR_LITTLE_ENDIAN,
)
.unwrap();
let rehydrated =
transcode_dcmnorm_object(&encapsulated, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
assert_eq!(
encapsulated.meta().transfer_syntax(),
uids::ENCAPSULATED_UNCOMPRESSED_EXPLICIT_VR_LITTLE_ENDIAN,
);
assert!(encapsulated
.element(tags::PIXEL_DATA)
.unwrap()
.fragments()
.is_some());
assert_core_fields_match(&original, &rehydrated);
assert_eq!(
original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap(),
rehydrated
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap(),
);
}
#[test]
fn reports_jpeg_2000_transfer_syntax_capabilities() {
let support = list_transfer_syntax_support();
let jpeg_2000 = support
.iter()
.find(|entry| entry.uid == JPEG_2000_IMAGE_COMPRESSION_UID)
.unwrap();
assert!(jpeg_2000.can_decode_pixel_data);
assert!(jpeg_2000.can_encode_pixel_data);
assert!(jpeg_2000.can_transcode_to());
let original = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let original_bytes = original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.to_vec();
let encoded = transcode_dcmnorm_object(&original, JPEG_2000_IMAGE_COMPRESSION_UID)
.expect("encoding to JPEG2000 Image Compression should succeed");
assert_eq!(
encoded.meta().transfer_syntax().trim_end_matches('\0'),
JPEG_2000_IMAGE_COMPRESSION_UID
);
let decoded_object = transcode_dcmnorm_object(&encoded, uids::EXPLICIT_VR_LITTLE_ENDIAN)
.expect("decode should succeed");
let decoded_bytes = decoded_object
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.to_vec();
assert_eq!(decoded_bytes.len(), original_bytes.len());
assert_ne!(
decoded_bytes, original_bytes,
"lossy JPEG2000 output should not be byte-identical"
);
let mean_abs_error: f64 = original_bytes
.chunks_exact(2)
.zip(decoded_bytes.chunks_exact(2))
.map(|(a, b)| {
let a = u16::from_le_bytes([a[0], a[1]]) as i32;
let b = u16::from_le_bytes([b[0], b[1]]) as i32;
(a - b).unsigned_abs() as f64
})
.sum::<f64>()
/ (original_bytes.len() / 2) as f64;
assert!(
mean_abs_error < 50.0,
"lossy JPEG2000 mean absolute sample error too high: {mean_abs_error}"
);
}
#[test]
fn jpeg_2000_lossless_only_round_trips_exactly() {
const JPEG_2000_LOSSLESS_ONLY_UID: &str = "1.2.840.10008.1.2.4.90";
let original = read_dicom_file(fixture_path("mr_small.dcm")).unwrap();
let original_bytes = original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.to_vec();
let encoded = transcode_dcmnorm_object(&original, JPEG_2000_LOSSLESS_ONLY_UID)
.expect("encoding to JPEG2000 Lossless Only should succeed");
let decoded_object = transcode_dcmnorm_object(&encoded, uids::EXPLICIT_VR_LITTLE_ENDIAN)
.expect("decode should succeed");
let decoded_bytes = decoded_object
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.to_vec();
assert_eq!(decoded_bytes, original_bytes);
}
#[test]
fn redacts_monochrome_pixels_in_dicom_to_dicom_path() {
let original = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let original_native =
transcode_dcmnorm_object(&original, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
let redacted = redact_dicom_pixels_to_transfer_syntax(
&original,
uids::EXPLICIT_VR_LITTLE_ENDIAN,
&[BoundingBox {
x: 0,
y: 0,
width: BoxLength::Pixels(8),
height: BoxLength::Pixels(8),
}],
[255, 0, 0],
)
.unwrap();
assert_eq!(
redacted.meta().transfer_syntax(),
uids::EXPLICIT_VR_LITTLE_ENDIAN
);
let baseline_inside = mono_sample_value(&original_native, 0, 0).unwrap();
let baseline_outside = mono_sample_value(&original_native, 16, 16).unwrap();
let redacted_inside = mono_sample_value(&redacted, 0, 0).unwrap();
let redacted_outside = mono_sample_value(&redacted, 16, 16).unwrap();
let bits_stored = redacted
.element(tags::BITS_STORED)
.unwrap()
.uint16()
.unwrap();
assert_ne!(baseline_inside, redacted_inside);
assert_eq!(baseline_outside, redacted_outside);
assert_eq!(redacted_inside, scaled_u8_to_bits_stored(54, bits_stored));
}
#[test]
fn redacts_rgb_pixels_when_planar_configuration_is_one() {
let source = read_dicom_file(fixture_path("sc.dcm")).unwrap();
let mut object = transcode_dcmnorm_object(&source, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
let samples = object
.get(tags::SAMPLES_PER_PIXEL)
.and_then(|element| element.uint16().ok())
.unwrap_or(1);
let bits_allocated = object
.get(tags::BITS_ALLOCATED)
.and_then(|element| element.uint16().ok())
.unwrap_or(0);
if samples != 3 || bits_allocated != 8 {
return;
}
let rows = object.element(tags::ROWS).unwrap().uint16().unwrap() as usize;
let cols = object.element(tags::COLUMNS).unwrap().uint16().unwrap() as usize;
let pixel_count = rows * cols;
let interleaved = object
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.into_owned();
if interleaved.len() < pixel_count * 3 {
return;
}
let mut planar = vec![0u8; pixel_count * 3];
for index in 0..pixel_count {
planar[index] = interleaved[index * 3];
planar[index + pixel_count] = interleaved[index * 3 + 1];
planar[index + 2 * pixel_count] = interleaved[index * 3 + 2];
}
object.put(DataElement::new(
tags::PLANAR_CONFIGURATION,
VR::US,
PrimitiveValue::from(1u16),
));
object.put(DataElement::new(
tags::PIXEL_DATA,
VR::OB,
PrimitiveValue::from(planar),
));
let redacted = redact_dicom_pixels_to_transfer_syntax(
&object,
uids::EXPLICIT_VR_LITTLE_ENDIAN,
&[BoundingBox {
x: 0,
y: 0,
width: BoxLength::Pixels(1),
height: BoxLength::Pixels(1),
}],
[12, 34, 56],
)
.unwrap();
let redacted_planar = redacted
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.into_owned();
assert_eq!(
redacted
.element(tags::PLANAR_CONFIGURATION)
.unwrap()
.uint16()
.unwrap(),
1
);
assert_eq!(redacted_planar[0], 12);
assert_eq!(redacted_planar[pixel_count], 34);
assert_eq!(redacted_planar[2 * pixel_count], 56);
}
#[test]
fn detects_kakadu_backend_from_search_path() {
let base = std::env::temp_dir().join(format!(
"dcmnorm-kakadu-detect-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&base).unwrap();
let kakadu_lib = base.join("libkdu_v84R.so");
fs::write(&kakadu_lib, []).unwrap();
let backend = detect_jpeg2000_backend_from_search_path(base.to_string_lossy().as_ref());
if kakadu_ffi_enabled() {
assert!(matches!(backend, Jpeg2000Backend::Kakadu { .. }));
} else {
assert_eq!(backend, Jpeg2000Backend::OpenJpeg);
}
fs::remove_file(kakadu_lib).unwrap();
fs::remove_dir(base).unwrap();
}
#[test]
fn falls_back_to_openjpeg_when_kakadu_not_in_search_path() {
let base = std::env::temp_dir().join(format!(
"dcmnorm-openjpeg-fallback-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&base).unwrap();
let backend = detect_jpeg2000_backend_from_search_path(base.to_string_lossy().as_ref());
if kakadu_ffi_enabled() {
assert!(matches!(backend, Jpeg2000Backend::Kakadu { .. }));
} else {
assert_eq!(backend, Jpeg2000Backend::OpenJpeg);
}
fs::remove_dir(base).unwrap();
}
#[test]
fn renders_dx_frame_to_png() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(&rendered.bytes[..8], b"\x89PNG\r\n\x1a\n");
assert_eq!(
rendered.width,
object.element(tags::COLUMNS).unwrap().uint16().unwrap()
);
assert_eq!(
rendered.height,
object.element(tags::ROWS).unwrap().uint16().unwrap()
);
}
#[test]
fn renders_frame_when_bits_stored_is_missing() {
let mut object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
assert!(remove_attribute(&mut object, tags::BITS_STORED));
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(&rendered.bytes[..8], b"\x89PNG\r\n\x1a\n");
}
#[test]
fn renders_dx_frame_to_jpeg() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Jpeg,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(&rendered.bytes[..2], b"\xFF\xD8");
assert!(rendered.bytes.len() > 100);
}
#[test]
fn renders_first_overlay_by_default() {
let object = read_dicom_file(fixture_path("overlay.dcm")).unwrap();
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(rendered.overlays.len(), 1);
assert_eq!(rendered.overlays[0].index, 0);
assert_eq!(rendered.overlays[0].group, 0x6000);
assert_eq!(rendered.selected_overlay_index, Some(0));
let image = image::load_from_memory(&rendered.bytes).unwrap().to_luma8();
assert_eq!(image.get_pixel(0, 0).0[0], 182);
assert_eq!(image.get_pixel(1, 0).0[0], 0);
}
#[test]
fn overlay_can_be_disabled() {
let object = read_dicom_file(fixture_path("overlay.dcm")).unwrap();
let options = RenderPipelineOptions {
show_overlays: false,
..RenderPipelineOptions::default()
};
let rendered = render_dicom_frame(&object, RenderOutputFormat::Png, &options).unwrap();
assert_eq!(
rendered.overlays.len(),
1,
"overlays should still be reported even when not rendered, so a client can offer to enable them"
);
assert_eq!(rendered.selected_overlay_index, None);
let image = image::load_from_memory(&rendered.bytes).unwrap().to_luma8();
assert_eq!(
image.get_pixel(0, 0).0[0],
0,
"overlay pixel should be untouched when disabled"
);
}
#[test]
fn overlay_color_is_configurable() {
let object = read_dicom_file(fixture_path("overlay.dcm")).unwrap();
let options = RenderPipelineOptions {
overlay_color: [255, 0, 0],
..RenderPipelineOptions::default()
};
let rendered = render_dicom_frame(&object, RenderOutputFormat::Png, &options).unwrap();
let image = image::load_from_memory(&rendered.bytes).unwrap().to_luma8();
assert_eq!(image.get_pixel(0, 0).0[0], 54);
}
#[test]
fn out_of_range_overlay_index_is_rejected() {
let object = read_dicom_file(fixture_path("overlay.dcm")).unwrap();
let options = RenderPipelineOptions {
overlay_index: Some(5),
..RenderPipelineOptions::default()
};
let error = render_dicom_frame(&object, RenderOutputFormat::Png, &options).unwrap_err();
assert!(matches!(
error,
RenderError::InvalidOverlayIndex {
requested: 5,
available: 1
}
));
}
#[test]
fn selects_among_multiple_overlays_by_index() {
let object = read_dicom_file(fixture_path("overlay_multi.dcm")).unwrap();
let default_rendered = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(default_rendered.overlays.len(), 2);
assert_eq!(default_rendered.overlays[0].group, 0x6000);
assert_eq!(
default_rendered.overlays[0].label.as_deref(),
Some("Diagonal")
);
assert_eq!(default_rendered.overlays[1].group, 0x6002);
assert_eq!(
default_rendered.overlays[1].label.as_deref(),
Some("Anti-diagonal")
);
assert_eq!(default_rendered.selected_overlay_index, Some(0));
let second_options = RenderPipelineOptions {
overlay_index: Some(1),
..RenderPipelineOptions::default()
};
let second_rendered =
render_dicom_frame(&object, RenderOutputFormat::Png, &second_options).unwrap();
assert_eq!(second_rendered.selected_overlay_index, Some(1));
let default_image = image::load_from_memory(&default_rendered.bytes)
.unwrap()
.to_luma8();
let second_image = image::load_from_memory(&second_rendered.bytes)
.unwrap()
.to_luma8();
assert_eq!(default_image.get_pixel(0, 0).0[0], 182);
assert_eq!(default_image.get_pixel(7, 0).0[0], 0);
assert_eq!(second_image.get_pixel(0, 0).0[0], 0);
assert_eq!(second_image.get_pixel(7, 0).0[0], 182);
}
#[test]
fn renders_overlay_embedded_in_pixel_data_high_bit() {
let object = read_dicom_file(fixture_path("overlay_embedded.dcm")).unwrap();
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(rendered.overlays.len(), 1);
assert_eq!(rendered.selected_overlay_index, Some(0));
let baseline = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions {
show_overlays: false,
..RenderPipelineOptions::default()
},
)
.unwrap();
let with_overlay = image::load_from_memory(&rendered.bytes).unwrap().to_luma8();
let without_overlay = image::load_from_memory(&baseline.bytes).unwrap().to_luma8();
assert_eq!(with_overlay.get_pixel(0, 0).0[0], 182);
assert_eq!(with_overlay.get_pixel(1, 0).0[0], 0);
assert_ne!(
without_overlay.get_pixel(0, 0).0[0],
182,
"baseline pixel should not already be overlay-colored"
);
}
#[test]
fn renders_dx_frame_to_raw_u8() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Raw,
&RenderPipelineOptions::default(),
)
.unwrap();
let rows = object.element(tags::ROWS).unwrap().uint16().unwrap() as usize;
let cols = object.element(tags::COLUMNS).unwrap().uint16().unwrap() as usize;
let samples = object
.get(tags::SAMPLES_PER_PIXEL)
.and_then(|element| element.uint16().ok())
.unwrap_or(1) as usize;
let bits_allocated = object
.get(tags::BITS_ALLOCATED)
.and_then(|element| element.uint16().ok())
.unwrap_or(8) as usize;
let samples_per_frame = rows * cols * samples;
let expected_len = match bits_allocated {
1 => samples_per_frame.div_ceil(8),
8 => samples_per_frame,
16 => samples_per_frame * 2,
other => panic!("unexpected BitsAllocated value in fixture: {other}"),
};
assert_eq!(rendered.bytes.len(), expected_len);
assert_eq!(rendered.bits_allocated as usize, bits_allocated);
}
#[test]
fn renders_dx_video_frames_as_raw_u8_with_consistent_shape() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let rendered =
render_all_dicom_video_frames(&object, &RenderPipelineOptions::default()).unwrap();
assert!(!rendered.is_empty());
let rows = object.element(tags::ROWS).unwrap().uint16().unwrap();
let cols = object.element(tags::COLUMNS).unwrap().uint16().unwrap();
for frame in &rendered {
assert_eq!(frame.format, RenderOutputFormat::Raw);
assert_eq!(frame.bits_allocated, 8);
assert_eq!(frame.width, cols);
assert_eq!(frame.height, rows);
assert_eq!(frame.samples_per_pixel, 1);
assert_eq!(frame.bytes.len(), usize::from(rows) * usize::from(cols));
}
}
#[test]
fn falls_back_when_window_is_outside_pixel_domain() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let default_rendered = render_dicom_frame(
&object,
RenderOutputFormat::Raw,
&RenderPipelineOptions::default(),
)
.unwrap();
let no_voi_rendered = render_dicom_frame(
&object,
RenderOutputFormat::Raw,
&RenderPipelineOptions {
apply_voi_lut: false,
..RenderPipelineOptions::default()
},
)
.unwrap();
assert_eq!(default_rendered.bytes, no_voi_rendered.bytes);
}
fn shared_functional_groups_sequence_with_rescale_and_window(
rescale_slope: &str,
rescale_intercept: &str,
window_center: &str,
window_width: &str,
) -> DataElement<InMemDicomObject> {
use dcmnorm_core::value::Value as DicomValue;
use dcmnorm_core::Length;
let pixel_value_transformation = InMemDicomObject::from_element_iter([
DataElement::new(
tags::RESCALE_SLOPE,
VR::DS,
PrimitiveValue::from(rescale_slope),
),
DataElement::new(
tags::RESCALE_INTERCEPT,
VR::DS,
PrimitiveValue::from(rescale_intercept),
),
]);
let frame_voi_lut = InMemDicomObject::from_element_iter([
DataElement::new(
tags::WINDOW_CENTER,
VR::DS,
PrimitiveValue::from(window_center),
),
DataElement::new(
tags::WINDOW_WIDTH,
VR::DS,
PrimitiveValue::from(window_width),
),
]);
let shared_group = InMemDicomObject::from_element_iter([
DataElement::new(
tags::PIXEL_VALUE_TRANSFORMATION_SEQUENCE,
VR::SQ,
DicomValue::new_sequence(vec![pixel_value_transformation], Length::UNDEFINED),
),
DataElement::new(
tags::FRAME_VOILUT_SEQUENCE,
VR::SQ,
DicomValue::new_sequence(vec![frame_voi_lut], Length::UNDEFINED),
),
]);
DataElement::new(
tags::SHARED_FUNCTIONAL_GROUPS_SEQUENCE,
VR::SQ,
dcmnorm_core::value::Value::new_sequence(vec![shared_group], Length::UNDEFINED),
)
}
#[test]
fn resolves_rescale_and_window_from_shared_functional_group_when_absent_at_top_level() {
use super::render::{decode_frame_grayscale_values, resolve_default_window};
let mut plain_object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
plain_object.remove_element(tags::RESCALE_SLOPE);
plain_object.remove_element(tags::RESCALE_INTERCEPT);
plain_object.remove_element(tags::WINDOW_CENTER);
plain_object.remove_element(tags::WINDOW_WIDTH);
let (_, raw_values) = decode_frame_grayscale_values(&plain_object, 0).unwrap();
assert_eq!(resolve_default_window(&plain_object, 0), (None, None));
let mut grouped_object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
grouped_object.remove_element(tags::RESCALE_SLOPE);
grouped_object.remove_element(tags::RESCALE_INTERCEPT);
grouped_object.remove_element(tags::WINDOW_CENTER);
grouped_object.remove_element(tags::WINDOW_WIDTH);
grouped_object.put(shared_functional_groups_sequence_with_rescale_and_window(
"2", "-100", "300", "500",
));
let (_, rescaled_values) = decode_frame_grayscale_values(&grouped_object, 0).unwrap();
assert_eq!(raw_values.len(), rescaled_values.len());
for (raw, rescaled) in raw_values.iter().zip(rescaled_values.iter()) {
assert!((rescaled - (raw * 2.0 - 100.0)).abs() < 1e-6);
}
assert_eq!(
resolve_default_window(&grouped_object, 0),
(Some(300.0), Some(500.0))
);
}
#[test]
fn pack_dicom_frame_texture_resolves_default_window_from_shared_functional_group() {
let mut object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
object.remove_element(tags::RESCALE_SLOPE);
object.remove_element(tags::RESCALE_INTERCEPT);
object.remove_element(tags::WINDOW_CENTER);
object.remove_element(tags::WINDOW_WIDTH);
object.put(shared_functional_groups_sequence_with_rescale_and_window(
"2", "-100", "300", "500",
));
let packed =
pack_dicom_frame_texture(&object, 0, None, None, TextureCompression::None).unwrap();
assert_eq!(packed.meta.default_window_center, Some(300.0));
assert_eq!(packed.meta.default_window_width, Some(500.0));
}
#[test]
fn resolve_grayscale_invert_prefers_presentation_lut_shape_over_photometric_interpretation() {
use super::render::resolve_grayscale_invert;
let mut object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
object.put(DataElement::new(
tags::PRESENTATION_LUT_SHAPE,
VR::CS,
PrimitiveValue::from("INVERSE"),
));
assert!(resolve_grayscale_invert(&object, "MONOCHROME2"));
object.put(DataElement::new(
tags::PRESENTATION_LUT_SHAPE,
VR::CS,
PrimitiveValue::from("IDENTITY"),
));
assert!(!resolve_grayscale_invert(&object, "MONOCHROME1"));
object.remove_element(tags::PRESENTATION_LUT_SHAPE);
assert!(resolve_grayscale_invert(&object, "MONOCHROME1"));
assert!(!resolve_grayscale_invert(&object, "MONOCHROME2"));
}
#[test]
fn render_dicom_frame_honors_presentation_lut_shape_override_when_it_disagrees_with_photometric_interpretation(
) {
let decode_luma = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_luma8();
let mut baseline = read_dicom_file(fixture_path("dx.dcm")).unwrap();
baseline.put(DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from("MONOCHROME2"),
));
let baseline_rendered = render_dicom_frame(
&baseline,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
let baseline_luma = decode_luma(&baseline_rendered.bytes);
let mut overridden = baseline.clone();
overridden.put(DataElement::new(
tags::PRESENTATION_LUT_SHAPE,
VR::CS,
PrimitiveValue::from("INVERSE"),
));
let overridden_rendered = render_dicom_frame(
&overridden,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
let overridden_luma = decode_luma(&overridden_rendered.bytes);
for (baseline_pixel, overridden_pixel) in baseline_luma.pixels().zip(overridden_luma.pixels()) {
assert_eq!(overridden_pixel.0[0], 255u8 - baseline_pixel.0[0]);
}
}
#[test]
fn pack_dicom_frame_texture_resolves_invert_from_presentation_lut_shape_override() {
let mut object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
object.put(DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from("MONOCHROME2"),
));
object.put(DataElement::new(
tags::PRESENTATION_LUT_SHAPE,
VR::CS,
PrimitiveValue::from("INVERSE"),
));
let packed =
pack_dicom_frame_texture(&object, 0, None, None, TextureCompression::None).unwrap();
assert!(packed.meta.invert);
}
#[test]
fn ignores_invalid_window_width_from_dataset() {
let mut object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
object.put(DataElement::new(
tags::WINDOW_CENTER,
VR::DS,
PrimitiveValue::from("40"),
));
object.put(DataElement::new(
tags::WINDOW_WIDTH,
VR::DS,
PrimitiveValue::from("0"),
));
let default_rendered = render_dicom_frame(
&object,
RenderOutputFormat::Raw,
&RenderPipelineOptions::default(),
)
.unwrap();
let no_voi_rendered = render_dicom_frame(
&object,
RenderOutputFormat::Raw,
&RenderPipelineOptions {
apply_voi_lut: false,
..RenderPipelineOptions::default()
},
)
.unwrap();
assert_eq!(default_rendered.bytes, no_voi_rendered.bytes);
}
#[test]
fn rejects_invalid_user_provided_window_width() {
let object = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let error = render_dicom_frame(
&object,
RenderOutputFormat::Raw,
&RenderPipelineOptions {
window_center: Some(40.0),
window_width: Some(0.0),
..RenderPipelineOptions::default()
},
)
.unwrap_err()
.to_string();
assert!(error.contains("window width must be greater than zero"));
}
#[test]
fn renders_rgb_fixture_when_present() {
let object = read_dicom_file(fixture_path("sc.dcm")).unwrap();
let samples = object
.get(tags::SAMPLES_PER_PIXEL)
.and_then(|element| element.uint16().ok())
.unwrap_or(1);
if samples != 3 {
return;
}
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(rendered.samples_per_pixel, 3);
assert_eq!(&rendered.bytes[..8], b"\x89PNG\r\n\x1a\n");
}
#[test]
fn renders_single_frame_with_stale_ybr_rct_after_decode() {
let source = read_dicom_file(fixture_path("sc.dcm")).unwrap();
let mut object = transcode_dcmnorm_object(
&source,
uids::ENCAPSULATED_UNCOMPRESSED_EXPLICIT_VR_LITTLE_ENDIAN,
)
.unwrap();
let samples = object
.get(tags::SAMPLES_PER_PIXEL)
.and_then(|element| element.uint16().ok())
.unwrap_or(1);
if samples != 3 {
return;
}
object.put(DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from("YBR_RCT"),
));
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Jpeg,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(&rendered.bytes[..2], b"\xFF\xD8");
}
#[test]
fn renders_jpeg_baseline_frame_mislabeled_ybr_full_422_without_pink_cast() {
let Some(path) = optional_fixture_path("wsi.dcm") else {
return;
};
let source = read_dicom_file(&path).unwrap();
assert_eq!(
source
.meta()
.transfer_syntax()
.trim_end_matches(['\0', ' ']),
"1.2.840.10008.1.2.4.50",
"fixture must be JPEG baseline to exercise the single-frame decode path"
);
let reference = render_dicom_frame(
&source,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
let reference_pixel = *image::load_from_memory(&reference.bytes)
.unwrap()
.to_rgb8()
.get_pixel(0, 0);
let mut mislabeled = source.clone();
mislabeled.put(DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from("YBR_FULL_422"),
));
let mislabeled_rendered = render_dicom_frame(
&mislabeled,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
let mislabeled_pixel = *image::load_from_memory(&mislabeled_rendered.bytes)
.unwrap()
.to_rgb8()
.get_pixel(0, 0);
for channel in 0..3 {
let diff =
(i16::from(reference_pixel[channel]) - i16::from(mislabeled_pixel[channel])).abs();
assert!(
diff <= 4,
"channel {} diverged after YBR_FULL_422 mislabel: reference={:?} mislabeled={:?}",
channel,
reference_pixel,
mislabeled_pixel,
);
}
}
#[test]
fn renders_wsi_fixture_without_green_seam() {
let Some(path) = optional_fixture_path("wsi.dcm") else {
return;
};
assert_rendered_wsi_has_no_green_seam(&path);
}
#[test]
fn renders_ybr_wsi_fixture_without_green_seam() {
let Some(path) = optional_fixture_path("wsi_ybr.dcm") else {
return;
};
assert_rendered_wsi_has_no_green_seam(&path);
}
fn assert_rendered_wsi_has_no_green_seam(path: &Path) {
let source = read_dicom_file(path).unwrap();
let rendered = render_dicom_frame(
&source,
RenderOutputFormat::Jpeg,
&RenderPipelineOptions::default(),
)
.unwrap();
let image = image::load_from_memory(&rendered.bytes).unwrap().to_rgb8();
let mid_row = usize::from(rendered.height) / 2;
assert!(mid_row > 0, "rendered image height must be > 1");
let upper = average_row_rgb(&image, mid_row - 1);
let lower = average_row_rgb(&image, mid_row);
let lower_green_dominance = lower.1 - lower.0.max(lower.2);
assert!(
lower_green_dominance < 80.0,
"unexpected green-dominant seam in {} at row {}: upper={:?} lower={:?}",
path.display(),
mid_row,
upper,
lower,
);
let seam_delta = (upper.0 - lower.0)
.abs()
.max((upper.1 - lower.1).abs())
.max((upper.2 - lower.2).abs());
assert!(
seam_delta < 120.0,
"unexpected hard color seam in {} at row {}: upper={:?} lower={:?}",
path.display(),
mid_row,
upper,
lower,
);
}
fn average_row_rgb(image: &image::RgbImage, row: usize) -> (f64, f64, f64) {
let y = u32::try_from(row).expect("row index must fit u32");
let width = image.width();
let mut red = 0u64;
let mut green = 0u64;
let mut blue = 0u64;
for x in 0..width {
let pixel = image.get_pixel(x, y).0;
red += u64::from(pixel[0]);
green += u64::from(pixel[1]);
blue += u64::from(pixel[2]);
}
let count = f64::from(width.max(1));
(
red as f64 / count,
green as f64 / count,
blue as f64 / count,
)
}
fn fixture_bytes(path: impl AsRef<Path>) -> Vec<u8> {
fs::read(path).unwrap()
}
fn optional_fixture_path(name: &str) -> Option<PathBuf> {
let path = fixture_path(name);
path.exists().then_some(path)
}
fn optional_repo_fixture_path(name: &str) -> Option<PathBuf> {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(name);
path.exists().then_some(path)
}
fn fixture_path(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("test/files")
.join(name)
}
fn repo_root_path(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("test/files")
.join(name)
}
fn assert_core_fields_match(
expected: &dcmnorm_object::DefaultDicomObject,
actual: &dcmnorm_object::DefaultDicomObject,
) {
assert_eq!(
expected.meta().transfer_syntax(),
actual.meta().transfer_syntax()
);
assert_dataset_fields_match(expected, actual);
}
fn assert_dataset_fields_match(
expected: &dcmnorm_object::DefaultDicomObject,
actual: &dcmnorm_object::DefaultDicomObject,
) {
assert_eq!(
expected
.element(tags::SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap(),
actual
.element(tags::SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap(),
);
assert_eq!(
expected
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
actual
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
);
assert_eq!(
expected.element(tags::MODALITY).unwrap().to_str().unwrap(),
actual.element(tags::MODALITY).unwrap().to_str().unwrap(),
);
assert_eq!(
expected.element(tags::ROWS).unwrap().uint16().unwrap(),
actual.element(tags::ROWS).unwrap().uint16().unwrap(),
);
assert_eq!(
expected.element(tags::COLUMNS).unwrap().uint16().unwrap(),
actual.element(tags::COLUMNS).unwrap().uint16().unwrap(),
);
}
fn temp_file_path(prefix: &str) -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
std::env::temp_dir().join(format!("{prefix}-{nanos}.dcm"))
}
fn mono_sample_value(
object: &dcmnorm_object::DefaultDicomObject,
x: usize,
y: usize,
) -> Option<u16> {
let cols = object.element(tags::COLUMNS).ok()?.uint16().ok()? as usize;
let rows = object.element(tags::ROWS).ok()?.uint16().ok()? as usize;
if x >= cols || y >= rows {
return None;
}
let bits_allocated = object.element(tags::BITS_ALLOCATED).ok()?.uint16().ok()?;
let bits_stored = object.element(tags::BITS_STORED).ok()?.uint16().ok()?;
let bytes = object
.element(tags::PIXEL_DATA)
.ok()?
.to_bytes()
.ok()?
.into_owned();
let index = y * cols + x;
match bits_allocated {
1 => {
let byte = *bytes.get(index / 8)?;
let bit = 7 - (index % 8);
Some(u16::from((byte >> bit) & 1))
}
8 => {
let raw = u16::from(*bytes.get(index)?);
let mask = if bits_stored >= 8 {
0xFF
} else {
(1u16 << bits_stored).saturating_sub(1)
};
Some(raw & mask.max(1))
}
16 => {
let base = index * 2;
let low = *bytes.get(base)?;
let high = *bytes.get(base + 1)?;
let raw = u16::from_le_bytes([low, high]);
let mask = if bits_stored >= 16 {
0xFFFF
} else {
(1u16 << bits_stored).saturating_sub(1)
};
Some(raw & mask.max(1))
}
_ => None,
}
}
fn scaled_u8_to_bits_stored(value: u8, bits_stored: u16) -> u16 {
let bits = bits_stored.clamp(1, 16);
let max_value = (1u32 << u32::from(bits)) - 1;
((u32::from(value) * max_value + 127) / 255) as u16
}
fn dimse_implicit_vr_le() -> &'static dcmnorm_encoding::TransferSyntax {
use dcmnorm_encoding::TransferSyntaxIndex;
dcmnorm_transcode::TransferSyntaxRegistry
.get(uids::IMPLICIT_VR_LITTLE_ENDIAN)
.unwrap()
}
fn spawn_mock_scp(
abstract_syntax: impl Into<String>,
handler: impl FnOnce(&mut dcmnorm_dimse::ServerAssociation<std::net::TcpStream>) + Send + 'static,
) -> (std::thread::JoinHandle<()>, std::net::SocketAddr) {
let abstract_syntax = abstract_syntax.into();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(abstract_syntax);
let handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
handler(&mut association);
let pdu = association.receive().unwrap();
assert_eq!(pdu, dcmnorm_dimse::pdu::Pdu::ReleaseRQ);
association
.send(&dcmnorm_dimse::pdu::Pdu::ReleaseRP)
.unwrap();
});
(handle, addr)
}
fn dimse_recv_command(
association: &mut dcmnorm_dimse::ServerAssociation<std::net::TcpStream>,
) -> InMemDicomObject {
match association.receive().unwrap() {
dcmnorm_dimse::pdu::Pdu::PData { data } => {
InMemDicomObject::read_dataset_with_ts(data[0].data.as_slice(), dimse_implicit_vr_le())
.unwrap()
}
other => panic!("expected a Command P-Data PDU, got {other:?}"),
}
}
fn dimse_send_command(
association: &mut dcmnorm_dimse::ServerAssociation<std::net::TcpStream>,
pc_id: u8,
command: &InMemDicomObject,
) {
let mut data = Vec::new();
command
.write_dataset_with_ts(&mut data, dimse_implicit_vr_le())
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Command,
is_last: true,
data,
}],
})
.unwrap();
}
fn dimse_message_id(command: &InMemDicomObject) -> u16 {
command.element(tags::MESSAGE_ID).unwrap().to_int().unwrap()
}
#[test]
fn echo_scu_round_trips_success_status() {
let (scp_handle, addr) = spawn_mock_scp(uids::VERIFICATION, |association| {
let request = dimse_recv_command(association);
let message_id = dimse_message_id(&request);
let pc_id = association.presentation_contexts()[0].id;
let response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, uids::VERIFICATION),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8030])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(association, pc_id, &response);
});
let status = echo_scu(
&addr.to_string(),
EchoScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(status, 0);
scp_handle.join().unwrap();
}
#[test]
fn echo_scu_returns_cancelled_error_when_signalled_mid_wait() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(uids::VERIFICATION);
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let _ = dimse_recv_command(&mut association);
std::thread::sleep(std::time::Duration::from_secs(2));
});
let cancel = CancelSignal::new();
let cancel_setter = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(50));
cancel_setter.request(CancelMode::Release);
});
let started = std::time::Instant::now();
let result = echo_scu(
&addr.to_string(),
EchoScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
timeout: None,
on_log: None,
cancel: Some(cancel),
},
);
assert!(
matches!(result, Err(DimseError::Cancelled(CancelMode::Release))),
"expected Cancelled, got {result:?}"
);
assert!(
started.elapsed() < std::time::Duration::from_millis(900),
"cancel took too long to be noticed: {:?}",
started.elapsed()
);
scp_handle.join().unwrap();
}
fn dimse_recv_command_with_data(
association: &mut dcmnorm_dimse::ServerAssociation<std::net::TcpStream>,
) -> (u8, InMemDicomObject, Vec<u8>) {
match association.receive_command().unwrap() {
dcmnorm_dimse::Incoming::Command {
presentation_context_id,
data,
} => {
let command =
InMemDicomObject::read_dataset_with_ts(data.as_slice(), dimse_implicit_vr_le())
.unwrap();
(
presentation_context_id,
command,
association.receive_data_set().unwrap(),
)
}
other => panic!("expected a Command, got {other:?}"),
}
}
#[test]
fn store_scu_round_trips_status_per_file() {
let source = fixture_path("sr.dcm");
let object = read_dicom_file(&source).unwrap();
let sop_class_uid = object
.meta()
.media_storage_sop_class_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let sop_instance_uid = object
.meta()
.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let expected_sop_class_uid = sop_class_uid.clone();
let (scp_handle, addr) = spawn_mock_scp(sop_class_uid, move |association| {
let (pc_id, request, dataset_bytes) = dimse_recv_command_with_data(association);
assert!(!dataset_bytes.is_empty());
assert_eq!(
request
.element(tags::AFFECTED_SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap(),
expected_sop_class_uid,
);
let message_id = dimse_message_id(&request);
let response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, expected_sop_class_uid.clone()),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8001])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(association, pc_id, &response);
});
let results = store_scu(
&addr.to_string(),
&[source],
StoreScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].status, 0);
assert_eq!(results[0].sop_instance_uid, sop_instance_uid);
scp_handle.join().unwrap();
}
#[test]
fn store_scu_streams_data_for_large_files() {
let source = fixture_path("dx.dcm");
let object = read_dicom_file(&source).unwrap();
let sop_class_uid = object
.element(tags::SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned();
let sop_instance_uid = object
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned();
let expected_sop_class_uid = sop_class_uid.clone();
let (scp_handle, addr) = spawn_mock_scp(sop_class_uid, move |association| {
let (pc_id, request, dataset_bytes) = dimse_recv_command_with_data(association);
assert!(
dataset_bytes.len() > 16384,
"expected a large streamed dataset, got {} bytes",
dataset_bytes.len()
);
assert_eq!(
request
.element(tags::AFFECTED_SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap(),
expected_sop_class_uid,
);
let message_id = dimse_message_id(&request);
let response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, expected_sop_class_uid.clone()),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8001])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(association, pc_id, &response);
});
let results = store_scu(
&addr.to_string(),
&[source],
StoreScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].status, 0);
assert_eq!(results[0].sop_instance_uid, sop_instance_uid);
scp_handle.join().unwrap();
}
#[test]
fn store_scu_avoids_transcoding_into_a_decode_only_transfer_syntax_shared_by_sop_class() {
let path_a = fixture_path("dx2.dcm");
let path_b = fixture_path("dx.dcm");
let object_a = read_dicom_file(&path_a).unwrap();
let object_b = read_dicom_file(&path_b).unwrap();
let sop_class_uid = object_a
.element(tags::SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned();
let sop_instance_a = object_a
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned();
let sop_instance_b = object_b
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned();
assert_eq!(
object_b
.meta()
.media_storage_sop_class_uid
.trim_end_matches(['\0', ' ']),
sop_class_uid,
"fixtures must share a SOP class for this test to be meaningful"
);
assert_eq!(
object_a
.meta()
.transfer_syntax
.trim_end_matches(['\0', ' ']),
"1.2.840.10008.1.2.4.90"
);
assert_eq!(
object_b
.meta()
.transfer_syntax
.trim_end_matches(['\0', ' ']),
uids::EXPLICIT_VR_LITTLE_ENDIAN
);
let expected_sop_class_uid = sop_class_uid.clone();
let (scp_handle, addr) = spawn_mock_scp(sop_class_uid, move |association| {
for _ in 0..2 {
let (pc_id, request, dataset_bytes) = dimse_recv_command_with_data(association);
assert!(!dataset_bytes.is_empty());
assert_eq!(
request
.element(tags::AFFECTED_SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap(),
expected_sop_class_uid,
);
let message_id = dimse_message_id(&request);
let response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, expected_sop_class_uid.clone()),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8001])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(association, pc_id, &response);
}
});
let results = store_scu(
&addr.to_string(),
&[path_a.clone(), path_b.clone()],
StoreScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: false,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 2);
assert!(
results.iter().all(|result| result.status == 0),
"expected both sends to succeed: {results:?}"
);
assert_eq!(results[0].sop_instance_uid, sop_instance_a);
assert_eq!(results[1].sop_instance_uid, sop_instance_b);
scp_handle.join().unwrap();
}
#[test]
fn store_scu_transcodes_into_fallback_context_when_peer_rejects_native_transfer_syntax() {
let source = fixture_path("dx2.dcm");
let object = read_dicom_file(&source).unwrap();
let sop_class_uid = object
.element(tags::SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned();
let sop_instance_uid = object
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned();
assert_eq!(
object.meta().transfer_syntax.trim_end_matches(['\0', ' ']),
"1.2.840.10008.1.2.4.90"
);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let expected_sop_class_uid = sop_class_uid.clone();
let scp_handle = std::thread::spawn(move || {
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(expected_sop_class_uid.clone())
.with_transfer_syntax(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.with_transfer_syntax(uids::IMPLICIT_VR_LITTLE_ENDIAN);
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let (pc_id, request, dataset_bytes) = dimse_recv_command_with_data(&mut association);
assert!(!dataset_bytes.is_empty());
assert_eq!(
request
.element(tags::AFFECTED_SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap(),
expected_sop_class_uid,
);
let message_id = dimse_message_id(&request);
let response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, expected_sop_class_uid.clone()),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8001])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(&mut association, pc_id, &response);
let pdu = association.receive().unwrap();
assert_eq!(pdu, dcmnorm_dimse::pdu::Pdu::ReleaseRQ);
association
.send(&dcmnorm_dimse::pdu::Pdu::ReleaseRP)
.unwrap();
});
let results = store_scu(
&addr.to_string(),
&[source],
StoreScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: false,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].status, 0);
assert_eq!(results[0].sop_instance_uid, sop_instance_uid);
scp_handle.join().unwrap();
}
#[test]
fn find_scu_collects_pending_matches_until_success_status() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let (scp_handle, addr) = spawn_mock_scp(abstract_syntax, move |association| {
let pc = association.presentation_contexts()[0].clone();
let ts = {
use dcmnorm_encoding::TransferSyntaxIndex;
dcmnorm_transcode::TransferSyntaxRegistry
.get(&pc.transfer_syntax)
.unwrap()
};
let (_pc_id, request, identifier_bytes) = dimse_recv_command_with_data(association);
let message_id = dimse_message_id(&request);
let query =
InMemDicomObject::read_dataset_with_ts(identifier_bytes.as_slice(), ts).unwrap();
assert_eq!(
query
.element(tags::QUERY_RETRIEVE_LEVEL)
.unwrap()
.to_str()
.unwrap(),
"STUDY"
);
assert_eq!(
query.element(tags::PATIENT_ID).unwrap().to_str().unwrap(),
"MRN123"
);
let pending_command = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8020])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0001]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0xFF00])),
]);
dimse_send_command(association, pc.id, &pending_command);
let matched = InMemDicomObject::from_element_iter([
DataElement::new(
tags::STUDY_INSTANCE_UID,
VR::UI,
dicom_value!(Str, "1.2.3.4.5"),
),
DataElement::new(tags::PATIENT_NAME, VR::PN, dicom_value!(Str, "DOE^JANE")),
]);
let mut matched_bytes = Vec::new();
matched
.write_dataset_with_ts(&mut matched_bytes, ts)
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc.id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Data,
is_last: true,
data: matched_bytes,
}],
})
.unwrap();
let final_command = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8020])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(association, pc.id, &final_command);
});
let mut query = std::collections::HashMap::new();
query.insert("PatientID".to_owned(), "MRN123".to_owned());
let matches = find_scu(
&addr.to_string(),
&query,
FindScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(matches.len(), 1);
let value: serde_json::Value = serde_json::from_str(&matches[0]).unwrap();
assert_eq!(value["0020000D"], "1.2.3.4.5");
assert_eq!(value["00100010"], "DOE^JANE");
scp_handle.join().unwrap();
}
#[test]
fn move_scu_collects_suboperation_progress_until_terminal_status() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let (scp_handle, addr) = spawn_mock_scp(abstract_syntax, move |association| {
let (pc_id, request, _identifier_bytes) = dimse_recv_command_with_data(association);
let message_id = dimse_message_id(&request);
assert_eq!(
request
.element(tags::MOVE_DESTINATION)
.unwrap()
.to_str()
.unwrap(),
"MOVE-DEST",
);
let pending = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0xFF00])),
DataElement::new(
tags::NUMBER_OF_REMAINING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [1]),
),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]);
dimse_send_command(association, pc_id, &pending);
let final_response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::NUMBER_OF_REMAINING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [1]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]);
dimse_send_command(association, pc_id, &final_response);
});
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: None,
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: None,
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
)
.unwrap();
assert_eq!(result.status, 0);
assert_eq!(result.completed, 1);
assert_eq!(result.failed, 0);
assert_eq!(result.warning, 0);
assert_eq!(result.remaining, 0);
scp_handle.join().unwrap();
}
#[test]
fn move_scu_drains_failed_sop_instance_uid_list_sent_as_separate_pdu() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let (scp_handle, addr) = spawn_mock_scp(abstract_syntax, move |association| {
let (pc_id, request, _identifier_bytes) = dimse_recv_command_with_data(association);
let message_id = dimse_message_id(&request);
let final_response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0001]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0xA702])),
DataElement::new(
tags::NUMBER_OF_REMAINING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [1]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]);
dimse_send_command(association, pc_id, &final_response);
let identifier = InMemDicomObject::from_element_iter([DataElement::new(
tags::FAILED_SOP_INSTANCE_UID_LIST,
VR::UI,
dicom_value!(Str, "1.2.3.4.5.6"),
)]);
let mut identifier_bytes = Vec::new();
identifier
.write_dataset_with_ts(&mut identifier_bytes, dimse_implicit_vr_le())
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Data,
is_last: true,
data: identifier_bytes,
}],
})
.unwrap();
});
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: None,
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: None,
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
)
.unwrap();
assert_eq!(result.status, 0xA702);
assert_eq!(result.failed, 1);
scp_handle.join().unwrap();
}
#[test]
fn move_scu_still_returns_the_terminal_result_when_the_peer_does_not_send_release_rp() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(abstract_syntax);
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let (pc_id, request, _identifier_bytes) = dimse_recv_command_with_data(&mut association);
let message_id = dimse_message_id(&request);
let final_response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [1]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]);
dimse_send_command(&mut association, pc_id, &final_response);
let pdu = association.receive().unwrap();
assert_eq!(pdu, dcmnorm_dimse::pdu::Pdu::ReleaseRQ);
let _ = association.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Data,
is_last: true,
data: vec![0u8; 4],
}],
});
});
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: Some(std::time::Duration::from_secs(5)),
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: None,
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
);
let result = result
.expect("a release-phase failure must not turn an already-successful move into an Err");
assert_eq!(result.status, 0x0000);
assert_eq!(result.completed, 1);
scp_handle.join().unwrap();
}
#[test]
fn move_scu_aborts_on_absolute_timeout_despite_continued_pending_responses() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(abstract_syntax);
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let (pc_id, request, _identifier_bytes) = dimse_recv_command_with_data(&mut association);
let message_id = dimse_message_id(&request);
for _ in 0..20 {
let pending = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0xFF00])),
DataElement::new(
tags::NUMBER_OF_REMAINING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [1]),
),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]);
if association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Command,
is_last: true,
data: {
let mut buf = Vec::new();
pending
.write_dataset_with_ts(&mut buf, dimse_implicit_vr_le())
.unwrap();
buf
},
}],
})
.is_err()
{
break;
}
std::thread::sleep(std::time::Duration::from_millis(40));
}
});
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: Some(std::time::Duration::from_millis(200)),
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: None,
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
);
assert!(
matches!(result, Err(DimseError::AbsoluteTimeout)),
"expected AbsoluteTimeout, got {result:?}"
);
scp_handle.join().unwrap();
}
#[test]
fn move_scu_aborts_when_stale_data_path_receives_no_new_files() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(abstract_syntax);
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let (pc_id, request, _identifier_bytes) = dimse_recv_command_with_data(&mut association);
let message_id = dimse_message_id(&request);
for _ in 0..20 {
let pending = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0xFF00])),
DataElement::new(
tags::NUMBER_OF_REMAINING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [1]),
),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]);
if association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Command,
is_last: true,
data: {
let mut buf = Vec::new();
pending
.write_dataset_with_ts(&mut buf, dimse_implicit_vr_le())
.unwrap();
buf
},
}],
})
.is_err()
{
break;
}
std::thread::sleep(std::time::Duration::from_millis(40));
}
});
let watch_dir = std::env::temp_dir().join(format!(
"dcmnorm-stale-data-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&watch_dir).unwrap();
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: None,
stale_data_path: Some(watch_dir.clone()),
stale_data_timeout: Some(std::time::Duration::from_millis(200)),
on_log: None,
cancel: None,
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
);
match &result {
Err(DimseError::StaleDataConnection { path }) => assert_eq!(path, &watch_dir),
other => panic!("expected StaleDataConnection, got {other:?}"),
}
scp_handle.join().unwrap();
fs::remove_dir_all(&watch_dir).ok();
}
#[test]
fn move_scu_returns_cancelled_result_when_signalled_mid_wait() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let cancel = CancelSignal::new();
let cancel_setter = cancel.clone();
let (scp_handle, addr) = spawn_mock_scp(abstract_syntax, move |association| {
let (pc_id, request, _identifier_bytes) = dimse_recv_command_with_data(association);
let message_id = dimse_message_id(&request);
let send_pending =
|association: &mut dcmnorm_dimse::ServerAssociation<std::net::TcpStream>| {
let pending = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0xFF00])),
DataElement::new(
tags::NUMBER_OF_REMAINING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [1]),
),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]);
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Command,
is_last: true,
data: {
let mut buf = Vec::new();
pending
.write_dataset_with_ts(&mut buf, dimse_implicit_vr_le())
.unwrap();
buf
},
}],
})
.unwrap();
};
send_pending(association);
std::thread::sleep(std::time::Duration::from_millis(40));
cancel_setter.request(CancelMode::Release);
send_pending(association);
});
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: None,
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: Some(cancel),
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
)
.unwrap();
assert!(
result.cancelled,
"expected a cancelled result, got {result:?}"
);
assert_eq!(result.cancelled_via, Some(CancelMode::Release));
assert_eq!(result.status, 0);
assert_eq!(result.remaining, 1);
assert_eq!(result.completed, 0);
scp_handle.join().unwrap();
}
#[test]
fn move_scu_hard_aborts_immediately_when_cancel_mode_is_abort() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(abstract_syntax);
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let _ = dimse_recv_command_with_data(&mut association);
let pdu = association.receive().unwrap();
assert!(
matches!(pdu, dcmnorm_dimse::pdu::Pdu::AbortRQ { .. }),
"expected AbortRQ, got {pdu:?}"
);
});
let cancel = CancelSignal::new();
let cancel_setter = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(50));
cancel_setter.request(CancelMode::Abort);
});
let started = std::time::Instant::now();
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: None,
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: Some(cancel),
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
)
.unwrap();
assert!(
result.cancelled,
"expected a cancelled result, got {result:?}"
);
assert_eq!(result.cancelled_via, Some(CancelMode::Abort));
assert!(
started.elapsed() < std::time::Duration::from_millis(900),
"abort took too long to be noticed: {:?}",
started.elapsed()
);
scp_handle.join().unwrap();
}
#[test]
fn find_scu_aborts_on_absolute_timeout_when_peer_never_responds() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(abstract_syntax);
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let _ = dimse_recv_command_with_data(&mut association);
std::thread::sleep(std::time::Duration::from_millis(500));
});
let mut query = std::collections::HashMap::new();
query.insert("PatientID".to_owned(), "MRN123".to_owned());
let result = find_scu(
&addr.to_string(),
&query,
FindScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: Some(std::time::Duration::from_millis(200)),
on_log: None,
cancel: None,
},
);
assert!(
matches!(result, Err(DimseError::AbsoluteTimeout)),
"expected AbsoluteTimeout, got {result:?}"
);
scp_handle.join().unwrap();
}
#[test]
fn find_scu_returns_cancelled_error_when_signalled_mid_wait() {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(abstract_syntax);
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let _ = dimse_recv_command_with_data(&mut association);
std::thread::sleep(std::time::Duration::from_secs(2));
});
let cancel = CancelSignal::new();
let cancel_setter = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(50));
cancel_setter.request(CancelMode::Release);
});
let mut query = std::collections::HashMap::new();
query.insert("PatientID".to_owned(), "MRN123".to_owned());
let started = std::time::Instant::now();
let result = find_scu(
&addr.to_string(),
&query,
FindScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: None,
on_log: None,
cancel: Some(cancel),
},
);
assert!(
matches!(result, Err(DimseError::Cancelled(CancelMode::Release))),
"expected Cancelled, got {result:?}"
);
assert!(
started.elapsed() < std::time::Duration::from_millis(900),
"cancel took too long to be noticed: {:?}",
started.elapsed()
);
scp_handle.join().unwrap();
}
#[test]
fn store_scu_aborts_on_absolute_timeout_when_peer_never_responds() {
let source = fixture_path("sr.dcm");
let object = read_dicom_file(&source).unwrap();
let sop_class_uid = object
.meta()
.media_storage_sop_class_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(sop_class_uid.clone());
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let _ = dimse_recv_command_with_data(&mut association);
std::thread::sleep(std::time::Duration::from_millis(500));
});
let result = store_scu(
&addr.to_string(),
&[source],
StoreScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: Some(std::time::Duration::from_millis(200)),
on_log: None,
cancel: None,
},
);
assert!(
matches!(result, Err(DimseError::AbsoluteTimeout)),
"expected AbsoluteTimeout, got {result:?}"
);
scp_handle.join().unwrap();
}
#[test]
fn store_scu_returns_cancelled_error_when_signalled_mid_wait() {
let source = fixture_path("sr.dcm");
let object = read_dicom_file(&source).unwrap();
let sop_class_uid = object
.meta()
.media_storage_sop_class_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("MOCK-SCP")
.with_abstract_syntax(sop_class_uid.clone());
let scp_handle = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let _ = dimse_recv_command_with_data(&mut association);
std::thread::sleep(std::time::Duration::from_secs(2));
});
let cancel = CancelSignal::new();
let cancel_setter = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(50));
cancel_setter.request(CancelMode::Release);
});
let started = std::time::Instant::now();
let result = store_scu(
&addr.to_string(),
&[source],
StoreScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: Some(cancel),
},
);
assert!(
matches!(result, Err(DimseError::Cancelled(CancelMode::Release))),
"expected Cancelled, got {result:?}"
);
assert!(
started.elapsed() < std::time::Duration::from_millis(900),
"cancel took too long to be noticed: {:?}",
started.elapsed()
);
scp_handle.join().unwrap();
}
struct TestScpHandlers {
find_query: std::sync::Mutex<Option<std::collections::HashMap<String, String>>>,
find_response: Vec<std::collections::HashMap<String, String>>,
move_calls: std::sync::Mutex<Vec<(String, String)>>,
move_result: bool,
association_complete: std::sync::Mutex<Option<std::collections::HashMap<String, Vec<String>>>>,
}
impl ScpHandlers for TestScpHandlers {
fn on_find(
&self,
filter: &std::collections::HashMap<String, String>,
) -> Result<Vec<std::collections::HashMap<String, String>>, String> {
*self.find_query.lock().unwrap() = Some(filter.clone());
Ok(self.find_response.clone())
}
fn on_move(&self, study_instance_uid: &str, move_destination_ae: &str) -> Result<bool, String> {
self.move_calls.lock().unwrap().push((
study_instance_uid.to_owned(),
move_destination_ae.to_owned(),
));
Ok(self.move_result)
}
fn on_association_complete(
&self,
stored_instances_by_study: &std::collections::HashMap<String, Vec<String>>,
) {
*self.association_complete.lock().unwrap() = Some(stored_instances_by_study.clone());
}
}
fn wait_for<T: Clone>(mut poll: impl FnMut() -> Option<T>) -> T {
for _ in 0..200 {
if let Some(value) = poll() {
return value;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
panic!("timed out waiting for condition");
}
#[test]
fn scp_round_trips_echo_store_find_move_against_the_scu_functions() {
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let mut find_match = std::collections::HashMap::new();
find_match.insert("StudyInstanceUID".to_owned(), "1.2.3.4.5".to_owned());
find_match.insert("PatientName".to_owned(), "DOE^JANE".to_owned());
let handlers = std::sync::Arc::new(TestScpHandlers {
find_query: std::sync::Mutex::new(None),
find_response: vec![find_match],
move_calls: std::sync::Mutex::new(Vec::new()),
move_result: true,
association_complete: std::sync::Mutex::new(None),
});
let scp = start_scp(
0,
cache_dir.clone(),
handlers.clone(),
ScpOptions {
ae_title: "TEST-SCP".to_owned(),
..Default::default()
},
)
.unwrap();
let destination = format!("127.0.0.1:{}", scp.local_port());
let status = echo_scu(
&destination,
EchoScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(status, 0);
let source = fixture_path("sr.dcm");
let object = read_dicom_file(&source).unwrap();
let sop_instance_uid = object
.meta()
.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let study_instance_uid = object
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
let modality = object
.element(tags::MODALITY)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
let results = store_scu(
&destination,
&[source],
StoreScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].status, 0);
assert_eq!(results[0].sop_instance_uid, sop_instance_uid);
let expected_path = cache_dir
.join(format!("S_{study_instance_uid}"))
.join(format!("{modality}_{sop_instance_uid}.dcm"));
assert!(
expected_path.exists(),
"expected stored file at {expected_path:?}"
);
let stored_object = read_dicom_file(&expected_path).unwrap();
assert_eq!(
stored_object
.meta()
.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' ']),
sop_instance_uid
);
let mut query = std::collections::HashMap::new();
query.insert("PatientID".to_owned(), "MRN123".to_owned());
let matches = find_scu(
&destination,
&query,
FindScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
max_pdu_length: 16384,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(matches.len(), 1);
let match_value: serde_json::Value = serde_json::from_str(&matches[0]).unwrap();
assert_eq!(match_value["0020000D"], "1.2.3.4.5");
let seen_query = handlers.find_query.lock().unwrap().clone().unwrap();
assert_eq!(
seen_query.get("PatientID").map(String::as_str),
Some("MRN123")
);
let move_result = move_scu(
&destination,
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
max_pdu_length: 16384,
timeout: None,
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: None,
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
)
.unwrap();
assert_eq!(move_result.status, 0);
let move_calls = handlers.move_calls.lock().unwrap().clone();
assert_eq!(
move_calls,
vec![("1.2.3.4.5".to_owned(), "MOVE-DEST".to_owned())]
);
let completed = wait_for(|| handlers.association_complete.lock().unwrap().clone());
assert_eq!(completed.get(&study_instance_uid).map(Vec::len), Some(1));
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
}
struct MockLogger {
lines: std::sync::Mutex<Vec<String>>,
}
impl DimseLogger for MockLogger {
fn log(&self, message: String) {
self.lines.lock().unwrap().push(message);
}
}
#[test]
fn scp_on_log_reports_association_negotiation_and_per_message_detail() {
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-onlog-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let handlers = std::sync::Arc::new(TestScpHandlers {
find_query: std::sync::Mutex::new(None),
find_response: Vec::new(),
move_calls: std::sync::Mutex::new(Vec::new()),
move_result: true,
association_complete: std::sync::Mutex::new(None),
});
let logger = std::sync::Arc::new(MockLogger {
lines: std::sync::Mutex::new(Vec::new()),
});
let scp = start_scp(
0,
cache_dir.clone(),
handlers,
ScpOptions {
ae_title: "TEST-SCP".to_owned(),
on_log: Some(logger.clone()),
..Default::default()
},
)
.unwrap();
let destination = format!("127.0.0.1:{}", scp.local_port());
let status = echo_scu(
&destination,
EchoScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(status, 0);
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
let joined = logger.lines.lock().unwrap().join("\n");
assert!(
joined.contains("accepting association from"),
"missing association-accept log, got: {joined}"
);
assert!(
joined.contains("established; negotiated presentation context(s)"),
"missing presentation-context negotiation log, got: {joined}"
);
assert!(
joined.contains("received C-ECHO-RQ"),
"missing per-message request log, got: {joined}"
);
assert!(
joined.contains("sending C-ECHO-RSP: status=0x0000"),
"missing per-message response log, got: {joined}"
);
assert!(
joined.contains("released"),
"missing association-release log, got: {joined}"
);
}
#[test]
fn scp_on_log_reports_study_uid_and_a_completion_summary_for_a_stored_instance() {
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-storelog-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let handlers = std::sync::Arc::new(TestScpHandlers {
find_query: std::sync::Mutex::new(None),
find_response: Vec::new(),
move_calls: std::sync::Mutex::new(Vec::new()),
move_result: true,
association_complete: std::sync::Mutex::new(None),
});
let logger = std::sync::Arc::new(MockLogger {
lines: std::sync::Mutex::new(Vec::new()),
});
let scp = start_scp(
0,
cache_dir.clone(),
handlers,
ScpOptions {
ae_title: "TEST-SCP".to_owned(),
on_log: Some(logger.clone()),
..Default::default()
},
)
.unwrap();
let destination = format!("127.0.0.1:{}", scp.local_port());
let source = fixture_path("sr.dcm");
let object = read_dicom_file(&source).unwrap();
let sop_instance_uid = object
.meta()
.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let study_instance_uid = object
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
let results = store_scu(
&destination,
&[source],
StoreScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results[0].status, 0);
let summary = "stored 1 instance(s) across 1 study before ending";
let joined = wait_for(|| {
let joined = logger.lines.lock().unwrap().join("\n");
joined.contains(summary).then_some(joined)
});
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
assert!(
joined.contains(&format!("received C-STORE-RQ dataset: study {study_instance_uid}, SOP instance {sop_instance_uid}")),
"missing per-dataset study/SOP UID log, got: {joined}"
);
assert!(
joined.contains("stored 1 instance(s) across 1 study before ending"),
"missing association-completion summary log, got: {joined}"
);
}
#[test]
fn scp_on_log_reports_when_an_association_ends_with_no_c_store() {
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-nostore-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let handlers = std::sync::Arc::new(TestScpHandlers {
find_query: std::sync::Mutex::new(None),
find_response: Vec::new(),
move_calls: std::sync::Mutex::new(Vec::new()),
move_result: true,
association_complete: std::sync::Mutex::new(None),
});
let logger = std::sync::Arc::new(MockLogger {
lines: std::sync::Mutex::new(Vec::new()),
});
let scp = start_scp(
0,
cache_dir.clone(),
handlers,
ScpOptions {
ae_title: "TEST-SCP".to_owned(),
on_log: Some(logger.clone()),
..Default::default()
},
)
.unwrap();
let destination = format!("127.0.0.1:{}", scp.local_port());
let status = echo_scu(
&destination,
EchoScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(status, 0);
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let joined = loop {
let joined = logger.lines.lock().unwrap().join("\n");
if joined.contains("ended with no C-STORE received") || std::time::Instant::now() > deadline
{
break joined;
}
std::thread::sleep(std::time::Duration::from_millis(20));
};
assert!(
joined.contains("ended with no C-STORE received"),
"missing no-C-STORE association summary log, got: {joined}"
);
}
#[test]
fn scp_find_response_with_non_ascii_text_does_not_close_the_connection() {
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-nonascii-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let mut find_match = std::collections::HashMap::new();
find_match.insert("StudyInstanceUID".to_owned(), "1.2.3.4.5".to_owned());
find_match.insert(
"StudyDescription".to_owned(),
"CT Chest \u{2013} followup".to_owned(),
);
let handlers = std::sync::Arc::new(TestScpHandlers {
find_query: std::sync::Mutex::new(None),
find_response: vec![find_match],
move_calls: std::sync::Mutex::new(Vec::new()),
move_result: true,
association_complete: std::sync::Mutex::new(None),
});
let scp = start_scp(
0,
cache_dir.clone(),
handlers.clone(),
ScpOptions {
ae_title: "TEST-SCP".to_owned(),
..Default::default()
},
)
.unwrap();
let destination = format!("127.0.0.1:{}", scp.local_port());
let matches = find_scu(
&destination,
&std::collections::HashMap::new(),
FindScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
max_pdu_length: 16384,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(matches.len(), 1);
let match_value: serde_json::Value = serde_json::from_str(&matches[0]).unwrap();
assert_eq!(match_value["00081030"], "CT Chest \u{2013} followup");
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
}
fn write_synthetic_ct_series(count: usize, spacing_mm: f64) -> Vec<PathBuf> {
let base = read_dicom_file(fixture_path("ct.dcm")).unwrap();
let base_z = 1115.0;
let mut paths = Vec::with_capacity(count);
for index in (0..count).rev() {
let mut object = base.clone();
let z = base_z + (index as f64) * spacing_mm;
object.put(DataElement::new(
tags::IMAGE_POSITION_PATIENT,
VR::DS,
PrimitiveValue::from(format!("-151.493508\\-36.6564417\\{z}")),
));
let path = temp_file_path(&format!("mpr-volume-slice-{index}"));
write_dicom_file(&mut object, &path).unwrap();
paths.push(path);
}
paths
}
#[test]
fn build_volume_sorts_slices_spatially_and_reformats_the_native_axial_plane() {
let paths = write_synthetic_ct_series(5, 1.0);
let volume = build_volume(&paths).unwrap();
assert_eq!(volume.rows, 512);
assert_eq!(volume.cols, 512);
assert_eq!(volume.num_slices, 5);
assert_eq!(volume.slice_zs.len(), 5);
for window in volume.slice_zs.windows(2) {
assert!(
window[1] > window[0],
"slice_zs must be spatially sorted ascending: {:?}",
volume.slice_zs
);
}
let observed_spacing = (volume.slice_zs[4] - volume.slice_zs[0]) / 4.0;
assert!(
(observed_spacing - 1.0).abs() < 1e-6,
"observed spacing {observed_spacing}"
);
let params = PlaneParams {
origin: volume.center(),
row_dir: volume.row_vector,
col_dir: volume.col_vector,
output_width: 64,
output_height: 64,
spacing_mm: volume.min_spacing_mm(),
window_center: None,
window_width: None,
interpolation: Interpolation::Trilinear,
slab_thickness_mm: 0.0,
slab_projection: SlabProjection::MaximumIntensity,
};
let output = reformat_plane(&volume, ¶ms, RenderOutputFormat::Png, 90).unwrap();
assert_eq!(output.width, 64);
assert_eq!(output.height, 64);
assert!(!output.bytes.is_empty());
for path in &paths {
fs::remove_file(path).ok();
}
}
#[test]
fn build_volume_puts_each_slice_s_own_pixels_in_its_spatial_plane_for_any_file_order() {
let base = read_dicom_file(fixture_path("ct.dcm")).unwrap();
let file_order = [2usize, 0, 4, 1, 3];
let mut paths = Vec::new();
for &index in &file_order {
let mut object = base.clone();
let z = 1115.0 + index as f64;
object.put(DataElement::new(
tags::IMAGE_POSITION_PATIENT,
VR::DS,
PrimitiveValue::from(format!("-151.493508\\-36.6564417\\{z}")),
));
object.put(DataElement::new(
tags::RESCALE_SLOPE,
VR::DS,
PrimitiveValue::from("1"),
));
object.put(DataElement::new(
tags::RESCALE_INTERCEPT,
VR::DS,
PrimitiveValue::from(format!("{}", index * 1000)),
));
let path = temp_file_path(&format!("mpr-volume-order-slice-{index}"));
write_dicom_file(&mut object, &path).unwrap();
paths.push(path);
}
let volume = build_volume(&paths).unwrap();
let plane = (volume.rows * volume.cols) as usize;
assert_eq!(volume.samples.len(), plane * 5);
for slice in 0..5 {
for pixel in [0usize, plane / 2, plane - 1] {
let offset = volume.samples[slice * plane + pixel] - volume.samples[pixel];
assert_eq!(offset, (slice * 1000) as f32, "slice {slice} pixel {pixel}");
}
}
for path in &paths {
fs::remove_file(path).ok();
}
}
#[test]
fn build_volume_rejects_a_non_parallel_orientation_in_the_stack() {
let paths = write_synthetic_ct_series(4, 1.0);
let mut tilted = read_dicom_file(&paths[1]).unwrap();
tilted.put(DataElement::new(
tags::IMAGE_ORIENTATION_PATIENT,
VR::DS,
PrimitiveValue::from("1\\0\\0\\0\\0.7071\\0.7071"),
));
write_dicom_file(&mut tilted, &paths[1]).unwrap();
let result = build_volume(&paths);
assert!(
matches!(result, Err(VolumeError::InconsistentGeometry(_))),
"expected InconsistentGeometry, got {result:?}"
);
for path in &paths {
fs::remove_file(path).ok();
}
}
#[test]
fn pack_dicom_frame_texture_rejects_a_color_instance_instead_of_misreading_it_as_grayscale() {
let source = fixture_bytes(fixture_path("us.dcm"));
let object = read_dicom_bytes(&source).unwrap();
let result = pack_dicom_frame_texture(&object, 0, None, None, TextureCompression::None);
assert!(
matches!(
result,
Err(TextureExportError::Render(
RenderError::UnsupportedSamplesPerPixel(3)
))
),
"expected UnsupportedSamplesPerPixel(3), got {result:?}"
);
}
#[test]
fn pack_dicom_frame_stack_texture_packs_multiple_sources_as_layers_in_order() {
let source = fixture_bytes(fixture_path("dx.dcm"));
let object = read_dicom_bytes(&source).unwrap();
let sources = [(&object, 0usize), (&object, 0usize)];
let packed = pack_dicom_frame_stack_texture(&sources, None, TextureCompression::None).unwrap();
assert_eq!(packed.meta.content_kind, ContentKind::FrameStack);
assert_eq!(packed.meta.depth, 2);
assert!(!packed.meta.downsampled);
let layer_bytes = packed.payload.len() / 2;
assert_eq!(packed.payload[..layer_bytes], packed.payload[layer_bytes..]);
}
#[test]
fn pack_dicom_frame_stack_texture_carries_each_layers_own_default_window_and_invert() {
let tagged = read_dicom_bytes(fixture_bytes(fixture_path("dx.dcm"))).unwrap();
let mut untagged_inverted = tagged.clone();
untagged_inverted.put(DataElement::new(
tags::WINDOW_CENTER,
VR::DS,
PrimitiveValue::from("123"),
));
untagged_inverted.put(DataElement::new(
tags::WINDOW_WIDTH,
VR::DS,
PrimitiveValue::from("456"),
));
untagged_inverted.put(DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from("MONOCHROME1"),
));
untagged_inverted.remove_element(tags::PRESENTATION_LUT_SHAPE);
let mut untagged = tagged.clone();
untagged.remove_element(tags::WINDOW_CENTER);
untagged.remove_element(tags::WINDOW_WIDTH);
let sources = [
(&tagged, 0usize),
(&untagged_inverted, 0usize),
(&untagged, 0usize),
];
let packed = pack_dicom_frame_stack_texture(&sources, None, TextureCompression::None).unwrap();
let windows = &packed.meta.layer_default_windows;
assert_eq!(windows.len(), 3);
assert_eq!(windows[1], (123.0, 456.0));
let (stack_center, stack_width) = (
packed.meta.default_window_center.unwrap(),
packed.meta.default_window_width.unwrap(),
);
assert_eq!(
windows[0],
(stack_center, stack_width),
"first layer still speaks for the stack-wide default"
);
assert!(windows[2].1 >= 1.0);
assert_eq!(packed.meta.layer_invert.len(), 3);
assert_ne!(packed.meta.layer_invert[0], packed.meta.layer_invert[1]);
let json = packed.meta.to_json();
assert_eq!(json["layerWindowCenters"][1], 123.0);
assert_eq!(json["layerWindowWidths"][1], 456.0);
assert_eq!(json["layerInvert"].as_array().unwrap().len(), 3);
}
#[test]
fn pack_dicom_frame_stack_texture_fails_closed_if_any_source_is_a_color_instance() {
let grayscale = read_dicom_bytes(fixture_bytes(fixture_path("dx.dcm"))).unwrap();
let color = read_dicom_bytes(fixture_bytes(fixture_path("us.dcm"))).unwrap();
let sources = [(&grayscale, 0usize), (&color, 0usize)];
let result = pack_dicom_frame_stack_texture(&sources, None, TextureCompression::None);
assert!(
matches!(
result,
Err(TextureExportError::Render(
RenderError::UnsupportedSamplesPerPixel(3)
))
),
"expected UnsupportedSamplesPerPixel(3), got {result:?}"
);
}
fn assert_single_frame_read_matches_full_read(path: &Path, frame_index: usize) {
let full = read_dicom_file(path).unwrap();
let single = read_dicom_file_for_frame(path, frame_index)
.unwrap()
.unwrap_or_else(|| {
panic!(
"{} frame {frame_index}: expected the single-frame fast path",
path.display()
)
});
let options = RenderPipelineOptions {
frame_index,
..Default::default()
};
for format in [RenderOutputFormat::Raw, RenderOutputFormat::Png] {
let expected = render_dicom_frame(&full, format, &options).unwrap();
let actual = render_dicom_frame(&single, format, &options).unwrap();
assert_eq!(
expected.bytes,
actual.bytes,
"{} frame {frame_index} {format:?}: single-frame read rendered differently",
path.display()
);
}
}
#[test]
fn read_dicom_file_for_frame_renders_identically_to_full_read_for_native_multi_frame() {
let us2 = fixture_path("us2.dcm");
for frame_index in [0, 1, 113, 226] {
assert_single_frame_read_matches_full_read(&us2, frame_index);
}
assert_single_frame_read_matches_full_read(&fixture_path("mr.dcm"), 0);
}
#[test]
fn read_dicom_file_for_frame_decodes_16_bit_ow_frames_in_each_native_byte_order() {
const ROWS: u16 = 4;
const COLS: u16 = 3;
const FRAMES: usize = 5;
let samples = usize::from(ROWS) * usize::from(COLS);
let pixels: Vec<u16> = (0..samples * FRAMES)
.map(|i| ((i * 97 + 13) % 4096) as u16)
.collect();
for ts in [
uids::IMPLICIT_VR_LITTLE_ENDIAN,
uids::EXPLICIT_VR_LITTLE_ENDIAN,
"1.2.840.10008.1.2.2",
] {
let dataset = InMemDicomObject::from_element_iter([
DataElement::new(
tags::SOP_CLASS_UID,
VR::UI,
PrimitiveValue::from("1.2.840.10008.5.1.4.1.1.7"),
),
DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from("1.2.3.4.5.6.7"),
),
DataElement::new(tags::SAMPLES_PER_PIXEL, VR::US, dicom_value!(U16, [1])),
DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from("MONOCHROME2"),
),
DataElement::new(
tags::NUMBER_OF_FRAMES,
VR::IS,
PrimitiveValue::from(FRAMES.to_string()),
),
DataElement::new(tags::ROWS, VR::US, dicom_value!(U16, [ROWS])),
DataElement::new(tags::COLUMNS, VR::US, dicom_value!(U16, [COLS])),
DataElement::new(tags::BITS_ALLOCATED, VR::US, dicom_value!(U16, [16])),
DataElement::new(tags::BITS_STORED, VR::US, dicom_value!(U16, [12])),
DataElement::new(tags::HIGH_BIT, VR::US, dicom_value!(U16, [11])),
DataElement::new(tags::PIXEL_REPRESENTATION, VR::US, dicom_value!(U16, [0])),
DataElement::new(
tags::PIXEL_DATA,
VR::OW,
PrimitiveValue::U16(pixels.clone().into()),
),
]);
let path = temp_file_path("dcmnorm-single-frame-ow");
write_dataset_as_dicom_file(dataset, &path, ts).unwrap();
for frame_index in 0..FRAMES {
assert_single_frame_read_matches_full_read(&path, frame_index);
}
fs::remove_file(&path).ok();
}
}
#[test]
fn read_dicom_file_for_frame_declines_what_it_cannot_read_partially() {
assert!(read_dicom_file_for_frame(fixture_path("ct.dcm"), 0)
.unwrap()
.is_none());
assert!(read_dicom_file_for_frame(fixture_path("deflated.dcm"), 0)
.unwrap()
.is_none());
assert!(read_dicom_file_for_frame(fixture_path("us2.dcm"), 227)
.unwrap()
.is_none());
assert!(
read_dicom_file_for_frame(fixture_path("mr_truncated.dcm"), 0)
.map(|object| object.is_none())
.unwrap_or(true)
);
}
fn json_via_full_read_and_scan(path: &Path, format: DicomJsonFormat) -> String {
let bytes = fs::read(path).unwrap();
let object = read_dicom_bytes(&bytes).unwrap();
let bulk_scan_failed = std::cell::Cell::new(false);
let bulk_scan_cursor = std::cell::Cell::new(0usize);
write_dicom_json_with_options(
&object,
DicomJsonWriteOptions {
format,
bulk_data_mode: DicomJsonBulkDataMode::Uri,
bulk_data_source: Some(&bytes),
bulk_scan_failed: Some(&bulk_scan_failed),
bulk_scan_cursor: Some(&bulk_scan_cursor),
..Default::default()
},
)
.unwrap()
}
fn json_via_deferred_read(path: &Path, format: DicomJsonFormat) -> String {
let options = DicomJsonWriteOptions {
format,
bulk_data_mode: DicomJsonBulkDataMode::Uri,
..Default::default()
};
dicom_file_to_json(path, options).unwrap()
}
fn bulk_data_uris(json: &JsonValue, out: &mut Vec<(usize, usize)>) {
match json {
JsonValue::Object(map) => {
if let Some(JsonValue::String(uri)) = map.get("BulkDataURI") {
let query = uri.split_once('?').unwrap().1;
let field = |name: &str| {
query
.split('&')
.find_map(|pair| pair.strip_prefix(name))
.unwrap()
.parse::<usize>()
.unwrap()
};
out.push((field("offset="), field("length=")));
}
map.values().for_each(|value| bulk_data_uris(value, out));
}
JsonValue::Array(items) => items.iter().for_each(|value| bulk_data_uris(value, out)),
_ => {}
}
}
#[test]
fn deferred_bulk_data_json_matches_full_read_and_scan_for_every_fixture() {
let mut deferred_files = 0;
for entry in fs::read_dir(fixture_path("")).unwrap() {
let path = entry.unwrap().path();
if path.extension().and_then(|ext| ext.to_str()) != Some("dcm")
|| read_dicom_file(&path).is_err()
{
continue;
}
if matches!(read_dicom_file_deferring_bulk_data(&path), Ok(Some(_))) {
deferred_files += 1;
}
for format in [DicomJsonFormat::Flat, DicomJsonFormat::Standard] {
let Ok(expected) =
std::panic::catch_unwind(|| json_via_full_read_and_scan(&path, format))
else {
continue; };
let actual = json_via_deferred_read(&path, format);
assert_eq!(
expected,
actual,
"{} ({format:?}): deferred JSON differs",
path.display()
);
}
}
assert!(
deferred_files > 20,
"only {deferred_files} fixtures took the deferred path"
);
}
#[test]
fn deferred_bulk_data_json_handles_defined_length_items_and_thresholds() {
fn element(group: u16, elem: u16, vr: &[u8; 2], value: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&group.to_le_bytes());
out.extend_from_slice(&elem.to_le_bytes());
out.extend_from_slice(vr);
if matches!(vr, b"OB" | b"OW" | b"SQ" | b"UN") {
out.extend_from_slice(&[0, 0]);
out.extend_from_slice(&(value.len() as u32).to_le_bytes());
} else {
out.extend_from_slice(&(value.len() as u16).to_le_bytes());
}
out.extend_from_slice(value);
out
}
fn item(content: &[u8]) -> Vec<u8> {
let mut out = vec![0xFE, 0xFF, 0x00, 0xE0];
out.extend_from_slice(&(content.len() as u32).to_le_bytes());
out.extend_from_slice(content);
out
}
let pattern = |seed: u8, len: usize| {
(0..len)
.map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))
.collect::<Vec<u8>>()
};
let items: Vec<u8> = (0..3u8)
.flat_map(|i| {
let mut content = element(0x0029, 0x1011, b"OB", &pattern(i, 100));
content.extend(element(0x0029, 0x1012, b"US", &u16::from(i).to_le_bytes()));
item(&content)
})
.collect();
let mut tail = element(0x0029, 0x0010, b"LO", b"TESTCREATOR ");
tail.extend(element(0x0029, 0x1010, b"SQ", &items));
tail.extend(element(0x0029, 0x1020, b"OB", &pattern(7, 32))); tail.extend(element(0x0029, 0x1021, b"OB", &pattern(8, 34))); tail.extend(element(0x0029, 0x1022, b"OW", &pattern(9, 64)));
tail.extend(element(0x7FE0, 0x0010, b"OB", &pattern(10, 300)));
tail.extend(element(0xFFFC, 0xFFFC, b"OB", &[0; 8]));
let path = temp_file_path("dcmnorm-deferred-json");
let dataset = InMemDicomObject::from_element_iter([
DataElement::new(
tags::SOP_CLASS_UID,
VR::UI,
PrimitiveValue::from("1.2.840.10008.5.1.4.1.1.7"),
),
DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from("1.2.3.4.5.6.8"),
),
]);
write_dataset_as_dicom_file(dataset, &path, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
let mut bytes = fs::read(&path).unwrap();
bytes.extend(tail);
fs::write(&path, &bytes).unwrap();
let (_, deferred) = read_dicom_file_deferring_bulk_data(&path)
.unwrap()
.expect("deferred path");
assert!(
deferred.value(Tag(0x0029, 0x1020)).is_none(),
"32-byte value must stay inline"
);
assert!(deferred.value(Tag(0x0029, 0x1021)).is_some());
for index in 0..3 {
assert!(deferred
.item(Tag(0x0029, 0x1010), index)
.unwrap()
.value(Tag(0x0029, 0x1011))
.is_some());
}
let full = read_dicom_file(&path).unwrap();
for format in [DicomJsonFormat::Flat, DicomJsonFormat::Standard] {
let actual = json_via_deferred_read(&path, format);
assert_eq!(
json_via_full_read_and_scan(&path, format),
actual,
"{format:?}"
);
let mut uris = Vec::new();
bulk_data_uris(&serde_json::from_str(&actual).unwrap(), &mut uris);
assert_eq!(
uris.len(),
6,
"{format:?}: 3 nested OB + 2 top-level + PixelData"
);
let mut expected_values: Vec<Vec<u8>> =
vec![pattern(8, 34), pattern(9, 64), pattern(10, 300)];
expected_values.extend((0..3u8).map(|i| pattern(i, 100)));
for (offset, length) in uris {
let referenced = &bytes[offset..offset + length];
assert!(
expected_values.iter().any(|value| value == referenced),
"URI {offset}+{length} points at the wrong bytes"
);
}
}
assert_eq!(
full.element(Tag(0x0029, 0x0010))
.unwrap()
.to_str()
.unwrap()
.trim(),
"TESTCREATOR"
);
let deferred_json = json_via_deferred_read(&path, DicomJsonFormat::Standard);
assert!(
deferred_json.contains("FFFCFFFC"),
"trailing element after PixelData was dropped"
);
fs::remove_file(&path).ok();
}
#[test]
fn writing_a_short_form_vr_value_longer_than_16_bits_fails_instead_of_corrupting_the_file() {
let mut object = read_dicom_file(fixture_path("mr_small.dcm")).unwrap();
object.put_str(
tags::STUDY_DESCRIPTION,
dcmnorm_core::VR::LO,
"X".repeat(70_000),
);
let error = write_dicom_bytes(&mut object)
.expect_err("a 70000-byte LO cannot be written in Explicit VR Little Endian");
assert!(
error.to_string().contains("16-bit length")
|| format!("{error:?}").contains("WriteHeaderTooLong"),
"unexpected error: {error} ({error:?})"
);
let mut object = read_dicom_file(fixture_path("sr.dcm")).unwrap();
object.put_str(
tags::STUDY_DESCRIPTION,
dcmnorm_core::VR::LO,
"X".repeat(70_000),
);
let bytes = write_dicom_bytes(&mut object).unwrap();
let roundtrip = read_dicom_bytes(&bytes).unwrap();
assert_eq!(
roundtrip
.element(tags::STUDY_DESCRIPTION)
.unwrap()
.to_str()
.unwrap()
.len(),
70_000
);
}
fn encapsulated_offset_table_and_fragment_offsets(bytes: &[u8]) -> (Vec<u32>, Vec<u32>) {
let header: &[u8] = &[
0xE0, 0x7F, 0x10, 0x00, b'O', b'B', 0, 0, 0xFF, 0xFF, 0xFF, 0xFF,
];
let start = bytes
.windows(header.len())
.rposition(|w| w == header)
.expect("written file should have undefined-length encapsulated Pixel Data")
+ header.len();
let item = |at: usize| -> Option<usize> {
(bytes.get(at..at + 4)? == [0xFE, 0xFF, 0x00, 0xE0])
.then(|| u32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()) as usize)
};
let bot_len = item(start).expect("Pixel Data should start with the offset table item");
let (bot, _) = bytes[start + 8..start + 8 + bot_len].as_chunks::<4>();
let bot = bot.iter().map(|c| u32::from_le_bytes(*c)).collect();
let first = start + 8 + bot_len;
let mut fragments = Vec::new();
let mut at = first;
while let Some(len) = item(at) {
fragments.push((at - first) as u32);
at += 8 + len;
}
(bot, fragments)
}
#[test]
fn transcoding_a_multi_frame_object_to_jpeg_baseline_writes_a_correct_basic_offset_table() {
let source = std::fs::read(fixture_path("us2.dcm")).unwrap();
let bytes = transcode_dicom_bytes(&source, "1.2.840.10008.1.2.4.50").unwrap();
let (bot, fragment_offsets) = encapsulated_offset_table_and_fragment_offsets(&bytes);
assert_eq!(fragment_offsets.len(), 227, "one fragment per frame");
assert_eq!(
bot, fragment_offsets,
"every Basic Offset Table entry must point at its frame's fragment"
);
let native = transcode_dicom_bytes(&bytes, "1.2.840.10008.1.2.1").unwrap();
let object = read_dicom_bytes(&native).unwrap();
let rows = object
.element(tags::ROWS)
.unwrap()
.to_int::<usize>()
.unwrap();
let cols = object
.element(tags::COLUMNS)
.unwrap()
.to_int::<usize>()
.unwrap();
let pixels = object
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap();
assert_eq!(pixels.len(), 227 * rows * cols);
}
#[test]
fn transcoding_rgb_to_jpeg_baseline_labels_it_ybr_and_round_trips_the_colors() {
let source = read_dicom_file(fixture_path("us.dcm")).unwrap();
assert_eq!(
source
.element(tags::PHOTOMETRIC_INTERPRETATION)
.unwrap()
.to_str()
.unwrap(),
"RGB"
);
let jpeg = transcode_dcmnorm_object(&source, "1.2.840.10008.1.2.4.50").unwrap();
assert_eq!(
jpeg.element(tags::PHOTOMETRIC_INTERPRETATION)
.unwrap()
.to_str()
.unwrap(),
"YBR_FULL_422"
);
let jpeg = read_dicom_bytes(write_dicom_bytes(&mut jpeg.clone()).unwrap()).unwrap();
let native = transcode_dcmnorm_object(&jpeg, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
assert_eq!(
native
.element(tags::PHOTOMETRIC_INTERPRETATION)
.unwrap()
.to_str()
.unwrap(),
"RGB"
);
let original = source
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap();
let decoded = native
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap();
assert_eq!(decoded.len(), original.len());
let mean_abs_error = original
.iter()
.zip(decoded.iter())
.map(|(a, b)| (i32::from(*a) - i32::from(*b)).unsigned_abs() as u64)
.sum::<u64>() as f64
/ original.len() as f64;
assert!(
mean_abs_error < 4.0,
"decoded samples drifted from the source: mean |error| = {mean_abs_error:.2}"
);
let render = |object: &dcmnorm_object::DefaultDicomObject| {
let rendered = render_dicom_frame(
object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
image::load_from_memory(&rendered.bytes).unwrap().to_rgb8()
};
let (reference, rendered) = (render(&source), render(&jpeg));
assert_eq!(reference.dimensions(), rendered.dimensions());
let render_error = reference
.as_raw()
.iter()
.zip(rendered.as_raw())
.map(|(a, b)| (i32::from(*a) - i32::from(*b)).unsigned_abs() as u64)
.sum::<u64>() as f64
/ reference.as_raw().len() as f64;
assert!(
render_error < 4.0,
"rendered JPEG drifted from the source render: mean |error| = {render_error:.2}"
);
}
fn implicit_vr_file_declaring_explicit_vr() -> Vec<u8> {
let mut bytes = std::fs::read(fixture_path("sr.dcm")).unwrap();
assert_eq!(&bytes[128..132], b"DICM");
assert_eq!(
&bytes[132..138],
b"\x02\x00\x00\x00UL",
"expected (0002,0000) first"
);
let group_length = u32::from_le_bytes(bytes[140..144].try_into().unwrap()) as usize;
let at = (144..144 + group_length)
.find(|&i| bytes[i..].starts_with(b"\x02\x00\x10\x00UI"))
.expect("TransferSyntaxUID in the meta group");
let old_len = u16::from_le_bytes(bytes[at + 6..at + 8].try_into().unwrap()) as usize;
assert_eq!(&bytes[at + 8..at + 8 + old_len], b"1.2.840.10008.1.2\0");
let new_value = b"1.2.840.10008.1.2.1\0";
let mut replacement = (new_value.len() as u16).to_le_bytes().to_vec();
replacement.extend_from_slice(new_value);
bytes.splice(at + 6..at + 8 + old_len, replacement);
let new_group_length = (group_length + new_value.len() - old_len) as u32;
bytes[140..144].copy_from_slice(&new_group_length.to_le_bytes());
bytes
}
fn canonical_dataset_bytes(object: &dcmnorm_object::InMemDicomObject) -> Vec<u8> {
use dcmnorm_encoding::TransferSyntaxIndex;
let ts = dcmnorm_transcode::TransferSyntaxRegistry
.get(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap();
let mut bytes = Vec::new();
object.write_dataset_with_ts(&mut bytes, ts).unwrap();
bytes
}
#[test]
fn reads_a_file_declaring_explicit_vr_that_is_encoded_implicit() {
let mismatched = implicit_vr_file_declaring_explicit_vr();
assert!(
dcmnorm_object::OpenFileOptions::new()
.read_preamble(dcmnorm_object::ReadPreamble::Always)
.from_reader(mismatched.as_slice())
.is_err(),
"the strict read should reject this file, or the fallback is not what's being tested"
);
let reference = read_dicom_file(fixture_path("sr.dcm")).unwrap();
let object = read_dicom_bytes(&mismatched).unwrap();
assert_eq!(
object.meta().transfer_syntax().trim_end_matches('\0'),
uids::EXPLICIT_VR_LITTLE_ENDIAN
);
assert_eq!(
canonical_dataset_bytes(&object),
canonical_dataset_bytes(&reference),
"the data set should read exactly as the correctly-labeled file"
);
let path = temp_file_path("dcmnorm-mismatched-ts");
std::fs::write(&path, &mismatched).unwrap();
let from_path = read_dicom_file(&path);
let _ = std::fs::remove_file(&path);
assert_eq!(
canonical_dataset_bytes(&from_path.unwrap()),
canonical_dataset_bytes(&reference)
);
let mut object = object;
let written = write_dicom_bytes(&mut object).unwrap();
let reread = dcmnorm_object::OpenFileOptions::new()
.read_preamble(dcmnorm_object::ReadPreamble::Always)
.from_reader(written.as_slice())
.unwrap();
assert_eq!(
canonical_dataset_bytes(&reread),
canonical_dataset_bytes(&reference)
);
}
#[test]
fn flexible_decoding_reads_conformant_files_unchanged() {
let mut compared = 0;
for entry in std::fs::read_dir(fixture_path("")).unwrap() {
let path = entry.unwrap().path();
let Ok(strict) = dcmnorm_object::OpenFileOptions::new().open_file(&path) else {
continue;
};
let flexible = dcmnorm_object::OpenFileOptions::new()
.flexible_decoding(true)
.open_file(&path);
let flexible = flexible.unwrap_or_else(|e| {
panic!(
"{}: strict read succeeded, flexible failed: {e}",
path.display()
)
});
assert_eq!(
canonical_dataset_bytes(&flexible),
canonical_dataset_bytes(&strict),
"{}",
path.display()
);
compared += 1;
}
assert!(
compared > 40,
"expected to compare most fixtures, compared {compared}"
);
}
fn dimse_pdv(
pc_id: u8,
value_type: dcmnorm_dimse::pdu::PDataValueType,
is_last: bool,
data: Vec<u8>,
) -> dcmnorm_dimse::pdu::PDataValue {
dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc_id,
value_type,
is_last,
data,
}
}
fn dimse_command_bytes(command: &InMemDicomObject) -> Vec<u8> {
let mut data = Vec::new();
command
.write_dataset_with_ts(&mut data, dimse_implicit_vr_le())
.unwrap();
data
}
#[test]
fn find_scu_reads_pending_match_and_final_response_packed_into_one_pdu() {
use dcmnorm_dimse::pdu::PDataValueType::{Command, Data};
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let (scp_handle, addr) = spawn_mock_scp(abstract_syntax, move |association| {
let (pc_id, request, _identifier) = dimse_recv_command_with_data(association);
let message_id = dimse_message_id(&request);
let response = |status: u16, data_set_type: u16| {
dimse_command_bytes(&InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8020])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [data_set_type]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [status])),
]))
};
let ts = {
use dcmnorm_encoding::TransferSyntaxIndex;
dcmnorm_transcode::TransferSyntaxRegistry
.get(&association.presentation_contexts()[0].transfer_syntax)
.unwrap()
};
let mut matched = Vec::new();
InMemDicomObject::from_element_iter([DataElement::new(
tags::STUDY_INSTANCE_UID,
VR::UI,
dicom_value!(Str, "1.2.3.4.5"),
)])
.write_dataset_with_ts(&mut matched, ts)
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![
dimse_pdv(pc_id, Command, true, response(0xFF00, 0x0001)),
dimse_pdv(pc_id, Data, true, matched),
dimse_pdv(pc_id, Command, true, response(0x0000, 0x0101)),
],
})
.unwrap();
});
let mut query = std::collections::HashMap::new();
query.insert("StudyInstanceUID".to_owned(), "1.2.3.4.5".to_owned());
let matches = find_scu(
&addr.to_string(),
&query,
FindScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: Some(std::time::Duration::from_secs(10)),
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(matches.len(), 1);
let value: serde_json::Value = serde_json::from_str(&matches[0]).unwrap();
assert_eq!(value["0020000D"], "1.2.3.4.5");
scp_handle.join().unwrap();
}
#[test]
fn move_scu_reads_a_failed_sop_instance_uid_list_packed_with_its_response() {
use dcmnorm_dimse::pdu::PDataValueType::{Command, Data};
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let (scp_handle, addr) = spawn_mock_scp(abstract_syntax, move |association| {
let (pc_id, request, _identifier) = dimse_recv_command_with_data(association);
let message_id = dimse_message_id(&request);
let response =
|status: u16, data_set_type: u16, completed: u16, failed: u16, remaining: u16| {
dimse_command_bytes(&InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [data_set_type]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [status])),
DataElement::new(
tags::NUMBER_OF_REMAINING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [remaining]),
),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [completed]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [failed]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]))
};
let mut failed_list = Vec::new();
InMemDicomObject::from_element_iter([DataElement::new(
tags::FAILED_SOP_INSTANCE_UID_LIST,
VR::UI,
dicom_value!(Str, "1.2.3.4.5.6"),
)])
.write_dataset_with_ts(&mut failed_list, dimse_implicit_vr_le())
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dimse_pdv(
pc_id,
Command,
true,
response(0xFF00, 0x0101, 1, 0, 1),
)],
})
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![
dimse_pdv(pc_id, Command, true, response(0xA702, 0x0001, 1, 1, 0)),
dimse_pdv(pc_id, Data, true, failed_list),
],
})
.unwrap();
});
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: Some(std::time::Duration::from_secs(10)),
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: None,
query_retrieve_level: None,
series_instance_uid: None,
sop_instance_uids: Vec::new(),
},
)
.unwrap();
assert_eq!(
(result.status, result.completed, result.failed),
(0xA702, 1, 1)
);
scp_handle.join().unwrap();
}
#[test]
fn scp_stores_a_data_set_whose_first_fragment_shares_the_command_pdu() {
use dcmnorm_dimse::pdu::PDataValueType::{Command, Data};
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-packed-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let handlers = std::sync::Arc::new(TestScpHandlers {
find_query: std::sync::Mutex::new(None),
find_response: Vec::new(),
move_calls: std::sync::Mutex::new(Vec::new()),
move_result: true,
association_complete: std::sync::Mutex::new(None),
});
let scp = start_scp(
0,
cache_dir.clone(),
handlers.clone(),
ScpOptions {
ae_title: "TEST-SCP".to_owned(),
..Default::default()
},
)
.unwrap();
let object = read_dicom_file(fixture_path("sr.dcm")).unwrap();
let sop_class_uid = object
.meta()
.media_storage_sop_class_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let sop_instance_uid = object
.meta()
.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let study_instance_uid = object
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
let ts_uid = object
.meta()
.transfer_syntax()
.trim_end_matches('\0')
.to_owned();
let ts = {
use dcmnorm_encoding::TransferSyntaxIndex;
dcmnorm_transcode::TransferSyntaxRegistry
.get(&ts_uid)
.unwrap()
};
let mut data_set = Vec::new();
object.write_dataset_with_ts(&mut data_set, ts).unwrap();
assert!(
data_set.len() > 300,
"fixture too small to split into three fragments"
);
let mut association = dcmnorm_dimse::association::client::ClientAssociationOptions::new()
.calling_ae_title("DCM4CHE-LIKE")
.called_ae_title("TEST-SCP")
.with_presentation_context(sop_class_uid.clone(), vec![ts_uid.clone()])
.establish_with(&format!("127.0.0.1:{}", scp.local_port()))
.unwrap();
let pc_id = association.presentation_contexts()[0].id;
let command = dimse_command_bytes(&InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, sop_class_uid.as_str()),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0001])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [1])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0000]),
),
DataElement::new(
tags::AFFECTED_SOP_INSTANCE_UID,
VR::UI,
dicom_value!(Str, sop_instance_uid.as_str()),
),
]));
let third = data_set.len() / 3;
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![
dimse_pdv(pc_id, Command, true, command),
dimse_pdv(pc_id, Data, false, data_set[..third].to_vec()),
],
})
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dimse_pdv(
pc_id,
Data,
false,
data_set[third..2 * third].to_vec(),
)],
})
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dimse_pdv(pc_id, Data, true, data_set[2 * third..].to_vec())],
})
.unwrap();
let status = match association.receive_command().unwrap() {
dcmnorm_dimse::Incoming::Command { data, .. } => {
let response =
InMemDicomObject::read_dataset_with_ts(data.as_slice(), dimse_implicit_vr_le())
.unwrap();
response
.element(tags::STATUS)
.unwrap()
.to_int::<u16>()
.unwrap()
}
other => panic!("expected C-STORE-RSP, got {other:?}"),
};
association.release().unwrap();
assert_eq!(status, 0x0000);
let stored = wait_for(|| handlers.association_complete.lock().unwrap().clone());
let paths = stored
.get(&study_instance_uid)
.expect("the study was stored");
assert_eq!(paths.len(), 1);
assert!(
paths[0].ends_with(&format!("{sop_instance_uid}.dcm")),
"unexpected path {}",
paths[0]
);
let written = read_dicom_file(Path::new(&paths[0])).unwrap();
assert_eq!(
written
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim(),
sop_instance_uid
);
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
}
struct SopClassFindHandlers {
calls: std::sync::Mutex<Vec<(String, std::collections::HashMap<String, String>)>>,
response: Vec<std::collections::HashMap<String, String>>,
gate: std::sync::Mutex<Option<std::sync::mpsc::Receiver<()>>>,
}
impl SopClassFindHandlers {
fn new(
response: Vec<std::collections::HashMap<String, String>>,
gate: Option<std::sync::mpsc::Receiver<()>>,
) -> Self {
Self {
calls: std::sync::Mutex::new(Vec::new()),
response,
gate: std::sync::Mutex::new(gate),
}
}
}
impl ScpHandlers for SopClassFindHandlers {
fn on_find(
&self,
_filter: &std::collections::HashMap<String, String>,
) -> Result<Vec<std::collections::HashMap<String, String>>, String> {
panic!("the SCP calls on_find_with_sop_class");
}
fn on_find_with_sop_class(
&self,
sop_class_uid: &str,
filter: &std::collections::HashMap<String, String>,
) -> Result<Vec<std::collections::HashMap<String, String>>, String> {
self.calls
.lock()
.unwrap()
.push((sop_class_uid.to_owned(), filter.clone()));
let gate = self.gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.recv_timeout(std::time::Duration::from_secs(10))
.unwrap();
}
Ok(self.response.clone())
}
fn on_move(
&self,
_study_instance_uid: &str,
_move_destination_ae: &str,
) -> Result<bool, String> {
Ok(false)
}
fn on_association_complete(
&self,
_stored_instances_by_study: &std::collections::HashMap<String, Vec<String>>,
) {
}
}
fn study_match(study_instance_uid: &str) -> std::collections::HashMap<String, String> {
std::collections::HashMap::from([(
"StudyInstanceUID".to_owned(),
study_instance_uid.to_owned(),
)])
}
fn context_id(
association: &dcmnorm_dimse::ClientAssociation<std::net::TcpStream>,
abstract_syntax: &str,
) -> u8 {
association
.presentation_contexts()
.iter()
.find(|pc| pc.abstract_syntax == abstract_syntax)
.unwrap_or_else(|| panic!("no presentation context for {abstract_syntax}"))
.id
}
fn send_raw_find(
association: &mut dcmnorm_dimse::ClientAssociation<std::net::TcpStream>,
pc_id: u8,
sop_class_uid: &str,
message_id: u16,
identifier: &InMemDicomObject,
) {
use dcmnorm_dimse::pdu::PDataValueType::{Command, Data};
let command = dimse_command_bytes(&InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, sop_class_uid),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0020])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [message_id])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0000]),
),
]));
let mut data = Vec::new();
identifier
.write_dataset_with_ts(&mut data, dimse_implicit_vr_le())
.unwrap();
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![
dimse_pdv(pc_id, Command, true, command),
dimse_pdv(pc_id, Data, true, data),
],
})
.unwrap();
}
fn send_raw_cancel(
association: &mut dcmnorm_dimse::ClientAssociation<std::net::TcpStream>,
pc_id: u8,
message_id: u16,
) {
use dcmnorm_dimse::pdu::PDataValueType::Command;
let command = dimse_command_bytes(&InMemDicomObject::command_from_element_iter([
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0FFF])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
]));
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dimse_pdv(pc_id, Command, true, command)],
})
.unwrap();
}
fn receive_raw_command(
association: &mut dcmnorm_dimse::ClientAssociation<std::net::TcpStream>,
) -> InMemDicomObject {
match association.receive_command().unwrap() {
dcmnorm_dimse::Incoming::Command { data, .. } => {
InMemDicomObject::read_dataset_with_ts(data.as_slice(), dimse_implicit_vr_le()).unwrap()
}
other => panic!("expected a DIMSE response, got {other:?}"),
}
}
fn receive_raw_find_responses(
association: &mut dcmnorm_dimse::ClientAssociation<std::net::TcpStream>,
) -> (Vec<String>, InMemDicomObject) {
let mut matches = Vec::new();
loop {
let response = receive_raw_command(association);
assert_eq!(
response
.element(tags::COMMAND_FIELD)
.unwrap()
.to_int::<u16>()
.unwrap(),
0x8020
);
let status = response
.element(tags::STATUS)
.unwrap()
.to_int::<u16>()
.unwrap();
if status != 0xFF00 && status != 0xFF01 {
return (matches, response);
}
let data = association.receive_data_set().unwrap();
let identifier =
InMemDicomObject::read_dataset_with_ts(data.as_slice(), dimse_implicit_vr_le())
.unwrap();
matches.push(
identifier
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned(),
);
}
}
fn response_status(response: &InMemDicomObject) -> u16 {
response
.element(tags::STATUS)
.unwrap()
.to_int::<u16>()
.unwrap()
}
fn mwl_identifier() -> InMemDicomObject {
let mut identifier = InMemDicomObject::new_empty();
identifier.put_str(tags::PATIENT_NAME, VR::PN, "");
identifier.put_str(tags::PATIENT_ID, VR::LO, "");
identifier.put_str(tags::ACCESSION_NUMBER, VR::SH, "");
identifier
}
fn study_identifier(patient_id: &str) -> InMemDicomObject {
let mut identifier = InMemDicomObject::new_empty();
identifier.put_str(tags::QUERY_RETRIEVE_LEVEL, VR::CS, "STUDY");
identifier.put_str(tags::PATIENT_ID, VR::LO, patient_id);
identifier.put_str(tags::STUDY_INSTANCE_UID, VR::UI, "");
identifier
}
#[test]
fn scp_answers_a_worklist_find_with_sop_class_not_supported_and_keeps_serving_the_association() {
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-mwl-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let handlers = std::sync::Arc::new(SopClassFindHandlers::new(
vec![study_match("1.2.3.4.5")],
None,
));
let logger = std::sync::Arc::new(MockLogger {
lines: std::sync::Mutex::new(Vec::new()),
});
let scp = start_scp(
0,
cache_dir.clone(),
handlers.clone(),
ScpOptions {
ae_title: "TEST-SCP".to_owned(),
on_log: Some(logger.clone()),
..Default::default()
},
)
.unwrap();
let object = read_dicom_file(fixture_path("sr.dcm")).unwrap();
let storage_sop_class = object
.meta()
.media_storage_sop_class_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let sop_instance_uid = object
.meta()
.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let ts_uid = object
.meta()
.transfer_syntax()
.trim_end_matches('\0')
.to_owned();
let ts = {
use dcmnorm_encoding::TransferSyntaxIndex;
dcmnorm_transcode::TransferSyntaxRegistry
.get(&ts_uid)
.unwrap()
};
let implicit = uids::IMPLICIT_VR_LITTLE_ENDIAN.to_owned();
let mwl = uids::MODALITY_WORKLIST_INFORMATION_MODEL_FIND;
let study_root = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let patient_root = uids::PATIENT_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let mut association = dcmnorm_dimse::association::client::ClientAssociationOptions::new()
.calling_ae_title("MODALITY")
.called_ae_title("TEST-SCP")
.with_presentation_context(mwl, vec![implicit.clone()])
.with_presentation_context(study_root, vec![implicit.clone()])
.with_presentation_context(patient_root, vec![implicit.clone()])
.with_presentation_context(storage_sop_class.clone(), vec![ts_uid.clone()])
.read_timeout(std::time::Duration::from_secs(10))
.establish_with(&format!("127.0.0.1:{}", scp.local_port()))
.unwrap();
let mwl_pc = context_id(&association, mwl);
send_raw_find(&mut association, mwl_pc, mwl, 1, &mwl_identifier());
let (matches, final_response) = receive_raw_find_responses(&mut association);
assert!(
matches.is_empty(),
"an MWL query must not be answered with studies: {matches:?}"
);
assert_eq!(response_status(&final_response), 0x0122);
assert_eq!(
final_response
.element(tags::MESSAGE_ID_BEING_RESPONDED_TO)
.unwrap()
.to_int::<u16>()
.unwrap(),
1
);
let comment = final_response
.element(tags::ERROR_COMMENT)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
assert!(
comment.contains(mwl) && comment.len() <= 64,
"unexpected Error Comment {comment:?}"
);
assert!(
handlers.calls.lock().unwrap().is_empty(),
"the handler must not see a worklist query"
);
use dcmnorm_dimse::pdu::PDataValueType::{Command, Data};
let store_pc = context_id(&association, &storage_sop_class);
let mut data_set = Vec::new();
object.write_dataset_with_ts(&mut data_set, ts).unwrap();
let store = dimse_command_bytes(&InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, storage_sop_class.as_str()),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0001])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [2])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0000]),
),
DataElement::new(
tags::AFFECTED_SOP_INSTANCE_UID,
VR::UI,
dicom_value!(Str, sop_instance_uid.as_str()),
),
]));
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![
dimse_pdv(store_pc, Command, true, store),
dimse_pdv(store_pc, Data, true, data_set),
],
})
.unwrap();
let store_response = receive_raw_command(&mut association);
assert_eq!(
store_response
.element(tags::COMMAND_FIELD)
.unwrap()
.to_int::<u16>()
.unwrap(),
0x8001
);
assert_eq!(response_status(&store_response), 0x0000);
let study_pc = context_id(&association, study_root);
send_raw_find(
&mut association,
study_pc,
study_root,
3,
&study_identifier("MRN123"),
);
let (matches, final_response) = receive_raw_find_responses(&mut association);
assert_eq!(matches, vec!["1.2.3.4.5".to_owned()]);
assert_eq!(response_status(&final_response), 0x0000);
let patient_pc = context_id(&association, patient_root);
send_raw_find(
&mut association,
patient_pc,
patient_root,
4,
&study_identifier("MRN456"),
);
let (matches, final_response) = receive_raw_find_responses(&mut association);
assert_eq!(matches.len(), 1);
assert_eq!(response_status(&final_response), 0x0000);
association.release().unwrap();
let calls = handlers.calls.lock().unwrap().clone();
assert_eq!(calls.len(), 2);
assert_eq!(calls[0].0, study_root);
assert_eq!(
calls[0].1.get("PatientID").map(String::as_str),
Some("MRN123")
);
assert_eq!(calls[1].0, patient_root);
assert_eq!(
calls[1].1.get("PatientID").map(String::as_str),
Some("MRN456")
);
let lines = wait_for(|| {
let lines = logger.lines.lock().unwrap().clone();
lines
.iter()
.any(|line| line.contains("released"))
.then_some(lines)
});
assert!(
lines.iter().any(|line| line
== &format!("received C-FIND-RQ (message id 1); SOP class {mwl} not supported")),
"{lines:#?}"
);
assert!(
lines
.iter()
.any(|line| line == "sending C-FIND-RSP: 0 match(es), final status=0x0122"),
"{lines:#?}"
);
assert!(
lines.iter().any(|line| line
== &format!(
"received C-FIND-RQ (message id 3); query key(s): [PatientID]; SOP class {study_root}"
)),
"{lines:#?}"
);
assert!(
!lines.iter().any(|line| line.contains("closed")),
"the association must not close: {lines:#?}"
);
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
}
#[test]
fn scp_find_sop_classes_option_controls_which_find_reaches_the_handler() {
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-find-classes-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let handlers = std::sync::Arc::new(SopClassFindHandlers::new(vec![study_match("1.2.3")], None));
let study_root = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let patient_root = uids::PATIENT_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let scp = start_scp(
0,
cache_dir.clone(),
handlers.clone(),
ScpOptions {
find_sop_classes: vec![study_root.to_owned()],
..Default::default()
},
)
.unwrap();
let implicit = uids::IMPLICIT_VR_LITTLE_ENDIAN.to_owned();
let mut association = dcmnorm_dimse::association::client::ClientAssociationOptions::new()
.calling_ae_title("TEST-SCU")
.called_ae_title("ANY-SCP")
.with_presentation_context(patient_root, vec![implicit.clone()])
.read_timeout(std::time::Duration::from_secs(10))
.establish_with(&format!("127.0.0.1:{}", scp.local_port()))
.unwrap();
let pc = context_id(&association, patient_root);
send_raw_find(
&mut association,
pc,
patient_root,
1,
&study_identifier("MRN"),
);
let (matches, final_response) = receive_raw_find_responses(&mut association);
association.release().unwrap();
assert!(matches.is_empty());
assert_eq!(response_status(&final_response), 0x0122);
assert!(handlers.calls.lock().unwrap().is_empty());
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
}
#[test]
fn scp_c_cancel_during_find_ends_it_with_fe00_and_the_association_stays_usable() {
let cache_dir = std::env::temp_dir().join(format!(
"dcmnorm-scp-cancel-test-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&cache_dir).unwrap();
let (release_handler, gate) = std::sync::mpsc::channel();
let handlers = std::sync::Arc::new(SopClassFindHandlers::new(
vec![study_match("1.1"), study_match("1.2"), study_match("1.3")],
Some(gate),
));
let logger = std::sync::Arc::new(MockLogger {
lines: std::sync::Mutex::new(Vec::new()),
});
let scp = start_scp(
0,
cache_dir.clone(),
handlers.clone(),
ScpOptions {
ae_title: "TEST-SCP".to_owned(),
on_log: Some(logger.clone()),
..Default::default()
},
)
.unwrap();
let implicit = uids::IMPLICIT_VR_LITTLE_ENDIAN.to_owned();
let study_root = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND;
let mut association = dcmnorm_dimse::association::client::ClientAssociationOptions::new()
.calling_ae_title("TEST-SCU")
.called_ae_title("TEST-SCP")
.with_presentation_context(study_root, vec![implicit.clone()])
.with_presentation_context(uids::VERIFICATION, vec![implicit.clone()])
.read_timeout(std::time::Duration::from_secs(10))
.establish_with(&format!("127.0.0.1:{}", scp.local_port()))
.unwrap();
let find_pc = context_id(&association, study_root);
send_raw_find(
&mut association,
find_pc,
study_root,
7,
&study_identifier(""),
);
wait_for(|| (!handlers.calls.lock().unwrap().is_empty()).then_some(()));
send_raw_cancel(&mut association, find_pc, 7);
std::thread::sleep(std::time::Duration::from_millis(100));
release_handler.send(()).unwrap();
let (matches, final_response) = receive_raw_find_responses(&mut association);
assert!(
matches.is_empty(),
"matches sent after the C-CANCEL-RQ: {matches:?}"
);
assert_eq!(response_status(&final_response), 0xFE00);
assert_eq!(
final_response
.element(tags::MESSAGE_ID_BEING_RESPONDED_TO)
.unwrap()
.to_int::<u16>()
.unwrap(),
7
);
send_raw_cancel(&mut association, find_pc, 7);
let echo_pc = context_id(&association, uids::VERIFICATION);
dimse_send_client_echo(&mut association, echo_pc, 8);
let echo_response = receive_raw_command(&mut association);
assert_eq!(
echo_response
.element(tags::COMMAND_FIELD)
.unwrap()
.to_int::<u16>()
.unwrap(),
0x8030
);
assert_eq!(response_status(&echo_response), 0x0000);
send_raw_find(
&mut association,
find_pc,
study_root,
9,
&study_identifier(""),
);
let (matches, final_response) = receive_raw_find_responses(&mut association);
assert_eq!(
matches,
vec!["1.1".to_owned(), "1.2".to_owned(), "1.3".to_owned()]
);
assert_eq!(response_status(&final_response), 0x0000);
association.release().unwrap();
let lines = wait_for(|| {
let lines = logger.lines.lock().unwrap().clone();
lines
.iter()
.any(|line| line.contains("released"))
.then_some(lines)
});
assert!(
lines
.iter()
.any(|line| line == "received C-CANCEL-RQ (message id being responded to 7)"),
"{lines:#?}"
);
assert!(
lines
.iter()
.any(|line| line == "sending C-FIND-RSP: 0 match(es), final status=0xFE00"),
"{lines:#?}"
);
assert!(
lines
.iter()
.any(|line| line.contains("with no C-FIND in progress; ignored")),
"{lines:#?}"
);
assert!(
!lines.iter().any(|line| line.contains("closed")),
"the association must not close: {lines:#?}"
);
scp.stop();
fs::remove_dir_all(&cache_dir).ok();
}
fn dimse_send_client_echo(
association: &mut dcmnorm_dimse::ClientAssociation<std::net::TcpStream>,
pc_id: u8,
message_id: u16,
) {
use dcmnorm_dimse::pdu::PDataValueType::Command;
let command = dimse_command_bytes(&InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, uids::VERIFICATION),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0030])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [message_id])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
]));
association
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dimse_pdv(pc_id, Command, true, command)],
})
.unwrap();
}
fn encode_identifier(identifier: &InMemDicomObject) -> Vec<u8> {
let mut bytes = Vec::new();
identifier
.write_dataset_with_ts(&mut bytes, dimse_implicit_vr_le())
.unwrap();
bytes
}
fn identifier_strings(identifier: &InMemDicomObject, tag: Tag) -> Vec<String> {
identifier
.element(tag)
.unwrap()
.to_multi_str()
.unwrap()
.iter()
.cloned()
.collect()
}
#[test]
fn move_identifier_study_level_is_byte_for_byte_unchanged() {
let mut legacy = InMemDicomObject::new_empty();
legacy.put_str(tags::QUERY_RETRIEVE_LEVEL, VR::CS, "STUDY");
legacy.put_str(tags::STUDY_INSTANCE_UID, VR::UI, "1.2.3.4.5");
let legacy_bytes = encode_identifier(&legacy);
let expected: &[u8] = &[
0x08, 0x00, 0x52, 0x00, 0x06, 0x00, 0x00, 0x00, b'S', b'T', b'U', b'D', b'Y', b' ', 0x20,
0x00, 0x0D, 0x00, 0x0A, 0x00, 0x00, 0x00, b'1', b'.', b'2', b'.', b'3', b'.', b'4', b'.',
b'5', 0x00,
];
assert_eq!(legacy_bytes, expected);
for level in [None, Some(QueryRetrieveLevel::Study)] {
let identifier =
build_move_identifier("1.2.3.4.5", level.unwrap_or_default(), None, &[]).unwrap();
assert_eq!(encode_identifier(&identifier), expected);
}
let identifier = build_move_identifier(
"1.2.3.4.5",
QueryRetrieveLevel::Study,
Some("1.2.3.4.5.6"),
&["1.2.3.4.5.6.7".to_owned()],
)
.unwrap();
assert_eq!(encode_identifier(&identifier), expected);
assert!(build_move_identifier("not-a-uid", QueryRetrieveLevel::Study, None, &[]).is_ok());
}
#[test]
fn move_identifier_series_level_carries_series_instance_uid() {
let identifier =
build_move_identifier("1.2.3", QueryRetrieveLevel::Series, Some("1.2.3.4"), &[]).unwrap();
let decoded = InMemDicomObject::read_dataset_with_ts(
encode_identifier(&identifier).as_slice(),
dimse_implicit_vr_le(),
)
.unwrap();
assert_eq!(
decoded
.element(tags::QUERY_RETRIEVE_LEVEL)
.unwrap()
.to_str()
.unwrap(),
"SERIES"
);
assert_eq!(
decoded
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"1.2.3"
);
assert_eq!(
decoded
.element(tags::SERIES_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"1.2.3.4"
);
assert!(decoded.element(tags::SOP_INSTANCE_UID).is_err());
assert_eq!(decoded.iter().count(), 3);
}
#[test]
fn move_identifier_image_level_sends_sop_instance_uids_as_one_uid_list() {
let sop_instance_uids = vec![
"1.2.3.4.1".to_owned(),
"1.2.3.4.22".to_owned(),
"1.2.3.4.333".to_owned(),
];
let identifier = build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Image,
Some("1.2.3.4"),
&sop_instance_uids,
)
.unwrap();
let bytes = encode_identifier(&identifier);
let mut sop_element = vec![0x08, 0x00, 0x18, 0x00, 32, 0x00, 0x00, 0x00];
sop_element.extend_from_slice(b"1.2.3.4.1\\1.2.3.4.22\\1.2.3.4.333");
assert!(bytes
.windows(sop_element.len())
.any(|window| window == sop_element.as_slice()));
let decoded =
InMemDicomObject::read_dataset_with_ts(bytes.as_slice(), dimse_implicit_vr_le()).unwrap();
assert_eq!(
decoded
.element(tags::QUERY_RETRIEVE_LEVEL)
.unwrap()
.to_str()
.unwrap(),
"IMAGE"
);
assert_eq!(
decoded
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"1.2.3"
);
assert_eq!(
decoded
.element(tags::SERIES_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"1.2.3.4"
);
assert_eq!(
decoded.element(tags::SOP_INSTANCE_UID).unwrap().vr(),
VR::UI
);
assert_eq!(
decoded
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.value()
.multiplicity(),
3
);
assert_eq!(
identifier_strings(&decoded, tags::SOP_INSTANCE_UID),
sop_instance_uids
);
let identifier = build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Image,
Some("1.2.3.4"),
&["1.2.3.4.5".to_owned()],
)
.unwrap();
let bytes = encode_identifier(&identifier);
let mut sop_element = vec![0x08, 0x00, 0x18, 0x00, 10, 0x00, 0x00, 0x00];
sop_element.extend_from_slice(b"1.2.3.4.5\0");
assert!(bytes
.windows(sop_element.len())
.any(|window| window == sop_element.as_slice()));
}
#[test]
fn move_identifier_rejects_incomplete_or_malformed_lower_level_keys() {
let invalid = |result: Result<InMemDicomObject, DimseError>| match result {
Err(DimseError::InvalidMoveIdentifier(message)) => message,
Err(other) => panic!("expected InvalidMoveIdentifier, got {other}"),
Ok(_) => panic!("expected InvalidMoveIdentifier, got an identifier"),
};
assert!(invalid(build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Series,
None,
&[]
))
.contains("SeriesInstanceUID"));
assert!(invalid(build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Series,
Some(""),
&[]
))
.contains("SeriesInstanceUID"));
assert!(invalid(build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Image,
None,
&["1.2".to_owned()]
))
.contains("SeriesInstanceUID"));
assert!(invalid(build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Image,
Some("1.2.3.4"),
&[]
))
.contains("SOPInstanceUID"));
assert!(invalid(build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Image,
Some("1.2.3.4"),
&["1.2.3.4.5\\1.2.3.4.6".to_owned()],
))
.contains("SOPInstanceUID"));
assert!(invalid(build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Image,
Some("1.2.3.4"),
&["".to_owned()]
))
.contains("SOPInstanceUID"));
assert!(invalid(build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Series,
Some("1.2.3.4 "),
&[]
))
.contains("SeriesInstanceUID"));
assert!(invalid(build_move_identifier(
"1.2.3",
QueryRetrieveLevel::Series,
Some(&"1".repeat(65)),
&[]
))
.contains("SeriesInstanceUID"));
assert!(invalid(build_move_identifier(
"x.1",
QueryRetrieveLevel::Series,
Some("1.2.3.4"),
&[]
))
.contains("StudyInstanceUID"));
assert!(
build_move_identifier("1.2.3", QueryRetrieveLevel::Series, Some("1.02.3"), &[]).is_ok()
);
assert_eq!(
"series".parse::<QueryRetrieveLevel>().unwrap(),
QueryRetrieveLevel::Series
);
assert_eq!(
" IMAGE ".parse::<QueryRetrieveLevel>().unwrap(),
QueryRetrieveLevel::Image
);
assert_eq!(
"STUDY".parse::<QueryRetrieveLevel>().unwrap(),
QueryRetrieveLevel::Study
);
assert!(matches!(
"PATIENT".parse::<QueryRetrieveLevel>(),
Err(DimseError::InvalidMoveIdentifier(_))
));
}
fn move_scu_capturing_identifier(
level: QueryRetrieveLevel,
series_instance_uid: Option<&str>,
sop_instance_uids: &[&str],
) -> InMemDicomObject {
let abstract_syntax = uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_MOVE;
let (sender, receiver) = std::sync::mpsc::channel();
let (scp_handle, addr) = spawn_mock_scp(abstract_syntax, move |association| {
let pc = association.presentation_contexts()[0].clone();
let ts = {
use dcmnorm_encoding::TransferSyntaxIndex;
dcmnorm_transcode::TransferSyntaxRegistry
.get(&pc.transfer_syntax)
.unwrap()
};
let (pc_id, request, identifier_bytes) = dimse_recv_command_with_data(association);
let message_id = dimse_message_id(&request);
sender
.send(InMemDicomObject::read_dataset_with_ts(identifier_bytes.as_slice(), ts).unwrap())
.unwrap();
let final_response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, abstract_syntax),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
DataElement::new(
tags::NUMBER_OF_REMAINING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_COMPLETED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [2]),
),
DataElement::new(
tags::NUMBER_OF_FAILED_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
DataElement::new(
tags::NUMBER_OF_WARNING_SUBOPERATIONS,
VR::US,
dicom_value!(U16, [0]),
),
]);
dimse_send_command(association, pc_id, &final_response);
});
let result = move_scu(
&addr.to_string(),
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: Some("MOCK-SCP".to_owned()),
max_pdu_length: 16384,
timeout: Some(std::time::Duration::from_secs(10)),
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: None,
query_retrieve_level: Some(level),
series_instance_uid: series_instance_uid.map(str::to_owned),
sop_instance_uids: sop_instance_uids
.iter()
.map(|uid| (*uid).to_owned())
.collect(),
},
)
.unwrap();
assert_eq!(result.status, 0);
assert_eq!(result.completed, 2);
scp_handle.join().unwrap();
receiver.recv().unwrap()
}
#[test]
fn move_scu_series_level_sends_series_identifier_to_scp() {
let identifier =
move_scu_capturing_identifier(QueryRetrieveLevel::Series, Some("1.2.3.4.5.6"), &[]);
assert_eq!(
identifier
.element(tags::QUERY_RETRIEVE_LEVEL)
.unwrap()
.to_str()
.unwrap(),
"SERIES"
);
assert_eq!(
identifier
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"1.2.3.4.5"
);
assert_eq!(
identifier
.element(tags::SERIES_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"1.2.3.4.5.6"
);
assert!(identifier.element(tags::SOP_INSTANCE_UID).is_err());
}
#[test]
fn move_scu_image_level_sends_sop_instance_uid_list_to_scp() {
let identifier = move_scu_capturing_identifier(
QueryRetrieveLevel::Image,
Some("1.2.3.4.5.6"),
&["1.2.3.4.5.6.1", "1.2.3.4.5.6.2"],
);
assert_eq!(
identifier
.element(tags::QUERY_RETRIEVE_LEVEL)
.unwrap()
.to_str()
.unwrap(),
"IMAGE"
);
assert_eq!(
identifier
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"1.2.3.4.5"
);
assert_eq!(
identifier
.element(tags::SERIES_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"1.2.3.4.5.6"
);
assert_eq!(
identifier_strings(&identifier, tags::SOP_INSTANCE_UID),
vec!["1.2.3.4.5.6.1".to_owned(), "1.2.3.4.5.6.2".to_owned()]
);
}
#[test]
fn move_scu_rejects_invalid_level_options_before_connecting() {
let error = move_scu(
"127.0.0.1:1",
"MOVE-DEST",
"1.2.3.4.5",
MoveScuOptions {
calling_ae_title: "TEST-SCU".to_owned(),
called_ae_title: None,
max_pdu_length: 16384,
timeout: Some(std::time::Duration::from_secs(1)),
stale_data_path: None,
stale_data_timeout: None,
on_log: None,
cancel: None,
query_retrieve_level: Some(QueryRetrieveLevel::Image),
series_instance_uid: Some("1.2.3.4.5.6".to_owned()),
sop_instance_uids: Vec::new(),
},
)
.unwrap_err();
assert!(
matches!(error, DimseError::InvalidMoveIdentifier(_)),
"got {error}"
);
}
fn be_u16_bytes(values: &[u16]) -> Vec<u8> {
values
.iter()
.flat_map(|value| value.to_be_bytes())
.collect()
}
const BE_NESTED_SEQUENCE: Tag = Tag(0x0029, 0x1010);
const BE_NESTED_OW: Tag = Tag(0x0029, 0x1011);
const BE_SMALL_OW: Tag = Tag(0x0029, 0x1020);
const BE_OF: Tag = Tag(0x0029, 0x1021);
const BE_OD: Tag = Tag(0x0029, 0x1022);
const BE_OL: Tag = Tag(0x0029, 0x1023);
const BE_OB: Tag = Tag(0x0029, 0x1024);
const BE_OVERLAY_DATA: Tag = Tag(0x6000, 0x3000);
fn be_ramp(seed: u16, count: u16) -> Vec<u16> {
(0..count)
.map(|i| seed.wrapping_add(i.wrapping_mul(257)))
.collect()
}
fn write_big_endian_bulk_file() -> (PathBuf, Vec<u8>) {
use dcmnorm_core::value::Value as DicomValue;
use dcmnorm_core::Length;
let nested = |seed| {
InMemDicomObject::from_element_iter([DataElement::new(
BE_NESTED_OW,
VR::OW,
PrimitiveValue::U16(be_ramp(seed, 40).into()),
)])
};
let dataset = InMemDicomObject::from_element_iter([
DataElement::new(
tags::SOP_CLASS_UID,
VR::UI,
PrimitiveValue::from("1.2.840.10008.5.1.4.1.1.7"),
),
DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from("1.2.3.4.5.6.9"),
),
DataElement::new(
Tag(0x0029, 0x0010),
VR::LO,
PrimitiveValue::from("TESTCREATOR "),
),
DataElement::new(
BE_NESTED_SEQUENCE,
VR::SQ,
DicomValue::new_sequence(vec![nested(0x0102), nested(0x0304)], Length::UNDEFINED),
),
DataElement::new(
BE_SMALL_OW,
VR::OW,
PrimitiveValue::U16(be_ramp(0x0506, 4).into()),
),
DataElement::new(
BE_OF,
VR::OF,
PrimitiveValue::F32(
vec![1.5f32, -2.25, 3.125, 4.0, 5.5, 6.75, 7.0, 8.5, 9.25, 10.0].into(),
),
),
DataElement::new(
BE_OD,
VR::OD,
PrimitiveValue::F64(vec![1.5f64, -2.25, 3.125, 4.0, 5.5].into()),
),
DataElement::new(
BE_OL,
VR::OL,
PrimitiveValue::U32(
(0..12u32)
.map(|i| 0x0102_0304 + i)
.collect::<Vec<_>>()
.into(),
),
),
DataElement::new(
BE_OB,
VR::OB,
PrimitiveValue::U8((0..64u8).collect::<Vec<_>>().into()),
),
DataElement::new(
BE_OVERLAY_DATA,
VR::OW,
PrimitiveValue::U16(be_ramp(0x0708, 50).into()),
),
DataElement::new(
tags::PIXEL_DATA,
VR::OW,
PrimitiveValue::U16(be_ramp(0x090A, 200).into()),
),
]);
let path = temp_file_path("dcmnorm-big-endian-bulk");
write_dataset_as_dicom_file(dataset, &path, EXPLICIT_VR_BIG_ENDIAN_UID).unwrap();
let bytes = fs::read(&path).unwrap();
(path, bytes)
}
#[test]
fn big_endian_bulk_values_become_uris_at_their_file_bytes() {
let (path, bytes) = write_big_endian_bulk_file();
let mut expected_values = vec![
be_u16_bytes(&be_ramp(0x0102, 40)),
be_u16_bytes(&be_ramp(0x0304, 40)),
[1.5f32, -2.25, 3.125, 4.0, 5.5, 6.75, 7.0, 8.5, 9.25, 10.0]
.iter()
.flat_map(|v| v.to_be_bytes())
.collect(),
[1.5f64, -2.25, 3.125, 4.0, 5.5]
.iter()
.flat_map(|v| v.to_be_bytes())
.collect(),
(0..12u32)
.flat_map(|i| (0x0102_0304 + i).to_be_bytes())
.collect(),
(0..64u8).collect(),
be_u16_bytes(&be_ramp(0x0708, 50)),
be_u16_bytes(&be_ramp(0x090A, 200)),
];
expected_values.sort();
for (format, pixel_key, overlay_key, small_key) in [
(
DicomJsonFormat::Flat,
"PixelData",
"OverlayData",
"00291020",
),
(
DicomJsonFormat::Standard,
"7FE00010",
"60003000",
"00291020",
),
] {
let json = json_via_deferred_read(&path, format);
assert_eq!(
json_via_full_read_and_scan(&path, format),
json,
"{format:?}: the scan must agree with the parser"
);
let value: JsonValue = serde_json::from_str(&json).unwrap();
assert!(
value[pixel_key]["BulkDataURI"].is_string(),
"{format:?}: PixelData must be a URI"
);
assert!(
value[overlay_key]["BulkDataURI"].is_string(),
"{format:?}: OverlayData must be a URI"
);
assert!(
value[small_key]["InlineBinary"].is_string(),
"{format:?}: small OW stays inline"
);
let mut uris = Vec::new();
bulk_data_uris(&value, &mut uris);
let mut referenced: Vec<Vec<u8>> = uris
.iter()
.map(|&(offset, length)| bytes[offset..offset + length].to_vec())
.collect();
referenced.sort();
assert_eq!(
expected_values, referenced,
"{format:?}: URIs must reference each value's big-endian file bytes"
);
}
fs::remove_file(&path).ok();
}
fn assert_big_endian_round_trip_values(
original: &dcmnorm_object::DefaultDicomObject,
roundtrip: &dcmnorm_object::DefaultDicomObject,
) {
assert_eq!(
roundtrip.meta().transfer_syntax(),
EXPLICIT_VR_BIG_ENDIAN_UID
);
for tag in [
tags::PIXEL_DATA,
BE_OVERLAY_DATA,
BE_SMALL_OW,
BE_OF,
BE_OD,
BE_OL,
BE_OB,
] {
assert_eq!(
original.element(tag).unwrap().to_bytes().unwrap(),
roundtrip.element(tag).unwrap().to_bytes().unwrap(),
"{tag} changed",
);
}
assert_eq!(
roundtrip
.element(tags::PIXEL_DATA)
.unwrap()
.to_multi_int::<u16>()
.unwrap(),
be_ramp(0x090A, 200)
);
let nested = |object: &dcmnorm_object::DefaultDicomObject| -> Vec<Vec<u16>> {
object
.element(BE_NESTED_SEQUENCE)
.unwrap()
.items()
.unwrap()
.iter()
.map(|item| {
item.element(BE_NESTED_OW)
.unwrap()
.to_multi_int::<u16>()
.unwrap()
})
.collect()
};
assert_eq!(
nested(roundtrip),
vec![be_ramp(0x0102, 40), be_ramp(0x0304, 40)]
);
assert_eq!(nested(original), nested(roundtrip));
}
#[test]
fn big_endian_json_round_trips_without_swapping_values() {
let (path, bytes) = write_big_endian_bulk_file();
let original = read_dicom_file(&path).unwrap();
for format in [DicomJsonFormat::Flat, DicomJsonFormat::Standard] {
let with_uris = json_via_deferred_read(&path, format);
let options = DicomJsonReadOptions {
format,
bulk_data_source: Some(&bytes),
};
let mut roundtrip = read_dicom_json_with_options(&with_uris, options).unwrap();
assert_big_endian_round_trip_values(&original, &roundtrip);
let written = write_dicom_bytes(&mut roundtrip).unwrap();
assert_big_endian_round_trip_values(&original, &read_dicom_bytes(&written).unwrap());
let pixels = be_u16_bytes(&be_ramp(0x090A, 200));
assert!(
written.windows(pixels.len()).any(|window| window == pixels),
"{format:?}: written PixelData isn't big-endian"
);
let inline = dicom_file_to_json(
&path,
DicomJsonWriteOptions {
format,
bulk_data_mode: DicomJsonBulkDataMode::InlineBinary,
..Default::default()
},
)
.unwrap();
let roundtrip = read_dicom_json_with_options(
&inline,
DicomJsonReadOptions {
format,
bulk_data_source: None,
},
)
.unwrap();
assert_big_endian_round_trip_values(&original, &roundtrip);
}
fs::remove_file(&path).ok();
}
#[test]
fn transcoded_big_endian_fixture_round_trips_through_bulk_data_uris() {
let original = read_dicom_file(fixture_path("dx.dcm")).unwrap();
let mut big_endian = transcode_dcmnorm_object(&original, EXPLICIT_VR_BIG_ENDIAN_UID).unwrap();
let path = temp_file_path("dcmnorm-big-endian-dx");
write_dicom_file(&mut big_endian, &path).unwrap();
let bytes = fs::read(&path).unwrap();
let json = json_via_deferred_read(&path, DicomJsonFormat::Standard);
let value: JsonValue = serde_json::from_str(&json).unwrap();
assert!(value["7FE00010"]["BulkDataURI"].is_string());
let roundtrip = read_dicom_json_full_with_source(&json, &bytes).unwrap();
assert_eq!(
original
.element(tags::PIXEL_DATA)
.unwrap()
.to_multi_int::<u16>()
.unwrap(),
roundtrip
.element(tags::PIXEL_DATA)
.unwrap()
.to_multi_int::<u16>()
.unwrap(),
);
fs::remove_file(&path).ok();
}
fn standard_json_has_member(value: &JsonValue, member: &str) -> bool {
match value {
JsonValue::Object(map) => {
map.contains_key(member)
|| map
.values()
.any(|child| standard_json_has_member(child, member))
}
JsonValue::Array(items) => items
.iter()
.any(|child| standard_json_has_member(child, member)),
_ => false,
}
}
#[test]
fn omit_keyword_vm_leaves_only_ps3_18_members_at_every_level() {
let (path, bytes) = write_big_endian_bulk_file();
let standard = DicomJsonWriteOptions {
format: DicomJsonFormat::Standard,
bulk_data_mode: DicomJsonBulkDataMode::Uri,
..Default::default()
};
let default_json = dicom_file_to_json(&path, standard).unwrap();
let default_value: JsonValue = serde_json::from_str(&default_json).unwrap();
assert_eq!(
default_value["7FE00010"]["Keyword"], "PixelData",
"the default output keeps Keyword"
);
assert_eq!(
default_value["7FE00010"]["VM"], 1,
"the default output keeps VM"
);
let bare_json = dicom_file_to_json(
&path,
DicomJsonWriteOptions {
omit_keyword_vm: true,
..standard
},
)
.unwrap();
let bare: JsonValue = serde_json::from_str(&bare_json).unwrap();
assert!(!standard_json_has_member(&bare, "Keyword"), "{bare_json}");
assert!(!standard_json_has_member(&bare, "VM"), "{bare_json}");
assert_eq!(
bare["00080018"].as_object().unwrap().len(),
2,
"vr and Value only"
);
assert_eq!(
bare["00291010"]["Value"].as_array().unwrap().len(),
2,
"sequence items are still there"
);
assert!(bare["00291010"]["Value"][1]["00291011"]["BulkDataURI"].is_string());
let mut stripped = default_value.clone();
for attribute in stripped.as_object_mut().unwrap().values_mut() {
let attribute = attribute.as_object_mut().unwrap();
attribute.remove("Keyword");
attribute.remove("VM");
}
assert_eq!(stripped, bare);
let original = read_dicom_file(&path).unwrap();
assert_big_endian_round_trip_values(
&original,
&read_dicom_json_full_with_source(&bare_json, &bytes).unwrap(),
);
let flat = DicomJsonWriteOptions {
format: DicomJsonFormat::Flat,
..standard
};
assert_eq!(
dicom_file_to_json(&path, flat).unwrap(),
dicom_file_to_json(
&path,
DicomJsonWriteOptions {
omit_keyword_vm: true,
..flat
}
)
.unwrap(),
);
fs::remove_file(&path).ok();
}
fn issue_fixture(name: &str) -> Vec<u8> {
fixture_bytes(fixture_path(&format!("issues/{name}")))
}
fn issue_standard_json(bytes: &[u8]) -> JsonValue {
let object = read_dicom_bytes(bytes).unwrap();
let text = write_dicom_json_with_options(
&object,
DicomJsonWriteOptions {
format: DicomJsonFormat::Standard,
bulk_data_mode: DicomJsonBulkDataMode::Uri,
key_style: DicomJsonKeyStyle::Hex,
bulk_data_source: Some(bytes),
bulk_data_uri_base: Some("urn:test"),
omit_keyword_vm: true,
..Default::default()
},
)
.unwrap();
serde_json::from_str(&text).unwrap()
}
fn issue_standard_json_round_trip(json: &JsonValue) -> dcmnorm_object::DefaultDicomObject {
read_dicom_json_with_options(
&json.to_string(),
DicomJsonReadOptions {
format: DicomJsonFormat::Standard,
..Default::default()
},
)
.unwrap()
}
#[test]
fn issue_23_standard_json_writes_at_values_as_hex() {
let json = issue_standard_json(&issue_fixture("at_values.dcm"));
assert_eq!(
json["00280009"],
serde_json::json!({"vr": "AT", "Value": ["00181063", "00181065"]})
);
let object = issue_standard_json_round_trip(&json);
assert_eq!(
object
.element(tags::FRAME_INCREMENT_POINTER)
.unwrap()
.value()
.primitive()
.unwrap(),
&PrimitiveValue::Tags([Tag(0x0018, 0x1063), Tag(0x0018, 0x1065)].as_ref().into())
);
}
#[test]
fn issue_24_iso_2022_person_names_decode_to_unicode() {
for (name, text) in [
("charset_iso2022_ir87.dcm", "試験^文字"),
("charset_iso2022_ir149.dcm", "테스트^문자"),
] {
let bytes = issue_fixture(name);
let json = issue_standard_json(&bytes);
assert_eq!(
json["00100010"],
serde_json::json!({"vr": "PN", "Value": [{"Alphabetic": text}]}),
"{name}"
);
let mut object = read_dicom_bytes(&bytes).unwrap();
assert_eq!(
object
.element(tags::PATIENT_NAME)
.unwrap()
.to_str()
.unwrap(),
text
);
let written = write_dicom_bytes(&mut object).unwrap();
let reread = read_dicom_bytes(&written).unwrap();
assert_eq!(
reread
.element(tags::PATIENT_NAME)
.unwrap()
.to_str()
.unwrap(),
text,
"{name}"
);
let needle: &[u8] = if name.contains("87") {
b"\x1b$B;n83\x1b(B^\x1b$BJ8;z\x1b(B"
} else {
b"\x1b$)C\xc5\xd7\xbd\xba\xc6\xae^\x1b$)C\xb9\xae\xc0\xda"
};
assert!(
bytes.windows(needle.len()).any(|w| w == needle),
"{name}: fixture bytes"
);
assert!(
written.windows(needle.len()).any(|w| w == needle),
"{name}: written bytes"
);
}
}
#[test]
fn issue_25_odd_group_private_creator_is_lo_in_implicit_vr() {
let json = issue_standard_json(&issue_fixture("private_creator_50f1_implicit.dcm"));
assert_eq!(
json["50F10010"],
serde_json::json!({"vr": "LO", "Value": ["SYNTHETIC"]})
);
}
#[test]
fn issue_26_undefined_length_un_reads_as_implicit_vr_sequence() {
let bytes = issue_fixture("un_undefined_length_sequence.dcm");
let object = read_dicom_bytes(&bytes).unwrap();
let sequence = object.element(Tag(0x0011, 0x1010)).unwrap();
let items = sequence.items().expect("a sequence");
assert_eq!(items.len(), 1);
assert_eq!(
items[0]
.element(tags::SERIES_DESCRIPTION)
.unwrap()
.to_str()
.unwrap(),
"TEST"
);
assert_eq!(
object
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"2.25.91002"
);
assert_eq!(
object
.element(tags::SERIES_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap(),
"2.25.91003"
);
issue_standard_json(&bytes);
}
#[test]
fn issue_27_explicit_unsigned_voi_lut_descriptor_is_kept() {
let json = issue_standard_json(&issue_fixture("voi_lut_unsigned_after_rescale.dcm"));
assert_eq!(
json["00283010"]["Value"][0]["00283002"],
serde_json::json!({"vr": "US", "Value": [4, 40000, 16]})
);
}
#[test]
fn issue_28_standard_json_empty_sequence_and_null_components() {
let json = issue_standard_json(&issue_fixture("empty_values.dcm"));
assert_eq!(json["00081111"], serde_json::json!({"vr": "SQ"}));
assert_eq!(
json["00111010"],
serde_json::json!({"vr": "LO", "Value": ["one", null, "three"]})
);
let object = issue_standard_json_round_trip(&json);
assert_eq!(
object
.element(Tag(0x0011, 0x1010))
.unwrap()
.to_multi_str()
.unwrap()
.as_ref(),
["one", "", "three"]
);
assert_eq!(
object
.element(Tag(0x0008, 0x1111))
.unwrap()
.items()
.unwrap()
.len(),
0
);
let mut object = object;
object.put(DataElement::new(
tags::PATIENT_NAME,
VR::PN,
PrimitiveValue::Strs(["A^B".to_owned(), String::new()].as_ref().into()),
));
object.put(DataElement::new(
tags::REFERENCED_SERIES_SEQUENCE,
VR::SQ,
dcmnorm_core::value::DataSetSequence::from(vec![InMemDicomObject::new_empty()]),
));
let text = write_dicom_json_with_options(
&object,
DicomJsonWriteOptions {
format: DicomJsonFormat::Standard,
key_style: DicomJsonKeyStyle::Hex,
omit_keyword_vm: true,
..Default::default()
},
)
.unwrap();
let json: JsonValue = serde_json::from_str(&text).unwrap();
assert_eq!(
json["00100010"]["Value"],
serde_json::json!([{"Alphabetic": "A^B"}, null])
);
assert_eq!(
json["00081115"],
serde_json::json!({"vr": "SQ", "Value": [{}]})
);
}
#[test]
fn issue_29_jpeg2000_decode_corrects_bits_stored_to_codestream_precision() {
let output = transcode_dicom_bytes(
issue_fixture("j2k_codestream_precision_above_bits_stored.dcm"),
uids::EXPLICIT_VR_LITTLE_ENDIAN,
)
.unwrap();
let object = read_dicom_bytes(&output).unwrap();
assert_eq!(
object
.element(tags::BITS_STORED)
.unwrap()
.to_int::<u16>()
.unwrap(),
10
);
assert_eq!(
object
.element(tags::HIGH_BIT)
.unwrap()
.to_int::<u16>()
.unwrap(),
9
);
assert_eq!(
object
.element(tags::BITS_ALLOCATED)
.unwrap()
.to_int::<u16>()
.unwrap(),
16
);
let words: Vec<u16> = object
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.chunks_exact(2)
.map(|w| u16::from_le_bytes([w[0], w[1]]))
.collect();
assert_eq!(words, [0, 1, 256, 644]);
}
#[test]
fn jp2_wrapped_ybr_rct_fixture_with_marker_like_icc_bytes_renders_and_decodes() {
let expected: [u8; 12] = [255, 0, 0, 0, 255, 0, 0, 0, 255, 17, 128, 250];
let bytes = issue_fixture("jp2_ybr_rct_icc_marker_bytes.dcm");
let object = read_dicom_bytes(&bytes).unwrap();
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap();
assert_eq!(
image::load_from_memory(&rendered.bytes)
.unwrap()
.to_rgb8()
.as_raw()
.as_slice(),
expected
);
let native =
read_dicom_bytes(transcode_dicom_bytes(bytes, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap())
.unwrap();
assert_eq!(
native
.element(tags::PHOTOMETRIC_INTERPRETATION)
.unwrap()
.to_str()
.unwrap()
.trim(),
"RGB"
);
assert_eq!(
native
.element(tags::BITS_STORED)
.unwrap()
.to_int::<u16>()
.unwrap(),
8
);
assert_eq!(
native
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected
);
}
fn issue_jp2_box(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
let mut out = ((8 + payload.len()) as u32).to_be_bytes().to_vec();
out.extend_from_slice(kind);
out.extend_from_slice(payload);
out
}
fn issue_jp2_with_marker_like_icc(codestream: &[u8], components: u16) -> Vec<u8> {
let mut icc = vec![0x11u8; 128];
icc.extend_from_slice(&[0xFF, 0x51]);
icc.extend(std::iter::repeat_n(0x22, 38));
icc.push(0x97);
icc.extend_from_slice(&[0xFF, 0x52, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00]);
icc.extend(std::iter::repeat_n(0x33, 64));
let mut file = dcmnorm_jpeg2000::codestream::JP2_SIGNATURE.to_vec();
file.extend(issue_jp2_box(b"ftyp", b"jp2 \0\0\0\0jp2 "));
let mut ihdr = vec![0, 0, 0, 2, 0, 0, 0, 2];
ihdr.extend_from_slice(&components.to_be_bytes());
ihdr.extend_from_slice(&[7, 7, 0, 0]);
let mut header = issue_jp2_box(b"ihdr", &ihdr);
let mut colr = vec![2, 0, 0];
colr.extend_from_slice(&icc);
header.extend(issue_jp2_box(b"colr", &colr));
file.extend(issue_jp2_box(b"jp2h", &header));
file.extend(issue_jp2_box(b"jp2c", codestream));
file
}
#[test]
fn jp2_wrapped_jpeg2000_fragment_with_icc_profile_decodes_and_renders() {
use dcmnorm_core::value::PixelFragmentSequence;
let expected: [u8; 12] = [255, 0, 0, 0, 255, 0, 0, 0, 255, 17, 128, 250];
for target in ["1.2.840.10008.1.2.4.90", "1.2.840.10008.1.2.4.201"] {
let encoded = transcode_dicom_bytes(issue_fixture("rgb_planar_2x2.dcm"), target).unwrap();
let (_, fragments) = issue_fragments(&encoded);
let wrapped = issue_jp2_with_marker_like_icc(&fragments[0], 3);
let mut object = read_dicom_bytes(&encoded).unwrap();
object.put(DataElement::new(
tags::PIXEL_DATA,
VR::OB,
PixelFragmentSequence::new(Vec::new(), vec![wrapped]),
));
let bytes = write_dicom_bytes(&mut object).unwrap();
let native = transcode_dicom_bytes(bytes.clone(), uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap_or_else(|error| panic!("{target}: {error}"));
let native = read_dicom_bytes(&native).unwrap();
assert_eq!(
native
.element(tags::BITS_STORED)
.unwrap()
.to_int::<u16>()
.unwrap(),
8,
"{target}"
);
assert_eq!(
native
.element(tags::SAMPLES_PER_PIXEL)
.unwrap()
.to_int::<u16>()
.unwrap(),
3,
"{target}"
);
assert_eq!(
native
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected,
"{target}"
);
let object = read_dicom_bytes(&bytes).unwrap();
let rendered = render_dicom_frame(
&object,
RenderOutputFormat::Png,
&RenderPipelineOptions::default(),
)
.unwrap_or_else(|error| panic!("{target}: {error}"));
let image = image::load_from_memory(&rendered.bytes).unwrap().to_rgb8();
assert_eq!(image.as_raw().as_slice(), expected, "{target}");
}
}
fn issue_fragments(bytes: &[u8]) -> (Vec<u32>, Vec<Vec<u8>>) {
let object = read_dicom_bytes(bytes).unwrap();
let element = object.element(tags::PIXEL_DATA).unwrap();
let dcmnorm_core::value::Value::PixelSequence(sequence) = element.value() else {
panic!("expected encapsulated pixel data");
};
(
sequence.offset_table().to_vec(),
sequence.fragments().iter().map(|f| f.to_vec()).collect(),
)
}
fn issue_decode_interleaved(codestream: &[u8]) -> Vec<i32> {
let image = dcmnorm_jpeg2000::openjpeg::decode(codestream).unwrap();
let pixels = image.components[0].data.len();
(0..pixels)
.flat_map(|i| image.components.iter().map(move |c| c.data[i]))
.collect()
}
#[test]
fn issue_30_planar_rgb_encodes_to_jpeg2000_with_samples_in_place() {
for target in ["1.2.840.10008.1.2.4.201", "1.2.840.10008.1.2.4.90"] {
let output = transcode_dicom_bytes(issue_fixture("rgb_planar_1x2.dcm"), target).unwrap();
let object = read_dicom_bytes(&output).unwrap();
assert_eq!(
object
.element(tags::PLANAR_CONFIGURATION)
.unwrap()
.to_int::<u16>()
.unwrap(),
0,
"{target}"
);
let (_, fragments) = issue_fragments(&output);
assert_eq!(fragments.len(), 1);
assert_eq!(
issue_decode_interleaved(&fragments[0]),
[1, 2, 255, 4, 5, 254],
"{target}"
);
let native = transcode_dicom_bytes(&output, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
let native = read_dicom_bytes(&native).unwrap();
assert_eq!(
native
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
[1, 2, 255, 4, 5, 254]
);
}
}
#[test]
fn issue_31_multiframe_jpeg2000_encode_writes_complete_basic_offset_table() {
for target in ["1.2.840.10008.1.2.4.201", "1.2.840.10008.1.2.4.90"] {
let output =
transcode_dicom_bytes(issue_fixture("rgb_interleaved_1x2_2frames.dcm"), target)
.unwrap();
let (offsets, fragments) = issue_fragments(&output);
assert_eq!(fragments.len(), 2, "{target}");
assert!(
fragments.iter().all(|f| f.len() % 2 == 0),
"{target}: even fragments"
);
assert_eq!(offsets, [0, 8 + fragments[0].len() as u32], "{target}");
assert_eq!(
issue_decode_interleaved(&fragments[0]),
[1, 2, 255, 4, 5, 254]
);
assert_eq!(
issue_decode_interleaved(&fragments[1]),
[0, 1, 254, 3, 4, 253]
);
}
}
#[test]
fn issue_31_basic_offset_table_is_complete_or_empty() {
use super::io::basic_offset_table;
let fragments = vec![vec![0u8; 10], vec![0u8; 4], vec![0u8; 6]];
assert_eq!(basic_offset_table(&fragments, 3), [0, 18, 30]);
assert_eq!(basic_offset_table(&fragments[..1], 1), [0]);
assert!(basic_offset_table(&fragments, 1).is_empty());
assert!(basic_offset_table(&fragments[..1], 4).is_empty());
}
#[test]
fn issue_32_jpeg_baseline_rgb_without_color_marker_is_not_ycbcr_converted() {
for name in [
"jpeg_rgb_adobe_transform0.dcm",
"jpeg_rgb_no_color_marker.dcm",
] {
let output =
transcode_dicom_bytes(issue_fixture(name), uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
let object = read_dicom_bytes(&output).unwrap();
assert_eq!(
object
.element(tags::PHOTOMETRIC_INTERPRETATION)
.unwrap()
.to_str()
.unwrap(),
"RGB"
);
let pixels = object
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.to_vec();
assert_eq!(pixels.len(), 8 * 8 * 3);
for (i, pixel) in pixels.chunks_exact(3).enumerate() {
for (channel, expected) in [200i32, 50, 10].into_iter().enumerate() {
let delta = (i32::from(pixel[channel]) - expected).abs();
assert!(
delta <= 1,
"{name}: pixel {i} channel {channel} is {}, expected {expected}",
pixel[channel]
);
}
}
}
}
#[cfg(feature = "jpeg-xl-codec")]
#[test]
fn issue_3_jpeg_xl_lossless_encode_round_trips() {
const JXL_LOSSLESS: &str = "1.2.840.10008.1.2.4.110";
for name in ["mono12_3x4_2frames.dcm", "rgb_planar_2x2.dcm"] {
let source = issue_fixture(name);
let encoded = transcode_dicom_bytes(&source, JXL_LOSSLESS).unwrap();
let object = read_dicom_bytes(&encoded).unwrap();
assert_eq!(
object.meta().transfer_syntax().trim_end_matches('\0'),
JXL_LOSSLESS
);
let (offsets, fragments) = issue_fragments(&encoded);
let frames = if name.contains("2frames") { 2 } else { 1 };
assert_eq!(fragments.len(), frames, "{name}");
assert_eq!(offsets.len(), frames, "{name}: complete Basic Offset Table");
assert!(
fragments.iter().all(|f| f.starts_with(&[0xFF, 0x0A])),
"{name}: JPEG XL codestreams"
);
let decoded = transcode_dicom_bytes(&encoded, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
let decoded = read_dicom_bytes(&decoded).unwrap();
let original = read_dicom_bytes(&source).unwrap();
let expected = if name.starts_with("rgb") {
vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 17, 128, 250]
} else {
original
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.to_vec()
};
assert_eq!(
decoded
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected.as_slice(),
"{name}"
);
if name.starts_with("rgb") {
assert_eq!(
decoded
.element(tags::PLANAR_CONFIGURATION)
.unwrap()
.to_int::<u16>()
.unwrap(),
0
);
}
}
let one_row =
transcode_dicom_bytes(issue_fixture("rgb_planar_1x2.dcm"), JXL_LOSSLESS).unwrap_err();
assert!(one_row.to_string().contains("2x2"), "{one_row}");
let signed = transcode_dicom_bytes(
issue_fixture("voi_lut_unsigned_after_rescale.dcm"),
JXL_LOSSLESS,
)
.unwrap_err();
assert!(signed.to_string().contains("unsigned"), "{signed}");
}
#[test]
fn flat_and_standard_json_trim_padded_number_strings_alike() {
let mut object = read_dicom_bytes(issue_fixture("at_values.dcm")).unwrap();
object.put(DataElement::new(
tags::SERIES_NUMBER,
VR::IS,
PrimitiveValue::from(" 107".to_owned()),
));
object.put(DataElement::new(
tags::WINDOW_CENTER,
VR::DS,
PrimitiveValue::Strs(["1.5 ".to_owned(), " 2".to_owned()].as_ref().into()),
));
let flat: JsonValue = serde_json::from_str(&write_dicom_json(&object).unwrap()).unwrap();
assert_eq!(flat["SeriesNumber"], "107");
assert_eq!(flat["WindowCenter"], "1.5\\2");
let standard = write_dicom_json_with_options(
&object,
DicomJsonWriteOptions {
format: DicomJsonFormat::Standard,
key_style: DicomJsonKeyStyle::Hex,
omit_keyword_vm: true,
..Default::default()
},
)
.unwrap();
let standard: JsonValue = serde_json::from_str(&standard).unwrap();
assert_eq!(standard["00200011"]["Value"], serde_json::json!(["107"]));
assert_eq!(
standard["00281050"]["Value"],
serde_json::json!(["1.5", "2"])
);
}
fn hand_built_rle_frame(segments: &[&[u8]]) -> Vec<u8> {
let mut frame = vec![0u8; 64];
frame[..4].copy_from_slice(&(segments.len() as u32).to_le_bytes());
let mut offset = 64u32;
for (i, segment) in segments.iter().enumerate() {
frame[4 + 4 * i..8 + 4 * i].copy_from_slice(&offset.to_le_bytes());
offset += segment.len() as u32;
}
for segment in segments {
frame.extend_from_slice(segment);
}
frame
}
fn synthetic_rle_dicom(
rows: u16,
cols: u16,
bits_allocated: u16,
samples_per_pixel: u16,
planar_configuration: Option<u16>,
frames: Vec<Vec<u8>>,
) -> Vec<u8> {
use dcmnorm_core::value::PixelFragmentSequence;
use dcmnorm_object::FileMetaTableBuilder;
let photometric = if samples_per_pixel == 3 {
"RGB"
} else {
"MONOCHROME2"
};
let mut elements = vec![
DataElement::new(
tags::SOP_CLASS_UID,
VR::UI,
PrimitiveValue::from(uids::SECONDARY_CAPTURE_IMAGE_STORAGE),
),
DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from("2.25.110101"),
),
DataElement::new(
tags::SAMPLES_PER_PIXEL,
VR::US,
PrimitiveValue::from(samples_per_pixel),
),
DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from(photometric),
),
DataElement::new(tags::ROWS, VR::US, PrimitiveValue::from(rows)),
DataElement::new(tags::COLUMNS, VR::US, PrimitiveValue::from(cols)),
DataElement::new(
tags::BITS_ALLOCATED,
VR::US,
PrimitiveValue::from(bits_allocated),
),
DataElement::new(
tags::BITS_STORED,
VR::US,
PrimitiveValue::from(bits_allocated),
),
DataElement::new(
tags::HIGH_BIT,
VR::US,
PrimitiveValue::from(bits_allocated - 1),
),
DataElement::new(
tags::PIXEL_REPRESENTATION,
VR::US,
PrimitiveValue::from(0u16),
),
];
if frames.len() > 1 {
elements.push(DataElement::new(
tags::NUMBER_OF_FRAMES,
VR::IS,
PrimitiveValue::from(frames.len().to_string()),
));
}
if let Some(planar_configuration) = planar_configuration {
elements.push(DataElement::new(
tags::PLANAR_CONFIGURATION,
VR::US,
PrimitiveValue::from(planar_configuration),
));
}
elements.push(DataElement::new(
tags::PIXEL_DATA,
VR::OB,
PixelFragmentSequence::new(Vec::new(), frames),
));
let mut object = InMemDicomObject::from_element_iter(elements)
.with_meta(
FileMetaTableBuilder::new()
.media_storage_sop_class_uid(uids::SECONDARY_CAPTURE_IMAGE_STORAGE)
.media_storage_sop_instance_uid("2.25.110101")
.transfer_syntax(uids::RLE_LOSSLESS),
)
.unwrap();
write_dicom_bytes(&mut object).unwrap()
}
fn assert_rle_transcodes_to(input: Vec<u8>, expected: &[u8]) -> dcmnorm_object::DefaultDicomObject {
let output = transcode_dicom_bytes(input, uids::EXPLICIT_VR_LITTLE_ENDIAN).unwrap();
let object = read_dicom_bytes(&output).unwrap();
assert_eq!(
object.meta().transfer_syntax().trim_end_matches('\0'),
uids::EXPLICIT_VR_LITTLE_ENDIAN
);
let pixel_data = object
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap();
assert_eq!(pixel_data.as_ref(), expected);
object
}
#[test]
fn rle_8_bit_monochrome_transcodes_to_the_exact_samples() {
let frame = hand_built_rle_frame(&[&[0x01, 0x11, 0x22, 0x01, 0x33, 0x44]]);
let input = synthetic_rle_dicom(2, 2, 8, 1, None, vec![frame]);
assert_rle_transcodes_to(input, &[17, 34, 51, 68]);
}
#[test]
fn rle_8_bit_monochrome_with_odd_width_padding_and_a_replicate_run_transcodes_exactly() {
let segment: &[u8] = &[0x01, 10, 11, 0x00, 12, 0xFE, 5, 0x00];
let input = synthetic_rle_dicom(2, 3, 8, 1, None, vec![hand_built_rle_frame(&[segment])]);
assert_rle_transcodes_to(input, &[10, 11, 12, 5, 5, 5]);
}
#[test]
fn rle_16_bit_monochrome_transcodes_to_little_endian_samples() {
let msb: &[u8] = &[0x01, 0x01, 0x03, 0x01, 0xFF, 0x00];
let lsb: &[u8] = &[0x01, 0x02, 0x04, 0x01, 0x00, 0xFF];
let input = synthetic_rle_dicom(2, 2, 16, 1, None, vec![hand_built_rle_frame(&[msb, lsb])]);
assert_rle_transcodes_to(input, &[0x02, 0x01, 0x04, 0x03, 0x00, 0xFF, 0xFF, 0x00]);
}
#[test]
fn rle_8_bit_rgb_transcodes_to_interleaved_pixels() {
let red: &[u8] = &[0x01, 1, 4, 0x00];
let green: &[u8] = &[0x01, 2, 5, 0x00];
let blue: &[u8] = &[0xFF, 7];
for planar_configuration in [None, Some(0), Some(1)] {
let frame = hand_built_rle_frame(&[red, green, blue]);
let input = synthetic_rle_dicom(1, 2, 8, 3, planar_configuration, vec![frame]);
let object = assert_rle_transcodes_to(input, &[1, 2, 7, 4, 5, 7]);
assert_eq!(
object
.element(tags::PLANAR_CONFIGURATION)
.unwrap()
.uint16()
.unwrap(),
0
);
}
}
#[test]
fn rle_16_bit_rgb_transcodes_to_little_endian_interleaved_pixels() {
let frame = hand_built_rle_frame(&[
&[0x01, 0x11, 0x77],
&[0x01, 0x22, 0x88],
&[0x01, 0x33, 0x99],
&[0x01, 0x44, 0xAA],
&[0x01, 0x55, 0xBB],
&[0x01, 0x66, 0xCC],
]);
let input = synthetic_rle_dicom(1, 2, 16, 3, Some(1), vec![frame]);
assert_rle_transcodes_to(
input,
&[
0x22, 0x11, 0x44, 0x33, 0x66, 0x55, 0x88, 0x77, 0xAA, 0x99, 0xCC, 0xBB,
],
);
}
#[test]
fn rle_multi_frame_8_bit_monochrome_transcodes_every_frame_exactly() {
let frames = vec![
hand_built_rle_frame(&[&[0x01, 0x11, 0x22, 0x01, 0x33, 0x44]]),
hand_built_rle_frame(&[&[0xFF, 9, 0xFF, 10]]),
hand_built_rle_frame(&[&[0x01, 0, 255, 0x01, 128, 1]]),
];
let input = synthetic_rle_dicom(2, 2, 8, 1, None, frames);
assert_rle_transcodes_to(input, &[17, 34, 51, 68, 9, 9, 10, 10, 0, 255, 128, 1]);
}
#[test]
fn rle_with_a_segment_count_mismatch_fails_to_transcode() {
let frame = hand_built_rle_frame(&[&[0x01, 1, 2], &[0x01, 3, 4]]);
let input = synthetic_rle_dicom(1, 2, 8, 1, None, vec![frame]);
assert!(transcode_dicom_bytes(input, uids::EXPLICIT_VR_LITTLE_ENDIAN).is_err());
}
fn synthetic_multiframe_u16_dimse_object(
sop_instance_uid: &str,
study_instance_uid: &str,
vr: VR,
rows: u16,
cols: u16,
frames: usize,
) -> (dcmnorm_object::DefaultDicomObject, Vec<u8>) {
let mut raw_le = Vec::with_capacity(usize::from(rows) * usize::from(cols) * frames * 2);
let mut raw_words = Vec::with_capacity(usize::from(rows) * usize::from(cols) * frames);
for f in 0..frames {
for r in 0..usize::from(rows) {
for c in 0..usize::from(cols) {
let sample = ((f * 173 + r * 19 + c * 7) & 0x03FF) as u16;
raw_words.push(sample);
raw_le.extend_from_slice(&sample.to_le_bytes());
}
}
}
let meta = dcmnorm_object::FileMetaTableBuilder::new()
.transfer_syntax(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.media_storage_sop_class_uid(uids::DIGITAL_MAMMOGRAPHY_X_RAY_IMAGE_STORAGE_FOR_PRESENTATION)
.media_storage_sop_instance_uid(sop_instance_uid);
let mut obj = InMemDicomObject::new_empty().with_meta(meta).unwrap();
for elem in [
DataElement::new(
tags::SOP_CLASS_UID,
VR::UI,
PrimitiveValue::from(
uids::DIGITAL_MAMMOGRAPHY_X_RAY_IMAGE_STORAGE_FOR_PRESENTATION.to_owned(),
),
),
DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(sop_instance_uid.to_owned()),
),
DataElement::new(
tags::STUDY_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(study_instance_uid.to_owned()),
),
DataElement::new(
tags::SERIES_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(format!("{study_instance_uid}.1")),
),
DataElement::new(
tags::MODALITY,
VR::CS,
PrimitiveValue::from("MG".to_owned()),
),
DataElement::new(tags::ROWS, VR::US, PrimitiveValue::from(rows)),
DataElement::new(tags::COLUMNS, VR::US, PrimitiveValue::from(cols)),
DataElement::new(tags::SAMPLES_PER_PIXEL, VR::US, PrimitiveValue::from(1u16)),
DataElement::new(tags::BITS_ALLOCATED, VR::US, PrimitiveValue::from(16u16)),
DataElement::new(tags::BITS_STORED, VR::US, PrimitiveValue::from(10u16)),
DataElement::new(tags::HIGH_BIT, VR::US, PrimitiveValue::from(9u16)),
DataElement::new(
tags::PIXEL_REPRESENTATION,
VR::US,
PrimitiveValue::from(0u16),
),
DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from("MONOCHROME2".to_owned()),
),
DataElement::new(
tags::NUMBER_OF_FRAMES,
VR::IS,
PrimitiveValue::from(frames.to_string()),
),
] {
obj.put(elem);
}
let mut icon = InMemDicomObject::new_empty();
icon.put(DataElement::new(
tags::ROWS,
VR::US,
PrimitiveValue::from(2u16),
));
icon.put(DataElement::new(
tags::COLUMNS,
VR::US,
PrimitiveValue::from(2u16),
));
icon.put(DataElement::new(
tags::PIXEL_DATA,
VR::OB,
PrimitiveValue::from(vec![11u8, 22, 33, 44]),
));
obj.put(DataElement::new(
Tag(0x0088, 0x0200),
VR::SQ,
dcmnorm_core::value::Value::Sequence(dcmnorm_core::value::DataSetSequence::from(vec![
icon,
])),
));
obj.put(DataElement::new(
Tag(0xFFFC, 0xFFFC),
VR::OB,
PrimitiveValue::from(vec![0xDEu8, 0xAD, 0xBE, 0xEF]),
));
let pixel_val = if vr == VR::OB {
PrimitiveValue::from(raw_le.clone())
} else {
PrimitiveValue::U16(raw_words.into())
};
obj.put(DataElement::new(tags::PIXEL_DATA, vr, pixel_val));
(obj, raw_le)
}
fn empty_test_scp_handlers() -> std::sync::Arc<TestScpHandlers> {
std::sync::Arc::new(TestScpHandlers {
find_query: std::sync::Mutex::new(None),
find_response: Vec::new(),
move_calls: std::sync::Mutex::new(Vec::new()),
move_result: true,
association_complete: std::sync::Mutex::new(None),
})
}
fn unique_dimse_temp_dir(label: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"dcmnorm-{label}-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn store_scu_and_scp_stream_multiframe_native_passthrough() {
let dir = unique_dimse_temp_dir("stream-passthrough");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
let study_uid = "1.2.826.0.1.3680043.8.498.10001";
let (mut ob_obj, ob_pixels) = synthetic_multiframe_u16_dimse_object(
"1.2.826.0.1.3680043.8.498.10001.1",
study_uid,
VR::OB,
128,
128,
4,
);
let (mut ow_obj, ow_pixels) = synthetic_multiframe_u16_dimse_object(
"1.2.826.0.1.3680043.8.498.10001.2",
study_uid,
VR::OW,
128,
128,
4,
);
let ob_path = dir.join("in_ob.dcm");
let ow_path = dir.join("in_ow.dcm");
write_dicom_file(&mut ob_obj, &ob_path).unwrap();
write_dicom_file(&mut ow_obj, &ow_path).unwrap();
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "STREAM-SCP".to_owned(),
..Default::default()
},
)
.unwrap();
let dest = format!("127.0.0.1:{}", scp.local_port());
let results = store_scu(
&dest,
&[ob_path, ow_path],
StoreScuOptions {
calling_ae_title: "STREAM-SCU".to_owned(),
called_ae_title: Some("STREAM-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 2);
assert!(results.iter().all(|r| r.status == 0));
for (sop_uid, expected_pixels) in [
("1.2.826.0.1.3680043.8.498.10001.1", &ob_pixels),
("1.2.826.0.1.3680043.8.498.10001.2", &ow_pixels),
] {
let stored_path = cache_dir
.join(format!("S_{study_uid}"))
.join(format!("MG_{sop_uid}.dcm"));
let stored = read_dicom_file(&stored_path).unwrap();
assert_eq!(
stored.meta().transfer_syntax().trim_end_matches('\0'),
uids::EXPLICIT_VR_LITTLE_ENDIAN
);
assert_eq!(
stored
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected_pixels.as_slice()
);
assert_eq!(
stored
.element(Tag(0xFFFC, 0xFFFC))
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
&[0xDE, 0xAD, 0xBE, 0xEF]
);
assert!(stored.element(Tag(0x0088, 0x0200)).is_ok());
}
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn store_scu_streams_multiframe_encapsulated_fallback_transcode() {
use dcmnorm_encoding::TransferSyntaxIndex;
use dcmnorm_transcode::TransferSyntaxRegistry;
let dir = unique_dimse_temp_dir("stream-scu-fallback");
let study_uid = "1.2.826.0.1.3680043.8.498.10002";
let sop_uid = "1.2.826.0.1.3680043.8.498.10002.1";
let (mut native_obj, expected_pixels) =
synthetic_multiframe_u16_dimse_object(sop_uid, study_uid, VR::OW, 128, 128, 4);
let raw_path = dir.join("raw.dcm");
let htj2k_path = dir.join("htj2k.dcm");
write_dicom_file(&mut native_obj, &raw_path).unwrap();
crate::dicom_io::transcode_dicom_file(&raw_path, &htj2k_path, "1.2.840.10008.1.2.4.201")
.unwrap();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let sop_class = uids::DIGITAL_MAMMOGRAPHY_X_RAY_IMAGE_STORAGE_FOR_PRESENTATION.to_owned();
let expected_pixels_clone = expected_pixels.clone();
let scp_handle = std::thread::spawn(move || {
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("NATIVE-ONLY-SCP")
.with_abstract_syntax(sop_class.clone())
.with_transfer_syntax(uids::EXPLICIT_VR_LITTLE_ENDIAN);
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let (pc_id, request, dataset_bytes) = dimse_recv_command_with_data(&mut association);
let ts = TransferSyntaxRegistry
.get(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap();
let parsed = InMemDicomObject::read_dataset_with_ts(dataset_bytes.as_slice(), ts).unwrap();
assert_eq!(
parsed
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected_pixels_clone.as_slice(),
);
assert_eq!(
parsed
.element(Tag(0xFFFC, 0xFFFC))
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
&[0xDE, 0xAD, 0xBE, 0xEF],
);
let message_id = dimse_message_id(&request);
let response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, sop_class),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8001])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(&mut association, pc_id, &response);
let pdu = association.receive().unwrap();
assert_eq!(pdu, dcmnorm_dimse::pdu::Pdu::ReleaseRQ);
association
.send(&dcmnorm_dimse::pdu::Pdu::ReleaseRP)
.unwrap();
});
let results = store_scu(
&addr.to_string(),
&[htj2k_path],
StoreScuOptions {
calling_ae_title: "STREAM-SCU".to_owned(),
called_ae_title: Some("NATIVE-ONLY-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: false,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].status, 0);
scp_handle.join().unwrap();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn scp_on_the_fly_transcodes_native_multiframe_to_htj2k() {
let dir = unique_dimse_temp_dir("scp-otf-native");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
let study_uid = "1.2.826.0.1.3680043.8.498.10003";
let (mut ob_obj, ob_pixels) = synthetic_multiframe_u16_dimse_object(
"1.2.826.0.1.3680043.8.498.10003.1",
study_uid,
VR::OB,
128,
128,
4,
);
let (mut ow_obj, ow_pixels) = synthetic_multiframe_u16_dimse_object(
"1.2.826.0.1.3680043.8.498.10003.2",
study_uid,
VR::OW,
128,
128,
4,
);
let ob_path = dir.join("ob.dcm");
let ow_path = dir.join("ow.dcm");
write_dicom_file(&mut ob_obj, &ob_path).unwrap();
write_dicom_file(&mut ow_obj, &ow_path).unwrap();
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "OTF-SCP".to_owned(),
max_pdu_length: 16384,
storage_transfer_syntax: Some("1.2.840.10008.1.2.4.201".to_owned()),
..Default::default()
},
)
.unwrap();
let dest = format!("127.0.0.1:{}", scp.local_port());
let results = store_scu(
&dest,
&[ob_path, ow_path],
StoreScuOptions {
calling_ae_title: "OTF-SCU".to_owned(),
called_ae_title: Some("OTF-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 2);
assert!(results.iter().all(|r| r.status == 0));
for (sop_uid, expected_pixels) in [
("1.2.826.0.1.3680043.8.498.10003.1", &ob_pixels),
("1.2.826.0.1.3680043.8.498.10003.2", &ow_pixels),
] {
let stored_path = cache_dir
.join(format!("S_{study_uid}"))
.join(format!("MG_{sop_uid}.dcm"));
let stored = read_dicom_file(&stored_path).unwrap();
assert_eq!(
stored.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.4.201"
);
let dcmnorm_core::value::Value::PixelSequence(seq) =
stored.element(tags::PIXEL_DATA).unwrap().value()
else {
panic!("expected encapsulated pixel data");
};
assert_eq!(seq.fragments().len(), 4);
assert_eq!(
seq.offset_table().len(),
4,
"Basic Offset Table should be populated for every frame",
);
assert_eq!(
stored
.element(Tag(0xFFFC, 0xFFFC))
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
&[0xDE, 0xAD, 0xBE, 0xEF]
);
assert!(stored.element(Tag(0x0088, 0x0200)).is_ok());
let decoded = crate::dicom_io::transcode_dcmnorm_object_owned(
stored,
uids::EXPLICIT_VR_LITTLE_ENDIAN,
)
.unwrap();
assert_eq!(
decoded
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected_pixels.as_slice(),
);
}
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[cfg(feature = "jpeg-ls-codec")]
#[test]
fn scp_on_the_fly_transcodes_encapsulated_multiframe_to_htj2k() {
let dir = unique_dimse_temp_dir("scp-otf-encap");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
let study_uid = "1.2.826.0.1.3680043.8.498.10004";
let sop_uid = "1.2.826.0.1.3680043.8.498.10004.1";
let (mut native_obj, expected_pixels) =
synthetic_multiframe_u16_dimse_object(sop_uid, study_uid, VR::OW, 128, 128, 4);
let raw_path = dir.join("raw.dcm");
let jpegls_path = dir.join("jpegls.dcm");
write_dicom_file(&mut native_obj, &raw_path).unwrap();
crate::dicom_io::transcode_dicom_file(&raw_path, &jpegls_path, uids::JPEGLS_LOSSLESS).unwrap();
let dx2_path = fixture_path("dx2.dcm");
let dx2_orig = read_dicom_file(&dx2_path).unwrap();
let dx2_sop_uid = dx2_orig
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' '])
.to_owned();
let dx2_study_uid = dx2_orig
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
let dx2_modality = dx2_orig
.element(tags::MODALITY)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
let dx2_expected_pixels =
crate::dicom_io::transcode_dcmnorm_object_owned(dx2_orig, uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap()
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.to_vec();
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "OTF-SCP".to_owned(),
max_pdu_length: 16384,
storage_transfer_syntax: Some("1.2.840.10008.1.2.4.201".to_owned()),
..Default::default()
},
)
.unwrap();
let dest = format!("127.0.0.1:{}", scp.local_port());
let results = store_scu(
&dest,
&[jpegls_path, dx2_path],
StoreScuOptions {
calling_ae_title: "OTF-SCU".to_owned(),
called_ae_title: Some("OTF-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 2);
assert!(results.iter().all(|r| r.status == 0));
let stored_jls = read_dicom_file(
cache_dir
.join(format!("S_{study_uid}"))
.join(format!("MG_{sop_uid}.dcm")),
)
.unwrap();
assert_eq!(
stored_jls.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.4.201"
);
let dcmnorm_core::value::Value::PixelSequence(jls_seq) =
stored_jls.element(tags::PIXEL_DATA).unwrap().value()
else {
panic!("expected encapsulated pixel data");
};
assert_eq!(jls_seq.offset_table().len(), 4);
assert_eq!(
stored_jls
.element(Tag(0xFFFC, 0xFFFC))
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
&[0xDE, 0xAD, 0xBE, 0xEF],
);
let decoded_jls = crate::dicom_io::transcode_dcmnorm_object_owned(
stored_jls,
uids::EXPLICIT_VR_LITTLE_ENDIAN,
)
.unwrap();
assert_eq!(
decoded_jls
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected_pixels.as_slice(),
);
let stored_dx2 = read_dicom_file(
cache_dir
.join(format!("S_{dx2_study_uid}"))
.join(format!("{dx2_modality}_{dx2_sop_uid}.dcm")),
)
.unwrap();
assert_eq!(
stored_dx2.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.4.201"
);
let decoded_dx2 = crate::dicom_io::transcode_dcmnorm_object_owned(
stored_dx2,
uids::EXPLICIT_VR_LITTLE_ENDIAN,
)
.unwrap();
assert_eq!(
decoded_dx2
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
dx2_expected_pixels.as_slice(),
);
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn scp_on_the_fly_transcode_passes_through_non_image_objects() {
let dir = unique_dimse_temp_dir("scp-otf-nonimage");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
let sr_path = fixture_path("sr.dcm");
let sr_orig = read_dicom_file(&sr_path).unwrap();
let sr_ts = sr_orig
.meta()
.transfer_syntax()
.trim_end_matches('\0')
.to_owned();
let sr_sop_uid = sr_orig
.meta()
.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' '])
.to_owned();
let sr_study_uid = sr_orig
.element(tags::STUDY_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
let sr_modality = sr_orig
.element(tags::MODALITY)
.unwrap()
.to_str()
.unwrap()
.trim()
.to_owned();
let study_uid = "1.2.826.0.1.3680043.8.498.10005";
let img_sop_uid = "1.2.826.0.1.3680043.8.498.10005.1";
let (mut img_obj, _) =
synthetic_multiframe_u16_dimse_object(img_sop_uid, study_uid, VR::OW, 32, 32, 2);
let img_path = dir.join("img.dcm");
write_dicom_file(&mut img_obj, &img_path).unwrap();
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "OTF-SCP".to_owned(),
max_pdu_length: 16384,
storage_transfer_syntax: Some("1.2.840.10008.1.2.4.201".to_owned()),
..Default::default()
},
)
.unwrap();
let dest = format!("127.0.0.1:{}", scp.local_port());
let results = store_scu(
&dest,
&[sr_path, img_path],
StoreScuOptions {
calling_ae_title: "OTF-SCU".to_owned(),
called_ae_title: Some("OTF-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 2);
assert!(results.iter().all(|r| r.status == 0));
let stored_sr = read_dicom_file(
cache_dir
.join(format!("S_{sr_study_uid}"))
.join(format!("{sr_modality}_{sr_sop_uid}.dcm")),
)
.unwrap();
assert_eq!(
stored_sr.meta().transfer_syntax().trim_end_matches('\0'),
sr_ts
);
let stored_img = read_dicom_file(
cache_dir
.join(format!("S_{study_uid}"))
.join(format!("MG_{img_sop_uid}.dcm")),
)
.unwrap();
assert_eq!(
stored_img.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.4.201"
);
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn scp_on_the_fly_transcode_drains_corrupt_dataset_and_keeps_association_alive() {
use dcmnorm_encoding::TransferSyntaxIndex;
use dcmnorm_transcode::TransferSyntaxRegistry;
let dir = unique_dimse_temp_dir("scp-otf-drain");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "OTF-SCP".to_owned(),
max_pdu_length: 16384,
storage_transfer_syntax: Some("1.2.840.10008.1.2.4.201".to_owned()),
..Default::default()
},
)
.unwrap();
let dest = format!("127.0.0.1:{}", scp.local_port());
let sop_class = uids::DIGITAL_MAMMOGRAPHY_X_RAY_IMAGE_STORAGE_FOR_PRESENTATION;
let mut assoc = dcmnorm_dimse::association::client::ClientAssociationOptions::new()
.calling_ae_title("DRAIN-SCU")
.called_ae_title("OTF-SCP")
.max_pdu_length(16384)
.with_presentation_context(sop_class, vec![uids::EXPLICIT_VR_LITTLE_ENDIAN.to_owned()])
.with_presentation_context(sop_class, vec!["1.2.840.10008.1.2.4.90".to_owned()])
.establish_with(&dest)
.unwrap();
let explicit_pc_id = assoc
.presentation_contexts()
.iter()
.find(|pc| pc.transfer_syntax == uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap()
.id;
let j2k_pc_id = assoc
.presentation_contexts()
.iter()
.find(|pc| pc.transfer_syntax == "1.2.840.10008.1.2.4.90")
.unwrap()
.id;
let bad_sop = "1.2.826.0.1.3680043.8.498.10006.1";
let bad_cmd = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, sop_class),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0001])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [1])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0000]),
),
DataElement::new(
tags::AFFECTED_SOP_INSTANCE_UID,
VR::UI,
dicom_value!(Str, bad_sop),
),
]);
let mut cmd_bytes = Vec::new();
bad_cmd
.write_dataset_with_ts(
&mut cmd_bytes,
TransferSyntaxRegistry
.get(uids::IMPLICIT_VR_LITTLE_ENDIAN)
.unwrap(),
)
.unwrap();
assoc
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: j2k_pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Command,
is_last: true,
data: cmd_bytes,
}],
})
.unwrap();
let bad_header = InMemDicomObject::from_element_iter([
DataElement::new(
tags::SOP_CLASS_UID,
VR::UI,
PrimitiveValue::from(sop_class.to_owned()),
),
DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(bad_sop.to_owned()),
),
DataElement::new(
tags::STUDY_INSTANCE_UID,
VR::UI,
PrimitiveValue::from("1.2.826.0.1.3680043.8.498.10006".to_owned()),
),
DataElement::new(
tags::MODALITY,
VR::CS,
PrimitiveValue::from("MG".to_owned()),
),
DataElement::new(tags::ROWS, VR::US, PrimitiveValue::from(16u16)),
DataElement::new(tags::COLUMNS, VR::US, PrimitiveValue::from(16u16)),
DataElement::new(tags::SAMPLES_PER_PIXEL, VR::US, PrimitiveValue::from(1u16)),
DataElement::new(tags::BITS_ALLOCATED, VR::US, PrimitiveValue::from(16u16)),
DataElement::new(tags::BITS_STORED, VR::US, PrimitiveValue::from(10u16)),
DataElement::new(tags::HIGH_BIT, VR::US, PrimitiveValue::from(9u16)),
DataElement::new(
tags::PIXEL_REPRESENTATION,
VR::US,
PrimitiveValue::from(0u16),
),
DataElement::new(
tags::PHOTOMETRIC_INTERPRETATION,
VR::CS,
PrimitiveValue::from("MONOCHROME2".to_owned()),
),
DataElement::new(
tags::NUMBER_OF_FRAMES,
VR::IS,
PrimitiveValue::from("2".to_owned()),
),
]);
let ts_j2k = TransferSyntaxRegistry
.get("1.2.840.10008.1.2.4.90")
.unwrap();
let ts_explicit = TransferSyntaxRegistry
.get(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap();
let mut bad_bytes = Vec::new();
bad_header
.write_dataset_with_ts(&mut bad_bytes, ts_j2k)
.unwrap();
bad_bytes.extend_from_slice(&[
0xE0, 0x7F, 0x10, 0x00, b'O', b'B', 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
]);
bad_bytes.extend_from_slice(&[0xFE, 0xFF, 0x00, 0xE0, 0x08, 0x00, 0x00, 0x00]); bad_bytes.extend_from_slice(&0u32.to_le_bytes());
bad_bytes.extend_from_slice(&12u32.to_le_bytes());
bad_bytes.extend_from_slice(&[0xFE, 0xFF, 0x0D, 0xE0, 0x00, 0x00, 0x00, 0x00]); bad_bytes.extend(std::iter::repeat_n(0x5Au8, 40_000));
{
let mut writer = assoc.send_pdata(j2k_pc_id);
std::io::Write::write_all(&mut writer, &bad_bytes).unwrap();
writer.finish().unwrap();
}
let rsp1_pdu = assoc.receive().unwrap();
let rsp1_bytes = match rsp1_pdu {
dcmnorm_dimse::pdu::Pdu::PData { data } => {
data.into_iter().flat_map(|v| v.data).collect::<Vec<u8>>()
}
other => panic!("expected C-STORE-RSP PData, got {other:?}"),
};
let rsp1 = InMemDicomObject::read_dataset_with_ts(
rsp1_bytes.as_slice(),
TransferSyntaxRegistry
.get(uids::IMPLICIT_VR_LITTLE_ENDIAN)
.unwrap(),
)
.unwrap();
assert_eq!(
rsp1.element(tags::STATUS).unwrap().uint16().unwrap(),
0xC000
);
for entry in fs::read_dir(&cache_dir).unwrap() {
let name = entry.unwrap().file_name().to_string_lossy().into_owned();
assert!(
!name.ends_with(".tmp"),
"unexpected leftover temp file: {name}"
);
}
let study_uid = "1.2.826.0.1.3680043.8.498.10006";
let good_sop = "1.2.826.0.1.3680043.8.498.10006.2";
let (good_obj, expected_pixels) =
synthetic_multiframe_u16_dimse_object(good_sop, study_uid, VR::OW, 64, 64, 2);
let good_cmd = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, sop_class),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0001])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [2])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0000]),
),
DataElement::new(
tags::AFFECTED_SOP_INSTANCE_UID,
VR::UI,
dicom_value!(Str, good_sop),
),
]);
let mut good_cmd_bytes = Vec::new();
good_cmd
.write_dataset_with_ts(
&mut good_cmd_bytes,
TransferSyntaxRegistry
.get(uids::IMPLICIT_VR_LITTLE_ENDIAN)
.unwrap(),
)
.unwrap();
assoc
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: explicit_pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Command,
is_last: true,
data: good_cmd_bytes,
}],
})
.unwrap();
{
let mut writer = assoc.send_pdata(explicit_pc_id);
good_obj
.write_dataset_with_ts(&mut writer, ts_explicit)
.unwrap();
writer.finish().unwrap();
}
let rsp2_pdu = assoc.receive().unwrap();
let rsp2_bytes = match rsp2_pdu {
dcmnorm_dimse::pdu::Pdu::PData { data } => {
data.into_iter().flat_map(|v| v.data).collect::<Vec<u8>>()
}
other => panic!("expected second C-STORE-RSP PData, got {other:?}"),
};
let rsp2 = InMemDicomObject::read_dataset_with_ts(
rsp2_bytes.as_slice(),
TransferSyntaxRegistry
.get(uids::IMPLICIT_VR_LITTLE_ENDIAN)
.unwrap(),
)
.unwrap();
assert_eq!(
rsp2.element(tags::STATUS).unwrap().uint16().unwrap(),
0x0000
);
assoc.release().unwrap();
let stored = read_dicom_file(
cache_dir
.join(format!("S_{study_uid}"))
.join(format!("MG_{good_sop}.dcm")),
)
.unwrap();
assert_eq!(
stored.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.4.201"
);
let decoded =
crate::dicom_io::transcode_dcmnorm_object_owned(stored, uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap();
assert_eq!(
decoded
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected_pixels.as_slice(),
);
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn store_scu_prefers_dataset_sop_uids_over_stale_file_meta_uids() {
let dir = unique_dimse_temp_dir("stale-file-meta-uids");
let stale_sop_class = uids::SECONDARY_CAPTURE_IMAGE_STORAGE;
let stale_sop_instance = "1.2.826.0.1.3680043.8.498.99999.1";
let real_sop_class = uids::DIGITAL_MAMMOGRAPHY_X_RAY_IMAGE_STORAGE_FOR_PRESENTATION;
let real_sop_instance = "1.2.826.0.1.3680043.8.498.99999.2";
let stale_meta = dcmnorm_object::FileMetaTableBuilder::new()
.transfer_syntax(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.media_storage_sop_class_uid(stale_sop_class)
.media_storage_sop_instance_uid(stale_sop_instance);
let obj = InMemDicomObject::from_element_iter([
DataElement::new(
tags::SOP_CLASS_UID,
VR::UI,
PrimitiveValue::from(real_sop_class.to_owned()),
),
DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(real_sop_instance.to_owned()),
),
DataElement::new(
tags::STUDY_INSTANCE_UID,
VR::UI,
PrimitiveValue::from("1.2.826.0.1.3680043.8.498.99999".to_owned()),
),
DataElement::new(
tags::SERIES_INSTANCE_UID,
VR::UI,
PrimitiveValue::from("1.2.826.0.1.3680043.8.498.99999.0".to_owned()),
),
DataElement::new(
tags::MODALITY,
VR::CS,
PrimitiveValue::from("MG".to_owned()),
),
])
.with_meta(stale_meta)
.unwrap();
let path = dir.join("stale_meta.dcm");
obj.write_to_file(&path).unwrap();
let mut file = fs::File::open(&path).unwrap();
let on_disk_meta = dcmnorm_object::FileMetaTable::read_from(&mut file)
.unwrap()
.unwrap();
assert_eq!(
on_disk_meta
.media_storage_sop_class_uid
.trim_end_matches(['\0', ' ']),
stale_sop_class
);
assert_eq!(
on_disk_meta
.media_storage_sop_instance_uid
.trim_end_matches(['\0', ' ']),
stale_sop_instance
);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let expected_class = real_sop_class.to_owned();
let expected_instance = real_sop_instance.to_owned();
let scp_handle = std::thread::spawn(move || {
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("UID-CHECK-SCP")
.with_abstract_syntax(expected_class.clone())
.with_transfer_syntax(uids::EXPLICIT_VR_LITTLE_ENDIAN);
let (stream, _) = listener.accept().unwrap();
let mut association = scp.establish(stream).unwrap();
let (pc_id, request, dataset_bytes) = dimse_recv_command_with_data(&mut association);
assert!(!dataset_bytes.is_empty());
assert_eq!(
request
.element(tags::AFFECTED_SOP_CLASS_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' ']),
expected_class,
);
assert_eq!(
request
.element(tags::AFFECTED_SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim_end_matches(['\0', ' ']),
expected_instance,
);
let message_id = dimse_message_id(&request);
let response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, expected_class),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8001])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(&mut association, pc_id, &response);
let pdu = association.receive().unwrap();
assert_eq!(pdu, dcmnorm_dimse::pdu::Pdu::ReleaseRQ);
association
.send(&dcmnorm_dimse::pdu::Pdu::ReleaseRP)
.unwrap();
});
let results = store_scu(
&addr.to_string(),
&[path],
StoreScuOptions {
calling_ae_title: "UID-CHECK-SCU".to_owned(),
called_ae_title: Some("UID-CHECK-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].status, 0);
assert_eq!(results[0].sop_instance_uid, real_sop_instance);
scp_handle.join().unwrap();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn scp_default_passthrough_rejects_truncated_pixel_data_and_preserves_existing_file() {
use dcmnorm_encoding::TransferSyntaxIndex;
use dcmnorm_transcode::TransferSyntaxRegistry;
let dir = unique_dimse_temp_dir("scp-truncated");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "TRUNC-SCP".to_owned(),
..Default::default()
},
)
.unwrap();
let dest = format!("127.0.0.1:{}", scp.local_port());
let study_uid = "1.2.826.0.1.3680043.8.498.20001";
let sop_uid = "1.2.826.0.1.3680043.8.498.20001.1";
let (mut good_obj, expected_pixels) =
synthetic_multiframe_u16_dimse_object(sop_uid, study_uid, VR::OW, 32, 32, 1);
let good_path = dir.join("good.dcm");
write_dicom_file(&mut good_obj, &good_path).unwrap();
let res = store_scu(
&dest,
&[good_path],
StoreScuOptions {
calling_ae_title: "TRUNC-SCU".to_owned(),
called_ae_title: Some("TRUNC-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(res[0].status, 0);
let stored_path = cache_dir
.join(format!("S_{study_uid}"))
.join(format!("MG_{sop_uid}.dcm"));
let original_bytes = fs::read(&stored_path).unwrap();
let sop_class = uids::DIGITAL_MAMMOGRAPHY_X_RAY_IMAGE_STORAGE_FOR_PRESENTATION;
let ts_implicit = TransferSyntaxRegistry
.get(uids::IMPLICIT_VR_LITTLE_ENDIAN)
.unwrap();
let ts_explicit = TransferSyntaxRegistry
.get(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap();
let mut assoc = dcmnorm_dimse::association::client::ClientAssociationOptions::new()
.calling_ae_title("TRUNC-SCU")
.called_ae_title("TRUNC-SCP")
.max_pdu_length(16384)
.with_presentation_context(sop_class, vec![uids::EXPLICIT_VR_LITTLE_ENDIAN.to_owned()])
.with_presentation_context(sop_class, vec![uids::JPEGLS_LOSSLESS.to_owned()])
.establish_with(&dest)
.unwrap();
let explicit_pc = assoc
.presentation_contexts()
.iter()
.find(|pc| pc.transfer_syntax == uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap()
.id;
let encap_pc = assoc
.presentation_contexts()
.iter()
.find(|pc| pc.transfer_syntax == uids::JPEGLS_LOSSLESS)
.unwrap()
.id;
let mut header_bytes = Vec::new();
let head_obj = InMemDicomObject::from_element_iter([
DataElement::new(
tags::SOP_CLASS_UID,
VR::UI,
PrimitiveValue::from(sop_class.to_owned()),
),
DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(sop_uid.to_owned()),
),
DataElement::new(
tags::STUDY_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(study_uid.to_owned()),
),
DataElement::new(
tags::SERIES_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(format!("{study_uid}.1")),
),
DataElement::new(
tags::MODALITY,
VR::CS,
PrimitiveValue::from("MG".to_owned()),
),
]);
head_obj
.write_dataset_with_ts(&mut header_bytes, ts_explicit)
.unwrap();
let mut trunc_native = header_bytes.clone();
trunc_native.extend_from_slice(&0x7FE0u16.to_le_bytes());
trunc_native.extend_from_slice(&0x0010u16.to_le_bytes());
trunc_native.extend_from_slice(b"OB");
trunc_native.extend_from_slice(&0u16.to_le_bytes());
trunc_native.extend_from_slice(&1024u32.to_le_bytes());
trunc_native.extend_from_slice(&[0xAA; 16]);
let mut trunc_encap = header_bytes;
trunc_encap.extend_from_slice(&0x7FE0u16.to_le_bytes());
trunc_encap.extend_from_slice(&0x0010u16.to_le_bytes());
trunc_encap.extend_from_slice(b"OB");
trunc_encap.extend_from_slice(&0u16.to_le_bytes());
trunc_encap.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
trunc_encap.extend_from_slice(&0xFFFEu16.to_le_bytes());
trunc_encap.extend_from_slice(&0xE000u16.to_le_bytes());
trunc_encap.extend_from_slice(&0u32.to_le_bytes());
trunc_encap.extend_from_slice(&0xFFFEu16.to_le_bytes());
trunc_encap.extend_from_slice(&0xE000u16.to_le_bytes());
trunc_encap.extend_from_slice(&4u32.to_le_bytes());
trunc_encap.extend_from_slice(&[1, 2, 3, 4]);
for (msg_id, pc_id, payload) in [
(1u16, explicit_pc, trunc_native),
(2u16, encap_pc, trunc_encap),
] {
let cmd = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, sop_class),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x0001])),
DataElement::new(tags::MESSAGE_ID, VR::US, dicom_value!(U16, [msg_id])),
DataElement::new(tags::PRIORITY, VR::US, dicom_value!(U16, [0])),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0000]),
),
DataElement::new(
tags::AFFECTED_SOP_INSTANCE_UID,
VR::UI,
dicom_value!(Str, sop_uid),
),
]);
let mut cmd_bytes = Vec::new();
cmd.write_dataset_with_ts(&mut cmd_bytes, ts_implicit)
.unwrap();
assoc
.send(&dcmnorm_dimse::pdu::Pdu::PData {
data: vec![dcmnorm_dimse::pdu::PDataValue {
presentation_context_id: pc_id,
value_type: dcmnorm_dimse::pdu::PDataValueType::Command,
is_last: true,
data: cmd_bytes,
}],
})
.unwrap();
{
let mut writer = assoc.send_pdata(pc_id);
std::io::Write::write_all(&mut writer, &payload).unwrap();
writer.finish().unwrap();
}
let rsp_pdu = assoc.receive().unwrap();
let rsp_bytes = match rsp_pdu {
dcmnorm_dimse::pdu::Pdu::PData { data } => {
data.into_iter().flat_map(|v| v.data).collect::<Vec<u8>>()
}
other => panic!("expected C-STORE-RSP, got {other:?}"),
};
let rsp =
InMemDicomObject::read_dataset_with_ts(rsp_bytes.as_slice(), ts_implicit).unwrap();
assert_eq!(rsp.element(tags::STATUS).unwrap().uint16().unwrap(), 0xC000);
}
assoc.release().unwrap();
assert_eq!(fs::read(&stored_path).unwrap(), original_bytes);
let stored = read_dicom_file(&stored_path).unwrap();
assert_eq!(
stored
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap()
.as_ref(),
expected_pixels.as_slice()
);
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn scp_rejects_invalid_storage_ts_at_startup_and_blocks_path_traversal() {
let dir = unique_dimse_temp_dir("scp-security");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
assert!(
start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "BAD-TS-SCP".to_owned(),
storage_transfer_syntax: Some("1.2.3.4.invalid".to_owned()),
..Default::default()
},
)
.is_err(),
"unknown storage_transfer_syntax should fail start_scp"
);
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "SEC-SCP".to_owned(),
..Default::default()
},
)
.unwrap();
let dest = format!("127.0.0.1:{}", scp.local_port());
let sop_uid = "1.2.826.0.1.3680043.8.498.20002.1";
let (mut evil_obj, _) = synthetic_multiframe_u16_dimse_object(
sop_uid,
"1.2.826.0.1.3680043.8.498.20002",
VR::OB,
8,
8,
1,
);
evil_obj.put(DataElement::new(
tags::MODALITY,
VR::CS,
PrimitiveValue::from("../../evil".to_owned()),
));
let evil_path = dir.join("evil.dcm");
write_dicom_file(&mut evil_obj, &evil_path).unwrap();
let results = store_scu(
&dest,
&[evil_path],
StoreScuOptions {
calling_ae_title: "SEC-SCU".to_owned(),
called_ae_title: Some("SEC-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0].status, 0xC000);
assert!(!dir.join(format!("evil_{sop_uid}.dcm")).exists());
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn scp_on_the_fly_preserves_multiframe_empty_bot_and_ineligible_encapsulated_streams() {
let dir = unique_dimse_temp_dir("scp-otf-fallback");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
let study_uid = "1.2.826.0.1.3680043.8.498.20003";
let sop_uid_split = "1.2.826.0.1.3680043.8.498.20003.1";
let rgb_obj = read_dicom_file(fixture_path("rgb_planar.dcm")).unwrap();
let jpeg_one =
crate::dicom_io::transcode_dcmnorm_object_owned(rgb_obj.clone(), "1.2.840.10008.1.2.4.50")
.unwrap();
let dcmnorm_core::value::Value::PixelSequence(orig_seq) =
jpeg_one.element(tags::PIXEL_DATA).unwrap().value()
else {
panic!("expected jpeg pixel sequence");
};
let frag_bytes = orig_seq.fragments()[0].clone();
let mid = (frag_bytes.len() / 2) & !1;
let mut split_obj = jpeg_one.clone();
split_obj.meta_mut().media_storage_sop_instance_uid = sop_uid_split.to_owned();
split_obj.put(DataElement::new(
tags::SOP_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(sop_uid_split.to_owned()),
));
split_obj.put(DataElement::new(
tags::STUDY_INSTANCE_UID,
VR::UI,
PrimitiveValue::from(study_uid.to_owned()),
));
split_obj.put(DataElement::new(
tags::MODALITY,
VR::CS,
PrimitiveValue::from("OT".to_owned()),
));
split_obj.put(DataElement::new(
tags::NUMBER_OF_FRAMES,
VR::IS,
PrimitiveValue::from("2".to_owned()),
));
split_obj.put(DataElement::new(
tags::PIXEL_DATA,
VR::OB,
dcmnorm_core::value::Value::PixelSequence(dcmnorm_core::value::PixelFragmentSequence::new(
Vec::new(), vec![
frag_bytes[..mid].to_vec(),
frag_bytes[mid..].to_vec(),
frag_bytes.clone(),
],
)),
));
let split_path = dir.join("split_empty_bot.dcm");
write_dicom_file(&mut split_obj, &split_path).unwrap();
let expected_input_fragments: Vec<Vec<u8>> = {
let written = read_dicom_file(&split_path).unwrap();
let dcmnorm_core::value::Value::PixelSequence(seq) =
written.element(tags::PIXEL_DATA).unwrap().value()
else {
panic!("expected pixel sequence");
};
seq.fragments().iter().map(|f| f.to_vec()).collect()
};
let scp_htj2k = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "OTF-HTJ2K".to_owned(),
storage_transfer_syntax: Some("1.2.840.10008.1.2.4.201".to_owned()),
..Default::default()
},
)
.unwrap();
let res = store_scu(
&format!("127.0.0.1:{}", scp_htj2k.local_port()),
&[split_path],
StoreScuOptions {
calling_ae_title: "OTF-SCU".to_owned(),
called_ae_title: Some("OTF-HTJ2K".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(res[0].status, 0);
let stored_split = read_dicom_file(
cache_dir
.join(format!("S_{study_uid}"))
.join(format!("OT_{sop_uid_split}.dcm")),
)
.unwrap();
assert_eq!(
stored_split.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.4.50"
);
let dcmnorm_core::value::Value::PixelSequence(stored_seq) =
stored_split.element(tags::PIXEL_DATA).unwrap().value()
else {
panic!("expected pixel sequence");
};
assert!(
stored_seq.offset_table().is_empty(),
"empty Basic Offset Table must be preserved"
);
assert_eq!(
stored_seq.fragments().len(),
3,
"all 3 fragments must be preserved intact"
);
for (idx, expected) in expected_input_fragments.iter().enumerate() {
assert_eq!(
stored_seq.fragments()[idx].as_slice(),
expected.as_slice(),
"stored fragment {idx} must match transmitted fragment byte-for-byte"
);
}
scp_htj2k.stop();
let _ = rgb_obj.meta();
let _ = fs::remove_dir_all(&dir);
}
#[cfg(feature = "jpeg-xl-codec")]
#[test]
fn scp_on_the_fly_falls_back_for_signed_htj2k_to_jxl() {
let dir = unique_dimse_temp_dir("scp-otf-signed-jxl");
let study_uid = "1.2.826.0.1.3680043.8.498.20003";
let sop_uid_signed = "1.2.826.0.1.3680043.8.498.20003.2";
let (mut signed_native, _) =
synthetic_multiframe_u16_dimse_object(sop_uid_signed, study_uid, VR::OW, 32, 32, 1);
signed_native.put(DataElement::new(
tags::PIXEL_REPRESENTATION,
VR::US,
PrimitiveValue::from(1u16),
));
let signed_raw_path = dir.join("signed_raw.dcm");
let signed_htj2k_path = dir.join("signed_htj2k.dcm");
write_dicom_file(&mut signed_native, &signed_raw_path).unwrap();
crate::dicom_io::transcode_dicom_file(
&signed_raw_path,
&signed_htj2k_path,
"1.2.840.10008.1.2.4.201",
)
.unwrap();
let cache_jxl = dir.join("cache_jxl");
fs::create_dir_all(&cache_jxl).unwrap();
let scp_jxl = start_scp(
0,
cache_jxl.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "OTF-JXL".to_owned(),
storage_transfer_syntax: Some("1.2.840.10008.1.2.4.110".to_owned()),
..Default::default()
},
)
.unwrap();
let res2 = store_scu(
&format!("127.0.0.1:{}", scp_jxl.local_port()),
&[signed_htj2k_path],
StoreScuOptions {
calling_ae_title: "OTF-SCU".to_owned(),
called_ae_title: Some("OTF-JXL".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(res2[0].status, 0);
let stored_signed = read_dicom_file(
cache_jxl
.join(format!("S_{study_uid}"))
.join(format!("MG_{sop_uid_signed}.dcm")),
)
.unwrap();
assert_eq!(
stored_signed
.meta()
.transfer_syntax()
.trim_end_matches('\0'),
"1.2.840.10008.1.2.4.201"
);
scp_jxl.stop();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn store_scu_reencodes_implicit_in_explicit_recovered_file_and_bounds_unlimited_peer_pdu() {
use dcmnorm_encoding::TransferSyntaxIndex;
use dcmnorm_transcode::TransferSyntaxRegistry;
let dir = unique_dimse_temp_dir("scu-implicit-in-explicit");
let sop_class = uids::DIGITAL_MAMMOGRAPHY_X_RAY_IMAGE_STORAGE_FOR_PRESENTATION;
let sop_uid = "1.2.826.0.1.3680043.8.498.20004.1";
let study_uid = "1.2.826.0.1.3680043.8.498.20004";
let ts_explicit = TransferSyntaxRegistry
.get(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.unwrap();
let ts_implicit = TransferSyntaxRegistry
.get(uids::IMPLICIT_VR_LITTLE_ENDIAN)
.unwrap();
let (obj, _) = synthetic_multiframe_u16_dimse_object(sop_uid, study_uid, VR::OB, 16, 16, 1);
let mismatched_path = dir.join("implicit_in_explicit.dcm");
{
let mut f = fs::File::create(&mismatched_path).unwrap();
obj.meta().write_to(&mut f).unwrap();
obj.write_dataset_with_ts(&mut f, ts_implicit).unwrap();
}
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let sop_class_owned = sop_class.to_owned();
let scp_handle = std::thread::spawn(move || {
let scp = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("STRICT-SCP")
.with_abstract_syntax(sop_class_owned.clone())
.with_transfer_syntax(uids::EXPLICIT_VR_LITTLE_ENDIAN);
let (stream, _) = listener.accept().unwrap();
let mut assoc = scp.establish(stream).unwrap();
let (pc_id, request, dataset_bytes) = dimse_recv_command_with_data(&mut assoc);
let parsed = InMemDicomObject::read_dataset_with_ts(dataset_bytes.as_slice(), ts_explicit)
.expect("SCU must re-encode recovered implicit-in-explicit file as Explicit VR LE");
assert_eq!(
parsed
.element(tags::SOP_INSTANCE_UID)
.unwrap()
.to_str()
.unwrap()
.trim(),
sop_uid
);
let message_id = dimse_message_id(&request);
let response = InMemDicomObject::command_from_element_iter([
DataElement::new(
tags::AFFECTED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, sop_class_owned),
),
DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8001])),
DataElement::new(
tags::MESSAGE_ID_BEING_RESPONDED_TO,
VR::US,
dicom_value!(U16, [message_id]),
),
DataElement::new(
tags::COMMAND_DATA_SET_TYPE,
VR::US,
dicom_value!(U16, [0x0101]),
),
DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
]);
dimse_send_command(&mut assoc, pc_id, &response);
let pdu = assoc.receive().unwrap();
assert_eq!(pdu, dcmnorm_dimse::pdu::Pdu::ReleaseRQ);
assoc.send(&dcmnorm_dimse::pdu::Pdu::ReleaseRP).unwrap();
});
let res = store_scu(
&addr.to_string(),
&[mismatched_path],
StoreScuOptions {
calling_ae_title: "STRICT-SCU".to_owned(),
called_ae_title: Some("STRICT-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(res[0].status, 0);
scp_handle.join().unwrap();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn scp_rejects_lossy_storage_targets_and_preserves_utf8_trailing_elements() {
let dir = unique_dimse_temp_dir("scp-otf-lossy-and-utf8");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
for lossy_uid in ["1.2.840.10008.1.2.4.81", "1.2.840.10008.1.2.4.91"] {
let err = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "LOSSY-SCP".to_owned(),
storage_transfer_syntax: Some(lossy_uid.to_owned()),
..Default::default()
},
)
.err()
.expect("lossy storage transfer syntax must be rejected");
assert!(
!err.to_string().is_empty(),
"expected descriptive rejection for {lossy_uid}"
);
}
let study_uid = "1.2.826.0.1.3680043.8.498.30001";
let sop_uid = "1.2.826.0.1.3680043.8.498.30001.1";
let (mut obj, _) = synthetic_multiframe_u16_dimse_object(sop_uid, study_uid, VR::OW, 32, 32, 1);
obj.put(DataElement::new(
tags::SPECIFIC_CHARACTER_SET,
VR::CS,
PrimitiveValue::from("ISO_IR 192".to_owned()),
));
let utf8_note = "Café — 日本語テスト";
obj.put(DataElement::new(
Tag(0x8001, 0x1010),
VR::LO,
PrimitiveValue::from(utf8_note.to_owned()),
));
let in_path = dir.join("utf8_trailing.dcm");
write_dicom_file(&mut obj, &in_path).unwrap();
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "UTF8-SCP".to_owned(),
storage_transfer_syntax: Some("1.2.840.10008.1.2.4.201".to_owned()),
..Default::default()
},
)
.unwrap();
let res = store_scu(
&format!("127.0.0.1:{}", scp.local_port()),
&[in_path],
StoreScuOptions {
calling_ae_title: "UTF8-SCU".to_owned(),
called_ae_title: Some("UTF8-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(res[0].status, 0);
let stored = read_dicom_file(
cache_dir
.join(format!("S_{study_uid}"))
.join(format!("MG_{sop_uid}.dcm")),
)
.unwrap();
assert_eq!(
stored.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.4.201"
);
assert_eq!(
stored
.element(Tag(0x8001, 0x1010))
.unwrap()
.to_str()
.unwrap()
.trim_end(),
utf8_note
);
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[cfg(feature = "jpeg-ls-codec")]
#[test]
fn scp_on_the_fly_jpegls_declines_16bit_allocated_8bit_stored() {
let dir = unique_dimse_temp_dir("scp-otf-jpegls-16-8");
let cache_dir = dir.join("cache");
fs::create_dir_all(&cache_dir).unwrap();
let study_uid = "1.2.826.0.1.3680043.8.498.20012";
let sop_uid = "1.2.826.0.1.3680043.8.498.20012.1";
let (mut obj, _) = synthetic_multiframe_u16_dimse_object(sop_uid, study_uid, VR::OW, 16, 16, 1);
let expected_pixels: Vec<u16> = (0u16..256).map(|i| (i * 13 + 5) & 0x00ff).collect();
obj.put(DataElement::new(
tags::BITS_ALLOCATED,
VR::US,
PrimitiveValue::from(16u16),
));
obj.put(DataElement::new(
tags::BITS_STORED,
VR::US,
PrimitiveValue::from(8u16),
));
obj.put(DataElement::new(
tags::HIGH_BIT,
VR::US,
PrimitiveValue::from(7u16),
));
obj.put(DataElement::new(
tags::PIXEL_DATA,
VR::OW,
PrimitiveValue::U16(expected_pixels.clone().into()),
));
let in_path = dir.join("u16_8bit_stored.dcm");
write_dicom_file(&mut obj, &in_path).unwrap();
let scp = start_scp(
0,
cache_dir.clone(),
empty_test_scp_handlers(),
ScpOptions {
ae_title: "JLS-16-8".to_owned(),
storage_transfer_syntax: Some("1.2.840.10008.1.2.4.80".to_owned()),
..Default::default()
},
)
.unwrap();
let res = store_scu(
&format!("127.0.0.1:{}", scp.local_port()),
&[in_path],
StoreScuOptions {
calling_ae_title: "JLS-SCU".to_owned(),
called_ae_title: Some("JLS-16-8".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: None,
on_log: None,
cancel: None,
},
)
.unwrap();
assert_eq!(res[0].status, 0);
let stored = read_dicom_file(
cache_dir
.join(format!("S_{study_uid}"))
.join(format!("MG_{sop_uid}.dcm")),
)
.unwrap();
assert_eq!(
stored.meta().transfer_syntax().trim_end_matches('\0'),
"1.2.840.10008.1.2.1",
"16-bit allocated with <= 8 bits stored must fall back to native passthrough instead of mis-encoding with CharLS"
);
let stored_bytes = stored
.element(tags::PIXEL_DATA)
.unwrap()
.to_bytes()
.unwrap();
let stored_pixels: Vec<u16> = stored_bytes
.chunks_exact(2)
.map(|c| u16::from_le_bytes([c[0], c[1]]))
.collect();
assert_eq!(stored_pixels, expected_pixels);
scp.stop();
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn store_scu_cancel_terminates_large_streaming_send() {
use std::io::Read;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
let dir = unique_dimse_temp_dir("scu-cancel-mid-send");
let sop_uid = "1.2.826.0.1.3680043.8.498.20099.1";
let study_uid = "1.2.826.0.1.3680043.8.498.20099";
let (mut obj, _) =
synthetic_multiframe_u16_dimse_object(sop_uid, study_uid, VR::OW, 512, 512, 8);
let in_path = dir.join("large_cancel.dcm");
write_dicom_file(&mut obj, &in_path).unwrap();
let cancel = CancelSignal::new();
let cancel_for_server = cancel.clone();
let triggered = Arc::new(AtomicBool::new(false));
let triggered_for_server = Arc::clone(&triggered);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let server_thread = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut assoc = dcmnorm_dimse::association::server::ServerAssociationOptions::new()
.ae_title("SLOW-SCP")
.max_pdu_length(16384)
.with_abstract_syntax(uids::DIGITAL_MAMMOGRAPHY_X_RAY_IMAGE_STORAGE_FOR_PRESENTATION)
.with_transfer_syntax(uids::EXPLICIT_VR_LITTLE_ENDIAN)
.establish(stream)
.unwrap();
let dcmnorm_dimse::Incoming::Command {
presentation_context_id,
..
} = assoc.receive_command().unwrap()
else {
panic!("expected C-STORE-RQ command");
};
let mut reader = assoc.receive_data_set_reader(presentation_context_id);
let mut first_chunk = [0u8; 4096];
let _ = reader.read(&mut first_chunk);
triggered_for_server.store(true, Ordering::Release);
cancel_for_server.request(CancelMode::Abort);
let mut scratch = [0u8; 4096];
while let Ok(n) = reader.read(&mut scratch) {
if n == 0 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
});
let start = std::time::Instant::now();
let err = store_scu(
&format!("127.0.0.1:{port}"),
&[in_path],
StoreScuOptions {
calling_ae_title: "CANCEL-SCU".to_owned(),
called_ae_title: Some("SLOW-SCP".to_owned()),
max_pdu_length: 16384,
never_transcode: true,
timeout: Some(std::time::Duration::from_secs(10)),
on_log: None,
cancel: Some(cancel),
},
)
.expect_err("mid-send cancellation must abort store_scu");
assert!(
matches!(err, DimseError::Cancelled(CancelMode::Abort)),
"expected DimseError::Cancelled(Abort), got {err:?}"
);
assert!(
triggered.load(Ordering::Acquire),
"server should have fired cancellation during dataset streaming"
);
assert!(
start.elapsed() < std::time::Duration::from_secs(5),
"cancellation must terminate promptly instead of looping"
);
let _ = server_thread.join();
let _ = fs::remove_dir_all(&dir);
}