Merge pull request #2 from gerzees/master

1234
pull/90/head
minsu4107 5 years ago committed by GitHub
commit 0c951f296e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -126,4 +126,28 @@ public final class BitBuffer implements Cloneable {
} }
} }
// Pad with alternating bytes until data capacity is reached
public void addPad(int dataCapacityBits) {
for (int padByte = 0xEC; bitLength() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
appendBits(padByte, 8);
}
// Pack bits into bytes in big endian
public byte[] toCodewords() {
byte[] dataCodewords = new byte[bitLength() / 8];
for (int i = 0; i < bitLength(); i++)
dataCodewords[i >>> 3] |= getBit(i) << (7 - (i & 7));
return dataCodewords;
}
// Add terminator and pad up to a byte if applicable
public void addTerminator(int dataCapacityBits) {
appendBits(0, Math.min(4, dataCapacityBits - bitLength()));
appendBits(0, (8 - bitLength() % 8) % 8);
assert bitLength() % 8 == 0;
}
} }

@ -0,0 +1,17 @@
package io.nayuki.qrcodegen;
public class Button {
public Command theCommand;
public Button(Command theCommand) {
setCommand(theCommand);
}
public void setCommand(Command newCommand) {
this.theCommand = newCommand;
}
public boolean pressed(int y, int x, int msk) {
return theCommand.excute(y, x, msk);
}
}

@ -0,0 +1,5 @@
package io.nayuki.qrcodegen;
public interface Command {
public abstract boolean excute(int y, int x, int msk);
}

@ -0,0 +1,7 @@
package io.nayuki.qrcodegen;
public class Msk0 {
public boolean operation(int y, int x, int msk) {
return ((x + y) % 2 == 0);
}
}

@ -0,0 +1,7 @@
package io.nayuki.qrcodegen;
public class Msk1 {
public boolean operation(int y, int x, int msk) {
return (y % 2 == 0);
}
}

@ -0,0 +1,7 @@
package io.nayuki.qrcodegen;
public class Msk2 {
public boolean operation(int y, int x, int msk) {
return (x % 3 == 0);
}
}

@ -0,0 +1,7 @@
package io.nayuki.qrcodegen;
public class Msk3 {
public boolean operation(int y, int x, int msk) {
return ((x + y) % 3 == 0);
}
}

@ -0,0 +1,7 @@
package io.nayuki.qrcodegen;
public class Msk4 {
public boolean operation(int y, int x, int msk) {
return ((x / 3 + y / 2) % 2 == 0);
}
}

@ -0,0 +1,7 @@
package io.nayuki.qrcodegen;
public class Msk5 {
public boolean operation(int y, int x, int msk) {
return (x * y % 2 + x * y % 3 == 0);
}
}

@ -0,0 +1,7 @@
package io.nayuki.qrcodegen;
public class Msk6 {
public boolean operation(int y, int x, int msk) {
return ((x * y % 2 + x * y % 3) % 2 == 0);
}
}

@ -0,0 +1,7 @@
package io.nayuki.qrcodegen;
public class Msk7 {
public boolean operation(int y, int x, int msk) {
return (((x + y) % 2 + x * y % 3) % 2 == 0);
}
}

@ -0,0 +1,46 @@
package io.nayuki.qrcodegen;
public class MskCommandFactory {
public static Command getCommand(int msk) {
Command theCommand = null;
Msk0 msk0 = new Msk0();
Msk1 msk1 = new Msk1();
Msk2 msk2 = new Msk2();
Msk3 msk3 = new Msk3();
Msk4 msk4 = new Msk4();
Msk5 msk5 = new Msk5();
Msk6 msk6 = new Msk6();
Msk7 msk7 = new Msk7();
switch (msk) {
case 0:
theCommand = new msk0Command(msk0);
break;
case 1:
theCommand = new msk1Command(msk1);
break;
case 2:
theCommand = new msk2Command(msk2);
break;
case 3:
theCommand = new msk3Command(msk3);
break;
case 4:
theCommand = new msk4Command(msk4);
break;
case 5:
theCommand = new msk5Command(msk5);
break;
case 6:
theCommand = new msk6Command(msk6);
break;
case 7:
theCommand = new msk7Command(msk7);
break;
default:
throw new AssertionError();
}
return theCommand;
}
}

