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). The table was double-checked by komatsu.
54 private static final int kPositionAdjustmentPatternCoordinateTable[][] = {
55 {-1, -1, -1, -1, -1, -1, -1}, // Version 1
56 { 6, 18, -1, -1, -1, -1, -1}, // Version 2
57 { 6, 22, -1, -1, -1, -1, -1}, // Version 3
58 { 6, 26, -1, -1, -1, -1, -1}, // Version 4
59 { 6, 30, -1, -1, -1, -1, -1}, // Version 5
60 { 6, 34, -1, -1, -1, -1, -1}, // Version 6
61 { 6, 22, 38, -1, -1, -1, -1}, // Version 7
62 { 6, 24, 42, -1, -1, -1, -1}, // Version 8
63 { 6, 26, 46, -1, -1, -1, -1}, // Version 9
64 { 6, 28, 50, -1, -1, -1, -1}, // Version 10
65 { 6, 30, 54, -1, -1, -1, -1}, // Version 11
66 { 6, 32, 58, -1, -1, -1, -1}, // Version 12
67 { 6, 34, 62, -1, -1, -1, -1}, // Version 13
68 { 6, 26, 46, 66, -1, -1, -1}, // Version 14
69 { 6, 26, 48, 70, -1, -1, -1}, // Version 15
70 { 6, 26, 50, 74, -1, -1, -1}, // Version 16
71 { 6, 30, 54, 78, -1, -1, -1}, // Version 17
72 { 6, 30, 56, 82, -1, -1, -1}, // Version 18
73 { 6, 30, 58, 86, -1, -1, -1}, // Version 19
74 { 6, 34, 62, 90, -1, -1, -1}, // Version 20
75 { 6, 28, 50, 72, 94, -1, -1}, // Version 21
76 { 6, 26, 50, 74, 98, -1, -1}, // Version 22
77 { 6, 30, 54, 78, 102, -1, -1}, // Version 23
78 { 6, 28, 54, 80, 106, -1, -1}, // Version 24
79 { 6, 32, 58, 84, 110, -1, -1}, // Version 25
80 { 6, 30, 58, 86, 114, -1, -1}, // Version 26
81 { 6, 34, 62, 90, 118, -1, -1}, // Version 27
82 { 6, 26, 50, 74, 98, 122, -1}, // Version 28
83 { 6, 30, 54, 78, 102, 126, -1}, // Version 29
84 { 6, 26, 52, 78, 104, 130, -1}, // Version 30
85 { 6, 30, 56, 82, 108, 134, -1}, // Version 31
86 { 6, 34, 60, 86, 112, 138, -1}, // Version 32
87 { 6, 30, 58, 86, 114, 142, -1}, // Version 33
88 { 6, 34, 62, 90, 118, 146, -1}, // Version 34
89 { 6, 30, 54, 78, 102, 126, 150}, // Version 35
90 { 6, 24, 50, 76, 102, 128, 154}, // Version 36
91 { 6, 28, 54, 80, 106, 132, 158}, // Version 37
92 { 6, 32, 58, 84, 110, 136, 162}, // Version 38
93 { 6, 26, 54, 82, 110, 138, 166}, // Version 39
94 { 6, 30, 58, 86, 114, 142, 170}, // Version 40
97 // Type info cells at the left top corner.
98 private static int kTypeInfoCoordinates[][] = {
116 // From Appendix D in JISX0510:2004 (p. 67)
117 private static final uint32 kVersionInfoPoly = 0x1f25; // 1 1111 0010 0101
119 // From Appendix C in JISX0510:2004 (p.65).
120 private static final uint32 kTypeInfoPoly = 0x537;
121 private static final uint32 kTypeInfoMaskPattern = 0x5412;
123 // Set all cells to -1. -1 means that the cell is empty (not set yet).
124 public static void ClearMatrix(Matrix matrix) {
125 for (int y = 0; y < matrix.height(); ++y) {
126 for (int x = 0; x < matrix.width(); ++x) {
127 matrix.set(y, x, -1);
132 // Convert "matrix" to ASCII String for debugging.
133 public static String ToASCII(final Matrix matrix) {
134 StringBuffer result = new StringBuffer();
135 for (int y = 0; y < matrix.height(); ++y) {
136 for (int x = 0; x < matrix.width(); ++x) {
137 switch (matrix.get(y, x)) {
151 return result.toString();
154 // Build 2D matrix of QR Code from "data_bits" with "ec_level", "version" and "mask_pattern". On
155 // success, store the result in "matrix" and return true. On error, return false.
156 public static boolean BuildMatrix(final BitVector &data_bits,
161 MatrixUtil.ClearMatrix(matrix);
162 if (!EmbedBasicPatterns(version, matrix)) {
165 // Type information appear with any version.
166 if (!EmbedTypeInfo(ec_level, mask_pattern, matrix)) {
169 // Version info appear if version >= 7.
170 if (!MaybeEmbedVersionInfo(version, matrix)) {
173 // Data should be embedded at end.
174 return EmbedDataBits(data_bits, mask_pattern, matrix);
177 // Embed basic patterns. On success, modify the matrix and return true. On error, return false.
178 // The basic patterns are:
179 // - Position detection patterns
181 // - Dark dot at the left bottom corner
182 // - Position adjustment patterns, if need be
183 public static boolean EmbedBasicPatterns(int version, Matrix matrix) {
184 // Let's get started with embedding big squares at corners.
185 EmbedPositionDetectionPatternsAndSeparators(matrix);
186 // Then, embed the dark dot at the left bottom corner.
187 EmbedDarkDotAtLeftBottomCorner(matrix);
189 // Position adjustment patterns appear if version >= 2.
190 MaybeEmbedPositionAdjustmentPatterns(version, matrix);
191 // Timing patterns should be embedded after position adj. patterns.
192 EmbedTimingPatterns(matrix);
196 // Embed type information. On success, modify the matrix and return true. On error, return false.
197 public static boolean EmbedTypeInfo(int ec_level, int mask_pattern, Matrix matrix) {
198 BitVector type_info_bits;
199 if (!MakeTypeInfoBits(ec_level, mask_pattern, &type_info_bits)) {
202 Debug.DCHECK_EQ(15, type_info_bits.size());
204 for (int i = 0; i < type_info_bits.size(); ++i) {
205 // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in
207 final int bit = type_info_bits.at(type_info_bits.size() - 1 - i);
209 // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
210 final int x1 = kTypeInfoCoordinates[i][0];
211 final int y1 = kTypeInfoCoordinates[i][1];
212 matrix.set(y1, x1, bit);
216 final int x2 = matrix.width() - i - 1;
218 matrix.set(y2, x2, bit);
220 // Left bottom corner.
222 final int y2 = matrix.height() - 7 + (i - 8);
223 matrix.set(y2, x2, bit);
229 // Embed version information if need be. On success, modify the matrix and return true. On error,
230 // return false. See 8.10 of JISX0510:2004 (p.47) for how to embed version information. Return
231 // true on success, otherwise return false.
232 public static boolean MaybeEmbedVersionInfo(int version, Matrix matrix) {
233 if (version < 7) { // Version info is necessary if version >= 7.
234 return true; // Don't need version info.
236 BitVector version_info_bits;
237 if (!MakeVersionInfoBits(version, &version_info_bits)) {
241 Debug.DCHECK_EQ(18, version_info_bits.size());
242 int bit_index = 6 * 3 - 1; // It will decrease from 17 to 0.
243 for (int i = 0; i < 6; ++i) {
244 for (int j = 0; j < 3; ++j) {
245 // Place bits in LSB (least significant bit) to MSB order.
246 final int bit = version_info_bits.at(bit_index--);
247 // Left bottom corner.
248 matrix.set(matrix.height() - 11 + j, i, bit);
249 // Right bottom corner.
250 matrix.set(i, matrix.height() - 11 + j, bit);
256 // Embed "data_bits" using "mask_pattern". On success, modify the matrix and return true. On
257 // error, return false. For debugging purposes, it skips masking process if "mask_pattern" is -1.
258 // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
259 public static boolean EmbedDataBits(final BitVector &data_bits, int mask_pattern, Matrix matrix) {
262 // Start from the right bottom cell.
263 int x = matrix.width() - 1;
264 int y = matrix.height() - 1;
266 // Skip the vertical timing pattern.
270 while (y >= 0 && y < matrix.height()) {
271 for (int i = 0; i < 2; ++i) {
272 final int xx = x - i;
273 // Skip the cell if it's not empty.
274 if (!IsEmpty(matrix.get(y, xx))) {
278 if (bit_index < data_bits.size()) {
279 bit = data_bits.at(bit_index);
282 // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described
283 // in 8.4.9 of JISX0510:2004 (p. 24).
286 Debug.DCHECK(IsValidValue(bit));
288 // Skip masking if mask_pattern is -1.
289 if (mask_pattern != -1) {
290 final int mask = MaskUtil.GetDataMaskBit(mask_pattern, xx, y);
291 Debug.DCHECK(mask == 0 || mask == 1);
294 matrix.set(y, xx, bit);
298 direction = -direction; // Reverse the direction.
300 x -= 2; // Move to the left.
302 // All bits should be consumed.
303 if (bit_index < data_bits.size()) {
304 Debug.LOG_ERROR("Not all bits consumed: " + bit_index + "/" + data_bits.size());
307 Debug.DCHECK_EQ(bit_index, data_bits.size());
311 // Return the position of the most significant bit set (to one) in the "value". The most
312 // significant bit is position 32. If there is no bit set, return 0. Examples:
313 // - FindMSBSet(0) => 0
314 // - FindMSBSet(1) => 1
315 // - FindMSBSet(255) => 8
316 public static int FindMSBSet(uint32 value) {
325 // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
326 // code is used for encoding type information and version information.
327 // Example: Calculation of version information of 7.
328 // f(x) is created from 7.
329 // - 7 = 000111 in 6 bits
330 // - f(x) = x^2 + x^2 + x^1
331 // g(x) is given by the standard (p. 67)
332 // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
333 // Multiply f(x) by x^(18 - 6)
334 // - f'(x) = f(x) * x^(18 - 6)
335 // - f'(x) = x^14 + x^13 + x^12
336 // Calculate the remainder of f'(x) / g(x)
338 // __________________________________________________
339 // g(x) )x^14 + x^13 + x^12
340 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
341 // --------------------------------------------------
342 // x^11 + x^10 + x^7 + x^4 + x^2
344 // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
345 // Encode it in binary: 110010010100
346 // The return value is 0xc94 (1100 1001 0100)
348 // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
349 // operations. We don't care if cofficients are positive or negative.
350 public static uint32 CalculateBCHCode(uint32 value, uint32 poly) {
351 // If poly is "1 1111 0010 0101" (version info poly), msb_set_in_poly is 13. We'll subtract 1
352 // from 13 to make it 12.
353 final int msb_set_in_poly = FindMSBSet(poly);
354 value <<= msb_set_in_poly - 1;
355 // Do the division business using exclusive-or operations.
356 while (FindMSBSet(value) >= msb_set_in_poly) {
357 value ^= poly << (FindMSBSet(value) - msb_set_in_poly);
359 // Now the "value" is the remainder (i.e. the BCH code)
363 // Make bit vector of type information. On success, store the result in "bits" and return true.
364 // On error, return false. Encode error correction level and mask pattern. See 8.9 of
365 // JISX0510:2004 (p.45) for details.
366 public static boolean MakeTypeInfoBits(int ec_level, final int mask_pattern, BitVector *bits) {
367 final int ec_code = QRCode.GetECLevelCode(ec_level);
371 if (!QRCode.IsValidMaskPattern(mask_pattern)) {
374 final uint32 type_info = (ec_code << 3) | mask_pattern;
375 bits.AppendBits(type_info, 5);
377 final uint32 bch_code = MatrixUtil.CalculateBCHCode(type_info,
379 bits.AppendBits(bch_code, 10);
382 mask_bits.AppendBits(kTypeInfoMaskPattern, 15);
385 if (bits.size() != 15) { // Just in case.
386 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
392 // Make bit vector of version information. On success, store the result in "bits" and return true.
393 // On error, return false. See 8.10 of JISX0510:2004 (p.45) for details.
394 public static boolean MakeVersionInfoBits(int version, BitVector *bits) {
395 bits.AppendBits(version, 6);
396 final uint32 bch_code = MatrixUtil.CalculateBCHCode(version,
398 bits.AppendBits(bch_code, 12);
399 if (bits.size() != 18) { // Just in case.
400 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
406 // Check if "value" is empty.
407 private static boolean IsEmpty(final int value) {
411 // Check if "value" is valid.
412 private static boolean IsValidValue(final int value) {
413 return (value == -1 || // Empty.
414 value == 0 || // Light (white).
415 value == 1); // Dark (black).
418 private static void EmbedTimingPatterns(Matrix matrix) {
419 // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical
420 // separation patterns (size 1). Thus, 8 = 7 + 1.
421 for (int i = 8; i < matrix.width() - 8; ++i) {
422 final int bit = (i + 1) % 2;
424 Debug.DCHECK(IsValidValue(matrix.get(6, i)));
425 if (IsEmpty(matrix.get(6, i))) {
426 matrix.set(6, i, bit);
429 Debug.DCHECK(IsValidValue(matrix.get(i, 6)));
430 if (IsEmpty(matrix.get(i, 6))) {
431 matrix.set(i, 6, bit);
436 // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
437 private static void EmbedDarkDotAtLeftBottomCorner(Matrix matrix) {
438 Debug.DCHECK(matrix.get(matrix.height() - 8, 8) != 0);
439 matrix.set(matrix.height() - 8, 8, 1);
442 private static void EmbedHorizontalSeparationPattern(final int x_start, final int y_start,
444 // We know the width and height.
445 Debug.DCHECK_EQ(8, arraysize(kHorizontalSeparationPattern[0]));
446 Debug.DCHECK_EQ(1, arraysize(kHorizontalSeparationPattern));
447 for (int x = 0; x < 8; ++x) {
448 Debug.DCHECK(IsEmpty(matrix.get(y_start, x_start + x)));
449 matrix.set(y_start, x_start + x, kHorizontalSeparationPattern[0][x]);
453 private static void EmbedVerticalSeparationPattern(final int x_start, final int y_start,
455 // We know the width and height.
456 Debug.DCHECK_EQ(1, arraysize(kVerticalSeparationPattern[0]));
457 Debug.DCHECK_EQ(7, arraysize(kVerticalSeparationPattern));
458 for (int y = 0; y < 7; ++y) {
459 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start)));
460 matrix.set(y_start + y, x_start, kVerticalSeparationPattern[y][0]);
464 // Note that we cannot unify the function with EmbedPositionDetectionPattern() despite they are
465 // almost identical, since we cannot write a function that takes 2D arrays in different sizes in
466 // C/C++. We should live with the fact.
467 private static void EmbedPositionAdjustmentPattern(final int x_start, final int y_start,
469 // We know the width and height.
470 Debug.DCHECK_EQ(5, arraysize(kPositionAdjustmentPattern[0]));
471 Debug.DCHECK_EQ(5, arraysize(kPositionAdjustmentPattern));
472 for (int y = 0; y < 5; ++y) {
473 for (int x = 0; x < 5; ++x) {
474 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start + x)));
475 matrix.set(y_start + y, x_start + x, kPositionAdjustmentPattern[y][x]);
480 private static void EmbedPositionDetectionPattern(final int x_start, final int y_start,
482 // We know the width and height.
483 Debug.DCHECK_EQ(7, arraysize(kPositionDetectionPattern[0]));
484 Debug.DCHECK_EQ(7, arraysize(kPositionDetectionPattern));
485 for (int y = 0; y < 7; ++y) {
486 for (int x = 0; x < 7; ++x) {
487 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start + x)));
488 matrix.set(y_start + y, x_start + x, kPositionDetectionPattern[y][x]);
493 // Embed position detection patterns and surrounding vertical/horizontal separators.
494 private static void EmbedPositionDetectionPatternsAndSeparators(Matrix matrix) {
495 // Embed three big squares at corners.
496 final int pdp_width = arraysize(kPositionDetectionPattern[0]);
498 EmbedPositionDetectionPattern(0, 0, matrix);
500 EmbedPositionDetectionPattern(matrix.width() - pdp_width, 0, matrix);
501 // Left bottom corner.
502 EmbedPositionDetectionPattern(0, matrix.width() - pdp_width, matrix);
504 // Embed horizontal separation patterns around the squares.
505 final int hsp_width = arraysize(kHorizontalSeparationPattern[0]);
507 EmbedHorizontalSeparationPattern(0, hsp_width - 1, matrix);
509 EmbedHorizontalSeparationPattern(matrix.width() - hsp_width,
510 hsp_width - 1, matrix);
511 // Left bottom corner.
512 EmbedHorizontalSeparationPattern(0, matrix.width() - hsp_width, matrix);
514 // Embed vertical separation patterns around the squares.
515 final int vsp_height = arraysize(kVerticalSeparationPattern);
517 EmbedVerticalSeparationPattern(vsp_height, 0, matrix);
519 EmbedVerticalSeparationPattern(matrix.height() - vsp_height - 1, 0, matrix);
520 // Left bottom corner.
521 EmbedVerticalSeparationPattern(vsp_height, matrix.height() - vsp_height,
525 // Embed position adjustment patterns if need be.
526 private static void MaybeEmbedPositionAdjustmentPatterns(final int version, Matrix matrix) {
527 if (version < 2) { // The patterns appear if version >= 2
530 final int index = version - 1;
531 final int *coordinates =
532 kPositionAdjustmentPatternCoordinateTable[index];
533 final int num_coordinates =
534 arraysize(kPositionAdjustmentPatternCoordinateTable[index]);
535 for (int i = 0; i < num_coordinates; ++i) {
536 for (int j = 0; j < num_coordinates; ++j) {
537 final int y = coordinates[i];
538 final int x = coordinates[j];
539 if (x == -1 || y == -1) {
542 // If the cell is unset, we embed the position adjustment pattern here.
543 if (IsEmpty(matrix.get(y, x))) {
544 // -2 is necessary since the x/y coordinates point to the center of the pattern, not the
546 EmbedPositionAdjustmentPattern(x - 2, y - 2, matrix);