-
Notifications
You must be signed in to change notification settings - Fork 1
/
sqz.h
2354 lines (2203 loc) · 87.6 KB
/
sqz.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
/**
* \file sqz.h
* \brief SQZ image compression library
*/
/*
SQZ - Low complexity, scalable lossless and lossy image compression library
Copyright (c) 2024, Márcio Pais
SPDX-License-Identifier: MIT
SQZ is a simple image codec designed to be scalable at a byte-level granularity,
providing lossless to extremelly low-rate lossy image compression without the need
for multiple images, simply by truncating an image at the required allocation budget.
It is responsive by design to the fullest extreme - encode once, serve many - where
every single additional byte allows for progressivelly better image quality, without
the need to reencode on-the-fly or store multiple versions of the same image.
(1) Technical details
SQZ uses a run-length wavelet bitplane encoding scheme with no entropy coding.
The chosen wavelet is the integer reversible 5/3 wavelet used in a myriad of other
codecs, and each subband bitplane is coded using a simple 2 stage DWT coefficient
significance and refinement method.
The subbands are scanned in one of 4 possible scan orders (raster, snake, Morton or
Hilbert), and the sorting pass encodes the linear distances between new significant
coefficients at each bitplane using the wavelet difference reduction method (WDR).
Internally, the image pixel data is stored in one of 4 color modes - 8bpp grayscale,
YCoCg-R, Oklab or logl1 - where the last 2 do not allow for lossless sRGB conversion.
For lossy compression of photographic images, the Oklab perceptual colorspace can
provide a significant gain in terms of perceived subjective image quality, at the
cost of increased computational load.
The DWT subband tree is encoded according to a schedule optimized for higher rate
compression, to try to squeeze the best possible subjective quality as early as
possible. An optional flag can be set to further delay encoding of the bitplanes
from the chroma planes, which acts as subsampling when doing lossy compression.
For lossless compression, none of this affects the final compressed size, as only
the priority of the bits being sent is changed.
A compressed SQZ bitstream starts with a compact 6 byte header:
- Magic [1 byte] ("0xA5")
- Width [2 bytes] (Big-Endian)
- Height [2 bytes] (Big-Endian)
- Color mode [1 bit]
- DWT levels [3 bits]
- Scan order [2 bits]
- Subsampling [1 bit]
No other information is stored, as it strives to provide the best possible LQIP
at every byte allocation budget.
(2) Implementation details
SQZ is provided as a C single header file only, to use it just define the macro
`SQZ_IMPLEMENTATION` in one file before including it:
#define SQZ_IMPLEMENTATION
#include "sqz.h"
No floating-point code is used in SQZ, the output is fully deterministic even when
using the non-reversible color modes.
To keep memory usage moderate, the DWT coefficients use 16 bits of precision, the
list nodes use 32-bit indexes for linking instead of pointers, and the lists are
only initialized on the first bitplane pass of their subband.
(3) License
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.
*/
#pragma once
#ifndef SQZ_H
#define SQZ_H
#include <stdint.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
SQZ_RESULT_OK, /*!< The operation was completed successfully */
SQZ_OUT_OF_MEMORY = -1, /*!< Not enough memory to perform the requested operation */
SQZ_INVALID_PARAMETER = -2, /*!< An invalid parameter was sent */
SQZ_BUFFER_TOO_SMALL = -3, /*!< The provided buffer was too small */
SQZ_DATA_CORRUPTED = -4 /*!< The compressed image data was corrupted */
} SQZ_status_t;
typedef enum {
SQZ_COLOR_MODE_GRAYSCALE, /*!< 8bpp grayscale mode */
SQZ_COLOR_MODE_YCOCG_R, /*!< YCoCg-R colorspace mode */
SQZ_COLOR_MODE_OKLAB, /*!< Oklab perceptual colorspace mode */
SQZ_COLOR_MODE_LOG_L1, /*!< logl1 colorspace mode */
SQZ_COLOR_MODE_COUNT, /*!< Number of color modes supported */
} SQZ_color_mode_t;
typedef enum {
SQZ_SCAN_ORDER_RASTER, /*!< Raster scan order */
SQZ_SCAN_ORDER_SNAKE, /*!< Snake scan order*/
SQZ_SCAN_ORDER_MORTON, /*!< Morton scan order */
SQZ_SCAN_ORDER_HILBERT, /*!< Hilbert scan order */
SQZ_SCAN_ORDER_COUNT, /*!< Number of scan orders supported */
} SQZ_scan_order_t;
/**
* \brief Maximum number of recursive spatial decompositions using the DWT
* \hideinitializer
*/
#define SQZ_DWT_MAX_LEVEL 8
/**
* \brief Smallest spatial dimension supported
* \hideinitializer
*/
#define SQZ_MIN_DIMENSION 8
/**
* \brief Highest spatial dimension supported
* \hideinitializer
*/
#define SQZ_MAX_DIMENSION ((1u << 16u) - 1u)
/**
* \brief Magic byte for SQZ image header
* \hideinitializer
*/
#define SQZ_HEADER_MAGIC 0xA5
/**
* \brief SQZ image header size (in bytes)
* \hideinitializer
*/
#define SQZ_HEADER_SIZE 6
/**
* \brief Structure used to describe an image
* \note When encoding, there is no need specifiy the number of planes
*/
typedef struct {
SQZ_color_mode_t color_mode;
SQZ_scan_order_t scan_order;
size_t width;
size_t height;
size_t dwt_levels; /*!< Number of DWT decomposition levels used */
size_t num_planes; /*!< Number of spectral planes in the image */
int subsampling; /*!< Specifies whether additional chroma subsampling is to be performed */
} SQZ_image_descriptor_t;
/**
* \brief Encode an image
* \warning The destination buffer will NOT be cleared before encoding
* \param[in] source : Pointer to the input pixel data
* \param[out] dest : Pointer to the buffer that will receive the compressed data, of at least `budget` bytes in size
* \param[in,out] descriptor : Pointer to an image descriptor, holding information about the image. Will be corrected if necessary
* \param[in,out] budget : Pointer to the byte budget allowed for compression, will be updated with the final compressed data size
* \return \ref SQZ_RESULT_OK on success, member of \ref SQZ_status_t otherwise
*/
SQZ_status_t SQZ_encode(void* const source, void* const dest, SQZ_image_descriptor_t* const descriptor, size_t* const budget);
/**
* \brief Decode an image
* \note Call this function with `dest_size` set to 0 to receive an image descriptor and the required buffer size,
* if the return result is \ref SQZ_BUFFER_TOO_SMALL, any other result will imply a decoding error
* \param[in] source : Pointer to the input compressed data
* \param[out] dest : Pointer to the buffer that will receive the decompressed pixel data
* \param[in] src_size: Pointer to the size of the input buffer
* \param[in,out] dest_size : Pointer to the size of the output buffer (or 0 to request the appropriate size)
* \param[in,out] descriptor : Pointer to an image descriptor, to be filled with information about the image
* \return \ref SQZ_RESULT_OK on success, member of \ref SQZ_status_t otherwise
*/
SQZ_status_t SQZ_decode(void* const source, void* const dest, size_t const src_size, size_t* const dest_size, SQZ_image_descriptor_t* const descriptor);
#ifdef __cplusplus
}
#endif
#endif /* SQZ_H */
#ifdef SQZ_IMPLEMENTATION
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
#define __restrict__ __restrict
#endif
#define restrict __restrict__
#if defined(CHAR_BIT) && (CHAR_BIT != 8)
#error "Unsupported platform"
#endif
/**
* \brief Structure used for bitwise memory IO
*/
typedef struct {
uint8_t* data; /*!< Pointer to the initial position in the buffer */
uint8_t* ptr; /*!< Pointer to the current byte being used in the buffer */
uint8_t* eob; /*!< End-of-buffer pointer */
size_t index; /*!< Index of the next bit available in the current byte */
} SQZ_bit_buffer_t;
/**
* \brief Node structure containing 2d coordinates relative to a subband, for a single-linked list
*/
typedef struct {
uint16_t x; /*!< Horizontal coordinate relative to the origin of the subband */
uint16_t y; /*!< Vertical coordinate relative to the origin of the subband */
int32_t next; /*!< Pointer to the next node in the list */
} SQZ_list_node_t;
/**
* \brief Structure containing the pre-allocated node cache used by all the lists in a subband
*/
typedef struct {
SQZ_list_node_t* nodes; /*!< Dynamic array of list nodes */
size_t capacity; /*!< Number of nodes contained in this cache (equal to the number of coefficients in the subband) */
size_t index; /*!< Index of the first available node */
} SQZ_list_node_cache_t;
/**
* \brief Single-linked list containing relative positions of coefficients from a subband
*/
typedef struct {
SQZ_list_node_cache_t* cache; /*!< Cache where the list nodes are stored */
SQZ_list_node_t* head; /*!< Pointer to the first element in the list */
SQZ_list_node_t* tail; /*!< Pointer to the last element in the list */
size_t length;
} SQZ_list_t;
typedef struct SQZ_scan_context SQZ_scan_context_t;
typedef int (*SQZ_scan_fn)(SQZ_scan_context_t* const ctx);
/**
* \brief Generic structure containing the common fields required for every scan order
*/
struct SQZ_scan_context {
void* workspace; /*!< Pointer to a structure holding the internal fields required for this scan order */
SQZ_scan_fn scan; /*!< Pointer to the spatial traverse function for this scan order */
SQZ_scan_order_t type; /*!< Type of scan order used in this context */
size_t x; /*!< Current relative horizontal coordinate */
size_t y; /*!< Current relative vertical coordinate */
size_t width; /*!< Width covered by this scan order */
size_t height; /*!< Height covered by this scan order */
};
/**
* \brief Structure containing the private fields required for the snake scan order
* \note This scan order divides the region to traverse into a grid of tiles, and
* proceeds in an alternating horizontal and vertical direction, both inside
* each tile and between tiles in the grid. It is the only scan order that
* ensures that the Manhattan distance between sucessive moves is exactly 1
*/
typedef struct {
struct {
size_t x;
size_t y;
size_t width;
size_t height;
struct {
size_t remaining;
int right_to_left;
} columns;
struct {
size_t remaining;
} rows;
struct {
size_t width;
size_t height;
} defaults;
} tile;
struct {
size_t x;
size_t y;
size_t width;
size_t height;
struct {
size_t index;
int odd;
} columns;
struct {
int odd;
} rows;
} grid;
struct {
size_t x;
size_t y;
} offsets;
} SQZ_snake_scan_context_t;
/**
* \brief Structure containing the private fields required for the Morton scan order
* \note Also known as Z-order, the coordinates are calculated by binary deinterleaving
* of the current linear index
*/
typedef struct {
size_t range;
size_t mask;
size_t index;
size_t length;
} SQZ_morton_scan_context_t;
/**
* \brief Stack item for the Hilbert scan order
*/
typedef struct {
int32_t x;
int32_t y;
int32_t ax;
int32_t ay;
int32_t bx;
int32_t by;
} SQZ_hilbert_scan_stack_item_t;
/**
* \brief Stack containing the recursive region sub-division information for the Hilbert scan order
*/
typedef struct {
SQZ_hilbert_scan_stack_item_t items[32];
int32_t index;
} SQZ_hilbert_scan_stack_t;
/**
* \brief Structure containing the private fields required for the Hilbert scan order
* \note Based on "Generalized Hilbert space-filling curve for rectangular domains of arbitrary
* (non-power of two) sizes" - by Jakub Červený - [https://github.com/jakubcerveny/gilbert]
*/
typedef struct {
SQZ_hilbert_scan_stack_t stack;
int32_t width;
int32_t height;
int32_t dax;
int32_t day;
int32_t dbx;
int32_t dby;
int32_t index;
} SQZ_hilbert_scan_context_t;
/**
* \brief Number of spectral planes supported
* \hideinitializer
*/
#define SQZ_SPECTRAL_PLANES 3
/**
* \brief Number of subbands output by the DWT per iteration
* \hideinitializer
*/
#define SQZ_DWT_SUBBANDS 4
typedef int16_t SQZ_dwt_coefficient_t;
/**
* \brief Structure used to describe a DWT subband
*/
typedef struct SQZ_dwt_subband {
SQZ_list_node_cache_t cache; /*!< Common node cache shared by the lists, pre-allocated on first use */
SQZ_list_t LIP; /*!< List of Insignificant Pixels */
SQZ_list_t LSP; /*!< List of Significant Pixels */
SQZ_list_t NSP; /*!< List of New Significant Pixels */
SQZ_dwt_coefficient_t* data; /*!< Pointer to the buffer holding the DWT coefficients for this subband */
size_t width; /*!< Width of this subband */
size_t height; /*!< Height of this subband */
size_t stride; /*!< Stride size, in number of coefficients, between the lines of this subband in the buffer*/
int max_bitplane; /*!< Highest bitplane in this subband containing at least one coefficient */
int bitplane; /*!< Current bitplane being processed */
int round; /*!< Starting round for scheduling processing of this subband */
} SQZ_dwt_subband_t;
/**
* \brief Structure used to describe a spectral image plane
*/
typedef struct {
SQZ_dwt_subband_t band[SQZ_DWT_MAX_LEVEL][SQZ_DWT_SUBBANDS]; /*!< DWT subband tree for this plane */
SQZ_dwt_coefficient_t* data; /*!< Pointer to the buffer holding the pixel data for this plane */
} SQZ_spectral_plane_t;
/**
* \brief Structure used to store the codec internal state
*/
typedef struct {
SQZ_spectral_plane_t plane[SQZ_SPECTRAL_PLANES]; /*!< Spectral planes for this image*/
SQZ_dwt_coefficient_t* data; /*!< Pointer to the buffer holding the pixel data for this image */
SQZ_bit_buffer_t buffer; /*!< I/O bit-wise buffer storing the compressed data */
SQZ_image_descriptor_t image; /*!< Image descriptor holding the relevant image information */
} SQZ_context_t;
typedef SQZ_status_t (*SQZ_init_subband_fn)(SQZ_dwt_subband_t* const band, SQZ_scan_context_t* const scan_ctx, SQZ_bit_buffer_t* const buffer);
typedef int (*SQZ_bitplane_task_fn)(SQZ_dwt_subband_t* const band, SQZ_bit_buffer_t* const buffer);
static uint8_t const SQZ_number_of_planes[SQZ_COLOR_MODE_COUNT] = { 1u, 3u, 3u, 3u, };
/**
* \brief Codec processing schedule defining the starting rounds for each subband, per level, plane and color mode
*/
static uint8_t const SQZ_schedule[SQZ_COLOR_MODE_COUNT][SQZ_SPECTRAL_PLANES][SQZ_DWT_MAX_LEVEL][SQZ_DWT_SUBBANDS] = {
/* Grayscale */
{
{
{ 0, 1, 1, 2, },
{ 0, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
},
{ { 0 } },
{ { 0 } },
},
/* YCoCg-R */
{
{
{ 0, 1, 1, 2, },
{ 0, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
},
{
{ 1, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
{ 0, 9, 9, 10, },
},
{
{ 1, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
{ 0, 9, 9, 10, },
},
},
/* Oklab */
{
{
{ 0, 1, 1, 2, },
{ 0, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
},
{
{ 1, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
{ 0, 9, 9, 10, },
},
{
{ 1, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
{ 0, 9, 9, 10, },
},
},
/* logl1 */
{
{
{ 0, 1, 1, 2, },
{ 0, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
},
{
{ 1, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
{ 0, 9, 9, 10, },
},
{
{ 1, 2, 2, 3, },
{ 0, 3, 3, 4, },
{ 0, 4, 4, 5, },
{ 0, 5, 5, 6, },
{ 0, 6, 6, 7, },
{ 0, 7, 7, 8, },
{ 0, 8, 8, 9, },
{ 0, 9, 9, 10, },
},
},
};
#undef SQZ_SPECTRAL_PLANES
#ifdef _MSC_VER
#include <intrin.h>
static uint32_t
SQZ_ilog2(uint32_t const x) {
unsigned long log = 0u;
if (x != 0u) {
_BitScanReverse(&log, x);
++log;
};
return log;
}
#elif defined(__GNUC__)
static uint32_t
SQZ_ilog2(uint32_t const x) {
return (x != 0u) ? 32 - __builtin_clz(x) : x;
}
#endif
/**
* \brief Mirrors a value to the interval [0..maximum], used for symmetric extension at the image boundaries
* \param value: The signed value we wish to mirror
* \param maximum: Largest positive value inside the interval
* \return An unsigned integer inside the requested interval, mirrored around its boundaries
*/
static uint32_t
SQZ_mirror(int32_t value, int32_t const maximum) {
if (maximum == 0) {
return 0u;
}
while ((uint32_t)value > (uint32_t)maximum) {
value = -value;
if (value < 0) {
value += 2 * maximum;
}
}
return (uint32_t)value;
}
/**
* \brief Interleaves the low 16-bits of a 32-bit unsigned integer to its even bits, clearing all the odd bits
* \param i: The value to interleave
* \return 32-bit unsigned integer containing the low 16-bits of `i` interleaved into the even bits
*/
static uint32_t
SQZ_deinterleave_u32_to_u16(uint32_t i) {
i &= 0x55555555u;
i = (i ^ (i >> 1u)) & 0x33333333u;
i = (i ^ (i >> 2u)) & 0x0F0F0F0Fu;
i = (i ^ (i >> 4u)) & 0x00FF00FFu;
i = (i ^ (i >> 8u)) & 0x0000FFFFu;
return i;
}
/**
* \brief Deinterleaves the even bits in a 32-bit unsigned integer
* \param i: The value to deinterleave
* \return 32-bit unsigned integer containing the even bits of `i` packed in its low 16-bits
*/
static uint32_t
SQZ_interleave_u16_to_u32(uint32_t i) {
i &= 0x0000FFFFu;
i = (i ^ (i << 8u)) & 0x00FF00FFu;
i = (i ^ (i << 4u)) & 0x0F0F0F0Fu;
i = (i ^ (i << 2u)) & 0x33333333u;
i = (i ^ (i << 1u)) & 0x55555555u;
return i;
}
static void
SQZ_bit_buffer_init(SQZ_bit_buffer_t* const buffer, void* const source, size_t const capacity) {
#ifdef DEBUG
if ((buffer == NULL) || (source == NULL) || (capacity == 0u)) {
return;
}
#endif
buffer->data = buffer->ptr = (uint8_t*)source;
buffer->eob = buffer->data + capacity;
buffer->index = 0u;
}
static int
SQZ_bit_buffer_eob(SQZ_bit_buffer_t const * const buffer) {
#ifdef DEBUG
if (buffer == NULL) {
return 1;
}
#endif
return (buffer->ptr >= buffer->eob);
}
static size_t
SQZ_bit_buffer_bits_used(SQZ_bit_buffer_t const * const buffer) {
#ifdef DEBUG
if (buffer == NULL) {
return 0;
}
#endif
return ((buffer->ptr - buffer->data) * CHAR_BIT) + buffer->index;
}
#define SQZ_BIT_BUFFER_MSB ((sizeof(uint8_t) * CHAR_BIT) - 1u)
static int
SQZ_bit_buffer_write_bit(SQZ_bit_buffer_t* const buffer, uint32_t const bit) {
#ifdef DEBUG
if (buffer == NULL) {
return 0;
}
#endif
if (SQZ_bit_buffer_eob(buffer)) {
return 0;
}
*(buffer->ptr) |= bit << (SQZ_BIT_BUFFER_MSB - buffer->index);
if (buffer->index < SQZ_BIT_BUFFER_MSB) {
buffer->index++;
}
else {
buffer->ptr++;
buffer->index = 0u;
}
return 1;
}
static int
SQZ_bit_buffer_write_bits(SQZ_bit_buffer_t* const buffer, uint32_t const bits, uint32_t width) {
#ifdef DEBUG
if (buffer == NULL) {
return 0;
}
#endif
do {
if (SQZ_bit_buffer_eob(buffer)) {
return 0;
}
uint32_t const bits_free = (SQZ_BIT_BUFFER_MSB + 1u) - buffer->index;
if (bits_free >= width) {
*(buffer->ptr) |= (bits & ((1u << width) - 1u)) << (bits_free - width);
buffer->index += width;
if (buffer->index > SQZ_BIT_BUFFER_MSB) {
buffer->ptr++;
buffer->index = 0u;
}
return 1;
}
else {
*(buffer->ptr) |= (bits >> (width - bits_free)) & ((1u << bits_free) - 1u);
buffer->ptr++;
buffer->index = 0u;
width -= bits_free;
}
} while (1);
}
static int32_t
SQZ_bit_buffer_read_bit(SQZ_bit_buffer_t* const buffer) {
#ifdef DEBUG
if (buffer == NULL) {
return -1;
}
#endif
if (SQZ_bit_buffer_eob(buffer)) {
return -1;
}
int32_t const bit = (*(buffer->ptr) >> (SQZ_BIT_BUFFER_MSB - buffer->index)) & 1;
if (buffer->index < SQZ_BIT_BUFFER_MSB) {
buffer->index++;
}
else {
buffer->ptr++;
buffer->index = 0u;
}
return bit;
}
static int32_t
SQZ_bit_buffer_read_bits(SQZ_bit_buffer_t* const buffer, uint32_t width) {
#ifdef DEBUG
if (buffer == NULL) {
return -1;
}
#endif
int32_t bits = 0;
do {
if (SQZ_bit_buffer_eob(buffer)) {
return -1;
}
uint32_t const bits_available = (SQZ_BIT_BUFFER_MSB + 1u) - buffer->index;
if (bits_available >= width) {
bits <<= width;
bits |= (*(buffer->ptr) >> (bits_available - width)) & ((1u << width) - 1u);
buffer->index += width;
if (buffer->index > SQZ_BIT_BUFFER_MSB) {
buffer->ptr++;
buffer->index = 0u;
}
break;
}
else {
bits <<= bits_available;
bits |= *(buffer->ptr) & ((1u << bits_available) - 1u);
buffer->ptr++;
buffer->index = 0u;
width -= bits_available;
}
} while (1);
return bits;
}
#undef SQZ_BIT_BUFFER_MSB
static SQZ_status_t
SQZ_node_cache_init(SQZ_list_node_cache_t* const cache, size_t const capacity) {
#ifdef DEBUG
if ((cache == NULL) || (capacity == 0u)) {
return SQZ_INVALID_PARAMETER;
}
#endif
cache->nodes = (SQZ_list_node_t*)calloc(capacity, sizeof(SQZ_list_node_t));
if (cache->nodes == NULL) {
return SQZ_OUT_OF_MEMORY;
}
cache->capacity = capacity;
cache->index = 0u;
return SQZ_RESULT_OK;
}
#define SQZ_LIST_NULL -1
static void
SQZ_list_init(SQZ_list_t* const list, SQZ_list_node_cache_t* const cache) {
#ifdef DEBUG
if ((list == NULL) || (cache == NULL)) {
return;
}
#endif
list->cache = cache;
list->head = list->tail = NULL;
list->length = 0u;
}
static SQZ_list_node_t*
SQZ_list_node_next(SQZ_list_node_t const * const node, SQZ_list_node_t* const base) {
#ifdef DEBUG
return ((node != NULL) && (node->next > SQZ_LIST_NULL) && (base != NULL)) ? base + node->next : NULL;
#else
return (node->next > SQZ_LIST_NULL) ? base + node->next : NULL;
#endif
}
static SQZ_list_node_t*
SQZ_list_add(SQZ_list_t* const list, uint16_t const x, uint16_t const y) {
#ifdef DEBUG
if (list == NULL) {
return NULL;
}
#endif
SQZ_list_node_cache_t* const cache = list->cache;
if (cache->index >= cache->capacity) {
return NULL;
}
SQZ_list_node_t* const node = cache->nodes + cache->index;
if (list->head == NULL) {
list->head = node;
}
else if (list->tail != NULL) {
list->tail->next = cache->index;
}
list->tail = node;
list->length++;
node->x = x;
node->y = y;
node->next = SQZ_LIST_NULL;
cache->index++;
return node;
}
/**
* \brief Exchanges a node from the source list to the destination list
* \warning Assumes that neither the list pointers nor the exchanged node pointer are `NULL`,
* and that both lists share the same node cache but are not the same
* \param[in,out] source: Source list
* \param[in,out] dest: Destination list
* \param[in,out] node: Node from the source list to be exchanged to the destination list
* \param[in,out] prv: Previous node in the source list
* \return Pointer to the next node in the source list if available, `NULL` otherwise
*/
static SQZ_list_node_t*
SQZ_list_exchange(SQZ_list_t* restrict const source, SQZ_list_t* restrict const dest, SQZ_list_node_t* restrict const node, SQZ_list_node_t* restrict const prv) {
#ifdef DEBUG
if ((source == NULL) || (dest == NULL) || (source == dest) || (source->cache != dest->cache) || (node == NULL)) {
return NULL;
}
#endif
SQZ_list_node_t* const base = source->cache->nodes;
SQZ_list_node_t* const next = SQZ_list_node_next(node, base);
if (prv != NULL) {
prv->next = node->next;
}
else {
source->head = next;
}
source->length--;
if (dest->head == NULL) {
dest->head = node;
}
else if (dest->tail != NULL) {
dest->tail->next = node - base;
}
dest->tail = node;
dest->length++;
node->next = SQZ_LIST_NULL;
return next;
}
/**
* \brief Merges the source list into the destination list, clearing the source list
* \warning Assumes that neither of the list pointers are `NULL`, and that both lists
* share the same node cache but are not the same
* \param[in,out] source: Source list
* \param[in,out] dest: Destination list
*/
static void
SQZ_list_merge(SQZ_list_t* const source, SQZ_list_t* const dest) {
#ifdef DEBUG
if ((source == NULL) || (dest == NULL) || (source == dest) || (source->cache != dest->cache)) {
return;
}
#endif
if (source->head == NULL) { /* source list is empty, nothing to do */
return;
}
else if (dest->tail != NULL) { /* both lists have elements, append source to destination */
dest->tail->next = source->head - source->cache->nodes;
}
else { /* destination list was empty, copy the source list to the head of the destination list */
dest->head = source->head;
}
dest->tail = source->tail;
dest->length += source->length;
source->length = 0u;
source->head = source->tail = NULL;
}
#undef SQZ_LIST_NULL
static int
SQZ_scan_raster(SQZ_scan_context_t* const ctx) {
#ifdef DEBUG
if (ctx == NULL) {
return 0;
}
#endif
++ctx->x;
if (ctx->x >= ctx->width) {
ctx->x = 0u;
++ctx->y;
if (ctx->y >= ctx->height) {
return 0;
}
}
return 1;
}
static SQZ_status_t
SQZ_scan_init_raster_context(SQZ_scan_context_t* const ctx, size_t const width, size_t const height) {
#ifdef DEBUG
if ((ctx == NULL) || (width == 0u) || (height == 0u)) {
return SQZ_INVALID_PARAMETER;
}
#endif
if (ctx->type != SQZ_SCAN_ORDER_RASTER) {
ctx->type = SQZ_SCAN_ORDER_RASTER;
}
ctx->scan = SQZ_scan_raster;
ctx->x = ctx->y = 0u;
ctx->width = width;
ctx->height = height;
return SQZ_RESULT_OK;
}
static int
SQZ_scan_snake(SQZ_scan_context_t* const ctx) {
#ifdef DEBUG
if ((ctx == NULL) || (ctx->workspace == NULL)) {
return 0;
}
#endif
SQZ_snake_scan_context_t* const snake = (SQZ_snake_scan_context_t*)ctx->workspace;
++snake->tile.x;
if (snake->tile.x < snake->tile.width) {
loop_tile_columns:
ctx->x = ((snake->tile.columns.right_to_left) ? (snake->tile.width - 1u) - snake->tile.x : snake->tile.x) + snake->offsets.x;
ctx->y = ((snake->grid.columns.odd) ? (snake->tile.height - 1u) - snake->tile.y : snake->tile.y) + snake->offsets.y;
}
else {
snake->tile.x = 0u;
++snake->tile.y;
/* can we move to next line in this tile? */
if (snake->tile.y < snake->tile.height) {
loop_tile_rows: ;
size_t const row = (snake->grid.columns.odd) ? (snake->tile.height - 1u) - snake->tile.y : snake->tile.y;
snake->tile.columns.right_to_left = (snake->grid.y ^ row) & 1u;
goto loop_tile_columns;
}
else {
snake->tile.y = 0u;
++snake->grid.columns.index;
/* can we move to next tile in this line of the grid? */
if (snake->grid.columns.index < snake->grid.width) {
loop_grid_columns: ;
size_t const width = snake->grid.width - 1u;
snake->grid.x = (snake->grid.rows.odd) ? width - snake->grid.columns.index : snake->grid.columns.index;
snake->grid.columns.odd = snake->grid.x & 1u;
snake->tile.width = (snake->grid.x < width) ? snake->tile.defaults.width : snake->tile.columns.remaining;
snake->offsets.x = snake->grid.x * snake->tile.defaults.width;
goto loop_tile_rows;
}
else {
snake->grid.columns.index = 0u;
++snake->grid.y;
/* can we move to the next line of tiles in the grid ? */
if (snake->grid.y < snake->grid.height) {
snake->grid.rows.odd = snake->grid.y & 1u;
snake->tile.height = (snake->grid.y < snake->grid.height - 1u) ? snake->tile.defaults.height : snake->tile.rows.remaining;
snake->offsets.y = snake->grid.y * snake->tile.defaults.height;
goto loop_grid_columns;
}
return 0;
}
}
}
return 1;
}
static SQZ_status_t
SQZ_scan_init_snake_context(SQZ_scan_context_t* const ctx, size_t width, size_t height, size_t tile_width, size_t tile_height) {
#ifdef DEBUG
if ((ctx == NULL) || (width == 0u) || (height == 0u) || (tile_width == 0u) || (tile_height == 0u)) {
return SQZ_INVALID_PARAMETER;
}
#endif
if ((ctx->type != SQZ_SCAN_ORDER_SNAKE) || (ctx->workspace == NULL)) {
ctx->type = SQZ_SCAN_ORDER_SNAKE;
free(ctx->workspace);
ctx->workspace = malloc(sizeof(SQZ_snake_scan_context_t));
if (ctx->workspace == NULL) {
return SQZ_OUT_OF_MEMORY;
}
}
SQZ_snake_scan_context_t* const snake = (SQZ_snake_scan_context_t*)ctx->workspace;
memset(snake, 0, sizeof(*snake));
/* sanitize inputs */
if (tile_width > width) {
tile_width = width;
}
if (tile_height > height) {
tile_height = height;
}
/* ensure that the grid has an odd number of columns */
int32_t step = 1;
for (;;) {
snake->grid.width = (width + tile_width - 1u) / tile_width;