ReedSolomonDecoder.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. {
  42. private $field;
  43. public function __construct($field)
  44. {
  45. $this->field = $field;
  46. }
  47. /**
  48. * <p>Decodes given set of received codewords, which include both data and error-correction
  49. * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
  50. * in the input.</p>
  51. *
  52. * @param received data and error-correction codewords
  53. * @param twoS number of error-correction codewords available
  54. *
  55. * @throws ReedSolomonException if decoding fails for any reason
  56. */
  57. public function decode(&$received, $twoS)
  58. {
  59. $poly = new GenericGFPoly($this->field, $received);
  60. $syndromeCoefficients = fill_array(0, $twoS, 0);
  61. $noError = true;
  62. for ($i = 0; $i < $twoS; $i++) {
  63. $eval = $poly->evaluateAt($this->field->exp($i + $this->field->getGeneratorBase()));
  64. $syndromeCoefficients[count($syndromeCoefficients) - 1 - $i] = $eval;
  65. if ($eval != 0) {
  66. $noError = false;
  67. }
  68. }
  69. if ($noError) {
  70. return;
  71. }
  72. $syndrome = new GenericGFPoly($this->field, $syndromeCoefficients);
  73. $sigmaOmega =
  74. $this->runEuclideanAlgorithm($this->field->buildMonomial($twoS, 1), $syndrome, $twoS);
  75. $sigma = $sigmaOmega[0];
  76. $omega = $sigmaOmega[1];
  77. $errorLocations = $this->findErrorLocations($sigma);
  78. $errorMagnitudes = $this->findErrorMagnitudes($omega, $errorLocations);
  79. $errorLocationsCount = count($errorLocations);
  80. for ($i = 0; $i < $errorLocationsCount; $i++) {
  81. $position = count($received) - 1 - $this->field->log($errorLocations[$i]);
  82. if ($position < 0) {
  83. throw new ReedSolomonException("Bad error location");
  84. }
  85. $received[$position] = GenericGF::addOrSubtract($received[$position], $errorMagnitudes[$i]);
  86. }
  87. }
  88. private function runEuclideanAlgorithm($a, $b, $R)
  89. {
  90. // Assume a's degree is >= b's
  91. if ($a->getDegree() < $b->getDegree()) {
  92. $temp = $a;
  93. $a = $b;
  94. $b = $temp;
  95. }
  96. $rLast = $a;
  97. $r = $b;
  98. $tLast = $this->field->getZero();
  99. $t = $this->field->getOne();
  100. // Run Euclidean algorithm until r's degree is less than R/2
  101. while ($r->getDegree() >= $R / 2) {
  102. $rLastLast = $rLast;
  103. $tLastLast = $tLast;
  104. $rLast = $r;
  105. $tLast = $t;
  106. // Divide rLastLast by rLast, with quotient in q and remainder in r
  107. if ($rLast->isZero()) {
  108. // Oops, Euclidean algorithm already terminated?
  109. throw new ReedSolomonException("r_{i-1} was zero");
  110. }
  111. $r = $rLastLast;
  112. $q = $this->field->getZero();
  113. $denominatorLeadingTerm = $rLast->getCoefficient($rLast->getDegree());
  114. $dltInverse = $this->field->inverse($denominatorLeadingTerm);
  115. while ($r->getDegree() >= $rLast->getDegree() && !$r->isZero()) {
  116. $degreeDiff = $r->getDegree() - $rLast->getDegree();
  117. $scale = $this->field->multiply($r->getCoefficient($r->getDegree()), $dltInverse);
  118. $q = $q->addOrSubtract($this->field->buildMonomial($degreeDiff, $scale));
  119. $r = $r->addOrSubtract($rLast->multiplyByMonomial($degreeDiff, $scale));
  120. }
  121. $t = $q->multiply($tLast)->addOrSubtract($tLastLast);
  122. if ($r->getDegree() >= $rLast->getDegree()) {
  123. throw new ReedSolomonException("Division algorithm failed to reduce polynomial?");
  124. }
  125. }
  126. $sigmaTildeAtZero = $t->getCoefficient(0);
  127. if ($sigmaTildeAtZero == 0) {
  128. throw new ReedSolomonException("sigmaTilde(0) was zero");
  129. }
  130. $inverse = $this->field->inverse($sigmaTildeAtZero);
  131. $sigma = $t->multiply($inverse);
  132. $omega = $r->multiply($inverse);
  133. return [$sigma, $omega];
  134. }
  135. private function findErrorLocations($errorLocator)
  136. {
  137. // This is a direct application of Chien's search
  138. $numErrors = $errorLocator->getDegree();
  139. if ($numErrors == 1) { // shortcut
  140. return [$errorLocator->getCoefficient(1)];
  141. }
  142. $result = fill_array(0, $numErrors, 0);
  143. $e = 0;
  144. for ($i = 1; $i < $this->field->getSize() && $e < $numErrors; $i++) {
  145. if ($errorLocator->evaluateAt($i) == 0) {
  146. $result[$e] = $this->field->inverse($i);
  147. $e++;
  148. }
  149. }
  150. if ($e != $numErrors) {
  151. throw new ReedSolomonException("Error locator degree does not match number of roots");
  152. }
  153. return $result;
  154. }
  155. private function findErrorMagnitudes($errorEvaluator, $errorLocations)
  156. {
  157. // This is directly applying Forney's Formula
  158. $s = count($errorLocations);
  159. $result = fill_array(0, $s, 0);
  160. for ($i = 0; $i < $s; $i++) {
  161. $xiInverse = $this->field->inverse($errorLocations[$i]);
  162. $denominator = 1;
  163. for ($j = 0; $j < $s; $j++) {
  164. if ($i != $j) {
  165. //denominator = field.multiply(denominator,
  166. // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
  167. // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
  168. // Below is a funny-looking workaround from Steven Parkes
  169. $term = $this->field->multiply($errorLocations[$j], $xiInverse);
  170. $termPlus1 = ($term & 0x1) == 0 ? $term | 1 : $term & ~1;
  171. $denominator = $this->field->multiply($denominator, $termPlus1);
  172. }
  173. }
  174. $result[$i] = $this->field->multiply($errorEvaluator->evaluateAt($xiInverse),
  175. $this->field->inverse($denominator));
  176. if ($this->field->getGeneratorBase() != 0) {
  177. $result[$i] = $this->field->multiply($result[$i], $xiInverse);
  178. }
  179. }
  180. return $result;
  181. }
  182. }