slitaz-forge annotate doc/lib/tpl/slitaz-orange/qrcode.js @ rev 688

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