Skip to content

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

Improve MP4 downloads with OPFS remux and add site permissions modal

Alyssa X1809accb38df
diff --git a/src/_locales/ca/messages.json b/src/_locales/ca/messages.json
index bad4b06..b249b4d 100644
--- a/src/_locales/ca/messages.json
+++ b/src/_locales/ca/messages.json
@@ -55,6 +55,14 @@
"message": "Descarta",
"description": "Botó de descarta del modal d'avís de permisos de càmera / micròfon"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Aquest lloc no permet accedir a la càmera ni al micròfon",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Sembla que la configuració de seguretat d'aquest lloc web impedeix que les extensions del navegador utilitzin la càmera o el micròfon en aquesta pàgina. Per gravar amb ells, inicia una gravació des d'una altra pestanya i torna aquí un cop comenci.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Permet l'accés a la càmera",
"description": "Botó per permetre l'accés a la càmera"
diff --git a/src/_locales/de/messages.json b/src/_locales/de/messages.json
index 90d8bf4..2904e94 100644
--- a/src/_locales/de/messages.json
+++ b/src/_locales/de/messages.json
@@ -55,6 +55,14 @@
"message": "Verwerfen",
"description": "Schaltfläche 'Verwerfen' im Modal für Kamera- / Mikrofonberechtigungen"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Diese Seite erlaubt keinen Zugriff auf Kamera oder Mikrofon",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Die Sicherheitseinstellungen dieser Website verhindern, dass Browser-Erweiterungen auf dieser Seite deine Kamera oder dein Mikrofon verwenden. Um mit ihnen aufzunehmen, starte die Aufnahme in einem anderen Tab und wechsle zurück hierher, sobald sie begonnen hat.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Kamerazugriff zulassen",
"description": "Schaltfläche 'Kamerazugriff zulassen'"
diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.json
index e6adecf..4c0a439 100644
--- a/src/_locales/en/messages.json
+++ b/src/_locales/en/messages.json
@@ -55,6 +55,14 @@
"message": "Dismiss",
"description": "Camera / microphone permissions warning modal dismiss button"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "This site doesn't allow camera or microphone access",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Looks like this website's security settings prevent browser extensions from using your camera or microphone on this page. To record with them, start a recording from another tab and switch back here once it begins.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Allow camera access",
"description": "Allow camera access button"
diff --git a/src/_locales/es/messages.json b/src/_locales/es/messages.json
index 6195486..127367b 100644
--- a/src/_locales/es/messages.json
+++ b/src/_locales/es/messages.json
@@ -55,6 +55,14 @@
"message": "Descartar",
"description": "Botón de descartar del modal de advertencia de permisos de cámara/micrófono"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Este sitio no permite el acceso a la cámara o al micrófono",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Parece que la configuración de seguridad de este sitio web impide que las extensiones del navegador utilicen tu cámara o micrófono en esta página. Para grabar con ellos, inicia una grabación en otra pestaña y vuelve aquí una vez que comience.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Permitir acceso a la cámara",
"description": "Botón de permitir acceso a la cámara"
diff --git a/src/_locales/fr/messages.json b/src/_locales/fr/messages.json
index f1aef9c..6fa40bb 100644
--- a/src/_locales/fr/messages.json
+++ b/src/_locales/fr/messages.json
@@ -55,6 +55,14 @@
"message": "Rejeter",
"description": "Bouton de rejet de la fenêtre modale d'avertissement des autorisations de la caméra/du microphone"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Ce site ne permet pas l'accès à la caméra ou au microphone",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Il semble que les paramètres de sécurité de ce site empêchent les extensions de navigateur d'utiliser votre caméra ou votre microphone sur cette page. Pour enregistrer avec eux, démarrez un enregistrement depuis un autre onglet et revenez ici une fois qu'il a commencé.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Autoriser l'accès à la caméra",
"description": "Bouton d'autorisation d'accès à la caméra"
diff --git a/src/_locales/hi/messages.json b/src/_locales/hi/messages.json
index aeb2386..862b0d1 100644
--- a/src/_locales/hi/messages.json
+++ b/src/_locales/hi/messages.json
@@ -55,6 +55,14 @@
"message": "रद्द करें",
"description": "कैमरा / माइक्रोफ़ोन अनुमतियों की चेतावनी मॉडल निरस्त करें बटन"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "यह साइट कैमरा या माइक्रोफोन एक्सेस की अनुमति नहीं देती",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "ऐसा लगता है कि इस वेबसाइट की सुरक्षा सेटिंग्स ब्राउज़र एक्सटेंशन को इस पेज पर आपके कैमरा या माइक्रोफोन का उपयोग करने से रोकती हैं। इनके साथ रिकॉर्ड करने के लिए, किसी अन्य टैब से रिकॉर्डिंग शुरू करें और रिकॉर्डिंग शुरू होने के बाद यहाँ वापस आएँ।",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "कैमरा अनुमति दें",
"description": "कैमरा अनुमति दें बटन"
diff --git a/src/_locales/id/messages.json b/src/_locales/id/messages.json
index 58f304f..92cf761 100644
--- a/src/_locales/id/messages.json
+++ b/src/_locales/id/messages.json
@@ -55,6 +55,14 @@
"message": "Abaikan",
"description": "Tombol abaikan modal peringatan izin kamera/mikrofon"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Situs ini tidak mengizinkan akses kamera atau mikrofon",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Tampaknya pengaturan keamanan situs web ini mencegah ekstensi peramban menggunakan kamera atau mikrofon Anda di halaman ini. Untuk merekam dengan keduanya, mulai rekaman dari tab lain dan beralih kembali ke sini setelah rekaman dimulai.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Izinkan akses kamera",
"description": "Tombol izinkan akses kamera"
diff --git a/src/_locales/it/messages.json b/src/_locales/it/messages.json
index ee1f16c..717c47f 100644
--- a/src/_locales/it/messages.json
+++ b/src/_locales/it/messages.json
@@ -55,6 +55,14 @@
"message": "Annulla",
"description": "Pulsante di annullamento del modulo di avviso dei permessi per fotocamera/microfono"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Questo sito non consente l'accesso alla fotocamera o al microfono",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Sembra che le impostazioni di sicurezza di questo sito impediscano alle estensioni del browser di utilizzare la fotocamera o il microfono in questa pagina. Per registrare con essi, avvia una registrazione da un'altra scheda e torna qui una volta iniziata.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Consenti accesso alla fotocamera",
"description": "Pulsante per consentire l'accesso alla fotocamera"
diff --git a/src/_locales/ko/messages.json b/src/_locales/ko/messages.json
index 7099784..1b4e4c0 100644
--- a/src/_locales/ko/messages.json
+++ b/src/_locales/ko/messages.json
@@ -55,6 +55,14 @@
"message": "닫기",
"description": "Camera / microphone permissions warning modal dismiss button"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "이 사이트에서는 카메라 또는 마이크 접근이 허용되지 않아요",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "이 웹사이트의 보안 설정이 브라우저 확장 프로그램에서 이 페이지의 카메라나 마이크를 사용하지 못하게 차단하고 있어요. 카메라와 마이크를 사용해 녹화하려면, 다른 탭에서 녹화를 시작한 뒤 녹화가 시작되면 이 탭으로 돌아오세요.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "카메라 액세스 허용",
"description": "Allow camera access button"
diff --git a/src/_locales/pl/messages.json b/src/_locales/pl/messages.json
index b0304ec..3517afe 100644
--- a/src/_locales/pl/messages.json
+++ b/src/_locales/pl/messages.json
@@ -55,6 +55,14 @@
"message": "Odrzuć",
"description": "Przycisk odrzucenia w modalnym okienku ostrzeżenia o uprawnieniach kamery / mikrofonu"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Ta strona nie zezwala na dostęp do kamery ani mikrofonu",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Wygląda na to, że ustawienia bezpieczeństwa tej witryny uniemożliwiają rozszerzeniom przeglądarki korzystanie z kamery i mikrofonu na tej stronie. Aby nagrywać z ich użyciem, rozpocznij nagrywanie z innej karty i wróć tutaj po jego rozpoczęciu.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Zezwól na dostęp do kamery",
"description": "Przycisk zezwalający na dostęp do kamery"
diff --git a/src/_locales/pt_BR/messages.json b/src/_locales/pt_BR/messages.json
index 35c4ad9..328042a 100644
--- a/src/_locales/pt_BR/messages.json
+++ b/src/_locales/pt_BR/messages.json
@@ -55,6 +55,14 @@
"message": "Ignorar",
"description": "Botão de ignorar no modal de aviso de permissões de câmera/microfone"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Este site não permite acesso à câmera ou ao microfone",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Parece que as configurações de segurança deste site impedem que extensões do navegador usem sua câmera ou microfone nesta página. Para gravar com eles, inicie uma gravação em outra aba e volte para cá assim que ela começar.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Permitir acesso à câmera",
"description": "Botão de permitir acesso à câmera"
diff --git a/src/_locales/pt_PT/messages.json b/src/_locales/pt_PT/messages.json
index f47e8fb..b6e52b5 100644
--- a/src/_locales/pt_PT/messages.json
+++ b/src/_locales/pt_PT/messages.json
@@ -55,6 +55,14 @@
"message": "Ignorar",
"description": "Botão de ignorar no modal de aviso de permissões de câmara/microfone"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Este site não permite acesso à câmara ou ao microfone",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Parece que as definições de segurança deste site impedem que extensões do navegador utilizem a tua câmara ou microfone nesta página. Para gravar com eles, inicia uma gravação noutro separador e volta para aqui assim que começar.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Permitir acesso à câmara",
"description": "Botão de permitir acesso à câmara"
diff --git a/src/_locales/ru/messages.json b/src/_locales/ru/messages.json
index 6e8e4e9..ef594a1 100644
--- a/src/_locales/ru/messages.json
+++ b/src/_locales/ru/messages.json
@@ -55,6 +55,14 @@
"message": "Отклонить",
"description": "Кнопка закрытия модального окна предупреждения о разрешениях для камеры / микрофона"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Этот сайт не разрешает доступ к камере или микрофону",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Похоже, настройки безопасности этого сайта не позволяют расширениям браузера использовать камеру или микрофон на этой странице. Чтобы записывать с их использованием, начните запись в другой вкладке и переключитесь сюда после её начала.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Разрешить доступ к камере",
"description": "Кнопка разрешения доступа к камере"
diff --git a/src/_locales/ta/messages.json b/src/_locales/ta/messages.json
index ca2392d..c98fc82 100644
--- a/src/_locales/ta/messages.json
+++ b/src/_locales/ta/messages.json
@@ -55,6 +55,14 @@
"message": "விலகு",
"description": "கேமரா / மைக்ரோஃபோன் அனுமதிகள் எச்சரிக்கை செய்தியின் விளக்கம் விளக்கம்"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "இந்த தளம் கேமரா அல்லது மைக்ரோஃபோன் அணுகலை அனுமதிக்கவில்லை",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "இந்த வலைத்தளத்தின் பாதுகாப்பு அமைப்புகள் உலாவி நீட்டிப்புகள் இந்தப் பக்கத்தில் உங்கள் கேமராவையோ அல்லது மைக்ரோஃபோனையோ பயன்படுத்துவதைத் தடுக்கின்றன. இவற்றுடன் பதிவு செய்ய, மற்றொரு தாவலில் பதிவைத் தொடங்கி, அது தொடங்கியதும் இங்கே திரும்பவும்.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "கேமரா அணுகலை அனுமதிக்கவும்",
"description": "கேமரா அணுகலை அனுமதிக்க பொத்தான்"
diff --git a/src/_locales/tr/messages.json b/src/_locales/tr/messages.json
index 30220eb..c621ea9 100644
--- a/src/_locales/tr/messages.json
+++ b/src/_locales/tr/messages.json
@@ -55,6 +55,14 @@
"message": "Kapat",
"description": "Kamera / mikrofon izinleri uyarı modalı kapatma düğmesi"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Bu site kamera veya mikrofon erişimine izin vermiyor",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Görünüşe göre bu web sitesinin güvenlik ayarları, tarayıcı uzantılarının bu sayfada kameranızı veya mikrofonunuzu kullanmasını engelliyor. Bunlarla kayıt yapmak için başka bir sekmede kayda başlayın ve kayıt başladıktan sonra buraya geri dönün.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Kamera erişimine izin ver",
"description": "Kamera erişimine izin verme düğmesi"
diff --git a/src/_locales/uk/messages.json b/src/_locales/uk/messages.json
index d6eb7d2..04300bf 100644
--- a/src/_locales/uk/messages.json
+++ b/src/_locales/uk/messages.json
@@ -55,6 +55,14 @@
"message": "Відхилити",
"description": "Camera / microphone permissions warning modal dismiss button"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "Цей сайт не дозволяє доступ до камери або мікрофона",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "Схоже, налаштування безпеки цього сайту не дозволяють розширенням браузера використовувати камеру або мікрофон на цій сторінці. Щоб записувати з ними, почніть запис в іншій вкладці та поверніться сюди після її початку.",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "Дозволити доступ до камери",
"description": "Allow camera access button"
diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.json
index 3dbce4d..3b8e066 100644
--- a/src/_locales/zh_CN/messages.json
+++ b/src/_locales/zh_CN/messages.json
@@ -55,6 +55,14 @@
"message": "忽略",
"description": "Camera / microphone permissions warning modal dismiss button"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "此网站不允许访问摄像头或麦克风",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "此网站的安全设置阻止浏览器扩展在此页面上使用您的摄像头或麦克风。如需使用它们录制,请从另一个标签页开始录制,并在录制开始后切换回此处。",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "允许摄像头访问",
"description": "Allow camera access button"
diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.json
index e30febc..2b26222 100644
--- a/src/_locales/zh_TW/messages.json
+++ b/src/_locales/zh_TW/messages.json
@@ -55,6 +55,14 @@
"message": "忽略",
"description": "Camera / microphone permissions warning modal dismiss button"
},
+ "sitePermissionsBlockedTitle": {
+ "message": "此網站不允許存取相機或麥克風",
+ "description": "Modal title shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
+ "sitePermissionsBlockedDescription": {
+ "message": "此網站的安全設定禁止瀏覽器擴充功能在此頁面上使用您的相機或麥克風。若要使用它們錄製,請從另一個分頁開始錄製,並在錄製開始後切換回此處。",
+ "description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"
+ },
"allowCameraAccessButton": {
"message": "允許攝影機存取",
"description": "Allow camera access button"
diff --git a/src/manifest.json b/src/manifest.json
index adbe0fe..6f21076 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.3.8",
+ "version": "4.3.9",
"background": {
"service_worker": "background.bundle.js"
},
diff --git a/src/pages/Background/index.js b/src/pages/Background/index.js
index c01f990..5be91bd 100644
--- a/src/pages/Background/index.js
+++ b/src/pages/Background/index.js
@@ -85,7 +85,7 @@ clearStaleLocks();
// so the sticky flags are no longer warranted and should be cleared once so
// affected users get WebCodecs again on their next recording. The user's
// explicit opt-out (useWebCodecsRecorder === false) is preserved.
-const CURRENT_MIGRATION_VERSION = "4.3.8";
+const CURRENT_MIGRATION_VERSION = "4.3.9";
const runUpgradeMigrations = async () => {
try {
const { screenityMigratedForVersion } = await chrome.storage.local.get([
diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.js
index 1892b12..b407c2b 100644
--- a/src/pages/Background/messaging/handlers.js
+++ b/src/pages/Background/messaging/handlers.js
@@ -22,6 +22,7 @@ import { sendMessageRecord } from "../recording/sendMessageRecord";
import { startRecorderSession } from "../recording/openRecorderTab";
import { acquireStreamForOffscreen } from "../offscreen/acquireStream";
import { registerProxyStorageHandlers } from "../offscreen/proxyStorageHandlers";
+import { ensureRemuxOffscreen } from "../offscreen/ensureRemuxOffscreen";
import { forceProcessing } from "../recording/forceProcessing";
import {
restartActiveTab,
@@ -802,6 +803,42 @@ export const setupHandlers = () => {
await clearRecordingSessionSafe("video-ready");
});
+ // Download-path remux request from the sandbox. Ensures the remux
+ // offscreen document is open, forwards the request, and returns the
+ // response. On any SW-side failure the caller falls back to the
+ // in-sandbox BufferTarget remux.
+ registerMessage("remux-request", async (message) => {
+ if (
+ !message?.requestId ||
+ !message?.inputFileName ||
+ !message?.outputFileName
+ ) {
+ return { ok: false, error: "invalid-remux-request-payload" };
+ }
+ try {
+ await ensureRemuxOffscreen();
+ } catch (err) {
+ return {
+ ok: false,
+ error: String(err?.message || err || "ensure-offscreen-failed"),
+ };
+ }
+ try {
+ const response = await chrome.runtime.sendMessage({
+ type: "remux-start",
+ requestId: message.requestId,
+ inputFileName: message.inputFileName,
+ outputFileName: message.outputFileName,
+ });
+ return response || { ok: false, error: "no-offscreen-response" };
+ } catch (err) {
+ return {
+ ok: false,
+ error: String(err?.message || err || "forward-to-offscreen-failed"),
+ };
+ }
+ });
+
// Fired by Region/Recorder.jsx pagehide — the iframe is being torn down
// because the user navigated away from the recorded tab.
registerMessage("region-iframe-destroyed", async () => {
diff --git a/src/pages/Background/offscreen/ensureRemuxOffscreen.js b/src/pages/Background/offscreen/ensureRemuxOffscreen.js
new file mode 100644
index 0000000..8e48f53
--- /dev/null
+++ b/src/pages/Background/offscreen/ensureRemuxOffscreen.js
@@ -0,0 +1,41 @@
+/*
+ * Creates or reuses the remux offscreen document. Chrome only permits one
+ * offscreen document per extension; if a different offscreen (audio beeps,
+ * cloud-upload resume) is currently open, we close it first.
+ *
+ * The remux offscreen uses the WORKERS reason so it can spawn a dedicated
+ * worker that calls createSyncAccessHandle() on OPFS, which is only
+ * available in Dedicated Workers.
+ */
+const REMUX_OFFSCREEN_URL = "remuxoffscreen.html";
+
+export const ensureRemuxOffscreen = async () => {
+ if (!chrome.offscreen || typeof chrome.offscreen.createDocument !== "function") {
+ throw new Error("offscreen-api-unavailable");
+ }
+
+ const contexts = await chrome.runtime.getContexts({});
+ const existing = contexts.find(
+ (c) => c.contextType === "OFFSCREEN_DOCUMENT",
+ );
+ if (existing) {
+ const alreadyRemux =
+ typeof existing.documentUrl === "string" &&
+ existing.documentUrl.endsWith(REMUX_OFFSCREEN_URL);
+ if (alreadyRemux) return;
+ try {
+ await chrome.offscreen.closeDocument();
+ } catch (err) {
+ // If closeDocument fails we still try to proceed; createDocument
+ // will surface a clearer error if the state is actually bad.
+ console.warn("ensureRemuxOffscreen: closeDocument failed", err);
+ }
+ }
+
+ await chrome.offscreen.createDocument({
+ url: REMUX_OFFSCREEN_URL,
+ reasons: ["WORKERS"],
+ justification:
+ "Re-mux fragmented MP4 recording to standard MP4 using a worker that writes to OPFS via a sync access handle.",
+ });
+};
diff --git a/src/pages/Background/recording/openRecorderTab.js b/src/pages/Background/recording/openRecorderTab.js
index a08b308..2b22bc5 100644
--- a/src/pages/Background/recording/openRecorderTab.js
+++ b/src/pages/Background/recording/openRecorderTab.js
@@ -4,6 +4,7 @@ import { sendMessageRecord } from "./sendMessageRecord.js";
import { closeOffscreenDocument } from "../offscreen/closeOffscreenDocument.js";
import { loginWithWebsite } from "../auth/loginWithWebsite.js";
import { traceStep } from "../../utils/startFlowTrace.js";
+import { handleGetStreamingData } from "./recordingHelpers.js";
const openRecorderTab = async (
activeTab,
@@ -127,6 +128,14 @@ const openRecorderTab = async (
}
: {}),
});
+ // Proactively push streaming-data shortly after "loaded". The tab
+ // also pulls it, but that pull can drop if the SW is still waking
+ // or the tab's listener is not yet mounted. This push plus the
+ // tab-side retry plus the tab's idempotency guard give the handshake
+ // multiple chances to succeed before the start gate times out.
+ setTimeout(() => {
+ handleGetStreamingData().catch(() => {});
+ }, 300);
}
});
};
diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.js
index c5df4b7..7adab74 100644
--- a/src/pages/Background/recording/recordingHelpers.js
+++ b/src/pages/Background/recording/recordingHelpers.js
@@ -185,7 +185,37 @@ export const handleRecordingError = async (request) => {
export const handleGetStreamingData = async () => {
const data = await getStreamingData();
- sendMessageRecord({ type: "streaming-data", data: JSON.stringify(data) });
+ const payload = { type: "streaming-data", data: JSON.stringify(data) };
+
+ // Retry delivery. The recorder tab's message listener may not be mounted
+ // yet when the tab first loads, or the tab may be briefly throttled by
+ // Chrome. A dropped delivery here is what causes REC_START_NO_STREAM_MSG
+ // at the tab's 12s start gate. Tab-side handler is idempotent (first
+ // delivery wins), so extra retries are safe.
+ const backoffMs = [0, 300, 800];
+ for (let attempt = 0; attempt < backoffMs.length; attempt++) {
+ if (backoffMs[attempt] > 0) {
+ await new Promise((r) => setTimeout(r, backoffMs[attempt]));
+ }
+ try {
+ await sendMessageRecord(payload);
+ if (attempt > 0) {
+ diagEvent("sw-streaming-data-send-ok", { attempt });
+ }
+ return;
+ } catch (err) {
+ diagEvent("sw-streaming-data-send-fail", {
+ attempt,
+ err: String(err?.message || err).slice(0, 120),
+ });
+ if (attempt === backoffMs.length - 1) {
+ console.warn(
+ "handleGetStreamingData: all delivery attempts failed",
+ err,
+ );
+ }
+ }
+ }
};
export const videoReady = async () => {
diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsx
index a9054bb..263113b 100644
--- a/src/pages/Content/context/ContentState.jsx
+++ b/src/pages/Content/context/ContentState.jsx
@@ -145,6 +145,30 @@ const ContentState = (props) => {
);
}, []);
+ // Detect Permissions-Policy camera/microphone blocks on the hosting page.
+ // Some sites (banking, enterprise SaaS, admin panels) set headers like
+ // `Permissions-Policy: camera=(), microphone=()` which disable those APIs
+ // for every iframe on the page, including extension iframes. When this is
+ // set, Screenity's camera/mic iframes fail with a NotAllowedError and the
+ // generic "check your permissions" modal is misleading because the browser
+ // setting is fine, the site is the blocker.
+ useEffect(() => {
+ try {
+ const pp = document.permissionsPolicy || document.featurePolicy;
+ if (!pp || typeof pp.allowsFeature !== "function") return;
+ const cameraBlocked = !pp.allowsFeature("camera");
+ const micBlocked = !pp.allowsFeature("microphone");
+ if (cameraBlocked || micBlocked) {
+ setContentState((prev) => ({
+ ...prev,
+ sitePermissionsBlocked: true,
+ }));
+ }
+ } catch {
+ // allowsFeature can throw on detached documents; treat as not blocked.
+ }
+ }, []);
+
useEffect(() => {
const locale = chrome.i18n.getMessage("@@ui_locale");
if (!locale.includes("en")) {
@@ -844,21 +868,37 @@ const ContentState = (props) => {
microphonePermission: false,
}));
if (contentStateRef.current.askForPermissions) {
- contentStateRef.current.openModal(
- chrome.i18n.getMessage("permissionsModalTitle"),
- chrome.i18n.getMessage("permissionsModalDescription"),
- chrome.i18n.getMessage("permissionsModalDismiss"),
- chrome.i18n.getMessage("permissionsModalNoShowAgain"),
- () => {},
- () => {
- noMorePermissions();
- },
- chrome.runtime.getURL("assets/helper/permissions.webp"),
- chrome.i18n.getMessage("learnMoreDot"),
- URL2,
- true,
- false,
- );
+ if (contentStateRef.current.sitePermissionsBlocked) {
+ contentStateRef.current.openModal(
+ chrome.i18n.getMessage("sitePermissionsBlockedTitle"),
+ chrome.i18n.getMessage("sitePermissionsBlockedDescription"),
+ null,
+ chrome.i18n.getMessage("permissionsModalDismiss"),
+ () => {},
+ () => {},
+ null,
+ chrome.i18n.getMessage("learnMoreDot"),
+ "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy",
+ true,
+ false,
+ );
+ } else {
+ contentStateRef.current.openModal(
+ chrome.i18n.getMessage("permissionsModalTitle"),
+ chrome.i18n.getMessage("permissionsModalDescription"),
+ chrome.i18n.getMessage("permissionsModalDismiss"),
+ chrome.i18n.getMessage("permissionsModalNoShowAgain"),
+ () => {},
+ () => {
+ noMorePermissions();
+ },
+ chrome.runtime.getURL("assets/helper/permissions.webp"),
+ chrome.i18n.getMessage("learnMoreDot"),
+ URL2,
+ true,
+ false,
+ );
+ }
}
}
};
@@ -914,6 +954,13 @@ const ContentState = (props) => {
setToolbarMode: null,
openModal: null,
openToast: null,
+ // True when the current page's Permissions-Policy header disallows
+ // camera and/or microphone. Computed once on content-script mount.
+ // Used to show a site-specific modal instead of the generic "check
+ // your permissions" one, which otherwise misleads users into
+ // clicking the camera icon in the address bar (which does nothing
+ // against a site-level Permissions-Policy block).
+ sitePermissionsBlocked: false,
timeWarning: false,
audioInput: [],
videoInput: [],
diff --git a/src/pages/Content/popup/layout/RecordingType.jsx b/src/pages/Content/popup/layout/RecordingType.jsx
index 4c495eb..c22ecbd 100644
--- a/src/pages/Content/popup/layout/RecordingType.jsx
+++ b/src/pages/Content/popup/layout/RecordingType.jsx
@@ -29,6 +29,48 @@ const RecordingType = (props) => {
const buttonRef = useRef(null);
const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0;
+ // Opens the right permissions modal based on why access is blocked.
+ // When the hosting page's Permissions-Policy header disallows camera or
+ // microphone, the usual "click the camera icon in the address bar" advice
+ // is wrong (the site is the blocker, not the browser). Route to a
+ // site-specific modal in that case.
+ const openPermissionsModal = () => {
+ if (typeof contentState.openModal !== "function") return;
+ if (contentState.sitePermissionsBlocked) {
+ contentState.openModal(
+ chrome.i18n.getMessage("sitePermissionsBlockedTitle"),
+ chrome.i18n.getMessage("sitePermissionsBlockedDescription"),
+ null,
+ chrome.i18n.getMessage("permissionsModalDismiss"),
+ () => {},
+ () => {},
+ null,
+ chrome.i18n.getMessage("learnMoreDot"),
+ "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy",
+ true,
+ false
+ );
+ return;
+ }
+ contentState.openModal(
+ chrome.i18n.getMessage("permissionsModalTitle"),
+ chrome.i18n.getMessage("permissionsModalDescription"),
+ chrome.i18n.getMessage("permissionsModalReview"),
+ chrome.i18n.getMessage("permissionsModalDismiss"),
+ () => {
+ chrome.runtime.sendMessage({
+ type: "extension-media-permissions",
+ });
+ },
+ () => {},
+ chrome.runtime.getURL("assets/helper/permissions.webp"),
+ chrome.i18n.getMessage("learnMoreDot"),
+ URL2,
+ true,
+ false
+ );
+ };
+
useEffect(() => {
const locale = chrome.i18n.getMessage("@@ui_locale");
if (!locale.includes("en")) {
@@ -156,27 +198,7 @@ const RecordingType = (props) => {
{!contentState.cameraPermission && (
<button
className="permission-button"
- onClick={() => {
- if (typeof contentState.openModal === "function") {
- contentState.openModal(
- chrome.i18n.getMessage("permissionsModalTitle"),
- chrome.i18n.getMessage("permissionsModalDescription"),
- chrome.i18n.getMessage("permissionsModalReview"),
- chrome.i18n.getMessage("permissionsModalDismiss"),
- () => {
- chrome.runtime.sendMessage({
- type: "extension-media-permissions",
- });
- },
- () => {},
- chrome.runtime.getURL("assets/helper/permissions.webp"),
- chrome.i18n.getMessage("learnMoreDot"),
- URL2,
- true,
- false
- );
- }
- }}
+ onClick={openPermissionsModal}
>
<img src={CameraOffBlue} />
<span>{chrome.i18n.getMessage("allowCameraAccessButton")}</span>
@@ -214,27 +236,7 @@ const RecordingType = (props) => {
{!contentState.microphonePermission && (
<button
className="permission-button"
- onClick={() => {
- if (typeof contentState.openModal === "function") {
- contentState.openModal(
- chrome.i18n.getMessage("permissionsModalTitle"),
- chrome.i18n.getMessage("permissionsModalDescription"),
- chrome.i18n.getMessage("permissionsModalReview"),
- chrome.i18n.getMessage("permissionsModalDismiss"),
- () => {
- chrome.runtime.sendMessage({
- type: "extension-media-permissions",
- });
- },
- () => {},
- chrome.runtime.getURL("assets/helper/permissions.webp"),
- chrome.i18n.getMessage("learnMoreDot"),
- URL2,
- true,
- false
- );
- }
- }}
+ onClick={openPermissionsModal}
>
<img src={MicOffBlue} />
<span>{chrome.i18n.getMessage("allowMicrophoneAccessButton")}</span>
diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsx
index 382f9af..a6148af 100644
--- a/src/pages/Recorder/Recorder.jsx
+++ b/src/pages/Recorder/Recorder.jsx
@@ -219,11 +219,65 @@ const Recorder = () => {
// Start gate: defers startRecording() until the stream is ready.
const startRequested = useRef(false);
const startRequestedAt = useRef(null);
- // Null on start-gate timeout → SW→tab handoff failed (distinct error code).
+ // Null on start-gate timeout: SW-to-tab handoff failed (distinct error code).
const streamingDataReceivedAt = useRef(null);
// Timeout if the stream never arrives
const startGateTimeout = useRef(null);
- const START_GATE_TIMEOUT_MS = 8000; // max wait for stream after start request
+ // 12s accounts for cold SW wake-ups on Windows Chrome, where the SW can
+ // take several seconds to revive after suspension before it can process
+ // get-streaming-data. 8s was too tight under that workload.
+ const START_GATE_TIMEOUT_MS = 12000;
+ const streamingDataRetryTimer = useRef(null);
+
+ // Pulls streaming-data from the SW with retry. Chrome can fail the initial
+ // sendMessage if the SW is in the middle of waking up (returns lastError
+ // "Receiving end does not exist") and silently drop the request. Retry
+ // with backoff until streaming-data arrives or the start gate times out.
+ // The SW also pushes streaming-data proactively, so duplicate delivery
+ // is possible; the streaming-data handler is idempotent to cover that.
+ const requestStreamingDataWithRetry = (attempt = 0) => {
+ if (streamingDataReceivedAt.current != null) return;
+ const maxAttempts = 5;
+ const backoffMs = [0, 250, 500, 1000, 2000];
+ const delay = backoffMs[Math.min(attempt, backoffMs.length - 1)];
+ if (streamingDataRetryTimer.current) {
+ clearTimeout(streamingDataRetryTimer.current);
+ }
+ streamingDataRetryTimer.current = setTimeout(() => {
+ streamingDataRetryTimer.current = null;
+ if (streamingDataReceivedAt.current != null) return;
+ slLog("get-streaming-data-send", { attempt });
+ try {
+ chrome.runtime.sendMessage({ type: "get-streaming-data" }, () => {
+ const err = chrome.runtime.lastError;
+ if (err) {
+ slLog("get-streaming-data-send-error", {
+ attempt,
+ err: String(err.message || err).slice(0, 120),
+ });
+ }
+ if (
+ err &&
+ streamingDataReceivedAt.current == null &&
+ attempt + 1 < maxAttempts
+ ) {
+ requestStreamingDataWithRetry(attempt + 1);
+ }
+ });
+ } catch (e) {
+ slLog("get-streaming-data-throw", {
+ attempt,
+ err: String(e?.message || e).slice(0, 120),
+ });
+ if (
+ streamingDataReceivedAt.current == null &&
+ attempt + 1 < maxAttempts
+ ) {
+ requestStreamingDataWithRetry(attempt + 1);
+ }
+ }
+ }, delay);
+ };
const liveStream = useRef(null);
@@ -772,6 +826,10 @@ const Recorder = () => {
streamingDataReceivedAt.current = null;
isStarting.current = false;
clearStartGateTimeout();
+ if (streamingDataRetryTimer.current) {
+ clearTimeout(streamingDataRetryTimer.current);
+ streamingDataRetryTimer.current = null;
+ }
}
/** Request recording start — immediate if stream is ready, deferred otherwise. */
@@ -2654,8 +2712,15 @@ const Recorder = () => {
} else {
isTab.current = false;
}
- chrome.runtime.sendMessage({ type: "get-streaming-data" });
+ requestStreamingDataWithRetry();
} else if (request.type === "streaming-data") {
+ // Guard against duplicate delivery: streaming-data may arrive more
+ // than once when the SW push and the tab pull both succeed, or when
+ // either side retries. First arrival wins; later ones are ignored.
+ if (streamingDataReceivedAt.current != null) {
+ slLog("msg-streaming-data-duplicate");
+ return;
+ }
slLog("msg-streaming-data");
streamingDataReceivedAt.current = Date.now();
startStreaming(JSON.parse(request.data));
diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsx
index 3fb6ed5..ee863ce 100644
--- a/src/pages/Region/Recorder.jsx
+++ b/src/pages/Region/Recorder.jsx
@@ -148,6 +148,61 @@ const Recorder = () => {
const lowStorageAbort = useRef(false);
const savedCount = useRef(0);
+ const streamingDataHandled = useRef(false);
+ const streamingDataRetryTimer = useRef(null);
+
+ // Retry get-streaming-data from the SW with backoff. The initial
+ // sendMessage can fail silently if the SW is mid-wakeup; this retry
+ // plus SW-side retry plus the handler's idempotency guard cover the
+ // handshake reliably on slow Windows cold-starts.
+ const requestStreamingDataWithRetry = (attempt = 0) => {
+ if (streamingDataHandled.current) return;
+ const backoffMs = [0, 250, 500, 1000, 2000];
+ const delay = backoffMs[Math.min(attempt, backoffMs.length - 1)];
+ if (streamingDataRetryTimer.current) {
+ clearTimeout(streamingDataRetryTimer.current);
+ }
+ streamingDataRetryTimer.current = setTimeout(() => {
+ streamingDataRetryTimer.current = null;
+ if (streamingDataHandled.current) return;
+ persistRegionStartDebug({
+ stage: "get-streaming-data-send",
+ attempt,
+ });
+ try {
+ chrome.runtime.sendMessage({ type: "get-streaming-data" }, () => {
+ const err = chrome.runtime.lastError;
+ if (err) {
+ persistRegionStartDebug({
+ stage: "get-streaming-data-send-error",
+ attempt,
+ err: String(err.message || err).slice(0, 120),
+ });
+ }
+ if (
+ err &&
+ !streamingDataHandled.current &&
+ attempt + 1 < backoffMs.length
+ ) {
+ requestStreamingDataWithRetry(attempt + 1);
+ }
+ });
+ } catch (e) {
+ persistRegionStartDebug({
+ stage: "get-streaming-data-throw",
+ attempt,
+ err: String(e?.message || e).slice(0, 120),
+ });
+ if (
+ !streamingDataHandled.current &&
+ attempt + 1 < backoffMs.length
+ ) {
+ requestStreamingDataWithRetry(attempt + 1);
+ }
+ }
+ }, delay);
+ };
+
const lastEstimateAt = useRef(0);
const ESTIMATE_INTERVAL_MS = 5000;
const MIN_HEADROOM = 25 * 1024 * 1024;
@@ -1821,10 +1876,12 @@ const Recorder = () => {
if (request.type === "loaded") {
backupRef.current = request.backup;
if (request.region) {
- chrome.runtime.sendMessage({ type: "get-streaming-data" });
+ requestStreamingDataWithRetry();
}
}
if (request.type === "streaming-data") {
+ if (streamingDataHandled.current) return;
+ streamingDataHandled.current = true;
if (regionRef.current) {
startStreaming(JSON.parse(request.data));
}
diff --git a/src/pages/RemuxOffscreen/index.html b/src/pages/RemuxOffscreen/index.html
new file mode 100644
index 0000000..1e03100
--- /dev/null
+++ b/src/pages/RemuxOffscreen/index.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <title>Screenity Remux Offscreen</title>
+ </head>
+ <body>
+ <!-- Headless offscreen document that hosts the remux worker.
+ No UI; all work happens in index.js and the spawned worker. -->
+ </body>
+</html>
diff --git a/src/pages/RemuxOffscreen/index.js b/src/pages/RemuxOffscreen/index.js
new file mode 100644
index 0000000..873943a
--- /dev/null
+++ b/src/pages/RemuxOffscreen/index.js
@@ -0,0 +1,110 @@
+/*
+ * Offscreen document entry. Acts as a message router between the service
+ * worker and a dedicated worker that runs the OPFS-backed remux. The
+ * offscreen doc itself does no CPU work: it only spawns the worker and
+ * proxies messages in both directions.
+ *
+ * Lifecycle:
+ * - Created by the SW on first remux-request.
+ * - Worker is lazily spawned on first remux-start message.
+ * - Stays alive as long as the SW keeps it open (SW tears down after
+ * idle timeout, which terminates this page and the worker with it).
+ */
+
+const devLog =
+ process.env.SCREENITY_DEV_MODE === "true"
+ ? (label, data) => console.log("[remux][offscreen]", label, data || "")
+ : () => {};
+
+let worker = null;
+// Pending remuxes keyed by requestId. Each entry holds the sendResponse
+// callback from chrome.runtime.onMessage, so we can reply once the worker
+// finishes or fails. Progress events don't use these; they broadcast to
+// the sandbox directly via chrome.runtime.sendMessage.
+const pending = new Map();
+
+const ensureWorker = () => {
+ if (worker) return worker;
+ devLog("spawn-worker");
+ worker = new Worker(chrome.runtime.getURL("remuxworker.bundle.js"));
+ worker.onmessage = (e) => {
+ const msg = e.data;
+ if (!msg || !msg.requestId) return;
+ const entry = pending.get(msg.requestId);
+ if (msg.type === "progress") {
+ // Forward progress to the sandbox. Swallow errors; progress is
+ // best-effort telemetry.
+ chrome.runtime
+ .sendMessage({
+ type: "remux-progress",
+ requestId: msg.requestId,
+ progress: msg.progress,
+ })
+ .catch(() => {});
+ return;
+ }
+ if (msg.type === "done") {
+ devLog("worker-done", {
+ requestId: msg.requestId,
+ outputFileName: msg.outputFileName,
+ });
+ pending.delete(msg.requestId);
+ entry?.sendResponse?.({ ok: true, outputFileName: msg.outputFileName });
+ return;
+ }
+ if (msg.type === "error") {
+ devLog("worker-error", { requestId: msg.requestId, err: msg.error });
+ pending.delete(msg.requestId);
+ entry?.sendResponse?.({ ok: false, error: msg.error });
+ return;
+ }
+ };
+ worker.onerror = (e) => {
+ // Worker-level error (module load failure, uncaught throw). Fail all
+ // pending remuxes so callers can fall back.
+ const errText = String(e?.message || e || "worker-error");
+ for (const [id, entry] of pending) {
+ entry?.sendResponse?.({ ok: false, error: errText });
+ }
+ pending.clear();
+ try {
+ worker.terminate();
+ } catch {
+ // already terminated
+ }
+ worker = null;
+ };
+ return worker;
+};
+
+chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
+ if (!message || message.type !== "remux-start") return undefined;
+ const { requestId, inputFileName, outputFileName } = message;
+ if (!requestId || !inputFileName || !outputFileName) {
+ sendResponse({ ok: false, error: "invalid-remux-start-payload" });
+ return false;
+ }
+ try {
+ const w = ensureWorker();
+ devLog("remux-start-received", {
+ requestId,
+ inputFileName,
+ outputFileName,
+ });
+ pending.set(requestId, { sendResponse });
+ w.postMessage({
+ type: "remux",
+ requestId,
+ inputFileName,
+ outputFileName,
+ });
+ } catch (err) {
+ pending.delete(requestId);
+ sendResponse({
+ ok: false,
+ error: String(err?.message || err || "remux-start-failed"),
+ });
+ return false;
+ }
+ return true;
+});
diff --git a/src/pages/RemuxOffscreen/opfsTarget.js b/src/pages/RemuxOffscreen/opfsTarget.js
new file mode 100644
index 0000000..077b3e5
--- /dev/null
+++ b/src/pages/RemuxOffscreen/opfsTarget.js
@@ -0,0 +1,35 @@
+/*
+ * Wraps a FileSystemSyncAccessHandle as a WritableStream, so mediabunny's
+ * StreamTarget can write to OPFS directly. Keeps zero bytes in memory past
+ * the last write. Supports positioned writes (required for fastStart: false
+ * MP4, which patches the mdat size header after samples are written).
+ *
+ * Must run inside a Dedicated Worker: createSyncAccessHandle() is not
+ * available on the main thread.
+ */
+export function createOpfsWritable(syncHandle) {
+ let writtenBytes = 0;
+ return new WritableStream({
+ write(chunk) {
+ // Mediabunny's StreamTarget emits chunks shaped as
+ // { data: Uint8Array | ArrayBuffer, position: number, type: string }.
+ // Fall back to append-mode for plain bytes so the writable is also
+ // usable outside StreamTarget.
+ const data = chunk?.data ?? chunk;
+ const position = chunk?.position ?? writtenBytes;
+ const buf =
+ data instanceof Uint8Array
+ ? data
+ : new Uint8Array(data);
+ const bytesWritten = syncHandle.write(buf, { at: position });
+ const end = position + (bytesWritten ?? buf.byteLength);
+ if (end > writtenBytes) writtenBytes = end;
+ },
+ close() {
+ syncHandle.flush();
+ },
+ abort() {
+ syncHandle.flush();
+ },
+ });
+}
diff --git a/src/pages/RemuxOffscreen/worker.js b/src/pages/RemuxOffscreen/worker.js
new file mode 100644
index 0000000..30bac45
--- /dev/null
+++ b/src/pages/RemuxOffscreen/worker.js
@@ -0,0 +1,176 @@
+/*
+ * Dedicated worker that re-muxes a fragmented MP4 file from OPFS to a
+ * standard (non-fragmented) MP4, also written to OPFS. Keeps peak RAM
+ * near zero regardless of recording length.
+ *
+ * Input and output are exchanged as OPFS filenames (strings) rather than
+ * Blobs, because chrome.runtime.sendMessage across the service worker
+ * loses Blob identity ("blob must be a Blob." errors). OPFS is shared
+ * between the sandbox and the worker since both live at the same
+ * chrome-extension origin.
+ *
+ * Flow:
+ * 1. Sweep OPFS remux-*.mp4 files older than STALE_AGE_MS.
+ * 2. Receive inputFileName + outputFileName from the offscreen doc.
+ * 3. Open the input OPFS file, read as a Blob via getFile().
+ * 4. Open the output OPFS file with a sync access handle.
+ * 5. Run mediabunny Conversion (fastStart: false) streaming through
+ * a WritableStream backed by the sync handle.
+ * 6. Flush + close the handle. Return the output filename.
+ * 7. Caller (sandbox) reads the output from OPFS and triggers the
+ * download, then cleans up the input file. Output file lingers;
+ * the next run's sweep removes it.
+ */
+import {
+ Input,
+ Output,
+ BlobSource,
+ StreamTarget,
+ Mp4OutputFormat,
+ ALL_FORMATS,
+ Conversion,
+} from "mediabunny";
+import { createOpfsWritable } from "./opfsTarget";
+
+const TEMP_FILE_PREFIX = "remux-";
+const STALE_AGE_MS = 5 * 60 * 1000;
+
+const devLog =
+ process.env.SCREENITY_DEV_MODE === "true"
+ ? (label, data) => console.log("[remux][worker]", label, data || "")
+ : () => {};
+
+const postProgress = (requestId, progress) => {
+ self.postMessage({ type: "progress", requestId, progress });
+};
+
+const postDone = (requestId, outputFileName) => {
+ self.postMessage({ type: "done", requestId, outputFileName });
+};
+
+const postError = (requestId, error) => {
+ self.postMessage({
+ type: "error",
+ requestId,
+ error: String(error?.message || error),
+ });
+};
+
+// Sweep stale remux-*.mp4 files from prior runs, but only those older than
+// STALE_AGE_MS. Previous remuxes intentionally leave their file around so
+// the sandbox can stream it to chrome.downloads without racing a delete;
+// the age window is plenty for a download to complete.
+const sweepOpfsStaleFiles = async () => {
+ try {
+ const dir = await navigator.storage.getDirectory();
+ const now = Date.now();
+ for await (const [name, handle] of dir.entries()) {
+ if (!name.startsWith(TEMP_FILE_PREFIX)) continue;
+ try {
+ const file = await handle.getFile();
+ if (now - file.lastModified > STALE_AGE_MS) {
+ await dir.removeEntry(name).catch(() => {});
+ }
+ } catch {
+ // Unable to stat the file; leave it alone.
+ }
+ }
+ } catch {
+ // best-effort
+ }
+};
+
+const remuxToOpfs = async ({ requestId, inputFileName, outputFileName }) => {
+ const startedAt = Date.now();
+ devLog("start", { requestId, inputFileName, outputFileName });
+ await sweepOpfsStaleFiles();
+
+ let dir;
+ let outputHandle;
+ let syncHandle;
+ let handleReleased = false;
+ let lastProgressLogged = -1;
+
+ try {
+ dir = await navigator.storage.getDirectory();
+
+ // Load the input as a Blob via getFile(). The Blob is disk-backed by
+ // Chrome; reads during mediabunny's processing stream from the OPFS
+ // file on demand without pulling all bytes into memory at once.
+ const inputHandle = await dir.getFileHandle(inputFileName);
+ const inputFile = await inputHandle.getFile();
+
+ outputHandle = await dir.getFileHandle(outputFileName, { create: true });
+ syncHandle = await outputHandle.createSyncAccessHandle();
+ syncHandle.truncate(0);
+
+ const writable = createOpfsWritable(syncHandle);
+
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(inputFile),
+ });
+ const output = new Output({
+ target: new StreamTarget(writable),
+ format: new Mp4OutputFormat({ fastStart: false }),
+ });
+
+ const conversion = await Conversion.init({
+ input,
+ output,
+ video: { forceTranscode: false },
+ audio: { forceTranscode: false },
+ });
+ conversion.onProgress = (p) => {
+ postProgress(requestId, p);
+ const decile = Math.floor(p * 10);
+ if (decile !== lastProgressLogged) {
+ lastProgressLogged = decile;
+ devLog("progress", { pct: Math.round(p * 100) });
+ }
+ };
+ await conversion.execute();
+
+ try {
+ await writable.close();
+ } catch {
+ // close is best-effort; the sync handle already has the data.
+ }
+ syncHandle.flush();
+ const finalSize = syncHandle.getSize();
+ syncHandle.close();
+ handleReleased = true;
+
+ devLog("done", {
+ durationMs: Date.now() - startedAt,
+ outputBytes: finalSize,
+ });
+ postDone(requestId, outputFileName);
+ } catch (err) {
+ devLog("error", {
+ err: String(err?.message || err).slice(0, 200),
+ durationMs: Date.now() - startedAt,
+ });
+ postError(requestId, err);
+ if (syncHandle && !handleReleased) {
+ try {
+ syncHandle.close();
+ } catch {
+ // already closed
+ }
+ }
+ if (dir && outputFileName) {
+ try {
+ await dir.removeEntry(outputFileName).catch(() => {});
+ } catch {
+ // best-effort
+ }
+ }
+ }
+};
+
+self.onmessage = (e) => {
+ const msg = e.data;
+ if (!msg || msg.type !== "remux") return;
+ remuxToOpfs(msg);
+};
diff --git a/src/pages/Sandbox/DevHUD.jsx b/src/pages/Sandbox/DevHUD.jsx
index e37ba9e..97c472a 100644
--- a/src/pages/Sandbox/DevHUD.jsx
+++ b/src/pages/Sandbox/DevHUD.jsx
@@ -13,7 +13,7 @@ const BTN = {
const BTN_RESET = { ...BTN, background: "rgba(200,50,50,0.7)" };
const Z = 2147483647;
-const DevHUD = ({ setContentState, contentStateRef }) => {
+const DevHUD = ({ setContentState, contentStateRef, lastDownloadInfo }) => {
const [collapsed, setCollapsed] = useState(true);
if (collapsed) {
@@ -215,6 +215,33 @@ const DevHUD = ({ setContentState, contentStateRef }) => {
x
</span>
</div>
+ {lastDownloadInfo && (
+ <div
+ style={{
+ color: "#0f0",
+ fontSize: "9px",
+ background: "rgba(0,40,0,0.4)",
+ padding: "4px 6px",
+ borderRadius: "3px",
+ lineHeight: 1.4,
+ whiteSpace: "normal",
+ }}
+ >
+ <div>Last download</div>
+ <div style={{ color: "#8f8" }}>{lastDownloadInfo.path}</div>
+ <div style={{ color: "#aaa" }}>
+ {Math.round(lastDownloadInfo.durationMs)}ms / in{" "}
+ {Math.round(
+ (lastDownloadInfo.inputBytes || 0) / (1024 * 1024),
+ )}
+ MB / out{" "}
+ {Math.round(
+ (lastDownloadInfo.outputBytes || 0) / (1024 * 1024),
+ )}
+ MB
+ </div>
+ </div>
+ )}
{actions.map((a) => (
<button key={a.label} style={BTN} onClick={a.fn}>
{a.label}
diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsx
index 2444c3b..ac7b29f 100644
--- a/src/pages/Sandbox/context/ContentState.jsx
+++ b/src/pages/Sandbox/context/ContentState.jsx
@@ -149,6 +149,10 @@ const ContentState = (props) => {
const defaultState = {
time: 0,
editLimit: 420,
+ // Last successful (or failed) download remux outcome. Populated at
+ // the end of download(); consumed by DevHUD in dev builds to show
+ // which tier ran and how long it took.
+ lastDownloadInfo: null,
blob: null,
webm: null,
originalBlob: null,
@@ -2184,6 +2188,96 @@ const ContentState = (props) => {
return new Blob([target.buffer], { type: "video/mp4" });
};
+ // Route the remux through an offscreen document that spawns a dedicated
+ // worker and writes the output to OPFS via a sync access handle. Keeps
+ // peak RAM near zero regardless of recording length, and avoids the
+ // 2 GB ArrayBuffer ceiling that BufferTarget hits on very long clips.
+ // Falls back silently: if any hop fails, the caller tries the in-sandbox
+ // BufferTarget path instead.
+ const remuxViaOffscreenOpfs = async (fragmentedBlob, onProgress) => {
+ const requestId =
+ (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
+ ? crypto.randomUUID()
+ : `${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ const devLog =
+ process.env.SCREENITY_DEV_MODE === "true"
+ ? (label, data) =>
+ console.log("[remux][sandbox]", label, data || "")
+ : () => {};
+ devLog("offscreen-remux-start", {
+ requestId,
+ inputBytes: fragmentedBlob?.size,
+ });
+
+ const progressListener = (msg) => {
+ if (
+ msg?.type === "remux-progress" &&
+ msg.requestId === requestId &&
+ typeof onProgress === "function"
+ ) {
+ onProgress(msg.progress);
+ }
+ };
+ chrome.runtime.onMessage.addListener(progressListener);
+
+ // Transport via OPFS rather than passing the Blob through
+ // chrome.runtime.sendMessage. Chrome's structured clone for extension
+ // messaging is lossy for Blobs crossing the service worker: the Blob
+ // arrives as a plain object and BlobSource rejects it with
+ // "blob must be a Blob.". Writing the input to OPFS first and passing
+ // a filename (string) sidesteps the issue entirely; the worker reads
+ // back via navigator.storage.getDirectory() in its own context.
+ const inputFileName = `remux-in-${requestId}.mp4`;
+ const outputFileName = `remux-${requestId}.mp4`;
+ let opfsDir;
+ try {
+ opfsDir = await navigator.storage.getDirectory();
+ } catch (err) {
+ chrome.runtime.onMessage.removeListener(progressListener);
+ throw new Error(
+ `opfs-unavailable: ${String(err?.message || err).slice(0, 120)}`,
+ );
+ }
+
+ try {
+ // Stage the input in OPFS. createWritable is async and streams to
+ // disk without blocking the main thread for the full duration.
+ const inputHandle = await opfsDir.getFileHandle(inputFileName, {
+ create: true,
+ });
+ const writable = await inputHandle.createWritable();
+ await writable.write(fragmentedBlob);
+ await writable.close();
+ devLog("staged-input-in-opfs", { inputFileName });
+
+ const response = await chrome.runtime.sendMessage({
+ type: "remux-request",
+ requestId,
+ inputFileName,
+ outputFileName,
+ });
+ if (!response || response.ok !== true) {
+ devLog("offscreen-remux-response-bad", response);
+ throw new Error(response?.error || "offscreen-remux-failed");
+ }
+
+ const outputHandle = await opfsDir.getFileHandle(outputFileName);
+ const file = await outputHandle.getFile();
+ const outputBlob = new Blob([file], { type: "video/mp4" });
+ devLog("offscreen-remux-ok", { outputBytes: outputBlob.size });
+ return outputBlob;
+ } finally {
+ chrome.runtime.onMessage.removeListener(progressListener);
+ // Input file is no longer needed once the worker finished (or failed).
+ try {
+ await opfsDir.removeEntry(inputFileName).catch(() => {});
+ } catch {}
+ // Output file is left in place; the Blob we just returned may still
+ // be streaming to chrome.downloads. The worker's age-based sweep
+ // cleans it up on the next remux.
+ }
+ };
+
const download = async () => {
if (contentState.isFfmpegRunning || contentState.downloading) return;
@@ -2194,23 +2288,88 @@ const ContentState = (props) => {
processingProgress: 0,
}));
+ const progressHandler = (p) =>
+ setContentState((prev) => ({
+ ...prev,
+ processingProgress: Math.round(p * 100),
+ }));
+
+ const inputSize = contentState.blob?.size || 0;
+ const remuxStartedAt = Date.now();
+ let remuxedBlob = null;
+ let remuxPath = null;
+ // Tier 1: offscreen + OPFS. Flat memory, works for any recording size.
try {
- // Re-mux fragmented MP4 → standard MP4 for universal compatibility.
- // Editor plays fMP4 directly (Chrome handles it), but downloaded
- // files need the standard layout so they seek cleanly in QuickTime,
- // DaVinci, Premiere, etc. Container-only operation, no re-encode.
- const remuxedBlob = await remuxFragmentedToStandardMp4(
+ diagForward("remux-offscreen-start", { inputBytes: inputSize });
+ remuxedBlob = await remuxViaOffscreenOpfs(
contentState.blob,
- (p) =>
- setContentState((prev) => ({
- ...prev,
- processingProgress: Math.round(p * 100),
- })),
+ progressHandler,
);
- const url = URL.createObjectURL(remuxedBlob);
- await requestDownload(url, ".mp4");
- URL.revokeObjectURL(url);
- setContentState((prev) => ({ ...prev, saved: true }));
+ remuxPath = "offscreen-opfs";
+ diagForward("remux-offscreen-ok", { inputBytes: inputSize });
+ } catch (err) {
+ console.warn("[Screenity] offscreen remux failed, falling back", err);
+ diagForward("remux-offscreen-fail", {
+ inputBytes: inputSize,
+ err: String(err?.message || err).slice(0, 200),
+ });
+ }
+
+ // Tier 2: in-sandbox BufferTarget. Costs ~recording size in RAM; hits
+ // a 2 GB ArrayBuffer ceiling on very long clips.
+ if (!remuxedBlob) {
+ try {
+ remuxedBlob = await remuxFragmentedToStandardMp4(
+ contentState.blob,
+ progressHandler,
+ );
+ remuxPath = "buffer-target";
+ diagForward("remux-buffer-target-ok", { inputBytes: inputSize });
+ } catch (err) {
+ console.warn("[Screenity] buffer-target remux failed, falling back", err);
+ diagForward("remux-buffer-target-fail", {
+ inputBytes: inputSize,
+ err: String(err?.message || err).slice(0, 200),
+ });
+ }
+ }
+
+ const remuxDurationMs = Date.now() - remuxStartedAt;
+ if (process.env.SCREENITY_DEV_MODE === "true") {
+ console.log("[remux][sandbox] summary", {
+ path: remuxPath || "fmp4-fallback",
+ durationMs: remuxDurationMs,
+ inputBytes: inputSize,
+ outputBytes: remuxedBlob?.size || 0,
+ });
+ }
+ setContentState((prev) => ({
+ ...prev,
+ lastDownloadInfo: {
+ path: remuxPath || "fmp4-fallback",
+ durationMs: remuxDurationMs,
+ inputBytes: inputSize,
+ outputBytes: remuxedBlob?.size || 0,
+ at: Date.now(),
+ },
+ }));
+
+ try {
+ if (remuxedBlob) {
+ const url = URL.createObjectURL(remuxedBlob);
+ await requestDownload(url, ".mp4");
+ URL.revokeObjectURL(url);
+ setContentState((prev) => ({ ...prev, saved: true }));
+ diagForward("remux-delivered", {
+ inputBytes: inputSize,
+ outputBytes: remuxedBlob.size || 0,
+ path: remuxPath,
+ });
+ } else {
+ // Tier 3: serve the fMP4 as-is. Plays in Chrome/VLC/most modern
+ // players; some older editors may have seeking quirks.
+ throw new Error("both-remux-paths-failed");
+ }
} catch (err) {
console.error("MP4 download failed:", err);
// Fallback: serve the fMP4 as-is so the user doesn't lose the
@@ -2355,6 +2514,7 @@ const ContentState = (props) => {
<DevHUD
setContentState={setContentState}
contentStateRef={contentStateRef}
+ lastDownloadInfo={contentState.lastDownloadInfo}
/>
)}
</ContentStateContext.Provider>
diff --git a/webpack.config.js b/webpack.config.js
index 9b6b522..f156157 100755
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -68,12 +68,30 @@ const entryPoints = {
"index.jsx"
),
backup: path.join(__dirname, "src", "pages", "Backup", "index.jsx"),
+ remuxoffscreen: path.join(
+ __dirname,
+ "src",
+ "pages",
+ "RemuxOffscreen",
+ "index.js"
+ ),
+ remuxworker: path.join(
+ __dirname,
+ "src",
+ "pages",
+ "RemuxOffscreen",
+ "worker.js"
+ ),
};
const htmlPlugins = Object.keys(entryPoints)
.map((entryName) => {
- // Skip background script as it doesn't need an HTML file
- if (entryName === "background" || entryName === "contentScript") {
+ // Skip background script and worker bundles; they have no HTML page.
+ if (
+ entryName === "background" ||
+ entryName === "contentScript" ||
+ entryName === "remuxworker"
+ ) {
return null;
}
@@ -84,6 +102,7 @@ const htmlPlugins = Object.keys(entryPoints)
audiooffscreen: "AudioOffscreen",
editorwebcodecs: "EditorWebCodecs",
editorviewer: "EditorViewer",
+ remuxoffscreen: "RemuxOffscreen",
};
const folderName =