ReedSolomonDecoder.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. <?php
  2. /*
  3. * Copyright 2007 ZXing authors
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Zxing\Common\Reedsolomon;
  18. /**
  19. * <p>Implements Reed-Solomon decoding, as the name implies.</p>
  20. *
  21. * <p>The algorithm will not be explained here, but the following references were helpful
  22. * in creating this implementation:</p>
  23. *
  24. * <ul>
  25. * <li>Bruce Maggs.
  26. * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
  27. * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
  28. * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
  29. * "Chapter 5. Generalized Reed-Solomon Codes"</a>
  30. * (see discussion of Euclidean algorithm)</li>
  31. * </ul>
  32. *
  33. * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
  34. * port of his C++ Reed-Solomon implementation.</p>
  35. *
  36. * @author Sean Owen
  37. * @author William Rucklidge
  38. * @author sanfordsquires
  39. */
  40. final class ReedSolomonDecoder {
  41. private $field;
  42. public function __construct($field) {
  43. $this->field = $field;
  44. }
  45. /**
  46. * <p>Decodes given set of received codewords, which include both data and error-correction
  47. * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
  48. * in the input.</p>
  49. *
  50. * @param received data and error-correction codewords
  51. * @param twoS number of error-correction codewords available
  52. * @throws ReedSolomonException if decoding fails for any reason
  53. */
  54. public function decode(&$received, $twoS) {
  55. $poly = new GenericGFPoly($this->field, $received);
  56. $syndromeCoefficients = fill_array(0,$twoS,0);
  57. $noError = true;
  58. for ($i = 0; $i < $twoS; $i++) {
  59. $eval = $poly->evaluateAt($this->field->exp($i + $this->field->getGeneratorBase()));
  60. $syndromeCoefficients[count($syndromeCoefficients) - 1 - $i] = $eval;
  61. if ($eval != 0) {
  62. $noError = false;
  63. }
  64. }
  65. if ($noError) {
  66. return;
  67. }
  68. $syndrome = new GenericGFPoly($this->field, $syndromeCoefficients);
  69. $sigmaOmega =
  70. $this->runEuclideanAlgorithm($this->field->buildMonomial($twoS, 1), $syndrome, $twoS);
  71. $sigma = $sigmaOmega[0];
  72. $omega = $sigmaOmega[1];
  73. $errorLocations = $this->findErrorLocations($sigma);
  74. $errorMagnitudes = $this->findErrorMagnitudes($omega, $errorLocations);
  75. for ($i = 0; $i < count($errorLocations); $i++) {
  76. $position = count($received) - 1 - $this->field->log($errorLocations[$i]);
  77. if ($position < 0) {
  78. throw new ReedSolomonException("Bad error location");
  79. }
  80. $received[$position] = GenericGF::addOrSubtract($received[$position], $errorMagnitudes[$i]);
  81. }
  82. }
  83. private function runEuclideanAlgorithm($a, $b, $R)
  84. {
  85. // Assume a's degree is >= b's
  86. if ($a->getDegree() < $b->getDegree()) {
  87. $temp = $a;
  88. $a = $b;
  89. $b = $temp;
  90. }
  91. $rLast = $a;
  92. $r = $b;
  93. $tLast = $this->field->getZero();
  94. $t = $this->field->getOne();
  95. // Run Euclidean algorithm until r's degree is less than R/2
  96. while ($r->getDegree() >= $R / 2) {
  97. $rLastLast = $rLast;
  98. $tLastLast = $tLast;
  99. $rLast = $r;
  100. $tLast = $t;
  101. // Divide rLastLast by rLast, with quotient in q and remainder in r
  102. if ($rLast->isZero()) {
  103. // Oops, Euclidean algorithm already terminated?
  104. throw new ReedSolomonException("r_{i-1} was zero");
  105. }
  106. $r = $rLastLast;
  107. $q = $this->field->getZero();
  108. $denominatorLeadingTerm = $rLast->getCoefficient($rLast->getDegree());
  109. $dltInverse = $this->field->inverse($denominatorLeadingTerm);
  110. while ($r->getDegree() >= $rLast->getDegree() && !$r->isZero()) {
  111. $degreeDiff = $r->getDegree() - $rLast->getDegree();
  112. $scale = $this->field->multiply($r->getCoefficient($r->getDegree()), $dltInverse);
  113. $q = $q->addOrSubtract($this->field->buildMonomial($degreeDiff, $scale));
  114. $r = $r->addOrSubtract($rLast->multiplyByMonomial($degreeDiff, $scale));
  115. }
  116. $t = $q->multiply($tLast)->addOrSubtract($tLastLast);
  117. if ($r->getDegree() >= $rLast->getDegree()) {
  118. throw new IllegalStateException("Division algorithm failed to reduce polynomial?");
  119. }
  120. }
  121. $sigmaTildeAtZero = $t->getCoefficient(0);
  122. if ($sigmaTildeAtZero == 0) {
  123. throw new ReedSolomonException("sigmaTilde(0) was zero");
  124. }
  125. $inverse = $this->field->inverse($sigmaTildeAtZero);
  126. $sigma = $t->multiply($inverse);
  127. $omega = $r->multiply($inverse);
  128. return array($sigma, $omega);
  129. }
  130. private function findErrorLocations($errorLocator) {
  131. // This is a direct application of Chien's search
  132. $numErrors = $errorLocator->getDegree();
  133. if ($numErrors == 1) { // shortcut
  134. return array($errorLocator->getCoefficient(1) );
  135. }
  136. $result = fill_array(0,$numErrors,0);
  137. $e = 0;
  138. for ($i = 1; $i < $this->field->getSize() && $e < $numErrors; $i++) {
  139. if ($errorLocator->evaluateAt($i) == 0) {
  140. $result[$e] = $this->field->inverse($i);
  141. $e++;
  142. }
  143. }
  144. if ($e != $numErrors) {
  145. throw new ReedSolomonException("Error locator degree does not match number of roots");
  146. }
  147. return $result;
  148. }
  149. private function findErrorMagnitudes($errorEvaluator, $errorLocations) {
  150. // This is directly applying Forney's Formula
  151. $s = count($errorLocations);
  152. $result = fill_array(0,$s,0);
  153. for ($i = 0; $i < $s; $i++) {
  154. $xiInverse = $this->field->inverse($errorLocations[$i]);
  155. $denominator = 1;
  156. for ($j = 0; $j < $s; $j++) {
  157. if ($i != $j) {
  158. //denominator = field.multiply(denominator,
  159. // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
  160. // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
  161. // Below is a funny-looking workaround from Steven Parkes
  162. $term = $this->field->multiply($errorLocations[$j], $xiInverse);
  163. $termPlus1 = ($term & 0x1) == 0 ? $term | 1 : $term & ~1;
  164. $denominator = $this->field->multiply($denominator, $termPlus1);
  165. }
  166. }
  167. $result[$i] = $this->field->multiply($errorEvaluator->evaluateAt($xiInverse),
  168. $this->field->inverse($denominator));
  169. if ($this->field->getGeneratorBase() != 0) {
  170. $result[$i] = $this->field->multiply($result[$i], $xiInverse);
  171. }
  172. }
  173. return $result;
  174. }
  175. }