-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsQR.js
executable file
·10042 lines (9990 loc) · 248 KB
/
jsQR.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
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["jsQR"] = factory();
else
root["jsQR"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 3);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BitMatrix = /** @class */ (function () {
function BitMatrix(data, width) {
this.width = width;
this.height = data.length / width;
this.data = data;
}
BitMatrix.createEmpty = function (width, height) {
return new BitMatrix(new Uint8ClampedArray(width * height), width);
};
BitMatrix.prototype.get = function (x, y) {
if (x < 0 || x >= this.width || y < 0 || y >= this.height) {
return false;
}
return !!this.data[y * this.width + x];
};
BitMatrix.prototype.set = function (x, y, v) {
this.data[y * this.width + x] = v ? 1 : 0;
};
BitMatrix.prototype.setRegion = function (left, top, width, height, v) {
for (var y = top; y < top + height; y++) {
for (var x = left; x < left + width; x++) {
this.set(x, y, !!v);
}
}
};
return BitMatrix;
}());
exports.BitMatrix = BitMatrix;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var GenericGFPoly_1 = __webpack_require__(2);
function addOrSubtractGF(a, b) {
return a ^ b; // tslint:disable-line:no-bitwise
}
exports.addOrSubtractGF = addOrSubtractGF;
var GenericGF = /** @class */ (function () {
function GenericGF(primitive, size, genBase) {
this.primitive = primitive;
this.size = size;
this.generatorBase = genBase;
this.expTable = new Array(this.size);
this.logTable = new Array(this.size);
var x = 1;
for (var i = 0; i < this.size; i++) {
this.expTable[i] = x;
x = x * 2;
if (x >= this.size) {
x = (x ^ this.primitive) & (this.size - 1); // tslint:disable-line:no-bitwise
}
}
for (var i = 0; i < this.size - 1; i++) {
this.logTable[this.expTable[i]] = i;
}
this.zero = new GenericGFPoly_1.default(this, Uint8ClampedArray.from([0]));
this.one = new GenericGFPoly_1.default(this, Uint8ClampedArray.from([1]));
}
GenericGF.prototype.multiply = function (a, b) {
if (a === 0 || b === 0) {
return 0;
}
return this.expTable[(this.logTable[a] + this.logTable[b]) % (this.size - 1)];
};
GenericGF.prototype.inverse = function (a) {
if (a === 0) {
throw new Error("Can't invert 0");
}
return this.expTable[this.size - this.logTable[a] - 1];
};
GenericGF.prototype.buildMonomial = function (degree, coefficient) {
if (degree < 0) {
throw new Error("Invalid monomial degree less than 0");
}
if (coefficient === 0) {
return this.zero;
}
var coefficients = new Uint8ClampedArray(degree + 1);
coefficients[0] = coefficient;
return new GenericGFPoly_1.default(this, coefficients);
};
GenericGF.prototype.log = function (a) {
if (a === 0) {
throw new Error("Can't take log(0)");
}
return this.logTable[a];
};
GenericGF.prototype.exp = function (a) {
return this.expTable[a];
};
return GenericGF;
}());
exports.default = GenericGF;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var GenericGF_1 = __webpack_require__(1);
var GenericGFPoly = /** @class */ (function () {
function GenericGFPoly(field, coefficients) {
if (coefficients.length === 0) {
throw new Error("No coefficients.");
}
this.field = field;
var coefficientsLength = coefficients.length;
if (coefficientsLength > 1 && coefficients[0] === 0) {
// Leading term must be non-zero for anything except the constant polynomial "0"
var firstNonZero = 1;
while (firstNonZero < coefficientsLength && coefficients[firstNonZero] === 0) {
firstNonZero++;
}
if (firstNonZero === coefficientsLength) {
this.coefficients = field.zero.coefficients;
}
else {
this.coefficients = new Uint8ClampedArray(coefficientsLength - firstNonZero);
for (var i = 0; i < this.coefficients.length; i++) {
this.coefficients[i] = coefficients[firstNonZero + i];
}
}
}
else {
this.coefficients = coefficients;
}
}
GenericGFPoly.prototype.degree = function () {
return this.coefficients.length - 1;
};
GenericGFPoly.prototype.isZero = function () {
return this.coefficients[0] === 0;
};
GenericGFPoly.prototype.getCoefficient = function (degree) {
return this.coefficients[this.coefficients.length - 1 - degree];
};
GenericGFPoly.prototype.addOrSubtract = function (other) {
if (this.isZero()) {
return other;
}
if (other.isZero()) {
return this;
}
var smallerCoefficients = this.coefficients;
var largerCoefficients = other.coefficients;
if (smallerCoefficients.length > largerCoefficients.length) {
_a = [largerCoefficients, smallerCoefficients], smallerCoefficients = _a[0], largerCoefficients = _a[1];
}
var sumDiff = new Uint8ClampedArray(largerCoefficients.length);
var lengthDiff = largerCoefficients.length - smallerCoefficients.length;
for (var i = 0; i < lengthDiff; i++) {
sumDiff[i] = largerCoefficients[i];
}
for (var i = lengthDiff; i < largerCoefficients.length; i++) {
sumDiff[i] = GenericGF_1.addOrSubtractGF(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
}
return new GenericGFPoly(this.field, sumDiff);
var _a;
};
GenericGFPoly.prototype.multiply = function (scalar) {
if (scalar === 0) {
return this.field.zero;
}
if (scalar === 1) {
return this;
}
var size = this.coefficients.length;
var product = new Uint8ClampedArray(size);
for (var i = 0; i < size; i++) {
product[i] = this.field.multiply(this.coefficients[i], scalar);
}
return new GenericGFPoly(this.field, product);
};
GenericGFPoly.prototype.multiplyPoly = function (other) {
if (this.isZero() || other.isZero()) {
return this.field.zero;
}
var aCoefficients = this.coefficients;
var aLength = aCoefficients.length;
var bCoefficients = other.coefficients;
var bLength = bCoefficients.length;
var product = new Uint8ClampedArray(aLength + bLength - 1);
for (var i = 0; i < aLength; i++) {
var aCoeff = aCoefficients[i];
for (var j = 0; j < bLength; j++) {
product[i + j] = GenericGF_1.addOrSubtractGF(product[i + j], this.field.multiply(aCoeff, bCoefficients[j]));
}
}
return new GenericGFPoly(this.field, product);
};
GenericGFPoly.prototype.multiplyByMonomial = function (degree, coefficient) {
if (degree < 0) {
throw new Error("Invalid degree less than 0");
}
if (coefficient === 0) {
return this.field.zero;
}
var size = this.coefficients.length;
var product = new Uint8ClampedArray(size + degree);
for (var i = 0; i < size; i++) {
product[i] = this.field.multiply(this.coefficients[i], coefficient);
}
return new GenericGFPoly(this.field, product);
};
GenericGFPoly.prototype.evaluateAt = function (a) {
var result = 0;
if (a === 0) {
// Just return the x^0 coefficient
return this.getCoefficient(0);
}
var size = this.coefficients.length;
if (a === 1) {
// Just the sum of the coefficients
this.coefficients.forEach(function (coefficient) {
result = GenericGF_1.addOrSubtractGF(result, coefficient);
});
return result;
}
result = this.coefficients[0];
for (var i = 1; i < size; i++) {
result = GenericGF_1.addOrSubtractGF(this.field.multiply(a, result), this.coefficients[i]);
}
return result;
};
return GenericGFPoly;
}());
exports.default = GenericGFPoly;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var binarizer_1 = __webpack_require__(4);
var decoder_1 = __webpack_require__(5);
var extractor_1 = __webpack_require__(11);
var locator_1 = __webpack_require__(12);
function scan(matrix) {
var location = locator_1.locate(matrix);
if (!location) {
return null;
}
var extracted = extractor_1.extract(matrix, location);
var decoded = decoder_1.decode(extracted.matrix);
if (!decoded) {
return null;
}
return {
binaryData: decoded.bytes,
data: decoded.text,
chunks: decoded.chunks,
location: {
topRightCorner: extracted.mappingFunction(location.dimension, 0),
topLeftCorner: extracted.mappingFunction(0, 0),
bottomRightCorner: extracted.mappingFunction(location.dimension, location.dimension),
bottomLeftCorner: extracted.mappingFunction(0, location.dimension),
topRightFinderPattern: location.topRight,
topLeftFinderPattern: location.topLeft,
bottomLeftFinderPattern: location.bottomLeft,
bottomRightAlignmentPattern: location.alignmentPattern,
},
};
}
var defaultOptions = {
inversionAttempts: "attemptBoth",
};
function jsQR(data, width, height, providedOptions) {
if (providedOptions === void 0) { providedOptions = {}; }
var options = defaultOptions;
Object.keys(options || {}).forEach(function (opt) {
options[opt] = providedOptions[opt] || options[opt];
});
var shouldInvert = options.inversionAttempts === "attemptBoth" || options.inversionAttempts === "invertFirst";
var tryInvertedFirst = options.inversionAttempts === "onlyInvert" || options.inversionAttempts === "invertFirst";
var _a = binarizer_1.binarize(data, width, height, shouldInvert), binarized = _a.binarized, inverted = _a.inverted;
var result = scan(tryInvertedFirst ? inverted : binarized);
if (!result && (options.inversionAttempts === "attemptBoth" || options.inversionAttempts === "invertFirst")) {
result = scan(tryInvertedFirst ? binarized : inverted);
}
return result;
}
jsQR.default = jsQR;
exports.default = jsQR;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BitMatrix_1 = __webpack_require__(0);
var REGION_SIZE = 8;
var MIN_DYNAMIC_RANGE = 24;
function numBetween(value, min, max) {
return value < min ? min : value > max ? max : value;
}
// Like BitMatrix but accepts arbitry Uint8 values
var Matrix = /** @class */ (function () {
function Matrix(width, height) {
this.width = width;
this.data = new Uint8ClampedArray(width * height);
}
Matrix.prototype.get = function (x, y) {
return this.data[y * this.width + x];
};
Matrix.prototype.set = function (x, y, value) {
this.data[y * this.width + x] = value;
};
return Matrix;
}());
function binarize(data, width, height, returnInverted) {
if (data.length !== width * height * 4) {
throw new Error("Malformed data passed to binarizer.");
}
// Convert image to greyscale
var greyscalePixels = new Matrix(width, height);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
var r = data[((y * width + x) * 4) + 0];
var g = data[((y * width + x) * 4) + 1];
var b = data[((y * width + x) * 4) + 2];
greyscalePixels.set(x, y, 0.2126 * r + 0.7152 * g + 0.0722 * b);
}
}
var horizontalRegionCount = Math.ceil(width / REGION_SIZE);
var verticalRegionCount = Math.ceil(height / REGION_SIZE);
var blackPoints = new Matrix(horizontalRegionCount, verticalRegionCount);
for (var verticalRegion = 0; verticalRegion < verticalRegionCount; verticalRegion++) {
for (var hortizontalRegion = 0; hortizontalRegion < horizontalRegionCount; hortizontalRegion++) {
var sum = 0;
var min = Infinity;
var max = 0;
for (var y = 0; y < REGION_SIZE; y++) {
for (var x = 0; x < REGION_SIZE; x++) {
var pixelLumosity = greyscalePixels.get(hortizontalRegion * REGION_SIZE + x, verticalRegion * REGION_SIZE + y);
sum += pixelLumosity;
min = Math.min(min, pixelLumosity);
max = Math.max(max, pixelLumosity);
}
}
var average = sum / (Math.pow(REGION_SIZE, 2));
if (max - min <= MIN_DYNAMIC_RANGE) {
// If variation within the block is low, assume this is a block with only light or only
// dark pixels. In that case we do not want to use the average, as it would divide this
// low contrast area into black and white pixels, essentially creating data out of noise.
//
// Default the blackpoint for these blocks to be half the min - effectively white them out
average = min / 2;
if (verticalRegion > 0 && hortizontalRegion > 0) {
// Correct the "white background" assumption for blocks that have neighbors by comparing
// the pixels in this block to the previously calculated black points. This is based on
// the fact that dark barcode symbology is always surrounded by some amount of light
// background for which reasonable black point estimates were made. The bp estimated at
// the boundaries is used for the interior.
// The (min < bp) is arbitrary but works better than other heuristics that were tried.
var averageNeighborBlackPoint = (blackPoints.get(hortizontalRegion, verticalRegion - 1) +
(2 * blackPoints.get(hortizontalRegion - 1, verticalRegion)) +
blackPoints.get(hortizontalRegion - 1, verticalRegion - 1)) / 4;
if (min < averageNeighborBlackPoint) {
average = averageNeighborBlackPoint;
}
}
}
blackPoints.set(hortizontalRegion, verticalRegion, average);
}
}
var binarized = BitMatrix_1.BitMatrix.createEmpty(width, height);
var inverted = null;
if (returnInverted) {
inverted = BitMatrix_1.BitMatrix.createEmpty(width, height);
}
for (var verticalRegion = 0; verticalRegion < verticalRegionCount; verticalRegion++) {
for (var hortizontalRegion = 0; hortizontalRegion < horizontalRegionCount; hortizontalRegion++) {
var left = numBetween(hortizontalRegion, 2, horizontalRegionCount - 3);
var top_1 = numBetween(verticalRegion, 2, verticalRegionCount - 3);
var sum = 0;
for (var xRegion = -2; xRegion <= 2; xRegion++) {
for (var yRegion = -2; yRegion <= 2; yRegion++) {
sum += blackPoints.get(left + xRegion, top_1 + yRegion);
}
}
var threshold = sum / 25;
for (var xRegion = 0; xRegion < REGION_SIZE; xRegion++) {
for (var yRegion = 0; yRegion < REGION_SIZE; yRegion++) {
var x = hortizontalRegion * REGION_SIZE + xRegion;
var y = verticalRegion * REGION_SIZE + yRegion;
var lum = greyscalePixels.get(x, y);
binarized.set(x, y, lum <= threshold);
if (returnInverted) {
inverted.set(x, y, !(lum <= threshold));
}
}
}
}
}
if (returnInverted) {
return { binarized: binarized, inverted: inverted };
}
return { binarized: binarized };
}
exports.binarize = binarize;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BitMatrix_1 = __webpack_require__(0);
var decodeData_1 = __webpack_require__(6);
var reedsolomon_1 = __webpack_require__(9);
var version_1 = __webpack_require__(10);
// tslint:disable:no-bitwise
function numBitsDiffering(x, y) {
var z = x ^ y;
var bitCount = 0;
while (z) {
bitCount++;
z &= z - 1;
}
return bitCount;
}
function pushBit(bit, byte) {
return (byte << 1) | bit;
}
// tslint:enable:no-bitwise
var FORMAT_INFO_TABLE = [
{ bits: 0x5412, formatInfo: { errorCorrectionLevel: 1, dataMask: 0 } },
{ bits: 0x5125, formatInfo: { errorCorrectionLevel: 1, dataMask: 1 } },
{ bits: 0x5E7C, formatInfo: { errorCorrectionLevel: 1, dataMask: 2 } },
{ bits: 0x5B4B, formatInfo: { errorCorrectionLevel: 1, dataMask: 3 } },
{ bits: 0x45F9, formatInfo: { errorCorrectionLevel: 1, dataMask: 4 } },
{ bits: 0x40CE, formatInfo: { errorCorrectionLevel: 1, dataMask: 5 } },
{ bits: 0x4F97, formatInfo: { errorCorrectionLevel: 1, dataMask: 6 } },
{ bits: 0x4AA0, formatInfo: { errorCorrectionLevel: 1, dataMask: 7 } },
{ bits: 0x77C4, formatInfo: { errorCorrectionLevel: 0, dataMask: 0 } },
{ bits: 0x72F3, formatInfo: { errorCorrectionLevel: 0, dataMask: 1 } },
{ bits: 0x7DAA, formatInfo: { errorCorrectionLevel: 0, dataMask: 2 } },
{ bits: 0x789D, formatInfo: { errorCorrectionLevel: 0, dataMask: 3 } },
{ bits: 0x662F, formatInfo: { errorCorrectionLevel: 0, dataMask: 4 } },
{ bits: 0x6318, formatInfo: { errorCorrectionLevel: 0, dataMask: 5 } },
{ bits: 0x6C41, formatInfo: { errorCorrectionLevel: 0, dataMask: 6 } },
{ bits: 0x6976, formatInfo: { errorCorrectionLevel: 0, dataMask: 7 } },
{ bits: 0x1689, formatInfo: { errorCorrectionLevel: 3, dataMask: 0 } },
{ bits: 0x13BE, formatInfo: { errorCorrectionLevel: 3, dataMask: 1 } },
{ bits: 0x1CE7, formatInfo: { errorCorrectionLevel: 3, dataMask: 2 } },
{ bits: 0x19D0, formatInfo: { errorCorrectionLevel: 3, dataMask: 3 } },
{ bits: 0x0762, formatInfo: { errorCorrectionLevel: 3, dataMask: 4 } },
{ bits: 0x0255, formatInfo: { errorCorrectionLevel: 3, dataMask: 5 } },
{ bits: 0x0D0C, formatInfo: { errorCorrectionLevel: 3, dataMask: 6 } },
{ bits: 0x083B, formatInfo: { errorCorrectionLevel: 3, dataMask: 7 } },
{ bits: 0x355F, formatInfo: { errorCorrectionLevel: 2, dataMask: 0 } },
{ bits: 0x3068, formatInfo: { errorCorrectionLevel: 2, dataMask: 1 } },
{ bits: 0x3F31, formatInfo: { errorCorrectionLevel: 2, dataMask: 2 } },
{ bits: 0x3A06, formatInfo: { errorCorrectionLevel: 2, dataMask: 3 } },
{ bits: 0x24B4, formatInfo: { errorCorrectionLevel: 2, dataMask: 4 } },
{ bits: 0x2183, formatInfo: { errorCorrectionLevel: 2, dataMask: 5 } },
{ bits: 0x2EDA, formatInfo: { errorCorrectionLevel: 2, dataMask: 6 } },
{ bits: 0x2BED, formatInfo: { errorCorrectionLevel: 2, dataMask: 7 } },
];
var DATA_MASKS = [
function (p) { return ((p.y + p.x) % 2) === 0; },
function (p) { return (p.y % 2) === 0; },
function (p) { return p.x % 3 === 0; },
function (p) { return (p.y + p.x) % 3 === 0; },
function (p) { return (Math.floor(p.y / 2) + Math.floor(p.x / 3)) % 2 === 0; },
function (p) { return ((p.x * p.y) % 2) + ((p.x * p.y) % 3) === 0; },
function (p) { return ((((p.y * p.x) % 2) + (p.y * p.x) % 3) % 2) === 0; },
function (p) { return ((((p.y + p.x) % 2) + (p.y * p.x) % 3) % 2) === 0; },
];
function buildFunctionPatternMask(version) {
var dimension = 17 + 4 * version.versionNumber;
var matrix = BitMatrix_1.BitMatrix.createEmpty(dimension, dimension);
matrix.setRegion(0, 0, 9, 9, true); // Top left finder pattern + separator + format
matrix.setRegion(dimension - 8, 0, 8, 9, true); // Top right finder pattern + separator + format
matrix.setRegion(0, dimension - 8, 9, 8, true); // Bottom left finder pattern + separator + format
// Alignment patterns
for (var _i = 0, _a = version.alignmentPatternCenters; _i < _a.length; _i++) {
var x = _a[_i];
for (var _b = 0, _c = version.alignmentPatternCenters; _b < _c.length; _b++) {
var y = _c[_b];
if (!(x === 6 && y === 6 || x === 6 && y === dimension - 7 || x === dimension - 7 && y === 6)) {
matrix.setRegion(x - 2, y - 2, 5, 5, true);
}
}
}
matrix.setRegion(6, 9, 1, dimension - 17, true); // Vertical timing pattern
matrix.setRegion(9, 6, dimension - 17, 1, true); // Horizontal timing pattern
if (version.versionNumber > 6) {
matrix.setRegion(dimension - 11, 0, 3, 6, true); // Version info, top right
matrix.setRegion(0, dimension - 11, 6, 3, true); // Version info, bottom left
}
return matrix;
}
function readCodewords(matrix, version, formatInfo) {
var dataMask = DATA_MASKS[formatInfo.dataMask];
var dimension = matrix.height;
var functionPatternMask = buildFunctionPatternMask(version);
var codewords = [];
var currentByte = 0;
var bitsRead = 0;
// Read columns in pairs, from right to left
var readingUp = true;
for (var columnIndex = dimension - 1; columnIndex > 0; columnIndex -= 2) {
if (columnIndex === 6) {
columnIndex--;
}
for (var i = 0; i < dimension; i++) {
var y = readingUp ? dimension - 1 - i : i;
for (var columnOffset = 0; columnOffset < 2; columnOffset++) {
var x = columnIndex - columnOffset;
if (!functionPatternMask.get(x, y)) {
bitsRead++;
var bit = matrix.get(x, y);
if (dataMask({ y: y, x: x })) {
bit = !bit;
}
currentByte = pushBit(bit, currentByte);
if (bitsRead === 8) {
codewords.push(currentByte);
bitsRead = 0;
currentByte = 0;
}
}
}
}
readingUp = !readingUp;
}
return codewords;
}
function readVersion(matrix) {
var dimension = matrix.height;
var provisionalVersion = Math.floor((dimension - 17) / 4);
if (provisionalVersion <= 6) {
return version_1.VERSIONS[provisionalVersion - 1];
}
var topRightVersionBits = 0;
for (var y = 5; y >= 0; y--) {
for (var x = dimension - 9; x >= dimension - 11; x--) {
topRightVersionBits = pushBit(matrix.get(x, y), topRightVersionBits);
}
}
var bottomLeftVersionBits = 0;
for (var x = 5; x >= 0; x--) {
for (var y = dimension - 9; y >= dimension - 11; y--) {
bottomLeftVersionBits = pushBit(matrix.get(x, y), bottomLeftVersionBits);
}
}
var bestDifference = Infinity;
var bestVersion;
for (var _i = 0, VERSIONS_1 = version_1.VERSIONS; _i < VERSIONS_1.length; _i++) {
var version = VERSIONS_1[_i];
if (version.infoBits === topRightVersionBits || version.infoBits === bottomLeftVersionBits) {
return version;
}
var difference = numBitsDiffering(topRightVersionBits, version.infoBits);
if (difference < bestDifference) {
bestVersion = version;
bestDifference = difference;
}
difference = numBitsDiffering(bottomLeftVersionBits, version.infoBits);
if (difference < bestDifference) {
bestVersion = version;
bestDifference = difference;
}
}
// We can tolerate up to 3 bits of error since no two version info codewords will
// differ in less than 8 bits.
if (bestDifference <= 3) {
return bestVersion;
}
}
function readFormatInformation(matrix) {
var topLeftFormatInfoBits = 0;
for (var x = 0; x <= 8; x++) {
if (x !== 6) {
topLeftFormatInfoBits = pushBit(matrix.get(x, 8), topLeftFormatInfoBits);
}
}
for (var y = 7; y >= 0; y--) {
if (y !== 6) {
topLeftFormatInfoBits = pushBit(matrix.get(8, y), topLeftFormatInfoBits);
}
}
var dimension = matrix.height;
var topRightBottomRightFormatInfoBits = 0;
for (var y = dimension - 1; y >= dimension - 7; y--) {
topRightBottomRightFormatInfoBits = pushBit(matrix.get(8, y), topRightBottomRightFormatInfoBits);
}
for (var x = dimension - 8; x < dimension; x++) {
topRightBottomRightFormatInfoBits = pushBit(matrix.get(x, 8), topRightBottomRightFormatInfoBits);
}
var bestDifference = Infinity;
var bestFormatInfo = null;
for (var _i = 0, FORMAT_INFO_TABLE_1 = FORMAT_INFO_TABLE; _i < FORMAT_INFO_TABLE_1.length; _i++) {
var _a = FORMAT_INFO_TABLE_1[_i], bits = _a.bits, formatInfo = _a.formatInfo;
if (bits === topLeftFormatInfoBits || bits === topRightBottomRightFormatInfoBits) {
return formatInfo;
}
var difference = numBitsDiffering(topLeftFormatInfoBits, bits);
if (difference < bestDifference) {
bestFormatInfo = formatInfo;
bestDifference = difference;
}
if (topLeftFormatInfoBits !== topRightBottomRightFormatInfoBits) {
difference = numBitsDiffering(topRightBottomRightFormatInfoBits, bits);
if (difference < bestDifference) {
bestFormatInfo = formatInfo;
bestDifference = difference;
}
}
}
// Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits differing means we found a match
if (bestDifference <= 3) {
return bestFormatInfo;
}
return null;
}
function getDataBlocks(codewords, version, ecLevel) {
var ecInfo = version.errorCorrectionLevels[ecLevel];
var dataBlocks = [];
var totalCodewords = 0;
ecInfo.ecBlocks.forEach(function (block) {
for (var i = 0; i < block.numBlocks; i++) {
dataBlocks.push({ numDataCodewords: block.dataCodewordsPerBlock, codewords: [] });
totalCodewords += block.dataCodewordsPerBlock + ecInfo.ecCodewordsPerBlock;
}
});
// In some cases the QR code will be malformed enough that we pull off more or less than we should.
// If we pull off less there's nothing we can do.
// If we pull off more we can safely truncate
if (codewords.length < totalCodewords) {
return null;
}
codewords = codewords.slice(0, totalCodewords);
var shortBlockSize = ecInfo.ecBlocks[0].dataCodewordsPerBlock;
// Pull codewords to fill the blocks up to the minimum size
for (var i = 0; i < shortBlockSize; i++) {
for (var _i = 0, dataBlocks_1 = dataBlocks; _i < dataBlocks_1.length; _i++) {
var dataBlock = dataBlocks_1[_i];
dataBlock.codewords.push(codewords.shift());
}
}
// If there are any large blocks, pull codewords to fill the last element of those
if (ecInfo.ecBlocks.length > 1) {
var smallBlockCount = ecInfo.ecBlocks[0].numBlocks;
var largeBlockCount = ecInfo.ecBlocks[1].numBlocks;
for (var i = 0; i < largeBlockCount; i++) {
dataBlocks[smallBlockCount + i].codewords.push(codewords.shift());
}
}
// Add the rest of the codewords to the blocks. These are the error correction codewords.
while (codewords.length > 0) {
for (var _a = 0, dataBlocks_2 = dataBlocks; _a < dataBlocks_2.length; _a++) {
var dataBlock = dataBlocks_2[_a];
dataBlock.codewords.push(codewords.shift());
}
}
return dataBlocks;
}
function decodeMatrix(matrix) {
var version = readVersion(matrix);
if (!version) {
return null;
}
var formatInfo = readFormatInformation(matrix);
if (!formatInfo) {
return null;
}
var codewords = readCodewords(matrix, version, formatInfo);
var dataBlocks = getDataBlocks(codewords, version, formatInfo.errorCorrectionLevel);
if (!dataBlocks) {
return null;
}
// Count total number of data bytes
var totalBytes = dataBlocks.reduce(function (a, b) { return a + b.numDataCodewords; }, 0);
var resultBytes = new Uint8ClampedArray(totalBytes);
var resultIndex = 0;
for (var _i = 0, dataBlocks_3 = dataBlocks; _i < dataBlocks_3.length; _i++) {
var dataBlock = dataBlocks_3[_i];
var correctedBytes = reedsolomon_1.decode(dataBlock.codewords, dataBlock.codewords.length - dataBlock.numDataCodewords);
if (!correctedBytes) {
return null;
}
for (var i = 0; i < dataBlock.numDataCodewords; i++) {
resultBytes[resultIndex++] = correctedBytes[i];
}
}
try {
return decodeData_1.decode(resultBytes, version.versionNumber);
}
catch (_a) {
return null;
}
}
function decode(matrix) {
if (matrix == null) {
return null;
}
var result = decodeMatrix(matrix);
if (result) {
return result;
}
// Decoding didn't work, try mirroring the QR across the topLeft -> bottomRight line.
for (var x = 0; x < matrix.width; x++) {
for (var y = x + 1; y < matrix.height; y++) {
if (matrix.get(x, y) !== matrix.get(y, x)) {
matrix.set(x, y, !matrix.get(x, y));
matrix.set(y, x, !matrix.get(y, x));
}
}
}
return decodeMatrix(matrix);
}
exports.decode = decode;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// tslint:disable:no-bitwise
var BitStream_1 = __webpack_require__(7);
var shiftJISTable_1 = __webpack_require__(8);
var Mode;
(function (Mode) {
Mode["Numeric"] = "numeric";
Mode["Alphanumeric"] = "alphanumeric";
Mode["Byte"] = "byte";
Mode["Kanji"] = "kanji";
Mode["ECI"] = "eci";
})(Mode = exports.Mode || (exports.Mode = {}));
var ModeByte;
(function (ModeByte) {
ModeByte[ModeByte["Terminator"] = 0] = "Terminator";
ModeByte[ModeByte["Numeric"] = 1] = "Numeric";
ModeByte[ModeByte["Alphanumeric"] = 2] = "Alphanumeric";
ModeByte[ModeByte["Byte"] = 4] = "Byte";
ModeByte[ModeByte["Kanji"] = 8] = "Kanji";
ModeByte[ModeByte["ECI"] = 7] = "ECI";
// StructuredAppend = 0x3,
// FNC1FirstPosition = 0x5,
// FNC1SecondPosition = 0x9,
})(ModeByte || (ModeByte = {}));
function decodeNumeric(stream, size) {
var bytes = [];
var text = "";
var characterCountSize = [10, 12, 14][size];
var length = stream.readBits(characterCountSize);
// Read digits in groups of 3
while (length >= 3) {
var num = stream.readBits(10);
if (num >= 1000) {
throw new Error("Invalid numeric value above 999");
}
var a = Math.floor(num / 100);
var b = Math.floor(num / 10) % 10;
var c = num % 10;
bytes.push(48 + a, 48 + b, 48 + c);
text += a.toString() + b.toString() + c.toString();
length -= 3;
}
// If the number of digits aren't a multiple of 3, the remaining digits are special cased.
if (length === 2) {
var num = stream.readBits(7);
if (num >= 100) {
throw new Error("Invalid numeric value above 99");
}
var a = Math.floor(num / 10);
var b = num % 10;
bytes.push(48 + a, 48 + b);
text += a.toString() + b.toString();
}
else if (length === 1) {
var num = stream.readBits(4);
if (num >= 10) {
throw new Error("Invalid numeric value above 9");
}
bytes.push(48 + num);
text += num.toString();
}
return { bytes: bytes, text: text };
}
var AlphanumericCharacterCodes = [
"0", "1", "2", "3", "4", "5", "6", "7", "8",
"9", "A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q",
"R", "S", "T", "U", "V", "W", "X", "Y", "Z",
" ", "$", "%", "*", "+", "-", ".", "/", ":",
];
function decodeAlphanumeric(stream, size) {
var bytes = [];
var text = "";
var characterCountSize = [9, 11, 13][size];
var length = stream.readBits(characterCountSize);
while (length >= 2) {
var v = stream.readBits(11);
var a = Math.floor(v / 45);
var b = v % 45;
bytes.push(AlphanumericCharacterCodes[a].charCodeAt(0), AlphanumericCharacterCodes[b].charCodeAt(0));
text += AlphanumericCharacterCodes[a] + AlphanumericCharacterCodes[b];
length -= 2;
}
if (length === 1) {
var a = stream.readBits(6);
bytes.push(AlphanumericCharacterCodes[a].charCodeAt(0));
text += AlphanumericCharacterCodes[a];
}
return { bytes: bytes, text: text };
}
function decodeByte(stream, size) {
var bytes = [];
var text = "";
var characterCountSize = [8, 16, 16][size];
var length = stream.readBits(characterCountSize);
for (var i = 0; i < length; i++) {
var b = stream.readBits(8);
bytes.push(b);
}
try {
text += decodeURIComponent(bytes.map(function (b) { return "%" + ("0" + b.toString(16)).substr(-2); }).join(""));
}
catch (_a) {
// failed to decode
}
return { bytes: bytes, text: text };
}
function decodeKanji(stream, size) {
var bytes = [];
var text = "";
var characterCountSize = [8, 10, 12][size];
var length = stream.readBits(characterCountSize);
for (var i = 0; i < length; i++) {
var k = stream.readBits(13);
var c = (Math.floor(k / 0xC0) << 8) | (k % 0xC0);
if (c < 0x1F00) {
c += 0x8140;
}
else {
c += 0xC140;
}
bytes.push(c >> 8, c & 0xFF);
text += String.fromCharCode(shiftJISTable_1.shiftJISTable[c]);
}
return { bytes: bytes, text: text };
}
function decode(data, version) {
var stream = new BitStream_1.BitStream(data);
// There are 3 'sizes' based on the version. 1-9 is small (0), 10-26 is medium (1) and 27-40 is large (2).
var size = version <= 9 ? 0 : version <= 26 ? 1 : 2;
var result = {
text: "",
bytes: [],
chunks: [],
};
while (stream.available() >= 4) {
var mode = stream.readBits(4);
if (mode === ModeByte.Terminator) {
return result;
}
else if (mode === ModeByte.ECI) {
if (stream.readBits(1) === 0) {
result.chunks.push({
type: Mode.ECI,
assignmentNumber: stream.readBits(7),
});
}
else if (stream.readBits(1) === 0) {
result.chunks.push({
type: Mode.ECI,
assignmentNumber: stream.readBits(14),
});
}
else if (stream.readBits(1) === 0) {
result.chunks.push({
type: Mode.ECI,
assignmentNumber: stream.readBits(21),
});
}
else {
// ECI data seems corrupted
result.chunks.push({
type: Mode.ECI,
assignmentNumber: -1,
});
}
}
else if (mode === ModeByte.Numeric) {
var numericResult = decodeNumeric(stream, size);
result.text += numericResult.text;
(_a = result.bytes).push.apply(_a, numericResult.bytes);
result.chunks.push({
type: Mode.Numeric,
text: numericResult.text,
});
}
else if (mode === ModeByte.Alphanumeric) {
var alphanumericResult = decodeAlphanumeric(stream, size);
result.text += alphanumericResult.text;
(_b = result.bytes).push.apply(_b, alphanumericResult.bytes);