Did a bunch of comments cleanup.
[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 // #include "util/array/array2d-inl.h"
20
21 /**
22  * @author satorux@google.com (Satoru Takabayashi) - creator
23  * @author dswitkin@google.com (Daniel Switkin) - ported from C++
24  */
25 public final class MatrixUtil {
26
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},
35   };
36
37   private static final int kHorizontalSeparationPattern[][] = {
38       {0, 0, 0, 0, 0, 0, 0, 0},
39   };
40
41   private static final int kVerticalSeparationPattern[][] = {
42       {0}, {0}, {0}, {0}, {0}, {0}, {0},
43   };
44
45   private static final int kPositionAdjustmentPattern[][] = {
46       {1, 1, 1, 1, 1},
47       {1, 0, 0, 0, 1},
48       {1, 0, 1, 0, 1},
49       {1, 0, 0, 0, 1},
50       {1, 1, 1, 1, 1},
51   };
52
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
95   };
96
97   // Type info cells at the left top corner.
98   private static int kTypeInfoCoordinates[][] = {
99       {8, 0},
100       {8, 1},
101       {8, 2},
102       {8, 3},
103       {8, 4},
104       {8, 5},
105       {8, 7},
106       {8, 8},
107       {7, 8},
108       {5, 8},
109       {4, 8},
110       {3, 8},
111       {2, 8},
112       {1, 8},
113       {0, 8},
114   };
115
116   // From Appendix D in JISX0510:2004 (p. 67)
117   private static final uint32 kVersionInfoPoly = 0x1f25;  // 1 1111 0010 0101
118
119   // From Appendix C in JISX0510:2004 (p.65).
120   private static final uint32 kTypeInfoPoly = 0x537;
121   private static final uint32 kTypeInfoMaskPattern = 0x5412;
122
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);
128       }
129     }
130   }
131
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)) {
138           case 0:
139             result.append(" 0");
140             break;
141           case 1:
142             result.append(" 1");
143             break;
144           default:
145             result.append("  ");
146             break;
147         }
148       }
149       result.append("\n");
150     }
151     return result.toString();
152   }
153
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,
157                                     int ec_level,
158                                     int version,
159                                     int mask_pattern,
160                                     Matrix matrix) {
161     MatrixUtil.ClearMatrix(matrix);
162     if (!EmbedBasicPatterns(version, matrix)) {
163       return false;
164     }
165     // Type information appear with any version.
166     if (!EmbedTypeInfo(ec_level, mask_pattern, matrix)) {
167       return false;
168     }
169     // Version info appear if version >= 7.
170     if (!MaybeEmbedVersionInfo(version, matrix)) {
171       return false;
172     }
173     // Data should be embedded at end.
174     return EmbedDataBits(data_bits,  mask_pattern, matrix);
175   }
176
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
180   // - Timing 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);
188
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);
193     return true;
194   }
195
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)) {
200       return false;
201     }
202     Debug.DCHECK_EQ(15, type_info_bits.size());
203
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
206       // "type_info_bits".
207       final int bit = type_info_bits.at(type_info_bits.size() - 1 - i);
208
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);
213
214       if (i < 8) {
215         // Right top corner.
216         final int x2 = matrix.width() - i - 1;
217         final int y2 = 8;
218         matrix.set(y2, x2, bit);
219       } else {
220         // Left bottom corner.
221         final int x2 = 8;
222         final int y2 = matrix.height() - 7 + (i - 8);
223         matrix.set(y2, x2, bit);
224       }
225     }
226     return true;
227   }
228
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.
235     }
236     BitVector version_info_bits;
237     if (!MakeVersionInfoBits(version, &version_info_bits)) {
238     return false;
239   }
240
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);
251       }
252     }
253     return true;
254   }
255
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) {
260     int bit_index = 0;
261     int direction = -1;
262     // Start from the right bottom cell.
263     int x = matrix.width() - 1;
264     int y = matrix.height() - 1;
265     while (x > 0) {
266       // Skip the vertical timing pattern.
267       if (x == 6) {
268         x -= 1;
269       }
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))) {
275           continue;
276         }
277           int bit = -1;
278           if (bit_index < data_bits.size()) {
279             bit = data_bits.at(bit_index);
280             ++bit_index;
281           } else {
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).
284             bit = 0;
285           }
286           Debug.DCHECK(IsValidValue(bit));
287
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);
292             bit ^= mask;
293           }
294           matrix.set(y, xx, bit);
295         }
296         y += direction;
297       }
298       direction = -direction;  // Reverse the direction.
299       y += direction;
300       x -= 2;  // Move to the left.
301     }
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());
305       return false;
306     }
307     Debug.DCHECK_EQ(bit_index, data_bits.size());
308     return true;
309   }
310
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) {
317     int num_digits = 0;
318     while (value != 0) {
319       value >>= 1;
320       ++num_digits;
321     }
322     return num_digits;
323   }
324
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)
337   //         x^2
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
343   //
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)
347   //
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);
358     }
359     // Now the "value" is the remainder (i.e. the BCH code)
360     return value;
361   }
362
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);
368     if (ec_code == -1) {
369       return false;
370     }
371     if (!QRCode.IsValidMaskPattern(mask_pattern)) {
372       return false;
373     }
374     final uint32 type_info = (ec_code << 3) | mask_pattern;
375     bits.AppendBits(type_info, 5);
376
377     final uint32 bch_code = MatrixUtil.CalculateBCHCode(type_info,
378         kTypeInfoPoly);
379     bits.AppendBits(bch_code, 10);
380
381     BitVector mask_bits;
382     mask_bits.AppendBits(kTypeInfoMaskPattern, 15);
383     bits.XOR(mask_bits);
384
385     if (bits.size() != 15) {  // Just in case.
386       Debug.LOG_ERROR("should not happen but we got: " + bits.size());
387       return false;
388     }
389     return true;
390   }
391
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,
397         kVersionInfoPoly);
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());
401       return false;
402     }
403     return true;
404   }
405
406   // Check if "value" is empty.
407   private static boolean IsEmpty(final int value) {
408     return value == -1;
409   }
410
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).
416   }
417
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;
423       // Horizontal line.
424       Debug.DCHECK(IsValidValue(matrix.get(6, i)));
425       if (IsEmpty(matrix.get(6, i))) {
426         matrix.set(6, i, bit);
427       }
428       // Vertical line.
429       Debug.DCHECK(IsValidValue(matrix.get(i, 6)));
430       if (IsEmpty(matrix.get(i, 6))) {
431         matrix.set(i, 6, bit);
432       }
433     }
434   }
435
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);
440   }
441
442   private static void EmbedHorizontalSeparationPattern(final int x_start, final int y_start,
443       Matrix matrix) {
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]);
450     }
451   }
452
453   private static void EmbedVerticalSeparationPattern(final int x_start, final int y_start,
454       Matrix matrix) {
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]);
461     }
462   }
463
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,
468       Matrix matrix) {
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]);
476       }
477     }
478   }
479
480   private static void EmbedPositionDetectionPattern(final int x_start, final int y_start,
481       Matrix matrix) {
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]);
489       }
490     }
491   }
492
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]);
497     // Left top corner.
498     EmbedPositionDetectionPattern(0, 0, matrix);
499     // Right top corner.
500     EmbedPositionDetectionPattern(matrix.width() - pdp_width, 0, matrix);
501     // Left bottom corner.
502     EmbedPositionDetectionPattern(0, matrix.width() - pdp_width, matrix);
503
504     // Embed horizontal separation patterns around the squares.
505     final int hsp_width = arraysize(kHorizontalSeparationPattern[0]);
506     // Left top corner.
507     EmbedHorizontalSeparationPattern(0, hsp_width - 1, matrix);
508     // Right top corner.
509     EmbedHorizontalSeparationPattern(matrix.width() - hsp_width,
510         hsp_width - 1, matrix);
511     // Left bottom corner.
512     EmbedHorizontalSeparationPattern(0, matrix.width() - hsp_width, matrix);
513
514     // Embed vertical separation patterns around the squares.
515     final int vsp_height = arraysize(kVerticalSeparationPattern);
516     // Left top corner.
517     EmbedVerticalSeparationPattern(vsp_height, 0, matrix);
518     // Right top corner.
519     EmbedVerticalSeparationPattern(matrix.height() - vsp_height - 1, 0, matrix);
520     // Left bottom corner.
521     EmbedVerticalSeparationPattern(vsp_height, matrix.height() - vsp_height,
522         matrix);
523   }
524
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
528       return;
529     }
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) {
540           continue;
541         }
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
545           // left top corner.
546           EmbedPositionAdjustmentPattern(x - 2, y - 2, matrix);
547         }
548       }
549     }
550   }
551
552 }