2 * Copyright 2008 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.qrcode.encoder;
19 import com.google.zxing.EncodeHintType;
20 import com.google.zxing.WriterException;
21 import com.google.zxing.common.BitArray;
22 import com.google.zxing.common.CharacterSetECI;
23 import com.google.zxing.common.reedsolomon.GF256;
24 import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
25 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
26 import com.google.zxing.qrcode.decoder.Mode;
27 import com.google.zxing.qrcode.decoder.Version;
29 import java.io.UnsupportedEncodingException;
30 import java.util.Hashtable;
31 import java.util.Vector;
34 * @author satorux@google.com (Satoru Takabayashi) - creator
35 * @author dswitkin@google.com (Daniel Switkin) - ported from C++
37 public final class Encoder {
39 // The original table is defined in the table 5 of JISX0510:2004 (p.19).
40 private static final int[] ALPHANUMERIC_TABLE = {
41 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f
42 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f
43 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f
44 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f
45 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f
46 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f
49 static final String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1";
54 // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
55 // Basically it applies four rules and summate all penalties.
56 private static int calculateMaskPenalty(ByteMatrix matrix) {
58 penalty += MaskUtil.applyMaskPenaltyRule1(matrix);
59 penalty += MaskUtil.applyMaskPenaltyRule2(matrix);
60 penalty += MaskUtil.applyMaskPenaltyRule3(matrix);
61 penalty += MaskUtil.applyMaskPenaltyRule4(matrix);
66 * Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
67 * internally by chooseMode(). On success, store the result in "qrCode".
69 * We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
70 * "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
71 * strong error correction for this purpose.
73 * Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
74 * with which clients can specify the encoding mode. For now, we don't need the functionality.
76 public static void encode(String content, ErrorCorrectionLevel ecLevel, QRCode qrCode)
77 throws WriterException {
78 encode(content, ecLevel, null, qrCode);
81 public static void encode(String content, ErrorCorrectionLevel ecLevel, Hashtable hints,
82 QRCode qrCode) throws WriterException {
84 String encoding = hints == null ? null : (String) hints.get(EncodeHintType.CHARACTER_SET);
85 if (encoding == null) {
86 encoding = DEFAULT_BYTE_MODE_ENCODING;
89 // Step 1: Choose the mode (encoding).
90 Mode mode = chooseMode(content, encoding);
92 // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
93 BitArray dataBits = new BitArray();
94 appendBytes(content, mode, dataBits, encoding);
95 // Step 3: Initialize QR code that can contain "dataBits".
96 int numInputBytes = dataBits.getSizeInBytes();
97 initQRCode(numInputBytes, ecLevel, mode, qrCode);
99 // Step 4: Build another bit vector that contains header and data.
100 BitArray headerAndDataBits = new BitArray();
102 // Step 4.5: Append ECI message if applicable
103 if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) {
104 CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
106 appendECI(eci, headerAndDataBits);
110 appendModeInfo(mode, headerAndDataBits);
112 int numLetters = mode.equals(Mode.BYTE) ? dataBits.getSizeInBytes() : content.length();
113 appendLengthInfo(numLetters, qrCode.getVersion(), mode, headerAndDataBits);
114 headerAndDataBits.appendBitArray(dataBits);
116 // Step 5: Terminate the bits properly.
117 terminateBits(qrCode.getNumDataBytes(), headerAndDataBits);
119 // Step 6: Interleave data bits with error correction code.
120 BitArray finalBits = new BitArray();
121 interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(),
122 qrCode.getNumRSBlocks(), finalBits);
124 // Step 7: Choose the mask pattern and set to "qrCode".
125 ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth());
126 qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
129 // Step 8. Build the matrix and set it to "qrCode".
130 MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
131 qrCode.getMaskPattern(), matrix);
132 qrCode.setMatrix(matrix);
133 // Step 9. Make sure we have a valid QR Code.
134 if (!qrCode.isValid()) {
135 throw new WriterException("Invalid QR code: " + qrCode.toString());
140 * @return the code point of the table used in alphanumeric mode or
141 * -1 if there is no corresponding code in the table.
143 static int getAlphanumericCode(int code) {
144 if (code < ALPHANUMERIC_TABLE.length) {
145 return ALPHANUMERIC_TABLE[code];
150 public static Mode chooseMode(String content) {
151 return chooseMode(content, null);
155 * Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
156 * if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
158 public static Mode chooseMode(String content, String encoding) {
159 if ("Shift_JIS".equals(encoding)) {
160 // Choose Kanji mode if all input are double-byte characters
161 return isOnlyDoubleByteKanji(content) ? Mode.KANJI : Mode.BYTE;
163 boolean hasNumeric = false;
164 boolean hasAlphanumeric = false;
165 for (int i = 0; i < content.length(); ++i) {
166 char c = content.charAt(i);
167 if (c >= '0' && c <= '9') {
169 } else if (getAlphanumericCode(c) != -1) {
170 hasAlphanumeric = true;
175 if (hasAlphanumeric) {
176 return Mode.ALPHANUMERIC;
177 } else if (hasNumeric) {
183 private static boolean isOnlyDoubleByteKanji(String content) {
186 bytes = content.getBytes("Shift_JIS");
187 } catch (UnsupportedEncodingException uee) {
190 int length = bytes.length;
191 if (length % 2 != 0) {
194 for (int i = 0; i < length; i += 2) {
195 int byte1 = bytes[i] & 0xFF;
196 if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) {
203 private static int chooseMaskPattern(BitArray bits, ErrorCorrectionLevel ecLevel, int version,
204 ByteMatrix matrix) throws WriterException {
206 int minPenalty = Integer.MAX_VALUE; // Lower penalty is better.
207 int bestMaskPattern = -1;
208 // We try all mask patterns to choose the best one.
209 for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
210 MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
211 int penalty = calculateMaskPenalty(matrix);
212 if (penalty < minPenalty) {
213 minPenalty = penalty;
214 bestMaskPattern = maskPattern;
217 return bestMaskPattern;
221 * Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success,
224 private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode,
225 QRCode qrCode) throws WriterException {
226 qrCode.setECLevel(ecLevel);
227 qrCode.setMode(mode);
229 // In the following comments, we use numbers of Version 7-H.
230 for (int versionNum = 1; versionNum <= 40; versionNum++) {
231 Version version = Version.getVersionForNumber(versionNum);
233 int numBytes = version.getTotalCodewords();
234 // getNumECBytes = 130
235 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
236 int numEcBytes = ecBlocks.getTotalECCodewords();
237 // getNumRSBlocks = 5
238 int numRSBlocks = ecBlocks.getNumBlocks();
239 // getNumDataBytes = 196 - 130 = 66
240 int numDataBytes = numBytes - numEcBytes;
241 // We want to choose the smallest version which can contain data of "numInputBytes" + some
242 // extra bits for the header (mode info and length info). The header can be three bytes
243 // (precisely 4 + 16 bits) at most. Hence we do +3 here.
244 if (numDataBytes >= numInputBytes + 3) {
245 // Yay, we found the proper rs block info!
246 qrCode.setVersion(versionNum);
247 qrCode.setNumTotalBytes(numBytes);
248 qrCode.setNumDataBytes(numDataBytes);
249 qrCode.setNumRSBlocks(numRSBlocks);
250 // getNumECBytes = 196 - 66 = 130
251 qrCode.setNumECBytes(numEcBytes);
252 // matrix width = 21 + 6 * 4 = 45
253 qrCode.setMatrixWidth(version.getDimensionForVersion());
257 throw new WriterException("Cannot find proper rs block info (input data too big?)");
261 * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
263 static void terminateBits(int numDataBytes, BitArray bits) throws WriterException {
264 int capacity = numDataBytes << 3;
265 if (bits.getSize() > capacity) {
266 throw new WriterException("data bits cannot fit in the QR Code" + bits.getSize() + " > " +
269 for (int i = 0; i < 4 && bits.getSize() < capacity; ++i) {
270 bits.appendBit(false);
272 // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
273 // If the last byte isn't 8-bit aligned, we'll add padding bits.
274 int numBitsInLastByte = bits.getSize() & 0x07;
275 if (numBitsInLastByte > 0) {
276 for (int i = numBitsInLastByte; i < 8; i++) {
277 bits.appendBit(false);
280 // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
281 int numPaddingBytes = numDataBytes - bits.getSizeInBytes();
282 for (int i = 0; i < numPaddingBytes; ++i) {
283 bits.appendBits(((i & 0x01) == 0) ? 0xEC : 0x11, 8);
285 if (bits.getSize() != capacity) {
286 throw new WriterException("Bits size does not equal capacity");
291 * Get number of data bytes and number of error correction bytes for block id "blockID". Store
292 * the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
293 * JISX0510:2004 (p.30)
295 static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes,
296 int numRSBlocks, int blockID, int[] numDataBytesInBlock,
297 int[] numECBytesInBlock) throws WriterException {
298 if (blockID >= numRSBlocks) {
299 throw new WriterException("Block ID too large");
301 // numRsBlocksInGroup2 = 196 % 5 = 1
302 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
303 // numRsBlocksInGroup1 = 5 - 1 = 4
304 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
305 // numTotalBytesInGroup1 = 196 / 5 = 39
306 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
307 // numTotalBytesInGroup2 = 39 + 1 = 40
308 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
309 // numDataBytesInGroup1 = 66 / 5 = 13
310 int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
311 // numDataBytesInGroup2 = 13 + 1 = 14
312 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
313 // numEcBytesInGroup1 = 39 - 13 = 26
314 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
315 // numEcBytesInGroup2 = 40 - 14 = 26
316 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
319 if (numEcBytesInGroup1 != numEcBytesInGroup2) {
320 throw new WriterException("EC bytes mismatch");
323 if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
324 throw new WriterException("RS blocks mismatch");
326 // 196 = (13 + 26) * 4 + (14 + 26) * 1
328 ((numDataBytesInGroup1 + numEcBytesInGroup1) *
329 numRsBlocksInGroup1) +
330 ((numDataBytesInGroup2 + numEcBytesInGroup2) *
331 numRsBlocksInGroup2)) {
332 throw new WriterException("Total bytes mismatch");
335 if (blockID < numRsBlocksInGroup1) {
336 numDataBytesInBlock[0] = numDataBytesInGroup1;
337 numECBytesInBlock[0] = numEcBytesInGroup1;
339 numDataBytesInBlock[0] = numDataBytesInGroup2;
340 numECBytesInBlock[0] = numEcBytesInGroup2;
345 * Interleave "bits" with corresponding error correction bytes. On success, store the result in
346 * "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
348 static void interleaveWithECBytes(BitArray bits, int numTotalBytes,
349 int numDataBytes, int numRSBlocks, BitArray result) throws WriterException {
351 // "bits" must have "getNumDataBytes" bytes of data.
352 if (bits.getSizeInBytes() != numDataBytes) {
353 throw new WriterException("Number of bits and data bytes does not match");
356 // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
357 // store the divided data bytes blocks and error correction bytes blocks into "blocks".
358 int dataBytesOffset = 0;
359 int maxNumDataBytes = 0;
360 int maxNumEcBytes = 0;
362 // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
363 Vector blocks = new Vector(numRSBlocks);
365 for (int i = 0; i < numRSBlocks; ++i) {
366 int[] numDataBytesInBlock = new int[1];
367 int[] numEcBytesInBlock = new int[1];
368 getNumDataBytesAndNumECBytesForBlockID(
369 numTotalBytes, numDataBytes, numRSBlocks, i,
370 numDataBytesInBlock, numEcBytesInBlock);
372 int size = numDataBytesInBlock[0];
373 byte[] dataBytes = new byte[size];
374 bits.toBytes(8*dataBytesOffset, dataBytes, 0, size);
375 byte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
376 blocks.addElement(new BlockPair(dataBytes, ecBytes));
378 maxNumDataBytes = Math.max(maxNumDataBytes, size);
379 maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.length);
380 dataBytesOffset += numDataBytesInBlock[0];
382 if (numDataBytes != dataBytesOffset) {
383 throw new WriterException("Data bytes does not match offset");
386 // First, place data blocks.
387 for (int i = 0; i < maxNumDataBytes; ++i) {
388 for (int j = 0; j < blocks.size(); ++j) {
389 byte[] dataBytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
390 if (i < dataBytes.length) {
391 result.appendBits(dataBytes[i], 8);
395 // Then, place error correction blocks.
396 for (int i = 0; i < maxNumEcBytes; ++i) {
397 for (int j = 0; j < blocks.size(); ++j) {
398 byte[] ecBytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
399 if (i < ecBytes.length) {
400 result.appendBits(ecBytes[i], 8);
404 if (numTotalBytes != result.getSizeInBytes()) { // Should be same.
405 throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
406 result.getSizeInBytes() + " differ.");
410 static byte[] generateECBytes(byte[] dataBytes, int numEcBytesInBlock) {
411 int numDataBytes = dataBytes.length;
412 int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
413 for (int i = 0; i < numDataBytes; i++) {
414 toEncode[i] = dataBytes[i] & 0xFF;
416 new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock);
418 byte[] ecBytes = new byte[numEcBytesInBlock];
419 for (int i = 0; i < numEcBytesInBlock; i++) {
420 ecBytes[i] = (byte) toEncode[numDataBytes + i];
426 * Append mode info. On success, store the result in "bits".
428 static void appendModeInfo(Mode mode, BitArray bits) {
429 bits.appendBits(mode.getBits(), 4);
434 * Append length info. On success, store the result in "bits".
436 static void appendLengthInfo(int numLetters, int version, Mode mode, BitArray bits)
437 throws WriterException {
438 int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version));
439 if (numLetters > ((1 << numBits) - 1)) {
440 throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1));
442 bits.appendBits(numLetters, numBits);
446 * Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
448 static void appendBytes(String content, Mode mode, BitArray bits, String encoding)
449 throws WriterException {
450 if (mode.equals(Mode.NUMERIC)) {
451 appendNumericBytes(content, bits);
452 } else if (mode.equals(Mode.ALPHANUMERIC)) {
453 appendAlphanumericBytes(content, bits);
454 } else if (mode.equals(Mode.BYTE)) {
455 append8BitBytes(content, bits, encoding);
456 } else if (mode.equals(Mode.KANJI)) {
457 appendKanjiBytes(content, bits);
459 throw new WriterException("Invalid mode: " + mode);
463 static void appendNumericBytes(String content, BitArray bits) {
464 int length = content.length();
467 int num1 = content.charAt(i) - '0';
468 if (i + 2 < length) {
469 // Encode three numeric letters in ten bits.
470 int num2 = content.charAt(i + 1) - '0';
471 int num3 = content.charAt(i + 2) - '0';
472 bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
474 } else if (i + 1 < length) {
475 // Encode two numeric letters in seven bits.
476 int num2 = content.charAt(i + 1) - '0';
477 bits.appendBits(num1 * 10 + num2, 7);
480 // Encode one numeric letter in four bits.
481 bits.appendBits(num1, 4);
487 static void appendAlphanumericBytes(String content, BitArray bits) throws WriterException {
488 int length = content.length();
491 int code1 = getAlphanumericCode(content.charAt(i));
493 throw new WriterException();
495 if (i + 1 < length) {
496 int code2 = getAlphanumericCode(content.charAt(i + 1));
498 throw new WriterException();
500 // Encode two alphanumeric letters in 11 bits.
501 bits.appendBits(code1 * 45 + code2, 11);
504 // Encode one alphanumeric letter in six bits.
505 bits.appendBits(code1, 6);
511 static void append8BitBytes(String content, BitArray bits, String encoding)
512 throws WriterException {
515 bytes = content.getBytes(encoding);
516 } catch (UnsupportedEncodingException uee) {
517 throw new WriterException(uee.toString());
519 for (int i = 0; i < bytes.length; ++i) {
520 bits.appendBits(bytes[i], 8);
524 static void appendKanjiBytes(String content, BitArray bits) throws WriterException {
527 bytes = content.getBytes("Shift_JIS");
528 } catch (UnsupportedEncodingException uee) {
529 throw new WriterException(uee.toString());
531 int length = bytes.length;
532 for (int i = 0; i < length; i += 2) {
533 int byte1 = bytes[i] & 0xFF;
534 int byte2 = bytes[i + 1] & 0xFF;
535 int code = (byte1 << 8) | byte2;
537 if (code >= 0x8140 && code <= 0x9ffc) {
538 subtracted = code - 0x8140;
539 } else if (code >= 0xe040 && code <= 0xebbf) {
540 subtracted = code - 0xc140;
542 if (subtracted == -1) {
543 throw new WriterException("Invalid byte sequence");
545 int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
546 bits.appendBits(encoded, 13);
550 private static void appendECI(CharacterSetECI eci, BitArray bits) {
551 bits.appendBits(Mode.ECI.getBits(), 4);
552 // This is correct for values up to 127, which is all we need now.
553 bits.appendBits(eci.getValue(), 8);