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