Skip to content

FujiDecompressor: add lossy-compressed RAF decoding support - #985

Open
igoreskub wants to merge 1 commit into
darktable-org:developfrom
igoreskub:fuji-lossy-compressed-raf
Open

igoreskub wants to merge 1 commit into
darktable-org:developfrom
igoreskub:fuji-lossy-compressed-raf

Conversation

@igoreskub

Copy link
Copy Markdown

FujiDecompressor previously only handled uncompressed and lossless-compressed Fuji RAF files; lossy-compressed ("compressed" quality setting) files were rejected at header validation.

Ports the lossy decode path from dnglab/rawler's Rust implementation (rawler/src/decoders/fuji_decompressor.rs), which already unifies lossless and lossy decoding in one algorithm, reconciled against rawspeed's existing lossless-only architecture:

  • Parse the per-line quantization base (q_base) array that follows the block-offset table in lossy files.
  • Add FujiQTable, generalizing the single quantization table into four: a "main" table rebuilt whenever q_base changes between lines, plus three static tables (fixed q_base 0/1/2) selected per-pixel by local gradient magnitude.
  • Wire table selection into the sample-decode hot path (fuji_decode_interpolation_even/odd_inner, fuji_decode_sample, fuji_quant_gradient), gated throughout by header.isLossless() so lossless-file behavior is unchanged.

Cross-validated pixel-exact against dnglab/rawler's independent decoder across 449 real-world files (one X-series body, both lossless- and lossy-compressed modes across a firmware change) at 25 spot-check coordinates per file.

Fixes a related regression found during that testing: passing q_bases.data() directly into Array1DRef crashed on every lossless file, since an empty vector's .data() can be null (observed on libc++) and Array1DRef's invariant check requires non-null even at size 0. Fixed with a static sentinel byte.

Includes an opt-in pixel spot-check diagnostic (RAWSPEED_FUJI_DIAG env var, off by default) used to produce the validation results above; zero overhead when unset. Also includes
src/utilities/dnglab-crossvalidate/, the standalone script (with README) used to run that cross-validation, so others can reproduce or extend it.

Closes #232
Closes #255
Closes #332
Closes #366
Closes #406

FujiDecompressor previously only handled uncompressed and
lossless-compressed Fuji RAF files; lossy-compressed ("compressed"
quality setting) files were rejected at header validation.

Ports the lossy decode path from dnglab/rawler's Rust implementation
(rawler/src/decoders/fuji_decompressor.rs), which already unifies
lossless and lossy decoding in one algorithm, reconciled against
rawspeed's existing lossless-only architecture:

- Parse the per-line quantization base (q_base) array that follows
  the block-offset table in lossy files.
- Add FujiQTable, generalizing the single quantization table into
  four: a "main" table rebuilt whenever q_base changes between
  lines, plus three static tables (fixed q_base 0/1/2) selected
  per-pixel by local gradient magnitude.
- Wire table selection into the sample-decode hot path
  (fuji_decode_interpolation_even/odd_inner, fuji_decode_sample,
  fuji_quant_gradient), gated throughout by header.isLossless() so
  lossless-file behavior is unchanged.

Cross-validated pixel-exact against dnglab/rawler's independent
decoder across 449 real-world files (one X-series body, both
lossless- and lossy-compressed modes across a firmware change) at
25 spot-check coordinates per file.

Fixes a related regression found during that testing: passing
q_bases.data() directly into Array1DRef crashed on every lossless
file, since an empty vector's .data() can be null (observed on
libc++) and Array1DRef's invariant check requires non-null even at
size 0. Fixed with a static sentinel byte.

Includes an opt-in pixel spot-check diagnostic (RAWSPEED_FUJI_DIAG
env var, off by default) used to produce the validation results
above; zero overhead when unset. Also includes
src/utilities/dnglab-crossvalidate/, the standalone script (with
README) used to run that cross-validation, so others can reproduce
or extend it.

