2 * Copyright 2007 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.common.reedsolomon;
20 * <p>Implements Reed-Solomon decoding, as the name implies.</p>
22 * <p>The algorithm will not be explained here, but the following references were helpful
23 * in creating this implementation:</p>
27 * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
28 * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
29 * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
30 * "Chapter 5. Generalized Reed-Solomon Codes"</a>
31 * (see discussion of Euclidean algorithm)</li>
34 * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
35 * port of his C++ Reed-Solomon implementation.</p>
37 * @author srowen@google.com (Sean Owen)
38 * @author William Rucklidge
40 public final class ReedSolomonDecoder {
42 private final GF256 field;
44 public ReedSolomonDecoder(GF256 field) {
49 * <p>Decodes given set of received codewords, which include both data and error-correction
50 * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
53 * @param received data and error-correction codewords
54 * @param twoS number of error-correction codewords available
55 * @param dataMatrix if true, then uses a calculation that matches the Data Matrix
56 * standard rather than the one used in QR Code
57 * @throws ReedSolomonException if decoding fails for any reason
59 public void decode(int[] received, int twoS, boolean dataMatrix) throws ReedSolomonException {
60 GF256Poly poly = new GF256Poly(field, received);
61 int[] syndromeCoefficients = new int[twoS];
62 boolean noError = true;
63 for (int i = 0; i < twoS; i++) {
64 // This difference in syndrome calculation appears to be correct, but then causes issues below
65 int eval = poly.evaluateAt(field.exp(dataMatrix ? i + 1 : i));
66 syndromeCoefficients[syndromeCoefficients.length - 1 - i] = eval;
74 GF256Poly syndrome = new GF256Poly(field, syndromeCoefficients);
76 // TODO Not clear this is correct for DataMatrix, but it gives almost-correct behavior;
77 // works except when number of errors is the maximum allowable.
78 syndrome = syndrome.multiply(field.buildMonomial(1, 1));
80 GF256Poly[] sigmaOmega =
81 runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
82 GF256Poly sigma = sigmaOmega[0];
83 GF256Poly omega = sigmaOmega[1];
84 int[] errorLocations = findErrorLocations(sigma);
85 int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations);
86 for (int i = 0; i < errorLocations.length; i++) {
87 int position = received.length - 1 - field.log(errorLocations[i]);
88 received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]);
92 private GF256Poly[] runEuclideanAlgorithm(GF256Poly a, GF256Poly b, int R)
93 throws ReedSolomonException {
94 // Assume a's degree is >= b's
95 if (a.getDegree() < b.getDegree()) {
103 GF256Poly sLast = field.getOne();
104 GF256Poly s = field.getZero();
105 GF256Poly tLast = field.getZero();
106 GF256Poly t = field.getOne();
108 // Run Euclidean algorithm until r's degree is less than R/2
109 while (r.getDegree() >= R / 2) {
110 GF256Poly rLastLast = rLast;
111 GF256Poly sLastLast = sLast;
112 GF256Poly tLastLast = tLast;
117 // Divide rLastLast by rLast, with quotient in q and remainder in r
118 if (rLast.isZero()) {
119 // Oops, Euclidean algorithm already terminated?
120 throw new ReedSolomonException("r_{i-1} was zero");
123 GF256Poly q = field.getZero();
124 int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
125 int dltInverse = field.inverse(denominatorLeadingTerm);
126 while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
127 int degreeDiff = r.getDegree() - rLast.getDegree();
128 int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
129 q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
130 r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
133 s = q.multiply(sLast).addOrSubtract(sLastLast);
134 t = q.multiply(tLast).addOrSubtract(tLastLast);
137 int sigmaTildeAtZero = t.getCoefficient(0);
138 if (sigmaTildeAtZero == 0) {
139 throw new ReedSolomonException("sigmaTilde(0) was zero");
142 int inverse = field.inverse(sigmaTildeAtZero);
143 GF256Poly sigma = t.multiply(inverse);
144 GF256Poly omega = r.multiply(inverse);
145 return new GF256Poly[]{sigma, omega};
148 private int[] findErrorLocations(GF256Poly errorLocator) throws ReedSolomonException {
149 // This is a direct application of Chien's search
150 int numErrors = errorLocator.getDegree();
151 if (numErrors == 1) { // shortcut
152 return new int[] { errorLocator.getCoefficient(1) };
154 int[] result = new int[numErrors];
156 for (int i = 1; i < 256 && e < numErrors; i++) {
157 if (errorLocator.evaluateAt(i) == 0) {
158 result[e] = field.inverse(i);
162 if (e != numErrors) {
163 throw new ReedSolomonException("Error locator degree does not match number of roots");
168 private int[] findErrorMagnitudes(GF256Poly errorEvaluator, int[] errorLocations) {
169 // This is directly applying Forney's Formula
170 int s = errorLocations.length;
171 int[] result = new int[s];
172 for (int i = 0; i < s; i++) {
173 int xiInverse = field.inverse(errorLocations[i]);
175 for (int j = 0; j < s; j++) {
177 denominator = field.multiply(denominator,
178 GF256.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
181 result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
182 field.inverse(denominator));