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.WriterException;
20 import com.google.zxing.EncodeHintType;
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.util.Vector;
31 import java.util.Hashtable;
32 import java.io.UnsupportedEncodingException;
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);
66 private static final class BlockPair {
68 private final ByteArray dataBytes;
69 private final ByteArray errorCorrectionBytes;
71 BlockPair(ByteArray data, ByteArray errorCorrection) {
73 errorCorrectionBytes = errorCorrection;
76 public ByteArray getDataBytes() {
80 public ByteArray getErrorCorrectionBytes() {
81 return errorCorrectionBytes;
87 * Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
88 * internally by chooseMode(). On success, store the result in "qrCode".
90 * We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
91 * "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
92 * strong error correction for this purpose.
94 * Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
95 * with which clients can specify the encoding mode. For now, we don't need the functionality.
97 public static void encode(String content, ErrorCorrectionLevel ecLevel, QRCode qrCode)
98 throws WriterException {
99 encode(content, ecLevel, null, qrCode);
102 public static void encode(String content, ErrorCorrectionLevel ecLevel, Hashtable hints,
103 QRCode qrCode) throws WriterException {
105 String encoding = hints == null ? null : (String) hints.get(EncodeHintType.CHARACTER_SET);
106 if (encoding == null) {
107 encoding = DEFAULT_BYTE_MODE_ENCODING;
110 // Step 1: Choose the mode (encoding).
111 Mode mode = chooseMode(content, encoding);
113 // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
114 BitVector dataBits = new BitVector();
115 appendBytes(content, mode, dataBits, encoding);
116 // Step 3: Initialize QR code that can contain "dataBits".
117 int numInputBytes = dataBits.sizeInBytes();
118 initQRCode(numInputBytes, ecLevel, mode, qrCode);
120 // Step 4: Build another bit vector that contains header and data.
121 BitVector headerAndDataBits = new BitVector();
123 // Step 4.5: Append ECI message if applicable
124 if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) {
125 CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
127 appendECI(eci, headerAndDataBits);
131 appendModeInfo(mode, headerAndDataBits);
133 int numLetters = mode.equals(Mode.BYTE) ? dataBits.sizeInBytes() : content.length();
134 appendLengthInfo(numLetters, qrCode.getVersion(), mode, headerAndDataBits);
135 headerAndDataBits.appendBitVector(dataBits);
137 // Step 5: Terminate the bits properly.
138 terminateBits(qrCode.getNumDataBytes(), headerAndDataBits);
140 // Step 6: Interleave data bits with error correction code.
141 BitVector finalBits = new BitVector();
142 interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(),
143 qrCode.getNumRSBlocks(), finalBits);
145 // Step 7: Choose the mask pattern and set to "qrCode".
146 ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth());
147 qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
150 // Step 8. Build the matrix and set it to "qrCode".
151 MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(),
152 qrCode.getMaskPattern(), matrix);
153 qrCode.setMatrix(matrix);
154 // Step 9. Make sure we have a valid QR Code.
155 if (!qrCode.isValid()) {
156 throw new WriterException("Invalid QR code: " + qrCode.toString());
161 * @return the code point of the table used in alphanumeric mode or
162 * -1 if there is no corresponding code in the table.
164 static int getAlphanumericCode(int code) {
165 if (code < ALPHANUMERIC_TABLE.length) {
166 return ALPHANUMERIC_TABLE[code];
171 public static Mode chooseMode(String content) {
172 return chooseMode(content, null);
176 * Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
177 * if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
179 public static Mode chooseMode(String content, String encoding) {
180 if ("Shift_JIS".equals(encoding)) {
181 // Choose Kanji mode if all input are double-byte characters
182 return isOnlyDoubleByteKanji(content) ? Mode.KANJI : Mode.BYTE;
184 boolean hasNumeric = false;
185 boolean hasAlphanumeric = false;
186 for (int i = 0; i < content.length(); ++i) {
187 char c = content.charAt(i);
188 if (c >= '0' && c <= '9') {
190 } else if (getAlphanumericCode(c) != -1) {
191 hasAlphanumeric = true;
196 if (hasAlphanumeric) {
197 return Mode.ALPHANUMERIC;
198 } else if (hasNumeric) {
204 private static boolean isOnlyDoubleByteKanji(String content) {
207 bytes = content.getBytes("Shift_JIS");
208 } catch (UnsupportedEncodingException uee) {
211 int length = bytes.length;
212 if (length % 2 != 0) {
215 for (int i = 0; i < length; i += 2) {
216 int byte1 = bytes[i] & 0xFF;
217 if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) {
224 private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version,
225 ByteMatrix matrix) throws WriterException {
227 int minPenalty = Integer.MAX_VALUE; // Lower penalty is better.
228 int bestMaskPattern = -1;
229 // We try all mask patterns to choose the best one.
230 for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
231 MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
232 int penalty = calculateMaskPenalty(matrix);
233 if (penalty < minPenalty) {
234 minPenalty = penalty;
235 bestMaskPattern = maskPattern;
238 return bestMaskPattern;
242 * Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success,
245 private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode,
246 QRCode qrCode) throws WriterException {
247 qrCode.setECLevel(ecLevel);
248 qrCode.setMode(mode);
250 // In the following comments, we use numbers of Version 7-H.
251 for (int versionNum = 1; versionNum <= 40; versionNum++) {
252 Version version = Version.getVersionForNumber(versionNum);
254 int numBytes = version.getTotalCodewords();
255 // getNumECBytes = 130
256 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
257 int numEcBytes = ecBlocks.getTotalECCodewords();
258 // getNumRSBlocks = 5
259 int numRSBlocks = ecBlocks.getNumBlocks();
260 // getNumDataBytes = 196 - 130 = 66
261 int numDataBytes = numBytes - numEcBytes;
262 // We want to choose the smallest version which can contain data of "numInputBytes" + some
263 // extra bits for the header (mode info and length info). The header can be three bytes
264 // (precisely 4 + 16 bits) at most. Hence we do +3 here.
265 if (numDataBytes >= numInputBytes + 3) {
266 // Yay, we found the proper rs block info!
267 qrCode.setVersion(versionNum);
268 qrCode.setNumTotalBytes(numBytes);
269 qrCode.setNumDataBytes(numDataBytes);
270 qrCode.setNumRSBlocks(numRSBlocks);
271 // getNumECBytes = 196 - 66 = 130
272 qrCode.setNumECBytes(numEcBytes);
273 // matrix width = 21 + 6 * 4 = 45
274 qrCode.setMatrixWidth(version.getDimensionForVersion());
278 throw new WriterException("Cannot find proper rs block info (input data too big?)");
282 * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
284 static void terminateBits(int numDataBytes, BitVector bits) throws WriterException {
285 int capacity = numDataBytes << 3;
286 if (bits.size() > capacity) {
287 throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " +
290 // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
291 // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if
292 // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes
294 for (int i = 0; i < 4 && bits.size() < capacity; ++i) {
297 int numBitsInLastByte = bits.size() % 8;
298 // If the last byte isn't 8-bit aligned, we'll add padding bits.
299 if (numBitsInLastByte > 0) {
300 int numPaddingBits = 8 - numBitsInLastByte;
301 for (int i = 0; i < numPaddingBits; ++i) {
305 // Should be 8-bit aligned here.
306 if (bits.size() % 8 != 0) {
307 throw new WriterException("Number of bits is not a multiple of 8");
309 // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
310 int numPaddingBytes = numDataBytes - bits.sizeInBytes();
311 for (int i = 0; i < numPaddingBytes; ++i) {
313 bits.appendBits(0xec, 8);
315 bits.appendBits(0x11, 8);
318 if (bits.size() != capacity) {
319 throw new WriterException("Bits size does not equal capacity");
324 * Get number of data bytes and number of error correction bytes for block id "blockID". Store
325 * the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
326 * JISX0510:2004 (p.30)
328 static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes,
329 int numRSBlocks, int blockID, int[] numDataBytesInBlock,
330 int[] numECBytesInBlock) throws WriterException {
331 if (blockID >= numRSBlocks) {
332 throw new WriterException("Block ID too large");
334 // numRsBlocksInGroup2 = 196 % 5 = 1
335 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
336 // numRsBlocksInGroup1 = 5 - 1 = 4
337 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
338 // numTotalBytesInGroup1 = 196 / 5 = 39
339 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
340 // numTotalBytesInGroup2 = 39 + 1 = 40
341 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
342 // numDataBytesInGroup1 = 66 / 5 = 13
343 int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
344 // numDataBytesInGroup2 = 13 + 1 = 14
345 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
346 // numEcBytesInGroup1 = 39 - 13 = 26
347 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
348 // numEcBytesInGroup2 = 40 - 14 = 26
349 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
352 if (numEcBytesInGroup1 != numEcBytesInGroup2) {
353 throw new WriterException("EC bytes mismatch");
356 if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
357 throw new WriterException("RS blocks mismatch");
359 // 196 = (13 + 26) * 4 + (14 + 26) * 1
361 ((numDataBytesInGroup1 + numEcBytesInGroup1) *
362 numRsBlocksInGroup1) +
363 ((numDataBytesInGroup2 + numEcBytesInGroup2) *
364 numRsBlocksInGroup2)) {
365 throw new WriterException("Total bytes mismatch");
368 if (blockID < numRsBlocksInGroup1) {
369 numDataBytesInBlock[0] = numDataBytesInGroup1;
370 numECBytesInBlock[0] = numEcBytesInGroup1;
372 numDataBytesInBlock[0] = numDataBytesInGroup2;
373 numECBytesInBlock[0] = numEcBytesInGroup2;
378 * Interleave "bits" with corresponding error correction bytes. On success, store the result in
379 * "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
381 static void interleaveWithECBytes(BitVector bits, int numTotalBytes,
382 int numDataBytes, int numRSBlocks, BitVector result) throws WriterException {
384 // "bits" must have "getNumDataBytes" bytes of data.
385 if (bits.sizeInBytes() != numDataBytes) {
386 throw new WriterException("Number of bits and data bytes does not match");
389 // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
390 // store the divided data bytes blocks and error correction bytes blocks into "blocks".
391 int dataBytesOffset = 0;
392 int maxNumDataBytes = 0;
393 int maxNumEcBytes = 0;
395 // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
396 Vector blocks = new Vector(numRSBlocks);
398 for (int i = 0; i < numRSBlocks; ++i) {
399 int[] numDataBytesInBlock = new int[1];
400 int[] numEcBytesInBlock = new int[1];
401 getNumDataBytesAndNumECBytesForBlockID(
402 numTotalBytes, numDataBytes, numRSBlocks, i,
403 numDataBytesInBlock, numEcBytesInBlock);
405 ByteArray dataBytes = new ByteArray();
406 dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]);
407 ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
408 blocks.addElement(new BlockPair(dataBytes, ecBytes));
410 maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size());
411 maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size());
412 dataBytesOffset += numDataBytesInBlock[0];
414 if (numDataBytes != dataBytesOffset) {
415 throw new WriterException("Data bytes does not match offset");
418 // First, place data blocks.
419 for (int i = 0; i < maxNumDataBytes; ++i) {
420 for (int j = 0; j < blocks.size(); ++j) {
421 ByteArray dataBytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
422 if (i < dataBytes.size()) {
423 result.appendBits(dataBytes.at(i), 8);
427 // Then, place error correction blocks.
428 for (int i = 0; i < maxNumEcBytes; ++i) {
429 for (int j = 0; j < blocks.size(); ++j) {
430 ByteArray ecBytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
431 if (i < ecBytes.size()) {
432 result.appendBits(ecBytes.at(i), 8);
436 if (numTotalBytes != result.sizeInBytes()) { // Should be same.
437 throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
438 result.sizeInBytes() + " differ.");
442 static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) {
443 int numDataBytes = dataBytes.size();
444 int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
445 for (int i = 0; i < numDataBytes; i++) {
446 toEncode[i] = dataBytes.at(i);
448 new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock);
450 ByteArray ecBytes = new ByteArray(numEcBytesInBlock);
451 for (int i = 0; i < numEcBytesInBlock; i++) {
452 ecBytes.set(i, toEncode[numDataBytes + i]);
458 * Append mode info. On success, store the result in "bits".
460 static void appendModeInfo(Mode mode, BitVector bits) {
461 bits.appendBits(mode.getBits(), 4);
466 * Append length info. On success, store the result in "bits".
468 static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits)
469 throws WriterException {
470 int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version));
471 if (numLetters > ((1 << numBits) - 1)) {
472 throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1));
474 bits.appendBits(numLetters, numBits);
478 * Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
480 static void appendBytes(String content, Mode mode, BitVector bits, String encoding)
481 throws WriterException {
482 if (mode.equals(Mode.NUMERIC)) {
483 appendNumericBytes(content, bits);
484 } else if (mode.equals(Mode.ALPHANUMERIC)) {
485 appendAlphanumericBytes(content, bits);
486 } else if (mode.equals(Mode.BYTE)) {
487 append8BitBytes(content, bits, encoding);
488 } else if (mode.equals(Mode.KANJI)) {
489 appendKanjiBytes(content, bits);
491 throw new WriterException("Invalid mode: " + mode);
495 static void appendNumericBytes(String content, BitVector bits) {
496 int length = content.length();
499 int num1 = content.charAt(i) - '0';
500 if (i + 2 < length) {
501 // Encode three numeric letters in ten bits.
502 int num2 = content.charAt(i + 1) - '0';
503 int num3 = content.charAt(i + 2) - '0';
504 bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
506 } else if (i + 1 < length) {
507 // Encode two numeric letters in seven bits.
508 int num2 = content.charAt(i + 1) - '0';
509 bits.appendBits(num1 * 10 + num2, 7);
512 // Encode one numeric letter in four bits.
513 bits.appendBits(num1, 4);
519 static void appendAlphanumericBytes(String content, BitVector bits) throws WriterException {
520 int length = content.length();
523 int code1 = getAlphanumericCode(content.charAt(i));
525 throw new WriterException();
527 if (i + 1 < length) {
528 int code2 = getAlphanumericCode(content.charAt(i + 1));
530 throw new WriterException();
532 // Encode two alphanumeric letters in 11 bits.
533 bits.appendBits(code1 * 45 + code2, 11);
536 // Encode one alphanumeric letter in six bits.
537 bits.appendBits(code1, 6);
543 static void append8BitBytes(String content, BitVector bits, String encoding)
544 throws WriterException {
547 bytes = content.getBytes(encoding);
548 } catch (UnsupportedEncodingException uee) {
549 throw new WriterException(uee.toString());
551 for (int i = 0; i < bytes.length; ++i) {
552 bits.appendBits(bytes[i], 8);
556 static void appendKanjiBytes(String content, BitVector bits) throws WriterException {
559 bytes = content.getBytes("Shift_JIS");
560 } catch (UnsupportedEncodingException uee) {
561 throw new WriterException(uee.toString());
563 int length = bytes.length;
564 for (int i = 0; i < length; i += 2) {
565 int byte1 = bytes[i] & 0xFF;
566 int byte2 = bytes[i + 1] & 0xFF;
567 int code = (byte1 << 8) | byte2;
569 if (code >= 0x8140 && code <= 0x9ffc) {
570 subtracted = code - 0x8140;
571 } else if (code >= 0xe040 && code <= 0xebbf) {
572 subtracted = code - 0xc140;
574 if (subtracted == -1) {
575 throw new WriterException("Invalid byte sequence");
577 int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
578 bits.appendBits(encoded, 13);
582 private static void appendECI(CharacterSetECI eci, BitVector bits) {
583 bits.appendBits(Mode.ECI.getBits(), 4);
584 // This is correct for values up to 127, which is all we need now.
585 bits.appendBits(eci.getValue(), 8);