# DataMatrix Reader 1.1 — C++ and C ABI

> Reads GS1 DataMatrix codes from industrial camera frames — for conveyor lines marked under Chestny ZNAK, the Russian product marking system.

Source page: https://libscanner.com/en/docs/datamatrix-gs1/1.1/

## Overview

The library reads **DataMatrix (ECC200)** codes from production-line camera frames — for example, boxes carrying Chestny ZNAK marking codes (the Russian national product marking system), where the symbol spans about a hundred pixels in the frame. The reader is designed for low capture resolution — around two pixels per symbol module — and verifies every geometry hypothesis with Reed-Solomon error correction. Accuracy and read speed are shown at the top of the page; below is the interface only.

The library is static; the public interface is C++20, eight headers in `include/dmr/`, plus a flat C interface for other languages (`dmr_c.h`, see C ABI). A frame is passed as a view over a foreign buffer (`dmr::ImageView`) — no copying, straight from the camera buffer or image you already have.

> **Scope.** By default the scanner reads DataMatrix of any structure. The `requireGs1` mode (see “Settings”) additionally checks the content format — AI 01 (GTIN, 14 digits with a valid check digit), then AI 21 — and rejects symbols that do not match the GS1 structure.

## Installation

The library ships prebuilt — you do not build it, you only build your own program. There are two ways to use it: **statically** — the C++ API from `libdmr.a` is linked into your program in full, or **dynamically** — through the `dmr_c` library with a flat C interface (C ABI). The package contents are the same on both OSes:

**Windows:**

```
include\dmr\{Dmr,Diagnostics,Geometry,Image,License,Scanner,Settings,Version}.h   C++ API
include\dmr\dmr_c.h                                                               C ABI
lib\libdmr.a                 C++ static library
lib\pkgconfig\dmr.pc
bin\dmr_c.dll                C ABI library
lib\dmr_c.dll.a              its import library (MinGW)
lib\pkgconfig\dmr_c.pc
bin\dmr.exe                  command-line utility
share\doc\dmr\licenses\       third-party licenses
```

**Linux:**

```
include/dmr/{Dmr,Diagnostics,Geometry,Image,License,Scanner,Settings,Version}.h   C++ API
include/dmr/dmr_c.h                                                             C ABI
lib/libdmr.a                  C++ static library
lib/pkgconfig/dmr.pc
lib/libdmr_c.so               C ABI library
lib/pkgconfig/dmr_c.pc
bin/dmr                       command-line utility
share/doc/dmr/licenses/       third-party licenses
```

