forked from BinomialLLC/basis_universal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basisu_enc.h
2315 lines (1850 loc) · 59 KB
/
basisu_enc.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
// basisu_enc.h
// Copyright (C) 2017-2019 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.
#pragma once
#include "transcoder/basisu.h"
#include "basisu_enc.h"
#include "transcoder/basisu_transcoder_internal.h"
#ifndef _WIN32
#include <libgen.h>
#endif
namespace basisu
{
extern uint8_t g_hamming_dist[256];
// Encoder library initialization
void basisu_encoder_init();
void error_printf(const char *pFmt, ...);
// Helpers
inline uint8_t clamp255(int32_t i)
{
return (uint8_t)((i & 0xFFFFFF00U) ? (~(i >> 31)) : i);
}
// Linear algebra
template <uint32_t N, typename T>
class vec
{
protected:
T m_v[N];
public:
enum { num_elements = N };
inline vec() { }
inline vec(eZero) { set_zero(); }
explicit inline vec(T val) { set(val); }
inline vec(T v0, T v1) { set(v0, v1); }
inline vec(T v0, T v1, T v2) { set(v0, v1, v2); }
inline vec(T v0, T v1, T v2, T v3) { set(v0, v1, v2, v3); }
inline vec(const vec &other) { for (uint32_t i = 0; i < N; i++) m_v[i] = other.m_v[i]; }
template <uint32_t OtherN, typename OtherT> inline vec(const vec<OtherN, OtherT> &other) { set(other); }
inline T operator[](uint32_t i) const { assert(i < N); return m_v[i]; }
inline T &operator[](uint32_t i) { assert(i < N); return m_v[i]; }
inline T getX() const { return m_v[0]; }
inline T getY() const { static_assert(N >= 2, "N too small"); return m_v[1]; }
inline T getZ() const { static_assert(N >= 3, "N too small"); return m_v[2]; }
inline T getW() const { static_assert(N >= 4, "N too small"); return m_v[3]; }
inline bool operator==(const vec &rhs) const { for (uint32_t i = 0; i < N; i++) if (m_v[i] != rhs.m_v[i]) return false; return true; }
inline bool operator<(const vec &rhs) const { for (uint32_t i = 0; i < N; i++) { if (m_v[i] < rhs.m_v[i]) return true; else if (m_v[i] != rhs.m_v[i]) return false; } return false; }
inline void set_zero() { for (uint32_t i = 0; i < N; i++) m_v[i] = 0; }
template <uint32_t OtherN, typename OtherT>
inline vec &set(const vec<OtherN, OtherT> &other)
{
uint32_t i;
if (static_cast<void *>(&other) == static_cast<void *>(this))
return *this;
const uint32_t m = minimum(OtherN, N);
for (i = 0; i < m; i++)
m_v[i] = static_cast<T>(other[i]);
for (; i < N; i++)
m_v[i] = 0;
return *this;
}
inline vec &set_component(uint32_t index, T val) { assert(index < N); m_v[index] = val; return *this; }
inline vec &set(T val) { for (uint32_t i = 0; i < N; i++) m_v[i] = val; return *this; }
inline void clear_elements(uint32_t s, uint32_t e) { assert(e <= N); for (uint32_t i = s; i < e; i++) m_v[i] = 0; }
inline vec &set(T v0, T v1)
{
m_v[0] = v0;
if (N >= 2)
{
m_v[1] = v1;
clear_elements(2, N);
}
return *this;
}
inline vec &set(T v0, T v1, T v2)
{
m_v[0] = v0;
if (N >= 2)
{
m_v[1] = v1;
if (N >= 3)
{
m_v[2] = v2;
clear_elements(3, N);
}
}
return *this;
}
inline vec &set(T v0, T v1, T v2, T v3)
{
m_v[0] = v0;
if (N >= 2)
{
m_v[1] = v1;
if (N >= 3)
{
m_v[2] = v2;
if (N >= 4)
{
m_v[3] = v3;
clear_elements(5, N);
}
}
}
return *this;
}
inline vec &operator=(const vec &rhs) { if (this != &rhs) for (uint32_t i = 0; i < N; i++) m_v[i] = rhs.m_v[i]; return *this; }
template <uint32_t OtherN, typename OtherT> inline vec &operator=(const vec<OtherN, OtherT> &rhs) { set(rhs); return *this; }
inline const T *get_ptr() const { return reinterpret_cast<const T *>(&m_v[0]); }
inline T *get_ptr() { return reinterpret_cast<T *>(&m_v[0]); }
inline vec operator- () const { vec res; for (uint32_t i = 0; i < N; i++) res.m_v[i] = -m_v[i]; return res; }
inline vec operator+ () const { return *this; }
inline vec &operator+= (const vec &other) { for (uint32_t i = 0; i < N; i++) m_v[i] += other.m_v[i]; return *this; }
inline vec &operator-= (const vec &other) { for (uint32_t i = 0; i < N; i++) m_v[i] -= other.m_v[i]; return *this; }
inline vec &operator/= (const vec &other) { for (uint32_t i = 0; i < N; i++) m_v[i] /= other.m_v[i]; return *this; }
inline vec &operator*=(const vec &other) { for (uint32_t i = 0; i < N; i++) m_v[i] *= other.m_v[i]; return *this; }
inline vec &operator/= (T s) { for (uint32_t i = 0; i < N; i++) m_v[i] /= s; return *this; }
inline vec &operator*= (T s) { for (uint32_t i = 0; i < N; i++) m_v[i] *= s; return *this; }
friend inline vec operator+(const vec &lhs, const vec &rhs) { vec res; for (uint32_t i = 0; i < N; i++) res.m_v[i] = lhs.m_v[i] + rhs.m_v[i]; return res; }
friend inline vec operator-(const vec &lhs, const vec &rhs) { vec res; for (uint32_t i = 0; i < N; i++) res.m_v[i] = lhs.m_v[i] - rhs.m_v[i]; return res; }
friend inline vec operator*(const vec &lhs, T val) { vec res; for (uint32_t i = 0; i < N; i++) res.m_v[i] = lhs.m_v[i] * val; return res; }
friend inline vec operator*(T val, const vec &rhs) { vec res; for (uint32_t i = 0; i < N; i++) res.m_v[i] = val * rhs.m_v[i]; return res; }
friend inline vec operator/(const vec &lhs, T val) { vec res; for (uint32_t i = 0; i < N; i++) res.m_v[i] = lhs.m_v[i] / val; return res; }
friend inline vec operator/(const vec &lhs, const vec &rhs) { vec res; for (uint32_t i = 0; i < N; i++) res.m_v[i] = lhs.m_v[i] / rhs.m_v[i]; return res; }
static inline T dot_product(const vec &lhs, const vec &rhs) { T res = lhs.m_v[0] * rhs.m_v[0]; for (uint32_t i = 1; i < N; i++) res += lhs.m_v[i] * rhs.m_v[i]; return res; }
inline T dot(const vec &rhs) const { return dot_product(*this, rhs); }
inline T norm() const { return dot_product(*this, *this); }
inline T length() const { return sqrt(norm()); }
inline T squared_distance(const vec &other) const { T d2 = 0; for (uint32_t i = 0; i < N; i++) { T d = m_v[i] - other.m_v[i]; d2 += d * d; } return d2; }
inline T distance(const vec &other) const { return squared_distance(other); }
inline vec &normalize_in_place() { T len = length(); if (len != 0.0f) *this *= (1.0f / len); return *this; }
inline vec &clamp(T l, T h)
{
for (uint32_t i = 0; i < N; i++)
m_v[i] = basisu::clamp(m_v[i], l, h);
return *this;
}
};
typedef vec<4, double> vec4D;
typedef vec<3, double> vec3D;
typedef vec<2, double> vec2D;
typedef vec<1, double> vec1D;
typedef vec<4, float> vec4F;
typedef vec<3, float> vec3F;
typedef vec<2, float> vec2F;
typedef vec<1, float> vec1F;
template <uint32_t Rows, uint32_t Cols, typename T>
class matrix
{
public:
typedef vec<Rows, T> col_vec;
typedef vec<Cols, T> row_vec;
typedef T scalar_type;
enum { rows = Rows, cols = Cols };
protected:
row_vec m_r[Rows];
public:
inline matrix() {}
inline matrix(eZero) { set_zero(); }
inline matrix(const matrix &other) { for (uint32_t i = 0; i < Rows; i++) m_r[i] = other.m_r[i]; }
inline matrix &operator=(const matrix &rhs) { if (this != &rhs) for (uint32_t i = 0; i < Rows; i++) m_r[i] = rhs.m_r[i]; return *this; }
inline T operator()(uint32_t r, uint32_t c) const { assert((r < Rows) && (c < Cols)); return m_r[r][c]; }
inline T &operator()(uint32_t r, uint32_t c) { assert((r < Rows) && (c < Cols)); return m_r[r][c]; }
inline const row_vec &operator[](uint32_t r) const { assert(r < Rows); return m_r[r]; }
inline row_vec &operator[](uint32_t r) { assert(r < Rows); return m_r[r]; }
inline matrix &set_zero()
{
for (uint32_t i = 0; i < Rows; i++)
m_r[i].set_zero();
return *this;
}
inline matrix &set_identity()
{
for (uint32_t i = 0; i < Rows; i++)
{
m_r[i].set_zero();
if (i < Cols)
m_r[i][i] = 1.0f;
}
return *this;
}
};
template<uint32_t N, typename VectorType>
inline VectorType compute_pca_from_covar(matrix<N, N, float> &cmatrix)
{
VectorType axis;
if (N == 1)
axis.set(1.0f);
else
{
for (uint32_t i = 0; i < N; i++)
axis[i] = lerp(.75f, 1.25f, i * (1.0f / maximum<int>(N - 1, 1)));
}
VectorType prev_axis(axis);
// Power iterations
for (uint32_t power_iter = 0; power_iter < 8; power_iter++)
{
VectorType trial_axis;
double max_sum = 0;
for (uint32_t i = 0; i < N; i++)
{
double sum = 0;
for (uint32_t j = 0; j < N; j++)
sum += cmatrix[i][j] * axis[j];
trial_axis[i] = static_cast<float>(sum);
max_sum = maximum(fabs(sum), max_sum);
}
if (max_sum != 0.0f)
trial_axis *= static_cast<float>(1.0f / max_sum);
VectorType delta_axis(prev_axis - trial_axis);
prev_axis = axis;
axis = trial_axis;
if (delta_axis.norm() < .0024f)
break;
}
return axis.normalize_in_place();
}
template<typename T> inline void indirect_sort(uint32_t num_indices, uint32_t* pIndices, const T* pKeys)
{
for (uint32_t i = 0; i < num_indices; i++)
pIndices[i] = i;
std::sort(
pIndices,
pIndices + num_indices,
[pKeys](uint32_t a, uint32_t b) { return pKeys[a] < pKeys[b]; }
);
}
// Simple 32-bit color class
class color_rgba_i16
{
public:
union
{
int16_t m_comps[4];
struct
{
int16_t r;
int16_t g;
int16_t b;
int16_t a;
};
};
inline color_rgba_i16()
{
static_assert(sizeof(*this) == sizeof(int16_t)*4, "sizeof(*this) == sizeof(int16_t)*4");
}
inline color_rgba_i16(int sr, int sg, int sb, int sa)
{
set(sr, sg, sb, sa);
}
inline color_rgba_i16 &set(int sr, int sg, int sb, int sa)
{
m_comps[0] = (int16_t)clamp<int>(sr, INT16_MIN, INT16_MAX);
m_comps[1] = (int16_t)clamp<int>(sg, INT16_MIN, INT16_MAX);
m_comps[2] = (int16_t)clamp<int>(sb, INT16_MIN, INT16_MAX);
m_comps[3] = (int16_t)clamp<int>(sa, INT16_MIN, INT16_MAX);
return *this;
}
};
class color_rgba
{
public:
union
{
uint8_t m_comps[4];
struct
{
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
};
inline color_rgba()
{
static_assert(sizeof(*this) == 4, "sizeof(*this) != 4");
}
inline color_rgba(int y)
{
set(y);
}
inline color_rgba(int y, int na)
{
set(y, na);
}
inline color_rgba(int sr, int sg, int sb, int sa)
{
set(sr, sg, sb, sa);
}
inline color_rgba(eNoClamp, int sr, int sg, int sb, int sa)
{
set_noclamp_rgba((uint8_t)sr, (uint8_t)sg, (uint8_t)sb, (uint8_t)sa);
}
inline color_rgba& set_noclamp_y(int y)
{
m_comps[0] = (uint8_t)y;
m_comps[1] = (uint8_t)y;
m_comps[2] = (uint8_t)y;
m_comps[3] = (uint8_t)255;
return *this;
}
inline color_rgba &set_noclamp_rgba(int sr, int sg, int sb, int sa)
{
m_comps[0] = (uint8_t)sr;
m_comps[1] = (uint8_t)sg;
m_comps[2] = (uint8_t)sb;
m_comps[3] = (uint8_t)sa;
return *this;
}
inline color_rgba &set(int y)
{
m_comps[0] = static_cast<uint8_t>(clamp<int>(y, 0, 255));
m_comps[1] = m_comps[0];
m_comps[2] = m_comps[0];
m_comps[3] = 255;
return *this;
}
inline color_rgba &set(int y, int na)
{
m_comps[0] = static_cast<uint8_t>(clamp<int>(y, 0, 255));
m_comps[1] = m_comps[0];
m_comps[2] = m_comps[0];
m_comps[3] = static_cast<uint8_t>(clamp<int>(na, 0, 255));
return *this;
}
inline color_rgba &set(int sr, int sg, int sb, int sa)
{
m_comps[0] = static_cast<uint8_t>(clamp<int>(sr, 0, 255));
m_comps[1] = static_cast<uint8_t>(clamp<int>(sg, 0, 255));
m_comps[2] = static_cast<uint8_t>(clamp<int>(sb, 0, 255));
m_comps[3] = static_cast<uint8_t>(clamp<int>(sa, 0, 255));
return *this;
}
inline color_rgba &set_rgb(int sr, int sg, int sb)
{
m_comps[0] = static_cast<uint8_t>(clamp<int>(sr, 0, 255));
m_comps[1] = static_cast<uint8_t>(clamp<int>(sg, 0, 255));
m_comps[2] = static_cast<uint8_t>(clamp<int>(sb, 0, 255));
return *this;
}
inline color_rgba &set_rgb(const color_rgba &other)
{
r = other.r;
g = other.g;
b = other.b;
return *this;
}
inline const uint8_t &operator[] (uint32_t index) const { assert(index < 4); return m_comps[index]; }
inline uint8_t &operator[] (uint32_t index) { assert(index < 4); return m_comps[index]; }
inline void clear()
{
m_comps[0] = 0;
m_comps[1] = 0;
m_comps[2] = 0;
m_comps[3] = 0;
}
inline bool operator== (const color_rgba &rhs) const
{
if (m_comps[0] != rhs.m_comps[0]) return false;
if (m_comps[1] != rhs.m_comps[1]) return false;
if (m_comps[2] != rhs.m_comps[2]) return false;
if (m_comps[3] != rhs.m_comps[3]) return false;
return true;
}
inline bool operator!= (const color_rgba &rhs) const
{
return !(*this == rhs);
}
inline bool operator<(const color_rgba &rhs) const
{
for (int i = 0; i < 4; i++)
{
if (m_comps[i] < rhs.m_comps[i])
return true;
else if (m_comps[i] != rhs.m_comps[i])
return false;
}
return false;
}
inline int get_601_luma() const { return (19595U * m_comps[0] + 38470U * m_comps[1] + 7471U * m_comps[2] + 32768U) >> 16U; }
inline int get_709_luma() const { return (13938U * m_comps[0] + 46869U * m_comps[1] + 4729U * m_comps[2] + 32768U) >> 16U; }
inline int get_luma(bool luma_601) const { return luma_601 ? get_601_luma() : get_709_luma(); }
};
typedef std::vector<color_rgba> color_rgba_vec;
const color_rgba g_black_color(0, 0, 0, 255);
const color_rgba g_white_color(255, 255, 255, 255);
inline int color_distance(int r0, int g0, int b0, int r1, int g1, int b1)
{
int dr = r0 - r1, dg = g0 - g1, db = b0 - b1;
return dr * dr + dg * dg + db * db;
}
inline int color_distance(int r0, int g0, int b0, int a0, int r1, int g1, int b1, int a1)
{
int dr = r0 - r1, dg = g0 - g1, db = b0 - b1, da = a0 - a1;
return dr * dr + dg * dg + db * db + da * da;
}
inline int color_distance(const color_rgba &c0, const color_rgba &c1, bool alpha)
{
if (alpha)
return color_distance(c0.r, c0.g, c0.b, c0.a, c1.r, c1.g, c1.b, c1.a);
else
return color_distance(c0.r, c0.g, c0.b, c1.r, c1.g, c1.b);
}
// TODO: Allow user to control channel weightings.
inline uint32_t color_distance(bool perceptual, const color_rgba &e1, const color_rgba &e2, bool alpha)
{
if (perceptual)
{
const float l1 = e1.r * .2126f + e1.g * .715f + e1.b * .0722f;
const float l2 = e2.r * .2126f + e2.g * .715f + e2.b * .0722f;
const float cr1 = e1.r - l1;
const float cr2 = e2.r - l2;
const float cb1 = e1.b - l1;
const float cb2 = e2.b - l2;
const float dl = l1 - l2;
const float dcr = cr1 - cr2;
const float dcb = cb1 - cb2;
uint32_t d = static_cast<uint32_t>(32.0f*4.0f*dl*dl + 32.0f*2.0f*(.5f / (1.0f - .2126f))*(.5f / (1.0f - .2126f))*dcr*dcr + 32.0f*.25f*(.5f / (1.0f - .0722f))*(.5f / (1.0f - .0722f))*dcb*dcb);
if (alpha)
{
int da = static_cast<int>(e1.a) - static_cast<int>(e2.a);
d += static_cast<uint32_t>(128.0f*da*da);
}
return d;
}
else
return color_distance(e1, e2, alpha);
}
// String helpers
inline int string_find_right(const std::string& filename, char c)
{
size_t result = filename.find_last_of(c);
return (result == std::string::npos) ? -1 : (int)result;
}
inline std::string string_get_extension(const std::string &filename)
{
int sep = -1;
#ifdef _WIN32
sep = string_find_right(filename, '\\');
#endif
if (sep < 0)
sep = string_find_right(filename, '/');
int dot = string_find_right(filename, '.');
if (dot <= sep)
return "";
std::string result(filename);
result.erase(0, dot + 1);
return result;
}
inline bool string_remove_extension(std::string &filename)
{
int sep = -1;
#ifdef _WIN32
sep = string_find_right(filename, '\\');
#endif
if (sep < 0)
sep = string_find_right(filename, '/');
int dot = string_find_right(filename, '.');
if ((dot < sep) || (dot < 0))
return false;
filename.resize(dot);
return true;
}
inline std::string string_format(const char* pFmt, ...)
{
char buf[2048];
va_list args;
va_start(args, pFmt);
#ifdef _WIN32
vsprintf_s(buf, sizeof(buf), pFmt, args);
#else
vsnprintf(buf, sizeof(buf), pFmt, args);
#endif
va_end(args);
return std::string(buf);
}
inline std::string string_tolower(const std::string& s)
{
std::string result(s);
for (size_t i = 0; i < result.size(); i++)
result[i] = (char)tolower((int)result[i]);
return result;
}
inline char *strcpy_safe(char *pDst, size_t dst_len, const char *pSrc)
{
assert(pDst && pSrc && dst_len);
if (!dst_len)
return pDst;
const size_t src_len = strlen(pSrc);
const size_t src_len_plus_terminator = src_len + 1;
if (src_len_plus_terminator <= dst_len)
memcpy(pDst, pSrc, src_len_plus_terminator);
else
{
if (dst_len > 1)
memcpy(pDst, pSrc, dst_len - 1);
pDst[dst_len - 1] = '\0';
}
return pDst;
}
inline bool string_ends_with(const std::string& s, char c)
{
return (s.size() != 0) && (s.back() == c);
}
inline bool string_split_path(const char *p, std::string *pDrive, std::string *pDir, std::string *pFilename, std::string *pExt)
{
#ifdef _MSC_VER
char drive_buf[_MAX_DRIVE] = { 0 };
char dir_buf[_MAX_DIR] = { 0 };
char fname_buf[_MAX_FNAME] = { 0 };
char ext_buf[_MAX_EXT] = { 0 };
errno_t error = _splitpath_s(p,
pDrive ? drive_buf : NULL, pDrive ? _MAX_DRIVE : 0,
pDir ? dir_buf : NULL, pDir ? _MAX_DIR : 0,
pFilename ? fname_buf : NULL, pFilename ? _MAX_FNAME : 0,
pExt ? ext_buf : NULL, pExt ? _MAX_EXT : 0);
if (error != 0)
return false;
if (pDrive) *pDrive = drive_buf;
if (pDir) *pDir = dir_buf;
if (pFilename) *pFilename = fname_buf;
if (pExt) *pExt = ext_buf;
return true;
#else
char dirtmp[1024], nametmp[1024];
strcpy_safe(dirtmp, sizeof(dirtmp), p);
strcpy_safe(nametmp, sizeof(nametmp), p);
if (pDrive)
pDrive->resize(0);
const char *pDirName = dirname(dirtmp);
const char* pBaseName = basename(nametmp);
if ((!pDirName) || (!pBaseName))
return false;
if (pDir)
{
*pDir = pDirName;
if ((pDir->size()) && (pDir->back() != '/'))
*pDir += "/";
}
if (pFilename)
{
*pFilename = pBaseName;
string_remove_extension(*pFilename);
}
if (pExt)
{
*pExt = pBaseName;
*pExt = string_get_extension(*pExt);
if (pExt->size())
*pExt = "." + *pExt;
}
return true;
#endif
}
inline bool is_path_separator(char c)
{
#ifdef _WIN32
return (c == '/') || (c == '\\');
#else
return (c == '/');
#endif
}
inline bool is_drive_separator(char c)
{
#ifdef _WIN32
return (c == ':');
#else
(void)c;
return false;
#endif
}
inline void string_combine_path(std::string &dst, const char *p, const char *q)
{
std::string temp(p);
if (temp.size() && !is_path_separator(q[0]))
{
if (!is_path_separator(temp.back()))
temp.append(1, BASISU_PATH_SEPERATOR_CHAR);
}
temp += q;
dst.swap(temp);
}
inline void string_combine_path(std::string &dst, const char *p, const char *q, const char *r)
{
string_combine_path(dst, p, q);
string_combine_path(dst, dst.c_str(), r);
}
inline void string_combine_path_and_extension(std::string &dst, const char *p, const char *q, const char *r, const char *pExt)
{
string_combine_path(dst, p, q, r);
if ((!string_ends_with(dst, '.')) && (pExt[0]) && (pExt[0] != '.'))
dst.append(1, '.');
dst.append(pExt);
}
inline bool string_get_pathname(const char *p, std::string &path)
{
std::string temp_drive, temp_path;
if (!string_split_path(p, &temp_drive, &temp_path, NULL, NULL))
return false;
string_combine_path(path, temp_drive.c_str(), temp_path.c_str());
return true;
}
inline bool string_get_filename(const char *p, std::string &filename)
{
std::string temp_ext;
if (!string_split_path(p, nullptr, nullptr, &filename, &temp_ext))
return false;
filename += temp_ext;
return true;
}
class rand
{
std::mt19937 m_mt;
public:
rand() { }
rand(uint32_t s) { seed(s); }
void seed(uint32_t s) { m_mt.seed(s); }
// between [l,h]
int irand(int l, int h) { std::uniform_int_distribution<int> d(l, h); return d(m_mt); }
uint32_t urand32() { return static_cast<uint32_t>(irand(INT32_MIN, INT32_MAX)); }
bool bit() { return irand(0, 1) == 1; }
uint8_t byte() { return static_cast<uint8_t>(urand32()); }
// between [l,h)
float frand(float l, float h) { std::uniform_real_distribution<float> d(l, h); return d(m_mt); }
float gaussian(float mean, float stddev) { std::normal_distribution<float> d(mean, stddev); return d(m_mt); }
};
class priority_queue
{
public:
priority_queue() :
m_size(0)
{
}
void clear()
{
m_heap.clear();
m_size = 0;
}
void init(uint32_t max_entries, uint32_t first_index, float first_priority)
{
m_heap.resize(max_entries + 1);
m_heap[1].m_index = first_index;
m_heap[1].m_priority = first_priority;
m_size = 1;
}
inline uint32_t size() const { return m_size; }
inline uint32_t get_top_index() const { return m_heap[1].m_index; }
inline float get_top_priority() const { return m_heap[1].m_priority; }
inline void delete_top()
{
assert(m_size > 0);
m_heap[1] = m_heap[m_size];
m_size--;
if (m_size)
down_heap(1);
}
inline void add_heap(uint32_t index, float priority)
{
m_size++;
uint32_t k = m_size;
if (m_size >= m_heap.size())
m_heap.resize(m_size + 1);
for (;;)
{
uint32_t parent_index = k >> 1;
if ((!parent_index) || (m_heap[parent_index].m_priority > priority))
break;
m_heap[k] = m_heap[parent_index];
k = parent_index;
}
m_heap[k].m_index = index;
m_heap[k].m_priority = priority;
}
private:
struct entry
{
uint32_t m_index;
float m_priority;
};
std::vector<entry> m_heap;
uint32_t m_size;
// Push down entry at index
inline void down_heap(uint32_t heap_index)
{
uint32_t orig_index = m_heap[heap_index].m_index;
const float orig_priority = m_heap[heap_index].m_priority;
uint32_t child_index;
while ((child_index = (heap_index << 1)) <= m_size)
{
if ((child_index < m_size) && (m_heap[child_index].m_priority < m_heap[child_index + 1].m_priority)) ++child_index;
if (orig_priority > m_heap[child_index].m_priority)
break;
m_heap[heap_index] = m_heap[child_index];
heap_index = child_index;
}
m_heap[heap_index].m_index = orig_index;
m_heap[heap_index].m_priority = orig_priority;
}
};
// Tree structured vector quantization (TSVQ)
template <typename TrainingVectorType>
class tree_vector_quant
{
public:
typedef std::pair<TrainingVectorType, uint32_t> training_vec_with_weight;
typedef std::vector< training_vec_with_weight > array_of_weighted_training_vecs;
tree_vector_quant()
{
}
void clear()
{
clear_vector(m_training_vecs);
clear_vector(m_nodes);
}
void add_training_vec(const TrainingVectorType &v, uint32_t weight) { m_training_vecs.push_back(std::make_pair(v, weight)); }
void retrieve(std::vector< std::vector<uint32_t> > &codebook) const
{
for (uint32_t i = 0; i < m_nodes.size(); i++)
{
const tsvq_node &n = m_nodes[i];
if (!n.is_leaf())
continue;
codebook.resize(codebook.size() + 1);
codebook.back() = n.m_training_vecs;
}
}
void retrieve(std::vector<TrainingVectorType> &codebook) const
{
for (uint32_t i = 0; i < m_nodes.size(); i++)
{
const tsvq_node &n = m_nodes[i];
if (!n.is_leaf())
continue;
codebook.resize(codebook.size() + 1);
codebook.back() = n.m_origin;
}
}
bool generate(uint32_t max_size)
{
if (!m_training_vecs.size())
return false;
clear_vector(m_nodes);
m_nodes.reserve(max_size * 2 + 1);
m_nodes.push_back(prepare_root());
priority_queue var_heap;
var_heap.init(max_size, 0, m_nodes[0].m_var);
std::vector<uint32_t> l_children, r_children;
// Now split the worst nodes
l_children.reserve(m_training_vecs.size() + 1);
r_children.reserve(m_training_vecs.size() + 1);
uint32_t total_leaf_nodes = 1;
while ((var_heap.size()) && (total_leaf_nodes < max_size))
{
const uint32_t node_index = var_heap.get_top_index();
const tsvq_node &node = m_nodes[node_index];
assert(node.m_var == var_heap.get_top_priority());
assert(node.is_leaf());
var_heap.delete_top();
if (node.m_training_vecs.size() > 1)
{
if (split_node(node_index, var_heap, l_children, r_children))
{
// This removes one leaf node (making an internal node) and replaces it with two new leaves, so +1 total.
total_leaf_nodes += 1;
}
}
}
return true;
}
private:
class tsvq_node
{
public:
inline tsvq_node() : m_weight(0), m_origin(cZero), m_left_index(-1), m_right_index(-1) { }
// vecs is erased
inline void set(const TrainingVectorType &org, uint64_t weight, float var, std::vector<uint32_t> &vecs) { m_origin = org; m_weight = weight; m_var = var; m_training_vecs.swap(vecs); }
inline bool is_leaf() const { return m_left_index < 0; }
float m_var;
uint64_t m_weight;
TrainingVectorType m_origin;
int32_t m_left_index, m_right_index;
std::vector<uint32_t> m_training_vecs;
};
typedef std::vector<tsvq_node> tsvq_node_vec;
tsvq_node_vec m_nodes;
array_of_weighted_training_vecs m_training_vecs;
tsvq_node prepare_root() const
{
double ttsum = 0.0f;
// Prepare root node containing all training vectors
tsvq_node root;
root.m_training_vecs.reserve(m_training_vecs.size());
for (uint32_t i = 0; i < m_training_vecs.size(); i++)
{
const TrainingVectorType &v = m_training_vecs[i].first;
const uint32_t weight = m_training_vecs[i].second;
root.m_training_vecs.push_back(i);
root.m_origin += (v * static_cast<float>(weight));
root.m_weight += weight;
ttsum += v.dot(v) * weight;
}
root.m_var = static_cast<float>(ttsum - (root.m_origin.dot(root.m_origin) / root.m_weight));