slitaz-forge annotate pro/lib/html/qrcode.js @ rev 355

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