Skip to content

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

Merge: resolve remaining conflicts (cloud recorder, bunny uploader, sandbox contentstate)

Alyssa X2958dba25c63
diff --git a/src/_locales/ca/messages.json b/src/_locales/ca/messages.json
index 78a05e8..63fa2af 100644
--- a/src/_locales/ca/messages.json
+++ b/src/_locales/ca/messages.json
@@ -1392,5 +1392,13 @@
"welcomeToProActionModal": {
"message": "Entès",
"description": "Botó d’acció del modal de benvinguda a Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 fallat — off",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/de/messages.json b/src/_locales/de/messages.json
index 73d2e66..d9cce7e 100644
--- a/src/_locales/de/messages.json
+++ b/src/_locales/de/messages.json
@@ -1392,5 +1392,13 @@
"welcomeToProActionModal": {
"message": "Verstanden",
"description": "Bestätigungsbutton im Willkommensmodal für Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 Fehler — aus",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.json
index c50f834..db50d4c 100644
--- a/src/_locales/en/messages.json
+++ b/src/_locales/en/messages.json
@@ -1388,5 +1388,13 @@
"welcomeToProActionModal": {
"message": "Got it",
"description": "Welcome to Pro modal action button"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 failed — off",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/es/messages.json b/src/_locales/es/messages.json
index e5a6b0a..d97bf04 100644
--- a/src/_locales/es/messages.json
+++ b/src/_locales/es/messages.json
@@ -1392,5 +1392,13 @@
"welcomeToProActionModal": {
"message": "Entendido",
"description": "Botón de acción del modal de bienvenida a Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 falló — off",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/fr/messages.json b/src/_locales/fr/messages.json
index 2ec3ed6..6521eae 100644
--- a/src/_locales/fr/messages.json
+++ b/src/_locales/fr/messages.json
@@ -1393,5 +1393,13 @@
"welcomeToProActionModal": {
"message": "Compris",
"description": "Bouton d’action de la fenêtre de bienvenue pour Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 échec — off",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/hi/messages.json b/src/_locales/hi/messages.json
index 15aeed5..cd41893 100644
--- a/src/_locales/hi/messages.json
+++ b/src/_locales/hi/messages.json
@@ -1393,5 +1393,13 @@
"welcomeToProActionModal": {
"message": "ठीक है",
"description": "Pro वेलकम मोडल का एक्शन बटन"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 विफल — ऑफ",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/id/messages.json b/src/_locales/id/messages.json
index 6ab465c..0a8f4ea 100644
--- a/src/_locales/id/messages.json
+++ b/src/_locales/id/messages.json
@@ -1393,5 +1393,13 @@
"welcomeToProActionModal": {
"message": "Mengerti",
"description": "Tombol aksi di modal sambutan Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 gagal — mati",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/it/messages.json b/src/_locales/it/messages.json
index be76223..f505cf4 100644
--- a/src/_locales/it/messages.json
+++ b/src/_locales/it/messages.json
@@ -1378,5 +1378,13 @@
"welcomeToProActionModal": {
"message": "Ho capito",
"description": "Pulsante di conferma della finestra di benvenuto per Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 errore — off",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/ko/messages.json b/src/_locales/ko/messages.json
index d2c8cd3..c669af9 100644
--- a/src/_locales/ko/messages.json
+++ b/src/_locales/ko/messages.json
@@ -1393,5 +1393,13 @@
"welcomeToProActionModal": {
"message": "알겠어요",
"description": "Pro 환영 모달 확인 버튼"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 실패 — 꺼짐",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/pl/messages.json b/src/_locales/pl/messages.json
index 2970655..ae9c230 100644
--- a/src/_locales/pl/messages.json
+++ b/src/_locales/pl/messages.json
@@ -1393,5 +1393,13 @@
"welcomeToProActionModal": {
"message": "Rozumiem",
"description": "Przycisk akcji w oknie powitalnym Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 błąd — off",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/pt_BR/messages.json b/src/_locales/pt_BR/messages.json
index d16ab2c..56c0f71 100644
--- a/src/_locales/pt_BR/messages.json
+++ b/src/_locales/pt_BR/messages.json
@@ -1390,5 +1390,13 @@
"welcomeToProActionModal": {
"message": "Entendi",
"description": "Botão de ação do modal de boas-vindas ao Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 falhou — off",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/pt_PT/messages.json b/src/_locales/pt_PT/messages.json
index 43a2279..e96ddb1 100644
--- a/src/_locales/pt_PT/messages.json
+++ b/src/_locales/pt_PT/messages.json
@@ -1392,5 +1392,13 @@
"welcomeToProActionModal": {
"message": "Percebi",
"description": "Botão de ação do modal de boas-vindas ao Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 falhou — off",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/ru/messages.json b/src/_locales/ru/messages.json
index 7e91619..98068eb 100644
--- a/src/_locales/ru/messages.json
+++ b/src/_locales/ru/messages.json
@@ -1392,5 +1392,13 @@
"welcomeToProActionModal": {
"message": "Понятно",
"description": "Кнопка действия в приветственном окне Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 ошибка — выкл",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/ta/messages.json b/src/_locales/ta/messages.json
index 9d1ed28..538e963 100644
--- a/src/_locales/ta/messages.json
+++ b/src/_locales/ta/messages.json
@@ -1392,5 +1392,13 @@
"welcomeToProActionModal": {
"message": "சரி, புரிந்துவிட்டது",
"description": "Pro வரவேற்பு தோன்றும் பதிலின் செயல்பாடு பொத்தான்"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 தோல்வி — ஆஃப்",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/tr/messages.json b/src/_locales/tr/messages.json
index 99b61a4..61ea4a1 100644
--- a/src/_locales/tr/messages.json
+++ b/src/_locales/tr/messages.json
@@ -1392,5 +1392,13 @@
"welcomeToProActionModal": {
"message": "Tamamdır",
"description": "Pro karşılama modali eylem düğmesi"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 hata — kapalı",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/uk/messages.json b/src/_locales/uk/messages.json
index 4ff93e1..2406ccb 100644
--- a/src/_locales/uk/messages.json
+++ b/src/_locales/uk/messages.json
@@ -1383,5 +1383,13 @@
"welcomeToProActionModal": {
"message": "Зрозуміло",
"description": "Кнопка дії у вікні привітання Pro"
+ },
+ "webcodecsToggleLabel": {
+ "message": "Fast MP4 (beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "Fast MP4 помилка — вимк",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.json
index bb748fb..39f1286 100644
--- a/src/_locales/zh_CN/messages.json
+++ b/src/_locales/zh_CN/messages.json
@@ -1388,5 +1388,13 @@
"welcomeToProActionModal": {
"message": "知道了",
"description": "Pro 欢迎弹窗确认按钮"
+ },
+ "webcodecsToggleLabel": {
+ "message": "极速 MP4(beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "极速 MP4 失败 — 关闭",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.json
index 9845d5c..8cecef0 100644
--- a/src/_locales/zh_TW/messages.json
+++ b/src/_locales/zh_TW/messages.json
@@ -1388,5 +1388,13 @@
"welcomeToProActionModal": {
"message": "了解",
"description": "Pro 歡迎視窗確認按鈕"
+ },
+ "webcodecsToggleLabel": {
+ "message": "快速 MP4(beta)",
+ "description": "WebCodecs recorder toggle label"
+ },
+ "webcodecsFailedOffToast": {
+ "message": "快速 MP4 失敗 — 關閉",
+ "description": "WebCodecs failure auto-disable toast"
}
}
diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.js
index 6d6fcb0..d1f1805 100644
--- a/src/pages/Background/messaging/handlers.js
+++ b/src/pages/Background/messaging/handlers.js
@@ -12,6 +12,8 @@ import {
handleStopRecordingTab,
handleStopRecordingTabBackup,
} from "../recording/stopRecording";
+import { sendChunks } from "../recording/sendChunks";
+import { chunksStore } from "../recording/chunkHandler";
import { handleSaveToDrive } from "../drive/handleSaveToDrive";
import { addAlarmListener } from "../alarms/addAlarmListener";
import { cancelRecording, handleDismiss } from "../recording/cancelRecording";
@@ -143,6 +145,52 @@ export const setupHandlers = () => {
registerMessage("video-ready", (message) => videoReady(message));
registerMessage("start-recording", (message) => startRecording(message));
registerMessage("restarted", (message) => restartActiveTab(message));
+ const sendChunksToSandbox = async () => {
+ const { sandboxTab } = await chrome.storage.local.get(["sandboxTab"]);
+ if (!sandboxTab) {
+ throw new Error("no-sandbox-tab");
+ }
+
+ const pingReady = async () => {
+ return new Promise((resolve) => {
+ chrome.runtime.sendMessage(
+ { type: "ping", _targetTabId: sandboxTab },
+ (response) => {
+ resolve(response?.status === "ready");
+ }
+ );
+ });
+ };
+ const maxPingAttempts = 10;
+ let pingOk = false;
+ for (let attempt = 1; attempt <= maxPingAttempts; attempt += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ pingOk = await pingReady();
+ if (pingOk) break;
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((r) => setTimeout(r, 200));
+ }
+ if (!pingOk) {
+ throw new Error("sandbox-not-ready");
+ }
+
+ const maxAttempts = 6;
+ const delayMs = 250;
+ let chunkCount = 0;
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ chunkCount = 0;
+ await chunksStore.iterate(() => {
+ chunkCount += 1;
+ });
+ if (chunkCount > 0) break;
+ await new Promise((r) => setTimeout(r, delayMs));
+ }
+
+ await sendChunks();
+ return { status: "ok", chunkCount };
+ };
+
+ registerMessage("send-chunks-to-sandbox", () => sendChunksToSandbox());
registerMessage("new-chunk", (message, sender, sendResponse) => {
newChunk(message, sendResponse);
@@ -205,6 +253,16 @@ export const setupHandlers = () => {
async (message, sender) => await handleRecordingComplete(message, sender)
);
registerMessage("check-recording", (message) => checkRecording(message));
+ registerMessage("open-download-mp4", async () => {
+ const tab = await createTab("download.html", true, true);
+ if (!tab?.id) return;
+ chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
+ if (info.status === "complete" && tabId === tab.id) {
+ chrome.tabs.onUpdated.removeListener(listener);
+ sendMessageTab(tab.id, { type: "recover-indexed-db-mp4" });
+ }
+ });
+ });
registerMessage("review-screenity", () =>
createTab(
diff --git a/src/pages/Background/offscreen/offscreenDocument.js b/src/pages/Background/offscreen/offscreenDocument.js
index 0cb035e..4e94117 100644
--- a/src/pages/Background/offscreen/offscreenDocument.js
+++ b/src/pages/Background/offscreen/offscreenDocument.js
@@ -47,6 +47,7 @@ const openRecorderTab = async (
region: false,
wasRegion: true,
clickEvents: [],
+ recordingUiTabId: activeTab.id,
...(isRegion ? { tabRecordedID: activeTab.id } : {}),
});
@@ -81,6 +82,7 @@ export const offscreenDocument = async (request, tabId = null) => {
activeTab: activeTab.id,
tabRecordedID: null,
memoryError: false,
+ recordingUiTabId: activeTab.id,
});
if (activeTab.url.includes(chrome.runtime.getURL("playground.html"))) {
@@ -98,6 +100,7 @@ export const offscreenDocument = async (request, tabId = null) => {
recordingTab: activeTab.id,
offscreen: false,
region: true,
+ recordingUiTabId: activeTab.id,
});
if (request.customRegion) {
@@ -138,6 +141,7 @@ export const offscreenDocument = async (request, tabId = null) => {
offscreen: true,
region: false,
wasRegion: false,
+ recordingUiTabId: activeTab.id,
});
sendMessageRecord({
diff --git a/src/pages/Background/recording/cancelRecording.js b/src/pages/Background/recording/cancelRecording.js
index 51947f3..1818664 100644
--- a/src/pages/Background/recording/cancelRecording.js
+++ b/src/pages/Background/recording/cancelRecording.js
@@ -16,6 +16,8 @@ export const handleDismiss = async () => {
chrome.action.setIcon({ path: "assets/icon-34.png" });
chrome.runtime.sendMessage({ type: "turn-off-pip" });
+ chrome.storage.local.set({ pipForceClose: Date.now() });
+ chrome.storage.local.set({ recordingUiTabId: null });
chrome.storage.local.remove(["recordingMeta"]);
} catch (error) {
console.error("Failed to handle dismiss:", error);
@@ -35,6 +37,8 @@ export const cancelRecording = async () => {
focusTab(activeTab);
discardOffscreenDocuments();
chrome.runtime.sendMessage({ type: "turn-off-pip" });
+ chrome.storage.local.set({ pipForceClose: Date.now() });
+ chrome.storage.local.set({ recordingUiTabId: null });
chrome.storage.local.remove(["recordingMeta"]);
} catch (error) {
console.error("Failed to cancel recording:", error.message);
diff --git a/src/pages/Background/recording/discardRecording.js b/src/pages/Background/recording/discardRecording.js
index 1ec81aa..40a4361 100644
--- a/src/pages/Background/recording/discardRecording.js
+++ b/src/pages/Background/recording/discardRecording.js
@@ -13,6 +13,8 @@ export const discardRecording = async () => {
sandboxTab: null,
recording: false,
});
+ chrome.storage.local.set({ pipForceClose: Date.now() });
+ chrome.storage.local.set({ recordingUiTabId: null });
chrome.storage.local.remove(["recordingMeta"]);
chrome.runtime.sendMessage({ type: "discard-backup" });
diff --git a/src/pages/Background/recording/restoreRecording.js b/src/pages/Background/recording/restoreRecording.js
index e097af9..cfdfafd 100644
--- a/src/pages/Background/recording/restoreRecording.js
+++ b/src/pages/Background/recording/restoreRecording.js
@@ -1,6 +1,5 @@
import { sendMessageTab } from "../tabManagement";
import { chunksStore } from "./chunkHandler";
-import { supportsWebCodecs } from "../utils/featureDetection";
export const checkRestore = async () => {
const chunks = [];
@@ -15,16 +14,19 @@ export const checkRestore = async () => {
};
export const restoreRecording = async () => {
+ const { fastRecorderInUse } = await chrome.storage.local.get([
+ "fastRecorderInUse",
+ ]);
//const hasWebCodecs = supportsWebCodecs();
- const hasWebCodecs = false; // FLAG: Force old FFMPEG for now
+ const hasWebCodecs = Boolean(fastRecorderInUse);
let editorUrl, messageType;
if (hasWebCodecs) {
- editorUrl = "editorwebcodecs.html";
+ editorUrl = "editorwebcodecs.html?mode=recover";
messageType = "restore-recording";
} else {
- editorUrl = "editorviewer.html";
+ editorUrl = "editorviewer.html?mode=recover";
messageType = "viewer-recording";
}
diff --git a/src/pages/Background/recording/sendChunks.js b/src/pages/Background/recording/sendChunks.js
index f172f67..a257b87 100644
--- a/src/pages/Background/recording/sendChunks.js
+++ b/src/pages/Background/recording/sendChunks.js
@@ -3,6 +3,19 @@ import { handleChunks } from "./chunkHandler";
export const sendChunks = async (override = false) => {
try {
+ // Wait briefly for chunks to be flushed to IndexedDB
+ const maxAttempts = 15;
+ const delayMs = 200;
+ let chunkCount = 0;
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ chunkCount = 0;
+ await chunksStore.iterate(() => {
+ chunkCount += 1;
+ });
+ if (chunkCount > 0) break;
+ await new Promise((r) => setTimeout(r, delayMs));
+ }
+
const chunks = [];
await chunksStore.iterate((value) => {
chunks.push(value);
diff --git a/src/pages/Background/recording/startRecording.js b/src/pages/Background/recording/startRecording.js
index 02bcb8e..c72629b 100644
--- a/src/pages/Background/recording/startRecording.js
+++ b/src/pages/Background/recording/startRecording.js
@@ -5,6 +5,11 @@ export const startRecording = async () => {
restarting: false,
});
+ const { activeTab } = await chrome.storage.local.get(["activeTab"]);
+ if (activeTab != null) {
+ chrome.storage.local.set({ recordingUiTabId: activeTab });
+ }
+
// Check if customRegion is set
const { customRegion } = await chrome.storage.local.get(["customRegion"]);
diff --git a/src/pages/Background/recording/stopRecording.js b/src/pages/Background/recording/stopRecording.js
index fb05120..97a55b9 100644
--- a/src/pages/Background/recording/stopRecording.js
+++ b/src/pages/Background/recording/stopRecording.js
@@ -2,8 +2,6 @@ import { focusTab, sendMessageTab } from "../tabManagement/";
import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocuments";
import { sendMessageRecord } from "./sendMessageRecord";
import { sendChunks } from "./sendChunks";
-import { waitForContentScript } from "../utils/waitForContentScript";
-import { supportsWebCodecs } from "../utils/featureDetection";
export const stopRecording = async () => {
chrome.action.setIcon({ path: "assets/icon-34.png" });
@@ -42,96 +40,144 @@ export const stopRecording = async () => {
recordingDuration: duration,
tabRecordedID: null,
});
+ chrome.storage.local.set({ recordingUiTabId: null });
+ chrome.storage.local.set({ pipForceClose: Date.now() });
chrome.storage.local.set({ recordingStartTime: 0 });
- // Check if browser supports WebCodecs for Mediabunny
+ const {
+ fastRecorderInUse,
+ fastRecorderActiveRecordingId,
+ fastRecorderValidation,
+ } = await chrome.storage.local.get([
+ "fastRecorderInUse",
+ "fastRecorderActiveRecordingId",
+ "fastRecorderValidation",
+ ]);
+ const validation =
+ fastRecorderValidation && typeof fastRecorderValidation === "object"
+ ? fastRecorderValidation
+ : null;
+ const validationMatches =
+ validation?.details?.recordingId &&
+ validation.details.recordingId === fastRecorderActiveRecordingId;
+ const hardFailForCurrent = Boolean(
+ validationMatches && validation?.hardFail
+ );
//const hasWebCodecs = supportsWebCodecs();
- // FLAG: Force old FFMPEG for now
- const hasWebCodecs = false;
+ const hasWebCodecs = Boolean(fastRecorderInUse) && !hardFailForCurrent;
+
+ const {
+ postStopEditorOpened,
+ postStopEditorOpening,
+ sandboxTab,
+ postStopRecordingId,
+ recordingTab,
+ } =
+ await chrome.storage.local.get([
+ "postStopEditorOpened",
+ "postStopEditorOpening",
+ "sandboxTab",
+ "postStopRecordingId",
+ "recordingTab",
+ ]);
if (isSubscribed) {
chrome.alarms.clear("recording-alarm");
discardOffscreenDocuments();
chrome.storage.local.remove(["recordingMeta"]);
+ } else if (postStopEditorOpening || postStopEditorOpened || recordingTab) {
+ // Editor already opened by stop-recording-tab flow; avoid opening a second tab.
+ // That flow will trigger processing when the tab finishes loading.
} else if (hasWebCodecs) {
// Use Mediabunny (editorwebcodecs.html) when WebCodecs is supported
- chrome.tabs.create({ url: "editorwebcodecs.html", active: true }, (tab) => {
- chrome.tabs.onUpdated.addListener(function _(
- tabId,
- changeInfo,
- updatedTab
- ) {
- if (tabId === tab.id && changeInfo.status === "complete") {
- chrome.tabs.onUpdated.removeListener(_);
- chrome.storage.local.set({ sandboxTab: tab.id });
- waitForContentScript(tab.id)
- .then(() => {
- // Use fallback-recording for WebCodecs flow
- sendMessageTab(tab.id, { type: "fallback-recording" });
- })
- .catch((err) => {
- console.error(
- "❌ Failed to wait for content script:",
- err.message
- );
- });
- }
- });
- });
+ const query = postStopRecordingId
+ ? `?mode=postStop&recordingId=${encodeURIComponent(postStopRecordingId)}`
+ : "?mode=postStop";
+ chrome.tabs.create(
+ { url: `editorwebcodecs.html${query}`, active: true },
+ (tab) => {
+ chrome.tabs.onUpdated.addListener(function _(
+ tabId,
+ changeInfo,
+ updatedTab
+ ) {
+ if (tabId === tab.id && changeInfo.status === "complete") {
+ chrome.tabs.onUpdated.removeListener(_);
+ chrome.storage.local.set({ sandboxTab: tab.id });
+ sendMessageTab(tab.id, { type: "fallback-recording" }).catch(
+ (err) => {
+ console.error(
+ "❌ Failed to send message:",
+ err?.message || err
+ );
+ }
+ );
+ }
+ });
+ }
+ );
chrome.runtime.sendMessage({ type: "turn-off-pip" });
} else if (duration > maxDuration) {
// Fallback for large recordings without WebCodecs - use viewer mode
- chrome.tabs.create({ url: "editorviewer.html", active: true }, (tab) => {
- chrome.tabs.onUpdated.addListener(function _(
- tabId,
- changeInfo,
- updatedTab
- ) {
- if (tabId === tab.id && changeInfo.status === "complete") {
- chrome.tabs.onUpdated.removeListener(_);
- chrome.storage.local.set({ sandboxTab: tab.id });
- waitForContentScript(tab.id)
- .then(() => {
- sendMessageTab(tab.id, { type: "viewer-recording" });
- })
- .catch((err) => {
- console.error(
- "❌ Failed to wait for content script:",
- err.message
- );
- });
- }
- });
- });
+ const query = postStopRecordingId
+ ? `?mode=postStop&recordingId=${encodeURIComponent(postStopRecordingId)}`
+ : "?mode=postStop";
+ chrome.tabs.create(
+ { url: `editorviewer.html${query}`, active: true },
+ (tab) => {
+ chrome.tabs.onUpdated.addListener(function _(
+ tabId,
+ changeInfo,
+ updatedTab
+ ) {
+ if (tabId === tab.id && changeInfo.status === "complete") {
+ chrome.tabs.onUpdated.removeListener(_);
+ chrome.storage.local.set({ sandboxTab: tab.id });
+ sendMessageTab(tab.id, { type: "viewer-recording" }).catch(
+ (err) => {
+ console.error(
+ "❌ Failed to send message:",
+ err?.message || err
+ );
+ }
+ );
+ }
+ });
+ }
+ );
chrome.runtime.sendMessage({ type: "turn-off-pip" });
} else {
// Use FFmpeg (editor.html) for browsers without WebCodecs
- chrome.tabs.create({ url: "editor.html", active: true }, (tab) => {
- chrome.tabs.onUpdated.addListener(function _(
- tabId,
- changeInfo,
- updatedTab
- ) {
- if (tabId === tab.id && changeInfo.status === "complete") {
- chrome.tabs.onUpdated.removeListener(_);
- chrome.storage.local.set({ sandboxTab: tab.id });
- waitForContentScript(tab.id)
- .then(() => {
- sendChunks();
- })
- .catch((err) => {
- console.error(
- "❌ Failed to wait for content script:",
- err.message
- );
- });
- }
- });
- });
+ const query = postStopRecordingId
+ ? `?mode=postStop&recordingId=${encodeURIComponent(postStopRecordingId)}`
+ : "?mode=postStop";
+ chrome.tabs.create(
+ { url: `editor.html${query}`, active: true },
+ (tab) => {
+ chrome.tabs.onUpdated.addListener(function _(
+ tabId,
+ changeInfo,
+ updatedTab
+ ) {
+ if (tabId === tab.id && changeInfo.status === "complete") {
+ chrome.tabs.onUpdated.removeListener(_);
+ chrome.storage.local.set({ sandboxTab: tab.id });
+ sendMessageTab(tab.id, { type: "fallback-recording" }).catch(
+ (err) => {
+ console.error(
+ "❌ Failed to send message:",
+ err?.message || err
+ );
+ }
+ );
+ }
+ });
+ }
+ );
chrome.runtime.sendMessage({ type: "turn-off-pip" });
}
@@ -156,6 +202,119 @@ export const handleStopRecordingTab = async (request) => {
});
}
+ const {
+ isSubscribed,
+ recordingStartTime,
+ paused,
+ pausedAt,
+ totalPausedMs,
+ fastRecorderInUse,
+ } = await chrome.storage.local.get([
+ "isSubscribed",
+ "recordingStartTime",
+ "paused",
+ "pausedAt",
+ "totalPausedMs",
+ "fastRecorderInUse",
+ ]);
+ if (!isSubscribed) {
+ const { fastRecorderActiveRecordingId } = await chrome.storage.local.get([
+ "fastRecorderActiveRecordingId",
+ ]);
+ const recordingId =
+ fastRecorderActiveRecordingId ||
+ `${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
+ const now = Date.now();
+ const startTime = Number(recordingStartTime);
+ const basePaused = Number(totalPausedMs) || 0;
+ const pausedAtMs = Number(pausedAt);
+ const extraPaused =
+ paused && Number.isFinite(pausedAtMs) && pausedAtMs > 0
+ ? Math.max(0, now - pausedAtMs)
+ : 0;
+ const duration =
+ Number.isFinite(startTime) && startTime > 0
+ ? Math.max(0, now - startTime - basePaused - extraPaused)
+ : 0;
+ const maxDuration = 7 * 60 * 1000;
+ if (fastRecorderInUse) {
+ const editorUrl = "editorwebcodecs.html";
+ await chrome.storage.local.set({
+ postStopEditorOpening: true,
+ postStopEditorOpened: true,
+ postStopRecordingId: recordingId,
+ });
+ // Open editor immediately in postStop mode (WebCodecs only)
+ chrome.tabs.create(
+ {
+ url: `${editorUrl}?mode=postStop&recordingId=${encodeURIComponent(
+ recordingId
+ )}`,
+ active: true,
+ },
+ (tab) => {
+ if (!tab?.id) return;
+ chrome.tabs.onUpdated.addListener(function _(
+ tabId,
+ changeInfo,
+ updatedTab
+ ) {
+ if (tabId === tab.id && changeInfo.status === "complete") {
+ chrome.tabs.onUpdated.removeListener(_);
+ chrome.storage.local.set({
+ sandboxTab: tab.id,
+ postStopEditorOpening: false,
+ postStopEditorOpened: false,
+ });
+ sendMessageTab(tab.id, { type: "fallback-recording" }).catch(
+ (err) => {
+ console.error(
+ "❌ Failed to send message:",
+ err?.message || err
+ );
+ }
+ );
+ }
+ });
+ }
+ );
+ } else {
+ const editorUrl =
+ duration > maxDuration ? "editorviewer.html" : "editor.html";
+ // MediaRecorder/FFmpeg path: open editor normally (no postStop gating)
+ chrome.tabs.create({ url: editorUrl, active: true }, (tab) => {
+ if (!tab?.id) return;
+ chrome.tabs.onUpdated.addListener(function _(
+ tabId,
+ changeInfo,
+ updatedTab
+ ) {
+ if (tabId === tab.id && changeInfo.status === "complete") {
+ chrome.tabs.onUpdated.removeListener(_);
+ chrome.storage.local.set({
+ sandboxTab: tab.id,
+ postStopEditorOpening: false,
+ postStopEditorOpened: false,
+ postStopRecordingId: null,
+ });
+ if (editorUrl === "editorviewer.html") {
+ sendMessageTab(tab.id, { type: "viewer-recording" }).catch(
+ (err) => {
+ console.error(
+ "❌ Failed to send message:",
+ err?.message || err
+ );
+ }
+ );
+ } else {
+ sendChunks();
+ }
+ }
+ });
+ });
+ }
+ }
+
sendMessageRecord({ type: "stop-recording-tab" });
};
diff --git a/src/pages/Background/tabManagement/sendMessageTab.js b/src/pages/Background/tabManagement/sendMessageTab.js
index 22e0fe3..de564d2 100644
--- a/src/pages/Background/tabManagement/sendMessageTab.js
+++ b/src/pages/Background/tabManagement/sendMessageTab.js
@@ -18,6 +18,31 @@ export const sendMessageTab = async (
});
});
+ const extOrigin = chrome.runtime.getURL("").replace(/\/$/, "");
+ const isExtUrl = tab?.url && tab.url.startsWith(extOrigin);
+ const isPendingExtUrl =
+ tab?.pendingUrl && tab.pendingUrl.startsWith(extOrigin);
+
+ if (isExtUrl || isPendingExtUrl) {
+ return new Promise((resolve, reject) => {
+ chrome.runtime.sendMessage(
+ { ...message, _targetTabId: tab.id },
+ (response) => {
+ if (chrome.runtime.lastError) {
+ const msg = chrome.runtime.lastError.message || "";
+ if (msg.includes("message port closed before a response")) {
+ responseCallback ? responseCallback(undefined) : resolve();
+ return;
+ }
+ reject(msg);
+ return;
+ }
+ responseCallback ? responseCallback(response) : resolve(response);
+ }
+ );
+ });
+ }
+
if (
!tab ||
!tab.url ||
diff --git a/src/pages/Backup/Backup.jsx b/src/pages/Backup/Backup.jsx
index dc97542..49fd7e7 100644
--- a/src/pages/Backup/Backup.jsx
+++ b/src/pages/Backup/Backup.jsx
@@ -93,7 +93,7 @@ const Backup = () => {
localSaving(prompt);
} else {
alert(
- "Failed to set up local backup. Reach out to us at [email protected] for more help. You can still record your screen."
+ "Failed to set up local backup. Reach out to us at [email protected] for more help. You can still record your screen.",
);
chrome.storage.local.set({ backup: false });
chrome.runtime.sendMessage({
@@ -120,7 +120,7 @@ const Backup = () => {
chrome.runtime.sendMessage({
type: "recording-error",
error: "backup-error",
- why: JSON.stringify(err),
+ why: String(err),
});
}
return;
@@ -131,7 +131,7 @@ const Backup = () => {
chrome.runtime.sendMessage({
type: "recording-error",
error: "backup-error",
- why: JSON.stringify(err),
+ why: String(err),
});
}
return;
@@ -144,7 +144,7 @@ const Backup = () => {
} else {
directoryHandle = await directoryPicker.getDirectoryHandle(
"Screenity Recordings",
- { create: true }
+ { create: true },
);
}
@@ -172,7 +172,7 @@ const Backup = () => {
if (directory) {
try {
const permissions = await verifyFilePermissions(
- directory.directoryHandle
+ directory.directoryHandle,
);
if (!permissions) {
directoryPicker(prompt);
@@ -189,7 +189,7 @@ const Backup = () => {
});
} else {
alert(
- "Your browser doesn't support local backups. Reach out to us at [email protected] for more help. You can still record your screen."
+ "Your browser doesn't support local backups. Reach out to us at [email protected] for more help. You can still record your screen.",
);
chrome.storage.local.set({ backup: false });
chrome.runtime.sendMessage({
@@ -257,7 +257,7 @@ const Backup = () => {
const directory = await localDirectoryStore.getItem("directoryHandle");
if (directory && directory !== null) {
const permissions = await verifyFilePermissions(
- directory.directoryHandle
+ directory.directoryHandle,
);
if (permissions) {
await directory.directoryHandle.removeEntry(titleRef.current);
diff --git a/src/pages/Camera/messaging/handlers.js b/src/pages/Camera/messaging/handlers.js
index 799e157..18902be 100644
--- a/src/pages/Camera/messaging/handlers.js
+++ b/src/pages/Camera/messaging/handlers.js
@@ -92,6 +92,24 @@ export const setupHandlers = ({ setLoading }) => {
});
messageRouter();
+
+ // Fallback: if a runtime message is missed, close PiP when storage flag flips.
+ chrome.storage.local.get(["pipForceClose"], (res) => {
+ if (res.pipForceClose && document.pictureInPictureElement) {
+ document.exitPictureInPicture().catch(() => {});
+ setPipMode(false);
+ chrome.runtime.sendMessage({ type: "pip-ended" });
+ }
+ });
+ chrome.storage.onChanged.addListener((changes, area) => {
+ if (area !== "local") return;
+ if (!changes.pipForceClose) return;
+ if (document.pictureInPictureElement) {
+ document.exitPictureInPicture().catch(() => {});
+ setPipMode(false);
+ chrome.runtime.sendMessage({ type: "pip-ended" });
+ }
+ });
};
const handleStopRecording = async (request) => {
diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsx
index 7c561d0..b61f390 100644
--- a/src/pages/CloudRecorder/CloudRecorder.jsx
+++ b/src/pages/CloudRecorder/CloudRecorder.jsx
@@ -25,6 +25,11 @@ const IS_IFRAME_CONTEXT =
!document.referrer.startsWith("chrome-extension://"));
const CloudRecorder = () => {
+ const DEBUG_BUNDLE_MAX_EVENTS = 200;
+ const debugBundleSessionRef = useRef(null);
+ const debugBundleEventsRef = useRef([]);
+ const debugBundleKeyRef = useRef(null);
+
const screenTimer = useRef({ start: null, total: 0, paused: false });
const cameraTimer = useRef({ start: null, total: 0, paused: false });
const [started, setStarted] = useState(false);
@@ -106,6 +111,286 @@ const CloudRecorder = () => {
const keepAliveAudioCtx = useRef(null);
const keepAliveOscillator = useRef(null);
+ const ensureDebugBundleSession = async () => {
+ if (debugBundleSessionRef.current) return debugBundleSessionRef.current;
+ const fallbackId = `recdbg-${Date.now()}-${Math.random()
+ .toString(36)
+ .slice(2, 8)}`;
+ const sessionId = recorderSession.current?.id || fallbackId;
+ const session = { id: sessionId, startedAt: Date.now() };
+ debugBundleSessionRef.current = session;
+ debugBundleKeyRef.current = `recorderDebugBundle:${sessionId}`;
+ try {
+ await chrome.storage.local.set({ recorderDebugBundleSessionId: sessionId });
+ } catch {
+ // ignore
+ }
+ return session;
+ };
+
+ const appendDebugBundleEvent = async (event) => {
+ if (!event) return;
+ debugBundleEventsRef.current = [
+ ...debugBundleEventsRef.current,
+ event,
+ ].slice(-DEBUG_BUNDLE_MAX_EVENTS);
+ const key = debugBundleKeyRef.current || `recorderDebugBundle:${event.sessionId}`;
+ try {
+ await chrome.storage.local.set({ [key]: debugBundleEventsRef.current });
+ } catch {
+ // ignore
+ }
+ };
+
+ const logDebugEvent = async (eventType, payload = {}) => {
+ const session = await ensureDebugBundleSession();
+ const event = {
+ sessionId: session.id,
+ eventType,
+ ts: Date.now(),
+ payload,
+ };
+ appendDebugBundleEvent(event);
+ };
+
+ const setPipelineState = async (step, extra = {}) => {
+ const state = {
+ step,
+ ts: Date.now(),
+ projectId: extra.projectId || null,
+ sceneId: extra.sceneId || null,
+ status: extra.status || null,
+ details: extra.details || null,
+ };
+ try {
+ await chrome.storage.local.set({ recorderPipelineState: state });
+ } catch {
+ // ignore
+ }
+ };
+
+ const getOrCreateSceneId = async ({ forceNew = false } = {}) => {
+ try {
+ const { sceneId, sceneIdStatus } = await chrome.storage.local.get([
+ "sceneId",
+ "sceneIdStatus",
+ ]);
+ if (!forceNew && sceneId && sceneIdStatus === "recording") {
+ return sceneId;
+ }
+ } catch {
+ // ignore
+ }
+ const next = crypto.randomUUID();
+ try {
+ await chrome.storage.local.set({
+ sceneId: next,
+ sceneIdStatus: "recording",
+ });
+ } catch {
+ // ignore
+ }
+ return next;
+ };
+
+ const markSceneComplete = async (sceneId) => {
+ if (!sceneId) return;
+ try {
+ await chrome.storage.local.set({
+ sceneIdStatus: "completed",
+ lastCompletedSceneId: sceneId,
+ });
+ } catch {
+ // ignore
+ }
+ };
+
+ const upsertPendingScene = async (sceneId, payload) => {
+ if (!sceneId) return;
+ const indexKey = "pendingSceneIndex";
+ const sceneKey = `pendingScene:${sceneId}`;
+ const { pendingSceneIndex = [] } = await chrome.storage.local.get([
+ indexKey,
+ ]);
+ const nextIndex = pendingSceneIndex.includes(sceneId)
+ ? pendingSceneIndex
+ : [...pendingSceneIndex, sceneId];
+ await chrome.storage.local.set({
+ [sceneKey]: { ...payload, sceneId, updatedAt: Date.now() },
+ [indexKey]: nextIndex,
+ });
+ };
+
+ const removePendingScene = async (sceneId) => {
+ if (!sceneId) return;
+ const indexKey = "pendingSceneIndex";
+ const sceneKey = `pendingScene:${sceneId}`;
+ const { pendingSceneIndex = [] } = await chrome.storage.local.get([
+ indexKey,
+ ]);
+ const nextIndex = pendingSceneIndex.filter((id) => id !== sceneId);
+ await chrome.storage.local.remove([sceneKey]);
+ await chrome.storage.local.set({ [indexKey]: nextIndex });
+ };
+
+ const getSceneCreateStatus = async (sceneId) => {
+ if (!sceneId) return null;
+ const key = `sceneCreateStatus:${sceneId}`;
+ const result = await chrome.storage.local.get([key]);
+ return result?.[key] || null;
+ };
+
+ const setSceneCreateStatus = async (sceneId, status, extra = {}) => {
+ if (!sceneId) return;
+ const key = `sceneCreateStatus:${sceneId}`;
+ await chrome.storage.local.set({
+ [key]: {
+ status,
+ updatedAt: Date.now(),
+ ...extra,
+ },
+ });
+ };
+
+ const linkMediaToScene = async (projectId, sceneId, mediaId) => {
+ if (!projectId || !sceneId || !mediaId) return;
+ await fetch(`${API_BASE}/media/${mediaId}/scene`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ projectId, sceneId }),
+ });
+ };
+
+ const confirmLinkedMedia = async (projectId, sceneId, mediaIds = []) => {
+ const filtered = mediaIds.filter(Boolean);
+ if (!projectId || !sceneId || filtered.length === 0) return;
+ await fetch(`${API_BASE}/media/confirm-linked`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ mediaIds: filtered, projectId, sceneId }),
+ });
+ };
+
+ const ensureMediaLinked = async ({ projectId, sceneId, mediaIds }) => {
+ const filtered = (mediaIds || []).filter(Boolean);
+ if (!projectId || !sceneId || filtered.length === 0) return;
+ await Promise.allSettled(
+ filtered.map((mediaId) => linkMediaToScene(projectId, sceneId, mediaId)),
+ );
+ await confirmLinkedMedia(projectId, sceneId, filtered);
+ };
+
+ const recoverScene = async ({
+ projectId,
+ sceneId,
+ screenMediaId,
+ cameraMediaId,
+ audioMediaId,
+ }) => {
+ if (!projectId || !sceneId) return { ok: false, error: "missing-ids" };
+ const mediaIds = [screenMediaId, cameraMediaId, audioMediaId].filter(
+ Boolean,
+ );
+ const res = await fetch(`${API_BASE}/videos/${projectId}/recover-scene`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({
+ sceneId,
+ mediaIds,
+ screenMediaId: screenMediaId || null,
+ cameraMediaId: cameraMediaId || null,
+ audioMediaId: audioMediaId || null,
+ }),
+ });
+ if (!res.ok) {
+ const errorText = await res.text();
+ return { ok: false, error: errorText || "recover-scene-failed" };
+ }
+ return { ok: true };
+ };
+
+ const exportDebugBundle = async () => {
+ try {
+ const session = await ensureDebugBundleSession();
+ const key = debugBundleKeyRef.current || `recorderDebugBundle:${session.id}`;
+ const storage = await chrome.storage.local.get([
+ key,
+ "projectId",
+ "sceneId",
+ "uploadMeta",
+ "recorderSession",
+ "lastStopRecordingEvent",
+ "lastFinalizeFailure",
+ "screenTrackLog",
+ "pendingSceneIndex",
+ "recorderPipelineState",
+ ]);
+ const events = Array.isArray(storage[key])
+ ? storage[key]
+ : debugBundleEventsRef.current;
+ const uploadMeta = uploadMetaRef.current || storage.uploadMeta || null;
+ const ids = {
+ projectId: storage.projectId || null,
+ sceneId:
+ uploadMeta?.sceneId ||
+ screenUploader.current?.getMeta()?.sceneId ||
+ cameraUploader.current?.getMeta()?.sceneId ||
+ storage.sceneId ||
+ null,
+ screenMediaId:
+ uploadMeta?.screen?.mediaId ||
+ screenUploader.current?.getMeta()?.mediaId ||
+ null,
+ cameraMediaId:
+ uploadMeta?.camera?.mediaId ||
+ cameraUploader.current?.getMeta()?.mediaId ||
+ null,
+ audioMediaId: uploadMeta?.audio?.mediaId || null,
+ screenVideoId:
+ uploadMeta?.screen?.videoId ||
+ screenUploader.current?.getMeta()?.videoId ||
+ null,
+ cameraVideoId:
+ uploadMeta?.camera?.videoId ||
+ cameraUploader.current?.getMeta()?.videoId ||
+ null,
+ };
+
+ const payload = {
+ sessionId: session.id,
+ exportedAt: Date.now(),
+ pipelineState: storage.recorderPipelineState || null,
+ recorderSession: storage.recorderSession || recorderSession.current || null,
+ ids,
+ uploadMeta,
+ lastStopRecordingEvent: storage.lastStopRecordingEvent || null,
+ lastFinalizeFailure: storage.lastFinalizeFailure || null,
+ screenTrackLog: storage.screenTrackLog || [],
+ pendingSceneIndex: storage.pendingSceneIndex || [],
+ events,
+ };
+
+ const blob = new Blob([JSON.stringify(payload, null, 2)], {
+ type: "application/json",
+ });
+ const objectUrl = URL.createObjectURL(blob);
+ try {
+ await chrome.downloads.download({
+ url: objectUrl,
+ filename: `Screenity-Debug-Bundle-${new Date().toISOString()}.json`,
+ saveAs: false,
+ });
+ } finally {
+ URL.revokeObjectURL(objectUrl);
+ }
+ } catch (err) {
+ console.warn("[CloudRecorder] Failed to export debug bundle", err);
+ }
+ };
+
// Note: We no longer try to "keep alive" the service worker with pings.
// Instead, we persist recording state to chrome.storage.local so the SW can
// recover context when it restarts. The CloudRecorder tab is the source of truth.
@@ -327,6 +612,11 @@ const CloudRecorder = () => {
};
recorderSession.current = session;
await chrome.storage.local.set({ recorderSession: session });
+ await ensureDebugBundleSession();
+ logDebugEvent("recorder-session-started", {
+ sessionId: session.id,
+ projectId: meta.projectId || null,
+ });
try {
const result = await chrome.runtime.sendMessage({
type: "register-recording-session",
@@ -362,6 +652,7 @@ const CloudRecorder = () => {
});
chrome.runtime.sendMessage({ type: "clear-recording-session" });
recorderSession.current = null;
+ logDebugEvent("recorder-session-finalized", { status });
};
const startChunkWatchdog = () => {
@@ -437,6 +728,100 @@ const CloudRecorder = () => {
screenTrackMonitor.current = null;
};
+ const shouldSimulateFinalizeFailure = () => {
+ try {
+ const params = new URLSearchParams(window.location.search);
+ if (params.get("simulateFinalizeFailure") === "1") return true;
+ return window.SCREENITY_SIMULATE_FINALIZE_FAILURE === true;
+ } catch {
+ return false;
+ }
+ };
+
+ const buildFinalizeDiagnostics = ({
+ stage,
+ settledResults = [],
+ rejectedResults = [],
+ incompleteUploaders = [],
+ reason = "finalize-failed",
+ }) => {
+ const screenMeta = screenUploader.current?.getMeta?.() || null;
+ const cameraMeta = cameraUploader.current?.getMeta?.() || null;
+
+ return {
+ reason,
+ stage,
+ ts: Date.now(),
+ settledResults: settledResults.map((result, i) => ({
+ index: i,
+ status: result?.status || "unknown",
+ reason:
+ result?.status === "rejected"
+ ? String(result.reason?.message || result.reason || "unknown")
+ : null,
+ })),
+ rejectedResults: rejectedResults.map((result, i) => ({
+ index: i,
+ reason: String(result.reason?.message || result.reason || "unknown"),
+ })),
+ incompleteUploaders,
+ uploaderMeta: {
+ screen: screenMeta,
+ camera: cameraMeta,
+ },
+ recorderSession: recorderSession.current,
+ finalizeContext: finalizeContextRef.current,
+ };
+ };
+
+ const exportFinalizeDiagnostics = async (diagnostics) => {
+ try {
+ const payload = diagnostics ||
+ finalizeFailureRef.current || { reason: "no-diagnostics" };
+ const blob = new Blob([JSON.stringify(payload, null, 2)], {
+ type: "application/json",
+ });
+ const objectUrl = URL.createObjectURL(blob);
+ try {
+ await chrome.downloads.download({
+ url: objectUrl,
+ filename: `Screenity-Finalize-Diagnostics-${new Date().toISOString()}.json`,
+ saveAs: false,
+ });
+ } finally {
+ URL.revokeObjectURL(objectUrl);
+ }
+ } catch (err) {
+ console.warn("[CloudRecorder][Finalize] Failed to export diagnostics", {
+ error: err?.message || err,
+ });
+ }
+ };
+
+ const markFinalizeFailure = async (diagnostics) => {
+ finalizeFailureRef.current = diagnostics;
+ setFinalizeFailure(diagnostics);
+ isFinishing.current = false;
+
+ console.error("[CloudRecorder][Finalize] Finalization failed", diagnostics);
+
+ await chrome.storage.local.set({
+ lastFinalizeFailure: diagnostics,
+ });
+ await persistSessionState({
+ status: "finalize-failed",
+ finalizeFailureAt: Date.now(),
+ finalizeFailureReason: diagnostics?.reason || "finalize-failed",
+ });
+ await setPipelineState("finalize-failed", {
+ status: diagnostics?.reason || "finalize-failed",
+ });
+ try {
+ await chrome.storage.local.set({ sceneIdStatus: "failed" });
+ } catch {
+ // ignore
+ }
+ };
const exportLocalRecovery = async (reason = "upload failed") => {
try {
let blob =
@@ -522,6 +907,80 @@ const CloudRecorder = () => {
}
}, []);
+ const recoverPendingScenes = useCallback(async () => {
+ try {
+ const { pendingSceneIndex = [] } = await chrome.storage.local.get([
+ "pendingSceneIndex",
+ ]);
+ if (!pendingSceneIndex.length) return;
+
+ for (const sceneId of pendingSceneIndex) {
+ const sceneKey = `pendingScene:${sceneId}`;
+ const result = await chrome.storage.local.get([sceneKey]);
+ const pending = result?.[sceneKey];
+ if (!pending || pending.status === "created") {
+ await removePendingScene(sceneId);
+ continue;
+ }
+
+ const {
+ projectId,
+ screenMediaId,
+ cameraMediaId,
+ audioMediaId,
+ } = pending;
+
+ if (!projectId) continue;
+
+ await setPipelineState("scene-recovering", {
+ projectId,
+ sceneId,
+ });
+ logDebugEvent("scene-recover-attempt", {
+ projectId,
+ sceneId,
+ });
+
+ const recoverResult = await recoverScene({
+ projectId,
+ sceneId,
+ screenMediaId,
+ cameraMediaId,
+ audioMediaId,
+ });
+
+ if (recoverResult.ok) {
+ await ensureMediaLinked({
+ projectId,
+ sceneId,
+ mediaIds: [screenMediaId, cameraMediaId, audioMediaId],
+ });
+ await setSceneCreateStatus(sceneId, "created", {
+ recovered: true,
+ });
+ await removePendingScene(sceneId);
+ await markSceneComplete(sceneId);
+ await setPipelineState("scene-recovered", {
+ projectId,
+ sceneId,
+ });
+ logDebugEvent("scene-recover-success", {
+ projectId,
+ sceneId,
+ });
+ } else {
+ logDebugEvent("scene-recover-failed", {
+ projectId,
+ sceneId,
+ error: recoverResult.error,
+ });
+ }
+ }
+ } catch (err) {
+ console.warn("Failed to recover pending scenes", err);
+ }
+ }, []);
+
const attachMicToStream = (videoStream, micStream) => {
if (!videoStream || !micStream) return videoStream;
return new MediaStream([
@@ -832,7 +1291,9 @@ const CloudRecorder = () => {
return;
}
- uploadersInitialized.current = await initializeUploaders();
+ uploadersInitialized.current = await initializeUploaders({
+ forceNewSceneId: true,
+ });
if (!uploadersInitialized.current) {
sendRecordingError("Failed to re-initialize uploaders on restart.");
return;
@@ -840,15 +1301,23 @@ const CloudRecorder = () => {
chrome.runtime.sendMessage({ type: "reset-active-tab-restart" });
};
- const initializeUploaders = async () => {
+ const initializeUploaders = async ({ forceNewSceneId = false } = {}) => {
try {
emptyCleanupRef.current = false;
const { projectId } = await chrome.storage.local.get(["projectId"]);
- const sceneId = crypto.randomUUID();
- chrome.storage.local.set({
+ const sceneId = await getOrCreateSceneId({
+ forceNew: forceNewSceneId,
+ });
+ await chrome.storage.local.set({
sceneId,
+ sceneIdStatus: "recording",
});
+ await setPipelineState("uploaders-initializing", {
+ projectId,
+ sceneId,
+ });
+ logDebugEvent("uploaders-init-start", { projectId, sceneId });
if (!projectId) {
throw new Error("Missing projectId");
@@ -894,6 +1363,13 @@ const CloudRecorder = () => {
height,
sceneId,
});
+ logDebugEvent("uploader-ready", {
+ type: "screen",
+ projectId,
+ sceneId,
+ mediaId: screenUploader.current?.getMeta()?.mediaId || null,
+ videoId: screenUploader.current?.getMeta()?.videoId || null,
+ });
}
if (cameraStream.current) {
@@ -921,12 +1397,29 @@ const CloudRecorder = () => {
height,
sceneId,
});
+ logDebugEvent("uploader-ready", {
+ type: "camera",
+ projectId,
+ sceneId,
+ mediaId: cameraUploader.current?.getMeta()?.mediaId || null,
+ videoId: cameraUploader.current?.getMeta()?.videoId || null,
+ });
}
+ await setPipelineState("uploaders-ready", {
+ projectId,
+ sceneId,
+ });
+ logDebugEvent("uploaders-init-complete", { projectId, sceneId });
return true;
} catch (err) {
console.error("❌ Failed to initialize uploaders:", err);
sendRecordingError("Failed to initialize uploaders: " + err.message);
+ await setPipelineState("uploaders-error", {
+ status: "error",
+ details: err?.message || String(err),
+ });
+ logDebugEvent("uploaders-init-failed", { error: err?.message || err });
return false;
}
};
@@ -990,6 +1483,9 @@ const CloudRecorder = () => {
return;
}
+ await setPipelineState("recording-starting", { projectId });
+ logDebugEvent("recording-starting", { projectId });
+
if (isTab.current && recordingTabId.current) {
const tabAlive = await chrome.tabs
.get(recordingTabId.current)
@@ -1272,6 +1768,20 @@ const CloudRecorder = () => {
pausedStateRef.current = false;
persistSessionState({ status: "recording" });
setStarted(true);
+ await setPipelineState("recording", {
+ projectId,
+ sceneId:
+ screenUploader.current?.getMeta()?.sceneId ||
+ cameraUploader.current?.getMeta()?.sceneId ||
+ null,
+ });
+ logDebugEvent("recording-started", {
+ projectId,
+ sceneId:
+ screenUploader.current?.getMeta()?.sceneId ||
+ cameraUploader.current?.getMeta()?.sceneId ||
+ null,
+ });
} catch (err) {
sendRecordingError("Recording failed: " + err.message);
}
@@ -1397,11 +1907,25 @@ const CloudRecorder = () => {
const audioFile = new File([audioBlob], "audio-recording.webm", {
type: "audio/webm",
});
+ logDebugEvent("audio-upload-start", {
+ projectId,
+ sceneId: uploadMeta?.sceneId || null,
+ });
const result = await uploadAudioToBunny(audioFile, projectId);
+ logDebugEvent("audio-upload-complete", {
+ projectId,
+ sceneId: uploadMeta?.sceneId || null,
+ mediaId: result?.mediaId || null,
+ });
return result;
} catch (err) {
console.warn("❌ Audio upload/transcription failed:", err);
+ logDebugEvent("audio-upload-failed", {
+ projectId,
+ sceneId: uploadMeta?.sceneId || null,
+ error: err?.message || String(err),
+ });
}
};
@@ -1412,6 +1936,10 @@ const CloudRecorder = () => {
uploadMeta.screen?.mediaId || uploadMeta.camera?.mediaId;
if (transcriptionTarget && uploadMeta.audio?.url) {
+ const dedupeKey = `transcriptionQueued:${uploadMeta.sceneId}:${uploadMeta.audio.mediaId}`;
+ const dedupe = await chrome.storage.local.get([dedupeKey]);
+ if (dedupe?.[dedupeKey]) return;
+
await fetch(`${API_BASE}/transcription/queue`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -1427,9 +1955,21 @@ const CloudRecorder = () => {
model: "tiny",
}),
});
+ await chrome.storage.local.set({ [dedupeKey]: true });
+ logDebugEvent("transcription-queued", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ inputMediaId: uploadMeta.audio.mediaId,
+ targetMediaId: transcriptionTarget,
+ });
}
} catch (err) {
console.warn("❌ Transcription failed:", err);
+ logDebugEvent("transcription-failed", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ error: err?.message || String(err),
+ });
}
};
@@ -1487,6 +2027,10 @@ const CloudRecorder = () => {
tryRecoverPreviousSession();
}, [tryRecoverPreviousSession]);
+ useEffect(() => {
+ recoverPendingScenes();
+ }, [recoverPendingScenes]);
+
useEffect(() => {
return () => {
stopAllIntervals();
@@ -1550,6 +2094,36 @@ const CloudRecorder = () => {
);
}
+ const existingStatus = await getSceneCreateStatus(uploadMeta.sceneId);
+ if (existingStatus?.status === "created") {
+ logDebugEvent("scene-create-skip", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
+ await ensureMediaLinked({
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ mediaIds: [
+ uploadMeta.screen?.mediaId,
+ uploadMeta.camera?.mediaId,
+ uploadMeta.audio?.mediaId,
+ ],
+ });
+ return { reused: true };
+ }
+
+ await setSceneCreateStatus(uploadMeta.sceneId, "creating", {
+ projectId,
+ });
+ await setPipelineState("scene-creating", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
+ logDebugEvent("scene-create-start", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
+
const payload = {
sceneId: uploadMeta.sceneId,
screenMediaId: uploadMeta.screen?.mediaId || null,
@@ -1557,6 +2131,7 @@ const CloudRecorder = () => {
screenVideoId: uploadMeta.screen?.videoId || null,
cameraVideoId: uploadMeta.camera?.videoId || null,
audioMediaId: uploadMeta.audio?.mediaId || null,
+ recordingSessionId: recorderSession.current?.id || null,
durations,
captionSource: uploadMeta.screen ? "screen" : "camera",
transcriptionSourceMediaId: !isSilent
@@ -1594,8 +2169,70 @@ const CloudRecorder = () => {
if (!res.ok) {
const errorText = await res.text();
+ const recoverResult = await recoverScene({
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ screenMediaId: uploadMeta.screen?.mediaId || null,
+ cameraMediaId: uploadMeta.camera?.mediaId || null,
+ audioMediaId: uploadMeta.audio?.mediaId || null,
+ });
+
+ if (recoverResult.ok) {
+ await setSceneCreateStatus(uploadMeta.sceneId, "created", {
+ recovered: true,
+ });
+ await ensureMediaLinked({
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ mediaIds: [
+ uploadMeta.screen?.mediaId,
+ uploadMeta.camera?.mediaId,
+ uploadMeta.audio?.mediaId,
+ ],
+ });
+ await removePendingScene(uploadMeta.sceneId);
+ await markSceneComplete(uploadMeta.sceneId);
+ await setPipelineState("scene-recovered", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
+ logDebugEvent("scene-recovered", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
+ return { recovered: true };
+ }
+
+ logDebugEvent("scene-create-failed", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ error: errorText,
+ });
+ await setSceneCreateStatus(uploadMeta.sceneId, "failed", {
+ error: errorText,
+ });
throw new Error(`Failed to create scene: ${errorText}`);
} else {
+ await setSceneCreateStatus(uploadMeta.sceneId, "created");
+ await ensureMediaLinked({
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ mediaIds: [
+ uploadMeta.screen?.mediaId,
+ uploadMeta.camera?.mediaId,
+ uploadMeta.audio?.mediaId,
+ ],
+ });
+ await removePendingScene(uploadMeta.sceneId);
+ await markSceneComplete(uploadMeta.sceneId);
+ await setPipelineState("scene-created", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
+ logDebugEvent("scene-create-complete", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
if (multiMode) {
await chrome.storage.local.set({
multiSceneCount: multiSceneCount + 1,
@@ -1672,6 +2309,7 @@ const CloudRecorder = () => {
ts: Date.now(),
},
});
+ const stage = reason || (shouldFinalize ? "finalize" : "stop");
if (keepAliveInterval.current) {
clearInterval(keepAliveInterval.current);
@@ -1725,14 +2363,77 @@ const CloudRecorder = () => {
await flushPendingChunks();
let finalizeError = null;
- try {
- await Promise.allSettled([
- screenUploader.current?.finalize?.(),
- cameraUploader.current?.finalize?.(),
- ]);
- } catch (err) {
- finalizeError = err;
- console.warn("Finalize threw an error:", err);
+ const finalizeCalls = [
+ screenUploader.current?.finalize?.(),
+ cameraUploader.current?.finalize?.(),
+ ];
+
+ if (
+ shouldSimulateFinalizeFailure() &&
+ !simulateFinalizeFailureConsumedRef.current
+ ) {
+ simulateFinalizeFailureConsumedRef.current = true;
+ finalizeCalls.push(
+ Promise.reject(new Error("simulated-finalize-failure")),
+ );
+ }
+
+ const settledResults = await Promise.allSettled(finalizeCalls);
+ const rejectedResults = settledResults.filter(
+ (result) => result.status === "rejected",
+ );
+
+ const screenMeta = screenUploader.current?.getMeta?.() || null;
+ const cameraMeta = cameraUploader.current?.getMeta?.() || null;
+ const incompleteUploaders = [];
+
+ if (screenUploader.current && screenMeta?.status !== "completed") {
+ incompleteUploaders.push({
+ uploader: "screen",
+ status: screenMeta?.status || "unknown",
+ offset: screenMeta?.offset || 0,
+ error: screenMeta?.error || null,
+ });
+ }
+
+ if (cameraUploader.current && cameraMeta?.status !== "completed") {
+ incompleteUploaders.push({
+ uploader: "camera",
+ status: cameraMeta?.status || "unknown",
+ offset: cameraMeta?.offset || 0,
+ error: cameraMeta?.error || null,
+ });
+ }
+
+ if (rejectedResults.length > 0 || incompleteUploaders.length > 0) {
+ const diagnostics = buildFinalizeDiagnostics({
+ stage,
+ settledResults,
+ rejectedResults,
+ incompleteUploaders,
+ reason: "uploader-finalize-incomplete",
+ });
+ await markFinalizeFailure(diagnostics);
+ logDebugEvent("finalize-failed", {
+ stage,
+ diagnostics,
+ });
+ finalizeError = new Error("uploader-finalize-incomplete");
+ } else {
+ console.info("[CloudRecorder][Finalize] Finalization complete", {
+ stage,
+ settledResults: settledResults.map((result, i) => ({
+ index: i,
+ status: result.status,
+ })),
+ screen: screenMeta,
+ camera: cameraMeta,
+ });
+ logDebugEvent("finalize-complete", {
+ stage,
+ screen: screenMeta,
+ camera: cameraMeta,
+ });
}
const { sceneId } = await chrome.storage.local.get(["sceneId"]);
@@ -1754,6 +2455,11 @@ const CloudRecorder = () => {
cleanupTimers();
if (!shouldFinalize) {
+ try {
+ await chrome.storage.local.set({ sceneIdStatus: "cancelled" });
+ } catch {
+ // ignore
+ }
await finalizeRecorderSession("cancelled");
return;
}
@@ -1834,9 +2540,23 @@ const CloudRecorder = () => {
// Create final audio blob from chunks
const audioBlob = createBlobFromChunks(audioChunks.current, "audio/webm");
+ const silent = audioBlob ? await isAudioSilent(audioBlob) : true;
- const result = await handleAudioUpload(audioBlob, projectId, uploadMeta);
- uploadMeta.audio = result;
+ await upsertPendingScene(uploadMeta.sceneId, {
+ projectId,
+ screenMediaId: uploadMeta.screen?.mediaId || null,
+ cameraMediaId: uploadMeta.camera?.mediaId || null,
+ audioMediaId: null,
+ status: "ready",
+ });
+ await setPipelineState("scene-ready", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
+ logDebugEvent("scene-ready", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
chrome.storage.local.set({ uploadMeta });
@@ -1844,10 +2564,21 @@ const CloudRecorder = () => {
if (!sentLast.current) {
sentLast.current = true;
- const silent = audioBlob ? await isAudioSilent(audioBlob) : true;
try {
await createSceneOrHandleMultiMode(uploadMeta, usedDurations, silent);
+ const result = await handleAudioUpload(audioBlob, projectId, uploadMeta);
+ uploadMeta.audio = result;
+ chrome.storage.local.set({ uploadMeta });
+
+ if (result?.mediaId) {
+ await ensureMediaLinked({
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ mediaIds: [uploadMeta.audio?.mediaId],
+ });
+ }
+
if (!silent && audioBlob) {
await handleTranscription(uploadMeta, projectId);
}
@@ -1862,6 +2593,10 @@ const CloudRecorder = () => {
} else {
window.location.reload();
}
+ await setPipelineState("completed", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
await finalizeRecorderSession("completed");
} catch (err) {
console.error("❌ Failed to create scene:", err);
@@ -1891,6 +2626,11 @@ const CloudRecorder = () => {
error: err.message,
},
});
+ await setPipelineState("failed", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ status: err.message,
+ });
// Still close the window even on error to prevent stuck tabs
// Give user time to see the error message
@@ -1904,11 +2644,17 @@ const CloudRecorder = () => {
}
}, 3000);
await exportLocalRecovery("scene-error");
+ try {
+ await chrome.storage.local.set({ sceneIdStatus: "failed" });
+ } catch {
+ // ignore
+ }
await finalizeRecorderSession("failed");
}
}
};
+
const startAudioStream = async (id) => {
const useExact = id && id !== "none";
const audioStreamOptions = {
@@ -2350,6 +3096,14 @@ const CloudRecorder = () => {
}
await chrome.storage.local.set({ projectId: videoId });
+ await setPipelineState("project-ready", {
+ projectId: videoId,
+ status: multiMode ? "multi" : "single",
+ });
+ logDebugEvent("project-ready", {
+ projectId: videoId,
+ multiMode: Boolean(multiMode),
+ });
uploadersInitialized.current = await initializeUploaders();
if (!uploadersInitialized.current) {
@@ -2615,6 +3369,13 @@ const CloudRecorder = () => {
started={started}
isTab={isTab.current}
initProject={initProject}
+ finalizeFailure={finalizeFailure}
+ retryingFinalize={retryingFinalize}
+ onRetryFinalize={retryFinalize}
+ onExportDiagnostics={() =>
+ exportFinalizeDiagnostics(finalizeFailureRef.current)
+ }
+ onExportDebugBundle={exportDebugBundle}
/>
);
};
diff --git a/src/pages/CloudRecorder/RecorderUI.jsx b/src/pages/CloudRecorder/RecorderUI.jsx
index 8351bf6..db602bc 100644
--- a/src/pages/CloudRecorder/RecorderUI.jsx
+++ b/src/pages/CloudRecorder/RecorderUI.jsx
@@ -1,7 +1,17 @@
import React from "react";
import Warning from "./warning/Warning";
-const RecorderUI = ({ started, initProject = false, isTab }) => {
+const RecorderUI = ({
+ started,
+ initProject = false,
+ isTab,
+ finalizeFailure = null,
+ retryingFinalize = false,
+ onRetryFinalize = null,
+ onExportDiagnostics = null,
+ onExportDebugBundle = null,
+}) => {
+ const hasFinalizeFailure = Boolean(finalizeFailure);
return (
<div className="wrap">
<img
@@ -26,6 +36,21 @@ const RecorderUI = ({ started, initProject = false, isTab }) => {
? chrome.i18n.getMessage("recorderSetupDescription")
: chrome.i18n.getMessage("recorderSelectDescription")}
</div>
+ {hasFinalizeFailure && (
+ <>
+ <div className="button-strong" onClick={onRetryFinalize}>
+ {retryingFinalize ? "Retrying..." : "Retry finalize"}
+ </div>
+ <div className="button-stop" onClick={onExportDiagnostics}>
+ Export diagnostics
+ </div>
+ </>
+ )}
+ {onExportDebugBundle && (
+ <div className="button-stop" onClick={onExportDebugBundle}>
+ Generate debug bundle
+ </div>
+ )}
{/*
Optionally:
<div className="button-stop" onClick={() => chrome.runtime.sendMessage({ type: "stop-recording-tab" })}>
diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.js
index 912c403..fb5a20f 100644
--- a/src/pages/CloudRecorder/bunnyTusUploader.js
+++ b/src/pages/CloudRecorder/bunnyTusUploader.js
@@ -94,6 +94,273 @@ export default class BunnyTusUploader {
this._hasExtractedMeta = true; // Skip in-flight thumbnail extraction to avoid timeouts/noise
}
+ debugLog(message, payload = null) {
+ if (!this.debug) return;
+ if (payload) {
+ console.info(`[BunnyTusUploader] ${message}`, payload);
+ return;
+ }
+ console.info(`[BunnyTusUploader] ${message}`);
+ }
+
+ getJournalKey(mediaId) {
+ return mediaId ? `uploadJournal-${mediaId}` : null;
+ }
+
+ getJournalLookupKey(projectId, sceneId, type) {
+ return `uploadJournalLookup-${projectId}-${sceneId || "none"}-${type}`;
+ }
+
+ getVideoMapKey(projectId, sceneId, type) {
+ return `bunnyVideoMap-${projectId}-${sceneId || "none"}-${type || "none"}`;
+ }
+
+ async getVideoMap(projectId, sceneId, type) {
+ if (typeof chrome === "undefined" || !chrome.storage?.local) return null;
+ const key = this.getVideoMapKey(projectId, sceneId, type);
+ const result = await chrome.storage.local.get([key]);
+ const entry = result?.[key];
+ if (!entry || !entry.videoId || !entry.mediaId) return null;
+ return { ...entry, key };
+ }
+
+ async persistVideoMap({
+ projectId,
+ sceneId,
+ type,
+ videoId,
+ mediaId,
+ sessionId,
+ }) {
+ if (typeof chrome === "undefined" || !chrome.storage?.local) return;
+ if (!projectId || !videoId || !mediaId) return;
+ const key = this.getVideoMapKey(projectId, sceneId, type);
+ await chrome.storage.local.set({
+ [key]: {
+ projectId,
+ sceneId: sceneId || null,
+ type: type || null,
+ videoId,
+ mediaId,
+ sessionId: sessionId || null,
+ updatedAt: Date.now(),
+ },
+ });
+ }
+
+ buildFingerprint({ projectId, sceneId, type, width, height, fingerprint }) {
+ if (fingerprint) return fingerprint;
+ return `${projectId || "none"}:${sceneId || "none"}:${type || "none"}:${
+ width || "na"
+ }x${height || "na"}`;
+ }
+
+ async clearUploadJournal(journal = null) {
+ if (typeof chrome === "undefined" || !chrome.storage?.local) return;
+ const keysToRemove = [];
+ const mediaId = journal?.mediaId || this.mediaId || null;
+ const journalKey = journal?.key || this.getJournalKey(mediaId);
+ const lookupKey = journal?.lookupKey || this.journalLookupKey;
+
+ if (journalKey) keysToRemove.push(journalKey);
+ if (lookupKey) keysToRemove.push(lookupKey);
+ if (!keysToRemove.length) return;
+
+ try {
+ await chrome.storage.local.remove(keysToRemove);
+ this.debugLog("Cleared upload journal", {
+ keys: keysToRemove,
+ });
+ } catch (err) {
+ this.debugLog("Failed to clear upload journal", {
+ error: err?.message || err,
+ keys: keysToRemove,
+ });
+ }
+ }
+
+ async persistUploadJournal() {
+ if (typeof chrome === "undefined" || !chrome.storage?.local || !this.mediaId)
+ return;
+ const journalKey = this.getJournalKey(this.mediaId);
+ const lookupKey = this.journalLookupKey;
+ const payload = {
+ key: journalKey,
+ projectId: this.projectId || null,
+ sceneId: this.sceneId || null,
+ type: this.metadata.type || null,
+ width: this.metaWidth || null,
+ height: this.metaHeight || null,
+ fingerprint: this.fingerprint || null,
+ sessionId: this.sessionId || null,
+ uploadUrl: this.uploadUrl || null,
+ signature: this.signature || null,
+ expires: this.expires || null,
+ libraryId: this.libraryId || null,
+ offset: this.offset,
+ totalBytes: this.totalBytes,
+ updatedAt: Date.now(),
+ videoId: this.videoId,
+ mediaId: this.mediaId,
+ stalled: this.stalled,
+ status: this.status,
+ };
+
+ const toStore = {
+ [journalKey]: payload,
+ };
+ if (lookupKey) {
+ toStore[lookupKey] = {
+ mediaId: this.mediaId,
+ key: journalKey,
+ updatedAt: payload.updatedAt,
+ };
+ }
+ await chrome.storage.local.set(toStore);
+ }
+
+ isResumeJournalStale(updatedAt) {
+ if (!updatedAt) return true;
+ const MAX_AGE_MS = 24 * 60 * 60 * 1000;
+ return Date.now() - updatedAt > MAX_AGE_MS;
+ }
+
+ validateResumeJournal(
+ journal,
+ { projectId, sceneId, type, fingerprint, allowSceneMismatch = false }
+ ) {
+ if (!journal || !journal.mediaId || !journal.videoId || !journal.uploadUrl) {
+ return { valid: false, reason: "missing-required-fields" };
+ }
+ if (journal.projectId !== projectId) {
+ return { valid: false, reason: "project-mismatch" };
+ }
+ if (journal.type !== type) {
+ return { valid: false, reason: "type-mismatch" };
+ }
+ if (!allowSceneMismatch && sceneId && journal.sceneId && journal.sceneId !== sceneId) {
+ return { valid: false, reason: "scene-mismatch" };
+ }
+ if (fingerprint && journal.fingerprint && journal.fingerprint !== fingerprint) {
+ return { valid: false, reason: "fingerprint-mismatch" };
+ }
+ if (this.isResumeJournalStale(journal.updatedAt)) {
+ return { valid: false, reason: "stale-journal" };
+ }
+ return { valid: true, reason: "ok" };
+ }
+
+ async getResumeJournal({
+ projectId,
+ sceneId,
+ type,
+ fingerprint,
+ reuse = null,
+ }) {
+ if (typeof chrome === "undefined" || !chrome.storage?.local) return null;
+ const lookupKey = this.getJournalLookupKey(projectId, sceneId, type);
+ const candidates = [];
+
+ if (reuse?.mediaId) {
+ const reuseKey = this.getJournalKey(reuse.mediaId);
+ const reuseResult = await chrome.storage.local.get([reuseKey]);
+ if (reuseResult[reuseKey]) {
+ candidates.push({
+ journal: reuseResult[reuseKey],
+ key: reuseKey,
+ lookupKey,
+ allowSceneMismatch: true,
+ });
+ }
+ }
+
+ const lookupResult = await chrome.storage.local.get([lookupKey]);
+ const mappedMediaId = lookupResult?.[lookupKey]?.mediaId || null;
+ if (mappedMediaId) {
+ const mappedKey = this.getJournalKey(mappedMediaId);
+ const mappedResult = await chrome.storage.local.get([mappedKey]);
+ if (mappedResult[mappedKey]) {
+ candidates.push({
+ journal: mappedResult[mappedKey],
+ key: mappedKey,
+ lookupKey,
+ allowSceneMismatch: false,
+ });
+ }
+ }
+
+ if (!candidates.length) return null;
+
+ for (const candidate of candidates) {
+ const validation = this.validateResumeJournal(candidate.journal, {
+ projectId,
+ sceneId,
+ type,
+ fingerprint,
+ allowSceneMismatch: candidate.allowSceneMismatch,
+ });
+ if (validation.valid) {
+ this.debugLog("Found valid upload journal for resume", {
+ mediaId: candidate.journal.mediaId,
+ projectId,
+ sceneId,
+ type,
+ offset: candidate.journal.offset || 0,
+ });
+ return {
+ ...candidate.journal,
+ key: candidate.key,
+ lookupKey: candidate.lookupKey,
+ };
+ }
+
+ this.debugLog("Discarding invalid upload journal", {
+ reason: validation.reason,
+ mediaId: candidate.journal?.mediaId || null,
+ projectId,
+ sceneId,
+ type,
+ });
+ await this.clearUploadJournal({
+ key: candidate.key,
+ lookupKey: candidate.lookupKey,
+ mediaId: candidate.journal?.mediaId || null,
+ });
+ }
+
+ return null;
+ }
+
+ async getServerOffset() {
+ if (!this.uploadUrl) return null;
+ try {
+ const headRes = await fetch(this.uploadUrl, {
+ method: "HEAD",
+ headers: {
+ "Tus-Resumable": "1.0.0",
+ AuthorizationSignature: this.signature,
+ AuthorizationExpire: String(this.expires),
+ LibraryId: String(this.libraryId),
+ VideoId: this.videoId,
+ },
+ });
+
+ if (!headRes.ok) {
+ this.debugLog("HEAD offset check failed", {
+ status: headRes.status,
+ });
+ return null;
+ }
+
+ const serverOffset = parseInt(headRes.headers.get("Upload-Offset") || "0", 10);
+ return Number.isFinite(serverOffset) ? serverOffset : null;
+ } catch (err) {
+ this.debugLog("HEAD offset check threw", {
+ error: err?.message || err,
+ });
+ return null;
+ }
+ }
async initialize(
projectId,
{
@@ -131,7 +398,43 @@ export default class BunnyTusUploader {
}
this.videoId = reuse.videoId;
this.mediaId = reuse.mediaId;
+ } else if (resumeJournal?.videoId && resumeJournal?.mediaId) {
+ this.videoId = resumeJournal.videoId;
+ this.mediaId = resumeJournal.mediaId;
+ this.uploadUrl = resumeJournal.uploadUrl || null;
+ this.offset = resumeJournal.offset || 0;
+ this.totalBytes = resumeJournal.totalBytes || 0;
+ this.journalKey = resumeJournal.key || this.getJournalKey(this.mediaId);
+ this.debugLog("Resuming upload from journal candidate", {
+ projectId,
+ sceneId,
+ type,
+ mediaId: this.mediaId,
+ offset: this.offset,
+ });
+ await this.persistVideoMap({
+ projectId,
+ sceneId,
+ type,
+ videoId: this.videoId,
+ mediaId: this.mediaId,
+ sessionId: this.sessionId,
+ });
} else {
+ const existingMap = await this.getVideoMap(projectId, sceneId, type);
+ if (existingMap?.videoId && existingMap?.mediaId) {
+ this.videoId = existingMap.videoId;
+ this.mediaId = existingMap.mediaId;
+ this.debugLog("Reusing Bunny video from map", {
+ projectId,
+ sceneId,
+ type,
+ mediaId: this.mediaId,
+ });
+ }
+ }
+
+ if (!this.videoId || !this.mediaId) {
const { authenticated, user } = await new Promise((resolve) => {
chrome.runtime.sendMessage({ type: "check-auth-status" }, resolve);
});
@@ -160,6 +463,7 @@ export default class BunnyTusUploader {
type,
linkedMediaId,
sceneId,
+ recordingSessionId: this.sessionId || null,
}),
});
@@ -167,6 +471,23 @@ export default class BunnyTusUploader {
const data = await res.json();
this.videoId = data.videoId;
this.mediaId = data.mediaId;
+ await this.persistVideoMap({
+ projectId,
+ sceneId,
+ type,
+ videoId: this.videoId,
+ mediaId: this.mediaId,
+ sessionId: this.sessionId,
+ });
+ } else {
+ await this.persistVideoMap({
+ projectId,
+ sceneId,
+ type,
+ videoId: this.videoId,
+ mediaId: this.mediaId,
+ sessionId: this.sessionId,
+ });
}
await this.refreshTusAuth();
@@ -214,19 +535,32 @@ export default class BunnyTusUploader {
? `https://video.bunnycdn.com${location}`
: location;
- await fetch(`${API_BASE}/bunny/videos/save-upload-meta`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${this.userToken}`,
- },
- body: JSON.stringify({
+ if (this.userToken) {
+ await fetch(`${API_BASE}/bunny/videos/save-upload-meta`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${this.userToken}`,
+ },
+ body: JSON.stringify({
+ mediaId: this.mediaId,
+ uploadUrl: this.uploadUrl,
+ signature: this.signature,
+ expires: this.expires,
+ projectId: this.projectId,
+ sceneId: this.sceneId || null,
+ recordingSessionId: this.sessionId || null,
+ type: this.metadata?.type || null,
+ }),
+ });
+ } else {
+ this.debugLog("Skipping save-upload-meta because user token is missing", {
mediaId: this.mediaId,
uploadUrl: this.uploadUrl,
signature: this.signature,
expires: this.expires,
- }),
- });
+ });
+ }
}
async write(chunk) {
diff --git a/src/pages/Content/Wrapper.jsx b/src/pages/Content/Wrapper.jsx
index af711e5..5115cd4 100644
--- a/src/pages/Content/Wrapper.jsx
+++ b/src/pages/Content/Wrapper.jsx
@@ -25,7 +25,10 @@ import { contentStateContext } from "./context/ContentState";
import { startClickTracking } from "./cursor/trackClicks";
-const RecordingLoader = () => {
+const RecordingLoader = ({ progress = 0 }) => {
+ const pct = Math.round(progress || 0);
+ const base = chrome.i18n.getMessage("preparingLabel") || "Preparing recording...";
+ const label = pct > 0 ? `${base} ${pct}%` : base;
return (
<div
style={{
@@ -86,7 +89,7 @@ const RecordingLoader = () => {
animation: "pulse 2s ease-in-out infinite",
}}
>
- Preparing recording...
+ {label}
</div>
<style>
{`
@@ -298,7 +301,9 @@ const Wrapper = () => {
{contentState.recordingType === "region" &&
contentState.customRegion && <Region />}
{shadowRef.current && <Modal shadowRef={shadowRef} />}
- {contentState.preparingRecording && <RecordingLoader />}
+ {contentState.preparingRecording && (
+ <RecordingLoader progress={contentState.processingProgress} />
+ )}
<Countdown />
{contentState.recordingType != "camera" &&
!contentState.onboarding &&
diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsx
index 94110ab..e51c327 100644
--- a/src/pages/Content/context/ContentState.jsx
+++ b/src/pages/Content/context/ContentState.jsx
@@ -56,15 +56,23 @@ const ContentState = (props) => {
const tabIdRef = useRef(null);
const activeTabRef = useRef(null);
const tabRecordedIdRef = useRef(null);
+ const recordingUiTabRef = useRef(null);
+ const recordingStartTimeRef = useRef(null);
+ const lastBeepStartTimeRef = useRef(null);
+ const recordingBeepTabIdRef = useRef(null);
const isTargetTab = useCallback(() => {
const tabId = tabIdRef.current;
const tabRecordedID = tabRecordedIdRef.current;
+ const recordingUiTabId = recordingUiTabRef.current;
const activeTab = activeTabRef.current;
if (tabRecordedID != null) {
return tabId != null && tabId === tabRecordedID;
}
+ if (recordingUiTabId != null) {
+ return tabId != null && tabId === recordingUiTabId;
+ }
if (activeTab != null) {
return tabId != null && tabId === activeTab;
}
@@ -110,10 +118,23 @@ const ContentState = (props) => {
}
});
- chrome.storage.local.get(["activeTab", "tabRecordedID"], (result) => {
- activeTabRef.current = result.activeTab ?? null;
- tabRecordedIdRef.current = result.tabRecordedID ?? null;
- });
+ chrome.storage.local.get(
+ [
+ "activeTab",
+ "tabRecordedID",
+ "recordingUiTabId",
+ "recordingStartTime",
+ "recordingBeepTabId",
+ "recordingNow",
+ ],
+ (result) => {
+ activeTabRef.current = result.activeTab ?? null;
+ tabRecordedIdRef.current = result.tabRecordedID ?? null;
+ recordingUiTabRef.current = result.recordingUiTabId ?? null;
+ recordingStartTimeRef.current = result.recordingStartTime ?? null;
+ recordingBeepTabIdRef.current = result.recordingBeepTabId ?? null;
+ },
+ );
}, []);
useEffect(() => {
@@ -161,6 +182,12 @@ const ContentState = (props) => {
? { countdownActive: false, isCountdownVisible: false }
: {}),
}));
+ if (tabIdRef.current != null) {
+ const preferredTab =
+ tabRecordedIdRef.current ?? recordingUiTabRef.current ?? tabIdRef.current;
+ chrome.storage.local.set({ recordingBeepTabId: preferredTab });
+ recordingBeepTabIdRef.current = preferredTab;
+ }
chrome.storage.local.set({ restarting: false });
// This cannot be triggered from here because the user might not have the page focused
@@ -811,6 +838,7 @@ const ContentState = (props) => {
swatch: 1,
time: 0,
timer: 0,
+ processingProgress: 0,
recording: false,
startRecording: startRecording,
restartRecording: restartRecording,
@@ -917,6 +945,9 @@ const ContentState = (props) => {
hasOpenedBefore: false,
qualityValue: "1080p",
fpsValue: "30",
+ fastRecorderBeta: null,
+ fastRecorderStatus: null,
+ useWebCodecsRecorder: false,
countdownActive: false,
countdownCancelled: false,
multiMode: false,
@@ -1003,6 +1034,62 @@ const ContentState = (props) => {
});
}, []);
+ useEffect(() => {
+ if (!contentState.preparingRecording) return;
+ let canceled = false;
+ let pollTimer = null;
+
+ const getStatus = async () => {
+ const { fastRecorderActiveRecordingId, postStopRecordingId } =
+ await chrome.storage.local.get([
+ "fastRecorderActiveRecordingId",
+ "postStopRecordingId",
+ ]);
+ const recordingId =
+ fastRecorderActiveRecordingId || postStopRecordingId || null;
+ if (!recordingId) return null;
+ const key = `freeFinalizeStatus:${recordingId}`;
+ const res = await chrome.storage.local.get([key]);
+ return res[key] || null;
+ };
+
+ const applyStatus = (status) => {
+ if (!status || canceled) return;
+ const pct =
+ typeof status.percent === "number" ? Math.round(status.percent) : 0;
+ setContentState((prev) => ({
+ ...prev,
+ processingProgress: pct,
+ }));
+ };
+
+ const onChanged = (changes, area) => {
+ if (area !== "local") return;
+ const entry = Object.keys(changes).find((k) =>
+ k.startsWith("freeFinalizeStatus:")
+ );
+ if (!entry) return;
+ applyStatus(changes[entry].newValue);
+ };
+
+ chrome.storage.onChanged.addListener(onChanged);
+
+ (async () => {
+ const status = await getStatus();
+ applyStatus(status);
+ pollTimer = setInterval(async () => {
+ const s = await getStatus();
+ applyStatus(s);
+ }, 500);
+ })();
+
+ return () => {
+ canceled = true;
+ chrome.storage.onChanged.removeListener(onChanged);
+ if (pollTimer) clearInterval(pollTimer);
+ };
+ }, [contentState.preparingRecording]);
+
useEffect(() => {
const isRecording = Boolean(contentState.recording);
if (!hydratedRef.current) {
@@ -1019,6 +1106,22 @@ const ContentState = (props) => {
}
if (prevRecordingRef.current === false && isRecording === true) {
+ if (
+ recordingBeepTabIdRef.current != null &&
+ tabIdRef.current != null &&
+ recordingBeepTabIdRef.current !== tabIdRef.current
+ ) {
+ prevRecordingRef.current = isRecording;
+ return;
+ }
+ const startTime = recordingStartTimeRef.current;
+ const isNewSession =
+ startTime != null && startTime !== lastBeepStartTimeRef.current;
+ if (!isNewSession) {
+ prevRecordingRef.current = isRecording;
+ return;
+ }
+ lastBeepStartTimeRef.current = startTime;
if (suppressStartBeepRef.current) {
suppressStartBeepRef.current = false;
} else {
@@ -1187,7 +1290,19 @@ const ContentState = (props) => {
const interval = setInterval(() => {
updateTimerFromStorage();
}, 1000);
- return () => clearInterval(interval);
+ const handleVisibility = () => {
+ if (!document.hidden) {
+ updateTimerFromStorage();
+ }
+ };
+ const handleFocus = () => updateTimerFromStorage();
+ document.addEventListener("visibilitychange", handleVisibility);
+ window.addEventListener("focus", handleFocus);
+ return () => {
+ clearInterval(interval);
+ document.removeEventListener("visibilitychange", handleVisibility);
+ window.removeEventListener("focus", handleFocus);
+ };
}, [updateTimerFromStorage]);
useEffect(() => {
@@ -1200,11 +1315,26 @@ const ContentState = (props) => {
if (changes.tabRecordedID) {
tabRecordedIdRef.current = changes.tabRecordedID.newValue ?? null;
}
+ if (changes.recordingUiTabId) {
+ recordingUiTabRef.current = changes.recordingUiTabId.newValue ?? null;
+ }
+ if (changes.recordingStartTime) {
+ recordingStartTimeRef.current =
+ changes.recordingStartTime.newValue ?? null;
+ }
+ if (changes.recordingBeepTabId) {
+ recordingBeepTabIdRef.current =
+ changes.recordingBeepTabId.newValue ?? null;
+ }
+ if (changes.recordingNow) {
+ updateTimerFromStorage();
+ }
if (changes.paused) {
setContentState((prev) => ({
...prev,
paused: Boolean(changes.paused.newValue),
}));
+ updateTimerFromStorage();
}
if (changes.recording) {
const isRecording = Boolean(changes.recording.newValue);
@@ -1229,6 +1359,14 @@ const ContentState = (props) => {
}
: {}),
}));
+ updateTimerFromStorage();
+ }
+ if (
+ changes.recordingStartTime ||
+ changes.totalPausedMs ||
+ changes.pausedAt
+ ) {
+ updateTimerFromStorage();
}
if (changes.cursorEffects) {
const nextEffects = normalizeCursorEffects(
diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.js
index 4690f39..c381456 100644
--- a/src/pages/Content/context/messaging/handlers.js
+++ b/src/pages/Content/context/messaging/handlers.js
@@ -7,6 +7,7 @@ import { setContentState, contentStateRef } from "../ContentState";
import { updateFromStorage } from "../utils/updateFromStorage";
import { checkAuthStatus } from "../utils/checkAuthStatus";
+import JSZip from "jszip";
const CLOUD_FEATURES_ENABLED =
process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";
@@ -335,6 +336,12 @@ export const setupHandlers = () => {
}
});
+ registerMessage("show-toast", (message) => {
+ const state = getState();
+ if (typeof state.openToast !== "function") return;
+ state.openToast(message?.message || "", () => {}, message?.timeout || 5000);
+ });
+
registerMessage("backup-error", () => {
const state = getState();
state.openModal(
@@ -351,6 +358,98 @@ export const setupHandlers = () => {
);
});
+ registerMessage("fast-recorder-hard-fail", async () => {
+ const state = getState();
+ if (typeof state.openModal !== "function") return;
+
+ const downloadBundle = async () => {
+ const userAgent = navigator.userAgent;
+ let platformInfo = {};
+ try {
+ platformInfo = await chrome.runtime.sendMessage({
+ type: "get-platform-info",
+ });
+ } catch {}
+
+ const manifestInfo = chrome.runtime.getManifest().version;
+ const fastRecorderData = await chrome.storage.local.get([
+ "fastRecorderBeta",
+ "fastRecorderDecision",
+ "fastRecorderDisabledForDevice",
+ "fastRecorderDisabledReason",
+ "fastRecorderDisabledDetails",
+ "fastRecorderDisabledAt",
+ "fastRecorderProbe",
+ "fastRecorderValidation",
+ "fastRecorderValidationFailed",
+ "fastRecorderInUse",
+ "fastRecorderActiveRecordingId",
+ ]);
+
+ const data = {
+ userAgent: userAgent,
+ platformInfo: platformInfo,
+ manifestInfo: manifestInfo,
+ defaultAudioInput: state.defaultAudioInput,
+ defaultAudioOutput: state.defaultAudioOutput,
+ defaultVideoInput: state.defaultVideoInput,
+ quality: state.quality,
+ systemAudio: state.systemAudio,
+ audioInput: state.audioInput,
+ audioOutput: state.audioOutput,
+ backgroundEffectsActive: state.backgroundEffectsActive,
+ recording: state.recording,
+ recordingType: state.recordingType,
+ askForPermissions: state.askForPermissions,
+ cameraPermission: state.cameraPermission,
+ microphonePermission: state.microphonePermission,
+ askMicrophone: state.askMicrophone,
+ cursorMode: state.cursorMode,
+ zoomEnabled: state.zoomEnabled,
+ offscreenRecording: state.offscreenRecording,
+ updateChrome: state.updateChrome,
+ permissionsChecked: state.permissionsChecked,
+ permissionsLoaded: state.permissionsLoaded,
+ hideUI: state.hideUI,
+ alarm: state.alarm,
+ alarmTime: state.alarmTime,
+ surface: state.surface,
+ blurMode: state.blurMode,
+ fastRecorder: fastRecorderData,
+ };
+
+ const zip = new JSZip();
+ zip.file("troubleshooting.json", JSON.stringify(data));
+ const blob = await zip.generateAsync({ type: "blob" });
+ const url = window.URL.createObjectURL(blob);
+
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "screenity-troubleshooting.zip";
+ a.click();
+ window.URL.revokeObjectURL(url);
+
+ chrome.runtime.sendMessage({ type: "indexed-db-download" });
+ };
+
+ state.openModal(
+ "Fast recorder failed",
+ "The fast recorder output couldn't be validated on this device.\nYou can download the file anyway, or grab a debug bundle for support.",
+ "Download anyway",
+ "Cancel",
+ () => {
+ chrome.runtime.sendMessage({ type: "open-download-mp4" });
+ },
+ () => {},
+ null,
+ null,
+ null,
+ true,
+ "Download debug bundle",
+ downloadBundle
+ );
+ });
+
registerMessage("recording-check", (message, sender) => {
const state = getState();
diff --git a/src/pages/Content/context/utils/updateFromStorage.js b/src/pages/Content/context/utils/updateFromStorage.js
index 2eb4250..561c738 100644
--- a/src/pages/Content/context/utils/updateFromStorage.js
+++ b/src/pages/Content/context/utils/updateFromStorage.js
@@ -68,6 +68,9 @@ export const updateFromStorage = (check = true, id = null) => {
"backupSetup",
"qualityValue",
"fpsValue",
+ "fastRecorderBeta",
+ "fastRecorderStatus",
+ "useWebCodecsRecorder",
"multiMode",
"multiSceneCount",
"sortBy",
@@ -300,6 +303,21 @@ export const updateFromStorage = (check = true, id = null) => {
result.fpsValue !== undefined && result.fpsValue !== null
? result.fpsValue
: prevContentState.fpsValue,
+ fastRecorderBeta:
+ result.fastRecorderBeta !== undefined &&
+ result.fastRecorderBeta !== null
+ ? result.fastRecorderBeta
+ : prevContentState.fastRecorderBeta,
+ fastRecorderStatus:
+ result.fastRecorderStatus !== undefined &&
+ result.fastRecorderStatus !== null
+ ? result.fastRecorderStatus
+ : prevContentState.fastRecorderStatus,
+ useWebCodecsRecorder:
+ result.useWebCodecsRecorder !== undefined &&
+ result.useWebCodecsRecorder !== null
+ ? result.useWebCodecsRecorder
+ : prevContentState.useWebCodecsRecorder,
multiMode: result.multiMode || false,
multiSceneCount: result.multiSceneCount || 0,
wasLoggedIn: result.wasLoggedIn || false,
diff --git a/src/pages/Content/popup/layout/SettingsMenu.jsx b/src/pages/Content/popup/layout/SettingsMenu.jsx
index 0610b0d..2b8b683 100644
--- a/src/pages/Content/popup/layout/SettingsMenu.jsx
+++ b/src/pages/Content/popup/layout/SettingsMenu.jsx
@@ -13,6 +13,11 @@ import JSZip from "jszip";
// Context
import { contentStateContext } from "../../context/ContentState";
+import {
+ probeFastRecorderSupport,
+ shouldUseFastRecorder,
+ getFastRecorderStickyState,
+} from "../../../../media/fastRecorderGate";
const CLOUD_FEATURES_ENABLED =
process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";
@@ -27,6 +32,15 @@ const SettingsMenu = (props) => {
const [RAM, setRAM] = useState(0);
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
+ const [fastRecorderInfo, setFastRecorderInfo] = useState({
+ status: null,
+ probe: null,
+ decision: null,
+ disabled: false,
+ disabledReason: null,
+ disabledDetails: null,
+ disabledAt: null,
+ });
useEffect(() => {
// Check chrome version
@@ -53,55 +67,71 @@ const SettingsMenu = (props) => {
.then((response) => {
platformInfo = response;
const manifestInfo = chrome.runtime.getManifest().version;
+ chrome.storage.local.get(
+ [
+ "fastRecorderBeta",
+ "fastRecorderDecision",
+ "fastRecorderDisabledForDevice",
+ "fastRecorderDisabledReason",
+ "fastRecorderDisabledDetails",
+ "fastRecorderDisabledAt",
+ "fastRecorderProbe",
+ "fastRecorderValidation",
+ "fastRecorderValidationFailed",
+ "fastRecorderInUse",
+ ],
+ (fastRecorderData) => {
+ const data = {
+ userAgent: userAgent,
+ platformInfo: platformInfo,
+ manifestInfo: manifestInfo,
+ defaultAudioInput: contentState.defaultAudioInput,
+ defaultAudioOutput: contentState.defaultAudioOutput,
+ defaultVideoInput: contentState.defaultVideoInput,
+ quality: contentState.quality,
+ systemAudio: contentState.systemAudio,
+ audioInput: contentState.audioInput,
+ audioOutput: contentState.audioOutput,
+ backgroundEffectsActive: contentState.backgroundEffectsActive,
+ recording: contentState.recording,
+ recordingType: contentState.recordingType,
+ askForPermissions: contentState.askForPermissions,
+ cameraPermission: contentState.cameraPermission,
+ microphonePermission: contentState.microphonePermission,
+ askMicrophone: contentState.askMicrophone,
+ cursorMode: contentState.cursorMode,
+ zoomEnabled: contentState.zoomEnabled,
+ offscreenRecording: contentState.offscreenRecording,
+ updateChrome: contentState.updateChrome,
+ permissionsChecked: contentState.permissionsChecked,
+ permissionsLoaded: contentState.permissionsLoaded,
+ hideUI: contentState.hideUI,
+ alarm: contentState.alarm,
+ alarmTime: contentState.alarmTime,
+ surface: contentState.surface,
+ blurMode: contentState.blurMode,
+ fastRecorder: fastRecorderData,
+ //contentState: contentStateData,
+ };
+ // Create a zip file with the original recording and the data
+ const zip = new JSZip();
+ zip.file("troubleshooting.json", JSON.stringify(data));
+ zip.generateAsync({ type: "blob" }).then(function (blob) {
+ const url = window.URL.createObjectURL(blob);
- const data = {
- userAgent: userAgent,
- platformInfo: platformInfo,
- manifestInfo: manifestInfo,
- defaultAudioInput: contentState.defaultAudioInput,
- defaultAudioOutput: contentState.defaultAudioOutput,
- defaultVideoInput: contentState.defaultVideoInput,
- quality: contentState.quality,
- systemAudio: contentState.systemAudio,
- audioInput: contentState.audioInput,
- audioOutput: contentState.audioOutput,
- backgroundEffectsActive: contentState.backgroundEffectsActive,
- recording: contentState.recording,
- recordingType: contentState.recordingType,
- askForPermissions: contentState.askForPermissions,
- cameraPermission: contentState.cameraPermission,
- microphonePermission: contentState.microphonePermission,
- askMicrophone: contentState.askMicrophone,
- cursorMode: contentState.cursorMode,
- zoomEnabled: contentState.zoomEnabled,
- offscreenRecording: contentState.offscreenRecording,
- updateChrome: contentState.updateChrome,
- permissionsChecked: contentState.permissionsChecked,
- permissionsLoaded: contentState.permissionsLoaded,
- hideUI: contentState.hideUI,
- alarm: contentState.alarm,
- alarmTime: contentState.alarmTime,
- surface: contentState.surface,
- blurMode: contentState.blurMode,
- //contentState: contentStateData,
- };
- // Create a zip file with the original recording and the data
- const zip = new JSZip();
- zip.file("troubleshooting.json", JSON.stringify(data));
- zip.generateAsync({ type: "blob" }).then(function (blob) {
- const url = window.URL.createObjectURL(blob);
+ // Download file
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "screenity-troubleshooting.zip";
+ a.click();
+ window.URL.revokeObjectURL(url);
- // Download file
- const a = document.createElement("a");
- a.href = url;
- a.download = "screenity-troubleshooting.zip";
- a.click();
- window.URL.revokeObjectURL(url);
-
- chrome.runtime.sendMessage({
- type: "indexed-db-download",
- });
- });
+ chrome.runtime.sendMessage({
+ type: "indexed-db-download",
+ });
+ });
+ }
+ );
});
},
() => {}
@@ -122,6 +152,154 @@ const SettingsMenu = (props) => {
setRAM(ram);
}, []);
+ const getFastRecDebug = () => {
+ try {
+ const params = new URLSearchParams(window.location.search);
+ return params.get("fastRecDebug") === "1";
+ } catch {
+ return false;
+ }
+ };
+
+ const hasLadderFields = (probe) => {
+ if (!probe || !probe.details) return false;
+ return (
+ Array.isArray(probe.details.attemptSummary) &&
+ probe.details.attemptSummary.length > 0 &&
+ Boolean(probe.details.selectedVideoConfig)
+ );
+ };
+
+ const runFastRecorderProbe = async (source = "auto") => {
+ if (!contentState) return;
+ const userSetting =
+ contentState.useWebCodecsRecorder === true
+ ? true
+ : contentState.useWebCodecsRecorder === false
+ ? false
+ : null;
+ const sticky = await getFastRecorderStickyState();
+ const probe = await probeFastRecorderSupport();
+ const useFast = shouldUseFastRecorder(userSetting, probe, sticky);
+ const decision = {
+ useFast,
+ why:
+ userSetting === false
+ ? "user_disabled"
+ : sticky?.disabled && userSetting !== true
+ ? "sticky_disabled"
+ : probe.ok
+ ? "probe_ok"
+ : "probe_failed",
+ at: Date.now(),
+ };
+ const status = {
+ userSetting,
+ probe: { ...probe, at: probe.at || Date.now() },
+ decision,
+ disabled: Boolean(sticky?.disabled),
+ disabledReason: sticky?.reason || null,
+ disabledDetails: sticky?.details || null,
+ disabledAt: null,
+ updatedAt: Date.now(),
+ };
+ try {
+ await chrome.storage.local.set({ fastRecorderStatus: status });
+ } catch {}
+ setFastRecorderInfo({
+ status,
+ probe: status.probe,
+ decision,
+ disabled: status.disabled,
+ disabledReason: status.disabledReason,
+ disabledDetails: status.disabledDetails,
+ disabledAt: status.disabledAt,
+ });
+ if (getFastRecDebug()) {
+ console.log("[FastRecorderStatus]", { source, status });
+ }
+ return status;
+ };
+
+ const migrateFastRecorderStatus = async () => {
+ const existing = await chrome.storage.local.get(["fastRecorderStatus"]);
+ if (existing.fastRecorderStatus) {
+ const status = existing.fastRecorderStatus;
+ if (!hasLadderFields(status?.probe)) {
+ await runFastRecorderProbe("stale-status");
+ const refreshed = await chrome.storage.local.get(["fastRecorderStatus"]);
+ return refreshed.fastRecorderStatus || status;
+ }
+ return status;
+ }
+ const legacy = await chrome.storage.local.get([
+ "fastRecorderBeta",
+ "fastRecorderProbe",
+ "fastRecorderDecision",
+ "fastRecorderDisabledForDevice",
+ "fastRecorderDisabledReason",
+ "fastRecorderDisabledDetails",
+ "fastRecorderDisabledAt",
+ ]);
+ const status = {
+ userSetting:
+ legacy.fastRecorderBeta === true
+ ? true
+ : legacy.fastRecorderBeta === false
+ ? false
+ : null,
+ probe: legacy.fastRecorderProbe || null,
+ decision: legacy.fastRecorderDecision || null,
+ disabled: Boolean(legacy.fastRecorderDisabledForDevice),
+ disabledReason: legacy.fastRecorderDisabledReason || null,
+ disabledDetails: legacy.fastRecorderDisabledDetails || null,
+ disabledAt: legacy.fastRecorderDisabledAt || null,
+ updatedAt: Date.now(),
+ };
+ try {
+ await chrome.storage.local.set({ fastRecorderStatus: status });
+ } catch {}
+ if (!hasLadderFields(status.probe)) {
+ await runFastRecorderProbe("stale-legacy");
+ const refreshed = await chrome.storage.local.get(["fastRecorderStatus"]);
+ return refreshed.fastRecorderStatus || status;
+ }
+ return status;
+ };
+
+ useEffect(() => {
+ let canceled = false;
+ (async () => {
+ const status = await migrateFastRecorderStatus();
+ if (canceled) return;
+ setFastRecorderInfo((prev) => ({
+ ...prev,
+ status,
+ probe: status?.probe || null,
+ decision: status?.decision || null,
+ disabled: Boolean(status?.disabled),
+ disabledReason: status?.disabledReason || null,
+ disabledDetails: status?.disabledDetails || null,
+ disabledAt: status?.disabledAt || null,
+ }));
+ const staleHours = 12;
+ const probeAgeMs =
+ status?.probe?.at && Number.isFinite(status.probe.at)
+ ? Date.now() - status.probe.at
+ : Infinity;
+ const shouldRun =
+ !status?.probe ||
+ probeAgeMs > staleHours * 60 * 60 * 1000 ||
+ !hasLadderFields(status?.probe);
+ if (shouldRun) {
+ await runFastRecorderProbe("effect");
+ }
+ })();
+ return () => {
+ canceled = true;
+ };
+ }, [contentState?.useWebCodecsRecorder]);
+
return (
<DropdownMenu.Root
open={props.open}
@@ -133,6 +311,20 @@ const SettingsMenu = (props) => {
.then((response) => {
setRestore(response.restore);
});
+
+ chrome.storage.local.get(["fastRecorderStatus"], (result) => {
+ const status = result.fastRecorderStatus || null;
+ setFastRecorderInfo((prev) => ({
+ ...prev,
+ status,
+ probe: status?.probe || null,
+ decision: status?.decision || null,
+ disabled: Boolean(status?.disabled),
+ disabledReason: status?.disabledReason || null,
+ disabledDetails: status?.disabledDetails || null,
+ disabledAt: status?.disabledAt || null,
+ }));
+ });
}}
>
<DropdownMenu.Trigger asChild>
@@ -544,6 +736,38 @@ const SettingsMenu = (props) => {
<img src={CheckWhiteIcon} />
</DropdownMenu.ItemIndicator>
</DropdownMenu.CheckboxItem>
+ {!contentState.isSubscribed &&
+ !contentState.isLoggedIn &&
+ fastRecorderInfo?.probe?.ok === true &&
+ fastRecorderInfo?.probe?.details?.selectedVideoConfig && (
+ <DropdownMenu.CheckboxItem
+ className="DropdownMenuItem"
+ onSelect={(e) => {
+ e.preventDefault();
+ }}
+ onCheckedChange={(checked) => {
+ setContentState((prevContentState) => ({
+ ...prevContentState,
+ useWebCodecsRecorder: checked,
+ }));
+ chrome.storage.local.set({
+ useWebCodecsRecorder: checked,
+ ...(checked
+ ? {
+ lastWebCodecsFailureAt: null,
+ lastWebCodecsFailureCode: null,
+ }
+ : {}),
+ });
+ }}
+ checked={contentState.useWebCodecsRecorder === true}
+ >
+ {chrome.i18n.getMessage("webcodecsToggleLabel")}
+ <DropdownMenu.ItemIndicator className="ItemIndicator">
+ <img src={CheckWhiteIcon} />
+ </DropdownMenu.ItemIndicator>
+ </DropdownMenu.CheckboxItem>
+ )}
{!oldChrome &&
!contentState.isSubscribed &&
!contentState.isLoggedIn && (
diff --git a/src/pages/Download/Download.jsx b/src/pages/Download/Download.jsx
index ae6edad..7da9cc6 100644
--- a/src/pages/Download/Download.jsx
+++ b/src/pages/Download/Download.jsx
@@ -77,6 +77,33 @@ const Download = () => {
window.close();
});
});
+ } else if (message.type === "recover-indexed-db-mp4") {
+ const chunkArray = [];
+ chunksStore
+ .iterate((value) => {
+ if (value && typeof value.index === "number" && value.chunk) {
+ chunkArray.push({ index: value.index, chunk: value.chunk });
+ }
+ })
+ .then(() => {
+ chunkArray.sort((a, b) => a.index - b.index);
+ const blob = new Blob(
+ chunkArray.map((entry) => entry.chunk),
+ { type: "video/mp4" }
+ );
+ const url = URL.createObjectURL(blob);
+ const filename = `screenity-recording-${Date.now()}.mp4`;
+ chrome.downloads
+ .download({
+ url: url,
+ filename,
+ saveAs: true,
+ })
+ .then(() => {
+ URL.revokeObjectURL(url);
+ window.close();
+ });
+ });
}
});
diff --git a/src/pages/Editor/Sandbox.jsx b/src/pages/Editor/Sandbox.jsx
index 95b1a14..007ed4b 100644
--- a/src/pages/Editor/Sandbox.jsx
+++ b/src/pages/Editor/Sandbox.jsx
@@ -251,7 +251,7 @@ const Sandbox = () => {
<div>
<iframe
ref={iframeRef}
- src="sandbox.html"
+ src={`sandbox.html${window.location.search || ""}`}
allowFullScreen={true}
style={{
width: "100%",
diff --git a/src/pages/EditorViewer/Sandbox.jsx b/src/pages/EditorViewer/Sandbox.jsx
index cb97e2c..1ed8069 100644
--- a/src/pages/EditorViewer/Sandbox.jsx
+++ b/src/pages/EditorViewer/Sandbox.jsx
@@ -39,7 +39,7 @@ const Sandbox = () => {
<div>
<iframe
ref={iframeRef}
- src="sandbox.html"
+ src={`sandbox.html${window.location.search || ""}`}
allowFullScreen
style={{
width: "100%",
diff --git a/src/pages/EditorWebCodecs/Sandbox.jsx b/src/pages/EditorWebCodecs/Sandbox.jsx
index 7b73766..ed6fbf7 100644
--- a/src/pages/EditorWebCodecs/Sandbox.jsx
+++ b/src/pages/EditorWebCodecs/Sandbox.jsx
@@ -285,7 +285,7 @@ const Sandbox = () => {
<div>
<iframe
ref={iframeRef}
- src="sandbox.html"
+ src={`sandbox.html${window.location.search || ""}`}
allowFullScreen
style={{
width: "100%",
diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsx
index 0079db3..99d780a 100644
--- a/src/pages/Recorder/Recorder.jsx
+++ b/src/pages/Recorder/Recorder.jsx
@@ -6,6 +6,19 @@ import { sendRecordingError, sendStopRecording } from "./messaging";
import { getBitrates, getResolutionForQuality } from "./recorderConfig";
import { WebCodecsRecorder } from "./webcodecs/WebCodecsRecorder";
import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";
+import {
+ debugRecordingEvent,
+ resetRecordingDebugSession,
+ isRecordingDebugEnabled,
+ hydrateRecordingDebugFlag,
+} from "../utils/recordingDebug";
+import {
+ probeFastRecorderSupport,
+ shouldUseFastRecorder,
+ getFastRecorderStickyState,
+ markFastRecorderFailure,
+ validateFastRecorderOutputBlob,
+} from "../../media/fastRecorderGate";
localforage.config({
driver: localforage.INDEXEDDB,
@@ -23,7 +36,10 @@ document.body.style.willChange = "contents";
// window.SCREENITY_DEBUG_RECORDER = true;
const DEBUG_RECORDER =
typeof window !== "undefined" ? !!window.SCREENITY_DEBUG_RECORDER : false;
-
+const FORCE_MEDIARECORDER =
+ typeof window !== "undefined"
+ ? !!window.SCREENITY_FORCE_MEDIARECORDER
+ : false;
const logPrefix = "[Screenity Recorder]";
function debug(...args) {
@@ -44,6 +60,125 @@ function debugError(...args) {
console.error(logPrefix, ...args);
}
+function logCaptureContext(label, stream) {
+ if (!DEBUG_RECORDER && !isRecordingDebugEnabled()) return;
+ const videoTracks =
+ stream && typeof stream.getVideoTracks === "function"
+ ? stream.getVideoTracks()
+ : [];
+
+ debug(`${label} environment`, {
+ devicePixelRatio: window.devicePixelRatio,
+ screen: { width: window.screen?.width, height: window.screen?.height },
+ inner: { width: window.innerWidth, height: window.innerHeight },
+ });
+
+ videoTracks.forEach((track, index) => {
+ const settings =
+ typeof track.getSettings === "function" ? track.getSettings() : {};
+ const constraints =
+ typeof track.getConstraints === "function" ? track.getConstraints() : {};
+ const capabilities =
+ typeof track.getCapabilities === "function"
+ ? track.getCapabilities()
+ : {};
+ debug(`${label} videoTrack[${index}]`, {
+ label: track.label,
+ settings,
+ constraints,
+ capabilities,
+ });
+ });
+}
+
+function buildTrackSnapshot(track) {
+ if (!track) return null;
+ const settings =
+ typeof track.getSettings === "function" ? track.getSettings() : {};
+ const constraints =
+ typeof track.getConstraints === "function" ? track.getConstraints() : {};
+ const capabilities =
+ typeof track.getCapabilities === "function" ? track.getCapabilities() : {};
+ return {
+ label: track.label,
+ settings,
+ constraints,
+ capabilities,
+ };
+}
+
+function logRecordingSnapshot(label, data) {
+ if (!DEBUG_RECORDER && !isRecordingDebugEnabled()) return;
+ debug(`Recording snapshot: ${label}`, data);
+}
+
+const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
+
+const QUALITY_ORDER = ["240p", "360p", "480p", "720p", "1080p", "4k"];
+
+const clampQualityValue = (value, maxValue) => {
+ const current = QUALITY_ORDER.includes(value) ? value : "1080p";
+ const max = QUALITY_ORDER.includes(maxValue) ? maxValue : "1080p";
+ return QUALITY_ORDER.indexOf(current) <= QUALITY_ORDER.indexOf(max)
+ ? current
+ : max;
+};
+
+const getFreeCaptureCaps = async () => {
+ try {
+ const { isLoggedIn, isSubscribed } = await chrome.storage.local.get([
+ "isLoggedIn",
+ "isSubscribed",
+ ]);
+ const isPro = Boolean(isLoggedIn && isSubscribed);
+ return {
+ isPro,
+ maxQuality: "1080p",
+ maxFps: 30,
+ };
+ } catch {
+ return {
+ isPro: false,
+ maxQuality: "1080p",
+ maxFps: 30,
+ };
+ }
+};
+
+const computeTargetVideoBps = (width, height, fps) => {
+ const pixels = Number(width) * Number(height);
+ const rate = Number.isFinite(fps) && fps > 0 ? fps : 30;
+ const target = Math.round(pixels * rate * 0.1);
+ return clamp(target, 6_000_000, 24_000_000);
+};
+
+const selectMimeType = (preferredCodec) => {
+ const preferred = (preferredCodec || "").toLowerCase();
+ const mimeTypes = [
+ "video/webm;codecs=vp9,opus",
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8,opus",
+ "video/webm;codecs=vp8",
+ "video/webm;codecs=avc1",
+ "video/webm;codecs=h264",
+ "video/webm",
+ ];
+ const ordered = preferred
+ ? mimeTypes
+ .filter((type) => type.includes(preferred))
+ .concat(mimeTypes.filter((type) => !type.includes(preferred)))
+ : mimeTypes;
+ return ordered.find((type) => MediaRecorder.isTypeSupported(type)) || null;
+};
+
+const getCodecLabel = (mimeType) => {
+ if (!mimeType) return "unknown";
+ if (mimeType.includes("vp9")) return "vp9";
+ if (mimeType.includes("vp8")) return "vp8";
+ if (mimeType.includes("avc1") || mimeType.includes("h264")) return "h264";
+ return "unknown";
+};
+
const Recorder = () => {
const isRestarting = useRef(false);
const isFinishing = useRef(false);
@@ -51,6 +186,8 @@ const Recorder = () => {
const lastTimecode = useRef(0);
const hasChunks = useRef(false);
+ const recdbgSessionRef = useRef(null);
+
const lastSize = useRef(0);
const index = useRef(0);
@@ -99,6 +236,7 @@ const Recorder = () => {
const recordingStartTime = useRef(null);
const sessionHeartbeat = useRef(null);
+ const recordingTick = useRef(null);
debug("Recorder component mounted");
@@ -240,6 +378,26 @@ const Recorder = () => {
}
};
+ /**
+ * Keep timer UI responsive in content scripts by updating a tick in storage.
+ * This runs in the recorder tab, which is kept alive during recording.
+ */
+ const startRecordingTick = () => {
+ if (recordingTick.current) clearInterval(recordingTick.current);
+ recordingTick.current = setInterval(() => {
+ if (isRecording.current) {
+ chrome.storage.local.set({ recordingNow: Date.now() });
+ }
+ }, 1000);
+ };
+
+ const stopRecordingTick = () => {
+ if (recordingTick.current) {
+ clearInterval(recordingTick.current);
+ recordingTick.current = null;
+ }
+ };
+
async function saveChunk(e, i) {
const ts = e.timecode ?? 0;
@@ -403,33 +561,113 @@ const Recorder = () => {
isFinishing.current = false;
const { qualityValue } = await chrome.storage.local.get(["qualityValue"]);
- const { audioBitsPerSecond, videoBitsPerSecond } =
- getBitrates(qualityValue);
+ const { isPro, maxQuality, maxFps } = await getFreeCaptureCaps();
+ const effectiveQualityValue = isPro
+ ? qualityValue
+ : clampQualityValue(qualityValue, maxQuality);
+ const { audioBitsPerSecond, videoBitsPerSecond: bitratePreset } =
+ getBitrates(effectiveQualityValue);
+ let videoBitsPerSecond = bitratePreset;
debug("Bitrates resolved", {
- qualityValue,
+ qualityValue: effectiveQualityValue,
audioBitsPerSecond,
videoBitsPerSecond,
});
- // FLAG: Force old MediaRecorder for testing
- const FORCE_MEDIARECORDER = true;
+ const recordingId = `${Date.now()}-${Math.random()
+ .toString(16)
+ .slice(2, 8)}`;
+ await chrome.storage.local.set({
+ fastRecorderActiveRecordingId: recordingId,
+ fastRecorderInUse: false,
+ fastRecorderValidationFailed: false,
+ fastRecorderValidation: null,
+ });
- const canUseWebCodecs =
- !FORCE_MEDIARECORDER &&
- typeof VideoEncoder !== "undefined" &&
- typeof AudioEncoder !== "undefined" &&
- typeof MediaStreamTrackProcessor !== "undefined";
+ const { useWebCodecsRecorder } = await chrome.storage.local.get([
+ "useWebCodecsRecorder",
+ ]);
+ const userSetting = useWebCodecsRecorder === true ? true : false;
+ const stickyState = await getFastRecorderStickyState();
+ const probeResult = await probeFastRecorderSupport();
+ const shouldUseFast = shouldUseFastRecorder(
+ userSetting,
+ probeResult,
+ stickyState,
+ );
+ const selectedVideoConfig =
+ probeResult?.details?.selectedVideoConfig || null;
+
+ await chrome.storage.local.set({
+ fastRecorderDecision: {
+ shouldUseFast,
+ reasons: probeResult.reasons,
+ stickyDisabled: stickyState.disabled,
+ },
+ fastRecorderStatus: {
+ userSetting,
+ probe: {
+ ok: probeResult.ok,
+ reasons: probeResult.reasons,
+ details: probeResult.details,
+ at: probeResult.at || Date.now(),
+ },
+ decision: {
+ useFast: shouldUseFast,
+ why:
+ userSetting === false
+ ? "user_disabled"
+ : stickyState?.disabled && userSetting !== true
+ ? "sticky_disabled"
+ : probeResult.ok
+ ? "probe_ok"
+ : "probe_failed",
+ at: Date.now(),
+ },
+ disabled: Boolean(stickyState?.disabled),
+ disabledReason: stickyState?.reason || null,
+ disabledDetails: stickyState?.details || null,
+ disabledAt: null,
+ updatedAt: Date.now(),
+ },
+ fastRecorderSelectedVideoConfig: selectedVideoConfig,
+ });
+
+ debugRecordingEvent(recdbgSessionRef, "fast-recorder-probe", {
+ probe: probeResult,
+ stickyState,
+ userSetting,
+ shouldUseFast,
+ });
+
+ const canUseWebCodecs = shouldUseFast;
const videoTrack = liveStream.current?.getVideoTracks()[0] ?? null;
const settings = videoTrack?.getSettings() || {};
- const width = settings.width ?? 1920;
- const height = settings.height ?? 1080;
+ const { width: qualityWidth, height: qualityHeight } =
+ getResolutionForQuality(effectiveQualityValue);
+ const trackWidth = settings.width ?? qualityWidth ?? 1920;
+ const trackHeight = settings.height ?? qualityHeight ?? 1080;
+ const width = Math.min(trackWidth, qualityWidth ?? trackWidth);
+ const height = Math.min(trackHeight, qualityHeight ?? trackHeight);
const { fpsValue } = await chrome.storage.local.get(["fpsValue"]);
let fps = parseInt(fpsValue);
if (Number.isNaN(fps)) fps = 30;
+ if (!isPro) {
+ fps = Math.min(fps, maxFps);
+ }
+ const computedBps = computeTargetVideoBps(width, height, fps);
+ videoBitsPerSecond = !isPro
+ ? Math.min(computedBps, bitratePreset)
+ : computedBps;
+ debug("Video bitrate target", {
+ bitratePreset,
+ videoBitsPerSecond,
+ });
+
debug("Recorder capabilities", {
canUseWebCodecs,
FORCE_MEDIARECORDER,
@@ -454,6 +692,7 @@ const Recorder = () => {
// Start session heartbeat for recovery tracking
startSessionHeartbeat();
+ startRecordingTick();
persistSessionState("recording");
const handleChunk = async (data, timestampMs) => {
@@ -523,7 +762,7 @@ const Recorder = () => {
if (pendingBytes.current > MAX_PENDING_BYTES) {
debugWarn(
- "Pending bytes exceeded threshold, pausing MediaRecorder and draining queue"
+ "Pending bytes exceeded threshold, pausing MediaRecorder and draining queue",
);
try {
if (
@@ -542,7 +781,7 @@ const Recorder = () => {
} catch (err) {
debugError(
"Error while draining queue with MediaRecorder paused",
- err
+ err,
);
await drainQueue();
}
@@ -573,10 +812,74 @@ const Recorder = () => {
videoBitrate: videoBitsPerSecond,
audioBitrate: hasAudioTrack ? audioBitsPerSecond : undefined,
enableAudio: hasAudioTrack,
+ videoEncoderConfig: selectedVideoConfig,
debug: DEBUG_RECORDER,
onFinalized: async () => {
debug("WebCodecsRecorder onFinalized()");
await waitForDrain();
+ await updateFreeFinalizeStatus("chunks_ready", 95);
+ let validation = null;
+ try {
+ const blob = await rebuildBlobFromChunks();
+ validation = await validateFastRecorderOutputBlob(blob, {
+ minBytes: 64 * 1024,
+ timeoutMs: 4000,
+ videoCodec: recorder.current?.selectedVideoCodec || undefined,
+ audioCodec: hasAudioTrack ? "mp4a.40.2" : null,
+ recordingId,
+ });
+ debugRecordingEvent(recdbgSessionRef, "fast-recorder-validate", {
+ validation,
+ });
+ } catch (err) {
+ validation = {
+ ok: false,
+ hardFail: true,
+ reasons: ["validation-exception"],
+ details: { error: String(err) },
+ };
+ }
+
+ if (validation && !validation.ok) {
+ await markFastRecorderFailure("validation-failed", validation);
+ await chrome.storage.local.set({
+ useWebCodecsRecorder: false,
+ lastWebCodecsFailureAt: Date.now(),
+ lastWebCodecsFailureCode: "validation-failed",
+ });
+ const hardFail = Boolean(validation.hardFail);
+ await chrome.storage.local.set({
+ fastRecorderValidationFailed: hardFail,
+ fastRecorderValidation: validation,
+ });
+ await updateFreeFinalizeStatus(
+ "failed",
+ 100,
+ validation.reasons || "validation-failed",
+ );
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
+ });
+ if (hardFail) {
+ chrome.runtime.sendMessage({
+ type: "fast-recorder-hard-fail",
+ recordingId,
+ });
+ if (!sentLast.current) {
+ sentLast.current = true;
+ isFinishing.current = false;
+ chrome.runtime.sendMessage({ type: "video-ready" });
+ }
+ return;
+ }
+ } else {
+ await chrome.storage.local.set({
+ fastRecorderValidationFailed: false,
+ fastRecorderValidation: validation,
+ });
+ }
+ await updateFreeFinalizeStatus("ready", 100);
if (!sentLast.current) {
sentLast.current = true;
isFinishing.current = false;
@@ -599,6 +902,19 @@ const Recorder = () => {
},
onError: (err) => {
debugError("WebCodecsRecorder error", err);
+ markFastRecorderFailure("webcodecs-error", {
+ error: String(err),
+ });
+ chrome.storage.local.set({
+ useWebCodecsRecorder: false,
+ lastWebCodecsFailureAt: Date.now(),
+ lastWebCodecsFailureCode: "webcodecs-error",
+ });
+ updateFreeFinalizeStatus("failed", 100, String(err));
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
+ });
sendRecordingError(String(err));
},
onStop: async () => {
@@ -613,28 +929,68 @@ const Recorder = () => {
if (!ok) {
debugWarn(
- "Falling back to MediaRecorder because WebCodecsRecorder failed"
+ "Falling back to MediaRecorder because WebCodecsRecorder failed",
);
useWebCodecs.current = false;
+ await chrome.storage.local.set({ fastRecorderInUse: false });
+ await chrome.storage.local.set({
+ useWebCodecsRecorder: false,
+ lastWebCodecsFailureAt: Date.now(),
+ lastWebCodecsFailureCode: "start-failed",
+ });
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
+ });
recorder.current = null;
return await startRecording();
}
+ await chrome.storage.local.set({ fastRecorderInUse: true });
+
+ debugRecordingEvent(recdbgSessionRef, "recorder-start", {
+ encoder: "webcodecs",
+ codec: "webcodecs",
+ width,
+ height,
+ fps,
+ videoBitrate: videoBitsPerSecond,
+ audioBitrate: hasAudioTrack ? audioBitsPerSecond : undefined,
+ });
+
+ setTimeout(() => {
+ const afterTrack = liveStream.current?.getVideoTracks?.()[0] ?? null;
+ logRecordingSnapshot("after-start-500ms", {
+ capture: buildTrackSnapshot(afterTrack),
+ });
+ debugRecordingEvent(recdbgSessionRef, "after-start-500ms", {
+ capture: buildTrackSnapshot(afterTrack),
+ });
+ }, 500);
+
+ setTimeout(() => {
+ const afterTrack = liveStream.current?.getVideoTracks?.()[0] ?? null;
+ debugRecordingEvent(recdbgSessionRef, "after-start-1500ms", {
+ capture: buildTrackSnapshot(afterTrack),
+ });
+ }, 1500);
} else {
debug("Using MediaRecorder fallback");
useWebCodecs.current = false;
- recorder.current = createMediaRecorder(liveStream.current, {
- audioBitsPerSecond,
- videoBitsPerSecond,
- });
+ await chrome.storage.local.set({ fastRecorderInUse: false });
+ let recorderToken = 0;
+ let codecFallbackTriggered = false;
+ let mediaRecorderStartAt = Date.now();
+ let recdbgChunkCount = 0;
+ let recdbgTotalBytes = 0;
+ let activeCodec = "vp9";
+ let activeMimeType = null;
try {
recorder.current.start(1000);
debug("MediaRecorder.start(1000) called");
} catch (err) {
debugError("Failed to start MediaRecorder", err);
- sendRecordingError(
- "Failed to start recording: " + JSON.stringify(err)
- );
+ sendRecordingError("Failed to start recording: " + String(err));
return;
}
@@ -690,7 +1046,18 @@ const Recorder = () => {
}
} catch (err) {
debugError("startRecording() top-level error", err);
- sendRecordingError(JSON.stringify(err));
+ if (useWebCodecs.current) {
+ await chrome.storage.local.set({
+ useWebCodecsRecorder: false,
+ lastWebCodecsFailureAt: Date.now(),
+ lastWebCodecsFailureCode: "start-exception",
+ });
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
+ });
+ }
+ sendRecordingError(String(err));
return;
}
@@ -711,7 +1078,7 @@ const Recorder = () => {
};
console.warn(
"[Recorder] Audio track ended unexpectedly",
- diagnosticInfo
+ diagnosticInfo,
);
chrome.storage.local.set({
recording: false,
@@ -760,7 +1127,7 @@ const Recorder = () => {
};
console.warn(
"[Recorder] helperVideoStream video track ended",
- diagnosticInfo
+ diagnosticInfo,
);
chrome.storage.local.set({
recording: false,
@@ -827,6 +1194,54 @@ const Recorder = () => {
debug("warmUpStream() done");
}
+ const rebuildBlobFromChunks = async () => {
+ const items = [];
+ await chunksStore.ready();
+ await chunksStore.iterate((value) => (items.push(value), undefined));
+ items.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));
+ const parts = items.map((c) =>
+ c.chunk instanceof Blob ? c.chunk : new Blob([c.chunk]),
+ );
+ if (!parts.length) return null;
+ const first = parts[0];
+ const inferredType = first?.type || "video/mp4";
+ return new Blob(parts, { type: inferredType });
+ };
+
+ const updateFreeFinalizeStatus = async (stage, percent = 0, error = null) => {
+ try {
+ const { fastRecorderActiveRecordingId } = await chrome.storage.local.get([
+ "fastRecorderActiveRecordingId",
+ ]);
+ if (!fastRecorderActiveRecordingId) return;
+ const key = `freeFinalizeStatus:${fastRecorderActiveRecordingId}`;
+ const existing = await chrome.storage.local.get([key]);
+ const current = existing[key];
+ if (
+ current &&
+ (current.stage === "ready" || current.stage === "chunks_ready") &&
+ (stage === "stopping" || stage === "finalizing")
+ ) {
+ return;
+ }
+ debugRecordingEvent(recdbgSessionRef, "free-finalize-status", {
+ recordingId: fastRecorderActiveRecordingId,
+ stage,
+ percent,
+ error: error || undefined,
+ });
+ await chrome.storage.local.set({
+ [key]: {
+ recordingId: fastRecorderActiveRecordingId,
+ stage,
+ percent,
+ updatedAt: Date.now(),
+ error: error || undefined,
+ },
+ });
+ } catch {}
+ };
+
async function stopRecording() {
if (isFinishing.current) {
debugWarn("stopRecording() called while already finishing");
@@ -835,9 +1250,11 @@ const Recorder = () => {
debug("stopRecording()");
isFinishing.current = true;
isRecording.current = false;
+ await updateFreeFinalizeStatus("stopping", 0);
// Stop the session heartbeat and persist final state
stopSessionHeartbeat();
+ stopRecordingTick();
persistSessionState("stopping");
await setRecordingTimingState({
recording: false,
@@ -854,9 +1271,11 @@ const Recorder = () => {
recorder.current instanceof WebCodecsRecorder
) {
debug("Stopping WebCodecsRecorder");
+ await updateFreeFinalizeStatus("finalizing", 20);
await recorder.current.stop();
} else if (recorder.current instanceof MediaRecorder) {
debug("Stopping MediaRecorder");
+ await updateFreeFinalizeStatus("finalizing", 20);
try {
recorder.current.requestData();
} catch {}
@@ -869,6 +1288,9 @@ const Recorder = () => {
}
await waitForDrain();
+ if (!useWebCodecs.current) {
+ await updateFreeFinalizeStatus("chunks_ready", 100);
+ }
recorder.current = null;
// Stop the silent audio keep-alive
@@ -887,6 +1309,9 @@ const Recorder = () => {
helperVideoStream.current = null;
helperAudioStream.current = null;
}
+ if (!useWebCodecs.current) {
+ await updateFreeFinalizeStatus("ready", 100);
+ }
}
const dismissRecording = async () => {
@@ -976,10 +1401,7 @@ const Recorder = () => {
};
const { defaultAudioInputLabel, audioinput } =
- await chrome.storage.local.get([
- "defaultAudioInputLabel",
- "audioinput",
- ]);
+ await chrome.storage.local.get(["defaultAudioInputLabel", "audioinput"]);
const desiredLabel =
defaultAudioInputLabel ||
audioinput?.find((device) => device.deviceId === id)?.label ||
@@ -1013,7 +1435,7 @@ const Recorder = () => {
.catch((err) => {
debugWarn(
"startAudioStream() exact device failed, retrying generic",
- err
+ err,
);
const audioStreamOptions = {
mimeType: "video/webm;codecs=vp8,opus",
@@ -1077,7 +1499,11 @@ const Recorder = () => {
});
const { qualityValue } = await chrome.storage.local.get(["qualityValue"]);
- const { width, height } = getResolutionForQuality(qualityValue);
+ const { isPro, maxQuality, maxFps } = await getFreeCaptureCaps();
+ const effectiveQualityValue = isPro
+ ? qualityValue
+ : clampQualityValue(qualityValue, maxQuality);
+ const { width, height } = getResolutionForQuality(effectiveQualityValue);
const { fpsValue } = await chrome.storage.local.get(["fpsValue"]);
let fps = parseInt(fpsValue);
@@ -1085,6 +1511,9 @@ const Recorder = () => {
if (isNaN(fps)) {
fps = 30;
}
+ if (!isPro) {
+ fps = Math.min(fps, maxFps);
+ }
let userConstraints = {
audio: {
@@ -1103,6 +1532,19 @@ const Recorder = () => {
},
},
};
+ if (!isPro && userConstraints.video) {
+ userConstraints.video = {
+ ...userConstraints.video,
+ width: {
+ ideal: width,
+ max: width,
+ },
+ height: {
+ ideal: height,
+ max: height,
+ },
+ };
+ }
if (permissions.state === "denied") {
userConstraints.video = false;
}
@@ -1112,7 +1554,7 @@ const Recorder = () => {
debug("User media constraints", {
userConstraints,
- qualityValue,
+ qualityValue: effectiveQualityValue,
fps,
});
@@ -1136,15 +1578,13 @@ const Recorder = () => {
]);
const desiredAudioLabel =
defaultAudioInputLabel ||
- audioinput?.find(
- (device) => device.deviceId === data.defaultAudioInput
- )?.label ||
+ audioinput?.find((device) => device.deviceId === data.defaultAudioInput)
+ ?.label ||
"";
const desiredVideoLabel =
defaultVideoInputLabel ||
- videoinput?.find(
- (device) => device.deviceId === data.defaultVideoInput
- )?.label ||
+ videoinput?.find((device) => device.deviceId === data.defaultVideoInput)
+ ?.label ||
"";
const hasAudioDevice =
@@ -1243,7 +1683,7 @@ const Recorder = () => {
}
} catch (err) {
debugError("Failed to get user media for desktop/tab capture", err);
- sendRecordingError("Failed to get user media: " + JSON.stringify(err));
+ sendRecordingError("Failed to get user media: " + String(err));
return;
}
@@ -1282,7 +1722,7 @@ const Recorder = () => {
debug("System/tab audio tracks", sysTracks.length);
if (sysTracks.length > 0) {
const sysSource = aCtx.current.createMediaStreamSource(
- new MediaStream([sysTracks[0]])
+ new MediaStream([sysTracks[0]]),
);
audioOutputGain.current = aCtx.current.createGain();
sysSource.connect(audioOutputGain.current).connect(destination.current);
@@ -1293,7 +1733,7 @@ const Recorder = () => {
debug("Mic audio tracks", micTracks.length);
if (micTracks.length > 0) {
const micSource = aCtx.current.createMediaStreamSource(
- new MediaStream([micTracks[0]])
+ new MediaStream([micTracks[0]]),
);
audioInputGain.current = aCtx.current.createGain();
micSource.connect(audioInputGain.current).connect(destination.current);
@@ -1321,7 +1761,7 @@ const Recorder = () => {
helperVideoStream.current.getAudioTracks().length > 0
) {
liveStream.current.addTrack(
- destination.current.stream.getAudioTracks()[0]
+ destination.current.stream.getAudioTracks()[0],
);
}
@@ -1380,7 +1820,7 @@ const Recorder = () => {
} else {
startStream(data, streamId, options, permissions, permissions2);
}
- }
+ },
);
} else {
debug("Streaming with pre-resolved tabID", tabID.current);
@@ -1388,10 +1828,7 @@ const Recorder = () => {
}
} catch (err) {
debugError("startStreaming() error", err);
- sendRecordingError(
- "Failed to start streaming: " + JSON.stringify(err),
- true
- );
+ sendRecordingError("Failed to start streaming: " + String(err), true);
}
}
@@ -1528,7 +1965,7 @@ const Recorder = () => {
dismissRecording();
}
},
- [recorder.current, tabPreferred.current]
+ [recorder.current, tabPreferred.current],
);
useEffect(() => {
diff --git a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
index 986bda2..7b82fe1 100644
--- a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
+++ b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
@@ -50,6 +50,11 @@ export class WebCodecsRecorder {
this.frameCount = 0;
// Monotonic video frame index for safe timestamps
this._videoFrameIndex = 0;
+ this._videoStartUs = null;
+ this._frameDurationUs = null;
+
+ this.audioSamplesWritten = 0;
+ this.audioSampleRate = null;
this.resizeCanvas = null;
this.resizeCtx = null;
@@ -92,6 +97,9 @@ export class WebCodecsRecorder {
this.firstVideoFrame = undefined;
this._stopping = false;
this._videoFrameIndex = 0;
+ this._videoStartUs = null;
+ this._frameDurationUs = null;
+ this.audioSamplesWritten = 0;
if (this.running) return this._startPromise;
@@ -148,14 +156,45 @@ export class WebCodecsRecorder {
this.log("[WCR] Target:", this.targetWidth, "x", this.targetHeight);
const fps = this.options.fps || 30;
+ this._frameDurationUs = Math.round(1_000_000 / fps);
const safeBitrate = this.options.videoBitrate || 10_000_000;
- const videoConfig = await this.chooseVideoEncoderConfig({
- width: this.targetWidth,
- height: this.targetHeight,
- fps,
- bitrate: safeBitrate,
- });
+ const overrideConfig =
+ this.options.videoEncoderConfig && typeof this.options.videoEncoderConfig === "object"
+ ? this.options.videoEncoderConfig
+ : null;
+
+ let videoConfig = null;
+ if (overrideConfig) {
+ const config = {
+ ...overrideConfig,
+ width: this.targetWidth,
+ height: this.targetHeight,
+ };
+ this.log("[WCR] Using override encoder config", config);
+ try {
+ // Verify override is still supported at runtime
+ const support = await VideoEncoder.isConfigSupported(config);
+ if (support?.supported) {
+ videoConfig = {
+ config: support.config || config,
+ codec: (support.config || config).codec || overrideConfig.codec,
+ containerCodec: "avc",
+ };
+ }
+ } catch (err) {
+ this.warn("[WCR] Override config unsupported", err);
+ }
+ }
+
+ if (!videoConfig) {
+ videoConfig = await this.chooseVideoEncoderConfig({
+ width: this.targetWidth,
+ height: this.targetHeight,
+ fps,
+ bitrate: safeBitrate,
+ });
+ }
this.selectedVideoCodec = videoConfig.codec;
const audioConfig = await this.prepareAudioEncoderConfig();
@@ -368,6 +407,10 @@ export class WebCodecsRecorder {
this.firstVideoFrame = undefined;
this.selectedVideoCodec = null;
this._videoFrameIndex = 0;
+ this._videoStartUs = null;
+ this._frameDurationUs = null;
+ this.audioSamplesWritten = 0;
+ this.audioSampleRate = null;
this.resizeCanvas = null;
this.resizeCtx = null;
@@ -432,6 +475,7 @@ export class WebCodecsRecorder {
this.warn("[WCR] AAC unsupported");
return null;
}
+ this.audioSampleRate = support.config?.sampleRate || candidateConfig.sampleRate;
return support.config || candidateConfig;
} catch {
this.warn("[WCR] AAC probe failed");
@@ -520,27 +564,53 @@ export class WebCodecsRecorder {
this.targetHeight
);
- if (!this.startTimeUs) this.startTimeUs = performance.now() * 1000;
+ if (!this._videoStartUs) this._videoStartUs = performance.now() * 1000;
const nowUs = performance.now() * 1000;
- const tsUs = nowUs - this.startTimeUs;
+ const elapsedUs = Math.max(
+ 0,
+ nowUs - this._videoStartUs - (this.totalPausedDurationUs || 0)
+ );
+ const frameDurationUs = this._frameDurationUs || Math.round(1_000_000 / 30);
+ const targetIndex = Math.max(0, Math.floor(elapsedUs / frameDurationUs));
- const resized = new VideoFrame(this.resizeCanvas, {
- timestamp: tsUs,
- });
+ // If we're ahead of wall-clock, drop this frame.
+ if (targetIndex < this._videoFrameIndex) {
+ frame.close();
+ continue;
+ }
- // Keyframe only first frame and after resume
- const keyFrame = this.frameCount === 0 || this.justResumed;
- this.justResumed = false;
+ const startIndex = this._videoFrameIndex;
+ const endIndex = targetIndex;
+ for (let i = startIndex; i <= endIndex; i += 1) {
+ const tsUs = i * frameDurationUs;
+ const resized = new VideoFrame(this.resizeCanvas, {
+ timestamp: tsUs,
+ duration: frameDurationUs,
+ });
- this.videoEncoder.encode(resized, {
- timestamp: tsUs,
- keyFrame,
- });
+ const keyFrame = i === 0 || (this.justResumed && i === startIndex);
+ if (this.justResumed && i === startIndex) {
+ this.justResumed = false;
+ }
- this.frameCount++;
+ this.videoEncoder.encode(resized, {
+ timestamp: tsUs,
+ keyFrame,
+ });
+ if (this.debug && (this.frameCount < 5 || this.frameCount % 300 === 0)) {
+ this.log("[WCR] video pts", {
+ frame: this.frameCount,
+ tsUs,
+ durUs: frameDurationUs,
+ targetIndex,
+ });
+ }
+ this.frameCount++;
+ this._videoFrameIndex = i + 1;
+ resized.close();
+ }
- resized.close();
frame.close();
}
} catch (err) {
@@ -557,6 +627,33 @@ export class WebCodecsRecorder {
if (!this.audioReader) return;
this.log("[WCR] audio loop start");
+ const encodeAudioData = (audioData) => {
+ const sampleRate =
+ audioData.sampleRate || this.audioSampleRate || 48000;
+ const frames =
+ typeof audioData.numberOfFrames === "number"
+ ? audioData.numberOfFrames
+ : 0;
+ const tsUs = Math.round(
+ (this.audioSamplesWritten * 1_000_000) / sampleRate
+ );
+ const durUs = Math.round((frames * 1_000_000) / sampleRate);
+
+ this.audioEncoder.encode(audioData, {
+ timestamp: tsUs,
+ });
+ this.audioSamplesWritten += frames;
+
+ if (this.debug && (this.audioSamplesWritten === frames || this.audioSamplesWritten % (sampleRate * 10) < frames)) {
+ this.log("[WCR] audio pts", {
+ samples: this.audioSamplesWritten,
+ tsUs,
+ durUs,
+ sampleRate,
+ });
+ }
+ };
+
try {
while (this.running) {
const { value: audioData, done } = await this.audioReader
@@ -575,14 +672,18 @@ export class WebCodecsRecorder {
continue;
}
- if (this.firstAudioTs === null) {
- this.firstAudioTs = audioData.timestamp;
- }
-
try {
- this.audioEncoder.encode(audioData, {
- timestamp: audioData.timestamp - this.firstAudioTs,
- });
+ if (this._prebufferedAudio.length) {
+ while (this._prebufferedAudio.length) {
+ const buffered = this._prebufferedAudio.shift();
+ try {
+ encodeAudioData(buffered);
+ } finally {
+ buffered.close?.();
+ }
+ }
+ }
+ encodeAudioData(audioData);
} catch (err) {
audioData.close?.();
this.options.onError?.(err);
diff --git a/src/pages/RecorderOffscreen/RecorderOffscreen.jsx b/src/pages/RecorderOffscreen/RecorderOffscreen.jsx
index 7a06cc2..9383f14 100644
--- a/src/pages/RecorderOffscreen/RecorderOffscreen.jsx
+++ b/src/pages/RecorderOffscreen/RecorderOffscreen.jsx
@@ -65,7 +65,7 @@ const RecorderOffscreen = () => {
} catch (err) {
console.warn(
"[RecorderOffscreen] Failed to persist recording timing state",
- err
+ err,
);
}
};
@@ -246,7 +246,7 @@ const RecorderOffscreen = () => {
// Check if the browser supports any of the mimeTypes, make sure to select the first one that is supported from the list
let mimeType = mimeTypes.find((mimeType) =>
- MediaRecorder.isTypeSupported(mimeType)
+ MediaRecorder.isTypeSupported(mimeType),
);
// If no mimeType is supported, throw an error
@@ -268,7 +268,7 @@ const RecorderOffscreen = () => {
chrome.runtime.sendMessage({
type: "recording-error",
error: "stream-error",
- why: JSON.stringify(err),
+ why: String(err),
});
return;
}
@@ -282,7 +282,7 @@ const RecorderOffscreen = () => {
chrome.runtime.sendMessage({
type: "recording-error",
error: "stream-error",
- why: JSON.stringify(err),
+ why: String(err),
});
return;
}
@@ -369,7 +369,7 @@ const RecorderOffscreen = () => {
};
console.warn(
"[RecorderOffscreen] liveStream video track ended",
- diagnosticInfo
+ diagnosticInfo,
);
chrome.storage.local.set({
recording: false,
@@ -395,7 +395,7 @@ const RecorderOffscreen = () => {
};
console.warn(
"[RecorderOffscreen] helperVideoStream video track ended",
- diagnosticInfo
+ diagnosticInfo,
);
chrome.storage.local.set({
recording: false,
@@ -486,10 +486,7 @@ const RecorderOffscreen = () => {
};
const { defaultAudioInputLabel, audioinput } =
- await chrome.storage.local.get([
- "defaultAudioInputLabel",
- "audioinput",
- ]);
+ await chrome.storage.local.get(["defaultAudioInputLabel", "audioinput"]);
const desiredLabel =
defaultAudioInputLabel ||
audioinput?.find((device) => device.deviceId === id)?.label ||
@@ -634,13 +631,13 @@ const RecorderOffscreen = () => {
const desiredAudioLabel =
defaultAudioInputLabel ||
audioinput?.find(
- (device) => device.deviceId === data.defaultAudioInput
+ (device) => device.deviceId === data.defaultAudioInput,
)?.label ||
"";
const desiredVideoLabel =
defaultVideoInputLabel ||
videoinput?.find(
- (device) => device.deviceId === data.defaultVideoInput
+ (device) => device.deviceId === data.defaultVideoInput,
)?.label ||
"";
@@ -774,7 +771,7 @@ const RecorderOffscreen = () => {
) {
audioInputGain.current = aCtx.current.createGain();
audioInputSource.current = aCtx.current.createMediaStreamSource(
- helperAudioStream.current
+ helperAudioStream.current,
);
audioInputSource.current
.connect(audioInputGain.current)
@@ -791,7 +788,7 @@ const RecorderOffscreen = () => {
if (helperVideoStream.current.getAudioTracks().length > 0) {
audioOutputGain.current = aCtx.current.createGain();
audioOutputSource.current = aCtx.current.createMediaStreamSource(
- helperVideoStream.current
+ helperVideoStream.current,
);
audioOutputSource.current
.connect(audioOutputGain.current)
@@ -802,7 +799,7 @@ const RecorderOffscreen = () => {
// Add the tracks to the stream
liveStream.current.addTrack(
- helperVideoStream.current.getVideoTracks()[0]
+ helperVideoStream.current.getVideoTracks()[0],
);
if (
(helperAudioStream.current != null &&
@@ -810,7 +807,7 @@ const RecorderOffscreen = () => {
helperVideoStream.current.getAudioTracks().length > 0
) {
liveStream.current.addTrack(
- destination.current.stream.getAudioTracks()[0]
+ destination.current.stream.getAudioTracks()[0],
);
}
@@ -821,7 +818,7 @@ const RecorderOffscreen = () => {
chrome.runtime.sendMessage({
type: "recording-error",
error: "cancel-modal",
- why: JSON.stringify(err),
+ why: String(err),
});
}
}
@@ -893,7 +890,7 @@ const RecorderOffscreen = () => {
} catch (err) {
console.warn(
"[RecorderOffscreen] Failed to update resume timing state",
- err
+ err,
);
}
})();
@@ -901,7 +898,7 @@ const RecorderOffscreen = () => {
dismissRecording();
}
},
- [recorder.current]
+ [recorder.current],
);
useEffect(() => {
diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsx
index 6e1bff1..45cbce3 100644
--- a/src/pages/Region/Recorder.jsx
+++ b/src/pages/Region/Recorder.jsx
@@ -1,5 +1,19 @@
import React, { useEffect, useRef, useCallback } from "react";
import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";
+import { WebCodecsRecorder } from "../Recorder/webcodecs/WebCodecsRecorder";
+import {
+ debugRecordingEvent,
+ resetRecordingDebugSession,
+ isRecordingDebugEnabled,
+ hydrateRecordingDebugFlag,
+} from "../utils/recordingDebug";
+import {
+ probeFastRecorderSupport,
+ shouldUseFastRecorder,
+ getFastRecorderStickyState,
+ markFastRecorderFailure,
+ validateFastRecorderOutputBlob,
+} from "../../media/fastRecorderGate";
import localforage from "localforage";
@@ -14,6 +28,78 @@ const chunksStore = localforage.createInstance({
name: "chunks",
});
+// Debug flag for logging
+// window.SCREENITY_DEBUG_RECORDER = true;
+const DEBUG_RECORDER =
+ typeof window !== "undefined" ? !!window.SCREENITY_DEBUG_RECORDER : false;
+const logPrefix = "[Screenity Region Recorder]";
+
+function debug(...args) {
+ if (!DEBUG_RECORDER) return;
+ // eslint-disable-next-line no-console
+ console.log(logPrefix, ...args);
+}
+
+function debugWarn(...args) {
+ if (!DEBUG_RECORDER) return;
+ // eslint-disable-next-line no-console
+ console.warn(logPrefix, ...args);
+}
+
+function debugError(...args) {
+ if (!DEBUG_RECORDER) return;
+ // eslint-disable-next-line no-console
+ console.error(logPrefix, ...args);
+}
+
+function buildTrackSnapshot(track) {
+ if (!track) return null;
+ const settings =
+ typeof track.getSettings === "function" ? track.getSettings() : {};
+ const constraints =
+ typeof track.getConstraints === "function" ? track.getConstraints() : {};
+ const capabilities =
+ typeof track.getCapabilities === "function" ? track.getCapabilities() : {};
+ return {
+ label: track.label,
+ settings,
+ constraints,
+ capabilities,
+ };
+}
+
+function logRecordingSnapshot(label, data) {
+ if (!DEBUG_RECORDER && !isRecordingDebugEnabled()) return;
+ debug(`Recording snapshot: ${label}`, data);
+}
+
+const selectMimeType = (preferredCodec) => {
+ const preferred = (preferredCodec || "").toLowerCase();
+ const mimeTypes = [
+ "video/webm;codecs=vp9,opus",
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8,opus",
+ "video/webm;codecs=vp8",
+ "video/webm;codecs=avc1",
+ "video/webm;codecs=h264",
+ "video/webm",
+ ];
+ const ordered = preferred
+ ? mimeTypes
+ .filter((type) => type.includes(preferred))
+ .concat(mimeTypes.filter((type) => !type.includes(preferred)))
+ : mimeTypes;
+ return ordered.find((type) => MediaRecorder.isTypeSupported(type)) || null;
+};
+
+const getCodecLabel = (mimeType) => {
+ if (!mimeType) return "unknown";
+ if (mimeType.includes("vp9")) return "vp9";
+ if (mimeType.includes("vp8")) return "vp8";
+ if (mimeType.includes("avc1") || mimeType.includes("h264")) return "h264";
+ return "unknown";
+};
+
const Recorder = () => {
const isRestarting = useRef(false);
const isDismissing = useRef(false);
@@ -42,6 +128,8 @@ const Recorder = () => {
const audioOutputGain = useRef(null);
const recorder = useRef(null);
+ const useWebCodecs = useRef(false);
+ const recdbgSessionRef = useRef(null);
// Target
const target = useRef(null);
@@ -61,6 +149,7 @@ const Recorder = () => {
const MIN_HEADROOM = 25 * 1024 * 1024;
const MAX_PENDING_BYTES = 8 * 1024 * 1024;
const pendingBytes = useRef(0);
+ const recordingIdRef = useRef(null);
const setRecordingTimingState = async (nextState) => {
try {
@@ -68,7 +157,7 @@ const Recorder = () => {
} catch (err) {
console.warn(
"[Region Recorder] Failed to persist recording timing state",
- err
+ err,
);
}
};
@@ -145,6 +234,49 @@ const Recorder = () => {
return true;
}
+ const rebuildBlobFromChunks = async () => {
+ const items = [];
+ await chunksStore.ready();
+ await chunksStore.iterate((value) => (items.push(value), undefined));
+ items.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));
+ const parts = items.map((c) =>
+ c.chunk instanceof Blob ? c.chunk : new Blob([c.chunk]),
+ );
+ if (!parts.length) return null;
+ const first = parts[0];
+ const inferredType = first?.type || "video/mp4";
+ return new Blob(parts, { type: inferredType });
+ };
+
+ const updateFreeFinalizeStatus = async (stage, percent = 0, error = null) => {
+ try {
+ const recordingId =
+ recordingIdRef.current ||
+ (await chrome.storage.local.get(["fastRecorderActiveRecordingId"]))
+ .fastRecorderActiveRecordingId;
+ if (!recordingId) return;
+ const key = `freeFinalizeStatus:${recordingId}`;
+ const existing = await chrome.storage.local.get([key]);
+ const current = existing[key];
+ if (
+ current &&
+ (current.stage === "ready" || current.stage === "chunks_ready") &&
+ (stage === "stopping" || stage === "finalizing")
+ ) {
+ return;
+ }
+ await chrome.storage.local.set({
+ [key]: {
+ recordingId,
+ stage,
+ percent,
+ updatedAt: Date.now(),
+ error: error || undefined,
+ },
+ });
+ } catch {}
+ };
+
async function drainQueue() {
if (draining.current) return;
draining.current = true;
@@ -196,7 +328,7 @@ const Recorder = () => {
{
type: "screenity-region-capture-loaded",
},
- "*"
+ "*",
);
}, []);
@@ -248,10 +380,21 @@ const Recorder = () => {
return;
}
} catch (err) {
+ if (useWebCodecs.current) {
+ await chrome.storage.local.set({
+ useWebCodecsRecorder: false,
+ lastWebCodecsFailureAt: Date.now(),
+ lastWebCodecsFailureCode: "start-exception",
+ });
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
+ });
+ }
chrome.runtime.sendMessage({
type: "recording-error",
error: "stream-error",
- why: JSON.stringify(err),
+ why: String(err),
});
// Reload this iframe
@@ -300,32 +443,470 @@ const Recorder = () => {
// Check if the browser supports any of the mimeTypes, make sure to select the first one that is supported from the list
let mimeType = mimeTypes.find((mimeType) =>
- MediaRecorder.isTypeSupported(mimeType)
+ MediaRecorder.isTypeSupported(mimeType),
);
- // If no mimeType is supported, throw an error
- if (!mimeType) {
- chrome.runtime.sendMessage({
- type: "recording-error",
- error: "stream-error",
- why: "No supported mimeTypes available",
- });
+ const recordingId = `${Date.now()}-${Math.random()
+ .toString(16)
+ .slice(2, 8)}`;
+ recordingIdRef.current = recordingId;
- // Reload this iframe
- window.location.reload();
- return;
- }
+ await chrome.storage.local.set({
+ fastRecorderActiveRecordingId: recordingId,
+ fastRecorderInUse: false,
+ fastRecorderValidationFailed: false,
+ fastRecorderValidation: null,
+ });
- recorder.current = new MediaRecorder(liveStream.current, {
- mimeType: mimeType,
- audioBitsPerSecond: audioBitsPerSecond,
- videoBitsPerSecond: videoBitsPerSecond,
+ const { useWebCodecsRecorder } = await chrome.storage.local.get([
+ "useWebCodecsRecorder",
+ ]);
+ const userSetting = useWebCodecsRecorder === true ? true : false;
+ const stickyState = await getFastRecorderStickyState();
+ const probeResult = await probeFastRecorderSupport();
+ const shouldUseFast = shouldUseFastRecorder(
+ userSetting,
+ probeResult,
+ stickyState,
+ );
+ const selectedVideoConfig =
+ probeResult?.details?.selectedVideoConfig || null;
+
+ await chrome.storage.local.set({
+ fastRecorderDecision: {
+ shouldUseFast,
+ reasons: probeResult.reasons,
+ stickyDisabled: stickyState.disabled,
+ },
+ fastRecorderStatus: {
+ userSetting,
+ probe: {
+ ok: probeResult.ok,
+ reasons: probeResult.reasons,
+ details: probeResult.details,
+ at: probeResult.at || Date.now(),
+ },
+ decision: {
+ useFast: shouldUseFast,
+ why:
+ userSetting === false
+ ? "user_disabled"
+ : stickyState?.disabled && userSetting !== true
+ ? "sticky_disabled"
+ : probeResult.ok
+ ? "probe_ok"
+ : "probe_failed",
+ at: Date.now(),
+ },
+ disabled: stickyState.disabled,
+ disabledReason: stickyState.reason || null,
+ disabledDetails: stickyState.details || null,
+ disabledAt: stickyState.disabledAt || null,
+ updatedAt: Date.now(),
+ },
});
+
+ const resetChunkState = async () => {
+ await chunksStore.clear();
+ index.current = 0;
+ pending.current = [];
+ pendingBytes.current = 0;
+ savedCount.current = 0;
+ hasChunks.current = false;
+ lastTimecode.current = 0;
+ lastSize.current = 0;
+ sentLast.current = false;
+ };
+
+ const handleWebCodecsChunk = async (blob, timestampUs) => {
+ if (lowStorageAbort.current) return;
+ const timecodeMs = timestampUs ? Math.floor(timestampUs / 1000) : 0;
+ recdbgChunkCount += 1;
+ recdbgTotalBytes += blob.size || 0;
+ if (recdbgChunkCount <= 3) {
+ debugRecordingEvent(recdbgSessionRef, "chunk", {
+ index: recdbgChunkCount,
+ size: blob.size,
+ timecode: timecodeMs,
+ });
+ } else if (recdbgChunkCount % 10 === 0) {
+ debugRecordingEvent(recdbgSessionRef, "chunk-progress", {
+ count: recdbgChunkCount,
+ totalBytes: recdbgTotalBytes,
+ });
+ }
+
+ pending.current.push({ data: blob, timecode: timecodeMs });
+ pendingBytes.current += blob.size;
+
+ if (pendingBytes.current > MAX_PENDING_BYTES) {
+ try {
+ await drainQueue();
+ } catch {}
+ }
+ void drainQueue();
+ };
+
+ const startWebCodecsRecorder = async () => {
+ const hasAudioTrack =
+ !!liveStream.current &&
+ typeof liveStream.current.getAudioTracks === "function" &&
+ liveStream.current.getAudioTracks().length > 0;
+
+ useWebCodecs.current = true;
+ await chrome.storage.local.set({ fastRecorderInUse: true });
+
+ recorder.current = new WebCodecsRecorder(liveStream.current, {
+ width,
+ height,
+ fps,
+ videoBitrate: videoBitsPerSecond,
+ audioBitrate: hasAudioTrack ? audioBitsPerSecond : undefined,
+ enableAudio: hasAudioTrack,
+ videoEncoderConfig: selectedVideoConfig,
+ debug: DEBUG_RECORDER,
+ onFinalized: async () => {
+ await waitForDrain();
+ await updateFreeFinalizeStatus("chunks_ready", 95);
+ let validation = null;
+ try {
+ const blob = await rebuildBlobFromChunks();
+ validation = await validateFastRecorderOutputBlob(blob, {
+ minBytes: 64 * 1024,
+ timeoutMs: 4000,
+ videoCodec: recorder.current?.selectedVideoCodec || undefined,
+ audioCodec: hasAudioTrack ? "mp4a.40.2" : null,
+ recordingId,
+ });
+ debugRecordingEvent(recdbgSessionRef, "fast-recorder-validate", {
+ validation,
+ });
+ } catch (err) {
+ validation = {
+ ok: false,
+ hardFail: true,
+ reasons: ["validation-exception"],
+ details: { error: String(err) },
+ };
+ }
+
+ if (validation && !validation.ok) {
+ await markFastRecorderFailure("validation-failed", validation);
+ await chrome.storage.local.set({
+ useWebCodecsRecorder: false,
+ lastWebCodecsFailureAt: Date.now(),
+ lastWebCodecsFailureCode: "validation-failed",
+ });
+ const hardFail = Boolean(validation.hardFail);
+ await chrome.storage.local.set({
+ fastRecorderValidationFailed: hardFail,
+ fastRecorderValidation: validation,
+ });
+ await updateFreeFinalizeStatus(
+ "failed",
+ 100,
+ validation.reasons || "validation-failed",
+ );
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
+ });
+ if (hardFail) {
+ chrome.runtime.sendMessage({
+ type: "fast-recorder-hard-fail",
+ recordingId,
+ });
+ if (!sentLast.current) {
+ sentLast.current = true;
+ isFinished.current = true;
+ isFinishing.current = false;
+ chrome.runtime.sendMessage({ type: "video-ready" });
+ }
+ return;
+ }
+ } else {
+ await chrome.storage.local.set({
+ fastRecorderValidationFailed: false,
+ fastRecorderValidation: validation,
+ });
+ }
+
+ await updateFreeFinalizeStatus("ready", 100);
+ if (!sentLast.current) {
+ sentLast.current = true;
+ isFinished.current = true;
+ isFinishing.current = false;
+ chrome.runtime.sendMessage({ type: "video-ready" });
+ }
+ },
+ onChunk: (chunkData, timestampUs) => {
+ const blob = new Blob([chunkData], { type: "video/mp4" });
+ handleWebCodecsChunk(blob, timestampUs);
+ },
+ onError: (err) => {
+ markFastRecorderFailure("webcodecs-error", {
+ error: String(err),
+ });
+ chrome.storage.local.set({
+ useWebCodecsRecorder: false,
+ lastWebCodecsFailureAt: Date.now(),
+ lastWebCodecsFailureCode: "webcodecs-error",
+ });
+ updateFreeFinalizeStatus("failed", 100, String(err));
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
+ });
+ chrome.runtime.sendMessage({
+ type: "recording-error",
+ error: "stream-error",
+ why: "Fast recorder failed. Please try compatibility mode.",
+ });
+ },
+ onStop: async () => {
+ debugRecordingEvent(recdbgSessionRef, "recorder-stop", {
+ count: recdbgChunkCount,
+ totalBytes: recdbgTotalBytes,
+ encoder: "webcodecs",
+ });
+ },
+ });
+
+ const started = await recorder.current.start();
+ if (!started) {
+ useWebCodecs.current = false;
+ await chrome.storage.local.set({ fastRecorderInUse: false });
+ await chrome.storage.local.set({
+ useWebCodecsRecorder: false,
+ lastWebCodecsFailureAt: Date.now(),
+ lastWebCodecsFailureCode: "start-failed",
+ });
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
+ });
+ return false;
+ }
+
+ debugRecordingEvent(recdbgSessionRef, "recorder-start", {
+ encoder: "webcodecs",
+ codec: "webcodecs",
+ width,
+ height,
+ fps,
+ timesliceMs: 1000,
+ });
+
+ return true;
+ };
+
+ const startMediaRecorderWithCodec = async (codec) => {
+ const mimeType = selectMimeType(codec);
+ if (!mimeType) {
+ chrome.runtime.sendMessage({
+ type: "recording-error",
+ error: "stream-error",
+ why: `No supported mimeTypes available for ${codec}`,
+ });
+
+ // Reload this iframe
+ window.location.reload();
+ return false;
+ }
+
+ recorderToken += 1;
+ const token = recorderToken;
+ recdbgChunkCount = 0;
+ recdbgTotalBytes = 0;
+ mediaRecorderStartAt = Date.now();
+
+ recorder.current = new MediaRecorder(liveStream.current, {
+ mimeType: mimeType,
+ audioBitsPerSecond: audioBitsPerSecond,
+ videoBitsPerSecond: videoBitsPerSecond,
+ });
+ debug("MediaRecorder config", {
+ mimeType: recorder.current?.mimeType,
+ audioBitsPerSecond,
+ videoBitsPerSecond,
+ });
+ debugRecordingEvent(recdbgSessionRef, "recorder-start", {
+ encoder: "mediarecorder",
+ codec: getCodecLabel(mimeType),
+ mimeType: recorder.current?.mimeType,
+ audioBitsPerSecond,
+ videoBitsPerSecond,
+ width,
+ height,
+ fps,
+ timesliceMs: 1000,
+ });
+
+ setTimeout(() => {
+ if (token !== recorderToken) return;
+ const afterTrack = liveStream.current?.getVideoTracks?.()[0] ?? null;
+ logRecordingSnapshot("after-start-500ms", {
+ capture: buildTrackSnapshot(afterTrack),
+ });
+ debugRecordingEvent(recdbgSessionRef, "after-start-500ms", {
+ capture: buildTrackSnapshot(afterTrack),
+ });
+ }, 500);
+
+ setTimeout(() => {
+ if (token !== recorderToken) return;
+ const afterTrack = liveStream.current?.getVideoTracks?.()[0] ?? null;
+ debugRecordingEvent(recdbgSessionRef, "after-start-1500ms", {
+ capture: buildTrackSnapshot(afterTrack),
+ });
+ }, 1500);
+
+ recorder.current.onerror = (ev) => {
+ if (token !== recorderToken) return;
+ chrome.runtime.sendMessage({
+ type: "recording-error",
+ error: "mediarecorder",
+ why: String(ev?.error || "unknown"),
+ });
+ };
+
+ recorder.current.onstop = async () => {
+ if (token !== recorderToken) return;
+ try {
+ recorder.current.requestData();
+ } catch {}
+
+ regionRef.current = false;
+ recordingRef.current = false;
+
+ if (isRestarting.current) return;
+
+ await waitForDrain();
+
+ if (!sentLast.current) {
+ sentLast.current = true;
+ isFinished.current = true;
+ chrome.runtime.sendMessage({ type: "video-ready" });
+ isFinishing.current = false;
+ window.location.reload();
+ }
+ };
+
+ recorder.current.ondataavailable = async (e) => {
+ if (token !== recorderToken) return;
+ if (!e || !e.data || !e.data.size) {
+ if (recorder.current && recorder.current.state === "inactive") {
+ chrome.storage.local.set({
+ recording: false,
+ restarting: false,
+ tabRecordedID: null,
+ });
+ chrome.runtime.sendMessage({ type: "stop-recording-tab" });
+ }
+ return;
+ }
+
+ if (lowStorageAbort.current) {
+ return;
+ }
+
+ recdbgChunkCount += 1;
+ recdbgTotalBytes += e.data.size || 0;
+ const elapsedSec = Math.max(
+ 0.001,
+ (Date.now() - mediaRecorderStartAt) / 1000,
+ );
+ const derivedMbps = (recdbgTotalBytes * 8) / elapsedSec / 1e6;
+
+ if (recdbgChunkCount <= 3) {
+ debugRecordingEvent(recdbgSessionRef, "chunk", {
+ index: recdbgChunkCount,
+ size: e.data.size,
+ timecode: e.timecode ?? 0,
+ });
+ }
+
+ if (recdbgChunkCount % 3 === 0) {
+ debugRecordingEvent(recdbgSessionRef, "bitrate", {
+ codec: getCodecLabel(mimeType),
+ elapsedSec,
+ derivedMbps,
+ bytes: recdbgTotalBytes,
+ targetVideoBps: videoBitsPerSecond,
+ });
+ }
+
+ if (
+ !codecFallbackTriggered &&
+ (recdbgChunkCount >= 3 || elapsedSec >= 3)
+ ) {
+ if (derivedMbps < 5) {
+ codecFallbackTriggered = true;
+ debugRecordingEvent(recdbgSessionRef, "codec-fallback", {
+ from: getCodecLabel(mimeType),
+ to: "vp8",
+ derivedMbps,
+ });
+ recorderToken += 1;
+ await resetChunkState();
+ try {
+ recorder.current.stop();
+ } catch {}
+ await startMediaRecorderWithCodec("vp8");
+ return;
+ }
+ }
+
+ if (!hasChunks.current) {
+ hasChunks.current = true;
+ lastTimecode.current = e.timecode ?? 0;
+ lastSize.current = e.data.size;
+ }
+
+ pending.current.push(e);
+ pendingBytes.current += e.data.size;
+
+ if (pendingBytes.current > MAX_PENDING_BYTES) {
+ try {
+ recorder.current.pause();
+ await drainQueue();
+ recorder.current.resume();
+ } catch {}
+ }
+
+ void drainQueue();
+ };
+
+ recorder.current.addEventListener("stop", () => {
+ if (token !== recorderToken) return;
+ debugRecordingEvent(recdbgSessionRef, "recorder-stop", {
+ count: recdbgChunkCount,
+ totalBytes: recdbgTotalBytes,
+ encoder: "mediarecorder",
+ codec: getCodecLabel(mimeType),
+ });
+ });
+
+ return true;
+ };
+
+ if (shouldUseFast) {
+ const ok = await startWebCodecsRecorder();
+ if (!ok) {
+ useWebCodecs.current = false;
+ await chrome.storage.local.set({ fastRecorderInUse: false });
+ await startMediaRecorderWithCodec("vp9");
+ }
+ } else {
+ useWebCodecs.current = false;
+ await chrome.storage.local.set({ fastRecorderInUse: false });
+ await startMediaRecorderWithCodec("vp9");
+ }
} catch (err) {
chrome.runtime.sendMessage({
type: "recording-error",
error: "stream-error",
- why: JSON.stringify(err),
+ why: String(err),
});
// Reload this iframe
@@ -511,6 +1092,7 @@ const Recorder = () => {
async function stopRecording() {
isFinishing.current = true;
regionRef.current = false;
+ await updateFreeFinalizeStatus("stopping", 0);
await setRecordingTimingState({
recording: false,
paused: false,
@@ -521,20 +1103,35 @@ const Recorder = () => {
pausedStateRef.current = false;
if (recorder.current) {
- try {
- recorder.current.requestData();
- } catch {}
+ if (
+ useWebCodecs.current &&
+ recorder.current instanceof WebCodecsRecorder
+ ) {
+ try {
+ await updateFreeFinalizeStatus("finalizing", 20);
+ await recorder.current.stop();
+ } catch {}
+ await waitForDrain();
+ recorder.current = null;
+ } else {
+ try {
+ recorder.current.requestData();
+ } catch {}
- try {
- if (recorder.current.state !== "inactive") {
- recorder.current.stop();
- }
- } catch {}
+ try {
+ if (recorder.current.state !== "inactive") {
+ recorder.current.stop();
+ }
+ } catch {}
- await waitForDrain();
- recorder.current = null;
+ await waitForDrain();
+ recorder.current = null;
+ await updateFreeFinalizeStatus("chunks_ready", 100);
+ }
}
+ useWebCodecs.current = false;
+
if (liveStream.current !== null) {
liveStream.current.getTracks().forEach(function (track) {
track.stop();
@@ -559,6 +1156,7 @@ const Recorder = () => {
const dismissRecording = async () => {
regionRef.current = false;
+ useWebCodecs.current = false;
await setRecordingTimingState({
recording: false,
paused: false,
@@ -600,6 +1198,7 @@ const Recorder = () => {
isRestarting.current = true;
isDismissing.current = false;
pausedStateRef.current = false;
+ useWebCodecs.current = false;
if (recorder.current) {
recorder.current.stop();
}
@@ -625,10 +1224,7 @@ const Recorder = () => {
};
const { defaultAudioInputLabel, audioinput } =
- await chrome.storage.local.get([
- "defaultAudioInputLabel",
- "audioinput",
- ]);
+ await chrome.storage.local.get(["defaultAudioInputLabel", "audioinput"]);
const desiredLabel =
defaultAudioInputLabel ||
audioinput?.find((device) => device.deviceId === id)?.label ||
@@ -756,7 +1352,7 @@ const Recorder = () => {
) {
audioInputGain.current = aCtx.current.createGain();
audioInputSource.current = aCtx.current.createMediaStreamSource(
- helperAudioStream.current
+ helperAudioStream.current,
);
audioInputSource.current
.connect(audioInputGain.current)
@@ -773,7 +1369,7 @@ const Recorder = () => {
if (helperVideoStream.current.getAudioTracks().length > 0) {
audioOutputGain.current = aCtx.current.createGain();
audioOutputSource.current = aCtx.current.createMediaStreamSource(
- helperVideoStream.current
+ helperVideoStream.current,
);
audioOutputSource.current
.connect(audioOutputGain.current)
@@ -784,7 +1380,7 @@ const Recorder = () => {
// Add the tracks to the stream
liveStream.current.addTrack(
- helperVideoStream.current.getVideoTracks()[0]
+ helperVideoStream.current.getVideoTracks()[0],
);
if (
@@ -793,7 +1389,7 @@ const Recorder = () => {
helperVideoStream.current.getAudioTracks().length > 0
) {
liveStream.current.addTrack(
- destination.current.stream.getAudioTracks()[0]
+ destination.current.stream.getAudioTracks()[0],
);
}
@@ -816,7 +1412,7 @@ const Recorder = () => {
chrome.runtime.sendMessage({
type: "recording-error",
error: "cancel-modal",
- why: JSON.stringify(err),
+ why: String(err),
});
// Reload this iframe
@@ -829,7 +1425,7 @@ const Recorder = () => {
chrome.runtime.sendMessage({
type: "recording-error",
error: "cancel-modal",
- why: JSON.stringify(err),
+ why: String(err),
});
// Reload this iframe
@@ -925,7 +1521,7 @@ const Recorder = () => {
} catch (err) {
console.warn(
"[Region Recorder] Failed to update resume timing state",
- err
+ err,
);
}
})();
@@ -933,7 +1529,7 @@ const Recorder = () => {
dismissRecording();
}
},
- [regionRef.current, isFinishing.current, recorder.current]
+ [regionRef.current, isFinishing.current, recorder.current],
);
useEffect(() => {
diff --git a/src/pages/Sandbox/Sandbox.jsx b/src/pages/Sandbox/Sandbox.jsx
index 42cc895..a0bb1f3 100644
--- a/src/pages/Sandbox/Sandbox.jsx
+++ b/src/pages/Sandbox/Sandbox.jsx
@@ -1,7 +1,7 @@
import "./styles/edit/_VideoPlayer.scss";
import "./styles/global/_app.scss";
-import React, { useState, useEffect, useRef, useContext } from "react";
+import React, { useEffect, useRef, useContext } from "react";
// Layout
import Editor from "./layout/editor/Editor";
import Player from "./layout/player/Player";
@@ -142,7 +142,9 @@ const Sandbox = () => {
<div className="title">
{chrome.i18n.getMessage("sandboxProgressTitle") +
" " +
- progress.current}
+ (contentState.processingProgress > 0
+ ? `(${Math.round(contentState.processingProgress)}%)`
+ : progress.current)}
</div>
<div className="subtitle">
{chrome.i18n.getMessage("sandboxProgressDescription")}
diff --git a/src/pages/Sandbox/components/player/VideoPlayer.jsx b/src/pages/Sandbox/components/player/VideoPlayer.jsx
index f2e3083..e8b75be 100644
--- a/src/pages/Sandbox/components/player/VideoPlayer.jsx
+++ b/src/pages/Sandbox/components/player/VideoPlayer.jsx
@@ -19,6 +19,15 @@ const VideoPlayer = (props) => {
contentStateRef.current = contentState;
}, [contentState]);
+ const getProcessingBannerText = () => {
+ const base = chrome.i18n.getMessage("processingBannerEditor");
+ const pct = Math.round(contentStateRef.current.processingProgress || 0);
+ if (pct > 0 && pct < 100) {
+ return `${base} (${pct}%)`;
+ }
+ return base;
+ };
+
useEffect(() => {
if (
playerRef.current &&
@@ -140,7 +149,7 @@ const VideoPlayer = (props) => {
"<img src='" +
chrome.runtime.getURL("assets/editor/icons/alert-white.svg") +
"'/> <span>" +
- chrome.i18n.getMessage("processingBannerEditor") +
+ getProcessingBannerText() +
"</span>";
document.querySelector(".plyr--video").appendChild(bannerRef.current);
@@ -162,6 +171,16 @@ const VideoPlayer = (props) => {
};
}, []);
+ useEffect(() => {
+ if (!bannerRef.current) return;
+ bannerRef.current.innerHTML =
+ "<img src='" +
+ chrome.runtime.getURL("assets/editor/icons/alert-white.svg") +
+ "'/> <span>" +
+ getProcessingBannerText() +
+ "</span>";
+ }, [contentState.processingProgress]);
+
return (
<div className="videoPlayer">
<div className="playerWrap">
diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsx
index bbd21e3..e34e2af 100644
--- a/src/pages/Sandbox/context/ContentState.jsx
+++ b/src/pages/Sandbox/context/ContentState.jsx
@@ -16,6 +16,10 @@ import {
getHostnameFromUrl,
sanitizeFilenameBase,
} from "../../utils/filenameHelpers";
+import {
+ debugRecordingEventWithSession,
+ isRecordingDebugEnabled,
+} from "../../utils/recordingDebug";
localforage.config({
driver: localforage.INDEXEDDB,
@@ -30,10 +34,58 @@ const chunksStore = localforage.createInstance({
export const ContentStateContext = createContext();
+const DEBUG_RECORDER =
+ typeof window !== "undefined" ? !!window.SCREENITY_DEBUG_RECORDER : false;
+
const ContentState = (props) => {
const videoChunks = useRef([]);
const makeVideoCheck = useRef(false);
const chunkCount = useRef(0);
+ const recdbgSessionRef = useRef(null);
+ const tabIdRef = useRef(null);
+
+ useEffect(() => {
+ if (!DEBUG_RECORDER && !isRecordingDebugEnabled()) return;
+ chrome.storage.local.get(
+ ["recordingDebugSessionId", "recordingDebugStartMs"],
+ (res) => {
+ if (!res?.recordingDebugSessionId) return;
+ recdbgSessionRef.current = {
+ sessionId: res.recordingDebugSessionId,
+ startTimeMs: res.recordingDebugStartMs || null,
+ startPerfMs: null,
+ };
+ },
+ );
+ }, []);
+
+ useEffect(() => {
+ try {
+ chrome.tabs.getCurrent((tab) => {
+ tabIdRef.current = tab?.id || null;
+ });
+ } catch {}
+ }, []);
+
+ useEffect(() => {
+ if (!DEBUG_RECORDER && !isRecordingDebugEnabled()) return;
+ window.__screenityExportRecordingDebug = async () => {
+ const { recordingDebugSessionId } = await chrome.storage.local.get([
+ "recordingDebugSessionId",
+ ]);
+ if (!recordingDebugSessionId) {
+ // eslint-disable-next-line no-console
+ console.warn("[Sandbox] No recording debug session id found.");
+ return;
+ }
+ chrome.runtime.sendMessage({
+ type: "export-recording-debug",
+ sessionId: recordingDebugSessionId,
+ });
+ };
+ window.__screenityPingRecdbg = () =>
+ chrome.runtime.sendMessage({ type: "recdbg-ping" });
+ }, []);
const defaultState = {
time: 0,
@@ -98,6 +150,11 @@ const ContentState = (props) => {
const [contentState, _setContentState] = useState(defaultState);
const contentStateRef = useRef(contentState);
+ const launchModeRef = useRef("normal");
+ const launchRecordingIdRef = useRef(null);
+ const pseudoProgressTimerRef = useRef(null);
+ const pseudoProgressStartRef = useRef(null);
+ const pseudoProgressStartAtRef = useRef(null);
const setContentState = useCallback((updater) => {
_setContentState((prev) => {
@@ -107,6 +164,168 @@ const ContentState = (props) => {
});
}, []);
+ useEffect(() => {
+ try {
+ const params = new URLSearchParams(window.location.search);
+ launchModeRef.current = params.get("mode") || "normal";
+ launchRecordingIdRef.current = params.get("recordingId") || null;
+ } catch {}
+ }, []);
+
+ useEffect(() => {
+ if (launchModeRef.current !== "postStop") return;
+ if (contentState.ready) {
+ if (pseudoProgressTimerRef.current) {
+ clearInterval(pseudoProgressTimerRef.current);
+ pseudoProgressTimerRef.current = null;
+ }
+ return;
+ }
+
+ if (pseudoProgressTimerRef.current || pseudoProgressStartRef.current)
+ return;
+ pseudoProgressStartRef.current = setTimeout(() => {
+ pseudoProgressStartRef.current = null;
+ if (contentStateRef.current?.ready) return;
+ if ((contentStateRef.current?.processingProgress || 0) > 0) return;
+ pseudoProgressStartAtRef.current = Date.now();
+ pseudoProgressTimerRef.current = setInterval(() => {
+ setContentState((prev) => {
+ if (prev.ready) return prev;
+ const current = Number(prev.processingProgress || 0);
+ const elapsedMs = Math.max(
+ 0,
+ Date.now() - (pseudoProgressStartAtRef.current || Date.now()),
+ );
+ const target = Math.min(90, Math.round((elapsedMs / 6000) * 90));
+ const next = Math.max(current, target);
+ if (next <= current) return prev;
+ return { ...prev, processingProgress: next };
+ });
+ }, 200);
+ }, 800);
+
+ return () => {
+ if (pseudoProgressStartRef.current) {
+ clearTimeout(pseudoProgressStartRef.current);
+ pseudoProgressStartRef.current = null;
+ }
+ pseudoProgressStartAtRef.current = null;
+ if (pseudoProgressTimerRef.current) {
+ clearInterval(pseudoProgressTimerRef.current);
+ pseudoProgressTimerRef.current = null;
+ }
+ };
+ }, [contentState.ready]);
+
+ const waitForFinalizeReady = async (recordingId) => {
+ if (!recordingId) return { ok: true };
+ const key = `freeFinalizeStatus:${recordingId}`;
+ const timeoutMs = 60_000;
+ const pollMs = 200;
+ const start = Date.now();
+ debugRecordingEventWithSession(recdbgSessionRef.current, "poststop-wait", {
+ recordingId,
+ key,
+ timeoutMs,
+ pollMs,
+ });
+
+ const getStatus = async () => {
+ const res = await chrome.storage.local.get([key]);
+ return res[key] || null;
+ };
+
+ return new Promise(async (resolve) => {
+ let done = false;
+ const cleanup = () => {
+ done = true;
+ chrome.storage.onChanged.removeListener(onChanged);
+ clearInterval(pollTimer);
+ };
+
+ const handleStatus = (status) => {
+ if (!status || done) return;
+ const rawPct =
+ typeof status.percent === "number" ? status.percent : 0;
+ const prePct = Math.min(90, Math.max(0, Math.round(rawPct * 0.9)));
+ debugRecordingEventWithSession(
+ recdbgSessionRef.current,
+ "poststop-status",
+ {
+ recordingId,
+ stage: status.stage,
+ percent: status.percent,
+ updatedAt: status.updatedAt,
+ },
+ );
+ setContentState((prev) => ({
+ ...prev,
+ isFfmpegRunning: true,
+ processingProgress: Math.max(prev.processingProgress || 0, prePct),
+ }));
+ if (status.stage === "chunks_ready" || status.stage === "ready") {
+ cleanup();
+ debugRecordingEventWithSession(
+ recdbgSessionRef.current,
+ "poststop-ready",
+ { recordingId, stage: status.stage },
+ );
+ resolve({ ok: true });
+ } else if (status.stage === "failed") {
+ cleanup();
+ debugRecordingEventWithSession(
+ recdbgSessionRef.current,
+ "poststop-failed",
+ { recordingId, error: status.error || "failed" },
+ );
+ resolve({ ok: false, error: status.error || "failed" });
+ }
+ };
+
+ const onChanged = (changes, area) => {
+ if (area !== "local") return;
+ if (!changes[key]) return;
+ handleStatus(changes[key].newValue);
+ };
+
+ chrome.storage.onChanged.addListener(onChanged);
+
+ const pollTimer = setInterval(async () => {
+ if (done) return;
+ if (Date.now() - start > timeoutMs) {
+ cleanup();
+ debugRecordingEventWithSession(
+ recdbgSessionRef.current,
+ "poststop-timeout",
+ { recordingId, timeoutMs },
+ );
+ resolve({ ok: false, error: "timeout" });
+ return;
+ }
+ const status = await getStatus();
+ handleStatus(status);
+ }, pollMs);
+
+ const initial = await getStatus();
+ handleStatus(initial);
+ });
+ };
+
+ useEffect(() => {
+ if (launchModeRef.current !== "postStop") return;
+ if (!contentState.chunkCount) return;
+ const ratio =
+ contentState.chunkCount > 0
+ ? contentState.chunkIndex / contentState.chunkCount
+ : 0;
+ const pct = Math.min(100, Math.max(20, Math.round(ratio * 80 + 20)));
+ setContentState((prev) => ({
+ ...prev,
+ processingProgress: pct,
+ }));
+ }, [contentState.chunkIndex, contentState.chunkCount]);
+
const buildBlobFromChunks = async () => {
const items = [];
@@ -119,12 +338,21 @@ const ContentState = (props) => {
c.chunk instanceof Blob ? c.chunk : new Blob([c.chunk]),
);
+ if (!parts.length) {
+ debug("No chunks found in IndexedDB");
+ debugRecordingEventWithSession(recdbgSessionRef.current, "blob-empty", {
+ chunkCount: 0,
+ });
+ return null;
+ }
+
const first = parts[0];
const inferredType = first?.type || "video/webm";
const blob = new Blob(parts, { type: inferredType });
reconstructVideo(blob);
+ return blob;
};
// useEffect(() => {
@@ -622,6 +850,13 @@ const ContentState = (props) => {
const onChromeMessage = useCallback(
(request, sender, sendResponse) => {
const message = request;
+ if (
+ message?._targetTabId &&
+ tabIdRef.current &&
+ message._targetTabId !== tabIdRef.current
+ ) {
+ return false;
+ }
if (message.type === "chunk-count") {
setContentState((prevState) => ({
...prevState,
@@ -653,7 +888,12 @@ const ContentState = (props) => {
}));
buildBlobFromChunks()
- .then(() => {
+ .then((blob) => {
+ if (!blob) {
+ chrome.runtime.sendMessage({ type: "send-chunks-to-sandbox" });
+ sendResponse({ status: "deferred" });
+ return;
+ }
sendResponse({ status: "ok" });
})
.catch((error) => {
@@ -665,12 +905,48 @@ const ContentState = (props) => {
setContentState((prevContentState) => ({
...prevContentState,
noffmpeg: false,
- isFfmpegRunning: false,
+ isFfmpegRunning: true,
editLimit: 0,
}));
+ const shouldGate =
+ launchModeRef.current === "postStop" &&
+ Boolean(launchRecordingIdRef.current);
+ if (shouldGate) {
+ waitForFinalizeReady(launchRecordingIdRef.current).then((result) => {
+ if (!result.ok) {
+ setContentState((prev) => ({
+ ...prev,
+ isFfmpegRunning: false,
+ noffmpeg: true,
+ ffmpegLoaded: true,
+ processingProgress: 0,
+ }));
+ sendResponse({ status: "error", error: result.error });
+ return;
+ }
+ buildBlobFromChunks()
+ .then((blob) => {
+ if (!blob) {
+ chrome.runtime.sendMessage({ type: "send-chunks-to-sandbox" });
+ sendResponse({ status: "deferred" });
+ return;
+ }
+ sendResponse({ status: "ok" });
+ })
+ .catch((error) =>
+ sendResponse({ status: "error", error: error.message })
+ );
+ });
+ return true;
+ }
buildBlobFromChunks()
- .then(() => {
+ .then((blob) => {
+ if (!blob) {
+ chrome.runtime.sendMessage({ type: "send-chunks-to-sandbox" });
+ sendResponse({ status: "deferred" });
+ return;
+ }
sendResponse({ status: "ok" });
})
.catch((error) => {
@@ -683,12 +959,48 @@ const ContentState = (props) => {
...prevContentState,
fallback: true,
noffmpeg: false,
- isFfmpegRunning: false,
+ isFfmpegRunning: true,
editLimit: 3600,
}));
+ const shouldGate =
+ launchModeRef.current === "postStop" &&
+ Boolean(launchRecordingIdRef.current);
+ if (shouldGate) {
+ waitForFinalizeReady(launchRecordingIdRef.current).then((result) => {
+ if (!result.ok) {
+ setContentState((prev) => ({
+ ...prev,
+ isFfmpegRunning: false,
+ noffmpeg: true,
+ ffmpegLoaded: true,
+ processingProgress: 0,
+ }));
+ sendResponse({ status: "error", error: result.error });
+ return;
+ }
+ buildBlobFromChunks()
+ .then((blob) => {
+ if (!blob) {
+ chrome.runtime.sendMessage({ type: "send-chunks-to-sandbox" });
+ sendResponse({ status: "deferred" });
+ return;
+ }
+ sendResponse({ status: "ok" });
+ })
+ .catch((error) =>
+ sendResponse({ status: "error", error: error.message })
+ );
+ });
+ return true;
+ }
buildBlobFromChunks()
- .then(() => {
+ .then((blob) => {
+ if (!blob) {
+ chrome.runtime.sendMessage({ type: "send-chunks-to-sandbox" });
+ sendResponse({ status: "deferred" });
+ return;
+ }
sendResponse({ status: "ok" });
})
.catch((error) => {
@@ -701,9 +1013,33 @@ const ContentState = (props) => {
...prevContentState,
fallback: true,
noffmpeg: true, // No FFmpeg
- isFfmpegRunning: false,
+ isFfmpegRunning: true,
editLimit: 0, // No editing allowed
}));
+ const shouldGate =
+ launchModeRef.current === "postStop" &&
+ Boolean(launchRecordingIdRef.current);
+ if (shouldGate) {
+ waitForFinalizeReady(launchRecordingIdRef.current).then((result) => {
+ if (!result.ok) {
+ setContentState((prev) => ({
+ ...prev,
+ isFfmpegRunning: false,
+ noffmpeg: true,
+ ffmpegLoaded: true,
+ processingProgress: 0,
+ }));
+ sendResponse({ status: "error", error: result.error });
+ return;
+ }
+ buildBlobFromChunks()
+ .then(() => sendResponse({ status: "ok" }))
+ .catch((error) =>
+ sendResponse({ status: "error", error: error.message })
+ );
+ });
+ return true;
+ }
buildBlobFromChunks()
.then(() => {
diff --git a/src/pages/Sandbox/layout/player/RightPanel.js b/src/pages/Sandbox/layout/player/RightPanel.js
index b39325c..a9e4a4a 100644
--- a/src/pages/Sandbox/layout/player/RightPanel.js
+++ b/src/pages/Sandbox/layout/player/RightPanel.js
@@ -30,6 +30,15 @@ const RightPanel = () => {
contentStateRef.current = contentState;
}, [contentState]);
+ const getPreparingLabel = () => {
+ const base = chrome.i18n.getMessage("preparingLabel");
+ const pct = Math.round(contentState.processingProgress || 0);
+ if (!contentState.mp4ready && pct > 0) {
+ return `${base} (${pct}%)`;
+ }
+ return base;
+ };
+
const saveToDrive = () => {
//if (contentState.noffmpeg) return;
setContentState((prevContentState) => ({
@@ -423,7 +432,7 @@ const RightPanel = () => {
? chrome.i18n.getMessage("notAvailableLabel")
: contentState.mp4ready
? chrome.i18n.getMessage("editButtonDescription")
- : chrome.i18n.getMessage("preparingLabel")}
+ : getPreparingLabel()}
</div>
</div>
<div className={styles.buttonRight}>
@@ -458,7 +467,7 @@ const RightPanel = () => {
? chrome.i18n.getMessage("notAvailableLabel")
: contentState.mp4ready
? chrome.i18n.getMessage("cropButtonDescription")
- : chrome.i18n.getMessage("preparingLabel")}
+ : getPreparingLabel()}
</div>
</div>
<div className={styles.buttonRight}>
@@ -493,7 +502,7 @@ const RightPanel = () => {
? chrome.i18n.getMessage("notAvailableLabel")
: contentState.mp4ready
? chrome.i18n.getMessage("addAudioButtonDescription")
- : chrome.i18n.getMessage("preparingLabel")}
+ : getPreparingLabel()}
</div>
</div>
<div className={styles.buttonRight}>
@@ -611,7 +620,7 @@ const RightPanel = () => {
? chrome.i18n.getMessage("notAvailableLabel")
: contentState.mp4ready && !contentState.isFfmpegRunning
? chrome.i18n.getMessage("downloadMP4ButtonDescription")
- : chrome.i18n.getMessage("preparingLabel")}
+ : getPreparingLabel()}
</div>
</div>
<div className={styles.buttonRight}>
@@ -639,7 +648,7 @@ const RightPanel = () => {
? chrome.i18n.getMessage(
"downloadWEBMButtonDescription"
)
- : chrome.i18n.getMessage("preparingLabel")}
+ : getPreparingLabel()}
</div>
</div>
<div className={styles.buttonRight}>
@@ -680,7 +689,7 @@ const RightPanel = () => {
? chrome.i18n.getMessage("notAvailableLabel")
: contentState.mp4ready
? chrome.i18n.getMessage("downloadGIFButtonDescription")
- : chrome.i18n.getMessage("preparingLabel")}
+ : getPreparingLabel()}
</div>
</div>
<div className={styles.buttonRight}>