Skip to content

🎥 Make videos programmatically with React

`@remotion/canvas-capture-extension`: Improve high-resolution recording (#10249)

Jonny Burgercb0402cac69a
diff --git a/.agents/skills/canvas-capture-extension/SKILL.md b/.agents/skills/canvas-capture-extension/SKILL.md
index f7457142a8..6ed33ab91a 100644
--- a/.agents/skills/canvas-capture-extension/SKILL.md
+++ b/.agents/skills/canvas-capture-extension/SKILL.md
@@ -20,11 +20,12 @@ the unpacked copy outside the checkout so deleting a worktree cannot break it.
--repo <remotion-checkout>
```
- The script builds with Bun and installs the four unpacked-extension files in
+ The script builds with Bun and installs the seven unpacked-extension files in
`/Users/jonathanburger/Applications/Remotion Canvas Capture Extension`.
3. Confirm that the installed directory contains `manifest.json`,
- `background.js`, `content.js`, and `receiver.js`.
+ `background.js`, `content.js`, `popup.css`, `popup.html`, `popup.js`, and
+ `receiver.js`.
## Reload in Chrome
diff --git a/.agents/skills/canvas-capture-extension/scripts/rebuild-extension.sh b/.agents/skills/canvas-capture-extension/scripts/rebuild-extension.sh
index 32ff69a490..73aeee0ffe 100755
--- a/.agents/skills/canvas-capture-extension/scripts/rebuild-extension.sh
+++ b/.agents/skills/canvas-capture-extension/scripts/rebuild-extension.sh
@@ -61,7 +61,7 @@ fi
bun run make
)
-for required_file in manifest.json background.js content.js receiver.js; do
+for required_file in manifest.json background.js content.js popup.css popup.html popup.js receiver.js; do
if [[ ! -f "$dist_dir/$required_file" ]]; then
printf 'Build did not produce %s\n' "$dist_dir/$required_file" >&2
exit 1
@@ -69,7 +69,7 @@ for required_file in manifest.json background.js content.js receiver.js; do
done
mkdir -p "$install_dir"
-for extension_file in manifest.json background.js content.js receiver.js; do
+for extension_file in manifest.json background.js content.js popup.css popup.html popup.js receiver.js; do
cp "$dist_dir/$extension_file" "$install_dir/$extension_file"
done
diff --git a/packages/canvas-capture-extension/README.md b/packages/canvas-capture-extension/README.md
index bf74391ddc..805dd4acdd 100644
--- a/packages/canvas-capture-extension/README.md
+++ b/packages/canvas-capture-extension/README.md
@@ -1,6 +1,6 @@
# Remotion Canvas Capture Chrome extension
-Record an element—or a whole webpage—as a high-resolution WebM using Chromium's experimental HTML-in-canvas implementation.
+Record an element—or a whole webpage—as a high-resolution H.264 MP4 or VP9 WebM using Chromium's experimental HTML-in-canvas implementation.
## Build and install
@@ -9,6 +9,6 @@ Record an element—or a whole webpage—as a high-resolution WebM using Chromiu
3. Select `packages/canvas-capture-extension/dist`.
4. Enable `chrome://flags/#canvas-draw-element` and restart Chrome if HTML-in-canvas is not already enabled.
-Click the extension icon on a webpage to open the recorder. Set the output scale, select an area (the extension picks the deepest DOM element containing it and encodes only the drawn crop using Mediabunny's `CropRectangle` transform) or choose **Whole page**, then press **Record**. Press **Stop and open in Convert** to load the recording in [remotion.dev/convert](https://remotion.dev/convert) without downloading it first, or **Stop and download WebM** to save it directly.
+Click the extension icon on a webpage to open the recorder window. Choose H.264 MP4 or VP9 WebM, set the output scale, select an area (the page is focused while you drag, but the recorder window remains open, and the extension picks the deepest DOM element containing the selection) or choose **Whole page**, then press **Record**. The recorder displays the rounded output dimensions and only enables **Record** after the browser confirms that Mediabunny's exact high-quality, realtime configuration is supported. The selected element is drawn at the display's native pixel density, then the crop is copied into a reusable, correctly sized `OffscreenCanvas`. Enable **Include page background** to render the whole page subtree and crop it to the selected area instead of isolating the selected element. Recording continues if the recorder window closes; click the extension icon to reopen it, then press **Stop and open in Convert** to load the recording in [remotion.dev/convert](https://remotion.dev/convert) without downloading it first, or **Stop and download** to save it directly.
The chosen element is temporarily placed inside a `layoutSubtree` canvas while recording and restored afterward. Websites that rely on direct-child CSS selectors may look different during capture. Chrome's own pages and the Chrome Web Store do not allow extension script injection.
diff --git a/packages/canvas-capture-extension/bundle.ts b/packages/canvas-capture-extension/bundle.ts
index 3e99b4b01b..ed2aca6c09 100644
--- a/packages/canvas-capture-extension/bundle.ts
+++ b/packages/canvas-capture-extension/bundle.ts
@@ -2,7 +2,12 @@ import path from 'path';
import {build} from 'bun';
const output = await build({
- entrypoints: ['src/background.ts', 'src/content.ts', 'src/receiver.ts'],
+ entrypoints: [
+ 'src/background.ts',
+ 'src/content.ts',
+ 'src/popup.ts',
+ 'src/receiver.ts',
+ ],
outdir: 'dist',
naming: '[name].js',
target: 'browser',
@@ -17,5 +22,7 @@ if (!output.success) {
}
await Bun.write(path.join('dist', 'manifest.json'), Bun.file('manifest.json'));
+await Bun.write(path.join('dist', 'popup.html'), Bun.file('popup.html'));
+await Bun.write(path.join('dist', 'popup.css'), Bun.file('popup.css'));
console.log('Built Chrome extension in packages/canvas-capture-extension/dist');
diff --git a/packages/canvas-capture-extension/manifest.json b/packages/canvas-capture-extension/manifest.json
index 3d7d8871d0..e819208dba 100644
--- a/packages/canvas-capture-extension/manifest.json
+++ b/packages/canvas-capture-extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Remotion Canvas Capture",
- "description": "Record any element on a webpage as a high-resolution WebM.",
+ "description": "Record any element on a webpage as a high-resolution MP4 or WebM.",
"version": "0.1.0",
"permissions": ["activeTab", "scripting", "storage", "unlimitedStorage"],
"action": {
diff --git a/packages/canvas-capture-extension/popup.css b/packages/canvas-capture-extension/popup.css
new file mode 100644
index 0000000000..6022d18192
--- /dev/null
+++ b/packages/canvas-capture-extension/popup.css
@@ -0,0 +1,142 @@
+:root {
+ color-scheme: dark;
+ font-family:
+ Inter,
+ ui-sans-serif,
+ system-ui,
+ -apple-system,
+ sans-serif;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ min-width: 312px;
+ margin: 0;
+ background: #151515;
+ color: #f5f5f5;
+ font-size: 13px;
+ line-height: 1.4;
+}
+
+main {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 14px;
+}
+
+.title {
+ font-size: 14px;
+ font-weight: 650;
+}
+
+.setting,
+.checkbox {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.setting input,
+.setting select {
+ width: 88px;
+ padding: 7px 8px;
+ border: 1px solid #454545;
+ border-radius: 7px;
+ background: #242424;
+ color: white;
+ font: inherit;
+}
+
+.setting select {
+ width: 126px;
+}
+
+.checkbox {
+ justify-content: flex-start;
+ color: #ddd;
+ cursor: pointer;
+}
+
+.checkbox input {
+ width: 16px;
+ height: 16px;
+ margin: 0;
+ accent-color: #db2339;
+}
+
+.checkbox:has(input:disabled) {
+ cursor: default;
+ opacity: 0.45;
+}
+
+.row {
+ display: flex;
+ gap: 8px;
+}
+
+button {
+ min-height: 34px;
+ padding: 7px 10px;
+ border: 1px solid #454545;
+ border-radius: 7px;
+ background: #292929;
+ color: #f5f5f5;
+ font: inherit;
+ font-weight: 550;
+ cursor: pointer;
+}
+
+button:hover:not(:disabled) {
+ background: #363636;
+}
+
+button:disabled {
+ cursor: default;
+ opacity: 0.45;
+}
+
+.row button {
+ flex: 1;
+}
+
+.record {
+ border-color: #ff4d61;
+ background: #db2339;
+}
+
+.record:hover:not(:disabled) {
+ background: #ef3349;
+}
+
+.record.recording {
+ border-color: #fafafa;
+ background: #fafafa;
+ color: #be1830;
+}
+
+.target {
+ padding: 8px 9px;
+ border-radius: 7px;
+ background: #202020;
+ color: #ddd;
+ overflow-wrap: anywhere;
+}
+
+.status {
+ min-height: 18px;
+ color: #aaa;
+ overflow-wrap: anywhere;
+}
+
+.status.error {
+ color: #ff7b8b;
+}
+
+[hidden] {
+ display: none !important;
+}
diff --git a/packages/canvas-capture-extension/popup.html b/packages/canvas-capture-extension/popup.html
new file mode 100644
index 0000000000..ee0a4e70ab
--- /dev/null
+++ b/packages/canvas-capture-extension/popup.html
@@ -0,0 +1,45 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Remotion Canvas Capture</title>
+ <link rel="stylesheet" href="popup.css" />
+ <script src="popup.js" defer></script>
+ </head>
+ <body>
+ <main>
+ <div class="title">Remotion Canvas Capture</div>
+ <label class="setting">
+ <span>Scale</span>
+ <input
+ id="scale"
+ type="number"
+ min="0.1"
+ step="0.1"
+ value="1"
+ disabled
+ />
+ </label>
+ <label class="setting">
+ <span>Format</span>
+ <select id="format" disabled>
+ <option value="mp4">MP4 (H.264)</option>
+ <option value="webm">WebM (VP9)</option>
+ </select>
+ </label>
+ <div class="row">
+ <button id="select-area" type="button" disabled>Select area</button>
+ <button id="whole-page" type="button" disabled>Whole page</button>
+ </div>
+ <label class="checkbox">
+ <input id="include-background" type="checkbox" disabled />
+ <span>Include page background</span>
+ </label>
+ <div id="target" class="target">Connecting…</div>
+ <button id="record" class="record" type="button" disabled>Record</button>
+ <button id="download" type="button" hidden></button>
+ <div id="status" class="status">Connecting to this page…</div>
+ </main>
+ </body>
+</html>
diff --git a/packages/canvas-capture-extension/src/background.ts b/packages/canvas-capture-extension/src/background.ts
index af49672896..daf66e8a41 100644
--- a/packages/canvas-capture-extension/src/background.ts
+++ b/packages/canvas-capture-extension/src/background.ts
@@ -1,23 +1,60 @@
-const togglePanel = {type: 'remotion-canvas-capture-toggle'};
+import {capturePopupTargetMessageType} from './messages';
+
+const captureWindowStorageKey = 'remotion-canvas-capture-window-id';
+let windowAction = Promise.resolve();
+
+const showCaptureWindow = async (tabId: number) => {
+ const stored = await chrome.storage.session.get(captureWindowStorageKey);
+ const storedWindowId = stored[captureWindowStorageKey];
+ if (typeof storedWindowId === 'number') {
+ try {
+ await chrome.windows.update(storedWindowId, {focused: true});
+ await chrome.runtime.sendMessage({
+ type: capturePopupTargetMessageType,
+ tabId,
+ });
+ return;
+ } catch {
+ await chrome.storage.session.remove(captureWindowStorageKey);
+ }
+ }
+
+ const url = new URL(chrome.runtime.getURL('popup.html'));
+ url.searchParams.set('tabId', String(tabId));
+ const captureWindow = await chrome.windows.create({
+ url: url.toString(),
+ type: 'popup',
+ width: 340,
+ height: 435,
+ focused: true,
+ });
+ if (captureWindow.id !== undefined) {
+ await chrome.storage.session.set({
+ [captureWindowStorageKey]: captureWindow.id,
+ });
+ }
+};
chrome.action.onClicked.addListener((tab) => {
if (tab.id === undefined) {
return;
}
- const open = async () => {
- try {
- await chrome.tabs.sendMessage(tab.id!, togglePanel);
- } catch {
- await chrome.scripting.executeScript({
- target: {tabId: tab.id!},
- files: ['content.js'],
- });
- await chrome.tabs.sendMessage(tab.id!, togglePanel);
+ const tabId = tab.id;
+ windowAction = windowAction
+ .then(() => showCaptureWindow(tabId))
+ .catch(() => undefined);
+});
+
+chrome.windows.onRemoved.addListener((windowId) => {
+ const clearStoredWindow = async () => {
+ const stored = await chrome.storage.session.get(captureWindowStorageKey);
+ if (stored[captureWindowStorageKey] === windowId) {
+ await chrome.storage.session.remove(captureWindowStorageKey);
}
};
- open().catch(() => undefined);
+ clearStoredWindow().catch(() => undefined);
});
chrome.runtime.onMessage.addListener((message) => {
diff --git a/packages/canvas-capture-extension/src/capture.ts b/packages/canvas-capture-extension/src/capture.ts
index 0337c0487e..cf9009ab99 100644
--- a/packages/canvas-capture-extension/src/capture.ts
+++ b/packages/canvas-capture-extension/src/capture.ts
@@ -1,16 +1,27 @@
import type {CropRectangle} from 'mediabunny';
+import type {CaptureFormat} from './messages';
import {
+ assertCanEncodeCapture,
CanvasCaptureRecorder,
+ getScaledCanvasSize,
type HtmlInCanvasElement,
+ type HtmlInCanvasOffscreenRenderingContext2D,
type HtmlInCanvasRenderingContext2D,
resetCanvas,
syncCanvasSize,
+ syncDisplayCanvasSize,
} from './recorder';
const maxCanvasDimension = 32_767;
+const maxEncodedDimension = 32_766;
export type CaptureCrop = CropRectangle;
+export type CapturePreflight = {
+ readonly sourceSize: {readonly width: number; readonly height: number};
+ readonly outputSize: {readonly width: number; readonly height: number};
+};
+
type WrappedElement = {
readonly canvas: HtmlInCanvasElement;
readonly content: Element;
@@ -128,20 +139,123 @@ const getPageSize = (
height: Math.max(minimum.height, content.scrollHeight, window.innerHeight),
});
+const getWholePageSize = () => ({
+ width: Math.max(
+ document.documentElement.scrollWidth,
+ document.body.scrollWidth,
+ window.innerWidth,
+ ),
+ height: Math.max(
+ document.documentElement.scrollHeight,
+ document.body.scrollHeight,
+ window.innerHeight,
+ ),
+});
+
+const resolveCrop = (
+ crop: CaptureCrop | null,
+ sourceWidth: number,
+ sourceHeight: number,
+) => {
+ if (!crop) {
+ return null;
+ }
+
+ const left = Math.max(0, Math.min(crop.left, sourceWidth - 1));
+ const top = Math.max(0, Math.min(crop.top, sourceHeight - 1));
+ return {
+ left,
+ top,
+ width: Math.max(1, Math.min(crop.width, sourceWidth - left)),
+ height: Math.max(1, Math.min(crop.height, sourceHeight - top)),
+ };
+};
+
+const validateCaptureSize = ({
+ width,
+ height,
+ crop,
+ scale,
+}: {
+ readonly width: number;
+ readonly height: number;
+ readonly crop: CaptureCrop | null;
+ readonly scale: number;
+}) => {
+ const resolvedCrop = resolveCrop(crop, width, height) ?? {
+ left: 0,
+ top: 0,
+ width,
+ height,
+ };
+ const displayWidth = Math.max(1, Math.round(width * window.devicePixelRatio));
+ const displayHeight = Math.max(
+ 1,
+ Math.round(height * window.devicePixelRatio),
+ );
+ const outputSize = getScaledCanvasSize(
+ resolvedCrop.width,
+ resolvedCrop.height,
+ scale,
+ );
+ if (displayWidth > maxCanvasDimension || displayHeight > maxCanvasDimension) {
+ throw new Error(
+ `The display canvas would be ${displayWidth}×${displayHeight} pixels; its maximum side is ${maxCanvasDimension.toLocaleString()} pixels.`,
+ );
+ }
+
+ if (
+ outputSize.width > maxEncodedDimension ||
+ outputSize.height > maxEncodedDimension
+ ) {
+ throw new Error(
+ `The encoded frame would be ${outputSize.width}×${outputSize.height} pixels at ${scale}× scale; its maximum even side is ${maxEncodedDimension.toLocaleString()} pixels. Reduce the scale or select a smaller area.`,
+ );
+ }
+
+ return outputSize;
+};
+
+export const getCapturePreflight = ({
+ element,
+ wholePage,
+ scale,
+ crop,
+}: {
+ readonly element: Element | null;
+ readonly wholePage: boolean;
+ readonly scale: number;
+ readonly crop: CaptureCrop | null;
+}): CapturePreflight => {
+ const sourceSize = wholePage
+ ? getWholePageSize()
+ : (() => {
+ if (!element?.isConnected) {
+ throw new Error(
+ 'Select an element again; the previous target was removed.',
+ );
+ }
+
+ const rect = element.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) {
+ throw new Error('The selected element has no visible size.');
+ }
+
+ return {width: rect.width, height: rect.height};
+ })();
+ return {
+ sourceSize,
+ outputSize: validateCaptureSize({
+ ...sourceSize,
+ crop,
+ scale,
+ }),
+ };
+};
+
const wrapWholePage = (): WrappedElement => {
const {body} = document;
- const minimumSize = {
- width: Math.max(
- document.documentElement.scrollWidth,
- body.scrollWidth,
- window.innerWidth,
- ),
- height: Math.max(
- document.documentElement.scrollHeight,
- body.scrollHeight,
- window.innerHeight,
- ),
- };
+ const minimumSize = getWholePageSize();
const canvas = document.createElement('canvas') as HtmlInCanvasElement;
const content = document.createElement('div');
canvas.layoutSubtree = true;
@@ -206,18 +320,22 @@ const wrapWholePage = (): WrappedElement => {
};
};
-const getFilename = () => {
+const getFilename = (format: CaptureFormat) => {
const host = location.hostname.replace(/[^a-z0-9.-]+/gi, '-') || 'page';
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
- return `remotion-capture-${host}-${timestamp}.webm`;
+ return `remotion-capture-${host}-${timestamp}.${format}`;
};
export class ElementCapture {
readonly #wrapped: WrappedElement;
readonly #scale: number;
+ readonly #format: CaptureFormat;
readonly #crop: CaptureCrop | null;
readonly #recorder: CanvasCaptureRecorder;
readonly #context: HtmlInCanvasRenderingContext2D;
+ readonly #captureCanvas: OffscreenCanvas;
+ readonly #captureContext: HtmlInCanvasOffscreenRenderingContext2D;
+ readonly #matteColors: readonly string[];
readonly #resizeObserver: ResizeObserver;
#restored = false;
#paintError: unknown = null;
@@ -226,42 +344,87 @@ export class ElementCapture {
element,
wholePage,
scale,
+ format,
crop,
}: {
readonly element: Element | null;
readonly wholePage: boolean;
readonly scale: number;
+ readonly format: CaptureFormat;
readonly crop: CaptureCrop | null;
}) {
this.#scale = scale;
+ this.#format = format;
this.#crop = crop;
+ this.#matteColors = [
+ '#fff',
+ ...(wholePage
+ ? [
+ window.getComputedStyle(document.documentElement).backgroundColor,
+ window.getComputedStyle(document.body).backgroundColor,
+ ]
+ : []),
+ ];
this.#wrapped = wholePage ? wrapWholePage() : wrapElement(element!);
const context = this.#wrapped.canvas.getContext(
'2d',
) as HtmlInCanvasRenderingContext2D | null;
- if (!context || typeof context.drawElementImage !== 'function') {
+ if (
+ !context ||
+ typeof context.drawElementImage !== 'function' ||
+ typeof this.#wrapped.canvas.captureElementImage !== 'function'
+ ) {
this.#wrapped.restore();
throw new Error(
- 'drawElementImage() is not available in this Chrome build.',
+ 'The HTML-in-canvas capture APIs are not available in this Chrome build.',
);
}
this.#context = context;
- const sourceSize = this.#wrapped.getSize();
- this.#assertValidSize(sourceSize.width, sourceSize.height);
- syncCanvasSize(
- this.#wrapped.canvas,
- sourceSize.width,
- sourceSize.height,
- this.#scale,
- );
+ this.#captureCanvas = new OffscreenCanvas(2, 2);
+ const captureContext = this.#captureCanvas.getContext(
+ '2d',
+ ) as HtmlInCanvasOffscreenRenderingContext2D | null;
+ if (
+ !captureContext ||
+ typeof captureContext.drawElementImage !== 'function'
+ ) {
+ this.#wrapped.restore();
+ throw new Error(
+ 'Could not create an HTML-in-canvas OffscreenCanvas 2D context.',
+ );
+ }
+
+ this.#captureContext = captureContext;
+ try {
+ const sourceSize = this.#wrapped.getSize();
+ this.#assertValidSize(sourceSize.width, sourceSize.height);
+ syncDisplayCanvasSize(
+ this.#wrapped.canvas,
+ sourceSize.width,
+ sourceSize.height,
+ window.devicePixelRatio,
+ );
+ const initialCrop = this.#resolveCrop(
+ sourceSize.width,
+ sourceSize.height,
+ ) ?? {left: 0, top: 0, ...sourceSize};
+ syncCanvasSize(
+ this.#captureCanvas,
+ initialCrop.width,
+ initialCrop.height,
+ this.#scale,
+ );
+ } catch (error) {
+ this.#wrapped.restore();
+ throw error;
+ }
this.#recorder = new CanvasCaptureRecorder({
- canvas: this.#wrapped.canvas,
- crop: this.#getMediabunnyCrop(sourceSize.width, sourceSize.height),
+ format,
getContentRect: this.#getRecordingRect,
getDensity: () => this.#scale,
- getFilename,
+ getFilename: () => getFilename(format),
});
this.#wrapped.canvas.addEventListener('paint', this.#onPaint);
this.#resizeObserver = new ResizeObserver(this.#requestPaint);
@@ -270,8 +433,14 @@ export class ElementCapture {
start = async () => {
const {width, height} = this.#wrapped.getSize();
- this.#assertValidSize(width, height);
- syncCanvasSize(this.#wrapped.canvas, width, height, this.#scale);
+ const outputSize = this.#assertValidSize(width, height);
+ await assertCanEncodeCapture(this.#format, outputSize);
+ syncDisplayCanvasSize(
+ this.#wrapped.canvas,
+ width,
+ height,
+ window.devicePixelRatio,
+ );
await this.#recorder.startRecording();
this.#requestPaint();
};
@@ -307,14 +476,12 @@ export class ElementCapture {
};
#assertValidSize = (width: number, height: number) => {
- if (
- width * this.#scale > maxCanvasDimension ||
- height * this.#scale > maxCanvasDimension
- ) {
- throw new Error(
- `The ${Math.round(width)}×${Math.round(height)} selection is too large at ${this.#scale}× scale.`,
- );
- }
+ return validateCaptureSize({
+ width,
+ height,
+ crop: this.#crop,
+ scale: this.#scale,
+ });
};
#requestPaint = () => {
@@ -322,64 +489,7 @@ export class ElementCapture {
};
#resolveCrop = (sourceWidth: number, sourceHeight: number) => {
- if (!this.#crop) {
- return null;
- }
-
- const left = Math.max(0, Math.min(this.#crop.left, sourceWidth - 1));
- const top = Math.max(0, Math.min(this.#crop.top, sourceHeight - 1));
- return {
- left,
- top,
- width: Math.max(1, Math.min(this.#crop.width, sourceWidth - left)),
- height: Math.max(1, Math.min(this.#crop.height, sourceHeight - top)),
- };
- };
-
- #getMediabunnyCrop = (
- sourceWidth: number,
- sourceHeight: number,
- ): CropRectangle | undefined => {
- const crop = this.#resolveCrop(sourceWidth, sourceHeight);
- if (!crop) {
- return undefined;
- }
-
- const left = Math.max(
- 0,
- Math.min(
- Math.round(crop.left * this.#scale),
- this.#wrapped.canvas.width - 1,
- ),
- );
- const top = Math.max(
- 0,
- Math.min(
- Math.round(crop.top * this.#scale),
- this.#wrapped.canvas.height - 1,
- ),
- );
- const right = Math.max(
- left + 1,
- Math.min(
- Math.round((crop.left + crop.width) * this.#scale),
- this.#wrapped.canvas.width,
- ),
- );
- const bottom = Math.max(
- top + 1,
- Math.min(
- Math.round((crop.top + crop.height) * this.#scale),
- this.#wrapped.canvas.height,
- ),
- );
-
- return {
- left,
- top,
- width: right - left,
- height: bottom - top,
- };
+ return resolveCrop(this.#crop, sourceWidth, sourceHeight);
};
#getRecordingRect = () => {
@@ -404,12 +514,56 @@ export class ElementCapture {
}
this.#assertValidSize(width, height);
- syncCanvasSize(this.#wrapped.canvas, width, height, this.#scale);
+ const crop = this.#resolveCrop(width, height) ?? {
+ left: 0,
+ top: 0,
+ width,
+ height,
+ };
+ syncDisplayCanvasSize(
+ this.#wrapped.canvas,
+ width,
+ height,
+ window.devicePixelRatio,
+ );
+ syncCanvasSize(this.#captureCanvas, crop.width, crop.height, this.#scale);
resetCanvas(this.#context, this.#wrapped.canvas);
- this.#context.scale(this.#scale, this.#scale);
+ const displayScaleX = this.#wrapped.canvas.width / width;
+ const displayScaleY = this.#wrapped.canvas.height / height;
+ this.#context.scale(displayScaleX, displayScaleY);
this.#context.drawElementImage!(this.#wrapped.content, 0, 0, width, height);
- this.#recorder.addFrame();
+ const elementImage = this.#wrapped.canvas.captureElementImage!(
+ this.#wrapped.content,
+ );
+ try {
+ resetCanvas(this.#captureContext, this.#captureCanvas);
+ for (const color of this.#matteColors) {
+ this.#captureContext.fillStyle = color;
+ this.#captureContext.fillRect(
+ 0,
+ 0,
+ this.#captureCanvas.width,
+ this.#captureCanvas.height,
+ );
+ }
+
+ this.#captureContext.drawElementImage!(
+ elementImage,
+ crop.left,
+ crop.top,
+ crop.width,
+ crop.height,
+ 0,
+ 0,
+ this.#captureCanvas.width,
+ this.#captureCanvas.height,
+ );
+
+ this.#recorder.addFrame(this.#captureCanvas);
+ } finally {
+ elementImage.close();
+ }
};
#onPaint = () => {
diff --git a/packages/canvas-capture-extension/src/chrome.d.ts b/packages/canvas-capture-extension/src/chrome.d.ts
index a034172c70..e5235b21ed 100644
--- a/packages/canvas-capture-extension/src/chrome.d.ts
+++ b/packages/canvas-capture-extension/src/chrome.d.ts
@@ -1,5 +1,10 @@
type ChromeTab = {
readonly id?: number;
+ readonly windowId?: number;
+};
+
+type ChromeWindow = {
+ readonly id?: number;
};
declare const chrome: {
@@ -14,6 +19,7 @@ declare const chrome: {
listener: (message: unknown) => void | Promise<unknown>,
) => void;
};
+ getURL: (path: string) => string;
sendMessage: (message: unknown) => Promise<unknown>;
};
readonly scripting: {
@@ -24,7 +30,16 @@ declare const chrome: {
};
readonly tabs: {
create: (options: {readonly url: string}) => Promise<unknown>;
+ get: (tabId: number) => Promise<ChromeTab>;
+ query: (options: {
+ readonly active: boolean;
+ readonly currentWindow: boolean;
+ }) => Promise<ChromeTab[]>;
sendMessage: (tabId: number, message: unknown) => Promise<unknown>;
+ update: (
+ tabId: number,
+ options: {readonly active: boolean},
+ ) => Promise<ChromeTab>;
};
readonly storage: {
readonly local: {
@@ -32,5 +47,27 @@ declare const chrome: {
remove: (keys: string | readonly string[]) => Promise<void>;
set: (items: Record<string, unknown>) => Promise<void>;
};
+ readonly session: {
+ get: (key: string) => Promise<Record<string, unknown>>;
+ remove: (key: string) => Promise<void>;
+ set: (items: Record<string, unknown>) => Promise<void>;
+ };
+ };
+ readonly windows: {
+ getCurrent: () => Promise<ChromeWindow>;
+ create: (options: {
+ readonly url: string;
+ readonly type: 'popup';
+ readonly width: number;
+ readonly height: number;
+ readonly focused: boolean;
+ }) => Promise<ChromeWindow>;
+ update: (
+ windowId: number,
+ options: {readonly focused: boolean},
+ ) => Promise<ChromeWindow>;
+ readonly onRemoved: {
+ addListener: (listener: (windowId: number) => void) => void;
+ };
};
};
diff --git a/packages/canvas-capture-extension/src/content.ts b/packages/canvas-capture-extension/src/content.ts
index 19bbcd5a82..bb8b44f8c9 100644
--- a/packages/canvas-capture-extension/src/content.ts
+++ b/packages/canvas-capture-extension/src/content.ts
@@ -1,6 +1,12 @@
-import {type CaptureCrop, ElementCapture} from './capture';
+import {type CaptureCrop, ElementCapture, getCapturePreflight} from './capture';
import {openCaptureInConvert} from './handoff';
-import {isHtmlInCanvasAvailable} from './recorder';
+import {
+ isCaptureControllerRequest,
+ type CaptureFormat,
+ type CaptureControllerRequest,
+ type CaptureControllerState,
+} from './messages';
+import {canEncodeCapture, isHtmlInCanvasAvailable} from './recorder';
import {
findLowestElementContainingRectangle,
makeSelectionRectangle,
@@ -8,21 +14,26 @@ import {
} from './selection';
type ExtensionController = {
- readonly togglePanel: () => void;
+ readonly handleRequest: (
+ request: CaptureControllerRequest,
+ ) => Promise<CaptureControllerState>;
};
type ExtensionWindow = Window & {
__remotionCanvasCapture?: ExtensionController;
};
-const extensionWindow = window as ExtensionWindow;
+type SelectedTarget =
+ | {readonly type: 'whole-page'}
+ | {readonly type: 'page-crop'; readonly crop: CaptureCrop}
+ | {
+ readonly type: 'element-crop';
+ readonly element: Element;
+ readonly elementCrop: CaptureCrop;
+ readonly pageCrop: CaptureCrop;
+ };
-const createButton = (label: string) => {
- const button = document.createElement('button');
- button.type = 'button';
- button.textContent = label;
- return button;
-};
+const extensionWindow = window as ExtensionWindow;
const downloadFile = (file: File) => {
const url = URL.createObjectURL(file);
@@ -44,6 +55,12 @@ const describeElement = (element: Element) => {
return `${element.tagName.toLowerCase()}${id}${className}`;
};
+const getContainerLabel = (format: CaptureFormat) =>
+ format === 'mp4' ? 'MP4' : 'WebM';
+
+const getFormatLabel = (format: CaptureFormat) =>
+ format === 'mp4' ? 'H.264 MP4' : 'VP9 WebM';
+
const getCropRelativeTo = (
selection: SelectionRectangle,
target: DOMRect,
@@ -68,65 +85,6 @@ const createController = (): ExtensionController => {
style.textContent = `
:host { all: initial; }
* { box-sizing: border-box; }
- .panel {
- position: fixed;
- top: 16px;
- right: 16px;
- display: none;
- flex-direction: column;
- gap: 10px;
- width: 292px;
- padding: 14px;
- border: 1px solid rgba(255,255,255,.16);
- border-radius: 12px;
- background: #151515;
- box-shadow: 0 12px 40px rgba(0,0,0,.35);
- color: #f5f5f5;
- font: 13px/1.4 Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
- pointer-events: auto;
- }
- .header { display: flex; align-items: center; justify-content: space-between; }
- .title { font-size: 14px; font-weight: 650; }
- .close {
- width: 26px;
- height: 26px;
- padding: 0;
- border: 0;
- background: transparent;
- color: #aaa;
- font-size: 20px;
- cursor: pointer;
- }
- .row { display: flex; gap: 8px; }
- label { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
- input {
- width: 88px;
- padding: 7px 8px;
- border: 1px solid #454545;
- border-radius: 7px;
- background: #242424;
- color: white;
- font: inherit;
- }
- button {
- min-height: 34px;
- padding: 7px 10px;
- border: 1px solid #454545;
- border-radius: 7px;
- background: #292929;
- color: #f5f5f5;
- font: inherit;
- font-weight: 550;
- cursor: pointer;
- }
- button:hover:not(:disabled) { background: #363636; }
- button:disabled { cursor: default; opacity: .45; }
- .row button { flex: 1; }
- .record { border-color: #ff4d61; background: #db2339; }
- .record:hover:not(:disabled) { background: #ef3349; }
- .record.recording { background: #fafafa; border-color: #fafafa; color: #be1830; }
- .status { min-height: 18px; color: #aaa; overflow-wrap: anywhere; }
- .status.error { color: #ff7b8b; }
.selection-layer {
position: fixed;
inset: 0;
@@ -151,50 +109,6 @@ const createController = (): ExtensionController => {
}
`;
- const panel = document.createElement('div');
- panel.className = 'panel';
- panel.style.display = 'none';
- const header = document.createElement('div');
- header.className = 'header';
- const title = document.createElement('div');
- title.className = 'title';
- title.textContent = 'Remotion Canvas Capture';
- const closeButton = createButton('×');
- closeButton.className = 'close';
- closeButton.title = 'Close';
- header.append(title, closeButton);
-
- const scaleLabel = document.createElement('label');
- scaleLabel.textContent = 'Scale';
- const scaleInput = document.createElement('input');
- scaleInput.type = 'number';
- scaleInput.min = '0.1';
- scaleInput.step = '0.1';
- scaleInput.value = String(Math.max(1, window.devicePixelRatio));
- scaleLabel.appendChild(scaleInput);
-
- const targetRow = document.createElement('div');
- targetRow.className = 'row';
- const selectButton = createButton('Select area');
- const wholePageButton = createButton('Whole page');
- targetRow.append(selectButton, wholePageButton);
-
- const recordButton = createButton('Record');
- recordButton.className = 'record';
- const downloadButton = createButton('Stop and download WebM');
- downloadButton.style.display = 'none';
- const status = document.createElement('div');
- status.className = 'status';
-
- panel.append(
- header,
- scaleLabel,
- targetRow,
- recordButton,
- downloadButton,
- status,
- );
-
const selectionLayer = document.createElement('div');
selectionLayer.className = 'selection-layer';
const selectionBox = document.createElement('div');
@@ -202,44 +116,178 @@ const createController = (): ExtensionController => {
selectionLayer.appendChild(selectionBox);
const highlight = document.createElement('div');
highlight.className = 'highlight';
- shadow.append(style, panel, highlight, selectionLayer);
+ shadow.append(style, highlight, selectionLayer);
- let selectedElement: Element | null = null;
- let selectedCrop: CaptureCrop | null = null;
- let wholePage = false;
+ let selectedTarget: SelectedTarget | null = null;
let capture: ElementCapture | null = null;
let finalizing = false;
- const isSupported = isHtmlInCanvasAvailable();
+ let selecting = false;
+ let scale = Math.max(1, window.devicePixelRatio);
+ let format: CaptureFormat = 'mp4';
+ let includePageBackground = false;
+ let encoderSupport: CaptureControllerState['encoderSupport'] = 'unavailable';
+ let outputSize: CaptureControllerState['outputSize'] = null;
+ let encoderSupportCheckId = 0;
+ let encoderSupportKey: string | null = null;
+ const supported = isHtmlInCanvasAvailable();
+ let status = supported
+ ? 'Choose an area or the whole page.'
+ : 'Enable chrome://flags/#canvas-draw-element, then reload.';
+ let statusIsError = !supported;
let selectionStart: {readonly x: number; readonly y: number} | null = null;
const setStatus = (message: string, error = false) => {
- status.textContent = message;
- status.classList.toggle('error', error);
+ status = message;
+ statusIsError = error;
+ };
+
+ const getTargetLabel = () => {
+ if (!selectedTarget) {
+ return null;
+ }
+
+ if (selectedTarget.type === 'whole-page') {
+ return 'Whole page';
+ }
+
+ if (selectedTarget.type === 'page-crop') {
+ return `Page crop (${Math.round(selectedTarget.crop.width)}×${Math.round(selectedTarget.crop.height)})`;
+ }
+
+ if (includePageBackground) {
+ return `Page crop with background (${Math.round(selectedTarget.pageCrop.width)}×${Math.round(selectedTarget.pageCrop.height)})`;
+ }
+
+ return `${describeElement(selectedTarget.element)} crop (${Math.round(selectedTarget.elementCrop.width)}×${Math.round(selectedTarget.elementCrop.height)})`;
+ };
+
+ const resolveCaptureTarget = () => {
+ if (!selectedTarget) {
+ return null;
+ }
+
+ if (selectedTarget.type === 'whole-page') {
+ return {element: null, wholePage: true, crop: null};
+ }
+
+ if (selectedTarget.type === 'page-crop') {
+ return {element: null, wholePage: true, crop: selectedTarget.crop};
+ }
+
+ if (includePageBackground) {
+ return {
+ element: null,
+ wholePage: true,
+ crop: selectedTarget.pageCrop,
+ };
+ }
+
+ return {
+ element: selectedTarget.element,
+ wholePage: false,
+ crop: selectedTarget.elementCrop,
+ };
+ };
+
+ const refreshEncoderSupport = async () => {
+ const checkId = ++encoderSupportCheckId;
+ if (!supported || !selectedTarget || capture || finalizing || selecting) {
+ if (!selectedTarget) {
+ encoderSupport = 'unavailable';
+ encoderSupportKey = null;
+ outputSize = null;
+ }
+
+ return;
+ }
+
+ const target = resolveCaptureTarget();
+ if (!target) {
+ encoderSupport = 'unavailable';
+ encoderSupportKey = null;
+ outputSize = null;
+ return;
+ }
+
+ try {
+ const preflight = getCapturePreflight({
+ element: target.element,
+ wholePage: target.wholePage,
+ scale,
+ crop: target.crop,
+ });
+ if (checkId !== encoderSupportCheckId) {
+ return;
+ }
+
+ const supportKey = `${format}:${preflight.outputSize.width}x${preflight.outputSize.height}`;
+ outputSize = preflight.outputSize;
+ if (
+ encoderSupportKey === supportKey &&
+ (encoderSupport === 'supported' || encoderSupport === 'unsupported')
+ ) {
+ return;
+ }
+
+ encoderSupport = 'checking';
+ setStatus(
+ `Checking ${getFormatLabel(format)} support at ${outputSize.width}×${outputSize.height}…`,
+ );
+ const canEncode = await canEncodeCapture(format, outputSize);
+ if (checkId !== encoderSupportCheckId) {
+ return;
+ }
+
+ if (canEncode) {
+ encoderSupport = 'supported';
+ encoderSupportKey = supportKey;
+ setStatus(
+ `Ready to record ${getFormatLabel(format)} at ${outputSize.width}×${outputSize.height}.`,
+ );
+ } else {
+ encoderSupport = 'unsupported';
+ encoderSupportKey = supportKey;
+ setStatus(
+ `${getFormatLabel(format)} encoding is not supported at ${outputSize.width}×${outputSize.height} in this browser. Reduce the scale or select a smaller area.`,
+ true,
+ );
+ }
+ } catch (error) {
+ if (checkId !== encoderSupportCheckId) {
+ return;
+ }
+
+ encoderSupport = 'unsupported';
+ encoderSupportKey = null;
+ outputSize = null;
+ setStatus(error instanceof Error ? error.message : String(error), true);
+ }
};
const updateHighlight = () => {
- if (capture) {
+ if (capture || selecting) {
highlight.style.display = 'none';
return;
}
+ const target = resolveCaptureTarget();
let rect: Pick<DOMRect, 'left' | 'top' | 'width' | 'height'> | null = null;
- if (wholePage && selectedCrop) {
+ if (target?.wholePage && target.crop) {
const pageRect = document.body.getBoundingClientRect();
rect = {
- left: pageRect.left + selectedCrop.left,
- top: pageRect.top + selectedCrop.top,
- width: selectedCrop.width,
- height: selectedCrop.height,
+ left: pageRect.left + target.crop.left,
+ top: pageRect.top + target.crop.top,
+ width: target.crop.width,
+ height: target.crop.height,
};
- } else if (selectedElement?.isConnected) {
- const elementRect = selectedElement.getBoundingClientRect();
- rect = selectedCrop
+ } else if (target?.element?.isConnected) {
+ const elementRect = target.element.getBoundingClientRect();
+ rect = target.crop
? {
- left: elementRect.left + selectedCrop.left,
- top: elementRect.top + selectedCrop.top,
- width: selectedCrop.width,
- height: selectedCrop.height,
+ left: elementRect.left + target.crop.left,
+ top: elementRect.top + target.crop.top,
+ width: target.crop.width,
+ height: target.crop.height,
}
: elementRect;
}
@@ -256,29 +304,39 @@ const createController = (): ExtensionController => {
highlight.style.height = `${rect.height}px`;
};
- const updateControls = () => {
- const isRecording = capture !== null;
- scaleInput.disabled = isRecording || finalizing;
- selectButton.disabled = isRecording || finalizing;
- wholePageButton.disabled = isRecording || finalizing;
- closeButton.disabled = finalizing;
- recordButton.disabled =
- !isSupported || finalizing || (!selectedElement && !wholePage);
- recordButton.textContent = isRecording
- ? 'Stop and open in Convert'
- : 'Record';
- recordButton.classList.toggle('recording', isRecording);
- downloadButton.style.display = isRecording ? 'block' : 'none';
- downloadButton.disabled = finalizing;
- updateHighlight();
- };
+ const getState = (): CaptureControllerState => ({
+ supported,
+ selecting,
+ hasTarget: selectedTarget !== null,
+ targetLabel: getTargetLabel(),
+ encoderSupport,
+ outputSize,
+ recording: capture !== null,
+ finalizing,
+ scale,
+ format,
+ includePageBackground,
+ status,
+ error: statusIsError,
+ });
+
+ const cancelSelection = () => {
+ selectionStart = null;
+ selecting = false;
+ selectionLayer.style.display = 'none';
+ selectionBox.style.display = 'none';
+ if (selectedTarget) {
+ encoderSupportKey = null;
+ refreshEncoderSupport().catch(() => undefined);
+ } else {
+ encoderSupportCheckId++;
+ encoderSupport = 'unavailable';
+ encoderSupportKey = null;
+ outputSize = null;
+ setStatus('Choose an area or the whole page.');
+ }
- const selectWholePage = () => {
- selectedElement = null;
- selectedCrop = null;
- wholePage = true;
- setStatus('Target: whole page');
- updateControls();
+ updateHighlight();
};
const finishSelection = (event: PointerEvent) => {
@@ -293,9 +351,9 @@ const createController = (): ExtensionController => {
event.clientY,
);
selectionStart = null;
+ selecting = false;
selectionLayer.style.display = 'none';
selectionBox.style.display = 'none';
- panel.style.display = 'flex';
const target = findLowestElementContainingRectangle({
selection,
@@ -306,36 +364,29 @@ const createController = (): ExtensionController => {
return;
}
+ const pageCrop = getCropRelativeTo(
+ selection,
+ document.body.getBoundingClientRect(),
+ );
if (target === document.body || target === document.documentElement) {
- selectedElement = null;
- wholePage = true;
- selectedCrop = getCropRelativeTo(
- selection,
- document.body.getBoundingClientRect(),
- );
- setStatus(
- `Target: page crop (${Math.round(selectedCrop.width)}×${Math.round(selectedCrop.height)})`,
- );
- updateControls();
- return;
+ selectedTarget = {type: 'page-crop', crop: pageCrop};
+ } else {
+ selectedTarget = {
+ type: 'element-crop',
+ element: target,
+ elementCrop: getCropRelativeTo(
+ selection,
+ target.getBoundingClientRect(),
+ ),
+ pageCrop,
+ };
}
- selectedElement = target;
- selectedCrop = getCropRelativeTo(selection, target.getBoundingClientRect());
- wholePage = false;
- setStatus(
- `Target: ${describeElement(target)} crop (${Math.round(selectedCrop.width)}×${Math.round(selectedCrop.height)})`,
- );
- updateControls();
+ encoderSupportKey = null;
+ refreshEncoderSupport().catch(() => undefined);
+ updateHighlight();
};
- selectButton.addEventListener('click', () => {
- panel.style.display = 'none';
- highlight.style.display = 'none';
- selectionLayer.style.display = 'block';
- setStatus('Drag over the area to capture.');
- });
-
selectionLayer.addEventListener('pointerdown', (event) => {
selectionStart = {x: event.clientX, y: event.clientY};
selectionBox.style.display = 'block';
@@ -360,16 +411,64 @@ const createController = (): ExtensionController => {
});
selectionLayer.addEventListener('pointerup', finishSelection);
- wholePageButton.addEventListener('click', selectWholePage);
+ selectionLayer.addEventListener('pointercancel', cancelSelection);
+ window.addEventListener('scroll', updateHighlight, true);
+ window.addEventListener('resize', () => {
+ updateHighlight();
+ refreshEncoderSupport().catch(() => undefined);
+ });
+ window.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape' && selecting) {
+ cancelSelection();
+ }
+ });
+
+ const setOptions = (
+ nextScale: number,
+ nextFormat: CaptureFormat,
+ nextIncludePageBackground: boolean,
+ ) => {
+ if (!Number.isFinite(nextScale) || nextScale <= 0) {
+ encoderSupportCheckId++;
+ encoderSupport = 'unsupported';
+ encoderSupportKey = null;
+ outputSize = null;
+ setStatus('Scale must be a number greater than 0.', true);
+ return false;
+ }
+
+ if (nextFormat !== 'mp4' && nextFormat !== 'webm') {
+ encoderSupportCheckId++;
+ encoderSupport = 'unsupported';
+ encoderSupportKey = null;
+ outputSize = null;
+ setStatus('Choose MP4 or WebM as the recording format.', true);
+ return false;
+ }
+
+ if (
+ scale !== nextScale ||
+ format !== nextFormat ||
+ includePageBackground !== nextIncludePageBackground
+ ) {
+ encoderSupportKey = null;
+ }
+
+ scale = nextScale;
+ format = nextFormat;
+ includePageBackground = nextIncludePageBackground;
+ updateHighlight();
+ return true;
+ };
const finishRecording = async (destination: 'convert' | 'download') => {
- if (!capture) {
+ if (!capture || finalizing) {
return;
}
finalizing = true;
- setStatus('Finalizing WebM…');
- updateControls();
+ const recordingFormat = format;
+ setStatus(`Finalizing ${getContainerLabel(recordingFormat)}…`);
const currentCapture = capture;
try {
const file = await currentCapture.stop();
@@ -379,103 +478,145 @@ const createController = (): ExtensionController => {
setStatus('Recording opened. Ready to record again.');
} else {
downloadFile(file);
- setStatus('WebM downloaded. Ready to record again.');
+ setStatus(
+ `${getContainerLabel(recordingFormat)} downloaded. Ready to record again.`,
+ );
}
} catch (error) {
setStatus(error instanceof Error ? error.message : String(error), true);
} finally {
capture = null;
finalizing = false;
- updateControls();
+ updateHighlight();
}
};
- recordButton.addEventListener('click', () => {
- const toggle = async () => {
- if (capture) {
- await finishRecording('convert');
- return;
+ return {
+ handleRequest: async (request) => {
+ if (request.command === 'get-state') {
+ await refreshEncoderSupport();
+ return getState();
}
- const scale = scaleInput.valueAsNumber;
- if (!Number.isFinite(scale) || scale <= 0) {
- setStatus('Scale must be a number greater than 0.', true);
- return;
- }
+ if (request.command === 'set-options') {
+ if (!capture && !finalizing) {
+ if (
+ setOptions(
+ request.scale,
+ request.format,
+ request.includePageBackground,
+ )
+ ) {
+ await refreshEncoderSupport();
+ }
+ }
- if (!wholePage && (!selectedElement || !selectedElement.isConnected)) {
- selectedElement = null;
- setStatus(
- 'Select an element again; the previous target was removed.',
- true,
- );
- updateControls();
- return;
+ return getState();
}
- try {
- capture = new ElementCapture({
- element: selectedElement,
- wholePage,
- scale,
- crop: selectedCrop,
- });
- await capture.start();
- setStatus(`Recording at ${scale}× scale…`);
- } catch (error) {
- capture?.restore();
- capture = null;
- setStatus(error instanceof Error ? error.message : String(error), true);
+ if (request.command === 'select-area') {
+ if (!capture && !finalizing) {
+ encoderSupportCheckId++;
+ encoderSupportKey = null;
+ selecting = true;
+ selectionStart = null;
+ selectionBox.style.display = 'none';
+ selectionLayer.style.display = 'block';
+ highlight.style.display = 'none';
+ setStatus('Drag over the area to capture. Press Escape to cancel.');
+ }
+
+ return getState();
}
- updateControls();
- };
+ if (request.command === 'cancel-selection') {
+ if (selecting) {
+ cancelSelection();
+ await refreshEncoderSupport();
+ }
- toggle().catch((error) => {
- setStatus(error instanceof Error ? error.message : String(error), true);
- });
- });
-
- downloadButton.addEventListener('click', () => {
- finishRecording('download').catch((error) => {
- setStatus(error instanceof Error ? error.message : String(error), true);
- });
- });
-
- closeButton.addEventListener('click', () => {
- panel.style.display = 'none';
- highlight.style.display = 'none';
- });
+ return getState();
+ }
- window.addEventListener('scroll', updateHighlight, true);
- window.addEventListener('resize', updateHighlight);
- window.addEventListener('keydown', (event) => {
- if (event.key !== 'Escape' || selectionLayer.style.display === 'none') {
- return;
- }
+ if (request.command === 'select-whole-page') {
+ if (!capture && !finalizing) {
+ if (selecting) {
+ cancelSelection();
+ }
- selectionStart = null;
- selectionLayer.style.display = 'none';
- selectionBox.style.display = 'none';
- panel.style.display = 'flex';
- updateHighlight();
- });
+ selectedTarget = {type: 'whole-page'};
+ encoderSupportKey = null;
+ updateHighlight();
+ await refreshEncoderSupport();
+ }
- if (!isSupported) {
- setStatus('Enable chrome://flags/#canvas-draw-element, then reload.', true);
- }
+ return getState();
+ }
- updateControls();
+ if (request.command === 'start-recording') {
+ if (capture || finalizing || selecting) {
+ return getState();
+ }
+
+ if (
+ !setOptions(
+ request.scale,
+ request.format,
+ request.includePageBackground,
+ )
+ ) {
+ return getState();
+ }
+
+ await refreshEncoderSupport();
+ if (encoderSupport !== 'supported') {
+ return getState();
+ }
+
+ const target = resolveCaptureTarget();
+ if (!target) {
+ setStatus('Choose an area or the whole page first.', true);
+ return getState();
+ }
+
+ if (!target.wholePage && !target.element?.isConnected) {
+ selectedTarget = null;
+ encoderSupport = 'unavailable';
+ encoderSupportKey = null;
+ outputSize = null;
+ setStatus(
+ 'Select an element again; the previous target was removed.',
+ true,
+ );
+ updateHighlight();
+ return getState();
+ }
+
+ try {
+ capture = new ElementCapture({
+ element: target.element,
+ wholePage: target.wholePage,
+ scale,
+ format,
+ crop: target.crop,
+ });
+ await capture.start();
+ setStatus(`Recording ${getFormatLabel(format)} at ${scale}× scale…`);
+ } catch (error) {
+ capture?.restore();
+ capture = null;
+ setStatus(
+ error instanceof Error ? error.message : String(error),
+ true,
+ );
+ }
- return {
- togglePanel: () => {
- const shouldOpen = panel.style.display === 'none';
- panel.style.display = shouldOpen ? 'flex' : 'none';
- if (!shouldOpen) {
- highlight.style.display = 'none';
- } else {
updateHighlight();
+ return getState();
}
+
+ await finishRecording(request.destination);
+ return getState();
},
};
};
@@ -485,12 +626,15 @@ if (!extensionWindow.__remotionCanvasCapture) {
}
chrome.runtime.onMessage.addListener((message) => {
- if (
- typeof message === 'object' &&
- message !== null &&
- 'type' in message &&
- message.type === 'remotion-canvas-capture-toggle'
- ) {
- extensionWindow.__remotionCanvasCapture?.togglePanel();
+ if (!isCaptureControllerRequest(message)) {
+ return;
}
+
+ return extensionWindow.__remotionCanvasCapture
+ ?.handleRequest(message)
+ .catch((error) => {
+ return {
+ message: error instanceof Error ? error.message : String(error),
+ };
+ });
});
diff --git a/packages/canvas-capture-extension/src/messages.ts b/packages/canvas-capture-extension/src/messages.ts
new file mode 100644
index 0000000000..a86cd91e3b
--- /dev/null
+++ b/packages/canvas-capture-extension/src/messages.ts
@@ -0,0 +1,94 @@
+export const captureControllerMessageType =
+ 'remotion-canvas-capture-controller';
+export const capturePopupTargetMessageType =
+ 'remotion-canvas-capture-popup-target';
+
+export type CaptureFormat = 'mp4' | 'webm';
+
+export type CapturePopupTargetMessage = {
+ readonly type: typeof capturePopupTargetMessageType;
+ readonly tabId: number;
+};
+
+export const isCapturePopupTargetMessage = (
+ message: unknown,
+): message is CapturePopupTargetMessage => {
+ return (
+ typeof message === 'object' &&
+ message !== null &&
+ 'type' in message &&
+ message.type === capturePopupTargetMessageType &&
+ 'tabId' in message &&
+ typeof message.tabId === 'number'
+ );
+};
+
+export type CaptureControllerState = {
+ readonly supported: boolean;
+ readonly selecting: boolean;
+ readonly hasTarget: boolean;
+ readonly targetLabel: string | null;
+ readonly encoderSupport:
+ | 'unavailable'
+ | 'checking'
+ | 'supported'
+ | 'unsupported';
+ readonly outputSize: {readonly width: number; readonly height: number} | null;
+ readonly recording: boolean;
+ readonly finalizing: boolean;
+ readonly scale: number;
+ readonly format: CaptureFormat;
+ readonly includePageBackground: boolean;
+ readonly status: string;
+ readonly error: boolean;
+};
+
+export type CaptureControllerRequest =
+ | {
+ readonly type: typeof captureControllerMessageType;
+ readonly command: 'get-state';
+ }
+ | {
+ readonly type: typeof captureControllerMessageType;
+ readonly command: 'set-options';
+ readonly scale: number;
+ readonly format: CaptureFormat;
+ readonly includePageBackground: boolean;
+ }
+ | {
+ readonly type: typeof captureControllerMessageType;
+ readonly command: 'select-area';
+ }
+ | {
+ readonly type: typeof captureControllerMessageType;
+ readonly command: 'cancel-selection';
+ }
+ | {
+ readonly type: typeof captureControllerMessageType;
+ readonly command: 'select-whole-page';
+ }
+ | {
+ readonly type: typeof captureControllerMessageType;
+ readonly command: 'start-recording';
+ readonly scale: number;
+ readonly format: CaptureFormat;
+ readonly includePageBackground: boolean;
+ }
+ | {
+ readonly type: typeof captureControllerMessageType;
+ readonly command: 'stop-recording';
+ readonly destination: 'convert' | 'download';
+ };
+
+export const isCaptureControllerRequest = (
+ message: unknown,
+): message is CaptureControllerRequest => {
+ return (
+ typeof message === 'object' &&
+ message !== null &&
+ 'type' in message &&
+ message.type === captureControllerMessageType &&
+ 'command' in message &&
+ typeof message.command === 'string'
+ );
+};
diff --git a/packages/canvas-capture-extension/src/popup.ts b/packages/canvas-capture-extension/src/popup.ts
new file mode 100644
index 0000000000..4c36f2c2db
--- /dev/null
+++ b/packages/canvas-capture-extension/src/popup.ts
@@ -0,0 +1,308 @@
+import {
+ captureControllerMessageType,
+ isCapturePopupTargetMessage,
+ type CaptureControllerRequest,
+ type CaptureControllerState,
+ type CaptureFormat,
+} from './messages';
+
+const getElement = <T extends HTMLElement>(id: string) => {
+ const element = document.getElementById(id);
+ if (!element) {
+ throw new Error(`Missing popup element: ${id}`);
+ }
+
+ return element as T;
+};
+
+const scaleInput = getElement<HTMLInputElement>('scale');
+const formatInput = getElement<HTMLSelectElement>('format');
+const selectAreaButton = getElement<HTMLButtonElement>('select-area');
+const wholePageButton = getElement<HTMLButtonElement>('whole-page');
+const backgroundInput = getElement<HTMLInputElement>('include-background');
+const recordButton = getElement<HTMLButtonElement>('record');
+const downloadButton = getElement<HTMLButtonElement>('download');
+const target = getElement<HTMLDivElement>('target');
+const status = getElement<HTMLDivElement>('status');
+const getStateRequest: CaptureControllerRequest = {
+ type: captureControllerMessageType,
+ command: 'get-state',
+};
+
+let activeTabId: number | null = null;
+let currentState: CaptureControllerState | null = null;
+let busy = true;
+let pollInFlight = false;
+
+const disableControls = () => {
+ scaleInput.disabled = true;
+ formatInput.disabled = true;
+ selectAreaButton.disabled = true;
+ wholePageButton.disabled = true;
+ backgroundInput.disabled = true;
+ recordButton.disabled = true;
+ downloadButton.hidden = true;
+};
+
+const renderConnecting = () => {
+ currentState = null;
+ busy = true;
+ disableControls();
+ target.textContent = 'Connecting…';
+ status.textContent = 'Connecting to the selected tab…';
+ status.classList.remove('error');
+};
+
+const renderDisconnected = (message: string) => {
+ currentState = null;
+ busy = false;
+ disableControls();
+ target.textContent = 'No capturable page';
+ status.textContent = message;
+ status.classList.add('error');
+};
+
+const render = (state: CaptureControllerState) => {
+ currentState = state;
+ const controlsDisabled = busy || state.finalizing;
+ if (document.activeElement !== scaleInput) {
+ scaleInput.value = String(state.scale);
+ }
+
+ formatInput.value = state.format;
+ backgroundInput.checked = state.includePageBackground;
+ scaleInput.disabled = controlsDisabled || state.recording;
+ formatInput.disabled = controlsDisabled || state.recording;
+ backgroundInput.disabled = controlsDisabled || state.recording;
+ selectAreaButton.disabled = controlsDisabled || state.recording;
+ selectAreaButton.textContent = state.selecting
+ ? 'Cancel selection'
+ : 'Select area';
+ wholePageButton.disabled = controlsDisabled || state.recording;
+ recordButton.disabled =
+ controlsDisabled ||
+ !state.supported ||
+ !state.hasTarget ||
+ state.selecting ||
+ (!state.recording && state.encoderSupport !== 'supported');
+ recordButton.textContent = state.recording
+ ? 'Stop and open in Convert'
+ : 'Record';
+ recordButton.classList.toggle('recording', state.recording);
+ recordButton.title =
+ state.encoderSupport === 'unsupported' ? state.status : '';
+ downloadButton.hidden = !state.recording;
+ downloadButton.disabled = controlsDisabled;
+ downloadButton.textContent = `Stop and download ${state.format === 'mp4' ? 'MP4' : 'WebM'}`;
+ target.textContent = state.targetLabel
+ ? `${state.targetLabel}${state.outputSize ? ` · ${state.outputSize.width}×${state.outputSize.height} output` : ''}`
+ : 'No target selected';
+ status.textContent = state.status;
+ status.classList.toggle('error', state.error);
+};
+
+const sendRequestToTab = async (
+ tabId: number,
+ request: CaptureControllerRequest,
+) => {
+ const response = (await chrome.tabs.sendMessage(tabId, request)) as
+ | CaptureControllerState
+ | {readonly message: string};
+ if ('message' in response) {
+ throw new Error(response.message);
+ }
+
+ return response;
+};
+
+const runCommand = async (request: CaptureControllerRequest) => {
+ const tabId = activeTabId;
+ if (tabId === null) {
+ renderDisconnected('No target tab is available.');
+ return null;
+ }
+
+ busy = true;
+ if (currentState) {
+ render(currentState);
+ }
+
+ try {
+ const nextState = await sendRequestToTab(tabId, request);
+ if (activeTabId !== tabId) {
+ return null;
+ }
+
+ busy = false;
+ render(nextState);
+ return nextState;
+ } catch (error) {
+ if (activeTabId === tabId) {
+ renderDisconnected(
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+
+ return null;
+ }
+};
+
+const getOptions = () => ({
+ scale: scaleInput.valueAsNumber,
+ format: formatInput.value as CaptureFormat,
+ includePageBackground: backgroundInput.checked,
+});
+
+const focusTargetPage = async () => {
+ const tabId = activeTabId;
+ if (tabId === null) {
+ return;
+ }
+
+ const tab = await chrome.tabs.get(tabId);
+ await chrome.tabs.update(tabId, {active: true});
+ if (tab.windowId !== undefined) {
+ await chrome.windows.update(tab.windowId, {focused: true});
+ }
+};
+
+const focusRecorderWindow = async () => {
+ const recorderWindow = await chrome.windows.getCurrent();
+ if (recorderWindow.id !== undefined) {
+ await chrome.windows.update(recorderWindow.id, {focused: true});
+ }
+};
+
+selectAreaButton.addEventListener('click', () => {
+ const command = currentState?.selecting ? 'cancel-selection' : 'select-area';
+ runCommand({type: captureControllerMessageType, command})
+ .then((state) => {
+ if (state?.selecting) {
+ return focusTargetPage();
+ }
+ })
+ .catch(() => undefined);
+});
+
+wholePageButton.addEventListener('click', () => {
+ runCommand({
+ type: captureControllerMessageType,
+ command: 'select-whole-page',
+ }).catch(() => undefined);
+});
+
+const updateOptions = () => {
+ const options = getOptions();
+ runCommand({
+ type: captureControllerMessageType,
+ command: 'set-options',
+ ...options,
+ }).catch(() => undefined);
+};
+
+scaleInput.addEventListener('change', updateOptions);
+formatInput.addEventListener('change', updateOptions);
+backgroundInput.addEventListener('change', updateOptions);
+
+recordButton.addEventListener('click', () => {
+ if (currentState?.recording) {
+ runCommand({
+ type: captureControllerMessageType,
+ command: 'stop-recording',
+ destination: 'convert',
+ }).catch(() => undefined);
+ return;
+ }
+
+ runCommand({
+ type: captureControllerMessageType,
+ command: 'start-recording',
+ ...getOptions(),
+ }).catch(() => undefined);
+});
+
+downloadButton.addEventListener('click', () => {
+ runCommand({
+ type: captureControllerMessageType,
+ command: 'stop-recording',
+ destination: 'download',
+ }).catch(() => undefined);
+});
+
+const connectToTab = async (tabId: number) => {
+ activeTabId = tabId;
+ renderConnecting();
+ try {
+ let state: CaptureControllerState;
+ try {
+ state = await sendRequestToTab(tabId, getStateRequest);
+ } catch {
+ await chrome.scripting.executeScript({
+ target: {tabId},
+ files: ['content.js'],
+ });
+ state = await sendRequestToTab(tabId, getStateRequest);
+ }
+
+ if (activeTabId !== tabId) {
+ return;
+ }
+
+ busy = false;
+ render(state);
+ } catch {
+ if (activeTabId === tabId) {
+ renderDisconnected(
+ 'This page cannot be captured. Open a regular webpage and click the extension icon again.',
+ );
+ }
+ }
+};
+
+chrome.runtime.onMessage.addListener((message) => {
+ if (!isCapturePopupTargetMessage(message)) {
+ return;
+ }
+
+ return connectToTab(message.tabId);
+});
+
+setInterval(() => {
+ const tabId = activeTabId;
+ if (tabId === null || busy || pollInFlight || currentState === null) {
+ return;
+ }
+
+ pollInFlight = true;
+ sendRequestToTab(tabId, getStateRequest)
+ .then((state) => {
+ if (activeTabId === tabId && !busy) {
+ const selectionFinished = currentState?.selecting && !state.selecting;
+ render(state);
+ if (selectionFinished) {
+ focusRecorderWindow().catch(() => undefined);
+ }
+ }
+ })
+ .catch((error) => {
+ if (activeTabId === tabId) {
+ renderDisconnected(
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+ })
+ .finally(() => {
+ pollInFlight = false;
+ });
+}, 500);
+
+const initialTabId = Number(
+ new URL(window.location.href).searchParams.get('tabId'),
+);
+if (Number.isInteger(initialTabId) && initialTabId >= 0) {
+ connectToTab(initialTabId).catch(() => undefined);
+} else {
+ renderDisconnected(
+ 'No target tab was provided. Click the extension icon on the page you want to capture.',
+ );
+}
diff --git a/packages/canvas-capture-extension/src/recorder.ts b/packages/canvas-capture-extension/src/recorder.ts
index ec253f709b..c39e3d790f 100644
--- a/packages/canvas-capture-extension/src/recorder.ts
+++ b/packages/canvas-capture-extension/src/recorder.ts
@@ -1,11 +1,8 @@
-import type {CropRectangle} from 'mediabunny';
-
-type CanvasVideoSource = {
- add: (
- timestamp: number,
- duration: number,
- encodeOptions?: VideoEncoderEncodeOptions,
- ) => Promise<void>;
+import type {Quality} from 'mediabunny';
+import type {CaptureFormat} from './messages';
+
+type VideoFrameSource = {
+ add: (frame: VideoFrame) => Promise<void>;
close: () => void;
};
@@ -58,44 +55,75 @@ type CaptureMetadata = {
type RecordingState = {
readonly output: RecordingOutput;
readonly target: RecordingTarget;
- readonly source: CanvasVideoSource;
+ readonly source: VideoFrameSource;
readonly startedAt: number;
readonly mouseMovements: MouseMovement[];
readonly pointerClicks: PointerClick[];
lastTimestampInSeconds: number | null;
lastFramePromise: Promise<void>;
+ pendingFrame: VideoFrame | null;
+ isEncodingFrame: boolean;
+ hasEncodingError: boolean;
+ encodingError: unknown;
frameCount: number;
captureMetadata: CaptureMetadata | null;
isFinalizing: boolean;
};
-export type HtmlInCanvasElement = HTMLCanvasElement & {
- layoutSubtree?: boolean;
- requestPaint?: () => void;
+export type HtmlInCanvasElementImage = {
+ readonly width: number;
+ readonly height: number;
+ close: () => void;
};
-export type HtmlInCanvasRenderingContext2D = CanvasRenderingContext2D & {
- drawElementImage?: (
- element: Element,
+type DrawElementImageSource = Element | HtmlInCanvasElementImage;
+
+type DrawElementImage = {
+ (
+ element: DrawElementImageSource,
dx: number,
dy: number,
dWidth?: number,
dHeight?: number,
- ) => DOMMatrix;
+ ): DOMMatrix;
+ (
+ element: DrawElementImageSource,
+ sx: number,
+ sy: number,
+ sWidth: number,
+ sHeight: number,
+ dx: number,
+ dy: number,
+ dWidth?: number,
+ dHeight?: number,
+ ): DOMMatrix;
+};
+
+export type HtmlInCanvasElement = HTMLCanvasElement & {
+ layoutSubtree?: boolean;
+ requestPaint?: () => void;
+ captureElementImage?: (element: Element) => HtmlInCanvasElementImage;
+};
+
+export type HtmlInCanvasRenderingContext2D = CanvasRenderingContext2D & {
+ drawElementImage?: DrawElementImage;
reset?: () => void;
};
+export type HtmlInCanvasOffscreenRenderingContext2D =
+ OffscreenCanvasRenderingContext2D & {
+ drawElementImage?: DrawElementImage;
+ reset?: () => void;
+ };
+
type CanvasCaptureRecorderOptions = {
- readonly canvas: HTMLCanvasElement;
- readonly crop?: CropRectangle;
+ readonly format: CaptureFormat;
readonly getContentRect: () => DOMRect;
readonly getDensity: () => number;
readonly getFilename: () => string;
};
const fallbackFrameDurationInSeconds = 1 / 60;
-const recordingVideoBitrate = 120_000_000;
-const recordingKeyFrameIntervalInSeconds = 0.5;
const CAPTURE_METADATA_TAG_KEY = 'REMOTION_CAPTURE_DATA';
@@ -108,16 +136,27 @@ export const isHtmlInCanvasAvailable = () => {
const context = canvas.getContext(
'2d',
) as HtmlInCanvasRenderingContext2D | null;
+ const captureContext =
+ typeof OffscreenCanvas === 'undefined'
+ ? null
+ : (new OffscreenCanvas(2, 2).getContext(
+ '2d',
+ ) as HtmlInCanvasOffscreenRenderingContext2D | null);
return (
typeof canvas.requestPaint === 'function' &&
- typeof context?.drawElementImage === 'function'
+ typeof canvas.captureElementImage === 'function' &&
+ typeof context?.drawElementImage === 'function' &&
+ typeof captureContext?.drawElementImage === 'function' &&
+ typeof VideoFrame !== 'undefined'
);
};
export const resetCanvas = (
- context: HtmlInCanvasRenderingContext2D,
- canvas: HTMLCanvasElement,
+ context:
+ | HtmlInCanvasRenderingContext2D
+ | HtmlInCanvasOffscreenRenderingContext2D,
+ canvas: HTMLCanvasElement | OffscreenCanvas,
) => {
if (typeof context.reset === 'function') {
context.reset();
@@ -128,20 +167,54 @@ export const resetCanvas = (
context.clearRect(0, 0, canvas.width, canvas.height);
};
-const roundUpToEven = (value: number) => {
- const rounded = Math.max(2, Math.ceil(value));
- return rounded % 2 === 0 ? rounded : rounded + 1;
-};
+const roundDownToEven = (value: number) =>
+ Math.max(2, Math.floor(value / 2) * 2);
-export const syncCanvasSize = (
- canvas: HTMLCanvasElement,
+export const getScaledCanvasSize = (
width: number,
height: number,
density: number,
+) => ({
+ width: roundDownToEven(width * density),
+ height: roundDownToEven(height * density),
+});
+
+const getVideoEncodingOptions = (bitrate: Quality) => ({
+ bitrate,
+ latencyMode: 'realtime' as const,
+});
+
+export const canEncodeCapture = async (
+ format: CaptureFormat,
+ {width, height}: {readonly width: number; readonly height: number},
) => {
- const scaledWidth = roundUpToEven(width * density);
- const scaledHeight = roundUpToEven(height * density);
+ const {canEncodeVideo, QUALITY_HIGH} = await import('mediabunny');
+ return canEncodeVideo(format === 'mp4' ? 'avc' : 'vp9', {
+ width,
+ height,
+ ...getVideoEncodingOptions(QUALITY_HIGH),
+ });
+};
+
+export const assertCanEncodeCapture = async (
+ format: CaptureFormat,
+ size: {readonly width: number; readonly height: number},
+) => {
+ if (await canEncodeCapture(format, size)) {
+ return;
+ }
+
+ const label = format === 'mp4' ? 'H.264 MP4' : 'VP9 WebM';
+ throw new Error(
+ `${label} encoding is not supported at ${size.width}×${size.height} in this browser. Reduce the scale or select a smaller area.`,
+ );
+};
+const setCanvasSize = (
+ canvas: HTMLCanvasElement | OffscreenCanvas,
+ scaledWidth: number,
+ scaledHeight: number,
+) => {
if (canvas.width !== scaledWidth) {
canvas.width = scaledWidth;
}
@@ -151,6 +224,29 @@ export const syncCanvasSize = (
}
};
+export const syncCanvasSize = (
+ canvas: HTMLCanvasElement | OffscreenCanvas,
+ width: number,
+ height: number,
+ density: number,
+) => {
+ const size = getScaledCanvasSize(width, height, density);
+ setCanvasSize(canvas, size.width, size.height);
+};
+
+export const syncDisplayCanvasSize = (
+ canvas: HTMLCanvasElement,
+ width: number,
+ height: number,
+ density: number,
+) => {
+ setCanvasSize(
+ canvas,
+ Math.max(1, Math.round(width * density)),
+ Math.max(1, Math.round(height * density)),
+ );
+};
+
const getCursorForElement = (element: Element | null): string => {
let current: Element | null = element;
@@ -166,7 +262,7 @@ const getCursorForElement = (element: Element | null): string => {
return 'auto';
};
-const addFrame = (recording: RecordingState) => {
+const addFrame = (recording: RecordingState, canvas: OffscreenCanvas) => {
const elapsedInSeconds = Math.max(
0,
(performance.now() - recording.startedAt) / 1000,
@@ -180,24 +276,54 @@ const addFrame = (recording: RecordingState) => {
fallbackFrameDurationInSeconds,
elapsedInSeconds - recording.lastTimestampInSeconds,
);
- const keyFrame = recording.lastTimestampInSeconds === null;
-
recording.lastTimestampInSeconds = timestampInSeconds;
- recording.lastFramePromise = recording.lastFramePromise.then(async () => {
- await recording.source.add(timestampInSeconds, durationInSeconds, {
- keyFrame,
- });
- recording.frameCount++;
+ const frame = new VideoFrame(canvas, {
+ timestamp: Math.round(timestampInSeconds * 1_000_000),
+ duration: Math.round(durationInSeconds * 1_000_000),
});
+
+ if (recording.hasEncodingError) {
+ frame.close();
+ return;
+ }
+
+ recording.pendingFrame?.close();
+ recording.pendingFrame = frame;
+ if (recording.isEncodingFrame) {
+ return;
+ }
+
+ recording.isEncodingFrame = true;
+ recording.lastFramePromise = (async () => {
+ try {
+ while (recording.pendingFrame) {
+ const frameToEncode = recording.pendingFrame;
+ recording.pendingFrame = null;
+ await recording.source.add(frameToEncode);
+ recording.frameCount++;
+ }
+ } catch (error) {
+ recording.hasEncodingError = true;
+ recording.encodingError = error;
+ recording.pendingFrame?.close();
+ recording.pendingFrame = null;
+ throw error;
+ } finally {
+ recording.isEncodingFrame = false;
+ }
+ })();
recording.lastFramePromise.catch(() => undefined);
};
const finalizeRecording = async (
recording: RecordingState,
filename: string,
+ format: CaptureFormat,
): Promise<File> => {
- addFrame(recording);
await recording.lastFramePromise;
+ if (recording.hasEncodingError) {
+ throw recording.encodingError;
+ }
if (recording.frameCount === 0) {
throw new Error('No frames were added to the canvas recording.');
@@ -224,6 +350,7 @@ const finalizeRecording = async (
BufferTarget,
Conversion,
Input,
+ Mp4OutputFormat,
Output,
WebMOutputFormat,
} = await import('mediabunny');
@@ -233,7 +360,10 @@ const finalizeRecording = async (
});
const remuxTarget = new BufferTarget();
const remuxOutput = new Output({
- format: new WebMOutputFormat(),
+ format:
+ format === 'mp4'
+ ? new Mp4OutputFormat({metadataFormat: 'mdta'})
+ : new WebMOutputFormat(),
target: remuxTarget,
});
const conversion = await Conversion.init({
@@ -250,7 +380,9 @@ const finalizeRecording = async (
throw new Error('Mediabunny remux did not return an output buffer.');
}
- return new File([remuxTarget.buffer], filename, {type: 'video/webm'});
+ return new File([remuxTarget.buffer], filename, {
+ type: format === 'mp4' ? 'video/mp4' : 'video/webm',
+ });
};
export class CanvasCaptureRecorder {
@@ -282,22 +414,41 @@ export class CanvasCaptureRecorder {
throw new Error('Canvas capture scale must be greater than 0.');
}
- const {BufferTarget, CanvasSource, Output, WebMOutputFormat} =
- await import('mediabunny');
+ const {
+ BufferTarget,
+ Mp4OutputFormat,
+ Output,
+ QUALITY_HIGH,
+ VideoSample,
+ VideoSampleSource,
+ WebMOutputFormat,
+ } = await import('mediabunny');
const target = new BufferTarget();
const output = new Output({
- format: new WebMOutputFormat(),
+ format:
+ this.#options.format === 'mp4'
+ ? new Mp4OutputFormat()
+ : new WebMOutputFormat(),
target,
});
- const source = new CanvasSource(this.#options.canvas, {
- codec: 'vp9',
- bitrate: recordingVideoBitrate,
- latencyMode: 'realtime',
- keyFrameInterval: recordingKeyFrameIntervalInSeconds,
- transform: this.#options.crop ? {crop: this.#options.crop} : undefined,
+ const videoSampleSource = new VideoSampleSource({
+ codec: this.#options.format === 'mp4' ? 'avc' : 'vp9',
+ ...getVideoEncodingOptions(QUALITY_HIGH),
});
+ const source: VideoFrameSource = {
+ add: async (frame) => {
+ const sample = new VideoSample(frame);
+ try {
+ await videoSampleSource.add(sample);
+ } finally {
+ sample.close();
+ frame.close();
+ }
+ },
+ close: () => videoSampleSource.close(),
+ };
- output.addVideoTrack(source);
+ output.addVideoTrack(videoSampleSource);
await output.start();
this.#recording = {
@@ -309,6 +460,10 @@ export class CanvasCaptureRecorder {
pointerClicks: [],
lastTimestampInSeconds: null,
lastFramePromise: Promise.resolve(),
+ pendingFrame: null,
+ isEncodingFrame: false,
+ hasEncodingError: false,
+ encodingError: undefined,
frameCount: 0,
captureMetadata: null,
isFinalizing: false,
@@ -323,7 +478,11 @@ export class CanvasCaptureRecorder {
recording.isFinalizing = true;
try {
- return await finalizeRecording(recording, this.#options.getFilename());
+ return await finalizeRecording(
+ recording,
+ this.#options.getFilename(),
+ this.#options.format,
+ );
} catch (err) {
await recording.output.cancel().catch(() => undefined);
throw err;
@@ -345,7 +504,7 @@ export class CanvasCaptureRecorder {
await this.#recordingAction;
};
- addFrame = () => {
+ addFrame = (canvas: OffscreenCanvas) => {
const recording = this.#recording;
if (!recording || recording.isFinalizing) {
return;
@@ -362,8 +521,8 @@ export class CanvasCaptureRecorder {
height: rect.height,
},
canvasSize: {
- width: this.#options.crop?.width ?? this.#options.canvas.width,
- height: this.#options.crop?.height ?? this.#options.canvas.height,
+ width: canvas.width,
+ height: canvas.height,
},
viewport: {
width: window.innerWidth,
@@ -372,7 +531,7 @@ export class CanvasCaptureRecorder {
scrollY: window.scrollY,
},
};
- addFrame(recording);
+ addFrame(recording, canvas);
};
dispose = () => {
@@ -391,6 +550,8 @@ export class CanvasCaptureRecorder {
}
recording.isFinalizing = true;
+ recording.pendingFrame?.close();
+ recording.pendingFrame = null;
recording.output.cancel().catch(() => undefined);
this.#recording = null;
};