Skip to main content

rxing/qrcode/encoder/
matrix_util.rs

1/*
2 * Copyright 2008 ZXing authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use crate::{
18    Exceptions,
19    common::{BitArray, BitFieldBaseType, Result},
20    qrcode::decoder::{ErrorCorrectionLevel, Version},
21};
22
23use super::{ByteMatrix, QRCode, mask_util};
24
25/*
26 * @author satorux@google.com (Satoru Takabayashi) - creator
27 * @author dswitkin@google.com (Daniel Switkin) - ported from C++
28 */
29
30const POSITION_DETECTION_PATTERN: [[u8; 7]; 7] = [
31    [1, 1, 1, 1, 1, 1, 1],
32    [1, 0, 0, 0, 0, 0, 1],
33    [1, 0, 1, 1, 1, 0, 1],
34    [1, 0, 1, 1, 1, 0, 1],
35    [1, 0, 1, 1, 1, 0, 1],
36    [1, 0, 0, 0, 0, 0, 1],
37    [1, 1, 1, 1, 1, 1, 1],
38];
39
40const POSITION_ADJUSTMENT_PATTERN: [[u8; 5]; 5] = [
41    [1, 1, 1, 1, 1],
42    [1, 0, 0, 0, 1],
43    [1, 0, 1, 0, 1],
44    [1, 0, 0, 0, 1],
45    [1, 1, 1, 1, 1],
46];
47
48// From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu.
49const POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE: [[i16; 7]; 40] = [
50    [-1, -1, -1, -1, -1, -1, -1],   // Version 1
51    [6, 18, -1, -1, -1, -1, -1],    // Version 2
52    [6, 22, -1, -1, -1, -1, -1],    // Version 3
53    [6, 26, -1, -1, -1, -1, -1],    // Version 4
54    [6, 30, -1, -1, -1, -1, -1],    // Version 5
55    [6, 34, -1, -1, -1, -1, -1],    // Version 6
56    [6, 22, 38, -1, -1, -1, -1],    // Version 7
57    [6, 24, 42, -1, -1, -1, -1],    // Version 8
58    [6, 26, 46, -1, -1, -1, -1],    // Version 9
59    [6, 28, 50, -1, -1, -1, -1],    // Version 10
60    [6, 30, 54, -1, -1, -1, -1],    // Version 11
61    [6, 32, 58, -1, -1, -1, -1],    // Version 12
62    [6, 34, 62, -1, -1, -1, -1],    // Version 13
63    [6, 26, 46, 66, -1, -1, -1],    // Version 14
64    [6, 26, 48, 70, -1, -1, -1],    // Version 15
65    [6, 26, 50, 74, -1, -1, -1],    // Version 16
66    [6, 30, 54, 78, -1, -1, -1],    // Version 17
67    [6, 30, 56, 82, -1, -1, -1],    // Version 18
68    [6, 30, 58, 86, -1, -1, -1],    // Version 19
69    [6, 34, 62, 90, -1, -1, -1],    // Version 20
70    [6, 28, 50, 72, 94, -1, -1],    // Version 21
71    [6, 26, 50, 74, 98, -1, -1],    // Version 22
72    [6, 30, 54, 78, 102, -1, -1],   // Version 23
73    [6, 28, 54, 80, 106, -1, -1],   // Version 24
74    [6, 32, 58, 84, 110, -1, -1],   // Version 25
75    [6, 30, 58, 86, 114, -1, -1],   // Version 26
76    [6, 34, 62, 90, 118, -1, -1],   // Version 27
77    [6, 26, 50, 74, 98, 122, -1],   // Version 28
78    [6, 30, 54, 78, 102, 126, -1],  // Version 29
79    [6, 26, 52, 78, 104, 130, -1],  // Version 30
80    [6, 30, 56, 82, 108, 134, -1],  // Version 31
81    [6, 34, 60, 86, 112, 138, -1],  // Version 32
82    [6, 30, 58, 86, 114, 142, -1],  // Version 33
83    [6, 34, 62, 90, 118, 146, -1],  // Version 34
84    [6, 30, 54, 78, 102, 126, 150], // Version 35
85    [6, 24, 50, 76, 102, 128, 154], // Version 36
86    [6, 28, 54, 80, 106, 132, 158], // Version 37
87    [6, 32, 58, 84, 110, 136, 162], // Version 38
88    [6, 26, 54, 82, 110, 138, 166], // Version 39
89    [6, 30, 58, 86, 114, 142, 170], // Version 40
90];
91
92// Type info cells at the left top corner.
93const TYPE_INFO_COORDINATES: [[u32; 2]; 15] = [
94    [8, 0],
95    [8, 1],
96    [8, 2],
97    [8, 3],
98    [8, 4],
99    [8, 5],
100    [8, 7],
101    [8, 8],
102    [7, 8],
103    [5, 8],
104    [4, 8],
105    [3, 8],
106    [2, 8],
107    [1, 8],
108    [0, 8],
109];
110
111// From Appendix D in JISX0510:2004 (p. 67)
112const VERSION_INFO_POLY: u32 = 0x1f25; // 1 1111 0010 0101
113
114// From Appendix C in JISX0510:2004 (p.65).
115const TYPE_INFO_POLY: u32 = 0x537;
116const TYPE_INFO_MASK_PATTERN: BitFieldBaseType = 0x5412;
117
118// Set all cells to -1.  -1 means that the cell is empty (not set yet).
119//
120// JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding
121// with the ByteMatrix initialized all to zero.
122pub fn clearMatrix(matrix: &mut ByteMatrix) {
123    matrix.clear(-1i8 as u8);
124}
125
126// Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On
127// success, store the result in "matrix" and return true.
128pub fn buildMatrix(
129    dataBits: &BitArray,
130    ecLevel: &ErrorCorrectionLevel,
131    version: &Version,
132    maskPattern: i32,
133    matrix: &mut ByteMatrix,
134) -> Result<()> {
135    clearMatrix(matrix);
136    embedBasicPatterns(version, matrix)?;
137    // Type information appear with any version.
138    embedTypeInfo(ecLevel, maskPattern, matrix)?;
139    // Version info appear if version >= 7.
140    maybeEmbedVersionInfo(version, matrix)?;
141    // Data should be embedded at end.
142    embedDataBits(dataBits, maskPattern, matrix)?;
143    Ok(())
144}
145
146// Embed basic patterns. On success, modify the matrix and return true.
147// The basic patterns are:
148// - Position detection patterns
149// - Timing patterns
150// - Dark dot at the left bottom corner
151// - Position adjustment patterns, if need be
152pub fn embedBasicPatterns(version: &Version, matrix: &mut ByteMatrix) -> Result<()> {
153    // Let's get started with embedding big squares at corners.
154    embedPositionDetectionPatternsAndSeparators(matrix)?;
155    // Then, embed the dark dot at the left bottom corner.
156    embedDarkDotAtLeftBottomCorner(matrix)?;
157
158    // Position adjustment patterns appear if version >= 2.
159    maybeEmbedPositionAdjustmentPatterns(version, matrix);
160    // Timing patterns should be embedded after position adj. patterns.
161    embedTimingPatterns(matrix);
162    Ok(())
163}
164
165// Embed type information. On success, modify the matrix.
166pub fn embedTypeInfo(
167    ecLevel: &ErrorCorrectionLevel,
168    maskPattern: i32,
169    matrix: &mut ByteMatrix,
170) -> Result<()> {
171    let mut typeInfoBits = BitArray::new();
172    makeTypeInfoBits(ecLevel, maskPattern as u32, &mut typeInfoBits)?;
173
174    for (i, coordinates) in TYPE_INFO_COORDINATES
175        .iter()
176        .enumerate()
177        .take(typeInfoBits.get_size())
178    {
179        // Place bits in LSB to MSB order.  LSB (least significant bit) is the last value in
180        // "typeInfoBits".
181        let bit = typeInfoBits.get(typeInfoBits.get_size() - 1 - i);
182
183        // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
184        // let coordinates = TYPE_INFO_COORDINATES[i];
185        let x1 = coordinates[0];
186        let y1 = coordinates[1];
187        matrix.set_bool(x1, y1, bit);
188
189        let x2;
190        let y2;
191        if i < 8 {
192            // Right top corner.
193            x2 = matrix.getWidth() - i as u32 - 1;
194            y2 = 8;
195        } else {
196            // Left bottom corner.
197            x2 = 8;
198            y2 = matrix.getHeight() - 7 + (i as u32 - 8);
199        }
200        matrix.set_bool(x2, y2, bit);
201    }
202    Ok(())
203}
204
205// Embed version information if need be. On success, modify the matrix and return true.
206// See 8.10 of JISX0510:2004 (p.47) for how to embed version information.
207pub fn maybeEmbedVersionInfo(version: &Version, matrix: &mut ByteMatrix) -> Result<()> {
208    if version.getVersionNumber() < 7 {
209        // Version info is necessary if version >= 7.
210        return Ok(()); // Don't need version info.
211    }
212    let mut versionInfoBits = BitArray::new();
213    makeVersionInfoBits(version, &mut versionInfoBits)?;
214
215    let mut bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0.
216    for i in 0..6 {
217        for j in 0..3 {
218            // Place bits in LSB (least significant bit) to MSB order.
219            let bit = versionInfoBits.get(bitIndex);
220            bitIndex = bitIndex.saturating_sub(1);
221            // Left bottom corner.
222            matrix.set_bool(i, matrix.getHeight() - 11 + j, bit);
223            // Right bottom corner.
224            matrix.set_bool(matrix.getHeight() - 11 + j, i, bit);
225        }
226    }
227    Ok(())
228}
229
230// Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true.
231// For debugging purposes, it skips masking process if "getMaskPattern" is -1.
232// See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
233pub fn embedDataBits(dataBits: &BitArray, maskPattern: i32, matrix: &mut ByteMatrix) -> Result<()> {
234    let mut bitIndex = 0;
235    let mut direction: i32 = -1;
236    // Start from the right bottom cell.
237    let mut x = matrix.getWidth() as i32 - 1;
238    let mut y = matrix.getHeight() as i32 - 1;
239    while x > 0 {
240        // Skip the vertical timing pattern.
241        if x == 6 {
242            x -= 1;
243        }
244        while y >= 0 && y < matrix.getHeight() as i32 {
245            for i in 0..2 {
246                let xx = x - i;
247                // Skip the cell if it's not empty.
248                if !isEmpty(matrix.get(xx as u32, y as u32)) {
249                    continue;
250                }
251                let mut bit;
252                if bitIndex < dataBits.get_size() {
253                    bit = dataBits.get(bitIndex);
254                    bitIndex += 1;
255                } else {
256                    // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described
257                    // in 8.4.9 of JISX0510:2004 (p. 24).
258                    bit = false;
259                }
260
261                // Skip masking if mask_pattern is -1.
262                if maskPattern != -1
263                    && mask_util::getDataMaskBit(maskPattern as u32, xx as u32, y as u32)?
264                {
265                    bit = !bit;
266                }
267                matrix.set_bool(xx as u32, y as u32, bit);
268            }
269            y += direction;
270        }
271        direction = -direction; // Reverse the direction.
272        y += direction;
273        x -= 2; // Move to the left.
274    }
275    // All bits should be consumed.
276    if bitIndex != dataBits.get_size() {
277        return Err(Exceptions::writer_with(format!(
278            "Not all bits consumed: {}/{}",
279            bitIndex,
280            dataBits.get_size()
281        )));
282    }
283    Ok(())
284}
285
286// Return the position of the most significant bit set (to one) in the "value". The most
287// significant bit is position 32. If there is no bit set, return 0. Examples:
288// - findMSBSet(0) => 0
289// - findMSBSet(1) => 1
290// - findMSBSet(255) => 8
291pub fn findMSBSet(value: u32) -> u32 {
292    32 - value.leading_zeros()
293}
294
295// Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
296// code is used for encoding type information and version information.
297// Example: Calculation of version information of 7.
298// f(x) is created from 7.
299//   - 7 = 000111 in 6 bits
300//   - f(x) = x^2 + x^1 + x^0
301// g(x) is given by the standard (p. 67)
302//   - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
303// Multiply f(x) by x^(18 - 6)
304//   - f'(x) = f(x) * x^(18 - 6)
305//   - f'(x) = x^14 + x^13 + x^12
306// Calculate the remainder of f'(x) / g(x)
307//         x^2
308//         __________________________________________________
309//   g(x) )x^14 + x^13 + x^12
310//         x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
311//         --------------------------------------------------
312//                              x^11 + x^10 + x^7 + x^4 + x^2
313//
314// The remainder is x^11 + x^10 + x^7 + x^4 + x^2
315// Encode it in binary: 110010010100
316// The return value is 0xc94 (1100 1001 0100)
317//
318// Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
319// operations. We don't care if coefficients are positive or negative.
320pub fn calculateBCHCode(value: u32, poly: u32) -> Result<u32> {
321    if poly == 0 {
322        return Err(Exceptions::illegal_argument_with("0 polynomial"));
323    }
324    let mut value = value;
325    // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
326    // from 13 to make it 12.
327    let msbSetInPoly = findMSBSet(poly);
328    value <<= msbSetInPoly - 1;
329    // Do the division business using exclusive-or operations.
330    while findMSBSet(value) >= msbSetInPoly {
331        value ^= poly << (findMSBSet(value) - msbSetInPoly);
332    }
333    // Now the "value" is the remainder (i.e. the BCH code)
334    Ok(value)
335}
336
337// Make bit vector of type information. On success, store the result in "bits" and return true.
338// Encode error correction level and mask pattern. See 8.9 of
339// JISX0510:2004 (p.45) for details.
340pub fn makeTypeInfoBits(
341    ecLevel: &ErrorCorrectionLevel,
342    maskPattern: u32,
343    bits: &mut BitArray,
344) -> Result<()> {
345    if !QRCode::isValidMaskPattern(maskPattern as i32) {
346        return Err(Exceptions::writer_with("Invalid mask pattern"));
347    }
348    let typeInfo = (ecLevel.get_value() << 3) as u32 | maskPattern;
349    bits.appendBits(typeInfo as BitFieldBaseType, 5)?;
350
351    let bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY)?;
352    bits.appendBits(bchCode as BitFieldBaseType, 10)?;
353
354    let mut maskBits = BitArray::new();
355    maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15)?;
356    bits.xor(&maskBits)?;
357
358    if bits.get_size() != 15 {
359        // Just in case.
360        return Err(Exceptions::writer_with(format!(
361            "should not happen but we got: {}",
362            bits.get_size()
363        )));
364    }
365    Ok(())
366}
367
368// Make bit vector of version information. On success, store the result in "bits" and return true.
369// See 8.10 of JISX0510:2004 (p.45) for details.
370pub fn makeVersionInfoBits(version: &Version, bits: &mut BitArray) -> Result<()> {
371    bits.appendBits(version.getVersionNumber() as BitFieldBaseType, 6)?;
372    let bchCode = calculateBCHCode(version.getVersionNumber(), VERSION_INFO_POLY)?;
373    bits.appendBits(bchCode as BitFieldBaseType, 12)?;
374
375    if bits.get_size() != 18 {
376        // Just in case.
377        return Err(Exceptions::writer_with(format!(
378            "should not happen but we got: {}",
379            bits.get_size()
380        )));
381    }
382    Ok(())
383}
384
385// Check if "value" is empty.
386pub fn isEmpty(value: u8) -> bool {
387    value == -1i8 as u8
388}
389
390pub fn embedTimingPatterns(matrix: &mut ByteMatrix) {
391    // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical
392    // separation patterns (size 1). Thus, 8 = 7 + 1.
393    for i in 8..matrix.getWidth() - 8 {
394        // for (int i = 8; i < matrix.getWidth() - 8; ++i) {
395        let bit = (i as u8 + 1) % 2;
396        // Horizontal line.
397        if isEmpty(matrix.get(i, 6)) {
398            matrix.set(i, 6, bit);
399        }
400        // Vertical line.
401        if isEmpty(matrix.get(6, i)) {
402            matrix.set(6, i, bit);
403        }
404    }
405}
406
407// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
408pub fn embedDarkDotAtLeftBottomCorner(matrix: &mut ByteMatrix) -> Result<()> {
409    if matrix.get(8, matrix.getHeight() - 8) == 0 {
410        return Err(Exceptions::WRITER);
411    }
412    matrix.set(8, matrix.getHeight() - 8, 1);
413    Ok(())
414}
415
416pub fn embedHorizontalSeparationPattern(
417    xStart: u32,
418    yStart: u32,
419    matrix: &mut ByteMatrix,
420) -> Result<()> {
421    for x in 0..8 {
422        if !isEmpty(matrix.get(xStart + x, yStart)) {
423            return Err(Exceptions::WRITER);
424        }
425        matrix.set(xStart + x, yStart, 0);
426    }
427    Ok(())
428}
429
430pub fn embedVerticalSeparationPattern(
431    xStart: u32,
432    yStart: u32,
433    matrix: &mut ByteMatrix,
434) -> Result<()> {
435    for y in 0..7 {
436        if !isEmpty(matrix.get(xStart, yStart + y)) {
437            return Err(Exceptions::WRITER);
438        }
439        matrix.set(xStart, yStart + y, 0);
440    }
441    Ok(())
442}
443
444pub fn embedPositionAdjustmentPattern(xStart: u32, yStart: u32, matrix: &mut ByteMatrix) {
445    for (y, patternY) in POSITION_ADJUSTMENT_PATTERN.iter().enumerate() {
446        for x in 0..5 {
447            matrix.set(xStart + x, yStart + y as u32, patternY[x as usize]);
448        }
449    }
450}
451
452pub fn embedPositionDetectionPattern(xStart: u32, yStart: u32, matrix: &mut ByteMatrix) {
453    for (y, patternY) in POSITION_DETECTION_PATTERN.iter().enumerate() {
454        for x in 0..7 {
455            matrix.set(xStart + x, yStart + y as u32, patternY[x as usize]);
456        }
457    }
458}
459
460// Embed position detection patterns and surrounding vertical/horizontal separators.
461pub fn embedPositionDetectionPatternsAndSeparators(matrix: &mut ByteMatrix) -> Result<()> {
462    // Embed three big squares at corners.
463    let pdpWidth = POSITION_DETECTION_PATTERN[0].len() as u32;
464    // Left top corner.
465    embedPositionDetectionPattern(0, 0, matrix);
466    // Right top corner.
467    embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix);
468    // Left bottom corner.
469    embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix);
470
471    // Embed horizontal separation patterns around the squares.
472    let hspWidth = 8;
473    // Left top corner.
474    embedHorizontalSeparationPattern(0, hspWidth - 1, matrix)?;
475    // Right top corner.
476    embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth, hspWidth - 1, matrix)?;
477    // Left bottom corner.
478    embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix)?;
479
480    // Embed vertical separation patterns around the squares.
481    let vspSize = 7;
482    // Left top corner.
483    embedVerticalSeparationPattern(vspSize, 0, matrix)?;
484    // Right top corner.
485    embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix)?;
486    // Left bottom corner.
487    embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize, matrix)?;
488
489    Ok(())
490}
491
492// Embed position adjustment patterns if need be.
493pub fn maybeEmbedPositionAdjustmentPatterns(version: &Version, matrix: &mut ByteMatrix) {
494    if version.getVersionNumber() < 2 {
495        // The patterns appear if version >= 2
496        return;
497    }
498    let index = version.getVersionNumber() - 1;
499    let coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index as usize];
500    for y in coordinates {
501        if y >= 0 {
502            for x in coordinates {
503                if x >= 0 && isEmpty(matrix.get(x as u32, y as u32)) {
504                    // If the cell is unset, we embed the position adjustment pattern here.
505                    // -2 is necessary since the x/y coordinates point to the center of the pattern, not the
506                    // left top corner.
507                    embedPositionAdjustmentPattern((x - 2) as u32, (y - 2) as u32, matrix);
508                }
509            }
510        }
511    }
512}