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 then we assume the input is Kanji and return {@link Mode#KANJI}.
179 public static Mode chooseMode(String content, String encoding) {
180 if ("Shift_JIS".equals(encoding)) {
183 boolean hasNumeric = false;
184 boolean hasAlphanumeric = false;
185 for (int i = 0; i < content.length(); ++i) {
186 char c = content.charAt(i);
187 if (c >= '0' && c <= '9') {
189 } else if (getAlphanumericCode(c) != -1) {
190 hasAlphanumeric = true;
195 if (hasAlphanumeric) {
196 return Mode.ALPHANUMERIC;
197 } else if (hasNumeric) {
203 private static int chooseMaskPattern(BitVector 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, BitVector bits) throws WriterException {
264 int capacity = numDataBytes << 3;
265 if (bits.size() > capacity) {
266 throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " +
269 // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
270 // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if
271 // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes
273 for (int i = 0; i < 4 && bits.size() < capacity; ++i) {
276 int numBitsInLastByte = bits.size() % 8;
277 // If the last byte isn't 8-bit aligned, we'll add padding bits.
278 if (numBitsInLastByte > 0) {
279 int numPaddingBits = 8 - numBitsInLastByte;
280 for (int i = 0; i < numPaddingBits; ++i) {
284 // Should be 8-bit aligned here.
285 if (bits.size() % 8 != 0) {
286 throw new WriterException("Number of bits is not a multiple of 8");
288 // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
289 int numPaddingBytes = numDataBytes - bits.sizeInBytes();
290 for (int i = 0; i < numPaddingBytes; ++i) {
292 bits.appendBits(0xec, 8);
294 bits.appendBits(0x11, 8);
297 if (bits.size() != capacity) {
298 throw new WriterException("Bits size does not equal capacity");
303 * Get number of data bytes and number of error correction bytes for block id "blockID". Store
304 * the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
305 * JISX0510:2004 (p.30)
307 static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes,
308 int numRSBlocks, int blockID, int[] numDataBytesInBlock,
309 int[] numECBytesInBlock) throws WriterException {
310 if (blockID >= numRSBlocks) {
311 throw new WriterException("Block ID too large");
313 // numRsBlocksInGroup2 = 196 % 5 = 1
314 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
315 // numRsBlocksInGroup1 = 5 - 1 = 4
316 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
317 // numTotalBytesInGroup1 = 196 / 5 = 39
318 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
319 // numTotalBytesInGroup2 = 39 + 1 = 40
320 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
321 // numDataBytesInGroup1 = 66 / 5 = 13
322 int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
323 // numDataBytesInGroup2 = 13 + 1 = 14
324 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
325 // numEcBytesInGroup1 = 39 - 13 = 26
326 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
327 // numEcBytesInGroup2 = 40 - 14 = 26
328 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
331 if (numEcBytesInGroup1 != numEcBytesInGroup2) {
332 throw new WriterException("EC bytes mismatch");
335 if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
336 throw new WriterException("RS blocks mismatch");
338 // 196 = (13 + 26) * 4 + (14 + 26) * 1
340 ((numDataBytesInGroup1 + numEcBytesInGroup1) *
341 numRsBlocksInGroup1) +
342 ((numDataBytesInGroup2 + numEcBytesInGroup2) *
343 numRsBlocksInGroup2)) {
344 throw new WriterException("Total bytes mismatch");
347 if (blockID < numRsBlocksInGroup1) {
348 numDataBytesInBlock[0] = numDataBytesInGroup1;
349 numECBytesInBlock[0] = numEcBytesInGroup1;
351 numDataBytesInBlock[0] = numDataBytesInGroup2;
352 numECBytesInBlock[0] = numEcBytesInGroup2;
357 * Interleave "bits" with corresponding error correction bytes. On success, store the result in
358 * "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
360 static void interleaveWithECBytes(BitVector bits, int numTotalBytes,
361 int numDataBytes, int numRSBlocks, BitVector result) throws WriterException {
363 // "bits" must have "getNumDataBytes" bytes of data.
364 if (bits.sizeInBytes() != numDataBytes) {
365 throw new WriterException("Number of bits and data bytes does not match");
368 // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
369 // store the divided data bytes blocks and error correction bytes blocks into "blocks".
370 int dataBytesOffset = 0;
371 int maxNumDataBytes = 0;
372 int maxNumEcBytes = 0;
374 // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
375 Vector blocks = new Vector(numRSBlocks);
377 for (int i = 0; i < numRSBlocks; ++i) {
378 int[] numDataBytesInBlock = new int[1];
379 int[] numEcBytesInBlock = new int[1];
380 getNumDataBytesAndNumECBytesForBlockID(
381 numTotalBytes, numDataBytes, numRSBlocks, i,
382 numDataBytesInBlock, numEcBytesInBlock);
384 ByteArray dataBytes = new ByteArray();
385 dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]);
386 ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
387 blocks.addElement(new BlockPair(dataBytes, ecBytes));
389 maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size());
390 maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size());
391 dataBytesOffset += numDataBytesInBlock[0];
393 if (numDataBytes != dataBytesOffset) {
394 throw new WriterException("Data bytes does not match offset");
397 // First, place data blocks.
398 for (int i = 0; i < maxNumDataBytes; ++i) {
399 for (int j = 0; j < blocks.size(); ++j) {
400 ByteArray dataBytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
401 if (i < dataBytes.size()) {
402 result.appendBits(dataBytes.at(i), 8);
406 // Then, place error correction blocks.
407 for (int i = 0; i < maxNumEcBytes; ++i) {
408 for (int j = 0; j < blocks.size(); ++j) {
409 ByteArray ecBytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
410 if (i < ecBytes.size()) {
411 result.appendBits(ecBytes.at(i), 8);
415 if (numTotalBytes != result.sizeInBytes()) { // Should be same.
416 throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
417 result.sizeInBytes() + " differ.");
421 static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) {
422 int numDataBytes = dataBytes.size();
423 int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
424 for (int i = 0; i < numDataBytes; i++) {
425 toEncode[i] = dataBytes.at(i);
427 new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock);
429 ByteArray ecBytes = new ByteArray(numEcBytesInBlock);
430 for (int i = 0; i < numEcBytesInBlock; i++) {
431 ecBytes.set(i, toEncode[numDataBytes + i]);
437 * Append mode info. On success, store the result in "bits".
439 static void appendModeInfo(Mode mode, BitVector bits) {
440 bits.appendBits(mode.getBits(), 4);
445 * Append length info. On success, store the result in "bits".
447 static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits)
448 throws WriterException {
449 int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version));
450 if (numLetters > ((1 << numBits) - 1)) {
451 throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1));
453 bits.appendBits(numLetters, numBits);
457 * Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
459 static void appendBytes(String content, Mode mode, BitVector bits, String encoding)
460 throws WriterException {
461 if (mode.equals(Mode.NUMERIC)) {
462 appendNumericBytes(content, bits);
463 } else if (mode.equals(Mode.ALPHANUMERIC)) {
464 appendAlphanumericBytes(content, bits);
465 } else if (mode.equals(Mode.BYTE)) {
466 append8BitBytes(content, bits, encoding);
467 } else if (mode.equals(Mode.KANJI)) {
468 appendKanjiBytes(content, bits);
470 throw new WriterException("Invalid mode: " + mode);
474 static void appendNumericBytes(String content, BitVector bits) {
475 int length = content.length();
478 int num1 = content.charAt(i) - '0';
479 if (i + 2 < length) {
480 // Encode three numeric letters in ten bits.
481 int num2 = content.charAt(i + 1) - '0';
482 int num3 = content.charAt(i + 2) - '0';
483 bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
485 } else if (i + 1 < length) {
486 // Encode two numeric letters in seven bits.
487 int num2 = content.charAt(i + 1) - '0';
488 bits.appendBits(num1 * 10 + num2, 7);
491 // Encode one numeric letter in four bits.
492 bits.appendBits(num1, 4);
498 static void appendAlphanumericBytes(String content, BitVector bits) throws WriterException {
499 int length = content.length();
502 int code1 = getAlphanumericCode(content.charAt(i));
504 throw new WriterException();
506 if (i + 1 < length) {
507 int code2 = getAlphanumericCode(content.charAt(i + 1));
509 throw new WriterException();
511 // Encode two alphanumeric letters in 11 bits.
512 bits.appendBits(code1 * 45 + code2, 11);
515 // Encode one alphanumeric letter in six bits.
516 bits.appendBits(code1, 6);
522 static void append8BitBytes(String content, BitVector bits, String encoding)
523 throws WriterException {
526 bytes = content.getBytes(encoding);
527 } catch (UnsupportedEncodingException uee) {
528 throw new WriterException(uee.toString());
530 for (int i = 0; i < bytes.length; ++i) {
531 bits.appendBits(bytes[i], 8);
535 static void appendKanjiBytes(String content, BitVector bits) throws WriterException {
538 bytes = content.getBytes("Shift_JIS");
539 } catch (UnsupportedEncodingException uee) {
540 throw new WriterException(uee.toString());
542 int length = bytes.length;
543 for (int i = 0; i < length; i += 2) {
544 int byte1 = bytes[i] & 0xFF;
545 int byte2 = bytes[i + 1] & 0xFF;
546 int code = (byte1 << 8) | byte2;
548 if (code >= 0x8140 && code <= 0x9ffc) {
549 subtracted = code - 0x8140;
550 } else if (code >= 0xe040 && code <= 0xebbf) {
551 subtracted = code - 0xc140;
553 if (subtracted == -1) {
554 throw new WriterException("Invalid byte sequence");
556 int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
557 bits.appendBits(encoded, 13);
561 static void appendECI(CharacterSetECI eci, BitVector bits) {
562 bits.appendBits(Mode.ECI.getBits(), 4);
563 // This is correct for values up to 127, which is all we need now.
564 bits.appendBits(eci.getValue(), 8);