Compare commits

..

15 Commits

Author SHA1 Message Date
jenkins
d2f4e920ff bstein: serve direct-duration digital RCT reference runs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:08:00 -06:00
jenkins
0e05c0cd38 bstein: serve passive RCT mic watch and log its numeric receipts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 13:59:48 -06:00
jenkins
2dc8a40e92 bstein: measure received speech for full selected microphone stage 2026-12-03 13:33:21 -06:00
jenkins
ec764ca66f bstein: show RCT duration selector and separate carrier from marker confidence 2026-12-03 13:14:01 -06:00
jenkins
496454fe06 bstein: acknowledge signed pitch and delay measurements 2026-12-03 13:02:40 -06:00
jenkins
7e03a67bac bstein: serve staged mic tests and authenticated numeric timing receipts 2026-12-03 13:01:22 -06:00
jenkins
8a377d2747 bstein: flag sustained RCT audio level drops separately from tone matching 2026-12-03 12:43:52 -06:00
jenkins
8113ebda75 bstein: prefer the observer worker with cached images
The previous rollout stalled resolving Docker Hub on titan-19. Static nginx uses 1 MiB. Reserve 8 MiB for it so the existing worker can accommodate the rolling overlap, preserving the existing container limits and worker eligibility.
2026-12-03 12:16:50 -06:00
jenkins
af45190bfb bstein: serve the phone sound source and 30-minute RCT microphone detector
Vendor the web assets from Lesavka a5758755. The RCT browser performs signal recognition and sends numeric observations through the existing receipt service.
2026-12-03 12:11:53 -06:00
jenkins
64d0eb42f6 bstein: publish microphone watch and selected output test
Vendor tested Lesavka observer source a1ac564e. Reuse numeric-only receipts; no backend, routing or installed relay changes. Validated Kustomize, client dry-run, 70 Node tests plus recent-level test, and isolated fake-device Chromium capture/output/cleanup.
2026-12-03 11:20:27 -06:00
jenkins
5f84adbf29 jenkins: redirect plain HTTP requests to HTTPS 2026-11-28 23:09:46 -06:00
jenkins
8e0e29b445 monitoring: detect ingress capacity loss and Jenkins outages 2026-11-28 22:50:31 -06:00
jenkins
e4cf47491c traefik: bound stalled connections and recover unhealthy ingress 2026-11-28 22:48:29 -06:00
jenkins
6285cdb4d8 storage(gitea): expand source volume to restore CI publishing 2026-11-27 08:21:57 -06:00
jenkins
43b6639516 ci: qualify explicit revision worker file reads 2026-11-14 18:09:07 -06:00
35 changed files with 1789 additions and 28 deletions

View File

