Got MatrixUtil to compile, and refactored some methods out of it, and into Matrix...
[zxing.git] / core / src / com / google / zxing / qrcode / encoder / MatrixUtil.java
1 /*
2  * Copyright 2008 ZXing authors
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.qrcode.encoder;
18
19 /**
20  * @author satorux@google.com (Satoru Takabayashi) - creator
21  * @author dswitkin@google.com (Daniel Switkin) - ported from C++
22  */
23 public final class MatrixUtil {
24
25   private static final int kPositionDetectionPattern[][] =  {
26       {1, 1, 1, 1, 1, 1, 1},
27       {1, 0, 0, 0, 0, 0, 1},
28       {1, 0, 1, 1, 1, 0, 1},
29       {1, 0, 1, 1, 1, 0, 1},
30       {1, 0, 1, 1, 1, 0, 1},
31       {1, 0, 0, 0, 0, 0, 1},
32       {1, 1, 1, 1, 1, 1, 1},
33   };
34
35   private static final int kHorizontalSeparationPattern[][] = {
36       {0, 0, 0, 0, 0, 0, 0, 0},
37   };
38
39   private static final int kVerticalSeparationPattern[][] = {
40       {0}, {0}, {0}, {0}, {0}, {0}, {0},
41   };
42
43   private static final int kPositionAdjustmentPattern[][] = {
44       {1, 1, 1, 1, 1},
45       {1, 0, 0, 0, 1},
46       {1, 0, 1, 0, 1},
47       {1, 0, 0, 0, 1},
48       {1, 1, 1, 1, 1},
49   };
50
51   // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu.
52   private static final int kPositionAdjustmentPatternCoordinateTable[][] = {
53       {-1, -1, -1, -1,  -1,  -1,  -1},  // Version 1
54       { 6, 18, -1, -1,  -1,  -1,  -1},  // Version 2
55       { 6, 22, -1, -1,  -1,  -1,  -1},  // Version 3
56       { 6, 26, -1, -1,  -1,  -1,  -1},  // Version 4
57       { 6, 30, -1, -1,  -1,  -1,  -1},  // Version 5
58       { 6, 34, -1, -1,  -1,  -1,  -1},  // Version 6
59       { 6, 22, 38, -1,  -1,  -1,  -1},  // Version 7
60       { 6, 24, 42, -1,  -1,  -1,  -1},  // Version 8
61       { 6, 26, 46, -1,  -1,  -1,  -1},  // Version 9
62       { 6, 28, 50, -1,  -1,  -1,  -1},  // Version 10
63       { 6, 30, 54, -1,  -1,  -1,  -1},  // Version 11
64       { 6, 32, 58, -1,  -1,  -1,  -1},  // Version 12
65       { 6, 34, 62, -1,  -1,  -1,  -1},  // Version 13
66       { 6, 26, 46, 66,  -1,  -1,  -1},  // Version 14
67       { 6, 26, 48, 70,  -1,  -1,  -1},  // Version 15
68       { 6, 26, 50, 74,  -1,  -1,  -1},  // Version 16
69       { 6, 30, 54, 78,  -1,  -1,  -1},  // Version 17
70       { 6, 30, 56, 82,  -1,  -1,  -1},  // Version 18
71       { 6, 30, 58, 86,  -1,  -1,  -1},  // Version 19
72       { 6, 34, 62, 90,  -1,  -1,  -1},  // Version 20
73       { 6, 28, 50, 72,  94,  -1,  -1},  // Version 21
74       { 6, 26, 50, 74,  98,  -1,  -1},  // Version 22
75       { 6, 30, 54, 78, 102,  -1,  -1},  // Version 23
76       { 6, 28, 54, 80, 106,  -1,  -1},  // Version 24
77       { 6, 32, 58, 84, 110,  -1,  -1},  // Version 25
78       { 6, 30, 58, 86, 114,  -1,  -1},  // Version 26
79       { 6, 34, 62, 90, 118,  -1,  -1},  // Version 27
80       { 6, 26, 50, 74,  98, 122,  -1},  // Version 28
81       { 6, 30, 54, 78, 102, 126,  -1},  // Version 29
82       { 6, 26, 52, 78, 104, 130,  -1},  // Version 30
83       { 6, 30, 56, 82, 108, 134,  -1},  // Version 31
84       { 6, 34, 60, 86, 112, 138,  -1},  // Version 32
85       { 6, 30, 58, 86, 114, 142,  -1},  // Version 33
86       { 6, 34, 62, 90, 118, 146,  -1},  // Version 34
87       { 6, 30, 54, 78, 102, 126, 150},  // Version 35
88       { 6, 24, 50, 76, 102, 128, 154},  // Version 36
89       { 6, 28, 54, 80, 106, 132, 158},  // Version 37
90       { 6, 32, 58, 84, 110, 136, 162},  // Version 38
91       { 6, 26, 54, 82, 110, 138, 166},  // Version 39
92       { 6, 30, 58, 86, 114, 142, 170},  // Version 40
93   };
94
95   // Type info cells at the left top corner.
96   private static int kTypeInfoCoordinates[][] = {
97       {8, 0},
98       {8, 1},
99       {8, 2},
100       {8, 3},
101       {8, 4},
102       {8, 5},
103       {8, 7},
104       {8, 8},
105       {7, 8},
106       {5, 8},
107       {4, 8},
108       {3, 8},
109       {2, 8},
110       {1, 8},
111       {0, 8},
112   };
113
114   // From Appendix D in JISX0510:2004 (p. 67)
115   private static final int kVersionInfoPoly = 0x1f25;  // 1 1111 0010 0101
116
117   // From Appendix C in JISX0510:2004 (p.65).
118   private static final int kTypeInfoPoly = 0x537;
119   private static final int kTypeInfoMaskPattern = 0x5412;
120
121   // Set all cells to -1.  -1 means that the cell is empty (not set yet).
122   //
123   // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding
124   // with the Matrix initialized all to zero.
125   public static void ClearMatrix(Matrix matrix) {
126     matrix.clear((byte) -1);
127   }
128
129   // Build 2D matrix of QR Code from "data_bits" with "ec_level", "version" and "mask_pattern". On
130   // success, store the result in "matrix" and return true.  On error, return false.
131   public static boolean BuildMatrix(final BitVector data_bits, int ec_level, int version,
132       int mask_pattern, Matrix matrix) {
133     MatrixUtil.ClearMatrix(matrix);
134     if (!EmbedBasicPatterns(version, matrix)) {
135       return false;
136     }
137     // Type information appear with any version.
138     if (!EmbedTypeInfo(ec_level, mask_pattern, matrix)) {
139       return false;
140     }
141     // Version info appear if version >= 7.
142     if (!MaybeEmbedVersionInfo(version, matrix)) {
143       return false;
144     }
145     // Data should be embedded at end.
146     return EmbedDataBits(data_bits, mask_pattern, matrix);
147   }
148
149   // Embed basic patterns. On success, modify the matrix and return true. On error, return false.
150   // The basic patterns are:
151   // - Position detection patterns
152   // - Timing patterns
153   // - Dark dot at the left bottom corner
154   // - Position adjustment patterns, if need be
155   public static boolean EmbedBasicPatterns(int version, Matrix matrix) {
156     // Let's get started with embedding big squares at corners.
157     EmbedPositionDetectionPatternsAndSeparators(matrix);
158     // Then, embed the dark dot at the left bottom corner.
159     EmbedDarkDotAtLeftBottomCorner(matrix);
160
161     // Position adjustment patterns appear if version >= 2.
162     MaybeEmbedPositionAdjustmentPatterns(version, matrix);
163     // Timing patterns should be embedded after position adj. patterns.
164     EmbedTimingPatterns(matrix);
165     return true;
166   }
167
168   // Embed type information. On success, modify the matrix and return true. On error, return false.
169   public static boolean EmbedTypeInfo(int ec_level, int mask_pattern, Matrix matrix) {
170     BitVector type_info_bits = new BitVector();
171     if (!MakeTypeInfoBits(ec_level, mask_pattern, type_info_bits)) {
172       return false;
173     }
174     Debug.DCHECK_EQ(15, type_info_bits.size());
175
176     for (int i = 0; i < type_info_bits.size(); ++i) {
177       // Place bits in LSB to MSB order.  LSB (least significant bit) is the last value in
178       // "type_info_bits".
179       final int bit = type_info_bits.at(type_info_bits.size() - 1 - i);
180
181       // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
182       final int x1 = kTypeInfoCoordinates[i][0];
183       final int y1 = kTypeInfoCoordinates[i][1];
184       matrix.set(y1, x1, bit);
185
186       if (i < 8) {
187         // Right top corner.
188         final int x2 = matrix.width() - i - 1;
189         final int y2 = 8;
190         matrix.set(y2, x2, bit);
191       } else {
192         // Left bottom corner.
193         final int x2 = 8;
194         final int y2 = matrix.height() - 7 + (i - 8);
195         matrix.set(y2, x2, bit);
196       }
197     }
198     return true;
199   }
200
201   // Embed version information if need be. On success, modify the matrix and return true. On error,
202   // return false. See 8.10 of JISX0510:2004 (p.47) for how to embed version information. Return
203   // true on success, otherwise return false.
204   public static boolean MaybeEmbedVersionInfo(int version, Matrix matrix) {
205     if (version < 7) {  // Version info is necessary if version >= 7.
206       return true;  // Don't need version info.
207     }
208     BitVector version_info_bits = new BitVector();
209     if (!MakeVersionInfoBits(version, version_info_bits)) {
210     return false;
211   }
212
213     Debug.DCHECK_EQ(18, version_info_bits.size());
214     int bit_index = 6 * 3 - 1;  // It will decrease from 17 to 0.
215     for (int i = 0; i < 6; ++i) {
216       for (int j = 0; j < 3; ++j) {
217         // Place bits in LSB (least significant bit) to MSB order.
218         final int bit = version_info_bits.at(bit_index);
219         bit_index--;
220         // Left bottom corner.
221         matrix.set(matrix.height() - 11 + j, i, bit);
222         // Right bottom corner.
223         matrix.set(i, matrix.height() - 11 + j, bit);
224       }
225     }
226     return true;
227   }
228
229   // Embed "data_bits" using "mask_pattern". On success, modify the matrix and return true. On
230   // error, return false. For debugging purposes, it skips masking process if "mask_pattern" is -1.
231   // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
232   public static boolean EmbedDataBits(final BitVector data_bits, int mask_pattern, Matrix matrix) {
233     int bit_index = 0;
234     int direction = -1;
235     // Start from the right bottom cell.
236     int x = matrix.width() - 1;
237     int y = matrix.height() - 1;
238     while (x > 0) {
239       // Skip the vertical timing pattern.
240       if (x == 6) {
241         x -= 1;
242       }
243       while (y >= 0 && y < matrix.height()) {
244         for (int i = 0; i < 2; ++i) {
245           final int xx = x - i;
246           // Skip the cell if it's not empty.
247           if (!IsEmpty(matrix.get(y, xx))) {
248             continue;
249           }
250           int bit = -1;
251           if (bit_index < data_bits.size()) {
252             bit = data_bits.at(bit_index);
253             ++bit_index;
254           } else {
255             // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described
256             // in 8.4.9 of JISX0510:2004 (p. 24).
257             bit = 0;
258           }
259           Debug.DCHECK(IsValidValue(bit));
260
261           // Skip masking if mask_pattern is -1.
262           if (mask_pattern != -1) {
263             final int mask = MaskUtil.GetDataMaskBit(mask_pattern, xx, y);
264             Debug.DCHECK(mask == 0 || mask == 1);
265             bit ^= mask;
266           }
267           matrix.set(y, xx, bit);
268         }
269         y += direction;
270       }
271       direction = -direction;  // Reverse the direction.
272       y += direction;
273       x -= 2;  // Move to the left.
274     }
275     // All bits should be consumed.
276     if (bit_index < data_bits.size()) {
277       Debug.LOG_ERROR("Not all bits consumed: " + bit_index + "/" + data_bits.size());
278       return false;
279     }
280     Debug.DCHECK_EQ(bit_index, data_bits.size());
281     return true;
282   }
283
284   // Return the position of the most significant bit set (to one) in the "value". The most
285   // significant bit is position 32. If there is no bit set, return 0. Examples:
286   // - FindMSBSet(0) => 0
287   // - FindMSBSet(1) => 1
288   // - FindMSBSet(255) => 8
289   public static int FindMSBSet(int value) {
290     int num_digits = 0;
291     while (value != 0) {
292       value >>= 1;
293       ++num_digits;
294     }
295     return num_digits;
296   }
297
298   // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
299   // code is used for encoding type information and version information.
300   // Example: Calculation of version information of 7.
301   // f(x) is created from 7.
302   //   - 7 = 000111 in 6 bits
303   //   - f(x) = x^2 + x^2 + x^1
304   // g(x) is given by the standard (p. 67)
305   //   - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
306   // Multiply f(x) by x^(18 - 6)
307   //   - f'(x) = f(x) * x^(18 - 6)
308   //   - f'(x) = x^14 + x^13 + x^12
309   // Calculate the remainder of f'(x) / g(x)
310   //         x^2
311   //         __________________________________________________
312   //   g(x) )x^14 + x^13 + x^12
313   //         x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
314   //         --------------------------------------------------
315   //                              x^11 + x^10 + x^7 + x^4 + x^2
316   //
317   // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
318   // Encode it in binary: 110010010100
319   // The return value is 0xc94 (1100 1001 0100)
320   //
321   // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
322   // operations. We don't care if cofficients are positive or negative.
323   public static int CalculateBCHCode(int value, int poly) {
324     // If poly is "1 1111 0010 0101" (version info poly), msb_set_in_poly is 13. We'll subtract 1
325     // from 13 to make it 12.
326     final int msb_set_in_poly = FindMSBSet(poly);
327     value <<= msb_set_in_poly - 1;
328     // Do the division business using exclusive-or operations.
329     while (FindMSBSet(value) >= msb_set_in_poly) {
330       value ^= poly << (FindMSBSet(value) - msb_set_in_poly);
331     }
332     // Now the "value" is the remainder (i.e. the BCH code)
333     return value;
334   }
335
336   // Make bit vector of type information. On success, store the result in "bits" and return true.
337   // On error, return false. Encode error correction level and mask pattern. See 8.9 of
338   // JISX0510:2004 (p.45) for details.
339   public static boolean MakeTypeInfoBits(int ec_level, final int mask_pattern, BitVector bits) {
340     final int ec_code = QRCode.GetECLevelCode(ec_level);
341     if (ec_code == -1) {
342       return false;
343     }
344     if (!QRCode.IsValidMaskPattern(mask_pattern)) {
345       return false;
346     }
347     final int type_info = (ec_code << 3) | mask_pattern;
348     bits.AppendBits(type_info, 5);
349
350     final int bch_code = MatrixUtil.CalculateBCHCode(type_info, kTypeInfoPoly);
351     bits.AppendBits(bch_code, 10);
352
353     BitVector mask_bits = new BitVector();
354     mask_bits.AppendBits(kTypeInfoMaskPattern, 15);
355     bits.XOR(mask_bits);
356
357     if (bits.size() != 15) {  // Just in case.
358       Debug.LOG_ERROR("should not happen but we got: " + bits.size());
359       return false;
360     }
361     return true;
362   }
363
364   // Make bit vector of version information. On success, store the result in "bits" and return true.
365   // On error, return false. See 8.10 of JISX0510:2004 (p.45) for details.
366   public static boolean MakeVersionInfoBits(int version, BitVector bits) {
367     bits.AppendBits(version, 6);
368     final int bch_code = MatrixUtil.CalculateBCHCode(version, kVersionInfoPoly);
369     bits.AppendBits(bch_code, 12);
370
371     if (bits.size() != 18) {  // Just in case.
372       Debug.LOG_ERROR("should not happen but we got: " + bits.size());
373       return false;
374     }
375     return true;
376   }
377
378   // Check if "value" is empty.
379   private static boolean IsEmpty(final int value) {
380     return value == -1;
381   }
382
383   // Check if "value" is valid.
384   private static boolean IsValidValue(final int value) {
385     return (value == -1 ||  // Empty.
386         value == 0 ||  // Light (white).
387         value == 1);  // Dark (black).
388   }
389
390   private static void EmbedTimingPatterns(Matrix matrix) {
391     // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical
392     // separation patterns (size 1). Thus, 8 = 7 + 1.
393     for (int i = 8; i < matrix.width() - 8; ++i) {
394       final int bit = (i + 1) % 2;
395       // Horizontal line.
396       Debug.DCHECK(IsValidValue(matrix.get(6, i)));
397       if (IsEmpty(matrix.get(6, i))) {
398         matrix.set(6, i, bit);
399       }
400       // Vertical line.
401       Debug.DCHECK(IsValidValue(matrix.get(i, 6)));
402       if (IsEmpty(matrix.get(i, 6))) {
403         matrix.set(i, 6, bit);
404       }
405     }
406   }
407
408   // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
409   private static void EmbedDarkDotAtLeftBottomCorner(Matrix matrix) {
410     Debug.DCHECK(matrix.get(matrix.height() - 8, 8) != 0);
411     matrix.set(matrix.height() - 8, 8, 1);
412   }
413
414   private static void EmbedHorizontalSeparationPattern(final int x_start, final int y_start,
415       Matrix matrix) {
416     // We know the width and height.
417     Debug.DCHECK_EQ(8, kHorizontalSeparationPattern[0].length);
418     Debug.DCHECK_EQ(1, kHorizontalSeparationPattern.length);
419     for (int x = 0; x < 8; ++x) {
420       Debug.DCHECK(IsEmpty(matrix.get(y_start, x_start + x)));
421       matrix.set(y_start, x_start + x, kHorizontalSeparationPattern[0][x]);
422     }
423   }
424
425   private static void EmbedVerticalSeparationPattern(final int x_start, final int y_start,
426       Matrix matrix) {
427     // We know the width and height.
428     Debug.DCHECK_EQ(1, kVerticalSeparationPattern[0].length);
429     Debug.DCHECK_EQ(7, kVerticalSeparationPattern.length);
430     for (int y = 0; y < 7; ++y) {
431       Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start)));
432       matrix.set(y_start + y, x_start, kVerticalSeparationPattern[y][0]);
433     }
434   }
435
436   // Note that we cannot unify the function with EmbedPositionDetectionPattern() despite they are
437   // almost identical, since we cannot write a function that takes 2D arrays in different sizes in
438   // C/C++. We should live with the fact.
439   private static void EmbedPositionAdjustmentPattern(final int x_start, final int y_start,
440       Matrix matrix) {
441     // We know the width and height.
442     Debug.DCHECK_EQ(5, kPositionAdjustmentPattern[0].length);
443     Debug.DCHECK_EQ(5, kPositionAdjustmentPattern.length);
444     for (int y = 0; y < 5; ++y) {
445       for (int x = 0; x < 5; ++x) {
446         Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start + x)));
447         matrix.set(y_start + y, x_start + x, kPositionAdjustmentPattern[y][x]);
448       }
449     }
450   }
451
452   private static void EmbedPositionDetectionPattern(final int x_start, final int y_start,
453       Matrix matrix) {
454     // We know the width and height.
455     Debug.DCHECK_EQ(7, kPositionDetectionPattern[0].length);
456     Debug.DCHECK_EQ(7, kPositionDetectionPattern.length);
457     for (int y = 0; y < 7; ++y) {
458       for (int x = 0; x < 7; ++x) {
459         Debug.DCHECK(IsEmpty(matrix.get(y_start + y, x_start + x)));
460         matrix.set(y_start + y, x_start + x, kPositionDetectionPattern[y][x]);
461       }
462     }
463   }
464
465   // Embed position detection patterns and surrounding vertical/horizontal separators.
466   private static void EmbedPositionDetectionPatternsAndSeparators(Matrix matrix) {
467     // Embed three big squares at corners.
468     final int pdp_width = kPositionDetectionPattern[0].length;
469     // Left top corner.
470     EmbedPositionDetectionPattern(0, 0, matrix);
471     // Right top corner.
472     EmbedPositionDetectionPattern(matrix.width() - pdp_width, 0, matrix);
473     // Left bottom corner.
474     EmbedPositionDetectionPattern(0, matrix.width() - pdp_width, matrix);
475
476     // Embed horizontal separation patterns around the squares.
477     final int hsp_width = kHorizontalSeparationPattern[0].length;
478     // Left top corner.
479     EmbedHorizontalSeparationPattern(0, hsp_width - 1, matrix);
480     // Right top corner.
481     EmbedHorizontalSeparationPattern(matrix.width() - hsp_width,
482         hsp_width - 1, matrix);
483     // Left bottom corner.
484     EmbedHorizontalSeparationPattern(0, matrix.width() - hsp_width, matrix);
485
486     // Embed vertical separation patterns around the squares.
487     final int vsp_size = kVerticalSeparationPattern.length;
488     // Left top corner.
489     EmbedVerticalSeparationPattern(vsp_size, 0, matrix);
490     // Right top corner.
491     EmbedVerticalSeparationPattern(matrix.height() - vsp_size - 1, 0, matrix);
492     // Left bottom corner.
493     EmbedVerticalSeparationPattern(vsp_size, matrix.height() - vsp_size,
494         matrix);
495   }
496
497   // Embed position adjustment patterns if need be.
498   private static void MaybeEmbedPositionAdjustmentPatterns(final int version, Matrix matrix) {
499     if (version < 2) {  // The patterns appear if version >= 2
500       return;
501     }
502     final int index = version - 1;
503     final int[] coordinates = kPositionAdjustmentPatternCoordinateTable[index];
504     final int num_coordinates = kPositionAdjustmentPatternCoordinateTable[index].length;
505     for (int i = 0; i < num_coordinates; ++i) {
506       for (int j = 0; j < num_coordinates; ++j) {
507         final int y = coordinates[i];
508         final int x = coordinates[j];
509         if (x == -1 || y == -1) {
510           continue;
511         }
512         // If the cell is unset, we embed the position adjustment pattern here.
513         if (IsEmpty(matrix.get(y, x))) {
514           // -2 is necessary since the x/y coordinates point to the center of the pattern, not the
515           // left top corner.
516           EmbedPositionAdjustmentPattern(x - 2, y - 2, matrix);
517         }
518       }
519     }
520   }
521
522 }