MatrixUtil.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. <?php
  2. declare(strict_types = 1);
  3. namespace BaconQrCode\Encoder;
  4. use BaconQrCode\Common\BitArray;
  5. use BaconQrCode\Common\ErrorCorrectionLevel;
  6. use BaconQrCode\Common\Version;
  7. use BaconQrCode\Exception\RuntimeException;
  8. use BaconQrCode\Exception\WriterException;
  9. /**
  10. * Matrix utility.
  11. */
  12. final class MatrixUtil
  13. {
  14. /**
  15. * Position detection pattern.
  16. */
  17. private const POSITION_DETECTION_PATTERN = [
  18. [1, 1, 1, 1, 1, 1, 1],
  19. [1, 0, 0, 0, 0, 0, 1],
  20. [1, 0, 1, 1, 1, 0, 1],
  21. [1, 0, 1, 1, 1, 0, 1],
  22. [1, 0, 1, 1, 1, 0, 1],
  23. [1, 0, 0, 0, 0, 0, 1],
  24. [1, 1, 1, 1, 1, 1, 1],
  25. ];
  26. /**
  27. * Position adjustment pattern.
  28. */
  29. private const POSITION_ADJUSTMENT_PATTERN = [
  30. [1, 1, 1, 1, 1],
  31. [1, 0, 0, 0, 1],
  32. [1, 0, 1, 0, 1],
  33. [1, 0, 0, 0, 1],
  34. [1, 1, 1, 1, 1],
  35. ];
  36. /**
  37. * Coordinates for position adjustment patterns for each version.
  38. */
  39. private const POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = [
  40. [null, null, null, null, null, null, null], // Version 1
  41. [ 6, 18, null, null, null, null, null], // Version 2
  42. [ 6, 22, null, null, null, null, null], // Version 3
  43. [ 6, 26, null, null, null, null, null], // Version 4
  44. [ 6, 30, null, null, null, null, null], // Version 5
  45. [ 6, 34, null, null, null, null, null], // Version 6
  46. [ 6, 22, 38, null, null, null, null], // Version 7
  47. [ 6, 24, 42, null, null, null, null], // Version 8
  48. [ 6, 26, 46, null, null, null, null], // Version 9
  49. [ 6, 28, 50, null, null, null, null], // Version 10
  50. [ 6, 30, 54, null, null, null, null], // Version 11
  51. [ 6, 32, 58, null, null, null, null], // Version 12
  52. [ 6, 34, 62, null, null, null, null], // Version 13
  53. [ 6, 26, 46, 66, null, null, null], // Version 14
  54. [ 6, 26, 48, 70, null, null, null], // Version 15
  55. [ 6, 26, 50, 74, null, null, null], // Version 16
  56. [ 6, 30, 54, 78, null, null, null], // Version 17
  57. [ 6, 30, 56, 82, null, null, null], // Version 18
  58. [ 6, 30, 58, 86, null, null, null], // Version 19
  59. [ 6, 34, 62, 90, null, null, null], // Version 20
  60. [ 6, 28, 50, 72, 94, null, null], // Version 21
  61. [ 6, 26, 50, 74, 98, null, null], // Version 22
  62. [ 6, 30, 54, 78, 102, null, null], // Version 23
  63. [ 6, 28, 54, 80, 106, null, null], // Version 24
  64. [ 6, 32, 58, 84, 110, null, null], // Version 25
  65. [ 6, 30, 58, 86, 114, null, null], // Version 26
  66. [ 6, 34, 62, 90, 118, null, null], // Version 27
  67. [ 6, 26, 50, 74, 98, 122, null], // Version 28
  68. [ 6, 30, 54, 78, 102, 126, null], // Version 29
  69. [ 6, 26, 52, 78, 104, 130, null], // Version 30
  70. [ 6, 30, 56, 82, 108, 134, null], // Version 31
  71. [ 6, 34, 60, 86, 112, 138, null], // Version 32
  72. [ 6, 30, 58, 86, 114, 142, null], // Version 33
  73. [ 6, 34, 62, 90, 118, 146, null], // Version 34
  74. [ 6, 30, 54, 78, 102, 126, 150], // Version 35
  75. [ 6, 24, 50, 76, 102, 128, 154], // Version 36
  76. [ 6, 28, 54, 80, 106, 132, 158], // Version 37
  77. [ 6, 32, 58, 84, 110, 136, 162], // Version 38
  78. [ 6, 26, 54, 82, 110, 138, 166], // Version 39
  79. [ 6, 30, 58, 86, 114, 142, 170], // Version 40
  80. ];
  81. /**
  82. * Type information coordinates.
  83. */
  84. private const TYPE_INFO_COORDINATES = [
  85. [8, 0],
  86. [8, 1],
  87. [8, 2],
  88. [8, 3],
  89. [8, 4],
  90. [8, 5],
  91. [8, 7],
  92. [8, 8],
  93. [7, 8],
  94. [5, 8],
  95. [4, 8],
  96. [3, 8],
  97. [2, 8],
  98. [1, 8],
  99. [0, 8],
  100. ];
  101. /**
  102. * Version information polynomial.
  103. */
  104. private const VERSION_INFO_POLY = 0x1f25;
  105. /**
  106. * Type information polynomial.
  107. */
  108. private const TYPE_INFO_POLY = 0x537;
  109. /**
  110. * Type information mask pattern.
  111. */
  112. private const TYPE_INFO_MASK_PATTERN = 0x5412;
  113. /**
  114. * Clears a given matrix.
  115. */
  116. public static function clearMatrix(ByteMatrix $matrix) : void
  117. {
  118. $matrix->clear(-1);
  119. }
  120. /**
  121. * Builds a complete matrix.
  122. */
  123. public static function buildMatrix(
  124. BitArray $dataBits,
  125. ErrorCorrectionLevel $level,
  126. Version $version,
  127. int $maskPattern,
  128. ByteMatrix $matrix
  129. ) : void {
  130. self::clearMatrix($matrix);
  131. self::embedBasicPatterns($version, $matrix);
  132. self::embedTypeInfo($level, $maskPattern, $matrix);
  133. self::maybeEmbedVersionInfo($version, $matrix);
  134. self::embedDataBits($dataBits, $maskPattern, $matrix);
  135. }
  136. /**
  137. * Removes the position detection patterns from a matrix.
  138. *
  139. * This can be useful if you need to render those patterns separately.
  140. */
  141. public static function removePositionDetectionPatterns(ByteMatrix $matrix) : void
  142. {
  143. $pdpWidth = count(self::POSITION_DETECTION_PATTERN[0]);
  144. self::removePositionDetectionPattern(0, 0, $matrix);
  145. self::removePositionDetectionPattern($matrix->getWidth() - $pdpWidth, 0, $matrix);
  146. self::removePositionDetectionPattern(0, $matrix->getWidth() - $pdpWidth, $matrix);
  147. }
  148. /**
  149. * Embeds type information into a matrix.
  150. */
  151. private static function embedTypeInfo(ErrorCorrectionLevel $level, int $maskPattern, ByteMatrix $matrix) : void
  152. {
  153. $typeInfoBits = new BitArray();
  154. self::makeTypeInfoBits($level, $maskPattern, $typeInfoBits);
  155. $typeInfoBitsSize = $typeInfoBits->getSize();
  156. for ($i = 0; $i < $typeInfoBitsSize; ++$i) {
  157. $bit = $typeInfoBits->get($typeInfoBitsSize - 1 - $i);
  158. $x1 = self::TYPE_INFO_COORDINATES[$i][0];
  159. $y1 = self::TYPE_INFO_COORDINATES[$i][1];
  160. $matrix->set($x1, $y1, (int) $bit);
  161. if ($i < 8) {
  162. $x2 = $matrix->getWidth() - $i - 1;
  163. $y2 = 8;
  164. } else {
  165. $x2 = 8;
  166. $y2 = $matrix->getHeight() - 7 + ($i - 8);
  167. }
  168. $matrix->set($x2, $y2, (int) $bit);
  169. }
  170. }
  171. /**
  172. * Generates type information bits and appends them to a bit array.
  173. *
  174. * @throws RuntimeException if bit array resulted in invalid size
  175. */
  176. private static function makeTypeInfoBits(ErrorCorrectionLevel $level, int $maskPattern, BitArray $bits) : void
  177. {
  178. $typeInfo = ($level->getBits() << 3) | $maskPattern;
  179. $bits->appendBits($typeInfo, 5);
  180. $bchCode = self::calculateBchCode($typeInfo, self::TYPE_INFO_POLY);
  181. $bits->appendBits($bchCode, 10);
  182. $maskBits = new BitArray();
  183. $maskBits->appendBits(self::TYPE_INFO_MASK_PATTERN, 15);
  184. $bits->xorBits($maskBits);
  185. if (15 !== $bits->getSize()) {
  186. throw new RuntimeException('Bit array resulted in invalid size: ' . $bits->getSize());
  187. }
  188. }
  189. /**
  190. * Embeds version information if required.
  191. */
  192. private static function maybeEmbedVersionInfo(Version $version, ByteMatrix $matrix) : void
  193. {
  194. if ($version->getVersionNumber() < 7) {
  195. return;
  196. }
  197. $versionInfoBits = new BitArray();
  198. self::makeVersionInfoBits($version, $versionInfoBits);
  199. $bitIndex = 6 * 3 - 1;
  200. for ($i = 0; $i < 6; ++$i) {
  201. for ($j = 0; $j < 3; ++$j) {
  202. $bit = $versionInfoBits->get($bitIndex);
  203. --$bitIndex;
  204. $matrix->set($i, $matrix->getHeight() - 11 + $j, (int) $bit);
  205. $matrix->set($matrix->getHeight() - 11 + $j, $i, (int) $bit);
  206. }
  207. }
  208. }
  209. /**
  210. * Generates version information bits and appends them to a bit array.
  211. *
  212. * @throws RuntimeException if bit array resulted in invalid size
  213. */
  214. private static function makeVersionInfoBits(Version $version, BitArray $bits) : void
  215. {
  216. $bits->appendBits($version->getVersionNumber(), 6);
  217. $bchCode = self::calculateBchCode($version->getVersionNumber(), self::VERSION_INFO_POLY);
  218. $bits->appendBits($bchCode, 12);
  219. if (18 !== $bits->getSize()) {
  220. throw new RuntimeException('Bit array resulted in invalid size: ' . $bits->getSize());
  221. }
  222. }
  223. /**
  224. * Calculates the BCH code for a value and a polynomial.
  225. */
  226. private static function calculateBchCode(int $value, int $poly) : int
  227. {
  228. $msbSetInPoly = self::findMsbSet($poly);
  229. $value <<= $msbSetInPoly - 1;
  230. while (self::findMsbSet($value) >= $msbSetInPoly) {
  231. $value ^= $poly << (self::findMsbSet($value) - $msbSetInPoly);
  232. }
  233. return $value;
  234. }
  235. /**
  236. * Finds and MSB set.
  237. */
  238. private static function findMsbSet(int $value) : int
  239. {
  240. $numDigits = 0;
  241. while (0 !== $value) {
  242. $value >>= 1;
  243. ++$numDigits;
  244. }
  245. return $numDigits;
  246. }
  247. /**
  248. * Embeds basic patterns into a matrix.
  249. */
  250. private static function embedBasicPatterns(Version $version, ByteMatrix $matrix) : void
  251. {
  252. self::embedPositionDetectionPatternsAndSeparators($matrix);
  253. self::embedDarkDotAtLeftBottomCorner($matrix);
  254. self::maybeEmbedPositionAdjustmentPatterns($version, $matrix);
  255. self::embedTimingPatterns($matrix);
  256. }
  257. /**
  258. * Embeds position detection patterns and separators into a byte matrix.
  259. */
  260. private static function embedPositionDetectionPatternsAndSeparators(ByteMatrix $matrix) : void
  261. {
  262. $pdpWidth = count(self::POSITION_DETECTION_PATTERN[0]);
  263. self::embedPositionDetectionPattern(0, 0, $matrix);
  264. self::embedPositionDetectionPattern($matrix->getWidth() - $pdpWidth, 0, $matrix);
  265. self::embedPositionDetectionPattern(0, $matrix->getWidth() - $pdpWidth, $matrix);
  266. $hspWidth = 8;
  267. self::embedHorizontalSeparationPattern(0, $hspWidth - 1, $matrix);
  268. self::embedHorizontalSeparationPattern($matrix->getWidth() - $hspWidth, $hspWidth - 1, $matrix);
  269. self::embedHorizontalSeparationPattern(0, $matrix->getWidth() - $hspWidth, $matrix);
  270. $vspSize = 7;
  271. self::embedVerticalSeparationPattern($vspSize, 0, $matrix);
  272. self::embedVerticalSeparationPattern($matrix->getHeight() - $vspSize - 1, 0, $matrix);
  273. self::embedVerticalSeparationPattern($vspSize, $matrix->getHeight() - $vspSize, $matrix);
  274. }
  275. /**
  276. * Embeds a single position detection pattern into a byte matrix.
  277. */
  278. private static function embedPositionDetectionPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void
  279. {
  280. for ($y = 0; $y < 7; ++$y) {
  281. for ($x = 0; $x < 7; ++$x) {
  282. $matrix->set($xStart + $x, $yStart + $y, self::POSITION_DETECTION_PATTERN[$y][$x]);
  283. }
  284. }
  285. }
  286. private static function removePositionDetectionPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void
  287. {
  288. for ($y = 0; $y < 7; ++$y) {
  289. for ($x = 0; $x < 7; ++$x) {
  290. $matrix->set($xStart + $x, $yStart + $y, 0);
  291. }
  292. }
  293. }
  294. /**
  295. * Embeds a single horizontal separation pattern.
  296. *
  297. * @throws RuntimeException if a byte was already set
  298. */
  299. private static function embedHorizontalSeparationPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void
  300. {
  301. for ($x = 0; $x < 8; $x++) {
  302. if (-1 !== $matrix->get($xStart + $x, $yStart)) {
  303. throw new RuntimeException('Byte already set');
  304. }
  305. $matrix->set($xStart + $x, $yStart, 0);
  306. }
  307. }
  308. /**
  309. * Embeds a single vertical separation pattern.
  310. *
  311. * @throws RuntimeException if a byte was already set
  312. */
  313. private static function embedVerticalSeparationPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void
  314. {
  315. for ($y = 0; $y < 7; $y++) {
  316. if (-1 !== $matrix->get($xStart, $yStart + $y)) {
  317. throw new RuntimeException('Byte already set');
  318. }
  319. $matrix->set($xStart, $yStart + $y, 0);
  320. }
  321. }
  322. /**
  323. * Embeds a dot at the left bottom corner.
  324. *
  325. * @throws RuntimeException if a byte was already set to 0
  326. */
  327. private static function embedDarkDotAtLeftBottomCorner(ByteMatrix $matrix) : void
  328. {
  329. if (0 === $matrix->get(8, $matrix->getHeight() - 8)) {
  330. throw new RuntimeException('Byte already set to 0');
  331. }
  332. $matrix->set(8, $matrix->getHeight() - 8, 1);
  333. }
  334. /**
  335. * Embeds position adjustment patterns if required.
  336. */
  337. private static function maybeEmbedPositionAdjustmentPatterns(Version $version, ByteMatrix $matrix) : void
  338. {
  339. if ($version->getVersionNumber() < 2) {
  340. return;
  341. }
  342. $index = $version->getVersionNumber() - 1;
  343. $coordinates = self::POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[$index];
  344. $numCoordinates = count($coordinates);
  345. for ($i = 0; $i < $numCoordinates; ++$i) {
  346. for ($j = 0; $j < $numCoordinates; ++$j) {
  347. $y = $coordinates[$i];
  348. $x = $coordinates[$j];
  349. if (null === $x || null === $y) {
  350. continue;
  351. }
  352. if (-1 === $matrix->get($x, $y)) {
  353. self::embedPositionAdjustmentPattern($x - 2, $y - 2, $matrix);
  354. }
  355. }
  356. }
  357. }
  358. /**
  359. * Embeds a single position adjustment pattern.
  360. */
  361. private static function embedPositionAdjustmentPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void
  362. {
  363. for ($y = 0; $y < 5; $y++) {
  364. for ($x = 0; $x < 5; $x++) {
  365. $matrix->set($xStart + $x, $yStart + $y, self::POSITION_ADJUSTMENT_PATTERN[$y][$x]);
  366. }
  367. }
  368. }
  369. /**
  370. * Embeds timing patterns into a matrix.
  371. */
  372. private static function embedTimingPatterns(ByteMatrix $matrix) : void
  373. {
  374. $matrixWidth = $matrix->getWidth();
  375. for ($i = 8; $i < $matrixWidth - 8; ++$i) {
  376. $bit = ($i + 1) % 2;
  377. if (-1 === $matrix->get($i, 6)) {
  378. $matrix->set($i, 6, $bit);
  379. }
  380. if (-1 === $matrix->get(6, $i)) {
  381. $matrix->set(6, $i, $bit);
  382. }
  383. }
  384. }
  385. /**
  386. * Embeds "dataBits" using "getMaskPattern".
  387. *
  388. * For debugging purposes, it skips masking process if "getMaskPattern" is -1. See 8.7 of JISX0510:2004 (p.38) for
  389. * how to embed data bits.
  390. *
  391. * @throws WriterException if not all bits could be consumed
  392. */
  393. private static function embedDataBits(BitArray $dataBits, int $maskPattern, ByteMatrix $matrix) : void
  394. {
  395. $bitIndex = 0;
  396. $direction = -1;
  397. // Start from the right bottom cell.
  398. $x = $matrix->getWidth() - 1;
  399. $y = $matrix->getHeight() - 1;
  400. while ($x > 0) {
  401. // Skip vertical timing pattern.
  402. if (6 === $x) {
  403. --$x;
  404. }
  405. while ($y >= 0 && $y < $matrix->getHeight()) {
  406. for ($i = 0; $i < 2; $i++) {
  407. $xx = $x - $i;
  408. // Skip the cell if it's not empty.
  409. if (-1 !== $matrix->get($xx, $y)) {
  410. continue;
  411. }
  412. if ($bitIndex < $dataBits->getSize()) {
  413. $bit = $dataBits->get($bitIndex);
  414. ++$bitIndex;
  415. } else {
  416. // Padding bit. If there is no bit left, we'll fill the
  417. // left cells with 0, as described in 8.4.9 of
  418. // JISX0510:2004 (p. 24).
  419. $bit = false;
  420. }
  421. // Skip masking if maskPattern is -1.
  422. if (-1 !== $maskPattern && MaskUtil::getDataMaskBit($maskPattern, $xx, $y)) {
  423. $bit = ! $bit;
  424. }
  425. $matrix->set($xx, $y, (int) $bit);
  426. }
  427. $y += $direction;
  428. }
  429. $direction = -$direction;
  430. $y += $direction;
  431. $x -= 2;
  432. }
  433. // All bits should be consumed
  434. if ($dataBits->getSize() !== $bitIndex) {
  435. throw new WriterException('Not all bits consumed (' . $bitIndex . ' out of ' . $dataBits->getSize() .')');
  436. }
  437. }
  438. }