ReedSolomonDecoder.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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\Decoder;
  12. use chillerlan\QRCode\Common\{BitBuffer, EccLevel, GenericGFPoly, GF256, Version};
  13. use function array_fill, array_reverse, count;
  14. /**
  15. * Implements Reed-Solomon decoding
  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. * @param int[] $rawCodewords
  46. */
  47. public function decode(array $rawCodewords):BitBuffer{
  48. $dataBlocks = $this->deinterleaveRawBytes($rawCodewords);
  49. $dataBytes = [];
  50. foreach($dataBlocks as [$numDataCodewords, $codewordBytes]){
  51. $corrected = $this->correctErrors($codewordBytes, $numDataCodewords);
  52. for($i = 0; $i < $numDataCodewords; $i++){
  53. $dataBytes[] = $corrected[$i];
  54. }
  55. }
  56. return new BitBuffer($dataBytes);
  57. }
  58. /**
  59. * When QR Codes use multiple data blocks, they are actually interleaved.
  60. * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
  61. * method will separate the data into original blocks.
  62. *
  63. * @throws \chillerlan\QRCode\Decoder\QRCodeDecoderException
  64. *
  65. * @param int[] $rawCodewords
  66. */
  67. private function deinterleaveRawBytes(array $rawCodewords):array{
  68. // Figure out the number and size of data blocks used by this version and
  69. // error correction level
  70. [$numEccCodewords, $eccBlocks] = $this->version->getRSBlocks($this->eccLevel);
  71. // Now establish DataBlocks of the appropriate size and number of data codewords
  72. $result = [];//new DataBlock[$totalBlocks];
  73. $numResultBlocks = 0;
  74. foreach($eccBlocks as [$numEccBlocks, $eccPerBlock]){
  75. for($i = 0; $i < $numEccBlocks; $i++, $numResultBlocks++){
  76. $result[$numResultBlocks] = [$eccPerBlock, array_fill(0, ($numEccCodewords + $eccPerBlock), 0)];
  77. }
  78. }
  79. // All blocks have the same amount of data, except that the last n
  80. // (where n may be 0) have 1 more byte. Figure out where these start.
  81. $shorterBlocksTotalCodewords = count($result[0][1]);
  82. $longerBlocksStartAt = (count($result) - 1);
  83. while($longerBlocksStartAt >= 0){
  84. $numCodewords = count($result[$longerBlocksStartAt][1]);
  85. if($numCodewords == $shorterBlocksTotalCodewords){
  86. break;
  87. }
  88. $longerBlocksStartAt--;
  89. }
  90. $longerBlocksStartAt++;
  91. $shorterBlocksNumDataCodewords = ($shorterBlocksTotalCodewords - $numEccCodewords);
  92. // The last elements of result may be 1 element longer;
  93. // first fill out as many elements as all of them have
  94. $rawCodewordsOffset = 0;
  95. for($i = 0; $i < $shorterBlocksNumDataCodewords; $i++){
  96. for($j = 0; $j < $numResultBlocks; $j++){
  97. $result[$j][1][$i] = $rawCodewords[$rawCodewordsOffset++];
  98. }
  99. }
  100. // Fill out the last data block in the longer ones
  101. for($j = $longerBlocksStartAt; $j < $numResultBlocks; $j++){
  102. $result[$j][1][$shorterBlocksNumDataCodewords] = $rawCodewords[$rawCodewordsOffset++];
  103. }
  104. // Now add in error correction blocks
  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. * @param int[] $codewordBytes
  120. * @return int[]
  121. */
  122. private function correctErrors(array $codewordBytes, int $numDataCodewords):array{
  123. // First read into an array of ints
  124. $codewordsInts = [];
  125. foreach($codewordBytes as $codewordByte){
  126. $codewordsInts[] = ($codewordByte & 0xFF);
  127. }
  128. $decoded = $this->decodeWords($codewordsInts, (count($codewordBytes) - $numDataCodewords));
  129. // Copy back into array of bytes -- only need to worry about the bytes that were data
  130. // We don't care about errors in the error-correction codewords
  131. for($i = 0; $i < $numDataCodewords; $i++){
  132. $codewordBytes[$i] = $decoded[$i];
  133. }
  134. return $codewordBytes;
  135. }
  136. /**
  137. * Decodes given set of received codewords, which include both data and error-correction
  138. * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
  139. * in the input.
  140. *
  141. * @param int[] $received data and error-correction codewords
  142. * @param int $numEccCodewords number of error-correction codewords available
  143. *
  144. * @return int[]
  145. * @throws \chillerlan\QRCode\Decoder\QRCodeDecoderException if decoding fails for any reason
  146. */
  147. private function decodeWords(array $received, int $numEccCodewords):array{
  148. $poly = new GenericGFPoly($received);
  149. $syndromeCoefficients = [];
  150. $error = false;
  151. for($i = 0; $i < $numEccCodewords; $i++){
  152. $syndromeCoefficients[$i] = $poly->evaluateAt(GF256::exp($i));
  153. if($syndromeCoefficients[$i] !== 0){
  154. $error = true;
  155. }
  156. }
  157. if(!$error){
  158. return $received;
  159. }
  160. [$sigma, $omega] = $this->runEuclideanAlgorithm(
  161. GF256::buildMonomial($numEccCodewords, 1),
  162. new GenericGFPoly(array_reverse($syndromeCoefficients)),
  163. $numEccCodewords
  164. );
  165. $errorLocations = $this->findErrorLocations($sigma);
  166. $errorMagnitudes = $this->findErrorMagnitudes($omega, $errorLocations);
  167. $errorLocationsCount = count($errorLocations);
  168. $receivedCount = count($received);
  169. for($i = 0; $i < $errorLocationsCount; $i++){
  170. $position = ($receivedCount - 1 - GF256::log($errorLocations[$i]));
  171. if($position < 0){
  172. throw new QRCodeDecoderException('Bad error location');
  173. }
  174. $received[$position] ^= $errorMagnitudes[$i];
  175. }
  176. return $received;
  177. }
  178. /**
  179. * @return \chillerlan\QRCode\Common\GenericGFPoly[] [sigma, omega]
  180. * @throws \chillerlan\QRCode\Decoder\QRCodeDecoderException
  181. */
  182. private function runEuclideanAlgorithm(GenericGFPoly $a, GenericGFPoly $b, int $z):array{
  183. // Assume a's degree is >= b's
  184. if($a->getDegree() < $b->getDegree()){
  185. $temp = $a;
  186. $a = $b;
  187. $b = $temp;
  188. }
  189. $rLast = $a;
  190. $r = $b;
  191. $tLast = new GenericGFPoly([0]);
  192. $t = new GenericGFPoly([1]);
  193. // Run Euclidean algorithm until r's degree is less than z/2
  194. while((2 * $r->getDegree()) >= $z){
  195. $rLastLast = $rLast;
  196. $tLastLast = $tLast;
  197. $rLast = $r;
  198. $tLast = $t;
  199. // Divide rLastLast by rLast, with quotient in q and remainder in r
  200. [$q, $r] = $rLastLast->divide($rLast);
  201. $t = $q->multiply($tLast)->addOrSubtract($tLastLast);
  202. if($r->getDegree() >= $rLast->getDegree()){
  203. throw new QRCodeDecoderException('Division algorithm failed to reduce polynomial?');
  204. }
  205. }
  206. $sigmaTildeAtZero = $t->getCoefficient(0);
  207. if($sigmaTildeAtZero === 0){
  208. throw new QRCodeDecoderException('sigmaTilde(0) was zero');
  209. }
  210. $inverse = GF256::inverse($sigmaTildeAtZero);
  211. return [$t->multiplyInt($inverse), $r->multiplyInt($inverse)];
  212. }
  213. /**
  214. * @return int[]
  215. * @throws \chillerlan\QRCode\Decoder\QRCodeDecoderException
  216. */
  217. private function findErrorLocations(GenericGFPoly $errorLocator):array{
  218. // This is a direct application of Chien's search
  219. $numErrors = $errorLocator->getDegree();
  220. if($numErrors === 1){ // shortcut
  221. return [$errorLocator->getCoefficient(1)];
  222. }
  223. $result = array_fill(0, $numErrors, 0);
  224. $e = 0;
  225. for($i = 1; $i < 256 && $e < $numErrors; $i++){
  226. if($errorLocator->evaluateAt($i) === 0){
  227. $result[$e] = GF256::inverse($i);
  228. $e++;
  229. }
  230. }
  231. if($e !== $numErrors){
  232. throw new QRCodeDecoderException('Error locator degree does not match number of roots');
  233. }
  234. return $result;
  235. }
  236. /**
  237. * @param int[] $errorLocations
  238. * @return int[]
  239. */
  240. private function findErrorMagnitudes(GenericGFPoly $errorEvaluator, array $errorLocations):array{
  241. // This is directly applying Forney's Formula
  242. $s = count($errorLocations);
  243. $result = [];
  244. for($i = 0; $i < $s; $i++){
  245. $xiInverse = GF256::inverse($errorLocations[$i]);
  246. $denominator = 1;
  247. for($j = 0; $j < $s; $j++){
  248. if($i !== $j){
  249. # $denominator = GF256::multiply($denominator, GF256::addOrSubtract(1, GF256::multiply($errorLocations[$j], $xiInverse)));
  250. // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
  251. // Below is a funny-looking workaround from Steven Parkes
  252. $term = GF256::multiply($errorLocations[$j], $xiInverse);
  253. $denominator = GF256::multiply($denominator, ((($term & 0x1) === 0) ? ($term | 1) : ($term & ~1)));
  254. }
  255. }
  256. $result[$i] = GF256::multiply($errorEvaluator->evaluateAt($xiInverse), GF256::inverse($denominator));
  257. }
  258. return $result;
  259. }
  260. }