Closes darktable-org#232
Closes darktable-org#255
Closes darktable-org#332
Closes darktable-org#366
Closes darktable-org#406
@igoreskub
igoreskub requested a review from LebedevRI as a code owner August 28, 2026 12:27
@igoreskub igoreskub closed this Aug 28, 2026
@igoreskub igoreskub reopened this Aug 28, 2026
@kmilos

kmilos commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

x-ref #972 (comment)

@igoreskub

Copy link
Copy Markdown
Author

Thanks for the context, @kmilos — no pressure on timeline.

This represents real, tested work (449 files cross-validated against an independent decoder, two compression modes, one regression caught along the way), so happy to have it sit until someone has bandwidth. I'm also glad to stick around and maintain it going forward — respond to feedback, fix issues, extend to other bodies if needed.

Is there anyone else with merge rights who might take a look, or best to just leave this open for now?

@nsubtil

nsubtil commented Oct 12, 2026

Copy link
Copy Markdown

This addresses a pretty significant gap in Fuji camera support, would be interested. Is there a path to getting this merged? Anything that can be done to help?

@pope pope left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for putting this together. This is a feature I would very much love.

Below is technical feedback (with the help of AIs, though I tried to coax and understand the feedback as much as possible focused on improving performance.


1. Performance & Memory Bottlenecks

A. In-Place Mutation Instead of Heap Reallocations (FujiDecompressor.cpp:1033)

In fuji_decode_strip:

if (cur_line == 0 || q_base != mainQTable.q_base) {
    const int max_value = (1 << header.raw_bits) - 1;
    mainQTable = rebuildMainQTable(header, max_value, q_base);
    ...
  • Issue: In lossy RAFs, q_base changes frequently from line to line. Whenever it changes, rebuildMainQTable calls buildQTable, which executes t.q_table.resize(NumGradientTableEntries). This triggers dynamic heap allocation (malloc for 32 KB on 14-bit or 128 KB on 16-bit) and deallocation on worker threads. Under OpenMP with 8–16 threads, this causes severe heap lock contention and cache thrashing.
  • Suggestion: The buffer size is small (32 KB for 14-bit, 128 KB for 16-bit). Simply pre-allocate mainQTable.q_table once in fuji_compressed_block's constructor:
    mainQTable.q_table.resize(NumGradientTableEntries);
    and mutate the existing vector buffer in-place whenever q_base changes. This completely eliminates dynamic allocations and thread contention during decoding with minimal code changes.

B. Replace 32,768 Scalar Iterations with 9 Fast Range Fills (FujiDecompressor.cpp:179-183)

In buildQTable:

for (int i = 0; i != NumGradientTableEntries; ++i)
  t.q_table[i] = GetGradient(t, i);
  • Issue: While the monotonic loop avoids branch mispredictions, executing scalar subtractions, absolute values, comparisons, and sign tests per iteration still burns ~15 instructions per element.
  • Suggestion: Since cur_val is monotonic, the resulting gradient is piecewise constant and strictly produces values in {-4, -3, -2, -1, 0, 1, 2, 3, 4}. The entire table can be populated in ~50 nanoseconds using 9 contiguous std::fill_n / memset range fills defined by qp0..qp4 (compiling to vector memset instructions), which is roughly 100× faster.

C. Preventing Regressions on Lossless Files (FujiDecompressor.cpp:750)

  • Issue: Lossless RAFs now incur extra runtime overhead (table-index selection branching, tuple unpacking, and lossy scaling/wrapping math) on every pixel that was not present in the original decoder.
  • Suggestion:
    • Pragmatic approach: Ensure lossless files short-circuit as early as possible before any lossy branching or parameter calculation.
    • Zero-overhead approach: If desired, templating the strip decoding loop on template <bool IsLossless> allows the compiler to optimize away table selection, branches, and scaling by 1 at compile time, guaranteeing zero performance regression on lossless files.

D. Decouple Interpolation from Gradient Quantization (FujiDecompressor.cpp:863-868)

  • Issue: In X-Trans blocks, many even-line pixels are purely interpolated (no sample difference in the bitstream). Right now, fuji_decode_interpolation_even calls fuji_decode_interpolation_even_inner, which runs table selection, fetches qtable, and executes fuji_quant_gradient (doing 2 LUT reads from memory), only to discard grad and tableIdx and return interp_val.
  • Suggestion: Eliminate fuji_decode_interpolation_even_inner and the std::tuple return entirely:
    1. Have fuji_decode_interpolation_even(c, col) compute only interp_val (the neighborhood blend).
    2. In fuji_decode_sample_even(c, col, colorIdx), call fuji_decode_interpolation_even for interp_val, and only perform selectLossyTableIndex and fuji_quant_gradient when decoding an actual sample:
      int interp_val = fuji_decode_interpolation_even(c, col);
      
      // Only do table selection and gradient math for real samples:
      int Rb = lines(c - 1, 1 + (2 * col) + 0);
      int Rc = lines(c - 1, 1 + (2 * (col - 1)) + 0);
      int Rf = lines(c - 2, 1 + (2 * col) + 0);
      
      int tableIdx = selectLossyTableIndex(common_info, header, mainQTable.q_base,
                                           std::abs(Rf - Rb) + std::abs(Rc - Rb));
      const FujiQTable& qtable =
          tableIdx == -1 ? mainQTable : common_info.staticLossyTables[tableIdx];
      int grad = fuji_quant_gradient(qtable, Rb - Rf, Rc - Rb);
      
      if (tableIdx == -1) {
        return fuji_decode_sample(grad, interp_val, mainQTable,
                                  grad_even[colorIdx].data());
      }
      return fuji_decode_sample(grad, interp_val,
                                common_info.staticLossyTables[tableIdx],
                                grad_even_lossy[colorIdx][tableIdx].data());
    This eliminates std::tuple, saves CPU cycles on every skipped/interpolated pixel, and cleans up the code.

2. Correctness & Bounds Safety

A. Array Bounds on gradSlot (FujiDecompressor.cpp:660)

  • In fuji_decode_sample, gradSlot is passed as a raw pointer int_pair*.
  • For the main table it points to an array of size 41, while for static lossy tables it points to an array of size 5 (grad_even_lossy).
  • While gradient <= 4 is mathematically expected when diffSum <= max_grad <= 7, adding an explicit assertion:
    assert(gradient < (tableIdx == -1 ? 41 : 5));
    or passing Array1DRef<int_pair> prevents out-of-bounds writes if a corrupted bitstream is encountered during fuzzing.

B. Upstream Camera Detection (RafDecoder.cpp)

  • On certain bodies/firmwares (such as initial Fujifilm X-H2S firmware), the camera wrote the uncompressed byte count into StripByteCounts even when recording in lossy compressed mode, causing count * 8 / (width * height) < bps to fail.
  • It would be worth checking whether probing the header magic (0x4953) is safer than relying solely on the byte count heuristic.

3. Upstream Cleanliness & Style

  1. Remove Diagnostic Code: Remove std::getenv("RAWSPEED_FUJI_DIAG") and fprintf(stderr) from FujiDecompressorImpl::decompress() (FujiDecompressor.cpp:1154).
  2. Remove Ad-Hoc Utilities: Move or exclude the standalone src/utilities/dnglab-crossvalidate/ script folder from the core library tree.
  3. Avoid the Sentinel Hack: In FujiDecompressor::decompress() (FujiDecompressor.cpp:1259), kEmptyQBasesSentinel is used to bypass Array1DRef's non-null check on size 0. Slicing q_bases per strip in FujiDecompressor into a std::vector<Array1DRef<const uint8_t>> strip_q_bases (matching how strips is handled) provides a cleaner design without sentinels or global offset arithmetic.

Disclosure: This review was prepared with AI-assisted code analysis and personally reviewed for accuracy and relevance.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants