-
Notifications
You must be signed in to change notification settings - Fork 4
/
encoder.js
4031 lines (3361 loc) · 105 KB
/
encoder.js
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
"use strict";
/**
* JBB - Javascript Binary Bundles - Binary Encoder
* Copyright (C) 2015 Ioannis Charalampidis <[email protected]>
*
* 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.
*
* @author Ioannis Charalampidis / https://github.com/wavesoft
*/
var bst = require("binary-search-tree");
var fs = require("fs");
var util = require("util");
var MockBrowser = require("mock-browser");
var colors = require("colors");
var mime = require("mime");
var deepEqual = require('deep-equal');
var BinaryStream = require("./lib/BinaryStream");
var Errors = require("./lib/Errors");
var EncodeProfile = require('./lib/EncodeProfile');
const FLOAT32_POS = 3.40282347e+38; // largest positive number in float32
const FLOAT32_NEG = -3.40282346e+38; // largest negative number in float32
const FLOAT32_SMALL = 1.175494350e-38; // smallest number in float32
/* Note that all these values are exclusive, for positive test (ex v < UING8_MAX) */
const UINT8_MAX = 256; // largest positive unsigned integer on 8-bit
const UINT16_MAX = 65536; // largest positive unsigned integer on 16-bit
const UINT32_MAX = 4294967296; // largest positive unsigned integer on 32-bit
const INT8_MIN = -129; // largest negative signed integer on 8-bit
const INT8_MAX = 128; // largest positive signed integer on 8-bit
const INT16_MIN = -32769; // largest negative signed integer on 16-bit
const INT16_MAX = 32768; // largest positive signed integer on 16-bit
const INT32_MIN = -2147483649; // largest negative signed integer on 16-bit
const INT32_MAX = 2147483648; // largest positive signed integer on 16-bit
/* Version of binary bundle */
const VERSION = (( 1 /* Major */ )<<8)|( 2 /* Minor */ );
/*
Known Limitations
* A TypedArray cannot have more than 4,294,967,296 items
* There cannot be more than 65,536 string literals in the bundle (dictionary keys, import/export labels)
*/
/**
* If this constant is true, the packing functions will do sanity checks,
* which might increase the build time.
*/
const SAFE = 1;
/**
* Fake DOM environment when from node
*/
if (typeof(document) === "undefined") {
// Prepare a fake browser
var MockBrowser = require('mock-browser').mocks.MockBrowser;
var mock = new MockBrowser();
// Fake 'self', 'document' and 'window'
global.document = mock.getDocument(),
global.self = MockBrowser.createWindow(),
global.window = global.self;
// Fake 'XMLHttpRequest' (shall not be used)
global.XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
// Fake 'DOMParser'
global.DOMParser = require('xmldom').DOMParser;
}
// Get references to DOM element classes
var DOMElement = window.Element;
var ImageElement = document.createElement('img').constructor;
var ScriptElement = document.createElement('script').constructor;
var AudioElement = document.createElement('audio').constructor;
var VideoElement = document.createElement('video').constructor;
/**
* Binary Search Tree Helpers
*/
var BinarySearchTree = bst.BinarySearchTree,
objectBstComparison = function(a,b) {
var tA, tB, i;
for (i=0; i<a.length; ++i) {
tA = typeof a[i]; tB = typeof b[i];
if (tA === tB) {
if ((tA === 'number') || (tA === 'string') || (tA === 'boolean')) {
if (a[i] < b[i]) return -1;
if (a[i] > b[i]) return 1;
if (a[i] !== b[i]) return 1;
/*if (a[i] == b[i]) continue;*/
} else {
if (a[i] === b[i]) continue;
return 1;
}
} else {
return 1;
}
}
return 0;
},
objectBstEquals = function(a,b) {
for (var i=0; i<a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
};
/**
* Numerical types
*/
var NUMTYPE = {
// For protocol use
UINT8: 0, INT8: 1,
UINT16: 2, INT16: 3,
UINT32: 4, INT32: 5,
FLOAT32: 6, FLOAT64: 7,
// For internal use
NUMERIC: 8, UNKNOWN: 9, NAN: 10
};
/**
* Numerical length types
*/
var NUMTYPE_LN = {
UINT16: 0,
UINT32 : 1
};
var NUMTYPE_LEN = {
UINT8: 0,
UINT16: 1,
UINT32: 2,
FLOAT64: 3
};
/**
* Log flags
*/
var LOG = {
PRM: 0x0001, // Primitive messages
ARR: 0x0002, // Array messages
CHU: 0x0004, // Array Chunk
STR: 0x0008, // String buffer
IREF: 0x0010, // Internal reference
XREF: 0x0020, // External reference
OBJ: 0x0040, // Object messages
EMB: 0x0080, // Embedded resource
PLO: 0x0100, // Simple objects
BULK: 0x0200, // Bulk-encoded objects
SUMM: 0x2000, // Log summary
WRT: 0x4000, // Debug writes
PDBG: 0x8000, // Protocol debug messages
};
/**
* Log prefix chunks
*/
var LOG_PREFIX_STR = {
0x0001 : 'PRM',
0x0002 : 'ARR',
0x0004 : 'CHU',
0x0008 : 'STR',
0x0010 : 'IRF',
0x0020 : 'XRF',
0x0040 : 'OBJ',
0x0080 : 'EMB',
0x0100 : 'PLO',
0x0200 : 'BLK',
0x2000 : 'SUM',
0x8000 : 'DBG',
};
/**
* Numerical type classes
*/
var NUMTYPE_CLASS = [
Uint8Array,
Int8Array,
Uint16Array,
Int16Array,
Uint32Array,
Int32Array,
Float32Array,
Float64Array
];
/**
* Downscaling numtype conversion table from/to
*/
var NUMTYPE_DOWNSCALE = {
FROM: [
NUMTYPE.UINT16,
NUMTYPE.INT16 ,
NUMTYPE.UINT32,
NUMTYPE.INT32 ,
NUMTYPE.UINT32,
NUMTYPE.INT32 ,
NUMTYPE.FLOAT32,
NUMTYPE.FLOAT32,
NUMTYPE.FLOAT32,
NUMTYPE.FLOAT32,
NUMTYPE.FLOAT64,
NUMTYPE.FLOAT64,
NUMTYPE.FLOAT64,
NUMTYPE.FLOAT64,
NUMTYPE.FLOAT64,
],
TO: [
NUMTYPE.UINT8 ,
NUMTYPE.INT8 ,
NUMTYPE.UINT8 ,
NUMTYPE.INT8 ,
NUMTYPE.UINT16 ,
NUMTYPE.INT16 ,
NUMTYPE.UINT8 ,
NUMTYPE.INT8 ,
NUMTYPE.UINT16 ,
NUMTYPE.INT16 ,
NUMTYPE.UINT8 ,
NUMTYPE.INT8 ,
NUMTYPE.UINT16 ,
NUMTYPE.INT16 ,
NUMTYPE.FLOAT32
]
};
/**
* Delta-Encoding for integers
*/
var NUMTYPE_DELTA_INT = {
FROM: [
NUMTYPE.UINT16,
NUMTYPE.INT16 ,
NUMTYPE.UINT32,
NUMTYPE.INT32 ,
NUMTYPE.UINT32,
NUMTYPE.INT32 ,
],
TO: [
NUMTYPE.INT8 ,
NUMTYPE.INT8 ,
NUMTYPE.INT8 ,
NUMTYPE.INT8 ,
NUMTYPE.INT16,
NUMTYPE.INT16,
]
};
/**
* Delta-Encoding for floats
*/
var NUMTYPE_DELTA_FLOAT = {
FROM: [
NUMTYPE.FLOAT32,
NUMTYPE.FLOAT32,
NUMTYPE.FLOAT64,
NUMTYPE.FLOAT64,
],
TO: [
NUMTYPE.INT8 ,
NUMTYPE.INT16,
NUMTYPE.INT8 ,
NUMTYPE.INT16,
]
};
/**
* Delta encoding scale factor
*/
var DELTASCALE = {
S_001 : 1, // Divide by 100 the value
S_1 : 2, // Keep value as-is
S_R : 3, // Multiply by 127 on 8-bit and by 32768 on 16-bit
S_R00 : 4, // Multiply by 12700 on 8-bit and by 3276800 on 16-bit
};
/**
* Control Op-Codes
*/
var CTRL_OP = {
ATTRIB : 0x80, // Attribute
EXPORT : 0xF8, // External Export
EMBED : 0xF9, // Embedded resource
};
/**
* Primitive Op-Codes
*/
var PRIM_OP = {
ARRAY: 0x00, // Array
OBJECT: 0x80, // Object / Plain Object [ID=0]
BUFFER: 0xC0, // Buffer
REF: 0xE0, // Internal Reference
NUMBER: 0xF0, // Number
SIMPLE: 0xF8, // Simple
SIMPLE_EX: 0xFC, // Extended simple primitive
IMPORT: 0xFE, // External Import
};
/**
* Object Op-Codes
*/
var OBJ_OP = {
KNOWN_5: 0x00, // Known object (5-bit)
KNOWN_12: 0x20, // Known object (12-bit)
PLAIN_LOOKUP: 0x30, // A plain object from lookup table
PLAIN_NEW: 0x3F, // A new plain object that will define a lookup entry
PRIMITIVE: 0x38, // Primitive object
PRIM_DATE: 0x38
};
/**
* Primitive object op-codes
*/
var OBJ_PRIM = {
DATE: 0x00, // A DATE primitive
};
/**
* Array Op-Codes
*/
var ARR_OP = {
NUM_DWS: 0x00, // Downscaled Numeric Type
NUM_DELTA_INT: 0x20, // Delta-Encoded Integer Array
NUM_DELTA_FLOAT: 0x30, // Delta-Encoded Float Array
NUM_REPEATED: 0x40, // Repeated Numeric Value
NUM_RAW: 0x50, // Raw Numeric Value
NUM_SHORT: 0x60, // Short Numeric Value
PRIM_REPEATED: 0x68, // Repeated Primitive Value
PRIM_RAW: 0x6A, // Raw Primitive Array
PRIM_BULK_PLAIN: 0x6E, // Bulk Array of Plain Objects
PRIM_SHORT: 0x6F, // Short Primitive Array
PRIM_CHUNK: 0x78, // Chunked Primitive ARray
PRIM_BULK_KNOWN: 0x7C, // Bulk Array of Known Objects
EMPTY: 0x7E, // Empty Array
PRIM_CHUNK_END: 0x7F, // End of primary chunk
};
/**
* Array chunk types
*/
var ARR_CHUNK = {
PRIMITIVES: 1, // Two or more primitives
REPEAT: 2, // Repeated of the same primitive
NUMERIC: 3, // A numeric TypedArray
BULK_PLAIN: 4, // A bulk of many plain objects
BULK_KNOWN: 5, // A bulk of known objects
};
var _ARR_CHUNK = [
undefined,
'PRIMITIVES',
'REPEAT',
'NUMERIC',
'BULK_PLAIN',
'BULK_KNOWN'
];
/**
* Simple primitives
*/
var PRIM_SIMPLE = {
UNDEFINED: 0,
NULL: 1,
FALSE: 2,
TRUE: 3
};
/**
* Extended simple primitives
*/
var PRIM_SIMPLE_EX = {
NAN: 0,
};
/**
* Buffer primitive MIME Types
*/
var PRIM_BUFFER_TYPE = {
STRING_LATIN: 0,
STRING_UTF8: 1,
BUF_IMAGE: 2,
BUF_SCRIPT: 3,
BUF_AUDIO: 4,
BUF_VIDEO: 5,
RESOURCE: 7,
};
/**
* BULK_KNOWN Array encoding operator codes
*/
var PRIM_BULK_KNOWN_OP = {
LREF_7: 0x00, // Local reference up to 7bit
LREF_11:0xF0, // Local reference up to 11bit
LREF_16:0xFE, // Local reference up to 16bit
IREF: 0xE0, // Internal reference up to 20bit
XREF: 0xFF, // External reference
DEFINE: 0x80, // Definition up to 5bit
REPEAT: 0xC0, // Repeat up to 4bit
};
/**
* String representation of numerical type for debug messages
*/
var _NUMTYPE = [
'UINT8',
'INT8',
'UINT16',
'INT16',
'UINT32',
'INT32',
'FLOAT32',
'FLOAT64',
'NUMERIC',
'UNKNOWN',
'NaN',
];
var _NUMTYPE_DOWNSCALE_DWS = [
'UINT16 -> UINT8',
'INT16 -> INT8',
'UINT32 -> UINT8',
'INT32 -> INT8',
'UINT32 -> UINT16',
'INT32 -> INT16',
'FLOAT32 -> UINT8',
'FLOAT32 -> INT8',
'FLOAT32 -> UINT16',
'FLOAT32 -> INT16',
'FLOAT64 -> UINT8',
'FLOAT64 -> INT8',
'FLOAT64 -> UINT16',
'FLOAT64 -> INT16',
'FLOAT64 -> FLOAT32'
];
var _NUMTYPE_DOWNSCALE_DELTA_INT = [
'UINT16 -> INT8',
'INT16 -> INT8',
'UINT32 -> INT8',
'INT32 -> INT8',
'UINT32 -> INT16',
'INT32 -> INT16'
];
var _NUMTYPE_DOWNSCALE_DELTA_FLOAT = [
'FLOAT32 -> INT8',
'FLOAT32 -> INT16',
'FLOAT64 -> INT8',
'FLOAT64 -> INT16 '
];
/**
* Pack accelerators
*/
var packBuffer = new ArrayBuffer(8),
packViewU8 = new Uint8Array(packBuffer),
packViewI8 = new Int8Array(packBuffer),
packViewU16 = new Uint16Array(packBuffer),
packViewI16 = new Int16Array(packBuffer),
packViewU32 = new Uint32Array(packBuffer),
packViewI32 = new Int32Array(packBuffer),
packViewF32 = new Float32Array(packBuffer),
packViewF64 = new Float64Array(packBuffer),
pack1b = function( num, signed ) {
var n = new Buffer(1);
if (SAFE) { if (signed) {
if (num < INT8_MIN)
throw new Errors.PackError('Packing number bigger than 8-bits ('+num+')!');
else if (num > INT8_MAX)
throw new Errors.PackError('Packing number bigger than 8-bits ('+num+')!');
} else {
if (num < 0) throw new Errors.PackError('Packing negative number on unsigned 8-bit ('+num+')!');
else if (num > UINT8_MAX)
throw new Errors.PackError('Packing number bigger than 8-bits ('+num+')!');
} }
if (signed) packViewI8[0] = num;
else packViewU8[0] = num;
n[0] = packViewU8[0];
return n;
},
pack2b = function( num, signed ) {
var n = new Buffer(2);
if (SAFE) { if (signed) {
if (num < INT16_MIN)
throw new Errors.PackError('Packing integer bigger than 16-bits ('+num+')!');
else if (num > INT16_MAX)
throw new Errors.PackError('Packing integer bigger than 16-bits ('+num+')!');
} else {
if (num < 0)
throw new Errors.PackError('Packing negative integer on unsigned 16-bit ('+num+')!');
else if (num > UINT16_MAX)
throw new Errors.PackError('Packing integer bigger than 16-bits ('+num+')!');
} }
if (signed) packViewI16[0] = num;
else packViewU16[0] = num;
for (var i=0; i<2; ++i) n[i]=packViewU8[i];
return n;
},
pack4b = function( num, signed ) {
var n = new Buffer(4);
if (SAFE) { if (signed) {
if (num < INT32_MIN)
throw new Errors.PackError('Packing integer bigger than 32-bits ('+num+')!');
else if (num > INT32_MAX)
throw new Errors.PackError('Packing integer bigger than 32-bits ('+num+')!');
} else {
if (num < 0)
throw new Errors.PackError('Packing negative integer on unsigned 32-bit ('+num+')!');
else if (num > UINT32_MAX)
throw new Errors.PackError('Packing integer bigger than 32-bits ('+num+')!');
} }
if (signed) packViewI32[0] = num;
else packViewU32[0] = num;
for (var i=0; i<4; ++i) n[i]=packViewU8[i];
return n;
},
pack4f = function( num ) {
var n = new Buffer(4);
if (SAFE) { if (num == 0.0) { }
else if ((Math.abs(num) < FLOAT32_SMALL) || (num < FLOAT32_NEG) || (num > FLOAT32_POS))
throw new Errors.PackError('Packing float bigger than 32-bits ('+num+')!');
}
packViewF32[0] = num;
for (var i=0; i<4; ++i) n[i]=packViewU8[i];
return n;
},
pack8f = function( num ) {
var n = new Buffer(8);
if (SAFE) { if (num == 0.0) { }
else if (Math.abs(num) < 1.7E-108)
throw new Errors.PackError('Packing float bigger than 64-bits ('+num+')!');
else if (Math.abs(num) > 1.7E+108)
throw new Errors.PackError('Packing float bigger than 64-bits ('+num+')!');
}
packViewF64[0] = num;
for (var i=0; i<8; ++i) n[i]=packViewU8[i];
return n;
},
packTypedArray = function( arr ) {
return new Buffer(arr.buffer);
},
packByNumType = [
pack1b, function(v) { return pack1b(v, true) },
pack2b, function(v) { return pack2b(v, true) },
pack4b, function(v) { return pack4b(v, true) },
pack4f, pack8f
];
//////////////////////////////////////////////////////////////////
// Analysis and Encoding helper functions
//////////////////////////////////////////////////////////////////
/**
* Get a new unique object ID
*/
var __objectID = 0;
function __newObjectID() {
return '_'+(++__objectID);
}
function fds( v_min, v_max ) {
var d_min = Math.log10(v_min),
d_max = Math.log10(v_max);
}
/**
* Get the scale factor for the specified float-based delta encoding
* using the NUMTYPE_DOWNSCALE and DELTASCALE provided.
*
* @param {int} t - The NUMTYPE_DOWNSCALE used in the encoding
* @param {int} scale - The DELTASCALE used in the encoding
* @return {float} - Return the scale factor
*/
function getFloatDeltaScale(t, scale) {
if (scale === DELTASCALE.S_1)
return 1.0;
else if (scale === DELTASCALE.S_001)
return 0.01;
else {
var multiplier = 1.0;
if (scale === DELTASCALE.S_R00) multiplier = 100.0;
// Check for INT8 target
if ( ((t >= 0) && (t <= 3)) || (t === 6) ) {
return multiplier * INT8_MAX;
} else {
return multiplier * INT16_MAX;
}
}
}
/**
* Check if the specified object is an empty array
*/
function isEmptyArray(v) {
if ((v instanceof Uint8Array) || (v instanceof Int8Array) ||
(v instanceof Uint16Array) || (v instanceof Int16Array) ||
(v instanceof Uint32Array) || (v instanceof Int32Array) ||
(v instanceof Float32Array) || (v instanceof Float64Array) ||
(v instanceof Array) ) {
return (v.length === 0);
}
return false;
}
/**
* Check if the specified type is float
*
* Works also on downscaled types because the last two 'FROM'
* conversions are FLOAT32.
*
* @param {int} t - The NUMTYPE or NUMTYPE_DOWNSCALE type to check
* @returns {boolean} - True if it's a float type (or float source type)
*/
function isFloatType(t) {
return (t >= NUMTYPE.FLOAT32);
}
/**
* Check if the specified number is a subclass of an other
*/
function isNumericSubclass( t, t_min, t_max, of_t ) {
if ((t === NUMTYPE.NAN) || (of_t === NUMTYPE.NAN)) return false;
switch (of_t) { // Parent
case NUMTYPE.UINT8:
switch (t) {
case NUMTYPE.UINT8:
return true;
case NUMTYPE.INT8:
return (t_min > 0);
default:
return false;
}
case NUMTYPE.INT8:
switch (t) {
case NUMTYPE.UINT8:
return (t_max < INT8_MAX);
case NUMTYPE.INT8:
return true;
default:
return false;
}
case NUMTYPE.UINT16:
switch (t) {
case NUMTYPE.UINT8:
case NUMTYPE.UINT16:
return true;
case NUMTYPE.INT8:
case NUMTYPE.INT16:
return (t_min > 0);
default:
return false;
}
case NUMTYPE.INT16:
switch (t) {
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
case NUMTYPE.INT16:
return true;
case NUMTYPE.UINT16:
return (t_max < INT16_MAX);
default:
return false;
}
case NUMTYPE.UINT32:
switch (t) {
case NUMTYPE.UINT8:
case NUMTYPE.UINT16:
case NUMTYPE.UINT32:
return true;
case NUMTYPE.INT8:
case NUMTYPE.INT16:
case NUMTYPE.INT32:
return (t_min > 0);
default:
return false;
}
case NUMTYPE.INT32:
switch (t) {
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
case NUMTYPE.UINT16:
case NUMTYPE.INT16:
case NUMTYPE.INT32:
return true;
case NUMTYPE.UINT32:
return (t_max < INT32_MAX);
default:
return false;
}
case NUMTYPE.FLOAT32:
switch (t) {
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
case NUMTYPE.UINT16:
case NUMTYPE.INT16:
case NUMTYPE.FLOAT32:
return true;
case NUMTYPE.UINT32:
case NUMTYPE.INT32:
return (t_min > FLOAT32_NEG) && (t_max < FLOAT32_POS);
default:
return false;
}
case NUMTYPE.FLOAT64:
return true;
}
return false;
}
/**
* Check if we are mixing floats
*/
function isFloatMixing( a, b ) {
return (
((a < NUMTYPE.FLOAT32 ) && (b >= NUMTYPE.FLOAT32 )) ||
((a >= NUMTYPE.FLOAT32 ) && (b < NUMTYPE.FLOAT32 ))
);
}
/**
* Return the array size in bytes of the specified type
*
* @param {int} t - The NUMTYPE type to check
* @returns {int} - Returns the size in bytes to hold this type
*/
function sizeOfType(t) {
switch (t) {
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
return 1;
case NUMTYPE.UINT16:
case NUMTYPE.INT16:
return 2;
case NUMTYPE.UINT32:
case NUMTYPE.INT32:
case NUMTYPE.FLOAT32:
return 4;
case NUMTYPE.FLOAT64:
return 8;
}
return 255;
}
/**
* Get the numerical type of a typed array
*
* @param {array} v - The TypedArray to check
* @returns {int} - Returns the NUMTYPE type for the specified array or NUMTYPE.UNKNOWN if not a TypedArray
*/
function getTypedArrayType( v ) {
if (v instanceof Float32Array) {
return NUMTYPE.FLOAT32;
} else if (v instanceof Float64Array) {
return NUMTYPE.FLOAT64;
} else if (v instanceof Uint8Array) {
return NUMTYPE.UINT8;
} else if (v instanceof Int8Array) {
return NUMTYPE.INT8;
} else if (v instanceof Uint16Array) {
return NUMTYPE.UINT16;
} else if (v instanceof Int16Array) {
return NUMTYPE.INT16;
} else if (v instanceof Uint32Array) {
return NUMTYPE.UINT32;
} else if (v instanceof Int32Array) {
return NUMTYPE.INT32;
} else if (v instanceof Array) {
// Sneaky but fast way to check if array is 100% numeric
// by testing the first, last and middle elemnet
var a=0,b=v.length-1,c=Math.floor((b-a)/2);
if((typeof v[a] === "number") &&
(typeof v[b] === "number") &&
(typeof v[c] === "number")) {
return NUMTYPE.NUMERIC;
} else {
return NUMTYPE.UNKNOWN;
}
} else {
return NUMTYPE.UNKNOWN;
}
}
/**
* Get the smallest possible numeric type fits this numberic bounds
*
* @param {number} vmin - The minimum number to check
* @param {number} vmax - The maximum number to check
* @param {boolean} is_float - Set to 'true' to assume that the numbers are float
* @return {NUMTYPE} - The numerical type to rerutn
*/
function getNumType( vmin, vmax, is_float ) {
if (typeof vmin !== "number") return NUMTYPE.NAN;
if (typeof vmax !== "number") return NUMTYPE.NAN;
if (isNaN(vmin) || isNaN(vmax)) return NUMTYPE.NAN;
// If float, test only-floats
if (is_float) {
// Try to find smallest value for float32 minimum tests
var smallest;
if (vmin === 0) {
// vmin is 0, which makes vmax positive, so
// test vmax for smallest
smallest = vmax;
} else if (vmax === 0) {
// if vmax is 0, it makes vmin negative, which
// means we should test it's positive version
smallest = -vmax;
} else {
// if vmin is positive, both values are positive
// so get the smallest for small test (vmin)
if (vmin > 0) {
smallest = vmin;
// if vmax is negative, both values are negative
// so get the biggest for small test (vmax)
} else if (vmax < 0) {
smallest = -vmax;
// if vmin is negative and vmax positive, get the
// smallest of their absolute values
} else if ((vmin < 0) && (vmax > 0)) {
smallest = -vmin;
if (vmax < smallest) smallest = vmax;
}
}
// Test if float number fits on 32 or 64 bits
if ((vmin > FLOAT32_NEG) && (vmax < FLOAT32_POS) && (smallest > FLOAT32_SMALL)) {
return NUMTYPE.FLOAT32;
} else {
return NUMTYPE.FLOAT64;
}
}
// If we have a negative value, switch to signed tests
if ((vmax < 0) || (vmin < 0)) {
// Get absolute maximum of bound values
var amax = -vmin;
if (vmax < 0) {
if (-vmax > amax) amax = -vmax;
} else {
if (vmax > amax) amax = vmax;
}
// Test for integer bounds
if (amax < INT8_MAX) {
return NUMTYPE.INT8;
} else if (amax < INT16_MAX) {
return NUMTYPE.INT16;
} else if (amax < INT32_MAX) {
return NUMTYPE.INT32;
} else {
return NUMTYPE.FLOAT64;
}
// Otherwise perform unsigned tests
} else {
// Check for unsigned cases
if (vmax < UINT8_MAX) {
return NUMTYPE.UINT8;
} else if (vmax < UINT16_MAX) {
return NUMTYPE.UINT16;
} else if (vmax < UINT32_MAX) {
return NUMTYPE.UINT32;
} else {
return NUMTYPE.FLOAT64;
}
}
}
/**
* Calculate and return the numerical type and the scale to
* apply to the float values given in order to minimize the error.
*/
function getFloatScale( values, min, max, error ) {
var mid = (min + max) / 2, range = mid - min,
norm_8 = (range / INT8_MAX),
norm_16 = (range / INT16_MAX),
ok_8 = true, ok_16 = true,
er_8 = 0, er_16 = 0,
v, uv, er;
// For the values given, check if 8-bit or 16-bit
// scaling brings smaller error value
for (var i=0, l=values.length; i<l; ++i) {
// Test 8-bit scaling
if (ok_8) {
v = Math.round((values[i] - mid) / norm_8);
uv = v * norm_8 + mid;
er = (uv-v)/v;
if (er > er_8) er_8 = er;
if (er >= error) {
ok_8 = false;
}
}
// Test 16-bit scaling
if (ok_16) {
v = Math.round((values[i] - mid) / norm_16);
uv = v * norm_16 + mid;
er = (uv-v)/v;
if (er > er_16) er_16 = er;
if (er >= error) {
ok_16 = false;
}
}
if (!ok_8 && !ok_16)
return [ 0, NUMTYPE.UNKNOWN ];
}
// Pick most appropriate normalization factor
if (ok_8 && ok_16) {
if (er_8 < er_16) {
return [ norm_8, NUMTYPE.INT8 ];
} else {
return [ norm_16, NUMTYPE.INT16 ];
}
} else if (ok_8) {
return [ norm_8, NUMTYPE.INT8 ];
} else if (ok_16) {
return [ norm_16, NUMTYPE.INT16 ];
} else {
return [ 0, NUMTYPE.UNKNOWN ];
}
}
/**
* Get the possible downscale type based on the specified analysis
*/
function getDownscaleType( n_type, analysis ) {
switch (n_type) {
// Not possible to downscale from 1-byte
case NUMTYPE.UINT8:
case NUMTYPE.INT8:
return NUMTYPE.UNKNOWN;
case NUMTYPE.UINT16:
switch (analysis.type) {
// UINT16 -> (U)INT8 = UINT8
case NUMTYPE.INT8: // Unsigned, so always positive
case NUMTYPE.UINT8:
return NUMTYPE.UINT8;