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