Skip to content

The free and privacy-friendly screen recorder with no limits πŸŽ₯

Windows H.264 recording reliability, stuck-recorder recovery, encoder + cleanup hardening

Alyssa X40566b7b37b5
diff --git a/package.json b/package.json
index bb5767d..45997dd 100755
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "screenity",
- "version": "4.4.10",
+ "version": "4.4.11",
"description": "The free and privacy-friendly screen recorder with no sign in needed.",
"scripts": {
"build": "cross-env NODE_ENV=production node utils/build.js",
diff --git a/src/manifest.json b/src/manifest.json
index c1a0764..18cb6da 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.4.10",
+ "version": "4.4.11",
"background": {
"service_worker": "background.bundle.js"
},
diff --git a/src/media/fastRecorderGate.ts b/src/media/fastRecorderGate.ts
index caf1362..b6fa0f2 100644
--- a/src/media/fastRecorderGate.ts
+++ b/src/media/fastRecorderGate.ts
@@ -451,7 +451,9 @@ const _probeFastRecorderSupportUncached = async (): Promise<FastRecorderProbeRes
{ width: 1280, height: 720 },
{ width: 1920, height: 1080 },
];
- const codecCandidates = ["avc1.64002A", "avc1.4D401F", "avc1.42E01E"];
+ // High L4.2 and Baseline L4.0. Main (avc1.4D...) excluded for the
+ // Windows MFT silent-no-output bug (see WebCodecsRecorder).
+ const codecCandidates = ["avc1.64002A", "avc1.42E028"];
const hwOptions: Array<VideoEncoderConfig["hardwareAcceleration"] | null> = [
"prefer-hardware",
"prefer-software",
@@ -551,7 +553,7 @@ const _probeFastRecorderSupportUncached = async (): Promise<FastRecorderProbeRes
}
}
- const videoCodecCandidates = ["avc1.64002A", "avc1.4D401F", "avc1.42E01E"];
+ const videoCodecCandidates = ["avc1.64002A", "avc1.42E028"];
const audioCodec = "mp4a.40.2";
details.videoCodecCandidates = videoCodecCandidates;
details.audioCodec = audioCodec;
diff --git a/src/pages/Background/listeners/onActionButtonClickedListener.js b/src/pages/Background/listeners/onActionButtonClickedListener.js
index ce9fa69..c8d8ee5 100644
--- a/src/pages/Background/listeners/onActionButtonClickedListener.js
+++ b/src/pages/Background/listeners/onActionButtonClickedListener.js
@@ -183,6 +183,17 @@ export const onActionButtonClickedListener = () => {
const { recording, pendingRecording, restarting, recorderSession } = snap;
const sessionRecording = recorderSession?.status === "recording";
+ // Whitelist of statuses that indicate a session may still have
+ // work in flight. Anything else β€” completed, cancelled, failed,
+ // crashed, stale-cleared, stopped, or any future addition β€” gets
+ // bypass treatment so stale pendingRecording/recordingTab flags
+ // can fall through to the reset+reopen path. Whitelisting is
+ // safer than blacklisting: forgetting to add a new terminal
+ // status would silently trap users.
+ const sessionInFlight =
+ recorderSession?.status === "recording" ||
+ recorderSession?.status === "restarting";
+ const sessionTerminal = Boolean(recorderSession?.status) && !sessionInFlight;
const isRecordingActive = Boolean(
recording || pendingRecording || restarting || sessionRecording,
);
@@ -210,7 +221,7 @@ export const onActionButtonClickedListener = () => {
}
}
- if (recordingTab && !hasActiveRecorder) {
+ if (recordingTab && !hasActiveRecorder && !sessionTerminal) {
if (await doesTabExist(recordingTab)) {
hasActiveRecorder = true;
} else {
@@ -219,7 +230,7 @@ export const onActionButtonClickedListener = () => {
}
}
- if (offscreen && !hasActiveRecorder) {
+ if (offscreen && !hasActiveRecorder && !sessionTerminal) {
if (await isOffscreenAlive()) {
hasActiveRecorder = true;
} else {
diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsx
index 0da568c..7224cb8 100644
--- a/src/pages/CloudRecorder/CloudRecorder.jsx
+++ b/src/pages/CloudRecorder/CloudRecorder.jsx
@@ -10,6 +10,7 @@ import localforage from "localforage";
import { createVideoProject } from "./createVideoProject";
import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";
import { shouldAcquireMicAtStart } from "../utils/micAcquisitionPolicy";
+import { attachAudioContextWatchdog } from "../utils/audioContextWatchdog";
import { traceStep } from "../utils/startFlowTrace";
import { IS_OFFSCREEN_HOST } from "../utils/recordingHost";
import { startPrewarm, stopPrewarm } from "../Recorder/streamWarmup";
@@ -5626,7 +5627,12 @@ const CloudRecorder = () => {
console.warn("⚠️ Failed to access camera stream:", err);
cameraStream.current = null;
}
- } else if (data.recordingType === "region" && IS_IFRAME_CONTEXT) {
+ } else if (
+ (data.recordingType === "region" || regionRef.current) &&
+ IS_IFRAME_CONTEXT
+ ) {
+ // Key off regionRef.current (set on the crop-target postMessage), not
+ // the raceable recordingType, so region uses preferCurrentTab + cropTo.
try {
const constraints = {
preferCurrentTab: true,
@@ -5929,7 +5935,7 @@ const CloudRecorder = () => {
perfMark("CloudRecorder.encoderPrewarm.fired", {
w,
h,
- codec: probeConfig?.codec || "avc1.4D401F",
+ codec: probeConfig?.codec || "avc1.64002A",
framerate:
Number(settings.frameRate) ||
Number(probeConfig?.framerate) ||
@@ -5938,7 +5944,7 @@ const CloudRecorder = () => {
void startEncoderPrewarm({
width: w,
height: h,
- codec: probeConfig?.codec || "avc1.4D401F",
+ codec: probeConfig?.codec || "avc1.64002A",
bitrate: Number(probeConfig?.bitrate) || 4_000_000,
framerate:
Number(settings.frameRate) ||
@@ -6181,6 +6187,7 @@ const CloudRecorder = () => {
// Some platforms reject hint sampleRates; fall back to default.
aCtx.current = new AudioContext();
}
+ attachAudioContextWatchdog(aCtx.current, "CloudRecorder");
destination.current = aCtx.current.createMediaStreamDestination();
if (micStream.current?.getAudioTracks().length) {
@@ -6388,6 +6395,7 @@ const CloudRecorder = () => {
});
} else if (
!isTab.current &&
+ !(IS_IFRAME_CONTEXT && regionRef.current) &&
(data.recordingType != "region" || tabPreferred.current)
) {
_diagBranch("desktop-picker");
diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.js
index ec9ae00..4811fc4 100644
--- a/src/pages/CloudRecorder/bunnyTusUploader.js
+++ b/src/pages/CloudRecorder/bunnyTusUploader.js
@@ -1,5 +1,39 @@
const API_BASE = process.env.SCREENITY_API_BASE_URL;
+// Guard so uploaders in the same page session don't sweep concurrently.
+let _journalSweepDone = false;
+
+// Sweep TTL is generous (14d) vs the 24h resume-validity check: the only cost
+// of not sweeping is quota buildup, so leave multi-day uploads room to resume.
+const JOURNAL_SWEEP_TTL_MS = 14 * 24 * 60 * 60 * 1000;
+
+// Orphan uploadJournal-<mediaId> entries accumulate against the storage.local
+// 5MB cap when an uploader dies before finalize/abort. Sweep once per session.
+async function sweepStaleUploadJournals() {
+ if (_journalSweepDone) return;
+ _journalSweepDone = true;
+ if (typeof chrome === "undefined" || !chrome.storage?.local) return;
+ try {
+ const all = await chrome.storage.local.get(null);
+ const cutoff = Date.now() - JOURNAL_SWEEP_TTL_MS;
+ const stale = [];
+ for (const [key, value] of Object.entries(all || {})) {
+ if (!key.startsWith("uploadJournal-")) continue;
+ const updatedAt = Number(value?.updatedAt) || 0;
+ if (updatedAt > 0 && updatedAt < cutoff) stale.push(key);
+ }
+ if (stale.length > 0) {
+ console.log(
+ `[bunnyTusUploader] sweeping ${stale.length} stale journal entries (>${JOURNAL_SWEEP_TTL_MS / (24 * 60 * 60 * 1000)}d)`,
+ );
+ await chrome.storage.local.remove(stale);
+ }
+ } catch (err) {
+ // Non-fatal: a future sweep catches the leftover quota.
+ console.warn("[bunnyTusUploader] journal sweep failed", err);
+ }
+}
+
export async function getThumbnailFromBlob(blob, seekTo = 0.1) {
return new Promise((resolve, reject) => {
const video = document.createElement("video");
@@ -196,7 +230,7 @@ export default class BunnyTusUploader {
}
}
- setUploaderError(errorCode, err = null) {
+ setUploaderError(errorCode, err = null, extra = null) {
this.status = "error";
this.error = errorCode || err?.message || "upload-error";
this.lastErrorAt = Date.now();
@@ -206,6 +240,7 @@ export default class BunnyTusUploader {
this.emitTelemetry("upload_error", {
errorCode: errorCode || null,
message: err?.message || this.error || "upload-error",
+ ...(extra && typeof extra === "object" ? extra : {}),
});
this.scheduleJournalPersist({ force: true });
}
@@ -634,6 +669,9 @@ export default class BunnyTusUploader {
throw new Error("Uploader has already been initialized");
}
+ // Fire-and-forget orphan-journal cleanup; doesn't block the hot path.
+ void sweepStaleUploadJournals();
+
try {
this.projectId = projectId;
this.metadata = { title, type, linkedMediaId, sceneId };
@@ -1096,13 +1134,16 @@ export default class BunnyTusUploader {
let didAuth401Refresh = false;
for (let attempt = 0; attempt <= this.MAX_RETRIES; attempt++) {
+ // Hoisted so the catch can read signal.reason (wake-jump/stall-recovery/
+ // upload-timeout) for telemetry; in-try it would be out of scope.
+ let controller = null;
try {
// AuthorizationSignature has ~20min TTL; refresh before every PATCH.
await this.checkAuthExpiration();
const currentOffset = this.offset;
- const controller = new AbortController();
+ controller = new AbortController();
// Exposed so the heartbeat can abort a stalled PATCH.
this.currentPatchAbort = controller;
const timeout = setTimeout(
@@ -1286,6 +1327,12 @@ export default class BunnyTusUploader {
throw new Error(`Upload failed (${res.status}): ${errorText}`);
}
} catch (err) {
+ // err.name collapses every abort to AbortError; signal.reason keeps the
+ // real trigger (wake-jump/stall-recovery/upload-timeout) for telemetry.
+ const abortReason =
+ controller?.signal?.aborted && typeof controller.signal.reason === "string"
+ ? controller.signal.reason
+ : null;
this.currentPatchAbort = null;
// Transient errors (network/timeout/stall-abort/5xx/408/429) retry forever with capped backoff.
const isExplicitAbort =
@@ -1302,14 +1349,19 @@ export default class BunnyTusUploader {
/Upload failed \((?:5\d\d|408|429)\b/.test(msg) ||
/network|Failed to fetch|timeout/i.test(msg);
if (err?.name === "AbortError") {
- console.warn("⚠️ Upload chunk aborted (timeout or stall-recovery)");
+ console.warn(
+ "⚠️ Upload chunk aborted",
+ abortReason ? `(${abortReason})` : "(reason unknown)",
+ );
}
if (!isTransient && attempt === this.MAX_RETRIES) {
console.error(
`❌ Non-transient failure after ${this.MAX_RETRIES} retries:`,
err,
);
- this.setUploaderError("chunk-upload-retries-exhausted", err);
+ this.setUploaderError("chunk-upload-retries-exhausted", err, {
+ abortReason,
+ });
throw err;
}
const attemptLabel = isTransient
diff --git a/src/pages/CloudRecorder/encoder/chooseEncoder.js b/src/pages/CloudRecorder/encoder/chooseEncoder.js
index 8500019..543cf37 100644
--- a/src/pages/CloudRecorder/encoder/chooseEncoder.js
+++ b/src/pages/CloudRecorder/encoder/chooseEncoder.js
@@ -125,7 +125,9 @@ export const inspectTrackPlan = async ({ track, probeOptions }) => {
return {
kind: "webcodecs",
container: "video/mp4",
- codec: "avc1.4D0028",
+ // Container/codec hint for Bunny's TUS Upload-Metadata. The real codec
+ // is picked at configure time by chooseVideoEncoderConfig.
+ codec: "avc1.64002A",
hwSlots: hwSlots.summary,
cameraPreferSoftware,
reason: cameraPreferSoftware ? "dual-webcodecs-camera-sw-mode" : "ok",
diff --git a/src/pages/CloudRecorder/encoder/hwSlotProbe.js b/src/pages/CloudRecorder/encoder/hwSlotProbe.js
index bec9d90..ab5bd46 100644
--- a/src/pages/CloudRecorder/encoder/hwSlotProbe.js
+++ b/src/pages/CloudRecorder/encoder/hwSlotProbe.js
@@ -5,15 +5,11 @@
// 4 Mbps baseline; real encoder uses the configured bitrate later.
const PROBE_BITRATE = 4_000_000;
-// Candidates ordered High β†’ Baseline so machines without the top
-// profile still probe successfully.
-// 64002A = High L4.2, 4D0028 = Main L4.0,
-// 4D401F = Main L3.1, 42E01E = Baseline L3.0
+// 64002A = High L4.2, 42E028 = Baseline L4.0 (Main 4D... omitted: silent-no-output
+// bug on Chromium's Windows MFT wrapper, accepts encode() but emits no chunks).
const CODEC_CANDIDATES = [
"avc1.64002A",
- "avc1.4D0028",
- "avc1.4D401F",
- "avc1.42E01E",
+ "avc1.42E028",
];
const HW_OPTIONS = ["prefer-hardware", "no-preference"];
@@ -83,6 +79,10 @@ const probeOne = async (label, { width, height, framerate }) => {
// buffering hides asymmetry until ~500ms in). 2s cap, memoized.
const CONCURRENT_FRAME_COUNT = 30;
const CONCURRENT_TIMEOUT_MS = 2500;
+// Windows D3D11 HW encoder (crbug 1504122) crashes when frames pile into
+// encode() without awaiting. Cap queue depth and yield so it can drain.
+const CONCURRENT_QUEUE_YIELD_EVERY = 5;
+const CONCURRENT_MAX_QUEUE_DEPTH = 16;
const probeConcurrentHw = async ({ codec, framerate }) => {
if (
@@ -152,6 +152,8 @@ const probeConcurrentHw = async ({ codec, framerate }) => {
}
const started =
typeof performance !== "undefined" ? performance.now() : Date.now();
+ let queueOverflow = false;
+ let framesSubmitted = 0;
for (let i = 0; i < CONCURRENT_FRAME_COUNT; i++) {
ctx.fillStyle = `hsl(${(i * 31) % 360}, 50%, 40%)`;
ctx.fillRect(0, 0, width, height);
@@ -173,6 +175,26 @@ const probeConcurrentHw = async ({ codec, framerate }) => {
b.encoder.encode(frameB, { keyFrame: i === 0 });
frameB.close();
} catch {}
+ framesSubmitted = i + 1;
+
+ // Yield every N frames so the encoder can drain. If either queue runs past
+ // the cap, HW is starved: bail and let the caller treat it as not-concurrent.
+ if (i % CONCURRENT_QUEUE_YIELD_EVERY === CONCURRENT_QUEUE_YIELD_EVERY - 1) {
+ await new Promise((r) => setTimeout(r, 0));
+ let qa = 0;
+ let qb = 0;
+ try {
+ qa = a.encoder?.encodeQueueSize ?? 0;
+ qb = b.encoder?.encodeQueueSize ?? 0;
+ } catch {}
+ if (
+ qa > CONCURRENT_MAX_QUEUE_DEPTH ||
+ qb > CONCURRENT_MAX_QUEUE_DEPTH
+ ) {
+ queueOverflow = true;
+ break;
+ }
+ }
}
try {
await Promise.race([
@@ -191,8 +213,10 @@ const probeConcurrentHw = async ({ codec, framerate }) => {
// We require at least 4 chunks from each (allowing for encoder
// buffering of the last keyframe close-out). A 2x ratio is the
// tripwire: anything worse means the second encoder is starved.
+ // Queue overflow is itself a not-concurrent signal: HW couldn't drain.
const minPerEncoder = 4;
const concurrent =
+ !queueOverflow &&
aChunks >= minPerEncoder &&
bChunks >= minPerEncoder &&
Math.max(aChunks, bChunks) / Math.max(1, Math.min(aChunks, bChunks)) < 2;
@@ -201,6 +225,8 @@ const probeConcurrentHw = async ({ codec, framerate }) => {
concurrent,
aChunks,
bChunks,
+ framesSubmitted,
+ queueOverflow,
elapsedMs: Math.round(elapsed),
};
};
diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsx
index 5677b88..f23a7c5 100644
--- a/src/pages/Recorder/Recorder.jsx
+++ b/src/pages/Recorder/Recorder.jsx
@@ -15,6 +15,7 @@ import {
} from "./encoderPrewarm";
import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";
import { shouldAcquireMicAtStart } from "../utils/micAcquisitionPolicy";
+import { attachAudioContextWatchdog } from "../utils/audioContextWatchdog";
import { IS_OFFSCREEN_HOST } from "../utils/recordingHost";
import { chooseWriter } from "./recorderStorage/chooseWriter";
import { chooseReader } from "./recorderStorage/chooseReader";
@@ -2618,14 +2619,32 @@ const Recorder = () => {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const audioInputs = devices.filter((d) => d.kind === "audioinput");
+ // If the mic label drops out of enumeration the device is gone and may emit
+ // silent zeros while readyState stays "live" (crbug 40275281). Match by label.
+ let currentMicLabel = null;
+ try {
+ const micTrack = helperAudioStream.current?.getAudioTracks?.()[0];
+ currentMicLabel = micTrack?.label || null;
+ } catch {}
+ const currentMicStillPresent = currentMicLabel
+ ? audioInputs.some((d) => d.label === currentMicLabel)
+ : null;
chrome.runtime.sendMessage({
type: "diag-forward",
event: "recorder-devicechange-mid-recording",
data: {
audioInputCount: audioInputs.length,
labels: audioInputs.map((d) => d.label).slice(0, 5),
+ currentMicLabel,
+ currentMicStillPresent,
},
});
+ if (currentMicLabel && currentMicStillPresent === false) {
+ console.warn(
+ "[Recorder] mid-recording devicechange: current mic label no longer enumerable",
+ { label: currentMicLabel },
+ );
+ }
} catch {}
};
try {
@@ -3250,6 +3269,27 @@ const Recorder = () => {
debug("startAudioStream() got stream with exact device", {
hasAudio: stream.getAudioTracks().length,
});
+ // A BT headset used as mic switches A2DP (48k) to HFP (8/16k mono), but
+ // the 48k AudioContext then upsamples garbage. Log as a diag breadcrumb.
+ try {
+ const aTrack = stream.getAudioTracks?.()[0];
+ const settings = aTrack?.getSettings?.() || {};
+ const trackSampleRate = Number(settings.sampleRate) || null;
+ if (trackSampleRate && trackSampleRate <= 24000) {
+ const label = String(aTrack?.label || "").slice(0, 80);
+ console.warn(
+ "[Recorder] mic acquired at low sample rate; likely Bluetooth HFP profile",
+ { trackSampleRate, label },
+ );
+ try {
+ chrome.runtime.sendMessage({
+ type: "diag-forward",
+ event: "recorder-low-sample-rate-mic",
+ data: { trackSampleRate, label },
+ });
+ } catch {}
+ }
+ } catch {}
return stream;
})
.catch((err) => {
@@ -3667,6 +3707,9 @@ const Recorder = () => {
perfMark("Recorder pre-audio-setup");
aCtx.current = new AudioContext();
+ // A mid-recording AudioContext "interrupted" (macOS audio-server restart,
+ // exclusive-audio grab, Energy Saver) silently encodes a muted gap; watchdog logs+resumes.
+ attachAudioContextWatchdog(aCtx.current, "Recorder");
destination.current = aCtx.current.createMediaStreamDestination();
liveStream.current = new MediaStream();
let mixedAudioConnected = false;
@@ -3889,10 +3932,9 @@ const Recorder = () => {
]);
const probeConfig =
probeData?.fastRecorderProbe?.details?.selectedVideoConfig || null;
- // Prefer the codec the probe selected (matches what WCR will
- // pick). Fall back to a Main-profile h264 that's broadly
- // supported by VTDecoder.
- const codec = probeConfig?.codec || "avc1.4D401F";
+ // Prefer the probe's codec; fall back to High L4.2 (Main is excluded
+ // from the ladder for Windows MFT silent-no-output, see WCR).
+ const codec = probeConfig?.codec || "avc1.64002A";
const bitrate =
Number(probeConfig?.bitrate) || 4_000_000;
const framerate =
diff --git a/src/pages/Recorder/recorderStorage/opfs/writerWorker.js b/src/pages/Recorder/recorderStorage/opfs/writerWorker.js
index 39cdac3..15b8cc3 100644
--- a/src/pages/Recorder/recorderStorage/opfs/writerWorker.js
+++ b/src/pages/Recorder/recorderStorage/opfs/writerWorker.js
@@ -35,6 +35,25 @@ const post = (payload) => {
self.postMessage(payload);
};
+// crbug/453704691: createSyncAccessHandle can throw NoModificationAllowedError
+// briefly while GC reclaims a prior handle. Retry with backoff before failing.
+const openSyncAccessHandleWithRetry = async (handle) => {
+ const delaysMs = [0, 200, 400, 600, 800];
+ let lastErr = null;
+ for (let i = 0; i < delaysMs.length; i += 1) {
+ if (delaysMs[i] > 0) {
+ await new Promise((r) => setTimeout(r, delaysMs[i]));
+ }
+ try {
+ return await handle.createSyncAccessHandle();
+ } catch (err) {
+ lastErr = err;
+ if (err?.name !== "NoModificationAllowedError") break;
+ }
+ }
+ throw lastErr;
+};
+
const openFile = async (recordingId, extension) => {
// Create NEW before deleting old: if creation fails, the previous
// recording remains intact for recovery, and a recovery editor
@@ -43,7 +62,7 @@ const openFile = async (recordingId, extension) => {
const ext = extension === "webm" ? "webm" : "mp4";
const name = `${FILE_PREFIX}${recordingId}.${ext}`;
const handle = await dir.getFileHandle(name, { create: true });
- const sync = await handle.createSyncAccessHandle();
+ const sync = await openSyncAccessHandleWithRetry(handle);
sync.truncate(0);
fileName = name;
syncHandle = sync;
diff --git a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
index 3b3c8cc..0341cc9 100644
--- a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
+++ b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
@@ -247,6 +247,27 @@ export class Mp4MuxerWrapper {
const next = last + durationUs;
(this as any)[key] = next;
this.log(`[MUX] audio ts +${durationUs} => ${next}`);
+ // AAC chunk.duration is unreliable (w3c/webcodecs#624), so our accumulated
+ // ts can drift from chunk.ts. Log when drift exceeds 100ms, once per ~30s.
+ if (
+ typeof timestampUs === "number" &&
+ timestampUs > 0 &&
+ !(this as any)._audioFirstTimestampUs
+ ) {
+ (this as any)._audioFirstTimestampUs = timestampUs;
+ }
+ const firstTs = (this as any)._audioFirstTimestampUs || 0;
+ if (firstTs && typeof timestampUs === "number") {
+ const expectedAccum = timestampUs - firstTs;
+ const drift = Math.abs(next - expectedAccum);
+ if (
+ drift > 100_000 &&
+ next - ((this as any)._audioDriftLogAt || 0) > 30_000_000
+ ) {
+ (this as any)._audioDriftLogAt = next;
+ this.warn(`[MUX] audio ts drift accum=${next} vs chunk.ts=${expectedAccum} (delta=${drift}us)`);
+ }
+ }
return next;
}
diff --git a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
index 5c5ea6f..089d3e4 100644
--- a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
+++ b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
@@ -621,7 +621,9 @@ export class WebCodecsRecorder {
this.err("[WCR] start() failed:", err);
this.options.onError?.(err);
this.running = false;
- this.cleanup();
+ // Await the async cleanup; fire-and-forget would let an immediate retry
+ // hit an in-flight reader with InvalidStateError.
+ await this.cleanup();
if (this._startResolve) {
this._startResolve(false);
@@ -632,7 +634,7 @@ export class WebCodecsRecorder {
this.err("[WCR] start() outer error:", err);
this.options.onError?.(err);
this.running = false;
- this.cleanup();
+ await this.cleanup();
if (this._startResolve) {
this._startResolve(false);
@@ -881,7 +883,9 @@ export class WebCodecsRecorder {
}
perfMark("WCR.stop.exit");
- this.cleanup();
+ // Await cleanup so reader-drain completes before onStop. Bounded by the
+ // 500ms per-reader cancel timeout, so it can't block stop() pathologically.
+ await this.cleanup();
if (this.options.onStop) {
await this.options.onStop();
@@ -952,7 +956,7 @@ export class WebCodecsRecorder {
this._lastChunkAt = performance.now();
}
- cleanup() {
+ async cleanup() {
this.log("[WCR] cleanup");
this._clearFirstChunkWatchdog();
@@ -960,12 +964,22 @@ export class WebCodecsRecorder {
this._detachVisibilityListener();
this._detachDeviceChangeListener();
- try {
- this.videoReader?.releaseLock();
- } catch {}
- try {
- this.audioReader?.releaseLock();
- } catch {}
+ // Drain readers before closing encoders: releaseLock doesn't cancel the in-flight
+ // read, so a frame can hit the encoder after close() (CVE-2026-5890 race). 500ms cap.
+ const cancelWithTimeout = async (reader) => {
+ if (!reader) return;
+ try {
+ await Promise.race([
+ reader.cancel(),
+ new Promise((resolve) => setTimeout(resolve, 500)),
+ ]);
+ } catch {}
+ try { reader.releaseLock(); } catch {}
+ };
+ await Promise.all([
+ cancelWithTimeout(this.videoReader),
+ cancelWithTimeout(this.audioReader),
+ ]);
try {
this.videoEncoder?.close();
@@ -2044,20 +2058,22 @@ export class WebCodecsRecorder {
]
: preferSoftware
? [
+ // Main (avc1.4D...) excluded: silent-no-output bug on Chromium's
+ // Windows MFT wrapper (encode() accepts, no chunks emit).
{ codec: "avc1.64002A", containerCodec: "avc", hw: "prefer-software" },
- { codec: "avc1.4D401F", containerCodec: "avc", hw: "prefer-software" },
- { codec: "avc1.42E01E", containerCodec: "avc", hw: "prefer-software" },
+ { codec: "avc1.42E028", containerCodec: "avc", hw: "prefer-software" },
+ { codec: "avc1.64002A", containerCodec: "avc", hw: "no-preference" },
{ codec: "avc1.64002A", containerCodec: "avc", hw: "prefer-hardware" },
- { codec: "avc1.4D401F", containerCodec: "avc", hw: "prefer-hardware" },
- { codec: "avc1.42E01E", containerCodec: "avc", hw: "prefer-hardware" },
+ { codec: "avc1.42E028", containerCodec: "avc", hw: "prefer-hardware" },
]
: [
+ // no-preference rung between High-HW and Baseline: on NVENC slot
+ // exhaustion (OBS/Zoom/Discord open) it keeps High over Baseline.
{ codec: "avc1.64002A", containerCodec: "avc", hw: "prefer-hardware" },
- { codec: "avc1.4D401F", containerCodec: "avc", hw: "prefer-hardware" },
- { codec: "avc1.42E01E", containerCodec: "avc", hw: "prefer-hardware" },
+ { codec: "avc1.64002A", containerCodec: "avc", hw: "no-preference" },
+ { codec: "avc1.42E028", containerCodec: "avc", hw: "prefer-hardware" },
{ codec: "avc1.64002A", containerCodec: "avc", hw: "prefer-software" },
- { codec: "avc1.4D401F", containerCodec: "avc", hw: "prefer-software" },
- { codec: "avc1.42E01E", containerCodec: "avc", hw: "prefer-software" },
+ { codec: "avc1.42E028", containerCodec: "avc", hw: "prefer-software" },
];
for (const c of candidates) {
@@ -2340,6 +2356,17 @@ export class WebCodecsRecorder {
this._forceNextKeyframe = true;
continue;
}
+ // Chrome 140+ caps the encode queue at 30 frames, throwing QuotaExceededError
+ // synchronously. Drop as backpressure so an oversubscribed recording survives.
+ if (encErr?.name === "QuotaExceededError") {
+ this._droppedForBackpressureCount += 1;
+ this._forceNextKeyframe = true;
+ this._videoFrameIndex = i + 1;
+ this.warn(
+ "[WCR] encode() QuotaExceededError; dropping frame as backpressure",
+ );
+ continue;
+ }
throw encErr;
}
if (
@@ -2531,9 +2558,23 @@ export class WebCodecsRecorder {
return;
}
- this.audioEncoder.encode(audioData, {
- timestamp: tsUs,
- });
+ try {
+ this.audioEncoder.encode(audioData, {
+ timestamp: tsUs,
+ });
+ } catch (encErr) {
+ // Audio encode-queue overflow: drop as backpressure (mirrors video) and
+ // advance the sample counter so timestamps stay aligned.
+ if (encErr?.name === "QuotaExceededError") {
+ this._droppedAudioForBackpressureCount += 1;
+ this.audioSamplesWritten += frames;
+ this.warn(
+ "[WCR] audio encode() QuotaExceededError; dropping audio data",
+ );
+ return;
+ }
+ throw encErr;
+ }
this.audioSamplesWritten += frames;
if (this.debug && (this.audioSamplesWritten === frames || this.audioSamplesWritten % (sampleRate * 10) < frames)) {
diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsx
index 1433f0c..327f02c 100644
--- a/src/pages/Region/Recorder.jsx
+++ b/src/pages/Region/Recorder.jsx
@@ -1,6 +1,7 @@
import React, { useEffect, useRef, useCallback } from "react";
import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";
import { shouldAcquireMicAtStart } from "../utils/micAcquisitionPolicy";
+import { attachAudioContextWatchdog } from "../utils/audioContextWatchdog";
import {
WebCodecsRecorder,
preloadWebCodecsModules,
@@ -2311,6 +2312,7 @@ const Recorder = () => {
preloadWebCodecsModules();
aCtx.current = new AudioContext();
+ attachAudioContextWatchdog(aCtx.current, "Region");
destination.current = aCtx.current.createMediaStreamDestination();
liveStream.current = new MediaStream();
// If the user disabled the mic, skip getUserMedia: gain-muting still
diff --git a/src/pages/RemuxOffscreen/worker.js b/src/pages/RemuxOffscreen/worker.js
index aa93b31..9ab8733 100644
--- a/src/pages/RemuxOffscreen/worker.js
+++ b/src/pages/RemuxOffscreen/worker.js
@@ -78,7 +78,24 @@ const remuxToOpfs = async ({ requestId, inputFileName, outputFileName }) => {
const inputFile = await inputHandle.getFile();
outputHandle = await dir.getFileHandle(outputFileName, { create: true });
- syncHandle = await outputHandle.createSyncAccessHandle();
+ // crbug/453704691: brief NoModificationAllowedError after prior
+ // handle GC. Retry with backoff before failing the remux.
+ syncHandle = await (async () => {
+ const delaysMs = [0, 200, 400, 600, 800];
+ let lastErr = null;
+ for (let i = 0; i < delaysMs.length; i += 1) {
+ if (delaysMs[i] > 0) {
+ await new Promise((r) => setTimeout(r, delaysMs[i]));
+ }
+ try {
+ return await outputHandle.createSyncAccessHandle();
+ } catch (err) {
+ lastErr = err;
+ if (err?.name !== "NoModificationAllowedError") break;
+ }
+ }
+ throw lastErr;
+ })();
syncHandle.truncate(0);
const writable = createOpfsWritable(syncHandle);
diff --git a/src/pages/utils/audioContextWatchdog.js b/src/pages/utils/audioContextWatchdog.js
new file mode 100644
index 0000000..3e8f2c0
--- /dev/null
+++ b/src/pages/utils/audioContextWatchdog.js
@@ -0,0 +1,70 @@
+// AudioContext lifecycle watchdog.
+//
+// Chrome's macOS "interrupted" state (audio-server restart, phone call,
+// exclusive-audio grab, Energy Saver) makes the connected MediaStreamDestination
+// emit silence, which the AudioEncoder encodes as an unflagged silent gap.
+// Diagnostic-first: log the transition and retry resume every 2s, but don't tear
+// down the recording, so user reports of "audio cut out" can be traced.
+
+import { diagEvent } from "./diagnosticLog";
+
+export function attachAudioContextWatchdog(aCtx, label) {
+ if (!aCtx || typeof aCtx.addEventListener !== "function") return;
+ let resumeTimer = null;
+ let interruptedAt = null;
+
+ const tryResume = () => {
+ if (!aCtx || aCtx.state === "closed" || aCtx.state === "running") {
+ return;
+ }
+ try {
+ aCtx.resume().catch(() => {});
+ } catch {}
+ };
+
+ const onChange = () => {
+ try {
+ const state = aCtx.state;
+ const detail = {
+ label,
+ state,
+ sinceInterruptedMs: interruptedAt ? Date.now() - interruptedAt : null,
+ };
+ try { diagEvent("audiocontext-statechange", detail); } catch {}
+ // Only auto-resume "interrupted" (OS-driven). "suspended" is the user's
+ // pause flow; resuming it would silently un-pause a Pro recording.
+ if (state === "interrupted") {
+ if (!interruptedAt) interruptedAt = Date.now();
+ if (!resumeTimer) {
+ resumeTimer = setInterval(tryResume, 2000);
+ }
+ } else if (state === "running") {
+ if (interruptedAt) {
+ try {
+ diagEvent("audiocontext-resumed", {
+ label,
+ interruptedForMs: Date.now() - interruptedAt,
+ });
+ } catch {}
+ }
+ interruptedAt = null;
+ if (resumeTimer) {
+ clearInterval(resumeTimer);
+ resumeTimer = null;
+ }
+ } else if (state === "closed" || state === "suspended") {
+ // suspended = user pause, closed = teardown: stop the resume timer.
+ // Re-arms via statechange if it later returns to interrupted.
+ interruptedAt = null;
+ if (resumeTimer) {
+ clearInterval(resumeTimer);
+ resumeTimer = null;
+ }
+ }
+ } catch {}
+ };
+
+ try {
+ aCtx.addEventListener("statechange", onChange);
+ } catch {}
+}