website view lib/js/qrcode.js @ rev 1344

Resize balinor logo to 120px
author Christophe Lincoln <pankso@slitaz.org>
date Fri Jan 22 23:02:15 2021 +0100 (2021-01-22)
parents
children
line source
1 /* qr.js -- QR code generator in Javascript (revision 2011-01-19)
2 * Written by Kang Seonghoon <public+qrjs@mearie.org>.
3 *
4 * This source code is in the public domain; if your jurisdiction does not
5 * recognize the public domain the terms of Creative Commons CC0 license
6 * apply. In the other words, you can always do what you want.
7 */
9 var QRCode = (function(){
11 /* Quick overview: QR code composed of 2D array of modules (a rectangular
12 * area that conveys one bit of information); some modules are fixed to help
13 * the recognition of the code, and remaining data modules are further divided
14 * into 8-bit code words which are augumented by Reed-Solomon error correcting
15 * codes (ECC). There could be multiple ECCs, in the case the code is so large
16 * that it is helpful to split the raw data into several chunks.
17 *
18 * The number of modules is determined by the code's "version", ranging from 1
19 * (21x21) to 40 (177x177). How many ECC bits are used is determined by the
20 * ECC level (L/M/Q/H). The number and size (and thus the order of generator
21 * polynomial) of ECCs depend to the version and ECC level.
22 */
24 // per-version information (cf. JIS X 0510:2004 pp. 30--36, 71)
25 //
26 // [0]: the degree of generator polynomial by ECC levels
27 // [1]: # of code blocks by ECC levels
28 // [2]: left-top positions of alignment patterns
29 //
30 // the number in this table (in particular, [0]) does not exactly match with
31 // the numbers in the specficiation. see augumenteccs below for the reason.
32 var VERSIONS = [
33 null,
34 [[10, 7,17,13], [ 1, 1, 1, 1], []],
35 [[16,10,28,22], [ 1, 1, 1, 1], [4,16]],
36 [[26,15,22,18], [ 1, 1, 2, 2], [4,20]],
37 [[18,20,16,26], [ 2, 1, 4, 2], [4,24]],
38 [[24,26,22,18], [ 2, 1, 4, 4], [4,28]],
39 [[16,18,28,24], [ 4, 2, 4, 4], [4,32]],
40 [[18,20,26,18], [ 4, 2, 5, 6], [4,20,36]],
41 [[22,24,26,22], [ 4, 2, 6, 6], [4,22,40]],
42 [[22,30,24,20], [ 5, 2, 8, 8], [4,24,44]],
43 [[26,18,28,24], [ 5, 4, 8, 8], [4,26,48]],
44 [[30,20,24,28], [ 5, 4,11, 8], [4,28,52]],
45 [[22,24,28,26], [ 8, 4,11,10], [4,30,56]],
46 [[22,26,22,24], [ 9, 4,16,12], [4,32,60]],
47 [[24,30,24,20], [ 9, 4,16,16], [4,24,44,64]],
48 [[24,22,24,30], [10, 6,18,12], [4,24,46,68]],
49 [[28,24,30,24], [10, 6,16,17], [4,24,48,72]],
50 [[28,28,28,28], [11, 6,19,16], [4,28,52,76]],
51 [[26,30,28,28], [13, 6,21,18], [4,28,54,80]],
52 [[26,28,26,26], [14, 7,25,21], [4,28,56,84]],
53 [[26,28,28,30], [16, 8,25,20], [4,32,60,88]],
54 [[26,28,30,28], [17, 8,25,23], [4,26,48,70,92]],
55 [[28,28,24,30], [17, 9,34,23], [4,24,48,72,96]],
56 [[28,30,30,30], [18, 9,30,25], [4,28,52,76,100]],
57 [[28,30,30,30], [20,10,32,27], [4,26,52,78,104]],
58 [[28,26,30,30], [21,12,35,29], [4,30,56,82,108]],
59 [[28,28,30,28], [23,12,37,34], [4,28,56,84,112]],
60 [[28,30,30,30], [25,12,40,34], [4,32,60,88,116]],
61 [[28,30,30,30], [26,13,42,35], [4,24,48,72,96,120]],
62 [[28,30,30,30], [28,14,45,38], [4,28,52,76,100,124]],
63 [[28,30,30,30], [29,15,48,40], [4,24,50,76,102,128]],
64 [[28,30,30,30], [31,16,51,43], [4,28,54,80,106,132]],
65 [[28,30,30,30], [33,17,54,45], [4,32,58,84,110,136]],
66 [[28,30,30,30], [35,18,57,48], [4,28,56,84,112,140]],
67 [[28,30,30,30], [37,19,60,51], [4,32,60,88,116,144]],
68 [[28,30,30,30], [38,19,63,53], [4,28,52,76,100,124,148]],
69 [[28,30,30,30], [40,20,66,56], [4,22,48,74,100,126,152]],
70 [[28,30,30,30], [43,21,70,59], [4,26,52,78,104,130,156]],
71 [[28,30,30,30], [45,22,74,62], [4,30,56,82,108,134,160]],
72 [[28,30,30,30], [47,24,77,65], [4,24,52,80,108,136,164]],
73 [[28,30,30,30], [49,25,81,68], [4,28,56,84,112,140,168]]];
75 // mode constants (cf. Table 2 in JIS X 0510:2004 p. 16)
76 var MODE_TERMINATOR = 0;
77 var MODE_NUMERIC = 1, MODE_ALPHANUMERIC = 2, MODE_OCTET = 4, MODE_KANJI = 8;
79 // validation regexps
80 var NUMERIC_REGEXP = /^\d*$/;
81 var ALPHANUMERIC_REGEXP = /^[A-Za-z0-9 $%*+\-./:]*$/;
82 var ALPHANUMERIC_OUT_REGEXP = /^[A-Z0-9 $%*+\-./:]*$/;
84 // ECC levels (cf. Table 22 in JIS X 0510:2004 p. 45)
85 var ECCLEVEL_L = 1, ECCLEVEL_M = 0, ECCLEVEL_Q = 3, ECCLEVEL_H = 2;
87 // GF(2^8)-to-integer mapping with a reducing polynomial x^8+x^4+x^3+x^2+1
88 // invariant: GF256_MAP[GF256_INVMAP[i]] == i for all i in [1,256)
89 var GF256_MAP = [], GF256_INVMAP = [-1];
90 for (var i = 0, v = 1; i < 255; ++i) {
91 GF256_MAP.push(v);
92 GF256_INVMAP[v] = i;
93 v = (v * 2) ^ (v >= 128 ? 0x11d : 0);
94 }
96 // generator polynomials up to degree 30
97 // (should match with polynomials in JIS X 0510:2004 Appendix A)
98 //
99 // generator polynomial of degree K is product of (x-\alpha^0), (x-\alpha^1),
100 // ..., (x-\alpha^(K-1)). by convention, we omit the K-th coefficient (always 1)
101 // from the result; also other coefficients are written in terms of the exponent
102 // to \alpha to avoid the redundant calculation. (see also calculateecc below.)
103 var GF256_GENPOLY = [[]];
104 for (var i = 0; i < 30; ++i) {
105 var prevpoly = GF256_GENPOLY[i], poly = [];
106 for (var j = 0; j <= i; ++j) {
107 var a = (j < i ? GF256_MAP[prevpoly[j]] : 0);
108 var b = GF256_MAP[(i + (prevpoly[j-1] || 0)) % 255];
109 poly.push(GF256_INVMAP[a ^ b]);
110 }
111 GF256_GENPOLY.push(poly);
112 }
114 // alphanumeric character mapping (cf. Table 5 in JIS X 0510:2004 p. 19)
115 var ALPHANUMERIC_MAP = {};
116 for (var i = 0; i < 45; ++i) {
117 ALPHANUMERIC_MAP['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'.charAt(i)] = i;
118 }
120 // mask functions in terms of row # and column #
121 // (cf. Table 20 in JIS X 0510:2004 p. 42)
122 var MASKFUNCS = [
123 function(i,j) { return (i+j) % 2 == 0; },
124 function(i,j) { return i % 2 == 0; },
125 function(i,j) { return j % 3 == 0; },
126 function(i,j) { return (i+j) % 3 == 0; },
127 function(i,j) { return (((i/2)|0) + ((j/3)|0)) % 2 == 0; },
128 function(i,j) { return (i*j) % 2 + (i*j) % 3 == 0; },
129 function(i,j) { return ((i*j) % 2 + (i*j) % 3) % 2 == 0; },
130 function(i,j) { return ((i+j) % 2 + (i*j) % 3) % 2 == 0; }];
132 // returns true when the version information has to be embeded.
133 var needsverinfo = function(ver) { return ver > 6; };
135 // returns the size of entire QR code for given version.
136 var getsizebyver = function(ver) { return 4 * ver + 17; };
138 // returns the number of bits available for code words in this version.
139 var nfullbits = function(ver) {
140 /*
141 * |<--------------- n --------------->|
142 * | |<----- n-17 ---->| |
143 * +-------+ ///+-------+ ----
144 * | | ///| | ^
145 * | 9x9 | @@@@@ ///| 9x8 | |
146 * | | # # # @5x5@ # # # | | |
147 * +-------+ @@@@@ +-------+ |
148 * # ---|
149 * ^ |
150 * # |
151 * @@@@@ @@@@@ @@@@@ | n
152 * @5x5@ @5x5@ @5x5@ n-17
153 * @@@@@ @@@@@ @@@@@ | |
154 * # | |
155 * ////// v |
156 * //////# ---|
157 * +-------+ @@@@@ @@@@@ |
158 * | | @5x5@ @5x5@ |
159 * | 8x9 | @@@@@ @@@@@ |
160 * | | v
161 * +-------+ ----
162 *
163 * when the entire code has n^2 modules and there are m^2-3 alignment
164 * patterns, we have:
165 * - 225 (= 9x9 + 9x8 + 8x9) modules for finder patterns and
166 * format information;
167 * - 2n-34 (= 2(n-17)) modules for timing patterns;
168 * - 36 (= 3x6 + 6x3) modules for version information, if any;
169 * - 25m^2-75 (= (m^2-3)(5x5)) modules for alignment patterns
170 * if any, but 10m-20 (= 2(m-2)x5) of them overlaps with
171 * timing patterns.
172 */
173 var v = VERSIONS[ver];
174 var nbits = 16*ver*ver + 128*ver + 64; // finder, timing and format info.
175 if (needsverinfo(ver)) nbits -= 36; // version information
176 if (v[2].length) { // alignment patterns
177 nbits -= 25 * v[2].length * v[2].length - 10 * v[2].length - 55;
178 }
179 return nbits;
180 };
182 // returns the number of bits available for data portions (i.e. excludes ECC
183 // bits but includes mode and length bits) in this version and ECC level.
184 var ndatabits = function(ver, ecclevel) {
185 var nbits = nfullbits(ver) & ~7; // no sub-octet code words
186 var v = VERSIONS[ver];
187 nbits -= 8 * v[0][ecclevel] * v[1][ecclevel]; // ecc bits
188 return nbits;
189 }
191 // returns the number of bits required for the length of data.
192 // (cf. Table 3 in JIS X 0510:2004 p. 16)
193 var ndatalenbits = function(ver, mode) {
194 switch (mode) {
195 case MODE_NUMERIC: return (ver < 10 ? 10 : ver < 27 ? 12 : 14);
196 case MODE_ALPHANUMERIC: return (ver < 10 ? 9 : ver < 27 ? 11 : 13);
197 case MODE_OCTET: return (ver < 10 ? 8 : 16);
198 case MODE_KANJI: return (ver < 10 ? 8 : ver < 27 ? 10 : 12);
199 }
200 };
202 // returns the maximum length of data possible in given configuration.
203 var getmaxdatalen = function(ver, mode, ecclevel) {
204 var nbits = ndatabits(ver, ecclevel) - 4 - ndatalenbits(ver, mode); // 4 for mode bits
205 switch (mode) {
206 case MODE_NUMERIC:
207 return ((nbits/10) | 0) * 3 + (nbits%10 < 4 ? 0 : nbits%10 < 7 ? 1 : 2);
208 case MODE_ALPHANUMERIC:
209 return ((nbits/11) | 0) * 2 + (nbits%11 < 6 ? 0 : 1);
210 case MODE_OCTET:
211 return (nbits/8) | 0;
212 case MODE_KANJI:
213 return (nbits/13) | 0;
214 }
215 };
217 // checks if the given data can be encoded in given mode, and returns
218 // the converted data for the further processing if possible. otherwise
219 // returns null.
220 //
221 // this function does not check the length of data; it is a duty of
222 // encode function below (as it depends on the version and ECC level too).
223 var validatedata = function(mode, data) {
224 switch (mode) {
225 case MODE_NUMERIC:
226 if (!data.match(NUMERIC_REGEXP)) return null;
227 return data;
229 case MODE_ALPHANUMERIC:
230 if (!data.match(ALPHANUMERIC_REGEXP)) return null;
231 return data.toUpperCase();
233 case MODE_OCTET:
234 if (typeof data === 'string') { // encode as utf-8 string
235 var newdata = [];
236 for (var i = 0; i < data.length; ++i) {
237 var ch = data.charCodeAt(i);
238 if (ch < 0x80) {
239 newdata.push(ch);
240 } else if (ch < 0x800) {
241 newdata.push(0xc0 | (ch >> 6),
242 0x80 | (ch & 0x3f));
243 } else if (ch < 0x10000) {
244 newdata.push(0xe0 | (ch >> 12),
245 0x80 | ((ch >> 6) & 0x3f),
246 0x80 | (ch & 0x3f));
247 } else {
248 newdata.push(0xf0 | (ch >> 18),
249 0x80 | ((ch >> 12) & 0x3f),
250 0x80 | ((ch >> 6) & 0x3f),
251 0x80 | (ch & 0x3f));
252 }
253 }
254 return newdata;
255 } else {
256 return data;
257 }
258 }
259 };
261 // returns the code words (sans ECC bits) for given data and configurations.
262 // requires data to be preprocessed by validatedata. no length check is
263 // performed, and everything has to be checked before calling this function.
264 var encode = function(ver, mode, data, maxbuflen) {
265 var buf = [];
266 var bits = 0, remaining = 8;
267 var datalen = data.length;
269 // this function is intentionally no-op when n=0.
270 var pack = function(x, n) {
271 if (n >= remaining) {
272 buf.push(bits | (x >> (n -= remaining)));
273 while (n >= 8) buf.push((x >> (n -= 8)) & 255);
274 bits = 0;
275 remaining = 8;
276 }
277 if (n > 0) bits |= (x & ((1 << n) - 1)) << (remaining -= n);
278 };
280 var nlenbits = ndatalenbits(ver, mode);
281 pack(mode, 4);
282 pack(datalen, nlenbits);
284 switch (mode) {
285 case MODE_NUMERIC:
286 for (var i = 2; i < datalen; i += 3) {
287 pack(parseInt(data.substring(i-2,i+1), 10), 10);
288 }
289 pack(parseInt(data.substring(i-2), 10), [0,4,7][datalen%3]);
290 break;
292 case MODE_ALPHANUMERIC:
293 for (var i = 1; i < datalen; i += 2) {
294 pack(ALPHANUMERIC_MAP[data.charAt(i-1)] * 45 +
295 ALPHANUMERIC_MAP[data.charAt(i)], 11);
296 }
297 if (datalen % 2 == 1) {
298 pack(ALPHANUMERIC_MAP[data.charAt(i-1)], 6);
299 }
300 break;
302 case MODE_OCTET:
303 for (var i = 0; i < datalen; ++i) {
304 pack(data[i], 8);
305 }
306 break;
307 };
309 // final bits. it is possible that adding terminator causes the buffer
310 // to overflow, but then the buffer truncated to the maximum size will
311 // be valid as the truncated terminator mode bits and padding is
312 // identical in appearance (cf. JIS X 0510:2004 sec 8.4.8).
313 pack(MODE_TERMINATOR, 4);
314 if (remaining < 8) buf.push(bits);
316 // the padding to fill up the remaining space. we should not add any
317 // words when the overflow already occurred.
318 while (buf.length + 1 < maxbuflen) buf.push(0xec, 0x11);
319 if (buf.length < maxbuflen) buf.push(0xec);
320 return buf;
321 };
323 // calculates ECC code words for given code words and generator polynomial.
324 //
325 // this is quite similar to CRC calculation as both Reed-Solomon and CRC use
326 // the certain kind of cyclic codes, which is effectively the division of
327 // zero-augumented polynomial by the generator polynomial. the only difference
328 // is that Reed-Solomon uses GF(2^8), instead of CRC's GF(2), and Reed-Solomon
329 // uses the different generator polynomial than CRC's.
330 var calculateecc = function(poly, genpoly) {
331 var modulus = poly.slice(0);
332 var polylen = poly.length, genpolylen = genpoly.length;
333 for (var i = 0; i < genpolylen; ++i) modulus.push(0);
334 for (var i = 0; i < polylen; ) {
335 var quotient = GF256_INVMAP[modulus[i++]];
336 if (quotient >= 0) {
337 for (var j = 0; j < genpolylen; ++j) {
338 modulus[i+j] ^= GF256_MAP[(quotient + genpoly[j]) % 255];
339 }
340 }
341 }
342 return modulus.slice(polylen);
343 };
345 // auguments ECC code words to given code words. the resulting words are
346 // ready to be encoded in the matrix.
347 //
348 // the much of actual augumenting procedure follows JIS X 0510:2004 sec 8.7.
349 // the code is simplified using the fact that the size of each code & ECC
350 // blocks is almost same; for example, when we have 4 blocks and 46 data words
351 // the number of code words in those blocks are 11, 11, 12, 12 respectively.
352 var augumenteccs = function(poly, nblocks, genpoly) {
353 var subsizes = [];
354 var subsize = (poly.length / nblocks) | 0, subsize0 = 0;
355 var pivot = nblocks - poly.length % nblocks;
356 for (var i = 0; i < pivot; ++i) {
357 subsizes.push(subsize0);
358 subsize0 += subsize;
359 }
360 for (var i = pivot; i < nblocks; ++i) {
361 subsizes.push(subsize0);
362 subsize0 += subsize+1;
363 }
364 subsizes.push(subsize0);
366 var eccs = [];
367 for (var i = 0; i < nblocks; ++i) {
368 eccs.push(calculateecc(poly.slice(subsizes[i], subsizes[i+1]), genpoly));
369 }
371 var result = [];
372 var nitemsperblock = (poly.length / nblocks) | 0;
373 for (var i = 0; i < nitemsperblock; ++i) {
374 for (var j = 0; j < nblocks; ++j) {
375 result.push(poly[subsizes[j] + i]);
376 }
377 }
378 for (var j = pivot; j < nblocks; ++j) {
379 result.push(poly[subsizes[j+1] - 1]);
380 }
381 for (var i = 0; i < genpoly.length; ++i) {
382 for (var j = 0; j < nblocks; ++j) {
383 result.push(eccs[j][i]);
384 }
385 }
386 return result;
387 };
389 // auguments BCH(p+q,q) code to the polynomial over GF(2), given the proper
390 // genpoly. the both input and output are in binary numbers, and unlike
391 // calculateecc genpoly should include the 1 bit for the highest degree.
392 //
393 // actual polynomials used for this procedure are as follows:
394 // - p=10, q=5, genpoly=x^10+x^8+x^5+x^4+x^2+x+1 (JIS X 0510:2004 Appendix C)
395 // - p=18, q=6, genpoly=x^12+x^11+x^10+x^9+x^8+x^5+x^2+1 (ibid. Appendix D)
396 var augumentbch = function(poly, p, genpoly, q) {
397 var modulus = poly << q;
398 for (var i = p - 1; i >= 0; --i) {
399 if ((modulus >> (q+i)) & 1) modulus ^= genpoly << i;
400 }
401 return (poly << q) | modulus;
402 };
404 // creates the base matrix for given version. it returns two matrices, one of
405 // them is the actual one and the another represents the "reserved" portion
406 // (e.g. finder and timing patterns) of the matrix.
407 //
408 // some entries in the matrix may be undefined, rather than 0 or 1. this is
409 // intentional (no initialization needed!), and putdata below will fill
410 // the remaining ones.
411 var makebasematrix = function(ver) {
412 var v = VERSIONS[ver], n = getsizebyver(ver);
413 var matrix = [], reserved = [];
414 for (var i = 0; i < n; ++i) {
415 matrix.push([]);
416 reserved.push([]);
417 }
419 var blit = function(y, x, h, w, bits) {
420 for (var i = 0; i < h; ++i) {
421 for (var j = 0; j < w; ++j) {
422 matrix[y+i][x+j] = (bits[i] >> j) & 1;
423 reserved[y+i][x+j] = 1;
424 }
425 }
426 };
428 // finder patterns and a part of timing patterns
429 // will also mark the format information area (not yet written) as reserved.
430 blit(0, 0, 9, 9, [0x7f, 0x41, 0x5d, 0x5d, 0x5d, 0x41, 0x17f, 0x00, 0x40]);
431 blit(n-8, 0, 8, 9, [0x100, 0x7f, 0x41, 0x5d, 0x5d, 0x5d, 0x41, 0x7f]);
432 blit(0, n-8, 9, 8, [0xfe, 0x82, 0xba, 0xba, 0xba, 0x82, 0xfe, 0x00, 0x00]);
434 // the rest of timing patterns
435 for (var i = 9; i < n-8; ++i) {
436 matrix[6][i] = matrix[i][6] = ~i & 1;
437 reserved[6][i] = reserved[i][6] = 1;
438 }
440 // alignment patterns
441 var aligns = v[2], m = aligns.length;
442 for (var i = 0; i < m; ++i) {
443 var minj = (i==0 || i==m-1 ? 1 : 0), maxj = (i==0 ? m-1 : m);
444 for (var j = minj; j < maxj; ++j) {
445 blit(aligns[i], aligns[j], 5, 5, [0x1f, 0x11, 0x15, 0x11, 0x1f]);
446 }
447 }
449 // version information
450 if (needsverinfo(ver)) {
451 var code = augumentbch(ver, 6, 0x1f25, 12);
452 var k = 0;
453 for (var i = 0; i < 6; ++i) {
454 for (var j = 0; j < 3; ++j) {
455 matrix[i][(n-11)+j] = matrix[(n-11)+j][i] = (code >> k++) & 1;
456 reserved[i][(n-11)+j] = reserved[(n-11)+j][i] = 1;
457 }
458 }
459 }
461 return {matrix: matrix, reserved: reserved};
462 };
464 // fills the data portion (i.e. unmarked in reserved) of the matrix with given
465 // code words. the size of code words should be no more than available bits,
466 // and remaining bits are padded to 0 (cf. JIS X 0510:2004 sec 8.7.3).
467 var putdata = function(matrix, reserved, buf) {
468 var n = matrix.length;
469 var k = 0, dir = -1;
470 for (var i = n-1; i >= 0; i -= 2) {
471 if (i == 6) --i; // skip the entire timing pattern column
472 var jj = (dir < 0 ? n-1 : 0);
473 for (var j = 0; j < n; ++j) {
474 for (var ii = i; ii > i-2; --ii) {
475 if (!reserved[jj][ii]) {
476 // may overflow, but (undefined >> x)
477 // is 0 so it will auto-pad to zero.
478 matrix[jj][ii] = (buf[k >> 3] >> (~k&7)) & 1;
479 ++k;
480 }
481 }
482 jj += dir;
483 }
484 dir = -dir;
485 }
486 return matrix;
487 };
489 // XOR-masks the data portion of the matrix. repeating the call with the same
490 // arguments will revert the prior call (convenient in the matrix evaluation).
491 var maskdata = function(matrix, reserved, mask) {
492 var maskf = MASKFUNCS[mask];
493 var n = matrix.length;
494 for (var i = 0; i < n; ++i) {
495 for (var j = 0; j < n; ++j) {
496 if (!reserved[i][j]) matrix[i][j] ^= maskf(i,j);
497 }
498 }
499 return matrix;
500 }
502 // puts the format information.
503 var putformatinfo = function(matrix, reserved, ecclevel, mask) {
504 var n = matrix.length;
505 var code = augumentbch((ecclevel << 3) | mask, 5, 0x537, 10) ^ 0x5412;
506 for (var i = 0; i < 15; ++i) {
507 var r = [0,1,2,3,4,5,7,8,n-7,n-6,n-5,n-4,n-3,n-2,n-1][i];
508 var c = [n-1,n-2,n-3,n-4,n-5,n-6,n-7,n-8,7,5,4,3,2,1,0][i];
509 matrix[r][8] = matrix[8][c] = (code >> i) & 1;
510 // we don't have to mark those bits reserved; always done
511 // in makebasematrix above.
512 }
513 return matrix;
514 };
516 // evaluates the resulting matrix and returns the score (lower is better).
517 // (cf. JIS X 0510:2004 sec 8.8.2)
518 //
519 // the evaluation procedure tries to avoid the problematic patterns naturally
520 // occuring from the original matrix. for example, it penaltizes the patterns
521 // which just look like the finder pattern which will confuse the decoder.
522 // we choose the mask which results in the lowest score among 8 possible ones.
523 //
524 // note: zxing seems to use the same procedure and in many cases its choice
525 // agrees to ours, but sometimes it does not. practically it doesn't matter.
526 var evaluatematrix = function(matrix) {
527 // N1+(k-5) points for each consecutive row of k same-colored modules, where k >= 5. no overlapping row counts.
528 var PENALTY_CONSECUTIVE = 3;
529 // N2 points for each 2x2 block of same-colored modules. Overlapping block does count.
530 var PENALTY_TWOBYTWO = 3;
531 // N3 points for each pattern with >4W:1B:1W:3B:1W:1B or
532 // 1B:1W:3B:1W:1B:>4W, or their multiples (e.g. highly unlikely, but 13W:3B:3W:9B:3W:3B counts).
533 var PENALTY_FINDERLIKE = 40;
534 // N4*k points for every (5*k)% deviation from 50% black density.
535 // i.e. k=1 for 55~60% and 40~45%, k=2 for 60~65% and 35~40%, etc.
536 var PENALTY_DENSITY = 10;
538 var evaluategroup = function(groups) { // assumes [W,B,W,B,W,...,B,W]
539 var score = 0;
540 for (var i = 0; i < groups.length; ++i) {
541 if (groups[i] >= 5) score += PENALTY_CONSECUTIVE + (groups[i]-5);
542 }
543 for (var i = 5; i < groups.length; i += 2) {
544 var p = groups[i];
545 if (groups[i-1] == p && groups[i-2] == 3*p && groups[i-3] == p &&
546 groups[i-4] == p && (groups[i-5] >= 4*p || groups[i+1] >= 4*p)) {
547 // this part differs from zxing...
548 score += PENALTY_FINDERLIKE;
549 }
550 }
551 return score;
552 };
554 var n = matrix.length;
555 var score = 0, nblacks = 0;
556 for (var i = 0; i < n; ++i) {
557 var row = matrix[i];
558 var groups;
560 // evaluate the current row
561 groups = [0]; // the first empty group of white
562 for (var j = 0; j < n; ) {
563 var k;
564 for (k = 0; j < n && row[j]; ++k) ++j;
565 groups.push(k);
566 for (k = 0; j < n && !row[j]; ++k) ++j;
567 groups.push(k);
568 }
569 score += evaluategroup(groups);
571 // evaluate the current column
572 groups = [0];
573 for (var j = 0; j < n; ) {
574 var k;
575 for (k = 0; j < n && matrix[j][i]; ++k) ++j;
576 groups.push(k);
577 for (k = 0; j < n && !matrix[j][i]; ++k) ++j;
578 groups.push(k);
579 }
580 score += evaluategroup(groups);
582 // check the 2x2 box and calculate the density
583 var nextrow = matrix[i+1] || [];
584 nblacks += row[0];
585 for (var j = 1; j < n; ++j) {
586 var p = row[j];
587 nblacks += p;
588 // at least comparison with next row should be strict...
589 if (row[j-1] == p && nextrow[j] === p && nextrow[j-1] === p) {
590 score += PENALTY_TWOBYTWO;
591 }
592 }
593 }
595 score += PENALTY_DENSITY * ((Math.abs(nblacks / n / n - 0.5) / 0.05) | 0);
596 return score;
597 };
599 // returns the fully encoded QR code matrix which contains given data.
600 // it also chooses the best mask automatically when mask is -1.
601 var generate = function(data, ver, mode, ecclevel, mask) {
602 var v = VERSIONS[ver];
603 var buf = encode(ver, mode, data, ndatabits(ver, ecclevel) >> 3);
604 buf = augumenteccs(buf, v[1][ecclevel], GF256_GENPOLY[v[0][ecclevel]]);
606 var result = makebasematrix(ver);
607 var matrix = result.matrix, reserved = result.reserved;
608 putdata(matrix, reserved, buf);
610 if (mask < 0) {
611 // find the best mask
612 maskdata(matrix, reserved, 0);
613 putformatinfo(matrix, reserved, ecclevel, 0);
614 var bestmask = 0, bestscore = evaluatematrix(matrix);
615 maskdata(matrix, reserved, 0);
616 for (mask = 1; mask < 8; ++mask) {
617 maskdata(matrix, reserved, mask);
618 putformatinfo(matrix, reserved, ecclevel, mask);
619 var score = evaluatematrix(matrix);
620 if (bestscore > score) {
621 bestscore = score;
622 bestmask = mask;
623 }
624 maskdata(matrix, reserved, mask);
625 }
626 mask = bestmask;
627 }
629 maskdata(matrix, reserved, mask);
630 putformatinfo(matrix, reserved, ecclevel, mask);
631 return matrix;
632 };
634 // the public interface is trivial; the options available are as follows:
635 //
636 // - version: an integer in [1,40]. when omitted (or -1) the smallest possible
637 // version is chosen.
638 // - mode: one of 'numeric', 'alphanumeric', 'octet'. when omitted the smallest
639 // possible mode is chosen.
640 // - ecclevel: one of 'L', 'M', 'Q', 'H'. defaults to 'L'.
641 // - mask: an integer in [0,7]. when omitted (or -1) the best mask is chosen.
642 //
643 // for generate{HTML,PNG}:
644 //
645 // - modulesize: a number. this is a size of each modules in pixels, and
646 // defaults to 5px.
647 // - margin: a number. this is a size of margin in *modules*, and defaults to
648 // 4 (white modules). the specficiation mandates the margin no less than 4
649 // modules, so it is better not to alter this value unless you know what
650 // you're doing.
651 var QRCode = {
652 'generate': function(data, options) {
653 var MODES = {'numeric': MODE_NUMERIC, 'alphanumeric': MODE_ALPHANUMERIC,
654 'octet': MODE_OCTET};
655 var ECCLEVELS = {'L': ECCLEVEL_L, 'M': ECCLEVEL_M, 'Q': ECCLEVEL_Q,
656 'H': ECCLEVEL_H};
658 options = options || {};
659 var ver = options.version || -1;
660 var ecclevel = ECCLEVELS[(options.ecclevel || 'L').toUpperCase()];
661 var mode = options.mode ? MODES[options.mode.toLowerCase()] : -1;
662 var mask = 'mask' in options ? options.mask : -1;
664 if (mode < 0) {
665 if (typeof data === 'string') {
666 if (data.match(NUMERIC_REGEXP)) {
667 mode = MODE_NUMERIC;
668 } else if (data.match(ALPHANUMERIC_OUT_REGEXP)) {
669 // while encode supports case-insensitive
670 // encoding, we restrict the data to be
671 // uppercased when auto-selecting the mode.
672 mode = MODE_ALPHANUMERIC;
673 } else {
674 mode = MODE_OCTET;
675 }
676 } else {
677 mode = MODE_OCTET;
678 }
679 } else if (!(mode == MODE_NUMERIC || mode == MODE_ALPHANUMERIC ||
680 mode == MODE_OCTET)) {
681 throw 'invalid or unsupported mode';
682 }
684 data = validatedata(mode, data);
685 if (data === null) throw 'invalid data format';
687 if (ecclevel < 0 || ecclevel > 3) throw 'invalid ECC level';
689 if (ver < 0) {
690 for (ver = 1; ver <= 40; ++ver) {
691 if (data.length <= getmaxdatalen(ver, mode, ecclevel)) break;
692 }
693 if (ver > 40) throw 'too large data';
694 } else if (ver < 1 || ver > 40) {
695 throw 'invalid version';
696 }
698 if (mask != -1 && (mask < 0 || mask > 8)) throw 'invalid mask';
700 return generate(data, ver, mode, ecclevel, mask);
701 },
704 'generatePNG': function(data, options) {
705 options = options || {};
706 var matrix = QRCode['generate'](data, options);
707 var modsize = Math.max(options.modulesize || 5, 0.5);
708 var margin = Math.max(options.margin || 4, 0.0);
709 var n = matrix.length;
710 var size = modsize * (n + 2 * margin);
712 var canvas = document.createElement('canvas'), context;
713 canvas.width = canvas.height = size;
714 context = canvas.getContext('2d');
715 if (!context) throw 'canvas support is needed for PNG output';
717 context.fillStyle = '#fff';
718 context.fillRect(0, 0, size, size);
719 context.fillStyle = '#000';
720 for (var i = 0; i < n; ++i) {
721 for (var j = 0; j < n; ++j) {
722 if (matrix[i][j]) {
723 context.fillRect(modsize * (margin + j), modsize * (margin + i), modsize, modsize);
724 }
725 }
726 }
727 //context.fillText('evaluation: ' + evaluatematrix(matrix), 10, 10);
728 return canvas.toDataURL();
729 }
730 };
732 return QRCode;
733 })();