-
Notifications
You must be signed in to change notification settings - Fork 30
/
tiny_dng_writer.h
2583 lines (2152 loc) · 70.9 KB
/
tiny_dng_writer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// TinyDNGWriter, single header only DNG writer in C++11.
//
/*
The MIT License (MIT)
Copyright (c) 2016 - 2020 Syoyo Fujita.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef TINY_DNG_WRITER_H_
#define TINY_DNG_WRITER_H_
#include <sstream>
#include <vector>
#include <cstring>
namespace tinydngwriter {
typedef enum {
TIFFTAG_SUB_FILETYPE = 254,
TIFFTAG_IMAGE_WIDTH = 256,
TIFFTAG_IMAGE_LENGTH = 257,
TIFFTAG_BITS_PER_SAMPLE = 258,
TIFFTAG_COMPRESSION = 259,
TIFFTAG_PHOTOMETRIC = 262,
TIFFTAG_IMAGEDESCRIPTION = 270,
TIFFTAG_STRIP_OFFSET = 273,
TIFFTAG_SAMPLES_PER_PIXEL = 277,
TIFFTAG_ROWS_PER_STRIP = 278,
TIFFTAG_STRIP_BYTE_COUNTS = 279,
TIFFTAG_PLANAR_CONFIG = 284,
TIFFTAG_ORIENTATION = 274,
TIFFTAG_XRESOLUTION = 282, // rational
TIFFTAG_YRESOLUTION = 283, // rational
TIFFTAG_RESOLUTION_UNIT = 296,
TIFFTAG_SOFTWARE = 305,
TIFFTAG_SAMPLEFORMAT = 339,
// DNG extension
TIFFTAG_CFA_REPEAT_PATTERN_DIM = 33421,
TIFFTAG_CFA_PATTERN = 33422,
TIFFTAG_DNG_VERSION = 50706,
TIFFTAG_DNG_BACKWARD_VERSION = 50707,
TIFFTAG_UNIQUE_CAMERA_MODEL = 50708,
TIFFTAG_CHRROMA_BLUR_RADIUS = 50703,
TIFFTAG_BLACK_LEVEL_REPEAT_DIM = 50713,
TIFFTAG_BLACK_LEVEL = 50714,
TIFFTAG_WHITE_LEVEL = 50717,
TIFFTAG_COLOR_MATRIX1 = 50721,
TIFFTAG_COLOR_MATRIX2 = 50722,
TIFFTAG_CAMERA_CALIBRATION1 = 50723,
TIFFTAG_CAMERA_CALIBRATION2 = 50724,
TIFFTAG_ANALOG_BALANCE = 50727,
TIFFTAG_AS_SHOT_NEUTRAL = 50728,
TIFFTAG_AS_SHOT_WHITE_XY = 50729,
TIFFTAG_CALIBRATION_ILLUMINANT1 = 50778,
TIFFTAG_CALIBRATION_ILLUMINANT2 = 50779,
TIFFTAG_EXTRA_CAMERA_PROFILES = 50933,
TIFFTAG_PROFILE_NAME = 50936,
TIFFTAG_AS_SHOT_PROFILE_NAME = 50934,
TIFFTAG_DEFAULT_BLACK_RENDER = 51110,
TIFFTAG_ACTIVE_AREA = 50829,
TIFFTAG_FORWARD_MATRIX1 = 50964,
TIFFTAG_FORWARD_MATRIX2 = 50965
} Tag;
// SUBFILETYPE(bit field)
static const int FILETYPE_REDUCEDIMAGE = 1;
static const int FILETYPE_PAGE = 2;
static const int FILETYPE_MASK = 4;
// PLANARCONFIG
static const int PLANARCONFIG_CONTIG = 1;
static const int PLANARCONFIG_SEPARATE = 2;
// COMPRESSION
// TODO(syoyo) more compressin types.
static const int COMPRESSION_NONE = 1;
static const int COMPRESSION_NEW_JPEG = 7;
// ORIENTATION
static const int ORIENTATION_TOPLEFT = 1;
static const int ORIENTATION_TOPRIGHT = 2;
static const int ORIENTATION_BOTRIGHT = 3;
static const int ORIENTATION_BOTLEFT = 4;
static const int ORIENTATION_LEFTTOP = 5;
static const int ORIENTATION_RIGHTTOP = 6;
static const int ORIENTATION_RIGHTBOT = 7;
static const int ORIENTATION_LEFTBOT = 8;
// RESOLUTIONUNIT
static const int RESUNIT_NONE = 1;
static const int RESUNIT_INCH = 2;
static const int RESUNIT_CENTIMETER = 2;
// PHOTOMETRIC
// TODO(syoyo): more photometric types.
static const int PHOTOMETRIC_WHITE_IS_ZERO = 0; // For bilevel and grayscale
static const int PHOTOMETRIC_BLACK_IS_ZERO = 1; // For bilevel and grayscale
static const int PHOTOMETRIC_RGB = 2; // Default
static const int PHOTOMETRIC_CFA = 32803; // DNG ext
static const int PHOTOMETRIC_LINEARRAW = 34892; // DNG ext
// Sample format
static const int SAMPLEFORMAT_UINT = 1; // Default
static const int SAMPLEFORMAT_INT = 2;
static const int SAMPLEFORMAT_IEEEFP = 3; // floating point
struct IFDTag {
unsigned short tag;
unsigned short type;
unsigned int count;
unsigned int offset_or_value;
};
// 12 bytes.
class DNGImage {
public:
DNGImage();
~DNGImage() {}
///
/// Optional: Explicitly specify endian.
/// Must be called before calling other Set methods.
///
void SetBigEndian(bool big_endian);
///
/// Default = 0
///
bool SetSubfileType(bool reduced_image = false, bool page = false,
bool mask = false);
bool SetImageWidth(unsigned int value);
bool SetImageLength(unsigned int value);
bool SetRowsPerStrip(unsigned int value);
bool SetSamplesPerPixel(unsigned short value);
// Set bits for each samples
bool SetBitsPerSample(const unsigned int num_samples,
const unsigned short *values);
bool SetPhotometric(unsigned short value);
bool SetPlanarConfig(unsigned short value);
bool SetOrientation(unsigned short value);
bool SetCompression(unsigned short value);
bool SetSampleFormat(const unsigned int num_samples,
const unsigned short *values);
bool SetXResolution(double value);
bool SetYResolution(double value);
bool SetResolutionUnit(const unsigned short value);
///
/// Set arbitrary string for image description.
/// Currently we limit to 1024*1024 chars at max.
///
bool SetImageDescription(const std::string &ascii);
///
/// Set arbitrary string for unique camera model name (not localized!).
/// Currently we limit to 1024*1024 chars at max.
///
bool SetUniqueCameraModel(const std::string &ascii);
///
/// Set software description(string).
/// Currently we limit to 4095 chars at max.
///
bool SetSoftware(const std::string &ascii);
bool SetActiveArea(const unsigned int values[4]);
bool SetChromaBlurRadius(double value);
/// Specify black level per sample.
bool SetBlackLevel(const unsigned int num_samples, const unsigned short *values);
/// Specify black level per sample (as rational values).
bool SetBlackLevelRational(unsigned int num_samples, const double *values);
/// Specify white level per sample.
bool SetWhiteLevelRational(unsigned int num_samples, const double *values);
/// Specify analog white balance from camera for raw values.
bool SetAnalogBalance(const unsigned int plane_count, const double *matrix_values);
/// Specify CFA repeating pattern dimensions.
bool SetCFARepeatPatternDim(const unsigned short width, const unsigned short height);
/// Specify black level repeating pattern dimensions.
bool SetBlackLevelRepeatDim(const unsigned short width, const unsigned short height);
bool SetCalibrationIlluminant1(const unsigned short value);
bool SetCalibrationIlluminant2(const unsigned short value);
/// Specify DNG version.
bool SetDNGVersion(const unsigned char a, const unsigned char b, const unsigned char c, const unsigned char d);
/// Specify transformation matrix (XYZ to reference camera native color space values, under the first calibration illuminant).
bool SetColorMatrix1(const unsigned int plane_count, const double *matrix_values);
/// Specify transformation matrix (XYZ to reference camera native color space values, under the second calibration illuminant).
bool SetColorMatrix2(const unsigned int plane_count, const double *matrix_values);
bool SetForwardMatrix1(const unsigned int plane_count, const double *matrix_values);
bool SetForwardMatrix2(const unsigned int plane_count, const double *matrix_values);
bool SetCameraCalibration1(const unsigned int plane_count, const double *matrix_values);
bool SetCameraCalibration2(const unsigned int plane_count, const double *matrix_values);
/// Specify CFA geometric pattern (left-to-right, top-to-bottom).
bool SetCFAPattern(const unsigned int num_components, const unsigned char *values);
/// Specify the selected white balance at time of capture, encoded as the coordinates of a perfectly neutral color in linear reference space values.
bool SetAsShotNeutral(const unsigned int plane_count, const double *matrix_values);
/// Specify the the selected white balance at time of capture, encoded as x-y chromaticity coordinates.
bool SetAsShotWhiteXY(const double x, const double y);
/// Set image data with packing (take 16-bit values and pack them to input_bpp values).
bool SetImageDataPacked(const unsigned short *input_buffer, const int input_count, const unsigned int input_bpp, bool big_endian);
/// Set image data.
bool SetImageData(const unsigned char *data, const size_t data_len);
/// Set image data.
bool SetImageDataJpeg(const unsigned short *data, unsigned int width, unsigned int height, unsigned int bpp);
/// Set custom field.
bool SetCustomFieldLong(const unsigned short tag, const int value);
bool SetCustomFieldULong(const unsigned short tag, const unsigned int value);
size_t GetDataSize() const { return data_os_.str().length(); }
size_t GetStripOffset() const { return data_strip_offset_; }
size_t GetStripBytes() const { return data_strip_bytes_; }
/// Write aux IFD data and strip image data to stream.
bool WriteDataToStream(std::ostream *ofs) const;
///
/// Write IFD to stream.
///
/// @param[in] data_base_offset : Byte offset to data
/// @param[in] strip_offset : Byte offset to image strip data
///
/// TODO(syoyo): Support multiple strips
///
bool WriteIFDToStream(const unsigned int data_base_offset,
const unsigned int strip_offset, std::ostream *ofs) const;
std::string Error() const { return err_; }
private:
std::ostringstream data_os_;
bool swap_endian_;
bool dng_big_endian_;
unsigned short num_fields_;
unsigned int samples_per_pixels_;
std::vector<unsigned short> bits_per_samples_;
// TODO(syoyo): Support multiple strips
size_t data_strip_offset_{0};
size_t data_strip_bytes_{0};
mutable std::string err_; // Error message
std::vector<IFDTag> ifd_tags_;
};
class DNGWriter {
public:
// TODO(syoyo): Use same endian setting with DNGImage.
DNGWriter(bool big_endian);
~DNGWriter() {}
///
/// Add DNGImage.
/// It just retains the pointer of the image, thus
/// application must not free resources until `WriteToFile` has been called.
///
bool AddImage(const DNGImage *image) {
images_.push_back(image);
return true;
}
/// Write DNG to a file.
/// Return error string to `err` when Write() returns false.
/// Returns true upon success.
bool WriteToFile(const char *filename, std::string *err) const;
private:
bool swap_endian_;
bool dng_big_endian_; // Endianness of DNG file.
std::vector<const DNGImage *> images_;
};
} // namespace tinydngwriter
#endif // TINY_DNG_WRITER_H_
#ifdef TINY_DNG_WRITER_IMPLEMENTATION
//
// TIFF format resources.
//
// http://c0de517e.blogspot.jp/2013/07/tiny-hdr-writer.html
// http://paulbourke.net/dataformats/tiff/ and
// http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
//
#include <algorithm>
#include <cassert>
#include <cfloat>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <limits>
// Undef if you want to use builtin function for clz
#if 0
#ifdef _MSC_VER
#include <intrin.h>
#endif
#endif
namespace tinydngwriter {
namespace detail {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
// Begin liblj92, Lossless JPEG decode/encoder ------------------------------
//
// With fixes: https://github.com/ilia3101/MLV-App/pull/151
/*
lj92.c
(c) Andrew Baldwin 2014
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
enum LJ92_ERRORS {
LJ92_ERROR_NONE = 0,
LJ92_ERROR_CORRUPT = -1,
LJ92_ERROR_NO_MEMORY = -2,
LJ92_ERROR_BAD_HANDLE = -3,
LJ92_ERROR_TOO_WIDE = -4
};
/*
* Encode a grayscale image supplied as 16bit values within the given bitdepth
* Read from tile in the image
* Apply delinearization if given
* Return the encoded lossless JPEG stream
*/
int lj92_encode(uint16_t *image, int width, int height, int bitdepth,
int readLength, int skipLength, uint16_t *delinearize,
int delinearizeLength, uint8_t **encoded, int *encodedLength);
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
//#define LJ92_DEBUG
/* Encoder implementation */
#if 0
uint32_t __inline clz32(uint32_t value) {
unsigned long leading_zero = 0;
if (_BitScanReverse(&leading_zero, value)) {
return 31 - leading_zero;
} else {
// Same remarks as above
return 32;
}
}
#endif
// Very simple count leading zero implementation.
static int clz32(unsigned int x) {
int n;
if (x == 0) return 32;
for (n = 0; ((x & 0x80000000) == 0); n++, x <<= 1)
;
return n;
}
typedef struct _lje {
uint16_t *image;
int width;
int height;
int bitdepth;
int readLength;
int skipLength;
uint16_t *delinearize;
int delinearizeLength;
uint8_t *encoded;
int encodedWritten;
int encodedLength;
int hist[17]; // SSSS frequency histogram
int bits[17];
int huffval[17];
u16 huffenc[17];
u16 huffbits[17];
int huffsym[17];
} lje;
int frequencyScan(lje *self) {
// Scan through the tile using the standard type 6 prediction
// Need to cache the previous 2 row in target coordinates because of tiling
uint16_t *pixel = self->image;
int pixcount = self->width * self->height;
int scan = self->readLength;
uint16_t *rowcache = (uint16_t *)calloc(1, self->width * 4);
uint16_t *rows[2];
rows[0] = rowcache;
rows[1] = &rowcache[self->width];
int col = 0;
int row = 0;
int Px = 0;
int32_t diff = 0;
int maxval = (1 << self->bitdepth);
while (pixcount--) {
uint16_t p = *pixel;
if (self->delinearize) {
if (p >= self->delinearizeLength) {
free(rowcache);
return LJ92_ERROR_TOO_WIDE;
}
p = self->delinearize[p];
}
if (p >= maxval) {
free(rowcache);
return LJ92_ERROR_TOO_WIDE;
}
rows[1][col] = p;
if ((row == 0) && (col == 0))
Px = 1 << (self->bitdepth - 1);
else if (row == 0)
Px = rows[1][col - 1];
else if (col == 0)
Px = rows[0][col];
else
Px = rows[0][col] + ((rows[1][col - 1] - rows[0][col - 1]) >> 1);
diff = rows[1][col] - Px;
int ssss = 32 - clz32(abs(diff));
if (diff == 0) ssss = 0;
self->hist[ssss]++;
// printf("%d %d %d %d %d %d\n",col,row,p,Px,diff,ssss);
pixel++;
scan--;
col++;
if (scan == 0) {
pixel += self->skipLength;
scan = self->readLength;
}
if (col == self->width) {
uint16_t *tmprow = rows[1];
rows[1] = rows[0];
rows[0] = tmprow;
col = 0;
row++;
}
}
#ifdef DEBUG
int sort[17];
for (int h = 0; h < 17; h++) {
sort[h] = h;
printf("%d:%d\n", h, self->hist[h]);
}
#endif
free(rowcache);
return LJ92_ERROR_NONE;
}
void createEncodeTable(lje *self) {
float freq[18];
int codesize[18];
int others[18];
// Calculate frequencies
float totalpixels = self->width * self->height;
for (int i = 0; i < 17; i++) {
freq[i] = (float)(self->hist[i]) / totalpixels;
#ifdef DEBUG
printf("%d:%f\n", i, freq[i]);
#endif
codesize[i] = 0;
others[i] = -1;
}
codesize[17] = 0;
others[17] = -1;
freq[17] = 1.0f;
float v1f, v2f;
int v1, v2;
while (1) {
v1f = 3.0f;
v1 = -1;
for (int i = 0; i < 18; i++) {
if ((freq[i] <= v1f) && (freq[i] > 0.0f)) {
v1f = freq[i];
v1 = i;
}
}
#ifdef DEBUG
printf("v1:%d,%f\n", v1, v1f);
#endif
v2f = 3.0f;
v2 = -1;
for (int i = 0; i < 18; i++) {
if (i == v1) continue;
if ((freq[i] < v2f) && (freq[i] > 0.0f)) {
v2f = freq[i];
v2 = i;
}
}
if (v2 == -1) break; // Done
freq[v1] += freq[v2];
freq[v2] = 0.0f;
while (1) {
codesize[v1]++;
if (others[v1] == -1) break;
v1 = others[v1];
}
others[v1] = v2;
while (1) {
codesize[v2]++;
if (others[v2] == -1) break;
v2 = others[v2];
}
}
int *bits = self->bits;
memset(bits, 0, sizeof(self->bits));
for (int i = 0; i < 18; i++) {
if (codesize[i] != 0) {
bits[codesize[i]]++;
}
}
#ifdef DEBUG
for (int i = 0; i < 17; i++) {
printf("bits:%d,%d,%d\n", i, bits[i], codesize[i]);
}
#endif
int *huffval = self->huffval;
int i = 1;
int k = 0;
int j;
memset(huffval, 0, sizeof(self->huffval));
while (i <= 32) {
j = 0;
while (j < 17) {
if (codesize[j] == i) {
huffval[k++] = j;
}
j++;
}
i++;
}
#ifdef DEBUG
for (i = 0; i < 17; i++) {
printf("i=%d,huffval[i]=%x\n", i, huffval[i]);
}
#endif
int maxbits = 16;
while (maxbits > 0) {
if (bits[maxbits]) break;
maxbits--;
}
u16 *huffenc = self->huffenc;
u16 *huffbits = self->huffbits;
int *huffsym = self->huffsym;
memset(huffenc, 0, sizeof(self->huffenc));
memset(huffbits, 0, sizeof(self->huffbits));
memset(self->huffsym, 0, sizeof(self->huffsym));
i = 0;
int hv = 0;
int rv = 0;
int vl = 0; // i
// int hcode;
int bitsused = 1;
int sym = 0;
// printf("%04x:%x:%d:%x\n",i,huffvals[hv],bitsused,1<<(maxbits-bitsused));
while (i < 1 << maxbits) {
if (bitsused > maxbits) {
break; // Done. Should never get here!
}
if (vl >= bits[bitsused]) {
bitsused++;
vl = 0;
continue;
}
if (rv == 1 << (maxbits - bitsused)) {
rv = 0;
vl++;
hv++;
// printf("%04x:%x:%d:%x\n",i,huffvals[hv],bitsused,1<<(maxbits-bitsused));
continue;
}
huffbits[sym] = bitsused;
huffenc[sym++] = i >> (maxbits - bitsused);
// printf("%d %d %d\n",i,bitsused,hcode);
i += (1 << (maxbits - bitsused));
rv = 1 << (maxbits - bitsused);
}
for (i = 0; i < 17; i++) {
if (huffbits[i] > 0) {
huffsym[huffval[i]] = i;
}
#ifdef DEBUG
printf("huffval[%d]=%d,huffenc[%d]=%x,bits=%d\n", i, huffval[i], i,
huffenc[i], huffbits[i]);
#endif
if (huffbits[i] > 0) {
huffsym[huffval[i]] = i;
}
}
#ifdef DEBUG
for (i = 0; i < 17; i++) {
printf("huffsym[%d]=%d\n", i, huffsym[i]);
}
#endif
}
void writeHeader(lje *self) {
int w = self->encodedWritten;
uint8_t *e = self->encoded;
e[w++] = 0xff;
e[w++] = 0xd8; // SOI
e[w++] = 0xff;
e[w++] = 0xc3; // SOF3
// Write SOF
e[w++] = 0x0;
e[w++] = 11; // Lf, frame header length
e[w++] = self->bitdepth;
e[w++] = self->height >> 8;
e[w++] = self->height & 0xFF;
e[w++] = self->width >> 8;
e[w++] = self->width & 0xFF;
e[w++] = 1; // Components
e[w++] = 0; // Component ID
e[w++] = 0x11; // Component X/Y
e[w++] = 0; // Unused (Quantisation)
e[w++] = 0xff;
e[w++] = 0xc4; // HUFF
// Write HUFF
int count = 0;
for (int i = 0; i < 17; i++) {
count += self->bits[i];
}
e[w++] = 0x0;
e[w++] = 17 + 2 + count; // Lf, frame header length
e[w++] = 0; // Table ID
for (int i = 1; i < 17; i++) {
e[w++] = self->bits[i];
}
for (int i = 0; i < count; i++) {
e[w++] = self->huffval[i];
}
e[w++] = 0xff;
e[w++] = 0xda; // SCAN
// Write SCAN
e[w++] = 0x0;
e[w++] = 8; // Ls, scan header length
e[w++] = 1; // Components
e[w++] = 0; //
e[w++] = 0; //
e[w++] = 6; // Predictor
e[w++] = 0; //
e[w++] = 0; //
self->encodedWritten = w;
}
void writePost(lje *self) {
int w = self->encodedWritten;
uint8_t *e = self->encoded;
e[w++] = 0xff;
e[w++] = 0xd9; // EOI
self->encodedWritten = w;
}
void writeBody(lje *self) {
// Scan through the tile using the standard type 6 prediction
// Need to cache the previous 2 row in target coordinates because of tiling
uint16_t *pixel = self->image;
int pixcount = self->width * self->height;
int scan = self->readLength;
uint16_t *rowcache = (uint16_t *)calloc(1, self->width * 4);
uint16_t *rows[2];
rows[0] = rowcache;
rows[1] = &rowcache[self->width];
int col = 0;
int row = 0;
int Px = 0;
int32_t diff = 0;
int bitcount = 0;
uint8_t *out = self->encoded;
int w = self->encodedWritten;
uint8_t next = 0;
uint8_t nextbits = 8;
while (pixcount--) {
uint16_t p = *pixel;
if (self->delinearize) p = self->delinearize[p];
rows[1][col] = p;
if ((row == 0) && (col == 0))
Px = 1 << (self->bitdepth - 1);
else if (row == 0)
Px = rows[1][col - 1];
else if (col == 0)
Px = rows[0][col];
else
Px = rows[0][col] + ((rows[1][col - 1] - rows[0][col - 1]) >> 1);
diff = rows[1][col] - Px;
int ssss = 32 - clz32(abs(diff));
if (diff == 0) ssss = 0;
// printf("%d %d %d %d %d\n",col,row,Px,diff,ssss);
// Write the huffman code for the ssss value
int huffcode = self->huffsym[ssss];
int huffenc = self->huffenc[huffcode];
int huffbits = self->huffbits[huffcode];
bitcount += huffbits + ssss;
int vt = ssss > 0 ? (1 << (ssss - 1)) : 0;
// printf("%d %d %d %d\n",rows[1][col],Px,diff,Px+diff);
#ifdef DEBUG
#endif
if (diff < vt) diff += (1 << (ssss)) - 1;
// Write the ssss
while (huffbits > 0) {
int usebits = huffbits > nextbits ? nextbits : huffbits;
// Add top usebits from huffval to next usebits of nextbits
int tophuff = huffenc >> (huffbits - usebits);
next |= (tophuff << (nextbits - usebits));
nextbits -= usebits;
huffbits -= usebits;
huffenc &= (1 << huffbits) - 1;
if (nextbits == 0) {
out[w++] = next;
if (next == 0xff) out[w++] = 0x0;
next = 0;
nextbits = 8;
}
}
// Write the rest of the bits for the value
while (ssss > 0) {
int usebits = ssss > nextbits ? nextbits : ssss;
// Add top usebits from huffval to next usebits of nextbits
int tophuff = diff >> (ssss - usebits);
next |= (tophuff << (nextbits - usebits));
nextbits -= usebits;
ssss -= usebits;
diff &= (1 << ssss) - 1;
if (nextbits == 0) {
out[w++] = next;
if (next == 0xff) out[w++] = 0x0;
next = 0;
nextbits = 8;
}
}
// printf("%d %d\n",diff,ssss);
pixel++;
scan--;
col++;
if (scan == 0) {
pixel += self->skipLength;
scan = self->readLength;
}
if (col == self->width) {
uint16_t *tmprow = rows[1];
rows[1] = rows[0];
rows[0] = tmprow;
col = 0;
row++;
}
}
// Flush the final bits
if (nextbits < 8) {
out[w++] = next;
if (next == 0xff) out[w++] = 0x0;
}
#ifdef DEBUG
int sort[17];
for (int h = 0; h < 17; h++) {
sort[h] = h;
printf("%d:%d\n", h, self->hist[h]);
}
printf("Total bytes: %d\n", bitcount >> 3);
#endif
free(rowcache);
self->encodedWritten = w;
}
/* Encoder
* Read tile from an image and encode in one shot
* Return the encoded data
*/
int lj92_encode(uint16_t *image, int width, int height, int bitdepth,
int readLength, int skipLength, uint16_t *delinearize,
int delinearizeLength, uint8_t **encoded, int *encodedLength) {
int ret = LJ92_ERROR_NONE;
lje *self = (lje *)calloc(sizeof(lje), 1);
if (self == NULL) return LJ92_ERROR_NO_MEMORY;
self->image = image;
self->width = width;
self->height = height;
self->bitdepth = bitdepth;
self->readLength = readLength;
self->skipLength = skipLength;
self->delinearize = delinearize;
self->delinearizeLength = delinearizeLength;
self->encodedLength = width * height * 3 + 200;
self->encoded = (uint8_t*)malloc(self->encodedLength);
if (self->encoded == NULL) {
free(self);
return LJ92_ERROR_NO_MEMORY;
}
// Scan through data to gather frequencies of ssss prefixes
ret = frequencyScan(self);
if (ret != LJ92_ERROR_NONE) {
free(self->encoded);
free(self);
return ret;
}
// Create encoded table based on frequencies
createEncodeTable(self);
// Write JPEG head and scan header
writeHeader(self);
// Scan through and do the compression
writeBody(self);
// Finish
writePost(self);
#ifdef DEBUG
printf("written:%d\n", self->encodedWritten);
#endif
self->encoded = (uint8_t*)realloc(self->encoded, self->encodedWritten);
self->encodedLength = self->encodedWritten;
*encoded = self->encoded;
*encodedLength = self->encodedLength;
free(self);
return ret;
}
// End liblj92 ---------------------------------------------------------
#ifdef __clang__
#pragma clang diagnostic pop
#endif
} // namespace detail
#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#endif
//
// TinyDNGWriter stores IFD table in the end of file so that offset to
// image data can be easily computed.
//
// +----------------------+
// | header |
// +----------------------+
// | |
// | image & meta 0 |
// | |
// +----------------------+
// | |
// | image & meta 1 |
// | |
// +----------------------+
// ...
// +----------------------+
// | |
// | image & meta N |
// | |
// +----------------------+
// | |
// | IFD 0 |
// | |
// +----------------------+
// | |
// | IFD 1 |
// | |
// +----------------------+
// ...
// +----------------------+
// | |
// | IFD 2 |
// | |
// +----------------------+
//
// From tiff.h
typedef enum {
TIFF_NOTYPE = 0, /* placeholder */
TIFF_BYTE = 1, /* 8-bit unsigned integer */
TIFF_ASCII = 2, /* 8-bit bytes w/ last byte null */
TIFF_SHORT = 3, /* 16-bit unsigned integer */
TIFF_LONG = 4, /* 32-bit unsigned integer */
TIFF_RATIONAL = 5, /* 64-bit unsigned fraction */
TIFF_SBYTE = 6, /* !8-bit signed integer */
TIFF_UNDEFINED = 7, /* !8-bit untyped data */
TIFF_SSHORT = 8, /* !16-bit signed integer */
TIFF_SLONG = 9, /* !32-bit signed integer */
TIFF_SRATIONAL = 10, /* !64-bit signed fraction */
TIFF_FLOAT = 11, /* !32-bit IEEE floating point */
TIFF_DOUBLE = 12, /* !64-bit IEEE floating point */
TIFF_IFD = 13, /* %32-bit unsigned integer (offset) */
TIFF_LONG8 = 16, /* BigTIFF 64-bit unsigned integer */
TIFF_SLONG8 = 17, /* BigTIFF 64-bit signed integer */
TIFF_IFD8 = 18 /* BigTIFF 64-bit unsigned integer (offset) */
} DataType;
const static int kHeaderSize = 8; // TIFF header size.
// floating point to integer rational value conversion
// https://stackoverflow.com/questions/51142275/exact-value-of-a-floating-point-number-as-a-rational
//
// Return error flag
static int DoubleToRational(double x, double *numerator, double *denominator) {
if (!std::isfinite(x)) {
*numerator = *denominator = 0.0;
if (x > 0.0) *numerator = 1.0;
if (x < 0.0) *numerator = -1.0;
return 1;
}
// TIFF Rational use two uint32's, so reduce the bits
int bdigits = FLT_MANT_DIG;
int expo;
*denominator = 1.0;
*numerator = std::frexp(x, &expo) * std::pow(2.0, bdigits);
expo -= bdigits;