BitMatrixParser.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <?php
  2. /**
  3. * Class BitMatrixParser
  4. *
  5. * @created 17.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 RuntimeException;
  13. use chillerlan\QRCode\Common\{Version, FormatInformation};
  14. use const PHP_INT_MAX, PHP_INT_SIZE;
  15. /**
  16. * @author Sean Owen
  17. */
  18. final class BitMatrixParser{
  19. private BitMatrix $bitMatrix;
  20. private ?Version $parsedVersion = null;
  21. private ?FormatInformation $parsedFormatInfo = null;
  22. private bool $mirror = false;
  23. /**
  24. * @param \chillerlan\QRCode\Decoder\BitMatrix $bitMatrix
  25. *
  26. * @throws \RuntimeException if dimension is not >= 21 and 1 mod 4
  27. */
  28. public function __construct(BitMatrix $bitMatrix){
  29. $dimension = $bitMatrix->getDimension();
  30. if($dimension < 21 || ($dimension % 4) !== 1){
  31. throw new RuntimeException('dimension is not >= 21, dimension mod 4 not 1');
  32. }
  33. $this->bitMatrix = $bitMatrix;
  34. }
  35. /**
  36. * Prepare the parser for a mirrored operation.
  37. * This flag has effect only on the {@link #readFormatInformation()} and the
  38. * {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the
  39. * {@link #mirror()} method should be called.
  40. *
  41. * @param bool $mirror Whether to read version and format information mirrored.
  42. */
  43. public function setMirror(bool $mirror):void{
  44. $this->parsedVersion = null;
  45. $this->parsedFormatInfo = null;
  46. $this->mirror = $mirror;
  47. }
  48. /**
  49. * Mirror the bit matrix in order to attempt a second reading.
  50. */
  51. public function mirror():void{
  52. $this->bitMatrix->mirror();
  53. }
  54. private function copyBit(int $i, int $j, int $versionBits):int{
  55. $bit = $this->mirror
  56. ? $this->bitMatrix->get($j, $i)
  57. : $this->bitMatrix->get($i, $j);
  58. return $bit ? ($versionBits << 1) | 0x1 : $versionBits << 1;
  59. }
  60. /**
  61. * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
  62. * correct order in order to reconstruct the codewords bytes contained within the
  63. * QR Code.</p>
  64. *
  65. * @return array bytes encoded within the QR Code
  66. * @throws \RuntimeException if the exact number of bytes expected is not read
  67. */
  68. public function readCodewords():array{
  69. $formatInfo = $this->readFormatInformation();
  70. $version = $this->readVersion();
  71. // Get the data mask for the format used in this QR Code. This will exclude
  72. // some bits from reading as we wind through the bit matrix.
  73. $dimension = $this->bitMatrix->getDimension();
  74. $this->bitMatrix->unmask($dimension, $formatInfo->getDataMask());
  75. $functionPattern = $this->bitMatrix->buildFunctionPattern($version);
  76. $readingUp = true;
  77. $result = [];
  78. $resultOffset = 0;
  79. $currentByte = 0;
  80. $bitsRead = 0;
  81. // Read columns in pairs, from right to left
  82. for($j = $dimension - 1; $j > 0; $j -= 2){
  83. if($j === 6){
  84. // Skip whole column with vertical alignment pattern;
  85. // saves time and makes the other code proceed more cleanly
  86. $j--;
  87. }
  88. // Read alternatingly from bottom to top then top to bottom
  89. for($count = 0; $count < $dimension; $count++){
  90. $i = $readingUp ? $dimension - 1 - $count : $count;
  91. for($col = 0; $col < 2; $col++){
  92. // Ignore bits covered by the function pattern
  93. if(!$functionPattern->get($j - $col, $i)){
  94. // Read a bit
  95. $bitsRead++;
  96. $currentByte <<= 1;
  97. if($this->bitMatrix->get($j - $col, $i)){
  98. $currentByte |= 1;
  99. }
  100. // If we've made a whole byte, save it off
  101. if($bitsRead === 8){
  102. $result[$resultOffset++] = $currentByte; //(byte)
  103. $bitsRead = 0;
  104. $currentByte = 0;
  105. }
  106. }
  107. }
  108. }
  109. $readingUp = !$readingUp; // switch directions
  110. }
  111. if($resultOffset !== $version->getTotalCodewords()){
  112. throw new RuntimeException('offset differs from total codewords for version');
  113. }
  114. return $result;
  115. }
  116. /**
  117. * <p>Reads format information from one of its two locations within the QR Code.</p>
  118. *
  119. * @return \chillerlan\QRCode\Common\FormatInformation encapsulating the QR Code's format info
  120. * @throws \RuntimeException if both format information locations cannot be parsed as
  121. * the valid encoding of format information
  122. */
  123. public function readFormatInformation():FormatInformation{
  124. if($this->parsedFormatInfo !== null){
  125. return $this->parsedFormatInfo;
  126. }
  127. // Read top-left format info bits
  128. $formatInfoBits1 = 0;
  129. for($i = 0; $i < 6; $i++){
  130. $formatInfoBits1 = $this->copyBit($i, 8, $formatInfoBits1);
  131. }
  132. // .. and skip a bit in the timing pattern ...
  133. $formatInfoBits1 = $this->copyBit(7, 8, $formatInfoBits1);
  134. $formatInfoBits1 = $this->copyBit(8, 8, $formatInfoBits1);
  135. $formatInfoBits1 = $this->copyBit(8, 7, $formatInfoBits1);
  136. // .. and skip a bit in the timing pattern ...
  137. for($j = 5; $j >= 0; $j--){
  138. $formatInfoBits1 = $this->copyBit(8, $j, $formatInfoBits1);
  139. }
  140. // Read the top-right/bottom-left pattern too
  141. $dimension = $this->bitMatrix->getDimension();
  142. $formatInfoBits2 = 0;
  143. $jMin = $dimension - 7;
  144. for($j = $dimension - 1; $j >= $jMin; $j--){
  145. $formatInfoBits2 = $this->copyBit(8, $j, $formatInfoBits2);
  146. }
  147. for($i = $dimension - 8; $i < $dimension; $i++){
  148. $formatInfoBits2 = $this->copyBit($i, 8, $formatInfoBits2);
  149. }
  150. $this->parsedFormatInfo = $this->doDecodeFormatInformation($formatInfoBits1, $formatInfoBits2);
  151. if($this->parsedFormatInfo !== null){
  152. return $this->parsedFormatInfo;
  153. }
  154. // Should return null, but, some QR codes apparently do not mask this info.
  155. // Try again by actually masking the pattern first.
  156. $this->parsedFormatInfo = $this->doDecodeFormatInformation(
  157. $formatInfoBits1 ^ FormatInformation::MASK_QR,
  158. $formatInfoBits2 ^ FormatInformation::MASK_QR
  159. );
  160. if($this->parsedFormatInfo !== null){
  161. return $this->parsedFormatInfo;
  162. }
  163. throw new RuntimeException('failed to read format info');
  164. }
  165. /**
  166. * @param int $maskedFormatInfo1 format info indicator, with mask still applied
  167. * @param int $maskedFormatInfo2 second copy of same info; both are checked at the same time
  168. * to establish best match
  169. *
  170. * @return \chillerlan\QRCode\Common\FormatInformation|null information about the format it specifies, or null
  171. * if doesn't seem to match any known pattern
  172. */
  173. private function doDecodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2):?FormatInformation{
  174. // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
  175. $bestDifference = PHP_INT_MAX;
  176. $bestFormatInfo = 0;
  177. foreach(FormatInformation::DECODE_LOOKUP as $decodeInfo){
  178. [$maskedBits, $dataBits] = $decodeInfo;
  179. if($maskedFormatInfo1 === $dataBits || $maskedFormatInfo2 === $dataBits){
  180. // Found an exact match
  181. return new FormatInformation($maskedBits);
  182. }
  183. $bitsDifference = self::numBitsDiffering($maskedFormatInfo1, $dataBits);
  184. if($bitsDifference < $bestDifference){
  185. $bestFormatInfo = $maskedBits;
  186. $bestDifference = $bitsDifference;
  187. }
  188. if($maskedFormatInfo1 !== $maskedFormatInfo2){
  189. // also try the other option
  190. $bitsDifference = self::numBitsDiffering($maskedFormatInfo2, $dataBits);
  191. if($bitsDifference < $bestDifference){
  192. $bestFormatInfo = $maskedBits;
  193. $bestDifference = $bitsDifference;
  194. }
  195. }
  196. }
  197. // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits differing means we found a match
  198. if($bestDifference <= 3){
  199. return new FormatInformation($bestFormatInfo);
  200. }
  201. return null;
  202. }
  203. /**
  204. * <p>Reads version information from one of its two locations within the QR Code.</p>
  205. *
  206. * @return \chillerlan\QRCode\Common\Version encapsulating the QR Code's version
  207. * @throws \RuntimeException if both version information locations cannot be parsed as
  208. * the valid encoding of version information
  209. */
  210. public function readVersion():Version{
  211. if($this->parsedVersion !== null){
  212. return $this->parsedVersion;
  213. }
  214. $dimension = $this->bitMatrix->getDimension();
  215. $provisionalVersion = ($dimension - 17) / 4;
  216. if($provisionalVersion <= 6){
  217. return new Version($provisionalVersion);
  218. }
  219. // Read top-right version info: 3 wide by 6 tall
  220. $versionBits = 0;
  221. $ijMin = $dimension - 11;
  222. for($j = 5; $j >= 0; $j--){
  223. for($i = $dimension - 9; $i >= $ijMin; $i--){
  224. $versionBits = $this->copyBit($i, $j, $versionBits);
  225. }
  226. }
  227. $this->parsedVersion = $this->decodeVersionInformation($versionBits);
  228. if($this->parsedVersion !== null && $this->parsedVersion->getDimension() === $dimension){
  229. return $this->parsedVersion;
  230. }
  231. // Hmm, failed. Try bottom left: 6 wide by 3 tall
  232. $versionBits = 0;
  233. for($i = 5; $i >= 0; $i--){
  234. for($j = $dimension - 9; $j >= $ijMin; $j--){
  235. $versionBits = $this->copyBit($i, $j, $versionBits);
  236. }
  237. }
  238. $this->parsedVersion = $this->decodeVersionInformation($versionBits);
  239. if($this->parsedVersion !== null && $this->parsedVersion->getDimension() === $dimension){
  240. return $this->parsedVersion;
  241. }
  242. throw new RuntimeException('failed to read version');
  243. }
  244. /**
  245. * @param int $versionBits
  246. *
  247. * @return \chillerlan\QRCode\Common\Version|null
  248. */
  249. private function decodeVersionInformation(int $versionBits):?Version{
  250. $bestDifference = PHP_INT_MAX;
  251. $bestVersion = 0;
  252. for($i = 7; $i <= 40; $i++){
  253. $targetVersion = new Version($i);
  254. $targetVersionPattern = $targetVersion->getVersionPattern();
  255. // Do the version info bits match exactly? done.
  256. if($targetVersionPattern === $versionBits){
  257. return $targetVersion;
  258. }
  259. // Otherwise see if this is the closest to a real version info bit string
  260. // we have seen so far
  261. /** @phan-suppress-next-line PhanTypeMismatchArgumentNullable ($targetVersionPattern is never null here) */
  262. $bitsDifference = self::numBitsDiffering($versionBits, $targetVersionPattern);
  263. if($bitsDifference < $bestDifference){
  264. $bestVersion = $i;
  265. $bestDifference = $bitsDifference;
  266. }
  267. }
  268. // We can tolerate up to 3 bits of error since no two version info codewords will
  269. // differ in less than 8 bits.
  270. if($bestDifference <= 3){
  271. return new Version($bestVersion);
  272. }
  273. // If we didn't find a close enough match, fail
  274. return null;
  275. }
  276. public static function uRShift(int $a, int $b):int{
  277. if($b === 0){
  278. return $a;
  279. }
  280. return ($a >> $b) & ~((1 << (8 * PHP_INT_SIZE - 1)) >> ($b - 1));
  281. }
  282. private static function numBitsDiffering(int $a, int $b):int{
  283. // a now has a 1 bit exactly where its bit differs with b's
  284. $a ^= $b;
  285. // Offset i holds the number of 1 bits in the binary representation of i
  286. $BITS_SET_IN_HALF_BYTE = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
  287. // Count bits set quickly with a series of lookups:
  288. $count = 0;
  289. for($i = 0; $i < 32; $i += 4){
  290. $count += $BITS_SET_IN_HALF_BYTE[self::uRShift($a, $i) & 0x0F];
  291. }
  292. return $count;
  293. }
  294. }