dechatter 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pedro Paulo Vezza Campos
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,241 @@
1
- # Temporary Holding Version
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.
1
+ # dechatter
2
+
3
+ dechatter finds the fastest chatter-free cut for one tool on one milling machine. It writes a
4
+ G-code program of test cuts, listens while the machine runs it, and decides from the sound
5
+ which cuts chattered. From that it either plans a finer round of cuts or reports the best
6
+ stable speeds and widths.
7
+
8
+ It runs as a widget inside [cncjs](https://cnc.js.org), entirely in the browser and recording
9
+ with that computer's microphone, or from the command line with a recording made on a phone.
10
+ The G-code is
11
+ plain Grbl dialect (`G0`, `G1`, `G4`, `M3`, `M5`), written for FluidNC and usable on Grbl and
12
+ grblHAL.
13
+
14
+ ## What it measures
15
+
16
+ Chatter depends on the machine, the holder, the cutter and how far the cutter sticks out.
17
+ Machine weight, spindle power and material cannot predict it. They only bound the search:
18
+ the speed range, the power cap and the starting chip load. The cuts are the measurement, and
19
+ a result applies to that one tool assembly. Change the stickout and you start a new session.
20
+
21
+ Each round holds chip load and axial depth constant and varies spindle speed and radial width,
22
+ one pass per combination, cutting along the front face of a block held in the vise. Feed
23
+ follows speed so the chip load stays put.
24
+
25
+ ### Comparing depths
26
+
27
+ A deep, narrow cut and a shallower, wider one can remove the same amount, and only cutting
28
+ tells which your machine prefers. List shallower depths in the wizard's Cut step (or
29
+ `other_depths_mm` in `setup.toml`) and the session continues with them once the deepest depth
30
+ is settled, deepest first. A width that was stable in a deeper cut is taken as stable in a
31
+ shallower one, so each further depth starts from those widths and only looks for how much
32
+ wider it can go. A depth is left once no cut within the power cap that would beat the best
33
+ one found keeps a fair chance of being stable. The results list the best cuts of all depths
34
+ together.
35
+
36
+ The depths run deepest first because a shallower cut leaves the face flat only above its own
37
+ depth. Planning a deeper cut on such a block is refused: mount fresh stock for it.
38
+
39
+ ## Use in cncjs
40
+
41
+ ```sh
42
+ npm install dechatter
43
+ cncjs --mount "/dechatter:$(npm root)/dechatter/web" # PowerShell or a POSIX shell
44
+ ```
45
+
46
+ The npm package is the widget as a static folder, about 30 MB. To build that folder from
47
+ source instead:
48
+
49
+ ```sh
50
+ uv tool install git+https://github.com/pedropaulovc/dechatter
51
+
52
+ dechatter widget ~/dechatter-widget
53
+ cncjs --mount /dechatter:$HOME/dechatter-widget
54
+ ```
55
+
56
+ In cncjs, open Manage Widgets, enable the Custom widget, and set its URL to `/dechatter/` in
57
+ the widget's settings. Open cncjs at `http://localhost:8000` or over HTTPS: browsers only give
58
+ a page the microphone on those. Then, in the widget:
59
+
60
+ 1. Create a session. A short wizard asks for the machine, the tool, the cut and the stock. It
61
+ shows lengths in inches when the machine is in G20 and in millimetres when it is in G21,
62
+ or with no machine connected. Its last step holds the planner's settings, which rarely
63
+ need changing. Saving from the wizard rewrites the session's setup file without comments.
64
+ Programs are always in millimetres (G21); one run on an inch machine switches it back to
65
+ G20 before it ends. A job you stop part-way leaves the machine in G21: the wizard keeps
66
+ showing inches and tells you to send G20, or you can choose to carry on in mm.
67
+ 2. Plan a round. Round 1 is a coarse grid of speeds and widths.
68
+ 3. Set the work zero at the left end of the stock, on its front face, at the top.
69
+ 4. Load the program into cncjs and press play in cncjs. The widget never starts the machine.
70
+ 5. Recording starts when the job starts and stops when it ends. The widget then shows each
71
+ pass as stable or chatter, the stability map and the best cuts so far.
72
+ 6. If your ears disagree with a verdict, change it in the table. Plan the next round and
73
+ repeat until the widget reports convergence.
74
+
75
+ Everything runs in the browser tab. The same Python that the command line uses runs there
76
+ under [Pyodide](https://pyodide.org), which `dechatter widget` downloads once and copies into
77
+ the folder, so the shop PC needs no Python and no internet. The microphone is the browser's,
78
+ on whichever computer shows cncjs, opened with echo cancellation, noise suppression and
79
+ automatic gain switched off. The widget shows its level before any cutting and warns if the
80
+ browser kept any of that processing on.
81
+
82
+ Sessions are stored in that browser (IndexedDB), per cncjs address. Export saves one as a zip
83
+ holding `setup.toml` and each round's plan, program, `recording.wav`, results and the job
84
+ timeline cncjs reported. Import loads it in another browser, and unzipped it is a session
85
+ folder the command line reads. Keep the tab open while a round runs: the recording lives in
86
+ the page until the job ends.
87
+
88
+ ### Manual spindle
89
+
90
+ If the spindle is started and set by hand, choose "me, by hand" on the wizard's first step
91
+ (`spindle = "manual"` under `[machine]` in a setup file). The program then never commands the
92
+ spindle. It stops with `M0` before each speed, with
93
+ the cutter clear of the work, and the widget (and cncjs) shows the speed to set. Set it and
94
+ press resume in cncjs. Cuts are grouped by speed, lightest first, so a round has one stop per
95
+ speed: five in round 1. The first stop is where you start the spindle, and you stop it yourself
96
+ after the program ends.
97
+
98
+ Set the speed within 5% of what is asked; the detector finds the actual speed inside that
99
+ range. The stability map is built on the requested speeds, so a dial that reads off by a
100
+ constant amount shifts the whole map by that amount.
101
+
102
+ ## Use from the command line
103
+
104
+ Without cncjs, record on a phone and run the same session by hand:
105
+
106
+ ```sh
107
+ dechatter plan al-10mm # writes al-10mm/round-01/program.nc
108
+ ```
109
+
110
+ Set the work zero at the left end of the stock, on its front face, at the top. Start one
111
+ continuous recording, run the program, stop recording after `M30`. Then:
112
+
113
+ ```sh
114
+ dechatter analyze al-10mm recording.wav # classifies each pass
115
+ dechatter plan al-10mm # next round, or "converged"
116
+ dechatter report al-10mm # stability map and best cuts so far
117
+ ```
118
+
119
+ Repeat until `plan` reports convergence. WAV, FLAC, OGG and MP3 load directly. Phone formats
120
+ such as M4A need `ffmpeg` on the path.
121
+
122
+ Round 1 is a coarse grid of speeds and widths. Later rounds are chosen from what was measured.
123
+ Every program orders its passes from the narrowest cut to the widest, starts with a light
124
+ truing pass, and tells you where the front face will end up.
125
+
126
+ ## Safety
127
+
128
+ The program looks for chatter on purpose, so later passes are heavier than earlier ones and
129
+ some of them will chatter. Feed-hold and abort when a cut gets violent. Analyze the recording
130
+ anyway: the passes that ran still count, the aborted one is marked as such, and the next
131
+ round starts by clearing the step it left on the face.
132
+
133
+ Every planned cut stays under a power cap (60% of rated spindle power by default) and inside
134
+ the material's surface-speed limit. The built-in cutting data (`dechatter materials`) is a
135
+ conservative starting point. Override `chip_load_mm` and the speed range when you know better.
136
+
137
+ ## How a pass is classified
138
+
139
+ Forced vibration sits on harmonics of the spindle rotation. Chatter is a strong tone anywhere
140
+ else. For each pass dechatter estimates the true spindle speed from the tooth-passing
141
+ harmonics, removes every spindle harmonic from the spectrum, and takes the strongest peak
142
+ left over. The pass is unstable when that peak is at least 27 dB above the median of the
143
+ remaining spectrum and at least 10 dB above the same frequency in the dwell just before the
144
+ pass, when the spindle was turning in air. The second test rejects tones the machine makes
145
+ without cutting, such as drive whine.
146
+
147
+ Passes are found in the recording by level, then matched in order to the planned passes by
148
+ how long each cut should last. A quiet pass that goes undetected is reported as missing and
149
+ does not shift the others. If matching fails, mark the cuts yourself and pass
150
+ `--segments labels.txt` (start and end seconds per pass; an Audacity label export works).
151
+
152
+ `results.json` in each round holds the verdicts and the numbers behind them. If your ears
153
+ disagree with a verdict, change it in the widget or edit it there before planning the next
154
+ round.
155
+
156
+ ### How well it works
157
+
158
+ `validation/purdue.py` scores the detector against the
159
+ [Purdue CNC cutting sound dataset](https://github.com/purduelamm/mt_cutting_dataset): 583 cuts
160
+ in steel and aluminium on a Hurco VM20i, each labelled by two operators.
161
+
162
+ | Operators say | Cuts | Detector agrees |
163
+ |---|---|---|
164
+ | chatter (both) | 169 | 142 (84%) |
165
+ | no chatter (both) | 254 | 233 (92%) |
166
+ | slight, or they disagree | 160 | not scored |
167
+
168
+ The 27 dB threshold was chosen on this same data, so these numbers are a fit and the detector
169
+ has not been scored on a second dataset. Most of those cuts last about a second; dechatter's
170
+ own passes are longer, which gives a finer spectrum. Removing the spindle harmonics matters:
171
+ without that step the best achievable balanced accuracy on this data falls from 88% to 75%.
172
+
173
+ It has not yet been run on a real machine end to end. The planner and the audio pipeline are
174
+ tested against a simulated machine with stability lobes (`tests/synth.py`), where a session
175
+ converges in about three rounds and 27 cuts to within 10% of the true best removal rate. The
176
+ widget was driven through that same session in Chrome against cncjs 1.11.5 and a simulated
177
+ Grbl (`e2e/`), with the simulated machine's sound played into the widget in place of the
178
+ microphone. Capture from a real webcam microphone was checked separately, without cutting.
179
+
180
+ Known limits:
181
+
182
+ - A chatter tone that lands within a few hertz of a spindle harmonic is hidden. Its sidebands
183
+ usually still trip the detector, but the reported frequency is then off by the tooth-passing
184
+ frequency. This is likeliest at low speed, where the harmonics are close together.
185
+ - Flood coolant and a noisy shop raise the noise floor. Record close to the spindle.
186
+ - Variable-pitch cutters break the assumption that tooth passing is one frequency.
187
+
188
+ ## How the next round is chosen
189
+
190
+ The planner follows Karandikar et al., "Evaluation of automated stability testing in machining
191
+ through closed-loop control and Bayesian machine learning"
192
+ ([MSSP 181, 2022](https://doi.org/10.1016/j.ymssp.2022.109531)). It keeps a probability of
193
+ stability over the speed and width grid, starting from "wider is less likely to be stable".
194
+ A stable cut raises the probability of everything narrower near that speed, and an unstable
195
+ cut lowers everything wider. The next cuts are the ones with the highest expected improvement
196
+ in removal rate, and the session has converged when no cut promises 5% more.
197
+
198
+ Three things differ from the paper, which tests one cut at a time under closed-loop control:
199
+
200
+ - A round is a batch with no feedback between cuts. Later cuts in a batch assume the earlier
201
+ ones pass, so widths can ramp at one speed, but each must also be at least 50% likely to be
202
+ stable on measured data alone. A cut that builds on no earlier cut in the batch must be at
203
+ least 80% likely.
204
+ - The paper does not give its likelihood. Here each speed has a distribution over its
205
+ stability limit, each verdict is assumed wrong 5% of the time, and evidence fades with
206
+ distance in speed (1.5% of the speed, one standard deviation).
207
+ - Chatter frequency is used. A chatter tone at `f` Hz predicts stable pockets where tooth
208
+ passing divides it, at `60 f / (flutes k)` rpm. Those speeds get partial credit for the
209
+ width that was stable where the chatter was heard, so the planner tries them.
210
+
211
+ The stock runs out before the search does on small blocks. `plan` then asks for fresh stock;
212
+ mount it, reset the face to `Y0` and run `dechatter plan --new-stock`.
213
+
214
+ ## Development
215
+
216
+ ```sh
217
+ uv sync
218
+ uv run pytest
219
+ uv run ruff check .
220
+ uv run validation/purdue.py ~/purdue-cache # downloads about 370 MB once
221
+ ```
222
+
223
+ `e2e/` runs real cncjs against a simulated Grbl inside WSL, for driving the widget without a
224
+ machine. See `e2e/README.md`.
225
+
226
+ To release, set the same version in `pyproject.toml` and `package.json`, merge to `main`, and
227
+ push a tag `vX.Y.Z` on that commit. The `release` workflow tests on Linux and Windows, builds
228
+ the widget once and publishes that build to npm. npm trusts the workflow itself, so no token
229
+ is stored; version 0.1.0 was published by hand, because that trust can only be registered
230
+ for a package that exists.
231
+
232
+ ## Related work
233
+
234
+ [Harmonizer](https://taptest.co/harmonizer) and
235
+ [ChatterPro Mobile](https://www.malinc.com/products/chatterpro-mobile/) are commercial phone
236
+ apps that recommend a speed from the sound of a cut. The test method, constant chip load with
237
+ stepped speed and width, is described in CNCCookbook's
238
+ [chatter article](https://www.cnccookbook.com/chatter-in-machining-milling-lathe-vibration/).
239
+
240
+ MIT licensed. The npm package also carries Pyodide, CPython, NumPy and SciPy under their own
241
+ licences; see `THIRD_PARTY_NOTICES.md`.
@@ -0,0 +1,24 @@
1
+ # Third-party software in the npm package
2
+
3
+ dechatter's own code is MIT licensed (see `LICENSE`). The npm package also redistributes the
4
+ software below in `web/pyodide/`, so that the widget runs in a browser tab without a server.
5
+ The exact versions are the ones pinned in `src/dechatter/export.py` and listed in
6
+ `web/pyodide/pyodide-lock.json`.
7
+
8
+ | Files | Software | Licence | Source |
9
+ | --- | --- | --- | --- |
10
+ | `pyodide.js`, `pyodide.asm.js`, `pyodide.asm.wasm`, `pyodide-lock.json` | Pyodide | MPL-2.0 | https://github.com/pyodide/pyodide |
11
+ | `python_stdlib.zip`, and the interpreter inside `pyodide.asm.wasm` | CPython | PSF-2.0 | https://github.com/python/cpython |
12
+ | `numpy-*.whl` | NumPy | BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0, as the wheel declares | https://github.com/numpy/numpy |
13
+ | `scipy-*.whl` | SciPy | BSD-3-Clause, with bundled components under their own licences | https://github.com/scipy/scipy |
14
+
15
+ Two of the files are renamed copies: `pyodide.js` and `pyodide.asm.js` are Pyodide's
16
+ `pyodide.mjs` and `pyodide.asm.mjs`, and the one reference between them is renamed to match,
17
+ because cncjs serves `.mjs` files with a type browsers refuse to run. Nothing else is changed.
18
+
19
+ The Pyodide runtime also contains the libraries it is built with; their licence texts are in
20
+ the Pyodide repository. Each wheel is a zip archive and carries the licence texts of its
21
+ project and of what it bundles: in `*.dist-info/` and beside the bundled components.
22
+
23
+ The source code for the Pyodide files, which the MPL-2.0 asks to be made available, is at the
24
+ repository above under the tag of the pinned version.
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
- {
2
- "name": "dechatter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dechatter",
3
+ "version": "0.1.0",
4
+ "description": "CNCjs custom widget that finds chatter-free milling speeds, widths and depths from test cuts heard through the microphone.",
5
+ "keywords": [
6
+ "cncjs",
7
+ "cnc",
8
+ "chatter",
9
+ "milling",
10
+ "stability-lobes",
11
+ "grbl",
12
+ "widget"
13
+ ],
14
+ "license": "MIT",
15
+ "author": "Pedro Paulo Vezza Campos <pedro@vezza.com.br>",
16
+ "homepage": "https://github.com/pedropaulovc/dechatter#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/pedropaulovc/dechatter/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/pedropaulovc/dechatter.git"
23
+ },
24
+ "exports": {
25
+ "./index.html": "./web/index.html",
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "web",
30
+ "THIRD_PARTY_NOTICES.md"
31
+ ],
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "build": "node .github/build_widget.mjs",
37
+ "prepack": "npm run build"
38
+ }
39
+ }
Binary file
package/web/engine.js ADDED
@@ -0,0 +1,92 @@
1
+ // Web worker: dechatter's Python running in Pyodide. Sessions live in a filesystem that is
2
+ // persisted to IndexedDB, so they survive reloads and browser restarts.
3
+
4
+ import { loadPyodide } from './pyodide/pyodide.js';
5
+
6
+ const ROOT = '/sessions';
7
+ // Calls that change files; the filesystem is flushed to IndexedDB after each of them.
8
+ const WRITES = new Set(['create', 'save_setup', 'plan', 'record_stop', 'analyze', 'set_verdict', 'import_zip']);
9
+
10
+ let pyodide;
11
+ let call;
12
+
13
+ // cncjs serves .wasm as application/octet-stream, which streaming compilation refuses.
14
+ // Relabel those responses; the bytes still stream straight through.
15
+ const plainFetch = self.fetch.bind(self);
16
+ self.fetch = async (input, init) => {
17
+ const response = await plainFetch(input, init);
18
+ const url = typeof input === 'string' ? input : (input.url ?? String(input));
19
+ if (!response.ok || !url.split('?')[0].endsWith('.wasm')) {
20
+ return response;
21
+ }
22
+ return new Response(response.body, { status: response.status, headers: { 'Content-Type': 'application/wasm' } });
23
+ };
24
+
25
+ function sync(populate) {
26
+ return new Promise((resolve, reject) => {
27
+ pyodide.FS.syncfs(populate, (err) => (err ? reject(err) : resolve()));
28
+ });
29
+ }
30
+
31
+ async function boot() {
32
+ postMessage({ boot: 'Loading Python' });
33
+ pyodide = await loadPyodide({ indexURL: new URL('./pyodide/', import.meta.url).href });
34
+ postMessage({ boot: 'Loading numpy and scipy' });
35
+ await pyodide.loadPackage(['numpy', 'scipy']);
36
+ const source = await fetch(new URL('./dechatter.zip', import.meta.url));
37
+ if (!source.ok) {
38
+ throw new Error(`cannot load dechatter.zip: ${source.status}`);
39
+ }
40
+ pyodide.unpackArchive(await source.arrayBuffer(), 'zip');
41
+ pyodide.FS.mkdirTree(ROOT);
42
+ pyodide.FS.mount(pyodide.FS.filesystems.IDBFS, {}, ROOT);
43
+ await sync(true);
44
+ call = pyodide.runPython(`
45
+ import logging
46
+ from pathlib import Path
47
+ from dechatter import browser
48
+
49
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
50
+ _sessions = browser.Sessions(Path("${ROOT}"))
51
+
52
+ def _call(method, *args):
53
+ return browser.call(_sessions, method, *args)
54
+
55
+ _call
56
+ `);
57
+ }
58
+
59
+ async function handle({ method, args }) {
60
+ const converted = args.map((arg) => (ArrayBuffer.isView(arg) ? pyodide.toPy(arg) : arg));
61
+ const result = call(method, ...converted);
62
+ for (const arg of converted) {
63
+ arg?.destroy?.();
64
+ }
65
+ if (typeof result !== 'string') {
66
+ const bytes = result.toJs();
67
+ result.destroy();
68
+ return { ok: bytes };
69
+ }
70
+ const reply = JSON.parse(result);
71
+ if ('ok' in reply && WRITES.has(method)) {
72
+ await sync(false);
73
+ }
74
+ return reply;
75
+ }
76
+
77
+ const ready = boot().then(
78
+ () => postMessage({ boot: null }),
79
+ (err) => {
80
+ postMessage({ boot: null, fatal: `dechatter could not start: ${err.message ?? err}` });
81
+ throw err;
82
+ },
83
+ );
84
+
85
+ onmessage = async ({ data }) => {
86
+ try {
87
+ await ready;
88
+ postMessage({ id: data.id, ...(await handle(data)) });
89
+ } catch (err) {
90
+ postMessage({ id: data.id, error: `${err.message ?? err}` });
91
+ }
92
+ };
package/web/index.html ADDED
@@ -0,0 +1,81 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>dechatter</title>
7
+ <link rel="stylesheet" href="widget.css">
8
+ </head>
9
+ <body>
10
+ <p id="error" class="error" hidden></p>
11
+ <p id="boot" class="muted">Starting.</p>
12
+
13
+ <div id="main" hidden>
14
+ <header>
15
+ <select id="sessions" aria-label="Session"></select>
16
+ <button id="new-session">New</button>
17
+ <button id="edit-setup" disabled>Setup</button>
18
+ <button id="export" disabled>Export</button>
19
+ <button id="import">Import</button>
20
+ <input id="import-file" type="file" accept=".zip" hidden>
21
+ <div id="summary" class="muted"></div>
22
+ </header>
23
+
24
+ <dl id="links">
25
+ <dt>cncjs</dt>
26
+ <dd id="cncjs">connecting</dd>
27
+ <dt>Microphone</dt>
28
+ <dd>
29
+ <button id="enable-mic" hidden>Enable microphone</button>
30
+ <select id="device" aria-label="Microphone" hidden></select>
31
+ <meter id="level" min="-100" max="0" low="-70" high="-6" optimum="-30" value="-100" hidden></meter>
32
+ <span id="level-db" class="muted"></span>
33
+ </dd>
34
+ </dl>
35
+ <p id="mic-warning" class="error" hidden></p>
36
+
37
+ <section id="setup" hidden>
38
+ <h2 id="setup-title"></h2>
39
+ <p id="setup-hint" class="muted"></p>
40
+ <form id="setup-form"></form>
41
+ <p class="wizard-buttons">
42
+ <button id="setup-back" type="button">Back</button>
43
+ <button id="setup-next" class="primary" type="submit" form="setup-form">Next</button>
44
+ <button id="cancel-setup" type="button">Cancel</button>
45
+ <span id="units" class="muted"></span>
46
+ <button id="follow-machine" type="button" hidden>Use mm instead</button>
47
+ </p>
48
+ </section>
49
+
50
+ <section id="step" hidden></section>
51
+
52
+ <section id="round" hidden>
53
+ <h2 id="round-title"></h2>
54
+ <table>
55
+ <thead>
56
+ <tr><th>#</th><th>rpm</th><th>width</th><th>feed</th><th>P</th><th>result</th></tr>
57
+ </thead>
58
+ <tbody id="passes"></tbody>
59
+ </table>
60
+ </section>
61
+
62
+ <section id="map-section" hidden>
63
+ <h2 id="map-title">Stability map</h2>
64
+ <canvas id="map" width="320" height="180"></canvas>
65
+ <p class="muted legend">
66
+ Green is likely stable, red likely chatter. Dots are stable cuts, crosses chatter.
67
+ </p>
68
+ </section>
69
+
70
+ <section id="best-section" hidden>
71
+ <h2>Best stable cuts</h2>
72
+ <table>
73
+ <thead><tr><th>rpm</th><th>width</th><th>depth</th><th>feed</th><th>cm³/min</th></tr></thead>
74
+ <tbody id="best"></tbody>
75
+ </table>
76
+ </section>
77
+ </div>
78
+
79
+ <script type="module" src="widget.js"></script>
80
+ </body>
81
+ </html>
@@ -0,0 +1,34 @@
1
+ // Audio thread: hand the microphone's samples to the page in blocks, mixed down to mono.
2
+
3
+ const BLOCK = 4096;
4
+
5
+ class Capture extends AudioWorkletProcessor {
6
+ constructor() {
7
+ super();
8
+ this.block = new Float32Array(BLOCK);
9
+ this.filled = 0;
10
+ }
11
+
12
+ process(inputs) {
13
+ const channels = inputs[0];
14
+ if (!channels.length) {
15
+ return true;
16
+ }
17
+ const frames = channels[0].length;
18
+ for (let i = 0; i < frames; i += 1) {
19
+ let sum = 0;
20
+ for (const channel of channels) {
21
+ sum += channel[i];
22
+ }
23
+ this.block[this.filled] = sum / channels.length;
24
+ this.filled += 1;
25
+ if (this.filled === BLOCK) {
26
+ this.port.postMessage(this.block.slice());
27
+ this.filled = 0;
28
+ }
29
+ }
30
+ return true;
31
+ }
32
+ }
33
+
34
+ registerProcessor('capture', Capture);
package/web/mic.js ADDED
@@ -0,0 +1,106 @@
1
+ // The browser's microphone, raw: the voice-call processing browsers apply by default
2
+ // (echo cancellation, noise suppression, automatic gain) would reshape the very spectrum the
3
+ // chatter detector reads, so it is switched off and checked.
4
+
5
+ const PROCESSING = ['echoCancellation', 'noiseSuppression', 'autoGainControl'];
6
+
7
+ export class Mic {
8
+ constructor() {
9
+ this.context = null;
10
+ this.stream = null;
11
+ this.label = '';
12
+ this.rate = 0;
13
+ this.levelDb = null;
14
+ this.processing = []; // processing the browser kept on despite being asked not to
15
+ this.chunks = null; // Float32Array blocks while recording, else null
16
+ this.frames = 0;
17
+ }
18
+
19
+ get open() {
20
+ return this.stream !== null;
21
+ }
22
+
23
+ get recording() {
24
+ return this.chunks !== null;
25
+ }
26
+
27
+ get seconds() {
28
+ return this.rate ? this.frames / this.rate : 0;
29
+ }
30
+
31
+ async devices() {
32
+ const all = await navigator.mediaDevices.enumerateDevices();
33
+ return all.filter((d) => d.kind === 'audioinput' && d.deviceId).map((d) => ({ id: d.deviceId, label: d.label }));
34
+ }
35
+
36
+ async start(deviceId) {
37
+ await this.close();
38
+ const audio = { channelCount: 1 };
39
+ for (const name of PROCESSING) {
40
+ audio[name] = false;
41
+ }
42
+ if (deviceId) {
43
+ audio.deviceId = { exact: deviceId };
44
+ }
45
+ const stream = await navigator.mediaDevices.getUserMedia({ audio });
46
+ const track = stream.getAudioTracks()[0];
47
+ const settings = track.getSettings();
48
+ const context = new AudioContext();
49
+ await context.audioWorklet.addModule(new URL('./mic-worklet.js', import.meta.url));
50
+ const capture = new AudioWorkletNode(context, 'capture');
51
+ capture.port.onmessage = ({ data }) => this.onBlock(data);
52
+ context.createMediaStreamSource(stream).connect(capture);
53
+
54
+ this.context = context;
55
+ this.stream = stream;
56
+ this.label = track.label;
57
+ this.rate = context.sampleRate;
58
+ this.processing = PROCESSING.filter((name) => settings[name] === true);
59
+ track.onended = () => this.close();
60
+ }
61
+
62
+ onBlock(block) {
63
+ let power = 0;
64
+ for (const sample of block) {
65
+ power += sample * sample;
66
+ }
67
+ this.levelDb = 10 * Math.log10(power / block.length + 1e-12);
68
+ if (this.chunks) {
69
+ this.chunks.push(block);
70
+ this.frames += block.length;
71
+ }
72
+ }
73
+
74
+ record() {
75
+ this.chunks = [];
76
+ this.frames = 0;
77
+ }
78
+
79
+ // Everything heard since record(), as one Float32Array.
80
+ finish() {
81
+ const samples = new Float32Array(this.frames);
82
+ let offset = 0;
83
+ for (const chunk of this.chunks ?? []) {
84
+ samples.set(chunk, offset);
85
+ offset += chunk.length;
86
+ }
87
+ this.chunks = null;
88
+ this.frames = 0;
89
+ return samples;
90
+ }
91
+
92
+ // Browsers may keep an audio context suspended until the user interacts with the page.
93
+ async resume() {
94
+ if (this.context?.state === 'suspended') {
95
+ await this.context.resume();
96
+ }
97
+ }
98
+
99
+ async close() {
100
+ this.stream?.getTracks().forEach((track) => track.stop());
101
+ await this.context?.close();
102
+ this.stream = null;
103
+ this.context = null;
104
+ this.levelDb = null;
105
+ }
106
+ }