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(QRCodeMatrix *matrix) {
127 for (int y = 0; y < matrix.height(); ++y) {
128 for (int x = 0; x < matrix.width(); ++x) {
129 (*matrix)(y, x) = -1;
134 // Convert "matrix" to ASCII String for debugging.
135 public static String ToASCII(final QRCodeMatrix &matrix) {
137 for (int y = 0; y < matrix.height(); ++y) {
138 for (int x = 0; x < matrix.width(); ++x) {
139 switch (matrix(y, x)) {
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,
163 QRCodeMatrix *matrix) {
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,
187 QRCodeMatrix *matrix) {
188 // Let's get started with embedding big squares at corners.
189 EmbedPositionDetectionPatternsAndSeparators(matrix);
190 // Then, embed the dark dot at the left bottom corner.
191 EmbedDarkDotAtLeftBottomCorner(matrix);
193 // Position adjustment patterns appear if version >= 2.
194 MaybeEmbedPositionAdjustmentPatterns(version, matrix);
195 // Timing patterns should be embedded after position adj. patterns.
196 EmbedTimingPatterns(matrix);
200 // Embed type information. On success, modify the matrix and return
201 // true. On error, return false.
202 public static boolean EmbedTypeInfo(int ec_level, int mask_pattern, QRCodeMatrix *matrix) {
203 BitVector type_info_bits;
204 if (!MakeTypeInfoBits(ec_level, mask_pattern, &type_info_bits)) {
207 Debug.DCHECK_EQ(15, type_info_bits.size());
209 for (int i = 0; i < type_info_bits.size(); ++i) {
210 // Place bits in LSB to MSB order. LSB (least significant bit)
211 // is the last value in "type_info_bits".
212 final int bit = type_info_bits.at(type_info_bits.size() - 1 - i);
214 // Type info bits at the left top corner.
215 // See 8.9 of JISX0510:2004 (p.46).
216 final int x1 = kTypeInfoCoordinates[i][0];
217 final int y1 = kTypeInfoCoordinates[i][1];
218 (*matrix)(y1, x1) = bit;
222 final int x2 = matrix.width() - i - 1;
224 (*matrix)(y2, x2) = bit;
226 // Left bottom corner.
228 final int y2 = matrix.height() - 7 + (i - 8);
229 (*matrix)(y2, x2) = bit;
235 // Embed version information if need be. On success, modify the
236 // matrix and return true. On error, return false.
237 // See 8.10 of JISX0510:2004 (p.47) for how to embed version
238 // information. Return true on success. Return false otherwise.
239 public static boolean MaybeEmbedVersionInfo(int version,
240 QRCodeMatrix *matrix) {
241 if (version < 7) { // Version info is necessary if version >= 7.
242 return true; // Don't need version info.
244 BitVector version_info_bits;
245 if (!MakeVersionInfoBits(version, &version_info_bits)) {
249 Debug.DCHECK_EQ(18, version_info_bits.size());
250 int bit_index = 6 * 3 - 1; // It will decrease from 17 to 0.
251 for (int i = 0; i < 6; ++i) {
252 for (int j = 0; j < 3; ++j) {
253 // Place bits in LSB (least significant bit) to MSB order.
254 final int bit = version_info_bits.at(bit_index--);
255 // Left bottom corner.
256 (*matrix)(matrix.height() - 11 + j, i) = bit;
257 // Right bottom corner.
258 (*matrix)(i, matrix.height() - 11 + j) = bit;
264 // Embed "data_bits" using "mask_pattern". On success, modify the
265 // matrix and return true. On error, return false. For debugging
266 // purpose, it skips masking process if "mask_pattern" is -1.
267 // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
268 public static boolean EmbedDataBits(final BitVector &data_bits,
270 QRCodeMatrix *matrix) {
273 // Start from the right bottom cell.
274 int x = matrix.width() - 1;
275 int y = matrix.height() - 1;
277 // Skip the vertical timing pattern.
281 while (y >= 0 && y < matrix.height()) {
282 for (int i = 0; i < 2; ++i) {
283 final int xx = x - i;
284 // Skip the cell if it's not empty.
285 if (!IsEmpty((*matrix)(y, xx))) {
289 if (bit_index < data_bits.size()) {
290 bit = data_bits.at(bit_index);
293 // Padding bit. If there is no bit left, we'll fill the
294 // left cells with 0, as described in 8.4.9 of
295 // JISX0510:2004 (p. 24).
298 Debug.DCHECK(IsValidValue(bit));
300 // Skip masking if mask_pattern is -1.
301 if (mask_pattern != -1) {
302 final int mask = MaskUtil.GetDataMaskBit(mask_pattern, xx, y);
303 Debug.DCHECK(mask == 0 || mask == 1);
306 (*matrix)(y, xx) = bit;
310 direction = -direction; // Reverse the direction.
312 x -= 2; // Move to the left.
314 // All bits should be consumed.
315 if (bit_index < data_bits.size()) {
316 Debug.LOG_ERROR("Not all bits consumed: " + bit_index + "/" + data_bits.size());
319 Debug.DCHECK_EQ(bit_index, data_bits.size());
323 // Return the position of the most significant bit set (to one) in
324 // the "value". The most significant bit is position 32. If there
325 // is no bit set, return 0.
327 // - FindMSBSet(0) => 0
328 // - FindMSBSet(1) => 1
329 // - FindMSBSet(255) => 8
330 public static int FindMSBSet(uint32 value) {
339 // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using
340 // polynomial "poly". The BCH code is used for encoding type
341 // information and version information.
342 // Example: Calculation of version information of 7.
343 // f(x) is created from 7.
344 // - 7 = 000111 in 6 bits
345 // - f(x) = x^2 + x^2 + x^1
346 // g(x) is given by the standard (p. 67)
347 // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
348 // Multiply f(x) by x^(18 - 6)
349 // - f'(x) = f(x) * x^(18 - 6)
350 // - f'(x) = x^14 + x^13 + x^12
351 // Calculate the remainder of f'(x) / g(x)
353 // __________________________________________________
354 // g(x) )x^14 + x^13 + x^12
355 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
356 // --------------------------------------------------
357 // x^11 + x^10 + x^7 + x^4 + x^2
359 // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
360 // Encode it in binary: 110010010100
361 // The return value is 0xc94 (1100 1001 0100)
363 // Since all coefficients in the polynomials are 1 or 0, we can do the
364 // calculation by bit operations. We don't care if cofficients are
365 // positive or nagative.
366 public static uint32 CalculateBCHCode(uint32 value, uint32 poly) {
367 // If poly is "1 1111 0010 0101" (version info poly),
368 // msb_set_in_poly is 13. We'll subtract 1 from 13 to make it 12.
369 final int msb_set_in_poly = FindMSBSet(poly);
370 value <<= msb_set_in_poly - 1;
371 // Do the division business using exclusive-or operations.
372 while (FindMSBSet(value) >= msb_set_in_poly) {
373 value ^= poly << (FindMSBSet(value) - msb_set_in_poly);
375 // Now the "value" is the remainder (i.e. the BCH code)
379 // Make bit vector of type information. On success, store the
380 // result in "bits" and return true. On error, return false.
381 // Encode error correction level and mask pattern. See 8.9 of
382 // JISX0510:2004 (p.45) for details.
383 public static boolean MakeTypeInfoBits(int ec_level, final int mask_pattern, BitVector *bits) {
384 final int ec_code = QRCode.GetECLevelCode(ec_level);
388 if (!QRCode.IsValidMaskPattern(mask_pattern)) {
391 final uint32 type_info = (ec_code << 3) | mask_pattern;
392 bits.AppendBits(type_info, 5);
394 final uint32 bch_code = MatrixUtil.CalculateBCHCode(type_info,
396 bits.AppendBits(bch_code, 10);
399 mask_bits.AppendBits(kTypeInfoMaskPattern, 15);
402 if (bits.size() != 15) { // Just in case.
403 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
409 // Make bit vector of version information. On success, store the
410 // result in "bits" and return true. On error, return false.
411 // Encode version information. See 8.10 of JISX0510:2004 (p.45) for
413 public static boolean MakeVersionInfoBits(int version, BitVector *bits) {
414 bits.AppendBits(version, 6);
415 final uint32 bch_code = MatrixUtil.CalculateBCHCode(version,
417 bits.AppendBits(bch_code, 12);
418 if (bits.size() != 18) { // Just in case.
419 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
425 // Check if "value" is empty.
426 private static boolean IsEmpty(final int value) {
430 // Check if "value" is valid.
431 private static boolean IsValidValue(final int value) {
432 return (value == -1 || // Empty.
433 value == 0 || // Light (white).
434 value == 1); // Dark (black).
437 private static void EmbedTimingPatterns(QRCodeMatrix *matrix) {
438 // -8 is for skipping position detection patterns (size 7), and
439 // two horizontal/vertical separation patterns (size 1).
441 for (int i = 8; i < matrix.width() - 8; ++i) {
442 final int bit = (i + 1) % 2;
444 Debug.DCHECK(IsValidValue((*matrix)(6, i)));
445 if (IsEmpty((*matrix)(6, i))) {
446 (*matrix)(6, i) = bit;
449 Debug.DCHECK(IsValidValue((*matrix)(i, 6)));
450 if (IsEmpty((*matrix)(i, 6))) {
451 (*matrix)(i, 6) = bit;
456 // Embed the lonely dark dot at left bottom corner.
457 // JISX0510:2004 (p.46)
458 private static void EmbedDarkDotAtLeftBottomCorner(
459 QRCodeMatrix *matrix) {
460 Debug.DCHECK((*matrix)(matrix.height() - 8, 8));
461 (*matrix)(matrix.height() - 8, 8) = 1;
464 private static void EmbedHorizontalSeparationPattern(final int x_start,
466 QRCodeMatrix *matrix) {
467 // We know the width and height.
468 Debug.DCHECK_EQ(8, arraysize(kHorizontalSeparationPattern[0]));
469 Debug.DCHECK_EQ(1, arraysize(kHorizontalSeparationPattern));
470 for (int x = 0; x < 8; ++x) {
471 Debug.DCHECK(IsEmpty((*matrix)(y_start, x_start + x)));
472 (*matrix)(y_start, x_start + x) = kHorizontalSeparationPattern[0][x];
476 private static void EmbedVerticalSeparationPattern(final int x_start,
478 QRCodeMatrix *matrix) {
479 // We know the width and height.
480 Debug.DCHECK_EQ(1, arraysize(kVerticalSeparationPattern[0]));
481 Debug.DCHECK_EQ(7, arraysize(kVerticalSeparationPattern));
482 for (int y = 0; y < 7; ++y) {
483 Debug.DCHECK(IsEmpty((*matrix)(y_start + y, x_start)));
484 (*matrix)(y_start + y, x_start) = kVerticalSeparationPattern[y][0];
488 // Note that we cannot unify the function with
489 // EmbedPositionDetectionPattern() despite they are almost
490 // identical, since we cannot write a function that takes 2D arrays
491 // in different sizes in C/C++. We should live with the fact.
492 private static void EmbedPositionAdjustmentPattern(final int x_start,
494 QRCodeMatrix *matrix) {
495 // We know the width and height.
496 Debug.DCHECK_EQ(5, arraysize(kPositionAdjustmentPattern[0]));
497 Debug.DCHECK_EQ(5, arraysize(kPositionAdjustmentPattern));
498 for (int y = 0; y < 5; ++y) {
499 for (int x = 0; x < 5; ++x) {
500 Debug.DCHECK(IsEmpty((*matrix)(y_start + y, x_start + x)));
501 (*matrix)(y_start + y, x_start + x) =
502 kPositionAdjustmentPattern[y][x];
507 private static void EmbedPositionDetectionPattern(final int x_start,
509 QRCodeMatrix *matrix) {
510 // We know the width and height.
511 Debug.DCHECK_EQ(7, arraysize(kPositionDetectionPattern[0]));
512 Debug.DCHECK_EQ(7, arraysize(kPositionDetectionPattern));
513 for (int y = 0; y < 7; ++y) {
514 for (int x = 0; x < 7; ++x) {
515 Debug.DCHECK(IsEmpty((*matrix)(y_start + y, x_start + x)));
516 (*matrix)(y_start + y, x_start + x) =
517 kPositionDetectionPattern[y][x];
522 // Embed position detection patterns and surrounding
523 // vertical/horizontal separators.
524 private static void EmbedPositionDetectionPatternsAndSeparators(QRCodeMatrix *matrix) {
525 // Embed three big squares at corners.
526 final int pdp_width = arraysize(kPositionDetectionPattern[0]);
528 EmbedPositionDetectionPattern(0, 0, matrix);
530 EmbedPositionDetectionPattern(matrix.width() - pdp_width, 0, matrix);
531 // Left bottom corner.
532 EmbedPositionDetectionPattern(0, matrix.width() - pdp_width, matrix);
534 // Embed horizontal separation patterns around the squares.
535 final int hsp_width = arraysize(kHorizontalSeparationPattern[0]);
537 EmbedHorizontalSeparationPattern(0, hsp_width - 1, matrix);
539 EmbedHorizontalSeparationPattern(matrix.width() - hsp_width,
540 hsp_width - 1, matrix);
541 // Left bottom corner.
542 EmbedHorizontalSeparationPattern(0, matrix.width() - hsp_width, matrix);
544 // Embed vertical separation patterns around the squares.
545 final int vsp_height = arraysize(kVerticalSeparationPattern);
547 EmbedVerticalSeparationPattern(vsp_height, 0, matrix);
549 EmbedVerticalSeparationPattern(matrix.height() - vsp_height - 1, 0, matrix);
550 // Left bottom corner.
551 EmbedVerticalSeparationPattern(vsp_height, matrix.height() - vsp_height,
555 // Embed position adjustment patterns if need be.
556 private static void MaybeEmbedPositionAdjustmentPatterns(final int version,
557 QRCodeMatrix *matrix) {
558 if (version < 2) { // The patterns appear if version >= 2
561 final int index = version - 1;
562 final int *coordinates =
563 kPositionAdjustmentPatternCoordinateTable[index];
564 final int num_coordinates =
565 arraysize(kPositionAdjustmentPatternCoordinateTable[index]);
566 for (int i = 0; i < num_coordinates; ++i) {
567 for (int j = 0; j < num_coordinates; ++j) {
568 final int y = coordinates[i];
569 final int x = coordinates[j];
570 if (x == -1 || y == -1) {
573 // If the cell is unset, we embed the position adjustment
575 if (IsEmpty((*matrix)(y, x))) {
576 // -2 is necessary since the x/y coordinates point to the
577 // center of the pattern, not the left top corner.
578 EmbedPositionAdjustmentPattern(x - 2, y - 2, matrix);