2d93c5ffe1485db9b0159135af606d4733a80ba2
[zxing.git] / core / src / com / google / zxing / common / reedsolomon / ReedSolomonDecoder.java
1 /*
2  * Copyright 2007 ZXing authors
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.common.reedsolomon;
18
19 /**
20  * <p>Implements Reed-Solomon decoding, as the name implies.</p>
21  *
22  * <p>The algorithm will not be explained here, but the following references were helpful
23  * in creating this implementation:</p>
24  *
25  * <ul>
26  * <li>Bruce Maggs.
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>
32  * </ul>
33  *
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>
36  *
37  * @author srowen@google.com (Sean Owen)
38  * @author William Rucklidge
39  */
40 public final class ReedSolomonDecoder {
41
42   private final GF256 field;
43
44   public ReedSolomonDecoder(GF256 field) {
45     this.field = field;
46   }
47
48   /**
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,
51    * in the input.</p>
52    *
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
58    */
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;
67       if (eval != 0) {
68         noError = false;
69       }
70     }
71     if (noError) {
72       return;
73     }
74     GF256Poly syndrome = new GF256Poly(field, syndromeCoefficients);
75     if (dataMatrix) {
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));
79     }
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]);
89     }
90   }
91
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()) {
96       GF256Poly temp = a;
97       a = b;
98       b = temp;
99     }
100
101     GF256Poly rLast = a;
102     GF256Poly r = b;
103     GF256Poly sLast = field.getOne();
104     GF256Poly s = field.getZero();
105     GF256Poly tLast = field.getZero();
106     GF256Poly t = field.getOne();
107
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;
113       rLast = r;
114       sLast = s;
115       tLast = t;
116
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");
121       }
122       r = rLastLast;
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));
131       }
132
133       s = q.multiply(sLast).addOrSubtract(sLastLast);
134       t = q.multiply(tLast).addOrSubtract(tLastLast);
135     }
136
137     int sigmaTildeAtZero = t.getCoefficient(0);
138     if (sigmaTildeAtZero == 0) {
139       throw new ReedSolomonException("sigmaTilde(0) was zero");
140     }
141
142     int inverse = field.inverse(sigmaTildeAtZero);
143     GF256Poly sigma = t.multiply(inverse);
144     GF256Poly omega = r.multiply(inverse);
145     return new GF256Poly[]{sigma, omega};
146   }
147
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) };
153     }
154     int[] result = new int[numErrors];
155     int e = 0;
156     for (int i = 1; i < 256 && e < numErrors; i++) {
157       if (errorLocator.evaluateAt(i) == 0) {
158         result[e] = field.inverse(i);
159         e++;
160       }
161     }
162     if (e != numErrors) {
163       throw new ReedSolomonException("Error locator degree does not match number of roots");
164     }
165     return result;
166   }
167
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]);
174       int denominator = 1;
175       for (int j = 0; j < s; j++) {
176         if (i != j) {
177           denominator = field.multiply(denominator,
178               GF256.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
179         }
180       }
181       result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
182           field.inverse(denominator));
183     }
184     return result;
185   }
186
187 }