-
Notifications
You must be signed in to change notification settings - Fork 333
Expand file tree
/
Copy pathbasisu_astc_ldr_encode.cpp
More file actions
11088 lines (8608 loc) · 377 KB
/
Copy pathbasisu_astc_ldr_encode.cpp
File metadata and controls
11088 lines (8608 loc) · 377 KB
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: basisu_astc_ldr_encode.cpp
// Copyright (C) 2019-2026 Binomial LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "basisu_enc.h"
#include "basisu_astc_ldr_encode.h"
#include "basisu_astc_hdr_common.h"
#include "basisu_astc_ldr_common.h"
#include "3rdparty/android_astc_decomp.h"
#include <queue>
// Set BASISU_ASTC_LDR_SUPPORT_ZSTD to 0 to disable Zstd support for ASTC LDR encoding (cFullZStd and cHybridArithZStd syntaxes)
#ifndef BASISU_ASTC_LDR_SUPPORT_ZSTD
#define BASISU_ASTC_LDR_SUPPORT_ZSTD 1
#endif
#if BASISU_ASTC_LDR_SUPPORT_ZSTD
#include "zstd.h"
#endif
namespace basisu {
namespace astc_ldr {
const bool g_devel_messages = true;
const bool ASTC_LDR_CONSISTENCY_CHECKING = true;
bool g_initialized;
const uint32_t EXPECTED_SUPERBUCKET_HASH_SIZE = 8192;
const uint32_t EXPECTED_SHORTLIST_HASH_SIZE = 4096;
const uint32_t MAX_BASE_PARTS2 = 128;
const uint32_t MAX_BASE_PARTS3 = 128;
const uint32_t PART_ESTIMATE_STAGE1_MULTIPLIER = 4;
const uint32_t MAX_WIDTH = 65535, MAX_HEIGHT = 65535;
void code_block_weights(
basist::astc_ldr_t::grid_weight_dct &gw_dct,
float q, uint32_t plane_index,
const astc_helpers::log_astc_block& log_blk,
const basist::astc_ldr_t::astc_block_grid_data* pGrid_data,
basisu::bitwise_coder& c,
basist::astc_ldr_t::dct_syms& syms)
{
assert(q > 0.0f);
syms.clear();
const uint32_t grid_width = log_blk.m_grid_width, grid_height = log_blk.m_grid_height;
const uint32_t total_grid_samples = grid_width * grid_height;
const uint32_t num_planes = log_blk.m_dual_plane ? 2 : 1;
//const auto& dequant_tab = astc_helpers::g_dequant_tables.get_weight_tab(log_blk.m_weight_ise_range).m_ISE_to_val;
//const auto& quant_tab = astc_helpers::g_dequant_tables.get_weight_tab(log_blk.m_weight_ise_range).m_val_to_ise;
uint8_t dequantized_raw_weights0[astc_helpers::MAX_BLOCK_PIXELS];
for (uint32_t i = 0; i < grid_width * grid_height; i++)
dequantized_raw_weights0[i] = astc_helpers::g_dequant_tables.get_weight_tab(log_blk.m_weight_ise_range).m_ISE_to_val[log_blk.m_weights[i * num_planes + plane_index]];
auto grid_dim_vals_iter = gw_dct.m_grid_dim_key_vals.find(basist::astc_ldr_t::grid_dim_key(grid_width, grid_height));
assert(grid_dim_vals_iter != gw_dct.m_grid_dim_key_vals.end());
auto& grid_dim_vals = grid_dim_vals_iter->second;
float orig_weights[astc_helpers::MAX_BLOCK_PIXELS];
float weight_sum = 0;
for (uint32_t y = 0; y < grid_height; y++)
{
for (uint32_t x = 0; x < grid_width; x++)
{
orig_weights[x + y * grid_width] = dequantized_raw_weights0[x + y * grid_width];
weight_sum += orig_weights[x + y * grid_width];
}
}
float scaled_weight_coding_scale = basist::astc_ldr_t::SCALED_WEIGHT_BASE_CODING_SCALE;
if (log_blk.m_weight_ise_range <= astc_helpers::BISE_8_LEVELS)
scaled_weight_coding_scale = 1.0f / 8.0f;
float scaled_mean_weight = std::round((float)scaled_weight_coding_scale * (weight_sum / total_grid_samples));
scaled_mean_weight = basisu::clamp<float>(scaled_mean_weight, 0.0f, 64.0f * (float)scaled_weight_coding_scale);
float mean_weight = scaled_mean_weight / (float)scaled_weight_coding_scale;
for (uint32_t y = 0; y < grid_height; y++)
for (uint32_t x = 0; x < grid_width; x++)
orig_weights[x + y * grid_width] -= mean_weight;
const float span_len = gw_dct.get_max_span_len(log_blk, plane_index);
float dct_weights[astc_helpers::MAX_BLOCK_PIXELS];
// TODO - temp alloc
basist::astc_ldr_t::fvec dct_work;
grid_dim_vals.m_dct.forward(orig_weights, dct_weights, dct_work);
const float level_scale = gw_dct.compute_level_scale(q, span_len, pGrid_data->m_weight_gamma, grid_width, grid_height, log_blk.m_weight_ise_range);
int dct_quant_tab[astc_helpers::MAX_BLOCK_PIXELS];
gw_dct.compute_quant_table(q, grid_width, grid_height, level_scale, dct_quant_tab);
#if defined(DEBUG) || defined(_DEBUG)
// sanity checking
basist::astc_ldr_t::sample_quant_table_state quant_state;
quant_state.init(q, gw_dct.m_block_width, gw_dct.m_block_height, level_scale);
#endif
c.put_truncated_binary((int)scaled_mean_weight, (uint32_t)(64.0f * scaled_weight_coding_scale) + 1);
syms.m_dc_sym = (int)scaled_mean_weight;
syms.m_num_dc_levels = (uint32_t)(64.0f * scaled_weight_coding_scale) + 1;
assert(syms.m_num_dc_levels == gw_dct.get_num_weight_dc_levels(log_blk.m_weight_ise_range));
int dct_coeffs[astc_helpers::MAX_BLOCK_PIXELS];
for (uint32_t y = 0; y < grid_height; y++)
{
for (uint32_t x = 0; x < grid_width; x++)
{
if (!x && !y)
{
dct_coeffs[0] = 0;
continue;
}
const int levels = dct_quant_tab[x + y * grid_width];
#if defined(DEBUG) || defined(_DEBUG)
// sanity checking
assert(levels == gw_dct.sample_quant_table(quant_state, x, y));
#endif
float d = dct_weights[x + y * grid_width];
int id = gw_dct.quantize_deadzone(d, levels, basist::astc_ldr_t::DEADZONE_ALPHA, x, y);
dct_coeffs[x + y * grid_width] = id;
} // x
} // y
const basisu::int_vec& zigzag = grid_dim_vals.m_zigzag;
assert(zigzag.size() == total_grid_samples);
int total_zeros = 0;
for (uint32_t i = 0; i < total_grid_samples; i++)
{
uint32_t dct_idx = zigzag[i];
if (!dct_idx)
continue;
int coeff = dct_coeffs[dct_idx];
if (!coeff)
{
total_zeros++;
continue;
}
basist::astc_ldr_t::dct_syms::coeff cf;
cf.m_num_zeros = basisu::safe_cast_uint16(total_zeros);
cf.m_coeff = basisu::safe_cast_int16(coeff);
syms.m_coeffs.push_back(cf);
syms.m_max_coeff_mag = basisu::maximum(syms.m_max_coeff_mag, basisu::iabs(coeff));
syms.m_max_zigzag_index = basisu::maximum(syms.m_max_zigzag_index, i);
c.put_rice(total_zeros, gw_dct.m_zero_run);
total_zeros = 0;
c.put_bits(coeff < 0 ? 1 : 0, 1);
if (coeff < 0)
coeff = -coeff;
c.put_rice(coeff, gw_dct.m_coeff);
}
if (total_zeros)
{
basist::astc_ldr_t::dct_syms::coeff cf;
cf.m_num_zeros = basisu::safe_cast_uint16(total_zeros);
cf.m_coeff = INT16_MAX;
syms.m_coeffs.push_back(cf);
c.put_rice(total_zeros, gw_dct.m_zero_run);
}
}
void astc_ldr_requantize_astc_weights(uint32_t n, const uint8_t* pSrc_ise_vals, uint32_t from_ise_range, uint8_t* pDst_ise_vals, uint32_t to_ise_range)
{
if (from_ise_range == to_ise_range)
{
if (pDst_ise_vals != pSrc_ise_vals)
memcpy(pDst_ise_vals, pSrc_ise_vals, n);
return;
}
// from/to BISE ranges not equal
if (from_ise_range == astc_helpers::BISE_64_LEVELS)
{
// from [0,64]
const auto& quant_tab = astc_helpers::g_dequant_tables.get_weight_tab(to_ise_range).m_val_to_ise;
for (uint32_t i = 0; i < n; i++)
pDst_ise_vals[i] = quant_tab[pSrc_ise_vals[i]];
}
else if (to_ise_range == astc_helpers::BISE_64_LEVELS)
{
// to [0,64]
const auto& dequant_tab = astc_helpers::g_dequant_tables.get_weight_tab(from_ise_range).m_ISE_to_val;
for (uint32_t i = 0; i < n; i++)
pDst_ise_vals[i] = dequant_tab[pSrc_ise_vals[i]];
}
else
{
// from/to any other
const auto& dequant_tab = astc_helpers::g_dequant_tables.get_weight_tab(from_ise_range).m_ISE_to_val;
const auto& quant_tab = astc_helpers::g_dequant_tables.get_weight_tab(to_ise_range).m_val_to_ise;
for (uint32_t i = 0; i < n; i++)
pDst_ise_vals[i] = quant_tab[dequant_tab[pSrc_ise_vals[i]]];
}
}
void astc_ldr_downsample_ise_weights(
uint32_t dequant_weight_ise_range, uint32_t quant_weight_ise_range,
uint32_t block_w, uint32_t block_h,
uint32_t grid_w, uint32_t grid_h,
const uint8_t* pSrc_weights, uint8_t* pDst_weights,
const float* pDownsample_matrix)
{
assert((block_w <= astc_ldr::ASTC_LDR_MAX_BLOCK_WIDTH) && (block_h <= astc_ldr::ASTC_LDR_MAX_BLOCK_HEIGHT));
assert((grid_w >= 2) && (grid_w <= block_w));
assert((grid_h >= 2) && (grid_h <= block_h));
assert(((dequant_weight_ise_range >= astc_helpers::FIRST_VALID_WEIGHT_ISE_RANGE) && (dequant_weight_ise_range <= astc_helpers::LAST_VALID_WEIGHT_ISE_RANGE)) ||
(dequant_weight_ise_range == astc_helpers::BISE_64_LEVELS));
assert(((quant_weight_ise_range >= astc_helpers::FIRST_VALID_WEIGHT_ISE_RANGE) && (quant_weight_ise_range <= astc_helpers::LAST_VALID_WEIGHT_ISE_RANGE)) ||
(quant_weight_ise_range == astc_helpers::BISE_64_LEVELS));
assert(pDownsample_matrix);
if ((block_w == grid_w) && (block_h == grid_h))
{
if (dequant_weight_ise_range != quant_weight_ise_range)
{
astc_ldr_requantize_astc_weights(block_w * block_h, pSrc_weights, dequant_weight_ise_range, pDst_weights, quant_weight_ise_range);
}
else
{
if (pDst_weights != pSrc_weights)
memcpy(pDst_weights, pSrc_weights, block_w * block_h);
}
return;
}
uint8_t desired_weights[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
if (dequant_weight_ise_range == astc_helpers::BISE_64_LEVELS)
{
memcpy(desired_weights, pSrc_weights, block_w * block_h);
}
else
{
const auto& dequant_tab = astc_helpers::g_dequant_tables.get_weight_tab(dequant_weight_ise_range).m_ISE_to_val;
for (uint32_t by = 0; by < block_h; by++)
for (uint32_t bx = 0; bx < block_w; bx++)
desired_weights[bx + by * block_w] = dequant_tab[pSrc_weights[bx + by * block_w]];
}
if (quant_weight_ise_range == astc_helpers::BISE_64_LEVELS)
{
downsample_weight_grid(
pDownsample_matrix,
block_w, block_h, // source/from dimension (block size)
grid_w, grid_h, // dest/to dimension (grid size)
desired_weights, // these are dequantized weights, NOT ISE symbols, [by][bx]
pDst_weights); // [wy][wx]
}
else
{
uint8_t raw_downsampled_weights[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
downsample_weight_grid(
pDownsample_matrix,
block_w, block_h, // source/from dimension (block size)
grid_w, grid_h, // dest/to dimension (grid size)
desired_weights, // these are dequantized weights, NOT ISE symbols, [by][bx]
raw_downsampled_weights); // [wy][wx]
const auto& weight_quant_tab = astc_helpers::g_dequant_tables.get_weight_tab(quant_weight_ise_range).m_val_to_ise;
for (uint32_t gy = 0; gy < grid_h; gy++)
for (uint32_t gx = 0; gx < grid_w; gx++)
pDst_weights[gx + gy * grid_w] = weight_quant_tab[raw_downsampled_weights[gx + gy * grid_w]];
}
}
void downsample_weight_residual_grid(
const float* pMatrix_weights,
uint32_t bx, uint32_t by, // source/from dimension (block size)
uint32_t wx, uint32_t wy, // dest/to dimension (grid size)
const int* pSrc_weights, // these are dequantized weights, NOT ISE symbols, [by][bx]
float* pDst_weights) // [wy][wx]
{
const uint32_t total_block_samples = bx * by;
for (uint32_t y = 0; y < wy; y++)
{
for (uint32_t x = 0; x < wx; x++)
{
float total = 0.0f;
for (uint32_t i = 0; i < total_block_samples; i++)
if (pMatrix_weights[i])
total += pMatrix_weights[i] * (float)pSrc_weights[i];
pDst_weights[x + y * wx] = total;
pMatrix_weights += total_block_samples;
}
}
}
void downsample_weightsf(
const float* pMatrix_weights,
uint32_t bx, uint32_t by, // source/from dimension (block size)
uint32_t wx, uint32_t wy, // dest/to dimension (grid size)
const float* pSrc_weights, // these are dequantized weights, NOT ISE symbols, [by][bx]
float* pDst_weights) // [wy][wx]
{
const uint32_t total_block_samples = bx * by;
for (uint32_t y = 0; y < wy; y++)
{
for (uint32_t x = 0; x < wx; x++)
{
float total = 0.0f;
for (uint32_t i = 0; i < total_block_samples; i++)
if (pMatrix_weights[i])
total += pMatrix_weights[i] * pSrc_weights[i];
pDst_weights[x + y * wx] = total;
pMatrix_weights += total_block_samples;
}
}
}
static inline uint32_t weighted_color_error(const color_rgba& a, const color_rgba& b, const astc_ldr::cem_encode_params& p)
{
uint32_t total_e = 0;
for (uint32_t c = 0; c < 4; c++)
{
int av = a[c];
int bv = b[c];
int ev = av - bv;
total_e += (uint32_t)(ev * ev) * p.m_comp_weights[c];
}
return total_e;
}
uint64_t eval_error(
uint32_t block_width, uint32_t block_height,
const astc_helpers::log_astc_block& enc_log_block,
const astc_ldr::pixel_stats_t& pixel_stats,
const astc_ldr::cem_encode_params& params)
{
color_rgba dec_block_pixels[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
bool status = astc_helpers::decode_block_xuastc_ldr(enc_log_block, dec_block_pixels, block_width, block_height, params.m_decode_mode_srgb ? astc_helpers::cDecodeModeSRGB8 : astc_helpers::cDecodeModeLDR8);
if (!status)
{
// Shouldn't ever happen
assert(0);
return UINT64_MAX;
}
#if defined(_DEBUG) || defined(DEBUG)
// Sanity check vs. unoptimized decoder
color_rgba dec_block_pixels_alt[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
bool alt_status = astc_helpers::decode_block(enc_log_block, dec_block_pixels_alt, block_width, block_height, params.m_decode_mode_srgb ? astc_helpers::cDecodeModeSRGB8 : astc_helpers::cDecodeModeLDR8);
if (!alt_status)
{
// Shouldn't ever happen
assert(0);
return UINT64_MAX;
}
if (memcmp(dec_block_pixels, dec_block_pixels_alt, sizeof(color_rgba) * block_width * block_height) != 0)
{
// Very bad
assert(0);
return UINT64_MAX;
}
#endif
uint64_t total_err = 0;
const uint32_t total_block_pixels = block_width * block_height;
for (uint32_t i = 0; i < total_block_pixels; i++)
total_err += weighted_color_error(dec_block_pixels[i], pixel_stats.m_pixels[i], params);
return total_err;
}
uint64_t eval_error(
uint32_t block_width, uint32_t block_height,
const astc_ldr::pixel_stats_t& pixel_stats,
uint32_t cem_index,
bool dual_plane_flag, int ccs_index,
uint32_t endpoint_ise_range, uint32_t weight_ise_range,
uint32_t grid_width, uint32_t grid_height,
const uint8_t* pEndpoint_vals, const uint8_t* pWeight_grid_vals0, const uint8_t* pWeight_grid_vals1,
const astc_ldr::cem_encode_params& params)
{
const uint32_t total_block_pixels = block_width * block_height;
const uint32_t total_grid_pixels = grid_width * grid_height;
astc_helpers::log_astc_block enc_log_block;
enc_log_block.clear();
enc_log_block.m_grid_width = (uint8_t)grid_width;
enc_log_block.m_grid_height = (uint8_t)grid_height;
enc_log_block.m_weight_ise_range = (uint8_t)weight_ise_range;
enc_log_block.m_endpoint_ise_range = (uint8_t)endpoint_ise_range;
enc_log_block.m_color_endpoint_modes[0] = (uint8_t)cem_index;
enc_log_block.m_num_partitions = 1;
memcpy(enc_log_block.m_endpoints, pEndpoint_vals, astc_helpers::get_num_cem_values(cem_index));
if (dual_plane_flag)
{
assert((ccs_index >= 0) && (ccs_index <= 3));
enc_log_block.m_dual_plane = true;
enc_log_block.m_color_component_selector = (uint8_t)ccs_index;
for (uint32_t i = 0; i < total_grid_pixels; i++)
{
enc_log_block.m_weights[i * 2 + 0] = pWeight_grid_vals0[i];
enc_log_block.m_weights[i * 2 + 1] = pWeight_grid_vals1[i];
}
}
else
{
assert(ccs_index < 0);
memcpy(enc_log_block.m_weights, pWeight_grid_vals0, total_grid_pixels);
}
color_rgba decoded_pixels[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
bool status = astc_helpers::decode_block(enc_log_block, decoded_pixels, block_width, block_height, params.m_decode_mode_srgb ? astc_helpers::cDecodeModeSRGB8 : astc_helpers::cDecodeModeLDR8);
assert(status);
if (!status)
return UINT64_MAX;
uint64_t total_err = 0;
for (uint32_t i = 0; i < total_block_pixels; i++)
total_err += weighted_color_error(pixel_stats.m_pixels[i], decoded_pixels[i], params);
return total_err;
}
float compute_psnr_from_wsse(uint32_t block_width, uint32_t block_height, uint64_t sse, float total_comp_weights)
{
const uint32_t total_block_pixels = block_width * block_height;
const float wmse = (float)sse / (total_comp_weights * (float)total_block_pixels);
const float wpsnr = (wmse > 1e-5f) ? (20.0f * log10f(255.0f / sqrtf(wmse))) : 10000.0f;
return wpsnr;
}
// quantized coordinate descent (QCD), quadratic objective
namespace qcd
{
struct qcd_min_solver
{
// geometry / sizes
int m_N = 0; // texels
int m_K = 0; // controls
int m_Q = 0; // label count
// inputs (not owned), (N x K) row-major
const float* m_pU = nullptr; // grid to texel upsample matrix
// cached
float_vec m_ucols; // N*K, column k at &m_ucols[k*m_N]
float_vec m_alpha; // K, ||u_k||^2 (>= eps)
float_vec m_labels; // Q, sorted unique u-labels (ints in [0..64]), ASTC raw [0,64] weights
bool m_ready_flag = false;
// init: cache columns, norms, and label set
bool init(const float* pU_rowmajor, int N, int K, const int* pLabels_u, int Q)
{
if ((!pU_rowmajor) || (!pLabels_u) || (N <= 0) || (K <= 0) || (Q <= 0))
return false;
m_pU = pU_rowmajor;
m_N = N;
m_K = K;
m_Q = Q;
// cache columns
m_ucols.assign(size_t(N) * K, 0.0f);
for (int k = 0; k < K; ++k)
{
float* pDst = &m_ucols[size_t(k) * size_t(N)];
const float* pSrc = m_pU + k; // first element of column k
for (int t = 0; t < N; ++t)
pDst[t] = pSrc[size_t(t) * size_t(K)];
}
// column norms
m_alpha.resize(K);
for (int k = 0; k < K; ++k)
{
const float* pUK = &m_ucols[size_t(k) * size_t(N)];
float a = 0.0f;
for (int t = 0; t < N; ++t)
a += pUK[t] * pUK[t];
if (!(a > 0.0f))
a = 1e-8f;
m_alpha[k] = a;
}
m_labels.assign(pLabels_u, pLabels_u + Q);
#if defined(_DEBUG) || defined(DEBUG)
for (size_t i = 1; i < m_labels.size(); ++i)
{
assert(m_labels[i] > m_labels[i - 1]); // strictly increasing
assert((m_labels[i] >= 0) && (m_labels[i] <= 64));
}
#endif
m_Q = (int)m_labels.size();
if (m_Q <= 0)
return false;
m_ready_flag = true;
return true;
}
// compute residual r = U*g - w* (uses label IDs -> u-values)
void build_residual(const int* pG_idx, const float* pW_star, float* pR_out) const
{
assert(m_ready_flag && pG_idx && pW_star && pR_out);
// r = sum_k (u_label[pG_idx[k]] * ucol_k) - pW_star
std::fill(pR_out, pR_out + m_N, 0.0f);
for (int k = 0; k < m_K; ++k)
{
const float* pUK = &m_ucols[size_t(k) * size_t(m_N)];
const float s = m_labels[pG_idx[k]];
for (int t = 0; t < m_N; ++t)
pR_out[t] += s * pUK[t];
}
for (int t = 0; t < m_N; ++t)
pR_out[t] -= pW_star[t];
}
// one QCD sweep: returns num moves accepted (strict dE < -eps)
int sweep(int* pG_idx, float* pR_io, float accept_eps = 1e-6f) const
{
assert(m_ready_flag && pG_idx && pR_io);
int num_moved = 0;
for (int k = 0; k < m_K; ++k)
{
const float* pUK = &m_ucols[size_t(k) * size_t(m_N)];
// beta = <r, u_k>
float beta = 0.0f;
for (int t = 0; t < m_N; ++t)
beta += pR_io[t] * pUK[t];
const float a = m_alpha[k]; // >= 1e-8
const float cur_u = m_labels[pG_idx[k]];
const float s_star = cur_u - beta / a; // continuous minimizer (u-domain)
// nearest label index to s_star (binary search)
const int j0 = nearest_label_idx(s_star);
const int cand[3] =
{
j0,
(j0 + 1 < m_Q) ? (j0 + 1) : j0,
(j0 - 1 >= 0) ? (j0 - 1) : j0
};
int best_j = pG_idx[k];
float best_dE = 0.0f;
for (int c = 0; c < 3; ++c)
{
const int j = cand[c];
if (j == pG_idx[k])
continue;
const float s = m_labels[j];
const float d = s - cur_u; // u-change at coord k
const float dE = 2.0f * d * beta + d * d * a; // exact delta E
if ((best_j == pG_idx[k]) || (dE < best_dE))
{
best_dE = dE;
best_j = j;
}
}
if ((best_j != pG_idx[k]) && (best_dE < -accept_eps))
{
// commit: update residual and label ID
const float d = m_labels[best_j] - cur_u;
for (int t = 0; t < m_N; ++t)
pR_io[t] += d * pUK[t];
pG_idx[k] = best_j;
++num_moved;
}
} // k
return num_moved;
}
// utility: energy from residual (sum r^2)
float residual_energy(const float* pR) const
{
assert(pR);
float E = 0.0f;
for (int t = 0; t < m_N; ++t)
E += pR[t] * pR[t];
return E;
}
private:
// nearest label index by u-value (handles non-uniform spacing)
int nearest_label_idx(float x) const
{
const int Q = m_Q;
if (Q <= 1)
return 0;
if (x <= m_labels.front())
return 0;
if (x >= m_labels.back())
return Q - 1;
int lo = 0, hi = Q - 1;
while (hi - lo > 1)
{
const int mid = (lo + hi) >> 1;
(x >= m_labels[mid]) ? lo = mid : hi = mid;
}
const float dlo = std::fabs(x - m_labels[lo]);
const float dhi = std::fabs(x - m_labels[hi]);
return (dlo <= dhi) ? lo : hi;
}
};
} // namespace qcd
// 1-3 subsets, requires initial weights
bool polish_block_weights(
uint32_t block_width, uint32_t block_height,
const astc_ldr::pixel_stats_t& pixel_stats,
astc_helpers::log_astc_block& enc_log_block, // assumes there is already a good encoding to improve here
const astc_ldr::cem_encode_params& params,
const astc_ldr::partition_pattern_vec* pPat,
bool& improved_flag,
bool gradient_descent_flag, bool polish_weights_flag, bool qcd_enabled_flag)
{
improved_flag = false;
if (!gradient_descent_flag && !polish_weights_flag && !qcd_enabled_flag)
return true;
const uint32_t grid_width = enc_log_block.m_grid_width, grid_height = enc_log_block.m_grid_height;
const uint32_t cem_index = enc_log_block.m_color_endpoint_modes[0];
const uint32_t num_subsets = enc_log_block.m_num_partitions;
const bool dual_plane_flag = enc_log_block.m_dual_plane;
//const uint32_t num_planes = dual_plane_flag ? 2 : 1;
const int ccs_index = dual_plane_flag ? enc_log_block.m_color_component_selector : -1;
const uint32_t endpoint_ise_range = enc_log_block.m_endpoint_ise_range;
const uint32_t weight_ise_range = enc_log_block.m_weight_ise_range;
const auto& dequant_tab = astc_helpers::g_dequant_tables.get_weight_tab(weight_ise_range).m_ISE_to_val;
const auto& quant_tab = astc_helpers::g_dequant_tables.get_weight_tab(weight_ise_range).m_val_to_ise;
//const bool is_downsampling = (grid_width < block_width) || (grid_height < block_height);
#if defined(_DEBUG) || defined(DEBUG)
if (num_subsets > 1)
{
for (uint32_t i = 1; i < num_subsets; i++)
{
assert(enc_log_block.m_color_endpoint_modes[i] == cem_index);
}
}
#endif
//const astc_block_grid_data* pBlock_grid_data = find_astc_block_grid_data(block_width, block_height, grid_width, grid_height);
const uint32_t total_block_pixels = block_width * block_height;
const uint32_t total_grid_pixels = grid_width * grid_height;
uint64_t cur_err = eval_error(block_width, block_height, enc_log_block, pixel_stats, params);
uint8_t weights0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
uint8_t weights1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
astc_helpers::extract_weights(enc_log_block, weights0, 0);
if (dual_plane_flag)
astc_helpers::extract_weights(enc_log_block, weights1, 1);
const bool global_gradient_desc_enabled = true;
const bool global_qcd_enabled = true;
const bool global_polish_weights_enabled = true;
const uint32_t NUM_WEIGHT_POLISH_PASSES = 1;
// Gradient descent
if ((gradient_descent_flag) && (global_gradient_desc_enabled))
{
// Downsample the residuals to grid res
vector2D<float> upsample_matrix;
compute_upsample_matrix(upsample_matrix, block_width, block_height, grid_width, grid_height);
// First compute the block's ideal raw weights given the current endpoints at full block/texel res
// TODO: Move to helper
uint8_t ideal_block_raw_weights0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], ideal_block_raw_weights1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
if (num_subsets == 1)
{
if (dual_plane_flag)
astc_ldr::eval_solution_dp(pixel_stats, cem_index, ccs_index, enc_log_block.m_endpoints, endpoint_ise_range, ideal_block_raw_weights0, ideal_block_raw_weights1, astc_helpers::BISE_64_LEVELS, params);
else
astc_ldr::eval_solution(pixel_stats, cem_index, enc_log_block.m_endpoints, endpoint_ise_range, ideal_block_raw_weights0, astc_helpers::BISE_64_LEVELS, params);
}
else
{
// Extract each subset's texels, compute the raw weights, place back into full res texel/block weight grid.
color_rgba part_pixels[astc_helpers::MAX_PARTITIONS][astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
uint32_t num_part_pixels[astc_helpers::MAX_PARTITIONS] = { 0 };
for (uint32_t y = 0; y < block_height; y++)
{
for (uint32_t x = 0; x < block_width; x++)
{
const color_rgba& px = pixel_stats.m_pixels[x + y * block_width];
const uint32_t part_index = (*pPat)(x, y);
assert(part_index < num_subsets);
// Sanity check
assert(part_index == (uint32_t)astc_helpers::compute_texel_partition(enc_log_block.m_partition_id, x, y, 0, num_subsets, astc_helpers::is_small_block(block_width, block_height)));
part_pixels[part_index][num_part_pixels[part_index]] = px;
num_part_pixels[part_index]++;
} // x
} // y
astc_ldr::pixel_stats_t part_pixel_stats[astc_helpers::MAX_PARTITIONS];
for (uint32_t i = 0; i < num_subsets; i++)
part_pixel_stats[i].clear();
uint8_t part_raw_weights[astc_helpers::MAX_PARTITIONS][astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
for (uint32_t part_index = 0; part_index < num_subsets; part_index++)
{
part_pixel_stats[part_index].init(num_part_pixels[part_index], &part_pixels[part_index][0]);
const uint8_t* pPart_endpoints = astc_helpers::get_endpoints(enc_log_block, part_index);
astc_ldr::eval_solution(part_pixel_stats[part_index], cem_index, pPart_endpoints, endpoint_ise_range, &part_raw_weights[part_index][0], astc_helpers::BISE_64_LEVELS, params);
} // part_index
clear_obj(num_part_pixels);
for (uint32_t y = 0; y < block_height; y++)
{
for (uint32_t x = 0; x < block_width; x++)
{
const uint32_t part_index = (*pPat)(x, y);
assert(part_index < num_subsets);
ideal_block_raw_weights0[x + y * block_width] = part_raw_weights[part_index][num_part_pixels[part_index]];
num_part_pixels[part_index]++;
} // x
} // y
}
#if 1
// Now compute the current block/texel res (upsampled) raw [0,64] weights given the current quantized grid weights. Dequant then upsample.
// This is what an ASTC decoder would use during unpacking.
uint8_t dequantized_grid_weights0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], dequantized_grid_weights1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
uint8_t dequantized_block_weights_upsampled0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], dequantized_block_weights_upsampled1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
astc_ldr_requantize_astc_weights(total_grid_pixels, weights0, weight_ise_range, dequantized_grid_weights0, astc_helpers::BISE_64_LEVELS);
if (dual_plane_flag)
astc_ldr_requantize_astc_weights(total_grid_pixels, weights1, weight_ise_range, dequantized_grid_weights1, astc_helpers::BISE_64_LEVELS);
astc_helpers::upsample_weight_grid(
block_width, block_height, // destination/to dimension
grid_width, grid_height, // source/from dimension
dequantized_grid_weights0, // these are dequantized [0,64] weights, NOT ISE symbols, [wy][wx]
dequantized_block_weights_upsampled0); // [by][bx]
if (dual_plane_flag)
{
astc_helpers::upsample_weight_grid(
block_width, block_height, // destination/to dimension
grid_width, grid_height, // source/from dimension
dequantized_grid_weights1, // these are dequantized [0,64] weights, NOT ISE symbols, [wy][wx]
dequantized_block_weights_upsampled1); // [by][bx]
}
// Now compute residuals at the block res
int weight_block_raw_residuals0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], weight_block_raw_residuals1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
for (uint32_t i = 0; i < total_block_pixels; i++)
weight_block_raw_residuals0[i] = ideal_block_raw_weights0[i] - dequantized_block_weights_upsampled0[i];
if (dual_plane_flag)
{
for (uint32_t i = 0; i < total_block_pixels; i++)
weight_block_raw_residuals1[i] = ideal_block_raw_weights1[i] - dequantized_block_weights_upsampled1[i];
}
float weight_grid_residuals_downsampled0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], weight_grid_residuals_downsampled1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
basisu::vector<float> unweighted_downsample_matrix;
// TODO: precompute, store in weight grid data
compute_upsample_matrix_transposed(unweighted_downsample_matrix, block_width, block_height, grid_width, grid_height);
basisu::vector<float> diag_AtA(total_grid_pixels);
compute_diag_AtA_vector(block_width, block_height, grid_width, grid_height, upsample_matrix, diag_AtA.get_ptr());
downsample_weight_residual_grid(
unweighted_downsample_matrix.get_ptr(),
block_width, block_height, // source/from dimension (block size)
grid_width, grid_height, // dest/to dimension (grid size)
weight_block_raw_residuals0, // these are dequantized weights, NOT ISE symbols, [by][bx]
weight_grid_residuals_downsampled0); // [wy][wx]
for (uint32_t i = 0; i < total_grid_pixels; i++)
weight_grid_residuals_downsampled0[i] /= diag_AtA[i];
if (dual_plane_flag)
{
downsample_weight_residual_grid(
unweighted_downsample_matrix.get_ptr(),
block_width, block_height, // source/from dimension (block size)
grid_width, grid_height, // dest/to dimension (grid size)
weight_block_raw_residuals1, // these are dequantized weights, NOT ISE symbols, [by][bx]
weight_grid_residuals_downsampled1); // [wy][wx]
for (uint32_t i = 0; i < total_grid_pixels; i++)
weight_grid_residuals_downsampled1[i] /= diag_AtA[i];
}
// Apply the residuals at grid res and quantize
const float Q = 1.0f;
uint8_t refined_grid_weights0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], refined_grid_weights1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
for (uint32_t i = 0; i < total_grid_pixels; i++)
{
float v = (float)dequant_tab[weights0[i]] + weight_grid_residuals_downsampled0[i] * Q;
int iv = clamp((int)std::roundf(v), 0, 64);
refined_grid_weights0[i] = quant_tab[iv];
}
if (dual_plane_flag)
{
for (uint32_t i = 0; i < total_grid_pixels; i++)
{
float v = (float)dequant_tab[weights1[i]] + weight_grid_residuals_downsampled1[i] * Q;
int iv = clamp((int)std::roundf(v), 0, 64);
refined_grid_weights1[i] = quant_tab[iv];
}
}
#else
uint8_t refined_grid_weights0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], refined_grid_weights1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
for (uint32_t i = 0; i < total_grid_pixels; i++)
refined_grid_weights0[i] = weights0[i];
if (dual_plane_flag)
{
for (uint32_t i = 0; i < total_grid_pixels; i++)
refined_grid_weights1[i] = weights1[i];
}
#endif
astc_helpers::log_astc_block refined_log_block(enc_log_block);
// TODO: This refines both weight planes simultanously, probably not optimal, could do individually.
astc_helpers::set_weights(refined_log_block, refined_grid_weights0, 0);
if (dual_plane_flag)
astc_helpers::set_weights(refined_log_block, refined_grid_weights1, 1);
uint64_t refined_err = eval_error(block_width, block_height, refined_log_block, pixel_stats, params);
if (refined_err < cur_err)
{
cur_err = refined_err;
memcpy(weights0, refined_grid_weights0, total_grid_pixels);
if (dual_plane_flag)
memcpy(weights1, refined_grid_weights1, total_grid_pixels);
improved_flag = true;
}
// QCD - not a huge boost (.05-.75 dB), but on the toughest blocks it does help.
if ((qcd_enabled_flag) && (global_qcd_enabled))
{
float ideal_block_weights0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], ideal_block_weights1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
for (uint32_t i = 0; i < total_block_pixels; i++)
{
ideal_block_weights0[i] = (float)ideal_block_raw_weights0[i];
if (dual_plane_flag)
ideal_block_weights1[i] = (float)ideal_block_raw_weights1[i];
}
const float* pUpsample_matrix = basist::astc_ldr_t::find_astc_block_grid_data(block_width, block_height, grid_width, grid_height)->m_upsample_matrix.get_ptr();
qcd::qcd_min_solver solver;
const uint32_t num_weight_levels = astc_helpers::get_ise_levels(weight_ise_range);
assert(num_weight_levels <= 32);
int labels[32 + 1];
for (uint32_t i = 0; i < num_weight_levels; i++)
labels[i] = astc_helpers::g_dequant_tables.get_weight_tab(weight_ise_range).get_rank_to_val(i);
solver.init(pUpsample_matrix, total_block_pixels, total_grid_pixels, labels, num_weight_levels);
int grid_idx0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], grid_idx1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
const auto& ise_to_rank = astc_helpers::g_dequant_tables.get_weight_tab(weight_ise_range).m_ISE_to_rank;
for (uint32_t i = 0; i < total_grid_pixels; i++)
{
grid_idx0[i] = ise_to_rank[refined_grid_weights0[i]];
if (dual_plane_flag)
grid_idx1[i] = ise_to_rank[refined_grid_weights1[i]];
}
float resid0[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS], resid1[astc_ldr::ASTC_LDR_MAX_BLOCK_PIXELS];
solver.build_residual(grid_idx0, ideal_block_weights0, resid0);
const uint32_t MAX_QCD_SWEEPS = 5;
for (uint32_t t = 0; t < MAX_QCD_SWEEPS; t++)