001/* 002 * Copyright 2008 ZXing authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.itextpdf.text.pdf.qrcode; 018 019/** 020 * @author satorux@google.com (Satoru Takabayashi) - creator 021 * @author dswitkin@google.com (Daniel Switkin) - ported from C++ 022 * @since 5.0.2 023 */ 024public final class MatrixUtil { 025 026 private MatrixUtil() { 027 // do nothing 028 } 029 030 private static final int[][] POSITION_DETECTION_PATTERN = { 031 {1, 1, 1, 1, 1, 1, 1}, 032 {1, 0, 0, 0, 0, 0, 1}, 033 {1, 0, 1, 1, 1, 0, 1}, 034 {1, 0, 1, 1, 1, 0, 1}, 035 {1, 0, 1, 1, 1, 0, 1}, 036 {1, 0, 0, 0, 0, 0, 1}, 037 {1, 1, 1, 1, 1, 1, 1}, 038 }; 039 040 private static final int[][] HORIZONTAL_SEPARATION_PATTERN = { 041 {0, 0, 0, 0, 0, 0, 0, 0}, 042 }; 043 044 private static final int[][] VERTICAL_SEPARATION_PATTERN = { 045 {0}, {0}, {0}, {0}, {0}, {0}, {0}, 046 }; 047 048 private static final int[][] POSITION_ADJUSTMENT_PATTERN = { 049 {1, 1, 1, 1, 1}, 050 {1, 0, 0, 0, 1}, 051 {1, 0, 1, 0, 1}, 052 {1, 0, 0, 0, 1}, 053 {1, 1, 1, 1, 1}, 054 }; 055 056 // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu. 057 private static final int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = { 058 {-1, -1, -1, -1, -1, -1, -1}, // Version 1 059 { 6, 18, -1, -1, -1, -1, -1}, // Version 2 060 { 6, 22, -1, -1, -1, -1, -1}, // Version 3 061 { 6, 26, -1, -1, -1, -1, -1}, // Version 4 062 { 6, 30, -1, -1, -1, -1, -1}, // Version 5 063 { 6, 34, -1, -1, -1, -1, -1}, // Version 6 064 { 6, 22, 38, -1, -1, -1, -1}, // Version 7 065 { 6, 24, 42, -1, -1, -1, -1}, // Version 8 066 { 6, 26, 46, -1, -1, -1, -1}, // Version 9 067 { 6, 28, 50, -1, -1, -1, -1}, // Version 10 068 { 6, 30, 54, -1, -1, -1, -1}, // Version 11 069 { 6, 32, 58, -1, -1, -1, -1}, // Version 12 070 { 6, 34, 62, -1, -1, -1, -1}, // Version 13 071 { 6, 26, 46, 66, -1, -1, -1}, // Version 14 072 { 6, 26, 48, 70, -1, -1, -1}, // Version 15 073 { 6, 26, 50, 74, -1, -1, -1}, // Version 16 074 { 6, 30, 54, 78, -1, -1, -1}, // Version 17 075 { 6, 30, 56, 82, -1, -1, -1}, // Version 18 076 { 6, 30, 58, 86, -1, -1, -1}, // Version 19 077 { 6, 34, 62, 90, -1, -1, -1}, // Version 20 078 { 6, 28, 50, 72, 94, -1, -1}, // Version 21 079 { 6, 26, 50, 74, 98, -1, -1}, // Version 22 080 { 6, 30, 54, 78, 102, -1, -1}, // Version 23 081 { 6, 28, 54, 80, 106, -1, -1}, // Version 24 082 { 6, 32, 58, 84, 110, -1, -1}, // Version 25 083 { 6, 30, 58, 86, 114, -1, -1}, // Version 26 084 { 6, 34, 62, 90, 118, -1, -1}, // Version 27 085 { 6, 26, 50, 74, 98, 122, -1}, // Version 28 086 { 6, 30, 54, 78, 102, 126, -1}, // Version 29 087 { 6, 26, 52, 78, 104, 130, -1}, // Version 30 088 { 6, 30, 56, 82, 108, 134, -1}, // Version 31 089 { 6, 34, 60, 86, 112, 138, -1}, // Version 32 090 { 6, 30, 58, 86, 114, 142, -1}, // Version 33 091 { 6, 34, 62, 90, 118, 146, -1}, // Version 34 092 { 6, 30, 54, 78, 102, 126, 150}, // Version 35 093 { 6, 24, 50, 76, 102, 128, 154}, // Version 36 094 { 6, 28, 54, 80, 106, 132, 158}, // Version 37 095 { 6, 32, 58, 84, 110, 136, 162}, // Version 38 096 { 6, 26, 54, 82, 110, 138, 166}, // Version 39 097 { 6, 30, 58, 86, 114, 142, 170}, // Version 40 098 }; 099 100 // Type info cells at the left top corner. 101 private static final int[][] TYPE_INFO_COORDINATES = { 102 {8, 0}, 103 {8, 1}, 104 {8, 2}, 105 {8, 3}, 106 {8, 4}, 107 {8, 5}, 108 {8, 7}, 109 {8, 8}, 110 {7, 8}, 111 {5, 8}, 112 {4, 8}, 113 {3, 8}, 114 {2, 8}, 115 {1, 8}, 116 {0, 8}, 117 }; 118 119 // From Appendix D in JISX0510:2004 (p. 67) 120 private static final int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101 121 122 // From Appendix C in JISX0510:2004 (p.65). 123 private static final int TYPE_INFO_POLY = 0x537; 124 private static final int TYPE_INFO_MASK_PATTERN = 0x5412; 125 126 // Set all cells to -1. -1 means that the cell is empty (not set yet). 127 // 128 // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding 129 // with the ByteMatrix initialized all to zero. 130 public static void clearMatrix(ByteMatrix matrix) { 131 matrix.clear((byte) -1); 132 } 133 134 // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On 135 // success, store the result in "matrix" and return true. 136 public static void buildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version, 137 int maskPattern, ByteMatrix matrix) throws WriterException { 138 clearMatrix(matrix); 139 embedBasicPatterns(version, matrix); 140 // Type information appear with any version. 141 embedTypeInfo(ecLevel, maskPattern, matrix); 142 // Version info appear if version >= 7. 143 maybeEmbedVersionInfo(version, matrix); 144 // Data should be embedded at end. 145 embedDataBits(dataBits, maskPattern, matrix); 146 } 147 148 // Embed basic patterns. On success, modify the matrix and return true. 149 // The basic patterns are: 150 // - Position detection patterns 151 // - Timing patterns 152 // - Dark dot at the left bottom corner 153 // - Position adjustment patterns, if need be 154 public static void embedBasicPatterns(int version, ByteMatrix matrix) throws WriterException { 155 // Let's get started with embedding big squares at corners. 156 embedPositionDetectionPatternsAndSeparators(matrix); 157 // Then, embed the dark dot at the left bottom corner. 158 embedDarkDotAtLeftBottomCorner(matrix); 159 160 // Position adjustment patterns appear if version >= 2. 161 maybeEmbedPositionAdjustmentPatterns(version, matrix); 162 // Timing patterns should be embedded after position adj. patterns. 163 embedTimingPatterns(matrix); 164 } 165 166 // Embed type information. On success, modify the matrix. 167 public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) 168 throws WriterException { 169 BitVector typeInfoBits = new BitVector(); 170 makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); 171 172 for (int i = 0; i < typeInfoBits.size(); ++i) { 173 // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in 174 // "typeInfoBits". 175 int bit = typeInfoBits.at(typeInfoBits.size() - 1 - i); 176 177 // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). 178 int x1 = TYPE_INFO_COORDINATES[i][0]; 179 int y1 = TYPE_INFO_COORDINATES[i][1]; 180 matrix.set(x1, y1, bit); 181 182 if (i < 8) { 183 // Right top corner. 184 int x2 = matrix.getWidth() - i - 1; 185 int y2 = 8; 186 matrix.set(x2, y2, bit); 187 } else { 188 // Left bottom corner. 189 int x2 = 8; 190 int y2 = matrix.getHeight() - 7 + (i - 8); 191 matrix.set(x2, y2, bit); 192 } 193 } 194 } 195 196 // Embed version information if need be. On success, modify the matrix and return true. 197 // See 8.10 of JISX0510:2004 (p.47) for how to embed version information. 198 public static void maybeEmbedVersionInfo(int version, ByteMatrix matrix) throws WriterException { 199 if (version < 7) { // Version info is necessary if version >= 7. 200 return; // Don't need version info. 201 } 202 BitVector versionInfoBits = new BitVector(); 203 makeVersionInfoBits(version, versionInfoBits); 204 205 int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. 206 for (int i = 0; i < 6; ++i) { 207 for (int j = 0; j < 3; ++j) { 208 // Place bits in LSB (least significant bit) to MSB order. 209 int bit = versionInfoBits.at(bitIndex); 210 bitIndex--; 211 // Left bottom corner. 212 matrix.set(i, matrix.getHeight() - 11 + j, bit); 213 // Right bottom corner. 214 matrix.set(matrix.getHeight() - 11 + j, i, bit); 215 } 216 } 217 } 218 219 // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. 220 // For debugging purposes, it skips masking process if "getMaskPattern" is -1. 221 // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. 222 public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix) 223 throws WriterException { 224 int bitIndex = 0; 225 int direction = -1; 226 // Start from the right bottom cell. 227 int x = matrix.getWidth() - 1; 228 int y = matrix.getHeight() - 1; 229 while (x > 0) { 230 // Skip the vertical timing pattern. 231 if (x == 6) { 232 x -= 1; 233 } 234 while (y >= 0 && y < matrix.getHeight()) { 235 for (int i = 0; i < 2; ++i) { 236 int xx = x - i; 237 // Skip the cell if it's not empty. 238 if (!isEmpty(matrix.get(xx, y))) { 239 continue; 240 } 241 int bit; 242 if (bitIndex < dataBits.size()) { 243 bit = dataBits.at(bitIndex); 244 ++bitIndex; 245 } else { 246 // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described 247 // in 8.4.9 of JISX0510:2004 (p. 24). 248 bit = 0; 249 } 250 251 // Skip masking if mask_pattern is -1. 252 if (maskPattern != -1) { 253 if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) { 254 bit ^= 0x1; 255 } 256 } 257 matrix.set(xx, y, bit); 258 } 259 y += direction; 260 } 261 direction = -direction; // Reverse the direction. 262 y += direction; 263 x -= 2; // Move to the left. 264 } 265 // All bits should be consumed. 266 if (bitIndex != dataBits.size()) { 267 throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size()); 268 } 269 } 270 271 // Return the position of the most significant bit set (to one) in the "value". The most 272 // significant bit is position 32. If there is no bit set, return 0. Examples: 273 // - findMSBSet(0) => 0 274 // - findMSBSet(1) => 1 275 // - findMSBSet(255) => 8 276 public static int findMSBSet(int value) { 277 int numDigits = 0; 278 while (value != 0) { 279 value >>>= 1; 280 ++numDigits; 281 } 282 return numDigits; 283 } 284 285 // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH 286 // code is used for encoding type information and version information. 287 // Example: Calculation of version information of 7. 288 // f(x) is created from 7. 289 // - 7 = 000111 in 6 bits 290 // - f(x) = x^2 + x^2 + x^1 291 // g(x) is given by the standard (p. 67) 292 // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 293 // Multiply f(x) by x^(18 - 6) 294 // - f'(x) = f(x) * x^(18 - 6) 295 // - f'(x) = x^14 + x^13 + x^12 296 // Calculate the remainder of f'(x) / g(x) 297 // x^2 298 // __________________________________________________ 299 // g(x) )x^14 + x^13 + x^12 300 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 301 // -------------------------------------------------- 302 // x^11 + x^10 + x^7 + x^4 + x^2 303 // 304 // The remainder is x^11 + x^10 + x^7 + x^4 + x^2 305 // Encode it in binary: 110010010100 306 // The return value is 0xc94 (1100 1001 0100) 307 // 308 // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit 309 // operations. We don't care if cofficients are positive or negative. 310 public static int calculateBCHCode(int value, int poly) { 311 // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 312 // from 13 to make it 12. 313 int msbSetInPoly = findMSBSet(poly); 314 value <<= msbSetInPoly - 1; 315 // Do the division business using exclusive-or operations. 316 while (findMSBSet(value) >= msbSetInPoly) { 317 value ^= poly << (findMSBSet(value) - msbSetInPoly); 318 } 319 // Now the "value" is the remainder (i.e. the BCH code) 320 return value; 321 } 322 323 // Make bit vector of type information. On success, store the result in "bits" and return true. 324 // Encode error correction level and mask pattern. See 8.9 of 325 // JISX0510:2004 (p.45) for details. 326 public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits) 327 throws WriterException { 328 if (!QRCode.isValidMaskPattern(maskPattern)) { 329 throw new WriterException("Invalid mask pattern"); 330 } 331 int typeInfo = (ecLevel.getBits() << 3) | maskPattern; 332 bits.appendBits(typeInfo, 5); 333 334 int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); 335 bits.appendBits(bchCode, 10); 336 337 BitVector maskBits = new BitVector(); 338 maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); 339 bits.xor(maskBits); 340 341 if (bits.size() != 15) { // Just in case. 342 throw new WriterException("should not happen but we got: " + bits.size()); 343 } 344 } 345 346 // Make bit vector of version information. On success, store the result in "bits" and return true. 347 // See 8.10 of JISX0510:2004 (p.45) for details. 348 public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException { 349 bits.appendBits(version, 6); 350 int bchCode = calculateBCHCode(version, VERSION_INFO_POLY); 351 bits.appendBits(bchCode, 12); 352 353 if (bits.size() != 18) { // Just in case. 354 throw new WriterException("should not happen but we got: " + bits.size()); 355 } 356 } 357 358 // Check if "value" is empty. 359 private static boolean isEmpty(int value) { 360 return value == -1; 361 } 362 363 // Check if "value" is valid. 364 private static boolean isValidValue(int value) { 365 return (value == -1 || // Empty. 366 value == 0 || // Light (white). 367 value == 1); // Dark (black). 368 } 369 370 private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException { 371 // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical 372 // separation patterns (size 1). Thus, 8 = 7 + 1. 373 for (int i = 8; i < matrix.getWidth() - 8; ++i) { 374 int bit = (i + 1) % 2; 375 // Horizontal line. 376 if (!isValidValue(matrix.get(i, 6))) { 377 throw new WriterException(); 378 } 379 if (isEmpty(matrix.get(i, 6))) { 380 matrix.set(i, 6, bit); 381 } 382 // Vertical line. 383 if (!isValidValue(matrix.get(6, i))) { 384 throw new WriterException(); 385 } 386 if (isEmpty(matrix.get(6, i))) { 387 matrix.set(6, i, bit); 388 } 389 } 390 } 391 392 // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) 393 private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException { 394 if (matrix.get(8, matrix.getHeight() - 8) == 0) { 395 throw new WriterException(); 396 } 397 matrix.set(8, matrix.getHeight() - 8, 1); 398 } 399 400 private static void embedHorizontalSeparationPattern(int xStart, int yStart, 401 ByteMatrix matrix) throws WriterException { 402 // We know the width and height. 403 if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) { 404 throw new WriterException("Bad horizontal separation pattern"); 405 } 406 for (int x = 0; x < 8; ++x) { 407 if (!isEmpty(matrix.get(xStart + x, yStart))) { 408 throw new WriterException(); 409 } 410 matrix.set(xStart + x, yStart, HORIZONTAL_SEPARATION_PATTERN[0][x]); 411 } 412 } 413 414 private static void embedVerticalSeparationPattern(int xStart, int yStart, 415 ByteMatrix matrix) throws WriterException { 416 // We know the width and height. 417 if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) { 418 throw new WriterException("Bad vertical separation pattern"); 419 } 420 for (int y = 0; y < 7; ++y) { 421 if (!isEmpty(matrix.get(xStart, yStart + y))) { 422 throw new WriterException(); 423 } 424 matrix.set(xStart, yStart + y, VERTICAL_SEPARATION_PATTERN[y][0]); 425 } 426 } 427 428 // Note that we cannot unify the function with embedPositionDetectionPattern() despite they are 429 // almost identical, since we cannot write a function that takes 2D arrays in different sizes in 430 // C/C++. We should live with the fact. 431 private static void embedPositionAdjustmentPattern(int xStart, int yStart, 432 ByteMatrix matrix) throws WriterException { 433 // We know the width and height. 434 if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) { 435 throw new WriterException("Bad position adjustment"); 436 } 437 for (int y = 0; y < 5; ++y) { 438 for (int x = 0; x < 5; ++x) { 439 if (!isEmpty(matrix.get(xStart + x, yStart + y))) { 440 throw new WriterException(); 441 } 442 matrix.set(xStart + x, yStart + y, POSITION_ADJUSTMENT_PATTERN[y][x]); 443 } 444 } 445 } 446 447 private static void embedPositionDetectionPattern(int xStart, int yStart, 448 ByteMatrix matrix) throws WriterException { 449 // We know the width and height. 450 if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) { 451 throw new WriterException("Bad position detection pattern"); 452 } 453 for (int y = 0; y < 7; ++y) { 454 for (int x = 0; x < 7; ++x) { 455 if (!isEmpty(matrix.get(xStart + x, yStart + y))) { 456 throw new WriterException(); 457 } 458 matrix.set(xStart + x, yStart + y, POSITION_DETECTION_PATTERN[y][x]); 459 } 460 } 461 } 462 463 // Embed position detection patterns and surrounding vertical/horizontal separators. 464 private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException { 465 // Embed three big squares at corners. 466 int pdpWidth = POSITION_DETECTION_PATTERN[0].length; 467 // Left top corner. 468 embedPositionDetectionPattern(0, 0, matrix); 469 // Right top corner. 470 embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix); 471 // Left bottom corner. 472 embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix); 473 474 // Embed horizontal separation patterns around the squares. 475 int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].length; 476 // Left top corner. 477 embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); 478 // Right top corner. 479 embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth, 480 hspWidth - 1, matrix); 481 // Left bottom corner. 482 embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix); 483 484 // Embed vertical separation patterns around the squares. 485 int vspSize = VERTICAL_SEPARATION_PATTERN.length; 486 // Left top corner. 487 embedVerticalSeparationPattern(vspSize, 0, matrix); 488 // Right top corner. 489 embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix); 490 // Left bottom corner. 491 embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize, 492 matrix); 493 } 494 495 // Embed position adjustment patterns if need be. 496 private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix) 497 throws WriterException { 498 if (version < 2) { // The patterns appear if version >= 2 499 return; 500 } 501 int index = version - 1; 502 int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; 503 int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].length; 504 for (int i = 0; i < numCoordinates; ++i) { 505 for (int j = 0; j < numCoordinates; ++j) { 506 int y = coordinates[i]; 507 int x = coordinates[j]; 508 if (x == -1 || y == -1) { 509 continue; 510 } 511 // If the cell is unset, we embed the position adjustment pattern here. 512 if (isEmpty(matrix.get(x, y))) { 513 // -2 is necessary since the x/y coordinates point to the center of the pattern, not the 514 // left top corner. 515 embedPositionAdjustmentPattern(x - 2, y - 2, matrix); 516 } 517 } 518 } 519 } 520 521}