The free and privacy-friendly screen recorder with no limits 🎥
JavaScript annotationannotation-toolaudiocamerachrome-extensiondesigneditorffmpegjavascriptproductivityrecorderscreen-capturescreen-recorderscreencasttensorflowvideo
Fix audio device retries and back to back recording issues
Alyssa X3cbcf863b446
diff --git a/.gitignore b/.gitignoreindex f386b32..c26f5a3 100644--- a/.gitignore+++ b/.gitignore@@ -13,6 +13,7 @@ node_modules/.env.*.localbuild/*.zip+*.tsbuildinfo.cws-credentials.jsondocs/tests/diff --git a/package.json b/package.jsonindex e1eed01..6d876f9 100755--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "screenity",- "version": "4.4.4",+ "version": "4.4.5","description": "The free and privacy-friendly screen recorder with no sign in needed.","scripts": {"build": "cross-env NODE_ENV=development node utils/build.js",diff --git a/src/manifest.json b/src/manifest.jsonindex 5059fe5..1e8d600 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.4",+ "version": "4.4.5","background": {"service_worker": "background.bundle.js"},diff --git a/src/pages/Background/index.js b/src/pages/Background/index.jsindex 7cb5fd7..1aa8fe3 100644--- a/src/pages/Background/index.js+++ b/src/pages/Background/index.js@@ -11,6 +11,7 @@ import {listSessionDirs,destroySessionDir,} from "../CloudRecorder/recorderStorage/opfsKvStore";+import { handleGetStreamingData } from "./recording/recordingHelpers";// Must run before any message/alarm handler can bail on a stale lock.const clearStaleLocks = async () => {@@ -167,6 +168,76 @@ const clearStaleLocks = async () => {}};+// SW death between opening the recorder tab and pushing streaming-data+// leaves the recorder stuck at "Starting recording...". Re-deliver+// `loaded` + streaming-data on next SW boot so it can complete the handshake.+const recoverInFlightRecording = async () => {+ try {+ const { pendingRecording, recording, recordingTab } =+ await chrome.storage.local.get([+ "pendingRecording",+ "recording",+ "recordingTab",+ ]);+ // Only the pre-active window needs recovery. Once recording=true the+ // streaming-data handshake already landed.+ if (!pendingRecording || recording || !recordingTab) return;+ let tab = null;+ try {+ tab = await chrome.tabs.get(recordingTab);+ } catch {+ return;+ }+ // Exact pathname match so "recorder.html" doesn't also match+ // "cloudrecorder.html" via substring inclusion.+ let recoveryTabUrl = null;+ try {+ recoveryTabUrl = tab?.url ? new URL(tab.url) : null;+ } catch {}+ const extOrigin = chrome.runtime.getURL("").replace(/\/$/, "");+ const recoveryPath = recoveryTabUrl?.pathname;+ const isRecoverableRecorder =+ recoveryTabUrl?.origin === extOrigin &&+ (recoveryPath === "/recorder.html" ||+ recoveryPath === "/cloudrecorder.html");+ if (!isRecoverableRecorder) return;+ diagEvent("sw-restart-recovery-redeliver-streaming-data", {+ recordingTab,+ tabUrl: tab?.url,+ status: tab?.status,+ });+ const { region, customRegion, tabRecordedID, backup, recordingType } =+ await chrome.storage.local.get([+ "region",+ "customRegion",+ "tabRecordedID",+ "backup",+ "recordingType",+ ]);+ const isRegion = Boolean(region) && !customRegion;+ try {+ await chrome.tabs.sendMessage(recordingTab, {+ type: "loaded",+ request: { recordingType, region, customRegion },+ backup: Boolean(backup),+ tabPreferred: false,+ ...(isRegion && tabRecordedID+ ? { isTab: true, tabID: tabRecordedID }+ : {}),+ });+ } catch (err) {+ console.warn("[Screenity][BG] redeliver loaded failed:", err);+ }+ // Both recorder pages dedup streaming-data via streamingDataReceivedAt,+ // so a duplicate push is safe.+ handleGetStreamingData().catch((err) => {+ console.warn("[Screenity][BG] redeliver streaming-data failed:", err);+ });+ } catch (err) {+ console.warn("[Screenity][BG] recoverInFlightRecording threw:", err);+ }+};+// reaps cloud-chunks/ session dirs not referenced by any// cloudRecorderSession:* snapshot or the latest recorderSession.// without this, an SW kill mid-recording leaks chunks forever.@@ -224,8 +295,13 @@ setupHandlers();initCountdownFallback();initLifecycleObserver();-// runs after listener registration, before queued events dispatch-clearStaleLocks();+// Recovery must run AFTER clearStaleLocks: if the recorder tab died+// with the SW, clearStaleLocks clears pendingRecording and recovery+// no-ops.+(async () => {+ await clearStaleLocks();+ await recoverInFlightRecording();+})();cleanupOrphanOpfsSessions();// 4.3.7 finalize-hang bug sticky-disabled WebCodecs for many users; clear once.diff --git a/src/pages/Background/recording/openRecorderTab.js b/src/pages/Background/recording/openRecorderTab.jsindex 29529d3..83b29cc 100644--- a/src/pages/Background/recording/openRecorderTab.js+++ b/src/pages/Background/recording/openRecorderTab.js@@ -43,18 +43,29 @@ const openRecorderTab = async (switchTab = true;}- // URL-guard: region recordings point recordingTab at the user's tab, never close that- const { recordingTab: prevRecTab } = await chrome.storage.local.get([- "recordingTab",- ]);+ // Region recordings point recordingTab at the user's tab; never close that.+ // For cloudrecorder.html, also skip removal while the previous session is+ // still uploading: killing it mid-TUS-upload corrupts scene data. It+ // closes itself via window.close() when finalize lands.+ const {+ recordingTab: prevRecTab,+ recorderSession: prevSession,+ } = await chrome.storage.local.get(["recordingTab", "recorderSession"]);if (prevRecTab != null) {try {const prevTab = await chrome.tabs.get(prevRecTab);const prevUrl = prevTab?.url || "";- if (- prevUrl.includes("recorder.html") ||- prevUrl.includes("cloudrecorder.html")- ) {+ const isCloudRecorderTab = prevUrl.includes("cloudrecorder.html");+ const isFreeRecorderTab =+ prevUrl.includes("recorder.html") && !isCloudRecorderTab;+ const prevSessionStatus = prevSession?.status || null;+ const stillFinalizing =+ prevSessionStatus === "recording" ||+ prevSessionStatus === "stopping" ||+ prevSessionStatus === "finishing";+ if (isFreeRecorderTab) {+ await removeTab(prevRecTab);+ } else if (isCloudRecorderTab && !stillFinalizing) {await removeTab(prevRecTab);}} catch {}diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.jsindex 889ea0d..9863839 100644--- a/src/pages/Background/recording/recordingHelpers.js+++ b/src/pages/Background/recording/recordingHelpers.js@@ -349,10 +349,13 @@ export const handleGetStreamingData = async () => {export const videoReady = async () => {perfMark("BG.recordingHelpers videoReady.enter");- const { backupTab, recordingDuration } = await chrome.storage.local.get([- "backupTab",- "recordingDuration",- ]);+ const { backupTab, recordingDuration, recordingTab, lastRecordingBackendRef } =+ await chrome.storage.local.get([+ "backupTab",+ "recordingDuration",+ "recordingTab",+ "lastRecordingBackendRef",+ ]);diagEvent("sw-received-video-ready", {recordingDurationMs: Number(recordingDuration) || 0,backupTabPresent: Boolean(backupTab),@@ -368,6 +371,33 @@ export const videoReady = async () => {.catch((err) => {diagEvent("warning", { note: "clear-session-safe undelivered (video-ready)", err: String(err).slice(0, 80) });});+ // For OPFS the editor reads chunks directly, so the recorder tab can+ // close as soon as video-ready fires. Keeping it alive holds Chrome's+ // tab-capture binding, which makes the next getMediaStreamId reject+ // with "Cannot capture a tab with an active stream" until Chrome+ // restarts. Cloudrecorder runs its own close on finalize, so skip it.+ if (lastRecordingBackendRef?.backend === "opfs" && recordingTab) {+ try {+ const tab = await chrome.tabs.get(recordingTab).catch(() => null);+ const tabUrl = tab?.url ? new URL(tab.url) : null;+ const isFreeRecorder =+ tabUrl?.pathname === "/recorder.html" &&+ tabUrl?.origin === chrome.runtime.getURL("").replace(/\/$/, "");+ if (isFreeRecorder) {+ diagEvent("eager-recorder-close", {+ recordingTab,+ reason: "video-ready-opfs",+ });+ await chrome.tabs.remove(recordingTab).catch(() => {});+ chrome.storage.local.set({ recordingTab: null });+ }+ } catch (closeErr) {+ diagEvent("warning", {+ note: "eager-recorder-close failed",+ err: String(closeErr?.message || closeErr).slice(0, 120),+ });+ }+ }await stopRecording();};diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsxindex fc91abc..368f361 100644--- a/src/pages/CloudRecorder/CloudRecorder.jsx+++ b/src/pages/CloudRecorder/CloudRecorder.jsx@@ -5869,6 +5869,13 @@ const CloudRecorder = () => {const onMessage = useCallback((request, sender, sendResponse) => {if (request.type === "loaded") {+ // BG redelivers `loaded` after an SW restart. Skip re-init if it+ // already ran: re-calling getStreamID would invalidate the active+ // tabCapture token (single-use). Just re-pull streaming-data.+ if (isInit.current) {+ chrome.runtime.sendMessage({ type: "get-streaming-data" });+ return;+ }setInitProject(false);backupRef.current = request.backup;if (IS_IFRAME_CONTEXT) {diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsxindex 3380002..408e7df 100644--- a/src/pages/Content/context/ContentState.jsx+++ b/src/pages/Content/context/ContentState.jsx@@ -1505,6 +1505,19 @@ const ContentState = (props) => {if (changes.recordingNow) {shouldUpdateTimer = true;}+ // Without this sync, the record button stays stuck on "Starting+ // recording..." after a teardown the React state didn't observe+ // (e.g. native Stop-sharing, SW-cleared start-fail).+ if (changes.pendingRecording) {+ const next = Boolean(changes.pendingRecording.newValue);+ if (!next) {+ setContentState((prev) => ({+ ...prev,+ pendingRecording: false,+ preparingRecording: false,+ }));+ }+ }if (changes.paused) {setContentState((prev) => ({...prev,diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsxindex 538bff7..27f97da 100644--- a/src/pages/Recorder/Recorder.jsx+++ b/src/pages/Recorder/Recorder.jsx@@ -248,6 +248,8 @@ const Recorder = () => {const startRequestedAt = useRef(null);// Null after a start-gate timeout marks SW-to-tab handoff failure.const streamingDataReceivedAt = useRef(null);+ const streamingDataTimeout = useRef(null);+ const loadedAt = useRef(0);const startGateTimeout = useRef(null);// 12s: cold SW wake-ups on Windows Chrome can take several seconds; 8s was too tight.const START_GATE_TIMEOUT_MS = 12000;@@ -3794,6 +3796,25 @@ const Recorder = () => {recordedTabId.current = null;}requestStreamingDataWithRetry();+ // If the SW never wakes to deliver streaming-data, the start-gate+ // timeout never arms (it depends on startRequested, which depends+ // on streaming-data). Surface an error after 15s.+ if (streamingDataTimeout.current) {+ clearTimeout(streamingDataTimeout.current);+ }+ streamingDataTimeout.current = setTimeout(() => {+ if (streamingDataReceivedAt.current != null) return;+ const diagInfo = {+ tabIDError: tabIDError.current,+ isTab: isTab.current,+ msSinceLoaded: Date.now() - loadedAt.current,+ };+ slLog("streaming-data-watchdog-fire", diagInfo);+ sendRecordingError(+ "Recording not ready: streaming-data never arrived from background",+ );+ }, 15000);+ loadedAt.current = Date.now();} else if (request.type === "streaming-data") {// Streaming-data may arrive twice (SW push + tab pull, or retries).if (streamingDataReceivedAt.current != null) {@@ -3803,6 +3824,10 @@ const Recorder = () => {slLog("msg-streaming-data");perfMark("Recorder streaming-data.received");streamingDataReceivedAt.current = Date.now();+ if (streamingDataTimeout.current) {+ clearTimeout(streamingDataTimeout.current);+ streamingDataTimeout.current = null;+ }startStreaming(JSON.parse(request.data));} else if (request.type === "start-recording-tab") {slLog("msg-start-recording-tab", {diff --git a/src/pages/utils/mediaDeviceFallback.js b/src/pages/utils/mediaDeviceFallback.jsindex b55b768..0d9ff33 100644--- a/src/pages/utils/mediaDeviceFallback.js+++ b/src/pages/utils/mediaDeviceFallback.js@@ -2,6 +2,15 @@ const DEVICE_ID_ERRORS = new Set(["OverconstrainedError", "NotFoundError"]);const isDeviceIdError = (err) => err && DEVICE_ID_ERRORS.has(err.name);+// Bluetooth/USB audio devices commonly return NotReadableError for 1-2s+// after wake/connect while the OS spins up the endpoint. A short retry+// turns the "headphones didn't record" complaint into a one-second pause.+const TRANSIENT_RETRY_DELAYS_MS = [350, 700];+const isTransientReadError = (err) =>+ err && (err.name === "NotReadableError" || err.name === "AbortError");++const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+// Constraints can contain nested objects (deviceId.exact) so a deep clone is required.const cloneConstraints = (constraints) => {const src = constraints || {};@@ -53,12 +62,29 @@ export const resolveDeviceIdByLabel = async (kind, desiredLabel) => {return matches[0].deviceId;};+const attemptGetUserMediaWithTransientRetry = async (constraints) => {+ let lastErr = null;+ const attempts = [0, ...TRANSIENT_RETRY_DELAYS_MS];+ for (let i = 0; i < attempts.length; i += 1) {+ if (attempts[i] > 0) await sleep(attempts[i]);+ try {+ return await navigator.mediaDevices.getUserMedia(constraints);+ } catch (err) {+ lastErr = err;+ // Permission/overconstrained errors must bail immediately so+ // callers can run their label fallback or surface the prompt.+ if (!isTransientReadError(err)) break;+ }+ }+ throw lastErr;+};+export const getUserMediaWithFallback = async ({constraints,fallbacks = [],}) => {try {- return await navigator.mediaDevices.getUserMedia(constraints);+ return await attemptGetUserMediaWithTransientRetry(constraints);} catch (err) {if (!isDeviceIdError(err) || fallbacks.length === 0) {throw err;@@ -84,7 +110,9 @@ export const getUserMediaWithFallback = async ({"[Screenity] Retrying getUserMedia with label-matched device IDs");- const stream = await navigator.mediaDevices.getUserMedia(nextConstraints);+ const stream = await attemptGetUserMediaWithTransientRetry(+ nextConstraints,+ );resolved.forEach(({ resolvedId, onResolved }) => {if (typeof onResolved === "function") {onResolved(resolvedId);