PACS System 0.1.0
PACS DICOM system library
Loading...
Searching...
No Matches
rle_codec.cpp
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2021-2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
8
9#include <algorithm>
10#include <array>
11#include <cstdint>
12#include <cstring>
13#include <stdexcept>
14#include <vector>
15
17
18namespace {
19
23inline uint32_t read_le32(const uint8_t* data) {
24 return static_cast<uint32_t>(data[0]) |
25 (static_cast<uint32_t>(data[1]) << 8) |
26 (static_cast<uint32_t>(data[2]) << 16) |
27 (static_cast<uint32_t>(data[3]) << 24);
28}
29
33inline void write_le32(uint8_t* data, uint32_t value) {
34 data[0] = static_cast<uint8_t>(value & 0xFF);
35 data[1] = static_cast<uint8_t>((value >> 8) & 0xFF);
36 data[2] = static_cast<uint8_t>((value >> 16) & 0xFF);
37 data[3] = static_cast<uint8_t>((value >> 24) & 0xFF);
38}
39
52void encode_rle_segment(std::span<const uint8_t> input, std::vector<uint8_t>& output) {
53 if (input.empty()) {
54 return;
55 }
56
57 size_t pos = 0;
58 const size_t size = input.size();
59
60 while (pos < size) {
61 // Look for runs of identical bytes
62 uint8_t current = input[pos];
63 size_t run_length = 1;
64
65 while (pos + run_length < size &&
66 input[pos + run_length] == current &&
67 run_length < 128) {
68 ++run_length;
69 }
70
71 if (run_length >= 3) {
72 // Encode as a run (replicate)
73 // Control byte = 1 - run_length (range: -127 to -2 for lengths 3-128)
74 output.push_back(static_cast<uint8_t>(1 - static_cast<int>(run_length)));
75 output.push_back(current);
76 pos += run_length;
77 } else {
78 // Collect literal bytes (non-repeating or short runs)
79 std::vector<uint8_t> literal;
80 literal.reserve(128);
81
82 while (pos < size && literal.size() < 128) {
83 // Check if a run of 3+ starts here
84 size_t ahead_run = 1;
85 while (pos + ahead_run < size &&
86 input[pos + ahead_run] == input[pos] &&
87 ahead_run < 3) {
88 ++ahead_run;
89 }
90
91 if (ahead_run >= 3) {
92 // Don't include this in literal, it's the start of a run
93 break;
94 }
95
96 literal.push_back(input[pos]);
97 ++pos;
98 }
99
100 if (!literal.empty()) {
101 // Control byte = literal.size() - 1 (range: 0 to 127)
102 output.push_back(static_cast<uint8_t>(literal.size() - 1));
103 output.insert(output.end(), literal.begin(), literal.end());
104 }
105 }
106 }
107}
108
121 std::span<const uint8_t> input, size_t expected_size) {
122 std::vector<uint8_t> output;
123 output.reserve(expected_size);
124
125 size_t pos = 0;
126 const size_t size = input.size();
127
128 while (pos < size && output.size() < expected_size) {
129 auto control = static_cast<int8_t>(input[pos]);
130 ++pos;
131
132 if (control >= 0) {
133 // Literal: copy next (control + 1) bytes
134 size_t count = static_cast<size_t>(control) + 1;
135 if (pos + count > size) {
136 return kcenon::pacs::pacs_error<std::vector<uint8_t>>(
138 "RLE decode: insufficient literal data");
139 }
140 output.insert(output.end(), input.begin() + pos, input.begin() + pos + count);
141 pos += count;
142 } else if (control != -128) {
143 // Run: repeat next byte (1 - control) times
144 if (pos >= size) {
145 return kcenon::pacs::pacs_error<std::vector<uint8_t>>(
147 "RLE decode: missing replicate byte");
148 }
149 size_t count = static_cast<size_t>(1 - control);
150 uint8_t value = input[pos];
151 ++pos;
152 for (size_t i = 0; i < count && output.size() < expected_size; ++i) {
153 output.push_back(value);
154 }
155 }
156 // control == -128 is a no-op
157 }
158
159 return kcenon::pacs::ok<std::vector<uint8_t>>(std::move(output));
160}
161
171int calculate_segment_count(const image_params& params) {
172 int bytes_per_sample = (params.bits_allocated + 7) / 8;
173 return params.samples_per_pixel * bytes_per_sample;
174}
175
176} // namespace
177
182public:
183 impl() = default;
184
185 [[nodiscard]] codec_result encode(
186 std::span<const uint8_t> pixel_data,
187 const image_params& params,
188 [[maybe_unused]] const compression_options& options) const {
189
190 if (pixel_data.empty()) {
192 }
193
194 if (!valid_for_rle(params)) {
196 "Invalid parameters for RLE: requires 8/16-bit, 1-3 samples per pixel");
197 }
198
199 size_t expected_size = params.frame_size_bytes();
200 if (pixel_data.size() != expected_size) {
202 "Pixel data size mismatch: expected " + std::to_string(expected_size) +
203 ", got " + std::to_string(pixel_data.size()));
204 }
205
206 try {
207 return encode_frame(pixel_data, params);
208 } catch (const std::exception& e) {
209 return kcenon::pacs::pacs_error<compression_result>(kcenon::pacs::error_codes::decompression_error, std::string("RLE encoding failed: ") + e.what());
210 }
211 }
212
213 [[nodiscard]] codec_result decode(
214 std::span<const uint8_t> compressed_data,
215 const image_params& params) const {
216
217 if (compressed_data.empty()) {
219 }
220
221 if (compressed_data.size() < kRLEHeaderSize) {
223 }
224
225 try {
226 return decode_frame(compressed_data, params);
227 } catch (const std::exception& e) {
228 return kcenon::pacs::pacs_error<compression_result>(kcenon::pacs::error_codes::decompression_error, std::string("RLE decoding failed: ") + e.what());
229 }
230 }
231
232private:
233 [[nodiscard]] bool valid_for_rle(const image_params& params) const noexcept {
234 // RLE supports 8-bit and 16-bit samples
235 if (params.bits_allocated != 8 && params.bits_allocated != 16) {
236 return false;
237 }
238 // 1-3 samples per pixel (grayscale, RGB)
239 if (params.samples_per_pixel < 1 || params.samples_per_pixel > 3) {
240 return false;
241 }
242 // Check segment count limit
243 int num_segments = calculate_segment_count(params);
244 if (num_segments > kMaxSegments) {
245 return false;
246 }
247 // Valid dimensions
248 if (params.width == 0 || params.height == 0) {
249 return false;
250 }
251 return true;
252 }
253
255 std::span<const uint8_t> pixel_data,
256 const image_params& params) const {
257
258 int num_segments = calculate_segment_count(params);
259 size_t pixels_per_frame = static_cast<size_t>(params.width) * params.height;
260 int bytes_per_sample = (params.bits_allocated + 7) / 8;
261
262 // Prepare segment data (one vector per segment)
263 std::vector<std::vector<uint8_t>> segments(num_segments);
264 for (auto& seg : segments) {
265 seg.reserve(pixels_per_frame);
266 }
267
268 // Extract segments from pixel data using SIMD optimization
269 // DICOM RLE stores each byte plane separately
270 // For 16-bit: high byte first, then low byte
271 // For color: each color component separately
272
273 if (bytes_per_sample == 1) {
274 // 8-bit samples
275 if (params.samples_per_pixel == 1) {
276 // Grayscale: single segment - direct copy
277 segments[0].assign(pixel_data.begin(), pixel_data.end());
278 } else if (params.samples_per_pixel == 3) {
279 // Color (RGB): 3 segments - use SIMD deinterleaving
280 segments[0].resize(pixels_per_frame);
281 segments[1].resize(pixels_per_frame);
282 segments[2].resize(pixels_per_frame);
284 pixel_data.data(),
285 segments[0].data(),
286 segments[1].data(),
287 segments[2].data(),
288 pixels_per_frame);
289 } else {
290 // Other sample counts: scalar fallback
291 for (size_t i = 0; i < pixels_per_frame; ++i) {
292 for (int s = 0; s < params.samples_per_pixel; ++s) {
293 segments[s].push_back(pixel_data[i * params.samples_per_pixel + s]);
294 }
295 }
296 }
297 } else {
298 // 16-bit samples (little-endian input)
299 // DICOM RLE stores: all high bytes, then all low bytes
300 if (params.samples_per_pixel == 1) {
301 // Grayscale: 2 segments (high byte, low byte) - use SIMD
302 segments[0].resize(pixels_per_frame);
303 segments[1].resize(pixels_per_frame);
305 pixel_data.data(),
306 segments[0].data(), // High byte
307 segments[1].data(), // Low byte
308 pixels_per_frame);
309 } else if (params.samples_per_pixel == 3) {
310 // 16-bit Color: 6 segments - SIMD for each color component
311 // First deinterleave RGB, then split each into high/low
312 std::vector<uint8_t> r_plane(pixels_per_frame * 2);
313 std::vector<uint8_t> g_plane(pixels_per_frame * 2);
314 std::vector<uint8_t> b_plane(pixels_per_frame * 2);
315
316 // Deinterleave 16-bit RGB (scalar for now, 16-bit RGB is rare)
317 for (size_t i = 0; i < pixels_per_frame; ++i) {
318 size_t src_idx = i * 6; // 3 samples * 2 bytes
319 size_t dst_idx = i * 2;
320 r_plane[dst_idx] = pixel_data[src_idx];
321 r_plane[dst_idx + 1] = pixel_data[src_idx + 1];
322 g_plane[dst_idx] = pixel_data[src_idx + 2];
323 g_plane[dst_idx + 1] = pixel_data[src_idx + 3];
324 b_plane[dst_idx] = pixel_data[src_idx + 4];
325 b_plane[dst_idx + 1] = pixel_data[src_idx + 5];
326 }
327
328 // Split each color plane into high/low using SIMD
329 segments[0].resize(pixels_per_frame); // R high
330 segments[1].resize(pixels_per_frame); // R low
331 segments[2].resize(pixels_per_frame); // G high
332 segments[3].resize(pixels_per_frame); // G low
333 segments[4].resize(pixels_per_frame); // B high
334 segments[5].resize(pixels_per_frame); // B low
335
336 simd::split_16bit_to_planes(r_plane.data(), segments[0].data(),
337 segments[1].data(), pixels_per_frame);
338 simd::split_16bit_to_planes(g_plane.data(), segments[2].data(),
339 segments[3].data(), pixels_per_frame);
340 simd::split_16bit_to_planes(b_plane.data(), segments[4].data(),
341 segments[5].data(), pixels_per_frame);
342 } else {
343 // Other sample counts: scalar fallback
344 for (size_t i = 0; i < pixels_per_frame; ++i) {
345 for (int s = 0; s < params.samples_per_pixel; ++s) {
346 size_t idx = (i * params.samples_per_pixel + s) * 2;
347 segments[s * 2].push_back(pixel_data[idx + 1]); // High byte
348 segments[s * 2 + 1].push_back(pixel_data[idx]); // Low byte
349 }
350 }
351 }
352 }
353
354 // Encode each segment
355 std::vector<std::vector<uint8_t>> encoded_segments(num_segments);
356 for (int i = 0; i < num_segments; ++i) {
357 encode_rle_segment(segments[i], encoded_segments[i]);
358 }
359
360 // Build output with RLE header
361 std::vector<uint8_t> output;
362
363 // Calculate total size (header + all segments, each padded to even length)
364 size_t total_size = kRLEHeaderSize;
365 for (const auto& seg : encoded_segments) {
366 total_size += seg.size();
367 if (seg.size() % 2 != 0) {
368 ++total_size; // Padding byte
369 }
370 }
371 output.reserve(total_size);
372
373 // Write header (16 x 4-byte offsets)
374 output.resize(kRLEHeaderSize, 0);
375
376 // First 4 bytes: number of segments
377 write_le32(output.data(), static_cast<uint32_t>(num_segments));
378
379 // Calculate and write segment offsets
380 uint32_t current_offset = kRLEHeaderSize;
381 for (int i = 0; i < num_segments; ++i) {
382 write_le32(output.data() + 4 + i * 4, current_offset);
383 current_offset += static_cast<uint32_t>(encoded_segments[i].size());
384 if (encoded_segments[i].size() % 2 != 0) {
385 ++current_offset; // Account for padding
386 }
387 }
388
389 // Write encoded segments
390 for (const auto& seg : encoded_segments) {
391 output.insert(output.end(), seg.begin(), seg.end());
392 if (seg.size() % 2 != 0) {
393 output.push_back(0); // Padding byte
394 }
395 }
396
397 image_params output_params = params;
398 return kcenon::pacs::ok<compression_result>(compression_result{std::move(output), output_params});
399 }
400
402 std::span<const uint8_t> compressed_data,
403 const image_params& params) const {
404
405 const uint8_t* header = compressed_data.data();
406
407 // Read number of segments from header
408 uint32_t num_segments = read_le32(header);
409 if (num_segments == 0 || num_segments > kMaxSegments) {
411 "Invalid RLE segment count: " + std::to_string(num_segments));
412 }
413
414 int expected_segments = calculate_segment_count(params);
415 if (static_cast<int>(num_segments) != expected_segments) {
417 "Segment count mismatch: expected " + std::to_string(expected_segments) +
418 ", got " + std::to_string(num_segments));
419 }
420
421 // Read segment offsets
422 std::vector<uint32_t> offsets(num_segments);
423 for (uint32_t i = 0; i < num_segments; ++i) {
424 offsets[i] = read_le32(header + 4 + i * 4);
425 if (offsets[i] >= compressed_data.size()) {
427 "Invalid segment offset: " + std::to_string(offsets[i]));
428 }
429 }
430
431 // Calculate segment sizes
432 std::vector<size_t> sizes(num_segments);
433 for (uint32_t i = 0; i < num_segments; ++i) {
434 if (i + 1 < num_segments) {
435 sizes[i] = offsets[i + 1] - offsets[i];
436 } else {
437 sizes[i] = compressed_data.size() - offsets[i];
438 }
439 }
440
441 size_t pixels_per_frame = static_cast<size_t>(params.width) * params.height;
442 int bytes_per_sample = (params.bits_allocated + 7) / 8;
443
444 // Decode each segment
445 std::vector<std::vector<uint8_t>> decoded_segments(num_segments);
446 for (uint32_t i = 0; i < num_segments; ++i) {
447 std::span<const uint8_t> segment_data(
448 compressed_data.data() + offsets[i], sizes[i]);
449 auto segment_result = decode_rle_segment(segment_data, pixels_per_frame);
450 if (segment_result.is_err()) {
453 "Segment " + std::to_string(i) + ": " + segment_result.error().message);
454 }
455 decoded_segments[i] = std::move(segment_result.value());
456
457 if (decoded_segments[i].size() != pixels_per_frame) {
459 "Segment " + std::to_string(i) + " decoded size mismatch: expected " +
460 std::to_string(pixels_per_frame) + ", got " +
461 std::to_string(decoded_segments[i].size()));
462 }
463 }
464
465 // Reconstruct pixel data from segments using SIMD optimization
466 size_t output_size = pixels_per_frame * params.samples_per_pixel * bytes_per_sample;
467 std::vector<uint8_t> output(output_size);
468
469 if (bytes_per_sample == 1) {
470 // 8-bit samples
471 if (params.samples_per_pixel == 1) {
472 // Grayscale: direct move
473 output = std::move(decoded_segments[0]);
474 } else if (params.samples_per_pixel == 3) {
475 // Color (RGB): interleave samples using SIMD
477 decoded_segments[0].data(),
478 decoded_segments[1].data(),
479 decoded_segments[2].data(),
480 output.data(),
481 pixels_per_frame);
482 } else {
483 // Other sample counts: scalar fallback
484 for (size_t i = 0; i < pixels_per_frame; ++i) {
485 for (int s = 0; s < params.samples_per_pixel; ++s) {
486 output[i * params.samples_per_pixel + s] = decoded_segments[s][i];
487 }
488 }
489 }
490 } else {
491 // 16-bit samples
492 if (params.samples_per_pixel == 1) {
493 // Grayscale: combine high and low byte segments using SIMD
495 decoded_segments[0].data(), // High byte
496 decoded_segments[1].data(), // Low byte
497 output.data(),
498 pixels_per_frame);
499 } else if (params.samples_per_pixel == 3) {
500 // 16-bit Color: merge each color component, then interleave
501 std::vector<uint8_t> r_plane(pixels_per_frame * 2);
502 std::vector<uint8_t> g_plane(pixels_per_frame * 2);
503 std::vector<uint8_t> b_plane(pixels_per_frame * 2);
504
505 // Merge high/low bytes for each color using SIMD
506 simd::merge_planes_to_16bit(decoded_segments[0].data(),
507 decoded_segments[1].data(),
508 r_plane.data(), pixels_per_frame);
509 simd::merge_planes_to_16bit(decoded_segments[2].data(),
510 decoded_segments[3].data(),
511 g_plane.data(), pixels_per_frame);
512 simd::merge_planes_to_16bit(decoded_segments[4].data(),
513 decoded_segments[5].data(),
514 b_plane.data(), pixels_per_frame);
515
516 // Interleave RGB (scalar for now, 16-bit RGB is rare)
517 for (size_t i = 0; i < pixels_per_frame; ++i) {
518 size_t src_idx = i * 2;
519 size_t dst_idx = i * 6; // 3 samples * 2 bytes
520 output[dst_idx] = r_plane[src_idx];
521 output[dst_idx + 1] = r_plane[src_idx + 1];
522 output[dst_idx + 2] = g_plane[src_idx];
523 output[dst_idx + 3] = g_plane[src_idx + 1];
524 output[dst_idx + 4] = b_plane[src_idx];
525 output[dst_idx + 5] = b_plane[src_idx + 1];
526 }
527 } else {
528 // Other sample counts: scalar fallback
529 for (size_t i = 0; i < pixels_per_frame; ++i) {
530 for (int s = 0; s < params.samples_per_pixel; ++s) {
531 size_t idx = (i * params.samples_per_pixel + s) * 2;
532 output[idx] = decoded_segments[s * 2 + 1][i]; // Low byte
533 output[idx + 1] = decoded_segments[s * 2][i]; // High byte
534 }
535 }
536 }
537 }
538
539 // Build output parameters
540 image_params output_params;
541 output_params.width = params.width;
542 output_params.height = params.height;
543 output_params.bits_allocated = params.bits_allocated;
544 output_params.bits_stored = params.bits_stored > 0 ? params.bits_stored : params.bits_allocated;
545 output_params.high_bit = output_params.bits_stored - 1;
546 output_params.samples_per_pixel = params.samples_per_pixel;
547 output_params.planar_configuration = 0; // Always interleaved output
548 output_params.pixel_representation = params.pixel_representation;
549 output_params.photometric = params.photometric;
550
551 return kcenon::pacs::ok<compression_result>(compression_result{std::move(output), output_params});
552 }
553};
554
555// rle_codec implementation
556
557rle_codec::rle_codec() : impl_(std::make_unique<impl>()) {}
558
559rle_codec::~rle_codec() = default;
560
561rle_codec::rle_codec(rle_codec&&) noexcept = default;
562
563rle_codec& rle_codec::operator=(rle_codec&&) noexcept = default;
564
565std::string_view rle_codec::transfer_syntax_uid() const noexcept {
566 return kTransferSyntaxUID;
567}
568
569std::string_view rle_codec::name() const noexcept {
570 return "RLE Lossless";
571}
572
573bool rle_codec::is_lossy() const noexcept {
574 return false;
575}
576
577bool rle_codec::can_encode(const image_params& params) const noexcept {
578 // RLE supports 8-bit and 16-bit samples
579 if (params.bits_allocated != 8 && params.bits_allocated != 16) {
580 return false;
581 }
582 // 1-3 samples per pixel
583 if (params.samples_per_pixel < 1 || params.samples_per_pixel > 3) {
584 return false;
585 }
586 // Check segment count limit
587 int bytes_per_sample = (params.bits_allocated + 7) / 8;
588 int num_segments = params.samples_per_pixel * bytes_per_sample;
589 if (num_segments > kMaxSegments) {
590 return false;
591 }
592 // Valid dimensions
593 if (params.width == 0 || params.height == 0) {
594 return false;
595 }
596 return true;
597}
598
599bool rle_codec::can_decode(const image_params& params) const noexcept {
600 // Can decode if parameters are valid for RLE
601 // Width/height can be 0 (unknown) for partial validation
602 if (params.bits_allocated != 0 &&
603 params.bits_allocated != 8 &&
604 params.bits_allocated != 16) {
605 return false;
606 }
607 if (params.samples_per_pixel != 0 &&
608 (params.samples_per_pixel < 1 || params.samples_per_pixel > 3)) {
609 return false;
610 }
611 return true;
612}
613
615 std::span<const uint8_t> pixel_data,
616 const image_params& params,
617 const compression_options& options) const {
618 return impl_->encode(pixel_data, params, options);
619}
620
622 std::span<const uint8_t> compressed_data,
623 const image_params& params) const {
624 return impl_->decode(compressed_data, params);
625}
626
627} // namespace kcenon::pacs::encoding::compression
PIMPL implementation for rle_codec.
codec_result decode_frame(std::span< const uint8_t > compressed_data, const image_params &params) const
codec_result encode(std::span< const uint8_t > pixel_data, const image_params &params, const compression_options &options) const
codec_result decode(std::span< const uint8_t > compressed_data, const image_params &params) const
bool valid_for_rle(const image_params &params) const noexcept
codec_result encode_frame(std::span< const uint8_t > pixel_data, const image_params &params) const
DICOM RLE Lossless codec implementation.
Definition rle_codec.h:49
std::string_view name() const noexcept override
Returns a human-readable name for the codec.
bool can_encode(const image_params &params) const noexcept override
Checks if this codec supports the given image parameters.
rle_codec()
Constructs an RLE codec instance.
codec_result decode(std::span< const uint8_t > compressed_data, const image_params &params) const override
Decompresses RLE data.
static constexpr size_t kRLEHeaderSize
RLE header size (64 bytes: 16 x 4-byte offsets)
Definition rle_codec.h:58
codec_result encode(std::span< const uint8_t > pixel_data, const image_params &params, const compression_options &options={}) const override
Compresses pixel data to RLE format.
bool can_decode(const image_params &params) const noexcept override
Checks if this codec can decode data with given parameters.
static constexpr int kMaxSegments
Maximum number of RLE segments allowed by DICOM specification.
Definition rle_codec.h:55
bool is_lossy() const noexcept override
Checks if this codec produces lossy compression.
void merge_planes_to_16bit(const uint8_t *high, const uint8_t *low, uint8_t *dst, size_t pixel_count) noexcept
Merge high and low byte planes into 16-bit data.
Definition simd_rle.h:837
void interleaved_to_planar_rgb8(const uint8_t *src, uint8_t *r, uint8_t *g, uint8_t *b, size_t pixel_count) noexcept
Convert interleaved RGB to planar format using best available SIMD.
Definition simd_rle.h:725
void planar_to_interleaved_rgb8(const uint8_t *r, const uint8_t *g, const uint8_t *b, uint8_t *dst, size_t pixel_count) noexcept
Convert planar RGB to interleaved format using best available SIMD.
Definition simd_rle.h:763
void split_16bit_to_planes(const uint8_t *src, uint8_t *high, uint8_t *low, size_t pixel_count) noexcept
Split 16-bit data into high and low byte planes.
Definition simd_rle.h:800
constexpr int decompression_error
Definition result.h:79
@ control
Internal pipeline control messages.
Result< T > pacs_error(int code, const std::string &message, const std::string &details="")
Create a PACS error result with module context.
Definition result.h:234
Result<T> type aliases and helpers for PACS system.
SIMD optimizations for RLE codec operations.
Compression quality settings for lossy codecs.
Successful result of a compression/decompression operation.
Parameters describing image pixel data.
uint16_t samples_per_pixel
Number of samples per pixel (0028,0002) 1 for grayscale, 3 for color.
uint16_t bits_allocated
Bits allocated per pixel sample (0028,0100) Valid values: 8, 16.
uint16_t height
Image height in pixels (Rows - 0028,0010)
size_t frame_size_bytes() const noexcept
Calculates the size of uncompressed pixel data in bytes.
photometric_interpretation photometric
Photometric interpretation (0028,0004)
uint16_t planar_configuration
Planar configuration (0028,0006) 0 = interleaved (R1G1B1R2G2B2...), 1 = separate planes (RRR....
uint16_t pixel_representation
Pixel representation (0028,0103) 0 = unsigned, 1 = signed.
uint16_t width
Image width in pixels (Columns - 0028,0011)
uint16_t bits_stored
Bits stored per pixel sample (0028,0101) Must be <= bits_allocated.
uint16_t high_bit
High bit position (0028,0102) Typically bits_stored - 1.