Another attack on integrating encoder and decoder: Version is done. Attempted to...
[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.ByteMatrix;
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(BitVector 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     BitVector typeInfoBits = new BitVector();
173     makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits);
174
175     for (int i = 0; i < typeInfoBits.size(); ++i) {
176       // Place bits in LSB to MSB order.  LSB (least significant bit) is the last value in
177       // "typeInfoBits".
178       int bit = typeInfoBits.at(typeInfoBits.size() - 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(y1, x1, bit);
184
185       if (i < 8) {
186         // Right top corner.
187         int x2 = matrix.width() - i - 1;
188         int y2 = 8;
189         matrix.set(y2, x2, bit);
190       } else {
191         // Left bottom corner.
192         int x2 = 8;
193         int y2 = matrix.height() - 7 + (i - 8);
194         matrix.set(y2, x2, 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     BitVector versionInfoBits = new BitVector();
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         int bit = versionInfoBits.at(bitIndex);
213         bitIndex--;
214         // Left bottom corner.
215         matrix.set(matrix.height() - 11 + j, i, bit);
216         // Right bottom corner.
217         matrix.set(i, matrix.height() - 11 + j, 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(BitVector 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.width() - 1;
231     int y = matrix.height() - 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.height()) {
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(y, xx))) {
242             continue;
243           }
244           int bit;
245           if (bitIndex < dataBits.size()) {
246             bit = dataBits.at(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 = 0;
252           }
253
254           // Skip masking if mask_pattern is -1.
255           if (maskPattern != -1) {
256             int mask = MaskUtil.getDataMaskBit(maskPattern, xx, y);
257             bit ^= mask;
258           }
259           matrix.set(y, xx, bit);
260         }
261         y += direction;
262       }
263       direction = -direction;  // Reverse the direction.
264       y += direction;
265       x -= 2;  // Move to the left.
266     }
267     // All bits should be consumed.
268     if (bitIndex != dataBits.size()) {
269       throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size());
270     }
271   }
272
273   // Return the position of the most significant bit set (to one) in the "value". The most
274   // significant bit is position 32. If there is no bit set, return 0. Examples:
275   // - findMSBSet(0) => 0
276   // - findMSBSet(1) => 1
277   // - findMSBSet(255) => 8
278   public static int findMSBSet(int value) {
279     int numDigits = 0;
280     while (value != 0) {
281       value >>>= 1;
282       ++numDigits;
283     }
284     return numDigits;
285   }
286
287   // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
288   // code is used for encoding type information and version information.
289   // Example: Calculation of version information of 7.
290   // f(x) is created from 7.
291   //   - 7 = 000111 in 6 bits
292   //   - f(x) = x^2 + x^2 + x^1
293   // g(x) is given by the standard (p. 67)
294   //   - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
295   // Multiply f(x) by x^(18 - 6)
296   //   - f'(x) = f(x) * x^(18 - 6)
297   //   - f'(x) = x^14 + x^13 + x^12
298   // Calculate the remainder of f'(x) / g(x)
299   //         x^2
300   //         __________________________________________________
301   //   g(x) )x^14 + x^13 + x^12
302   //         x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
303   //         --------------------------------------------------
304   //                              x^11 + x^10 + x^7 + x^4 + x^2
305   //
306   // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
307   // Encode it in binary: 110010010100
308   // The return value is 0xc94 (1100 1001 0100)
309   //
310   // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
311   // operations. We don't care if cofficients are positive or negative.
312   public static int calculateBCHCode(int value, int poly) {
313     // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
314     // from 13 to make it 12.
315     int msbSetInPoly = findMSBSet(poly);
316     value <<= msbSetInPoly - 1;
317     // Do the division business using exclusive-or operations.
318     while (findMSBSet(value) >= msbSetInPoly) {
319       value ^= poly << (findMSBSet(value) - msbSetInPoly);
320     }
321     // Now the "value" is the remainder (i.e. the BCH code)
322     return value;
323   }
324
325   // Make bit vector of type information. On success, store the result in "bits" and return true.
326   // Encode error correction level and mask pattern. See 8.9 of
327   // JISX0510:2004 (p.45) for details.
328   public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits)
329       throws WriterException {
330     if (!QRCode.isValidMaskPattern(maskPattern)) {
331       throw new WriterException("Invalid mask pattern");
332     }
333     int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
334     bits.appendBits(typeInfo, 5);
335
336     int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
337     bits.appendBits(bchCode, 10);
338
339     BitVector maskBits = new BitVector();
340     maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
341     bits.xor(maskBits);
342
343     if (bits.size() != 15) {  // Just in case.
344       throw new WriterException("should not happen but we got: " + bits.size());
345     }
346   }
347
348   // Make bit vector of version information. On success, store the result in "bits" and return true.
349   // See 8.10 of JISX0510:2004 (p.45) for details.
350   public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException {
351     bits.appendBits(version, 6);
352     int bchCode = calculateBCHCode(version, VERSION_INFO_POLY);
353     bits.appendBits(bchCode, 12);
354
355     if (bits.size() != 18) {  // Just in case.
356       throw new WriterException("should not happen but we got: " + bits.size());
357     }
358   }
359
360   // Check if "value" is empty.
361   private static boolean isEmpty(int value) {
362     return value == -1;
363   }
364
365   // Check if "value" is valid.
366   private static boolean isValidValue(int value) {
367     return (value == -1 ||  // Empty.
368         value == 0 ||  // Light (white).
369         value == 1);  // Dark (black).
370   }
371
372   private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException {
373     // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical
374     // separation patterns (size 1). Thus, 8 = 7 + 1.
375     for (int i = 8; i < matrix.width() - 8; ++i) {
376       int bit = (i + 1) % 2;
377       // Horizontal line.
378       if (!isValidValue(matrix.get(6, i))) {
379         throw new WriterException();
380       }
381       if (isEmpty(matrix.get(6, i))) {
382         matrix.set(6, i, bit);
383       }
384       // Vertical line.
385       if (!isValidValue(matrix.get(i, 6))) {
386         throw new WriterException();
387       }
388       if (isEmpty(matrix.get(i, 6))) {
389         matrix.set(i, 6, bit);
390       }
391     }
392   }
393
394   // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
395   private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException {
396     if (matrix.get(matrix.height() - 8, 8) == 0) {
397       throw new WriterException();
398     }
399     matrix.set(matrix.height() - 8, 8, 1);
400   }
401
402   private static void embedHorizontalSeparationPattern(int xStart, int yStart,
403       ByteMatrix matrix) throws WriterException {
404     // We know the width and height.
405     if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) {
406       throw new WriterException("Bad horizontal separation pattern");
407     }
408     for (int x = 0; x < 8; ++x) {
409       if (!isEmpty(matrix.get(yStart, xStart + x))) {
410         throw new WriterException();
411       }
412       matrix.set(yStart, xStart + x, HORIZONTAL_SEPARATION_PATTERN[0][x]);
413     }
414   }
415
416   private static void embedVerticalSeparationPattern(int xStart, int yStart,
417       ByteMatrix matrix) throws WriterException {
418     // We know the width and height.
419     if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) {
420       throw new WriterException("Bad vertical separation pattern");
421     }
422     for (int y = 0; y < 7; ++y) {
423       if (!isEmpty(matrix.get(yStart + y, xStart))) {
424         throw new WriterException();
425       }
426       matrix.set(yStart + y, xStart, VERTICAL_SEPARATION_PATTERN[y][0]);
427     }
428   }
429
430   // Note that we cannot unify the function with embedPositionDetectionPattern() despite they are
431   // almost identical, since we cannot write a function that takes 2D arrays in different sizes in
432   // C/C++. We should live with the fact.
433   private static void embedPositionAdjustmentPattern(int xStart, int yStart,
434       ByteMatrix matrix) throws WriterException {
435     // We know the width and height.
436     if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) {
437       throw new WriterException("Bad position adjustment");
438     }
439     for (int y = 0; y < 5; ++y) {
440       for (int x = 0; x < 5; ++x) {
441         if (!isEmpty(matrix.get(yStart + y, xStart + x))) {
442           throw new WriterException();
443         }
444         matrix.set(yStart + y, xStart + x, POSITION_ADJUSTMENT_PATTERN[y][x]);
445       }
446     }
447   }
448
449   private static void embedPositionDetectionPattern(int xStart, int yStart,
450       ByteMatrix matrix) throws WriterException {
451     // We know the width and height.
452     if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) {
453       throw new WriterException("Bad position detection pattern");
454     }
455     for (int y = 0; y < 7; ++y) {
456       for (int x = 0; x < 7; ++x) {
457         if (!isEmpty(matrix.get(yStart + y, xStart + x))) {
458           throw new WriterException();
459         }
460         matrix.set(yStart + y, xStart + x, POSITION_DETECTION_PATTERN[y][x]);
461       }
462     }
463   }
464
465   // Embed position detection patterns and surrounding vertical/horizontal separators.
466   private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException {
467     // Embed three big squares at corners.
468     int pdpWidth = POSITION_DETECTION_PATTERN[0].length;
469     // Left top corner.
470     embedPositionDetectionPattern(0, 0, matrix);
471     // Right top corner.
472     embedPositionDetectionPattern(matrix.width() - pdpWidth, 0, matrix);
473     // Left bottom corner.
474     embedPositionDetectionPattern(0, matrix.width() - pdpWidth, matrix);
475
476     // Embed horizontal separation patterns around the squares.
477     int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].length;
478     // Left top corner.
479     embedHorizontalSeparationPattern(0, hspWidth - 1, matrix);
480     // Right top corner.
481     embedHorizontalSeparationPattern(matrix.width() - hspWidth,
482         hspWidth - 1, matrix);
483     // Left bottom corner.
484     embedHorizontalSeparationPattern(0, matrix.width() - hspWidth, matrix);
485
486     // Embed vertical separation patterns around the squares.
487     int vspSize = VERTICAL_SEPARATION_PATTERN.length;
488     // Left top corner.
489     embedVerticalSeparationPattern(vspSize, 0, matrix);
490     // Right top corner.
491     embedVerticalSeparationPattern(matrix.height() - vspSize - 1, 0, matrix);
492     // Left bottom corner.
493     embedVerticalSeparationPattern(vspSize, matrix.height() - vspSize,
494         matrix);
495   }
496
497   // Embed position adjustment patterns if need be.
498   private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix)
499       throws WriterException {
500     if (version < 2) {  // The patterns appear if version >= 2
501       return;
502     }
503     int index = version - 1;
504     int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index];
505     int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].length;
506     for (int i = 0; i < numCoordinates; ++i) {
507       for (int j = 0; j < numCoordinates; ++j) {
508         int y = coordinates[i];
509         int x = coordinates[j];
510         if (x == -1 || y == -1) {
511           continue;
512         }
513         // If the cell is unset, we embed the position adjustment pattern here.
514         if (isEmpty(matrix.get(y, x))) {
515           // -2 is necessary since the x/y coordinates point to the center of the pattern, not the
516           // left top corner.
517           embedPositionAdjustmentPattern(x - 2, y - 2, matrix);
518         }
519       }
520     }
521   }
522
523 }