9188c790c599ef2db1e6bc239cc288cbafe1490d
[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 /**
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    * @throws ReedSolomonException if decoding fails for any reaosn
56    */
57   public void decode(int[] received, int twoS) throws ReedSolomonException {
58     GF256Poly poly = new GF256Poly(field, received);
59     int[] syndromeCoefficients = new int[twoS];
60     boolean noError = true;
61     for (int i = 0; i < twoS; i++) {
62       int eval =  poly.evaluateAt(field.exp(i));
63       syndromeCoefficients[syndromeCoefficients.length - 1 - i] = eval;
64       if (eval != 0) {
65         noError = false;
66       }
67     }
68     if (noError) {
69       return;
70     }
71     GF256Poly syndrome = new GF256Poly(field, syndromeCoefficients);
72     GF256Poly[] sigmaOmega =
73         runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
74     int[] errorLocations = findErrorLocations(sigmaOmega[0]);
75     int[] errorMagnitudes = findErrorMagnitudes(sigmaOmega[1], errorLocations);
76     for (int i = 0; i < errorLocations.length; i++) {
77       int position = received.length - 1 - field.log(errorLocations[i]);
78       received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]);
79     }
80   }
81
82   private GF256Poly[] runEuclideanAlgorithm(GF256Poly a, GF256Poly b, int R)
83       throws ReedSolomonException {
84     // Assume a's degree is >= b's
85     if (a.getDegree() < b.getDegree()) {
86       GF256Poly temp = a;
87       a = b;
88       b = temp;
89     }
90
91     GF256Poly rLast = a;
92     GF256Poly r = b;
93     GF256Poly sLast = field.getOne();
94     GF256Poly s = field.getZero();
95     GF256Poly tLast = field.getZero();
96     GF256Poly t = field.getOne();
97
98     // Run Euclidean algorithm until r's degree is less than R/2
99     while (r.getDegree() >= R / 2) {
100       GF256Poly rLastLast = rLast;
101       GF256Poly sLastLast = sLast;
102       GF256Poly tLastLast = tLast;
103       rLast = r;
104       sLast = s;
105       tLast = t;
106
107       // Divide rLastLast by rLast, with quotient in q and remainder in r
108       if (rLast.isZero()) {
109         // Oops, Euclidean algorithm already terminated?
110         throw new ReedSolomonException("r_{i-1} was zero");
111       }
112       r = rLastLast;
113       GF256Poly q = field.getZero();
114       int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
115       int dltInverse = field.inverse(denominatorLeadingTerm);
116       while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
117         int degreeDiff = r.getDegree() - rLast.getDegree();
118         int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
119         q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
120         r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
121       }
122
123       s = q.multiply(sLast).addOrSubtract(sLastLast);
124       t = q.multiply(tLast).addOrSubtract(tLastLast);
125     }
126
127     int sigmaTildeAtZero = t.getCoefficient(0);
128     if (sigmaTildeAtZero == 0) {
129       throw new ReedSolomonException("sigmaTilde(0) was zero");
130     }
131
132     int inverse = field.inverse(sigmaTildeAtZero);
133     GF256Poly sigma = t.multiply(inverse);
134     GF256Poly omega = r.multiply(inverse);
135     return new GF256Poly[]{sigma, omega};
136   }
137
138   private int[] findErrorLocations(GF256Poly errorLocator) throws ReedSolomonException {
139     // This is a direct application of Chien's search
140     int numErrors = errorLocator.getDegree();
141     if (numErrors == 1) { // shortcut
142       return new int[] { errorLocator.getCoefficient(1) };
143     }
144     int[] result = new int[numErrors];
145     int e = 0;
146     for (int i = 1; i < 256 && e < numErrors; i++) {
147       if (errorLocator.evaluateAt(i) == 0) {
148         result[e] = field.inverse(i);
149         e++;
150       }
151     }
152     if (e != numErrors) {
153       throw new ReedSolomonException("Error locator degree does not match number of roots");
154     }
155     return result;
156   }
157
158   private int[] findErrorMagnitudes(GF256Poly errorEvaluator, int[] errorLocations) {
159     // This is directly applying Forney's Formula
160     int s = errorLocations.length;
161     if (s == 1) { // shortcut
162       return new int[] { errorEvaluator.getCoefficient(0) };
163     }
164     int[] result = new int[s];
165     for (int i = 0; i < s; i++) {
166       int xiInverse = field.inverse(errorLocations[i]);
167       int denominator = 1;
168       for (int j = 0; j < s; j++) {
169         if (i != j) {
170           denominator = field.multiply(denominator,
171               GF256.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
172         }
173       }
174       result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
175           field.inverse(denominator));
176     }
177     return result;
178   }
179
180 }