]> Pileus Git - ~andy/freeotp/blob - src/com/google/zxing/qrcode/decoder/BitMatrixParser.java
Add native camera support
[~andy/freeotp] / src / com / google / zxing / qrcode / decoder / BitMatrixParser.java
1 /*
2  * Copyright 2007 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.decoder;
18
19 import com.google.zxing.FormatException;
20 import com.google.zxing.common.BitMatrix;
21
22 /**
23  * @author Sean Owen
24  */
25 final class BitMatrixParser {
26
27   private final BitMatrix bitMatrix;
28   private Version parsedVersion;
29   private FormatInformation parsedFormatInfo;
30   private boolean mirror;
31
32   /**
33    * @param bitMatrix {@link BitMatrix} to parse
34    * @throws FormatException if dimension is not >= 21 and 1 mod 4
35    */
36   BitMatrixParser(BitMatrix bitMatrix) throws FormatException {
37     int dimension = bitMatrix.getHeight();
38     if (dimension < 21 || (dimension & 0x03) != 1) {
39       throw FormatException.getFormatInstance();
40     }
41     this.bitMatrix = bitMatrix;
42   }
43
44   /**
45    * <p>Reads format information from one of its two locations within the QR Code.</p>
46    *
47    * @return {@link FormatInformation} encapsulating the QR Code's format info
48    * @throws FormatException if both format information locations cannot be parsed as
49    * the valid encoding of format information
50    */
51   FormatInformation readFormatInformation() throws FormatException {
52
53     if (parsedFormatInfo != null) {
54       return parsedFormatInfo;
55     }
56
57     // Read top-left format info bits
58     int formatInfoBits1 = 0;
59     for (int i = 0; i < 6; i++) {
60       formatInfoBits1 = copyBit(i, 8, formatInfoBits1);
61     }
62     // .. and skip a bit in the timing pattern ...
63     formatInfoBits1 = copyBit(7, 8, formatInfoBits1);
64     formatInfoBits1 = copyBit(8, 8, formatInfoBits1);
65     formatInfoBits1 = copyBit(8, 7, formatInfoBits1);
66     // .. and skip a bit in the timing pattern ...
67     for (int j = 5; j >= 0; j--) {
68       formatInfoBits1 = copyBit(8, j, formatInfoBits1);
69     }
70
71     // Read the top-right/bottom-left pattern too
72     int dimension = bitMatrix.getHeight();
73     int formatInfoBits2 = 0;
74     int jMin = dimension - 7;
75     for (int j = dimension - 1; j >= jMin; j--) {
76       formatInfoBits2 = copyBit(8, j, formatInfoBits2);
77     }
78     for (int i = dimension - 8; i < dimension; i++) {
79       formatInfoBits2 = copyBit(i, 8, formatInfoBits2);
80     }
81
82     parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits1, formatInfoBits2);
83     if (parsedFormatInfo != null) {
84       return parsedFormatInfo;
85     }
86     throw FormatException.getFormatInstance();
87   }
88
89   /**
90    * <p>Reads version information from one of its two locations within the QR Code.</p>
91    *
92    * @return {@link Version} encapsulating the QR Code's version
93    * @throws FormatException if both version information locations cannot be parsed as
94    * the valid encoding of version information
95    */
96   Version readVersion() throws FormatException {
97
98     if (parsedVersion != null) {
99       return parsedVersion;
100     }
101
102     int dimension = bitMatrix.getHeight();
103
104     int provisionalVersion = (dimension - 17) >> 2;
105     if (provisionalVersion <= 6) {
106       return Version.getVersionForNumber(provisionalVersion);
107     }
108
109     // Read top-right version info: 3 wide by 6 tall
110     int versionBits = 0;
111     int ijMin = dimension - 11;
112     for (int j = 5; j >= 0; j--) {
113       for (int i = dimension - 9; i >= ijMin; i--) {
114         versionBits = copyBit(i, j, versionBits);
115       }
116     }
117
118     Version theParsedVersion = Version.decodeVersionInformation(versionBits);
119     if (theParsedVersion != null && theParsedVersion.getDimensionForVersion() == dimension) {
120       parsedVersion = theParsedVersion;
121       return theParsedVersion;
122     }
123
124     // Hmm, failed. Try bottom left: 6 wide by 3 tall
125     versionBits = 0;
126     for (int i = 5; i >= 0; i--) {
127       for (int j = dimension - 9; j >= ijMin; j--) {
128         versionBits = copyBit(i, j, versionBits);
129       }
130     }
131
132     theParsedVersion = Version.decodeVersionInformation(versionBits);
133     if (theParsedVersion != null && theParsedVersion.getDimensionForVersion() == dimension) {
134       parsedVersion = theParsedVersion;
135       return theParsedVersion;
136     }
137     throw FormatException.getFormatInstance();
138   }
139
140   private int copyBit(int i, int j, int versionBits) {
141     boolean bit = mirror ? bitMatrix.get(j, i) : bitMatrix.get(i, j);
142     return bit ? (versionBits << 1) | 0x1 : versionBits << 1;
143   }
144
145   /**
146    * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
147    * correct order in order to reconstruct the codewords bytes contained within the
148    * QR Code.</p>
149    *
150    * @return bytes encoded within the QR Code
151    * @throws FormatException if the exact number of bytes expected is not read
152    */
153   byte[] readCodewords() throws FormatException {
154
155     FormatInformation formatInfo = readFormatInformation();
156     Version version = readVersion();
157
158     // Get the data mask for the format used in this QR Code. This will exclude
159     // some bits from reading as we wind through the bit matrix.
160     DataMask dataMask = DataMask.forReference(formatInfo.getDataMask());
161     int dimension = bitMatrix.getHeight();
162     dataMask.unmaskBitMatrix(bitMatrix, dimension);
163
164     BitMatrix functionPattern = version.buildFunctionPattern();
165
166     boolean readingUp = true;
167     byte[] result = new byte[version.getTotalCodewords()];
168     int resultOffset = 0;
169     int currentByte = 0;
170     int bitsRead = 0;
171     // Read columns in pairs, from right to left
172     for (int j = dimension - 1; j > 0; j -= 2) {
173       if (j == 6) {
174         // Skip whole column with vertical alignment pattern;
175         // saves time and makes the other code proceed more cleanly
176         j--;
177       }
178       // Read alternatingly from bottom to top then top to bottom
179       for (int count = 0; count < dimension; count++) {
180         int i = readingUp ? dimension - 1 - count : count;
181         for (int col = 0; col < 2; col++) {
182           // Ignore bits covered by the function pattern
183           if (!functionPattern.get(j - col, i)) {
184             // Read a bit
185             bitsRead++;
186             currentByte <<= 1;
187             if (bitMatrix.get(j - col, i)) {
188               currentByte |= 1;
189             }
190             // If we've made a whole byte, save it off
191             if (bitsRead == 8) {
192               result[resultOffset++] = (byte) currentByte;
193               bitsRead = 0;
194               currentByte = 0;
195             }
196           }
197         }
198       }
199       readingUp ^= true; // readingUp = !readingUp; // switch directions
200     }
201     if (resultOffset != version.getTotalCodewords()) {
202       throw FormatException.getFormatInstance();
203     }
204     return result;
205   }
206
207   /**
208    * Revert the mask removal done while reading the code words. The bit matrix should revert to its original state.
209    */
210   void remask() {
211     if (parsedFormatInfo == null) {
212       return; // We have no format information, and have no data mask
213     }
214     DataMask dataMask = DataMask.forReference(parsedFormatInfo.getDataMask());
215     int dimension = bitMatrix.getHeight();
216     dataMask.unmaskBitMatrix(bitMatrix, dimension);
217   }
218
219   /**
220    * Prepare the parser for a mirrored operation.
221    * This flag has effect only on the {@link #readFormatInformation()} and the
222    * {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the
223    * {@link #mirror()} method should be called.
224    * 
225    * @param mirror Whether to read version and format information mirrored.
226    */
227   void setMirror(boolean mirror) {
228     parsedVersion = null;
229     parsedFormatInfo = null;
230     this.mirror = mirror;
231   }
232
233   /** Mirror the bit matrix in order to attempt a second reading. */
234   void mirror() {
235     for (int x = 0; x < bitMatrix.getWidth(); x++) {
236       for (int y = x + 1; y < bitMatrix.getHeight(); y++) {
237         if (bitMatrix.get(x, y) != bitMatrix.get(y, x)) {
238           bitMatrix.flip(y, x);
239           bitMatrix.flip(x, y);          
240         }
241       }
242     }
243   }
244
245 }