Refactored Reed-Solomon so it can be used with different GF(256) primitive polynomials
[zxing.git] / core / src / com / google / zxing / common / reedsolomon / ReedSolomonDecoder.java
1 /*
2  * Copyright 2007 Google Inc.
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 import java.util.Vector;
20
21 /**
22  * <p>Implements Reed-Solomon decoding, as the name implies.</p>
23  *
24  * <p>The algorithm will not be explained here, but the following references were helpful
25  * in creating this implementation:</p>
26  *
27  * <ul>
28  * <li>Bruce Maggs.
29  * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
30  * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
31  * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
32  * "Chapter 5. Generalized Reed-Solomon Codes"</a>
33  * (see discussion of Euclidean algorithm)</li>
34  * </ul>
35  *
36  * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
37  * port of his C++ Reed-Solomon implementation.</p>
38  *
39  * @author srowen@google.com (Sean Owen)
40  * @author William Rucklidge
41  */
42 public final class ReedSolomonDecoder {
43
44   private final GF256 field;
45
46   public ReedSolomonDecoder(GF256 field) {
47     this.field = field;
48   }
49
50   /**
51    * <p>Decodes given set of received codewords, which include both data and error-correction
52    * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
53    * in the input.</p>
54    *
55    * @param received data and error-correction codewords
56    * @param twoS number of error-correction codewords available
57    * @throws ReedSolomonException if decoding fails for any reaosn
58    */
59   public void decode(int[] received, int twoS) throws ReedSolomonException {
60     GF256Poly poly = new GF256Poly(field, received);
61     int[] syndromeCoefficients = new int[twoS];
62     for (int i = 0; i < twoS; i++) {
63       syndromeCoefficients[syndromeCoefficients.length - 1 - i] = poly.evaluateAt(field.exp(i));
64     }
65     GF256Poly syndrome = new GF256Poly(field, syndromeCoefficients);
66     if (!syndrome.isZero()) { // Error
67       GF256Poly[] sigmaOmega =
68           runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
69       int[] errorLocations = findErrorLocations(sigmaOmega[0]);
70       int[] errorMagnitudes = findErrorMagnitudes(sigmaOmega[1], errorLocations);
71       for (int i = 0; i < errorLocations.length; i++) {
72         int position = received.length - 1 - field.log(errorLocations[i]);
73         received[position] = field.addOrSubtract(received[position], errorMagnitudes[i]);
74       }
75     }
76   }
77
78   private GF256Poly[] runEuclideanAlgorithm(GF256Poly a, GF256Poly b, int R)
79       throws ReedSolomonException {
80     // Assume a's degree is >= b's
81     if (a.getDegree() < b.getDegree()) {
82       GF256Poly temp = a;
83       a = b;
84       b = temp;
85     }
86
87     GF256Poly rLast = a;
88     GF256Poly r = b;
89     GF256Poly sLast = field.getOne();
90     GF256Poly s = field.getZero();
91     GF256Poly tLast = field.getZero();
92     GF256Poly t = field.getOne();
93
94     // Run Euclidean algorithm until r's degree is less than R/2
95     while (r.getDegree() >= R / 2) {
96       GF256Poly rLastLast = rLast;
97       GF256Poly sLastLast = sLast;
98       GF256Poly tLastLast = tLast;
99       rLast = r;
100       sLast = s;
101       tLast = t;
102
103       // Divide rLastLast by rLast, with quotient in q and remainder in r
104       if (rLast.isZero()) {
105         // Oops, Euclidean algorithm already terminated?
106         throw new ReedSolomonException("r_{i-1} was zero");
107       }
108       r = rLastLast;
109       GF256Poly q = field.getZero();
110       int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
111       int dltInverse = field.inverse(denominatorLeadingTerm);
112       while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
113         int degreeDiff = r.getDegree() - rLast.getDegree();
114         int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
115         q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
116         r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
117       }
118
119       s = q.multiply(sLast).addOrSubtract(sLastLast);
120       t = q.multiply(tLast).addOrSubtract(tLastLast);
121     }
122
123     int sigmaTildeAtZero = t.getCoefficient(0);
124     if (sigmaTildeAtZero == 0) {
125       throw new ReedSolomonException("sigmaTilde(0) was zero");
126     }
127
128     int inverse = field.inverse(sigmaTildeAtZero);
129     GF256Poly sigma = t.multiply(inverse);
130     GF256Poly omega = r.multiply(inverse);
131     return new GF256Poly[]{sigma, omega};
132   }
133
134   private int[] findErrorLocations(GF256Poly errorLocator)
135       throws ReedSolomonException {
136     // This is a direct application of Chien's search
137     Vector errorLocations = new Vector(3);
138     for (int i = 1; i < 256; i++) {
139       if (errorLocator.evaluateAt(i) == 0) {
140         errorLocations.addElement(new Integer(field.inverse(i)));
141       }
142     }
143     if (errorLocations.size() != errorLocator.getDegree()) {
144       throw new ReedSolomonException("Error locator degree does not match number of roots");
145     }
146     int[] result = new int[errorLocations.size()]; // Can't use toArray() here
147     for (int i = 0; i < result.length; i++) {
148       result[i] = ((Integer) errorLocations.elementAt(i)).intValue();
149     }
150     return result;
151   }
152
153   private int[] findErrorMagnitudes(GF256Poly errorEvaluator,
154                                            int[] errorLocations) {
155     // This is directly applying Forney's Formula
156     int s = errorLocations.length;
157     int[] result = new int[s];
158     for (int i = 0; i < errorLocations.length; i++) {
159       int xiInverse = field.inverse(errorLocations[i]);
160       int denominator = 1;
161       for (int j = 0; j < s; j++) {
162         if (i != j) {
163           denominator = field.multiply(denominator,
164               field.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
165         }
166       }
167       result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
168           field.inverse(denominator));
169     }
170     return result;
171   }
172
173 }