Files
ezDent-MacOS/Sources/EzDent/DICOM.swift
T

392 lines
19 KiB
Swift

import CoreGraphics
import Foundation
import simd
struct DICOMImage {
struct Geometry {
let origin: SIMD3<Double>
let row: SIMD3<Double>
let column: SIMD3<Double>
let spacing: SIMD2<Double>
}
let width: Int
let height: Int
let frames: Int
let pixels: [Float]
let rgb: Data?
let monochrome1: Bool
let window: SIMD2<Float>?
let series: String?
let geometry: Geometry?
let frameGeometry: [Geometry]?
static func recognizes(_ url: URL) -> Bool {
guard let file = try? FileHandle(forReadingFrom: url) else { return false }
defer { try? file.close() }
try? file.seek(toOffset: 128)
return (try? file.read(upToCount: 4)) == Data("DICM".utf8)
}
static func directoryReferences(_ url: URL) throws -> [URL] {
let data = try Data(contentsOf: url, options: .mappedIfSafe)
guard data.count >= 132, data[128..<132].elementsEqual("DICM".utf8) else {
throw DICOMError.invalid
}
var reader = DICOMReader(data)
let folder = url.deletingLastPathComponent().resolvingSymlinksInPath()
let folderPrefix = folder.path.hasSuffix("/") ? folder.path : folder.path + "/"
while reader.group != nil {
let element = try reader.element(explicit: true)
guard element.tag == 0x0004_1220 else { continue }
return try reader.children(in: element.range, explicit: true).compactMap { item in
guard item.tag == 0xFFFE_E000,
let reference = try reader.children(in: item.range, explicit: true)
.first(where: { $0.tag == 0x0004_1500 }) else { return nil }
let parts = reader.string(reference.range).split(separator: "\\")
guard !parts.isEmpty, parts.allSatisfy({
!$0.contains("/") && !$0.contains("\0") && $0 != "." && $0 != ".."
}) else { return nil }
let target = parts.reduce(folder) { $0.appendingPathComponent(String($1)) }
.resolvingSymlinksInPath()
guard target.path.hasPrefix(folderPrefix),
(try? target.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
else { return nil }
return target
}
}
return []
}
static func stackSeriesIdentifier(_ url: URL) -> String? {
guard let data = try? Data(contentsOf: url, options: .mappedIfSafe),
data.count >= 132, data[128..<132].elementsEqual("DICM".utf8) else { return nil }
var reader = DICOMReader(data)
var syntax = ""
do {
while reader.group == 2 {
let element = try reader.element(explicit: true)
if element.tag == 0x0002_0010 { syntax = reader.string(element.range) }
}
// Big Endian and deflated datasets require normalization before reading tags.
guard !syntax.isEmpty, syntax != "1.2.840.10008.1.2.2", syntax != "1.2.840.10008.1.2.1.99" else {
return nil
}
var series: String?
while let group = reader.group, group <= 0x0028 {
let element = try reader.element(explicit: syntax != "1.2.840.10008.1.2")
if element.tag == 0x0020_000E { series = reader.string(element.range) }
if element.tag == 0x0028_0008, reader.string(element.range) != "1" { return nil }
}
return series.flatMap { $0.isEmpty ? nil : $0 }
} catch {
return nil
}
}
init(url: URL) throws {
let data = try Data(contentsOf: url, options: .mappedIfSafe)
if data.count >= 132, data[128..<132].elementsEqual("DICM".utf8) {
do {
try self.init(data: data)
return
} catch DICOMError.transferSyntax {
// The bundled decoder normalizes encapsulated and other transfer syntaxes.
} catch DICOMError.palette {
try self.init(data: DICOMCodec.normalized(from: url, applyPalette: true))
return
}
}
do {
try self.init(data: DICOMCodec.normalized(from: url))
} catch DICOMError.palette {
try self.init(data: DICOMCodec.normalized(from: url, applyPalette: true))
}
}
private init(data: Data) throws {
guard data.count >= 132, data[128..<132].elementsEqual("DICM".utf8) else {
throw DICOMError.invalid
}
var reader = DICOMReader(data)
var syntax = ""
while reader.group == 2 {
let element = try reader.element(explicit: true)
if element.tag == 0x0002_0010 { syntax = reader.string(element.range) }
}
guard syntax == "1.2.840.10008.1.2" || syntax == "1.2.840.10008.1.2.1" else {
throw DICOMError.transferSyntax
}
let explicit = syntax.hasSuffix(".1")
var fields: [UInt32: Range<Int>] = [:]
while reader.group != nil {
let element = try reader.element(explicit: explicit)
if element.tag == 0x7FE0_0010 {
fields[element.tag] = element.range
break
}
fields[element.tag] = element.range
}
func number(_ tag: UInt32) -> Int? {
guard let range = fields[tag], range.count == 2 else { return nil }
return Int(reader.word(range.lowerBound))
}
func string(_ tag: UInt32, in source: [UInt32: Range<Int>]? = nil) -> String? {
(source ?? fields)[tag].map(reader.string)
}
func decimals(_ tag: UInt32, count: Int, in source: [UInt32: Range<Int>]) -> [Double]? {
guard let value = string(tag, in: source) else { return nil }
let values = value.split(separator: "\\").compactMap {
Double($0.trimmingCharacters(in: .whitespaces))
}
return values.count == count && values.allSatisfy(\.isFinite) ? values : nil
}
func decimal(_ tag: UInt32, in source: [UInt32: Range<Int>]? = nil) -> Float? {
guard let first = string(tag, in: source)?.split(separator: "\\").first,
let value = Float(first.trimmingCharacters(in: .whitespaces)), value.isFinite else { return nil }
return value
}
let frameCount = string(0x0028_0008).flatMap(Int.init) ?? 1
let photometric = string(0x0028_0004) ?? ""
if photometric == "PALETTE COLOR" { throw DICOMError.palette }
let color = ["RGB", "YBR_FULL", "YBR_FULL_422"].contains(photometric)
let planar = number(0x0028_0006) ?? 0
guard let width = number(0x0028_0011), let height = number(0x0028_0010),
width > 0, height > 0, (1...4096).contains(frameCount),
width * height <= 32_000_000 / frameCount,
number(0x0028_0002) == (color ? 3 : 1),
color || ["MONOCHROME1", "MONOCHROME2"].contains(photometric),
let bits = number(0x0028_0100), [1, 8, 16, 32].contains(bits),
let stored = number(0x0028_0101), (1...bits).contains(stored),
number(0x0028_0102) == stored - 1,
let representation = number(0x0028_0103), representation == 0 || representation == 1,
let pixelRange = fields[0x7FE0_0010] else { throw DICOMError.unsupported }
let sampleCount = width * height * frameCount
let bytes = bits / 8
let packed = photometric == "YBR_FULL_422"
if color {
guard bits == 8, stored == 8, representation == 0, (0...1).contains(planar),
!packed || (width.isMultiple(of: 2) && planar == 0) else { throw DICOMError.unsupported }
}
let length = bits == 1 ? (sampleCount + 7) / 8 : sampleCount * (color ? (packed ? 2 : 3) : bytes)
guard pixelRange.count == length || (length % 2 == 1 && pixelRange.count == length + 1) else {
throw DICOMError.invalid
}
let mask = (1 << stored) - 1
let signBit = 1 << (stored - 1)
func attributes(in range: Range<Int>) throws -> [UInt32: Range<Int>] {
try reader.children(in: range, explicit: explicit).reduce(into: [:]) {
$0[$1.tag] = $1.range
}
}
func items(_ range: Range<Int>?) throws -> [Range<Int>] {
guard let range else { return [] }
let children = try reader.children(in: range, explicit: explicit)
guard children.allSatisfy({ $0.tag == 0xFFFE_E000 }) else { throw DICOMError.invalid }
return children.map(\.range)
}
func functionalGroup(_ range: Range<Int>) throws -> [UInt32: Range<Int>] {
let macros = try attributes(in: range)
var result: [UInt32: Range<Int>] = [:]
for tag: UInt32 in [0x0020_9113, 0x0020_9116, 0x0028_9110, 0x0028_9145, 0x0028_9132] {
if let item = try items(macros[tag]).first {
result.merge(try attributes(in: item)) { _, new in new }
}
}
return result
}
var common = fields
if let shared = try items(fields[0x5200_9229]).first {
common.merge(try functionalGroup(shared)) { _, new in new }
}
let perFrame = try items(fields[0x5200_9230])
guard perFrame.isEmpty || perFrame.count == frameCount else { throw DICOMError.invalid }
func geometry(in values: [UInt32: Range<Int>]) -> Geometry? {
guard let position = decimals(0x0020_0032, count: 3, in: values),
let axes = decimals(0x0020_0037, count: 6, in: values),
let spacing = decimals(0x0028_0030, count: 2, in: values),
spacing.allSatisfy({ $0 > 0 && $0 <= 1000 }) else { return nil }
return Geometry(origin: SIMD3(position[0], position[1], position[2]),
row: SIMD3(axes[0], axes[1], axes[2]),
column: SIMD3(axes[3], axes[4], axes[5]),
spacing: SIMD2(spacing[1], spacing[0]))
}
let frameAttributes = try perFrame.map {
try common.merging(functionalGroup($0)) { _, new in new }
}
let geometryValues = frameAttributes.compactMap { geometry(in: $0) }
self.geometry = geometry(in: common)
frameGeometry = !geometryValues.isEmpty && geometryValues.count == frameCount ? geometryValues : nil
let transforms = try (frameAttributes.isEmpty ? [common] : frameAttributes).map { values in
let slope = decimal(0x0028_1053, in: values) ?? 1
let intercept = decimal(0x0028_1052, in: values) ?? 0
guard abs(slope) <= 1_000_000, abs(intercept) <= 1_000_000_000 else { throw DICOMError.invalid }
return SIMD2(slope, intercept)
}
self.width = width
self.height = height
frames = frameCount
monochrome1 = photometric == "MONOCHROME1"
series = string(0x0020_000E)
let windowValues = frameAttributes.first ?? common
if let center = decimal(0x0028_1050, in: windowValues),
let windowWidth = decimal(0x0028_1051, in: windowValues), windowWidth >= 1 {
window = SIMD2(center, windowWidth)
} else {
window = nil
}
if color {
pixels = []
rgb = Self.colorPixels(data[pixelRange], sampleCount: sampleCount, planeSize: width * height,
photometric: photometric, planar: planar)
return
}
rgb = nil
pixels = data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
(0..<sampleCount).map { index in
let raw: Int
if bits == 1 {
raw = Int(buffer[pixelRange.lowerBound + index / 8]) >> (index % 8) & 1
} else {
let offset = pixelRange.lowerBound + index * bytes
raw = (0..<bytes).reduce(0) { $0 | Int(buffer[offset + $1]) << ($1 * 8) }
}
let value = raw & mask
let signed = representation == 1 && value & signBit != 0 ? value - (1 << stored) : value
let transform = transforms.count == 1 ? transforms[0] : transforms[index / (width * height)]
return Float(signed) * transform.x + transform.y
}
}
}
private static func colorPixels(_ data: Data, sampleCount: Int, planeSize: Int,
photometric: String, planar: Int) -> Data {
var result = Data(count: sampleCount * 3)
data.withUnsafeBytes { (input: UnsafeRawBufferPointer) in
result.withUnsafeMutableBytes { (output: UnsafeMutableRawBufferPointer) in
for pixel in 0..<sampleCount {
let destination = pixel * 3
let first: UInt8
let second: UInt8
let third: UInt8
if photometric == "YBR_FULL_422" {
let pair = pixel / 2 * 4
first = input[pair + pixel % 2]
second = input[pair + 2]
third = input[pair + 3]
} else if planar == 1 {
let source = pixel / planeSize * planeSize * 3 + pixel % planeSize
first = input[source]
second = input[source + planeSize]
third = input[source + 2 * planeSize]
} else {
first = input[destination]
second = input[destination + 1]
third = input[destination + 2]
}
if photometric == "RGB" {
output[destination] = first
output[destination + 1] = second
output[destination + 2] = third
} else {
let luma = Double(first)
let cb = Double(second) - 128
let cr = Double(third) - 128
output[destination] = UInt8(clamping: Int((luma + 1.402 * cr).rounded()))
output[destination + 1] = UInt8(clamping: Int((luma - 0.344136 * cb - 0.714136 * cr).rounded()))
output[destination + 2] = UInt8(clamping: Int((luma + 1.772 * cb).rounded()))
}
}
}
}
return result
}
static func grayscale(_ pixels: [Float], width: Int, height: Int,
center: Float, span: Float, invert: Bool = false) -> CGImage? {
let bytes = pixels.map { value -> UInt8 in
let normalized = span <= 1 ? (value > center - 0.5 ? Float(1) : 0)
: min(1, max(0, (value - (center - 0.5)) / (span - 1) + 0.5))
return UInt8(((invert ? 1 - normalized : normalized) * 255).rounded())
}
guard let provider = CGDataProvider(data: Data(bytes) as CFData) else { return nil }
return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8,
bytesPerRow: width, space: CGColorSpaceCreateDeviceGray(),
bitmapInfo: [], provider: provider, decode: nil, shouldInterpolate: true,
intent: .defaultIntent)
}
}
enum DICOMError: LocalizedError {
case invalid, transferSyntax, unsupported, geometry, palette
var errorDescription: String? {
switch self {
case .invalid: return "Файл DICOM повреждён или имеет неподдерживаемую структуру."
case .transferSyntax: return "Не удалось декодировать схему передачи DICOM."
case .unsupported: return "Формат пикселей DICOM не поддерживается или размер превышает лимит памяти."
case .palette: return "Не удалось применить цветовую палитру DICOM."
case .geometry: return "Для 3D выберите все срезы одной серии с одинаковой геометрией и равномерным шагом."
}
}
}
private struct DICOMReader {
let data: Data
var cursor = 132
var group: UInt16? { cursor <= data.count - 8 ? word(cursor) : nil }
private static let longVR: Set<String> = ["OB", "OD", "OF", "OL", "OV", "OW", "SQ", "SV", "UC", "UN", "UR", "UT", "UV"]
init(_ data: Data) { self.data = data }
func word(_ offset: Int) -> UInt16 {
UInt16(data[offset]) | UInt16(data[offset + 1]) << 8
}
func string(_ range: Range<Int>) -> String {
String(decoding: data[range], as: UTF8.self)
.trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: "\0")))
}
func children(in range: Range<Int>, explicit: Bool) throws -> [(tag: UInt32, range: Range<Int>)] {
var reader = self
reader.cursor = range.lowerBound
var result: [(UInt32, Range<Int>)] = []
while reader.cursor < range.upperBound {
let value = try reader.element(explicit: explicit)
guard reader.cursor <= range.upperBound else { throw DICOMError.invalid }
result.append(value)
}
return result
}
mutating func element(explicit: Bool, depth: Int = 0) throws -> (tag: UInt32, range: Range<Int>) {
guard let group, depth < 32 else { throw DICOMError.invalid }
let tag = UInt32(group) << 16 | UInt32(word(cursor + 2))
let long = group == 0xfffe || !explicit
|| Self.longVR.contains(String(decoding: data[(cursor + 4)..<(cursor + 6)], as: UTF8.self))
let header = long && group != 0xfffe && explicit ? 12 : 8
guard cursor <= data.count - header else { throw DICOMError.invalid }
let lengthOffset = cursor + header - (long ? 4 : 2)
let length = long ? Int(word(lengthOffset)) | Int(word(lengthOffset + 2)) << 16 : Int(word(lengthOffset))
cursor += header
if length == Int(UInt32.max) {
guard tag != 0x7FE0_0010 else { throw DICOMError.transferSyntax }
let delimiter: UInt32 = tag == 0xFFFE_E000 ? 0xFFFE_E00D : 0xFFFE_E0DD
let start = cursor
while true {
let end = cursor
let child = try element(explicit: explicit, depth: depth + 1)
if child.tag == delimiter { return (tag, start..<end) }
}
}
guard length <= data.count - cursor else { throw DICOMError.invalid }
let start = cursor
cursor += length
return (tag, start..<cursor)
}
}