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);
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 // TODO: Why is this commented out?
126 if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) {
127 CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
129 appendECI(eci, headerAndDataBits);
133 appendModeInfo(mode, headerAndDataBits);
134 appendLengthInfo(content.length(), 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];
172 * Choose the best mode by examining the content.
174 * Note that this function does not return MODE_KANJI, as we cannot distinguish Shift_JIS from
175 * other encodings such as ISO-8859-1, from data bytes alone. For example "\xE0\xE0" can be
176 * interpreted as one character in Shift_JIS, but also two characters in ISO-8859-1.
178 public static Mode chooseMode(String content) {
179 boolean hasNumeric = false;
180 boolean hasAlphanumeric = false;
181 for (int i = 0; i < content.length(); ++i) {
182 char c = content.charAt(i);
183 if (c >= '0' && c <= '9') {
185 } else if (getAlphanumericCode(c) != -1) {
186 hasAlphanumeric = true;
191 if (hasAlphanumeric) {
192 return Mode.ALPHANUMERIC;
193 } else if (hasNumeric) {
199 private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version,
200 ByteMatrix matrix) throws WriterException {
202 int minPenalty = Integer.MAX_VALUE; // Lower penalty is better.
203 int bestMaskPattern = -1;
204 // We try all mask patterns to choose the best one.
205 for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
206 MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
207 int penalty = calculateMaskPenalty(matrix);
208 if (penalty < minPenalty) {
209 minPenalty = penalty;
210 bestMaskPattern = maskPattern;
213 return bestMaskPattern;
217 * Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success,
220 private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode,
221 QRCode qrCode) throws WriterException {
222 qrCode.setECLevel(ecLevel);
223 qrCode.setMode(mode);
225 // In the following comments, we use numbers of Version 7-H.
226 for (int versionNum = 1; versionNum <= 40; versionNum++) {
227 Version version = Version.getVersionForNumber(versionNum);
229 int numBytes = version.getTotalCodewords();
230 // getNumECBytes = 130
231 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
232 int numEcBytes = ecBlocks.getTotalECCodewords();
233 // getNumRSBlocks = 5
234 int numRSBlocks = ecBlocks.getNumBlocks();
235 // getNumDataBytes = 196 - 130 = 66
236 int numDataBytes = numBytes - numEcBytes;
237 // We want to choose the smallest version which can contain data of "numInputBytes" + some
238 // extra bits for the header (mode info and length info). The header can be three bytes
239 // (precisely 4 + 16 bits) at most. Hence we do +3 here.
240 if (numDataBytes >= numInputBytes + 3) {
241 // Yay, we found the proper rs block info!
242 qrCode.setVersion(versionNum);
243 qrCode.setNumTotalBytes(numBytes);
244 qrCode.setNumDataBytes(numDataBytes);
245 qrCode.setNumRSBlocks(numRSBlocks);
246 // getNumECBytes = 196 - 66 = 130
247 qrCode.setNumECBytes(numEcBytes);
248 // matrix width = 21 + 6 * 4 = 45
249 qrCode.setMatrixWidth(version.getDimensionForVersion());
253 throw new WriterException("Cannot find proper rs block info (input data too big?)");
257 * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
259 static void terminateBits(int numDataBytes, BitVector bits) throws WriterException {
260 int capacity = numDataBytes << 3;
261 if (bits.size() > capacity) {
262 throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " +
265 // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
266 // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if
267 // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes
269 for (int i = 0; i < 4 && bits.size() < capacity; ++i) {
272 int numBitsInLastByte = bits.size() % 8;
273 // If the last byte isn't 8-bit aligned, we'll add padding bits.
274 if (numBitsInLastByte > 0) {
275 int numPaddingBits = 8 - numBitsInLastByte;
276 for (int i = 0; i < numPaddingBits; ++i) {
280 // Should be 8-bit aligned here.
281 if (bits.size() % 8 != 0) {
282 throw new WriterException("Number of bits is not a multiple of 8");
284 // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
285 int numPaddingBytes = numDataBytes - bits.sizeInBytes();
286 for (int i = 0; i < numPaddingBytes; ++i) {
288 bits.appendBits(0xec, 8);
290 bits.appendBits(0x11, 8);
293 if (bits.size() != capacity) {
294 throw new WriterException("Bits size does not equal capacity");
299 * Get number of data bytes and number of error correction bytes for block id "blockID". Store
300 * the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
301 * JISX0510:2004 (p.30)
303 static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes,
304 int numRSBlocks, int blockID, int[] numDataBytesInBlock,
305 int[] numECBytesInBlock) throws WriterException {
306 if (blockID >= numRSBlocks) {
307 throw new WriterException("Block ID too large");
309 // numRsBlocksInGroup2 = 196 % 5 = 1
310 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
311 // numRsBlocksInGroup1 = 5 - 1 = 4
312 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
313 // numTotalBytesInGroup1 = 196 / 5 = 39
314 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
315 // numTotalBytesInGroup2 = 39 + 1 = 40
316 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
317 // numDataBytesInGroup1 = 66 / 5 = 13
318 int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
319 // numDataBytesInGroup2 = 13 + 1 = 14
320 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
321 // numEcBytesInGroup1 = 39 - 13 = 26
322 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
323 // numEcBytesInGroup2 = 40 - 14 = 26
324 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
327 if (numEcBytesInGroup1 != numEcBytesInGroup2) {
328 throw new WriterException("EC bytes mismatch");
331 if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
332 throw new WriterException("RS blocks mismatch");
334 // 196 = (13 + 26) * 4 + (14 + 26) * 1
336 ((numDataBytesInGroup1 + numEcBytesInGroup1) *
337 numRsBlocksInGroup1) +
338 ((numDataBytesInGroup2 + numEcBytesInGroup2) *
339 numRsBlocksInGroup2)) {
340 throw new WriterException("Total bytes mismatch");
343 if (blockID < numRsBlocksInGroup1) {
344 numDataBytesInBlock[0] = numDataBytesInGroup1;
345 numECBytesInBlock[0] = numEcBytesInGroup1;
347 numDataBytesInBlock[0] = numDataBytesInGroup2;
348 numECBytesInBlock[0] = numEcBytesInGroup2;
353 * Interleave "bits" with corresponding error correction bytes. On success, store the result in
354 * "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
356 static void interleaveWithECBytes(BitVector bits, int numTotalBytes,
357 int numDataBytes, int numRSBlocks, BitVector result) throws WriterException {
359 // "bits" must have "getNumDataBytes" bytes of data.
360 if (bits.sizeInBytes() != numDataBytes) {
361 throw new WriterException("Number of bits and data bytes does not match");
364 // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
365 // store the divided data bytes blocks and error correction bytes blocks into "blocks".
366 int dataBytesOffset = 0;
367 int maxNumDataBytes = 0;
368 int maxNumEcBytes = 0;
370 // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
371 Vector blocks = new Vector(numRSBlocks);
373 for (int i = 0; i < numRSBlocks; ++i) {
374 int[] numDataBytesInBlock = new int[1];
375 int[] numEcBytesInBlock = new int[1];
376 getNumDataBytesAndNumECBytesForBlockID(
377 numTotalBytes, numDataBytes, numRSBlocks, i,
378 numDataBytesInBlock, numEcBytesInBlock);
380 ByteArray dataBytes = new ByteArray();
381 dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]);
382 ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
383 blocks.addElement(new BlockPair(dataBytes, ecBytes));
385 maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size());
386 maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size());
387 dataBytesOffset += numDataBytesInBlock[0];
389 if (numDataBytes != dataBytesOffset) {
390 throw new WriterException("Data bytes does not match offset");
393 // First, place data blocks.
394 for (int i = 0; i < maxNumDataBytes; ++i) {
395 for (int j = 0; j < blocks.size(); ++j) {
396 ByteArray dataBytes = ((BlockPair) blocks.elementAt(j)).getDataBytes();
397 if (i < dataBytes.size()) {
398 result.appendBits(dataBytes.at(i), 8);
402 // Then, place error correction blocks.
403 for (int i = 0; i < maxNumEcBytes; ++i) {
404 for (int j = 0; j < blocks.size(); ++j) {
405 ByteArray ecBytes = ((BlockPair) blocks.elementAt(j)).getErrorCorrectionBytes();
406 if (i < ecBytes.size()) {
407 result.appendBits(ecBytes.at(i), 8);
411 if (numTotalBytes != result.sizeInBytes()) { // Should be same.
412 throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
413 result.sizeInBytes() + " differ.");
417 static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) {
418 int numDataBytes = dataBytes.size();
419 int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
420 for (int i = 0; i < numDataBytes; i++) {
421 toEncode[i] = dataBytes.at(i);
423 new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock);
425 ByteArray ecBytes = new ByteArray(numEcBytesInBlock);
426 for (int i = 0; i < numEcBytesInBlock; i++) {
427 ecBytes.set(i, toEncode[numDataBytes + i]);
433 * Append mode info. On success, store the result in "bits".
435 static void appendModeInfo(Mode mode, BitVector bits) {
436 bits.appendBits(mode.getBits(), 4);
441 * Append length info. On success, store the result in "bits".
443 static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits)
444 throws WriterException {
445 int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version));
446 if (numLetters > ((1 << numBits) - 1)) {
447 throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1));
449 bits.appendBits(numLetters, numBits);
453 * Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
455 static void appendBytes(String content, Mode mode, BitVector bits, String encoding)
456 throws WriterException {
457 if (mode.equals(Mode.NUMERIC)) {
458 appendNumericBytes(content, bits);
459 } else if (mode.equals(Mode.ALPHANUMERIC)) {
460 appendAlphanumericBytes(content, bits);
461 } else if (mode.equals(Mode.BYTE)) {
462 append8BitBytes(content, bits, encoding);
463 } else if (mode.equals(Mode.KANJI)) {
464 appendKanjiBytes(content, bits);
466 throw new WriterException("Invalid mode: " + mode);
470 static void appendNumericBytes(String content, BitVector bits) {
471 int length = content.length();
474 int num1 = content.charAt(i) - '0';
475 if (i + 2 < length) {
476 // Encode three numeric letters in ten bits.
477 int num2 = content.charAt(i + 1) - '0';
478 int num3 = content.charAt(i + 2) - '0';
479 bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
481 } else if (i + 1 < length) {
482 // Encode two numeric letters in seven bits.
483 int num2 = content.charAt(i + 1) - '0';
484 bits.appendBits(num1 * 10 + num2, 7);
487 // Encode one numeric letter in four bits.
488 bits.appendBits(num1, 4);
494 static void appendAlphanumericBytes(String content, BitVector bits) throws WriterException {
495 int length = content.length();
498 int code1 = getAlphanumericCode(content.charAt(i));
500 throw new WriterException();
502 if (i + 1 < length) {
503 int code2 = getAlphanumericCode(content.charAt(i + 1));
505 throw new WriterException();
507 // Encode two alphanumeric letters in 11 bits.
508 bits.appendBits(code1 * 45 + code2, 11);
511 // Encode one alphanumeric letter in six bits.
512 bits.appendBits(code1, 6);
518 static void append8BitBytes(String content, BitVector bits, String encoding)
519 throws WriterException {
522 bytes = content.getBytes(encoding);
523 } catch (UnsupportedEncodingException uee) {
524 throw new WriterException(uee.toString());
526 for (int i = 0; i < bytes.length; ++i) {
527 bits.appendBits(bytes[i], 8);
531 static void appendKanjiBytes(String content, BitVector bits) throws WriterException {
534 bytes = content.getBytes("Shift_JIS");
535 } catch (UnsupportedEncodingException uee) {
536 throw new WriterException(uee.toString());
538 int length = bytes.length;
539 for (int i = 0; i < length; i += 2) {
540 int byte1 = bytes[i] & 0xFF;
541 int byte2 = bytes[i + 1] & 0xFF;
542 int code = (byte1 << 8) | byte2;
544 if (code >= 0x8140 && code <= 0x9ffc) {
545 subtracted = code - 0x8140;
546 } else if (code >= 0xe040 && code <= 0xebbf) {
547 subtracted = code - 0xc140;
549 if (subtracted == -1) {
550 throw new WriterException("Invalid byte sequence");
552 int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
553 bits.appendBits(encoded, 13);
557 static void appendECI(CharacterSetECI eci, BitVector bits) {
558 bits.appendBits(Mode.ECI.getBits(), 4);
559 // This is correct for values up to 127, which is all we need now.
560 bits.appendBits(eci.getValue(), 8);