RawSpeed
fast raw decoding library
Loading...
Searching...
No Matches
NikonDecompressor.cpp
Go to the documentation of this file.
1/*
2 RawSpeed - RAW file decoder.
3
4 Copyright (C) 2009-2014 Klaus Post
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with this library; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19*/
20
22#include "adt/Array1DRef.h"
23#include "adt/Array2DRef.h"
24#include "adt/Bit.h"
25#include "adt/Casts.h"
26#include "adt/Invariant.h"
27#include "adt/Point.h"
30#include "codes/HuffmanCode.h"
32#include "common/Common.h"
33#include "common/RawImage.h"
35#include "io/Buffer.h"
36#include "io/ByteStream.h"
37#include <array>
38#include <cassert>
39#include <cstddef>
40#include <cstdint>
41#include <cstdio>
42#include <utility>
43#include <vector>
44
45namespace rawspeed {
46
47const std::array<std::array<std::array<uint8_t, 16>, 2>, 6>
49 {{/* 12-bit lossy */
50 {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
51 {5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}}},
52 {{/* 12-bit lossy after split */
53 {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
54 {0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}}},
55 {{/* 12-bit lossless */
56 {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
57 {5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}}},
58 {{/* 14-bit lossy */
59 {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
60 {5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}}},
61 {{/* 14-bit lossy after split */
62 {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0},
63 {8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}}},
64 {{/* 14-bit lossless */
65 {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0},
66 {7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}},
67 }};
68
69namespace {
70
71const std::array<uint32_t, 32> bitMask = {
72 {0xffffffff, 0x7fffffff, 0x3fffffff, 0x1fffffff, 0x0fffffff, 0x07ffffff,
73 0x03ffffff, 0x01ffffff, 0x00ffffff, 0x007fffff, 0x003fffff, 0x001fffff,
74 0x000fffff, 0x0007ffff, 0x0003ffff, 0x0001ffff, 0x0000ffff, 0x00007fff,
75 0x00003fff, 0x00001fff, 0x00000fff, 0x000007ff, 0x000003ff, 0x000001ff,
76 0x000000ff, 0x0000007f, 0x0000003f, 0x0000001f, 0x0000000f, 0x00000007,
77 0x00000003, 0x00000001}};
78
80 bool mUseBigtable = true;
81 bool mDNGCompatible = false;
82
83 struct PrefixCodeDecoder final {
84 /*
85 * These two fields directly represent the contents of a JPEG DHT
86 * marker
87 */
88 std::array<uint32_t, 17> bits;
89 std::array<uint32_t, 256> huffval;
90
91 /*
92 * The remaining fields are computed from the above to allow more
93 * efficient coding and decoding. These fields should be considered
94 * private to the Huffman compression & decompression modules.
95 */
96
97 std::array<uint16_t, 17> mincode;
98 std::array<int, 18> maxcode;
99 std::array<int16_t, 17> valptr;
100 std::array<uint32_t, 256> numbits;
101 std::vector<int> bigTable;
103 };
105
107 int p;
108 int i;
109 int l;
110 int lastp;
111 int si;
112 std::array<int8_t, 257> huffsize;
113 std::array<uint16_t, 257> huffcode;
114 uint16_t code;
115 int size;
116 int value;
117 int ll;
118 int ul;
119
120 /*
121 * Figure C.1: make table of Huffman code length for each symbol
122 * Note that this is in code-length order.
123 */
124 p = 0;
125 for (l = 1; l <= 16; l++) {
126 for (i = 1; i <= static_cast<int>(dctbl1.bits[l]); i++) {
127 huffsize[p] = static_cast<int8_t>(l);
128 ++p;
129 if (p > 256)
130 ThrowRDE("LJpegDecoder::createPrefixCodeDecoder: Code length too "
131 "long. Corrupt data.");
132 }
133 }
134 huffsize[p] = 0;
135 lastp = p;
136
137 /*
138 * Figure C.2: generate the codes themselves
139 * Note that this is in code-length order.
140 */
141 code = 0;
142 si = huffsize[0];
143 p = 0;
144 while (huffsize[p]) {
145 while ((static_cast<int>(huffsize[p])) == si) {
146 huffcode[p] = code;
147 ++p;
148 code++;
149 }
150 code <<= 1;
151 si++;
152 if (p > 256)
153 ThrowRDE(
154 "createPrefixCodeDecoder: Code length too long. Corrupt data.");
155 }
156
157 /*
158 * Figure F.15: generate decoding tables
159 */
160 dctbl1.mincode[0] = 0;
161 dctbl1.maxcode[0] = 0;
162 p = 0;
163 for (l = 1; l <= 16; l++) {
164 if (dctbl1.bits[l]) {
165 dctbl1.valptr[l] = implicit_cast<int16_t>(p);
166 dctbl1.mincode[l] = huffcode[p];
167 p += dctbl1.bits[l];
168 dctbl1.maxcode[l] = huffcode[p - 1];
169 } else {
170 dctbl1.valptr[l] =
171 0xff; // This check must be present to avoid crash on junk
172 dctbl1.maxcode[l] = -1;
173 }
174 if (p > 256)
175 ThrowRDE(
176 "createPrefixCodeDecoder: Code length too long. Corrupt data.");
177 }
178
179 /*
180 * We put in this value to ensure HuffDecode terminates.
181 */
182 dctbl1.maxcode[17] = 0xFFFFFL;
183
184 /*
185 * Build the numbits, value lookup tables.
186 * These table allow us to gather 8 bits from the bits stream,
187 * and immediately lookup the size and value of the huffman codes.
188 * If size is zero, it means that more than 8 bits are in the huffman
189 * code (this happens about 3-4% of the time).
190 */
191 dctbl1.numbits.fill(0);
192 for (p = 0; p < lastp; p++) {
193 size = huffsize[p];
194 if (size <= 8) {
195 value = dctbl1.huffval[p];
196 code = huffcode[p];
197 ll = code << (8 - size);
198 if (size < 8) {
199 ul = ll | bitMask[24 + size];
200 } else {
201 ul = ll;
202 }
203 if (ul > 256 || ll > ul)
204 ThrowRDE(
205 "createPrefixCodeDecoder: Code length too long. Corrupt data.");
206 for (i = ll; i <= ul; i++) {
207 dctbl1.numbits[i] = size | (value << 4);
208 }
209 }
210 }
211 if (mUseBigtable)
213 dctbl1.initialized = true;
214 }
215
216 /************************************
217 * Bitable creation
218 *
219 * This is expanding the concept of fast lookups
220 *
221 * A complete table for 14 arbitrary bits will be
222 * created that enables fast lookup of number of bits used,
223 * and final delta result.
224 * Hit rate is about 90-99% for typical LJPEGS, usually about 98%
225 *
226 ************************************/
227
229 const uint32_t bits =
230 14; // HuffDecode functions must be changed, if this is modified.
231 const uint32_t size = 1 << bits;
232 int rv = 0;
233 int temp;
234 uint32_t l;
235
236 dctbl1.bigTable.resize(size);
237 for (uint32_t i = 0; i < size; i++) {
238 auto input = implicit_cast<uint16_t>(i << 2); // Calculate input value
239 int code = input >> 8; // Get 8 bits
240 uint32_t val = dctbl1.numbits[code];
241 l = val & 15;
242 if (l) {
243 rv = val >> 4;
244 } else {
245 l = 8;
246 while (code > dctbl1.maxcode[l]) {
247 temp = extractHighBits(input, l, /*effectiveBitwidth=*/15) & 1;
248 code = (code << 1) | temp;
249 l++;
250 }
251
252 /*
253 * With garbage input we may reach the sentinel value l = 17.
254 */
255
256 if (l > 16 || dctbl1.valptr[l] == 0xff) {
257 dctbl1.bigTable[i] = 0xff;
258 continue;
259 }
260 rv = dctbl1.huffval[dctbl1.valptr[l] + (code - dctbl1.mincode[l])];
261 }
262
263 if (rv == 16) {
264 if (mDNGCompatible)
265 dctbl1.bigTable[i] = (-(32768 << 8)) | (16 + l);
266 else
267 dctbl1.bigTable[i] = (-(32768 << 8)) | l;
268 continue;
269 }
270
271 if (rv + l > bits) {
272 dctbl1.bigTable[i] = 0xff;
273 continue;
274 }
275
276 if (rv) {
277 int x = extractHighBits(input, l + rv) & ((1 << rv) - 1);
278 if ((x & (1 << (rv - 1))) == 0)
279 x -= (1 << rv) - 1;
280 dctbl1.bigTable[i] =
281 static_cast<int>((static_cast<unsigned>(x) << 8) | (l + rv));
282 } else {
283 dctbl1.bigTable[i] = l;
284 }
285 }
286 }
287
288public:
290 uint32_t acc = 0;
291 for (uint32_t i = 0; i < 16; i++) {
292 dctbl1.bits[i + 1] = data[i];
293 acc += dctbl1.bits[i + 1];
294 }
295 dctbl1.bits[0] = 0;
296 return acc;
297 }
298
300 for (int i = 0; i < data.size(); i++)
301 dctbl1.huffval[i] = data(i);
302 }
303
304 void setup([[maybe_unused]] bool fullDecode_,
305 [[maybe_unused]] bool fixDNGBug16_) {
307 }
308
309 /*
310 *--------------------------------------------------------------
311 *
312 * HuffDecode --
313 *
314 * Taken from Figure F.16: extract next coded symbol from
315 * input stream. This should becode a macro.
316 *
317 * Results:
318 * Next coded symbol
319 *
320 * Side effects:
321 * Bitstreamer is parsed.
322 *
323 *--------------------------------------------------------------
324 */
326 int rv;
327 int l;
328 int temp;
329 int code;
330 unsigned val;
331
332 bits.fill();
333 code = bits.peekBitsNoFill(14);
334 val = static_cast<unsigned>(dctbl1.bigTable[code]);
335 if ((val & 0xff) != 0xff) {
336 bits.skipBitsNoFill(val & 0xff);
337 return static_cast<int>(val) >> 8;
338 }
339
340 rv = 0;
341 code = bits.peekBitsNoFill(8);
342 val = dctbl1.numbits[code];
343 l = val & 15;
344 if (l) {
345 bits.skipBitsNoFill(l);
346 rv = static_cast<int>(val) >> 4;
347 } else {
348 bits.skipBitsNoFill(8);
349 l = 8;
350 while (code > dctbl1.maxcode[l]) {
351 temp = bits.getBitsNoFill(1);
352 code = (code << 1) | temp;
353 l++;
354 }
355
356 if (l > 16) {
357 ThrowRDE("Corrupt JPEG data: bad Huffman code:%d\n", l);
358 } else {
359 rv = dctbl1.huffval[dctbl1.valptr[l] + (code - dctbl1.mincode[l])];
360 }
361 }
362
363 if (rv == 16)
364 return -32768;
365
366 /*
367 * Section F.2.2.1: decode the difference and
368 * Figure F.12: extend sign bit
369 */
370 uint32_t len = rv & 15;
371 uint32_t shl = rv >> 4;
372 int diff = ((bits.getBits(len - shl) << 1) + 1) << shl >> 1;
373 if ((diff & (1 << (len - 1))) == 0)
374 diff -= (1 << len) - !shl;
375 return diff;
376 }
377};
378
379} // namespace
380
383 uint32_t v0, uint32_t v1,
384 uint32_t* split) {
385 // Nikon Z7 12/14 bit compressed hack.
386 if (v0 == 68 && v1 == 64)
387 bitsPS -= 2;
388
389 // 'curve' will hold a peace wise linearly interpolated function.
390 // there are 'csize' segments, each is 'step' values long.
391 // the very last value is not part of the used table but necessary
392 // to linearly interpolate the last segment, therefore the '+1/-1'
393 // size adjustments of 'curve'.
394 std::vector<uint16_t> curve((1 << bitsPS & 0x7fff) + 1);
395 assert(curve.size() > 1);
396
397 for (size_t i = 0; i < curve.size(); i++)
399
400 uint32_t step = 0;
401 uint32_t csize = metadata.getU16();
402 if (csize > 1)
403 step = implicit_cast<uint32_t>(curve.size() / (csize - 1));
404
405 if (v0 == 68 && (v1 == 32 || v1 == 64) && step > 0) {
406 if ((csize - 1) * step != curve.size() - 1)
407 ThrowRDE("Bad curve segment count (%u)", csize);
408
409 for (size_t i = 0; i < csize; i++)
410 curve[i * step] = metadata.getU16();
411 for (size_t i = 0; i < curve.size() - 1; i++) {
412 const uint32_t b_scale = i % step;
413
414 const auto a_pos = implicit_cast<uint32_t>(i - b_scale);
415 const uint32_t b_pos = a_pos + step;
416 assert(a_pos < curve.size());
417 assert(b_pos > 0);
418 assert(b_pos < curve.size());
419 assert(a_pos < b_pos);
420
421 const uint32_t a_scale = step - b_scale;
423 (a_scale * curve[a_pos] + b_scale * curve[b_pos]) / step);
424 }
425
426 metadata.setPosition(562);
427 *split = metadata.getU16();
428 } else if (v0 != 70) {
429 if (csize == 0 || csize > 0x4001)
430 ThrowRDE("Don't know how to compute curve! csize = %u", csize);
431
432 curve.resize(csize + 1UL);
433 assert(curve.size() > 1);
434
435 for (uint32_t i = 0; i < csize; i++) {
436 curve[i] = metadata.getU16();
437 }
438 }
439
440 // and drop the last value
441 curve.resize(curve.size() - 1);
442 assert(!curve.empty());
443
444 return curve;
445}
446
447template <typename Huffman>
449 Huffman ht;
450 uint32_t count =
451 ht.setNCodesPerLength(Buffer(nikon_tree[huffSelect][0].data(), 16));
452 ht.setCodeValues(
454 ht.setup(true, false);
455 return ht;
456}
457
458template <>
461 uint32_t huffSelect) {
463 uint32_t count =
464 hc.setNCodesPerLength(Buffer(nikon_tree[huffSelect][0].data(), 16));
465 hc.setCodeValues(
466 Array1DRef<const uint8_t>(nikon_tree[huffSelect][1].data(), count));
467
468 PrefixCodeDecoder<> ht(std::move(hc));
469 ht.setup(true, false);
470 return ht;
471}
472
474 uint32_t bitsPS_)
475 : mRaw(std::move(raw)), bitsPS(bitsPS_) {
476 if (mRaw->getCpp() != 1 || mRaw->getDataType() != RawImageType::UINT16 ||
477 mRaw->getBpp() != sizeof(uint16_t))
478 ThrowRDE("Unexpected component count / data type");
479
480 if (!mRaw->dim.hasPositiveArea() || mRaw->dim.x % 2 != 0 ||
481 mRaw->dim.x > 8288 || mRaw->dim.y > 5520)
482 ThrowRDE("Unexpected image dimensions found: (%d; %d)", mRaw->dim.x,
483 mRaw->dim.y);
484
485 switch (bitsPS) {
486 case 12:
487 case 14:
488 break;
489 default:
490 ThrowRDE("Invalid bpp found: %u", bitsPS);
491 }
492
493 uint32_t v0 = metadata.getByte();
494 uint32_t v1 = metadata.getByte();
495
496 writeLog(DEBUG_PRIO::EXTRA, "Nef version v0:%u, v1:%u", v0, v1);
497
498 if (v0 == 73 || v1 == 88)
499 metadata.skipBytes(2110);
500
501 if (v0 == 70)
502 huffSelect = 2;
503 if (bitsPS == 14)
504 huffSelect += 3;
505
506 pUp[0][0] = metadata.getU16();
507 pUp[1][0] = metadata.getU16();
508 pUp[0][1] = metadata.getU16();
509 pUp[1][1] = metadata.getU16();
510
511 curve = createCurve(metadata, bitsPS, v0, v1, &split);
512
513 // If the 'split' happens outside of the image, it does not actually happen.
514 if (split >= static_cast<unsigned>(mRaw->dim.y))
515 split = 0;
516}
517
518template <typename Huffman>
520 int end_y) {
522
523 const Array2DRef<uint16_t> out(mRaw->getU16DataAsUncroppedArray2DRef());
524
525 // allow gcc to devirtualize the calls below
526 auto* rawdata = reinterpret_cast<RawImageDataU16*>(mRaw.get());
527
528 invariant(out.width() % 2 == 0);
529 invariant(out.width() >= 2);
530 for (int row = start_y; row < end_y; row++) {
531 std::array<int, 2> pred = pUp[row & 1];
532 for (int col = 0; col < out.width(); col++) {
533 pred[col & 1] += ht.decodeDifference(bits);
534 if (col < 2)
535 pUp[row & 1][col & 1] = pred[col & 1];
536 rawdata->setWithLookUp(clampBits(pred[col & 1], 15),
537 reinterpret_cast<std::byte*>(&out(row, col)),
538 &random);
539 }
540 }
541}
542
544 bool uncorrectedRawValues) {
545 RawImageCurveGuard curveHandler(&mRaw, curve, uncorrectedRawValues);
546
547 BitStreamerMSB bits(input);
548
549 random = bits.peekBits(24);
550
551 invariant(split == 0 || split < static_cast<unsigned>(mRaw->dim.y));
552
553 if (!split) {
554 decompress<PrefixCodeDecoder<>>(bits, 0, mRaw->dim.y);
555 } else {
557 huffSelect += 1;
559 }
560}
561
562} // namespace rawspeed
#define invariant(expr)
Definition Invariant.h:27
#define ThrowRDE(...)
assert(dim.area() >=area)
dim x
Definition Common.cpp:50
int RAWSPEED_READONLY size() const
int RAWSPEED_READONLY width() const
uint32_t peekBits(int nbits)
uint32_t getBitsNoFill(int nbits)
void skipBitsNoFill(int nbits)
uint32_t getBits(int nbits)
uint32_t RAWSPEED_READONLY peekBitsNoFill(int nbits)
void fill(int nbits=Cache::MaxGetBits)
uint32_t setNCodesPerLength(Buffer data)
Definition HuffmanCode.h:99
void setCodeValues(Array1DRef< const typename Traits::CodeValueTy > data)
std::array< std::array< int, 2 >, 2 > pUp
static const std::array< std::array< std::array< uint8_t, 16 >, 2 >, 6 > nikon_tree
static Huffman createPrefixCodeDecoder(uint32_t huffSelect)
std::vector< uint16_t > curve
static std::vector< uint16_t > createCurve(ByteStream &metadata, uint32_t bitsPS, uint32_t v0, uint32_t v1, uint32_t *split)
NikonDecompressor(RawImage raw, ByteStream metadata, uint32_t bitsPS)
void decompress(Array1DRef< const uint8_t > input, bool uncorrectedRawValues)
static T createPrefixCodeDecoder(rawspeed::ByteStream &bs)
Definition Common.h:147
static const rawspeed::CameraMetaData metadata
Definition main.cpp:54
PrefixCodeLUTDecoder< CodeTag, PrefixCodeLookupDecoder< CodeTag > > PrefixCodeDecoder
constexpr RAWSPEED_READNONE Ttgt implicit_cast(Tsrc value)
Definition Casts.h:32
void writeLog(DEBUG_PRIO priority, const char *format,...)
Definition Common.cpp:37
constexpr RAWSPEED_READNONE T extractHighBits(T value, unsigned nBits, unsigned effectiveBitwidth=bitwidth< T >())
Definition Bit.h:120
constexpr auto RAWSPEED_READNONE clampBits(T value, unsigned int nBits)
Definition Bit.h:75
constexpr RAWSPEED_READNONE Ttgt implicit_cast(Tsrc value)
Definition Casts.h:32