slitaz-forge annotate doc/lib/tpl/slitaz-grey/qrcode.js @ rev 568

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