]> Pileus Git - ~andy/freeotp/blob - src/com/google/zxing/common/reedsolomon/ReedSolomonDecoder.java
Add native camera support
[~andy/freeotp] / 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 Sean Owen
38  * @author William Rucklidge
39  * @author sanfordsquires
40  */
41 public final class ReedSolomonDecoder {
42
43   private final GenericGF field;
44
45   public ReedSolomonDecoder(GenericGF field) {
46     this.field = field;
47   }
48
49   /**
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,
52    * in the input.</p>
53    *
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
57    */
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;
65       if (eval != 0) {
66         noError = false;
67       }
68     }
69     if (noError) {
70       return;
71     }
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]);
81       if (position < 0) {
82         throw new ReedSolomonException("Bad error location");
83       }
84       received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
85     }
86   }
87
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;
93       a = b;
94       b = temp;
95     }
96
97     GenericGFPoly rLast = a;
98     GenericGFPoly r = b;
99     GenericGFPoly tLast = field.getZero();
100     GenericGFPoly t = field.getOne();
101
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;
106       rLast = r;
107       tLast = t;
108
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");
113       }
114       r = rLastLast;
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));
123       }
124
125       t = q.multiply(tLast).addOrSubtract(tLastLast);
126       
127       if (r.getDegree() >= rLast.getDegree()) {
128         throw new IllegalStateException("Division algorithm failed to reduce polynomial?");
129       }
130     }
131
132     int sigmaTildeAtZero = t.getCoefficient(0);
133     if (sigmaTildeAtZero == 0) {
134       throw new ReedSolomonException("sigmaTilde(0) was zero");
135     }
136
137     int inverse = field.inverse(sigmaTildeAtZero);
138     GenericGFPoly sigma = t.multiply(inverse);
139     GenericGFPoly omega = r.multiply(inverse);
140     return new GenericGFPoly[]{sigma, omega};
141   }
142
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) };
148     }
149     int[] result = new int[numErrors];
150     int e = 0;
151     for (int i = 1; i < field.getSize() && e < numErrors; i++) {
152       if (errorLocator.evaluateAt(i) == 0) {
153         result[e] = field.inverse(i);
154         e++;
155       }
156     }
157     if (e != numErrors) {
158       throw new ReedSolomonException("Error locator degree does not match number of roots");
159     }
160     return result;
161   }
162
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]);
169       int denominator = 1;
170       for (int j = 0; j < s; j++) {
171         if (i != 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);
179         }
180       }
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);
185       }
186     }
187     return result;
188   }
189
190 }