From 6b95fbb1fc7cb87dd1130f32813caf1a827af40d Mon Sep 17 00:00:00 2001 From: SantaSpeen Date: Sun, 22 Nov 2026 01:37:28 +0300 Subject: [PATCH] Expand DICOM decoding and Enhanced CT support --- README.md | 14 +- Sources/EzDent/DICOM.swift | 258 ++++++++++++++++++++++---- Sources/EzDent/DICOMCodec.swift | 26 +++ Sources/EzDent/DICOMViewer.swift | 55 +++++- Sources/EzDent/DICOMVolume.swift | 91 +++++---- Sources/EzDent/PatientLibrary.swift | 10 +- Sources/EzDent/PatientWorkspace.swift | 100 ++++++++-- scripts/build-app.sh | 16 +- scripts/build-dicom-decoder.sh | 34 ++++ 9 files changed, 508 insertions(+), 96 deletions(-) create mode 100644 Sources/EzDent/DICOMCodec.swift create mode 100755 scripts/build-dicom-decoder.sh diff --git a/README.md b/README.md index 336ff17..3915594 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,9 @@ ## Разработка -Нужны Xcode или Xcode Command Line Tools с Swift 5.9 или новее и SDK macOS. Откройте `Package.swift` в Xcode или запустите приложение из терминала. +Нужны Xcode или Xcode Command Line Tools с Swift 5.9 или новее и SDK macOS. Для универсального пакета также нужен CMake 3.16 или новее. Первый запуск скрипта скачивает закреплённую версию исходников GDCM, а затем собирает встроенный декодер. Если CMake отсутствует в `PATH`, укажите его путь через `EZDENT_CMAKE`. + +Для разработки можно открыть `Package.swift` в Xcode или выполнить команду ниже. Форматы, которым нужен GDCM, проверяйте в собранном `EzDent.app`. ```sh swift run EzDent @@ -38,8 +40,8 @@ open dist/EzDent.app ## DICOM и 3D -- Нажмите «Добавить снимки…» и выберите файл DICOM для 2D-просмотра. Для 3D выберите одновременно все файлы **одной** серии однослойных срезов. EzDent сортирует их по геометрии, независимо от имён и порядка выбора. При импорте оригиналы копируются в локальную библиотеку. -- Для серии доступны три плоскости с учётом физического размера вокселей. Ползунки «Уровень» и «Окно» меняют отображение. -- Режим «3D» открывается в той же карточке. Перетаскивайте изображение, чтобы вращать объём. Доступны пороговая поверхность и проекция максимальной интенсивности (MIP), масштаб и сброс ракурса. -- Читаются монохромные DICOM Part 10 без сжатия с 8- или 16-битными пикселями, Explicit или Implicit VR Little Endian. Многофреймовый файл можно листать в 2D. Для 3D нужны отдельные срезы с одинаковой ориентацией, размером и равномерным шагом. JPEG/JPEG 2000/RLE, цвет и Enhanced CT с геометрией по кадрам пока не поддерживаются. Для 3D текстура уменьшается до 256 вокселей по длинной стороне. Совместимость с клиническими сериями ezServer ещё не проверялась. -- В установщике Ez3D-i 5.5.12.3 найдены отдельные модули DICOM, MPR и VolumeViz. Приложение macOS реализует эти сценарии средствами SwiftUI и Metal. Геометрия серии строится по [DICOM PS3.3 C.7.6.2](https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.2.html), декодирование использует [DICOM PS3.5, раздел A](https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_A.html). +- Нажмите «Добавить снимки…» и выберите файл, набор файлов, папку или индекс DICOMDIR. EzDent объединяет однослойные файлы с одинаковым Series Instance UID, если идентификатор доступен в заголовке. Многофреймовые файлы открываются отдельно. Приложение сортирует срезы по физическому положению и хранит оригиналы в локальной библиотеке. Кнопка экспорта копирует исходный файл или всю серию. +- Для томов с согласованной геометрией доступны три плоскости с учётом физического шага вокселей. Enhanced CT использует позицию, ориентацию, размер вокселя и преобразование интенсивности из общих и покадровых групп. Несогласованные многофреймовые стеки остаются доступны для просмотра по кадрам. +- Во встроенном 3D-просмотрщике можно вращать и масштабировать объём, менять порог поверхности и переключаться на проекцию максимальной интенсивности (MIP). Для 3D текстура уменьшается до 256 вокселей по длинной стороне. +- Встроенный GDCM 3.2.3 декодирует JPEG, JPEG-LS, JPEG 2000 и RLE и нормализует Big Endian и Deflated. EzDent отображает целочисленные монохромные кадры и 8-битные цветные RGB/YBR. Покадровая геометрия реализована для согласованных серий. Видео DICOM, объекты без пиксельных данных и построение объёма из нерегулярных серий не поддерживаются. Совместимость с клиническими сериями ezServer ещё не проверялась. +- В установщике Ez3D-i 5.5.12.3 найдены отдельные модули DICOM, MPR и VolumeViz. Приложение macOS реализует эти сценарии средствами SwiftUI, Metal и [GDCM](https://github.com/malaterre/GDCM). Геометрия и покадровые группы строятся по [DICOM PS3.3](https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.16.html), декодирование использует [DICOM PS3.5, раздел A](https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_A.html). diff --git a/Sources/EzDent/DICOM.swift b/Sources/EzDent/DICOM.swift index 971720f..169bc24 100644 --- a/Sources/EzDent/DICOM.swift +++ b/Sources/EzDent/DICOM.swift @@ -14,10 +14,12 @@ struct DICOMImage { let height: Int let frames: Int let pixels: [Float] + let rgb: Data? let monochrome1: Bool let window: SIMD2? 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 } @@ -26,8 +28,83 @@ struct DICOMImage { 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 } @@ -55,77 +132,180 @@ struct DICOMImage { guard let range = fields[tag], range.count == 2 else { return nil } return Int(reader.word(range.lowerBound)) } - func string(_ tag: UInt32) -> String? { - fields[tag].map(reader.string) + func string(_ tag: UInt32, in source: [UInt32: Range]? = nil) -> String? { + (source ?? fields)[tag].map(reader.string) } - func decimals(_ tag: UInt32, count: Int) -> [Double]? { - guard let value = string(tag) else { return nil } + func decimals(_ tag: UInt32, count: Int, in source: [UInt32: Range]) -> [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) -> Float? { - guard let first = string(tag)?.split(separator: "\\").first, + func decimal(_ tag: UInt32, in source: [UInt32: Range]? = 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) == 1, - let photometric = string(0x0028_0004), ["MONOCHROME1", "MONOCHROME2"].contains(photometric), - let bits = number(0x0028_0100), bits == 8 || bits == 16, + 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 length = sampleCount * bytes + 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) - let slope = decimal(0x0028_1053) ?? 1 - let intercept = decimal(0x0028_1052) ?? 0 - guard abs(slope) <= 1_000_000, abs(intercept) <= 1_000_000_000 else { throw DICOMError.invalid } + func attributes(in range: Range) throws -> [UInt32: Range] { + try reader.children(in: range, explicit: explicit).reduce(into: [:]) { + $0[$1.tag] = $1.range + } + } + func items(_ range: Range?) throws -> [Range] { + 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) throws -> [UInt32: Range] { + let macros = try attributes(in: range) + var result: [UInt32: Range] = [:] + 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]) -> 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) - if let center = decimal(0x0028_1050), let windowWidth = decimal(0x0028_1051), windowWidth >= 1 { + 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 let position = decimals(0x0020_0032, count: 3), - let axes = decimals(0x0020_0037, count: 6), - let spacing = decimals(0x0028_0030, count: 2), spacing.allSatisfy({ $0 > 0 }) { - geometry = 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])) - } else { - geometry = 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..> (index % 8) & 1 + } else { + let offset = pixelRange.lowerBound + index * bytes + raw = (0.. Data { + var result = Data(count: sampleCount * 3) + data.withUnsafeBytes { (input: UnsafeRawBufferPointer) in + result.withUnsafeMutableBytes { (output: UnsafeMutableRawBufferPointer) in + for pixel in 0.. CGImage? { let bytes = pixels.map { value -> UInt8 in @@ -142,12 +322,13 @@ struct DICOMImage { } enum DICOMError: LocalizedError { - case invalid, transferSyntax, unsupported, geometry + case invalid, transferSyntax, unsupported, geometry, palette var errorDescription: String? { switch self { case .invalid: return "Файл DICOM повреждён или имеет неподдерживаемую структуру." - case .transferSyntax: return "Поддерживается DICOM Little Endian без сжатия." - case .unsupported: return "Поддерживаются монохромные DICOM с пикселями 8 или 16 бит в пределах лимита памяти." + case .transferSyntax: return "Не удалось декодировать схему передачи DICOM." + case .unsupported: return "Формат пикселей DICOM не поддерживается или размер превышает лимит памяти." + case .palette: return "Не удалось применить цветовую палитру DICOM." case .geometry: return "Для 3D выберите все срезы одной серии с одинаковой геометрией и равномерным шагом." } } @@ -170,6 +351,18 @@ private struct DICOMReader { .trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: "\0"))) } + func children(in range: Range, explicit: Bool) throws -> [(tag: UInt32, range: Range)] { + var reader = self + reader.cursor = range.lowerBound + var result: [(UInt32, Range)] = [] + 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) { guard let group, depth < 32 else { throw DICOMError.invalid } let tag = UInt32(group) << 16 | UInt32(word(cursor + 2)) @@ -183,11 +376,12 @@ private struct DICOMReader { 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 { break } + if child.tag == delimiter { return (tag, start.. Data { + let decoder = Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/gdcmconv") + guard FileManager.default.isExecutableFile(atPath: decoder.path) else { throw DICOMError.transferSyntax } + + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, + attributes: [.posixPermissions: 0o700]) + defer { try? FileManager.default.removeItem(at: folder) } + let decoded = folder.appendingPathComponent("decoded.dcm") + let process = Process() + process.executableURL = decoder + process.arguments = (applyPalette ? ["--apply-lut8"] : ["--raw", "--explicit"]) + + ["-i", source.path, "-o", decoded.path] + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + try process.run() + process.waitUntilExit() + guard process.terminationReason == .exit, process.terminationStatus == 0 else { + throw DICOMError.transferSyntax + } + return try Data(contentsOf: decoded, options: .mappedIfSafe) + } +} diff --git a/Sources/EzDent/DICOMViewer.swift b/Sources/EzDent/DICOMViewer.swift index ec01c95..71159dd 100644 --- a/Sources/EzDent/DICOMViewer.swift +++ b/Sources/EzDent/DICOMViewer.swift @@ -1,10 +1,13 @@ +import AppKit import SwiftUI struct DICOMViewer: View { let urls: [URL] + let name: String @State private var volume: DICOMVolume? @State private var error: String? + @State private var exportError: String? @State private var plane = DICOMVolume.Plane.slices @State private var index = 0.0 @State private var center = 0.0 @@ -27,6 +30,14 @@ struct DICOMViewer: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } } + .alert("Не удалось экспортировать DICOM", isPresented: Binding( + get: { exportError != nil }, + set: { if !$0 { exportError = nil } } + )) { + Button("Закрыть", role: .cancel) {} + } message: { + Text(exportError ?? "") + } .task { do { let urls = self.urls @@ -76,6 +87,13 @@ struct DICOMViewer: View { Text("DICOM • \(volume.size.x) × \(volume.size.y) × \(volume.size.z)") .font(.caption) .foregroundStyle(.secondary) + Button { + exportOriginals() + } label: { + Label("Экспорт DICOM…", systemImage: "square.and.arrow.up") + .labelStyle(.iconOnly) + } + .help("Экспортировать исходные файлы DICOM") } .padding(10) @@ -116,18 +134,45 @@ struct DICOMViewer: View { Text("Срез \(min(Int(index) + 1, volume.count(plane))) из \(volume.count(plane))") } } - HStack { - Slider(value: $center, in: centerRange(volume)) { Text(show3D && surface ? "Порог" : "Уровень") } - if !show3D || !surface { - Slider(value: $width, in: 1...windowLimit(volume)) { Text("Окно") } + if volume.rgb == nil { + HStack { + Slider(value: $center, in: centerRange(volume)) { Text(show3D && surface ? "Порог" : "Уровень") } + if !show3D || !surface { + Slider(value: $width, in: 1...windowLimit(volume)) { Text("Окно") } + } + Button("Сбросить окно") { resetWindow(volume) } } - Button("Сбросить окно") { resetWindow(volume) } } } .padding(10) } } + private func exportOriginals() { + let panel = NSSavePanel() + panel.nameFieldStringValue = urls.count == 1 ? name : "Серия DICOM" + guard panel.runModal() == .OK, let destination = panel.url else { return } + do { + if urls.count == 1 { + try Data(contentsOf: urls[0], options: .mappedIfSafe).write(to: destination, options: .atomic) + return + } + + let manager = FileManager.default + try manager.createDirectory(at: destination, withIntermediateDirectories: false) + do { + for source in urls { + try manager.copyItem(at: source, to: destination.appendingPathComponent(source.lastPathComponent)) + } + } catch { + try? manager.removeItem(at: destination) + throw error + } + } catch { + exportError = error.localizedDescription + } + } + private func centerRange(_ volume: DICOMVolume) -> ClosedRange { let preset = volume.window?.x ?? volume.minimum return Double(min(volume.minimum, preset))...Double(max(volume.minimum + 1, volume.maximum, preset)) diff --git a/Sources/EzDent/DICOMVolume.swift b/Sources/EzDent/DICOMVolume.swift index 7ea3178..32b3ca6 100644 --- a/Sources/EzDent/DICOMVolume.swift +++ b/Sources/EzDent/DICOMVolume.swift @@ -14,6 +14,8 @@ struct DICOMVolume { let size: SIMD3 let spacing: SIMD3? let pixels: [Float] + let rgb: Data? + let pixelSpacing: SIMD2? let window: SIMD2? let inverted: Bool let minimum: Float @@ -27,45 +29,62 @@ struct DICOMVolume { size = SIMD3(first.width, first.height, urls.count == 1 ? first.frames : urls.count) window = first.window inverted = first.monochrome1 + rgb = first.rgb + pixelSpacing = first.geometry?.spacing ?? first.frameGeometry?.first?.spacing if urls.count == 1 { - spacing = nil - pixels = first.pixels + if first.rgb == nil, first.frames > 1, let geometry = first.frameGeometry, + let sorted = try? Self.sortSlices(geometry) { + spacing = sorted.spacing + pixels = sorted.order.flatMap { frame in + first.pixels[(frame * planeSize)..<((frame + 1) * planeSize)] + } + } else { + spacing = nil + pixels = first.pixels + } } else { - guard let series = first.series, !series.isEmpty, let basis = first.geometry, - abs(simd_length(basis.row) - 1) < 0.001, - abs(simd_length(basis.column) - 1) < 0.001, - abs(simd_dot(basis.row, basis.column)) < 0.001 else { throw DICOMError.geometry } - let normal = simd_normalize(simd_cross(basis.row, basis.column)) - func position(_ image: DICOMImage) throws -> Double { - guard image.frames == 1, image.series == series, image.width == first.width, + guard first.rgb == nil, let series = first.series, !series.isEmpty else { throw DICOMError.geometry } + var slices: [[Float]] = [] + var geometry: [DICOMImage.Geometry] = [] + for (index, url) in urls.enumerated() { + let image = index == 0 ? first : try DICOMImage(url: url) + guard image.rgb == nil, image.frames == 1, image.series == series, image.width == first.width, image.height == first.height, image.monochrome1 == first.monochrome1, - let geometry = image.geometry, - simd_distance(geometry.row, basis.row) < 0.001, - simd_distance(geometry.column, basis.column) < 0.001, - simd_distance(geometry.spacing, basis.spacing) < 0.001 else { throw DICOMError.geometry } - let offset = geometry.origin - basis.origin - let depth = simd_dot(offset, normal) - guard depth.isFinite, simd_length(offset - depth * normal) < 0.1 else { throw DICOMError.geometry } - return depth + let frame = image.geometry ?? image.frameGeometry?.first else { throw DICOMError.geometry } + geometry.append(frame) + slices.append(image.pixels) } - - var slices = [(depth: try position(first), pixels: first.pixels)] - for url in urls.dropFirst() { - let image = try DICOMImage(url: url) - slices.append((try position(image), image.pixels)) - } - slices.sort { $0.depth < $1.depth } - let step = (slices[slices.count - 1].depth - slices[0].depth) / Double(slices.count - 1) - guard step > 0.001, zip(slices, slices.dropFirst()).allSatisfy({ - abs($1.depth - $0.depth - step) <= max(0.01, step * 0.02) - }) else { throw DICOMError.geometry } - spacing = SIMD3(basis.spacing.x, basis.spacing.y, step) - pixels = slices.flatMap(\.pixels) + let sorted = try Self.sortSlices(geometry) + spacing = sorted.spacing + pixels = sorted.order.flatMap { slices[$0] } } minimum = pixels.min() ?? 0 maximum = pixels.max() ?? 1 } + private static func sortSlices(_ geometry: [DICOMImage.Geometry]) throws + -> (spacing: SIMD3, order: [Int]) { + guard geometry.count > 1, let basis = geometry.first, + abs(simd_length(basis.row) - 1) < 0.001, + abs(simd_length(basis.column) - 1) < 0.001, + abs(simd_dot(basis.row, basis.column)) < 0.001 else { throw DICOMError.geometry } + let normal = simd_normalize(simd_cross(basis.row, basis.column)) + let slices = try geometry.enumerated().map { index, frame in + let offset = frame.origin - basis.origin + let depth = simd_dot(offset, normal) + guard depth.isFinite, simd_length(offset - depth * normal) < 0.1, + simd_distance(frame.row, basis.row) < 0.001, + simd_distance(frame.column, basis.column) < 0.001, + simd_distance(frame.spacing, basis.spacing) < 0.001 else { throw DICOMError.geometry } + return (index: index, depth: depth) + }.sorted { $0.depth < $1.depth } + let step = (slices[slices.count - 1].depth - slices[0].depth) / Double(slices.count - 1) + guard (0.001...1000).contains(step), zip(slices, slices.dropFirst()).allSatisfy({ + abs($1.depth - $0.depth - step) <= max(0.01, step * 0.02) + }) else { throw DICOMError.geometry } + return (SIMD3(basis.spacing.x, basis.spacing.y, step), slices.map(\.index)) + } + func count(_ plane: Plane) -> Int { switch plane { case .slices: return size.z @@ -78,7 +97,17 @@ struct DICOMVolume { let values: [Float] let width: Int let height: Int - let pitch = spacing ?? SIMD3(repeating: 1) + let pitch = spacing ?? SIMD3(pixelSpacing?.x ?? 1, pixelSpacing?.y ?? 1, 1) + if let rgb, plane == .slices { + let stride = size.x * size.y * 3 + let frame = rgb[(index * stride)..<((index + 1) * stride)] + guard let provider = CGDataProvider(data: frame as CFData), + let image = CGImage(width: size.x, height: size.y, bitsPerComponent: 8, bitsPerPixel: 24, + bytesPerRow: size.x * 3, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: [], provider: provider, decode: nil, shouldInterpolate: true, + intent: .defaultIntent) else { return nil } + return (image, Double(size.x) * pitch.x / (Double(size.y) * pitch.y)) + } let aspect: Double switch plane { case .slices: diff --git a/Sources/EzDent/PatientLibrary.swift b/Sources/EzDent/PatientLibrary.swift index 35c40cf..3863073 100644 --- a/Sources/EzDent/PatientLibrary.swift +++ b/Sources/EzDent/PatientLibrary.swift @@ -83,13 +83,15 @@ final class PatientLibrary: ObservableObject { return image } - func importDICOM(from sources: [URL], for patientID: UUID) throws -> PatientImage { + func importDICOM(from sources: [URL], for patientID: UUID) async throws -> PatientImage { + let accessed = sources.filter { $0.startAccessingSecurityScopedResource() } + defer { accessed.forEach { $0.stopAccessingSecurityScopedResource() } } + try await Task.detached(priority: .userInitiated) { + _ = try DICOMVolume(urls: sources) + }.value guard let position = patients.firstIndex(where: { $0.id == patientID }) else { throw LibraryError.patientMissing } - let accessed = sources.filter { $0.startAccessingSecurityScopedResource() } - defer { accessed.forEach { $0.stopAccessingSecurityScopedResource() } } - _ = try DICOMVolume(urls: sources) try prepareDirectory() let name = sources.count == 1 ? sources[0].lastPathComponent : "Серия DICOM (\(sources.count) срезов)" let image = PatientImage(id: UUID(), name: name, importedAt: Date(), dicomCount: sources.count) diff --git a/Sources/EzDent/PatientWorkspace.swift b/Sources/EzDent/PatientWorkspace.swift index 33b5502..16b8802 100644 --- a/Sources/EzDent/PatientWorkspace.swift +++ b/Sources/EzDent/PatientWorkspace.swift @@ -10,6 +10,7 @@ struct PatientWorkspace: View { @State private var editor: PatientEditor? @State private var importPatientID: PatientRecord.ID? @State private var showImporter = false + @State private var isImporting = false @State private var errorMessage: String? private var filteredPatients: [PatientRecord] { @@ -96,8 +97,16 @@ struct PatientWorkspace: View { patientID = id } } - .fileImporter(isPresented: $showImporter, allowedContentTypes: [.data], allowsMultipleSelection: true, - onCompletion: importImages) + .fileImporter(isPresented: $showImporter, allowedContentTypes: [.data, .folder], allowsMultipleSelection: true, + onCompletion: { result in + guard let patient = importPatientID else { return } + importPatientID = nil + isImporting = true + Task { + defer { isImporting = false } + await importImages(result, for: patient) + } + }) .alert("Ошибка", isPresented: Binding( get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } } @@ -123,6 +132,10 @@ struct PatientWorkspace: View { Label("Добавить снимки…", systemImage: "plus") } .buttonStyle(.borderedProminent) + .disabled(isImporting) + if isImporting { + ProgressView().controlSize(.small).accessibilityLabel("Импорт снимков") + } } .padding(18) Divider() @@ -146,7 +159,7 @@ struct PatientWorkspace: View { Divider() Group { if selected.dicomCount != nil { - DICOMViewer(urls: library.dicomURLs(for: selected)) + DICOMViewer(urls: library.dicomURLs(for: selected), name: selected.name) } else { ImageViewer(image: selected, url: library.url(for: selected)) { message in errorMessage = message @@ -169,26 +182,27 @@ struct PatientWorkspace: View { showImporter = true } - private func importImages(_ result: Result<[URL], Error>) { - guard let importPatientID else { return } - self.importPatientID = nil + private func importImages(_ result: Result<[URL], Error>, for importPatientID: UUID) async { do { var errors: [String] = [] var firstImported: UUID? - let urls = try result.get() - let dicom = Set(urls.filter { url in - let access = url.startAccessingSecurityScopedResource() - defer { if access { url.stopAccessingSecurityScopedResource() } } - return ["dcm", "dicom"].contains(url.pathExtension.lowercased()) || DICOMImage.recognizes(url) - }) - if !dicom.isEmpty { + let selection = try result.get() + let accessed = selection.filter { $0.startAccessingSecurityScopedResource() } + defer { accessed.forEach { $0.stopAccessingSecurityScopedResource() } } + let files = await Task.detached(priority: .userInitiated) { + ImageImportSelection(urls: selection) + }.value + errors.append(contentsOf: files.errors) + + for series in files.series { do { - firstImported = try library.importDICOM(from: urls.filter { dicom.contains($0) }, for: importPatientID).id + let image = try await library.importDICOM(from: series, for: importPatientID) + firstImported = firstImported ?? image.id } catch { - errors.append(error.localizedDescription) + errors.append("\(series[0].lastPathComponent) — \(error.localizedDescription)") } } - for url in urls where !dicom.contains(url) { + for url in files.images { do { let image = try library.importImage(from: url, for: importPatientID) firstImported = firstImported ?? image.id @@ -199,6 +213,9 @@ struct PatientWorkspace: View { if patientID == importPatientID, let firstImported { imageID = firstImported } + if files.images.isEmpty, files.series.isEmpty { + errors.append("В выбранных папках нет поддерживаемых снимков.") + } if !errors.isEmpty { errorMessage = errors.joined(separator: "\n") } } catch { errorMessage = error.localizedDescription @@ -221,6 +238,57 @@ struct PatientWorkspace: View { } } +private struct ImageImportSelection { + let series: [[URL]] + let images: [URL] + let errors: [String] + + init(urls: [URL]) { + let keys: Set = [.isDirectoryKey, .isRegularFileKey] + var candidates: [(url: URL, direct: Bool)] = [] + var errors: [String] = [] + for url in urls { + if url.lastPathComponent.uppercased() == "DICOMDIR" { + do { + candidates.append(contentsOf: try DICOMImage.directoryReferences(url).map { ($0, true) }) + } catch { + errors.append("DICOMDIR — \(error.localizedDescription)") + } + } else if (try? url.resourceValues(forKeys: keys).isDirectory) == true { + if let items = FileManager.default.enumerator(at: url, includingPropertiesForKeys: Array(keys), + options: [.skipsHiddenFiles, .skipsPackageDescendants]) { + for case let item as URL in items { + if (try? item.resourceValues(forKeys: keys).isRegularFile) == true { + candidates.append((item, false)) + } + } + } + } else { + candidates.append((url, true)) + } + } + + var groups: [String: [URL]] = [:] + var groupOrder: [String] = [] + var images: [URL] = [] + var seen = Set() + for (url, direct) in candidates where seen.insert(url.standardizedFileURL).inserted { + if url.lastPathComponent.uppercased() == "DICOMDIR" { continue } + let ext = url.pathExtension.lowercased() + if ["dcm", "dicom"].contains(ext) || DICOMImage.recognizes(url) { + let key = DICOMImage.stackSeriesIdentifier(url) ?? UUID().uuidString + if groups[key] == nil { groupOrder.append(key) } + groups[key, default: []].append(url) + } else if direct || UTType(filenameExtension: ext)?.conforms(to: .image) == true { + images.append(url) + } + } + series = groupOrder.compactMap { groups[$0] } + self.images = images + self.errors = errors + } +} + private struct PatientEditor: Identifiable { let id = UUID() let patientID: UUID? diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 6ce2f3c..ec7f3c7 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -10,6 +10,8 @@ build_for_arch() { swift build -c release --arch "$arch" --scratch-path "$scratch_path" --show-bin-path } +decoder="$(./scripts/build-dicom-decoder.sh)" + arm64_bin="$(build_for_arch arm64)" x86_64_bin="$(build_for_arch x86_64)" @@ -19,12 +21,22 @@ trap 'rm -rf "$stage"' EXIT app="$stage/EzDent.app" executable="$app/Contents/MacOS/EzDent" -mkdir -p "$app/Contents/MacOS" +mkdir -p "$app/Contents/MacOS" "$app/Contents/Helpers" +cp "$decoder" "$app/Contents/Helpers/gdcmconv" +licenses="$app/Contents/Resources/Licenses" +mkdir -p "$licenses" +gdcm_source=".build/dicom-tools/gdcm" +cp "$gdcm_source/Copyright.txt" "$licenses/GDCM.txt" +cp "$gdcm_source/Utilities/gdcmjpeg/COPYRIGHT.dcmtk" "$licenses/DCMTK.txt" +cp "$gdcm_source/Utilities/gdcmcharls/License.txt" "$licenses/CharLS.txt" +cp "$gdcm_source/Utilities/gdcmopenjpeg/LICENSE" "$licenses/OpenJPEG.txt" +cp "$gdcm_source/Utilities/gdcmzlib/LICENSE" "$licenses/zlib.txt" +codesign --force --sign - "$app/Contents/Helpers/gdcmconv" cp Packaging/Info.plist "$app/Contents/Info.plist" xcrun lipo -create "$arm64_bin/EzDent" "$x86_64_bin/EzDent" -output "$executable" xcrun lipo "$executable" -verify_arch arm64 x86_64 codesign --force --sign - "$app" -codesign --verify --strict "$app" +codesign --verify --deep --strict "$app" rm -rf dist/EzDent.app mv "$app" dist/EzDent.app diff --git a/scripts/build-dicom-decoder.sh b/scripts/build-dicom-decoder.sh new file mode 100755 index 0000000..bb1f6a6 --- /dev/null +++ b/scripts/build-dicom-decoder.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -euo pipefail + +cd "$(dirname "${BASH_SOURCE[0]}")/.." +cache="$PWD/.build/dicom-tools" +source="$cache/gdcm" +build="$cache/gdcm-universal" +revision="54d8fbc814b01e493c82666716460799c1a1e76b" +cmake="${EZDENT_CMAKE:-cmake}" + +if ! command -v "$cmake" >/dev/null; then + printf '%s\n' 'CMake is required to build the bundled DICOM decoder. Set EZDENT_CMAKE to its path.' >&2 + exit 1 +fi + +mkdir -p "$cache" +if [[ ! -d "$source/.git" ]]; then + checkout="$(mktemp -d "$cache/.gdcm.XXXXXX")" + trap 'rm -rf "$checkout"' EXIT + git clone --depth 1 --branch v3.2.3 https://github.com/malaterre/GDCM.git "$checkout" >&2 + mv "$checkout" "$source" +fi +if [[ "$(git -C "$source" rev-parse HEAD)" != "$revision" ]]; then + printf '%s\n' 'Unexpected revision in the cached GDCM checkout.' >&2 + exit 1 +fi + +"$cmake" -S "$source" -B "$build" -DCMAKE_BUILD_TYPE=Release \ + "-DEXECUTABLE_OUTPUT_PATH=$build/bin" "-DLIBRARY_OUTPUT_PATH=$build/bin" \ + '-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64' -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 \ + -DGDCM_BUILD_APPLICATIONS=ON -DGDCM_BUILD_TESTING=OFF -DGDCM_BUILD_SHARED_LIBS=OFF >&2 +"$cmake" --build "$build" --target gdcmconv --parallel "${EZDENT_BUILD_JOBS:-4}" >&2 +xcrun lipo "$build/bin/gdcmconv" -verify_arch arm64 x86_64 +printf '%s\n' "$build/bin/gdcmconv"