@ -151,60 +151,82 @@ public final class QrCode {
Objects.requireNonNull(segments); Objects.requireNonNull(segments);
Objects.requireNonNull(errorCorrectionLevel); Objects.requireNonNull(errorCorrectionLevel);
final boolean isVersionInRange = MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION; final boolean isVersionInRange = MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION;
final boolean isMaskValid = mask < -1 || mask > 7; final boolean isMaskOutOfRange = mask < -1 || mask > 7;
if (!isVersionInRange || isMaskValid) if (!isVersionInRange || isMaskOutOfRange)
throw new IllegalArgumentException("Invalid value"); throw new IllegalArgumentException("Invalid value");
// Find the minimal version number to use
int version, dataUsedBits;
for (version = minVersion; ; version++) {
int dataCapacityBits = getNumDataCodewords(version, errorCorrectionLevel) * 8; // Number of data bits available
dataUsedBits = QrSegment.getTotalBits(segments, version);
if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
break; // This version number is found to be suitable
if (version >= maxVersion) { // All versions in the range could not fit the given data
String message = "Segment too long";
if (dataUsedBits != -1)
message = String.format("Data length = %d bits, Max capacity = %d bits", dataUsedBits, dataCapacityBits);
throw new DataTooLongException(message);
}
}
assert dataUsedBits != -1;
// Increase the error correction level while the data still fits in the current version number int version = findMinimalVersion(segments, errorCorrectionLevel, minVersion, maxVersion);
for (Ecc newEcl : Ecc.values()) { // From low to high
final boolean canIncreaseErrorCorrectionLevel = dataUsedBits <= getNumDataCodewords(version, newEcl) * 8; int dataUsedBits = QrSegment.getTotalBits(segments, version);
if (boostEcl && canIncreaseErrorCorrectionLevel)
errorCorrectionLevel = newEcl; errorCorrectionLevel = findMaximalErrorCorrectionLevel(errorCorrectionLevel, boostEcl, version, dataUsedBits);
BitBuffer bitBuffer = segmentsToBitBuffer(segments, version);
assert bitBuffer.bitLength() == dataUsedBits;
int dataCapacityBits = getNumDataCodewords(version, errorCorrectionLevel) * 8;
assert bitBuffer.bitLength() <= dataCapacityBits;
bitBuffer.addTerminator(dataCapacityBits);
bitBuffer.addPad(dataCapacityBits);
byte[] dataCodewords = bitBuffer.toCodewords();
// Create the QR Code object
return new QrCode(version, errorCorrectionLevel, dataCodewords, mask);
} }
/*---- Private helper methods for encodeSegments ----*/
// Concatenate all segments to create the data bit string // Concatenate all segments to create the data bit string
private static BitBuffer segmentsToBitBuffer(List<QrSegment> segments, int version) {
BitBuffer bitBuffer = new BitBuffer(); BitBuffer bitBuffer = new BitBuffer();
for (QrSegment segment : segments) { for (QrSegment segment : segments) {
bitBuffer.appendBits(segment.mode.modeBits, 4); bitBuffer.appendBits(segment.mode.modeBits, 4);
bitBuffer.appendBits(segment.numChars, segment.mode.numCharCountBits(version)); bitBuffer.appendBits(segment.numChars, segment.mode.numCharCountBits(version));
bitBuffer.appendData(segment.data); bitBuffer.appendData(segment.data);
} }
assert bitBuffer.bitLength() == dataUsedBits; return bitBuffer;
}
// Add terminator and pad up to a byte if applicable
int dataCapacityBits = getNumDataCodewords(version, errorCorrectionLevel) * 8;
assert bitBuffer.bitLength() <= dataCapacityBits;
bitBuffer.appendBits(0, Math.min(4, dataCapacityBits - bitBuffer.bitLength()));
bitBuffer.appendBits(0, (8 - bitBuffer.bitLength() % 8) % 8);
assert bitBuffer.bitLength() % 8 == 0;
// Pad with alternating bytes until data capacity is reached // Increase the error correction level while the data still fits in the current version number
for (int padByte = 0xEC; bitBuffer.bitLength() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) private static Ecc findMaximalErrorCorrectionLevel(Ecc errorCorrectionLevel, boolean boostEcl, int version,
bitBuffer.appendBits(padByte, 8); int dataUsedBits) {
for (Ecc newEcl : Ecc.values()) { // From low to high
final boolean canIncreaseErrorCorrectionLevel = dataUsedBits <= getNumDataCodewords(version, newEcl) * 8;
if (boostEcl && canIncreaseErrorCorrectionLevel)
errorCorrectionLevel = newEcl;
}
return errorCorrectionLevel;
}
// Pack bits into bytes in big endian
byte[] dataCodewords = new byte[bitBuffer.bitLength() / 8];
for (int i = 0; i < bitBuffer.bitLength(); i++)
dataCodewords[i >>> 3] |= bitBuffer.getBit(i) << (7 - (i & 7));
// Create the QR Code object //Returns the minimal version number to use
return new QrCode(version, errorCorrectionLevel, dataCodewords, mask); private static int findMinimalVersion(List<QrSegment> segments, Ecc errorCorrectionLevel, int minVersion,
int maxVersion) {
int version, dataUsedBits;
for (version = minVersion; ; version++) {
int dataCapacityBits = getNumDataCodewords(version, errorCorrectionLevel) * 8; // Number of data bits available
dataUsedBits = QrSegment.getTotalBits(segments, version);
if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
break; // This version number is found to be suitable
if (version >= maxVersion) { // All versions in the range could not fit the given data
String message = "Segment too long";
if (dataUsedBits != -1)
message = String.format("Data length = %d bits, Max capacity = %d bits", dataUsedBits, dataCapacityBits);
throw new DataTooLongException(message);
}
}
assert dataUsedBits != -1;
return version;
} }
/*---- Instance fields ----*/ /*---- Instance fields ----*/
@ -370,7 +392,16 @@ public final class QrCode {
drawFinderPattern(size - 1 - FINDER_SIZE, FINDER_SIZE); drawFinderPattern(size - 1 - FINDER_SIZE, FINDER_SIZE);
drawFinderPattern(FINDER_SIZE, size - 1 - FINDER_SIZE); drawFinderPattern(FINDER_SIZE, size - 1 - FINDER_SIZE);
drawAlignmentsPatterns();
// Draw configuration data
drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
drawVersion();
}
// Draw numerous alignment patterns // Draw numerous alignment patterns
private void drawAlignmentsPatterns() {
int[] alignPatPos = getAlignmentPatternPositions(); int[] alignPatPos = getAlignmentPatternPositions();
int numAlign = alignPatPos.length; int numAlign = alignPatPos.length;
for (int i = 0; i < numAlign; i++) { for (int i = 0; i < numAlign; i++) {
@ -383,10 +414,6 @@ public final class QrCode {
drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
} }
} }
// Draw configuration data
drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
drawVersion();
} }
@ -553,23 +580,20 @@ public final class QrCode {
// before masking. Due to the arithmetic of XOR, calling applyMask() with // before masking. Due to the arithmetic of XOR, calling applyMask() with
// the same mask value a second time will undo the mask. A final well-formed // the same mask value a second time will undo the mask. A final well-formed
// QR Code needs exactly one (not zero, two, etc.) mask applied. // QR Code needs exactly one (not zero, two, etc.) mask applied.
private void applyMask(int msk) { private void applyMask(int msk) {
if (msk < 0 || msk > 7) if (msk < 0 || msk > 7)
throw new IllegalArgumentException("Mask value out of range"); throw new IllegalArgumentException("Mask value out of range");
for (int y = 0; y < size; y++) { for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) { for (int x = 0; x < size; x++) {
boolean invert; boolean invert;
switch (msk) {
case 0: invert = (x + y) % 2 == 0; break; Command mskCommand = MskCommandFactory.getCommand(msk);
case 1: invert = y % 2 == 0; break; Button button = new Button(mskCommand);
case 2: invert = x % 3 == 0; break; invert = button.pressed(y, x, msk);
case 3: invert = (x + y) % 3 == 0; break;
case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
case 5: invert = x * y % 2 + x * y % 3 == 0; break;
case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
default: throw new AssertionError();
}
modules[y][x] ^= invert & !isFunction[y][x]; modules[y][x] ^= invert & !isFunction[y][x];
} }
} }
@ -579,30 +603,60 @@ public final class QrCode {
// A messy helper function for the constructor. This QR Code must be in an unmasked state when this // A messy helper function for the constructor. This QR Code must be in an unmasked state when this
// method is called. The given argument is the requested mask, which is -1 for auto or 0 to 7 for fixed. // method is called. The given argument is the requested mask, which is -1 for auto or 0 to 7 for fixed.
// This method applies and returns the actual mask chosen, from 0 to 7. // This method applies and returns the actual mask chosen, from 0 to 7.
private int handleConstructorMasking(int msk) { private int handleConstructorMasking(int mask) {
if (msk == -1) { // Automatically choose best mask if (mask == -1) {
mask = findBestMask();
}
assert 0 <= mask && mask <= 7;
applyMask(mask); // Apply the final choice of mask
drawFormatBits(mask); // Overwrite old format bits
return mask; // The caller shall assign this value to the final-declared field
}
// Automatically choose best mask
private int findBestMask() {
int mask = -1;
int minPenalty = Integer.MAX_VALUE; int minPenalty = Integer.MAX_VALUE;
for (int i = 0; i < 8; i++) { for (int i = 0; i < 8; i++) {
applyMask(i); applyMask(i);
drawFormatBits(i); drawFormatBits(i);
int penalty = getPenaltyScore(); int penalty = getPenaltyScore();
if (penalty < minPenalty) { if (penalty < minPenalty) {
msk = i; mask = i;
minPenalty = penalty; minPenalty = penalty;
} }
applyMask(i); // Undoes the mask due to XOR applyMask(i); // Undoes the mask due to XOR
} }
return mask;
} }
assert 0 <= msk && msk <= 7;
applyMask(msk); // Apply the final choice of mask
drawFormatBits(msk); // Overwrite old format bits private int havingSameColor(int run, boolean runColor, int[] runHistory, int result, int y, int x) {
return msk; // The caller shall assign this value to the final-declared field if (modules[y][x] == runColor) {
run++;
if (run == 5)
result += PENALTY_N1;
else if (run > 5)
result++;
} else {
finderPenaltyAddHistory(run, runHistory);
if (!runColor)
result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
runColor = modules[y][x];
run = 1;
} }
return result;
}
// Calculates and returns the penalty score based on state of this QR Code's current modules. // Calculates and returns the penalty score based on state of this QR Code's current modules.
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
private int getPenaltyScore() { private int getPenaltyScore() {
int result = 0; int result = 0;
// Adjacent modules in row having same color, and finder-like patterns // Adjacent modules in row having same color, and finder-like patterns
@ -611,19 +665,7 @@ public final class QrCode {
int runX = 0; int runX = 0;
int[] runHistory = new int[7]; int[] runHistory = new int[7];
for (int x = 0; x < size; x++) { for (int x = 0; x < size; x++) {
if (modules[y][x] == runColor) { result += havingSameColor(runX, runColor, runHistory, result, y, x);
runX++;
if (runX == 5)
result += PENALTY_N1;
else if (runX > 5)
result++;
} else {
finderPenaltyAddHistory(runX, runHistory);
if (!runColor)
result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
runColor = modules[y][x];
runX = 1;
}
} }
result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3;
} }
@ -633,33 +675,13 @@ public final class QrCode {
int runY = 0; int runY = 0;
int[] runHistory = new int[7]; int[] runHistory = new int[7];
for (int y = 0; y < size; y++) { for (int y = 0; y < size; y++) {
if (modules[y][x] == runColor) { result += havingSameColor(runY, runColor, runHistory, result, y, x);
runY++;
if (runY == 5)
result += PENALTY_N1;
else if (runY > 5)
result++;
} else {
finderPenaltyAddHistory(runY, runHistory);
if (!runColor)
result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
runColor = modules[y][x];
runY = 1;
}
} }
result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3;
} }
// 2*2 blocks of modules having same color result += twobytwoHavingSameColor(modules);
for (int y = 0; y < size - 1; y++) {
for (int x = 0; x < size - 1; x++) {
boolean color = modules[y][x];
if ( color == modules[y][x + 1] &&
color == modules[y + 1][x] &&
color == modules[y + 1][x + 1])
result += PENALTY_N2;
}
}
// Balance of black and white modules // Balance of black and white modules
int black = 0; int black = 0;
@ -676,7 +698,20 @@ public final class QrCode {
return result; return result;
} }
private int twobytwoHavingSameColor(boolean[][] modules) {
int result = 0;
// 2*2 blocks of modules having same color.
for (int y = 0; y < size - 1; y++) {
for (int x = 0; x < size - 1; x++) {
boolean color = modules[y][x];
if ( color == modules[y][x + 1] &&
color == modules[y + 1][x] &&
color == modules[y + 1][x + 1])
result += PENALTY_N2;
}
}
return result;
}
/*---- Private helper functions ----*/ /*---- Private helper functions ----*/
@ -709,6 +744,13 @@ public final class QrCode {
if (ver < MIN_VERSION || ver > MAX_VERSION) if (ver < MIN_VERSION || ver > MAX_VERSION)
throw new IllegalArgumentException("Version number out of range"); throw new IllegalArgumentException("Version number out of range");
int result = calculateNumOfModules(ver);
assert 208 <= result && result <= 29648;
return result;
}
private static int calculateNumOfModules(int ver) {
int size = ver * 4 + 17; int size = ver * 4 + 17;
int result = size * size; // Number of modules in the whole QR Code square int result = size * size; // Number of modules in the whole QR Code square
result -= 8 * 8 * 3; // Subtract the three finders with separators result -= 8 * 8 * 3; // Subtract the three finders with separators
@ -723,11 +765,9 @@ public final class QrCode {
if (ver >= 7) if (ver >= 7)
result -= 6 * 3 * 2; // Subtract version information result -= 6 * 3 * 2; // Subtract version information
} }
assert 208 <= result && result <= 29648;
return result; return result;
} }
// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
// implemented as a lookup table over all possible parameter values, instead of as an algorithm. // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
private static byte[] reedSolomonComputeDivisor(int degree) { private static byte[] reedSolomonComputeDivisor(int degree) {

@ -0,0 +1,13 @@
package io.nayuki.qrcodegen;
public class msk0Command implements Command{
private Msk0 theMsk0;
public msk0Command(Msk0 theMsk0) {
this.theMsk0 = theMsk0;
}
public boolean excute(int y, int x, int msk) {
return theMsk0.operation(y, x, msk);
}
}

@ -0,0 +1,13 @@
package io.nayuki.qrcodegen;
public class msk1Command implements Command {
private Msk1 theMsk1;
public msk1Command(Msk1 theMsk1) {
this.theMsk1 = theMsk1;
}
public boolean excute(int y, int x, int msk) {
return theMsk1.operation(y, x, msk);
}
}

@ -0,0 +1,13 @@
package io.nayuki.qrcodegen;
public class msk2Command implements Command {
private Msk2 theMsk2;
public msk2Command(Msk2 theMsk2) {
this.theMsk2 = theMsk2;
}
public boolean excute(int y, int x, int msk) {
return theMsk2.operation(y, x, msk);
}
}

@ -0,0 +1,13 @@
package io.nayuki.qrcodegen;
public class msk3Command implements Command {
private Msk3 theMsk3;
public msk3Command(Msk3 theMsk3) {
this.theMsk3 = theMsk3;
}
public boolean excute(int y, int x, int msk) {
return theMsk3.operation(y, x, msk);
}
}

@ -0,0 +1,13 @@
package io.nayuki.qrcodegen;
public class msk4Command implements Command {
private Msk4 theMsk4;
public msk4Command(Msk4 theMsk4) {
this.theMsk4 = theMsk4;
}
public boolean excute(int y, int x, int msk) {
return theMsk4.operation(y, x, msk);
}
}

@ -0,0 +1,13 @@
package io.nayuki.qrcodegen;
public class msk5Command implements Command {
private Msk5 theMsk5;
public msk5Command(Msk5 theMsk5) {
this.theMsk5 = theMsk5;
}
public boolean excute(int y, int x, int msk) {
return theMsk5.operation(y, x, msk);
}
}

@ -0,0 +1,13 @@
package io.nayuki.qrcodegen;
public class msk6Command implements Command {
private Msk6 theMsk6;
public msk6Command(Msk6 theMsk6) {
this.theMsk6 = theMsk6;
}
public boolean excute(int y, int x, int msk) {
return theMsk6.operation(y, x, msk);
}
}

@ -0,0 +1,13 @@
package io.nayuki.qrcodegen;
public class msk7Command implements Command {
private Msk7 theMsk7;
public msk7Command(Msk7 theMsk7) {
this.theMsk7 = theMsk7;
}
public boolean excute(int y, int x, int msk) {
return theMsk7.operation(y, x, msk);
}
}
Loading…
Cancel
Save