Skip to content

The free and privacy-friendly screen recorder with no limits 🎥

Recording starts torn down early, silent MP4 exports, unresponsive popup, + oversized camera uploads

Alyssa X512606387b8d
diff --git a/package-lock.json b/package-lock.json
index c934a24..b4cb500 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "screenity",
- "version": "4.6.6",
+ "version": "4.6.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "screenity",
- "version": "4.6.6",
+ "version": "4.6.7",
"hasInstallScript": true,
"dependencies": {
"@babel/plugin-transform-react-jsx": "^7.27.1",
diff --git a/package.json b/package.json
index 0232e39..dba84a5 100755
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "screenity",
- "version": "4.6.6",
+ "version": "4.6.7",
"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/patches/fabric+5.3.0.patch b/patches/fabric+5.3.0.patch
deleted file mode 100644
index 0917bd6..0000000
--- a/patches/fabric+5.3.0.patch
+++ /dev/null
@@ -1,22 +0,0 @@
-diff --git a/node_modules/fabric/dist/fabric.js b/node_modules/fabric/dist/fabric.js
-index faee7fc..02e5ae3 100644
---- a/node_modules/fabric/dist/fabric.js
-+++ b/node_modules/fabric/dist/fabric.js
-@@ -12591,7 +12591,7 @@ fabric.PatternBrush = fabric.util.createClass(fabric.PencilBrush, /** @lends fab
- this.cacheCanvasEl = this._createCanvasElement();
- this.cacheCanvasEl.setAttribute('width', this.width);
- this.cacheCanvasEl.setAttribute('height', this.height);
-- this.contextCache = this.cacheCanvasEl.getContext('2d');
-+ this.contextCache = this.cacheCanvasEl.getContext('2d', {willReadFrequently: true});
- },
-
- /**
-@@ -15103,7 +15103,7 @@ fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.Stati
- _createCacheCanvas: function() {
- this._cacheProperties = {};
- this._cacheCanvas = fabric.util.createCanvasElement();
-- this._cacheContext = this._cacheCanvas.getContext('2d');
-+ this._cacheContext = this._cacheCanvas.getContext('2d', {willReadFrequently: true});
- this._updateCacheCanvas();
- // if canvas gets created, is empty, so dirty.
- this.dirty = true;
diff --git a/patches/fabric+5.5.2.patch b/patches/fabric+5.5.2.patch
deleted file mode 100644
index 4501e30..0000000
--- a/patches/fabric+5.5.2.patch
+++ /dev/null
@@ -1,22 +0,0 @@
-diff --git a/node_modules/fabric/dist/fabric.js b/node_modules/fabric/dist/fabric.js
-index a7ad0f5..d8e7670 100644
---- a/node_modules/fabric/dist/fabric.js
-+++ b/node_modules/fabric/dist/fabric.js
-@@ -12596,7 +12596,7 @@ fabric.PatternBrush = fabric.util.createClass(fabric.PencilBrush, /** @lends fab
- this.cacheCanvasEl = this._createCanvasElement();
- this.cacheCanvasEl.setAttribute('width', this.width);
- this.cacheCanvasEl.setAttribute('height', this.height);
-- this.contextCache = this.cacheCanvasEl.getContext('2d');
-+ this.contextCache = this.cacheCanvasEl.getContext('2d', {willReadFrequently: true});
- },
-
- /**
-@@ -15108,7 +15108,7 @@ fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.Stati
- _createCacheCanvas: function() {
- this._cacheProperties = {};
- this._cacheCanvas = fabric.util.createCanvasElement();
-- this._cacheContext = this._cacheCanvas.getContext('2d');
-+ this._cacheContext = this._cacheCanvas.getContext('2d', {willReadFrequently: true});
- this._updateCacheCanvas();
- // if canvas gets created, is empty, so dirty.
- this.dirty = true;
diff --git a/src/manifest.json b/src/manifest.json
index 5abb446..363ffba 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.6.6",
+ "version": "4.6.7",
"background": {
"service_worker": "background.bundle.js"
},
diff --git a/src/pages/Background/recording/startRecording.js b/src/pages/Background/recording/startRecording.js
index 74e5ce4..bd26fd9 100644
--- a/src/pages/Background/recording/startRecording.js
+++ b/src/pages/Background/recording/startRecording.js
@@ -469,10 +469,14 @@ const _startRecordingInner = async (caller) => {
setTimeout(recheck, RECHECK_INTERVAL_MS);
return;
}
+ // No writer at all reads the same as a stalled one, so keep them apart.
+ const stalledStage = isThisStart
+ ? String(progress.stage || "unknown").slice(0, 40)
+ : "none";
if (isThisStart) {
diagEvent("warning", {
note: "start-fail after progress stalled",
- stage: String(progress.stage || "").slice(0, 40),
+ stage: stalledStage,
stalledMs: Date.now() - progress.ts,
});
}
@@ -492,6 +496,16 @@ const _startRecordingInner = async (caller) => {
error: errStr,
staleTab: isStaleTab,
});
+ // diagEvent only reaches the local ring buffer, which is never uploaded.
+ // reason is the one field that survives both telemetry allowlists.
+ void emitRecordingTelemetry("recording_forensic_event", {
+ recordingSessionId: recordingAttemptId,
+ name: "start-fail-progress",
+ reason: `start-progress-${stalledStage}`,
+ stalledMs: isThisStart ? Date.now() - progress.ts : null,
+ elapsedMs: Date.now() - startDispatchedAt,
+ errMsg: errStr,
+ });
releaseStartRecordingGuard();
chrome.storage.local.set({
pendingRecording: false,
diff --git a/src/pages/Background/utils/executeScripts.js b/src/pages/Background/utils/executeScripts.js
index 4101d2d..f22ac3c 100644
--- a/src/pages/Background/utils/executeScripts.js
+++ b/src/pages/Background/utils/executeScripts.js
@@ -11,6 +11,10 @@ const INJECT_CONCURRENCY = 3;
// background time instead of a pinned CPU.
const BACKFILL_CONCURRENCY = 1;
const BACKFILL_GAP_MS = 250;
+// sendMessage never settles while a tab is still loading, so an unbounded
+// ping parks a worker forever. Shorter on the click path.
+const PING_TIMEOUT_MS = 750;
+const BACKFILL_PING_TIMEOUT_MS = 2000;
// executeScript resolves as a promise only when no callback is passed. The
@@ -51,17 +55,14 @@ export const injectContentScriptIntoTab = async (tabId) => {
}
};
-// The backfill is no longer guaranteed to have reached the tab, so callers
-// can't assume a content script is there.
+// Pings first: a blind send to a loading tab hangs instead of erroring, which
+// is what made the popup take minutes. A resend would toggle the popup twice.
export const sendMessageEnsuringContentScript = async (tabId, message) => {
const { sendMessageTab } = await import("../tabManagement");
- try {
- return await sendMessageTab(tabId, message);
- } catch (err) {
- if (!String(err).includes("Receiving end does not exist")) throw err;
- }
- if (!(await injectContentScriptIntoTab(tabId))) {
- throw new Error(`content script injection failed for tab ${tabId}`);
+ if (!(await hasContentScript(tabId))) {
+ if (!(await injectContentScriptIntoTab(tabId))) {
+ throw new Error(`content script injection failed for tab ${tabId}`);
+ }
}
return sendMessageTab(tabId, message);
};
@@ -76,13 +77,28 @@ const injectionPriority = (tab, focusedWindowId) => {
// Skips the ~1MB re-parse when the script is already there. Only absence
// reads "Receiving end does not exist", so any other reply means it is.
-const hasContentScript = async (tabId) => {
+// A timeout counts as absent. Injection is deduped by
+// window.__screenityContentBootstrapped, so guessing wrong costs one parse.
+const hasContentScript = async (tabId, timeoutMs = PING_TIMEOUT_MS) => {
const { sendMessageTab } = await import("../tabManagement");
+ let timer = null;
+ const timeout = new Promise((resolve) => {
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
+ });
try {
- await sendMessageTab(tabId, { type: "screenity-ping" });
- return true;
- } catch (err) {
- return !String(err).includes("Receiving end does not exist");
+ const result = await Promise.race([
+ sendMessageTab(tabId, { type: "screenity-ping" }).then(
+ () => "present",
+ (err) =>
+ String(err).includes("Receiving end does not exist")
+ ? "absent"
+ : "present",
+ ),
+ timeout,
+ ]);
+ return result === "present";
+ } finally {
+ clearTimeout(timer);
}
};
@@ -106,7 +122,8 @@ const injectIfMissing = async (tabId, files, gapMs = 0) => {
while (gapMs > 0 && (await recordingInFlight())) {
await new Promise((r) => setTimeout(r, 2000));
}
- if (await hasContentScript(tabId)) return;
+ if (await hasContentScript(tabId, gapMs > 0 ? BACKFILL_PING_TIMEOUT_MS : PING_TIMEOUT_MS))
+ return;
await injectInto(tabId, files);
if (gapMs > 0) await new Promise((r) => setTimeout(r, gapMs));
};
diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsx
index 3442f9f..e6175e1 100644
--- a/src/pages/CloudRecorder/CloudRecorder.jsx
+++ b/src/pages/CloudRecorder/CloudRecorder.jsx
@@ -21,6 +21,7 @@ import {
stopTabKeepalive,
} from "../utils/tabKeepalive";
import { traceStep } from "../utils/startFlowTrace";
+import { markStartProgress } from "../utils/startProgress";
import { IS_OFFSCREEN_HOST } from "../utils/recordingHost";
import { sendSystemAudioGuidanceToast } from "../utils/systemAudioGuidance";
import {
@@ -40,10 +41,15 @@ import {
openExistingChunksStore,
} from "./recorderStorage/chooseChunksStore";
import { destroySessionDir } from "./recorderStorage/opfsKvStore";
+import {
+ createTrackStallState,
+ sweepTrackStalls,
+} from "./trackStallSweep";
import {
chooseTrackEncoder,
resetEncoderProbeCache,
computeEncodedDimensions,
+ computeCameraBitrate,
WEBCODECS_CAP_WIDTH,
WEBCODECS_CAP_HEIGHT,
} from "./encoder/chooseEncoder";
@@ -91,9 +97,9 @@ const RESUMABLE_UPLOADER_STATUSES = new Set([
]);
// Stop is user-visible, so the pre-finalize gap re-send is capped.
const GAP_RESEND_BUDGET_MS = 45000;
-// Off until prepareGapResend gets an in-flight guard: it rewinds offset against
-// a live queue, which corrupts instead of failing.
-const GAP_RESEND_ENABLED = false;
+// prepareGapResend refuses to rewind under an in-flight PATCH, and the call
+// site quiesces the queue before reading the offset it plans against.
+const GAP_RESEND_ENABLED = true;
const SCREEN_CHUNK_MEMORY_WINDOW = 8;
const CAMERA_CHUNK_MEMORY_WINDOW = 8;
const AUDIO_CHUNK_MEMORY_WINDOW = 8;
@@ -357,6 +363,10 @@ const CloudRecorder = () => {
const sessionHeartbeat = useRef(null);
const chunkStallTimer = useRef(null);
const uploadHeartbeatTimer = useRef(null);
+ const trackSweepTicks = useRef(0);
+ // Set when the resend budget expires. finalize starts the moment the outer
+ // race resolves, and a write landing after that is lost bytes.
+ const gapResendAbortRef = useRef(false);
const lastUploadProgress = useRef({
screen: 0,
camera: 0,
@@ -798,6 +808,48 @@ const CloudRecorder = () => {
// One id per host (page load). Two ids on one bunnyVideoId means two
// writers. The same id twice means one host re-signed.
clientSessionId: eventPayload.clientSessionId || null,
+ trackSweepTicks:
+ typeof eventPayload.trackSweepTicks === "number"
+ ? eventPayload.trackSweepTicks
+ : null,
+ queueLength:
+ typeof eventPayload.queueLength === "number"
+ ? eventPayload.queueLength
+ : null,
+ // PATCH accounting. This shaper has no passthrough, so a field that
+ // is not named here never leaves the extension.
+ patchAttempts:
+ typeof eventPayload.patchAttempts === "number"
+ ? eventPayload.patchAttempts
+ : null,
+ patchResponses:
+ typeof eventPayload.patchResponses === "number"
+ ? eventPayload.patchResponses
+ : null,
+ patchThrows:
+ typeof eventPayload.patchThrows === "number"
+ ? eventPayload.patchThrows
+ : null,
+ patchInFlight:
+ typeof eventPayload.patchInFlight === "boolean"
+ ? eventPayload.patchInFlight
+ : null,
+ lastPatchStatus:
+ typeof eventPayload.lastPatchStatus === "number"
+ ? eventPayload.lastPatchStatus
+ : null,
+ lastPatchOutcome:
+ typeof eventPayload.lastPatchOutcome === "string"
+ ? eventPayload.lastPatchOutcome
+ : null,
+ sinceLastPatchStartMs:
+ typeof eventPayload.sinceLastPatchStartMs === "number"
+ ? eventPayload.sinceLastPatchStartMs
+ : null,
+ sinceLastPatchEndMs:
+ typeof eventPayload.sinceLastPatchEndMs === "number"
+ ? eventPayload.sinceLastPatchEndMs
+ : null,
// Allowlisting here is necessary but not sufficient: the server sanitizer
// needs them too. Folded into `reason`, which survives either way.
queuedBytes:
@@ -1101,6 +1153,8 @@ const CloudRecorder = () => {
serverBytesConfirmed,
uploaderType: "cloud_recorder",
encodeStats,
+ // recording_outcome always lands, unlike upload_track_stalled itself.
+ trackSweepTicks: trackSweepTicks.current,
...extra,
});
};
@@ -2635,6 +2689,11 @@ const CloudRecorder = () => {
return;
}
try {
+ // The plan is built from this HEAD, so the queue has to stop moving
+ // before it is read or the rewind lands under a live PATCH.
+ if (typeof uploader.waitForInFlightChunk === "function") {
+ await uploader.waitForInFlightChunk();
+ }
const serverOffset = await uploader.getServerOffset();
if (serverOffset === null) return;
const clientBytes = Number(uploader.totalBytes) || 0;
@@ -2666,6 +2725,15 @@ const CloudRecorder = () => {
});
let sentBytes = 0;
for (const step of plan.plan) {
+ if (gapResendAbortRef.current) {
+ void emitUploadTelemetry("upload_gap_resend_aborted", {
+ trackType: track,
+ reason: `budget-expired-after-${sentBytes}-of-${plan.gapBytes}`,
+ sentBytes,
+ gapBytes: plan.gapBytes,
+ });
+ return;
+ }
const entry = await store.getItem(`${keyPrefix}${step.index}`);
if (!entry?.chunk) {
// Stopping here is safe: everything sent so far was contiguous from
@@ -2748,18 +2816,7 @@ const CloudRecorder = () => {
// The session-wide stall check below ORs the tracks together, so a healthy
// screen masks a camera frozen at its first byte.
- const TRACK_STALL_MS = 30000;
- // mediabunny's fMP4 ftyp is 28 bytes and lands before any encoded packet, so
- // an offset this low means the muxer opened and no fragment ever closed.
- const INIT_ONLY_OFFSET = 64;
-
- // ts null, not 0: a falsy check would read a legitimate epoch-0 stamp as
- // "no baseline yet" and never flag the track.
- const trackStallState = useRef({
- screen: { offset: -1, ts: null, notified: false },
- camera: { offset: -1, ts: null, notified: false },
- audio: { offset: -1, ts: null, notified: false },
- });
+ const trackStallState = useRef(createTrackStallState());
const uploaderFailureCounters = {
screen: consecutiveScreenFailures,
@@ -2773,47 +2830,29 @@ const CloudRecorder = () => {
camera: cameraUploader.current,
audio: audioUploader.current,
};
- const state = trackStallState.current;
- let anyAdvanced = false;
-
- for (const [track, uploader] of Object.entries(uploaders)) {
- const entry = state[track];
- if (!uploader) {
- entry.offset = -1;
- continue;
- }
- const offset = Number(uploader.offset) || 0;
- if (offset !== entry.offset) {
- entry.offset = offset;
- entry.ts = now;
- entry.notified = false;
- anyAdvanced = true;
- }
- }
-
- for (const [track, uploader] of Object.entries(uploaders)) {
- const entry = state[track];
- if (!uploader || entry.ts === null || entry.notified) continue;
- if (now - entry.ts <= TRACK_STALL_MS) continue;
- if (uploader.status === "completed" || uploader.status === "aborted") {
- continue;
- }
- entry.notified = true;
- // The signature from the churned-user report: one track pinned at its
- // init segment while another uploads normally.
- const stuckAtInit = entry.offset > 0 && entry.offset <= INIT_ONLY_OFFSET;
+ const stalls = sweepTrackStalls({
+ state: trackStallState.current,
+ uploaders,
+ now,
+ });
+ // Proves the sweep ran at all. upload_track_stalled has never fired in
+ // prod, and a silent detector and a healthy fleet look identical.
+ trackSweepTicks.current += 1;
+
+ for (const stall of stalls) {
+ const { track, uploader } = stall;
void emitUploadTelemetry("upload_track_stalled", {
trackType: track,
// The mapping reads `offset`, not `offsetBytes`.
- offset: entry.offset,
- reason: `${stuckAtInit ? "stuck-at-init" : "stalled"}-${track}${
- anyAdvanced ? "-sibling-progressing" : ""
+ offset: stall.offset,
+ reason: `${stall.stuckAtInit ? "stuck-at-init" : "stalled"}-${track}${
+ stall.siblingProgressing ? "-sibling-progressing" : ""
}`,
totalBytes: Number(uploader.totalBytes) || 0,
queuedBytes: Number(uploader.queuedBytes) || 0,
- stallMs: now - entry.ts,
- stuckAtInit,
- siblingProgressing: anyAdvanced,
+ stallMs: stall.stallMs,
+ stuckAtInit: stall.stuckAtInit,
+ siblingProgressing: stall.siblingProgressing,
uploaderStatus: uploader.status || null,
errorCode: uploader.lastErrorCode || null,
isPaused: Boolean(uploader.isPaused),
@@ -3409,6 +3448,21 @@ const CloudRecorder = () => {
persistSessionState({});
};
+ // The TUS filetype is fixed at uploader init, which runs before encoder
+ // selection. A flip here leaves Bunny's label wrong, so record the truth.
+ const syncSelectedContainer = (track, uploaderRef, container) => {
+ const uploader = uploaderRef?.current;
+ if (!uploader || !container) return;
+ const declared = uploader.container || null;
+ uploader.updateEncoderInfo?.({ container });
+ if (declared && declared !== container) {
+ void emitUploadTelemetry("upload_container_mismatch", {
+ trackType: track,
+ reason: `declared-${declared}-actual-${container}`,
+ });
+ }
+ };
+
const checkMaxMemory = () => {
const now = Date.now();
if (now - storagePressureRef.current.lastEstimateAt < STORAGE_CHECK_INTERVAL_MS) {
@@ -4515,6 +4569,9 @@ const CloudRecorder = () => {
};
const startRecording = async () => {
+ // The BG start-fail re-check tears the recorder down after 2.5s unless a
+ // stage lands. The free recorders mark, this one never did.
+ markStartProgress("preflight-enter");
setInitProject(false);
await clearLocalScreenPlaybackOffer("start-recording");
startTabKeepAlive();
@@ -4527,6 +4584,7 @@ const CloudRecorder = () => {
if (!storageReady) return;
await ensureAudioChunkStoreReady();
await ensureCameraChunkStoreReady();
+ markStartProgress("stores-ready");
if (!uploadersInitialized.current) {
sendRecordingError(
@@ -4651,12 +4709,14 @@ const CloudRecorder = () => {
}
if (!recorderSession.current) {
+ markStartProgress("session-register");
const registered = await startRecorderSession({
projectId,
sessionId: ensureRecordingSessionId(),
});
if (!registered) return;
}
+ markStartProgress("session-ready");
await Promise.allSettled([
screenUploader.current?.setSessionId?.(recorderSession.current?.id || null),
@@ -4671,9 +4731,11 @@ const CloudRecorder = () => {
}
try {
+ markStartProgress("stores-clear");
await chunksStore.clear();
await clearAudioChunkStore("start-recording");
await clearCameraChunkStore("start-recording");
+ markStartProgress("stores-cleared");
} catch (err) {
fatalErrorRef.current = true;
sendRecordingError(
@@ -4856,6 +4918,7 @@ const CloudRecorder = () => {
};
const screenSettings = screenTrack?.getSettings?.() || {};
+ markStartProgress("encoder-probe");
const screenSelection = await chooseTrackEncoder({
track: "screen",
stream,
@@ -5014,6 +5077,7 @@ const CloudRecorder = () => {
framerate: Number(screenSettings.frameRate) || 30,
},
});
+ markStartProgress("encoder-probe-done");
screenRecorder.current = screenSelection.recorder;
// Only WebCodecsTrackRecorder disposes the prewarm. On the
// MediaRecorder fallback nothing would, leaving a configured hardware
@@ -5029,6 +5093,7 @@ const CloudRecorder = () => {
encoderKinds.screen = screenSelection.kind;
trackContainers.screen = screenSelection.container;
trackCodecs.screen = screenSelection.codec;
+ syncSelectedContainer("screen", screenUploader, screenSelection.container);
encoderHwSlots = screenSelection.hwSlots || encoderHwSlots;
logDebugEvent("encoder-selected", {
track: "screen",
@@ -5063,6 +5128,7 @@ const CloudRecorder = () => {
audioBitsPerSecond: 128000,
};
+ markStartProgress("audio-encoder-probe");
const audioSelection = await chooseTrackEncoder({
track: "audio",
stream: rawMicStream.current,
@@ -5176,10 +5242,12 @@ const CloudRecorder = () => {
}
},
});
+ markStartProgress("audio-encoder-probe-done");
audioRecorder.current = audioSelection.recorder;
encoderKinds.audio = audioSelection.kind;
trackContainers.audio = audioSelection.container;
trackCodecs.audio = audioSelection.codec;
+ syncSelectedContainer("audio", audioUploader, audioSelection.container);
logDebugEvent("encoder-selected", {
track: "audio",
kind: audioSelection.kind,
@@ -5213,19 +5281,29 @@ const CloudRecorder = () => {
streamToRecord = new MediaStream(cameraStream.current.getVideoTracks());
}
+ const cameraSettings = cameraTrack?.getSettings?.() || {};
+
const cameraOptions = {
mimeType:
recordingType.current === "camera"
? "video/webm;codecs=vp9,opus"
: "video/webm;codecs=vp9",
- videoBitsPerSecond: 16000000,
+ // Priced on the encoded size: WebCodecs resizes a 4K webcam to the
+ // 1080p cap first. The MediaRecorder fallback takes no bitrate at all.
+ videoBitsPerSecond: computeCameraBitrate(
+ computeEncodedDimensions({
+ width: Number(cameraSettings.width),
+ height: Number(cameraSettings.height),
+ }),
+ ),
audioBitsPerSecond: 128000,
};
-
- const cameraSettings = cameraTrack?.getSettings?.() || {};
const cameraHasAudio =
recordingType.current === "camera" &&
(streamToRecord?.getAudioTracks?.()?.length ?? 0) > 0;
+ // probeConcurrentHw runs here, and its flush race alone is capped at
+ // 2.5s, the same window the BG teardown uses.
+ markStartProgress("camera-encoder-probe");
const cameraSelection = await chooseTrackEncoder({
track: "camera",
stream: streamToRecord,
@@ -5337,10 +5415,12 @@ const CloudRecorder = () => {
}
},
});
+ markStartProgress("camera-encoder-probe-done");
cameraRecorder.current = cameraSelection.recorder;
encoderKinds.camera = cameraSelection.kind;
trackContainers.camera = cameraSelection.container;
trackCodecs.camera = cameraSelection.codec;
+ syncSelectedContainer("camera", cameraUploader, cameraSelection.container);
encoderHwSlots = cameraSelection.hwSlots || encoderHwSlots;
logDebugEvent("encoder-selected", {
track: "camera",
@@ -6463,6 +6543,10 @@ const CloudRecorder = () => {
// Close any server/client byte gap before declaring a length. A track whose
// PATCHes 2xx'd without landing still has its bytes on disk.
if (GAP_RESEND_ENABLED) {
+ gapResendAbortRef.current = false;
+ const budgetTimer = setTimeout(() => {
+ gapResendAbortRef.current = true;
+ }, GAP_RESEND_BUDGET_MS);
await Promise.race([
Promise.allSettled([
resendUploadGap("screen", screenUploader, chunksStore, "chunk_", screenChunkByteRangesRef),
@@ -6471,6 +6555,9 @@ const CloudRecorder = () => {
]),
new Promise((r) => setTimeout(r, GAP_RESEND_BUDGET_MS)),
]);
+ // Stops stragglers at their next step, before finalize declares a length.
+ gapResendAbortRef.current = true;
+ clearTimeout(budgetTimer);
}
const finalizeCalls = [
diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.js
index ae4cdd0..182a986 100644
--- a/src/pages/CloudRecorder/bunnyTusUploader.js
+++ b/src/pages/CloudRecorder/bunnyTusUploader.js
@@ -184,6 +184,36 @@ export default class BunnyTusUploader {
// instead of silently truncating; the throw inside write() is
// unobserved because MediaRecorder.ondataavailable is fire-and-forget.
this.bytesLostAfterFinalize = 0;
+
+ // PATCH accounting. Without it a stall report cannot tell a dead loop
+ // from a hanging request, and those two need opposite fixes.
+ this.patchAttempts = 0;
+ this.patchResponses = 0;
+ this.patchThrows = 0;
+ this.patchInFlight = false;
+ this.lastPatchStartedAt = null;
+ this.lastPatchEndedAt = null;
+ this.lastPatchStatus = null;
+ this.lastPatchOutcome = null;
+ }
+
+ // Flat and bounded so both telemetry allowlists can carry it verbatim.
+ patchStats() {
+ const now = Date.now();
+ return {
+ patchAttempts: this.patchAttempts,
+ patchResponses: this.patchResponses,
+ patchThrows: this.patchThrows,
+ patchInFlight: this.patchInFlight,
+ lastPatchStatus: this.lastPatchStatus,
+ lastPatchOutcome: this.lastPatchOutcome,
+ sinceLastPatchStartMs: this.lastPatchStartedAt
+ ? now - this.lastPatchStartedAt
+ : null,
+ sinceLastPatchEndMs: this.lastPatchEndedAt
+ ? now - this.lastPatchEndedAt
+ : null,
+ };
}
debugLog(message, payload = null) {
@@ -259,6 +289,7 @@ export default class BunnyTusUploader {
this.emitTelemetry("upload_error", {
errorCode: errorCode || null,
message: err?.message || this.error || "upload-error",
+ ...this.patchStats(),
...(extra && typeof extra === "object" ? extra : {}),
});
this.scheduleJournalPersist({ force: true });
@@ -476,6 +507,7 @@ export default class BunnyTusUploader {
lastErrorCode: this.lastErrorCode || null,
lastServerOffset: this.lastServerOffset || 0,
resumeCount: this.resumeCount || 0,
+ ...this.patchStats(),
};
const toStore = {
@@ -638,11 +670,32 @@ export default class BunnyTusUploader {
return null;
}
+ // prepareGapResend refuses while the queue is live, so callers quiesce first.
+ // Bounded: a queue that never settles must skip the re-send, not hang stop.
+ async waitForInFlightChunk(timeoutMs = 15000) {
+ const deadline = Date.now() + timeoutMs;
+ while (this.currentPatchAbort || this.isProcessingQueue) {
+ if (Date.now() >= deadline) return false;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ return true;
+ }
+
// Rewinds local accounting to server truth, else write() trips the
// server-offset-regressed guard on the first re-sent PATCH.
prepareGapResend(serverOffset) {
if (!Number.isFinite(serverOffset) || serverOffset < 0) return false;
if (this.isFinalizing) return false;
+ // A PATCH that returns after the rewind sets this.offset from its own
+ // pre-rewind value, which undoes it silently. Refuse rather than corrupt.
+ if (this.currentPatchAbort || this.isProcessingQueue) {
+ this.emitTelemetry("upload_gap_resend_blocked", {
+ reason: this.currentPatchAbort ? "patch-in-flight" : "queue-processing",
+ serverOffset,
+ clientOffset: this.offset,
+ });
+ return false;
+ }
this.chunkQueue = [];
this.queuedBytes = 0;
this.offset = serverOffset;
@@ -713,7 +766,7 @@ export default class BunnyTusUploader {
if (this._offsetDivergenceCount >= 2) {
// Deliberately not rewriting this.offset down: PATCHing from the server's
// offset would skip the missing bytes and mux a hole into the file.
- this.setUploaderError("server-offset-behind-client", {
+ this.setUploaderError("server-offset-behind-client", null, {
clientOffset: this.offset,
serverOffset,
divergence,
@@ -1312,6 +1365,9 @@ export default class BunnyTusUploader {
this.UPLOAD_TIMEOUT_MS,
);
+ this.patchAttempts += 1;
+ this.patchInFlight = true;
+ this.lastPatchStartedAt = Date.now();
const res = await fetch(this.uploadUrl, {
// Followed silently by default: a proxy or captive-portal 3xx sends
// the chunk and signature onward, and its 200 reads as a good write.
@@ -1331,6 +1387,12 @@ export default class BunnyTusUploader {
});
clearTimeout(timeout);
this.currentPatchAbort = null;
+ this.patchInFlight = false;
+ this.patchResponses += 1;
+ this.lastPatchEndedAt = Date.now();
+ this.lastPatchStatus = res.status;
+ this.lastPatchOutcome =
+ res.ok || res.status === 204 ? "2xx" : `http-${res.status}`;
if (res.ok || res.status === 204) {
const serverOffsetHeader = res.headers.get("Upload-Offset");
@@ -1346,11 +1408,15 @@ export default class BunnyTusUploader {
parsed < currentOffset ||
parsed > expectedOffset
) {
- this.setUploaderError("invalid-server-offset", {
- serverOffsetHeader,
- parsed,
- currentOffset,
- expectedOffset,
+ this.setUploaderError("invalid-server-offset", null, {
+ clientOffset: currentOffset,
+ serverOffset: Number.isFinite(parsed) ? parsed : null,
+ httpStatus: res.status,
+ // Raw header has no allowlisted home and is unvetted server
+ // text, so it rides reason bounded.
+ reason: `invalid-offset-header-${String(
+ serverOffsetHeader,
+ ).slice(0, 32)}-expected-${expectedOffset}`,
});
throw new Error(
`Invalid Upload-Offset from server: "${serverOffsetHeader}"`,
@@ -1360,6 +1426,7 @@ export default class BunnyTusUploader {
// Short write. Counting it as a full one is what let a camera
// track discard 10k chunks while pinned at offset 28.
const acceptedBytes = parsed - currentOffset;
+ this.lastPatchOutcome = `short-write-${acceptedBytes}`;
this.offset = parsed;
this.lastServerOffset = parsed;
this.noServerProgressCount =
@@ -1380,9 +1447,11 @@ export default class BunnyTusUploader {
resUrlMatches: res.url === this.uploadUrl,
});
if (this.noServerProgressCount >= 3) {
- this.setUploaderError("server-offset-not-advancing", {
- parsed,
- currentOffset,
+ this.setUploaderError("server-offset-not-advancing", null, {
+ clientOffset: currentOffset,
+ serverOffset: parsed,
+ httpStatus: res.status,
+ reason: `offset-stuck-at-${parsed}-streak-${this.noServerProgressCount}`,
});
throw new Error(`Server offset stuck at ${parsed}`);
}
@@ -1506,9 +1575,11 @@ export default class BunnyTusUploader {
// if it is, server state is corrupted. Fail loudly.
const priorOffset = this.offset;
if (serverOffset < priorOffset - data.length) {
- this.setUploaderError("server-offset-regressed", {
+ this.setUploaderError("server-offset-regressed", null, {
+ clientOffset: priorOffset,
serverOffset,
- priorOffset,
+ divergence: priorOffset - serverOffset,
+ httpStatus: res.status,
});
throw new Error(
`Server offset regressed (${serverOffset} < ${priorOffset})`,
@@ -1560,8 +1631,10 @@ export default class BunnyTusUploader {
continue;
}
// serverOffset null/NaN: HEAD response unparseable.
- this.setUploaderError("offset-conflict-head-unparseable", {
- priorOffset: this.offset,
+ this.setUploaderError("offset-conflict-head-unparseable", null, {
+ clientOffset: this.offset,
+ httpStatus: res.status,
+ reason: "offset-conflict-head-unparseable",
});
throw new Error(
"409 offset conflict but HEAD returned unparseable offset",
@@ -1586,6 +1659,14 @@ export default class BunnyTusUploader {
? controller.signal.reason
: null;
this.currentPatchAbort = null;
+ if (this.patchInFlight) {
+ this.patchInFlight = false;
+ this.patchThrows += 1;
+ this.lastPatchEndedAt = Date.now();
+ this.lastPatchOutcome = String(
+ abortReason || err?.name || "throw",
+ ).slice(0, 40);
+ }
// Transient errors (network/timeout/stall-abort/5xx/408/423/425/429)
// retry forever with capped backoff. 423 = Bunny's resource lock.
const isExplicitAbort =
@@ -1618,7 +1699,8 @@ export default class BunnyTusUploader {
err,
);
this.setUploaderError("chunk-upload-retries-exhausted", err, {
- abortReason,
+ clientOffset: this.offset,
+ reason: `retries-exhausted-${abortReason || "none"}`,
});
throw err;
}
@@ -1677,10 +1759,10 @@ export default class BunnyTusUploader {
}
// Falling out means the chunk never fully landed. Returning here reads as
// success to processQueue, which then shifts the next chunk over the gap.
- this.setUploaderError(exhaustedReason, {
- chunkStartOffset,
- remaining: data.length,
- shortWritePasses,
+ this.setUploaderError(exhaustedReason, null, {
+ clientOffset: this.offset,
+ serverOffset: this.lastServerOffset ?? null,
+ reason: `${exhaustedReason}-from-${chunkStartOffset}-remaining-${data.length}-passes-${shortWritePasses}`,
});
throw new Error(`Chunk upload did not complete (${exhaustedReason})`);
} catch (err) {
@@ -2087,6 +2169,8 @@ export default class BunnyTusUploader {
this.stalled = true;
this.emitTelemetry("upload_stalled", {
stallMs: diff,
+ queueLength: this.chunkQueue.length,
+ ...this.patchStats(),
});
this.scheduleJournalPersist({ force: true });
if (typeof this.onStall === "function") {
diff --git a/src/pages/CloudRecorder/encoder/chooseEncoder.js b/src/pages/CloudRecorder/encoder/chooseEncoder.js
index 25ced76..48d424c 100644
--- a/src/pages/CloudRecorder/encoder/chooseEncoder.js
+++ b/src/pages/CloudRecorder/encoder/chooseEncoder.js
@@ -120,6 +120,31 @@ export const computeEncodedDimensions = ({
return { width: targetWidth, height: targetHeight };
};
+// Webcam noise is incompressible, so a 640x480 camera took the flat 16 Mbps
+// target at its word: 13 Mbps, 1.4 bpp against 0.1-0.2 for good 480p H.264.
+const CAMERA_BITRATE_RUNGS = [
+ { maxPixels: 854 * 480, bitrate: 2_000_000 },
+ { maxPixels: 1280 * 720, bitrate: 4_000_000 },
+];
+// The web recorder uses the same ladder. Keep both sides in step.
+const CAMERA_BITRATE_MAX = 6_000_000;
+
+// Takes ENCODED dims, not captured. computeEncodedDimensions caps the camera
+// at 1920x1080, so the top rung also answers unknown dimensions.
+export const computeCameraBitrate = ({ width, height } = {}) => {
+ if (
+ !Number.isFinite(width) ||
+ !Number.isFinite(height) ||
+ width <= 0 ||
+ height <= 0
+ ) {
+ return CAMERA_BITRATE_MAX;
+ }
+ const pixels = width * height;
+ const rung = CAMERA_BITRATE_RUNGS.find((r) => pixels <= r.maxPixels);
+ return rung ? rung.bitrate : CAMERA_BITRATE_MAX;
+};
+
// memoize per-session: chooseTrackEncoder() runs once per track during
// start, so the probe fires three times back-to-back without this cache.
let _hwSlotsPromise = null;
diff --git a/src/pages/CloudRecorder/trackStallSweep.js b/src/pages/CloudRecorder/trackStallSweep.js
new file mode 100644
index 0000000..bcf557a
--- /dev/null
+++ b/src/pages/CloudRecorder/trackStallSweep.js
@@ -0,0 +1,65 @@
+// Decides which upload tracks have gone quiet. Split out of CloudRecorder so
+// the rule can be tested: upload_track_stalled has never fired in prod.
+
+// mediabunny's fMP4 ftyp is 28 bytes and lands before any encoded packet, so
+// an offset this low means the muxer opened and no fragment ever closed.
+export const INIT_ONLY_OFFSET = 64;
+export const TRACK_STALL_MS = 30000;
+
+// ts null, not 0: a falsy check would read a legitimate epoch-0 stamp as
+// "no baseline yet" and never flag the track.
+export const createTrackStallState = () => ({
+ screen: { offset: -1, ts: null, notified: false },
+ camera: { offset: -1, ts: null, notified: false },
+ audio: { offset: -1, ts: null, notified: false },
+});
+
+const SETTLED = new Set(["completed", "aborted"]);
+
+// Mutates state, returns one report per track that just crossed the threshold.
+export const sweepTrackStalls = ({
+ state,
+ uploaders,
+ now,
+ stallMs = TRACK_STALL_MS,
+ initOnlyOffset = INIT_ONLY_OFFSET,
+}) => {
+ let anyAdvanced = false;
+
+ for (const [track, uploader] of Object.entries(uploaders)) {
+ const entry = state[track];
+ if (!entry) continue;
+ if (!uploader) {
+ entry.offset = -1;
+ continue;
+ }
+ const offset = Number(uploader.offset) || 0;
+ if (offset !== entry.offset) {
+ entry.offset = offset;
+ entry.ts = now;
+ entry.notified = false;
+ anyAdvanced = true;
+ }
+ }
+
+ const reports = [];
+ for (const [track, uploader] of Object.entries(uploaders)) {
+ const entry = state[track];
+ if (!entry || !uploader || entry.ts === null || entry.notified) continue;
+ if (now - entry.ts <= stallMs) continue;
+ if (SETTLED.has(uploader.status)) continue;
+ entry.notified = true;
+ // The reported failure shape: one track pinned at its init segment while
+ // another uploads normally.
+ const stuckAtInit = entry.offset > 0 && entry.offset <= initOnlyOffset;
+ reports.push({
+ track,
+ uploader,
+ offset: entry.offset,
+ stuckAtInit,
+ siblingProgressing: anyAdvanced,
+ stallMs: now - entry.ts,
+ });
+ }
+ return reports;
+};
diff --git a/src/pages/EditorApp/editorOps.js b/src/pages/EditorApp/editorOps.js
index a7804f4..e5041ef 100644
--- a/src/pages/EditorApp/editorOps.js
+++ b/src/pages/EditorApp/editorOps.js
@@ -3,6 +3,7 @@
// used to post, so ContentState's result handlers fire unchanged.
// Each video op is lazy-loaded to keep the ~630KB mediabunny chunk off mount.
import { fixWebmDurationOffThread } from "../Editor/utils/fixWebmDurationOffThread";
+import { blobHasAudioTrack } from "../utils/hasAudioTrack";
const lazyUtil = (importFn) =>
(...args) =>
@@ -173,6 +174,22 @@ export async function runEditorOp(message, reply, { viewer = false } = {}) {
break;
}
+ // A silent MP4 is worse than the WebM it came from, so keep the source
+ // when AAC is missing and the recording actually has sound.
+ let aacOk = false;
+ try {
+ const { ensureAacEncoder } = await import("../utils/aacPolyfill");
+ aacOk = await ensureAacEncoder();
+ } catch {}
+ if (!aacOk && (await blobHasAudioTrack(rawBlob))) {
+ reply({
+ type: "updated-blob",
+ base64: message.base64,
+ topLevel: true,
+ });
+ break;
+ }
+
// reuse the already-decoded rawBlob; mediabunny sniffs the container
// from bytes, so no second base64 decode is needed
const mp4Blob = await convertWebmToMp4(rawBlob, (progress) =>
diff --git a/src/pages/RemuxOffscreen/worker.js b/src/pages/RemuxOffscreen/worker.js
index c12c5f8..21ef79b 100644
--- a/src/pages/RemuxOffscreen/worker.js
+++ b/src/pages/RemuxOffscreen/worker.js
@@ -18,6 +18,7 @@ import {
import { createOpfsWritable } from "./opfsTarget";
import { videoConverter } from "../Editor/mediabunny/lib/videoConverter";
import { ensureAacEncoder, getAacPath } from "../utils/aacPolyfill";
+import { blobHasAudioTrack } from "../utils/hasAudioTrack";
const TEMP_FILE_PREFIX = "remux-";
const STALE_AGE_MS = 5 * 60 * 1000;
@@ -305,7 +306,14 @@ const convertViaEncoder = async (
// Linux Chromium has no AAC encoder, so without the wasm one the MP4
// comes back silent.
if (targetFormat === "mp4") {
- await ensureAacEncoder();
+ const aacOk = await ensureAacEncoder();
+ // Registering alone makes mediabunny report AAC as encodable, so a
+ // broken encoder ships a silent MP4 instead of dropping the track.
+ if (!aacOk && (await blobHasAudioTrack(inputFile))) {
+ const err = new Error("mp4 transcode needs AAC and none is usable");
+ err.code = "aac-unavailable";
+ throw err;
+ }
}
let audioDropped = false;
diff --git a/src/pages/utils/hasAudioTrack.js b/src/pages/utils/hasAudioTrack.js
new file mode 100644
index 0000000..49492ef
--- /dev/null
+++ b/src/pages/utils/hasAudioTrack.js
@@ -0,0 +1,15 @@
+// Header-only track check. Decides whether a missing AAC encoder actually
+// costs the user audio, or the source was silent to begin with.
+export const blobHasAudioTrack = async (blob) => {
+ try {
+ const { Input, ALL_FORMATS, BlobSource } = await import("mediabunny");
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(blob),
+ });
+ return Boolean(await input.getPrimaryAudioTrack());
+ } catch {
+ // Unknown beats silent. Keep the audio-correct source.
+ return true;
+ }
+};