2 * Copyright 2008 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.qrcode.encoder;
19 import com.google.zxing.WriterException;
20 import com.google.zxing.common.ByteMatrix;
21 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
24 * @author satorux@google.com (Satoru Takabayashi) - creator
25 * @author dswitkin@google.com (Daniel Switkin) - ported from C++
27 public final class MatrixUtil {
29 private MatrixUtil() {
33 private static final int[][] POSITION_DETECTION_PATTERN = {
34 {1, 1, 1, 1, 1, 1, 1},
35 {1, 0, 0, 0, 0, 0, 1},
36 {1, 0, 1, 1, 1, 0, 1},
37 {1, 0, 1, 1, 1, 0, 1},
38 {1, 0, 1, 1, 1, 0, 1},
39 {1, 0, 0, 0, 0, 0, 1},
40 {1, 1, 1, 1, 1, 1, 1},
43 private static final int[][] HORIZONTAL_SEPARATION_PATTERN = {
44 {0, 0, 0, 0, 0, 0, 0, 0},
47 private static final int[][] VERTICAL_SEPARATION_PATTERN = {
48 {0}, {0}, {0}, {0}, {0}, {0}, {0},
51 private static final int[][] POSITION_ADJUSTMENT_PATTERN = {
59 // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu.
60 private static final int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = {
61 {-1, -1, -1, -1, -1, -1, -1}, // Version 1
62 { 6, 18, -1, -1, -1, -1, -1}, // Version 2
63 { 6, 22, -1, -1, -1, -1, -1}, // Version 3
64 { 6, 26, -1, -1, -1, -1, -1}, // Version 4
65 { 6, 30, -1, -1, -1, -1, -1}, // Version 5
66 { 6, 34, -1, -1, -1, -1, -1}, // Version 6
67 { 6, 22, 38, -1, -1, -1, -1}, // Version 7
68 { 6, 24, 42, -1, -1, -1, -1}, // Version 8
69 { 6, 26, 46, -1, -1, -1, -1}, // Version 9
70 { 6, 28, 50, -1, -1, -1, -1}, // Version 10
71 { 6, 30, 54, -1, -1, -1, -1}, // Version 11
72 { 6, 32, 58, -1, -1, -1, -1}, // Version 12
73 { 6, 34, 62, -1, -1, -1, -1}, // Version 13
74 { 6, 26, 46, 66, -1, -1, -1}, // Version 14
75 { 6, 26, 48, 70, -1, -1, -1}, // Version 15
76 { 6, 26, 50, 74, -1, -1, -1}, // Version 16
77 { 6, 30, 54, 78, -1, -1, -1}, // Version 17
78 { 6, 30, 56, 82, -1, -1, -1}, // Version 18
79 { 6, 30, 58, 86, -1, -1, -1}, // Version 19
80 { 6, 34, 62, 90, -1, -1, -1}, // Version 20
81 { 6, 28, 50, 72, 94, -1, -1}, // Version 21
82 { 6, 26, 50, 74, 98, -1, -1}, // Version 22
83 { 6, 30, 54, 78, 102, -1, -1}, // Version 23
84 { 6, 28, 54, 80, 106, -1, -1}, // Version 24
85 { 6, 32, 58, 84, 110, -1, -1}, // Version 25
86 { 6, 30, 58, 86, 114, -1, -1}, // Version 26
87 { 6, 34, 62, 90, 118, -1, -1}, // Version 27
88 { 6, 26, 50, 74, 98, 122, -1}, // Version 28
89 { 6, 30, 54, 78, 102, 126, -1}, // Version 29
90 { 6, 26, 52, 78, 104, 130, -1}, // Version 30
91 { 6, 30, 56, 82, 108, 134, -1}, // Version 31
92 { 6, 34, 60, 86, 112, 138, -1}, // Version 32
93 { 6, 30, 58, 86, 114, 142, -1}, // Version 33
94 { 6, 34, 62, 90, 118, 146, -1}, // Version 34
95 { 6, 30, 54, 78, 102, 126, 150}, // Version 35
96 { 6, 24, 50, 76, 102, 128, 154}, // Version 36
97 { 6, 28, 54, 80, 106, 132, 158}, // Version 37
98 { 6, 32, 58, 84, 110, 136, 162}, // Version 38
99 { 6, 26, 54, 82, 110, 138, 166}, // Version 39
100 { 6, 30, 58, 86, 114, 142, 170}, // Version 40
103 // Type info cells at the left top corner.
104 private static final int[][] TYPE_INFO_COORDINATES = {
122 // From Appendix D in JISX0510:2004 (p. 67)
123 private static final int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101
125 // From Appendix C in JISX0510:2004 (p.65).
126 private static final int TYPE_INFO_POLY = 0x537;
127 private static final int TYPE_INFO_MASK_PATTERN = 0x5412;
129 // Set all cells to -1. -1 means that the cell is empty (not set yet).
131 // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding
132 // with the ByteMatrix initialized all to zero.
133 public static void clearMatrix(ByteMatrix matrix) {
134 matrix.clear((byte) -1);
137 // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On
138 // success, store the result in "matrix" and return true.
139 public static void buildMatrix(final BitVector dataBits, ErrorCorrectionLevel ecLevel, int version,
140 int maskPattern, ByteMatrix matrix) throws WriterException {
141 MatrixUtil.clearMatrix(matrix);
142 embedBasicPatterns(version, matrix);
143 // Type information appear with any version.
144 embedTypeInfo(ecLevel, maskPattern, matrix);
145 // Version info appear if version >= 7.
146 maybeEmbedVersionInfo(version, matrix);
147 // Data should be embedded at end.
148 embedDataBits(dataBits, maskPattern, matrix);
151 // Embed basic patterns. On success, modify the matrix and return true.
152 // The basic patterns are:
153 // - Position detection patterns
155 // - Dark dot at the left bottom corner
156 // - Position adjustment patterns, if need be
157 public static void embedBasicPatterns(int version, ByteMatrix matrix) throws WriterException {
158 // Let's get started with embedding big squares at corners.
159 embedPositionDetectionPatternsAndSeparators(matrix);
160 // Then, embed the dark dot at the left bottom corner.
161 embedDarkDotAtLeftBottomCorner(matrix);
163 // Position adjustment patterns appear if version >= 2.
164 maybeEmbedPositionAdjustmentPatterns(version, matrix);
165 // Timing patterns should be embedded after position adj. patterns.
166 embedTimingPatterns(matrix);
169 // Embed type information. On success, modify the matrix.
170 public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix)
171 throws WriterException {
172 BitVector typeInfoBits = new BitVector();
173 makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits);
175 for (int i = 0; i < typeInfoBits.size(); ++i) {
176 // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in
178 final int bit = typeInfoBits.at(typeInfoBits.size() - 1 - i);
180 // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
181 final int x1 = TYPE_INFO_COORDINATES[i][0];
182 final int y1 = TYPE_INFO_COORDINATES[i][1];
183 matrix.set(y1, x1, bit);
187 final int x2 = matrix.width() - i - 1;
189 matrix.set(y2, x2, bit);
191 // Left bottom corner.
193 final int y2 = matrix.height() - 7 + (i - 8);
194 matrix.set(y2, x2, bit);
199 // Embed version information if need be. On success, modify the matrix and return true.
200 // See 8.10 of JISX0510:2004 (p.47) for how to embed version information.
201 public static void maybeEmbedVersionInfo(int version, ByteMatrix matrix) throws WriterException {
202 if (version < 7) { // Version info is necessary if version >= 7.
203 return; // Don't need version info.
205 BitVector versionInfoBits = new BitVector();
206 makeVersionInfoBits(version, versionInfoBits);
208 int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0.
209 for (int i = 0; i < 6; ++i) {
210 for (int j = 0; j < 3; ++j) {
211 // Place bits in LSB (least significant bit) to MSB order.
212 final int bit = versionInfoBits.at(bitIndex);
214 // Left bottom corner.
215 matrix.set(matrix.height() - 11 + j, i, bit);
216 // Right bottom corner.
217 matrix.set(i, matrix.height() - 11 + j, bit);
222 // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true.
223 // For debugging purposes, it skips masking process if "getMaskPattern" is -1.
224 // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
225 public static void embedDataBits(final BitVector dataBits, int maskPattern, ByteMatrix matrix)
226 throws WriterException {
229 // Start from the right bottom cell.
230 int x = matrix.width() - 1;
231 int y = matrix.height() - 1;
233 // Skip the vertical timing pattern.
237 while (y >= 0 && y < matrix.height()) {
238 for (int i = 0; i < 2; ++i) {
239 final int xx = x - i;
240 // Skip the cell if it's not empty.
241 if (!isEmpty(matrix.get(y, xx))) {
245 if (bitIndex < dataBits.size()) {
246 bit = dataBits.at(bitIndex);
249 // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described
250 // in 8.4.9 of JISX0510:2004 (p. 24).
254 // Skip masking if mask_pattern is -1.
255 if (maskPattern != -1) {
256 final int mask = MaskUtil.getDataMaskBit(maskPattern, xx, y);
259 matrix.set(y, xx, bit);
263 direction = -direction; // Reverse the direction.
265 x -= 2; // Move to the left.
267 // All bits should be consumed.
268 if (bitIndex != dataBits.size()) {
269 throw new WriterException("Not all bits consumed: " + bitIndex + "/" + dataBits.size());
273 // Return the position of the most significant bit set (to one) in the "value". The most
274 // significant bit is position 32. If there is no bit set, return 0. Examples:
275 // - findMSBSet(0) => 0
276 // - findMSBSet(1) => 1
277 // - findMSBSet(255) => 8
278 public static int findMSBSet(int value) {
287 // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
288 // code is used for encoding type information and version information.
289 // Example: Calculation of version information of 7.
290 // f(x) is created from 7.
291 // - 7 = 000111 in 6 bits
292 // - f(x) = x^2 + x^2 + x^1
293 // g(x) is given by the standard (p. 67)
294 // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
295 // Multiply f(x) by x^(18 - 6)
296 // - f'(x) = f(x) * x^(18 - 6)
297 // - f'(x) = x^14 + x^13 + x^12
298 // Calculate the remainder of f'(x) / g(x)
300 // __________________________________________________
301 // g(x) )x^14 + x^13 + x^12
302 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
303 // --------------------------------------------------
304 // x^11 + x^10 + x^7 + x^4 + x^2
306 // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
307 // Encode it in binary: 110010010100
308 // The return value is 0xc94 (1100 1001 0100)
310 // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
311 // operations. We don't care if cofficients are positive or negative.
312 public static int calculateBCHCode(int value, int poly) {
313 // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
314 // from 13 to make it 12.
315 final int msbSetInPoly = findMSBSet(poly);
316 value <<= msbSetInPoly - 1;
317 // Do the division business using exclusive-or operations.
318 while (findMSBSet(value) >= msbSetInPoly) {
319 value ^= poly << (findMSBSet(value) - msbSetInPoly);
321 // Now the "value" is the remainder (i.e. the BCH code)
325 // Make bit vector of type information. On success, store the result in "bits" and return true.
326 // Encode error correction level and mask pattern. See 8.9 of
327 // JISX0510:2004 (p.45) for details.
328 public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, final int maskPattern, BitVector bits)
329 throws WriterException {
330 if (!QRCode.isValidMaskPattern(maskPattern)) {
331 throw new WriterException("Invalid mask pattern");
333 final int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
334 bits.appendBits(typeInfo, 5);
336 final int bchCode = MatrixUtil.calculateBCHCode(typeInfo, TYPE_INFO_POLY);
337 bits.appendBits(bchCode, 10);
339 BitVector maskBits = new BitVector();
340 maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
343 if (bits.size() != 15) { // Just in case.
344 throw new WriterException("should not happen but we got: " + bits.size());
348 // Make bit vector of version information. On success, store the result in "bits" and return true.
349 // See 8.10 of JISX0510:2004 (p.45) for details.
350 public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException {
351 bits.appendBits(version, 6);
352 final int bchCode = MatrixUtil.calculateBCHCode(version, VERSION_INFO_POLY);
353 bits.appendBits(bchCode, 12);
355 if (bits.size() != 18) { // Just in case.
356 throw new WriterException("should not happen but we got: " + bits.size());
360 // Check if "value" is empty.
361 private static boolean isEmpty(final int value) {
365 // Check if "value" is valid.
366 private static boolean isValidValue(final int value) {
367 return (value == -1 || // Empty.
368 value == 0 || // Light (white).
369 value == 1); // Dark (black).
372 private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException {
373 // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical
374 // separation patterns (size 1). Thus, 8 = 7 + 1.
375 for (int i = 8; i < matrix.width() - 8; ++i) {
376 final int bit = (i + 1) % 2;
378 if (!isValidValue(matrix.get(6, i))) {
379 throw new WriterException();
381 if (isEmpty(matrix.get(6, i))) {
382 matrix.set(6, i, bit);
385 if (!isValidValue(matrix.get(i, 6))) {
386 throw new WriterException();
388 if (isEmpty(matrix.get(i, 6))) {
389 matrix.set(i, 6, bit);
394 // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
395 private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException {
396 if (matrix.get(matrix.height() - 8, 8) == 0) {
397 throw new WriterException();
399 matrix.set(matrix.height() - 8, 8, 1);
402 private static void embedHorizontalSeparationPattern(final int xStart, final int yStart,
403 ByteMatrix matrix) throws WriterException {
404 // We know the width and height.
405 if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) {
406 throw new WriterException("Bad horizontal separation pattern");
408 for (int x = 0; x < 8; ++x) {
409 if (!isEmpty(matrix.get(yStart, xStart + x))) {
410 throw new WriterException();
412 matrix.set(yStart, xStart + x, HORIZONTAL_SEPARATION_PATTERN[0][x]);
416 private static void embedVerticalSeparationPattern(final int xStart, final int yStart,
417 ByteMatrix matrix) throws WriterException {
418 // We know the width and height.
419 if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) {
420 throw new WriterException("Bad vertical separation pattern");
422 for (int y = 0; y < 7; ++y) {
423 if (!isEmpty(matrix.get(yStart + y, xStart))) {
424 throw new WriterException();
426 matrix.set(yStart + y, xStart, VERTICAL_SEPARATION_PATTERN[y][0]);
430 // Note that we cannot unify the function with embedPositionDetectionPattern() despite they are
431 // almost identical, since we cannot write a function that takes 2D arrays in different sizes in
432 // C/C++. We should live with the fact.
433 private static void embedPositionAdjustmentPattern(final int xStart, final int yStart,
434 ByteMatrix matrix) throws WriterException {
435 // We know the width and height.
436 if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) {
437 throw new WriterException("Bad position adjustment");
439 for (int y = 0; y < 5; ++y) {
440 for (int x = 0; x < 5; ++x) {
441 if (!isEmpty(matrix.get(yStart + y, xStart + x))) {
442 throw new WriterException();
444 matrix.set(yStart + y, xStart + x, POSITION_ADJUSTMENT_PATTERN[y][x]);
449 private static void embedPositionDetectionPattern(final int xStart, final int yStart,
450 ByteMatrix matrix) throws WriterException {
451 // We know the width and height.
452 if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) {
453 throw new WriterException("Bad position detection pattern");
455 for (int y = 0; y < 7; ++y) {
456 for (int x = 0; x < 7; ++x) {
457 if (!isEmpty(matrix.get(yStart + y, xStart + x))) {
458 throw new WriterException();
460 matrix.set(yStart + y, xStart + x, POSITION_DETECTION_PATTERN[y][x]);
465 // Embed position detection patterns and surrounding vertical/horizontal separators.
466 private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException {
467 // Embed three big squares at corners.
468 final int pdpWidth = POSITION_DETECTION_PATTERN[0].length;
470 embedPositionDetectionPattern(0, 0, matrix);
472 embedPositionDetectionPattern(matrix.width() - pdpWidth, 0, matrix);
473 // Left bottom corner.
474 embedPositionDetectionPattern(0, matrix.width() - pdpWidth, matrix);
476 // Embed horizontal separation patterns around the squares.
477 final int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].length;
479 embedHorizontalSeparationPattern(0, hspWidth - 1, matrix);
481 embedHorizontalSeparationPattern(matrix.width() - hspWidth,
482 hspWidth - 1, matrix);
483 // Left bottom corner.
484 embedHorizontalSeparationPattern(0, matrix.width() - hspWidth, matrix);
486 // Embed vertical separation patterns around the squares.
487 final int vspSize = VERTICAL_SEPARATION_PATTERN.length;
489 embedVerticalSeparationPattern(vspSize, 0, matrix);
491 embedVerticalSeparationPattern(matrix.height() - vspSize - 1, 0, matrix);
492 // Left bottom corner.
493 embedVerticalSeparationPattern(vspSize, matrix.height() - vspSize,
497 // Embed position adjustment patterns if need be.
498 private static void maybeEmbedPositionAdjustmentPatterns(final int version, ByteMatrix matrix)
499 throws WriterException {
500 if (version < 2) { // The patterns appear if version >= 2
503 final int index = version - 1;
504 final int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index];
505 final int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].length;
506 for (int i = 0; i < numCoordinates; ++i) {
507 for (int j = 0; j < numCoordinates; ++j) {
508 final int y = coordinates[i];
509 final int x = coordinates[j];
510 if (x == -1 || y == -1) {
513 // If the cell is unset, we embed the position adjustment pattern here.
514 if (isEmpty(matrix.get(y, x))) {
515 // -2 is necessary since the x/y coordinates point to the center of the pattern, not the
517 embedPositionAdjustmentPattern(x - 2, y - 2, matrix);