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,
160 QRCode.ECLevel ec_level,
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(QRCode.ECLevel ec_level,
204 QRCodeMatrix *matrix) {
205 BitVector type_info_bits;
206 if (!MakeTypeInfoBits(ec_level, mask_pattern, &type_info_bits)) {
209 Debug.DCHECK_EQ(15, type_info_bits.size());
211 for (int i = 0; i < type_info_bits.size(); ++i) {
212 // Place bits in LSB to MSB order. LSB (least significant bit)
213 // is the last value in "type_info_bits".
214 final int bit = type_info_bits.at(type_info_bits.size() - 1 - i);
216 // Type info bits at the left top corner.
217 // See 8.9 of JISX0510:2004 (p.46).
218 final int x1 = kTypeInfoCoordinates[i][0];
219 final int y1 = kTypeInfoCoordinates[i][1];
220 (*matrix)(y1, x1) = bit;
224 final int x2 = matrix.width() - i - 1;
226 (*matrix)(y2, x2) = bit;
228 // Left bottom corner.
230 final int y2 = matrix.height() - 7 + (i - 8);
231 (*matrix)(y2, x2) = bit;
237 // Embed version information if need be. On success, modify the
238 // matrix and return true. On error, return false.
239 // See 8.10 of JISX0510:2004 (p.47) for how to embed version
240 // information. Return true on success. Return false otherwise.
241 public static boolean MaybeEmbedVersionInfo(int version,
242 QRCodeMatrix *matrix) {
243 if (version < 7) { // Version info is necessary if version >= 7.
244 return true; // Don't need version info.
246 BitVector version_info_bits;
247 if (!MakeVersionInfoBits(version, &version_info_bits)) {
251 Debug.DCHECK_EQ(18, version_info_bits.size());
252 int bit_index = 6 * 3 - 1; // It will decrease from 17 to 0.
253 for (int i = 0; i < 6; ++i) {
254 for (int j = 0; j < 3; ++j) {
255 // Place bits in LSB (least significant bit) to MSB order.
256 final int bit = version_info_bits.at(bit_index--);
257 // Left bottom corner.
258 (*matrix)(matrix.height() - 11 + j, i) = bit;
259 // Right bottom corner.
260 (*matrix)(i, matrix.height() - 11 + j) = bit;
266 // Embed "data_bits" using "mask_pattern". On success, modify the
267 // matrix and return true. On error, return false. For debugging
268 // purpose, it skips masking process if "mask_pattern" is -1.
269 // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
270 public static boolean EmbedDataBits(final BitVector &data_bits,
272 QRCodeMatrix *matrix) {
275 // Start from the right bottom cell.
276 int x = matrix.width() - 1;
277 int y = matrix.height() - 1;
279 // Skip the vertical timing pattern.
283 while (y >= 0 && y < matrix.height()) {
284 for (int i = 0; i < 2; ++i) {
285 final int xx = x - i;
286 // Skip the cell if it's not empty.
287 if (!IsEmpty((*matrix)(y, xx))) {
291 if (bit_index < data_bits.size()) {
292 bit = data_bits.at(bit_index);
295 // Padding bit. If there is no bit left, we'll fill the
296 // left cells with 0, as described in 8.4.9 of
297 // JISX0510:2004 (p. 24).
300 Debug.DCHECK(IsValidValue(bit));
302 // Skip masking if mask_pattern is -1.
303 if (mask_pattern != -1) {
304 final int mask = MaskUtil.GetDataMaskBit(mask_pattern, xx, y);
305 Debug.DCHECK(mask == 0 || mask == 1);
308 (*matrix)(y, xx) = bit;
312 direction = -direction; // Reverse the direction.
314 x -= 2; // Move to the left.
316 // All bits should be consumed.
317 if (bit_index < data_bits.size()) {
318 Debug.LOG_ERROR("Not all bits consumed: " + bit_index + "/" + data_bits.size());
321 Debug.DCHECK_EQ(bit_index, data_bits.size());
325 // Return the position of the most significant bit set (to one) in
326 // the "value". The most significant bit is position 32. If there
327 // is no bit set, return 0.
329 // - FindMSBSet(0) => 0
330 // - FindMSBSet(1) => 1
331 // - FindMSBSet(255) => 8
332 public static int FindMSBSet(uint32 value) {
341 // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using
342 // polynomial "poly". The BCH code is used for encoding type
343 // information and version information.
344 // Example: Calculation of version information of 7.
345 // f(x) is created from 7.
346 // - 7 = 000111 in 6 bits
347 // - f(x) = x^2 + x^2 + x^1
348 // g(x) is given by the standard (p. 67)
349 // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
350 // Multiply f(x) by x^(18 - 6)
351 // - f'(x) = f(x) * x^(18 - 6)
352 // - f'(x) = x^14 + x^13 + x^12
353 // Calculate the remainder of f'(x) / g(x)
355 // __________________________________________________
356 // g(x) )x^14 + x^13 + x^12
357 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
358 // --------------------------------------------------
359 // x^11 + x^10 + x^7 + x^4 + x^2
361 // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
362 // Encode it in binary: 110010010100
363 // The return value is 0xc94 (1100 1001 0100)
365 // Since all coefficients in the polynomials are 1 or 0, we can do the
366 // calculation by bit operations. We don't care if cofficients are
367 // positive or nagative.
368 public static uint32 CalculateBCHCode(uint32 value, uint32 poly) {
369 // If poly is "1 1111 0010 0101" (version info poly),
370 // msb_set_in_poly is 13. We'll subtract 1 from 13 to make it 12.
371 final int msb_set_in_poly = FindMSBSet(poly);
372 value <<= msb_set_in_poly - 1;
373 // Do the division business using exclusive-or operations.
374 while (FindMSBSet(value) >= msb_set_in_poly) {
375 value ^= poly << (FindMSBSet(value) - msb_set_in_poly);
377 // Now the "value" is the remainder (i.e. the BCH code)
381 // Make bit vector of type information. On success, store the
382 // result in "bits" and return true. On error, return false.
383 // Encode error correction level and mask pattern. See 8.9 of
384 // JISX0510:2004 (p.45) for details.
385 public static boolean MakeTypeInfoBits(QRCode.ECLevel ec_level,
386 final int mask_pattern,
388 final int ec_code = QRCode.GetECLevelCode(ec_level);
392 if (!QRCode.IsValidMaskPattern(mask_pattern)) {
395 final uint32 type_info = (ec_code << 3) | mask_pattern;
396 bits.AppendBits(type_info, 5);
398 final uint32 bch_code = MatrixUtil.CalculateBCHCode(type_info,
400 bits.AppendBits(bch_code, 10);
403 mask_bits.AppendBits(kTypeInfoMaskPattern, 15);
406 if (bits.size() != 15) { // Just in case.
407 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
413 // Make bit vector of version information. On success, store the
414 // result in "bits" and return true. On error, return false.
415 // Encode version information. See 8.10 of JISX0510:2004 (p.45) for
417 public static boolean MakeVersionInfoBits(int version, BitVector *bits) {
418 bits.AppendBits(version, 6);
419 final uint32 bch_code = MatrixUtil.CalculateBCHCode(version,
421 bits.AppendBits(bch_code, 12);
422 if (bits.size() != 18) { // Just in case.
423 Debug.LOG_ERROR("should not happen but we got: " + bits.size());
429 // Check if "value" is empty.
430 private static boolean IsEmpty(final int value) {
434 // Check if "value" is valid.
435 private static boolean IsValidValue(final int value) {
436 return (value == -1 || // Empty.
437 value == 0 || // Light (white).
438 value == 1); // Dark (black).
441 private static void EmbedTimingPatterns(QRCodeMatrix *matrix) {
442 // -8 is for skipping position detection patterns (size 7), and
443 // two horizontal/vertical separation patterns (size 1).
445 for (int i = 8; i < matrix.width() - 8; ++i) {
446 final int bit = (i + 1) % 2;
448 Debug.DCHECK(IsValidValue((*matrix)(6, i)));
449 if (IsEmpty((*matrix)(6, i))) {
450 (*matrix)(6, i) = bit;
453 Debug.DCHECK(IsValidValue((*matrix)(i, 6)));
454 if (IsEmpty((*matrix)(i, 6))) {
455 (*matrix)(i, 6) = bit;
460 // Embed the lonely dark dot at left bottom corner.
461 // JISX0510:2004 (p.46)
462 private static void EmbedDarkDotAtLeftBottomCorner(
463 QRCodeMatrix *matrix) {
464 Debug.DCHECK((*matrix)(matrix.height() - 8, 8));
465 (*matrix)(matrix.height() - 8, 8) = 1;
468 private static void EmbedHorizontalSeparationPattern(final int x_start,
470 QRCodeMatrix *matrix) {
471 // We know the width and height.
472 Debug.DCHECK_EQ(8, arraysize(kHorizontalSeparationPattern[0]));
473 Debug.DCHECK_EQ(1, arraysize(kHorizontalSeparationPattern));
474 for (int x = 0; x < 8; ++x) {
475 Debug.DCHECK(IsEmpty((*matrix)(y_start, x_start + x)));
476 (*matrix)(y_start, x_start + x) = kHorizontalSeparationPattern[0][x];
480 private static void EmbedVerticalSeparationPattern(final int x_start,
482 QRCodeMatrix *matrix) {
483 // We know the width and height.
484 Debug.DCHECK_EQ(1, arraysize(kVerticalSeparationPattern[0]));
485 Debug.DCHECK_EQ(7, arraysize(kVerticalSeparationPattern));
486 for (int y = 0; y < 7; ++y) {
487 Debug.DCHECK(IsEmpty((*matrix)(y_start + y, x_start)));
488 (*matrix)(y_start + y, x_start) = kVerticalSeparationPattern[y][0];
492 // Note that we cannot unify the function with
493 // EmbedPositionDetectionPattern() despite they are almost
494 // identical, since we cannot write a function that takes 2D arrays
495 // in different sizes in C/C++. We should live with the fact.
496 private static void EmbedPositionAdjustmentPattern(final int x_start,
498 QRCodeMatrix *matrix) {
499 // We know the width and height.
500 Debug.DCHECK_EQ(5, arraysize(kPositionAdjustmentPattern[0]));
501 Debug.DCHECK_EQ(5, arraysize(kPositionAdjustmentPattern));
502 for (int y = 0; y < 5; ++y) {
503 for (int x = 0; x < 5; ++x) {
504 Debug.DCHECK(IsEmpty((*matrix)(y_start + y, x_start + x)));
505 (*matrix)(y_start + y, x_start + x) =
506 kPositionAdjustmentPattern[y][x];
511 private static void EmbedPositionDetectionPattern(final int x_start,
513 QRCodeMatrix *matrix) {
514 // We know the width and height.
515 Debug.DCHECK_EQ(7, arraysize(kPositionDetectionPattern[0]));
516 Debug.DCHECK_EQ(7, arraysize(kPositionDetectionPattern));
517 for (int y = 0; y < 7; ++y) {
518 for (int x = 0; x < 7; ++x) {
519 Debug.DCHECK(IsEmpty((*matrix)(y_start + y, x_start + x)));
520 (*matrix)(y_start + y, x_start + x) =
521 kPositionDetectionPattern[y][x];
526 // Embed position detection patterns and surrounding
527 // vertical/horizontal separators.
528 private static void EmbedPositionDetectionPatternsAndSeparators(QRCodeMatrix *matrix) {
529 // Embed three big squares at corners.
530 final int pdp_width = arraysize(kPositionDetectionPattern[0]);
532 EmbedPositionDetectionPattern(0, 0, matrix);
534 EmbedPositionDetectionPattern(matrix.width() - pdp_width, 0, matrix);
535 // Left bottom corner.
536 EmbedPositionDetectionPattern(0, matrix.width() - pdp_width, matrix);
538 // Embed horizontal separation patterns around the squares.
539 final int hsp_width = arraysize(kHorizontalSeparationPattern[0]);
541 EmbedHorizontalSeparationPattern(0, hsp_width - 1, matrix);
543 EmbedHorizontalSeparationPattern(matrix.width() - hsp_width,
544 hsp_width - 1, matrix);
545 // Left bottom corner.
546 EmbedHorizontalSeparationPattern(0, matrix.width() - hsp_width, matrix);
548 // Embed vertical separation patterns around the squares.
549 final int vsp_height = arraysize(kVerticalSeparationPattern);
551 EmbedVerticalSeparationPattern(vsp_height, 0, matrix);
553 EmbedVerticalSeparationPattern(matrix.height() - vsp_height - 1, 0, matrix);
554 // Left bottom corner.
555 EmbedVerticalSeparationPattern(vsp_height, matrix.height() - vsp_height,
559 // Embed position adjustment patterns if need be.
560 private static void MaybeEmbedPositionAdjustmentPatterns(final int version,
561 QRCodeMatrix *matrix) {
562 if (version < 2) { // The patterns appear if version >= 2
565 final int index = version - 1;
566 final int *coordinates =
567 kPositionAdjustmentPatternCoordinateTable[index];
568 final int num_coordinates =
569 arraysize(kPositionAdjustmentPatternCoordinateTable[index]);
570 for (int i = 0; i < num_coordinates; ++i) {
571 for (int j = 0; j < num_coordinates; ++j) {
572 final int y = coordinates[i];
573 final int x = coordinates[j];
574 if (x == -1 || y == -1) {
577 // If the cell is unset, we embed the position adjustment
579 if (IsEmpty((*matrix)(y, x))) {
580 // -2 is necessary since the x/y coordinates point to the
581 // center of the pattern, not the left top corner.
582 EmbedPositionAdjustmentPattern(x - 2, y - 2, matrix);