xref: /third_party/qrcodegen/cpp/qrcodegen.cpp (revision 5317bbaf)
1/*
2 * QR Code generator library (C++)
3 *
4 * Copyright (c) Project Nayuki. (MIT License)
5 * https://www.nayuki.io/page/qr-code-generator-library
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy of
8 * this software and associated documentation files (the "Software"), to deal in
9 * the Software without restriction, including without limitation the rights to
10 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11 * the Software, and to permit persons to whom the Software is furnished to do so,
12 * subject to the following conditions:
13 * - The above copyright notice and this permission notice shall be included in
14 *   all copies or substantial portions of the Software.
15 * - The Software is provided "as is", without warranty of any kind, express or
16 *   implied, including but not limited to the warranties of merchantability,
17 *   fitness for a particular purpose and noninfringement. In no event shall the
18 *   authors or copyright holders be liable for any claim, damages or other
19 *   liability, whether in an action of contract, tort or otherwise, arising from,
20 *   out of or in connection with the Software or the use or other dealings in the
21 *   Software.
22 */
23
24#include <algorithm>
25#include <cassert>
26#include <climits>
27#include <cstddef>
28#include <cstdlib>
29#include <cstring>
30#include <sstream>
31#include <utility>
32#include "qrcodegen.hpp"
33
34using std::int8_t;
35using std::uint8_t;
36using std::size_t;
37using std::vector;
38
39
40namespace qrcodegen {
41
42/*---- Class QrSegment ----*/
43
44QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) :
45		modeBits(mode) {
46	numBitsCharCount[0] = cc0;
47	numBitsCharCount[1] = cc1;
48	numBitsCharCount[2] = cc2;
49}
50
51
52int QrSegment::Mode::getModeBits() const {
53	return modeBits;
54}
55
56
57int QrSegment::Mode::numCharCountBits(int ver) const {
58	return numBitsCharCount[(ver + 7) / 17];
59}
60
61
62const QrSegment::Mode QrSegment::Mode::NUMERIC     (0x1, 10, 12, 14);
63const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2,  9, 11, 13);
64const QrSegment::Mode QrSegment::Mode::BYTE        (0x4,  8, 16, 16);
65const QrSegment::Mode QrSegment::Mode::KANJI       (0x8,  8, 10, 12);
66const QrSegment::Mode QrSegment::Mode::ECI         (0x7,  0,  0,  0);
67
68
69QrSegment QrSegment::makeBytes(const vector<uint8_t> &data) {
70	if (data.size() > static_cast<unsigned int>(INT_MAX))
71		throw std::length_error("Data too long");
72	BitBuffer bb;
73	for (uint8_t b : data)
74		bb.appendBits(b, 8);
75	return QrSegment(Mode::BYTE, static_cast<int>(data.size()), std::move(bb));
76}
77
78
79QrSegment QrSegment::makeNumeric(const char *digits) {
80	BitBuffer bb;
81	int accumData = 0;
82	int accumCount = 0;
83	int charCount = 0;
84	for (; *digits != '\0'; digits++, charCount++) {
85		char c = *digits;
86		if (c < '0' || c > '9')
87			throw std::domain_error("String contains non-numeric characters");
88		accumData = accumData * 10 + (c - '0');
89		accumCount++;
90		if (accumCount == 3) {
91			bb.appendBits(static_cast<uint32_t>(accumData), 10);
92			accumData = 0;
93			accumCount = 0;
94		}
95	}
96	if (accumCount > 0)  // 1 or 2 digits remaining
97		bb.appendBits(static_cast<uint32_t>(accumData), accumCount * 3 + 1);
98	return QrSegment(Mode::NUMERIC, charCount, std::move(bb));
99}
100
101
102QrSegment QrSegment::makeAlphanumeric(const char *text) {
103	BitBuffer bb;
104	int accumData = 0;
105	int accumCount = 0;
106	int charCount = 0;
107	for (; *text != '\0'; text++, charCount++) {
108		const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text);
109		if (temp == nullptr)
110			throw std::domain_error("String contains unencodable characters in alphanumeric mode");
111		accumData = accumData * 45 + static_cast<int>(temp - ALPHANUMERIC_CHARSET);
112		accumCount++;
113		if (accumCount == 2) {
114			bb.appendBits(static_cast<uint32_t>(accumData), 11);
115			accumData = 0;
116			accumCount = 0;
117		}
118	}
119	if (accumCount > 0)  // 1 character remaining
120		bb.appendBits(static_cast<uint32_t>(accumData), 6);
121	return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb));
122}
123
124
125vector<QrSegment> QrSegment::makeSegments(const char *text) {
126	// Select the most efficient segment encoding automatically
127	vector<QrSegment> result;
128	if (*text == '\0');  // Leave result empty
129	else if (isNumeric(text))
130		result.push_back(makeNumeric(text));
131	else if (isAlphanumeric(text))
132		result.push_back(makeAlphanumeric(text));
133	else {
134		vector<uint8_t> bytes;
135		for (; *text != '\0'; text++)
136			bytes.push_back(static_cast<uint8_t>(*text));
137		result.push_back(makeBytes(bytes));
138	}
139	return result;
140}
141
142
143QrSegment QrSegment::makeEci(long assignVal) {
144	BitBuffer bb;
145	if (assignVal < 0)
146		throw std::domain_error("ECI assignment value out of range");
147	else if (assignVal < (1 << 7))
148		bb.appendBits(static_cast<uint32_t>(assignVal), 8);
149	else if (assignVal < (1 << 14)) {
150		bb.appendBits(2, 2);
151		bb.appendBits(static_cast<uint32_t>(assignVal), 14);
152	} else if (assignVal < 1000000L) {
153		bb.appendBits(6, 3);
154		bb.appendBits(static_cast<uint32_t>(assignVal), 21);
155	} else
156		throw std::domain_error("ECI assignment value out of range");
157	return QrSegment(Mode::ECI, 0, std::move(bb));
158}
159
160
161QrSegment::QrSegment(const Mode &md, int numCh, const std::vector<bool> &dt) :
162		mode(&md),
163		numChars(numCh),
164		data(dt) {
165	if (numCh < 0)
166		throw std::domain_error("Invalid value");
167}
168
169
170QrSegment::QrSegment(const Mode &md, int numCh, std::vector<bool> &&dt) :
171		mode(&md),
172		numChars(numCh),
173		data(std::move(dt)) {
174	if (numCh < 0)
175		throw std::domain_error("Invalid value");
176}
177
178
179int QrSegment::getTotalBits(const vector<QrSegment> &segs, int version) {
180	int result = 0;
181	for (const QrSegment &seg : segs) {
182		int ccbits = seg.mode->numCharCountBits(version);
183		if (seg.numChars >= (1L << ccbits))
184			return -1;  // The segment's length doesn't fit the field's bit width
185		if (4 + ccbits > INT_MAX - result)
186			return -1;  // The sum will overflow an int type
187		result += 4 + ccbits;
188		if (seg.data.size() > static_cast<unsigned int>(INT_MAX - result))
189			return -1;  // The sum will overflow an int type
190		result += static_cast<int>(seg.data.size());
191	}
192	return result;
193}
194
195
196bool QrSegment::isNumeric(const char *text) {
197	for (; *text != '\0'; text++) {
198		char c = *text;
199		if (c < '0' || c > '9')
200			return false;
201	}
202	return true;
203}
204
205
206bool QrSegment::isAlphanumeric(const char *text) {
207	for (; *text != '\0'; text++) {
208		if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr)
209			return false;
210	}
211	return true;
212}
213
214
215const QrSegment::Mode &QrSegment::getMode() const {
216	return *mode;
217}
218
219
220int QrSegment::getNumChars() const {
221	return numChars;
222}
223
224
225const std::vector<bool> &QrSegment::getData() const {
226	return data;
227}
228
229
230const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
231
232
233
234/*---- Class QrCode ----*/
235
236int QrCode::getFormatBits(Ecc ecl) {
237	switch (ecl) {
238		case Ecc::LOW     :  return 1;
239		case Ecc::MEDIUM  :  return 0;
240		case Ecc::QUARTILE:  return 3;
241		case Ecc::HIGH    :  return 2;
242		default:  throw std::logic_error("Unreachable");
243	}
244}
245
246
247QrCode QrCode::encodeText(const char *text, Ecc ecl) {
248	vector<QrSegment> segs = QrSegment::makeSegments(text);
249	return encodeSegments(segs, ecl);
250}
251
252
253QrCode QrCode::encodeBinary(const vector<uint8_t> &data, Ecc ecl) {
254	vector<QrSegment> segs{QrSegment::makeBytes(data)};
255	return encodeSegments(segs, ecl);
256}
257
258
259QrCode QrCode::encodeSegments(const vector<QrSegment> &segs, Ecc ecl,
260		int minVersion, int maxVersion, int mask, bool boostEcl) {
261	if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7)
262		throw std::invalid_argument("Invalid value");
263
264	// Find the minimal version number to use
265	int version, dataUsedBits;
266	for (version = minVersion; ; version++) {
267		int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;  // Number of data bits available
268		dataUsedBits = QrSegment::getTotalBits(segs, version);
269		if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
270			break;  // This version number is found to be suitable
271		if (version >= maxVersion) {  // All versions in the range could not fit the given data
272			std::ostringstream sb;
273			if (dataUsedBits == -1)
274				sb << "Segment too long";
275			else {
276				sb << "Data length = " << dataUsedBits << " bits, ";
277				sb << "Max capacity = " << dataCapacityBits << " bits";
278			}
279			throw data_too_long(sb.str());
280		}
281	}
282	assert(dataUsedBits != -1);
283
284	// Increase the error correction level while the data still fits in the current version number
285	for (Ecc newEcl : {Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) {  // From low to high
286		if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8)
287			ecl = newEcl;
288	}
289
290	// Concatenate all segments to create the data bit string
291	BitBuffer bb;
292	for (const QrSegment &seg : segs) {
293		bb.appendBits(static_cast<uint32_t>(seg.getMode().getModeBits()), 4);
294		bb.appendBits(static_cast<uint32_t>(seg.getNumChars()), seg.getMode().numCharCountBits(version));
295		bb.insert(bb.end(), seg.getData().begin(), seg.getData().end());
296	}
297	assert(bb.size() == static_cast<unsigned int>(dataUsedBits));
298
299	// Add terminator and pad up to a byte if applicable
300	size_t dataCapacityBits = static_cast<size_t>(getNumDataCodewords(version, ecl)) * 8;
301	assert(bb.size() <= dataCapacityBits);
302	bb.appendBits(0, std::min(4, static_cast<int>(dataCapacityBits - bb.size())));
303	bb.appendBits(0, (8 - static_cast<int>(bb.size() % 8)) % 8);
304	assert(bb.size() % 8 == 0);
305
306	// Pad with alternating bytes until data capacity is reached
307	for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
308		bb.appendBits(padByte, 8);
309
310	// Pack bits into bytes in big endian
311	vector<uint8_t> dataCodewords(bb.size() / 8);
312	for (size_t i = 0; i < bb.size(); i++)
313		dataCodewords.at(i >> 3) |= (bb.at(i) ? 1 : 0) << (7 - (i & 7));
314
315	// Create the QR Code object
316	return QrCode(version, ecl, dataCodewords, mask);
317}
318
319
320QrCode::QrCode(int ver, Ecc ecl, const vector<uint8_t> &dataCodewords, int msk) :
321		// Initialize fields and check arguments
322		version(ver),
323		errorCorrectionLevel(ecl) {
324	if (ver < MIN_VERSION || ver > MAX_VERSION)
325		throw std::domain_error("Version value out of range");
326	if (msk < -1 || msk > 7)
327		throw std::domain_error("Mask value out of range");
328	size = ver * 4 + 17;
329	size_t sz = static_cast<size_t>(size);
330	modules    = vector<vector<bool> >(sz, vector<bool>(sz));  // Initially all light
331	isFunction = vector<vector<bool> >(sz, vector<bool>(sz));
332
333	// Compute ECC, draw modules
334	drawFunctionPatterns();
335	const vector<uint8_t> allCodewords = addEccAndInterleave(dataCodewords);
336	drawCodewords(allCodewords);
337
338	// Do masking
339	if (msk == -1) {  // Automatically choose best mask
340		long minPenalty = LONG_MAX;
341		for (int i = 0; i < 8; i++) {
342			applyMask(i);
343			drawFormatBits(i);
344			long penalty = getPenaltyScore();
345			if (penalty < minPenalty) {
346				msk = i;
347				minPenalty = penalty;
348			}
349			applyMask(i);  // Undoes the mask due to XOR
350		}
351	}
352	assert(0 <= msk && msk <= 7);
353	mask = msk;
354	applyMask(msk);  // Apply the final choice of mask
355	drawFormatBits(msk);  // Overwrite old format bits
356
357	isFunction.clear();
358	isFunction.shrink_to_fit();
359}
360
361
362int QrCode::getVersion() const {
363	return version;
364}
365
366
367int QrCode::getSize() const {
368	return size;
369}
370
371
372QrCode::Ecc QrCode::getErrorCorrectionLevel() const {
373	return errorCorrectionLevel;
374}
375
376
377int QrCode::getMask() const {
378	return mask;
379}
380
381
382bool QrCode::getModule(int x, int y) const {
383	return 0 <= x && x < size && 0 <= y && y < size && module(x, y);
384}
385
386
387void QrCode::drawFunctionPatterns() {
388	// Draw horizontal and vertical timing patterns
389	for (int i = 0; i < size; i++) {
390		setFunctionModule(6, i, i % 2 == 0);
391		setFunctionModule(i, 6, i % 2 == 0);
392	}
393
394	// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
395	drawFinderPattern(3, 3);
396	drawFinderPattern(size - 4, 3);
397	drawFinderPattern(3, size - 4);
398
399	// Draw numerous alignment patterns
400	const vector<int> alignPatPos = getAlignmentPatternPositions();
401	size_t numAlign = alignPatPos.size();
402	for (size_t i = 0; i < numAlign; i++) {
403		for (size_t j = 0; j < numAlign; j++) {
404			// Don't draw on the three finder corners
405			if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
406				drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j));
407		}
408	}
409
410	// Draw configuration data
411	drawFormatBits(0);  // Dummy mask value; overwritten later in the constructor
412	drawVersion();
413}
414
415
416void QrCode::drawFormatBits(int msk) {
417	// Calculate error correction code and pack bits
418	int data = getFormatBits(errorCorrectionLevel) << 3 | msk;  // errCorrLvl is uint2, msk is uint3
419	int rem = data;
420	for (int i = 0; i < 10; i++)
421		rem = (rem << 1) ^ ((rem >> 9) * 0x537);
422	int bits = (data << 10 | rem) ^ 0x5412;  // uint15
423	assert(bits >> 15 == 0);
424
425	// Draw first copy
426	for (int i = 0; i <= 5; i++)
427		setFunctionModule(8, i, getBit(bits, i));
428	setFunctionModule(8, 7, getBit(bits, 6));
429	setFunctionModule(8, 8, getBit(bits, 7));
430	setFunctionModule(7, 8, getBit(bits, 8));
431	for (int i = 9; i < 15; i++)
432		setFunctionModule(14 - i, 8, getBit(bits, i));
433
434	// Draw second copy
435	for (int i = 0; i < 8; i++)
436		setFunctionModule(size - 1 - i, 8, getBit(bits, i));
437	for (int i = 8; i < 15; i++)
438		setFunctionModule(8, size - 15 + i, getBit(bits, i));
439	setFunctionModule(8, size - 8, true);  // Always dark
440}
441
442
443void QrCode::drawVersion() {
444	if (version < 7)
445		return;
446
447	// Calculate error correction code and pack bits
448	int rem = version;  // version is uint6, in the range [7, 40]
449	for (int i = 0; i < 12; i++)
450		rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
451	long bits = static_cast<long>(version) << 12 | rem;  // uint18
452	assert(bits >> 18 == 0);
453
454	// Draw two copies
455	for (int i = 0; i < 18; i++) {
456		bool bit = getBit(bits, i);
457		int a = size - 11 + i % 3;
458		int b = i / 3;
459		setFunctionModule(a, b, bit);
460		setFunctionModule(b, a, bit);
461	}
462}
463
464
465void QrCode::drawFinderPattern(int x, int y) {
466	for (int dy = -4; dy <= 4; dy++) {
467		for (int dx = -4; dx <= 4; dx++) {
468			int dist = std::max(std::abs(dx), std::abs(dy));  // Chebyshev/infinity norm
469			int xx = x + dx, yy = y + dy;
470			if (0 <= xx && xx < size && 0 <= yy && yy < size)
471				setFunctionModule(xx, yy, dist != 2 && dist != 4);
472		}
473	}
474}
475
476
477void QrCode::drawAlignmentPattern(int x, int y) {
478	for (int dy = -2; dy <= 2; dy++) {
479		for (int dx = -2; dx <= 2; dx++)
480			setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1);
481	}
482}
483
484
485void QrCode::setFunctionModule(int x, int y, bool isDark) {
486	size_t ux = static_cast<size_t>(x);
487	size_t uy = static_cast<size_t>(y);
488	modules   .at(uy).at(ux) = isDark;
489	isFunction.at(uy).at(ux) = true;
490}
491
492
493bool QrCode::module(int x, int y) const {
494	return modules.at(static_cast<size_t>(y)).at(static_cast<size_t>(x));
495}
496
497
498vector<uint8_t> QrCode::addEccAndInterleave(const vector<uint8_t> &data) const {
499	if (data.size() != static_cast<unsigned int>(getNumDataCodewords(version, errorCorrectionLevel)))
500		throw std::invalid_argument("Invalid argument");
501
502	// Calculate parameter numbers
503	int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(errorCorrectionLevel)][version];
504	int blockEccLen = ECC_CODEWORDS_PER_BLOCK  [static_cast<int>(errorCorrectionLevel)][version];
505	int rawCodewords = getNumRawDataModules(version) / 8;
506	int numShortBlocks = numBlocks - rawCodewords % numBlocks;
507	int shortBlockLen = rawCodewords / numBlocks;
508
509	// Split data into blocks and append ECC to each block
510	vector<vector<uint8_t> > blocks;
511	const vector<uint8_t> rsDiv = reedSolomonComputeDivisor(blockEccLen);
512	for (int i = 0, k = 0; i < numBlocks; i++) {
513		vector<uint8_t> dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)));
514		k += static_cast<int>(dat.size());
515		const vector<uint8_t> ecc = reedSolomonComputeRemainder(dat, rsDiv);
516		if (i < numShortBlocks)
517			dat.push_back(0);
518		dat.insert(dat.end(), ecc.cbegin(), ecc.cend());
519		blocks.push_back(std::move(dat));
520	}
521
522	// Interleave (not concatenate) the bytes from every block into a single sequence
523	vector<uint8_t> result;
524	for (size_t i = 0; i < blocks.at(0).size(); i++) {
525		for (size_t j = 0; j < blocks.size(); j++) {
526			// Skip the padding byte in short blocks
527			if (i != static_cast<unsigned int>(shortBlockLen - blockEccLen) || j >= static_cast<unsigned int>(numShortBlocks))
528				result.push_back(blocks.at(j).at(i));
529		}
530	}
531	assert(result.size() == static_cast<unsigned int>(rawCodewords));
532	return result;
533}
534
535
536void QrCode::drawCodewords(const vector<uint8_t> &data) {
537	if (data.size() != static_cast<unsigned int>(getNumRawDataModules(version) / 8))
538		throw std::invalid_argument("Invalid argument");
539
540	size_t i = 0;  // Bit index into the data
541	// Do the funny zigzag scan
542	for (int right = size - 1; right >= 1; right -= 2) {  // Index of right column in each column pair
543		if (right == 6)
544			right = 5;
545		for (int vert = 0; vert < size; vert++) {  // Vertical counter
546			for (int j = 0; j < 2; j++) {
547				size_t x = static_cast<size_t>(right - j);  // Actual x coordinate
548				bool upward = ((right + 1) & 2) == 0;
549				size_t y = static_cast<size_t>(upward ? size - 1 - vert : vert);  // Actual y coordinate
550				if (!isFunction.at(y).at(x) && i < data.size() * 8) {
551					modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast<int>(i & 7));
552					i++;
553				}
554				// If this QR Code has any remainder bits (0 to 7), they were assigned as
555				// 0/false/light by the constructor and are left unchanged by this method
556			}
557		}
558	}
559	assert(i == data.size() * 8);
560}
561
562
563void QrCode::applyMask(int msk) {
564	if (msk < 0 || msk > 7)
565		throw std::domain_error("Mask value out of range");
566	size_t sz = static_cast<size_t>(size);
567	for (size_t y = 0; y < sz; y++) {
568		for (size_t x = 0; x < sz; x++) {
569			bool invert;
570			switch (msk) {
571				case 0:  invert = (x + y) % 2 == 0;                    break;
572				case 1:  invert = y % 2 == 0;                          break;
573				case 2:  invert = x % 3 == 0;                          break;
574				case 3:  invert = (x + y) % 3 == 0;                    break;
575				case 4:  invert = (x / 3 + y / 2) % 2 == 0;            break;
576				case 5:  invert = x * y % 2 + x * y % 3 == 0;          break;
577				case 6:  invert = (x * y % 2 + x * y % 3) % 2 == 0;    break;
578				case 7:  invert = ((x + y) % 2 + x * y % 3) % 2 == 0;  break;
579				default:  throw std::logic_error("Unreachable");
580			}
581			modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x));
582		}
583	}
584}
585
586
587long QrCode::getPenaltyScore() const {
588	long result = 0;
589
590	// Adjacent modules in row having same color, and finder-like patterns
591	for (int y = 0; y < size; y++) {
592		bool runColor = false;
593		int runX = 0;
594		std::array<int,7> runHistory = {};
595		for (int x = 0; x < size; x++) {
596			if (module(x, y) == runColor) {
597				runX++;
598				if (runX == 5)
599					result += PENALTY_N1;
600				else if (runX > 5)
601					result++;
602			} else {
603				finderPenaltyAddHistory(runX, runHistory);
604				if (!runColor)
605					result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
606				runColor = module(x, y);
607				runX = 1;
608			}
609		}
610		result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3;
611	}
612	// Adjacent modules in column having same color, and finder-like patterns
613	for (int x = 0; x < size; x++) {
614		bool runColor = false;
615		int runY = 0;
616		std::array<int,7> runHistory = {};
617		for (int y = 0; y < size; y++) {
618			if (module(x, y) == runColor) {
619				runY++;
620				if (runY == 5)
621					result += PENALTY_N1;
622				else if (runY > 5)
623					result++;
624			} else {
625				finderPenaltyAddHistory(runY, runHistory);
626				if (!runColor)
627					result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
628				runColor = module(x, y);
629				runY = 1;
630			}
631		}
632		result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3;
633	}
634
635	// 2*2 blocks of modules having same color
636	for (int y = 0; y < size - 1; y++) {
637		for (int x = 0; x < size - 1; x++) {
638			bool  color = module(x, y);
639			if (  color == module(x + 1, y) &&
640			      color == module(x, y + 1) &&
641			      color == module(x + 1, y + 1))
642				result += PENALTY_N2;
643		}
644	}
645
646	// Balance of dark and light modules
647	int dark = 0;
648	for (const vector<bool> &row : modules) {
649		for (bool color : row) {
650			if (color)
651				dark++;
652		}
653	}
654	int total = size * size;  // Note that size is odd, so dark/total != 1/2
655	// Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
656	int k = static_cast<int>((std::abs(dark * 20L - total * 10L) + total - 1) / total) - 1;
657	assert(0 <= k && k <= 9);
658	result += k * PENALTY_N4;
659	assert(0 <= result && result <= 2568888L);  // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
660	return result;
661}
662
663
664vector<int> QrCode::getAlignmentPatternPositions() const {
665	if (version == 1)
666		return vector<int>();
667	else {
668		int numAlign = version / 7 + 2;
669		int step = (version == 32) ? 26 :
670			(version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2;
671		vector<int> result;
672		for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step)
673			result.insert(result.begin(), pos);
674		result.insert(result.begin(), 6);
675		return result;
676	}
677}
678
679
680int QrCode::getNumRawDataModules(int ver) {
681	if (ver < MIN_VERSION || ver > MAX_VERSION)
682		throw std::domain_error("Version number out of range");
683	int result = (16 * ver + 128) * ver + 64;
684	if (ver >= 2) {
685		int numAlign = ver / 7 + 2;
686		result -= (25 * numAlign - 10) * numAlign - 55;
687		if (ver >= 7)
688			result -= 36;
689	}
690	assert(208 <= result && result <= 29648);
691	return result;
692}
693
694
695int QrCode::getNumDataCodewords(int ver, Ecc ecl) {
696	return getNumRawDataModules(ver) / 8
697		- ECC_CODEWORDS_PER_BLOCK    [static_cast<int>(ecl)][ver]
698		* NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(ecl)][ver];
699}
700
701
702vector<uint8_t> QrCode::reedSolomonComputeDivisor(int degree) {
703	if (degree < 1 || degree > 255)
704		throw std::domain_error("Degree out of range");
705	// Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
706	// For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
707	vector<uint8_t> result(static_cast<size_t>(degree));
708	result.at(result.size() - 1) = 1;  // Start off with the monomial x^0
709
710	// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
711	// and drop the highest monomial term which is always 1x^degree.
712	// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
713	uint8_t root = 1;
714	for (int i = 0; i < degree; i++) {
715		// Multiply the current product by (x - r^i)
716		for (size_t j = 0; j < result.size(); j++) {
717			result.at(j) = reedSolomonMultiply(result.at(j), root);
718			if (j + 1 < result.size())
719				result.at(j) ^= result.at(j + 1);
720		}
721		root = reedSolomonMultiply(root, 0x02);
722	}
723	return result;
724}
725
726
727vector<uint8_t> QrCode::reedSolomonComputeRemainder(const vector<uint8_t> &data, const vector<uint8_t> &divisor) {
728	vector<uint8_t> result(divisor.size());
729	for (uint8_t b : data) {  // Polynomial division
730		uint8_t factor = b ^ result.at(0);
731		result.erase(result.begin());
732		result.push_back(0);
733		for (size_t i = 0; i < result.size(); i++)
734			result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor);
735	}
736	return result;
737}
738
739
740uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) {
741	// Russian peasant multiplication
742	int z = 0;
743	for (int i = 7; i >= 0; i--) {
744		z = (z << 1) ^ ((z >> 7) * 0x11D);
745		z ^= ((y >> i) & 1) * x;
746	}
747	assert(z >> 8 == 0);
748	return static_cast<uint8_t>(z);
749}
750
751
752int QrCode::finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const {
753	int n = runHistory.at(1);
754	assert(n <= size * 3);
755	bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n;
756	return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0)
757	     + (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0);
758}
759
760
761int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const {
762	if (currentRunColor) {  // Terminate dark run
763		finderPenaltyAddHistory(currentRunLength, runHistory);
764		currentRunLength = 0;
765	}
766	currentRunLength += size;  // Add light border to final run
767	finderPenaltyAddHistory(currentRunLength, runHistory);
768	return finderPenaltyCountPatterns(runHistory);
769}
770
771
772void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const {
773	if (runHistory.at(0) == 0)
774		currentRunLength += size;  // Add light border to initial run
775	std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end());
776	runHistory.at(0) = currentRunLength;
777}
778
779
780bool QrCode::getBit(long x, int i) {
781	return ((x >> i) & 1) != 0;
782}
783
784
785/*---- Tables of constants ----*/
786
787const int QrCode::PENALTY_N1 =  3;
788const int QrCode::PENALTY_N2 =  3;
789const int QrCode::PENALTY_N3 = 40;
790const int QrCode::PENALTY_N4 = 10;
791
792
793const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = {
794	// Version: (note that index 0 is for padding, and is set to an illegal value)
795	//0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level
796	{-1,  7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30},  // Low
797	{-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28},  // Medium
798	{-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30},  // Quartile
799	{-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30},  // High
800};
801
802const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = {
803	// Version: (note that index 0 is for padding, and is set to an illegal value)
804	//0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level
805	{-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4,  4,  4,  4,  4,  6,  6,  6,  6,  7,  8,  8,  9,  9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25},  // Low
806	{-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5,  5,  8,  9,  9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49},  // Medium
807	{-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8,  8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68},  // Quartile
808	{-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81},  // High
809};
810
811
812data_too_long::data_too_long(const std::string &msg) :
813	std::length_error(msg) {}
814
815
816
817/*---- Class BitBuffer ----*/
818
819BitBuffer::BitBuffer()
820	: std::vector<bool>() {}
821
822
823void BitBuffer::appendBits(std::uint32_t val, int len) {
824	if (len < 0 || len > 31 || val >> len != 0)
825		throw std::domain_error("Value out of range");
826	for (int i = len - 1; i >= 0; i--)  // Append bit by bit
827		this->push_back(((val >> i) & 1) != 0);
828}
829
830}
831