-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfxv.cpp
More file actions
4507 lines (4197 loc) · 152 KB
/
fxv.cpp
File metadata and controls
4507 lines (4197 loc) · 152 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
/* fxv file compressor/archiver.
Copyright (C) 2019-2024 Kaido Orav, 2006-2007 Matt Mahoney (paq8), 2014-2017 Robert Swierczek (c4), etc
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details at
Visit <http://www.gnu.org/copyleft/gpl.html>.
Based on paq8 type compressors. See http://www.mattmahoney.net/dc/text.html
*/
#define VERSION "1"
#define PROGNAME "fxv" // Please change this if you change the program.
#define MT // uncomment for multithreading, compression only
#define ERRMSG // uncomment to show error messages if programm quits
#define VMMSG // prints vm error messages and x86 asm to console
#define FXTUNE // uncomment to enable tune
#ifdef WINDOWS
#ifdef MT
//#define PTHREAD //uncomment to force pthread to igore windows native threads
#endif
#endif
#ifdef UNIX
#error "This will not compile under Linux"
#ifdef MT
#define PTHREAD 1
#endif
#endif
#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
#define NDEBUG // remove for debugging (turns on Array bound checks)
#include <assert.h>
#ifdef MT
#include <vector>
#endif
#ifdef UNIX
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <memory.h>
#include <cstdio>
#include <ctype.h>
#include <sys/cdefs.h>
#include <dirent.h>
#include <errno.h>
#endif
#ifdef WINDOWS
#include <windows.h>
#endif
#include <stdint.h>
#ifdef _MSC_VER
//
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#endif
// 8, 16, 32, 64 bit unsigned types
typedef unsigned char U8;
typedef unsigned short U16;
typedef unsigned int U32;
typedef uint64_t U64;
struct object {
U32 size;
char *data;
};
// min, max functions
#if !defined(WINDOWS) || !defined (min)
inline int min(int a, int b) {return a<b?a:b;}
inline int max(int a, int b) {return a<b?b:a;}
#endif
#ifdef MT
#ifdef PTHREAD
#include "pthread.h"
#endif
#endif
#define ispowerof2(x) ((x&(x-1))==0)
#include <math.h>
// Error handler: print message if any, and exit
void quit(const char* message=0) {
#ifdef ERRMSG
printf("%s",message);
#endif
exit(1);
}
// strings are equal ignoring case?
int equals(const char* a, const char* b) {
assert(a && b);
while (*a && *b) {
int c1=*a;
if (c1>='A'&&c1<='Z') c1+='a'-'A';
int c2=*b;
if (c2>='A'&&c2<='Z') c2+='a'-'A';
if (c1!=c2) return 0;
++a;
++b;
}
return *a==*b;
}
// Array
// Array<T,Align> a(n); allocates memory for n elements of T.
// The base address is aligned if the "alignment" parameter is given.
// Constructors for T are not called, the allocated memory is initialized to 0s.
// It's the caller's responsibility to populate the array with elements.
// Parameters are checked and indexing is bounds checked if assertions are on.
// Use of copy and assignment constructors are not supported.
//
// a.size(): returns the number of T elements currently in the array.
// a.resize(newsize): grows or shrinks the array.
// a.append(x): appends x to the end of the array and reserving space for more elements if needed.
// a.pop_back(): removes the last element by reducing the size by one (but does not free memory).
#ifndef NDEBUG
static void chkindex(U32 index, U32 upper_bound) {
if (index>=upper_bound) {
fprintf(stderr, "out of upper bound %d\n",index);
quit();
}
}
#endif
template <class T, const int Align=16> class Array {
private:
U64 used_size;
U64 reserved_size;
char *ptr; // Address of allocated memory (may not be aligned)
T* data; // Aligned base address of the elements, (ptr <= T)
void create(U64 requested_size);
inline U64 padding() const {return Align-1;}
inline U64 allocated_bytes() const {return (reserved_size==0)?0:reserved_size*sizeof(T)+padding();}
public:
explicit Array(U64 requested_size) {create(requested_size);}
~Array();
T& operator[](U64 i) {
#ifndef NDEBUG
chkindex(U32(i),U32(used_size));
#endif
return data[U32(i)];
}
const T& operator[](U64 i) const {
#ifndef NDEBUG
chkindex(U32(i),U32(used_size));
#endif
return data[U32(i)];
}
U64 size() const {return used_size;}
int size32() const {return int(used_size);}
void resize(U64 new_size);
void pop_back() {assert(used_size>0); --used_size; } // decrement size
void push_back(const T& x); // increment size, append x
Array(const Array&) { assert(false); } //prevent copying - this method must be public (gcc must see it but actually won't use it)
//private:
Array& operator=(const Array&); //prevent assignment
};
template<class T, const int Align> void Array<T,Align>::create(U64 requested_size) {
assert((Align&(Align-1))==0);
used_size=reserved_size=requested_size;
if (requested_size==0) {
data=0;ptr=0;
return;
}
U64 bytes_to_allocate=allocated_bytes();
ptr=(char*)calloc(bytes_to_allocate,1);
if(!ptr){
printf("Requested size %d b.\n",(U32)(bytes_to_allocate));
#ifdef MT
printf("Try using less memory in your cfg file or reduce thread count.\n");
#endif
quit("Out of memory.");
}
U64 pad=padding();
data=(T*)(((uintptr_t)ptr+pad) & ~(uintptr_t)pad);
assert(ptr<=(char*)data && (char*)data<=ptr+Align);
assert(((uintptr_t)data & (Align-1))==0); //aligned as expected?
}
template<class T, const int Align> void Array<T,Align>::resize(U64 new_size) {
if (new_size<=reserved_size) {
used_size=new_size;
return;
}
char *old_ptr=ptr;
T *old_data=data;
U64 old_size=used_size;
create(new_size);
if(old_size>0) {
assert(old_ptr && old_data);
memcpy(data, old_data, sizeof(T)*old_size);
}
if(old_ptr){free(old_ptr);old_ptr=0;}
}
template<class T, const int Align> void Array<T,Align>::push_back(const T& x) {
if(used_size==reserved_size) {
U64 old_size=used_size;
U64 new_size=used_size*2+16;
resize(new_size);
used_size=old_size;
}
data[used_size++]=x;
}
template<class T, const int Align> Array<T, Align>::~Array() {
free(ptr);
used_size=reserved_size=0;
data=0;ptr=0;
}
//
template <class T> void alloc(T*&ptr, int c) {
ptr=(T*)calloc(c, sizeof(T));
if (!ptr) {
quit("Out of memory.\n");
}
}
template <class T> void alloc1(T*&data, int c,T*&ptr,const int align=16) {
ptr=(T*)calloc(c, sizeof(T));
if (!ptr) {
quit("Out of memory.\n");
}
data=(T*)(((uintptr_t)ptr+(align-1)) & ~(uintptr_t)(align-1));
}
template <class T> void ralloc(T*&ptr, int c) {
ptr=(T*)realloc(ptr,c);
if (!ptr) {
quit("Out of memory.\n");
}
}
// String
// A tiny subset of std::string
// size() includes NUL terminator.
class String: public Array<char> {
public:
const char* c_str() const {return &(*this)[0];}
void operator=(const char* s) {
resize(strlen(s)+1);
strcpy(&(*this)[0], s);
}
void operator+=(const char* s) {
assert(s);
pop_back();
while (*s) push_back(*s++);
push_back(0);
}
String(const char* s=""): Array<char>(1) {
(*this)+=s;
}
};
FILE* tmpfile2(void){
FILE *f;
#if defined(WINDOWS)
int i;
char temppath[MAX_PATH];
char filename[MAX_PATH];
//i=GetTempPath(MAX_PATH,temppath); //store temp file in system temp path
i=GetModuleFileName(NULL,temppath,MAX_PATH); //store temp file in program folder
if ((i==0) || (i>MAX_PATH)) return NULL;
char *p=strrchr(temppath, '\\');
if (p==0) return NULL;
p++;*p=0;
if (GetTempFileName(temppath,"tmp",0,filename)==0) return NULL;
f=fopen(filename,"w+bTD");
if (f==NULL) unlink(filename);
return f;
#else
f=tmpfile(); // temporary file
if (!f) return NULL;
return f;
#endif
}
// Buffer for file segment info
// type size info(if not -1)
class Segment {
Array<U8> b;
public:
U32 pos; //size of buffer
U64 hpos; //header pos points to segment info at archive end
Segment(int i=0): b(i),pos(0),hpos(0) {}
void setsize(int i) {
if (!i) return;
assert(i>0);
b.resize(i);
}
U8& operator[](U32 i) {
if (i>=b.size()) setsize(i+1);
return b[i];
}
U8 operator()(U32 i) const {
assert(i>=0);
assert(i<=b.size());
return b[i];
}
// put 8 bytes to segment buffer
void put8(U64 num){
if ((pos+8)>=b.size()) setsize(pos+8);
b[pos++]=(num>>56)&0xff;
b[pos++]=(num>>48)&0xff;
b[pos++]=(num>>40)&0xff;
b[pos++]=(num>>32)&0xff;
b[pos++]=(num>>24)&0xff;
b[pos++]=(num>>16)&0xff;
b[pos++]=(num>>8)&0xff;
b[pos++]=num&0xff;
}
void put4(U32 num){
if ((pos+4)>=b.size()) setsize(pos+4);
b[pos++]=(num>>24)&0xff;
b[pos++]=(num>>16)&0xff;
b[pos++]=(num>>8)&0xff;
b[pos++]=num&0xff;
}
void put1(U8 num){
if (pos>=b.size()) setsize(pos+1);
b[pos++]=num;
}
int size() const {
return b.size();
}
};
// Global context
U8 level=1; // Compression level 0 no compression
// level 1 compression
// level 2 tune
int defaultType;
Segment segment; //for file segments type size info(if not -1)
int streamCount;
FILE **filestreams;
#ifdef FXTUNE
bool doFullOpt=false;
int maxfull=0;
#endif
bool doBounds=false;
bool doBoundsRun=false;
bool doDebugInfo=false;
bool doVerbose=false;
// Contain all global data usable between models
struct BlockData {
int y; // Last bit, 0 or 1, set by encoder
int c0; // Last 0-7 bits of the partial byte with a leading 1 bit (1-255)
U32 c4; // Last 4 whole bytes, packed. Last byte is bits 0-7.
int bpos; // bits in c0 (0 to 7)
int blpos; // Relative position in block
int filetype;
int finfo;
int bposshift;
int c0shift_bpos;
int cmBitState;
struct Inputs{
int ncount=0; // mixer input count
short *n,*ptr; // input array
int size;
unsigned int This(){
return size_t(this);
}
void add(int p) {
assert(p>-2048 && p<2048);
assert(ncount>=0 && ncount<=size);
n[ncount++]=p;
}
void Init(int m){
alloc1(n,m+64,ptr,64);
size=m;
}
void Free(){
if (size)
free(ptr);
}
};
Inputs mxInputs[256]; // array of inputs
int cInputs;
void Init(){
y=0, c0=1, c4=0,bpos=0,blpos=0,filetype=defaultType,finfo=-1,bposshift=0,c0shift_bpos=0,cInputs=-1,cmBitState=0;
}
};
// ilog(x) = round(log2(x) * 16), 0 <= x < 256
class Ilog {
U8 t[256];
public:
int operator()(U16 x) const {return t[x];}
Ilog();
} ilog;
// Compute lookup table by numerical integration of 1/x
Ilog::Ilog() {
U32 x=14155776;
for (int i=2; i<257; ++i) {
x+=774541002/(i*2-1); // numerator is 2^29/ln 2
t[i-1]=x>>24;
}
}
// State table
// State table:
// nex(state, 0) = next state if bit y is 0, 0 <= state < 256
// nex(state, 1) = next state if bit y is 1
// nex(state, 2) = number of zeros in bit history represented by state
// nex(state, 3) = number of ones represented
//
// States represent a bit history within some context.
// State 0 is the starting state (no bits seen).
// States 1-30 represent all possible sequences of 1-4 bits.
// States 31-252 represent a pair of counts, (n0,n1), the number
// of 0 and 1 bits respectively. If n0+n1 < 16 then there are
// two states for each pair, depending on if a 0 or 1 was the last
// bit seen.
// If n0 and n1 are too large, then there is no state to represent this
// pair, so another state with about the same ratio of n0/n1 is substituted.
// Also, when a bit is observed and the count of the opposite bit is large,
// then part of this count is discarded to favor newer data over old.
struct StateTable {
int mdc;
enum {B=5, N=64}; // sizes of b, t
int b[6]; // x -> max y, y -> max x
// x,y -> state number, number of states
U8 t[N][N][2];
U8 ns[1024]; // state*4 -> next state if 0, if 1, n0, n1
U8 nn01[256];
int next(int state, int sel) {return ns[state*4+sel];}
int num_states(int x, int y) {
if (x<y) return num_states(y, x);
if (x<0 || y<0 || x>=N || y>=N || y>=B || x>=b[y]) return 0;
return 1+(y>0 && x+y<b[5]);
}
// New value of count x if the opposite bit is observed
void discount(int& x) {
int y=0;
if (x>2){
for (int i=1;i<mdc;i++) y+=x>=i;
x=y;
}
}
// compute next x,y (0 to N) given input b (0 or 1)
void next_state(int& x, int& y, int b) {
if (x<y)
next_state(y, x, 1-b);
else {
if (b) {
++y;
discount(x);
}
else {
++x;
discount(y);
}
while (!t[x][y][1]) {
if (y<2 && x) --x;
else if(y){
x=(x*(y-1)+(y/2))/y;
--y;
}
}
}
}
// Initialize next state table ns[state*4] -> next if 0, next if 1, x, y
void generate() {
memset(ns, 0, sizeof(ns));
memset(nn01, 0, sizeof(nn01));
memset(t, 0, sizeof(t));
// Assign states
int state=0;
for (int i=0; i<256; ++i) {
for (int y=0; y<=i; ++y) {
int x=i-y;
int n=num_states(x, y);
if (n) {
assert(x<64);
assert(y<64);
t[x][y][0]=state;
t[x][y][1]=n;
state+=n;
}
}
}
// Print/generate next state table
state=0;
for (int i=0; i<N; ++i) {
for (int y=0; y<=i; ++y) {
int x=i-y;
for (int k=0; k<t[x][y][1]; ++k) {
int x0=x, y0=y, x1=x, y1=y; // next x,y for input 0,1
int ns0=0, ns1=0;
next_state(x0, y0, 0);
next_state(x1, y1, 1);
ns[state*4]=ns0=t[x0][y0][0];
ns[state*4+1]=ns1=t[x1][y1][0]+(t[x1][y1][1]>1);
ns[state*4+2]=x;
ns[state*4+3]=y;
if (t[x][y][1]==0 || t[x0][y0][1]==0 || t[x1][y1][1]==0) return;
assert(state>=0 && state<256);
assert(t[x][y][1]>0);
assert(t[x][y][0]<=state);
assert(t[x][y][0]+t[x][y][1]>state);
assert(t[x][y][1]<=6);
assert(t[x0][y0][1]>0);
assert(t[x1][y1][1]>0);
assert(ns0-t[x0][y0][0]<t[x0][y0][1]);
assert(ns0-t[x0][y0][0]>=0);
assert(ns1-t[x1][y1][0]<t[x1][y1][1]);
assert(ns1-t[x1][y1][0]>=0);
++state;
if (state>255) return;
}
}
}
}
// Initialize next state table ns[state*4] -> next if 0, next if 1, n0, n1
void Init(int s0,int s1,int s2,int s3,int s4,int s5,int s6) {
b[0]=s0;b[1]=s1;b[2]=s2;b[3]=s3;b[4]=s4;b[5]=s5;mdc=s6;
generate();
for (int i=0;i<256;i++) {
int n0=-!next(i,2);
int n1=-!next(i,3);
int r=0;
if ((n1-n0)==1) r=2;
if ((n1-n0)==-1) r=1;
nn01[i]=r;
}
}
};
///////////////////////////// Squash //////////////////////////////
short sqt[4095];
int squashc(int d ) {
if (d < -2047)return 1;
if (d > 2047)return 4095;
float p = 1.0f / (1.0f + exp(-d / 256.0));
p *= 4096.0;
U32 pi = (U32)round(p);
if (pi > 4095)pi = 4095;
if (pi < 1)pi = 1;
return pi;
}
inline int squash(int d) {
if (d < -2047)return 1;
if (d > 2047)return 4095;
return sqt[d + 2047];
}
//////////////////////////// Stretch ///////////////////////////////
short strt[4096];
int stretchc(int p) {
assert(p >= 0 && p <= 4095);
if (p == 0)p = 1;
float f = p / 4096.0f;
float d = log(f / (1.0f - f)) * 256.0f;
int di = (int)round(d);
if (di > 2047)di = 2047;
if (di < -2047)di = -2047;
return di;
}
inline short stretch(int p) {
return strt[p];
}
#if !defined(__GNUC__)
#if (2 == _M_IX86_FP) // 2 if /arch:SSE2 was used.
# define __SSE2__
#elif (1 == _M_IX86_FP) // 1 if /arch:SSE was used.
# define __SSE__
#endif
#endif /* __GNUC__ */
#if defined(__AVX2__)
#include <immintrin.h>
#define OPTIMIZE "AVX2-"
#elif defined(__SSE4_1__)
#include<smmintrin.h>
#elif defined(__SSSE3__)
#include<tmmintrin.h>
#elif defined(__SSE2__)
#include <emmintrin.h>
#define OPTIMIZE "SSE2-"
#elif defined(__SSE__)
#include <xmmintrin.h>
#define OPTIMIZE "SSE-"
#endif
/**
* Vector product a*b of n signed words, returning signed integer scaled down by 8 bits.
* n is rounded up to a multiple of 8.
*/
/**
* Train n neural network weights w[n] on inputs t[n] and err.
* w[i] += ((t[i]*2*err)+(1<<16))>>17 bounded to +- 32K.
* n is rounded up to a multiple of 8.
*/
//static void train (const short* const t, short* const w, int n, const int e);
#if defined(__MMX__)
typedef __m128i XMM;
#endif
struct COMPONENT{
U8 id;
U8 idx;
U8 flags;
bool enabled;
};
// APM1
// APM1 maps a probability and a context into a new probability
// that bit y will next be 1. After each guess it updates
// its state to improve future guesses. Methods:
//
// APM1 a(N) creates with N contexts, uses 66*N bytes memory.
// a.p(pr, cx, rate=7) returned adjusted probability in context cx (0 to
// N-1). rate determines the learning rate (smaller = faster, default 7).
// Probabilities are scaled 12 bits (0-4095).
struct APM1 {
int index; // last p, context
U16* t; // [N][33]: p, context -> p
int mask;
int rate,cxt;
int p1; // pr select index
unsigned int This(){
return size_t(this);
}
void Init(int n,int r,int d){
index=0, mask=(n-1),rate=(r),cxt=(0),p1=(d);
assert(ispowerof2(n));
alloc(t,n*33);
for (int i=0; i<n; ++i)
for (int j=0; j<33; ++j)
t[i*33+j] = i==0 ? squash((j-16)*128)*16 : t[j];
}
void Free(){
free(t);
}
void set(int c){
cxt=c;
}
int __attribute__ ((noinline)) p(int pr,int y) {
assert(pr>=0 && pr<4096 && rate>0 && rate<32);
pr=stretch(pr);
int g=(y<<16)+(y<<rate)-y-y;
t[index] += (g-t[index]) >> rate;
t[index+1] += (g-t[index+1]) >> rate;
const int w=pr&127; // interpolation weight (33 points)
index=((pr+2048)>>7)+(cxt&mask)*33;
return (t[index]*(128-w)+t[index+1]*w) >> 11;
}
};
// Mixer
// Mixer m(N, M, S=1, w=0) combines models using M neural networks with
// N inputs each, of which up to S may be selected. If S > 1 then
// the outputs of these neural networks are combined using another
// neural network (with parameters S, 1, 1). If S = 1 then the
// output is direct. The weights are initially w (+-32K).
// It is used as follows:
// m.update() trains the network where the expected output is the
// last bit (in the global variable y).
// m.add(stretch(p)) inputs prediction from one of N models. The
// prediction should be positive to predict a 1 bit, negative for 0,
// nominally +-256 to +-2K. The maximum allowed value is +-32K but
// using such large values may cause overflow if N is large.
// m.set(cxt, range) selects cxt as one of 'range' neural networks to
// use. 0 <= cxt < range. Should be called up to S times such
// that the total of the ranges is <= M.
// m.p() returns the output prediction that the next bit is 1 as a
// 12 bit number (0 to 4095).
struct Mixer1 {
int N, M; // max inputs, max contexts, max context sets
short*tx; // N inputs from add()
short* wx ; // N*M weights
short *ptr;
int cxt; // S contexts
int pr; // last result (scaled 12 bits)
int shift1;
int elim;
int uperr;
int err;
unsigned int This(){
return size_t(this);
}
#if defined(__AVX2__)
int dot_product (const short* const t, const short* const w, int n) {
assert(n == ((n + 15) & -16));
__m256i sum = _mm256_setzero_si256 ();
while ((n -= 16) >= 0) { // Each loop sums 16 products
__m256i tmp = _mm256_madd_epi16 (*(__m256i *) &t[n], *(__m256i *) &w[n]); // t[n] * w[n] + t[n+1] * w[n+1]
tmp = _mm256_srai_epi32 (tmp, 8); // (t[n] * w[n] + t[n+1] * w[n+1]) >> 8
sum = _mm256_add_epi32 (sum, tmp); // sum += (t[n] * w[n] + t[n+1] * w[n+1]) >> 8
}
sum =_mm256_hadd_epi32(sum,_mm256_setzero_si256 ()); //add [1]=[1]+[2], [2]=[3]+[4], [3]=0, [4]=0, [5]=[5]+[6], [6]=[7]+[8], [7]=0, [8]=0
sum =_mm256_hadd_epi32(sum,_mm256_setzero_si256 ()); //add [1]=[1]+[2], [2]=0, [3]=0, [4]=0, [5]=[5]+[6], [6]=0, [7]=0, [8]=0
__m128i lo = _mm256_extractf128_si256(sum, 0);
__m128i hi = _mm256_extractf128_si256(sum, 1);
__m128i newsum = _mm_add_epi32(lo, hi); //sum last two
return _mm_cvtsi128_si32(newsum);
}
void train (const short* const t, short* const w, int n, const int e) {
assert(n == ((n + 15) & -16));
if (e) {
const __m256i one = _mm256_set1_epi16 (1);
const __m256i err = _mm256_set1_epi16 (short(e));
while ((n -= 16) >= 0) { // Each iteration adjusts 16 weights
__m256i tmp = _mm256_adds_epi16 (*(__m256i *) &t[n], *(__m256i *) &t[n]); // t[n] * 2
tmp = _mm256_mulhi_epi16 (tmp, err); // (t[n] * 2 * err) >> 16
tmp = _mm256_adds_epi16 (tmp, one); // ((t[n] * 2 * err) >> 16) + 1
tmp = _mm256_srai_epi16 (tmp, 1); // (((t[n] * 2 * err) >> 16) + 1) >> 1
tmp = _mm256_adds_epi16 (tmp, *(__m256i *) &w[n]); // ((((t[n] * 2 * err) >> 16) + 1) >> 1) + w[n]
*(__m256i *) &w[n] = tmp; // save the new eight weights, bounded to +- 32K
}
}
}
#elif defined(__SSE2__) || defined(__SSSE3__)
int dot_product (const short* const t, const short* const w, int n) {
assert(n == ((n + 15) & -16));
XMM sum = _mm_setzero_si128 ();
while ((n -= 8) >= 0) { // Each loop sums eight products
XMM tmp = _mm_madd_epi16 (*(XMM *) &t[n], *(XMM *) &w[n]); // t[n] * w[n] + t[n+1] * w[n+1]
tmp = _mm_srai_epi32 (tmp, 8); // (t[n] * w[n] + t[n+1] * w[n+1]) >> 8
sum = _mm_add_epi32 (sum, tmp); // sum += (t[n] * w[n] + t[n+1] * w[n+1]) >> 8
}
#if defined(__SSSE3__)
sum=_mm_hadd_epi32 (sum,sum);
sum=_mm_hadd_epi32 (sum,sum);
#else
sum = _mm_add_epi32(sum, _mm_srli_si128 (sum, 8));
sum = _mm_add_epi32(sum, _mm_srli_si128 (sum, 4));
#endif
return _mm_cvtsi128_si32 (sum); // ... and scale back to integer
}
void train (const short* const t, short* const w, int n, const int e) {
assert(n == ((n + 15) & -16));
if (e) {
const XMM one = _mm_set1_epi16 (1);
const XMM err = _mm_set1_epi16 (short(e));
while ((n -= 8) >= 0) { // Each iteration adjusts eight weights
XMM tmp = _mm_adds_epi16 (*(XMM *) &t[n], *(XMM *) &t[n]); // t[n] * 2
tmp = _mm_mulhi_epi16 (tmp, err); // (t[n] * 2 * err) >> 16
tmp = _mm_adds_epi16 (tmp, one); // ((t[n] * 2 * err) >> 16) + 1
tmp = _mm_srai_epi16 (tmp, 1); // (((t[n] * 2 * err) >> 16) + 1) >> 1
tmp = _mm_adds_epi16 (tmp, *(XMM *) &w[n]); // ((((t[n] * 2 * err) >> 16) + 1) >> 1) + w[n]
*(XMM *) &w[n] = tmp; // save the new eight weights, bounded to +- 32K
}
}
}
#elif defined(__SSE__)
int dot_product (const short* const t, const short* const w, int n) {
assert(n == ((n + 15) & -16));
__m64 sum = _mm_setzero_si64 ();
while ((n -= 8) >= 0) { // Each loop sums eight products
__m64 tmp = _mm_madd_pi16 (*(__m64 *) &t[n], *(__m64 *) &w[n]); // t[n] * w[n] + t[n+1] * w[n+1]
tmp = _mm_srai_pi32 (tmp, 8); // (t[n] * w[n] + t[n+1] * w[n+1]) >> 8
sum = _mm_add_pi32 (sum, tmp); // sum += (t[n] * w[n] + t[n+1] * w[n+1]) >> 8
tmp = _mm_madd_pi16 (*(__m64 *) &t[n + 4], *(__m64 *) &w[n + 4]); // t[n+4] * w[n+4] + t[n+5] * w[n+5]
tmp = _mm_srai_pi32 (tmp, 8); // (t[n+4] * w[n+4] + t[n+5] * w[n+5]) >> 8
sum = _mm_add_pi32 (sum, tmp); // sum += (t[n+4] * w[n+4] + t[n+5] * w[n+5]) >> 8
}
sum = _mm_add_pi32 (sum, _mm_srli_si64 (sum, 32)); // Add eight sums together ...
const int retval = _mm_cvtsi64_si32 (sum); // ... and scale back to integer
_mm_empty(); // Empty the multimedia state
return retval;
}
void train (const short* const t, short* const w, int n, const int e) {
assert(n == ((n + 15) & -16));
if (e) {
const __m64 one = _mm_set1_pi16 (1);
const __m64 err = _mm_set1_pi16 (short(e));
while ((n -= 8) >= 0) { // Each iteration adjusts eight weights
__m64 tmp = _mm_adds_pi16 (*(__m64 *) &t[n], *(__m64 *) &t[n]); // t[n] * 2
tmp = _mm_mulhi_pi16 (tmp, err); // (t[n] * 2 * err) >> 16
tmp = _mm_adds_pi16 (tmp, one); // ((t[n] * 2 * err) >> 16) + 1
tmp = _mm_srai_pi16 (tmp, 1); // (((t[n] * 2 * err) >> 16) + 1) >> 1
tmp = _mm_adds_pi16 (tmp, *(__m64 *) &w[n]); // ((((t[n] * 2 * err) >> 16) + 1) >> 1) + w[n]
*(__m64 *) &w[n] = tmp; // save the new four weights, bounded to +- 32K
tmp = _mm_adds_pi16 (*(__m64 *) &t[n + 4], *(__m64 *) &t[n + 4]); // t[n+4] * 2
tmp = _mm_mulhi_pi16 (tmp, err); // (t[n+4] * 2 * err) >> 16
tmp = _mm_adds_pi16 (tmp, one); // ((t[n+4] * 2 * err) >> 16) + 1
tmp = _mm_srai_pi16 (tmp, 1); // (((t[n+4] * 2 * err) >> 16) + 1) >> 1
tmp = _mm_adds_pi16 (tmp, *(__m64 *) &w[n + 4]); // ((((t[n+4] * 2 * err) >> 16) + 1) >> 1) + w[n]
*(__m64 *) &w[n + 4] = tmp; // save the new four weights, bounded to +- 32K
}
_mm_empty(); // Empty the multimedia state
}
}
#else
// dot_product returns dot product t*w of n elements. n is rounded
// up to a multiple of 8. Result is scaled down by 8 bits.
int dot_product(short *t, short *w, int n) {
int sum=0;
n=(n+15)&-16;
for (int i=0; i<n; i+=2)
sum+=(t[i]*w[i]+t[i+1]*w[i+1]) >> 8;
return sum;
}
// Train neural network weights w[n] given inputs t[n] and err.
// w[i] += t[i]*err, i=0..n-1. t, w, err are signed 16 bits (+- 32K).
// err is scaled 16 bits (representing +- 1/2). w[i] is clamped to +- 32K
// and rounded. n is rounded up to a multiple of 8.
void train(short *t, short *w, int n, int err) {
n=(n+15)&-16;
for (int i=0; i<n; ++i) {
int wt=w[i]+(((t[i]*err*2>>16)+1)>>1);
if (wt<-32768) wt=-32768;
if (wt>32767) wt=32767;
w[i]=wt;
}
}
#endif
// Adjust weights to minimize coding cost of last prediction
void update(int y) {
err=((y<<12)-pr)*uperr/4;
if (err>32767)
err=32767;
if (err<-32768)
err=-32768;
if(err>=-elim && err<=elim) err=0;
train(&tx[0], &wx[cxt*N], N, err);
}
// predict next bit
int p() {
assert(cxt<M);
int dp=dot_product(&tx[0], &wx[cxt*N], N)*shift1>>11;
return pr=squash(dp);
}
void setTxWx(int n,short* mn){
N=n;
alloc1(wx,(N*M)+32,ptr,32);
tx=mn;
}
void set(int c){
assert(cxt>=0 && c<M);
cxt=c;
}
void Init(int m, U32 s,U32 e,U32 ue){
M=m, cxt=0, shift1=s,elim=e,uperr=ue;err=0;
pr=2048; //initial p=0.5
}
void Free(){
// print N weights averaged over context
if (doDebugInfo==true){
printf("Mixer(%d,%d): ", N, M);
for (int i=0; i<N; ++i) {
int w=0;
for (int j=0; j<M; ++j)
w+=wx[j*N+i];
printf("%d ", w/M);
}
printf("\n");
}
free(ptr);
}
};
// StateMap
// A StateMap maps a context to a probability. Methods:
//
// Statemap sm(n) creates a StateMap with n contexts using 4*n bytes memory.
// sm.p(y, cx, limit) converts state cx (0..n-1) to a probability (0..4095).
// that the next y=1, updating the previous prediction with y (0..1).
// limit (1..1023, default 1023) is the maximum count for computing a
// prediction. Larger values are better for stationary sources.
static int dt[1024]; // i -> 16K/(i+i+3)
struct StateMapContext {
BlockData *x;
int N; // Number of contexts
int cxt; // Context of last prediction
U32 *t; // cxt -> prediction in high 22 bits, count in low 10 bits
int pr;
int mask;
int limit;
U8 *nn;
unsigned int This(){
return size_t(this);
}
int next(int i, int y){
return nn[ y + 4 *i];
}
void Init( BlockData *bd,int n, int lim,U8 *nn1){
nn=nn1;
x=bd;
N=n, cxt=0, pr=2048, mask=n-1,limit=lim;
assert(ispowerof2(n));
alloc(t,n);
assert(limit>0 && limit<1024);
if (N==256){
for (int i=0; i<N; ++i){
U32 n0=next(i, 2)*3+1;
U32 n1=next(i, 3)*3+1;
t[i]=(((n1<<20) / (n0+n1)) << 12);
}
}else{
for (int i=0; i<N; ++i)
t[i]=1<<31;
}
}
void Free(){
free(t);
}
inline void update() {
U32 *p=&t[cxt], p0=p[0];
int n=p0&1023, pr1=p0>>12; // count, prediction
p0+=(n<limit);
p0+=(((((x->y<<20)-pr1)))*dt[n]+512)&0xfffffc00;
p[0]=p0;
}
// update bit y (0..1), predict next bit in context cx
void set(int c) {
assert(cxt>=0 && cxt<N);
update();
pr=t[cxt=(c&mask)]>>20;
}
int p(){
return stretch(pr);
}
void print(){
for (int i=0;i<N;i++){
printf("%d\n",t[i]>>17);
}
printf("\n");
}
};
struct StateMap {
int N; // Number of contexts
int cxt; // Context of last prediction
U32 *t; // cxt -> prediction in high 22 bits, count in low 10 bits
int pr;
const U8 *nn;
int next(int i, int y){
return nn[ y + 4 *i];
}
void __attribute__ ((noinline)) Init(int n, int lim, U8 *nn1){