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