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>
38 * @author William Rucklidge
39 * @author sanfordsquires
41 public final class ReedSolomonDecoder {
43 private final GenericGF field;
45 public ReedSolomonDecoder(GenericGF field) {
50 * <p>Decodes given set of received codewords, which include both data and error-correction
51 * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
54 * @param received data and error-correction codewords
55 * @param twoS number of error-correction codewords available
56 * @throws ReedSolomonException if decoding fails for any reason
58 public void decode(int[] received, int twoS) throws ReedSolomonException {
59 GenericGFPoly poly = new GenericGFPoly(field, received);
60 int[] syndromeCoefficients = new int[twoS];
61 boolean noError = true;
62 for (int i = 0; i < twoS; i++) {
63 int eval = poly.evaluateAt(field.exp(i + field.getGeneratorBase()));
64 syndromeCoefficients[syndromeCoefficients.length - 1 - i] = eval;
72 GenericGFPoly syndrome = new GenericGFPoly(field, syndromeCoefficients);
73 GenericGFPoly[] sigmaOmega =
74 runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
75 GenericGFPoly sigma = sigmaOmega[0];
76 GenericGFPoly omega = sigmaOmega[1];
77 int[] errorLocations = findErrorLocations(sigma);
78 int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations);
79 for (int i = 0; i < errorLocations.length; i++) {
80 int position = received.length - 1 - field.log(errorLocations[i]);
82 throw new ReedSolomonException("Bad error location");
84 received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
88 private GenericGFPoly[] runEuclideanAlgorithm(GenericGFPoly a, GenericGFPoly b, int R)
89 throws ReedSolomonException {
90 // Assume a's degree is >= b's
91 if (a.getDegree() < b.getDegree()) {
92 GenericGFPoly temp = a;
97 GenericGFPoly rLast = a;
99 GenericGFPoly tLast = field.getZero();
100 GenericGFPoly t = field.getOne();
102 // Run Euclidean algorithm until r's degree is less than R/2
103 while (r.getDegree() >= R / 2) {
104 GenericGFPoly rLastLast = rLast;
105 GenericGFPoly tLastLast = tLast;
109 // Divide rLastLast by rLast, with quotient in q and remainder in r
110 if (rLast.isZero()) {
111 // Oops, Euclidean algorithm already terminated?
112 throw new ReedSolomonException("r_{i-1} was zero");
115 GenericGFPoly q = field.getZero();
116 int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
117 int dltInverse = field.inverse(denominatorLeadingTerm);
118 while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
119 int degreeDiff = r.getDegree() - rLast.getDegree();
120 int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
121 q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
122 r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
125 t = q.multiply(tLast).addOrSubtract(tLastLast);
127 if (r.getDegree() >= rLast.getDegree()) {
128 throw new IllegalStateException("Division algorithm failed to reduce polynomial?");
132 int sigmaTildeAtZero = t.getCoefficient(0);
133 if (sigmaTildeAtZero == 0) {
134 throw new ReedSolomonException("sigmaTilde(0) was zero");
137 int inverse = field.inverse(sigmaTildeAtZero);
138 GenericGFPoly sigma = t.multiply(inverse);
139 GenericGFPoly omega = r.multiply(inverse);
140 return new GenericGFPoly[]{sigma, omega};
143 private int[] findErrorLocations(GenericGFPoly errorLocator) throws ReedSolomonException {
144 // This is a direct application of Chien's search
145 int numErrors = errorLocator.getDegree();
146 if (numErrors == 1) { // shortcut
147 return new int[] { errorLocator.getCoefficient(1) };
149 int[] result = new int[numErrors];
151 for (int i = 1; i < field.getSize() && e < numErrors; i++) {
152 if (errorLocator.evaluateAt(i) == 0) {
153 result[e] = field.inverse(i);
157 if (e != numErrors) {
158 throw new ReedSolomonException("Error locator degree does not match number of roots");
163 private int[] findErrorMagnitudes(GenericGFPoly errorEvaluator, int[] errorLocations) {
164 // This is directly applying Forney's Formula
165 int s = errorLocations.length;
166 int[] result = new int[s];
167 for (int i = 0; i < s; i++) {
168 int xiInverse = field.inverse(errorLocations[i]);
170 for (int j = 0; j < s; j++) {
172 //denominator = field.multiply(denominator,
173 // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
174 // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
175 // Below is a funny-looking workaround from Steven Parkes
176 int term = field.multiply(errorLocations[j], xiInverse);
177 int termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1;
178 denominator = field.multiply(denominator, termPlus1);
181 result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
182 field.inverse(denominator));
183 if (field.getGeneratorBase() != 0) {
184 result[i] = field.multiply(result[i], xiInverse);