Repository navigation
Conversation
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
|
x-ref #972 (comment) |
|
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? |
|
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
left a comment
There was a problem hiding this comment.
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_basechanges frequently from line to line. Whenever it changes,rebuildMainQTablecallsbuildQTable, which executest.q_table.resize(NumGradientTableEntries). This triggers dynamic heap allocation (mallocfor 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_tableonce infuji_compressed_block's constructor:and mutate the existing vector buffer in-place whenevermainQTable.q_table.resize(NumGradientTableEntries);
q_basechanges. 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_valis 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 contiguousstd::fill_n/memsetrange fills defined byqp0..qp4(compiling to vectormemsetinstructions), 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_evencallsfuji_decode_interpolation_even_inner, which runs table selection, fetchesqtable, and executesfuji_quant_gradient(doing 2 LUT reads from memory), only to discardgradandtableIdxand returninterp_val. - Suggestion: Eliminate
fuji_decode_interpolation_even_innerand thestd::tuplereturn entirely:- Have
fuji_decode_interpolation_even(c, col)compute onlyinterp_val(the neighborhood blend). - In
fuji_decode_sample_even(c, col, colorIdx), callfuji_decode_interpolation_evenforinterp_val, and only performselectLossyTableIndexandfuji_quant_gradientwhen 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());
std::tuple, saves CPU cycles on every skipped/interpolated pixel, and cleans up the code. - Have
2. Correctness & Bounds Safety
A. Array Bounds on gradSlot (FujiDecompressor.cpp:660)
- In
fuji_decode_sample,gradSlotis passed as a raw pointerint_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 <= 4is mathematically expected whendiffSum <= max_grad <= 7, adding an explicit assertion:or passingassert(gradient < (tableIdx == -1 ? 41 : 5));
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
StripByteCountseven when recording in lossy compressed mode, causingcount * 8 / (width * height) < bpsto 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
- Remove Diagnostic Code: Remove
std::getenv("RAWSPEED_FUJI_DIAG")andfprintf(stderr)fromFujiDecompressorImpl::decompress()(FujiDecompressor.cpp:1154). - Remove Ad-Hoc Utilities: Move or exclude the standalone
src/utilities/dnglab-crossvalidate/script folder from the core library tree. - Avoid the Sentinel Hack: In
FujiDecompressor::decompress()(FujiDecompressor.cpp:1259),kEmptyQBasesSentinelis used to bypassArray1DRef's non-null check on size 0. Slicingq_basesper strip inFujiDecompressorinto astd::vector<Array1DRef<const uint8_t>> strip_q_bases(matching howstripsis 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.
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:
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