@ -251,6 +251,45 @@ source restrictions, TLS and service authentication. The communications pool
retains `.4` through `.6`; its Local-policy services need a speaker on their retains `.4` through `.6`; its Local-policy services need a speaker on their
actual endpoint node. Do not restrict all pools to ingress nodes indiscriminately. actual endpoint node. Do not restrict all pools to ingress nodes indiscriminately.
The November 28 Jenkins incident was an ingress failure: Jenkins answered
`/login` locally, its PVC was only 13% full, and the controller had no restarts.
Both Traefik replicas had `OOMKilled` terminations at their former 512 MiB limit.
One stayed unready for roughly eleven hours without a liveness probe. The other
held over 6,000 HTTPS connections; all request-read and idle timeouts were disabled.
Metrics recorded periods with zero available ingress replicas.
Traefik now bounds request reads to 300 seconds and idle keep-alive connections
to 180 seconds. The read deadline includes the entire upload body: clients with
uploads longer than five minutes must use chunks or a separately configured
entrypoint. Keep response writes unlimited for streaming. Do not globally remove
read/idle deadlines to accommodate an individual application. See the
[Traefik timeout definitions](https://doc.traefik.io/traefik/v3.3/routing/entrypoints/#respondingtimeouts).
The 1 GiB container limit has a 768 MiB Go soft limit, leaving headroom for
non-runtime memory; the [Go memory limit](https://go.dev/doc/gc-guide#Memory_limit)
does not replace connection bounds or the container limit.
Startup and liveness probes use the same internal `/ping` endpoint as readiness.
Six failed ten-second liveness checks restart an unresponsive container with a
30-second termination grace, while normal rollouts retain the five-minute drain
window and keep at least one ready replica. The `atlas.ingress.health` rule group
evaluates every minute and detects total ingress loss, lost redundancy, recent
OOM restarts, sustained memory pressure and Jenkins controller unavailability.
These rules reach Alertmanager's existing silent default receiver; email routing
remains limited to the previously configured Hermes alerts.
Jenkins also has an HTTP-only ingress with `jenkins-https-redirect` middleware.
It redirects `http://ci.bstein.dev/` to HTTPS, preserving paths and query strings.
The HTTPS ingress alone does not match plain HTTP: without the separate route,
typing the hostname can return Traefik's plain-text 404 even while HTTPS is healthy.
For a repeat report, check both `http://ci.bstein.dev/` and
`https://ci.bstein.dev/login`, compare `/login` inside
the Jenkins container, then check the SSO redirect at
`https://ci.bstein.dev/securityRealm/commenceLogin`. Inspect Traefik pod termination
reasons, `/ping`, `traefik_open_connections` and memory before restarting Jenkins.
Apply recovery configuration through Git and reconcile `traefik`; verify two ready
replicas and a working public login before declaring recovery.
MetalLB uses native L2 mode, without unused FRR/BGP sidecars. There are no BGP MetalLB uses native L2 mode, without unused FRR/BGP sidecars. There are no BGP
peers or advertisements. Titan-05/06 are excluded from the speaker DaemonSet peers or advertisements. Titan-05/06 are excluded from the speaker DaemonSet
until their recovery checks pass. Remove that explicit exclusion in until their recovery checks pass. Remove that explicit exclusion in

View File

@ -40,12 +40,13 @@ items:
- --metrics.prometheus.addEntryPointsLabels=true - --metrics.prometheus.addEntryPointsLabels=true
- --metrics.prometheus.addRoutersLabels=true - --metrics.prometheus.addRoutersLabels=true
- --metrics.prometheus.addServicesLabels=true - --metrics.prometheus.addServicesLabels=true
- --entrypoints.web.transport.respondingTimeouts.readTimeout=0s # Bound stalled reads and idle connections; allow five minutes for uploads.
- --entrypoints.web.transport.respondingTimeouts.readTimeout=300s
- --entrypoints.web.transport.respondingTimeouts.writeTimeout=0s - --entrypoints.web.transport.respondingTimeouts.writeTimeout=0s
- --entrypoints.web.transport.respondingTimeouts.idleTimeout=0s - --entrypoints.web.transport.respondingTimeouts.idleTimeout=180s
- --entrypoints.websecure.transport.respondingTimeouts.readTimeout=0s - --entrypoints.websecure.transport.respondingTimeouts.readTimeout=300s
- --entrypoints.websecure.transport.respondingTimeouts.writeTimeout=0s - --entrypoints.websecure.transport.respondingTimeouts.writeTimeout=0s
- --entrypoints.websecure.transport.respondingTimeouts.idleTimeout=0s - --entrypoints.websecure.transport.respondingTimeouts.idleTimeout=180s
- --ping=true - --ping=true
- --ping.entrypoint=health - --ping.entrypoint=health
- --entrypoints.health.address=:8082 - --entrypoints.health.address=:8082
@ -58,13 +59,33 @@ items:
image: traefik:v3.3.3@sha256:19884a9d0b922b321c9cff54cbfe43f3169893041b8dd4ea6100677afaddce46 image: traefik:v3.3.3@sha256:19884a9d0b922b321c9cff54cbfe43f3169893041b8dd4ea6100677afaddce46
imagePullPolicy: IfNotPresent imagePullPolicy: IfNotPresent
name: traefik name: traefik
env:
# Leave room for socket buffers and memory outside the Go heap.
- name: GOMEMLIMIT
value: 768MiB
resources: resources:
requests: requests:
cpu: 100m cpu: 250m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi memory: 512Mi
limits:
cpu: "1"
memory: 1Gi
startupProbe:
httpGet:
path: /ping
port: health
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 30
livenessProbe:
httpGet:
path: /ping
port: health
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 6
# A wedged process cannot use the normal five-minute drain window.
terminationGracePeriodSeconds: 30
readinessProbe: readinessProbe:
httpGet: httpGet:
path: /ping path: /ping

View File

@ -0,0 +1,165 @@
// Match a pilot plus changing marker in 10 ms windows of the selected RCT input.
import {ANCHOR_HZ, MARKERS_HZ, ORDER, SYMBOL_SECONDS, STAGE_MINUTES} from './acoustic-pattern.js';
import {AcousticTiming} from './acoustic-timing.js';
import {PilotWindow} from './pilot-window.js';
// A review threshold for continuous test sound. It does not model intelligibility.
export const LEVEL_DROP_MS = 100;
const DROP_POWER_RATIO = 0.01; // 20 dB below the recently recognized reference.
export class AcousticDetector {
constructor(rate, minutes = STAGE_MINUTES.at(-1)) {
if (!STAGE_MINUTES.includes(minutes)) throw new RangeError('unsupported stage');
this.minutes = minutes;
this.rate = rate;
this.size = Math.round(0.01 * rate);
this.windowMs = 1000 * this.size / rate;
this.timing = new AcousticTiming(this.windowMs);
this.anchorSin = Math.sin(2*Math.PI*ANCHOR_HZ/rate);
this.target = Math.ceil(minutes * 60 * rate / this.size);
this.coeff = [ANCHOR_HZ, ...MARKERS_HZ].map(f => 2 * Math.cos(2 * Math.PI * f / rate));
this.q1 = new Float64Array(this.coeff.length);
this.q2 = new Float64Array(this.coeff.length);
this.count = this.energy = this.tick = this.edges = this.lastChange = 0;
this.lastMarker = this.slot = -1;
this.locked = false;
this.windows = this.bad = this.gap = this.longest = this.sequenceFaults = this.interruptions = 0;
this.faults = [];
this.recent = new PilotWindow(this.windowMs);
this.nextFrame = null;
this.referencePower = null;
this.quietWindows = this.dropCount = this.longestDropMs = 0;
this.firstDropMs = null;
this.firstUnclearMs = null;
this.haveInput = true;
this.inputMissing = false;
}
interrupt() {
this.timing.reset();
if (this.locked && this.windows < this.target) {
this.interruptions++;
this.record('observation interrupted');
this.recent.interrupt();
}
this.edges = 0;
this.slot = this.lastMarker = -1;
this.count = this.energy = 0;
this.quietWindows = 0;
this.referencePower = null;
this.haveInput = true;
this.q1.fill(0); this.q2.fill(0);
}
record(kind) {
if (this.faults.length < 64) this.faults.push({atMs: Math.round(this.windows * this.windowMs), kind});
}
detect() {
const power = this.coeff.map((c, i) => Math.max(0,
this.q1[i] ** 2 + this.q2[i] ** 2 - c * this.q1[i] * this.q2[i]));
const marker = power.indexOf(Math.max(...power.slice(1)), 1);
// Both tones must be distinguishable at room level, including against
// the optional RCT's separate 1 kHz output pulses.
const min = Math.max((0.0008 * this.size / 2) ** 2, 0.035 * this.size * this.energy);
this.carrierPresent = power[0]>=min && this.energy>0;
const runnerUp = Math.max(...power.slice(1).filter((_,i)=>i+1!==marker));
this.timingMarker = power[marker]>=min && power[marker]>=2*runnerUp ? marker-1 : -1;
if (!this.carrierPresent || power[marker] < min) return -1;
return marker - 1;
}
observeLevel(valid) {
const power = this.energy / this.size;
const quiet = this.haveInput && this.referencePower !== null &&
power <= DROP_POWER_RATIO * this.referencePower;
if (valid && this.haveInput && !quiet) {
this.referencePower = this.referencePower === null ? power :
this.referencePower + 0.05 * (power - this.referencePower);
}
this.quietWindows = quiet ? this.quietWindows + 1 : 0;
const threshold = Math.ceil(LEVEL_DROP_MS / this.windowMs);
if (this.quietWindows < threshold) return;
if (this.quietWindows === threshold) {
this.dropCount++;
this.firstDropMs ??= Math.round((this.windows - this.quietWindows) * this.windowMs);
}
this.longestDropMs = Math.max(this.longestDropMs, this.quietWindows * this.windowMs);
}
window(marker, endMs) {
this.tick++;
let valid = marker >= 0;
const dwellMs = (this.tick - this.lastChange) * this.windowMs;
if (valid && marker !== this.lastMarker) {
const pair = ORDER.findIndex((v, i) => v === marker &&
ORDER[(i + ORDER.length - 1) % ORDER.length] === this.lastMarker);
const expected = this.slot < 0 || pair === (this.slot + 1) % ORDER.length;
const onTime = Math.abs(dwellMs - 1000 * SYMBOL_SECONDS) <= 2.1 * this.windowMs;
const matched = pair >= 0 && expected && onTime;
this.edges = matched ? this.edges + 1 : 0;
if (this.locked && !matched) {
this.sequenceFaults++;
this.record('marker order or timing');
valid = false;
}
this.slot = pair;
this.lastMarker = marker;
this.lastChange = this.tick;
} else if (valid && dwellMs > 1000 * SYMBOL_SECONDS + 2.1 * this.windowMs) {
valid = false; // A frozen or replayed single symbol is audible energy too.
}
if (!this.locked) {
if (!valid) this.edges = 0;
if (this.edges < 4) return;
this.locked = true;
}
this.windows++;
this.scoredEndMs = endMs;
this.observeLevel(valid);
this.timing.marker(this.haveInput && !this.quietWindows ? this.timingMarker : -1,
this.windows*this.windowMs);
const phase = this.carrierPresent && this.haveInput && !this.quietWindows ?
Math.atan2(this.anchorSin*this.q2[0], this.q1[0]-0.5*this.coeff[0]*this.q2[0])/(2*Math.PI) : null;
this.timing.carrier(phase, this.windows*this.windowMs);
if (!valid) {
if (!this.gap) this.record('signal missing or out of sequence');
this.bad++;
this.gap++;
this.longest = Math.max(this.longest, this.gap);
if (this.gap * this.windowMs >= LEVEL_DROP_MS) {
this.firstUnclearMs ??= Math.round((this.windows - this.gap) * this.windowMs);
}
} else this.gap = 0;
this.recent.observe(valid, endMs);
}
process(samples, frame, length) {
if (this.windows >= this.target) return;
const missing = !samples || samples.length < length;
if ((this.nextFrame !== null && this.nextFrame !== frame) ||
(missing && !this.inputMissing)) this.interrupt();
this.inputMissing = missing;
this.nextFrame = frame + length;
for (let i = 0; i < length && this.windows < this.target; i++) {
if (missing && i >= (samples?.length ?? 0)) this.haveInput = false;
const x = samples?.[i] ?? 0;
this.energy += x * x;
for (let j = 0; j < this.coeff.length; j++) {
const q = x + this.coeff[j] * this.q1[j] - this.q2[j];
this.q2[j] = this.q1[j]; this.q1[j] = q;
}
if (++this.count === this.size) {
this.window(this.detect(), (frame + i + 1) * 1000 / this.rate);
this.q1.fill(0); this.q2.fill(0); this.count = this.energy = 0;
this.haveInput = true;
}
}
}
summary(nowMs) {
return {locked: this.locked, complete: this.windows >= this.target,
observedMs: this.windows * this.windowMs, windows: this.windows,
levelDrops: this.dropCount, longestLevelDropMs: this.longestDropMs,
firstLevelDropMs: this.firstDropMs, firstUnclearMs: this.firstUnclearMs,
timing:this.timing.summary(), stageMinutes: this.minutes, scoredEndMs: this.scoredEndMs ?? null,
missingWindows: this.bad, sequenceFaults: this.sequenceFaults,
missingFraction: this.windows ? this.bad / this.windows : null,
gapMaxMs: this.longest * this.windowMs, trailingGapMs: this.gap * this.windowMs,
discontinuities: this.interruptions, recent: this.recent.summary(nowMs),
firstFaults: this.faults.slice()};
}
}

View File

@ -0,0 +1,24 @@
// Every ordered pair in the repeating marker sequence occurs once. This lets
// a receiver joining mid-cycle identify position without synchronized clocks.
export const ANCHOR_HZ = 900;
export const MARKERS_HZ = [1400, 1800, 2200, 2600];
export const ORDER = [0,1,0,2,0,3,1,2,1,3,2,3];
export const SYMBOL_SECONDS = 0.1;
export const STAGE_MINUTES = Object.freeze([1, 5, 10, 15, 20, 30]);
export const TRIAL_SECONDS = STAGE_MINUTES.at(-1) * 60;
export const SOURCE_LEAD_SECONDS = 15;
export function referenceLoop(rate) {
const data = new Float32Array(Math.round(rate * SYMBOL_SECONDS * ORDER.length));
for (let i = 0; i < data.length; i++) {
const t = i / rate;
const slot = Math.min(ORDER.length - 1, Math.floor(i * ORDER.length / data.length));
const tone = MARKERS_HZ[ORDER[slot]];
const oldTone = MARKERS_HZ[ORDER[(slot + ORDER.length - 1) % ORDER.length]];
const fade = Math.min(1, Math.max(0, (t - slot * SYMBOL_SECONDS) / 0.004));
const phase = 2 * Math.PI * t;
data[i] = 0.15 * Math.sin(phase * ANCHOR_HZ) +
0.15 * (fade * Math.sin(phase * tone) + (1 - fade) * Math.sin(phase * oldTone));
}
return data;
}

View File

@ -0,0 +1,85 @@
// Relative timing of a repeating acoustic reference; no phone/RCT clock synchronization required.
import {ANCHOR_HZ, ORDER, SYMBOL_SECONDS} from './acoustic-pattern.js';
const cycleMs = ORDER.length * SYMBOL_SECONDS * 1000;
const phaseDifference = (v, period) => v - period * Math.round(v / period);
export const RATE_REVIEW_PPM = 3000;
export const SHIFT_REVIEW_MS = 40;
export class AcousticTiming {
constructor(windowMs) {
this.windowMs=windowMs;
this.blockSize=Math.ceil(199.99/windowMs);
this.rateCoverageMs=0; this.edgeCount=0;
this.maxRatePpm=0; this.maxShiftMs=0;
this.firstRateMs=null; this.firstShiftMs=null; this.basePpm=null;
this.reset();
}
reset() {
this.lastPhase=null; this.sum=0; this.count=0; this.pairs=0; this.priorBlock=null;
this.markerCandidate=-1; this.markerCount=0; this.lastMarker=-1; this.lastSeen=null;
this.markerStart=null; this.markerSlot=-1;
this.edgePhase=null; this.lastEdge=null; this.candidate=null;
}
carrier(phase, atMs) {
if (phase!==null && this.lastPhase!==null) {
const turns=phaseDifference(phase-this.lastPhase-ANCHOR_HZ*this.windowMs/1000,1);
if (Math.abs(turns)<=0.35) { this.sum+=turns; this.pairs++; }
}
this.lastPhase=phase;
if (++this.count<this.blockSize) return;
const span=this.count*this.windowMs, measured=this.pairs*this.windowMs;
const ppm=this.pairs>=Math.ceil(0.8*this.count) ? this.sum*1e9/(measured*ANCHOR_HZ) : null;
const prior=this.priorBlock;
this.priorBlock=ppm; this.count=0; this.pairs=0; this.sum=0;
if (ppm===null || prior===null || Math.abs(prior-ppm)>1500) return;
this.rateCoverageMs+=measured;
const stable=(prior+ppm)/2;
this.basePpm??=stable;
const change=Math.round(stable-this.basePpm);
if (Math.abs(change)>Math.abs(this.maxRatePpm)) this.maxRatePpm=change;
if (Math.abs(change)>=RATE_REVIEW_PPM) this.firstRateMs??=Math.max(0,Math.round(atMs-2*span));
}
marker(value, atMs) {
// Time a change only when both measured symbols agree over two windows.
if (value!==this.markerCandidate) { this.markerCandidate=value; this.markerCount=0; }
this.markerCount++;
if (value<0) return;
if (value===this.lastMarker) { this.lastSeen=atMs; return; }
if (this.markerCount<2) return;
const start=atMs-this.windowMs;
const slot=ORDER.findIndex((m,i)=>m===value && ORDER[(i+ORDER.length-1)%ORDER.length]===this.lastMarker);
const consecutive=this.markerSlot>=0 && slot===(this.markerSlot+1)%ORDER.length;
const dwell=start-this.markerStart, symbolMs=SYMBOL_SECONDS*1000;
if (consecutive && start-this.lastSeen<=2.1*this.windowMs &&
Math.abs(dwell-symbolMs)<=2.1*this.windowMs) this.edge(slot,start);
this.markerSlot=slot; this.markerStart=start; this.lastMarker=value; this.lastSeen=atMs;
}
edge(slot, atMs) {
this.edgeCount++;
const phase=atMs-slot*SYMBOL_SECONDS*1000;
if (this.lastEdge===null || atMs-this.lastEdge>=cycleMs/2) {
// Reacquisition across half a cycle is ambiguous. Start a fresh timing comparison.
this.edgePhase=phase; this.candidate=null;
}
this.lastEdge=atMs;
const shift=phaseDifference(phase-this.edgePhase,cycleMs);
if (Math.abs(shift)<SHIFT_REVIEW_MS-0.01) {
this.edgePhase+=0.2*shift; this.candidate=null; return;
}
if (this.candidate===null || Math.abs(shift-this.candidate.shift)>1.5*this.windowMs) {
this.candidate={atMs,shift,count:1}; return;
}
const c=this.candidate;
c.shift+=(shift-c.shift)/++c.count;
if (c.count<3) return;
const value=Math.round(c.shift);
if (Math.abs(value)>Math.abs(this.maxShiftMs)) this.maxShiftMs=value;
this.firstShiftMs??=Math.round(c.atMs);
this.edgePhase=phase; this.candidate=null;
}
summary() {
return {rateCoverageMs:Math.round(this.rateCoverageMs),edgeCount:this.edgeCount,
baselinePpm:this.basePpm===null?null:Math.round(this.basePpm),maxRatePpm:this.maxRatePpm,
firstRateMs:this.firstRateMs,maxShiftMs:this.maxShiftMs,firstShiftMs:this.firstShiftMs};
}
}

View File

@ -0,0 +1,124 @@
import {attachSpeech} from './speech-watch.js';
import {STAGE_MINUTES, TRIAL_SECONDS} from './acoustic-pattern.js';
const query = new URLSearchParams(location.search);
// test=digital: direct duration, no staging/unlock, for a digitally injected reference.
export const digitalTest = query.get('test') === 'digital';
export const phoneTest = query.get('test') === 'phone' || digitalTest;
const DIGITAL_MINUTES = [1, 5, 10, 15, 20, 30, 60];
const MINUTES = digitalTest ? DIGITAL_MINUTES : STAGE_MINUTES;
export const speechMode = new URLSearchParams(location.search).get('signal') !== 'tones';
const status = document.getElementById('path-state');
const detail = document.getElementById('path-detail');
const duration = document.getElementById('stage-duration');
const timing = document.getElementById('path-timing');
const requested = MINUTES.indexOf(Number(query.get('minutes')));
let stageIndex = digitalTest ? Math.max(0, requested) : 0, unlockedIndex = 0, device = null, attempt = 0;
function renderStage() {
for (const [index, option] of Array.from(duration.options).entries()) {
option.disabled = !digitalTest && index > unlockedIndex;
}
duration.selectedIndex = stageIndex;
document.getElementById('start').textContent = 'Start ' + MINUTES[stageIndex] + '-minute receiver';
}
export function selectStageInput(input) {
if (device === input) return;
device = input; if (!digitalTest) stageIndex = 0; unlockedIndex = 0; attempt++;
renderStage();
}
export function beginStage(input) {
selectStageInput(input);
unlockedIndex = stageIndex;
renderStage();
return {minutes:MINUTES[stageIndex], attempt:++attempt};
}
export async function reviewStage(run, reason, delivered) {
if (reason !== 'phone test complete' || digitalTest) return;
const ok = await delivered;
if (attempt !== run.stage.attempt) return;
if (!ok) { status.textContent = 'Stage held · Atlas receipt unavailable'; return; }
unlockedIndex = Math.min(STAGE_MINUTES.length - 1, STAGE_MINUTES.indexOf(run.stage.minutes) + 1);
renderStage();
}
const clock = ms => {
const s = Math.min(TRIAL_SECONDS, Math.floor(ms / 1000));
return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
};
export function setupPhoneMode() {
if (!phoneTest) return;
document.title = digitalTest ? 'RCT digital reference run' : 'RCT microphone path test';
document.querySelector('h1').textContent = document.title;
for (const minutes of MINUTES) duration.add(new Option(minutes+' min',String(minutes)));
document.getElementById('stage-label').hidden = false;
renderStage();
document.getElementById('local-review').hidden = !speechMode;
if (speechMode) status.title='Compare received speech to the phone phrase';
duration.onchange = () => {
if (!duration.disabled && duration.selectedIndex>=0 && (digitalTest || duration.selectedIndex<=unlockedIndex)) {
stageIndex = duration.selectedIndex;
}
renderStage();
};
document.getElementById('start').title = 'Wait for the phone signal, then measure the selected stage.';
for (const id of ['tone','tone-stop','output-status','output-report','path-link']) {
document.getElementById(id).hidden = true;
}
document.getElementById('output').closest('label').hidden = true;
status.hidden = false; status.textContent = 'Choose the Lesavka USB microphone';
}
export async function attachDetector(run, isCurrent, finish) {
if (speechMode) return attachSpeech(run,isCurrent,finish);
await run.context.audioWorklet.addModule('acoustic-worklet.js');
if (!isCurrent()) return;
const node = new AudioWorkletNode(run.context, 'acoustic-probe', {processorOptions:{minutes:run.stage.minutes}});
run.detector = node;
run.pathInterruptions = 0;
status.textContent = 'Waiting for phone signal';
detail.hidden = true; timing.hidden = true;
const listenStart = performance.now();
node.onprocessorerror = () => { if (isCurrent()) finish('detector failed'); };
node.port.onmessage = ({data}) => {
if (!isCurrent()) return;
if (data.expired) { finish('receiver deadline or lost observer'); return; }
node.port.postMessage('ack');
const now = performance.now();
const wall = Date.now();
if (data.locked && run.pathStart === undefined) {
run.pathStart = now - data.observedMs;
run.pathWall = wall - data.observedMs;
}
if (data.locked && (Math.abs(now - run.pathStart - data.observedMs) > 2000 ||
Math.abs(wall - run.pathWall - data.observedMs) > 2000)) run.clockGap = true;
const interruptions = data.discontinuities + run.pathInterruptions + Number(!!run.clockGap);
const age = data.scoredEndMs === null ? 0 : Math.max(0, run.context.currentTime * 1000 - data.scoredEndMs);
run.path = {...data, discontinuities:interruptions, observedAtMono:now - age};
if (!data.locked && now-listenStart>=30000) { finish('phone signal not acquired'); return; }
if (data.locked) {
timing.hidden = data.timing.baselinePpm===null;
timing.textContent = 'Largest pitch change · ' + (data.timing.maxRatePpm/10000).toFixed(2) +
'% · Confirmed marker timing step · ' + data.timing.maxShiftMs + ' ms';
const target = run.stage.minutes + ':00';
const label = clock(data.observedMs) + ' / ' + target;
detail.hidden = data.missingWindows === 0 && data.sequenceFaults === 0;
detail.textContent = 'Longest reference mismatch · ' + Math.round(data.gapMaxMs) + ' ms';
let hold;
if (interruptions) hold = 'Observation interrupted';
else if (data.levelDrops) hold = 'Received audio level drop · ' + Math.round(data.longestLevelDropMs) + ' ms';
else if (data.timing.firstRateMs !== null) hold = 'Received pitch changed · ' + (data.timing.maxRatePpm/10000).toFixed(2) + '%';
else if (data.timing.firstShiftMs !== null) hold = 'Relative timing shift · ' + data.timing.maxShiftMs + ' ms';
else if (data.firstUnclearMs !== null) hold = 'Reference unclear · ' + Math.round(data.gapMaxMs) + ' ms';
else if (data.complete && (data.timing.rateCoverageMs < 0.8*data.observedMs ||
data.timing.edgeCount < 0.8*data.observedMs/100)) hold = 'Insufficient timing coverage · pitch ' + Math.round(100*data.timing.rateCoverageMs/data.observedMs) +
'% · markers ' + Math.round(10000*data.timing.edgeCount/data.observedMs) + '%';
if (hold) {
status.textContent = (data.complete ? 'Stage held · ' : 'Still measuring · ') + hold + ' · ' + label;
if (data.complete) finish('stage finding');
} else if (data.complete) {
status.textContent = 'Stage complete · ' + label + ' · review before advancing';
finish('phone test complete');
} else status.textContent = 'Signal tracking · ' + label;
}
};
run.source.connect(node); node.connect(run.context.destination);
}

View File

@ -0,0 +1,35 @@
import {AcousticDetector} from './acoustic-detector.js';
class AcousticProbe extends AudioWorkletProcessor {
constructor(options) {
super();
this.detector = new AcousticDetector(sampleRate, options.processorOptions.minutes);
this.next = currentFrame;
this.deadline = currentFrame + sampleRate * (this.detector.minutes * 60 + 60);
this.ack = currentFrame;
this.credit = true;
this.stopped = false;
this.port.onmessage = ({data}) => {
if (data === 'stop') this.stopped = true;
if (data === 'ack') { this.credit = true; this.ack = currentFrame; }
};
}
process(inputs, outputs) {
if (this.stopped) return false;
if (currentFrame >= this.deadline || currentFrame - this.ack > 10 * sampleRate) {
this.port.postMessage({expired:true});
return false;
}
const size = outputs[0][0].length;
this.detector.process(inputs[0]?.[0], currentFrame, size);
if (this.credit && currentFrame >= this.next) {
const sample = this.detector.summary((currentFrame + size) * 1000 / sampleRate);
this.port.postMessage(sample);
if (sample.complete) return false;
this.next = currentFrame + sampleRate;
this.credit = false;
}
return true;
}
}
registerProcessor('acoustic-probe', AcousticProbe);

View File

@ -4,6 +4,8 @@ class Activity extends AudioWorkletProcessor {
super(); this.frames=0; this.inputFrames=0; this.zeroFrames=0; super(); this.frames=0; this.inputFrames=0; this.zeroFrames=0;
this.energy=0; this.peak=0; this.credit=true; this.next=0; this.stopped=false; this.energy=0; this.peak=0; this.credit=true; this.next=0; this.stopped=false;
this.watch=options?.processorOptions?.continuityWatch===true; this.watch=options?.processorOptions?.continuityWatch===true;
this.recent=options?.processorOptions?.recentLevels===true;
this.windowEnergy=0;this.windowFrames=0;this.windowPeak=0;
this.startedFrame=this.watch?currentFrame:0;this.lastAckFrame=this.startedFrame; this.startedFrame=this.watch?currentFrame:0;this.lastAckFrame=this.startedFrame;
this.port.onmessage=({data})=>{ this.port.onmessage=({data})=>{
if(data==='ack'){this.credit=true;if(this.watch)this.lastAckFrame=currentFrame;} if(data==='ack'){this.credit=true;if(this.watch)this.lastAckFrame=currentFrame;}
@ -25,14 +27,17 @@ class Activity extends AudioWorkletProcessor {
this.frames+=block; this.frames+=block;
if(samples) for(const value of samples) { if(samples) for(const value of samples) {
this.inputFrames++; this.energy+=value*value; this.inputFrames++; this.energy+=value*value;
this.windowFrames++;this.windowEnergy+=value*value;this.windowPeak=Math.max(this.windowPeak,Math.abs(value));
this.peak=Math.max(this.peak,Math.abs(value)); this.peak=Math.max(this.peak,Math.abs(value));
if(value===0)this.zeroFrames++; if(value===0)this.zeroFrames++;
} }
// Output is left at zero: no monitoring/playback or acoustic feedback. // Output is left at zero: no monitoring/playback or acoustic feedback.
if(this.credit && this.frames>=this.next) { if(this.credit && this.frames>=this.next) {
this.port.postMessage({inputFrames:this.inputFrames,processedFrames:this.frames, this.port.postMessage({inputFrames:this.inputFrames,processedFrames:this.frames,
exactZeroFrames:this.zeroFrames,rms:this.inputFrames ? Math.sqrt(this.energy/this.inputFrames) : 0, exactZeroFrames:this.zeroFrames,rms:this.recent ? (this.windowFrames?Math.sqrt(this.windowEnergy/this.windowFrames):0)
peak:this.peak,sampleRate}); : (this.inputFrames?Math.sqrt(this.energy/this.inputFrames):0),
peak:this.recent?this.windowPeak:this.peak,sampleRate});
this.windowFrames=0;this.windowEnergy=0;this.windowPeak=0;
this.credit=false; this.next=this.frames+sampleRate; this.credit=false; this.next=this.frames+sampleRate;
} }
return true; return true;

View File

@ -13,6 +13,15 @@ spec:
labels: {app: lesavka-av-observer} labels: {app: lesavka-av-observer}
spec: spec:
automountServiceAccountToken: false automountServiceAccountToken: false
# This worker already holds both pinned ARM64 images. Keep other workers
# eligible when it has insufficient capacity.
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- {key: kubernetes.io/hostname, operator: In, values: [titan-07]}
nodeSelector: nodeSelector:
kubernetes.io/arch: arm64 kubernetes.io/arch: arm64
node-role.kubernetes.io/worker: "true" node-role.kubernetes.io/worker: "true"
@ -33,7 +42,8 @@ spec:
readOnlyRootFilesystem: true readOnlyRootFilesystem: true
capabilities: {drop: [ALL]} capabilities: {drop: [ALL]}
resources: resources:
requests: {cpu: 10m, memory: 16Mi} # Static nginx used 1 MiB during the previous rollout.
requests: {cpu: 10m, memory: 8Mi}
limits: {cpu: 100m, memory: 64Mi} limits: {cpu: 100m, memory: 64Mi}
readinessProbe: readinessProbe:
httpGet: {path: /av-test/, port: http} httpGet: {path: /av-test/, port: http}

View File

@ -4,6 +4,8 @@
<title>A/V Test</title> <title>A/V Test</title>
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
<main><h1>A/V Test</h1> <main><h1>A/V Test</h1>
<a href="mic.html" title="Microphone-only observation and selected speaker output, with numeric reports">Audio Test</a>
<p><a href="mic.html?test=phone">Staged RCT mic test</a> · <a href="phone.html">Phone sound source</a></p>
<p>Select a camera and microphone. Quick checks report numeric metrics automatically. Watches keep metrics here for Save metrics; audio and video never upload.</p> <p>Select a camera and microphone. Quick checks report numeric metrics automatically. Watches keep metrics here for Save metrics; audio and video never upload.</p>
<div><button id="devices">Choose devices…</button> <div><button id="devices">Choose devices…</button>
<label>Video <select id="video-device"></select></label> <label>Video <select id="video-device"></select></label>

View File

@ -10,6 +10,26 @@ configMapGenerator:
files: [nginx.conf] files: [nginx.conf]
- name: lesavka-av-observer-assets - name: lesavka-av-observer-assets
files: files:
- mic-entry.js
- mic-watch.js
- watch-worklet.js
- speech-reference.flac
- speech-alignment.js
- speech-detector.js
- speech-envelope.js
- speech-watch.js
- speech-worklet.js
- acoustic-detector.js
- acoustic-pattern.js
- acoustic-watch.js
- acoustic-worklet.js
- acoustic-timing.js
- phone-source.js
- phone.html
- mic.html
- mic-observer.js
- mic-reporting.js
- mic-output.js
- index.html - index.html
- observer.js - observer.js
- local-recording.js - local-recording.js

View File

@ -2,8 +2,8 @@
// tracks or a network client; stopping it must not stop the numeric observer. // tracks or a network client; stopping it must not stop the numeric observer.
export class LocalRecording { export class LocalRecording {
constructor({Recorder=globalThis.MediaRecorder,onStatus=()=>{},onReady=()=>{}, constructor({Recorder=globalThis.MediaRecorder,onStatus=()=>{},onReady=()=>{},
maxBytes=128*1024*1024,maxMs=180000}={}) { maxBytes=128*1024*1024,maxMs=180000,audioOnly=false}={}) {
Object.assign(this,{Recorder,onStatus,onReady,maxBytes,maxMs}); Object.assign(this,{Recorder,onStatus,onReady,maxBytes,maxMs,audioOnly});
this.serial=0;this.active=null; this.serial=0;this.active=null;
} }
get supported() {return typeof this.Recorder==='function';} get supported() {return typeof this.Recorder==='function';}
@ -11,11 +11,13 @@ export class LocalRecording {
this.discard(); this.discard();
if(!this.supported){this.onStatus('Recording unavailable in this browser.');return false;} if(!this.supported){this.onStatus('Recording unavailable in this browser.');return false;}
const serial=this.serial; const serial=this.serial;
const mimeType=['video/webm;codecs=vp8,opus','video/webm','video/mp4'].find( const types=this.audioOnly?['audio/webm;codecs=opus','audio/webm','audio/mp4']:
['video/webm;codecs=vp8,opus','video/webm','video/mp4'];
const mimeType=types.find(
type=>this.Recorder.isTypeSupported(type)); type=>this.Recorder.isTypeSupported(type));
try { try {
const recorder=new this.Recorder(stream,{...(mimeType?{mimeType}:{}), const recorder=new this.Recorder(stream,{...(mimeType?{mimeType}:{}),
videoBitsPerSecond:4000000,audioBitsPerSecond:128000}); ...(this.audioOnly?{}:{videoBitsPerSecond:4000000}),audioBitsPerSecond:this.audioOnly?64000:128000});
const run={recorder,chunks:[],bytes:0,failed:false}; const run={recorder,chunks:[],bytes:0,failed:false};
this.active=run; this.active=run;
recorder.ondataavailable=({data})=>{ recorder.ondataavailable=({data})=>{
@ -40,7 +42,7 @@ export class LocalRecording {
if(serial!==this.serial)return; if(serial!==this.serial)return;
this.active=null; this.active=null;
if(!run.failed&&run.bytes) { if(!run.failed&&run.bytes) {
const blob=new Blob(run.chunks,{type:recorder.mimeType||mimeType||'video/webm'}); const blob=new Blob(run.chunks,{type:recorder.mimeType||mimeType||(this.audioOnly?'audio/webm':'video/webm')});
this.onReady(blob); this.onReady(blob);
this.onStatus('Ready for local replay · nothing uploaded'); this.onStatus('Ready for local replay · nothing uploaded');
} else if(!run.failed)this.onStatus('No recording data was produced.'); } else if(!run.failed)this.onStatus('No recording data was produced.');

View File

@ -0,0 +1,41 @@
// mic.html?mode=watch: passive long watch; otherwise the existing mic page.
const watchMode=new URLSearchParams(location.search).get('mode')==='watch';
if(!watchMode) await import('./mic-observer.js');
else {
const {WatchSession}=await import('./mic-watch.js');
const el=id=>document.getElementById(id);
for(const id of ['output','tone','tone-stop','stage-label','local-review','output-status','output-report','path-link'])
(el(id).closest('label')??el(id)).hidden=true;
document.querySelector('h1').textContent='Passive mic watch';
el('start').textContent='Start watch';el('start').title='Holds the selected microphone open up to 24 h; numeric report every 10 s.';
let session=null,last=null;
const buttons=()=>{el('start').disabled=!!session||!el('input').value;el('stop').disabled=!session;
el('devices').disabled=!!session;el('input').disabled=!!session;el('save').disabled=!last;};
const show=s=>{last={watchId:s.id,events:s.events,last:{...s.last,_stats:undefined}};
el('level').value=(s.last?.peakE5??0)/1e5;el('metrics').textContent=JSON.stringify(last,null,2);buttons();};
el('devices').onclick=async()=>{
try {
const stream=await navigator.mediaDevices.getUserMedia({audio:true,video:false});
for(const t of stream.getTracks())t.stop();
const select=el('input'),saved=select.value;select.replaceChildren(new Option('Select device',''));
for(const d of await navigator.mediaDevices.enumerateDevices())
if(d.kind==='audioinput'&&!['default','communications'].includes(d.deviceId))select.add(new Option(d.label||'Unnamed device',d.deviceId));
select.value=saved;el('status').textContent='Select the USB microphone';
} catch {el('status').textContent='Device permission unavailable';}
buttons();
};
el('input').onchange=buttons;
el('start').onclick=async()=>{
if(session||!el('input').value)return;
session=new WatchSession({deviceId:el('input').value,status:t=>{el('status').textContent=t;},show});
session.reports.status=t=>{el('report-status').textContent=t;};
buttons();await session.start();
};
el('stop').onclick=()=>{session?.stop();if(session)show(session);session=null;buttons();};
el('save').onclick=()=>{
const url=URL.createObjectURL(new Blob([JSON.stringify(last,null,2)],{type:'application/json'}));
const a=document.createElement('a');a.href=url;a.download='mic-watch.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
};
window.addEventListener('pagehide',()=>session?.stop('page closed'));
buttons();
}

View File

@ -0,0 +1,167 @@
import {phoneTest, speechMode, setupPhoneMode, attachDetector, beginStage, reviewStage, selectStageInput} from './acoustic-watch.js';
import {AudioReports} from './mic-reporting.js';
import {OutputPulses} from './mic-output.js';
import {stopTracks} from './capture-lifecycle.js';
const el=id=>document.getElementById(id);
setupPhoneMode();
let generation=0,current=null,output=null,last=null,reportingRun=null,reportingOutput=null;
const event=(run,kind)=>{if(run.events.length<256)run.events.push({atUnixMs:Date.now(),kind});};
function buttons() {
el('start').disabled=!!current||!el('input').value;
el('stop').disabled=!current;
el('devices').disabled=!!current||!!output;
if(phoneTest){el('stage-duration').disabled=!!current;el('keep-speech').disabled=!!current;}
el('input').disabled=!!current;el('output').disabled=!!output;
el('tone').disabled=!!output||!el('output').value;
el('tone-stop').disabled=!output;
}
function snapshot(run) {
run.reports.remember();
return {schema:'audio-test.observer.v1',elapsedMs:performance.now()-run.started,
startedUnixMs:run.wall,audio:run.audio,settings:run.settings,
observationAgeMs:run.audioAt===null?null:performance.now()-run.audioAt,
contextState:run.context?.state??'unavailable',trackMuted:run.track?.muted??null,
trackState:run.track?.readyState??'unavailable',events:run.events,
microphoneRunIds:run.reports.ids,outputRunIds:run.outputIds??[],
path:run.path??null,
outputContextFrames:output?.pulses.sample()?.processedFrames??null,
endpointPlaybackMeasured:false,audioUploaded:false};
}
function audioReport(run) {
return run.audio || run.path ? {...run.audio,path:run.path} : null;
}
function update(run) {
if(current!==run)return;
const now=performance.now();
// Timer keeps reporting even when the worklet or input stops making progress.
run.reports.observe(now,audioReport(run),run.settings);
if(output)output.reports.observe(now,output.pulses.sample(),{sampleRate:output.pulses.context?.sampleRate,channelCount:1});
el('level').value=run.audio?.peak??0;
el('metrics').textContent=JSON.stringify(snapshot(run),null,2);
}
function stopOutput(reason='operator') {
const run=output;output=null;
if(run){
const sample=run.pulses.sample();run.pulses.stop();clearTimeout(run.timeout);clearInterval(run.timer);
run.reports.finish(performance.now(),sample,{sampleRate:run.pulses.context?.sampleRate,channelCount:1},reason);
if(current){event(current,'output-stopped');current.outputIds=run.reports.ids;}
}
el('output-status').textContent=`Output stopped · ${reason}`;buttons();
}
function release(run) {
run.recording?.finish();
stopTracks(run.stream);clearTimeout(run.setupTimer);clearTimeout(run.deadline);clearInterval(run.timer);
if(run.detector){run.detector.port.onmessage=null;run.detector.onprocessorerror=null;
run.detector.port.postMessage('stop');run.detector.disconnect();}
if(run.node){run.node.port.onmessage=null;run.node.onprocessorerror=null;
try{run.node.port.postMessage('stop');run.node.disconnect();}catch{}}
try{run.source?.disconnect();}catch{}
if(run.context){run.context.onstatechange=null;void run.context.close().catch(()=>{});}
}
function stop(reason='operator') {
generation++;
stopOutput(reason);
const run=current;current=null;
if(run){event(run,reason);
if(phoneTest && !['stage finding','phone test complete'].includes(reason))el('path-state').textContent='Incomplete · '+reason;
release(run);
const delivered=run.reports.finish(performance.now(),audioReport(run),run.settings,reason);
if(phoneTest)void reviewStage(run,reason,delivered);
last=snapshot(run);el('metrics').textContent=JSON.stringify(last,null,2);el('save').disabled=false;}
el('status').textContent=`Stopped · ${reason}`;buttons();
}
el('devices').onclick=async()=>{
stop('selecting devices');const ticket=++generation;
el('devices').disabled=true;el('stop').disabled=false;el('status').textContent='Requesting microphone permission';
const deadline=setTimeout(()=>{if(ticket===generation)stop('permission timeout');},20000);
try {
const stream=await navigator.mediaDevices.getUserMedia({audio:true,video:false});
stopTracks(stream);if(ticket!==generation)return;
const devices=await navigator.mediaDevices.enumerateDevices();if(ticket!==generation)return;
for(const [id,kind] of [['input','audioinput'],['output','audiooutput']]) {
const select=el(id),saved=select.value;select.replaceChildren(new Option('Select device',''));
for(const device of devices.filter(d=>d.kind===kind&&(!phoneTest||!['default','communications'].includes(d.deviceId))))select.add(new Option(device.label||'Unnamed device',device.deviceId));
select.value=saved;
}
el('status').textContent=phoneTest?'Select the USB microphone':'Select microphone and output';buttons();
} catch {if(ticket===generation)stop('device permission unavailable');}
finally {clearTimeout(deadline);}
};
el('input').onchange=()=>{if(phoneTest)selectStageInput(el('input').value);buttons();};
el('output').onchange=buttons;
el('start').onclick=async()=>{
if(current||!el('input').value)return;
const ticket=++generation;
const run={started:performance.now(),wall:Date.now(),audio:null,audioAt:null,settings:{},events:[],
reports:new AudioReports(text=>{if(reportingRun===run)el('report-status').textContent=text;})};
if(phoneTest)run.stage=beginStage(el('input').value);
current=run;reportingRun=run;last=null;run.reports.observe(performance.now(),null,run.settings);buttons();el('save').disabled=true;el('status').textContent='Starting microphone';
run.setupTimer=setTimeout(()=>{if(current===run)stop('setup timeout');},20000);
try {
const stream=await navigator.mediaDevices.getUserMedia({video:false,audio:{
deviceId:{exact:el('input').value},echoCancellation:false,noiseSuppression:false,autoGainControl:false}});
if(ticket!==generation){stopTracks(stream);return;}run.stream=stream;run.track=stream.getAudioTracks()[0];
const settings=run.track.getSettings();
if(phoneTest && settings.deviceId!==el('input').value)throw new Error('USB selection unverified');
run.settings={sampleRate:settings.sampleRate,channelCount:settings.channelCount,
echoCancellation:settings.echoCancellation,noiseSuppression:settings.noiseSuppression,autoGainControl:settings.autoGainControl};
run.track.onended=()=>{if(current===run)stop('device ended');};
run.track.onmute=()=>{if(current===run){event(run,'track-muted');if(run.path?.locked)run.pathInterruptions++;update(run);}};
run.track.onunmute=()=>{if(current===run){event(run,'track-unmuted');update(run);}};
if(typeof AudioContext.prototype.setSinkId!=='function')throw new Error('Silent sink unsupported');
run.context=new AudioContext({sinkId:{type:'none'}});
await run.context.setSinkId({type:'none'});if(ticket!==generation)return;
await run.context.audioWorklet.addModule('activity-worklet.js');if(ticket!==generation)return;
run.node=new AudioWorkletNode(run.context,'av-activity',{processorOptions:{continuityWatch:true,recentLevels:true}});
run.node.onprocessorerror=()=>{if(current===run)stop('audio observer error');};
run.node.port.onmessage=({data})=>{
if(current!==run)return;
if(data.watchStopped){stop('audio observer deadline or lost owner');return;}
run.audio=data;run.audioAt=performance.now();run.node.port.postMessage('ack');
};
run.source=run.context.createMediaStreamSource(stream);run.source.connect(run.node);run.node.connect(run.context.destination);
if(phoneTest){await attachDetector(run,()=>current===run,stop);if(ticket!==generation)return;}
run.context.onstatechange=()=>{if(current===run){
event(run,`context-${run.context.state}`);
if(run.path?.locked && run.context.state!=='running')run.pathInterruptions++;
}};
await run.context.resume();if(ticket!==generation)return;
if(run.context.state!=='running')throw new Error('Context suspended');
clearTimeout(run.setupTimer);event(run,'capture-started');
el('selection').textContent=`Microphone: ${run.track.label}\nCapture output: silent sink`;
el('status').textContent=phoneTest?'Receiver listening':'Watching microphone · 20-minute limit';
run.timer=setInterval(()=>update(run),1000);
run.deadline=setTimeout(()=>{if(current===run)stop(phoneTest?'receiver time limit':'operator');},phoneTest?(run.stage.minutes+1)*60000:1200000);update(run);
} catch {if(current===run)stop('capture/setup failed');}
finally {if(current!==run)release(run);}
};
el('tone').onclick=async()=>{
if(output||!el('output').value)return;
const run={pulses:new OutputPulses(),reports:new AudioReports(text=>{if(reportingOutput===run)el('output-report').textContent=text;})};
output=run;reportingOutput=run;buttons();el('output-status').textContent='Starting selected output';
run.timeout=setTimeout(()=>{if(output===run)stopOutput('setup timeout');},10000);
try {
await run.pulses.start(el('output').value,()=>{if(output===run)stopOutput('120 seconds complete');});
if(output!==run)return;clearTimeout(run.timeout);
if(current)event(current,'output-started');
el('output-status').textContent='Output pulses · 1 kHz · two minutes';
run.timer=setInterval(()=>{if(output===run)run.reports.observe(performance.now(),run.pulses.sample(),
{sampleRate:run.pulses.context.sampleRate,channelCount:1});},1000);
} catch {if(output===run)stopOutput('output selection/setup failed');}
};
el('tone-stop').onclick=()=>stopOutput();el('stop').onclick=()=>stop();
el('save').onclick=()=>{
if(!last)return;const url=URL.createObjectURL(new Blob([JSON.stringify(last,null,2)],{type:'application/json'}));
const link=document.createElement('a');link.href=url;link.download='audio-test-metrics.json';link.click();
setTimeout(()=>URL.revokeObjectURL(url),1000);
};
navigator.mediaDevices?.addEventListener('devicechange',()=>{if(current)event(current,'device-list-changed');});
window.addEventListener('pagehide',()=>stop('page closed'));
document.addEventListener('visibilitychange',()=>{
if (phoneTest && speechMode && current) {
event(current,document.hidden?'page-hidden':'page-visible');update(current);
} else if(document.hidden&&(current||output))stop('page hidden; timing invalid');
});
if(!window.isSecureContext||!navigator.mediaDevices||!window.AudioWorkletNode){
el('devices').disabled=true;el('status').textContent='Audio observation unavailable';
}

View File

@ -0,0 +1,45 @@
// Explicit selected output only. A scheduled native audio deadline bounds tones
// even when JavaScript is delayed. No microphone is connected to this graph.
export function pulseSamples(rate) {
const data=new Float32Array(rate);
for(let i=0;i<rate;i++) {
const time=i/rate;
const envelope=time<.12?Math.min(1,time/.005,(.12-time)/.005):0;
data[i]=.025*envelope*Math.sin(2*Math.PI*1000*time);
}
return data;
}
export class OutputPulses {
constructor(Context=AudioContext){this.Context=Context;this.closed=false;this.context=null;}
async start(device,ended) {
if(!device)throw new Error('Output selection required');
const context=this.context=new this.Context({sinkId:device});
if(typeof context.setSinkId!=='function')throw new Error('Output selection unavailable');
await context.setSinkId(device);
if(this.closed)return;
this.source=context.createBufferSource();
const buffer=context.createBuffer(1,context.sampleRate,context.sampleRate);
buffer.copyToChannel(pulseSamples(context.sampleRate),0);
this.source.buffer=buffer;this.source.loop=true;
this.source.connect(context.destination);
await context.resume();
if(this.closed)return;
if(context.state!=='running')throw new Error('Output suspended');
this.started=context.currentTime;
this.source.onended=ended;
this.source.start();this.source.stop(this.started+120);
}
sample() {
if(!Number.isFinite(this.started))return null;
// Context-clock progress is not USB or acoustic playback evidence.
return {inputFrames:null,processedFrames:Math.round(Math.min(120,
Math.max(0,this.context.currentTime-this.started))*this.context.sampleRate),
exactZeroFrames:null,rms:null,peak:null,sampleRate:this.context.sampleRate};
}
stop() {
this.closed=true;
if(this.source){this.source.onended=null;try{this.source.stop();}catch{}try{this.source.disconnect();}catch{}}
if(this.context)void this.context.close().catch(()=>{});
}
}

View File

@ -0,0 +1,40 @@
// Existing numeric-only receipt contract; no new backend or media upload.
import {RunReporter} from './reporting.js';
/** Rotate bounded receipt windows without reopening the selected audio device. */
export class AudioReports {
constructor(status,Reporter=RunReporter) {
this.status=status;this.Reporter=Reporter;this.reporter=null;this.start=0;
this.baseline=null;this.ids=[];this.last=null;this.stageWindows=[];
}
snapshot(now,audio,settings,reason) {
const b=this.baseline??{};
const delta=k=>typeof audio?.[k]==='number'?Math.max(0,audio[k]-(b[k]??0)):null;
const path=audio?.path;
const boundedMs=value=>value<=180000?value:null;
const paired=path?{pilot:{...path,windows:path.windows-(b.path?.windows??0),
gapMaxMs:boundedMs(path.gapMaxMs),trailingGapMs:boundedMs(path.trailingGapMs)},
continuity:{badMarkers:path.sequenceFaults}}:null;
return {paired,elapsedMs:Math.max(0,now-this.start),reason,settings:{audio:settings},video:null,
audio:audio?{...audio,inputFrames:delta('inputFrames'),processedFrames:delta('processedFrames'),
exactZeroFrames:delta('exactZeroFrames')}:null};
}
observe(now,audio,settings) {
if(this.reporter&&now-this.start>=120000) {
const reason=audio?.path?'signal report window closed':'120 seconds complete';
const delivered=this.reporter.finish(this.snapshot(now,audio,settings,reason));
if(audio?.path)this.stageWindows.push(delivered);
this.remember();this.reporter=null;this.baseline=audio?{...audio}:null;
}
if(!this.reporter){this.start=now;this.reporter=new this.Reporter(this.status);}
this.last=this.snapshot(now,audio,settings,'observing');this.reporter.observe(this.last);
}
remember() {
if(this.reporter?.runId&&this.ids.length<32&&!this.ids.includes(this.reporter.runId))this.ids.push(this.reporter.runId);
}
finish(now,audio,settings,reason) {
if(!this.reporter)return;
const result=this.reporter.finish(this.snapshot(now,audio,settings,reason));this.remember();
return audio?.path ? Promise.all([...this.stageWindows,result]).then(values=>values.every(Boolean)) : result;
}
}

View File

@ -0,0 +1,167 @@
// Passive hours-long watch of one explicitly selected microphone. Numeric only.
import {AudioReports} from './mic-reporting.js';
import {stopTracks} from './capture-lifecycle.js';
export const EVENTS={mute:1,unmute:2,ended:3,devicechange:4,'context-running':5,'context-suspended':6,
'context-closed':7,'context-interrupted':7,hidden:8,visible:9,freeze:10,resume:11,
'restart-attempt':12,'restart-ok':13,'restart-failed':14,'capture-started':15,'observer-error':16,
'worklet-stale':17,stop:18};
const CONTEXT={running:0,suspended:1,closed:2,interrupted:3};
const RETRY=[2000,5000,15000,30000,60000];
const LIMIT_MS=24*3600000;
// Field order is the X-AV-Watch wire contract (see correlate-watch.mjs).
export const FIELDS=['version','watchId','seq','sentUnixMs','intervalMs','contextFrames','contextRate',
'callbackGaps','callbackGapMaxMs','callbackGapStartUnixMs','rmsE5','peakE5','zeroFrames',
'zeroRunMaxMs','zeroRunStartUnixMs','deviceFrames','deviceDeliveredFrames','deviceDurationMs',
'frameDeficitMs','mutes','unmutes','ends','deviceChanges','contextChanges','visibilityChanges',
'hidden','contextState','trackState','restarts','timerLateMaxMs','messageLatencyMaxMs','workletAgeMs'];
export function watchHeader(values, events) {
const ints=FIELDS.map(k=>Math.round(values[k]??-1));
if(ints.some(v=>!Number.isSafeInteger(v)||Math.abs(v)>9999999999999))return null;
const rows=events.slice(-16).map(e=>[e.serial,e.kind,e.at].join(','));
return [ints.join(','),...rows].join(';');
}
export class WatchSession {
constructor({deviceId,status,show,media=navigator.mediaDevices,Context=globalThis.AudioContext,
Node=globalThis.AudioWorkletNode,Reports=AudioReports,now=()=>Date.now(),mono=()=>performance.now()}) {
Object.assign(this,{deviceId,status,show,media,Context,Node,now,mono});
this.reports=new Reports(status);
this.id=1+Math.floor(Math.random()*999999998);this.seq=0;this.events=[];this.serial=0;
this.count={mutes:0,unmutes:0,ends:0,deviceChanges:0,contextChanges:0,visibilityChanges:0,restarts:0};
this.total={frames:0,zero:0};this.reset();this.live=null;this.stopped=false;this.failures=0;
}
reset(stats=null) {
this.iv={frames:0,energy:0,peak:0,zero:0,gaps:0,gapMax:0,gapStart:0,zeroMax:0,zeroStart:0,
late:0,latency:0,since:this.now(),stats};
}
event(name) {
const kind=EVENTS[name];if(!kind)return;
this.events.push({serial:++this.serial,kind,at:this.now()});
if(this.events.length>16)this.events.shift();
}
async start() {
this.started=this.now();this.timerAt=this.mono();
this.timer=setInterval(()=>this.tick(),10000);
this.deadline=setTimeout(()=>this.stop('24 hours complete'),LIMIT_MS);
this.listeners=[[this.media,'devicechange',()=>{this.count.deviceChanges++;this.event('devicechange');}],
[globalThis.document,'visibilitychange',()=>{this.count.visibilityChanges++;this.event(document.hidden?'hidden':'visible');}],
[globalThis.document,'freeze',()=>this.event('freeze')],[globalThis.document,'resume',()=>this.event('resume')]];
for(const [target,name,fn] of this.listeners)target?.addEventListener?.(name,fn);
await this.open();
}
async open() {
const live={};this.live=live;
try {
const stream=await this.media.getUserMedia({video:false,audio:{deviceId:{exact:this.deviceId},
echoCancellation:false,noiseSuppression:false,autoGainControl:false}});
live.stream=stream;
if(this.live!==live||this.stopped){stopTracks(stream);return;}
const track=live.track=stream.getAudioTracks()[0];
// Never accept a substituted device.
if(track?.getSettings().deviceId!==this.deviceId)throw new Error('selection');
track.onmute=()=>{this.count.mutes++;this.event('mute');};
track.onunmute=()=>{this.count.unmutes++;this.event('unmute');};
track.onended=()=>{this.count.ends++;this.event('ended');this.restart();};
const context=live.context=new this.Context({sinkId:{type:'none'}});
if(typeof context.setSinkId!=='function')throw new Error('silent sink');
await context.setSinkId({type:'none'});
await context.audioWorklet.addModule('watch-worklet.js');
if(this.live!==live)return;
const node=live.node=new this.Node(context,'av-watch');
node.onprocessorerror=()=>{this.event('observer-error');this.restart();};
node.port.onmessage=({data})=>this.second(data);
live.source=context.createMediaStreamSource(stream);live.source.connect(node);node.connect(context.destination);
context.onstatechange=()=>{
this.count.contextChanges++;this.event('context-'+context.state);
if(context.state==='suspended'||context.state==='interrupted')
setTimeout(()=>{if(this.live===live)void context.resume().catch(()=>{});},1000);
if(context.state==='closed')this.restart();
};
await context.resume();
this.iv.stats=this.deviceStats();
this.event('capture-started');this.failures=0;this.workletAt=this.mono();
this.status(`Watching · ${track.label}`);
} catch {
if(this.live===live&&!this.stopped){this.event('restart-failed');this.restart();}
}
}
deviceStats() {
const s=this.live?.track?.stats;
return s&&typeof s.totalFrames==='number'?{total:s.totalFrames,delivered:s.deliveredFrames,
durationMs:s.totalFramesDuration}:null;
}
release(live) {
if(!live)return;
stopTracks(live.stream);
try{live.node.port.onmessage=null;live.node.port.postMessage('stop');live.node.disconnect();}catch{}
try{live.source.disconnect();}catch{}
if(live.context){live.context.onstatechange=null;void live.context.close().catch(()=>{});}
}
restart() {
const old=this.live;if(!old||this.stopped)return;
this.live=null;this.release(old);
const wait=RETRY[Math.min(this.failures++,RETRY.length-1)];
this.status(`Capture lost · retrying same microphone in ${wait/1000} s`);
setTimeout(async()=>{
if(this.stopped||this.live)return;
this.event('restart-attempt');await this.open();
if(this.live?.node){this.count.restarts++;this.event('restart-ok');}
},wait);
}
second(d) {
const iv=this.iv;this.workletAt=this.mono();this.stale=false;
this.iv.latency=Math.max(iv.latency,this.now()-d.at);this.rate=d.rate;
iv.frames+=d.frames;iv.energy+=d.rms*d.rms*d.frames;iv.peak=Math.max(iv.peak,d.peak);iv.zero+=d.zeroFrames;
this.total.frames+=d.frames;this.total.zero+=d.zeroFrames;
if(d.gapMaxMs>iv.gapMax){iv.gapMax=d.gapMaxMs;iv.gapStart=d.gapStart;}iv.gaps+=d.gaps;
if(d.zeroRunMs>iv.zeroMax){iv.zeroMax=d.zeroRunMs;iv.zeroStart=d.zeroRunStart;}
if(this.now()-iv.since>=10000)this.send();
}
tick() {
const now=this.mono();
this.iv.late=Math.max(this.iv.late,now-this.timerAt-10000);this.timerAt=now;
// Audio-thread messages normally drive reports; the timer covers their absence.
if(this.mono()-(this.workletAt??0)>15000) {
if(!this.stale)this.event('worklet-stale');
this.stale=true;this.send();
}
}
values() {
const iv=this.iv,now=this.now(),stats=this.deviceStats(),prev=iv.stats;
const delta=k=>stats&&prev?stats[k]-prev[k]:-1;
const track=this.live?.track;
return {version:1,watchId:this.id,seq:++this.seq,sentUnixMs:now,intervalMs:now-iv.since,
contextFrames:iv.frames,contextRate:this.rate??-1,callbackGaps:iv.gaps,callbackGapMaxMs:iv.gapMax,
callbackGapStartUnixMs:iv.gapStart,rmsE5:iv.frames?1e5*Math.sqrt(iv.energy/iv.frames):0,
peakE5:1e5*iv.peak,zeroFrames:iv.zero,zeroRunMaxMs:iv.zeroMax,zeroRunStartUnixMs:iv.zeroStart,
deviceFrames:delta('total'),deviceDeliveredFrames:delta('delivered'),deviceDurationMs:delta('durationMs'),
frameDeficitMs:this.rate?(now-this.started)-1000*this.total.frames/this.rate:-1,...this.count,
hidden:Number(!!globalThis.document?.hidden),contextState:CONTEXT[this.live?.context?.state]??-1,
trackState:!track?3:track.readyState==='ended'?2:track.muted?1:0,
timerLateMaxMs:Math.max(0,iv.late),messageLatencyMaxMs:Math.max(0,iv.latency),
workletAgeMs:this.workletAt===undefined?-1:this.mono()-this.workletAt,_stats:stats};
}
snapshot() {
const audio={inputFrames:this.total.frames,processedFrames:this.total.frames,exactZeroFrames:this.total.zero,
rms:this.iv.frames?Math.sqrt(this.iv.energy/this.iv.frames):0,peak:this.iv.peak,sampleRate:this.rate};
// Evaluated at send time so the sequence counts real transmissions.
audio.watch=()=>{const v=this.values();this.last=v;this.reset(v._stats);return watchHeader(v,this.events);};
return audio;
}
send() {
const settings=this.live?.track?.getSettings?.()??{};
this.reports.observe(this.mono(),this.snapshot(),{sampleRate:settings.sampleRate,channelCount:settings.channelCount});
this.show?.(this);
}
stop(reason='operator') {
if(this.stopped)return;
this.event('stop');this.stopped=true;clearInterval(this.timer);clearTimeout(this.deadline);
for(const [target,name,fn] of this.listeners??[])target?.removeEventListener?.(name,fn);
const live=this.live;this.live=null;this.release(live);
this.reports.finish(this.mono(),this.snapshot(),{},reason);
this.status(`Stopped · ${reason}`);
}
}

View File

@ -0,0 +1,23 @@
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
<title>Audio Test</title><link rel="stylesheet" href="style.css">
<main><h1>Audio Test</h1><a href="./">A/V Test</a>
<p><a id="path-link" href="mic.html?test=phone">Staged RCT receiver test</a> <a href="phone.html">Phone sound source</a> <a href="mic.html?mode=watch">Passive watch</a></p>
<p id="path-state" role="status" title="Level drops require at least 100 ms at least 20 dB below the recognized phone reference." hidden></p>
<p id="path-detail" hidden></p><p id="path-timing" hidden></p>
<div><button id="devices">Choose devices…</button>
<label>Microphone <select id="input"></select></label>
<label>Output <select id="output"></select></label></div>
<div><button id="start" disabled title="One uninterrupted microphone capture, up to 20 minutes. Numeric reports every ten seconds. No camera or audio upload.">Start mic watch</button>
<button id="stop" disabled>Stop</button>
<span id="stage-label" hidden><label>Test duration <select id="stage-duration" title="Longer durations unlock after a completed and reported stage on this microphone."></select></label></span>
<button id="tone" disabled title="Quiet 1 kHz pulses on the explicitly selected output for two minutes. This exercises output separately; microphone audio is never monitored.">Start output pulses</button>
<button id="tone-stop" disabled>Stop output</button>
<button id="save" disabled>Save metrics</button></div>
<div id="local-review" hidden><label><input type="checkbox" id="keep-speech"> Keep received audio for replay on this RCT</label>
<span id="record-status"></span><audio controls id="speech-replay" hidden></audio> <button id="hear-finding" hidden>Replay first finding</button></div>
<p id="status" role="status">Stopped</p><p id="report-status">Mic reporting idle</p><p id="output-status">Output stopped</p>
<p id="output-report">Output reporting idle</p>
<meter id="level" min="0" max="1" value="0" title="Current microphone peak"></meter>
<pre id="selection"></pre><pre id="metrics">No observations</pre>
</main><script type="module" src="mic-entry.js"></script></html>

View File

@ -6,6 +6,45 @@ http {
include /etc/nginx/mime.types; include /etc/nginx/mime.types;
default_type application/octet-stream; default_type application/octet-stream;
access_log off; access_log off;
# The receipt service authenticates the body and sequence. Log only the
# numeric stage annotation of an accepted report, correlated by that body.
map $request_body $av_identity {
default "";
'~^[{]"run_id":"(?<av_id>[0-9a-f]{32})","sequence":(?<av_sequence>[1-9][0-9]?),"state":"(?<av_state>running|completed|failed|hidden|closed|stopped|device-change)",' "$av_id/$av_sequence/$av_state";
}
map $http_x_av_stage $av_annotation {
default "";
'~^(1|5|10|15|20|30|60)(,[0-9]{1,7}){6},(0|[0-9]{13}),[0-9]{1,5}(,-?[0-9]{1,7}){7}$' $http_x_av_stage;
}
map "$uri|$upstream_status|$av_identity|$av_annotation" $av_ack {
default "";
'~^/av-test/api/report[|]204[|][^|]+[|][-0-9,]+$' 1;
}
map $http_x_av_speech $av_speech {
default "";
'~^[12],[0-9]{1,7},-?[0-9]{1,4},-?[0-9]{1,7},[0-9]{1,6},-?[0-9]{1,7}(;[0-9]{1,6},[1-4],[0-9]{1,7},[0-9]{1,7},-?[0-9]{1,7},-?[0-9]{1,4}){0,16}$' $http_x_av_speech;
}
map "$av_ack|$av_speech" $av_speech_ack {
default "";
'~^1[|][12],' 1;
}
map $http_x_av_watch $av_watch {
default "";
'~^1(,-?[0-9]{1,13}){31}(;[0-9]{1,6},[0-9]{1,2},[0-9]{13}){0,16}$' $http_x_av_watch;
}
map "$uri|$upstream_status|$av_identity|$av_watch" $av_watch_ack {
default "";
'~^/av-test/api/report[|]204[|][^|]+[|]1,' 1;
}
map "$av_ack$av_watch_ack" $av_log {
default 1;
"" 0;
}
map "$uri|$upstream_status" $av_clock {
default "";
"/av-test/api/start|201" $msec;
}
log_format av_stage escape=json '{"schema":"av-test.acoustic-stage.v1","received":"$msec","receipt":"$av_identity","stage":"$av_annotation","speech":"$av_speech","watch":"$av_watch"}';
server_tokens off; server_tokens off;
client_max_body_size 4k; client_max_body_size 4k;
client_body_timeout 5s; client_body_timeout 5s;
@ -19,11 +58,15 @@ http {
listen 8080; listen 8080;
absolute_redirect off; absolute_redirect off;
root /usr/share/nginx/html; root /usr/share/nginx/html;
add_header X-AV-Clock $av_clock always;
add_header X-AV-Speech-Ack $av_speech_ack always;
add_header X-AV-Watch-Ack $av_watch_ack always;
add_header X-AV-Stage-Ack $av_ack always;
add_header Cache-Control "no-store" always; add_header Cache-Control "no-store" always;
add_header X-Content-Type-Options "nosniff" always; add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always; add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "no-referrer" always; add_header Referrer-Policy "no-referrer" always;
add_header Permissions-Policy "camera=(self), microphone=(self), geolocation=(), display-capture=()" always; add_header Permissions-Policy "camera=(self), microphone=(self), speaker-selection=(self), geolocation=(), display-capture=()" always;
add_header Cross-Origin-Opener-Policy "same-origin" always; add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; media-src 'self' blob:; connect-src 'self'; worker-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" always; add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; media-src 'self' blob:; connect-src 'self'; worker-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" always;
location = /lesavka-av-test { return 308 /av-test/; } location = /lesavka-av-test { return 308 /av-test/; }
@ -42,11 +85,12 @@ http {
if ($request_method !~ ^(GET|HEAD)$) { return 405; } if ($request_method !~ ^(GET|HEAD)$) { return 405; }
try_files /av-test/index.html =404; try_files /av-test/index.html =404;
} }
location ~ ^/av-test/(index\.html|observer\.js|local-recording\.js|review-controls\.js|metrics\.js|reporting\.js|activity-worklet\.js|paired-observer\.js|paired-worklet\.js|paired-signals\.js|test-signals\.js|continuity-signals\.js|pilot-window\.js|capture-lifecycle\.js|continuity-watch\.js|style\.css)$ { location ~ ^/av-test/(mic-entry\.js|mic-watch\.js|watch-worklet\.js|speech-reference\.flac|speech-alignment\.js|speech-detector\.js|speech-envelope\.js|speech-watch\.js|speech-worklet\.js|acoustic-detector\.js|acoustic-pattern\.js|acoustic-watch\.js|acoustic-worklet\.js|acoustic-timing\.js|phone-source\.js|phone\.html|mic\.html|mic-observer\.js|mic-reporting\.js|mic-output\.js|index\.html|observer\.js|local-recording\.js|review-controls\.js|metrics\.js|reporting\.js|activity-worklet\.js|paired-observer\.js|paired-worklet\.js|paired-signals\.js|test-signals\.js|continuity-signals\.js|pilot-window\.js|capture-lifecycle\.js|continuity-watch\.js|style\.css)$ {
if ($request_method !~ ^(GET|HEAD)$) { return 405; } if ($request_method !~ ^(GET|HEAD)$) { return 405; }
try_files $uri =404; try_files $uri =404;
} }
location ~ ^/av-test/api/(start|report)$ { location ~ ^/av-test/api/(start|report)$ {
access_log /dev/stdout av_stage if=$av_log;
if ($request_method != POST) { return 405; } if ($request_method != POST) { return 405; }
proxy_pass http://127.0.0.1:8081; proxy_pass http://127.0.0.1:8081;
proxy_connect_timeout 2s; proxy_connect_timeout 2s;

View File

@ -0,0 +1,88 @@
import {speechBuffer} from './speech-envelope.js';
import {AudioReports} from './mic-reporting.js';
import {referenceLoop, STAGE_MINUTES, SOURCE_LEAD_SECONDS} from './acoustic-pattern.js';
const play = document.getElementById('play');
const stopButton = document.getElementById('stop');
const status = document.getElementById('state');
const duration = document.getElementById('duration');
for (const minutes of STAGE_MINUTES) duration.add(new Option(minutes + ' min', String(minutes)));
const speechMode = new URLSearchParams(location.search).get('signal') !== 'tones';
play.textContent = speechMode ? 'Play spoken phrase' : 'Play diagnostic tones';
let active = null;
function clockSample(owner) {
const frames = Math.floor(Math.max(0,owner.context.currentTime - owner.started) * owner.context.sampleRate);
return {processedFrames:frames, sampleRate:owner.context.sampleRate};
}
function stop(message) {
const owner = active;
active = null;
if (owner) {
clearInterval(owner.timer);
const reason = message === 'Playback complete' ? 'reference complete' :
message === 'Playback stopped' ? 'operator' : 'source interrupted';
owner.reports?.finish(performance.now(), clockSample(owner), {sampleRate:owner.context.sampleRate}, reason);
owner.context.onstatechange = null;
if (owner.source) {
owner.source.onended = null;
try { owner.source.stop(); } catch {}
}
void owner.context.close().catch(() => {});
void owner.wake?.release().catch(() => {});
}
play.disabled = false; stopButton.disabled = true; duration.disabled = false;
status.textContent = message;
}
play.onclick = async () => {
if (active) return;
try {
const minutes = Number(duration.value);
if (!STAGE_MINUTES.includes(minutes)) return;
const sourceSeconds = 60 * minutes + SOURCE_LEAD_SECONDS;
duration.disabled = true;
const context = new AudioContext();
const owner = {context};
active = owner; play.disabled = true; stopButton.disabled = false;
status.textContent = 'Starting speaker';
await context.resume();
if (active !== owner) return;
let buffer;
if (speechMode) buffer = await speechBuffer(context);
else {
const data = referenceLoop(context.sampleRate);
buffer = context.createBuffer(1,data.length,context.sampleRate);
buffer.copyToChannel(data,0);
}
if (active !== owner) return;
const source = context.createBufferSource();
owner.source = source; source.buffer = buffer; source.loop = true;
source.connect(context.destination);
const start = context.currentTime;
owner.started = start;
owner.reports = new AudioReports(text => {
if (active === owner) document.getElementById('report').textContent = text;
});
source.onended = () => { if (active === owner) stop('Playback complete'); };
context.onstatechange = () => {
if (active === owner && context.state !== 'running') stop('Speaker interrupted');
};
source.start(start); source.stop(start + sourceSeconds);
const show = () => {
owner.reports.observe(performance.now(), clockSample(owner), {sampleRate:context.sampleRate});
const remaining = Math.max(0, Math.ceil(sourceSeconds - (context.currentTime - start)));
status.textContent = 'Playing · ' + Math.floor(remaining / 60) + ':' +
String(remaining % 60).padStart(2, '0') + ' remaining';
};
show(); owner.timer = setInterval(show, 1000);
try {
const wake = await navigator.wakeLock?.request('screen');
if (active === owner) owner.wake = wake;
else await wake?.release();
} catch {}
} catch { if (active) stop('Speaker or reference unavailable'); }
};
stopButton.onclick = () => stop('Playback stopped');
document.addEventListener('visibilitychange', () => {
if (document.hidden && active) stop('Playback interrupted · phone page hidden');
});
window.addEventListener('pagehide', () => stop('Playback stopped'));

View File

@ -0,0 +1,11 @@
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Phone audio source</title><link rel="stylesheet" href="style.css">
<main><h1>Phone audio source</h1>
<p>Place the phone near the microphone. Use its speaker at a comfortable volume and keep this page visible.</p>
<label>Receiver stage <select id="duration"></select></label>
<button id="play">Play test sound</button><button id="stop" disabled>Stop</button>
<p id="state" role="status">Ready</p>
<p id="report">Playback reporting idle</p>
<a href="mic.html?test=phone">RCT receiver test</a></main>
<script type="module" src="phone-source.js"></script></html>

View File

@ -32,14 +32,48 @@ export function reportMetrics(receipt) {
} }
export function stopState(reason) { export function stopState(reason) {
if(reason==='120 seconds complete')return 'completed'; if(reason==='120 seconds complete'||reason==='phone test complete'||reason==='reference complete')return 'completed';
if(reason==='page hidden; timing invalid')return 'hidden'; if(reason==='page hidden; timing invalid')return 'hidden';
if(reason==='page closed')return 'closed'; if(reason==='page closed')return 'closed';
if(reason==='device ended'||reason==='device selection changed')return 'device-change'; if(reason==='device ended'||reason==='device selection changed')return 'device-change';
if(reason==='operator'||reason==='selecting devices')return 'stopped'; if(reason==='operator'||reason==='selecting devices'||reason==='signal report window closed')return 'stopped';
return 'failed'; return 'failed';
} }
// Only fixed, bounded integers supplement an authenticated acoustic receipt.
// First-event offsets use offset+1, reserving zero for no event.
export function acousticReceipt(path, clock) {
if (!path || ![1,5,10,15,20,30,60].includes(path.stageMinutes)) return null;
const offset = value => value === null ? 0 : Math.round(value) + 1;
const timing = [path.stageMinutes,Math.round(path.observedMs),offset(path.firstLevelDropMs),
Math.round(path.longestLevelDropMs),offset(path.firstUnclearMs),Math.round(path.gapMaxMs),
path.discontinuities];
if (!timing.every(v=>Number.isSafeInteger(v) && v>=0 && v<=3600011)) return null;
const end = clock && Number.isFinite(path.observedAtMono) ? Math.round(path.observedAtMono + clock.offset) : 0;
const t=path.timing;
if (!t) return null;
const warp=[Math.round(t.rateCoverageMs),t.edgeCount,t.maxRatePpm,offset(t.firstRateMs),t.maxShiftMs,offset(t.firstShiftMs),t.baselinePpm??0];
if (!warp.every(v=>Number.isSafeInteger(v) && Math.abs(v)<=3600011)) return null;
return [...timing,end,clock?.uncertainty ?? 0,...warp].join(',');
}
export function speechReceipt(speech) {
if (!speech) return null;
const integer = (v,min,max) => Number.isSafeInteger(v) && v>=min && v<=max;
if (!integer(speech.coverageMs,0,3600000) || !integer(speech.phase,-1,9999) ||
!integer(speech.phaseAgeMs,-1,3600000) || !integer(speech.total,0,999999) ||
!integer(speech.maxCadencePpm,-1000000,1000000) || !Array.isArray(speech.events) ||
speech.events.length>16) return null;
const rows=[[speech.kind===2?2:1,speech.coverageMs,speech.phase,speech.phaseAgeMs,speech.total,speech.maxCadencePpm]];
for (const row of speech.events) {
if (!Array.isArray(row) || row.length!==6 || !integer(row[0],1,speech.total) ||
!integer(row[1],1,4) || !integer(row[2],0,3600000) ||
!integer(row[3],0,3600000-row[2]) || !integer(row[4],-1000000,1000000) || !integer(row[5],-1,9999)) return null;
rows.push(row);
}
return rows.map(row=>row.join(',')).join(';');
}
export class RunReporter { export class RunReporter {
constructor(status,request=globalThis.fetch.bind(globalThis)) { constructor(status,request=globalThis.fetch.bind(globalThis)) {
this.status=status;this.request=request;this.pending=null;this.busy=false; this.status=status;this.request=request;this.pending=null;this.busy=false;
@ -49,9 +83,16 @@ export class RunReporter {
} }
async open() { async open() {
try { try {
const sentAt=performance.now();
const r=await this.request('/av-test/api/start',{method:'POST',credentials:'omit', const r=await this.request('/av-test/api/start',{method:'POST',credentials:'omit',
headers:{'Content-Type':'application/json'},body:'{}',signal:AbortSignal.timeout(5000)}); headers:{'Content-Type':'application/json'},body:'{}',signal:AbortSignal.timeout(5000)});
if(!r.ok)throw new Error('start rejected'); if(!r.ok)throw new Error('start rejected');
const receivedAt=performance.now();
const stamp=r.headers?.get?.('X-AV-Clock');
if (/^[0-9]{10}\.[0-9]{3}$/.test(stamp)) {
this.clock={offset:Number(stamp)*1000-(sentAt+receivedAt)/2,
uncertainty:Math.ceil((receivedAt-sentAt)/2)+1};
}
const data=await r.json(); const data=await r.json();
if(!/^[a-f0-9]{32}$/.test(data.run_id)||!/^[A-Za-z0-9_-]{43}$/.test(data.write_token))throw new Error('bad receipt'); if(!/^[a-f0-9]{32}$/.test(data.run_id)||!/^[A-Za-z0-9_-]{43}$/.test(data.write_token))throw new Error('bad receipt');
this.runId=data.run_id;this.token=data.write_token; this.runId=data.run_id;this.token=data.write_token;
@ -69,13 +110,17 @@ export class RunReporter {
this.lastProgress=receipt.elapsedMs;this.queue('running',receipt); this.lastProgress=receipt.elapsedMs;this.queue('running',receipt);
} }
finish(receipt) { finish(receipt) {
if(this.terminal)return; if(!this.terminal) {
this.terminal=true;this.queue(stopState(receipt.reason),receipt); this.terminal=true;
this.finished=new Promise(resolve=>{this.resolveFinished=resolve;});
this.queue(stopState(receipt.reason),receipt);
}
return this.finished;
} }
queue(state,receipt) { queue(state,receipt) {
// One latest snapshot, not a growing queue. Terminal state supersedes // One latest snapshot, not a growing queue. Terminal state supersedes
// pending progress; a stopped run never becomes running again. // pending progress; a stopped run never becomes running again.
this.pending={state,metrics:reportMetrics(receipt)}; this.pending={state,metrics:reportMetrics(receipt),path:receipt.paired?.pilot,watch:receipt.audio?.watch};
void this.flush(); void this.flush();
} }
async flush() { async flush() {
@ -83,23 +128,33 @@ export class RunReporter {
this.busy=true; this.busy=true;
try { try {
await this.ready; await this.ready;
if(!this.available){this.pending=null;return;} if(!this.available){this.pending=null;this.resolveFinished?.(false);return;}
while(this.pending) { while(this.pending) {
const report=this.pending;this.pending=null; const report=this.pending;this.pending=null;
const payload={run_id:this.runId,sequence:++this.sequence,...report}; const payload={run_id:this.runId,sequence:++this.sequence,state:report.state,metrics:report.metrics};
const stage=acousticReceipt(report.path,this.clock);
const headers={'Content-Type':'application/json',Authorization:`Bearer ${this.token}`};
if(stage)headers['X-AV-Stage']=stage;
const speech=speechReceipt(report.path?.speech);
if(speech)headers['X-AV-Speech']=speech;
const watch=typeof report.watch==='function'?report.watch():null;
if(watch)headers['X-AV-Watch']=watch;
let delivered=false; let delivered=false;
for(let attempt=0;attempt<2&&!delivered;attempt++) { for(let attempt=0;attempt<2&&!delivered;attempt++) {
try { try {
const response=await this.request('/av-test/api/report',{ const response=await this.request('/av-test/api/report',{
method:'POST',credentials:'omit',keepalive:true, method:'POST',credentials:'omit',keepalive:true,
headers:{'Content-Type':'application/json',Authorization:`Bearer ${this.token}`}, headers,
body:JSON.stringify(payload),signal:AbortSignal.timeout(5000), body:JSON.stringify(payload),signal:AbortSignal.timeout(5000),
}); });
delivered=response.ok; delivered=response.ok && (!stage || (this.clock && response.headers?.get?.('X-AV-Stage-Ack')==='1')) &&
(!report.path?.speech || (speech && response.headers?.get?.('X-AV-Speech-Ack')==='1')) &&
(!watch || response.headers?.get?.('X-AV-Watch-Ack')==='1');
if(response.status>=400&&response.status<500)break; if(response.status>=400&&response.status<500)break;
} catch { /* No raw exception or endpoint response is displayed. */ } } catch { /* No raw exception or endpoint response is displayed. */ }
} }
if(report.state!=='running') { if(report.state!=='running') {
this.resolveFinished?.(!!delivered);
this.status(delivered ? `Result reported · test ${this.runId.slice(0,8)}` : this.status(delivered ? `Result reported · test ${this.runId.slice(0,8)}` :
'Result not reported · use Save metrics'); 'Result not reported · use Save metrics');
} else if(!delivered) { } else if(!delivered) {

View File

@ -0,0 +1,66 @@
// Match the envelope of the published phrase at any loop position. Clipping
// each band to its own dynamic range tolerates different mic gain/noise floors.
const wrap = (n, length) => ((n % length) + length) % length;
export const phaseDelta = (a, b, length) => wrap(a-b+Math.floor(length/2), length)-Math.floor(length/2);
const LOOKBACK = 125;
function normalized(values) {
const floor = Math.max(...values)-30;
const clipped = values.map(x => Math.max(x, floor));
const mean = clipped.reduce((sum, x) => sum + x, 0) / clipped.length;
const centered = clipped.map(x => x-mean);
const norm = Math.sqrt(centered.reduce((sum,x) => sum+x*x,0));
if (norm < 3 * Math.sqrt(values.length)) return null;
return centered.map(x => x/norm);
}
export class SpeechAlignment {
constructor({levels, highs}) {
this.length = levels.length;
this.bands = [levels, highs];
this.peak = Math.max(...levels);
this.patterns = levels.map((_, phase) => this.bands.map(band =>
normalized(Array.from({length:LOOKBACK}, (_,i)=>band[(phase+i)%this.length]))));
}
match(frames, end) {
if (frames.length < LOOKBACK) return null;
const window = frames.slice(-LOOKBACK);
if (window.some(row=>!row[2])) return null;
const received = [0,1].map(b=>normalized(window.map(row=>row[b])));
if (received.some(band=>!band)) return null;
let best = -1, bestScore = 0;
const scores = this.patterns.map((pattern, i) => {
if (pattern.some(band=>!band)) return -1;
let dot = 0;
for (let k = 0; k < LOOKBACK; k++)
dot += pattern[0][k]*received[0][k] + pattern[1][k]*received[1][k];
const score = dot/2;
if (score>bestScore) { best=i; bestScore=score; }
return score;
});
if (bestScore<0.74 || scores.some((s,i)=>Math.abs(phaseDelta(i,best,this.length))>6 && s>bestScore-0.07)) return null;
const gains = [];
for (let k=0;k<LOOKBACK;k++) {
const expected=this.bands[0][(best+k)%this.length];
if (expected>this.peak-18) gains.push(window[k][0]-expected);
}
if (gains.length<15) return null;
gains.sort((a,b)=>a-b);
return {phase:wrap(best-(end-LOOKBACK),this.length), gain:gains[gains.length>>1]};
}
// A loud unrelated sound can overlap a word without reducing RMS. Examine
// the shape of short, active passages independently of the long phase lock.
unclearPassage(frames, first, anchor) {
const received=frames.map(row=>row[0]);
let best=-1;
for (const delta of [-1,0,1]) {
const expected=received.map((_,i)=>this.expected(first+i,anchor.phase+delta));
if (expected.filter(x=>x>this.peak-20).length<6) return false;
if (Math.max(...received)<Math.max(...expected)+anchor.gain-14) return false;
const a=normalized(expected), b=normalized(received);
if (!a) return false;
if (b) best=Math.max(best,a.reduce((sum,x,i)=>sum+x*b[i],0));
}
return best<0.38;
}
expected(index,phase) { return this.bands[0][wrap(index+phase,this.length)]; }
}

View File

@ -0,0 +1,105 @@
import {SpeechAlignment, phaseDelta} from './speech-alignment.js';
// Event codes on the numeric receipt: 1 attenuated speech, 2 timing step,
// 3 uncertain alignment/level, 4 sustained cadence change. Time units are ms.
export class SpeechDetector {
constructor(reference,minutes) {
this.align=new SpeechAlignment(reference);
this.minutes=minutes;
this.frames=[]; this.end=this.scored=this.trusted=this.count=0;
this.events=[]; this.maxDrop=this.maxUnknown=this.shift=this.maxRate=0;
this.firstDrop=this.firstUnknown=this.firstShift=this.firstRate=null;
this.discontinuities=0; this.known=false; this.passage=[];
}
event(kind, start, duration, value=0, phase=null) {
const position=phase===null?-1:(start+phase)%this.align.length;
const row=[++this.count,kind,10*start,10*duration,value,position];
this.events.push(row);
if (this.events.length>16) this.events.shift();
if (kind===1) { this.firstDrop??=row[2]; this.maxDrop=Math.max(this.maxDrop,row[3]); }
if (kind===3) { this.firstUnknown??=row[2]; this.maxUnknown=Math.max(this.maxUnknown,row[3]); }
}
flushLoss() {
const loss=this.loss;
if (loss && loss.active>=10) this.event(1,loss.start,loss.last-loss.start+1,0,loss.phase);
this.loss=null;
}
score(to, anchor) {
const base=this.end-this.frames.length;
for (;this.scored<to;this.scored++) {
const i=this.scored, frame=this.frames[i-base];
if (!anchor || !frame?.[2]) {
this.flushLoss(); this.passage=[]; this.unknownStart??=i; continue;
}
if (this.unknownStart!=null) {
if (i-this.unknownStart>=10) this.event(3,this.unknownStart,i-this.unknownStart);
this.unknownStart=null;
}
this.trusted++;
this.passage.push(frame);
if (this.passage.length===20) {
if (this.align.unclearPassage(this.passage,i-19,anchor)) this.event(3,i-19,20,0,anchor.phase);
this.passage=[];
}
const expected=this.align.expected(i,anchor.phase);
const quietest=Math.min(expected,this.align.expected(i-1,anchor.phase),this.align.expected(i+1,anchor.phase));
const attenuated=expected>this.align.peak-20 && frame[0]<quietest+anchor.gain-18;
if (attenuated) {
this.loss??={start:i,last:i,active:0,phase:anchor.phase};
this.loss.last=i; this.loss.active++;
} else if (this.loss && (i-this.loss.last>3 || frame[0]>expected+anchor.gain-8)) this.flushLoss();
}
}
cadence(anchor) {
if (!this.rateBase) { this.rateBase={...anchor,end:this.end}; return; }
const ticks=this.end-this.rateBase.end;
if (ticks<500) return;
const ppm=Math.round(1e6*phaseDelta(anchor.phase,this.rateBase.phase,this.align.length)/ticks);
if (Math.abs(ppm)>=4000 && Math.sign(ppm)===Math.sign(this.previousRate) && Math.abs(this.previousRate)>=4000) {
this.firstRate??=10*this.rateBase.end;
this.event(4,this.rateBase.end,ticks,ppm,this.rateBase.phase);
}
if (Math.abs(ppm)>Math.abs(this.maxRate)) this.maxRate=ppm;
this.previousRate=ppm; this.rateBase={...anchor,end:this.end};
}
observe(batch, endMs, complete) {
this.frames.push(...batch); this.end+=batch.length;
const anchor=this.align.match(this.frames,this.end);
if (batch.some(row=>!row[2])) this.discontinuities++;
const previous=this.candidate;
const stable=anchor && previous && this.end-previous.end<=50 &&
Math.abs(phaseDelta(anchor.phase,previous.phase,this.align.length))<=2;
if (stable) {
const shift=this.anchor ? phaseDelta(anchor.phase,this.anchor.phase,this.align.length) : 0;
const fresh=this.anchor && this.end-this.anchor.end<=275;
if (!this.anchor && this.scored<this.end-150) this.score(this.end-150,null);
if (Math.abs(shift)>=4 && fresh) {
this.flushLoss(); this.firstShift??=10*this.scored;
if (Math.abs(10*shift)>Math.abs(this.shift)) this.shift=-10*shift;
this.event(2,this.scored,this.end-this.scored,-10*shift,this.anchor.phase);
this.rateBase=null; this.previousRate=0;
this.score(this.end,null);
} else {
this.score(this.end,anchor);
this.cadence(anchor);
}
this.anchor={...anchor,end:this.end}; this.known=true;
} else if (this.end-this.scored>275) this.score(this.end-150,null);
if (anchor) this.candidate={...anchor,end:this.end};
if (complete) {
this.score(this.end,null); this.flushLoss();
if (this.unknownStart!=null && this.end-this.unknownStart>=10) {
this.event(3,this.unknownStart,this.end-this.unknownStart); this.unknownStart=null;
}
}
if (this.frames.length>300) this.frames.splice(0,this.frames.length-300);
const drift=this.anchor ? (this.anchor.phase+this.end)%this.align.length : -1;
return {locked:this.known, complete, observedMs:10*this.end, windows:this.end, scoredEndMs:endMs,
stageMinutes:this.minutes,firstLevelDropMs:this.firstDrop,longestLevelDropMs:this.maxDrop,
firstUnclearMs:this.firstUnknown,gapMaxMs:this.maxUnknown,discontinuities:this.discontinuities,
timing:{rateCoverageMs:0,edgeCount:0,maxRatePpm:0,firstRateMs:null,maxShiftMs:this.shift,
firstShiftMs:this.firstShift,baselinePpm:null},
speech:{coverageMs:10*this.trusted,phase:drift,phaseAgeMs:this.anchor?10*(this.end-this.anchor.end):-1,
total:this.count,events:this.events.slice(),firstRateMs:this.firstRate,maxCadencePpm:this.maxRate}};
}
}

View File

@ -0,0 +1,45 @@
// A 10 ms speech-band level and a high-frequency level. The worklet sends
// these features to the page. Raw input never leaves the worklet on this port.
export class SpeechEnvelope {
constructor(rate, emit) {
this.rate = rate;
this.emit = emit;
this.lowCoeff = 1 - Math.exp(-2 * Math.PI * 150 / rate);
this.highCoeff = 1 - Math.exp(-2 * Math.PI * 1600 / rate);
this.low = this.high = this.energy = this.highEnergy = 0;
this.frames = this.count = 0;
this.next = Math.round(rate / 100);
this.bin = 0;
this.present = true;
}
push(samples, length) {
for (let i = 0; i < length; i++) {
const x = samples?.[i] ?? 0;
this.present &&= i < (samples?.length ?? 0);
this.low += this.lowCoeff * (x - this.low);
this.high += this.highCoeff * (x - this.high);
this.energy += (x - this.low) ** 2;
this.highEnergy += (x - this.high) ** 2;
this.count++;
if (++this.frames < this.next) continue;
const db = e => 10 * Math.log10(Math.max(1e-10, e / this.count));
this.emit(db(this.energy), db(this.highEnergy), this.present);
this.energy = this.highEnergy = this.count = 0;
this.present = true;
this.next = Math.round((++this.bin + 1) * this.rate / 100);
}
}
}
export async function speechBuffer(context) {
const response = await fetch('speech-reference.flac');
if (!response.ok) throw Error('Speech reference unavailable');
return context.decodeAudioData(await response.arrayBuffer());
}
export function referenceFeatures(samples, rate) {
const levels = [], highs = [];
const envelope = new SpeechEnvelope(rate, (level, high) => { levels.push(level); highs.push(high); });
envelope.push(samples, samples.length);
return {levels, highs};
}

View File

@ -0,0 +1,88 @@
import {speechBuffer, referenceFeatures} from './speech-envelope.js';
import {SpeechDetector} from './speech-detector.js';
import {LocalRecording} from './local-recording.js';
const el=id=>document.getElementById(id);
const digital=new URLSearchParams(location.search).get('test')==='digital';
let replayUrl=null, replayGeneration=0;
function resetReplay() {
el('hear-finding').hidden=true; el('hear-finding').onclick=null;
el('speech-replay').hidden=true;
el('speech-replay').removeAttribute('src');
el('speech-replay').load();
if (replayUrl) URL.revokeObjectURL(replayUrl);
replayUrl=null;
}
const time=ms=>(ms/1000).toFixed(2)+' s';
export async function attachSpeech(run, isCurrent, finish) {
const serial=++replayGeneration;
resetReplay();
el('record-status').textContent='';
await run.context.audioWorklet.addModule('speech-worklet.js');
const buffer=await speechBuffer(run.context);
if (!isCurrent()) return;
const detector=new SpeechDetector(referenceFeatures(buffer.getChannelData(0),buffer.sampleRate),run.stage.minutes);
const node=new AudioWorkletNode(run.context,'speech-probe',{processorOptions:{minutes:run.stage.minutes}});
run.detector=node; run.pathInterruptions=0;
el('path-state').textContent='Listening for the spoken phrase';
el('path-detail').hidden=false;
el('path-timing').hidden=true;
if (el('keep-speech').checked) {
run.recording=new LocalRecording({audioOnly:true,maxMs:(run.stage.minutes+1)*60000,maxBytes:32*1024*1024,
onStatus:text=>{if(serial===replayGeneration) el('record-status').textContent=text;},
onReady:blob=>{
if(serial!==replayGeneration) return;
replayUrl=URL.createObjectURL(blob);
const player=el('speech-replay');
player.src=replayUrl; player.hidden=false;
if (Number.isFinite(run.firstFindingMs)) {
el('hear-finding').hidden=false;
el('hear-finding').onclick=()=>{
player.currentTime=Math.max(0,(run.pathStart-run.clipStart+run.firstFindingMs)/1000-1.5);
void player.play().catch(()=>{});
};
}
}});
run.clipStart=performance.now();
run.recording.start(run.stream);
}
node.onprocessorerror=()=>{if(isCurrent()) finish('speech detector failed');};
node.port.onmessage=({data})=>{
if (!isCurrent()) return;
if (data.expired) {finish('lost speech observer');return;}
node.port.postMessage('ack');
const path=detector.observe(data.batch,data.endMs,data.complete);
const now=performance.now();
const observedAtMono=now-Math.max(0,1000*run.context.currentTime-data.endMs);
run.pathStart??=observedAtMono-path.observedMs;
if(Math.abs(observedAtMono-run.pathStart-path.observedMs)>2000) run.clockGap=true;
path.discontinuities+=run.pathInterruptions+Number(!!run.clockGap);
run.path={...path,observedAtMono};
// Receipt kind 2 marks a digitally injected source; 1 is the phone/acoustic source.
if (digital) run.path.speech={...path.speech,kind:2};
const s=path.speech;
const first=s.events[0]?.[2];
if (Number.isFinite(first)) run.firstFindingMs=Math.min(run.firstFindingMs??Infinity,first);
const clock=Math.floor(path.observedMs/60000)+':'+String(Math.floor(path.observedMs/1000)%60).padStart(2,'0');
let finding='';
if (path.firstLevelDropMs!==null) finding='Speech attenuation at '+time(path.firstLevelDropMs)+' · longest '+path.longestLevelDropMs+' ms';
else if (path.timing.firstShiftMs!==null) finding='Phrase timing shifted near '+time(path.timing.firstShiftMs);
else if (s.firstRateMs!==null) finding='Speech cadence changed near '+time(s.firstRateMs);
else if (path.discontinuities) finding='Capture interrupted';
else if (path.firstUnclearMs!==null || (data.complete && s.coverageMs<path.observedMs))
finding='Part of the phrase could not be verified';
el('path-detail').textContent='Reference matched '+time(s.coverageMs)+' of '+time(path.observedMs)+
(s.total?' · '+s.total+' recorded observations':'');
if (digital) {
el('path-state').textContent=(data.complete?'Digital run complete':path.locked?'Digital run':'Acquiring reference')+
' · '+clock+' / '+run.stage.minutes+':00 · '+s.total+' events';
if (data.complete) finish('phone test complete');
return;
}
el('path-state').textContent=(data.complete?(finding?'Stage held':'Stage complete'):
(finding?'Still measuring':path.locked?'Tracking speech':'Acquiring speech'))+' · '+clock+' / '+run.stage.minutes+':00'+
(finding?' · '+finding:'');
if (data.complete) finish(finding?'stage finding':'phone test complete');
};
run.source.connect(node); node.connect(run.context.destination);
}

View File

@ -0,0 +1,42 @@
import {SpeechEnvelope} from './speech-envelope.js';
class SpeechProbe extends AudioWorkletProcessor {
constructor({processorOptions:{minutes}}) {
super();
this.limit = 6000 * minutes;
this.ticks = 0;
this.batch = [];
this.lastAck = currentFrame;
this.previousEnd = null;
this.contiguous = true;
this.port.onmessage = ({data}) => {
if (data === 'stop') this.stopped = true;
if (data === 'ack') this.lastAck = currentFrame;
};
this.envelope = new SpeechEnvelope(sampleRate, (level, high, present) => {
if (this.ticks >= this.limit) return;
this.batch.push([level, high, present && this.contiguous]);
this.contiguous = true;
this.ticks++;
});
}
process(inputs, outputs) {
if (this.stopped) return false;
if (currentFrame - this.lastAck > 10 * sampleRate) {
this.port.postMessage({expired:true}); return false;
}
const count = outputs[0][0].length;
if (this.previousEnd !== null && this.previousEnd !== currentFrame) this.contiguous = false;
this.previousEnd = currentFrame + count;
const before = this.envelope.frames;
this.envelope.push(inputs[0]?.[0], count);
const complete = this.ticks === this.limit;
if (this.batch.length >= 25 || complete) {
const end = currentFrame + Math.round(this.ticks * sampleRate / 100) - before;
this.port.postMessage({batch:this.batch, endMs:end * 1000 / sampleRate, complete});
this.batch = [];
}
return !complete;
}
}
registerProcessor('speech-probe', SpeechProbe);

View File

@ -0,0 +1,51 @@
// Passive long watch: counts render callbacks and input samples on the audio
// thread (not subject to page timer throttling). Never copies or sends audio.
export class WatchCounter {
constructor(rate, now) {
this.rate=rate;this.now=now;this.last=0;this.zeroRun=0;this.zeroStart=0;this.reset(now());
}
reset(at) {
this.w={at,blocks:0,frames:0,noInput:0,energy:0,peak:0,zero:0,zeroMax:0,zeroMaxStart:0,
gaps:0,gapMax:0,gapStart:0};
}
block(samples, length) {
const now=this.now(),w=this.w;
// A render callback gap: the audio thread itself was not serviced.
if(this.last && now-this.last>50) {
w.gaps++;
if(now-this.last>w.gapMax){w.gapMax=now-this.last;w.gapStart=this.last;}
}
this.last=now;w.blocks++;
if(!samples){w.noInput+=length;this.zeroRun=0;}
else for(const v of samples) {
w.frames++;w.energy+=v*v;const a=Math.abs(v);if(a>w.peak)w.peak=a;
if(v===0) {
if(!this.zeroRun++)this.zeroStart=now;
w.zero++;
if(this.zeroRun>w.zeroMax){w.zeroMax=this.zeroRun;w.zeroMaxStart=this.zeroStart;}
} else this.zeroRun=0;
}
if(now-w.at<1000)return null;
const out={at:now,startedAt:w.at,blocks:w.blocks,frames:w.frames,noInputFrames:w.noInput,
rms:w.frames?Math.sqrt(w.energy/w.frames):0,peak:w.peak,zeroFrames:w.zero,
zeroRunMs:Math.round(w.zeroMax*1000/this.rate),zeroRunStart:w.zeroMaxStart,
gaps:w.gaps,gapMaxMs:w.gapMax,gapStart:w.gapStart,rate:this.rate};
this.reset(now);
return out;
}
}
if(typeof registerProcessor==='function') {
registerProcessor('av-watch',class extends AudioWorkletProcessor {
constructor() {
super();this.counter=new WatchCounter(sampleRate,()=>Date.now());this.stopped=false;
this.port.onmessage=({data})=>{if(data==='stop')this.stopped=true;};
}
process(inputs,outputs) {
if(this.stopped)return false;
const second=this.counter.block(inputs[0]?.[0],outputs[0]?.[0]?.length??128);
if(second)this.port.postMessage(second);
return true;
}
});
}

View File

@ -9,4 +9,4 @@ spec:
- ReadWriteOnce - ReadWriteOnce
resources: resources:
requests: requests:
storage: 25Gi storage: 40Gi

View File

@ -0,0 +1,23 @@
# services/jenkins/ingress-http.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: jenkins-http
namespace: jenkins
annotations:
traefik.ingress.kubernetes.io/router.entrypoints: web
traefik.ingress.kubernetes.io/router.tls: "false"
traefik.ingress.kubernetes.io/router.middlewares: jenkins-jenkins-https-redirect@kubernetescrd
spec:
ingressClassName: traefik
rules:
- host: ci.bstein.dev
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: jenkins
port:
name: http

View File

@ -17,6 +17,8 @@ resources:
- vault-sync-deployment.yaml - vault-sync-deployment.yaml
- deployment.yaml - deployment.yaml
- service.yaml - service.yaml
- middleware-https-redirect.yaml
- ingress-http.yaml
- ingress.yaml - ingress.yaml
- lesavka-userns-probe.yaml - lesavka-userns-probe.yaml
- lesavka-kvm-device-plugin.yaml - lesavka-kvm-device-plugin.yaml

View File

@ -0,0 +1,10 @@
# services/jenkins/middleware-https-redirect.yaml
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: jenkins-https-redirect
namespace: jenkins
spec:
redirectScheme:
scheme: https
permanent: true

View File

@ -0,0 +1,56 @@
// Read public worker definitions through the installed Pipeline step. Supply two
// reviewed commits with different payload hashes and an existing software run.
// No job is created, saved, queued or changed; credentials stay inside GitSCMSource.
import groovy.json.JsonOutput
import hudson.model.Run
import hudson.model.TaskListener
import jenkins.model.Jenkins
import jenkins.plugins.git.GitSCMSource
import org.jenkinsci.plugins.workflow.steps.StepContext
import org.jenkinsci.plugins.workflow.steps.scm.ReadScmFileStep
import java.security.MessageDigest
def job = Jenkins.get().getItemByFullName('lesavka-software-tests')
def build = job.getBuildByNumber(binding.getVariable('existingBuild') as int)
assert build != null && !build.building
def before = job.configFile.asString()
def context = [get: { Class type ->
if (type == Run) { return build }
if (type == TaskListener) { return TaskListener.NULL }
throw new IllegalStateException('Unexpected step context: ' + type.name)
}] as StepContext
def source = new GitSCMSource('https://scm.bstein.dev/bstein/lesavka.git')
source.credentialsId = 'gitea-pat'
def read = { String revision, String path ->
def execution = new ReadScmFileStep(source, revision, path).start(context)
def method = execution.class.getDeclaredMethod('run')
method.accessible = true
method.invoke(execution)
}
def digest = { String value ->
MessageDigest.getInstance('SHA-256').digest(value.getBytes('UTF-8')).encodeHex().toString()
}
def expected = binding.getVariable('expectedPayloads')
assert expected.size() == 2 && expected.values().toSet().size() == 2
def checks = []
expected.each { revision, sha256 ->
assert revision ==~ /[0-9a-f]{40}/
assert sha256 ==~ /[0-9a-f]{64}/
assert digest(read(revision, 'docker/software-test-pod.yaml')) == sha256
checks << 'exact_worker_payload_' + revision
}
boolean missingRefused = false
try {
read('0' * 40, 'docker/software-test-pod.yaml')
} catch (java.lang.reflect.InvocationTargetException failure) {
assert failure.cause instanceof hudson.AbortException
assert failure.cause.message == 'No such revision'
missingRefused = true
}
assert missingRefused
checks << 'missing_revision_refused_without_fallback'
assert job.configFile.asString() == before
checks << 'installed_job_unchanged'
println(JsonOutput.toJson([status: 'passed', checks: checks,
plugin: Jenkins.get().pluginManager.getPlugin('workflow-scm-step').version]))
return null

View File

@ -5,6 +5,66 @@ metadata:
name: vmalert-atlas-availability-rules name: vmalert-atlas-availability-rules
namespace: monitoring namespace: monitoring
data: data:
ingress-health.yaml: |
groups:
- name: atlas.ingress.health
interval: 1m
# Availability must use fresh samples, not the rollups' one-hour lookback.
params:
step: [2m]
rules:
- alert: AtlasIngressUnavailable
expr: (max(kube_deployment_status_replicas_available{namespace="traefik",deployment="traefik"}) or vector(0)) == 0
for: 1m
labels:
severity: critical
service: atlas-ingress
annotations:
summary: "Atlas ingress has no available replicas"
description: "Public services including ci.bstein.dev may be unreachable. Check Traefik readiness, termination reasons and kube-state-metrics freshness before restarting applications."
- alert: AtlasIngressRedundancyLost
expr: |
(max(kube_deployment_status_replicas_available{namespace="traefik",deployment="traefik"}) < 2)
and (max(kube_deployment_status_replicas_available{namespace="traefik",deployment="traefik"}) > 0)
for: 5m
labels:
severity: warning
service: atlas-ingress
annotations:
summary: "Atlas ingress has lost its second replica"
description: "Only one Traefik replica has been available for five minutes. Inspect rollout events, /ping and memory pressure before the remaining replica fails."
- alert: AtlasIngressOOMKilled
expr: |
(max by (namespace, pod, container) (kube_pod_container_status_last_terminated_reason{namespace="traefik",container="traefik",reason="OOMKilled"}) == 1)
and on (namespace, pod, container)
(max by (namespace, pod, container) (increase(kube_pod_container_status_restarts_total{namespace="traefik",container="traefik"}[15m])) > 0)
labels:
severity: warning
service: atlas-ingress
annotations:
summary: "Traefik was killed by its memory limit"
description: "{{ $labels.pod }} restarted after an OOM kill. Inspect open connections, request timeouts and Go memory usage; increasing the limit alone does not bound retained connections."
- alert: AtlasIngressMemoryPressure
expr: |
max by (namespace, pod, container) (container_memory_working_set_bytes{namespace="traefik",container="traefik"})
/ on (namespace, pod, container)
max by (namespace, pod, container) (kube_pod_container_resource_limits{namespace="traefik",container="traefik",resource="memory"}) > 0.85
for: 5m
labels:
severity: warning
service: atlas-ingress
annotations:
summary: "Traefik memory has exceeded 85% of its limit"
description: "{{ $labels.pod }} is approaching its memory limit. Check connection counts and timeout settings before ingress becomes unavailable."
- alert: JenkinsControllerUnavailable
expr: (max(kube_deployment_status_replicas_available{namespace="jenkins",deployment="jenkins"}) or vector(0)) == 0
for: 2m
labels:
severity: critical
service: jenkins
annotations:
summary: "Jenkins has no available controller"
description: "Check Jenkins pod events, /login, its PVC and Vault initialization. If the controller is healthy, check Traefik and SSO separately. Missing deployment telemetry also triggers this alert."
hermes-triage.yaml: | hermes-triage.yaml: |
groups: groups:
- name: hermes.triage - name: hermes.triage