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(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version,
140 int maskPattern, ByteMatrix matrix) throws WriterException {
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 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 int x1 = TYPE_INFO_COORDINATES[i][0];
182 int y1 = TYPE_INFO_COORDINATES[i][1];
183 matrix.set(x1, y1, bit);
187 int x2 = matrix.width() - i - 1;
189 matrix.set(x2, y2, bit);
191 // Left bottom corner.
193 int y2 = matrix.height() - 7 + (i - 8);
194 matrix.set(x2, y2, 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 int bit = versionInfoBits.at(bitIndex);
214 // Left bottom corner.
215 matrix.set(i, matrix.height() - 11 + j, bit);
216 // Right bottom corner.
217 matrix.set(matrix.height() - 11 + j, i, 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(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) {
240 // Skip the cell if it's not empty.
241 if (!isEmpty(matrix.get(xx, y))) {
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 if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) {
260 matrix.set(xx, y, bit);
264 direction = -direction; // Reverse the direction.
266 x -= 2; // Move to the left.
268 // All bits should be consumed.
269 if (bitIndex != dataBits.size()) {
270 throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size());
274 // Return the position of the most significant bit set (to one) in the "value". The most
275 // significant bit is position 32. If there is no bit set, return 0. Examples:
276 // - findMSBSet(0) => 0
277 // - findMSBSet(1) => 1
278 // - findMSBSet(255) => 8
279 public static int findMSBSet(int value) {
288 // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
289 // code is used for encoding type information and version information.
290 // Example: Calculation of version information of 7.
291 // f(x) is created from 7.
292 // - 7 = 000111 in 6 bits
293 // - f(x) = x^2 + x^2 + x^1
294 // g(x) is given by the standard (p. 67)
295 // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
296 // Multiply f(x) by x^(18 - 6)
297 // - f'(x) = f(x) * x^(18 - 6)
298 // - f'(x) = x^14 + x^13 + x^12
299 // Calculate the remainder of f'(x) / g(x)
301 // __________________________________________________
302 // g(x) )x^14 + x^13 + x^12
303 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
304 // --------------------------------------------------
305 // x^11 + x^10 + x^7 + x^4 + x^2
307 // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
308 // Encode it in binary: 110010010100
309 // The return value is 0xc94 (1100 1001 0100)
311 // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
312 // operations. We don't care if cofficients are positive or negative.
313 public static int calculateBCHCode(int value, int poly) {
314 // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
315 // from 13 to make it 12.
316 int msbSetInPoly = findMSBSet(poly);
317 value <<= msbSetInPoly - 1;
318 // Do the division business using exclusive-or operations.
319 while (findMSBSet(value) >= msbSetInPoly) {
320 value ^= poly << (findMSBSet(value) - msbSetInPoly);
322 // Now the "value" is the remainder (i.e. the BCH code)
326 // Make bit vector of type information. On success, store the result in "bits" and return true.
327 // Encode error correction level and mask pattern. See 8.9 of
328 // JISX0510:2004 (p.45) for details.
329 public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits)
330 throws WriterException {
331 if (!QRCode.isValidMaskPattern(maskPattern)) {
332 throw new WriterException("Invalid mask pattern");
334 int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
335 bits.appendBits(typeInfo, 5);
337 int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
338 bits.appendBits(bchCode, 10);
340 BitVector maskBits = new BitVector();
341 maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
344 if (bits.size() != 15) { // Just in case.
345 throw new WriterException("should not happen but we got: " + bits.size());
349 // Make bit vector of version information. On success, store the result in "bits" and return true.
350 // See 8.10 of JISX0510:2004 (p.45) for details.
351 public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException {
352 bits.appendBits(version, 6);
353 int bchCode = calculateBCHCode(version, VERSION_INFO_POLY);
354 bits.appendBits(bchCode, 12);
356 if (bits.size() != 18) { // Just in case.
357 throw new WriterException("should not happen but we got: " + bits.size());
361 // Check if "value" is empty.
362 private static boolean isEmpty(int value) {
366 // Check if "value" is valid.
367 private static boolean isValidValue(int value) {
368 return (value == -1 || // Empty.
369 value == 0 || // Light (white).
370 value == 1); // Dark (black).
373 private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException {
374 // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical
375 // separation patterns (size 1). Thus, 8 = 7 + 1.
376 for (int i = 8; i < matrix.width() - 8; ++i) {
377 int bit = (i + 1) % 2;
379 if (!isValidValue(matrix.get(i, 6))) {
380 throw new WriterException();
382 if (isEmpty(matrix.get(i, 6))) {
383 matrix.set(i, 6, bit);
386 if (!isValidValue(matrix.get(6, i))) {
387 throw new WriterException();
389 if (isEmpty(matrix.get(6, i))) {
390 matrix.set(6, i, bit);
395 // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
396 private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException {
397 if (matrix.get(8, matrix.height() - 8) == 0) {
398 throw new WriterException();
400 matrix.set(8, matrix.height() - 8, 1);
403 private static void embedHorizontalSeparationPattern(int xStart, int yStart,
404 ByteMatrix matrix) throws WriterException {
405 // We know the width and height.
406 if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) {
407 throw new WriterException("Bad horizontal separation pattern");
409 for (int x = 0; x < 8; ++x) {
410 if (!isEmpty(matrix.get(xStart + x, yStart))) {
411 throw new WriterException();
413 matrix.set(xStart + x, yStart, HORIZONTAL_SEPARATION_PATTERN[0][x]);
417 private static void embedVerticalSeparationPattern(int xStart, int yStart,
418 ByteMatrix matrix) throws WriterException {
419 // We know the width and height.
420 if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) {
421 throw new WriterException("Bad vertical separation pattern");
423 for (int y = 0; y < 7; ++y) {
424 if (!isEmpty(matrix.get(xStart, yStart + y))) {
425 throw new WriterException();
427 matrix.set(xStart, yStart + y, VERTICAL_SEPARATION_PATTERN[y][0]);
431 // Note that we cannot unify the function with embedPositionDetectionPattern() despite they are
432 // almost identical, since we cannot write a function that takes 2D arrays in different sizes in
433 // C/C++. We should live with the fact.
434 private static void embedPositionAdjustmentPattern(int xStart, int yStart,
435 ByteMatrix matrix) throws WriterException {
436 // We know the width and height.
437 if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) {
438 throw new WriterException("Bad position adjustment");
440 for (int y = 0; y < 5; ++y) {
441 for (int x = 0; x < 5; ++x) {
442 if (!isEmpty(matrix.get(xStart + x, yStart + y))) {
443 throw new WriterException();
445 matrix.set(xStart + x, yStart + y, POSITION_ADJUSTMENT_PATTERN[y][x]);
450 private static void embedPositionDetectionPattern(int xStart, int yStart,
451 ByteMatrix matrix) throws WriterException {
452 // We know the width and height.
453 if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) {
454 throw new WriterException("Bad position detection pattern");
456 for (int y = 0; y < 7; ++y) {
457 for (int x = 0; x < 7; ++x) {
458 if (!isEmpty(matrix.get(xStart + x, yStart + y))) {
459 throw new WriterException();
461 matrix.set(xStart + x, yStart + y, POSITION_DETECTION_PATTERN[y][x]);
466 // Embed position detection patterns and surrounding vertical/horizontal separators.
467 private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException {
468 // Embed three big squares at corners.
469 int pdpWidth = POSITION_DETECTION_PATTERN[0].length;
471 embedPositionDetectionPattern(0, 0, matrix);
473 embedPositionDetectionPattern(matrix.width() - pdpWidth, 0, matrix);
474 // Left bottom corner.
475 embedPositionDetectionPattern(0, matrix.width() - pdpWidth, matrix);
477 // Embed horizontal separation patterns around the squares.
478 int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].length;
480 embedHorizontalSeparationPattern(0, hspWidth - 1, matrix);
482 embedHorizontalSeparationPattern(matrix.width() - hspWidth,
483 hspWidth - 1, matrix);
484 // Left bottom corner.
485 embedHorizontalSeparationPattern(0, matrix.width() - hspWidth, matrix);
487 // Embed vertical separation patterns around the squares.
488 int vspSize = VERTICAL_SEPARATION_PATTERN.length;
490 embedVerticalSeparationPattern(vspSize, 0, matrix);
492 embedVerticalSeparationPattern(matrix.height() - vspSize - 1, 0, matrix);
493 // Left bottom corner.
494 embedVerticalSeparationPattern(vspSize, matrix.height() - vspSize,
498 // Embed position adjustment patterns if need be.
499 private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix)
500 throws WriterException {
501 if (version < 2) { // The patterns appear if version >= 2
504 int index = version - 1;
505 int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index];
506 int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].length;
507 for (int i = 0; i < numCoordinates; ++i) {
508 for (int j = 0; j < numCoordinates; ++j) {
509 int y = coordinates[i];
510 int x = coordinates[j];
511 if (x == -1 || y == -1) {
514 // If the cell is unset, we embed the position adjustment pattern here.
515 if (isEmpty(matrix.get(x, y))) {
516 // -2 is necessary since the x/y coordinates point to the center of the pattern, not the
518 embedPositionAdjustmentPattern(x - 2, y - 2, matrix);