| Your program | What to use |
| --- | --- |
| C++, built with MinGW-w64 GCC (Windows) or GCC (Linux) | Static linking — C++ API, `libdmr.a` |
| MSVC or another compiler; another language (C, C#, Delphi, Go…); updating the library without rebuilding the program | Dynamic linking — C ABI, `dmr_c` |
| Python | The wheel from “Downloads” — [Python documentation](https://libscanner.com/en/docs/datamatrix-gs1/1.2/python.md) |

### Static linking — C++ API

`libdmr.a` is linked into your program in full: nothing needs to sit next to it except the key file `license.key`, which goes next to the program (see “License”). A **C++20** compiler is required. The API is C++ and returns `std::string` and `std::vector`, so the compiler and its standard library must be the same as the package's (the same or a newer version).

**Windows:**

> **MinGW-w64 GCC required, not MSVC.** The Windows package is built with MinGW-w64 GCC — `libdmr.a` is in its format and with its ABI. MSVC cannot link this static archive; your program needs the same toolchain (for example, MSYS2/MinGW or CLion with a MinGW profile). From MSVC, link dynamically, via dmr_c.
>
> The toolchain is free: [MSYS2](https://www.msys2.org/) — run the installer from the website, then in its **MINGW64** shell (the package is built in exactly this environment, not UCRT64):
>
> ```bash
> pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-pkgconf
> ```

Include paths and the link line come from `dmr.pc`. Point an environment variable (PowerShell) at `lib\pkgconfig` of the unpacked package; paths in the `.pc` are relative to the file itself, so the unpack directory can be anywhere:

```bash
$env:PKG_CONFIG_PATH = "C:\path\to\unpacked\lib\pkgconfig"
pkg-config --static --cflags --libs dmr
```

The system libraries `winhttp`, `crypt32`, `shell32` and `advapi32` (used by the license check) are already listed in the package's `Libs.private` — no need to add them separately.

**Linux:**

The package is built with GCC 12 (Debian 12): GCC 12 or newer is required. Include paths and the link line come from `dmr.pc`; point an environment variable at `lib/pkgconfig` of the unpacked package — the unpack directory can be anywhere:

```bash
PKG_CONFIG_PATH=/path/to/unpacked/lib/pkgconfig pkg-config --static --cflags --libs dmr
```

`-pthread -ldl` are required — they are already in the package. The `.pc` does not add `-std=c++20`: pass it yourself (GCC 12 defaults to C++17). Without pkg-config the same line by hand:

```bash
g++ -std=c++20 main.cpp -o myprogram -I/path/to/unpacked/include /path/to/unpacked/lib/libdmr.a -pthread -ldl
```

OpenSSL is not a link dependency: for the license server's `https://` the library loads `libssl.so.3` (or `.so.1.1`) at run time.

> **The pkg-config query must be static.** The package is a single static library, so the caller also needs the libraries it depends on. Without `--static` they will not be on the command line, and linking will fail with unresolved symbols.

In meson — a dependency by package name:

```cpp
dmr_dep = dependency('dmr', required: true, static: true)
executable('myprogram', 'main.cpp', dependencies: [dmr_dep],
  link_args: ['-static'])   # Windows: MinGW runtime linked into the program
```

On Windows, `-static` also links the compiler runtime into the program: without it, the program will need `libstdc++-6.dll`, `libgcc_s_seh-1.dll` and `libwinpthread-1.dll` from MSYS2 next to it. On Linux it is not needed. A complete `meson.build` is in “Quick start”.

### Dynamic linking — C ABI

`dmr_c` is the same library behind a flat C interface (header `dmr/dmr_c.h`): `dmr_*` functions and opaque pointers, no C++ types. The compiler runtime is linked into it statically, so it depends neither on the caller's compiler nor on its C++ standard library — it works with MSVC, Clang and any language that can call C functions. Everything the library returns (results, strings) is freed by its own functions: `dmr_scan_result_free`, `dmr_image_free`, `dmr_free_string`.

The rules of the interface, a complete example and every function — in C ABI.

**Windows:**

**MinGW-w64 GCC** — via `dmr_c.pc` and the import library `lib\dmr_c.dll.a`, without `--static`:

```bash
$env:PKG_CONFIG_PATH = "C:\path\to\unpacked\lib\pkgconfig"
pkg-config --cflags --libs dmr_c
```

This yields `-I…\include -L…\lib -ldmr_c`. Contents of `dmr_c.pc`:

```cpp
prefix=${pcfiledir}/../..
includedir=${prefix}/include
libdir=${prefix}/lib

Name: dmr_c
Version: 1.1.3
Libs: -L${libdir} -ldmr_c
Cflags: -I${includedir}
```

**MSVC** — the package has no `.lib` file; you generate it from the DLL itself. In the MSYS2 shell, extract the export definitions:

```bash
gendef dmr_c.dll          # package mingw-w64-x86_64-tools; writes dmr_c.def
```

then, in the Developer Command Prompt for VS (x64), create the import library and build:

```bash
lib /def:dmr_c.def /machine:x64 /out:dmr_c.lib
cl /I C:\path\to\unpacked\include main.c dmr_c.lib
```

At run time `dmr_c.dll` must be next to your `.exe` (or in a directory on `PATH`), and the key file `license.key` goes next to `dmr_c.dll` or next to the `.exe` (see “License”).

**Linux:**

```bash
PKG_CONFIG_PATH=/path/to/unpacked/lib/pkgconfig pkg-config --cflags --libs dmr_c
```

This yields `-I…/include -L…/lib -ldmr_c`. At run time the loader must find `libdmr_c.so`: either via `LD_LIBRARY_PATH`, or put it next to the program and set the search path at link time:

```bash
LD_LIBRARY_PATH=/path/to/unpacked/lib ./myprogram

# or: libdmr_c.so next to the program
cc main.c -o myprogram $(pkg-config --cflags --libs dmr_c) -Wl,-rpath,'$ORIGIN'
cp /path/to/unpacked/lib/libdmr_c.so .
```

The key file `license.key` goes next to `libdmr_c.so` or next to the program (see “License”). The library has no versioned SONAME — the file is simply `libdmr_c.so`.

In meson — likewise by package name, without `static`:

```cpp
dmr_c_dep = dependency('dmr_c', required: true)
executable('myprogram', 'main.c', dependencies: [dmr_c_dep])
```

The Python wheel is a wrapper over `dmr_c`, with the library bundled inside the package: [Python documentation](https://libscanner.com/en/docs/datamatrix-gs1/1.2/python.md).

## Quick start

A minimal program: load an image from disk, read it, print the text. All you need is one header:

```cpp
#include <dmr/Dmr.h>
#include <iostream>

int main() {
    dmr::Image frame;
    if (dmr::loadImage("frame.jpg", frame) != dmr::LoadStatus::Ok) {
        std::cerr << "could not read the file\n";
        return 1;
    }

    dmr::Scanner scanner;                          // frame stream of one label
    const dmr::ScanResult r = scanner.scan(frame);  // Image converts implicitly to ImageView

    if (r.ok()) {
        std::cout << r.text() << "\n";
    } else if (r.status == dmr::Status::NotFound) {
        std::cout << "no symbol in the frame\n";
    } else {
        std::cout << "symbol found but could not be read\n";
    }
}
```

The example can be built with Meson. Next to `main.cpp` put the unpacked package `dmr-1.1.3-windows-x64` and a `meson.build` file:

```cpp
project('test_dmr', 'cpp',
  version : '0.1.0',
  default_options : ['cpp_std=c++20', 'warning_level=3', 'buildtype=release'])

cxx = meson.get_compiler('cpp')

# The prebuilt dmr sits next to the project. The dependency is declared by hand,
# so pkg-config is not needed at all (in 1.0.0 archives downloaded before
# 2026-10-04 the .pc paths pointed at the build machine; this way works with them too).
dmr_root = meson.current_source_dir() / 'dmr-1.1.3-windows-x64'

dmr_lib = cxx.find_library('dmr', dirs : dmr_root / 'lib', static : true)

# Libs.private from dmr.pc — required for static linking
dmr_private = []
foreach l : ['winhttp', 'crypt32', 'shell32', 'advapi32']
  dmr_private += cxx.find_library(l)
endforeach

dmr_dep = declare_dependency(
  include_directories : include_directories('dmr-1.1.3-windows-x64/include'),
  dependencies : [dmr_lib] + dmr_private)

executable('test_dmr', 'main.cpp',
  dependencies : dmr_dep,
  cpp_args : ['-finput-charset=UTF-8', '-fexec-charset=UTF-8'],
  link_args : ['-static'])
```

Build in the MSYS2 MINGW64 shell:

```bash
meson setup build
meson compile -C build
```

The same via pkg-config: the package's `.pc` files are relocatable, so instead of the manual declaration one line in `meson.build` is enough — `dmr_dep = dependency('dmr', static : true)` — plus the path to the unpacked `lib/pkgconfig` at setup:

```bash
meson setup build --pkg-config-path="$PWD/dmr-1.1.3-windows-x64/lib/pkgconfig"
meson compile -C build
```

For a frame from your own capture pipeline (camera SDK, OpenCV buffer, Windows bitmap) the disk is not involved — you build a view over the buffer you already have, without copying:

```cpp
const dmr::ImageView view{ m.data, m.cols, m.rows, (int)m.step, dmr::PixelFormat::Bgr8 };
const dmr::ScanResult r = scanner.scan(view);
```

## Headers

There are seven public C++ headers, all under `include/dmr/`; the eighth, `dmr/Dmr.h`, includes them all at once. The ninth file, `dmr/dmr_c.h`, is the separate C interface (C ABI).

| Header | Contents |
| --- | --- |
| `dmr/Dmr.h` | Umbrella header — includes everything below |
| `dmr/Image.h` | `ImageView`, `Image`, `PixelFormat`, `loadImage`, paths |
| `dmr/Scanner.h` | `Scanner`, `ScanResult`, `Code`, `Status` |
| `dmr/Settings.h` | Scanner settings and presets |
| `dmr/Geometry.h` | `Point`, `Box`, `Quad` — where the code is located in the frame |
| `dmr/Diagnostics.h` | `explain()`, log sink (`LogSink`) |
| `dmr/License.h` | License check and activation, namespace `dmr::license` |
| `dmr/Version.h` | Header version (macros) and built library version (`dmr::version()`) |

Headers depend on each other no more than necessary: `Settings.h` and `Scanner.h` pull in `<functional>` and `<vector>`, while code that only builds a frame view needs just `Image.h`.

## Scanner

`Scanner` is an object, not a function, and you should not create one per frame: the symbol size hint (`Settings::mcHintRun`) accumulates over the frames of a stream and must outlive them, and the thread pool size is a per-process setting. Still, `scan()` is declared `const` and stores nothing in the object except that hint: the result depends on the frame, not on the history of reads. Candidates are tried in parallel internally — there is no need to run your own thread pool on top of `scan()`.

```cpp
class Scanner {
public:
    explicit Scanner(Settings s = Settings::stream());
    ~Scanner();

    Scanner(Scanner&&) noexcept;
    Scanner& operator=(Scanner&&) noexcept;
    Scanner(const Scanner&)            = delete;
    Scanner& operator=(const Scanner&) = delete;

    // Read the codes in a frame.
    //   frame        the whole frame, color or grayscale
    //   moduleCount  symbol side in modules; 0 — detect automatically
    ScanResult scan(ImageView frame, int moduleCount = 0) const;

    // An image from disk and the codes in it under ONE deadline (budgetMs,
    // timeoutMs): loading and scanning together. Not loaded — ImageTooLarge
    // or InvalidImage (plus timedOut if decoding hit the deadline); details
    // in load. Since 1.0.10.
    ScanResult scanFile(const std::string& path, int moduleCount = 0,
                        LoadStatus* load = nullptr) const;

    // Symbol size suggested by previous frames; 0 — no hint.
    int moduleCountHint() const;

    // Forget the hint.
    void resetStream();

    const Settings& settings() const;
};

// One-off read without an object: a probe, a script, a single file. The size
// hint from a frame stream does not apply here — there is nothing to accumulate it in.
ScanResult scan(ImageView frame, const Settings& s = Settings::single());
```

When the label on the conveyor changes, reset the hint explicitly instead of waiting for it to fade on its own:

```cpp
scanner.resetStream();
```

> **Errors are returned, not thrown.** `scan()` catches everything inside: an internal failure (for example, out of memory) is `Status::Failed`, the process stays alive. `loadImage()` reports problems with `LoadStatus`. Only `std::bad_alloc` can leave the `Scanner` constructor and the `license::` functions — like any C++ code that allocates memory. The C ABI does not let even that through.

> **Move-only.** `Scanner` can be moved (`Scanner&&`), but not copied — the copy constructor and copy assignment operator are explicitly deleted.

## Scan result

### Status

```cpp
enum class Status {
    Ok            = 0,  // at least one code was read
    NotFound      = 1,  // no symbol found in the frame
    NotDecoded    = 2,  // symbol found but not read
    Unlicensed    = 3,  // frame not processed: no trial period and no license
    ImageTooLarge = 4,  // frame exceeds Settings::imageLimits, not processed
    InvalidImage  = 5,  // inconsistent frame description: stride smaller than
                        // the width, unknown pixel format
    Failed        = 6,  // processing aborted by an internal error (e.g. out of
                        // memory); the process stays alive
};
```

With `Status::Unlicensed` the frame was not processed at all — the reason is given by `dmr::license::status()` (see “License”). `Ok` always comes with at least one code in `codes`; with any other status `codes` is empty.

### ScanResult

| Field | Type | Meaning |
| --- | --- | --- |
| `status` | `Status` | How processing of the frame ended |
| `codes` | `std::vector<Code>` | Codes read, one per symbol, in reading order: top to bottom, left to right for equal top edges. Empty if `status` is not `Ok`. With `Settings::maxCodes = 1` the length is at most one |
| `timedOut` | `bool` | The search was cut short by `Settings::budgetMs` or `Settings::timeoutMs`. Set only when the budget actually cut something off — success with the flag set is possible: a code was read, but some hypotheses were not checked |
| `elapsedMs` | `double` | Frame processing time, ms, excluding loading the image from disk |
| `details` | `std::shared_ptr<const Details>` | Diagnostic breakdown; empty unless requested via `Settings::collectDetails` |

Methods: `bool ok() const` — shorthand for `status == Status::Ok`; `const std::string& text() const` — the text of the first code or an empty string, so you don't have to write `codes.empty() ? "" : codes[0].text` on every call.

### Code

| Field | Type | Meaning |
| --- | --- | --- |
| `text` | `std::string` | The decoded string. Bytes as is: GS separators stay as the byte `0x1D` and are not replaced with a printable form |
| `box` | `Box` | Where the symbol was found in the source frame — the candidate rectangle |
| `corners` | `Quad` | The four symbol corners in the same frame, more precise than the box (see “Geometry”) |
| `moduleCount` | `int` | Symbol side in modules |

`codes` are already de-duplicated: two candidates with the same string and overlapping `box` are one symbol seen twice and come back as one code; two identical labels whose boxes do not overlap stay two codes. Order — top to bottom, then left to right.

### Multiple codes per frame

```cpp
const dmr::Scanner scanner(dmr::Settings::multi(0));   // 0 — as many as found
for (const dmr::Code& c : scanner.scan(frame).codes)
    use(c.text, c.box, c.moduleCount);
```

`multi(n)` is `stream()` with `maxCodes = n`: tuned for a camera stream. For unrelated images (a folder, single files) with several codes, combine it with what `single()` changes — fields are independent:

```cpp
auto s = dmr::Settings::multi(0);
s.mcHintRun    = 0;    // no hint from previous frames
s.maxSizeTries = 24;   // try all sizes on a frame where nothing was read
```

## Frame

### PixelFormat

```cpp
enum class PixelFormat {
    Gray8,   // single channel: luminance; cheapest for the scanner
    Bgr8,    // three channels, OpenCV order
    Rgb8,    // three channels, the order most others use
    Bgra8,   // four channels, OpenCV and Windows order
    Rgba8,   // four channels
};
```

The scanner works on luminance and converts a color frame to it first. For a monochrome camera, pass the frame as `Gray8` rather than replicated into three channels — the result is the same, and the frame is processed faster.

### ImageView

A view over a foreign buffer: the library does not copy it, free it or keep it beyond the call — the buffer must stay alive for the whole call.

```cpp
struct ImageView {
    const uint8_t* data   = nullptr;
    int            width  = 0;
    int            height = 0;
    int            stride = 0;              // bytes per row; 0 — tightly packed
    PixelFormat    format = PixelFormat::Gray8;

    bool empty()    const;
    int  channels() const;
    int  rowBytes() const;                  // stride with the zero already resolved
    const uint8_t* row(int y) const;
};
```

`stride = 0` means “tightly packed” (`width * channels`), not “zero bytes per row”: a camera frame is almost never tightly packed — rows are aligned, and a crop inherits the row length of the original. Built at the call site without copying:

```cpp
const dmr::ImageView view{ m.data, m.cols, m.rows, (int)m.step, dmr::PixelFormat::Bgr8 };
```

### Image

A frame owned by the library itself — needed where the library creates it, i.e. when reading from disk. It converts implicitly to `ImageView`, so it is passed to `scan()` directly, without `.view()`:

```cpp
class Image {
public:
    Image() = default;
    Image(int width, int height, PixelFormat format);

    void reset(int width, int height, PixelFormat format);  // tightly packed layout
    void clear();

    int         width()    const;
    int         height()   const;
    int         stride()   const;
    PixelFormat format()   const;
    int         channels() const;
    bool        empty()    const;

    uint8_t*       data();
    uint8_t*       row(int y);

    ImageView view() const;
    operator ImageView() const;   // implicit — for calling scan(image)
};
```

### Reading from disk

```cpp
enum class LoadStatus {
    Ok,          // image read
    NotFound,    // no such file
    Unreadable,  // the file exists but is not a readable image
    TooLarge,    // size from the header exceeds ImageLimits; pixels were not read
};

enum class LoadAs {
    Color,  // three channels, PixelFormat::Bgr8
    Gray,   // one channel, PixelFormat::Gray8
};

LoadStatus loadImage(const std::string& path, Image& out, LoadAs as = LoadAs::Color,
                     const ImageLimits& limits = ImageLimits{});   // 16384 per side, 100 MP
```

Formats: **JPEG and PNG** — recognised by the first bytes of the file, not by the extension. Baseline and progressive JPEG, grayscale or color; CMYK JPEG is not supported. PNG of any bit depth and color type: 16-bit is reduced to 8, palette and low bit depths are expanded, the alpha channel is dropped (no compositing over a background). BMP, GIF, TIFF and WebP give `Unreadable` — convert them first or pass the decoded pixels as an `ImageView`. A truncated JPEG is read as far as it goes.

For the scanner, `Gray` is the best choice: an image from a monochrome camera (grayscale in a three-channel JPEG) is cheaper to read this way, and the result is byte-for-byte the same, because each `Color` channel is exactly that luminance. On failure `out` is cleared — half a frame from a previous attempt is worse than an empty one.

```cpp
dmr::Image frame;
switch (dmr::loadImage("frame.jpg", frame, dmr::LoadAs::Gray)) {
    case dmr::LoadStatus::Ok:         break;
    case dmr::LoadStatus::NotFound:   /* no such file */ break;
    case dmr::LoadStatus::Unreadable: /* the file exists but is not an image */ break;
}
```

> **Path encoding.** `loadImage` handles the system path encoding itself — a directory with a non-ASCII (e.g. Cyrillic) name does not break reading. For your own path handling the header provides `toPath(const std::string&)`, `fromPath(const std::filesystem::path&)` (the reverse conversion) and `printablePath(...)` — the path in UTF-8, for logging.

## Geometry

```cpp
struct Point {
    float x = 0.0f;
    float y = 0.0f;
};

struct Box {
    int x = 0, y = 0, width = 0, height = 0;
    bool empty() const;
};

struct Quad {
    Point corner[4];
};
```

`Point` is fractional: symbol corners are found with sub-module precision, and rounding to integers would lose exactly that. `Box` is the candidate rectangle in the source frame; `Quad` gives its four corners more precisely than a rectangle can: on a conveyor the symbol is captured at an angle.

```cpp
for (const dmr::Point& p : c.corners.corner)
    drawTo(p.x, p.y);
```

> **Corner order.** `Quad` corners go around the symbol, and index 3 holds the one the **detector** took for the corner of the solid L-shaped finder — a decision made from edge density before any reading. The final symbol rotation is chosen later and may differ from it. `corner[3]` is fine for drawing overlays on the frame, but not for drawing conclusions about the symbol's content.

## Settings

The defaults are not arbitrary — they are the result of testing on a large set of frames. Start with a preset rather than individual fields — the preset name already tells which scenario it is tuned for.

| Preset | Purpose | How it differs |
| --- | --- | --- |
| `Settings::stream()` | A frame stream of one label — conveyor, camera. The default | Size hint from previous frames on, size search off |
| `Settings::single()` | One-off images — a folder, manual checks | No hint; 24 symbol sizes are tried |
| `Settings::multi(n)` | Multiple codes in one frame | `stream()` with `maxCodes = n` (0 — as many as found): hint on, no size search. Every frame goes through the full search — about four times as expensive as a single read |

```cpp
auto s = dmr::Settings::stream();
s.budgetMs   = 120.0;     // 0 — no limit
s.requireGs1 = true;      // accept only GS1-structured codes
const dmr::Scanner scanner(s);
```

> **stream() vs single().** The difference is not stylistic but in speed. `single()` tries up to 24 symbol sizes when the size is not known in advance — on a frame that could not be read in the end (a failure) this is noticeably slower than without the search, although it raises the success rate by a few percent. In a frame stream of one label the size does not change from frame to frame, so the search gives no accuracy gain at all — it only costs time on every failure. That is why it is off in `stream()` and on in `single()`: for unrelated images, where you don't know the size in advance, the cost is justified.

### All fields

| Field | Default | Meaning |
| --- | --- | --- |
| `maxCodes` | 1 | How many codes to look for: 1 — one, 0 — as many as found, N — at most N |
| `requireGs1` | false | Accept only GS1-structured codes. Successful Reed-Solomon correction alone does not prove a correct read — the check also looks at the content format (AI 01, a 14-digit GTIN with a valid check digit, then AI 21) |
| `forcedRotation` | -1 | Symbol rotation, 0..3 — quarter turns clockwise; -1 — detect automatically |
| `imageLimits` | 16384 per side, 100 000 000 px | The largest frame the scanner agrees to process (`dmr::ImageLimits` from `dmr/Image.h`: `maxSide`, `maxPixels`; 0 — the hard ceiling 65535 and 2^29). A larger frame gets `Status::ImageTooLarge` at once. Pass the same limits to `loadImage()` — there they are checked against the file header before memory is allocated. A protection, not a quality setting |
| `budgetMs` | 0.0 | Time budget per frame, ms; 0 — no limit. The deadline is soft: it is checked between search stages, not inside them, so frame time may exceed the budget by the duration of the current stage |
| `timeoutMs` | 10000.0 | Safety timeout per frame, ms; 0 and anything above 60000 mean the 60 s ceiling: a frame is never processed longer. For frames from an untrusted source also set `budgetMs`. A protection against hostile frames (hatching, texture edge to edge), not a latency setting: works like `budgetMs` — the smaller of the two applies, on expiry `timedOut` is set — but does not change how the search trades CPU for latency. The C++ `loadImage()` takes only size limits, while `Scanner::scanFile()` loads and scans under one deadline; in the C ABI (`dmr_load_image_ex` → `DMR_LOAD_TIMED_OUT`) and in Python (`dmr.Image(path, settings=…)`) the deadline applies to decoding too |
| `rowParallel` | true | Split rows of image kernels among pool threads while the frame runs on a single thread. Lowers frame latency at the cost of CPU time — turn it off if the machine runs several scanners or if throughput matters more than latency |
| `maxSizeTries` | 1 | How many symbol sizes to try when the size cannot be trusted; 1 — no search |
| `warpScales` | empty | Rectification canvas scales for the last pass, pixels per module; empty — no search; values outside 1…32 are skipped. Parsed from a string such as `"7,8,10"` by `setWarpScales()` |
| `maxCandidates` | 6 | How many candidates to take from the L-pattern detector per pass |
| `readerCacheMb` | 64.0 | Memory limit, MB per frame, for reusing work; 0 — store nothing. Does not affect the result |
| `mcHintRun` | 5 | How many consecutive frames must agree on one symbol size for it to be tried first from then on; 0 — no hint |
| `maxPatternError` | 0.25 | Maximum error fraction in the function modules (L-shaped finder, timing pattern) for a result to be considered at all |
| `lpatRetryScale` | 0.8 | Repeat the L-pattern search at a finer scale as a second hypothesis; 0 — no repeat |
| `directSampling` | false | Sample module intensities directly from the source, bypassing the rectification canvas |
| `useLPatternFinder` / `useTextureFinder` | true / true | Candidate sources; turning them off is meant for comparing detectors on the same corpus |
| `collectDetails` | false | Collect a breakdown of the read or the failure into `ScanResult::details` (about 2 MB per result) |

## Diagnostics

The library does not write to the console — the log sink is passed explicitly, and without it log lines are not even built (from the environment it reads only the message language, see below):

```cpp
using LogSink = std::function<void(std::string_view line)>;

void setLogSink(LogSink sink);   // empty — turn off
void setVerbose(bool on);        // off by default
bool isVerbose();                // on AND a sink is set
std::ostream& dbg();             // output stream: to the sink, otherwise nowhere
```

```cpp
dmr::setLogSink([](std::string_view line) { std::cerr << line; });
dmr::setVerbose(true);
```

The breakdown of why a particular read succeeded or failed is separate and on demand, as a string rather than in the log. It is collected only if `Settings::collectDetails` was on during the read:

```cpp
struct ExplainOptions {
    int moduleCount     = 0;      // size given at read time; 0 — detected automatically
    int forcedRotation  = -1;     // rotation given at read time
    bool images         = false;  // save debug PNGs next to the working directory
    std::string imagePath;        // image name — for labeling debug files
};

std::string explain(const Details& details, const ExplainOptions& opt = {});
```

```cpp
auto s = dmr::Settings::stream();
s.collectDetails = true;                 // about 2 MB per result
const dmr::ScanResult r = dmr::Scanner(s).scan(frame);
if (r.details) std::cerr << dmr::explain(*r.details);
```

> **explain() does not deliver a verdict.** The frame status has already been set by the scanner. When a symbol is found but not read, there is nothing to break down — so the crop is rectified and decoded again to give the failure an explanation, which costs about as much as reading the frame itself.

### Message language

Human-readable text — the license state (`status().message`), error messages, the debug log — is in Russian or English. By default the language comes from the `LIBSCANNER_LANG` environment variable (`ru` or `en`); without it, from the system language: a Russian system gives Russian, any other (including the `C` locale in a container) gives English. Machine-readable fields and codes are not translated.

```cpp
bool setMessageLanguage(std::string_view lang);   // "ru" or "en"; otherwise false
std::string_view messageLanguage();               // "ru" or "en"
```

```cpp
dmr::setMessageLanguage("en");   // for the whole process
```

## Library version

```cpp
#define DMR_VERSION_MAJOR 1
#define DMR_VERSION_MINOR 1
#define DMR_VERSION_PATCH 3
#define DMR_VERSION_STRING "1.1.3"

#define DMR_VERSION_AT(ma, mi, pa) ((ma) * 10000 + (mi) * 100 + (pa))
#define DMR_VERSION DMR_VERSION_AT(DMR_VERSION_MAJOR, DMR_VERSION_MINOR, DMR_VERSION_PATCH)

namespace dmr { std::string version(); }
```

The macros describe the header you compiled against; `dmr::version()` describes the library you linked against. They can diverge: the library is installed into a prefix and lives there longer than whoever built against it remembers.

```cpp
#if DMR_VERSION >= DMR_VERSION_AT(1, 1, 0)
    // code for header 1.1.0 and newer
#endif
```

## License

The scanner reads frames while the trial period (one month from the first run on the machine, no network or registration needed) or a license is in effect. Otherwise `Scanner::scan()` immediately returns `Status::Unlicensed` without processing the frame. The license is bound to the hardware (motherboard, CPU, system disk), not to the OS installation.

```cpp
#include <dmr/License.h>

const dmr::LicenseStatus s = dmr::license::status();
if (!s.canScan()) show(s.message);   // "The trial period has ended. A license is required"

dmr::LicenseResult r = dmr::license::activate(keyFromUser);   // "DMR-XXXXX-XXXXX-XXXXX-XXXXX"
if (!r.ok) show(r.message);
```

### Key file license.key

Instead of calling `activate()` from your program, put the key into a text file `license.key`. The library looks for it, first match wins:

1. next to the module that contains the library: `dmr_c.dll` / `libdmr_c.so` for the C ABI and Python (`dmr/_lib/`), the program itself for static `libdmr.a`;
2. next to the program's executable.

The current directory and environment variables are not searched. Format: the first line that is not empty and not a `#` comment is the key, as issued — `DMR-XXXXX-XXXXX-XXXXX-XXXXX` (case, spaces and dashes do not matter; a UTF-8 BOM is fine; files over 4 KB are ignored). The file is read when the library starts (the first `Scanner` or `license::` call — this call waits for the server once) and again by the background check about every hour, so a key added while the program runs is picked up within an hour. A working license is not replaced by a file with a different key; a key released with `deactivate()` is not activated again from the file. If the key is rejected, `status().message` says so.

### LicenseState

| Value | Meaning |
| --- | --- |
| `Trial` | Trial period in progress |
| `Active` | License is in effect |
| `RefreshDue` | In effect, but there has been no contact with the server for a long time; auto-check retries hourly |
| `TrialExpired` | Trial period over, no license |
| `Expired` | The paid license term has ended; a renewal in your account is picked up by the auto-check |
| `NetworkRequired` | Cannot continue without contacting the server; as soon as the server responds, the auto-check restores the license |
| `WrongMachine` | The license was issued to a different machine |
| `Invalid` | The license record fails signature verification |

### LicenseStatus

| Field | Meaning |
| --- | --- |
| `state` | `LicenseState` |
| `canScan()` | Whether the scanner reads right now — true for `Trial`, `Active` or `RefreshDue` |
| `validUntil` | End of the trial period or of the paid term, Unix seconds UTC |
| `refreshAfter` | When the token is considered stale and the license moves to RefreshDue; 0 — never goes stale |
| `offlineUntil` | Beyond this time the license does not work without contacting the server; 0 — no limit |
| `daysLeft` | Whole days until the nearest of the limits above; 0 — limit passed |
| `licenseId` / `activationId` | IDs of the license and of the specific activation |
| `offlineMode` | `limited \| extended \| full \| instances`; empty without a license |
| `clockRollback` | The system clock is behind a time the machine has already seen — rolling back the clock does not extend the term |
| `message` | The state in words, for display to the user — in the message language (below) |

### Activation: online and offline

Online — a key from your account; the machine contacts the license server itself:

```cpp
dmr::LicenseResult r = dmr::license::activate("DMR-XXXXX-XXXXX-XXXXX-XXXXX");
```

Offline — for a machine without internet access: the request file is carried to a machine with network access and uploaded to your account, which returns `license.lic`:

```cpp
dmr::license::writeActivationRequest("request.json");   // → upload to your account, get license.lic
dmr::license::importLicenseFile("license.lic");          // the same call renews: the new file replaces the old one
```

A license activated online checks in with the server once a day in a background thread — refreshing the token and picking up revocation and term renewal. You don't need to call anything for this, and reading a frame never waits for the network; if the server is unreachable, it retries in an hour, and the license keeps working until the offline period runs out.

### Deactivation and other functions

```cpp
namespace dmr::license {
    void configure(const LicenseOptions& options);   // before the first network call; optional
    LicenseStatus status();
    LicenseResult activate(const std::string& licenseKey);
    LicenseResult refresh();                                    // check now, without waiting a day
    LicenseResult deactivate(const std::string& reason = {});    // the receipt is sent to the server
    LicenseResult deactivateToFile(const std::string& receiptPath, const std::string& reason = {});
    LicenseResult writeActivationRequest(const std::string& path);
    LicenseResult importLicenseFile(const std::string& path);
    std::string machineFingerprint();                           // for support requests
}
```

To move to another machine, call `deactivate()` on the old one: the seat is released on the server with a receipt signed by that machine's secret. Without network access, use `deactivateToFile()`: the receipt is written to a file that can be sent from any machine. All functions are thread-safe; functions that use the network block the caller until a response arrives or `LicenseOptions::timeoutMs` expires (15000 ms by default).

Every license server response is bound to its request: the library sends a random nonce, the server returns it in the signed response, and a previously recorded response will not be accepted again. The seat release receipt is also single-use — it carries the number from the latest server response received, so the server will not accept a receipt from a restored copy of the machine's old state. The server issues the secret for signing receipts only on the machine's first activation. For licenses with full autonomy (`full`) releasing a seat consumes the transfer limit; once it is exhausted, transfers are handled by support. A seat of a license can be released by yourself at most twice in 30 days in the limited mode and at most once in the extended mode; further transfers are handled by support.

> **Activation key.** The activation key for `activate()` is issued in your account after you purchase a plan in the [catalog](https://libscanner.com/en/).

### Containers: Docker, Kubernetes

Since 1.1, in a container the library runs under an *instance* license: pass the key in the`DMR_LICENSE_KEY` environment variable or as a secret — the file`/run/secrets/license.key` (the variable is checked first, then the secret, then the key file next to the library and the program). Nothing to activate or release: an instance takes a seat at start, reports to the license server every 30 minutes in the background and frees the seat when the program exits. There is no trial without a key in a container — get a container trial key (2 instances, 30 days) in your account. A machine license key does not activate in a container.[More on instance licenses](https://libscanner.com/en/articles/library-license-docker-kubernetes/).

Each process is a separate instance. If a program starts worker processes with fork after the library is loaded (gunicorn with `--preload`, `multiprocessing`, uWSGI without `lazy-apps`), each worker takes its own seat on its first scan, and a master process that does not scan itself frees its seat within 30 minutes. You need as many seats as processes running at the same time. A process that ends without a normal exit (`os._exit`, `kill -9`) frees its seat after an hour.

An instance license cannot be activated with a file: an instance needs a connection to the license server and works for 7 days after its last report without one. An ordinary machine without internet (a machine license) can be activated with a file for the whole paid term: when uploading the request in your account, tick “Machine without internet — work the whole term offline”.

## C ABI

The same library behind a flat C99 interface — header `dmr/dmr_c.h`, library`dmr_c.dll` / `libdmr_c.so` (how to link it —Installation). Use it from C, from MSVC and from any language that can call C functions (C#, Go, Delphi, Rust…). The rules of the boundary:

- Only plain C types cross it: integers, `double`, pointers to buffers of known size, enumerations as `int` and opaque handles. A C++ exception never crosses it — an internal failure becomes `NULL` or an error code.
- Ownership: everything a function *returns* (a handle, a string) belongs to the caller and has its own `*_free` function (`dmr_image_free`,`dmr_scan_result_free`, `dmr_free_string`; scanner — `dmr_scanner_destroy`). Pointers from accessors (`dmr_scan_result_code_text` and the like) live as long as the object they came from and are not freed.
- `dmr_settings_t` starts with `struct_size` and the `abi_tag` marker: the caller sets both **before** applying a preset — in C simply `dmr_settings_t s = DMR_SETTINGS_INIT;`, in C++ `dmr_settings_prepare(&s)`. A preset writes no further than `struct_size`; fields the caller does not know (a newer library) keep the defaults. A foreign marker or an out-of-range size is rejected: the preset returns 0, `dmr_scanner_create` returns `NULL`. A program built with an ABI 1.x or 2.0 header (dmr before 1.0.8) must be rebuilt.
- The decoded text keeps the GS separator as the byte `0x1D` (unlike the`dmr` tool, which prints `<GS>`) and may contain a zero byte — take the length from `dmr_scan_result_code_text_len`, not `strlen()`.
- Paths are in the process's system code page, like `argv` (on Windows this is not UTF-8 unless the process code page is set to UTF-8).
- Status values are the same as `dmr::Status` (see “Scan result”), plus`DMR_STATUS_INTERNAL_ERROR = -1` for a failure of the C layer itself.`dmr_scanner_scan` returns `NULL` only on an internal error; “no code” is a result with `DMR_STATUS_NOT_FOUND`.
- License functions return the same JSON as `dmr --license … --json` (see “Command line”), one contract for the shell, the C ABI and Python.

### Complete example: read every code from a file

```cpp
#include <dmr/dmr_c.h>
#include <stdio.h>

/* Read every code from an image file: 0 — read, 1 — none, 2 — error. */
int main(int argc, char** argv) {
    if (argc < 2) return 2;

    dmr_settings_t settings = DMR_SETTINGS_INIT;   /* size and marker — before the preset */
    dmr_settings_multi(&settings, 0);         /* all codes in the image */
    settings.mc_hint_run    = 0;              /* a single file: no hint from previous frames, */
    settings.max_size_tries = 24;             /* all sizes — like single() */

    dmr_image_t* image = NULL;
    if (dmr_load_image_ex(argv[1], DMR_LOAD_GRAY, &settings, &image) != DMR_LOAD_OK)
        return 2;                             /* no such file, not an image, too large */

    dmr_scanner_t* scanner = dmr_scanner_create(&settings);
    if (!scanner) { dmr_image_free(image); return 2; }

    dmr_image_view_t view = dmr_image_view(image);
    dmr_scan_result_t* r = dmr_scanner_scan(scanner, &view, 0);   /* 0 — size auto */
    int rc = 2;
    if (r) {                                  /* NULL — internal error */
        dmr_status_t st = dmr_scan_result_status(r);
        if (st == DMR_STATUS_OK) {
            for (int i = 0; i < dmr_scan_result_code_count(r); ++i) {
                /* the text may contain 0x1D (GS) and even 0x00 — use the length, not strlen() */
                fwrite(dmr_scan_result_code_text(r, i), 1, dmr_scan_result_code_text_len(r, i), stdout);
                putchar('\n');
            }
            rc = 0;
        } else if (st == DMR_STATUS_NOT_FOUND || st == DMR_STATUS_NOT_DECODED) {
            rc = 1;
        } else if (st == DMR_STATUS_UNLICENSED) {
            char* why = dmr_license_status_json();    /* {"state":"trial_expired",...} */
            fprintf(stderr, "%s\n", why ? why : "unlicensed");
            dmr_free_string(why);
        }
        dmr_scan_result_free(r);
    }
    dmr_scanner_destroy(scanner);
    dmr_image_free(image);
    return rc;
}
```

On Linux: `cc main.c -o read $(pkg-config --cflags --libs dmr_c)`, run with`LD_LIBRARY_PATH=/path/to/unpacked/lib ./read label.png`. On a code from a Chestny ZNAK pack it prints the string with raw `0x1D` bytes between the elements.

### Reference

Every declaration of `dmr_c.h` (ABI 3.1, library 1.1.3); comments shortened — the full ones are in the header itself.

```cpp
/* ── versions ── */
#define DMR_C_ABI_VERSION_MAJOR 3
#define DMR_C_ABI_VERSION_MINOR 0
size_t dmr_c_abi_version(char* buf, size_t buf_size);   /* "3.1" */
size_t dmr_version(char* buf, size_t buf_size);         /* library version, "1.1.3" */

/* ── frame ── */
typedef enum { DMR_PIXEL_GRAY8 = 0, DMR_PIXEL_BGR8 = 1, DMR_PIXEL_RGB8 = 2,
               DMR_PIXEL_BGRA8 = 3, DMR_PIXEL_RGBA8 = 4 } dmr_pixel_format_t;
typedef struct {
    const uint8_t*     data;     /* caller-owned, alive for the whole scan call */
    int                width;
    int                height;
    int                stride;   /* bytes per row; 0 — tightly packed */
    dmr_pixel_format_t format;
} dmr_image_view_t;

typedef struct dmr_image dmr_image_t;                   /* opaque, library-owned */
typedef struct dmr_settings dmr_settings_t;             /* defined below */
typedef enum { DMR_LOAD_COLOR = 0, DMR_LOAD_GRAY = 1 } dmr_load_as_t;
typedef enum { DMR_LOAD_OK = 0, DMR_LOAD_NOT_FOUND = 1, DMR_LOAD_UNREADABLE = 2,
               DMR_LOAD_TOO_LARGE = 3, DMR_LOAD_TIMED_OUT = 4,
               DMR_LOAD_INVALID_ARGUMENT = 5 } dmr_load_status_t;
dmr_load_status_t dmr_load_image(const char* path, dmr_load_as_t as, dmr_image_t** out);
dmr_load_status_t dmr_load_image_ex(const char* path, dmr_load_as_t as,
                                    const dmr_settings_t* settings,   /* NULL — defaults */
                                    dmr_image_t** out);
dmr_image_view_t  dmr_image_view(const dmr_image_t* image);
void              dmr_image_free(dmr_image_t* image);

/* ── settings: same fields and defaults as dmr::Settings ── */
struct dmr_settings {
    uint32_t struct_size;        /* sizeof(dmr_settings_t), set by the caller FIRST */
    uint32_t abi_tag;            /* DMR_SETTINGS_TAG, also before the preset */
    int    max_codes;            /* 1 — one, 0 — all, N — at most N */
    int    require_gs1;          /* 0/1 */
    int    forced_rotation;      /* -1 — auto */
    double budget_ms;            /* 0 — no limit */
    int    row_parallel;         /* 0/1 */
    int    max_size_tries;
    int    warp_scales[16];      /* DMR_MAX_WARP_SCALES */
    int    warp_scales_count;    /* values outside 1..32 are skipped */
    int    max_candidates;
    double reader_cache_mb;
    int    mc_hint_run;
    double max_pattern_error;
    double lpat_retry_scale;
    int    direct_sampling;      /* 0/1 */
    int    use_lpattern_finder;  /* 0/1 */
    int    use_texture_finder;   /* 0/1 */
    int    collect_details;      /* 0/1 */
    int     max_image_side;      /* 0 — library ceiling 65535; presets: 16384 */
    int64_t max_image_pixels;    /* 0 — ceiling 2^29; presets: 100 000 000 */
    double  timeout_ms;          /* safety timeout, presets: 10000; 0 — 60 s ceiling */
};
#define DMR_SETTINGS_TAG 0x33524D44u                   /* 'D' 'M' 'R' '3' */
#define DMR_SETTINGS_INIT { .struct_size = (uint32_t)sizeof(dmr_settings_t), .abi_tag = DMR_SETTINGS_TAG }
#define DMR_SETTINGS_MAX_SIZE 4096u
static inline void dmr_settings_prepare(dmr_settings_t* s);   /* zeroes, sets size and marker */
int dmr_settings_stream(dmr_settings_t* out);           /* 1 — filled; 0 — NULL, foreign */
int dmr_settings_single(dmr_settings_t* out);           /*   marker or size           */
int dmr_settings_multi(dmr_settings_t* out, int max_codes);

/* ── scanner ── */
typedef struct dmr_scanner dmr_scanner_t;               /* opaque */
dmr_scanner_t* dmr_scanner_create(const dmr_settings_t* settings);   /* NULL settings — stream() */
void           dmr_scanner_destroy(dmr_scanner_t* scanner);
int            dmr_scanner_module_count_hint(const dmr_scanner_t* scanner);
void           dmr_scanner_reset_stream(dmr_scanner_t* scanner);

/* ── result ── */
typedef enum { DMR_STATUS_OK = 0, DMR_STATUS_NOT_FOUND = 1, DMR_STATUS_NOT_DECODED = 2,
               DMR_STATUS_UNLICENSED = 3, DMR_STATUS_IMAGE_TOO_LARGE = 4,
               DMR_STATUS_INVALID = 5, DMR_STATUS_FAILED = 6,
               DMR_STATUS_INTERNAL_ERROR = -1 } dmr_status_t;
typedef struct dmr_scan_result dmr_scan_result_t;       /* opaque */
dmr_scan_result_t* dmr_scanner_scan(dmr_scanner_t* scanner, const dmr_image_view_t* frame,
                                    int module_count);  /* 0 — auto; NULL — internal error */
/* ABI 3.1: an image from disk and the codes in it under the scanner's single
 * deadline; the load outcome goes to *load_status (NULL — not needed) */
dmr_scan_result_t* dmr_scanner_scan_file(dmr_scanner_t* scanner, const char* path,
                                         int module_count, dmr_load_status_t* load_status);
void         dmr_scan_result_free(dmr_scan_result_t* result);
dmr_status_t dmr_scan_result_status(const dmr_scan_result_t* result);
int          dmr_scan_result_timed_out(const dmr_scan_result_t* result);
double       dmr_scan_result_elapsed_ms(const dmr_scan_result_t* result);
int          dmr_scan_result_code_count(const dmr_scan_result_t* result);
const char*  dmr_scan_result_code_text(const dmr_scan_result_t* result, int index);
size_t       dmr_scan_result_code_text_len(const dmr_scan_result_t* result, int index);
void         dmr_scan_result_code_box(const dmr_scan_result_t* result, int index,
                                      int* x, int* y, int* width, int* height);
void         dmr_scan_result_code_corners(const dmr_scan_result_t* result, int index,
                                          float corners_xy[8]);   /* x0,y0 … x3,y3 */
int          dmr_scan_result_code_module_count(const dmr_scan_result_t* result, int index);

/* ── diagnostics ── */
typedef void (*dmr_log_sink_t)(const char* line, size_t len, void* user);   /* line is not 0-terminated */
void dmr_set_log_sink(dmr_log_sink_t sink, void* user);
void dmr_set_verbose(int on);
int  dmr_is_verbose(void);

/* ── license: JSON as in "dmr --license … --json"; free with dmr_free_string, NULL — internal error ── */
void  dmr_license_configure(const char* server_url, const char* app_version,
                            int timeout_ms, int auto_check);
char* dmr_license_status_json(void);
char* dmr_license_activate_json(const char* key);
char* dmr_license_refresh_json(void);
char* dmr_license_deactivate_json(const char* reason);           /* reason may be NULL */
char* dmr_license_deactivate_to_file_json(const char* path, const char* reason);
char* dmr_license_write_activation_request_json(const char* path);
char* dmr_license_import_license_file_json(const char* path);
char* dmr_license_fingerprint_json(void);
void  dmr_free_string(char* s);
```

## Command line

The package includes, alongside the library, a ready-made command-line tool `dmr` — for quick checks without writing code: a single image, a folder, a list of paths, or a stream for an external service.

```
dmr <image> [module_count] [--verbose] [--rot 0..3] [--budget-ms N] [--codes N]
dmr --batch  <list>  [module_count] [--verbose]
dmr --folder <directory> [module_count] [--verbose]
dmr --serve  [module_count] [--verbose]
dmr --license status | activate <key> | refresh | deactivate | fingerprint [--json]
```

### Single image

The utility prints messages in the system language (English on any non-Russian system); `--lang ru|en` or the `LIBSCANNER_LANG` variable sets it explicitly (message language). The `--batch`/`--serve` lines and the `--json` output do not depend on the language.

```
$ dmr label.jpg
startup: 4.6 ms
processing: 24.9 ms
code: 0104627191145677215n5Gr,pHTGIU&<GS>93CuXU
```

One line `code:` per code; in the text GS is shown as `<GS>`, TAB as `<TAB>`, line breaks as spaces. When the budget cut the search short, a line `budget: exhausted` follows. Errors go to stderr. The exit code is the result:

| Code | Meaning |
| --- | --- |
| 0 | Code read (also when the budget cut the search short but codes were found) |
| 1 | No code found; also no such file, not a JPEG/PNG, decoding deadline exceeded |
| 2 | Symbol found but not read |
| 3 | No trial period and no license |
| 4 | Image larger than the limit |
| 5 | Invalid image description |
| 6 | Internal error |

### Batch mode and streaming

`--batch` and `--folder` run one process over the whole set of images known in advance, with results line by line on stdout: `path · exit code · milliseconds · text`, separated by TAB — one line per code, one line with empty text for an image without a code; the second column uses the codes from the table above.`--corners` adds a fifth column, `x0,y0 x1,y1 x2,y2 x3,y3`. A summary goes to stderr. Without a license the run stops with exit code 3.

`--serve` uses the same line format, but the images are not known in advance: paths arrive one at a time, one line from stdin each, and are processed immediately — the process keeps the scanner alive between requests from an external service instead of paying for initialization on each one. The result is flushed immediately (`std::flush`) without waiting for the whole input to close — this is how the demo section of this site ([/scan](https://libscanner.com/en/scan/)) runs one process for all requests instead of one process per image. After the lines of each image comes a line `#END#`, so the reader knows the answer is complete even with several codes. The process exits on the end of input.

```
$ mkfifo queue
$ dmr --serve < queue &
$ echo /path/to/image.jpg > queue
/path/to/image.jpg	0	91.2	0104627191145677215n5Gr,pHTGIU&<GS>93CuXU
```

### License: machine-readable output

All `--license` subcommands accept the `--json` flag — the same result as the human-readable output, but as a single JSON line on stdout, for scripts and admin panels:

```
$ dmr --license status --json
{"state":"trial","can_scan":true,"valid_until":1792831857,"refresh_after":0,
 "offline_until":0,"days_left":28,"license_id":"","activation_id":"",
 "offline_mode":"","clock_rollback":false,"message":"Trial period: 28 days left"}
```

The `state` field is a stable machine-readable code (`trial`, `active`, `refresh_due`, `trial_expired`, `expired`, `network_required`, `wrong_machine`, `invalid`) — part of the output format; it is not translated and its wording does not change. The `message` field is human-readable text in the message language.
