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.ByteArray;
22 import com.google.zxing.common.ByteMatrix;
23 import com.google.zxing.common.CharacterSetECI;
24 import com.google.zxing.common.reedsolomon.GF256;
25 import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
26 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
27 import com.google.zxing.qrcode.decoder.Mode;
28 import com.google.zxing.qrcode.decoder.Version;
30 import java.io.UnsupportedEncodingException;
31 import java.util.Hashtable;
32 import java.util.Vector;
35 * @author satorux@google.com (Satoru Takabayashi) - creator
36 * @author dswitkin@google.com (Daniel Switkin) - ported from C++
38 public final class Encoder {
40 // The original table is defined in the table 5 of JISX0510:2004 (p.19).
41 private static final int[] ALPHANUMERIC_TABLE = {
42 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f
43 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f
44 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f
45 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f
46 -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f
47 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f
50 static final String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1";
55 // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
56 // Basically it applies four rules and summate all penalties.
57 private static int calculateMaskPenalty(ByteMatrix matrix) {
59 penalty += MaskUtil.applyMaskPenaltyRule1(matrix);
60 penalty += MaskUtil.applyMaskPenaltyRule2(matrix);
61 penalty += MaskUtil.applyMaskPenaltyRule3(matrix);
62 penalty += MaskUtil.applyMaskPenaltyRule4(matrix);
67 * Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
68 * internally by chooseMode(). On success, store the result in "qrCode".
70 * We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
71 * "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
72 * strong error correction for this purpose.
74 * Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
75 * with which clients can specify the encoding mode. For now, we don't need the functionality.
77 public static void encode(String content, ErrorCorrectionLevel ecLevel, QRCode qrCode)
78 throws WriterException {
79 encode(content, ecLevel, null, qrCode);
82 public static void encode(String content, ErrorCorrectionLevel ecLevel, Hashtable hints,
83 QRCode qrCode) throws WriterException {
85 String encoding = hints == null ? null : (String) hints.get(EncodeHintType.CHARACTER_SET);
86 if (encoding == null) {
87 encoding = DEFAULT_BYTE_MODE_ENCODING;
90 // Step 1: Choose the mode (encoding).
91 Mode mode = chooseMode(content, encoding);
93 // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
94 BitVector dataBits = new BitVector();
95 appendBytes(content, mode, dataBits, encoding);
96 // Step 3: Initialize QR code that can contain "dataBits".
97 int numInputBytes = dataBits.sizeInBytes();
98 initQRCode(numInputBytes, ecLevel, mode, qrCode);
100 // Step 4: Build another bit vector that contains header and data.
101 BitVector headerAndDataBits = new BitVector();
103 // Step 4.5: Append ECI message if applicable
104 if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) {
105 CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
107 appendECI(eci, headerAndDataBits);
111 appendModeInfo(mode, headerAndDataBits);
113 int numLetters = mode.equals(Mode.BYTE) ? dataBits.sizeInBytes() : content.length();
114 appendLengthInfo(numLetters, qrCode.getVersion(), mode, headerAndDataBits);
115 headerAndDataBits.appendBitVector(dataBits);
117 // Step 5: Terminate the bits properly.
118 terminateBits(qrCode.getNumDataBytes(), headerAndDataBits);
120 // Step 6: Interleave data bits with error correction code.
121 BitVector finalBits = new BitVector();
122 interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(),
123 qrCode.getNumRSBlocks(), finalBits);
125 // Step 7: Choose the mask pattern and set to "qrCode".
126 ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth());
127 qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
130 // Step 8. Build the matrix and set it to "qrCode".
131 MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
132 qrCode.getMaskPattern(), matrix);
133 qrCode.setMatrix(matrix);
134 // Step 9. Make sure we have a valid QR Code.
135 if (!qrCode.isValid()) {
136 throw new WriterException("Invalid QR code: " + qrCode.toString());
141 * @return the code point of the table used in alphanumeric mode or
142 * -1 if there is no corresponding code in the table.
144 static int getAlphanumericCode(int code) {
145 if (code < ALPHANUMERIC_TABLE.length) {
146 return ALPHANUMERIC_TABLE[code];
151 public static Mode chooseMode(String content) {
152 return chooseMode(content, null);
156 * Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
157 * if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
159 public static Mode chooseMode(String content, String encoding) {
160 if ("Shift_JIS".equals(encoding)) {
161 // Choose Kanji mode if all input are double-byte characters
162 return isOnlyDoubleByteKanji(content) ? Mode.KANJI : Mode.BYTE;
164 boolean hasNumeric = false;
165 boolean hasAlphanumeric = false;
166 for (int i = 0; i < content.length(); ++i) {
167 char c = content.charAt(i);
168 if (c >= '0' && c <= '9') {
170 } else if (getAlphanumericCode(c) != -1) {
171 hasAlphanumeric = true;
176 if (hasAlphanumeric) {
177 return Mode.ALPHANUMERIC;
178 } else if (hasNumeric) {
184 private static boolean isOnlyDoubleByteKanji(String content) {
187 bytes = content.getBytes("Shift_JIS");
188 } catch (UnsupportedEncodingException uee) {
191 int length = bytes.length;
192 if (length % 2 != 0) {
195 for (int i = 0; i < length; i += 2) {
196 int byte1 = bytes[i] & 0xFF;
197 if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) {
204 private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version,
205 ByteMatrix matrix) throws WriterException {
207 int minPenalty = Integer.MAX_VALUE; // Lower penalty is better.
208 int bestMaskPattern = -1;
209 // We try all mask patterns to choose the best one.
210 for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
211 MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
212 int penalty = calculateMaskPenalty(matrix);
213 if (penalty < minPenalty) {
214 minPenalty = penalty;
215 bestMaskPattern = maskPattern;
218 return bestMaskPattern;
222 * Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success,
225 private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode,
226 QRCode qrCode) throws WriterException {
227 qrCode.setECLevel(ecLevel);
228 qrCode.setMode(mode);
230 // In the following comments, we use numbers of Version 7-H.
231 for (int versionNum = 1; versionNum <= 40; versionNum++) {
232 Version version = Version.getVersionForNumber(versionNum);
234 int numBytes = version.getTotalCodewords();
235 // getNumECBytes = 130
236 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
237 int numEcBytes = ecBlocks.getTotalECCodewords();
238 // getNumRSBlocks = 5
239 int numRSBlocks = ecBlocks.getNumBlocks();
240 // getNumDataBytes = 196 - 130 = 66
241 int numDataBytes = numBytes - numEcBytes;
242 // We want to choose the smallest version which can contain data of "numInputBytes" + some
243 // extra bits for the header (mode info and length info). The header can be three bytes
244 // (precisely 4 + 16 bits) at most. Hence we do +3 here.
245 if (numDataBytes >= numInputBytes + 3) {
246 // Yay, we found the proper rs block info!
247 qrCode.setVersion(versionNum);
248 qrCode.setNumTotalBytes(numBytes);
249 qrCode.setNumDataBytes(numDataBytes);
250 qrCode.setNumRSBlocks(numRSBlocks);
251 // getNumECBytes = 196 - 66 = 130
252 qrCode.setNumECBytes(numEcBytes);
253 // matrix width = 21 + 6 * 4 = 45
254 qrCode.setMatrixWidth(version.getDimensionForVersion());
258 throw new WriterException("Cannot find proper rs block info (input data too big?)");
262 * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
264 static void terminateBits(int numDataBytes, BitVector bits) throws WriterException {
265 int capacity = numDataBytes << 3;
266 if (bits.size() > capacity) {
267 throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " +
270 // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
271 // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if
272 // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes
274 for (int i = 0; i < 4 && bits.size() < capacity; ++i) {
277 int numBitsInLastByte = bits.size() % 8;
278 // If the last byte isn't 8-bit aligned, we'll add padding bits.
279 if (numBitsInLastByte > 0) {
280 int numPaddingBits = 8 - numBitsInLastByte;
281 for (int i = 0; i < numPaddingBits; ++i) {
285 // Should be 8-bit aligned here.
286 if (bits.size() % 8 != 0) {
287 throw new WriterException("Number of bits is not a multiple of 8");
289 // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
290 int numPaddingBytes = numDataBytes - bits.sizeInBytes();
291 for (int i = 0; i < numPaddingBytes; ++i) {
293 bits.appendBits(0xec, 8);
295 bits.appendBits(0x11, 8);
298 if (bits.size() != capacity) {
299 throw new WriterException("Bits size does not equal capacity");
304 * Get number of data bytes and number of error correction bytes for block id "blockID". Store
305 * the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
306 * JISX0510:2004 (p.30)
308 static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes,
309 int numRSBlocks, int blockID, int[] numDataBytesInBlock,
310 int[] numECBytesInBlock) throws WriterException {
311 if (blockID >= numRSBlocks) {
312 throw new WriterException("Block ID too large");
314 // numRsBlocksInGroup2 = 196 % 5 = 1
315 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
316 // numRsBlocksInGroup1 = 5 - 1 = 4
317 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
318 // numTotalBytesInGroup1 = 196 / 5 = 39
319 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
320 // numTotalBytesInGroup2 = 39 + 1 = 40
321 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
322 // numDataBytesInGroup1 = 66 / 5 = 13
323 int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
324 // numDataBytesInGroup2 = 13 + 1 = 14
325 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
326 // numEcBytesInGroup1 = 39 - 13 = 26
327 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
328 // numEcBytesInGroup2 = 40 - 14 = 26
329 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
332 if (numEcBytesInGroup1 != numEcBytesInGroup2) {
333 throw new WriterException("EC bytes mismatch");
336 if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
337 throw new WriterException("RS blocks mismatch");
339 // 196 = (13 + 26) * 4 + (14 + 26) * 1
341 ((numDataBytesInGroup1 + numEcBytesInGroup1) *
342 numRsBlocksInGroup1) +
343 ((numDataBytesInGroup2 + numEcBytesInGroup2) *
344 numRsBlocksInGroup2)) {
345 throw new WriterException("Total bytes mismatch");
348 if (blockID < numRsBlocksInGroup1) {
349 numDataBytesInBlock[0] = numDataBytesInGroup1;
350 numECBytesInBlock[0] = numEcBytesInGroup1;
352 numDataBytesInBlock[0] = numDataBytesInGroup2;
353 numECBytesInBlock[0] = numEcBytesInGroup2;
358 * Interleave "bits" with corresponding error correction bytes. On success, store the result in
359 * "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
361 static void interleaveWithECBytes(BitVector bits, int numTotalBytes,
362 int numDataBytes, int numRSBlocks, BitVector result) throws WriterException {
364 // "bits" must have "getNumDataBytes" bytes of data.
365 if (bits.sizeInBytes() != numDataBytes) {
366 throw new WriterException("Number of bits and data bytes does not match");
369 // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
370 // store the divided data bytes blocks and error correction bytes blocks into "blocks".
371 int dataBytesOffset = 0;
372 int maxNumDataBytes = 0;
373 int maxNumEcBytes = 0;
375 // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
376 Vector blocks = new Vector(numRSBlocks);
378 for (int i = 0; i < numRSBlocks; ++i) {
379 int[] numDataBytesInBlock = new int[1];
380 int[] numEcBytesInBlock = new int[1];
381 getNumDataBytesAndNumECBytesForBlockID(
382 numTotalBytes, numDataBytes, numRSBlocks, i,
383 numDataBytesInBlock, numEcBytesInBlock);
385 ByteArray dataBytes = new ByteArray();
386 dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]);
387 ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
388 blocks.addElement(new BlockPair(dataBytes, ecBytes));
390 maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size());
391 maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size());
392 dataBytesOffset += numDataBytesInBlock[0];
394 if (numDataBytes != dataBytesOffset) {
395 throw new WriterException("Data bytes does not match offset");
398 // First, place data blocks.
399 for (int i = 0; i < maxNumDataBytes; ++i) {
400 for (int j = 0; j < blocks.size(); ++j) {
401 ByteArray dataBytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
402 if (i < dataBytes.size()) {
403 result.appendBits(dataBytes.at(i), 8);
407 // Then, place error correction blocks.
408 for (int i = 0; i < maxNumEcBytes; ++i) {
409 for (int j = 0; j < blocks.size(); ++j) {
410 ByteArray ecBytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
411 if (i < ecBytes.size()) {
412 result.appendBits(ecBytes.at(i), 8);
416 if (numTotalBytes != result.sizeInBytes()) { // Should be same.
417 throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
418 result.sizeInBytes() + " differ.");
422 static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) {
423 int numDataBytes = dataBytes.size();
424 int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
425 for (int i = 0; i < numDataBytes; i++) {
426 toEncode[i] = dataBytes.at(i);
428 new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock);
430 ByteArray ecBytes = new ByteArray(numEcBytesInBlock);
431 for (int i = 0; i < numEcBytesInBlock; i++) {
432 ecBytes.set(i, toEncode[numDataBytes + i]);
438 * Append mode info. On success, store the result in "bits".
440 static void appendModeInfo(Mode mode, BitVector bits) {
441 bits.appendBits(mode.getBits(), 4);
446 * Append length info. On success, store the result in "bits".
448 static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits)
449 throws WriterException {
450 int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version));
451 if (numLetters > ((1 << numBits) - 1)) {
452 throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1));
454 bits.appendBits(numLetters, numBits);
458 * Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
460 static void appendBytes(String content, Mode mode, BitVector bits, String encoding)
461 throws WriterException {
462 if (mode.equals(Mode.NUMERIC)) {
463 appendNumericBytes(content, bits);
464 } else if (mode.equals(Mode.ALPHANUMERIC)) {
465 appendAlphanumericBytes(content, bits);
466 } else if (mode.equals(Mode.BYTE)) {
467 append8BitBytes(content, bits, encoding);
468 } else if (mode.equals(Mode.KANJI)) {
469 appendKanjiBytes(content, bits);
471 throw new WriterException("Invalid mode: " + mode);
475 static void appendNumericBytes(String content, BitVector bits) {
476 int length = content.length();
479 int num1 = content.charAt(i) - '0';
480 if (i + 2 < length) {
481 // Encode three numeric letters in ten bits.
482 int num2 = content.charAt(i + 1) - '0';
483 int num3 = content.charAt(i + 2) - '0';
484 bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
486 } else if (i + 1 < length) {
487 // Encode two numeric letters in seven bits.
488 int num2 = content.charAt(i + 1) - '0';
489 bits.appendBits(num1 * 10 + num2, 7);
492 // Encode one numeric letter in four bits.
493 bits.appendBits(num1, 4);
499 static void appendAlphanumericBytes(String content, BitVector bits) throws WriterException {
500 int length = content.length();
503 int code1 = getAlphanumericCode(content.charAt(i));
505 throw new WriterException();
507 if (i + 1 < length) {
508 int code2 = getAlphanumericCode(content.charAt(i + 1));
510 throw new WriterException();
512 // Encode two alphanumeric letters in 11 bits.
513 bits.appendBits(code1 * 45 + code2, 11);
516 // Encode one alphanumeric letter in six bits.
517 bits.appendBits(code1, 6);
523 static void append8BitBytes(String content, BitVector bits, String encoding)
524 throws WriterException {
527 bytes = content.getBytes(encoding);
528 } catch (UnsupportedEncodingException uee) {
529 throw new WriterException(uee.toString());
531 for (int i = 0; i < bytes.length; ++i) {
532 bits.appendBits(bytes[i], 8);
536 static void appendKanjiBytes(String content, BitVector bits) throws WriterException {
539 bytes = content.getBytes("Shift_JIS");
540 } catch (UnsupportedEncodingException uee) {
541 throw new WriterException(uee.toString());
543 int length = bytes.length;
544 for (int i = 0; i < length; i += 2) {
545 int byte1 = bytes[i] & 0xFF;
546 int byte2 = bytes[i + 1] & 0xFF;
547 int code = (byte1 << 8) | byte2;
549 if (code >= 0x8140 && code <= 0x9ffc) {
550 subtracted = code - 0x8140;
551 } else if (code >= 0xe040 && code <= 0xebbf) {
552 subtracted = code - 0xc140;
554 if (subtracted == -1) {
555 throw new WriterException("Invalid byte sequence");
557 int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
558 bits.appendBits(encoded, 13);
562 private static void appendECI(CharacterSetECI eci, BitVector bits) {
563 bits.appendBits(Mode.ECI.getBits(), 4);
564 // This is correct for values up to 127, which is all we need now.
565 bits.appendBits(eci.getValue(), 8);