ReedSolomonDecoder.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. <?php
  2. /**
  3. * Class ReedSolomonDecoder
  4. *
  5. * @created 24.01.2021
  6. * @author ZXing Authors
  7. * @author Smiley <smiley@chillerlan.net>
  8. * @copyright 2021 Smiley
  9. * @license Apache-2.0
  10. */
  11. namespace chillerlan\QRCode\Common;
  12. use chillerlan\QRCode\QRCodeException;
  13. use function array_fill, array_reverse, count;
  14. /**
  15. * Implements Reed-Solomon decoding, as the name implies.
  16. *
  17. * The algorithm will not be explained here, but the following references were helpful
  18. * in creating this implementation:
  19. *
  20. * - Bruce Maggs "Decoding Reed-Solomon Codes" (see discussion of Forney's Formula)
  21. * http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps
  22. * - J.I. Hall. "Chapter 5. Generalized Reed-Solomon Codes" (see discussion of Euclidean algorithm)
  23. * https://users.math.msu.edu/users/halljo/classes/codenotes/GRS.pdf
  24. *
  25. * Much credit is due to William Rucklidge since portions of this code are an indirect
  26. * port of his C++ Reed-Solomon implementation.
  27. *
  28. * @author Sean Owen
  29. * @author William Rucklidge
  30. * @author sanfordsquires
  31. */
  32. final class ReedSolomonDecoder{
  33. private Version $version;
  34. private EccLevel $eccLevel;
  35. /**
  36. * ReedSolomonDecoder constructor
  37. */
  38. public function __construct(Version $version, EccLevel $eccLevel){
  39. $this->version = $version;
  40. $this->eccLevel = $eccLevel;
  41. }
  42. /**
  43. * Error-correct and copy data blocks together into a stream of bytes
  44. */
  45. public function decode(array $rawCodewords):BitBuffer{
  46. $dataBlocks = $this->deinterleaveRawBytes($rawCodewords);
  47. $dataBytes = [];
  48. foreach($dataBlocks as $dataBlock){
  49. [$numDataCodewords, $codewordBytes] = $dataBlock;
  50. $corrected = $this->correctErrors($codewordBytes, $numDataCodewords);
  51. for($i = 0; $i < $numDataCodewords; $i++){
  52. $dataBytes[] = $corrected[$i];
  53. }
  54. }
  55. return new BitBuffer($dataBytes);
  56. }
  57. /**
  58. * When QR Codes use multiple data blocks, they are actually interleaved.
  59. * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
  60. * method will separate the data into original blocks.
  61. *
  62. * @throws \chillerlan\QRCode\Decoder\QRCodeDecoderException
  63. */
  64. private function deinterleaveRawBytes(array $rawCodewords):array{
  65. // Figure out the number and size of data blocks used by this version and
  66. // error correction level
  67. [$numEccCodewords, $eccBlocks] = $this->version->getRSBlocks($this->eccLevel);
  68. // Now establish DataBlocks of the appropriate size and number of data codewords
  69. $result = [];//new DataBlock[$totalBlocks];
  70. $numResultBlocks = 0;
  71. foreach($eccBlocks as $blockData){
  72. [$numEccBlocks, $eccPerBlock] = $blockData;
  73. for($i = 0; $i < $numEccBlocks; $i++, $numResultBlocks++){
  74. $result[$numResultBlocks] = [$eccPerBlock, array_fill(0, $numEccCodewords + $eccPerBlock, 0)];
  75. }
  76. }
  77. // All blocks have the same amount of data, except that the last n
  78. // (where n may be 0) have 1 more byte. Figure out where these start.
  79. /** @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset */
  80. $shorterBlocksTotalCodewords = count($result[0][1]);
  81. $longerBlocksStartAt = count($result) - 1;
  82. while($longerBlocksStartAt >= 0){
  83. $numCodewords = count($result[$longerBlocksStartAt][1]);
  84. if($numCodewords == $shorterBlocksTotalCodewords){
  85. break;
  86. }
  87. $longerBlocksStartAt--;
  88. }
  89. $longerBlocksStartAt++;
  90. $shorterBlocksNumDataCodewords = $shorterBlocksTotalCodewords - $numEccCodewords;
  91. // The last elements of result may be 1 element longer;
  92. // first fill out as many elements as all of them have
  93. $rawCodewordsOffset = 0;
  94. for($i = 0; $i < $shorterBlocksNumDataCodewords; $i++){
  95. for($j = 0; $j < $numResultBlocks; $j++){
  96. $result[$j][1][$i] = $rawCodewords[$rawCodewordsOffset++];
  97. }
  98. }
  99. // Fill out the last data block in the longer ones
  100. for($j = $longerBlocksStartAt; $j < $numResultBlocks; $j++){
  101. $result[$j][1][$shorterBlocksNumDataCodewords] = $rawCodewords[$rawCodewordsOffset++];
  102. }
  103. // Now add in error correction blocks
  104. /** @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset */
  105. $max = count($result[0][1]);
  106. for($i = $shorterBlocksNumDataCodewords; $i < $max; $i++){
  107. for($j = 0; $j < $numResultBlocks; $j++){
  108. $iOffset = $j < $longerBlocksStartAt ? $i : $i + 1;
  109. $result[$j][1][$iOffset] = $rawCodewords[$rawCodewordsOffset++];
  110. }
  111. }
  112. // DataBlocks containing original bytes, "de-interleaved" from representation in the QR Code
  113. return $result;
  114. }
  115. /**
  116. * Given data and error-correction codewords received, possibly corrupted by errors, attempts to
  117. * correct the errors in-place using Reed-Solomon error correction.
  118. */
  119. private function correctErrors(array $codewordBytes, int $numDataCodewords):array{
  120. // First read into an array of ints
  121. $codewordsInts = [];
  122. foreach($codewordBytes as $codewordByte){
  123. $codewordsInts[] = $codewordByte & 0xFF;
  124. }
  125. $decoded = $this->decodeWords($codewordsInts, (count($codewordBytes) - $numDataCodewords));
  126. // Copy back into array of bytes -- only need to worry about the bytes that were data
  127. // We don't care about errors in the error-correction codewords
  128. for($i = 0; $i < $numDataCodewords; $i++){
  129. $codewordBytes[$i] = $decoded[$i];
  130. }
  131. return $codewordBytes;
  132. }
  133. /**
  134. * Decodes given set of received codewords, which include both data and error-correction
  135. * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
  136. * in the input.
  137. *
  138. * @param array $received data and error-correction codewords
  139. * @param int $numEccCodewords number of error-correction codewords available
  140. *
  141. * @return int[]
  142. * @throws \chillerlan\QRCode\QRCodeException if decoding fails for any reason
  143. */
  144. private function decodeWords(array $received, int $numEccCodewords):array{
  145. $poly = new GenericGFPoly($received);
  146. $syndromeCoefficients = [];
  147. $error = false;
  148. for($i = 0; $i < $numEccCodewords; $i++){
  149. $syndromeCoefficients[$i] = $poly->evaluateAt(GF256::exp($i));
  150. if($syndromeCoefficients[$i] !== 0){
  151. $error = true;
  152. }
  153. }
  154. if(!$error){
  155. return $received;
  156. }
  157. [$sigma, $omega] = $this->runEuclideanAlgorithm(
  158. GF256::buildMonomial($numEccCodewords, 1),
  159. new GenericGFPoly(array_reverse($syndromeCoefficients)),
  160. $numEccCodewords
  161. );
  162. $errorLocations = $this->findErrorLocations($sigma);
  163. $errorMagnitudes = $this->findErrorMagnitudes($omega, $errorLocations);
  164. $errorLocationsCount = count($errorLocations);
  165. $receivedCount = count($received);
  166. for($i = 0; $i < $errorLocationsCount; $i++){
  167. $position = $receivedCount - 1 - GF256::log($errorLocations[$i]);
  168. if($position < 0){
  169. throw new QRCodeException('Bad error location');
  170. }
  171. $received[$position] ^= $errorMagnitudes[$i];
  172. }
  173. return $received;
  174. }
  175. /**
  176. * @return \chillerlan\QRCode\Common\GenericGFPoly[] [sigma, omega]
  177. * @throws \chillerlan\QRCode\QRCodeException
  178. */
  179. private function runEuclideanAlgorithm(GenericGFPoly $a, GenericGFPoly $b, int $R):array{
  180. // Assume a's degree is >= b's
  181. if($a->getDegree() < $b->getDegree()){
  182. $temp = $a;
  183. $a = $b;
  184. $b = $temp;
  185. }
  186. $rLast = $a;
  187. $r = $b;
  188. $tLast = new GenericGFPoly([0]);
  189. $t = new GenericGFPoly([1]);
  190. // Run Euclidean algorithm until r's degree is less than R/2
  191. while(2 * $r->getDegree() >= $R){
  192. $rLastLast = $rLast;
  193. $tLastLast = $tLast;
  194. $rLast = $r;
  195. $tLast = $t;
  196. // Divide rLastLast by rLast, with quotient in q and remainder in r
  197. [$q, $r] = $rLastLast->divide($rLast);
  198. $t = $q->multiply($tLast)->addOrSubtract($tLastLast);
  199. if($r->getDegree() >= $rLast->getDegree()){
  200. throw new QRCodeException('Division algorithm failed to reduce polynomial?');
  201. }
  202. }
  203. $sigmaTildeAtZero = $t->getCoefficient(0);
  204. if($sigmaTildeAtZero === 0){
  205. throw new QRCodeException('sigmaTilde(0) was zero');
  206. }
  207. $inverse = GF256::inverse($sigmaTildeAtZero);
  208. return [$t->multiplyInt($inverse), $r->multiplyInt($inverse)];
  209. }
  210. /**
  211. * @throws \chillerlan\QRCode\QRCodeException
  212. */
  213. private function findErrorLocations(GenericGFPoly $errorLocator):array{
  214. // This is a direct application of Chien's search
  215. $numErrors = $errorLocator->getDegree();
  216. if($numErrors === 1){ // shortcut
  217. return [$errorLocator->getCoefficient(1)];
  218. }
  219. $result = array_fill(0, $numErrors, 0);
  220. $e = 0;
  221. for($i = 1; $i < 256 && $e < $numErrors; $i++){
  222. if($errorLocator->evaluateAt($i) === 0){
  223. $result[$e] = GF256::inverse($i);
  224. $e++;
  225. }
  226. }
  227. if($e !== $numErrors){
  228. throw new QRCodeException('Error locator degree does not match number of roots');
  229. }
  230. return $result;
  231. }
  232. /**
  233. *
  234. */
  235. private function findErrorMagnitudes(GenericGFPoly $errorEvaluator, array $errorLocations):array{
  236. // This is directly applying Forney's Formula
  237. $s = count($errorLocations);
  238. $result = [];
  239. for($i = 0; $i < $s; $i++){
  240. $xiInverse = GF256::inverse($errorLocations[$i]);
  241. $denominator = 1;
  242. for($j = 0; $j < $s; $j++){
  243. if($i !== $j){
  244. # $denominator = GF256::multiply($denominator, GF256::addOrSubtract(1, GF256::multiply($errorLocations[$j], $xiInverse)));
  245. // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
  246. // Below is a funny-looking workaround from Steven Parkes
  247. $term = GF256::multiply($errorLocations[$j], $xiInverse);
  248. $denominator = GF256::multiply($denominator, (($term & 0x1) === 0 ? $term | 1 : $term & ~1));
  249. }
  250. }
  251. $result[$i] = GF256::multiply($errorEvaluator->evaluateAt($xiInverse), GF256::inverse($denominator));
  252. }
  253. return $result;
  254. }
  255. }