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 // #include "util/array/array2d-inl.h"
22 * @author satorux@google.com (Satoru Takabayashi) - creator
23 * @author dswitkin@google.com (Daniel Switkin) - ported from C++
25 public final class MatrixUtil {
27 private static final int kPositionDetectionPattern[][] = {
28 {1, 1, 1, 1, 1, 1, 1},
29 {1, 0, 0, 0, 0, 0, 1},
30 {1, 0, 1, 1, 1, 0, 1},
31 {1, 0, 1, 1, 1, 0, 1},
32 {1, 0, 1, 1, 1, 0, 1},
33 {1, 0, 0, 0, 0, 0, 1},
34 {1, 1, 1, 1, 1, 1, 1},
37 private static final int kHorizontalSeparationPattern[][] = {
38 {0, 0, 0, 0, 0, 0, 0, 0},
41 private static final int kVerticalSeparationPattern[][] = {
42 {0}, {0}, {0}, {0}, {0}, {0}, {0},
45 private static final int kPositionAdjustmentPattern[][] = {
53 // From Appendix E. Table 1, JIS0510X:2004 (p 71).
54 // The table was double-checked by komatsu.
55 private static final int kPositionAdjustmentPatternCoordinateTable[][] = {
56 {-1, -1, -1, -1, -1, -1, -1}, // Version 1
57 { 6, 18, -1, -1, -1, -1, -1}, // Version 2
58 { 6, 22, -1, -1, -1, -1, -1}, // Version 3
59 { 6, 26, -1, -1, -1, -1, -1}, // Version 4
60 { 6, 30, -1, -1, -1, -1, -1}, // Version 5
61 { 6, 34, -1, -1, -1, -1, -1}, // Version 6
62 { 6, 22, 38, -1, -1, -1, -1}, // Version 7
63 { 6, 24, 42, -1, -1, -1, -1}, // Version 8
64 { 6, 26, 46, -1, -1, -1, -1}, // Version 9
65 { 6, 28, 50, -1, -1, -1, -1}, // Version 10
66 { 6, 30, 54, -1, -1, -1, -1}, // Version 11
67 { 6, 32, 58, -1, -1, -1, -1}, // Version 12
68 { 6, 34, 62, -1, -1, -1, -1}, // Version 13
69 { 6, 26, 46, 66, -1, -1, -1}, // Version 14
70 { 6, 26, 48, 70, -1, -1, -1}, // Version 15
71 { 6, 26, 50, 74, -1, -1, -1}, // Version 16
72 { 6, 30, 54, 78, -1, -1, -1}, // Version 17
73 { 6, 30, 56, 82, -1, -1, -1}, // Version 18
74 { 6, 30, 58, 86, -1, -1, -1}, // Version 19
75 { 6, 34, 62, 90, -1, -1, -1}, // Version 20
76 { 6, 28, 50, 72, 94, -1, -1}, // Version 21
77 { 6, 26, 50, 74, 98, -1, -1}, // Version 22
78 { 6, 30, 54, 78, 102, -1, -1}, // Version 23
79 { 6, 28, 54, 80, 106, -1, -1}, // Version 24
80 { 6, 32, 58, 84, 110, -1, -1}, // Version 25
81 { 6, 30, 58, 86, 114, -1, -1}, // Version 26
82 { 6, 34, 62, 90, 118, -1, -1}, // Version 27
83 { 6, 26, 50, 74, 98, 122, -1}, // Version 28
84 { 6, 30, 54, 78, 102, 126, -1}, // Version 29
85 { 6, 26, 52, 78, 104, 130, -1}, // Version 30
86 { 6, 30, 56, 82, 108, 134, -1}, // Version 31
87 { 6, 34, 60, 86, 112, 138, -1}, // Version 32
88 { 6, 30, 58, 86, 114, 142, -1}, // Version 33
89 { 6, 34, 62, 90, 118, 146, -1}, // Version 34
90 { 6, 30, 54, 78, 102, 126, 150}, // Version 35
91 { 6, 24, 50, 76, 102, 128, 154}, // Version 36
92 { 6, 28, 54, 80, 106, 132, 158}, // Version 37
93 { 6, 32, 58, 84, 110, 136, 162}, // Version 38
94 { 6, 26, 54, 82, 110, 138, 166}, // Version 39
95 { 6, 30, 58, 86, 114, 142, 170}, // Version 40
98 // Type info cells at the left top corner.
99 private static int kTypeInfoCoordinates[][] = {
117 // From Appendix D in JISX0510:2004 (p. 67)
118 private static final uint32 kVersionInfoPoly = 0x1f25; // 1 1111 0010 0101
120 // From Appendix C in JISX0510:2004 (p.65).
121 private static final uint32 kTypeInfoPoly = 0x537;
122 private static final uint32 kTypeInfoMaskPattern = 0x5412;
124 // Set all cells to -1. -1 means that the cell is empty (not set
126 public static void ClearMatrix(Matrix matrix) {
127 for (int y = 0; y < matrix.height(); ++y) {
128 for (int x = 0; x < matrix.width(); ++x) {
129 matrix.set(y, x, -1);
134 // Convert "matrix" to ASCII String for debugging.
135 public static String ToASCII(final Matrix matrix) {
136 StringBuffer result = new StringBuffer();
137 for (int y = 0; y < matrix.height(); ++y) {
138 for (int x = 0; x < matrix.width(); ++x) {
139 switch (matrix.get(y, x)) {
153 return result.toString();
156 // Build 2D matrix of QR Code from "data_bits" with "ec_level",
157 // "version" and "mask_pattern". On success, store the result in
158 // "matrix" and return true. On error, return false.
159 public static boolean BuildMatrix(final BitVector &data_bits,
164 MatrixUtil.ClearMatrix(matrix);
165 if (!EmbedBasicPatterns(version, matrix)) {
168 // Type information appear with any version.
169 if (!EmbedTypeInfo(ec_level, mask_pattern, matrix)) {
172 // Version info appear if version >= 7.
173 if (!MaybeEmbedVersionInfo(version, matrix)) {
176 // Data should be embedded at end.
177 return EmbedDataBits(data_bits, mask_pattern, matrix);
180 // Embed basic patterns. On success, modify the matrix and return
181 // true. On error, return false. The basic patterns are:
182 // - Position detection patterns
184 // - Dark dot at the left bottom corner
185 // - Position adjustment patterns, if need be
186 public static boolean EmbedBasicPatterns(int version, Matrix matrix) {
187 // Let's get started with embedding big squares at corners.
188 EmbedPositionDetectionPatternsAndSeparators(matrix);
189 // Then, embed the dark dot at the left bottom corner.
190 EmbedDarkDotAtLeftBottomCorner(matrix);
192 // Position adjustment patterns appear if version >= 2.
193 MaybeEmbedPositionAdjustmentPatterns(version, matrix);
194 // Timing patterns should be embedded after position adj. patterns.
195 EmbedTimingPatterns(matrix);
199 // Embed type information. On success, modify the matrix and return
200 // true. On error, return false.
201 public static boolean EmbedTypeInfo(int ec_level, int mask_pattern, Matrix matrix) {
202 BitVector type_info_bits;
203 if (!MakeTypeInfoBits(ec_level, mask_pattern, &type_info_bits)) {
206 Debug.DCHECK_EQ(15, type_info_bits.size());
208 for (int i = 0; i < type_info_bits.size(); ++i) {
209 // Place bits in LSB to MSB order. LSB (least significant bit)
210 // is the last value in "type_info_bits".
211 final int bit = type_info_bits.at(type_info_bits.size() - 1 - i);
213 // Type info bits at the left top corner.
214 // See 8.9 of JISX0510:2004 (p.46).
215 final int x1 = kTypeInfoCoordinates[i][0];
216 final int y1 = kTypeInfoCoordinates[i][1];
217 matrix.set(y1, x1, bit);
221 final int x2 = matrix.width() - i - 1;
223 matrix.set(y2, x2, bit);
225 // Left bottom corner.
227 final int y2 = matrix.height() - 7 + (i - 8);
228 matrix.set(y2, x2, bit);
234 // Embed version information if need be. On success, modify the
235 // matrix and return true. On error, return false.
236 // See 8.10 of JISX0510:2004 (p.47) for how to embed version
237 // information. Return true on success. Return false otherwise.
238 public static boolean MaybeEmbedVersionInfo(int version, Matrix matrix) {
239 if (version < 7) { // Version info is necessary if version >= 7.
240 return true; // Don't need version info.
242 BitVector version_info_bits;
243 if (!MakeVersionInfoBits(version, &version_info_bits)) {
247 Debug.DCHECK_EQ(18, version_info_bits.size());
248 int bit_index = 6 * 3 - 1; // It will decrease from 17 to 0.
249 for (int i = 0; i < 6; ++i) {
250 for (int j = 0; j < 3; ++j) {
251 // Place bits in LSB (least significant bit) to MSB order.
252 final int bit = version_info_bits.at(bit_index--);
253 // Left bottom corner.
254 matrix.set(matrix.height() - 11 + j, i, bit);
255 // Right bottom corner.
256 matrix.set(i, matrix.height() - 11 + j, bit);
262 // Embed "data_bits" using "mask_pattern". On success, modify the
263 // matrix and return true. On error, return false. For debugging
264 // purpose, it skips masking process if "mask_pattern" is -1.
265 // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
266 public static boolean EmbedDataBits(final BitVector &data_bits, int mask_pattern, Matrix matrix) {
269 // Start from the right bottom cell.
270 int x = matrix.width() - 1;
271 int y = matrix.height() - 1;
273 // Skip the vertical timing pattern.
277 while (y >= 0 && y < matrix.height()) {
278 for (int i = 0; i < 2; ++i) {
279 final int xx = x - i;
280 // Skip the cell if it's not empty.
281 if (!IsEmpty(matrix.get(y, xx))) {
285 if (bit_index < data_bits.size()) {
286 bit = data_bits.at(bit_index);
289 // Padding bit. If there is no bit left, we'll fill the
290 // left cells with 0, as described in 8.4.9 of
291 // JISX0510:2004 (p. 24).
294 Debug.DCHECK(IsValidValue(bit));
296 // Skip masking if mask_pattern is -1.
297 if (mask_pattern != -1) {
298 final int mask = MaskUtil.GetDataMaskBit(mask_pattern, xx, y);
299 Debug.DCHECK(mask == 0 || mask == 1);
302 matrix.set(y, xx, bit);
306 direction = -direction; // Reverse the direction.
308 x -= 2; // Move to the left.
310 // All bits should be consumed.
311 if (bit_index < data_bits.size()) {
312 Debug.LOG_ERROR("Not all bits consumed: " + bit_index + "/" + data_bits.size());
315 Debug.DCHECK_EQ(bit_index, data_bits.size());
319 // Return the position of the most significant bit set (to one) in
320 // the "value". The most significant bit is position 32. If there
321 // is no bit set, return 0.
323 // - FindMSBSet(0) => 0
324 // - FindMSBSet(1) => 1
325 // - FindMSBSet(255) => 8
326 public static int FindMSBSet(uint32 value) {
335 // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using
336 // polynomial "poly". The BCH code is used for encoding type
337 // information and version information.
338 // Example: Calculation of version information of 7.
339 // f(x) is created from 7.
340 // - 7 = 000111 in 6 bits
341 // - f(x) = x^2 + x^2 + x^1
342 // g(x) is given by the standard (p. 67)
343 // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
344 // Multiply f(x) by x^(18 - 6)
345 // - f'(x) = f(x) * x^(18 - 6)
346 // - f'(x) = x^14 + x^13 + x^12
347 // Calculate the remainder of f'(x) / g(x)
349 // __________________________________________________
350 // g(x) )x^14 + x^13 + x^12
351 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
352 // --------------------------------------------------
353 // x^11 + x^10 + x^7 + x^4 + x^2
355 // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
356 // Encode it in binary: 110010010100
357 // The return value is 0xc94 (1100 1001 0100)
359 // Since all coefficients in the polynomials are 1 or 0, we can do the
360 // calculation by bit operations. We don't care if cofficients are
361 // positive or nagative.
362 public static uint32 CalculateBCHCode(uint32 value, uint32 poly) {
363 // If poly is "1 1111 0010 0101" (version info poly),
364 // msb_set_in_poly is 13. We'll subtract 1 from 13 to make it 12.
365 final int msb_set_in_poly = FindMSBSet(poly);
366 value <<= msb_set_in_poly - 1;
367 // Do the division business using exclusive-or operations.
368 while (FindMSBSet(value) >= msb_set_in_poly) {
369 value ^= poly << (FindMSBSet(value) - msb_set_in_poly);
371 // Now the "value" is the remainder (i.e. the BCH code)
375 // Make bit vector of type information. On success, store the
376 // result in "bits" and return true. On error, return false.
377 // Encode error correction level and mask pattern. See 8.9 of
378 // JISX0510:2004 (p.45) for details.
379 public static boolean MakeTypeInfoBits(int ec_level, final int mask_pattern, BitVector *bits) {
380 final int ec_code = QRCode.GetECLevelCode(ec_level);
384 if (!QRCode.IsValidMaskPattern(mask_pattern)) {
387 final uint32 type_info = (ec_code << 3) | mask_pattern;
388 bits.AppendBits(type_info, 5);
390 final uint32 bch_code = MatrixUtil.CalculateBCHCode(type_info,
392 bits.AppendBits(bch_code, 10);
395 mask_bits.AppendBits(kTypeInfoMaskPattern, 15);
398 if (bits.size() != 15) { // Just in case.
399 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
405 // Make bit vector of version information. On success, store the
406 // result in "bits" and return true. On error, return false.
407 // Encode version information. See 8.10 of JISX0510:2004 (p.45) for
409 public static boolean MakeVersionInfoBits(int version, BitVector *bits) {
410 bits.AppendBits(version, 6);
411 final uint32 bch_code = MatrixUtil.CalculateBCHCode(version,
413 bits.AppendBits(bch_code, 12);
414 if (bits.size() != 18) { // Just in case.
415 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
421 // Check if "value" is empty.
422 private static boolean IsEmpty(final int value) {
426 // Check if "value" is valid.
427 private static boolean IsValidValue(final int value) {
428 return (value == -1 || // Empty.
429 value == 0 || // Light (white).
430 value == 1); // Dark (black).
433 private static void EmbedTimingPatterns(Matrix matrix) {
434 // -8 is for skipping position detection patterns (size 7), and
435 // two horizontal/vertical separation patterns (size 1).
437 for (int i = 8; i < matrix.width() - 8; ++i) {
438 final int bit = (i + 1) % 2;
440 Debug.DCHECK(IsValidValue(matrix.get(6, i)));
441 if (IsEmpty(matrix.get(6, i))) {
442 matrix.set(6, i, bit);
445 Debug.DCHECK(IsValidValue(matrix.get(i, 6)));
446 if (IsEmpty(matrix.get(i, 6))) {
447 matrix.set(i, 6, bit);
452 // Embed the lonely dark dot at left bottom corner.
453 // JISX0510:2004 (p.46)
454 private static void EmbedDarkDotAtLeftBottomCorner(Matrix matrix) {
455 Debug.DCHECK(matrix.get(matrix.height() - 8, 8) != 0);
456 matrix.set(matrix.height() - 8, 8, 1);
459 private static void EmbedHorizontalSeparationPattern(final int x_start, final int y_start,
461 // We know the width and height.
462 Debug.DCHECK_EQ(8, arraysize(kHorizontalSeparationPattern[0]));
463 Debug.DCHECK_EQ(1, arraysize(kHorizontalSeparationPattern));
464 for (int x = 0; x < 8; ++x) {
465 Debug.DCHECK(IsEmpty(matrix.get(y_start, x_start + x)));
466 matrix.set(y_start, x_start + x, kHorizontalSeparationPattern[0][x]);
470 private static void EmbedVerticalSeparationPattern(final int x_start, final int y_start,
472 // We know the width and height.
473 Debug.DCHECK_EQ(1, arraysize(kVerticalSeparationPattern[0]));
474 Debug.DCHECK_EQ(7, arraysize(kVerticalSeparationPattern));
475 for (int y = 0; y < 7; ++y) {
476 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start)));
477 matrix.set(y_start + y, x_start, kVerticalSeparationPattern[y][0]);
481 // Note that we cannot unify the function with EmbedPositionDetectionPattern() despite they are
482 // almost identical, since we cannot write a function that takes 2D arrays in different sizes in
483 // C/C++. We should live with the fact.
484 private static void EmbedPositionAdjustmentPattern(final int x_start, final int y_start,
486 // We know the width and height.
487 Debug.DCHECK_EQ(5, arraysize(kPositionAdjustmentPattern[0]));
488 Debug.DCHECK_EQ(5, arraysize(kPositionAdjustmentPattern));
489 for (int y = 0; y < 5; ++y) {
490 for (int x = 0; x < 5; ++x) {
491 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start + x)));
492 matrix.set(y_start + y, x_start + x, kPositionAdjustmentPattern[y][x]);
497 private static void EmbedPositionDetectionPattern(final int x_start, final int y_start,
499 // We know the width and height.
500 Debug.DCHECK_EQ(7, arraysize(kPositionDetectionPattern[0]));
501 Debug.DCHECK_EQ(7, arraysize(kPositionDetectionPattern));
502 for (int y = 0; y < 7; ++y) {
503 for (int x = 0; x < 7; ++x) {
504 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start + x)));
505 matrix.set(y_start + y, x_start + x, kPositionDetectionPattern[y][x]);
510 // Embed position detection patterns and surrounding
511 // vertical/horizontal separators.
512 private static void EmbedPositionDetectionPatternsAndSeparators(Matrix matrix) {
513 // Embed three big squares at corners.
514 final int pdp_width = arraysize(kPositionDetectionPattern[0]);
516 EmbedPositionDetectionPattern(0, 0, matrix);
518 EmbedPositionDetectionPattern(matrix.width() - pdp_width, 0, matrix);
519 // Left bottom corner.
520 EmbedPositionDetectionPattern(0, matrix.width() - pdp_width, matrix);
522 // Embed horizontal separation patterns around the squares.
523 final int hsp_width = arraysize(kHorizontalSeparationPattern[0]);
525 EmbedHorizontalSeparationPattern(0, hsp_width - 1, matrix);
527 EmbedHorizontalSeparationPattern(matrix.width() - hsp_width,
528 hsp_width - 1, matrix);
529 // Left bottom corner.
530 EmbedHorizontalSeparationPattern(0, matrix.width() - hsp_width, matrix);
532 // Embed vertical separation patterns around the squares.
533 final int vsp_height = arraysize(kVerticalSeparationPattern);
535 EmbedVerticalSeparationPattern(vsp_height, 0, matrix);
537 EmbedVerticalSeparationPattern(matrix.height() - vsp_height - 1, 0, matrix);
538 // Left bottom corner.
539 EmbedVerticalSeparationPattern(vsp_height, matrix.height() - vsp_height,
543 // Embed position adjustment patterns if need be.
544 private static void MaybeEmbedPositionAdjustmentPatterns(final int version, Matrix matrix) {
545 if (version < 2) { // The patterns appear if version >= 2
548 final int index = version - 1;
549 final int *coordinates =
550 kPositionAdjustmentPatternCoordinateTable[index];
551 final int num_coordinates =
552 arraysize(kPositionAdjustmentPatternCoordinateTable[index]);
553 for (int i = 0; i < num_coordinates; ++i) {
554 for (int j = 0; j < num_coordinates; ++j) {
555 final int y = coordinates[i];
556 final int x = coordinates[j];
557 if (x == -1 || y == -1) {
560 // If the cell is unset, we embed the position adjustment
562 if (IsEmpty(matrix.get(y, x))) {
563 // -2 is necessary since the x/y coordinates point to the
564 // center of the pattern, not the left top corner.
565 EmbedPositionAdjustmentPattern(x - 2, y - 2, matrix);