summaryrefslogtreecommitdiff
path: root/docs/handbook/genqrcode/micro-qr.md
blob: d202ceb76c02ff6c61bf7fb209f51d5adc60658c (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# genqrcode / libqrencode — Micro QR Code Support

## Overview

Micro QR Code is a compact variant of QR Code standardized in JIS X0510:2004 and ISO/IEC 18004. libqrencode supports Micro QR versions M1 through M4 via dedicated spec tables in `mqrspec.c`, masking in `mmask.c`, and encoding paths in `qrencode.c`.

---

## Micro QR vs. Full QR

| Feature | Full QR Code | Micro QR Code |
|---|---|---|
| Versions | 1–40 | M1–M4 (1–4 internally) |
| Max constant | `QRSPEC_VERSION_MAX = 40` | `MQRSPEC_VERSION_MAX = 4` |
| Finder patterns | 3 | 1 |
| Alignment patterns | 0–46 per version | None |
| Timing patterns | Horizontal + Vertical | Horizontal + Vertical |
| Version information | Versions 7+ | Never |
| Mask patterns | 8 | 4 |
| Mask selection | Minimize penalty | Maximize edge score |
| EC Levels | L, M, Q, H | Version-dependent subset |
| Structured append | Supported | Not supported |
| ECI mode | Supported | Not supported |
| FNC1 mode | Supported | Not supported |

---

## Version Capacities

From `mqrspec.c`:

```c
typedef struct {
    int width;
    int ec[4];
} MQRspec_Capacity;

static const MQRspec_Capacity mqrspecCapacity[MQRSPEC_VERSION_MAX + 1] = {
    {0,  { 0,  0,  0,  0}},
    {11, { 2,  0,  0,  0}},   // M1: 11×11
    {13, { 5,  4,  0,  0}},   // M2: 13×13
    {15, {11,  9,  7,  0}},   // M3: 15×15
    {17, {16, 14, 10,  0}}    // M4: 17×17
};
```

Width formula: `version * 2 + 9` (vs. `version * 4 + 17` for full QR).

### Detailed Capacities

| Version | Width | Total Data Words | L Data | M Data | Q Data | H Data |
|---|---|---|---|---|---|---|
| M1 | 11 | 5 | 2* | — | — | — |
| M2 | 13 | 10 | 5 | 4 | — | — |
| M3 | 15 | 17 | 11 | 9 | 7 | — |
| M4 | 17 | 24 | 16 | 14 | 10 | — |

*M1 has error detection only, not error correction.

### ECC Lengths

```c
int MQRspec_getECCLength(int version, QRecLevel level)
{
    return mqrspecCapacity[version].width * mqrspecCapacity[version].width
           - mqrspecCapacity[version].ec[level]
           - ... (function pattern modules) ...;
}
```

Returns 0 for unsupported version/level combinations, which `QRinput_newMQR()` uses to reject invalid inputs.

### Character Capacities by Mode

| Version | Level | Numeric | Alphanumeric | Byte | Kanji |
|---|---|---|---|---|---|
| M1 | — | 5 | — | — | — |
| M2 | L | 10 | 6 | — | — |
| M2 | M | 8 | 5 | — | — |
| M3 | L | 23 | 14 | 9 | 6 |
| M3 | M | 18 | 11 | 7 | 4 |
| M4 | L | 35 | 21 | 15 | 9 |
| M4 | M | 30 | 18 | 13 | 8 |
| M4 | Q | 21 | 12 | 9 | 5 |

---

## Mode Restrictions

Not all encoding modes are available in every Micro QR version:

| Version | Numeric | Alphanumeric | 8-bit | Kanji | ECI | FNC1 | Structured |
|---|---|---|---|---|---|---|---|
| M1 | Yes | No | No | No | No | No | No |
| M2 | Yes | Yes | No | No | No | No | No |
| M3 | Yes | Yes | Yes | Yes | No | No | No |
| M4 | Yes | Yes | Yes | Yes | No | No | No |

This is enforced by `QRinput_encodeBitStream()` which calls validation functions:

```c
static int QRinput_isModeNumValid(int version, QRinput_List *entry, int mqr)
{
    if(mqr) {
        if(MQRspec_maximumWords(QR_MODE_NUM, version) < entry->size)
            return -1;
    }
    return 0;
}
```

`MQRspec_maximumWords()` returns 0 for unsupported modes at a given version.

---

## MQR-Specific Encoding

### Mode Indicator Sizes

Micro QR uses shorter mode indicators than full QR. From `mqrspec.c`:

```c
// MQR mode indicator bit lengths per version:
// M1: 0 bits (only numeric, implied)
// M2: 1 bit
// M3: 2 bits
// M4: 3 bits
```

These are retrieved by `MQRspec_lengthIndicator()`.

### Character Count Indicator Sizes

```c
static const int lengthTableBits[4][4] = {
    { 3, 0, 0, 0},   // QR_MODE_NUM: M1=3, M2=4, M3=5, M4=6
    { 0, 3, 0, 0},   // QR_MODE_AN:  M1=0, M2=3, M3=4, M4=5
    { 0, 0, 4, 0},   // QR_MODE_8:   M1=0, M2=0, M3=4, M4=5
    { 0, 0, 3, 0},   // QR_MODE_KANJI: M1=0, M2=0, M3=3, M4=4
};
```

A value of 0 means the mode is unsupported for that version.

### Data Length in Bits

A key difference: `MQRspec_getDataLengthBit()` returns data length in **bits**, not bytes:

```c
int MQRspec_getDataLengthBit(int version, QRecLevel level)
{
    int w = mqrspecCapacity[version].width - 1;
    return w * w - 64 - MQRspec_getECCLength(version, level) * 8;
}
```

This matters because M1 and some M2 configurations have data lengths that are not byte-aligned.

---

## MQRRawCode — Micro QR Block Structure

From `qrencode.c`:

```c
typedef struct {
    int version;
    int dataLength;
    int eccLength;
    unsigned char *datacode;
    unsigned char *ecccode;
    int b1;
    int rsblock_num;
    RSblock *rsblock;
    int count;
    int oddbits;       // Number of "odd" bits in last data byte
} MQRRawCode;
```

Micro QR always has exactly **one RS block** (no block interleaving):

```c
static MQRRawCode *MQRraw_new(QRinput *input)
{
    MQRRawCode *raw;
    raw->version = input->version;
    raw->dataLength = MQRspec_getDataLength(input->version, input->level);
    raw->eccLength = MQRspec_getECCLength(input->version, input->level);
    raw->oddbits = raw->dataLength * 8 - MQRspec_getDataLengthBit(input->version, input->level);

    raw->datacode = QRinput_getByteStream(input);
    raw->ecccode = (unsigned char *)malloc(raw->eccLength);
    raw->rsblock_num = 1;
    raw->rsblock = calloc(1, sizeof(RSblock));

    RSblock_initBlock(raw->rsblock, raw->dataLength, raw->datacode,
                      raw->eccLength, raw->ecccode, RSECC_encode);
    raw->count = 0;
    return raw;
}
```

### Odd Bits Handling

The `oddbits` field handles versions where data capacity is not byte-aligned:

```c
unsigned char MQRraw_getCode(MQRRawCode *raw)
{
    if(raw->count < raw->dataLength) {
        return raw->datacode[raw->count++];
    } else {
        return raw->ecccode[raw->count++ - raw->dataLength];
    }
}
```

In `QRcode_encodeMaskMQR()`, the odd bits are handled after placing full codewords:

```c
j = MQRspec_getDataLengthBit(input->version, input->level)
    - MQRraw_getDataLength(raw) * 8;
if(j > 0) {
    // Place remaining odd bits from last data byte
    code = MQRraw_getCode(raw);
    bit = 0x80;
    for(i = 0; i < j; i++) {
        p = FrameFiller_next(filler);
        *p = 0x02 | ((code & bit) != 0);
        bit >>= 1;
    }
}
```

---

## Frame Creation

`MQRspec_createFrame()` builds the base frame with function patterns:

```c
unsigned char *MQRspec_createFrame(int version)
{
    unsigned char *frame;
    int width = mqrspecCapacity[version].width;

    frame = (unsigned char *)calloc(width * width, 1);

    // 1. Finder pattern (only ONE, top-left)
    putFinderPattern(frame, width, 0, 0);

    // 2. Separator (no full separator ring — only right and bottom)

    // 3. Timing pattern (horizontal and vertical)
    for(int i = 0; i < width - 8; i++) {
        // horizontal timing along row 0, starting at column 8
        frame[8 + i] = 0x90 | (i & 1);
        // vertical timing along column 0, starting at row 8
        frame[(8 + i) * width] = 0x90 | (i & 1);
    }

    // 4. Format information area (reserved)
    // No version information (unlike QR versions 7+)
    // No alignment patterns (unlike QR versions 2+)

    return frame;
}
```

Key differences from `QRspec_createFrame()`:
- Single finder pattern instead of three
- No alignment patterns
- No version information area
- Simpler separator structure

---

## Micro QR Masking

See [masking-algorithms.md](masking-algorithms.md) for the full details. Summary:

### 4 Patterns

```c
MMask_mask0: y % 2 == 0
MMask_mask1: (y/2 + x/3) % 2 == 0
MMask_mask2: ((y*x)%2 + (y*x)%3) % 2 == 0
MMask_mask3: ((y+x)%2 + (y*x)%3) % 2 == 0
```

### Selection Criterion

Micro QR picks the mask with the **highest** score (opposite of full QR):

```c
// Sum of dark modules in bottom row × 16 + sum of dark modules in right column
score = sum1 * 16 + sum2;
```

The right column gets lower weight (×1) than the bottom row (×16).

---

## Format Information

Micro QR encodes version, EC level, and mask pattern in a single 15-bit format info:

```c
static const unsigned int typeTable[MQRSPEC_VERSION_MAX + 1][3] = {
    {0x00000, 0x00000, 0x00000},  // unused
    {0x04445, 0x04172, 0x04e2b},  // M1
    {0x02f7f, 0x02a48, 0x02511},  // M2
    {0x07f46, 0x07a71, 0x07528},  // M3
    {0x00dc5, 0x008f2, 0x007ab}   // M4
};
```

Indexed as `typeTable[version][typeNumber]` where `typeNumber` depends on the EC level:

```c
unsigned int MQRspec_getFormatInfo(int mask, int version, QRecLevel level)
{
    // ... compute typeNumber from version and level ...
    // ... XOR with mask-dependent pattern ...
}
```

Written into the symbol by `MMask_writeFormatInformation()` in a single strip around the finder pattern (8 bits on the left side, 7 bits on the top).

---

## API for Micro QR

### Input Creation

```c
QRinput *input = QRinput_newMQR(int version, QRecLevel level);
```

- `version` must be 1–4 (no auto-detection for manual input)
- Invalid version/level combinations are rejected

### High-Level Encoding

```c
QRcode *QRcode_encodeStringMQR(const char *string, int version,
                                QRecLevel level, QRencodeMode hint,
                                int casesensitive);
QRcode *QRcode_encodeString8bitMQR(const char *string, int version,
                                    QRecLevel level);
QRcode *QRcode_encodeDataMQR(int size, const unsigned char *data,
                              int version, QRecLevel level);
```

When `version` is 0, these functions try versions M1 through M4 incrementally:

```c
if(version == 0) {
    for(i = 1; i <= MQRSPEC_VERSION_MAX; i++) {
        QRcode *code = QRcode_encodeDataReal(data, size, i, level, 1);
        if(code != NULL) return code;
    }
}
```

### Version/Level Validation

Use `QRinput_setVersionAndErrorCorrectionLevel()` for Micro QR — it validates the combination. Using `QRinput_setVersion()` or `QRinput_setErrorCorrectionLevel()` individually on MQR inputs returns `EINVAL`.

---

## Structured Append — Not Supported

Micro QR does not support structured append mode. Attempting to encode structured append with MQR results in an error:

```c
static int QRinput_encodeModeStructure(QRinput_List *entry, int mqr)
{
    if(mqr) {
        errno = EINVAL;
        return -1;
    }
    // ...
}
```

`QRinput_Struct_appendInput()` also rejects MQR inputs:

```c
int QRinput_Struct_appendInput(QRinput_Struct *s, QRinput *input)
{
    if(input == NULL || input->mqr) {
        errno = EINVAL;
        return -1;
    }
    // ...
}
```

---

## Encoding Pipeline Differences

`QRcode_encodeMaskMQR()` in `qrencode.c` follows a modified pipeline:

1. **Create frame**: `MQRspec_createFrame(version)` — single finder, no alignment
2. **Initialize RS**: `MQRraw_new(input)` — single block, with odd bits tracking
3. **Place data**: Via `FrameFiller_next()`, but handles odd bits at boundary:
   ```c
   // Place full data bytes
   for(i = 0; i < MQRraw_getDataLength(raw) - 1; i++) {
       code = MQRraw_getCode(raw);
       bit = 0x80;
       for(j = 0; j < 8; j++) {
           p = FrameFiller_next(filler);
           *p = 0x02 | ((bit & code) != 0);
           bit >>= 1;
       }
   }
   // Handle odd bits from last data byte
   ```
4. **Place ECC**: Full ECC bytes, then remainder bits (if any)
5. **Apply mask**: `MMask_mask(version, frame, level)` — 4 patterns, maximize score
6. **Package**: `QRcode_new(version, width, masked)`

---

## CLI Support

The `qrencode` CLI tool supports Micro QR via the `-M` / `--micro` flag:

```bash
qrencode -M -v 3 -l M -o output.png "Hello"
```

In `qrenc.c`:

```c
case 'M':
    micro = 1;
    break;
```

When `micro` is set, `encode()` calls `QRcode_encodeStringMQR()` or `QRcode_encodeDataMQR()` instead of the standard variants.

---

## Limitations Summary

1. **No H level**: Maximum EC is Q (M4 only)
2. **No structured append**: Cannot split data across multiple symbols
3. **No ECI**: Cannot specify character encodings
4. **No FNC1**: Cannot create GS1-compatible codes
5. **Small capacity**: Maximum 35 numeric or 15 byte characters (M4-L)
6. **Single finder**: Only top-left finder pattern — orientation from timing patterns
7. **Version must be specified**: For `QRinput_newMQR()`, version 0 is not auto-detect (though high-level `QRcode_encodeStringMQR()` with version 0 does try all versions)