f19e81b36539cb506426b4f50cf14af1ee079a8f
[zxing.git] / core / src / com / google / zxing / qrcode / encoder / Encoder.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.ByteArray;
21 import com.google.zxing.common.ByteMatrix;
22 import com.google.zxing.common.reedsolomon.GF256;
23 import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
24 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
25 import com.google.zxing.qrcode.decoder.Mode;
26 import com.google.zxing.qrcode.decoder.Version;
27
28 import java.util.Vector;
29
30 /**
31  * @author satorux@google.com (Satoru Takabayashi) - creator
32  * @author dswitkin@google.com (Daniel Switkin) - ported from C++
33  */
34 public final class Encoder {
35
36   // The original table is defined in the table 5 of JISX0510:2004 (p.19).
37   private static final int[] ALPHANUMERIC_TABLE = {
38       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  // 0x00-0x0f
39       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  // 0x10-0x1f
40       36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,  // 0x20-0x2f
41       0,   1,  2,  3,  4,  5,  6,  7,  8,  9, 44, -1, -1, -1, -1, -1,  // 0x30-0x3f
42       -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,  // 0x40-0x4f
43       25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,  // 0x50-0x5f
44   };
45
46   private static final class RSBlockInfo {
47
48     final int numBytes;
49     final int[][] blockInfo;
50
51     public RSBlockInfo(int numBytes, int[][] blockInfo) {
52       this.numBytes = numBytes;
53       this.blockInfo = blockInfo;
54     }
55
56   }
57
58   // The table is from table 12 of JISX0510:2004 (p. 30). The "blockInfo" parts are ordered by
59   // L, M, Q, H. Within each blockInfo, the 0th element is getNumECBytes, and the 1st element is
60   // getNumRSBlocks. The table was doublechecked by komatsu.
61   private static final RSBlockInfo[] RS_BLOCK_TABLE = {
62       new RSBlockInfo(  26, new int[][]{ {  7,  1}, {  10,  1}, {  13,  1}, {  17,  1}}),  // Version  1
63       new RSBlockInfo(  44, new int[][]{ { 10,  1}, {  16,  1}, {  22,  1}, {  28,  1}}),  // Version  2
64       new RSBlockInfo(  70, new int[][]{ { 15,  1}, {  26,  1}, {  36,  2}, {  44,  2}}),  // Version  3
65       new RSBlockInfo( 100, new int[][]{ { 20,  1}, {  36,  2}, {  52,  2}, {  64,  4}}),  // Version  4
66       new RSBlockInfo( 134, new int[][]{ { 26,  1}, {  48,  2}, {  72,  4}, {  88,  4}}),  // Version  5
67       new RSBlockInfo( 172, new int[][]{ { 36,  2}, {  64,  4}, {  96,  4}, { 112,  4}}),  // Version  6
68       new RSBlockInfo( 196, new int[][]{ { 40,  2}, {  72,  4}, { 108,  6}, { 130,  5}}),  // Version  7
69       new RSBlockInfo( 242, new int[][]{ { 48,  2}, {  88,  4}, { 132,  6}, { 156,  6}}),  // Version  8
70       new RSBlockInfo( 292, new int[][]{ { 60,  2}, { 110,  5}, { 160,  8}, { 192,  8}}),  // Version  9
71       new RSBlockInfo( 346, new int[][]{ { 72,  4}, { 130,  5}, { 192,  8}, { 224,  8}}),  // Version 10
72       new RSBlockInfo( 404, new int[][]{ { 80,  4}, { 150,  5}, { 224,  8}, { 264, 11}}),  // Version 11
73       new RSBlockInfo( 466, new int[][]{ { 96,  4}, { 176,  8}, { 260, 10}, { 308, 11}}),  // Version 12
74       new RSBlockInfo( 532, new int[][]{ {104,  4}, { 198,  9}, { 288, 12}, { 352, 16}}),  // Version 13
75       new RSBlockInfo( 581, new int[][]{ {120,  4}, { 216,  9}, { 320, 16}, { 384, 16}}),  // Version 14
76       new RSBlockInfo( 655, new int[][]{ {132,  6}, { 240, 10}, { 360, 12}, { 432, 18}}),  // Version 15
77       new RSBlockInfo( 733, new int[][]{ {144,  6}, { 280, 10}, { 408, 17}, { 480, 16}}),  // Version 16
78       new RSBlockInfo( 815, new int[][]{ {168,  6}, { 308, 11}, { 448, 16}, { 532, 19}}),  // Version 17
79       new RSBlockInfo( 901, new int[][]{ {180,  6}, { 338, 13}, { 504, 18}, { 588, 21}}),  // Version 18
80       new RSBlockInfo( 991, new int[][]{ {196,  7}, { 364, 14}, { 546, 21}, { 650, 25}}),  // Version 19
81       new RSBlockInfo(1085, new int[][]{ {224,  8}, { 416, 16}, { 600, 20}, { 700, 25}}),  // Version 20
82       new RSBlockInfo(1156, new int[][]{ {224,  8}, { 442, 17}, { 644, 23}, { 750, 25}}),  // Version 21
83       new RSBlockInfo(1258, new int[][]{ {252,  9}, { 476, 17}, { 690, 23}, { 816, 34}}),  // Version 22
84       new RSBlockInfo(1364, new int[][]{ {270,  9}, { 504, 18}, { 750, 25}, { 900, 30}}),  // Version 23
85       new RSBlockInfo(1474, new int[][]{ {300, 10}, { 560, 20}, { 810, 27}, { 960, 32}}),  // Version 24
86       new RSBlockInfo(1588, new int[][]{ {312, 12}, { 588, 21}, { 870, 29}, {1050, 35}}),  // Version 25
87       new RSBlockInfo(1706, new int[][]{ {336, 12}, { 644, 23}, { 952, 34}, {1110, 37}}),  // Version 26
88       new RSBlockInfo(1828, new int[][]{ {360, 12}, { 700, 25}, {1020, 34}, {1200, 40}}),  // Version 27
89       new RSBlockInfo(1921, new int[][]{ {390, 13}, { 728, 26}, {1050, 35}, {1260, 42}}),  // Version 28
90       new RSBlockInfo(2051, new int[][]{ {420, 14}, { 784, 28}, {1140, 38}, {1350, 45}}),  // Version 29
91       new RSBlockInfo(2185, new int[][]{ {450, 15}, { 812, 29}, {1200, 40}, {1440, 48}}),  // Version 30
92       new RSBlockInfo(2323, new int[][]{ {480, 16}, { 868, 31}, {1290, 43}, {1530, 51}}),  // Version 31
93       new RSBlockInfo(2465, new int[][]{ {510, 17}, { 924, 33}, {1350, 45}, {1620, 54}}),  // Version 32
94       new RSBlockInfo(2611, new int[][]{ {540, 18}, { 980, 35}, {1440, 48}, {1710, 57}}),  // Version 33
95       new RSBlockInfo(2761, new int[][]{ {570, 19}, {1036, 37}, {1530, 51}, {1800, 60}}),  // Version 34
96       new RSBlockInfo(2876, new int[][]{ {570, 19}, {1064, 38}, {1590, 53}, {1890, 63}}),  // Version 35
97       new RSBlockInfo(3034, new int[][]{ {600, 20}, {1120, 40}, {1680, 56}, {1980, 66}}),  // Version 36
98       new RSBlockInfo(3196, new int[][]{ {630, 21}, {1204, 43}, {1770, 59}, {2100, 70}}),  // Version 37
99       new RSBlockInfo(3362, new int[][]{ {660, 22}, {1260, 45}, {1860, 62}, {2220, 74}}),  // Version 38
100       new RSBlockInfo(3532, new int[][]{ {720, 24}, {1316, 47}, {1950, 65}, {2310, 77}}),  // Version 39
101       new RSBlockInfo(3706, new int[][]{ {750, 25}, {1372, 49}, {2040, 68}, {2430, 81}}),  // Version 40
102   };
103
104   private static final class BlockPair {
105
106     private final ByteArray dataBytes;
107     private final ByteArray errorCorrectionBytes;
108
109     public BlockPair(ByteArray data, ByteArray errorCorrection) {
110       dataBytes = data;
111       errorCorrectionBytes = errorCorrection;
112     }
113
114     public ByteArray getDataBytes() {
115       return dataBytes;
116     }
117
118     public ByteArray getErrorCorrectionBytes() {
119       return errorCorrectionBytes;
120     }
121
122   }
123
124   // Encode "bytes" with the error correction level "getECLevel". The encoding mode will be chosen
125   // internally by chooseMode(). On success, store the result in "qrCode" and return true.
126   // We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
127   // "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
128   // strong error correction for this purpose.
129   //
130   // Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
131   // with which clients can specify the encoding mode. For now, we don't need the functionality.
132   public static void encode(final ByteArray bytes, ErrorCorrectionLevel ecLevel, QRCode qrCode)
133       throws WriterException {
134     // Step 1: Choose the mode (encoding).
135     final Mode mode = chooseMode(bytes);
136
137     // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
138     BitVector dataBits = new BitVector();
139     appendBytes(bytes, mode, dataBits);
140     // Step 3: Initialize QR code that can contain "dataBits".
141     final int numInputBytes = dataBits.sizeInBytes();
142     initQRCode(numInputBytes, ecLevel, mode, qrCode);
143
144     // Step 4: Build another bit vector that contains header and data.
145     BitVector headerAndDataBits = new BitVector();
146     appendModeInfo(qrCode.getMode(), headerAndDataBits);
147     appendLengthInfo(bytes.size(), qrCode.getVersion(), qrCode.getMode(), headerAndDataBits);
148     headerAndDataBits.appendBitVector(dataBits);
149
150     // Step 5: Terminate the bits properly.
151     terminateBits(qrCode.getNumDataBytes(), headerAndDataBits);
152
153     // Step 6: Interleave data bits with error correction code.
154     BitVector finalBits = new BitVector();
155     interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(),
156         qrCode.getNumRSBlocks(), finalBits);
157
158     // Step 7: Choose the mask pattern and set to "qrCode".
159     ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth());
160     qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
161         matrix));
162
163     // Step 8.  Build the matrix and set it to "qrCode".
164     MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
165         qrCode.getMaskPattern(), matrix);
166     qrCode.setMatrix(matrix);
167     // Step 9.  Make sure we have a valid QR Code.
168     if (!qrCode.isValid()) {
169       throw new WriterException("Invalid QR code: " + qrCode.toString());
170     }
171   }
172
173   // Return the code point of the table used in alphanumeric mode. Return -1 if there is no
174   // corresponding code in the table.
175   static int getAlphanumericCode(int code) {
176     if (code < ALPHANUMERIC_TABLE.length) {
177       return ALPHANUMERIC_TABLE[code];
178     }
179     return -1;
180   }
181
182   // Choose the best mode by examining the content of "bytes". The function is guaranteed to return
183   // a valid mode.
184   //
185   // Note that this function does not return MODE_KANJI, as we cannot distinguish Shift_JIS from
186   // other encodings such as ISO-8859-1, from data bytes alone. For example "\xE0\xE0" can be
187   // interpreted as one character in Shift_JIS, but also two characters in ISO-8859-1.
188   //
189   // JAVAPORT: This MODE_KANJI limitation sounds like a problem for us.
190   public static Mode chooseMode(final ByteArray bytes) throws WriterException {
191     boolean hasNumeric = false;
192     boolean hasAlphanumeric = false;
193     boolean hasOther = false;
194     for (int i = 0; i < bytes.size(); ++i) {
195       final int oneByte = bytes.at(i);
196       if (oneByte >= '0' && oneByte <= '9') {
197         hasNumeric = true;
198       } else if (getAlphanumericCode(oneByte) != -1) {
199         hasAlphanumeric = true;
200       } else {
201         hasOther = true;
202       }
203     }
204     if (hasOther) {
205       return Mode.BYTE;
206     } else if (hasAlphanumeric) {
207       return Mode.ALPHANUMERIC;
208     } else if (hasNumeric) {
209       return Mode.NUMERIC;
210     }
211     // "bytes" must be empty to reach here.
212     if (!bytes.empty()) {
213       throw new WriterException("Bytes left over");
214     }
215     return Mode.BYTE;
216   }
217
218   private static int chooseMaskPattern(final BitVector bits, ErrorCorrectionLevel ecLevel, int version,
219       ByteMatrix matrix) throws WriterException {
220     if (!QRCode.isValidMatrixWidth(matrix.width())) {
221       throw new WriterException("Invalid matrix width: " + matrix.width());
222     }
223
224     int minPenalty = Integer.MAX_VALUE;  // Lower penalty is better.
225     int bestMaskPattern = -1;
226     // We try all mask patterns to choose the best one.
227     for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
228       MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
229       final int penalty = MaskUtil.calculateMaskPenalty(matrix);
230       if (penalty < minPenalty) {
231         minPenalty = penalty;
232         bestMaskPattern = maskPattern;
233       }
234     }
235     return bestMaskPattern;
236   }
237
238   // Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success, modify
239   // "qrCode" and return true.
240   private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode)
241       throws WriterException {
242     qrCode.setECLevel(ecLevel);
243     qrCode.setMode(mode);
244
245     // In the following comments, we use numbers of Version 7-H.
246     for (int i = 0; i < RS_BLOCK_TABLE.length; ++i) {
247       final RSBlockInfo row = RS_BLOCK_TABLE[i];
248       // numBytes = 196
249       final int numBytes = row.numBytes;
250       // getNumECBytes = 130
251       final int numEcBytes  = row.blockInfo[ecLevel.ordinal()][0];
252       // getNumRSBlocks = 5
253       final int numRSBlocks = row.blockInfo[ecLevel.ordinal()][1];
254       // getNumDataBytes = 196 - 130 = 66
255       final int numDataBytes = numBytes - numEcBytes;
256       // We want to choose the smallest version which can contain data of "numInputBytes" + some
257       // extra bits for the header (mode info and length info). The header can be three bytes
258       // (precisely 4 + 16 bits) at most. Hence we do +3 here.
259       if (numDataBytes >= numInputBytes + 3) {
260         // Yay, we found the proper rs block info!
261         qrCode.setVersion(i + 1);
262         qrCode.setNumTotalBytes(numBytes);
263         qrCode.setNumDataBytes(numDataBytes);
264         qrCode.setNumRSBlocks(numRSBlocks);
265         // getNumECBytes = 196 - 66 = 130
266         qrCode.setNumECBytes(numBytes - numDataBytes);
267         // matrix width = 21 + 6 * 4 = 45
268         qrCode.setMatrixWidth(21 + i * 4);
269         return;
270       }
271     }
272     throw new WriterException("Cannot find proper rs block info (input data too big?)");
273   }
274
275   // Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
276   static void terminateBits(int numDataBytes, BitVector bits) throws WriterException {
277     final int capacity = numDataBytes * 8;
278     if (bits.size() > capacity) {
279       throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity);
280     }
281     // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
282     for (int i = 0; i < 4 && bits.size() < capacity; ++i) {
283       bits.appendBit(0);
284     }
285     final int numBitsInLastByte = bits.size() % 8;
286     // If the last byte isn't 8-bit aligned, we'll add padding bits.
287     if (numBitsInLastByte > 0) {
288       final int numPaddingBits = 8 - numBitsInLastByte;
289       for (int i = 0; i < numPaddingBits; ++i) {
290         bits.appendBit(0);
291       }
292     }
293     // Should be 8-bit aligned here.
294     if (bits.size() % 8 != 0) {
295       throw new WriterException("Number of bits is not a multiple of 8");
296     }
297     // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
298     final int numPaddingBytes = numDataBytes - bits.sizeInBytes();
299     for (int i = 0; i < numPaddingBytes; ++i) {
300       if (i % 2 == 0) {
301         bits.appendBits(0xec, 8);
302       } else {
303         bits.appendBits(0x11, 8);
304       }
305     }
306     if (bits.size() != capacity) {
307       throw new WriterException("Bits size does not equal capacity");
308     }
309   }
310
311   // Get number of data bytes and number of error correction bytes for block id "blockID". Store
312   // the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
313   // JISX0510:2004 (p.30)
314   static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes,
315       int numRSBlocks, int blockID, int[] numDataBytesInBlock,
316       int[] numECBytesInBlock) throws WriterException {
317     if (blockID >= numRSBlocks) {
318       throw new WriterException("Block ID too large");
319     }
320     // numRsBlocksInGroup2 = 196 % 5 = 1
321     final int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
322     // numRsBlocksInGroup1 = 5 - 1 = 4
323     final int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
324     // numTotalBytesInGroup1 = 196 / 5 = 39
325     final int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
326     // numTotalBytesInGroup2 = 39 + 1 = 40
327     final int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
328     // numDataBytesInGroup1 = 66 / 5 = 13
329     final int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
330     // numDataBytesInGroup2 = 13 + 1 = 14
331     final int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
332     // numEcBytesInGroup1 = 39 - 13 = 26
333     final int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
334     // numEcBytesInGroup2 = 40 - 14 = 26
335     final int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
336     // Sanity checks.
337     // 26 = 26
338     if (numEcBytesInGroup1 != numEcBytesInGroup2) {
339       throw new WriterException("EC bytes mismatch");
340     }
341     // 5 = 4 + 1.
342     if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
343       throw new WriterException("RS blocks mismatch");
344     }
345     // 196 = (13 + 26) * 4 + (14 + 26) * 1
346     if (numTotalBytes !=
347         ((numDataBytesInGroup1 + numEcBytesInGroup1) *
348             numRsBlocksInGroup1) +
349             ((numDataBytesInGroup2 + numEcBytesInGroup2) *
350                 numRsBlocksInGroup2)) {
351       throw new WriterException("Total bytes mismatch");
352     }
353
354     if (blockID < numRsBlocksInGroup1) {
355       numDataBytesInBlock[0] = numDataBytesInGroup1;
356       numECBytesInBlock[0] = numEcBytesInGroup1;
357     } else {
358       numDataBytesInBlock[0] = numDataBytesInGroup2;
359       numECBytesInBlock[0] = numEcBytesInGroup2;
360     }
361   }
362
363   // Interleave "bits" with corresponding error correction bytes. On success, store the result in
364   // "result" and return true. The interleave rule is complicated. See 8.6
365   // of JISX0510:2004 (p.37) for details.
366   static void interleaveWithECBytes(final BitVector bits, int numTotalBytes,
367       int numDataBytes, int numRSBlocks, BitVector result) throws WriterException {
368
369     // "bits" must have "getNumDataBytes" bytes of data.
370     if (bits.sizeInBytes() != numDataBytes) {
371       throw new WriterException("Number of bits and data bytes does not match");
372     }
373
374     // Step 1.  Divide data bytes into blocks and generate error correction bytes for them. We'll
375     // store the divided data bytes blocks and error correction bytes blocks into "blocks".
376     int dataBytesOffset = 0;
377     int maxNumDataBytes = 0;
378     int maxNumEcBytes = 0;
379
380     // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
381     Vector blocks = new Vector(numRSBlocks);
382
383     for (int i = 0; i < numRSBlocks; ++i) {
384       int[] numDataBytesInBlock = new int[1];
385       int[] numEcBytesInBlock = new int[1];
386       getNumDataBytesAndNumECBytesForBlockID(
387           numTotalBytes, numDataBytes, numRSBlocks, i,
388           numDataBytesInBlock, numEcBytesInBlock);
389
390       ByteArray dataBytes = new ByteArray();
391       dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]);
392       ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
393       blocks.addElement(new BlockPair(dataBytes, ecBytes));
394
395       maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size());
396       maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size());
397       dataBytesOffset += numDataBytesInBlock[0];
398     }
399     if (numDataBytes != dataBytesOffset) {
400       throw new WriterException("Data bytes does not match offset");
401     }
402
403     // First, place data blocks.
404     for (int i = 0; i < maxNumDataBytes; ++i) {
405       for (int j = 0; j < blocks.size(); ++j) {
406         final ByteArray dataBytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
407         if (i < dataBytes.size()) {
408           result.appendBits(dataBytes.at(i), 8);
409         }
410       }
411     }
412     // Then, place error correction blocks.
413     for (int i = 0; i < maxNumEcBytes; ++i) {
414       for (int j = 0; j < blocks.size(); ++j) {
415         final ByteArray ecBytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
416         if (i < ecBytes.size()) {
417           result.appendBits(ecBytes.at(i), 8);
418         }
419       }
420     }
421     if (numTotalBytes != result.sizeInBytes()) {  // Should be same.
422       throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() +
423         " differ.");
424     }
425   }
426
427   static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) {
428     int numDataBytes = dataBytes.size();
429     int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
430     for (int i = 0; i < numDataBytes; i++) {
431       toEncode[i] = dataBytes.at(i);
432     }
433     new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock);
434
435     ByteArray ecBytes = new ByteArray(numEcBytesInBlock);
436     for (int i = 0; i < numEcBytesInBlock; i++) {
437       ecBytes.set(i, toEncode[numDataBytes + i]);
438     }
439     return ecBytes;
440   }
441
442   // Append mode info. On success, store the result in "bits" and return true. On error, return
443   // false.
444   static void appendModeInfo(Mode mode, BitVector bits) {
445     bits.appendBits(mode.getBits(), 4);
446   }
447
448
449   // Append length info. On success, store the result in "bits" and return true. On error, return
450   // false.
451   static void appendLengthInfo(int numBytes, int version, Mode mode, BitVector bits) throws WriterException {
452     int numLetters = numBytes;
453     // In Kanji mode, a letter is represented in two bytes.
454     if (mode.equals(Mode.KANJI)) {
455       if (numLetters % 2 != 0) {
456         throw new WriterException("Number of letters must be even");
457       }
458       numLetters /= 2;
459     }
460
461     final int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version));
462
463     if (numLetters > ((1 << numBits) - 1)) {
464       throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1));
465     }
466     bits.appendBits(numLetters, numBits);
467   }
468
469   // Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits"
470   // and return true.
471   static void appendBytes(final ByteArray bytes, Mode mode, BitVector bits) throws WriterException {
472     if (mode.equals(Mode.NUMERIC)) {
473       appendNumericBytes(bytes, bits);
474     } else if (mode.equals(Mode.ALPHANUMERIC)) {
475       appendAlphanumericBytes(bytes, bits);
476     } else if (mode.equals(Mode.BYTE)) {
477       append8BitBytes(bytes, bits);
478     } else if (mode.equals(Mode.KANJI)) {
479       appendKanjiBytes(bytes, bits);
480     } else {
481       throw new WriterException("Invalid mode: " + mode);
482     }
483   }
484
485   // Append "bytes" to "bits" using QRCode.MODE_NUMERIC mode. On success, store the result in "bits"
486   // and return true.
487   static void appendNumericBytes(final ByteArray bytes, BitVector bits) throws WriterException {
488     // Validate all the bytes first.
489     for (int i = 0; i < bytes.size(); ++i) {
490       int oneByte = bytes.at(i);
491       if (oneByte < '0' || oneByte > '9') {
492         throw new WriterException("Non-digit found");
493       }
494     }
495     for (int i = 0; i < bytes.size();) {
496       final int num1 = bytes.at(i) - '0';
497       if (i + 2 < bytes.size()) {
498         // Encode three numeric letters in ten bits.
499         final int num2 = bytes.at(i + 1) - '0';
500         final int num3 = bytes.at(i + 2) - '0';
501         bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
502         i += 3;
503       } else if (i + 1 < bytes.size()) {
504         // Encode two numeric letters in seven bits.
505         final int num2 = bytes.at(i + 1) - '0';
506         bits.appendBits(num1 * 10 + num2, 7);
507         i += 2;
508       } else {
509         // Encode one numeric letter in four bits.
510         bits.appendBits(num1, 4);
511         ++i;
512       }
513     }
514   }
515
516   // Append "bytes" to "bits" using QRCode.MODE_ALPHANUMERIC mode. On success, store the result in
517   // "bits" and return true.
518   static void appendAlphanumericBytes(final ByteArray bytes, BitVector bits) throws WriterException {
519     for (int i = 0; i < bytes.size();) {
520       final int code1 = getAlphanumericCode(bytes.at(i));
521       if (code1 == -1) {
522         throw new WriterException();
523       }
524       if (i + 1 < bytes.size()) {
525         final int code2 = getAlphanumericCode(bytes.at(i + 1));
526         if (code2 == -1) {
527           throw new WriterException();
528         }
529         // Encode two alphanumeric letters in 11 bits.
530         bits.appendBits(code1 * 45 + code2, 11);
531         i += 2;
532       } else {
533         // Encode one alphanumeric letter in six bits.
534         bits.appendBits(code1, 6);
535         ++i;
536       }
537     }
538   }
539
540   // Append "bytes" to "bits" using QRCode.MODE_8BIT_BYTE mode. On success, store the result in
541   // "bits" and return true.
542   static void append8BitBytes(final ByteArray bytes, BitVector bits) {
543     for (int i = 0; i < bytes.size(); ++i) {
544       bits.appendBits(bytes.at(i), 8);
545     }
546   }
547
548   // Append "bytes" to "bits" using QRCode.MODE_KANJI mode. On success, store the result in "bits"
549   // and return true. See 8.4.5 of JISX0510:2004 (p.21) for how to encode
550   // Kanji bytes.
551   static void appendKanjiBytes(final ByteArray bytes, BitVector bits) throws WriterException {
552     if (bytes.size() % 2 != 0) {
553       throw new WriterException("Number of bytes must be even");
554     }
555     for (int i = 0; i < bytes.size(); i += 2) {
556       if (!isValidKanji(bytes.at(i), bytes.at(i + 1))) {
557         throw new WriterException("Invalid Kanji at " + i);
558       }
559       final int code = (bytes.at(i) << 8) | bytes.at(i + 1);
560       int subtracted = -1;
561       if (code >= 0x8140 && code <= 0x9ffc) {
562         subtracted = code - 0x8140;
563       } else if (code >= 0xe040 && code <= 0xebbf) {
564         subtracted = code - 0xc140;
565       }
566       if (subtracted == -1) {
567         throw new WriterException("Invalid byte sequence: " + bytes);
568       }
569       final int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
570       bits.appendBits(encoded, 13);
571     }
572   }
573
574   // Check if "byte1" and "byte2" can compose a valid Kanji letter (2-byte Shift_JIS letter). The
575   // numbers are from http://ja.wikipedia.org/wiki/Shift_JIS.
576   static boolean isValidKanji(final int byte1, final int byte2) {
577     return (byte2 != 0x7f &&
578         ((byte1 >= 0x81 && byte1 <= 0x9f &&
579             byte2 >= 0x40 && byte2 <= 0xfc) ||
580             ((byte1 >= 0xe0 && byte1 <= 0xfc &&
581                 byte2 >= 0x40 && byte2 <= 0xfc))));
582   }
583
584   // Check if "bytes" is a valid Kanji sequence. Used by the unit tests.
585   static boolean isValidKanjiSequence(final ByteArray bytes) {
586     if (bytes.size() % 2 != 0) {
587       return false;
588     }
589     int i = 0;
590     for (; i < bytes.size(); i += 2) {
591       if (!isValidKanji(bytes.at(i), bytes.at(i + 1))) {
592         break;
593       }
594     }
595     return i == bytes.size();  // Consumed all bytes?
596   }
597
598 }