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.common.ByteMatrix;
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 int kVersionInfoPoly = 0x1f25; // 1 1111 0010 0101
119 // From Appendix C in JISX0510:2004 (p.65).
120 private static final int kTypeInfoPoly = 0x537;
121 private static final int kTypeInfoMaskPattern = 0x5412;
123 // Set all cells to -1. -1 means that the cell is empty (not set yet).
125 // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding
126 // with the ByteMatrix initialized all to zero.
127 public static void ClearMatrix(ByteMatrix matrix) {
128 matrix.clear((byte) -1);
131 // Build 2D matrix of QR Code from "data_bits" with "ec_level", "version" and "mask_pattern". On
132 // success, store the result in "matrix" and return true. On error, return false.
133 public static boolean BuildMatrix(final BitVector data_bits, int ec_level, int version,
134 int mask_pattern, ByteMatrix matrix) {
135 MatrixUtil.ClearMatrix(matrix);
136 if (!EmbedBasicPatterns(version, matrix)) {
139 // Type information appear with any version.
140 if (!EmbedTypeInfo(ec_level, mask_pattern, matrix)) {
143 // Version info appear if version >= 7.
144 if (!MaybeEmbedVersionInfo(version, matrix)) {
147 // Data should be embedded at end.
148 return EmbedDataBits(data_bits, mask_pattern, matrix);
151 // Embed basic patterns. On success, modify the matrix and return true. On error, return false.
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 boolean EmbedBasicPatterns(int version, ByteMatrix matrix) {
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);
170 // Embed type information. On success, modify the matrix and return true. On error, return false.
171 public static boolean EmbedTypeInfo(int ec_level, int mask_pattern, ByteMatrix matrix) {
172 BitVector type_info_bits = new BitVector();
173 if (!MakeTypeInfoBits(ec_level, mask_pattern, type_info_bits)) {
176 Debug.DCHECK_EQ(15, type_info_bits.size());
178 for (int i = 0; i < type_info_bits.size(); ++i) {
179 // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in
181 final int bit = type_info_bits.at(type_info_bits.size() - 1 - i);
183 // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
184 final int x1 = kTypeInfoCoordinates[i][0];
185 final int y1 = kTypeInfoCoordinates[i][1];
186 matrix.set(y1, x1, bit);
190 final int x2 = matrix.width() - i - 1;
192 matrix.set(y2, x2, bit);
194 // Left bottom corner.
196 final int y2 = matrix.height() - 7 + (i - 8);
197 matrix.set(y2, x2, bit);
203 // Embed version information if need be. On success, modify the matrix and return true. On error,
204 // return false. See 8.10 of JISX0510:2004 (p.47) for how to embed version information. Return
205 // true on success, otherwise return false.
206 public static boolean MaybeEmbedVersionInfo(int version, ByteMatrix matrix) {
207 if (version < 7) { // Version info is necessary if version >= 7.
208 return true; // Don't need version info.
210 BitVector version_info_bits = new BitVector();
211 if (!MakeVersionInfoBits(version, version_info_bits)) {
215 Debug.DCHECK_EQ(18, version_info_bits.size());
216 int bit_index = 6 * 3 - 1; // It will decrease from 17 to 0.
217 for (int i = 0; i < 6; ++i) {
218 for (int j = 0; j < 3; ++j) {
219 // Place bits in LSB (least significant bit) to MSB order.
220 final int bit = version_info_bits.at(bit_index);
222 // Left bottom corner.
223 matrix.set(matrix.height() - 11 + j, i, bit);
224 // Right bottom corner.
225 matrix.set(i, matrix.height() - 11 + j, bit);
231 // Embed "data_bits" using "mask_pattern". On success, modify the matrix and return true. On
232 // error, return false. For debugging purposes, it skips masking process if "mask_pattern" is -1.
233 // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
234 public static boolean EmbedDataBits(final BitVector data_bits, int mask_pattern, ByteMatrix matrix) {
237 // Start from the right bottom cell.
238 int x = matrix.width() - 1;
239 int y = matrix.height() - 1;
241 // Skip the vertical timing pattern.
245 while (y >= 0 && y < matrix.height()) {
246 for (int i = 0; i < 2; ++i) {
247 final int xx = x - i;
248 // Skip the cell if it's not empty.
249 if (!IsEmpty(matrix.get(y, xx))) {
253 if (bit_index < data_bits.size()) {
254 bit = data_bits.at(bit_index);
257 // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described
258 // in 8.4.9 of JISX0510:2004 (p. 24).
261 Debug.DCHECK(IsValidValue(bit));
263 // Skip masking if mask_pattern is -1.
264 if (mask_pattern != -1) {
265 final int mask = MaskUtil.GetDataMaskBit(mask_pattern, xx, y);
266 Debug.DCHECK(mask == 0 || mask == 1);
269 matrix.set(y, xx, bit);
273 direction = -direction; // Reverse the direction.
275 x -= 2; // Move to the left.
277 // All bits should be consumed.
278 if (bit_index < data_bits.size()) {
279 Debug.LOG_ERROR("Not all bits consumed: " + bit_index + "/" + data_bits.size());
282 Debug.DCHECK_EQ(bit_index, data_bits.size());
286 // Return the position of the most significant bit set (to one) in the "value". The most
287 // significant bit is position 32. If there is no bit set, return 0. Examples:
288 // - FindMSBSet(0) => 0
289 // - FindMSBSet(1) => 1
290 // - FindMSBSet(255) => 8
291 public static int FindMSBSet(int value) {
300 // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
301 // code is used for encoding type information and version information.
302 // Example: Calculation of version information of 7.
303 // f(x) is created from 7.
304 // - 7 = 000111 in 6 bits
305 // - f(x) = x^2 + x^2 + x^1
306 // g(x) is given by the standard (p. 67)
307 // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
308 // Multiply f(x) by x^(18 - 6)
309 // - f'(x) = f(x) * x^(18 - 6)
310 // - f'(x) = x^14 + x^13 + x^12
311 // Calculate the remainder of f'(x) / g(x)
313 // __________________________________________________
314 // g(x) )x^14 + x^13 + x^12
315 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
316 // --------------------------------------------------
317 // x^11 + x^10 + x^7 + x^4 + x^2
319 // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
320 // Encode it in binary: 110010010100
321 // The return value is 0xc94 (1100 1001 0100)
323 // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
324 // operations. We don't care if cofficients are positive or negative.
325 public static int CalculateBCHCode(int value, int poly) {
326 // If poly is "1 1111 0010 0101" (version info poly), msb_set_in_poly is 13. We'll subtract 1
327 // from 13 to make it 12.
328 final int msb_set_in_poly = FindMSBSet(poly);
329 value <<= msb_set_in_poly - 1;
330 // Do the division business using exclusive-or operations.
331 while (FindMSBSet(value) >= msb_set_in_poly) {
332 value ^= poly << (FindMSBSet(value) - msb_set_in_poly);
334 // Now the "value" is the remainder (i.e. the BCH code)
338 // Make bit vector of type information. On success, store the result in "bits" and return true.
339 // On error, return false. Encode error correction level and mask pattern. See 8.9 of
340 // JISX0510:2004 (p.45) for details.
341 public static boolean MakeTypeInfoBits(int ec_level, final int mask_pattern, BitVector bits) {
342 final int ec_code = QRCode.GetECLevelCode(ec_level);
346 if (!QRCode.IsValidMaskPattern(mask_pattern)) {
349 final int type_info = (ec_code << 3) | mask_pattern;
350 bits.AppendBits(type_info, 5);
352 final int bch_code = MatrixUtil.CalculateBCHCode(type_info, kTypeInfoPoly);
353 bits.AppendBits(bch_code, 10);
355 BitVector mask_bits = new BitVector();
356 mask_bits.AppendBits(kTypeInfoMaskPattern, 15);
359 if (bits.size() != 15) { // Just in case.
360 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
366 // Make bit vector of version information. On success, store the result in "bits" and return true.
367 // On error, return false. See 8.10 of JISX0510:2004 (p.45) for details.
368 public static boolean MakeVersionInfoBits(int version, BitVector bits) {
369 bits.AppendBits(version, 6);
370 final int bch_code = MatrixUtil.CalculateBCHCode(version, kVersionInfoPoly);
371 bits.AppendBits(bch_code, 12);
373 if (bits.size() != 18) { // Just in case.
374 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
380 // Check if "value" is empty.
381 private static boolean IsEmpty(final int value) {
385 // Check if "value" is valid.
386 private static boolean IsValidValue(final int value) {
387 return (value == -1 || // Empty.
388 value == 0 || // Light (white).
389 value == 1); // Dark (black).
392 private static void EmbedTimingPatterns(ByteMatrix matrix) {
393 // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical
394 // separation patterns (size 1). Thus, 8 = 7 + 1.
395 for (int i = 8; i < matrix.width() - 8; ++i) {
396 final int bit = (i + 1) % 2;
398 Debug.DCHECK(IsValidValue(matrix.get(6, i)));
399 if (IsEmpty(matrix.get(6, i))) {
400 matrix.set(6, i, bit);
403 Debug.DCHECK(IsValidValue(matrix.get(i, 6)));
404 if (IsEmpty(matrix.get(i, 6))) {
405 matrix.set(i, 6, bit);
410 // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
411 private static void EmbedDarkDotAtLeftBottomCorner(ByteMatrix matrix) {
412 Debug.DCHECK(matrix.get(matrix.height() - 8, 8) != 0);
413 matrix.set(matrix.height() - 8, 8, 1);
416 private static void EmbedHorizontalSeparationPattern(final int x_start, final int y_start,
418 // We know the width and height.
419 Debug.DCHECK_EQ(8, kHorizontalSeparationPattern[0].length);
420 Debug.DCHECK_EQ(1, kHorizontalSeparationPattern.length);
421 for (int x = 0; x < 8; ++x) {
422 Debug.DCHECK(IsEmpty(matrix.get(y_start, x_start + x)));
423 matrix.set(y_start, x_start + x, kHorizontalSeparationPattern[0][x]);
427 private static void EmbedVerticalSeparationPattern(final int x_start, final int y_start,
429 // We know the width and height.
430 Debug.DCHECK_EQ(1, kVerticalSeparationPattern[0].length);
431 Debug.DCHECK_EQ(7, kVerticalSeparationPattern.length);
432 for (int y = 0; y < 7; ++y) {
433 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start)));
434 matrix.set(y_start + y, x_start, kVerticalSeparationPattern[y][0]);
438 // Note that we cannot unify the function with EmbedPositionDetectionPattern() despite they are
439 // almost identical, since we cannot write a function that takes 2D arrays in different sizes in
440 // C/C++. We should live with the fact.
441 private static void EmbedPositionAdjustmentPattern(final int x_start, final int y_start,
443 // We know the width and height.
444 Debug.DCHECK_EQ(5, kPositionAdjustmentPattern[0].length);
445 Debug.DCHECK_EQ(5, kPositionAdjustmentPattern.length);
446 for (int y = 0; y < 5; ++y) {
447 for (int x = 0; x < 5; ++x) {
448 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start + x)));
449 matrix.set(y_start + y, x_start + x, kPositionAdjustmentPattern[y][x]);
454 private static void EmbedPositionDetectionPattern(final int x_start, final int y_start,
456 // We know the width and height.
457 Debug.DCHECK_EQ(7, kPositionDetectionPattern[0].length);
458 Debug.DCHECK_EQ(7, kPositionDetectionPattern.length);
459 for (int y = 0; y < 7; ++y) {
460 for (int x = 0; x < 7; ++x) {
461 Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start + x)));
462 matrix.set(y_start + y, x_start + x, kPositionDetectionPattern[y][x]);
467 // Embed position detection patterns and surrounding vertical/horizontal separators.
468 private static void EmbedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) {
469 // Embed three big squares at corners.
470 final int pdp_width = kPositionDetectionPattern[0].length;
472 EmbedPositionDetectionPattern(0, 0, matrix);
474 EmbedPositionDetectionPattern(matrix.width() - pdp_width, 0, matrix);
475 // Left bottom corner.
476 EmbedPositionDetectionPattern(0, matrix.width() - pdp_width, matrix);
478 // Embed horizontal separation patterns around the squares.
479 final int hsp_width = kHorizontalSeparationPattern[0].length;
481 EmbedHorizontalSeparationPattern(0, hsp_width - 1, matrix);
483 EmbedHorizontalSeparationPattern(matrix.width() - hsp_width,
484 hsp_width - 1, matrix);
485 // Left bottom corner.
486 EmbedHorizontalSeparationPattern(0, matrix.width() - hsp_width, matrix);
488 // Embed vertical separation patterns around the squares.
489 final int vsp_size = kVerticalSeparationPattern.length;
491 EmbedVerticalSeparationPattern(vsp_size, 0, matrix);
493 EmbedVerticalSeparationPattern(matrix.height() - vsp_size - 1, 0, matrix);
494 // Left bottom corner.
495 EmbedVerticalSeparationPattern(vsp_size, matrix.height() - vsp_size,
499 // Embed position adjustment patterns if need be.
500 private static void MaybeEmbedPositionAdjustmentPatterns(final int version, ByteMatrix matrix) {
501 if (version < 2) { // The patterns appear if version >= 2
504 final int index = version - 1;
505 final int[] coordinates = kPositionAdjustmentPatternCoordinateTable[index];
506 final int num_coordinates = kPositionAdjustmentPatternCoordinateTable[index].length;
507 for (int i = 0; i < num_coordinates; ++i) {
508 for (int j = 0; j < num_coordinates; ++j) {
509 final int y = coordinates[i];
510 final 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(y, x))) {
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);