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