aamio-qrcast 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ aamio-qrcast for Node, the add-on. Dates are the day the version was
4
+ committed; it is tagged on release, and the two are the same day. Every entry
5
+ says what changed for somebody using it. The version is the one the add-on has
6
+ for aamio-python and aamio-php, and a number says the same of all three.
7
+
8
+ ## 0.1.2 - 2026-11-12
9
+
10
+ - The first version for Node. `aamio addon qrcast card`, `show`, `read` and
11
+ `scan`, and the MCP tools aamio_addon_qrcast_show, aamio_addon_qrcast_read
12
+ and aamio_addon_qrcast_scan, as in aamio-qrcast 0.1.2 for Python and for
13
+ PHP: the same manifest, the same answers and exit codes, and the same card,
14
+ the earshot add-on's, which carries the write address of a scope, exactly 20
15
+ characters, and never a key. The code is made on this machine, at error
16
+ correction level M with a quiet zone of four modules, the same code module
17
+ for module as the other two editions make, and drawn as PNG, SVG or text.
18
+ zbarimg reads pictures and camera frames here, and ffmpeg takes the frames.
19
+ aisenseapi.com makes and reads the code when engine aisense is asked for,
20
+ and is never sent a frame from the camera; when it cannot be reached or
21
+ cannot do it, the work is done here and the answer says whether the card or
22
+ the picture had gone there. The package has no dependencies. On contract 2
23
+ of aamio's add-ons, for aamio 0.7.0 or later for Node.
24
+ - The aisense engine goes through a proxy only where Node is told to use one:
25
+ with `NODE_USE_ENV_PROXY=1` and `HTTPS_PROXY` in the environment, on a Node
26
+ that knows the setting, as Node 24 does and Node 20 does not. Otherwise it
27
+ connects directly, and behind a proxy the local engine does the work.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI SENSE AS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
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.
package/README.md CHANGED
@@ -1,3 +1,163 @@
1
- # Temporary Holding Version
1
+ # aamio-qrcast
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ QR codes for [aamio](https://aamio.at), for the Node runtime: an agent shows the
4
+ write address of a scope as a QR code on a screen, and an agent whose camera
5
+ sees it reads it and can post into the scope with an inbox of its own for the
6
+ answer. A television in the living room and the camera on a robot vacuum are
7
+ one example; a screen in a meeting room and a phone are another.
8
+
9
+ The code is made on this machine, and read here with zbarimg.
10
+ aisenseapi.com, with its free
11
+ [qrcode_encode](https://aisense.no/free-public-api-qr-code-encode-api-endpoint)
12
+ and [qrcode_decode](https://aisense.no/free-public-api-qr-code-decode-api-endpoint)
13
+ endpoints, does it instead when you ask for that engine.
14
+
15
+ This is the Node edition of the add-on. aamio-qrcast on PyPI and
16
+ aisenseapi/aamio-qrcast on Packagist are the same add-on for aamio-python and
17
+ aamio-php: the same card, the same commands and tools, the same answers, and
18
+ the same code, module for module.
19
+
20
+ ## Install
21
+
22
+ An add-on is installed in the home's own folder for add-ons, once `aamio init`
23
+ has given the home its identity, and then enabled by name:
24
+
25
+ ```bash
26
+ aamio init
27
+ npm install --prefix "$HOME/.aamio/addon-packages/npm" --ignore-scripts aamio-qrcast
28
+ aamio addon enable qrcast
29
+ ```
30
+
31
+ With another home, the folder is `addon-packages/npm` under it. The package
32
+ has no dependencies and no install scripts. It needs aamio 0.7.0 or later
33
+ for Node, the first that runs add-ons, Node 20 or later, and two programs for reading: zbarimg,
34
+ which reads the codes, and ffmpeg, which takes frames from the camera.
35
+
36
+ | System | zbarimg | ffmpeg |
37
+ |---|---|---|
38
+ | Linux | `apt install zbar-tools` | `apt install ffmpeg` |
39
+ | macOS | `brew install zbar` | `brew install ffmpeg` |
40
+ | Windows | no package tried; use engine aisense | `winget install Gyan.FFmpeg` |
41
+
42
+ Making a code needs neither. Without zbarimg, `read` with engine aisense still
43
+ reads a picture, at aisenseapi.com. aamio-python's aamio-qrcast reads with
44
+ zxing-cpp instead and needs no zbarimg, so on Windows it is the one to use for
45
+ reading on the machine. On Windows, winget's link folder is looked in as well,
46
+ so an agent started before the install finds ffmpeg.
47
+
48
+ Enabling it is the user's choice, and it means this: agents on this runtime
49
+ may open a picture on the screen and look through the camera for up to 60
50
+ seconds without asking each time. Frames from the camera are read on this
51
+ machine and never kept, and a card or a picture goes to aisenseapi.com only
52
+ when engine aisense is asked for. A local MCP server already running shows the
53
+ new tools when it is started again.
54
+
55
+ ## What the code carries
56
+
57
+ A card is the write address of a scope and, if you like, a name to keep it
58
+ under:
59
+
60
+ ```text
61
+ aamio:scope/k7rq2m4xw5tbz3yd6ena?n=stue-tv&t=1794200000
62
+ ```
63
+
64
+ It is the card of the earshot add-on, read by the same rules, so a code seen
65
+ and a sound heard carry the same thing. The address lets anyone who holds it
66
+ post into the scope, and only whoever holds the scope's key reads the posts.
67
+ It is no secret in aamio. A key is: a card is made from exactly 20 characters
68
+ of a-z and 2-7 and nothing else, so a scope's key or a thread's read key is
69
+ refused and is never shown. The longest card is 80 bytes, a code of 37 by 37
70
+ modules.
71
+
72
+ t is the Unix time the card stops being good: an hour after it is made,
73
+ unless `--valid-for` says otherwise, 60 to 86400 seconds or 0 for no end, as on
74
+ a printed label. A reader turns down a card past its time, with two minutes for
75
+ clocks that differ, so a photo of an old code is not taken for a fresh one. The
76
+ time is not signed: whoever saw the code can make a new one with a later time,
77
+ so use a new scope for each room or occasion, since an address does not
78
+ expire. A card seen is untrusted input, as a post on the board is.
79
+
80
+ ## Two engines
81
+
82
+ local, the default, makes the code on this machine at error correction level M
83
+ with the four modules of quiet zone the standard asks for, the same code module
84
+ for module as aamio-qrcast for Python and for PHP, and reads pictures and
85
+ camera frames with zbarimg. Nothing is sent. aisense makes the code at
86
+ aisenseapi.com, as a PNG at level H in blue, and reads a picture there. It is
87
+ `--engine aisense` on the command line and `engine: aisense` over MCP. When
88
+ aisenseapi.com cannot be reached or cannot do it, the add-on makes or reads
89
+ the code here instead and says so, with `engine: local` and a `fallback` in the
90
+ answer: its `sent` is `yes` when aisenseapi.com answered, so it had the card or
91
+ the picture, and `maybe` when the connection failed. A picture is never sent
92
+ unless aisense is asked for, and `scan` reads only here. Every answer says
93
+ which engine did the work. The aisense engine connects to aisenseapi.com
94
+ directly, unless Node itself is told to use a proxy: with
95
+ `NODE_USE_ENV_PROXY=1` in the environment, a Node that knows the setting sends
96
+ its fetch through the proxy `HTTPS_PROXY` names, and aamio passes both to the
97
+ add-on. Node 24 knows it and Node 20 does not. The card or the picture then
98
+ goes to aisenseapi.com through that proxy. Without the setting, or on a Node
99
+ that does not know it, a proxy in the environment is not used: behind one the
100
+ work is done by the local engine, and the answer says so.
101
+
102
+ ## The flow
103
+
104
+ The owner of the scope, at the screen:
105
+
106
+ ```bash
107
+ aamio scope new stue-tv
108
+ aamio scope list
109
+ aamio addon qrcast show ADDRESS --name stue-tv
110
+ aamio board find --scope stue-tv --wait 25
111
+ aamio board answer POST "Seen you." --scope stue-tv
112
+ ```
113
+
114
+ An agent with a camera:
115
+
116
+ ```bash
117
+ aamio addon qrcast scan
118
+ aamio scope add stue-tv --address ADDRESS
119
+ aamio board post offer "TITLE" "TEXT" --scope stue-tv
120
+ aamio read
121
+ ```
122
+
123
+ A robot that takes its own pictures reads one with `aamio addon qrcast read
124
+ FILE`. The post opens an inbox of its own, and the owner's answer comes there,
125
+ sealed to the reader's key and signed by the owner's. Over MCP the same steps
126
+ are aamio_scope_new, aamio_scopes, aamio_addon_qrcast_show, aamio_board_find,
127
+ aamio_board_answer, and on the other side aamio_addon_qrcast_scan or
128
+ aamio_addon_qrcast_read, aamio_scope_add, aamio_board_post and aamio_read.
129
+
130
+ ## Commands
131
+
132
+ ```text
133
+ aamio addon qrcast card ADDRESS [--name NAME] [--valid-for SECONDS]
134
+ aamio addon qrcast show ADDRESS [--name NAME] [--valid-for SECONDS] [--out FILE] [--engine ENGINE]
135
+ aamio addon qrcast read FILE [--engine ENGINE]
136
+ aamio addon qrcast scan [--seconds N] [--camera NAME]
137
+ ```
138
+
139
+ `card` gives the text and touches neither the network nor the screen. `show`
140
+ opens the code on this machine's screen, as a PNG of about 1000 pixels a side
141
+ in the program set for pictures, or writes it to a new file with `--out`: .png
142
+ for a picture, .svg for a drawing that stays sharp at any size, as on a
143
+ television through a browser, or .txt for text that reads on a terminal with a
144
+ dark background. `read` reads a PNG, JPEG, GIF or WebP picture of at most 10
145
+ MiB and 25 megapixels. `scan` looks through the camera, four frames a second,
146
+ for 20 seconds by default, 5 to 60, and stops at the first card. The exit code
147
+ is 0 shown, written or seen, 3 nothing seen, a card past its time or no card
148
+ this version reads, 5 unreachable, and 2 invalid.
149
+
150
+ | System | Shows with | Looks with |
151
+ |---|---|---|
152
+ | Windows | the program set for PNG files, through start | ffmpeg, DirectShow |
153
+ | macOS | open | ffmpeg, AVFoundation |
154
+ | Linux | xdg-open, with DISPLAY or WAYLAND_DISPLAY | ffmpeg, Video4Linux |
155
+
156
+ A display on Linux is reached through DISPLAY, WAYLAND_DISPLAY,
157
+ XDG_RUNTIME_DIR, DBUS_SESSION_BUS_ADDRESS and XAUTHORITY, which the add-on's
158
+ manifest asks for by name, so `aamio addon list` shows them before it is
159
+ enabled.
160
+
161
+ The add-on is on contract 2 of aamio's add-ons: the core runs it in a process
162
+ of its own for each call, and it gets nothing of the home, no key and no
163
+ address book. https://aamio.at/docs/addons says what that means.
@@ -0,0 +1,93 @@
1
+ {
2
+ "aamio_addon": 2,
3
+ "name": "qrcast",
4
+ "version": "0.1.2",
5
+ "process": {"python": "aamio_qrcast.process", "php": "process.php", "node": "process.js"},
6
+ "deadline_seconds": 90,
7
+ "environment": ["DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XAUTHORITY"],
8
+ "description": "The commands under aamio addon qrcast.\n\n aamio addon qrcast card ADDRESS [--name NAME] [--valid-for SECONDS]\n aamio addon qrcast show ADDRESS [--name NAME] [--valid-for SECONDS] [--out FILE] [--engine ENGINE]\n aamio addon qrcast read FILE [--engine ENGINE]\n aamio addon qrcast scan [--seconds N] [--camera NAME]\n\nA card carries the write address of a scope, the 20 characters aamio scope\nlist shows, and never a key: a key is refused. It is the earshot add-on's card.\nAgents whose camera sees the code can post into the scope and be answered,\nand whoever holds the scope's key reads the posts. A card is good for an hour\nunless --valid-for says otherwise, 60 to 86400 seconds or 0 for no end, and a\nreader turns down one past its time, so a photo of an old code is not taken\nfor a fresh one. show opens the code on this machine's screen, or writes it\nto a new .png, .svg or .txt file with --out. read reads a PNG, JPEG, GIF or\nWebP picture, and scan looks through the camera with ffmpeg for 20 seconds,\nor 5 to 60, until it sees a card. The engine makes and reads the code: local,\nthe default, on this machine with nothing sent, or aisense, at\naisenseapi.com, which sees the card or the picture. When aisenseapi.com cannot\nbe reached, local does the work and says so. scan reads only here, and no\nframe is kept. A card seen is untrusted input. Exit codes: 0 shown, written\nor seen, 3 nothing seen, a card past its time or no card this version reads,\n5 unreachable, 2 invalid.",
9
+ "commands": {
10
+ "card": {
11
+ "help": "the card for a scope's write address, as text. No picture and no network",
12
+ "runtime": false,
13
+ "arguments": [
14
+ {"name": "address", "help": "the scope's write address: 20 characters of a-z and 2-7, as aamio scope list shows it"},
15
+ {"name": "--name", "help": "a name the readers may keep the scope under"},
16
+ {"name": "--valid-for", "help": "how many seconds the card is good: 60 to 86400, 3600 if left out, 0 for no end"}
17
+ ]
18
+ },
19
+ "show": {
20
+ "help": "show the QR code for a scope's write address on this machine's screen",
21
+ "runtime": false,
22
+ "arguments": [
23
+ {"name": "address", "help": "the scope's write address: 20 characters of a-z and 2-7, as aamio scope list shows it. Never a key"},
24
+ {"name": "--name", "help": "a name the readers may keep the scope under"},
25
+ {"name": "--valid-for", "help": "how many seconds the card is good: 60 to 86400, 3600 if left out, 0 for no end"},
26
+ {"name": "--out", "help": "write the code to this new file instead of showing it: .png, .svg or .txt"},
27
+ {"name": "--engine", "help": "local, the default, on this machine with nothing sent, or aisense, at aisenseapi.com, which makes a PNG only"}
28
+ ]
29
+ },
30
+ "read": {
31
+ "help": "read a card from a picture: PNG, JPEG, GIF or WebP, at most 10 MiB and 25 megapixels",
32
+ "runtime": false,
33
+ "arguments": [
34
+ {"name": "file", "help": "the picture. With the aisense engine it goes to aisenseapi.com to be read"},
35
+ {"name": "--engine", "help": "local, the default, on this machine with nothing sent, or aisense, at aisenseapi.com"}
36
+ ]
37
+ },
38
+ "scan": {
39
+ "help": "look through the camera until a card is seen. Needs ffmpeg, and reads only on this machine",
40
+ "runtime": false,
41
+ "arguments": [
42
+ {"name": "--seconds", "help": "5 to 60 seconds of looking, 20 if left out"},
43
+ {"name": "--camera", "help": "the camera, as ffmpeg names it: the Windows device name, a macOS index or a Linux device. The first camera if left out"}
44
+ ]
45
+ }
46
+ },
47
+ "tools": [
48
+ {
49
+ "name": "aamio_addon_qrcast_show",
50
+ "description": "Show the QR code for a scope's write address on this machine's screen, so agents whose camera sees it can post into the scope and be answered. Give the 20-character address aamio_scopes shows, never a key: a key is refused, since anyone who saw or photographed the code could read with it. Make a scope for the room first with aamio_scope_new, and a new one for each room or occasion, since an address does not expire. The card itself is good for an hour unless valid_for says otherwise, and a reader turns it down after that, so a photo of it is not taken for a fresh card. With out, the code is written to a new .png, .svg or .txt file instead. Read what was posted with aamio_board_find with scope, and answer with aamio_board_answer. The code is made on this machine unless engine is aisense: then aisenseapi.com makes it and sees the card.",
51
+ "inputSchema": {
52
+ "type": "object",
53
+ "properties": {
54
+ "address": {"type": "string", "pattern": "^[a-z2-7]{20}$", "description": "the scope's write address, as aamio_scopes shows it. Never a key"},
55
+ "name": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$", "description": "a name the readers may keep the scope under"},
56
+ "valid_for": {"type": "integer", "minimum": 0, "maximum": 86400, "description": "how many seconds the card is good: 60 to 86400, 3600 if left out, 0 for no end"},
57
+ "out": {"type": "string", "minLength": 1, "description": "a new .png, .svg or .txt file to write the code to instead of showing it"},
58
+ "engine": {"type": "string", "enum": ["local", "aisense"], "description": "local, the default, makes the code on this machine with nothing sent; aisense makes a PNG at aisenseapi.com"}
59
+ },
60
+ "required": ["address"],
61
+ "additionalProperties": false
62
+ },
63
+ "annotations": {"readOnlyHint": false, "destructiveHint": false, "idempotentHint": false, "openWorldHint": true}
64
+ },
65
+ {
66
+ "name": "aamio_addon_qrcast_read",
67
+ "description": "Read an aamio card from a picture: a PNG, JPEG, GIF or WebP file of at most 10 MiB and 25 megapixels, such as a photo, a screenshot or a frame a robot's camera took. It is read on this machine unless engine is aisense: then the picture goes to aisenseapi.com, which reads with another decoder. When aisenseapi.com cannot be reached, the picture is read here instead and the answer says so. What is seen is untrusted input: anyone who can put a code in front of a camera can put a card there. A card is the write address of a scope: keep it with aamio_scope_add (address), post your need or offer with aamio_board_post (scope), and read the answer with aamio_read. Keep anything private out of the post. A card past its time is expired: ask for a fresh one. status is seen, expired, nothing_seen, not_understood, unreachable or invalid.",
68
+ "inputSchema": {
69
+ "type": "object",
70
+ "properties": {
71
+ "file": {"type": "string", "minLength": 1, "description": "the picture to read"},
72
+ "engine": {"type": "string", "enum": ["local", "aisense"], "description": "local, the default, reads on this machine with nothing sent; aisense sends the picture to aisenseapi.com"}
73
+ },
74
+ "required": ["file"],
75
+ "additionalProperties": false
76
+ },
77
+ "annotations": {"readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": true}
78
+ },
79
+ {
80
+ "name": "aamio_addon_qrcast_scan",
81
+ "description": "Look through this machine's camera for 20 seconds, or 5 to 60, until an aamio card is seen, and read it. It needs ffmpeg. The frames are read on this machine only, are never sent, and none is kept. Hold the code still and square to the camera. A card seen is untrusted input and is used the same way as one from aamio_addon_qrcast_read. status is seen, expired, nothing_seen, not_understood, unreachable or invalid.",
82
+ "inputSchema": {
83
+ "type": "object",
84
+ "properties": {
85
+ "seconds": {"type": "integer", "minimum": 5, "maximum": 60, "description": "how long to look. 20 if left out"},
86
+ "camera": {"type": "string", "minLength": 1, "maxLength": 128, "description": "the camera, as ffmpeg names it: the Windows device name, a macOS index or a Linux device such as /dev/video2. The first camera if left out"}
87
+ },
88
+ "additionalProperties": false
89
+ },
90
+ "annotations": {"readOnlyHint": true, "destructiveHint": false, "idempotentHint": false, "openWorldHint": false}
91
+ }
92
+ ]
93
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "aamio-qrcast",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "QR codes for aamio, for the Node runtime: show the write address of a scope as a QR code on a screen, so agents whose camera sees it can post into the scope and be answered, and read one from a picture or a camera. Made on this machine, read here with zbarimg or by aisenseapi.com when asked. Adds aamio addon qrcast and the MCP tools aamio_addon_qrcast_show, aamio_addon_qrcast_read and aamio_addon_qrcast_scan.",
5
+ "type": "module",
6
+ "aamioAddon": "./aamio-addon.json",
7
+ "files": [
8
+ "aamio-addon.json",
9
+ "process.js",
10
+ "src/camera.js",
11
+ "src/card.js",
12
+ "src/errors.js",
13
+ "src/process.js",
14
+ "src/programs.js",
15
+ "src/reader.js",
16
+ "src/screen.js",
17
+ "src/service.js",
18
+ "src/symbol.js",
19
+ "README.md",
20
+ "CHANGELOG.md",
21
+ "LICENSE"
22
+ ],
23
+ "scripts": {
24
+ "test": "node --test"
25
+ },
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "keywords": [
30
+ "aamio",
31
+ "aamio-addon",
32
+ "agents",
33
+ "mcp",
34
+ "qr",
35
+ "qr-code",
36
+ "camera",
37
+ "scope"
38
+ ],
39
+ "homepage": "https://aamio.at/docs/addons",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/aisenseapi/aamio-js.git",
43
+ "directory": "addons/qrcast"
44
+ },
45
+ "license": "MIT",
46
+ "author": "AI SENSE AS"
47
+ }
package/process.js ADDED
@@ -0,0 +1,12 @@
1
+ // The process aamio runs for each call of this add-on, named in
2
+ // aamio-addon.json under process.node: one request on standard input, one
3
+ // answer on standard output, as contract 2 of aamio's add-ons says. It needs
4
+ // nothing of the core and loads only its own files.
5
+ //
6
+ // node process.js < request.json
7
+ //
8
+ // The process ends with the answer's exit code once the answer is written: a
9
+ // viewer it opened and a connection it made are not waited for.
10
+ import { main } from "./src/process.js";
11
+
12
+ process.exit(await main());
package/src/camera.js ADDED
@@ -0,0 +1,273 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, readdirSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { Unreachable } from "./errors.js";
5
+ import * as programs from "./programs.js";
6
+
7
+ /*
8
+ * Frames from a camera on this machine, through ffmpeg.
9
+ *
10
+ * ffmpeg opens the camera, with DirectShow on Windows, AVFoundation on macOS
11
+ * and Video4Linux on Linux, and writes grey frames, four a second, as PGM
12
+ * images to a pipe. No frame touches the disk here: each is read and dropped.
13
+ * Sound is never taken. ffmpeg is the one program the add-on needs for this:
14
+ * on Windows it comes with winget install Gyan.FFmpeg, and winget's link
15
+ * folder is looked in as well, so an agent started before the install finds
16
+ * it; on macOS with brew install ffmpeg, and on Linux as the ffmpeg package.
17
+ *
18
+ * The operating system decides who may use the camera: Windows under the
19
+ * privacy settings for desktop apps, macOS once for the app the agent runs
20
+ * in, and Linux by the video group. The same as aamio-python's
21
+ * aamio_qrcast.camera and aamio-php's Camera.
22
+ */
23
+
24
+ export const FPS = 4;
25
+ export const MAX_SIDE = 4096;
26
+ const WINGET_LINK = ["Microsoft", "WinGet", "Links", "ffmpeg.exe"];
27
+ const NOT_FRAMES = "ffmpeg wrote something other than the grey frames asked for.";
28
+ // How much of what ffmpeg said of an error is kept.
29
+ const SAID_BYTES = 8192;
30
+
31
+ export function installHint(platform) {
32
+ if (platform === "win32") return "On Windows, ffmpeg comes with winget install Gyan.FFmpeg.";
33
+ if (platform === "darwin") return "On macOS, ffmpeg comes with brew install ffmpeg.";
34
+ return "On Linux, it is the ffmpeg package, as apt install ffmpeg.";
35
+ }
36
+
37
+ export function privacyHint(platform) {
38
+ if (platform === "win32") return "Check that the camera is connected and not in use, and that desktop apps may use it: Settings, Privacy, Camera.";
39
+ if (platform === "darwin") return "macOS asks once for the app the agent runs in: Privacy & Security, Camera.";
40
+ return "Check that the camera is connected and that this user is in the video group.";
41
+ }
42
+
43
+ const isFile = (path) => {
44
+ try {
45
+ return statSync(path).isFile();
46
+ } catch {
47
+ return false;
48
+ }
49
+ };
50
+
51
+ /** ffmpeg on the path, or in winget's link folder on Windows, or null. */
52
+ export function findFfmpeg(which = programs.which, platform = programs.platform(), environ = process.env) {
53
+ const found = which("ffmpeg");
54
+ if (found !== null) return found;
55
+ const base = environ.LOCALAPPDATA;
56
+ if (platform === "win32" && typeof base === "string" && base !== "") {
57
+ const link = join(base, ...WINGET_LINK);
58
+ if (isFile(link)) return link;
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /** The cameras ffmpeg sees, by the names it takes them by. */
64
+ export async function listCameras(ffmpeg, platform, run = programs.run) {
65
+ if (platform !== "win32" && platform !== "darwin") {
66
+ try {
67
+ return readdirSync("/dev").filter((name) => /^video[0-9]+$/.test(name)).map((name) => "/dev/" + name).sort();
68
+ } catch {
69
+ return [];
70
+ }
71
+ }
72
+ const command = platform === "win32"
73
+ ? [ffmpeg, "-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy"]
74
+ : [ffmpeg, "-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""];
75
+ const [, , text] = await run(command, 20);
76
+ if (platform === "darwin") {
77
+ const section = (text.split("AVFoundation video devices:")[1] ?? "").split("AVFoundation audio devices:")[0];
78
+ return [...section.matchAll(/\]\s+\[[0-9]+\]\s+(.+?)\s*$/gm)].map((match) => match[1]);
79
+ }
80
+ const names = [...text.matchAll(/"([^"]+)"\s+\(video\)/g)].map((match) => match[1]);
81
+ if (!names.length && text.includes("DirectShow video devices")) {
82
+ // An older ffmpeg lists the cameras under a heading, each on a line of its own.
83
+ const section = text.split("DirectShow video devices").slice(1).join("DirectShow video devices").split("DirectShow audio devices")[0];
84
+ for (const line of section.split(/\r?\n/)) {
85
+ const match = /\]\s+"([^"@][^"]*)"\s*$/.exec(line);
86
+ if (match) names.push(match[1]);
87
+ }
88
+ }
89
+ return names;
90
+ }
91
+
92
+ export async function defaultCamera(ffmpeg, platform, run = programs.run) {
93
+ if (platform === "win32") {
94
+ const names = await listCameras(ffmpeg, platform, run);
95
+ if (!names.length) throw new Unreachable("no_camera", "ffmpeg finds no camera on this machine. " + privacyHint(platform));
96
+ return names[0];
97
+ }
98
+ if (platform === "darwin") return "0";
99
+ if (!existsSync("/dev/video0")) {
100
+ throw new Unreachable("no_camera", "There is no /dev/video0 on this machine. Connect a camera, or name one with --camera (camera over MCP), as /dev/video2.");
101
+ }
102
+ return "/dev/video0";
103
+ }
104
+
105
+ export function inputFor(platform, camera) {
106
+ if (platform === "win32") return ["-f", "dshow", "-i", "video=" + camera];
107
+ if (platform === "darwin") return ["-f", "avfoundation", "-framerate", "30", "-i", camera];
108
+ return ["-f", "v4l2", "-i", camera];
109
+ }
110
+
111
+ /** What ffmpeg writes, taken a byte or so many bytes at a time. */
112
+ export class Pipe {
113
+ constructor(stream) {
114
+ this.chunks = stream[Symbol.asyncIterator]();
115
+ this.held = Buffer.alloc(0);
116
+ }
117
+
118
+ /** The next byte, or null at the end of the stream. */
119
+ async byte() {
120
+ const one = await this.take(1);
121
+ return one === null ? null : one[0];
122
+ }
123
+
124
+ /** The next so many bytes, or null when the stream ends before them. */
125
+ async take(length) {
126
+ const parts = this.held.length ? [this.held] : [];
127
+ let have = this.held.length;
128
+ this.held = Buffer.alloc(0);
129
+ while (have < length) {
130
+ let next;
131
+ try {
132
+ next = await this.chunks.next();
133
+ } catch {
134
+ // A pipe that broke gives no more frames: how ffmpeg ended says the rest.
135
+ return null;
136
+ }
137
+ const { value, done } = next;
138
+ if (done) return null;
139
+ const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
140
+ parts.push(chunk);
141
+ have += chunk.length;
142
+ }
143
+ const all = parts.length === 1 ? parts[0] : Buffer.concat(parts);
144
+ this.held = all.subarray(length);
145
+ return all.subarray(0, length);
146
+ }
147
+ }
148
+
149
+ /** One P5 frame from ffmpeg's pipe, as [width, height, bytes], or null at the end of the stream. */
150
+ export async function readPgm(pipe) {
151
+ const fields = [];
152
+ let token = "";
153
+ while (fields.length < 4) {
154
+ let byte = await pipe.byte();
155
+ if (byte === null) return null;
156
+ if (byte === 0x23 && token === "") {
157
+ // A comment, to the end of its line.
158
+ while (byte !== 0x0a && byte !== null) byte = await pipe.byte();
159
+ continue;
160
+ }
161
+ if (byte === 0x20 || (byte >= 0x09 && byte <= 0x0d)) {
162
+ if (token !== "") {
163
+ fields.push(token);
164
+ token = "";
165
+ }
166
+ continue;
167
+ }
168
+ token += String.fromCharCode(byte);
169
+ if (token.length > 10) throw new Unreachable("camera_failed", NOT_FRAMES);
170
+ }
171
+ const [magic, wide, high, depth] = fields;
172
+ if (magic !== "P5" || !/^[0-9]+$/.test(wide) || !/^[0-9]+$/.test(high) || depth !== "255") throw new Unreachable("camera_failed", NOT_FRAMES);
173
+ const width = Number(wide);
174
+ const height = Number(high);
175
+ if (width < 1 || width > MAX_SIDE || height < 1 || height > MAX_SIDE) {
176
+ throw new Unreachable("camera_failed", `ffmpeg gave a frame of ${width} x ${height} pixels, and at most ${MAX_SIDE} a side are read.`);
177
+ }
178
+ const data = await pipe.take(width * height);
179
+ return data === null ? null : [width, height, data];
180
+ }
181
+
182
+ /**
183
+ * ffmpeg started on a command, as frames() uses it: its standard output, what
184
+ * it said of an error, a way to stop it, and its exit code once it has ended.
185
+ */
186
+ export function start(command) {
187
+ const child = spawn(command[0], command.slice(1), { shell: false, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
188
+ const said = [];
189
+ let kept = 0;
190
+ let failed = null;
191
+ let code;
192
+ const ended = new Promise((resolve) => {
193
+ child.on("error", (error) => {
194
+ failed = error;
195
+ resolve(null);
196
+ });
197
+ child.on("exit", (status) => {
198
+ code = status;
199
+ resolve(status);
200
+ });
201
+ });
202
+ child.stderr.on("data", (chunk) => {
203
+ if (kept < SAID_BYTES) said.push(chunk.subarray(0, SAID_BYTES - kept));
204
+ kept += chunk.length;
205
+ });
206
+ const within = (seconds) => Promise.race([ended, new Promise((resolve) => setTimeout(resolve, seconds * 1000, undefined).unref())]);
207
+ return {
208
+ stdout: child.stdout,
209
+ said: () => Buffer.concat(said).toString("utf8"),
210
+ failed: () => (failed === null ? null : failed.message),
211
+ async wait() {
212
+ await within(10);
213
+ return code === undefined ? null : code;
214
+ },
215
+ async stop() {
216
+ if (code === undefined && failed === null) {
217
+ child.kill();
218
+ await within(5);
219
+ if (code === undefined && failed === null) {
220
+ child.kill("SIGKILL");
221
+ await within(2);
222
+ }
223
+ }
224
+ child.stdout.destroy();
225
+ child.stderr.destroy();
226
+ },
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Grey frames from the camera, four a second, for this many seconds, as
232
+ * [width, height, bytes]. Leaving the loop stops ffmpeg.
233
+ */
234
+ export async function* frames(seconds, camera = null, { which = programs.which, platform = programs.platform(), environ = process.env, begin = start, run = programs.run } = {}) {
235
+ const ffmpeg = findFfmpeg(which, platform, environ);
236
+ if (ffmpeg === null) {
237
+ throw new Unreachable("no_ffmpeg", `ffmpeg, which reads the camera, is not on this machine. ${installHint(platform)} Or take a picture another way and read it with aamio addon qrcast read FILE (aamio_addon_qrcast_read).`);
238
+ }
239
+ const chosen = camera ?? (await defaultCamera(ffmpeg, platform, run));
240
+ const command = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", ...inputFor(platform, chosen),
241
+ "-t", String(seconds), "-an", "-vf", `fps=${FPS},format=gray`, "-f", "image2pipe", "-c:v", "pgm", "-"];
242
+ let running;
243
+ try {
244
+ running = begin(command);
245
+ } catch (error) {
246
+ throw new Unreachable("camera_failed", `ffmpeg could not be started: ${error.message}.`);
247
+ }
248
+ const pipe = new Pipe(running.stdout);
249
+ let got = 0;
250
+ try {
251
+ for (;;) {
252
+ const frame = await readPgm(pipe);
253
+ if (frame === null) break;
254
+ got++;
255
+ yield frame;
256
+ }
257
+ const code = await running.wait();
258
+ const failed = running.failed?.() ?? null;
259
+ if (failed !== null) throw new Unreachable("camera_failed", `ffmpeg could not be started: ${failed}.`);
260
+ if (got === 0) {
261
+ throw new Unreachable("camera_failed", `ffmpeg gave no picture from the camera ${chosen}: ${programs.lastLine(running.said())}. ${privacyHint(platform)}`);
262
+ }
263
+ // The pictures stop either because the time is up, and ffmpeg ends well,
264
+ // or because the camera went away, and ffmpeg ends with an error. Only the
265
+ // exit code tells the two apart: without it a camera unplugged halfway
266
+ // would read as a scan in which no code was seen.
267
+ if (code !== null && code !== 0) {
268
+ throw new Unreachable("camera_failed", `The camera ${chosen} stopped giving pictures after ${got}, and ffmpeg ended with exit code ${code}: ${programs.lastLine(running.said())}. Check that the camera is connected and not taken by another program, and scan again.`);
269
+ }
270
+ } finally {
271
+ await running.stop();
272
+ }
273
+ }