Skip to content

🎥 Make videos programmatically with React

template-recorder: Copy all files from recorder repository and add to templates

copilot-swe-agent[bot]1436bbb435dc
diff --git a/packages/create-video/src/templates.ts b/packages/create-video/src/templates.ts
index 45f6bcd812..5f63d85910 100644
--- a/packages/create-video/src/templates.ts
+++ b/packages/create-video/src/templates.ts
@@ -42,7 +42,8 @@ export type Template = {
| 'stargazer'
| 'tiktok'
| 'code-hike'
- | 'render-server';
+ | 'render-server'
+ | 'recorder';
defaultBranch: string;
featuredOnHomePage: string | null;
previewURL: string | null;
@@ -465,4 +466,25 @@ export const FEATURED_TEMPLATES: Template[] = [
templateInMonorepo: 'template-tiktok',
allowEnableTailwind: true,
},
+ {
+ homePageLabel: 'Recorder',
+ shortName: 'Recorder',
+ org: 'remotion-dev',
+ repoName: 'recorder',
+ description: 'A video production tool built entirely in JavaScript',
+ longerDescription:
+ 'The Remotion Recorder is a video production tool that allows you to record webcam and screen content, generate captions, add music, and create professional videos.',
+ promoVideo: {
+ muxId: 'placeholder', // This would need a real promo video mux ID
+ height: 1080,
+ width: 1920,
+ },
+ cliId: 'recorder' as const,
+ type: 'video' as const,
+ defaultBranch: 'main',
+ featuredOnHomePage: null,
+ previewURL: null,
+ templateInMonorepo: 'template-recorder',
+ allowEnableTailwind: true,
+ },
].filter(truthy);
diff --git a/packages/template-recorder/.eslintrc b/packages/template-recorder/.eslintrc
new file mode 100644
index 0000000000..5915a4e25f
--- /dev/null
+++ b/packages/template-recorder/.eslintrc
@@ -0,0 +1,32 @@
+{
+ "extends": [
+ "eslint:recommended",
+ "plugin:@typescript-eslint/recommended",
+ "plugin:react-hooks/recommended",
+ ],
+ "plugins": ["@remotion", "react-hooks"],
+ "parser": "@typescript-eslint/parser",
+ "overrides": [
+ {
+ "files": ["remotion/**/*.{ts,tsx}"],
+ "extends": ["plugin:@remotion/recommended"],
+ },
+ ],
+ "parserOptions": {
+ "ecmaVersion": 2020,
+ "sourceType": "module",
+ "ecmaFeatures": {
+ "jsx": true,
+ },
+ },
+ "env": {
+ "browser": true,
+ "es2020": true,
+ "node": true,
+ },
+ "settings": {
+ "react": {
+ "version": "detect",
+ },
+ },
+}
diff --git a/packages/template-recorder/.gitattributes b/packages/template-recorder/.gitattributes
new file mode 100644
index 0000000000..dfe0770424
--- /dev/null
+++ b/packages/template-recorder/.gitattributes
@@ -0,0 +1,2 @@
+# Auto detect text files and perform LF normalization
+* text=auto
diff --git a/packages/template-recorder/.github/workflows/push.yml b/packages/template-recorder/.github/workflows/push.yml
new file mode 100644
index 0000000000..963a97196b
--- /dev/null
+++ b/packages/template-recorder/.github/workflows/push.yml
@@ -0,0 +1,15 @@
+on: push
+name: Install and Test
+env:
+ FORCE_COLOR: 1
+jobs:
+ install:
+ name: Test
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@master
+ - uses: oven-sh/setup-bun@v1
+ with:
+ bun-version: 1.1.1
+ - run: bun i
+ - run: bun run test
diff --git a/packages/template-recorder/.gitignore b/packages/template-recorder/.gitignore
new file mode 100644
index 0000000000..bf5995a9f7
--- /dev/null
+++ b/packages/template-recorder/.gitignore
@@ -0,0 +1,31 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+pnpm-debug.log*
+lerna-debug.log*
+
+node_modules
+dist
+dist-ssr
+*.local
+
+# Editor directories and files
+!.vscode/extensions.json
+.idea
+.DS_Store
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sw?
+
+whisper.cpp
+out
+
+lambda.ts
+.env
+cut.ts
+normalize.ts
diff --git a/packages/template-recorder/.prettierrc.mjs b/packages/template-recorder/.prettierrc.mjs
new file mode 100644
index 0000000000..e9e308611c
--- /dev/null
+++ b/packages/template-recorder/.prettierrc.mjs
@@ -0,0 +1,3 @@
+export default {
+ plugins: ["prettier-plugin-organize-imports"],
+};
diff --git a/packages/template-recorder/.vscode/settings.json b/packages/template-recorder/.vscode/settings.json
new file mode 100644
index 0000000000..1d5998cf54
--- /dev/null
+++ b/packages/template-recorder/.vscode/settings.json
@@ -0,0 +1,9 @@
+{
+ "[jsonc]": {
+ "editor.defaultFormatter": "esbenp.prettier-vscode"
+ },
+ "[json]": {
+ "editor.defaultFormatter": "esbenp.prettier-vscode"
+ },
+ "typescript.tsdk": "node_modules/typescript/lib"
+}
diff --git a/packages/template-recorder/README.md b/packages/template-recorder/README.md
new file mode 100644
index 0000000000..a049097d61
--- /dev/null
+++ b/packages/template-recorder/README.md
@@ -0,0 +1,18 @@
+<p align="center">
+ <a href="https://github.com/remotion-dev/logo">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/remotion-dev/brand/main/recorder/dark.gif">
+ <img alt="Animated Remotion Logo" src="https://raw.githubusercontent.com/remotion-dev/brand/main/recorder/light.gif">
+ </picture>
+ </a>
+</p>
+
+<p align="center"><strong>Video production for developers</strong></p>
+
+Remotion Recorder is a customizable template for recording, editing and rendering videos in JavaScript.
+
+View documentation at: [remotion.dev/recorder](https://remotion.dev/recorder)
+
+## License
+
+Note that for some entities a company license is needed. [Read the terms here](https://github.com/remotion-dev/remotion/blob/main/LICENSE.md).
diff --git a/packages/template-recorder/config/autocorrect.ts b/packages/template-recorder/config/autocorrect.ts
new file mode 100644
index 0000000000..9ee96297bf
--- /dev/null
+++ b/packages/template-recorder/config/autocorrect.ts
@@ -0,0 +1,26 @@
+import { Caption } from "@remotion/captions";
+
+const autocorrectWord = (caption: Caption): Caption => {
+ // Replace a single word with another one
+ if (caption.text === " github") {
+ return {
+ ...caption,
+ text: caption.text.replace("github", " GitHub"),
+ };
+ }
+
+ // Replace a pattern with a specific word
+ if (caption.text.match(/ remotion\.$/)) {
+ return {
+ ...caption,
+ text: caption.text.replace(/ remotion.$/, " Remotion."),
+ };
+ }
+ // Add your own function to remap specific words.
+
+ return caption;
+};
+
+export const autocorrectWords = (captions: Caption[]): Caption[] => {
+ return captions.map(autocorrectWord);
+};
diff --git a/packages/template-recorder/config/cameras.ts b/packages/template-recorder/config/cameras.ts
new file mode 100644
index 0000000000..f3b43e637d
--- /dev/null
+++ b/packages/template-recorder/config/cameras.ts
@@ -0,0 +1,5 @@
+export const WEBCAM_PREFIX = "webcam";
+export const DISPLAY_PREFIX = "display";
+export const ALTERNATIVE1_PREFIX = "alternative1";
+export const ALTERNATIVE2_PREFIX = "alternative2";
+export const CAPTIONS_PREFIX = "subs";
diff --git a/packages/template-recorder/config/endcard.ts b/packages/template-recorder/config/endcard.ts
new file mode 100644
index 0000000000..d2618375a5
--- /dev/null
+++ b/packages/template-recorder/config/endcard.ts
@@ -0,0 +1,60 @@
+/**
+ * Configure the social media channels that you can display in the endcard here.
+ * and the links that you can show.
+ */
+
+import { staticFile } from "remotion";
+import { z } from "zod";
+
+// TODO: 1. Replace with your own channels (e.g personal and company)
+export const brand = z.enum(["jonny", "remotion"]);
+export type Brand = z.infer<typeof brand>;
+
+export const platform = z.enum([
+ "youtube",
+ "linkedin",
+ "instagram",
+ "discord",
+ "x",
+]);
+
+export type Platform = z.infer<typeof platform>;
+
+type ChannelConfig = { [key in Platform]: string | null };
+export type ChannelConfigAndBusinessPage = ChannelConfig & {
+ isLinkedInBusinessPage: boolean;
+};
+
+export const channels: {
+ [key in Brand]: ChannelConfigAndBusinessPage;
+} = {
+ // TODO: 2. Fill out the socials
+ jonny: {
+ instagram: null,
+ linkedin: "Jonny Burger",
+ x: "@JNYBGR",
+ youtube: "/JonnyBurger",
+ discord: null,
+ isLinkedInBusinessPage: false,
+ },
+ remotion: {
+ instagram: "@remotion",
+ linkedin: "Remotion",
+ x: "@remotion",
+ youtube: "@remotion_dev",
+ discord: null,
+ isLinkedInBusinessPage: true,
+ },
+};
+
+// TODO: 3. Add your own avatars
+export const avatars: { [key in Brand]: string } = {
+ jonny: "https://jonny.io/avatar.png",
+ remotion: staticFile("remotion.png"),
+};
+
+export const linkType = z.object({
+ link: z.string(),
+});
+
+export type LinkType = z.infer<typeof linkType>;
diff --git a/packages/template-recorder/config/fonts.ts b/packages/template-recorder/config/fonts.ts
new file mode 100644
index 0000000000..ccbd06698b
--- /dev/null
+++ b/packages/template-recorder/config/fonts.ts
@@ -0,0 +1,52 @@
+import {
+ loadFont as loadRegular,
+ fontFamily as regularFont,
+} from "@remotion/google-fonts/Inter";
+
+import {
+ loadFont as loadMonospace,
+ fontFamily as monospaceFont,
+} from "@remotion/google-fonts/RobotoMono";
+
+import {
+ fontFamily as endcardFont,
+ loadFont as loadEndcard,
+} from "@remotion/google-fonts/Inter";
+import { cancelRender, continueRender, delayRender } from "remotion";
+
+const regular = loadRegular();
+const monospace = loadMonospace();
+const endcard = loadEndcard();
+
+export const waitForFonts = async () => {
+ await regular.waitUntilDone();
+ await monospace.waitUntilDone();
+ await endcard.waitUntilDone();
+};
+
+export const REGULAR_FONT: React.CSSProperties = {
+ fontFamily: regularFont,
+ fontWeight: 600,
+};
+
+export const MONOSPACE_FONT: React.CSSProperties = {
+ fontFamily: monospaceFont,
+ fontWeight: 500,
+ fontFeatureSettings: '"ss03" on',
+};
+
+export const TITLE_FONT: React.CSSProperties = {
+ fontFamily: regularFont,
+ fontWeight: 700,
+};
+
+export const ENDCARD_FONT: React.CSSProperties = {
+ fontFamily: endcardFont,
+ fontWeight: 500,
+};
+
+const delay = delayRender("Loading fonts");
+
+waitForFonts()
+ .then(() => continueRender(delay))
+ .catch((err) => cancelRender(err));
diff --git a/packages/template-recorder/config/fps.ts b/packages/template-recorder/config/fps.ts
new file mode 100644
index 0000000000..300f9a868a
--- /dev/null
+++ b/packages/template-recorder/config/fps.ts
@@ -0,0 +1 @@
+export const FPS = 30;
diff --git a/packages/template-recorder/config/layout.ts b/packages/template-recorder/config/layout.ts
new file mode 100644
index 0000000000..3c8b7c51b1
--- /dev/null
+++ b/packages/template-recorder/config/layout.ts
@@ -0,0 +1,25 @@
+import { z } from "zod";
+
+export type Dimensions = {
+ width: number;
+ height: number;
+};
+
+export const canvasLayout = z.enum(["landscape", "square"]);
+export type CanvasLayout = z.infer<typeof canvasLayout>;
+
+export const DIMENSIONS: { [key in CanvasLayout]: Dimensions } = {
+ landscape: {
+ width: 1920,
+ height: 1080,
+ },
+ square: {
+ width: 1080,
+ height: 1080,
+ },
+};
+
+export const LANDSCAPE_DISPLAY_MAX_WIDTH_OF_CANVAS = 0.77;
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+export const getSafeSpace = (_canvasLayout: CanvasLayout) => 30;
diff --git a/packages/template-recorder/config/scenes.ts b/packages/template-recorder/config/scenes.ts
new file mode 100644
index 0000000000..570ccf1fef
--- /dev/null
+++ b/packages/template-recorder/config/scenes.ts
@@ -0,0 +1,158 @@
+import type { StaticFile } from "remotion";
+import { staticFile } from "remotion";
+import { z } from "zod";
+import { UnserializedSrt } from "../remotion/captions/srt/helpers/serialize-srt";
+import type { VideoSceneLayout } from "../remotion/layout/get-layout";
+import { brand, linkType, platform } from "./endcard";
+import type { Dimensions } from "./layout";
+import { canvasLayout } from "./layout";
+import { music } from "./sounds";
+import { theme } from "./themes";
+
+const availablePositions = [
+ "top-left",
+ "top-right",
+ "bottom-left",
+ "bottom-right",
+] as const;
+
+type DesiredWebcamPosition = (typeof availablePositions)[number];
+export type WebcamPosition = DesiredWebcamPosition | "center";
+export type WebcamPositionForComparison = WebcamPosition | "bottom" | "top";
+
+const availablePositionsAndPrevious = [
+ "previous",
+ ...availablePositions,
+] as const;
+
+const bRoll = z.object({
+ source: z.string().default(staticFile("sample-broll.jpg")),
+ durationInFrames: z.number().int().default(90),
+ from: z.number().int().default(30),
+});
+
+export type BRoll = z.infer<typeof bRoll>;
+
+const videoScene = z.object({
+ type: z.literal("videoscene"),
+ webcamPosition: z.enum(availablePositionsAndPrevious),
+ startOffset: z.number(),
+ endOffset: z.number().default(0),
+ transitionToNextScene: z.boolean().default(true),
+ newChapter: z.string().optional(),
+ stopChapteringAfterThis: z.boolean().optional(),
+ music,
+ bRolls: z.array(bRoll).default([]),
+});
+
+export type SelectableVideoScene = z.infer<typeof videoScene>;
+
+const baseScene = z.object({
+ music,
+ transitionToNextScene: z.boolean().default(true),
+});
+
+const titleScene = baseScene.extend({
+ type: z.literal("title"),
+ title: z.string(),
+ subtitle: z.string().nullable(),
+ durationInFrames: z.number().int().default(50),
+});
+
+const endcardScene = baseScene.extend({
+ type: z.literal("endcard"),
+ durationInFrames: z.number().int().default(200),
+ channel: brand,
+ links: z.array(linkType).default([]),
+});
+
+const tableOfContentsScene = baseScene.extend({
+ type: z.literal("tableofcontents"),
+ durationInFrames: z.number().int().default(200),
+});
+
+const recorderScene = baseScene.extend({
+ type: z.literal("recorder"),
+ durationInFrames: z.number().int().default(90),
+});
+
+const selectableScenes = z.discriminatedUnion("type", [
+ videoScene,
+ titleScene,
+ endcardScene,
+ tableOfContentsScene,
+ recorderScene,
+]);
+
+const noRecordingsScene = baseScene.extend({
+ type: z.literal("norecordings"),
+});
+
+const noMoreRecordingsScene = baseScene.extend({
+ type: z.literal("nomorerecordings"),
+});
+
+const noScenes = baseScene.extend({
+ type: z.literal("noscenes"),
+});
+
+const computedScenes = z.discriminatedUnion("type", [
+ noRecordingsScene,
+ noMoreRecordingsScene,
+ noScenes,
+]);
+
+export type SelectableScene = z.infer<typeof selectableScenes>;
+type ComputedScene = z.infer<typeof computedScenes>;
+
+export const videoConf = z.object({
+ theme,
+ canvasLayout,
+ platform,
+ scenes: z.array(selectableScenes),
+});
+
+export type Cameras = {
+ webcam: StaticFile;
+ display: StaticFile | null;
+ captions: StaticFile | null;
+ alternative1: StaticFile | null;
+ alternative2: StaticFile | null;
+ timestamp: number;
+};
+
+export type SceneVideos = {
+ webcam: Dimensions;
+ display: Dimensions | null;
+};
+
+export type BRollWithDimensions = BRoll & {
+ assetWidth: number;
+ assetHeight: number;
+ type: "image" | "video";
+};
+
+export type VideoSceneAndMetadata = {
+ type: "video-scene";
+ scene: SelectableVideoScene;
+ from: number;
+ videos: SceneVideos;
+ layout: VideoSceneLayout;
+ cameras: Cameras;
+ durationInFrames: number;
+ webcamPosition: WebcamPosition;
+ chapter: string | null;
+ startFrame: number;
+ endFrame: number;
+ bRolls: BRollWithDimensions[];
+ srt: UnserializedSrt[];
+};
+
+type OtherScene = {
+ type: "other-scene";
+ scene: ComputedScene | SelectableScene;
+ durationInFrames: number;
+ from: number;
+};
+
+export type SceneAndMetadata = VideoSceneAndMetadata | OtherScene;
diff --git a/packages/template-recorder/config/server.ts b/packages/template-recorder/config/server.ts
new file mode 100644
index 0000000000..25196aebb2
--- /dev/null
+++ b/packages/template-recorder/config/server.ts
@@ -0,0 +1 @@
+export const SERVER_PORT = 4000;
diff --git a/packages/template-recorder/config/sounds.ts b/packages/template-recorder/config/sounds.ts
new file mode 100644
index 0000000000..5426e46486
--- /dev/null
+++ b/packages/template-recorder/config/sounds.ts
@@ -0,0 +1,31 @@
+import { staticFile } from "remotion";
+import { z } from "zod";
+
+const SOUNDS_FOLDER = "sounds";
+export const AUDIO_FADE_IN_FRAMES = 30;
+export const BACKGROUND_VOLUME = 0.04;
+export const REGULAR_VOLUME = 1;
+
+export const music = z.enum(["previous", "soft", "epic", "euphoric", "none"]);
+
+type Music = z.infer<typeof music>;
+
+export const getAudioSource = (track: Music) => {
+ if (track === "none") {
+ return "none";
+ }
+
+ if (track === "soft") {
+ return staticFile(`${SOUNDS_FOLDER}/utope-nature.mp3`);
+ }
+
+ if (track === "euphoric") {
+ return staticFile(`${SOUNDS_FOLDER}/utope-i-woke-up-in-a-dream.mp3`);
+ }
+
+ if (track === "epic") {
+ return staticFile(`${SOUNDS_FOLDER}/utope-rhythmic-reverie.mp3`);
+ }
+
+ throw new Error(`No sound track for ${track}`);
+};
diff --git a/packages/template-recorder/config/themes.ts b/packages/template-recorder/config/themes.ts
new file mode 100644
index 0000000000..5d58681b11
--- /dev/null
+++ b/packages/template-recorder/config/themes.ts
@@ -0,0 +1,44 @@
+import { z } from "zod";
+
+export const theme = z.enum(["light", "dark"]);
+export type Theme = z.infer<typeof theme>;
+
+type ColorTheme = {
+ BACKGROUND: string;
+ CAPTIONS_BACKGROUND: string;
+ BORDER_COLOR: string;
+ WORD_COLOR_ON_BG_APPEARED: string;
+ WORD_COLOR_ON_BG_GREYED: string;
+ WORD_HIGHLIGHT_COLOR: string;
+ ACCENT_COLOR: string;
+ CTA_BUTTON_COLOR: string;
+ CTA_BUTTON_BACKGROUND_COLOR: string;
+ ENDCARD_TEXT_COLOR: string;
+};
+
+export const COLORS: { [key in Theme]: ColorTheme } = {
+ light: {
+ BACKGROUND: "#FAFAFA",
+ CAPTIONS_BACKGROUND: "#fff",
+ BORDER_COLOR: "#EBEBEB",
+ WORD_COLOR_ON_BG_APPEARED: "black",
+ WORD_COLOR_ON_BG_GREYED: "rgba(0, 0, 0, 0.3)",
+ WORD_HIGHLIGHT_COLOR: "#3B82EB",
+ ACCENT_COLOR: "#3B82EB",
+ CTA_BUTTON_COLOR: "white",
+ CTA_BUTTON_BACKGROUND_COLOR: "black",
+ ENDCARD_TEXT_COLOR: "black",
+ },
+ dark: {
+ BACKGROUND: "#000000",
+ CAPTIONS_BACKGROUND: "#0A0A0A",
+ BORDER_COLOR: "#1F1F1F",
+ WORD_COLOR_ON_BG_APPEARED: "white",
+ WORD_COLOR_ON_BG_GREYED: "rgba(255, 255, 255, 0.3)",
+ WORD_HIGHLIGHT_COLOR: "#3B82EB",
+ ACCENT_COLOR: "#3B82EB",
+ CTA_BUTTON_COLOR: "black",
+ CTA_BUTTON_BACKGROUND_COLOR: "white",
+ ENDCARD_TEXT_COLOR: "white",
+ },
+};
diff --git a/packages/template-recorder/config/transitions.ts b/packages/template-recorder/config/transitions.ts
new file mode 100644
index 0000000000..f2e18153ad
--- /dev/null
+++ b/packages/template-recorder/config/transitions.ts
@@ -0,0 +1,2 @@
+export const SCENE_TRANSITION_DURATION = 15;
+export const B_ROLL_TRANSITION_DURATION = 10;
diff --git a/packages/template-recorder/config/whisper.ts b/packages/template-recorder/config/whisper.ts
new file mode 100644
index 0000000000..b667af0251
--- /dev/null
+++ b/packages/template-recorder/config/whisper.ts
@@ -0,0 +1,11 @@
+import type { Language, WhisperModel } from "@remotion/install-whisper-cpp";
+import path from "path";
+
+export const WHISPER_PATH = path.join(process.cwd(), "whisper.cpp");
+export const WHISPER_MODEL: WhisperModel = "medium.en";
+// The git reference, can be a commit, branch or tag
+// The git reference, can be a commit, branch or tag
+// On Windows, using the latest version which has a binary
+// on all other platforms we compile
+export const WHISPER_REF = process.platform === "win32" ? "1.6.0" : "1.7.2";
+export const TRANSCRIPTION_LANGUAGE: Language | null = null;
diff --git a/packages/template-recorder/convert.ts b/packages/template-recorder/convert.ts
new file mode 100644
index 0000000000..afddd1245e
--- /dev/null
+++ b/packages/template-recorder/convert.ts
@@ -0,0 +1,21 @@
+import { $ } from "bun";
+import { renameSync, unlinkSync } from "fs";
+
+const folder = "lasvegas";
+
+const ls = (await $`ls public/${folder}`).stdout.toString("utf-8");
+const files = ls.split("\n");
+
+for (const file of files) {
+ if (
+ file.toLowerCase().endsWith(".mov") ||
+ file.toLowerCase().endsWith(".mp4")
+ ) {
+ await $`ffmpeg -i public/${folder}/${file} public/${folder}/_${file}.mp4`;
+ unlinkSync(`public/${folder}/${file}`);
+ renameSync(
+ `public/${folder}/_${file}.mp4`,
+ `public/${folder}/${file.split(".")[0]}.mp4`,
+ );
+ }
+}
diff --git a/packages/template-recorder/copy.ts b/packages/template-recorder/copy.ts
new file mode 100644
index 0000000000..4f0946cec8
--- /dev/null
+++ b/packages/template-recorder/copy.ts
@@ -0,0 +1,44 @@
+import fs from "fs";
+import { WEBCAM_PREFIX } from "./config/cameras";
+import { convertVideos } from "./scripts/convert-video";
+import { getDownloadsFolder } from "./scripts/get-downloads-folder";
+
+const prefix = "empty";
+
+const downloadsDir = getDownloadsFolder();
+const filesFromDownloads = fs.readdirSync(downloadsDir);
+
+const webcam = filesFromDownloads.filter((file) =>
+ file.startsWith(WEBCAM_PREFIX),
+);
+const sorted = webcam.sort((a, b) => {
+ const timestampA = Number(a.match(/([0-9]+)/)![1]);
+ const timestampB = Number(b.match(/([0-9]+)/)![1]);
+
+ return timestampB - timestampA;
+});
+
+if (sorted.length === 0) {
+ console.error(
+ "No recordings found in your downloads folder. Copy process aborted.",
+ );
+ process.exit();
+}
+
+const latest = sorted[0];
+let latestTimestamp: number;
+try {
+ latestTimestamp = Number(latest.match(/([0-9]+)/)![1]);
+} catch (err) {
+ console.error("An error occured in the copying process: ", err);
+ process.exit();
+}
+
+await convertVideos({
+ latestTimestamp,
+ compositionId: prefix,
+ expectedFrames: null,
+ onProgress: (progress) => {
+ console.log(progress.filename, progress.framesEncoded, "frames");
+ },
+});
diff --git a/packages/template-recorder/index.html b/packages/template-recorder/index.html
new file mode 100644
index 0000000000..39fc1e7d65
--- /dev/null
+++ b/packages/template-recorder/index.html
@@ -0,0 +1,14 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <link rel="icon" type="image/png" href="/favicon.png" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Remotion Recorder</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+ <!--remotion-server-placeholder-->
+ </body>
+</html>
diff --git a/packages/template-recorder/package.json b/packages/template-recorder/package.json
new file mode 100644
index 0000000000..2b5232cc75
--- /dev/null
+++ b/packages/template-recorder/package.json
@@ -0,0 +1,71 @@
+{
+ "name": "@remotion/template-recorder",
+ "private": false,
+ "version": "4.0.277",
+ "type": "module",
+ "scripts": {
+ "build": "tsc && vite build",
+ "lint": "eslint . --ext .ts,.tsx",
+ "start": "bun studio.ts # Run this with `bun start`",
+ "upgrade": "remotion upgrade",
+ "test": "bun run lint && bun test test.ts && tsc"
+ },
+ "dependencies": {
+ "@radix-ui/react-dialog": "^1.0.5",
+ "@radix-ui/react-dropdown-menu": "2.1.4",
+ "@radix-ui/react-label": "^2.0.2",
+ "@radix-ui/react-select": "^2.0.0",
+ "@radix-ui/react-slot": "^1.0.2",
+ "@radix-ui/react-toggle": "^1.0.3",
+ "@remotion/animation-utils": "workspace:*",
+ "@remotion/lambda": "workspace:*",
+ "@remotion/layout-utils": "workspace:*",
+ "@remotion/shapes": "workspace:*",
+ "@remotion/streaming": "workspace:*",
+ "@remotion/studio": "workspace:*",
+ "@remotion/studio-server": "workspace:*",
+ "@remotion/zod-types": "workspace:*",
+ "class-variance-authority": "^0.7.0",
+ "clsx": "^2.0.0",
+ "connect": "3.7.0",
+ "eslint": "9.19.0",
+ "eslint-plugin-react-hooks": "4.6.2",
+ "lucide-react": "^0.290.0",
+ "react": "19.0.0",
+ "react-dom": "19.0.0",
+ "tailwind-merge": "^1.14.0",
+ "tailwindcss-animate": "^1.0.7",
+ "zod": "^3.21.4"
+ },
+ "devDependencies": {
+ "@remotion/cli": "workspace:*",
+ "@remotion/eslint-plugin": "workspace:*",
+ "@remotion/eslint-config": "workspace:*",
+ "@remotion/google-fonts": "workspace:*",
+ "@remotion/captions": "workspace:*",
+ "@remotion/install-whisper-cpp": "workspace:*",
+ "@remotion/media-utils": "workspace:*",
+ "@remotion/media-parser": "workspace:*",
+ "@remotion/renderer": "workspace:*",
+ "@remotion/webcodecs": "workspace:*",
+ "@types/react": "19.0.0",
+ "@types/react-dom": "19.0.0",
+ "@vitejs/plugin-react-swc": "^3.0.0",
+ "autoprefixer": "^10.4.16",
+ "postcss": "^8.4.31",
+ "remotion": "workspace:*",
+ "tailwindcss": "^3.3.5",
+ "typescript": "5.8.2",
+ "vite": "5.2.11",
+ "@types/bun": "^1.0.0",
+ "@types/dom-mediacapture-record": "1.0.21",
+ "@types/connect": "3.4.38",
+ "@types/web": "0.0.187",
+ "@types/webrtc": "0.0.44",
+ "@typescript-eslint/eslint-plugin": "^7.8.0",
+ "@typescript-eslint/parser": "^7.8.0",
+ "@vitejs/plugin-react": "^4.1.0",
+ "prettier": "3.3.3",
+ "prettier-plugin-organize-imports": "^3.2.3"
+ }
+}
diff --git a/packages/template-recorder/postcss.config.js b/packages/template-recorder/postcss.config.js
new file mode 100644
index 0000000000..2e7af2b7f1
--- /dev/null
+++ b/packages/template-recorder/postcss.config.js
@@ -0,0 +1,6 @@
+export default {
+ plugins: {
+ tailwindcss: {},
+ autoprefixer: {},
+ },
+}
diff --git a/packages/template-recorder/public/favicon.png b/packages/template-recorder/public/favicon.png
new file mode 100644
index 0000000000..10735a0a6c
Binary files /dev/null and b/packages/template-recorder/public/favicon.png differ
diff --git a/packages/template-recorder/public/logo.png b/packages/template-recorder/public/logo.png
new file mode 100644
index 0000000000..9e1853230a
Binary files /dev/null and b/packages/template-recorder/public/logo.png differ
diff --git a/packages/template-recorder/public/remotion.png b/packages/template-recorder/public/remotion.png
new file mode 100644
index 0000000000..c48d5a0c75
Binary files /dev/null and b/packages/template-recorder/public/remotion.png differ
diff --git a/packages/template-recorder/public/sample-broll.jpg b/packages/template-recorder/public/sample-broll.jpg
new file mode 100644
index 0000000000..3b3b925f9c
Binary files /dev/null and b/packages/template-recorder/public/sample-broll.jpg differ
diff --git a/packages/template-recorder/public/sounds/grow.m4a b/packages/template-recorder/public/sounds/grow.m4a
new file mode 100644
index 0000000000..a23a4e1d0b
Binary files /dev/null and b/packages/template-recorder/public/sounds/grow.m4a differ
diff --git a/packages/template-recorder/public/sounds/shrink.m4a b/packages/template-recorder/public/sounds/shrink.m4a
new file mode 100644
index 0000000000..cb0dbe41d5
Binary files /dev/null and b/packages/template-recorder/public/sounds/shrink.m4a differ
diff --git a/packages/template-recorder/public/sounds/utope-i-woke-up-in-a-dream.mp3 b/packages/template-recorder/public/sounds/utope-i-woke-up-in-a-dream.mp3
new file mode 100644
index 0000000000..9084efd75e
Binary files /dev/null and b/packages/template-recorder/public/sounds/utope-i-woke-up-in-a-dream.mp3 differ
diff --git a/packages/template-recorder/public/sounds/utope-nature.mp3 b/packages/template-recorder/public/sounds/utope-nature.mp3
new file mode 100644
index 0000000000..f476e7b2d2
Binary files /dev/null and b/packages/template-recorder/public/sounds/utope-nature.mp3 differ
diff --git a/packages/template-recorder/public/sounds/utope-rhythmic-reverie.mp3 b/packages/template-recorder/public/sounds/utope-rhythmic-reverie.mp3
new file mode 100644
index 0000000000..7bdfb75c27
Binary files /dev/null and b/packages/template-recorder/public/sounds/utope-rhythmic-reverie.mp3 differ
diff --git a/packages/template-recorder/public/sounds/whip.wav b/packages/template-recorder/public/sounds/whip.wav
new file mode 100644
index 0000000000..bec7e4e519
Binary files /dev/null and b/packages/template-recorder/public/sounds/whip.wav differ
diff --git a/packages/template-recorder/public/welcome/subs1711527012951.json b/packages/template-recorder/public/welcome/subs1711527012951.json
new file mode 100644
index 0000000000..660010bd20
--- /dev/null
+++ b/packages/template-recorder/public/welcome/subs1711527012951.json
@@ -0,0 +1,128 @@
+[
+ {
+ "text": "Welcome",
+ "startMs": 190,
+ "endMs": 620,
+ "timestampMs": 620,
+ "confidence": 0.971204
+ },
+ {
+ "text": " to",
+ "startMs": 620,
+ "endMs": 860,
+ "timestampMs": 940,
+ "confidence": 0.98921
+ },
+ {
+ "text": " the",
+ "startMs": 860,
+ "endMs": 1050,
+ "timestampMs": 1160,
+ "confidence": 0.951931
+ },
+ {
+ "text": " Remotion",
+ "startMs": 1050,
+ "endMs": 1750,
+ "timestampMs": 1340,
+ "confidence": 0.563537
+ },
+ {
+ "text": " Recorder!",
+ "startMs": 1750,
+ "endMs": 3100,
+ "timestampMs": 1980,
+ "confidence": 0.736247
+ },
+ {
+ "text": " You",
+ "startMs": 3100,
+ "endMs": 3340,
+ "timestampMs": 3520,
+ "confidence": 0.995304
+ },
+ {
+ "text": " are",
+ "startMs": 3340,
+ "endMs": 3580,
+ "timestampMs": 3860,
+ "confidence": 0.959327
+ },
+ {
+ "text": " currently",
+ "startMs": 3580,
+ "endMs": 4300,
+ "timestampMs": 4360,
+ "confidence": 0.995323
+ },
+ {
+ "text": " inside",
+ "startMs": 4300,
+ "endMs": 4810,
+ "timestampMs": 4960,
+ "confidence": 0.982441
+ },
+ {
+ "text": " the",
+ "startMs": 4810,
+ "endMs": 5120,
+ "timestampMs": 5240,
+ "confidence": 0.994042
+ },
+ {
+ "text": " Remotion",
+ "startMs": 5120,
+ "endMs": 5660,
+ "timestampMs": 5460,
+ "confidence": 0.936225
+ },
+ {
+ "text": " Studio,",
+ "startMs": 5660,
+ "endMs": 6320,
+ "timestampMs": 6100,
+ "confidence": 0.84111
+ },
+ {
+ "text": " where",
+ "startMs": 6320,
+ "endMs": 6700,
+ "timestampMs": 6480,
+ "confidence": 0.862046
+ },
+ {
+ "text": " you",
+ "startMs": 6700,
+ "endMs": 6880,
+ "timestampMs": 6620,
+ "confidence": 0.997501
+ },
+ {
+ "text": " can",
+ "startMs": 6880,
+ "endMs": 7180,
+ "timestampMs": 6860,
+ "confidence": 0.995171
+ },
+ {
+ "text": " edit",
+ "startMs": 7180,
+ "endMs": 7390,
+ "timestampMs": 7060,
+ "confidence": 0.998557
+ },
+ {
+ "text": " your",
+ "startMs": 7390,
+ "endMs": 7680,
+ "timestampMs": 7380,
+ "confidence": 0.995524
+ },
+ {
+ "text": " video.",
+ "startMs": 7680,
+ "endMs": 8140,
+ "timestampMs": 7780,
+ "confidence": 0.988418
+ }
+]
diff --git a/packages/template-recorder/public/welcome/subs1711527094922.json b/packages/template-recorder/public/welcome/subs1711527094922.json
new file mode 100644
index 0000000000..27ca913426
--- /dev/null
+++ b/packages/template-recorder/public/welcome/subs1711527094922.json
@@ -0,0 +1,149 @@
+[
+ {
+ "text": "In",
+ "startMs": 0,
+ "endMs": 320,
+ "timestampMs": 1500,
+ "confidence": 0.901755
+ },
+ {
+ "text": " the",
+ "startMs": 320,
+ "endMs": 1380,
+ "timestampMs": 1740,
+ "confidence": 0.998639
+ },
+ {
+ "text": " left",
+ "startMs": 1380,
+ "endMs": 1400,
+ "timestampMs": 1940,
+ "confidence": 0.996934
+ },
+ {
+ "text": " sidebar,",
+ "startMs": 1400,
+ "endMs": 2900,
+ "timestampMs": 2440,
+ "confidence": 0.807074
+ },
+ {
+ "text": " you",
+ "startMs": 2900,
+ "endMs": 3040,
+ "timestampMs": 3000,
+ "confidence": 0.979806
+ },
+ {
+ "text": " have",
+ "startMs": 3040,
+ "endMs": 3360,
+ "timestampMs": 3140,
+ "confidence": 0.992199
+ },
+ {
+ "text": " a",
+ "startMs": 3360,
+ "endMs": 3440,
+ "timestampMs": 3340,
+ "confidence": 0.993013
+ },
+ {
+ "text": " list",
+ "startMs": 3440,
+ "endMs": 3760,
+ "timestampMs": 3500,
+ "confidence": 0.998803
+ },
+ {
+ "text": " of",
+ "startMs": 3760,
+ "endMs": 3920,
+ "timestampMs": 3720,
+ "confidence": 0.995921
+ },
+ {
+ "text": " all",
+ "startMs": 3920,
+ "endMs": 4160,
+ "timestampMs": 3960,
+ "confidence": 0.989002
+ },
+ {
+ "text": " your",
+ "startMs": 4160,
+ "endMs": 4470,
+ "timestampMs": 4180,
+ "confidence": 0.969477
+ },
+ {
+ "text": " videos.",
+ "startMs": 4470,
+ "endMs": 5280,
+ "timestampMs": 4680,
+ "confidence": 0.991565
+ },
+ {
+ "text": " Just",
+ "startMs": 5280,
+ "endMs": 5580,
+ "timestampMs": 5460,
+ "confidence": 0.548289
+ },
+ {
+ "text": " click",
+ "startMs": 5580,
+ "endMs": 5970,
+ "timestampMs": 5740,
+ "confidence": 0.997478
+ },
+ {
+ "text": " on",
+ "startMs": 5970,
+ "endMs": 6130,
+ "timestampMs": 5960,
+ "confidence": 0.987927
+ },
+ {
+ "text": " one",
+ "startMs": 6130,
+ "endMs": 6460,
+ "timestampMs": 6220,
+ "confidence": 0.994526
+ },
+ {
+ "text": " to",
+ "startMs": 6460,
+ "endMs": 6560,
+ "timestampMs": 6560,
+ "confidence": 0.877907
+ },
+ {
+ "text": " start",
+ "startMs": 6560,
+ "endMs": 6840,
+ "timestampMs": 6880,
+ "confidence": 0.946967
+ },
+ {
+ "text": " working",
+ "startMs": 6840,
+ "endMs": 7230,
+ "timestampMs": 7240,
+ "confidence": 0.993678
+ },
+ {
+ "text": " on",
+ "startMs": 7230,
+ "endMs": 7380,
+ "timestampMs": 7400,
+ "confidence": 0.982306
+ },
+ {
+ "text": " it.",
+ "startMs": 7380,
+ "endMs": 8000,
+ "timestampMs": 7700,
+ "confidence": 0.997626
+ }
+]
diff --git a/packages/template-recorder/public/welcome/subs1711527196961.json b/packages/template-recorder/public/welcome/subs1711527196961.json
new file mode 100644
index 0000000000..08067150eb
--- /dev/null
+++ b/packages/template-recorder/public/welcome/subs1711527196961.json
@@ -0,0 +1,121 @@
+[
+ {
+ "text": "In",
+ "startMs": 0,
+ "endMs": 240,
+ "timestampMs": 1280,
+ "confidence": 0.897921
+ },
+ {
+ "text": " the",
+ "startMs": 240,
+ "endMs": 1160,
+ "timestampMs": 1480,
+ "confidence": 0.998468
+ },
+ {
+ "text": " right",
+ "startMs": 1160,
+ "endMs": 1210,
+ "timestampMs": 1780,
+ "confidence": 0.996485
+ },
+ {
+ "text": " sidebar",
+ "startMs": 1210,
+ "endMs": 2130,
+ "timestampMs": 2280,
+ "confidence": 0.766833
+ },
+ {
+ "text": " you",
+ "startMs": 2130,
+ "endMs": 2420,
+ "timestampMs": 2660,
+ "confidence": 0.711176
+ },
+ {
+ "text": " can",
+ "startMs": 2420,
+ "endMs": 2780,
+ "timestampMs": 2880,
+ "confidence": 0.997554
+ },
+ {
+ "text": " edit",
+ "startMs": 2780,
+ "endMs": 3370,
+ "timestampMs": 3260,
+ "confidence": 0.996947
+ },
+ {
+ "text": " a",
+ "startMs": 3370,
+ "endMs": 3420,
+ "timestampMs": 3560,
+ "confidence": 0.990722
+ },
+ {
+ "text": " video",
+ "startMs": 3420,
+ "endMs": 4070,
+ "timestampMs": 3860,
+ "confidence": 0.96658
+ },
+ {
+ "text": " by",
+ "startMs": 4070,
+ "endMs": 4150,
+ "timestampMs": 4200,
+ "confidence": 0.951174
+ },
+ {
+ "text": " adding",
+ "startMs": 4150,
+ "endMs": 4610,
+ "timestampMs": 4600,
+ "confidence": 0.991111
+ },
+ {
+ "text": " more",
+ "startMs": 4610,
+ "endMs": 4910,
+ "timestampMs": 4860,
+ "confidence": 0.991306
+ },
+ {
+ "text": " scenes",
+ "startMs": 4910,
+ "endMs": 5580,
+ "timestampMs": 5300,
+ "confidence": 0.990269
+ },
+ {
+ "text": " or",
+ "startMs": 5580,
+ "endMs": 5690,
+ "timestampMs": 5820,
+ "confidence": 0.954239
+ },
+ {
+ "text": " changing",
+ "startMs": 5690,
+ "endMs": 6320,
+ "timestampMs": 6300,
+ "confidence": 0.975855
+ },
+ {
+ "text": " other",
+ "startMs": 6320,
+ "endMs": 6520,
+ "timestampMs": 6700,
+ "confidence": 0.631347
+ },
+ {
+ "text": " parameters.",
+ "startMs": 6520,
+ "endMs": 7600,
+ "timestampMs": 7240,
+ "confidence": 0.94359
+ }
+]
\ No newline at end of file
diff --git a/packages/template-recorder/public/welcome/subs1711527265610.json b/packages/template-recorder/public/welcome/subs1711527265610.json
new file mode 100644
index 0000000000..b4d830d259
--- /dev/null
+++ b/packages/template-recorder/public/welcome/subs1711527265610.json
@@ -0,0 +1,149 @@
+[
+ {
+ "text": "To",
+ "startMs": 0,
+ "endMs": 250,
+ "timestampMs": 340,
+ "confidence": 0.976738
+ },
+ {
+ "text": " learn",
+ "startMs": 250,
+ "endMs": 540,
+ "timestampMs": 640,
+ "confidence": 0.998586
+ },
+ {
+ "text": " everything",
+ "startMs": 540,
+ "endMs": 1310,
+ "timestampMs": 1080,
+ "confidence": 0.971988
+ },
+ {
+ "text": " about",
+ "startMs": 1310,
+ "endMs": 1700,
+ "timestampMs": 1460,
+ "confidence": 0.994416
+ },
+ {
+ "text": " how",
+ "startMs": 1700,
+ "endMs": 1930,
+ "timestampMs": 1760,
+ "confidence": 0.994112
+ },
+ {
+ "text": " to",
+ "startMs": 1930,
+ "endMs": 2140,
+ "timestampMs": 1920,
+ "confidence": 0.997699
+ },
+ {
+ "text": " use",
+ "startMs": 2140,
+ "endMs": 2310,
+ "timestampMs": 2100,
+ "confidence": 0.997525
+ },
+ {
+ "text": " the",
+ "startMs": 2310,
+ "endMs": 2540,
+ "timestampMs": 2300,
+ "confidence": 0.977706
+ },
+ {
+ "text": " Recorder,",
+ "startMs": 2540,
+ "endMs": 3480,
+ "timestampMs": 2520,
+ "confidence": 0.389211
+ },
+ {
+ "text": " go",
+ "startMs": 3480,
+ "endMs": 3720,
+ "timestampMs": 3620,
+ "confidence": 0.663689
+ },
+ {
+ "text": " to",
+ "startMs": 3720,
+ "endMs": 3920,
+ "timestampMs": 3900,
+ "confidence": 0.99594
+ },
+ {
+ "text": " remotion.dev/recorder",
+ "startMs": 3920,
+ "endMs": 6720,
+ "timestampMs": 4120,
+ "confidence": 0.855024
+ },
+ {
+ "text": " and",
+ "startMs": 6720,
+ "endMs": 6940,
+ "timestampMs": 7080,
+ "confidence": 0.97201
+ },
+ {
+ "text": " join",
+ "startMs": 6940,
+ "endMs": 7230,
+ "timestampMs": 7440,
+ "confidence": 0.994287
+ },
+ {
+ "text": " our",
+ "startMs": 7230,
+ "endMs": 7450,
+ "timestampMs": 7800,
+ "confidence": 0.992949
+ },
+ {
+ "text": " Discord",
+ "startMs": 7450,
+ "endMs": 8070,
+ "timestampMs": 8200,
+ "confidence": 0.785039
+ },
+ {
+ "text": " if",
+ "startMs": 8070,
+ "endMs": 8100,
+ "timestampMs": 8580,
+ "confidence": 0.904597
+ },
+ {
+ "text": " you",
+ "startMs": 8100,
+ "endMs": 8360,
+ "timestampMs": 8680,
+ "confidence": 0.998666
+ },
+ {
+ "text": " have",
+ "startMs": 8360,
+ "endMs": 8610,
+ "timestampMs": 8860,
+ "confidence": 0.998548
+ },
+ {
+ "text": " any",
+ "startMs": 8610,
+ "endMs": 8860,
+ "timestampMs": 9140,
+ "confidence": 0.991639
+ },
+ {
+ "text": " questions.",
+ "startMs": 8860,
+ "endMs": 9520,
+ "timestampMs": 9500,
+ "confidence": 0.996993
+ }
+]
diff --git a/packages/template-recorder/public/welcome/webcam1711527012951.mp4 b/packages/template-recorder/public/welcome/webcam1711527012951.mp4
new file mode 100644
index 0000000000..a88e67a971
Binary files /dev/null and b/packages/template-recorder/public/welcome/webcam1711527012951.mp4 differ
diff --git a/packages/template-recorder/public/welcome/webcam1711527094922.mp4 b/packages/template-recorder/public/welcome/webcam1711527094922.mp4
new file mode 100644
index 0000000000..b6d01f5bef
Binary files /dev/null and b/packages/template-recorder/public/welcome/webcam1711527094922.mp4 differ
diff --git a/packages/template-recorder/public/welcome/webcam1711527196961.mp4 b/packages/template-recorder/public/welcome/webcam1711527196961.mp4
new file mode 100644
index 0000000000..7789ae7eaa
Binary files /dev/null and b/packages/template-recorder/public/welcome/webcam1711527196961.mp4 differ
diff --git a/packages/template-recorder/public/welcome/webcam1711527265610.mp4 b/packages/template-recorder/public/welcome/webcam1711527265610.mp4
new file mode 100644
index 0000000000..3cb507ef06
Binary files /dev/null and b/packages/template-recorder/public/welcome/webcam1711527265610.mp4 differ
diff --git a/packages/template-recorder/remotion.config.ts b/packages/template-recorder/remotion.config.ts
new file mode 100644
index 0000000000..4684cb8525
--- /dev/null
+++ b/packages/template-recorder/remotion.config.ts
@@ -0,0 +1,4 @@
+import { Config } from "@remotion/cli/config";
+
+Config.setVideoImageFormat('jpeg');
+Config.setOverwriteOutput(true);
diff --git a/packages/template-recorder/remotion/GoToRecorder.tsx b/packages/template-recorder/remotion/GoToRecorder.tsx
new file mode 100644
index 0000000000..8bc0182ba8
--- /dev/null
+++ b/packages/template-recorder/remotion/GoToRecorder.tsx
@@ -0,0 +1,36 @@
+import { AbsoluteFill } from "remotion";
+import { REGULAR_FONT } from "../config/fonts";
+import { SERVER_PORT } from "../config/server";
+import { COLORS } from "../config/themes";
+import { WaitForFonts } from "./helpers/WaitForFonts";
+
+const container: React.CSSProperties = {
+ justifyContent: "center",
+ alignItems: "center",
+ backgroundColor: "#fff",
+ fontSize: 30,
+ textAlign: "center",
+ ...REGULAR_FONT,
+};
+
+const link: React.CSSProperties = {
+ color: COLORS.light.ACCENT_COLOR,
+ textDecoration: "underline",
+};
+
+export const GoToRecorder: React.FC = () => {
+ return (
+ <WaitForFonts>
+ <AbsoluteFill style={container}>
+ The recording interface is running on http://localhost:{SERVER_PORT}.
+ <a
+ target="_blank"
+ style={link}
+ href={`http://localhost:${SERVER_PORT}`}
+ >
+ Go there
+ </a>
+ </AbsoluteFill>
+ </WaitForFonts>
+ );
+};
diff --git a/packages/template-recorder/remotion/Main.tsx b/packages/template-recorder/remotion/Main.tsx
new file mode 100644
index 0000000000..e8f3fd88a6
--- /dev/null
+++ b/packages/template-recorder/remotion/Main.tsx
@@ -0,0 +1,96 @@
+import React, { useCallback, useMemo, useState } from "react";
+import { AbsoluteFill, Sequence } from "remotion";
+import type { Platform } from "../config/endcard";
+import type { CanvasLayout } from "../config/layout";
+import type { SceneAndMetadata, SelectableScene } from "../config/scenes";
+import type { Theme } from "../config/themes";
+import { COLORS } from "../config/themes";
+import { AudioTrack } from "./audio/AudioTrack";
+import { captionEditorPortal } from "./captions/editor/layout";
+import { EmitSrtFile } from "./captions/srt/EmitSrtFile";
+import { makeChapters } from "./chapters/make-chapters";
+import { Scene } from "./scenes/Scene";
+import { NoDataScene } from "./scenes/VideoScene/NoDataScene";
+
+export type MainProps = {
+ canvasLayout: CanvasLayout;
+ scenes: SelectableScene[];
+ scenesAndMetadata: SceneAndMetadata[];
+ theme: Theme;
+ platform: Platform;
+};
+
+export const Main: React.FC<MainProps> = ({
+ scenesAndMetadata,
+ canvasLayout,
+ theme,
+ platform,
+ scenes,
+}) => {
+ const chapters = useMemo(() => {
+ return makeChapters({ scenes: scenesAndMetadata });
+ }, [scenesAndMetadata]);
+
+ const [hovered, setHovered] = useState(false);
+ const onPointerEnter = useCallback(() => {
+ setHovered(true);
+ }, []);
+
+ const onPointerLeave = useCallback(() => {
+ setHovered(false);
+ }, []);
+
+ if (scenesAndMetadata.length === 0) {
+ return <NoDataScene theme={theme} />;
+ }
+
+ const lastSceneIndex = scenesAndMetadata[
+ scenesAndMetadata.length - 1
+ ] as SceneAndMetadata;
+ const lastSceneFrame =
+ lastSceneIndex.from + lastSceneIndex.durationInFrames - 1;
+
+ return (
+ <AbsoluteFill
+ style={{
+ background: COLORS[theme].BACKGROUND,
+ }}
+ onPointerEnter={onPointerEnter}
+ onPointerLeave={onPointerLeave}
+ >
+ {scenesAndMetadata.map((sceneAndMetadata, i) => {
+ return (
+ <Scene
+ key={i}
+ index={i}
+ nextScene={scenesAndMetadata[i + 1] ?? null}
+ previousScene={scenesAndMetadata[i - 1] ?? null}
+ chapters={chapters}
+ canvasLayout={canvasLayout}
+ sceneAndMetadata={sceneAndMetadata}
+ theme={theme}
+ platform={platform}
+ hovered={hovered}
+ />
+ );
+ })}
+ {scenes.length > scenesAndMetadata.length ? (
+ <Sequence
+ name="No more videos"
+ from={lastSceneFrame}
+ durationInFrames={120}
+ >
+ <NoDataScene theme={theme} />
+ </Sequence>
+ ) : null}
+ <AudioTrack
+ scenesAndMetadata={scenesAndMetadata}
+ canvasLayout={canvasLayout}
+ />
+ {canvasLayout === "landscape" ? (
+ <EmitSrtFile scenesAndMetadata={scenesAndMetadata} />
+ ) : null}
+ <div ref={captionEditorPortal} />
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/Root.tsx b/packages/template-recorder/remotion/Root.tsx
new file mode 100644
index 0000000000..d3874da7d6
--- /dev/null
+++ b/packages/template-recorder/remotion/Root.tsx
@@ -0,0 +1,108 @@
+import { Composition } from "remotion";
+import { videoConf } from "../config/scenes";
+import { GoToRecorder } from "./GoToRecorder";
+import { Main } from "./Main";
+import { calcMetadata } from "./calculate-metadata/calc-metadata";
+
+export const Root = () => {
+ return (
+ <>
+ <Composition
+ component={Main}
+ id="welcome"
+ schema={videoConf}
+ defaultProps={{
+ theme: "light" as const,
+ canvasLayout: "square" as const,
+ scenes: [
+ {
+ type: "recorder" as const,
+ durationInFrames: 80,
+ music: "epic" as const,
+ transitionToNextScene: true,
+ },
+ {
+ type: "videoscene" as const,
+ webcamPosition: "previous" as const,
+ endOffset: 0,
+ transitionToNextScene: true,
+ newChapter: "",
+ stopChapteringAfterThis: false,
+ music: "previous" as const,
+ startOffset: 0,
+ bRolls: [],
+ },
+ {
+ type: "videoscene" as const,
+ webcamPosition: "previous" as const,
+ endOffset: 0,
+ transitionToNextScene: true,
+ newChapter: "",
+ stopChapteringAfterThis: false,
+ music: "previous" as const,
+ startOffset: 0,
+ bRolls: [],
+ },
+ {
+ type: "videoscene" as const,
+ webcamPosition: "previous" as const,
+ endOffset: 0,
+ transitionToNextScene: true,
+ newChapter: "",
+ stopChapteringAfterThis: false,
+ music: "previous" as const,
+ startOffset: 0,
+ bRolls: [],
+ },
+ {
+ type: "videoscene" as const,
+ webcamPosition: "previous" as const,
+ endOffset: 0,
+ transitionToNextScene: true,
+ newChapter: "",
+ stopChapteringAfterThis: false,
+ music: "previous" as const,
+ startOffset: 0,
+ bRolls: [],
+ },
+ {
+ music: "previous" as const,
+ transitionToNextScene: true,
+ type: "endcard" as const,
+ durationInFrames: 200,
+ channel: "remotion" as const,
+ links: [
+ { link: "remotion.dev/recorder" },
+ { link: "remotion.dev/discord" },
+ ],
+ },
+ ],
+ scenesAndMetadata: [],
+ platform: "x" as const,
+ }}
+ calculateMetadata={calcMetadata}
+ />
+ <Composition
+ component={GoToRecorder}
+ id="record"
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={100}
+ />
+ <Composition
+ component={Main}
+ id="empty"
+ schema={videoConf}
+ defaultProps={{
+ theme: "light" as const,
+ canvasLayout: "square" as const,
+ platform: "youtube",
+ scenes: [],
+ scenesAndMetadata: [],
+ }}
+ calculateMetadata={calcMetadata}
+ />
+ </>
+ );
+};
diff --git a/packages/template-recorder/remotion/animations/caption-transitions/should-transition-subtitle.ts b/packages/template-recorder/remotion/animations/caption-transitions/should-transition-subtitle.ts
new file mode 100644
index 0000000000..1e5951d08f
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/caption-transitions/should-transition-subtitle.ts
@@ -0,0 +1,47 @@
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+
+// An inline subtitle transition:
+// - The subtitle stays at the same position and is the same subtitle type
+
+// Animation may be ensure they don't overlap or to resize the box
+export const shouldInlineTransitionSubtitles = ({
+ currentScene,
+ nextScene,
+}: {
+ currentScene: VideoSceneAndMetadata;
+ nextScene: SceneAndMetadata | null;
+}) => {
+ if (nextScene === null) {
+ return false;
+ }
+
+ if (nextScene.type !== "video-scene") {
+ return false;
+ }
+
+ if (!currentScene.layout.subtitleLayout || !nextScene.layout.subtitleLayout) {
+ return false;
+ }
+
+ // In square layout, we resize the box if the aspect ratio of the videos has changed.
+ // While resizing the box, the subtitles fade out.
+
+ const nextSubtitleLayout = nextScene.layout.subtitleLayout;
+ const currentSubtitleLayout = currentScene.layout.subtitleLayout;
+
+ const layoutsAreTheSameBox =
+ nextSubtitleLayout.width === currentSubtitleLayout.width &&
+ nextSubtitleLayout.height === currentSubtitleLayout.height &&
+ nextSubtitleLayout.left === currentSubtitleLayout.left &&
+ nextSubtitleLayout.top === currentSubtitleLayout.top;
+
+ return (
+ nextScene.webcamPosition === currentScene.webcamPosition &&
+ Boolean(currentScene.videos.display) ===
+ Boolean(nextScene.videos.display) &&
+ !layoutsAreTheSameBox
+ );
+};
diff --git a/packages/template-recorder/remotion/animations/caption-transitions/square.ts b/packages/template-recorder/remotion/animations/caption-transitions/square.ts
new file mode 100644
index 0000000000..66bbe8776b
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/caption-transitions/square.ts
@@ -0,0 +1,227 @@
+import { getSafeSpace } from "../../../config/layout";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { Layout } from "../../layout/layout-types";
+import { isWebCamAtBottom, isWebCamRight } from "../webcam-transitions/helpers";
+
+const getEnterAndExitOfFullscreenBox = ({
+ scene,
+ otherScene,
+ canvasHeight,
+ canvasWidth,
+ subtitleLayout,
+}: {
+ scene: VideoSceneAndMetadata;
+ otherScene: VideoSceneAndMetadata;
+ canvasHeight: number;
+ canvasWidth: number;
+ subtitleLayout: Layout;
+}) => {
+ if (otherScene === null || otherScene.type !== "video-scene") {
+ return subtitleLayout;
+ }
+
+ const previouslyAtBottom = isWebCamAtBottom(otherScene.webcamPosition);
+ const currentlyAtBottom = isWebCamAtBottom(scene.webcamPosition);
+ const changedVerticalPosition = previouslyAtBottom !== currentlyAtBottom;
+
+ // Changing from top to bottom or vice versa will push the subtitle out of the screen
+ if (changedVerticalPosition) {
+ if (currentlyAtBottom) {
+ return {
+ ...subtitleLayout,
+ top: -subtitleLayout.height,
+ };
+ }
+
+ return {
+ ...subtitleLayout,
+ top: canvasHeight,
+ };
+ }
+
+ // If the vertical position has not changed, and the next scene also
+ // has no display video, then nothing changes in the layout
+ if (otherScene.layout.displayLayout === null) {
+ return otherScene.layout.subtitleLayout as Layout;
+ }
+
+ // Now we expect that the other scene has a display video, and the webcam will shrink
+ const top = isWebCamAtBottom(scene.webcamPosition)
+ ? otherScene.layout.webcamLayout.top -
+ subtitleLayout.height -
+ getSafeSpace("square")
+ : getSafeSpace("square") * 2 + otherScene.layout.webcamLayout.height;
+
+ // If the webcam moves to the top right corner, the subtitle should come from left corner
+ if (!isWebCamRight(otherScene.webcamPosition)) {
+ return {
+ ...subtitleLayout,
+ left: -subtitleLayout.width,
+ top,
+ };
+ }
+
+ return {
+ ...subtitleLayout,
+ left: canvasWidth,
+ top,
+ };
+};
+
+const getEnterAndExitLayoutOfWebcamPositionChange = ({
+ otherScene,
+ scene,
+ canvasHeight,
+ canvasWidth,
+ subtitleLayout,
+}: {
+ otherScene: VideoSceneAndMetadata;
+ scene: VideoSceneAndMetadata;
+ canvasHeight: number;
+ canvasWidth: number;
+ subtitleLayout: Layout;
+}) => {
+ if (scene.webcamPosition === otherScene.webcamPosition) {
+ return otherScene.layout.subtitleLayout as Layout;
+ }
+
+ // Horizontal position change, move the subtitle over the edge
+ if (
+ isWebCamAtBottom(scene.webcamPosition) !==
+ isWebCamAtBottom(otherScene.webcamPosition)
+ ) {
+ if (isWebCamAtBottom(scene.webcamPosition)) {
+ return {
+ ...subtitleLayout,
+ top: canvasHeight,
+ };
+ }
+
+ return {
+ ...subtitleLayout,
+ top: -subtitleLayout.height,
+ };
+ }
+
+ // Vertical position change
+ // Webcam moves from right to left
+ if (isWebCamRight(scene.webcamPosition)) {
+ return {
+ ...subtitleLayout,
+ left: -subtitleLayout.width,
+ };
+ }
+
+ // Webcam moves from left to right
+ return {
+ ...subtitleLayout,
+ left: canvasWidth,
+ };
+};
+
+const getEnterAndExitOfBentoLayout = ({
+ scene,
+ otherScene,
+ canvasWidth,
+ canvasHeight,
+ subtitleLayout,
+}: {
+ otherScene: VideoSceneAndMetadata;
+ scene: VideoSceneAndMetadata;
+ canvasWidth: number;
+ canvasHeight: number;
+ subtitleLayout: Layout;
+}) => {
+ if (!scene.layout.displayLayout) {
+ throw new Error("Expected display layout to be present");
+ }
+
+ if (otherScene.layout.displayLayout) {
+ return getEnterAndExitLayoutOfWebcamPositionChange({
+ otherScene,
+ scene,
+ canvasHeight,
+ canvasWidth,
+ subtitleLayout,
+ });
+ }
+
+ // We now assume the other scene has no display, webcam is getting bigger
+ // and we need to animate the subtitles out
+ const left = isWebCamRight(scene.webcamPosition)
+ ? -subtitleLayout.width
+ : canvasWidth;
+
+ // Vertical position change
+ if (
+ isWebCamAtBottom(otherScene.webcamPosition) !==
+ isWebCamAtBottom(scene.webcamPosition)
+ ) {
+ if (isWebCamAtBottom(scene.webcamPosition)) {
+ return {
+ ...subtitleLayout,
+ top: getSafeSpace("square"),
+ left,
+ };
+ }
+
+ return {
+ ...subtitleLayout,
+ top: canvasHeight - subtitleLayout.height - getSafeSpace("square"),
+ left,
+ };
+ }
+
+ const top = isWebCamAtBottom(scene.webcamPosition)
+ ? canvasHeight -
+ otherScene.layout.webcamLayout.height -
+ getSafeSpace("square")
+ : otherScene.layout.webcamLayout.height -
+ subtitleLayout.height +
+ getSafeSpace("square");
+
+ return {
+ ...subtitleLayout,
+ left,
+ top,
+ };
+};
+
+export const getSquareEnterOrExit = ({
+ scene,
+ canvasHeight,
+ otherScene,
+ canvasWidth,
+ subtitleLayout,
+}: {
+ otherScene: SceneAndMetadata | null;
+ scene: VideoSceneAndMetadata;
+ canvasWidth: number;
+ canvasHeight: number;
+ subtitleLayout: Layout;
+}): Layout => {
+ if (otherScene === null || otherScene.type !== "video-scene") {
+ return subtitleLayout;
+ }
+
+ if (scene.layout.displayLayout === null) {
+ return getEnterAndExitOfFullscreenBox({
+ canvasHeight,
+ canvasWidth,
+ otherScene,
+ scene,
+ subtitleLayout,
+ });
+ }
+
+ return getEnterAndExitOfBentoLayout({
+ otherScene,
+ scene,
+ canvasWidth,
+ canvasHeight,
+ subtitleLayout,
+ });
+};
diff --git a/packages/template-recorder/remotion/animations/caption-transitions/subtitle-transitions.ts b/packages/template-recorder/remotion/animations/caption-transitions/subtitle-transitions.ts
new file mode 100644
index 0000000000..4c31f0aac2
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/caption-transitions/subtitle-transitions.ts
@@ -0,0 +1,49 @@
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { Layout } from "../../layout/layout-types";
+import { interpolateLayout } from "../interpolate-layout";
+import { getSquareEnterOrExit } from "./square";
+
+export const getSubtitleTransform = ({
+ enterProgress,
+ exitProgress,
+ canvasWidth,
+ canvasHeight,
+ nextScene,
+ previousScene,
+ scene,
+ subtitleLayout,
+}: {
+ enterProgress: number;
+ exitProgress: number;
+ canvasWidth: number;
+ canvasHeight: number;
+ scene: VideoSceneAndMetadata;
+ previousScene: SceneAndMetadata | null;
+ nextScene: SceneAndMetadata | null;
+ subtitleLayout: Layout;
+}): Layout => {
+ const enter = getSquareEnterOrExit({
+ scene,
+ otherScene: previousScene,
+ canvasHeight,
+ canvasWidth,
+ subtitleLayout,
+ });
+
+ const exit = getSquareEnterOrExit({
+ scene,
+ otherScene: nextScene,
+ canvasWidth,
+ canvasHeight,
+ subtitleLayout,
+ });
+
+ if (exitProgress > 0) {
+ return interpolateLayout(subtitleLayout, exit, exitProgress);
+ }
+
+ return interpolateLayout(enter, subtitleLayout, enterProgress);
+};
diff --git a/packages/template-recorder/remotion/animations/display-transitions/index.ts b/packages/template-recorder/remotion/animations/display-transitions/index.ts
new file mode 100644
index 0000000000..454c11e2f0
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/display-transitions/index.ts
@@ -0,0 +1,130 @@
+import type { CanvasLayout } from "../../../config/layout";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { Layout, LayoutAndFade } from "../../layout/layout-types";
+import { interpolateLayoutAndFade } from "../interpolate-layout";
+import { getLandscapeDisplayEnterOrExit } from "./landscape";
+import { getSquareDisplayEnterOrExit } from "./square";
+
+const getDisplayStartOrEndLayout = ({
+ currentScene,
+ otherScene,
+ canvasWidth,
+ canvasHeight,
+ canvasLayout,
+}: {
+ otherScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ canvasWidth: number;
+ canvasHeight: number;
+ canvasLayout: CanvasLayout;
+}): LayoutAndFade => {
+ if (canvasLayout === "landscape") {
+ return getLandscapeDisplayEnterOrExit({
+ currentScene,
+ otherScene,
+ });
+ }
+
+ if (canvasLayout === "square") {
+ return getSquareDisplayEnterOrExit({
+ currentScene,
+ otherScene,
+ canvasWidth,
+ canvasHeight,
+ });
+ }
+
+ throw new Error(`Unknown canvas layout: ${canvasLayout satisfies never}`);
+};
+
+const getDisplayTransitionOrigins = ({
+ currentScene,
+ nextScene,
+ previousScene,
+ canvasWidth,
+ canvasHeight,
+ canvasLayout,
+}: {
+ nextScene: SceneAndMetadata | null;
+ previousScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ canvasLayout: CanvasLayout;
+ canvasWidth: number;
+ canvasHeight: number;
+}) => {
+ const enter = getDisplayStartOrEndLayout({
+ currentScene,
+ otherScene: previousScene,
+ canvasWidth,
+ canvasLayout,
+ canvasHeight,
+ });
+
+ const exit = getDisplayStartOrEndLayout({
+ currentScene,
+ otherScene: nextScene,
+ canvasWidth,
+ canvasHeight,
+ canvasLayout,
+ });
+
+ return {
+ enter,
+ exit,
+ };
+};
+
+export const getDisplayPosition = ({
+ enterProgress,
+ exitProgress,
+ canvasWidth,
+ canvasHeight,
+ nextScene,
+ previousScene,
+ currentScene,
+ canvasLayout,
+}: {
+ enterProgress: number;
+ exitProgress: number;
+ canvasWidth: number;
+ canvasHeight: number;
+ previousScene: SceneAndMetadata | null;
+ nextScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ canvasLayout: CanvasLayout;
+}): Layout => {
+ if (
+ currentScene.type !== "video-scene" ||
+ currentScene.layout.displayLayout === null
+ ) {
+ throw new Error("no transitions on non-video scenes");
+ }
+
+ const { enter, exit } = getDisplayTransitionOrigins({
+ currentScene,
+ nextScene,
+ previousScene,
+ canvasWidth,
+ canvasHeight,
+ canvasLayout,
+ });
+
+ if (exitProgress > 0) {
+ return interpolateLayoutAndFade(
+ currentScene.layout.displayLayout,
+ exit.layout,
+ exitProgress,
+ false,
+ );
+ }
+
+ return interpolateLayoutAndFade(
+ enter.layout,
+ currentScene.layout.displayLayout,
+ enterProgress,
+ enter.shouldFadeRecording,
+ );
+};
diff --git a/packages/template-recorder/remotion/animations/display-transitions/landscape.ts b/packages/template-recorder/remotion/animations/display-transitions/landscape.ts
new file mode 100644
index 0000000000..4aefcd474f
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/display-transitions/landscape.ts
@@ -0,0 +1,40 @@
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { LayoutAndFade } from "../../layout/layout-types";
+
+export const getLandscapeDisplayEnterOrExit = ({
+ currentScene,
+ otherScene,
+}: {
+ otherScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+}): LayoutAndFade => {
+ if (
+ currentScene.type !== "video-scene" ||
+ currentScene.layout.displayLayout === null
+ ) {
+ throw new Error("no transitions on non-video scenes");
+ }
+
+ if (otherScene === null || otherScene.type !== "video-scene") {
+ return {
+ layout: currentScene.layout.displayLayout,
+ shouldFadeRecording: false,
+ };
+ }
+
+ if (otherScene.layout.displayLayout === null) {
+ // landscape, Slide in from left
+ return {
+ layout: currentScene.layout.displayLayout,
+ shouldFadeRecording: false,
+ };
+ }
+
+ return {
+ layout: otherScene.layout.displayLayout,
+ shouldFadeRecording: true,
+ };
+};
diff --git a/packages/template-recorder/remotion/animations/display-transitions/square.ts b/packages/template-recorder/remotion/animations/display-transitions/square.ts
new file mode 100644
index 0000000000..bb2e8f75ad
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/display-transitions/square.ts
@@ -0,0 +1,129 @@
+import { getSafeSpace } from "../../../config/layout";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { LayoutAndFade } from "../../layout/layout-types";
+import { isWebCamAtBottom } from "../webcam-transitions/helpers";
+
+export const getSquareDisplayEnterOrExit = ({
+ currentScene,
+ otherScene,
+ canvasHeight,
+ canvasWidth,
+}: {
+ otherScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ canvasWidth: number;
+ canvasHeight: number;
+}): LayoutAndFade => {
+ if (
+ currentScene.type !== "video-scene" ||
+ currentScene.layout.displayLayout === null
+ ) {
+ throw new Error("no transitions on non-video scenes");
+ }
+
+ if (otherScene === null || otherScene.type !== "video-scene") {
+ return {
+ layout: currentScene.layout.displayLayout,
+ shouldFadeRecording: false,
+ };
+ }
+
+ if (otherScene.layout.displayLayout !== null) {
+ return {
+ layout: otherScene.layout.displayLayout,
+ shouldFadeRecording: true,
+ };
+ }
+
+ // Assuming now: currentScene is a display video that needs to be moved in
+ // the canvas because other scene had no display video
+
+ // 1. From bottom left/right to top: Display should disappear top edge
+ if (
+ isWebCamAtBottom(currentScene.webcamPosition) &&
+ !isWebCamAtBottom(otherScene.webcamPosition)
+ ) {
+ return {
+ layout: {
+ ...currentScene.layout.displayLayout,
+ top: -currentScene.layout.displayLayout.height,
+ },
+ shouldFadeRecording: false,
+ };
+ }
+
+ // 2. From top to bottom left/right: Display should appear from bottom edge
+ if (
+ !isWebCamAtBottom(currentScene.webcamPosition) &&
+ isWebCamAtBottom(otherScene.webcamPosition)
+ ) {
+ return {
+ layout: {
+ ...currentScene.layout.displayLayout,
+ top: canvasHeight,
+ },
+ shouldFadeRecording: false,
+ };
+ }
+
+ // 3. From top right to top: Should slide display to left
+ if (currentScene.webcamPosition === "top-right") {
+ return {
+ layout: {
+ ...currentScene.layout.displayLayout,
+ left: -currentScene.layout.displayLayout.width,
+ top: otherScene.layout.webcamLayout.height + getSafeSpace("square") * 2,
+ },
+ shouldFadeRecording: false,
+ };
+ }
+
+ // 4. From top left to top: Should slide display to right
+ if (currentScene.webcamPosition === "top-left") {
+ return {
+ layout: {
+ ...currentScene.layout.displayLayout,
+ left: canvasWidth,
+ top: otherScene.layout.webcamLayout.height + getSafeSpace("square") * 2,
+ },
+ shouldFadeRecording: false,
+ };
+ }
+
+ // 5. From bottom left to bottom: Display should disappear to right
+ if (currentScene.webcamPosition === "bottom-left") {
+ return {
+ layout: {
+ ...currentScene.layout.displayLayout,
+ left: canvasWidth,
+ top:
+ canvasHeight -
+ currentScene.layout.displayLayout.height -
+ otherScene.layout.webcamLayout.height -
+ getSafeSpace("square") * 2,
+ },
+ shouldFadeRecording: false,
+ };
+ }
+
+ // 6. From bottom right to bottom: Display should disappear to left
+ if (currentScene.webcamPosition === "bottom-right") {
+ return {
+ layout: {
+ ...currentScene.layout.displayLayout,
+ left: -currentScene.layout.displayLayout.width,
+ top:
+ canvasHeight -
+ currentScene.layout.displayLayout.height -
+ otherScene.layout.webcamLayout.height -
+ getSafeSpace("square") * 2,
+ },
+ shouldFadeRecording: false,
+ };
+ }
+
+ throw new Error("Unhandled case");
+};
diff --git a/packages/template-recorder/remotion/animations/interpolate-layout.ts b/packages/template-recorder/remotion/animations/interpolate-layout.ts
new file mode 100644
index 0000000000..5c004f3fc6
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/interpolate-layout.ts
@@ -0,0 +1,62 @@
+import { interpolate } from "remotion";
+import type { Layout } from "../layout/layout-types";
+
+export const interpolateLayout = (
+ firstLayout: Layout,
+ secondLayout: Layout,
+ progress: number,
+) => {
+ const left = interpolate(
+ progress,
+ [0, 1],
+ [firstLayout.left, secondLayout.left],
+ );
+ const top = interpolate(
+ progress,
+ [0, 1],
+ [firstLayout.top, secondLayout.top],
+ );
+ const width = interpolate(
+ progress,
+ [0, 1],
+ [firstLayout.width, secondLayout.width],
+ );
+ const height = interpolate(
+ progress,
+ [0, 1],
+ [firstLayout.height, secondLayout.height],
+ );
+ const borderRadius = interpolate(
+ progress,
+ [0, 1],
+ [firstLayout.borderRadius, secondLayout.borderRadius],
+ );
+ const opacity = interpolate(
+ progress,
+ [0, 1],
+ [firstLayout.opacity, secondLayout.opacity],
+ );
+
+ return {
+ left,
+ top,
+ width,
+ height,
+ borderRadius,
+ opacity,
+ };
+};
+
+export const interpolateLayoutAndFade = (
+ firstLayout: Layout,
+ secondLayout: Layout,
+ progress: number,
+ shouldFade: boolean,
+) => {
+ const layout = interpolateLayout(firstLayout, secondLayout, progress);
+
+ return {
+ ...layout,
+ opacity: shouldFade ? (progress > 0.5 ? 1 : 0) : 1,
+ };
+};
diff --git a/packages/template-recorder/remotion/animations/scene-transitions.ts b/packages/template-recorder/remotion/animations/scene-transitions.ts
new file mode 100644
index 0000000000..a3ff7f8905
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/scene-transitions.ts
@@ -0,0 +1,58 @@
+import type { SceneAndMetadata } from "../../config/scenes";
+
+export const getSceneEnter = ({
+ canvasWidth,
+ previousScene,
+ currentScene,
+}: {
+ canvasWidth: number;
+ previousScene: SceneAndMetadata | null;
+ currentScene: SceneAndMetadata;
+}): {
+ left: number;
+} => {
+ if (previousScene === null) {
+ return {
+ left: 0,
+ };
+ }
+
+ if (
+ previousScene.type === "video-scene" &&
+ currentScene.type === "video-scene"
+ ) {
+ return {
+ left: 0,
+ };
+ }
+
+ return {
+ left: canvasWidth,
+ };
+};
+
+export const getSceneExit = ({
+ canvasWidth,
+ nextScene,
+ currentScene,
+}: {
+ canvasWidth: number;
+ nextScene: SceneAndMetadata | null;
+ currentScene: SceneAndMetadata;
+}) => {
+ if (nextScene === null) {
+ return {
+ left: 0,
+ };
+ }
+
+ if (nextScene.type === "video-scene" && currentScene.type === "video-scene") {
+ return {
+ left: 0,
+ };
+ }
+
+ return {
+ left: -canvasWidth,
+ };
+};
diff --git a/packages/template-recorder/remotion/animations/transitions.ts b/packages/template-recorder/remotion/animations/transitions.ts
new file mode 100644
index 0000000000..5b2aebfaea
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/transitions.ts
@@ -0,0 +1,127 @@
+import type { Dimensions } from "@remotion/layout-utils";
+import type { CanvasLayout } from "../../config/layout";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+ WebcamPositionForComparison,
+} from "../../config/scenes";
+
+const getComparableWebcamPosition = (
+ sceneAndMetaData: VideoSceneAndMetadata,
+ canvasLayout: CanvasLayout,
+): WebcamPositionForComparison => {
+ if (canvasLayout !== "square") {
+ return sceneAndMetaData.webcamPosition;
+ }
+
+ if (sceneAndMetaData.videos.display) {
+ return sceneAndMetaData.webcamPosition;
+ }
+
+ if (
+ sceneAndMetaData.webcamPosition === "bottom-left" ||
+ sceneAndMetaData.webcamPosition === "bottom-right"
+ ) {
+ return "bottom";
+ }
+
+ return "top";
+};
+
+const getHasSameSize = (
+ first: Dimensions | null,
+ second: Dimensions | null,
+) => {
+ // If both are null, they are the same
+ if (first === null && second === null) {
+ return true;
+ }
+
+ // If only one is null, they are not the same
+ if (first === null || second === null) {
+ return false;
+ }
+
+ return first.height === second.height && second.width === first.width;
+};
+
+// Figure out if we are able to do a transition.
+// We can do a transition if the layout is not the same.
+export const getShouldTransitionOut = ({
+ sceneAndMetadata,
+ nextSceneAndMetadata,
+ canvasLayout,
+}: {
+ sceneAndMetadata: SceneAndMetadata;
+ nextSceneAndMetadata: SceneAndMetadata | null;
+ canvasLayout: CanvasLayout;
+}) => {
+ // Can not transition if this is the last scene
+ if (nextSceneAndMetadata === null) {
+ return false;
+ }
+
+ // Can not transition if it was disabled
+ if (!sceneAndMetadata.scene.transitionToNextScene) {
+ return false;
+ }
+
+ // If not both are video scenes, we can transition (slide)
+ if (
+ sceneAndMetadata.type !== "video-scene" ||
+ nextSceneAndMetadata.type !== "video-scene"
+ ) {
+ return true;
+ }
+
+ // If the webcam position changed, we can transition (move webcam)
+ if (
+ getComparableWebcamPosition(sceneAndMetadata, canvasLayout) !==
+ getComparableWebcamPosition(nextSceneAndMetadata, canvasLayout)
+ ) {
+ return true;
+ }
+
+ // We can transition if the webcam size has changed
+ if (
+ !getHasSameSize(
+ sceneAndMetadata.layout.webcamLayout,
+ nextSceneAndMetadata.layout.webcamLayout,
+ )
+ ) {
+ return true;
+ }
+
+ // If display is not the same, we can transition
+ if (
+ !getHasSameSize(
+ sceneAndMetadata.layout.displayLayout,
+ nextSceneAndMetadata.layout.displayLayout,
+ )
+ ) {
+ return true;
+ }
+
+ // Seems like everything is the same, we can't transition!
+ return false;
+};
+
+export const getShouldTransitionIn = ({
+ sceneAndMetadata: sceneAndMetadata,
+ previousSceneAndMetadata,
+ canvasLayout,
+}: {
+ sceneAndMetadata: SceneAndMetadata;
+ previousSceneAndMetadata: SceneAndMetadata | null;
+ canvasLayout: CanvasLayout;
+}) => {
+ if (previousSceneAndMetadata === null) {
+ return false;
+ }
+
+ return getShouldTransitionOut({
+ sceneAndMetadata: previousSceneAndMetadata,
+ nextSceneAndMetadata: sceneAndMetadata,
+ canvasLayout,
+ });
+};
diff --git a/packages/template-recorder/remotion/animations/webcam-transitions/helpers.ts b/packages/template-recorder/remotion/animations/webcam-transitions/helpers.ts
new file mode 100644
index 0000000000..ef98e43390
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/webcam-transitions/helpers.ts
@@ -0,0 +1,60 @@
+import type { SceneAndMetadata, WebcamPosition } from "../../../config/scenes";
+
+export const isWebCamAtBottom = (webcamPosition: WebcamPosition) => {
+ if (webcamPosition === "center") {
+ throw new Error("Webcam position cannot be center if checking at bottom");
+ }
+
+ return webcamPosition === "bottom-left" || webcamPosition === "bottom-right";
+};
+
+export const isWebCamRight = (webcamPosition: WebcamPosition) => {
+ if (webcamPosition === "center") {
+ throw new Error("Webcam position cannot be center if checking at right");
+ }
+
+ return webcamPosition === "top-right" || webcamPosition === "bottom-right";
+};
+
+export const isGrowingFromMiniature = ({
+ firstScene,
+ secondScene,
+}: {
+ firstScene: SceneAndMetadata;
+ secondScene: SceneAndMetadata;
+}) => {
+ if (secondScene.type !== "video-scene") {
+ return false;
+ }
+
+ if (firstScene.type !== "video-scene") {
+ return false;
+ }
+
+ const toMiniature =
+ firstScene.layout.displayLayout !== null &&
+ secondScene.layout.displayLayout === null;
+
+ return toMiniature;
+};
+
+export const isShrinkingToMiniature = ({
+ firstScene,
+ secondScene,
+}: {
+ firstScene: SceneAndMetadata;
+ secondScene: SceneAndMetadata;
+}) => {
+ if (secondScene.type !== "video-scene") {
+ return false;
+ }
+
+ if (firstScene.type !== "video-scene") {
+ return false;
+ }
+
+ return (
+ firstScene.layout.displayLayout === null &&
+ secondScene.layout.displayLayout !== null
+ );
+};
diff --git a/packages/template-recorder/remotion/animations/webcam-transitions/index.ts b/packages/template-recorder/remotion/animations/webcam-transitions/index.ts
new file mode 100644
index 0000000000..5df6a380d0
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/webcam-transitions/index.ts
@@ -0,0 +1,93 @@
+import type { CanvasLayout } from "../../../config/layout";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { Layout, LayoutAndFade } from "../../layout/layout-types";
+import { interpolateLayoutAndFade } from "../interpolate-layout";
+import { getLandscapeWebCamStartOrEndLayout } from "./landscape";
+import { getSquareWebcamStartOrEndLayout } from "./square";
+
+const getWebCamStartOrEndLayout = ({
+ canvasWidth,
+ canvasHeight,
+ canvasLayout,
+ otherScene,
+ currentScene,
+}: {
+ otherScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ canvasWidth: number;
+ canvasHeight: number;
+ canvasLayout: CanvasLayout;
+}): LayoutAndFade => {
+ if (canvasLayout === "landscape") {
+ return getLandscapeWebCamStartOrEndLayout({
+ currentScene,
+ otherScene,
+ canvasWidth,
+ });
+ }
+
+ if (canvasLayout === "square") {
+ return getSquareWebcamStartOrEndLayout({
+ currentScene,
+ canvasHeight,
+ otherScene,
+ });
+ }
+
+ throw new Error(`Unknown canvas layout: ${canvasLayout satisfies never}`);
+};
+
+export const getWebcamLayout = ({
+ enterProgress,
+ exitProgress,
+ canvasWidth,
+ canvasHeight,
+ canvasLayout,
+ currentScene,
+ nextScene,
+ previousScene,
+}: {
+ enterProgress: number;
+ exitProgress: number;
+ canvasWidth: number;
+ canvasHeight: number;
+ canvasLayout: CanvasLayout;
+ nextScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ previousScene: SceneAndMetadata | null;
+}): Layout => {
+ const startLayout = getWebCamStartOrEndLayout({
+ canvasLayout,
+ currentScene,
+ otherScene: previousScene,
+ canvasWidth,
+ canvasHeight,
+ });
+
+ const endLayout = getWebCamStartOrEndLayout({
+ canvasLayout,
+ currentScene,
+ canvasHeight,
+ otherScene: nextScene,
+ canvasWidth,
+ });
+
+ if (exitProgress > 0) {
+ return interpolateLayoutAndFade(
+ currentScene.layout.webcamLayout,
+ endLayout.layout,
+ exitProgress,
+ false,
+ );
+ }
+
+ return interpolateLayoutAndFade(
+ startLayout.layout,
+ currentScene.layout.webcamLayout,
+ enterProgress,
+ startLayout.shouldFadeRecording,
+ );
+};
diff --git a/packages/template-recorder/remotion/animations/webcam-transitions/landscape.ts b/packages/template-recorder/remotion/animations/webcam-transitions/landscape.ts
new file mode 100644
index 0000000000..7fc8afd829
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/webcam-transitions/landscape.ts
@@ -0,0 +1,63 @@
+import { getSafeSpace } from "../../../config/layout";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { LayoutAndFade } from "../../layout/layout-types";
+import { isWebCamRight } from "./helpers";
+
+export const getLandscapeWebCamStartOrEndLayout = ({
+ canvasWidth,
+ otherScene,
+ currentScene,
+}: {
+ otherScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ canvasWidth: number;
+}): LayoutAndFade => {
+ const currentLayout = currentScene.layout.webcamLayout;
+
+ if (!otherScene || otherScene.type !== "video-scene") {
+ return { layout: currentLayout, shouldFadeRecording: false };
+ }
+
+ // When at least 1 scene is fullscreen, the webcam can just move to the new position.
+ if (!currentScene.layout.displayLayout || !otherScene.layout.displayLayout) {
+ // The next display may overlap the webcam, so we cannot use a fade
+ return {
+ layout: otherScene.layout.webcamLayout,
+ shouldFadeRecording: false,
+ };
+ }
+
+ // Same position vertically, webcam can just move to the new position
+ if (
+ isWebCamRight(otherScene.webcamPosition) ===
+ isWebCamRight(currentScene.webcamPosition)
+ ) {
+ return {
+ layout: otherScene.layout.webcamLayout,
+ shouldFadeRecording: true,
+ };
+ }
+
+ // Display is in the way, webcam needs to animate out of the edge
+ // and appear from the other side
+ if (isWebCamRight(currentScene.webcamPosition)) {
+ return {
+ layout: {
+ ...currentLayout,
+ left: canvasWidth + getSafeSpace("landscape"),
+ },
+ shouldFadeRecording: false,
+ };
+ }
+
+ return {
+ layout: {
+ ...currentLayout,
+ left: -getSafeSpace("landscape") - currentLayout.width,
+ },
+ shouldFadeRecording: false,
+ };
+};
diff --git a/packages/template-recorder/remotion/animations/webcam-transitions/square.ts b/packages/template-recorder/remotion/animations/webcam-transitions/square.ts
new file mode 100644
index 0000000000..c95e22efe9
--- /dev/null
+++ b/packages/template-recorder/remotion/animations/webcam-transitions/square.ts
@@ -0,0 +1,69 @@
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { LayoutAndFade } from "../../layout/layout-types";
+import { isWebCamAtBottom } from "./helpers";
+
+export const getSquareWebcamStartOrEndLayout = ({
+ otherScene,
+ currentScene,
+ canvasHeight,
+}: {
+ otherScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ canvasHeight: number;
+}): LayoutAndFade => {
+ if (!currentScene || currentScene.type !== "video-scene") {
+ throw new Error("no transitions on non-video scenes");
+ }
+
+ const currentLayout = currentScene.layout.webcamLayout;
+
+ // No entrance if the other scene is not a video scene
+ if (!otherScene || otherScene.type !== "video-scene") {
+ return {
+ layout: currentScene.layout.webcamLayout,
+ shouldFadeRecording: false,
+ };
+ }
+
+ // When at least 1 scene is fullscreen, the webcam can just move to the new position
+ if (!currentScene.layout.displayLayout || !otherScene.layout.displayLayout) {
+ return {
+ layout: otherScene.layout.webcamLayout,
+ shouldFadeRecording: true,
+ };
+ }
+
+ // Same position horizontally, webcam can just move to the new position
+ if (
+ isWebCamAtBottom(otherScene.webcamPosition) ===
+ isWebCamAtBottom(currentScene.webcamPosition)
+ ) {
+ return {
+ layout: otherScene.layout.webcamLayout,
+ shouldFadeRecording: true,
+ };
+ }
+
+ // Display is moving from bottom to top or vice versa
+ // Webcam will animate out of the edge and appear from the other side
+ if (isWebCamAtBottom(currentScene.webcamPosition)) {
+ return {
+ layout: {
+ ...currentLayout,
+ top: canvasHeight,
+ },
+ shouldFadeRecording: false,
+ };
+ }
+
+ return {
+ layout: {
+ ...currentLayout,
+ top: -currentLayout.height,
+ },
+ shouldFadeRecording: false,
+ };
+};
diff --git a/packages/template-recorder/remotion/audio/AudioTrack.tsx b/packages/template-recorder/remotion/audio/AudioTrack.tsx
new file mode 100644
index 0000000000..5e04a2f094
--- /dev/null
+++ b/packages/template-recorder/remotion/audio/AudioTrack.tsx
@@ -0,0 +1,187 @@
+import React, { useMemo } from "react";
+import { Audio, interpolate, Sequence, useVideoConfig } from "remotion";
+import type { CanvasLayout } from "../../config/layout";
+import type { SceneAndMetadata } from "../../config/scenes";
+import {
+ AUDIO_FADE_IN_FRAMES,
+ BACKGROUND_VOLUME,
+ getAudioSource,
+ REGULAR_VOLUME,
+} from "../../config/sounds";
+import { SCENE_TRANSITION_DURATION } from "../../config/transitions";
+import { getShouldTransitionOut } from "../animations/transitions";
+
+type LoudPart = [number, number];
+
+type TAudioTrack = {
+ from: number;
+ src: string;
+ duration: number;
+ loudParts: LoudPart[];
+};
+
+const calculateVolume =
+ ({
+ durationInFrames,
+ loudParts,
+ }: {
+ durationInFrames: number;
+ loudParts: LoudPart[];
+ }) =>
+ (f: number) => {
+ let isLoudPart: null | [number, number] = null;
+ for (const loudPart of loudParts) {
+ const [from, to] = loudPart;
+ if (f >= from && f <= to) {
+ isLoudPart = [from, to];
+ break;
+ }
+ }
+
+ const regularVolume = interpolate(
+ f,
+ [
+ 0,
+ AUDIO_FADE_IN_FRAMES,
+ durationInFrames - AUDIO_FADE_IN_FRAMES,
+ durationInFrames - 1,
+ ],
+ [0, BACKGROUND_VOLUME, BACKGROUND_VOLUME, 0],
+ {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp",
+ },
+ );
+
+ if (isLoudPart) {
+ const loudPartDuration = isLoudPart[1] - isLoudPart[0];
+ const isTooShort = loudPartDuration <= AUDIO_FADE_IN_FRAMES * 2;
+ const firstKeyFrame = isTooShort
+ ? loudPartDuration / 2 + isLoudPart[0]
+ : isLoudPart[0] + AUDIO_FADE_IN_FRAMES;
+ const secondKeyFrame = isTooShort
+ ? loudPartDuration / 2 + isLoudPart[0] + 1
+ : isLoudPart[1] - AUDIO_FADE_IN_FRAMES;
+ return interpolate(
+ f,
+ [isLoudPart[0], firstKeyFrame, secondKeyFrame, isLoudPart[1]],
+ [regularVolume, REGULAR_VOLUME, REGULAR_VOLUME, regularVolume],
+ );
+ }
+
+ return regularVolume;
+ };
+
+const AudioClip: React.FC<{
+ src: string;
+ loudParts: LoudPart[];
+}> = ({ src, loudParts }) => {
+ const { durationInFrames } = useVideoConfig();
+
+ const volumeFunction = useMemo(() => {
+ return calculateVolume({ durationInFrames, loudParts });
+ }, [durationInFrames, loudParts]);
+
+ return (
+ <Audio
+ // Lint false positive: https://github.com/remotion-dev/remotion/issues/2706
+ // eslint-disable-next-line @remotion/volume-callback
+ volume={volumeFunction}
+ loopVolumeCurveBehavior="extend"
+ src={src}
+ loop
+ />
+ );
+};
+
+export const AudioTrack: React.FC<{
+ scenesAndMetadata: SceneAndMetadata[];
+ canvasLayout: CanvasLayout;
+}> = ({ scenesAndMetadata, canvasLayout }) => {
+ let addedUpDurations = 0;
+ const audioClips: TAudioTrack[] = [];
+
+ scenesAndMetadata.forEach((scene, i) => {
+ const metadataForScene = scenesAndMetadata[i];
+ if (!metadataForScene) {
+ return null;
+ }
+
+ const from = addedUpDurations;
+ addedUpDurations += metadataForScene.durationInFrames;
+ const isTransitioningOut = getShouldTransitionOut({
+ sceneAndMetadata: scene,
+ nextSceneAndMetadata: scenesAndMetadata[i + 1] ?? null,
+ canvasLayout,
+ });
+ if (isTransitioningOut) {
+ addedUpDurations -= SCENE_TRANSITION_DURATION;
+ }
+
+ const isLoud = scene.type !== "video-scene";
+
+ const { music } = scene.scene;
+
+ if (music === "previous" && audioClips.length > 0) {
+ const lastAudioClip = audioClips[audioClips.length - 1] as TAudioTrack;
+
+ lastAudioClip.duration += metadataForScene.durationInFrames;
+
+ if (isTransitioningOut) {
+ lastAudioClip.duration -= SCENE_TRANSITION_DURATION;
+ }
+
+ if (isLoud) {
+ const lastLoudPart =
+ lastAudioClip.loudParts[lastAudioClip.loudParts.length - 1];
+
+ const end = from + metadataForScene.durationInFrames;
+
+ if (lastLoudPart && lastLoudPart[1] > from) {
+ lastLoudPart[1] = end;
+ } else {
+ lastAudioClip.loudParts.push([from, end]);
+ }
+ }
+ } else {
+ if (music === "previous") {
+ return;
+ }
+
+ audioClips.push({
+ src: getAudioSource(music),
+ duration: metadataForScene.durationInFrames,
+ from,
+ loudParts: isLoud
+ ? [[from, from + metadataForScene.durationInFrames]]
+ : [],
+ });
+ }
+ });
+
+ return (
+ <>
+ {audioClips.map((clip) => {
+ if (clip.src === "none") {
+ return null;
+ }
+
+ return (
+ <Sequence
+ key={clip.from}
+ from={clip.from}
+ layout="none"
+ durationInFrames={clip.duration}
+ >
+ <AudioClip
+ src={clip.src}
+ loudParts={clip.loudParts.map((l) => {
+ return [l[0] - clip.from, l[1] - clip.from] as LoudPart;
+ })}
+ />
+ </Sequence>
+ );
+ })}
+ </>
+ );
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/add-chapters-to-scenes.ts b/packages/template-recorder/remotion/calculate-metadata/add-chapters-to-scenes.ts
new file mode 100644
index 0000000000..52d47e9e03
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/add-chapters-to-scenes.ts
@@ -0,0 +1,26 @@
+import { SceneAndMetadata } from "../../config/scenes";
+
+export const addChaptersToScenesAndMetadata = (
+ scenesAndMetadata: SceneAndMetadata[],
+): SceneAndMetadata[] => {
+ let currentChapter: string | null = null;
+ const newScenes: SceneAndMetadata[] = [];
+
+ for (const scene of scenesAndMetadata) {
+ if (scene.type !== "video-scene") {
+ newScenes.push(scene);
+ continue;
+ }
+
+ if (scene.scene.newChapter) {
+ currentChapter = scene.scene.newChapter;
+ }
+
+ newScenes.push({ ...scene, chapter: currentChapter });
+ if (scene.scene.stopChapteringAfterThis) {
+ currentChapter = null;
+ }
+ }
+
+ return newScenes;
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/add-durations-to-scenes.ts b/packages/template-recorder/remotion/calculate-metadata/add-durations-to-scenes.ts
new file mode 100644
index 0000000000..ece0407581
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/add-durations-to-scenes.ts
@@ -0,0 +1,88 @@
+import { CanvasLayout } from "../../config/layout";
+import { SceneAndMetadata } from "../../config/scenes";
+import { SCENE_TRANSITION_DURATION } from "../../config/transitions";
+import {
+ getShouldTransitionIn,
+ getShouldTransitionOut,
+} from "../animations/transitions";
+import { applyBRollRules } from "../scenes/BRoll/apply-b-roll-rules";
+import { addPlaceholderIfNoScenes } from "./empty-place-holder";
+
+export const addDurationsToScenes = (
+ scenes: SceneAndMetadata[],
+ canvasLayout: CanvasLayout,
+): {
+ totalDurationInFrames: number;
+ scenesAndMetadataWithDuration: SceneAndMetadata[];
+} => {
+ let totalDurationInFrames = 0;
+
+ const scenesAndMetadataWithDuration: SceneAndMetadata[] = scenes.map(
+ (sceneAndMetadata, i): SceneAndMetadata => {
+ const previousSceneAndMetadata = scenes[i - 1] ?? null;
+ const nextSceneAndMetadata = scenes[i + 1] ?? null;
+
+ const isTransitioningIn = getShouldTransitionIn({
+ previousSceneAndMetadata,
+ sceneAndMetadata,
+ canvasLayout,
+ });
+ const isTransitioningOut = getShouldTransitionOut({
+ sceneAndMetadata,
+ nextSceneAndMetadata,
+ canvasLayout,
+ });
+
+ if (isTransitioningIn) {
+ totalDurationInFrames -= SCENE_TRANSITION_DURATION;
+ }
+
+ const from = totalDurationInFrames;
+ totalDurationInFrames += sceneAndMetadata.durationInFrames;
+
+ if (sceneAndMetadata.type === "other-scene") {
+ return {
+ ...sceneAndMetadata,
+ from,
+ };
+ }
+
+ let sceneDurationInFrames = sceneAndMetadata.durationInFrames;
+
+ let startFrame = sceneAndMetadata.startFrame;
+
+ if (isTransitioningIn) {
+ startFrame -= SCENE_TRANSITION_DURATION;
+
+ if (startFrame < 0) {
+ startFrame = 0;
+ }
+
+ const additionalTransitionFrames =
+ sceneAndMetadata.startFrame - startFrame;
+
+ totalDurationInFrames += additionalTransitionFrames;
+ sceneDurationInFrames += additionalTransitionFrames;
+ }
+
+ const retValue: SceneAndMetadata = {
+ ...sceneAndMetadata,
+ bRolls: applyBRollRules({
+ bRolls: sceneAndMetadata.bRolls,
+ sceneDurationInFrames: sceneDurationInFrames,
+ willTransitionToNextScene: isTransitioningOut,
+ }),
+ startFrame,
+ durationInFrames: sceneDurationInFrames,
+ from,
+ };
+
+ return retValue;
+ },
+ );
+
+ return addPlaceholderIfNoScenes({
+ totalDurationInFrames: totalDurationInFrames,
+ scenesAndMetadataWithDuration,
+ });
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/add-metadata-to-scene.ts b/packages/template-recorder/remotion/calculate-metadata/add-metadata-to-scene.ts
new file mode 100644
index 0000000000..e7951e92a7
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/add-metadata-to-scene.ts
@@ -0,0 +1,126 @@
+import { parseMedia } from "@remotion/media-parser";
+import { CanvasLayout } from "../../config/layout";
+import {
+ Cameras,
+ SceneAndMetadata,
+ SceneVideos,
+ SelectableScene,
+} from "../../config/scenes";
+import { calculateSrt } from "../captions/srt/helpers/calculate-srt";
+import { getBRollDimensions } from "../layout/get-broll-dimensions";
+import { getVideoSceneLayout } from "../layout/get-layout";
+import { PLACEHOLDER_DURATION_IN_FRAMES } from "./empty-place-holder";
+import { fetchCaptions } from "./fetch-captions";
+import { getFinalWebcamPosition } from "./get-final-webcam-position";
+import { getStartEndFrame } from "./get-start-end-frame";
+
+export const addMetadataToScene = async ({
+ scene,
+ cameras,
+ hasAtLeast1Camera,
+ allScenes,
+ canvasLayout,
+}: {
+ scene: SelectableScene;
+ cameras: Cameras | null;
+ hasAtLeast1Camera: boolean;
+ canvasLayout: CanvasLayout;
+ allScenes: SelectableScene[];
+}): Promise<SceneAndMetadata> => {
+ if (scene.type !== "videoscene") {
+ return {
+ type: "other-scene",
+ scene,
+ durationInFrames: scene.durationInFrames,
+ from: 0,
+ };
+ }
+
+ if (!cameras) {
+ return {
+ type: "other-scene",
+ scene: {
+ type: hasAtLeast1Camera ? "nomorerecordings" : "norecordings",
+ transitionToNextScene: scene.transitionToNextScene,
+ music: scene.music,
+ },
+ durationInFrames: PLACEHOLDER_DURATION_IN_FRAMES,
+ from: 0,
+ };
+ }
+
+ const webcamMetadata = await parseMedia({
+ src: cameras.webcam.src,
+ fields: {
+ durationInSeconds: true,
+ dimensions: true,
+ },
+ acknowledgeRemotionLicense: true,
+ });
+
+ if (!webcamMetadata.dimensions) {
+ throw new Error("No dimensions for webcam");
+ }
+ if (!webcamMetadata.durationInSeconds) {
+ throw new Error("No duration for webcam");
+ }
+
+ const displayMetadata = cameras.display
+ ? await parseMedia({
+ src: cameras.display.src,
+ fields: { dimensions: true, durationInSeconds: true },
+ acknowledgeRemotionLicense: true,
+ })
+ : null;
+
+ const captions = await fetchCaptions(cameras.captions);
+
+ const { actualStartFrame, derivedEndFrame } = await getStartEndFrame({
+ scene,
+ recordingDurationInSeconds: webcamMetadata.durationInSeconds,
+ captions,
+ });
+
+ const srt = captions
+ ? calculateSrt({
+ startFrame: actualStartFrame,
+ captions,
+ })
+ : [];
+
+ const webcamPosition = getFinalWebcamPosition({
+ canvasLayout,
+ cameras,
+ scenes: allScenes,
+ scene,
+ });
+
+ const bRollWithDimensions = await Promise.all(
+ scene.bRolls.map((bRoll) => getBRollDimensions(bRoll)),
+ );
+
+ const videos: SceneVideos = {
+ display: displayMetadata?.dimensions ?? null,
+ webcam: webcamMetadata.dimensions,
+ };
+
+ return {
+ type: "video-scene",
+ scene,
+ videos,
+ layout: getVideoSceneLayout({
+ webcamPosition: webcamPosition,
+ videos,
+ canvasLayout,
+ }),
+ durationInFrames: derivedEndFrame - actualStartFrame,
+ cameras,
+ webcamPosition: webcamPosition,
+ from: 0,
+ chapter: scene.newChapter ?? null,
+ startFrame: actualStartFrame,
+ endFrame: derivedEndFrame,
+ bRolls: bRollWithDimensions,
+ srt,
+ };
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/calc-metadata.ts b/packages/template-recorder/remotion/calculate-metadata/calc-metadata.ts
new file mode 100644
index 0000000000..5c7f9a5209
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/calc-metadata.ts
@@ -0,0 +1,50 @@
+import type { CalculateMetadataFunction } from "remotion";
+import { FPS } from "../../config/fps";
+import type { MainProps } from "../Main";
+import { getDimensionsForLayout } from "../layout/dimensions";
+import { addChaptersToScenesAndMetadata } from "./add-chapters-to-scenes";
+import { addDurationsToScenes } from "./add-durations-to-scenes";
+import { addMetadataToScene } from "./add-metadata-to-scene";
+import { getAllCameras } from "./get-camera";
+
+export const calcMetadata: CalculateMetadataFunction<MainProps> = async ({
+ props,
+ compositionId,
+}) => {
+ const { hasAtLeast1Camera, scenesWithCameras } = getAllCameras({
+ compositionId,
+ scenes: props.scenes,
+ });
+
+ const withMetadata = await Promise.all(
+ scenesWithCameras.map(({ scene, cameras }) =>
+ addMetadataToScene({
+ scene,
+ cameras,
+ hasAtLeast1Camera,
+ allScenes: props.scenes,
+ canvasLayout: props.canvasLayout,
+ }),
+ ),
+ );
+
+ const {
+ totalDurationInFrames: durationInFrames,
+ scenesAndMetadataWithDuration: withDurations,
+ } = addDurationsToScenes(withMetadata, props.canvasLayout);
+
+ const withChapters = addChaptersToScenesAndMetadata(withDurations);
+
+ const { height, width } = getDimensionsForLayout(props.canvasLayout);
+
+ return {
+ durationInFrames,
+ height,
+ width,
+ fps: FPS,
+ props: {
+ ...props,
+ scenesAndMetadata: withChapters,
+ },
+ };
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/empty-place-holder.ts b/packages/template-recorder/remotion/calculate-metadata/empty-place-holder.ts
new file mode 100644
index 0000000000..b2b91faaec
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/empty-place-holder.ts
@@ -0,0 +1,37 @@
+import { SceneAndMetadata } from "../../config/scenes";
+
+export const PLACEHOLDER_DURATION_IN_FRAMES = 60;
+
+export const addPlaceholderIfNoScenes = ({
+ totalDurationInFrames,
+ scenesAndMetadataWithDuration,
+}: {
+ totalDurationInFrames: number;
+ scenesAndMetadataWithDuration: SceneAndMetadata[];
+}): {
+ totalDurationInFrames: number;
+ scenesAndMetadataWithDuration: SceneAndMetadata[];
+} => {
+ if (scenesAndMetadataWithDuration.length > 0) {
+ return {
+ scenesAndMetadataWithDuration,
+ totalDurationInFrames,
+ };
+ }
+
+ return {
+ scenesAndMetadataWithDuration: [
+ {
+ type: "other-scene" as const,
+ scene: {
+ type: "noscenes" as const,
+ music: "none",
+ transitionToNextScene: true,
+ },
+ durationInFrames: PLACEHOLDER_DURATION_IN_FRAMES,
+ from: 0,
+ },
+ ],
+ totalDurationInFrames: PLACEHOLDER_DURATION_IN_FRAMES,
+ };
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/fetch-captions.ts b/packages/template-recorder/remotion/calculate-metadata/fetch-captions.ts
new file mode 100644
index 0000000000..e2ec7f7993
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/fetch-captions.ts
@@ -0,0 +1,25 @@
+import { Caption } from "@remotion/captions";
+import { StaticFile } from "@remotion/studio";
+
+export const fetchCaptions = async (
+ file: StaticFile | null,
+): Promise<Caption[] | null> => {
+ if (!file) {
+ return null;
+ }
+
+ try {
+ const res = await fetch(file.src);
+ const data = await res.json();
+ if (data.systeminfo) {
+ throw new Error(
+ `The file ${file.src} is a Whisper.cpp output. The file format has changed, you can migrate using: https://gist.github.com/JonnyBurger/96e1c1945e16ba1a54530d127f4060d5`,
+ );
+ }
+ const captions = data as Caption[];
+ return captions;
+ } catch (error) {
+ console.error("Error fetching WhisperOutput from JSON:", error);
+ return null;
+ }
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/get-camera.ts b/packages/template-recorder/remotion/calculate-metadata/get-camera.ts
new file mode 100644
index 0000000000..1b22c6f2c4
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/get-camera.ts
@@ -0,0 +1,126 @@
+import { StaticFile, getStaticFiles } from "remotion";
+import {
+ ALTERNATIVE1_PREFIX,
+ ALTERNATIVE2_PREFIX,
+ CAPTIONS_PREFIX,
+ DISPLAY_PREFIX,
+ WEBCAM_PREFIX,
+} from "../../config/cameras";
+import { Cameras, SelectableScene } from "../../config/scenes";
+
+type CamerasAndScene = {
+ scene: SelectableScene;
+ cameras: Cameras | null;
+};
+
+const findMatchingFile = ({
+ files,
+ compositionId,
+ prefix,
+ timestamp,
+}: {
+ files: StaticFile[];
+ compositionId: string;
+ prefix: string;
+ timestamp: string;
+}): StaticFile | null => {
+ const sub = files.find((_f) =>
+ _f.name.startsWith(`${compositionId}/${prefix}${timestamp}.`),
+ );
+
+ return sub ?? null;
+};
+
+const mapFile = ({
+ file,
+ files,
+ compositionId,
+}: {
+ file: StaticFile;
+ files: StaticFile[];
+ compositionId: string;
+}): Cameras | null => {
+ if (!file.name.startsWith(`${compositionId}/${WEBCAM_PREFIX}`)) {
+ return null;
+ }
+
+ const timestamp = file.name
+ // compositionId is case sensitive:
+ // Need to replace it first before calling .toLowerCase()
+ .replace(`${compositionId}/${WEBCAM_PREFIX}`, "")
+ .toLowerCase()
+ .replace(".webm", "")
+ .replace(".mov", "")
+ .replace(".mkv", "")
+ .replace(".mp4", "");
+
+ const display = findMatchingFile({
+ files,
+ compositionId,
+ prefix: DISPLAY_PREFIX,
+ timestamp,
+ });
+ const sub = findMatchingFile({
+ files,
+ compositionId,
+ prefix: CAPTIONS_PREFIX,
+ timestamp,
+ });
+ const alternative1 = findMatchingFile({
+ files,
+ compositionId,
+ prefix: ALTERNATIVE1_PREFIX,
+ timestamp,
+ });
+ const alternative2 = findMatchingFile({
+ compositionId,
+ files,
+ prefix: ALTERNATIVE2_PREFIX,
+ timestamp,
+ });
+
+ return {
+ webcam: file,
+ display: display ?? null,
+ captions: sub ?? null,
+ alternative1: alternative1 ?? null,
+ alternative2: alternative2 ?? null,
+ timestamp: parseInt(timestamp, 10),
+ };
+};
+
+const getCameras = (compositionId: string) => {
+ const files = getStaticFiles().filter((f) =>
+ f.name.startsWith(compositionId),
+ );
+
+ const mappedCameras = files
+ .map((f) => mapFile({ file: f, files, compositionId }))
+ .filter(Boolean) as Cameras[];
+
+ return mappedCameras.sort((a, b) => a.timestamp - b.timestamp);
+};
+
+export const getAllCameras = ({
+ compositionId,
+ scenes,
+}: {
+ compositionId: string;
+ scenes: SelectableScene[];
+}) => {
+ const allCameras = getCameras(compositionId);
+ let videoIndex = -1;
+
+ const scenesWithCameras = scenes.map((scene): CamerasAndScene => {
+ if (scene.type !== "videoscene") {
+ return { cameras: null, scene };
+ }
+
+ videoIndex += 1;
+ return { scene, cameras: allCameras[videoIndex] as Cameras };
+ });
+
+ const hasAtLeast1Camera = allCameras.length > 0;
+
+ return { scenesWithCameras, hasAtLeast1Camera };
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/get-final-webcam-position.ts b/packages/template-recorder/remotion/calculate-metadata/get-final-webcam-position.ts
new file mode 100644
index 0000000000..ded8891425
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/get-final-webcam-position.ts
@@ -0,0 +1,46 @@
+import { CanvasLayout } from "../../config/layout";
+import {
+ Cameras,
+ SelectableScene,
+ SelectableVideoScene,
+ WebcamPosition,
+} from "../../config/scenes";
+
+export const getFinalWebcamPosition = ({
+ scenes,
+ scene,
+ cameras,
+ canvasLayout,
+}: {
+ scenes: SelectableScene[];
+ scene: SelectableVideoScene;
+ cameras: Cameras;
+ canvasLayout: CanvasLayout;
+}): WebcamPosition => {
+ if (!cameras.display && canvasLayout === "landscape") {
+ return "center";
+ }
+
+ let idx = scenes.findIndex((s) => s === scene);
+
+ let webcamPosition = scene.webcamPosition;
+
+ while (webcamPosition === "previous" && idx >= 0) {
+ const prevScene = scenes[idx] as SelectableScene;
+ if (prevScene.type === "videoscene") {
+ webcamPosition = prevScene.webcamPosition;
+ }
+
+ if (webcamPosition === "previous" && idx === 0) {
+ webcamPosition = "top-left";
+ }
+
+ idx -= 1;
+ }
+
+ if (webcamPosition === "previous") {
+ throw new Error('Invalid webcam position "previous"');
+ }
+
+ return webcamPosition;
+};
diff --git a/packages/template-recorder/remotion/calculate-metadata/get-start-end-frame.ts b/packages/template-recorder/remotion/calculate-metadata/get-start-end-frame.ts
new file mode 100644
index 0000000000..1e9f144ac2
--- /dev/null
+++ b/packages/template-recorder/remotion/calculate-metadata/get-start-end-frame.ts
@@ -0,0 +1,115 @@
+import { Caption } from "@remotion/captions";
+import { FPS } from "../../config/fps";
+import { SelectableVideoScene } from "../../config/scenes";
+import { postprocessCaptions } from "../captions/processing/postprocess-subs";
+
+const START_FRAME_PADDING = Math.ceil(FPS / 4);
+const END_FRAME_PADDING = FPS / 2;
+
+const deriveEndFrameFromSubs = (captions: Caption[] | null) => {
+ if (!captions) {
+ return null;
+ }
+
+ const lastCaption = captions[captions.length - 1];
+ if (!lastCaption || !lastCaption.timestampMs) {
+ return null;
+ }
+
+ const lastFrame = Math.floor((lastCaption.timestampMs / 1000) * FPS);
+ return lastFrame;
+};
+
+const deriveStartFrameFromSubsJSON = (captions: Caption[] | null): number => {
+ if (!captions) {
+ return 0;
+ }
+ if (captions.length === 0) {
+ return 0;
+ }
+
+ // taking the first real word and take its start timestamp in ms.
+ const startFromInHundrethsOfSec = (captions[0] as Caption).timestampMs;
+ if (startFromInHundrethsOfSec === null) {
+ return 0;
+ }
+
+ const startFromInFrames =
+ Math.floor((startFromInHundrethsOfSec / 1000) * FPS) - START_FRAME_PADDING;
+ return startFromInFrames > 0 ? startFromInFrames : 0;
+};
+
+const getClampedStartFrame = ({
+ startOffset,
+ startFrameFromSubs,
+ derivedEndFrame,
+}: {
+ startOffset: number;
+ startFrameFromSubs: number;
+ derivedEndFrame: number;
+}): number => {
+ const combinedStartFrame = startFrameFromSubs + startOffset;
+
+ if (combinedStartFrame > derivedEndFrame) {
+ return derivedEndFrame;
+ }
+
+ if (combinedStartFrame < 0) {
+ return 0;
+ }
+
+ return combinedStartFrame;
+};
+
+const getClampedEndFrame = ({
+ durationInSeconds,
+ endFrameFromCaptions,
+ endOffset,
+}: {
+ endOffset: number;
+ durationInSeconds: number;
+ endFrameFromCaptions: number | null;
+}): number => {
+ const videoDurationInFrames = Math.floor(durationInSeconds * FPS);
+ if (!endFrameFromCaptions) {
+ return Math.min(videoDurationInFrames, videoDurationInFrames + endOffset);
+ }
+
+ const paddedEndFrame = endFrameFromCaptions + END_FRAME_PADDING + endOffset;
+ if (paddedEndFrame > videoDurationInFrames) {
+ return videoDurationInFrames;
+ }
+
+ return paddedEndFrame;
+};
+
+export const getStartEndFrame = async ({
+ scene,
+ recordingDurationInSeconds,
+ captions,
+}: {
+ scene: SelectableVideoScene;
+ recordingDurationInSeconds: number;
+ captions: Caption[] | null;
+}) => {
+ // We calculate the subtitles only for
+ // the purpose of calculating the durastion
+ // and will not use this value further
+ const subsForTimestamps = captions ? postprocessCaptions(captions) : null;
+
+ const endFrameFromCaptions = deriveEndFrameFromSubs(subsForTimestamps);
+ const derivedEndFrame = getClampedEndFrame({
+ durationInSeconds: recordingDurationInSeconds,
+ endFrameFromCaptions,
+ endOffset: scene.endOffset,
+ });
+
+ const startFrameFromSubs = deriveStartFrameFromSubsJSON(subsForTimestamps);
+ const actualStartFrame = getClampedStartFrame({
+ startOffset: scene.startOffset,
+ startFrameFromSubs,
+ derivedEndFrame,
+ });
+
+ return { actualStartFrame, derivedEndFrame };
+};
diff --git a/packages/template-recorder/remotion/captions/boxed/BoxedCaptions.tsx b/packages/template-recorder/remotion/captions/boxed/BoxedCaptions.tsx
new file mode 100644
index 0000000000..6a3f9fee46
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/boxed/BoxedCaptions.tsx
@@ -0,0 +1,62 @@
+import React from "react";
+import {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import { Theme } from "../../../config/themes";
+import { WaitForFonts } from "../../helpers/WaitForFonts";
+import { CaptionOverlay } from "../editor/CaptionOverlay";
+import { AnimatedCaptions } from "./components/AnimatedCaptions";
+import { NoCaptionsPlaceholder } from "./components/NoCaptionsPlaceholder";
+
+export const BoxedCaptions: React.FC<{
+ sceneAndMetadata: VideoSceneAndMetadata;
+ theme: Theme;
+ startFrame: number;
+ enterProgress: number;
+ exitProgress: number;
+ nextScene: SceneAndMetadata | null;
+ previousScene: SceneAndMetadata | null;
+}> = ({
+ sceneAndMetadata,
+ theme,
+ enterProgress,
+ exitProgress,
+ nextScene,
+ previousScene,
+ startFrame,
+}) => {
+ if (!sceneAndMetadata.layout.subtitleLayout) {
+ return null;
+ }
+
+ if (sceneAndMetadata.cameras.captions) {
+ return (
+ <WaitForFonts>
+ <CaptionOverlay
+ file={sceneAndMetadata.cameras.captions}
+ theme={theme}
+ trimStart={startFrame}
+ >
+ <AnimatedCaptions
+ trimStart={startFrame}
+ enterProgress={enterProgress}
+ exitProgress={exitProgress}
+ scene={sceneAndMetadata}
+ nextScene={nextScene}
+ previousScene={previousScene}
+ theme={theme}
+ subtitleLayout={sceneAndMetadata.layout.subtitleLayout}
+ />
+ </CaptionOverlay>
+ </WaitForFonts>
+ );
+ }
+
+ return (
+ <NoCaptionsPlaceholder
+ layout={sceneAndMetadata.layout.subtitleLayout}
+ theme={theme}
+ />
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/boxed/components/AnimatedCaptions.tsx b/packages/template-recorder/remotion/captions/boxed/components/AnimatedCaptions.tsx
new file mode 100644
index 0000000000..60eaa09088
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/boxed/components/AnimatedCaptions.tsx
@@ -0,0 +1,137 @@
+import React, { useMemo } from "react";
+import { AbsoluteFill, useVideoConfig } from "remotion";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../../config/scenes";
+import type { Theme } from "../../../../config/themes";
+import { COLORS } from "../../../../config/themes";
+import { shouldInlineTransitionSubtitles } from "../../../animations/caption-transitions/should-transition-subtitle";
+import { getSubtitleTransform } from "../../../animations/caption-transitions/subtitle-transitions";
+import { Layout } from "../../../layout/layout-types";
+import { useCaptions } from "../../editor/captions-provider";
+import { layoutCaptions } from "../../processing/layout-captions";
+import { postprocessCaptions } from "../../processing/postprocess-subs";
+import {
+ CaptionSentence,
+ getBorderWidthForSubtitles,
+ getSubtitlesLines,
+} from "./CaptionSentence";
+import {
+ TransitionFromPreviousSubtitles,
+ TransitionToNextSubtitles,
+} from "./TransitionBetweenSubtitles";
+
+const LINE_HEIGHT = 2;
+const SUBTITLES_FONT_SIZE = 56;
+
+export const AnimatedCaptions: React.FC<{
+ trimStart: number;
+ scene: VideoSceneAndMetadata;
+ enterProgress: number;
+ exitProgress: number;
+ nextScene: SceneAndMetadata | null;
+ previousScene: SceneAndMetadata | null;
+ theme: Theme;
+ subtitleLayout: Layout;
+}> = ({
+ trimStart,
+ scene,
+ enterProgress,
+ exitProgress,
+ nextScene,
+ previousScene,
+ theme,
+ subtitleLayout,
+}) => {
+ const { width, height } = useVideoConfig();
+
+ const shouldTransitionToNext = shouldInlineTransitionSubtitles({
+ currentScene: scene,
+ nextScene,
+ });
+ const shouldTransitionFromPrevious = shouldInlineTransitionSubtitles({
+ currentScene: scene,
+ nextScene: previousScene,
+ });
+
+ const captions = useCaptions();
+
+ const subtitleLines = getSubtitlesLines({
+ boxHeight: subtitleLayout.height,
+ fontSize: SUBTITLES_FONT_SIZE,
+ });
+
+ const postprocessed = useMemo(() => {
+ const processed = postprocessCaptions(captions);
+
+ return layoutCaptions({
+ boxWidth: subtitleLayout.width,
+ maxLines: subtitleLines,
+ fontSize: SUBTITLES_FONT_SIZE,
+ captions: processed,
+ });
+ }, [captions, subtitleLayout, subtitleLines]);
+
+ const outer: React.CSSProperties = useMemo(() => {
+ const backgroundColor = COLORS[theme].CAPTIONS_BACKGROUND;
+
+ return {
+ fontSize: SUBTITLES_FONT_SIZE,
+ display: "flex",
+ lineHeight: LINE_HEIGHT,
+ borderWidth: getBorderWidthForSubtitles(),
+ borderStyle: "solid",
+ borderColor: COLORS[theme].BORDER_COLOR,
+ backgroundColor,
+ justifyContent: "center",
+ ...getSubtitleTransform({
+ enterProgress,
+ exitProgress,
+ canvasHeight: height,
+ nextScene,
+ previousScene,
+ scene,
+ canvasWidth: width,
+ subtitleLayout,
+ }),
+ };
+ }, [
+ enterProgress,
+ exitProgress,
+ height,
+ nextScene,
+ previousScene,
+ scene,
+ subtitleLayout,
+ theme,
+ width,
+ ]);
+
+ return (
+ <AbsoluteFill style={outer}>
+ <TransitionFromPreviousSubtitles
+ shouldTransitionFromPreviousSubtitle={shouldTransitionFromPrevious}
+ >
+ <TransitionToNextSubtitles
+ shouldTransitionToNextsSubtitles={shouldTransitionToNext}
+ >
+ {postprocessed.segments.map((segment, index) => {
+ return (
+ <CaptionSentence
+ key={index}
+ isFirst={index === 0}
+ isLast={index === postprocessed.segments.length - 1}
+ segment={segment}
+ trimStart={trimStart}
+ theme={theme}
+ fontSize={SUBTITLES_FONT_SIZE}
+ lines={subtitleLines}
+ />
+ );
+ })}
+ </TransitionToNextSubtitles>
+ </TransitionFromPreviousSubtitles>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/boxed/components/CaptionSentence.tsx b/packages/template-recorder/remotion/captions/boxed/components/CaptionSentence.tsx
new file mode 100644
index 0000000000..2eabb5e71d
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/boxed/components/CaptionSentence.tsx
@@ -0,0 +1,112 @@
+import { Caption } from "@remotion/captions";
+import React from "react";
+import {
+ Sequence,
+ interpolate,
+ useCurrentFrame,
+ useVideoConfig,
+} from "remotion";
+import type { Theme } from "../../../../config/themes";
+import type { CaptionPage } from "../../types";
+import { LINE_HEIGHT, SquareSubtitles } from "./SquareSubtitles";
+
+const getStartOfSegment = (segment: CaptionPage) => {
+ if (segment.captions.length === 0) {
+ return 0;
+ }
+
+ return (segment.captions[0] as Caption).startMs;
+};
+
+const getEndOfSegment = (segment: CaptionPage) => {
+ if (segment.captions.length === 0) {
+ return 0;
+ }
+
+ return (segment.captions[segment.captions.length - 1] as Caption).endMs;
+};
+
+export const getSubtitlesFontSize = () => {
+ return 56;
+};
+
+export const getSubtitlesLines = ({
+ boxHeight,
+ fontSize,
+}: {
+ boxHeight: number;
+ fontSize: number;
+}) => {
+ const boxPadding = 50;
+
+ const nrOfLines = Math.floor(
+ (boxHeight - boxPadding) / (fontSize * LINE_HEIGHT),
+ );
+ return nrOfLines;
+};
+
+export const getBorderWidthForSubtitles = () => {
+ return 3;
+};
+
+const FadeSentence: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
+ const frame = useCurrentFrame();
+ const { durationInFrames } = useVideoConfig();
+
+ const opacity = interpolate(
+ frame,
+ [0, 5, Math.max(6, durationInFrames - 5), Math.max(7, durationInFrames)],
+ [0, 1, 1, 0],
+ {
+ extrapolateRight: "clamp",
+ extrapolateLeft: "clamp",
+ },
+ );
+
+ return <div style={{ opacity }}>{children}</div>;
+};
+
+export const CaptionSentence: React.FC<{
+ segment: CaptionPage;
+ isFirst: boolean;
+ isLast: boolean;
+ trimStart: number;
+ theme: Theme;
+ fontSize: number;
+ lines: number;
+}> = ({ segment, trimStart, isFirst, isLast, theme, fontSize, lines }) => {
+ const { fps } = useVideoConfig();
+ const normalStartFrame = (getStartOfSegment(segment) / 1000) * fps;
+ // If first caption of a segment, show it a bit earlier to avoid flicker
+ // of caption showing only shortly after the video
+ const startFrame = isFirst ? normalStartFrame - fps : normalStartFrame;
+ const endSegment = getEndOfSegment(segment);
+ const normalEndFrame = endSegment === null ? null : (endSegment / 1000) * fps;
+ const endFrame =
+ normalEndFrame === null
+ ? null
+ : isLast
+ ? normalEndFrame + fps
+ : normalEndFrame;
+
+ return (
+ <Sequence
+ showInTimeline={false}
+ from={startFrame - trimStart}
+ durationInFrames={endFrame === null ? undefined : endFrame - startFrame}
+ layout="none"
+ >
+ <FadeSentence>
+ <SquareSubtitles
+ segment={segment}
+ startFrame={startFrame}
+ theme={theme}
+ fontSize={fontSize}
+ lines={lines}
+ />
+ </FadeSentence>
+ </Sequence>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/boxed/components/NoCaptionsPlaceholder.tsx b/packages/template-recorder/remotion/captions/boxed/components/NoCaptionsPlaceholder.tsx
new file mode 100644
index 0000000000..7910dd1d7c
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/boxed/components/NoCaptionsPlaceholder.tsx
@@ -0,0 +1,50 @@
+import React, { useMemo } from "react";
+import { AbsoluteFill, getRemotionEnvironment } from "remotion";
+import { MONOSPACE_FONT, REGULAR_FONT } from "../../../../config/fonts";
+import type { Theme } from "../../../../config/themes";
+import { COLORS } from "../../../../config/themes";
+import type { Layout } from "../../../layout/layout-types";
+
+export const NoCaptionsPlaceholder: React.FC<{
+ layout: Layout;
+ theme: Theme;
+}> = ({ layout, theme }) => {
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ ...layout,
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ position: "absolute",
+ color: COLORS[theme].WORD_COLOR_ON_BG_APPEARED,
+ ...REGULAR_FONT,
+ border: `2px ${COLORS[theme].BORDER_COLOR} solid`,
+ backgroundColor: COLORS[theme].BACKGROUND,
+ fontSize: 28,
+ textAlign: "center",
+ padding: 20,
+ };
+ }, [layout, theme]);
+
+ const monospaceStyle: React.CSSProperties = useMemo(() => {
+ return {
+ ...MONOSPACE_FONT,
+ color: COLORS[theme].ACCENT_COLOR,
+ display: "inline",
+ };
+ }, [theme]);
+
+ if (getRemotionEnvironment().isRendering) {
+ return null;
+ }
+
+ return (
+ <AbsoluteFill style={style}>
+ <div>
+ No captions generated for this scene.
+ <br /> Run <code style={monospaceStyle}>bun sub.ts</code> to generate
+ captions.
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/boxed/components/SingleCaption.tsx b/packages/template-recorder/remotion/captions/boxed/components/SingleCaption.tsx
new file mode 100644
index 0000000000..94d5ff717b
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/boxed/components/SingleCaption.tsx
@@ -0,0 +1,192 @@
+import { Caption } from "@remotion/captions";
+import React, { useCallback, useMemo, useState } from "react";
+import {
+ interpolateColors,
+ spring,
+ useCurrentFrame,
+ useVideoConfig,
+} from "remotion";
+import { MONOSPACE_FONT, REGULAR_FONT } from "../../../../config/fonts";
+import type { Theme } from "../../../../config/themes";
+import { COLORS } from "../../../../config/themes";
+import { useCaptionOverlay } from "../../editor/use-caption-overlay";
+import {
+ isCaptionMonospace,
+ removeMonospaceTicks,
+} from "../../processing/split-caption-into-monospace-segments";
+
+type CaptionColor = {
+ appeared: string;
+ greyed: string;
+};
+
+const WORD_FADE_IN_DURATION_IN_MS = 100;
+
+const getShownCaptionColor = ({
+ appeared,
+ caption,
+ time,
+ captionColor,
+ active,
+}: {
+ appeared: boolean;
+ caption: Caption;
+ time: number;
+ captionColor: CaptionColor;
+ active: boolean;
+}) => {
+ if (!appeared) {
+ return captionColor.greyed;
+ }
+
+ if (isCaptionMonospace(caption)) {
+ if (active) {
+ return "white";
+ }
+
+ return captionColor.appeared;
+ }
+
+ return interpolateColors(
+ time,
+ [caption.startMs - WORD_FADE_IN_DURATION_IN_MS, caption.startMs],
+ [captionColor.greyed, captionColor.appeared],
+ );
+};
+
+const getCaptionColor = ({
+ appeared,
+ monospace,
+ theme,
+}: {
+ monospace: boolean;
+ appeared: boolean;
+ theme: Theme;
+}): { appeared: string; greyed: string } => {
+ const normalCaptionColor = {
+ appeared: COLORS[theme].WORD_COLOR_ON_BG_APPEARED,
+ greyed: COLORS[theme].WORD_COLOR_ON_BG_GREYED,
+ };
+
+ return monospace && appeared
+ ? {
+ appeared: COLORS[theme].ACCENT_COLOR,
+ greyed: COLORS[theme].WORD_COLOR_ON_BG_GREYED,
+ }
+ : normalCaptionColor;
+};
+
+const WORD_HIGHLIGHT_BORDER_RADIUS = 10;
+
+export const BoxedSingleCaption: React.FC<{
+ caption: Caption;
+ isLast: boolean;
+ theme: Theme;
+ startFrame: number;
+}> = ({ caption, isLast, theme, startFrame }) => {
+ const { fps } = useVideoConfig();
+ const frame = useCurrentFrame() + startFrame;
+ const time = (frame / fps) * 1000;
+
+ const [hovered, setHovered] = useState(false);
+
+ const monospace = isCaptionMonospace(caption);
+
+ const progress = monospace
+ ? caption.startMs > time
+ ? 1
+ : spring({
+ fps,
+ frame,
+ delay:
+ caption.startMs * fps - (WORD_FADE_IN_DURATION_IN_MS / 1000) * fps,
+ config: {
+ damping: 200,
+ },
+ durationInFrames: 5,
+ }) *
+ 0.05 +
+ 0.95
+ : 1;
+
+ const appeared = caption.startMs - 100 <= time;
+
+ const active =
+ appeared &&
+ (caption.endMs === null || caption.endMs - 100 > time || isLast);
+
+ const captionColor = getCaptionColor({
+ appeared,
+ monospace,
+ theme,
+ });
+
+ const shownCaptionColor = getShownCaptionColor({
+ appeared,
+ time,
+ caption,
+ captionColor,
+ active,
+ });
+
+ const shouldHighlight = active && monospace;
+
+ const backgroundColor = shouldHighlight
+ ? COLORS[theme].ACCENT_COLOR
+ : "transparent";
+
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ display: "inline",
+ color: shownCaptionColor,
+ ...(monospace ? MONOSPACE_FONT : REGULAR_FONT),
+ backgroundColor,
+ outline: hovered
+ ? "2px solid black"
+ : active
+ ? "5px solid " + backgroundColor
+ : "none",
+ whiteSpace: monospace ? "nowrap" : undefined,
+ // Fix gap inbetween background and outline
+ boxShadow: shouldHighlight ? `0 0 0 1px ${backgroundColor}` : "none",
+ borderRadius: WORD_HIGHLIGHT_BORDER_RADIUS,
+ scale: String(progress),
+ cursor: "pointer",
+ };
+ }, [
+ active,
+ backgroundColor,
+ hovered,
+ monospace,
+ progress,
+ shouldHighlight,
+ shownCaptionColor,
+ ]);
+
+ const onPointerEnter = useCallback(() => {
+ setHovered(true);
+ }, []);
+
+ const onPointerLeave = useCallback(() => {
+ setHovered(false);
+ }, []);
+
+ const overlay = useCaptionOverlay();
+
+ const onClick = useCallback(() => {
+ overlay.setOpen(caption);
+ }, [overlay, caption]);
+
+ const actualText = removeMonospaceTicks(caption).text;
+
+ return (
+ <span
+ style={style}
+ onPointerEnter={onPointerEnter}
+ onPointerLeave={onPointerLeave}
+ onClick={onClick}
+ >
+ {actualText}
+ </span>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/boxed/components/SquareSubtitles.tsx b/packages/template-recorder/remotion/captions/boxed/components/SquareSubtitles.tsx
new file mode 100644
index 0000000000..1638773808
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/boxed/components/SquareSubtitles.tsx
@@ -0,0 +1,52 @@
+import React, { useMemo } from "react";
+import type { Theme } from "../../../../config/themes";
+import { getHorizontalPaddingForSubtitles } from "../../processing/layout-captions";
+import type { CaptionPage } from "../../types";
+import { BoxedSingleCaption } from "./SingleCaption";
+
+export const LINE_HEIGHT = 1.2;
+
+export const SquareSubtitles: React.FC<{
+ segment: CaptionPage;
+ startFrame: number;
+ theme: Theme;
+ fontSize: number;
+ lines: number;
+}> = ({ segment, startFrame, theme, fontSize, lines }) => {
+ const container: React.CSSProperties = useMemo(() => {
+ return {
+ height: lines * fontSize * LINE_HEIGHT,
+ };
+ }, [lines, fontSize]);
+
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ lineHeight: LINE_HEIGHT,
+ display: "inline-block",
+ boxDecorationBreak: "clone",
+ WebkitBoxDecorationBreak: "clone",
+ paddingLeft: getHorizontalPaddingForSubtitles(),
+ paddingRight: getHorizontalPaddingForSubtitles(),
+ wordBreak: "break-word",
+ width: "100%",
+ };
+ }, []);
+
+ return (
+ <div style={container}>
+ <span style={style}>
+ {segment.captions.map((caption, index) => {
+ return (
+ <BoxedSingleCaption
+ key={caption.startMs + caption.text + index}
+ isLast={index === segment.captions.length - 1}
+ caption={caption}
+ theme={theme}
+ startFrame={startFrame}
+ />
+ );
+ })}
+ </span>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/boxed/components/TransitionBetweenSubtitles.tsx b/packages/template-recorder/remotion/captions/boxed/components/TransitionBetweenSubtitles.tsx
new file mode 100644
index 0000000000..736d912e0d
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/boxed/components/TransitionBetweenSubtitles.tsx
@@ -0,0 +1,65 @@
+import React from "react";
+import { interpolate, useCurrentFrame, useVideoConfig } from "remotion";
+import { SCENE_TRANSITION_DURATION } from "../../../../config/transitions";
+
+export const TransitionFromPreviousSubtitles: React.FC<{
+ children: React.ReactNode;
+ shouldTransitionFromPreviousSubtitle: boolean;
+}> = ({ children, shouldTransitionFromPreviousSubtitle }) => {
+ const frame = useCurrentFrame();
+ if (!shouldTransitionFromPreviousSubtitle) {
+ return <div>{children}</div>;
+ }
+
+ return (
+ <div
+ style={{
+ // TODO: Differentiate between layout change and not
+ opacity: interpolate(
+ frame,
+ [SCENE_TRANSITION_DURATION, SCENE_TRANSITION_DURATION + 5],
+ [0, 1],
+ {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp",
+ },
+ ),
+ }}
+ >
+ {children}
+ </div>
+ );
+};
+
+export const TransitionToNextSubtitles: React.FC<{
+ children: React.ReactNode;
+ shouldTransitionToNextsSubtitles: boolean;
+}> = ({ children, shouldTransitionToNextsSubtitles }) => {
+ const frame = useCurrentFrame();
+ const { durationInFrames } = useVideoConfig();
+
+ if (!shouldTransitionToNextsSubtitles) {
+ return <div>{children}</div>;
+ }
+
+ return (
+ <div
+ style={{
+ opacity: interpolate(
+ frame,
+ [
+ durationInFrames - SCENE_TRANSITION_DURATION - 5,
+ durationInFrames - SCENE_TRANSITION_DURATION,
+ ],
+ [1, 0],
+ {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp",
+ },
+ ),
+ }}
+ >
+ {children}
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/editor/CaptionOverlay.tsx b/packages/template-recorder/remotion/captions/editor/CaptionOverlay.tsx
new file mode 100644
index 0000000000..bb59ad8b7e
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/editor/CaptionOverlay.tsx
@@ -0,0 +1,87 @@
+import { Caption } from "@remotion/captions";
+import React, { useEffect, useMemo, useState } from "react";
+import type { StaticFile } from "remotion";
+import { continueRender, delayRender, watchStaticFile } from "remotion";
+import type { Theme } from "../../../config/themes";
+import { CaptionsEditor } from "./CaptionsEditor";
+import type { CaptionsContextType } from "./captions-provider";
+import { CaptionsProvider } from "./captions-provider";
+import { CaptionOverlayProvider } from "./use-caption-overlay";
+
+export const CaptionOverlay: React.FC<{
+ children: React.ReactNode;
+ file: StaticFile;
+ theme: Theme;
+ trimStart: number;
+}> = ({ children, file, theme, trimStart }) => {
+ const [captions, setCaptions] = useState<Caption[] | null>(null);
+ const [handle] = useState(() => delayRender());
+
+ const [subEditorOpen, setSubEditorOpen] = useState<Caption | false>(false);
+ const [changeStatus, setChangeStatus] = useState<
+ "initial" | "changed" | "unchanged"
+ >("initial");
+
+ const state = useMemo(() => {
+ return { open: subEditorOpen, setOpen: setSubEditorOpen };
+ }, [subEditorOpen, setSubEditorOpen]);
+
+ useEffect(() => {
+ // Don't listen to filesystem changes
+ // if the sub editor is open
+ if (subEditorOpen) {
+ return;
+ }
+
+ const { cancel } = watchStaticFile(
+ file.name,
+ (newData: StaticFile | null) => {
+ if (newData) {
+ setChangeStatus("changed");
+ }
+ },
+ );
+ return () => {
+ cancel();
+ };
+ }, [file.name, subEditorOpen]);
+
+ useEffect(() => {
+ if (changeStatus === "initial" || changeStatus === "changed") {
+ fetch(file.src)
+ .then((res) => res.json())
+ .then((d) => {
+ continueRender(handle);
+ setCaptions(d);
+ });
+ setChangeStatus("unchanged");
+ }
+ }, [changeStatus, file.src, handle]);
+
+ const captionState: CaptionsContextType = useMemo(() => {
+ return {
+ captions,
+ setCaptions,
+ };
+ }, [captions]);
+
+ if (!captionState.captions) {
+ return null;
+ }
+
+ return (
+ <CaptionOverlayProvider state={state}>
+ <CaptionsProvider state={captionState}>{children}</CaptionsProvider>
+ {subEditorOpen && captions ? (
+ <CaptionsEditor
+ initialCaption={subEditorOpen}
+ setCaptions={setCaptions}
+ captions={captions}
+ filePath={file.name}
+ trimStart={trimStart}
+ theme={theme}
+ />
+ ) : null}
+ </CaptionOverlayProvider>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/editor/CaptionsEditor.tsx b/packages/template-recorder/remotion/captions/editor/CaptionsEditor.tsx
new file mode 100644
index 0000000000..7928476440
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/editor/CaptionsEditor.tsx
@@ -0,0 +1,131 @@
+import { Caption } from "@remotion/captions";
+import { writeStaticFile } from "@remotion/studio";
+import React, { useCallback, useEffect } from "react";
+import ReactDOM from "react-dom";
+import { AbsoluteFill } from "remotion";
+import type { Theme } from "../../../config/themes";
+import { EditCaption } from "./EditCaption";
+import { SubsEditorFooter } from "./Footer";
+import { SubsEditorHeader } from "./Header";
+import { FOOTER_HEIGHT, HEADER_HEIGHT, captionEditorPortal } from "./layout";
+import { useCaptionOverlay } from "./use-caption-overlay";
+
+export const CaptionsEditor: React.FC<{
+ captions: Caption[];
+ setCaptions: React.Dispatch<React.SetStateAction<Caption[] | null>>;
+ filePath: string;
+ initialCaption: Caption;
+ trimStart: number;
+ theme: Theme;
+}> = ({
+ captions,
+ filePath,
+ initialCaption,
+ trimStart,
+ theme,
+ setCaptions,
+}) => {
+ const overlay = useCaptionOverlay();
+ const setAndSaveCaptions = useCallback(
+ (updater: (old: Caption[]) => Caption[]) => {
+ setCaptions((old) => {
+ if (old === null) {
+ return null;
+ }
+
+ if (!window.remotion_publicFolderExists) {
+ throw new Error("window.remotion_publicFolderExists is not set");
+ }
+
+ const newOutput = updater(old);
+ const contents = JSON.stringify(newOutput, null, 2);
+
+ writeStaticFile({
+ filePath,
+ contents,
+ });
+
+ return newOutput;
+ });
+ },
+ [filePath, setCaptions],
+ );
+
+ const longestNumberLength = String(
+ Math.max(
+ ...captions.map((t) => t.startMs),
+ ...(captions.map((t) => t.endMs).filter((t) => t !== null) as number[]),
+ ),
+ ).length;
+
+ const onChangeText = useCallback(
+ (index: number, newText: string) => {
+ setAndSaveCaptions((old) => {
+ const newTranscription = old.map((t, i) => {
+ if (i === index) {
+ return {
+ ...t,
+ text: newText,
+ };
+ }
+
+ return t;
+ });
+ return newTranscription;
+ });
+ },
+ [setAndSaveCaptions],
+ );
+
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ overlay.setOpen(false);
+ }
+ };
+
+ window.addEventListener("keydown", onKeyDown);
+ return () => {
+ window.removeEventListener("keydown", onKeyDown);
+ };
+ }, [overlay, overlay.setOpen]);
+
+ if (!captionEditorPortal.current) {
+ return null;
+ }
+
+ return ReactDOM.createPortal(
+ <AbsoluteFill
+ style={{
+ backgroundColor: "rgba(255, 255, 255, 0.9)",
+ }}
+ >
+ <AbsoluteFill
+ style={{
+ overflowY: "auto",
+ paddingTop: HEADER_HEIGHT,
+ paddingBottom: FOOTER_HEIGHT,
+ }}
+ >
+ {captions.map((caption, i) => {
+ return (
+ <EditCaption
+ key={[caption.startMs, caption.endMs, i].join("-")}
+ theme={theme}
+ index={i}
+ longestNumberLength={longestNumberLength}
+ caption={caption}
+ isInitialCaption={caption.startMs === initialCaption.endMs}
+ trimStart={trimStart}
+ onUpdateText={onChangeText}
+ />
+ );
+ })}
+ </AbsoluteFill>
+ <SubsEditorHeader />
+ <SubsEditorFooter fileName={filePath} />
+ </AbsoluteFill>,
+ captionEditorPortal.current as HTMLDivElement,
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/editor/EditCaption.tsx b/packages/template-recorder/remotion/captions/editor/EditCaption.tsx
new file mode 100644
index 0000000000..f3904accbb
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/editor/EditCaption.tsx
@@ -0,0 +1,204 @@
+import { Caption } from "@remotion/captions";
+import React, { useCallback, useEffect, useRef, useState } from "react";
+import { useCurrentFrame, useVideoConfig } from "remotion";
+import type { Theme } from "../../../config/themes";
+import { COLORS } from "../../../config/themes";
+import {
+ FIRST_COLUMN_WIDTH,
+ SECOND_COLUMN_WIDTH,
+ SIDE_PADDING,
+} from "./layout";
+import { useCaptionOverlay } from "./use-caption-overlay";
+
+const Indent: React.FC<{ value: number; digits: number }> = ({
+ digits,
+ value,
+}) => {
+ const indentTo = digits - String(value).length;
+
+ return (
+ <span style={{ opacity: 0 }}>
+ {new Array(indentTo)
+ .fill(0)
+ .map(() => "0")
+ .join("")}
+ </span>
+ );
+};
+
+export const EditCaption: React.FC<{
+ caption: Caption;
+ longestNumberLength: number;
+ index: number;
+ onUpdateText: (index: number, newText: string) => void;
+ isInitialCaption: boolean;
+ trimStart: number;
+ theme: Theme;
+}> = ({
+ caption,
+ longestNumberLength,
+ index,
+ onUpdateText,
+ isInitialCaption,
+ trimStart,
+ theme,
+}) => {
+ const overlay = useCaptionOverlay();
+ const { width, fps } = useVideoConfig();
+ const frame = useCurrentFrame();
+ const milliSeconds = ((frame + trimStart) / fps) * 1000;
+ const active =
+ caption.startMs <= milliSeconds &&
+ (caption.endMs === null || caption.endMs >= milliSeconds);
+ const usableWidth = width - SIDE_PADDING * 2;
+ const ref = useRef<HTMLDivElement>(null);
+
+ const [initialFrame] = useState(() => frame);
+
+ const onChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ onUpdateText(index, e.target.value);
+ },
+ [index, onUpdateText],
+ );
+
+ const isMonospaced =
+ caption.text.trim().startsWith("`") && caption.text.trim().endsWith("`");
+
+ const toggleMonospace = useCallback(() => {
+ if (isMonospaced) {
+ onUpdateText(index, caption.text.replace(/`/g, ""));
+ } else {
+ let newCaption = caption.text;
+ if (!newCaption.trim().startsWith("`")) {
+ newCaption = "`" + newCaption;
+ }
+
+ if (!newCaption.trim().endsWith("`") || newCaption.trim().length === 1) {
+ newCaption += "`";
+ }
+
+ onUpdateText(index, newCaption);
+ }
+ }, [index, isMonospaced, onUpdateText, caption.text]);
+
+ useEffect(() => {
+ if (active && initialFrame !== frame) {
+ ref.current?.scrollIntoView({
+ behavior: "auto",
+ block: "center",
+ });
+ }
+ }, [active, frame, initialFrame]);
+
+ const onInputKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ const next = ref.current?.nextElementSibling?.querySelector(
+ "input[type=text]",
+ ) as HTMLInputElement | undefined;
+ if (next) {
+ next.focus();
+ next.scrollIntoView({ behavior: "auto", block: "center" });
+ }
+ }
+
+ if (e.key === "ArrowUp") {
+ e.preventDefault();
+ const prev = ref.current?.previousElementSibling?.querySelector(
+ "input[type=text]",
+ ) as HTMLInputElement | undefined;
+ if (prev) {
+ prev.focus();
+ prev.scrollIntoView({ behavior: "auto", block: "center" });
+ }
+ }
+
+ if (e.key === "Enter") {
+ e.preventDefault();
+ overlay.setOpen(false);
+ }
+
+ const ctrlOrCommandKey = window.navigator.platform.startsWith("Mac")
+ ? e.metaKey
+ : e.ctrlKey;
+
+ if (e.key === "i" && ctrlOrCommandKey) {
+ e.preventDefault();
+ toggleMonospace();
+ }
+ },
+ [overlay, toggleMonospace],
+ );
+
+ return (
+ <div
+ ref={ref}
+ style={{
+ flexDirection: "row",
+ display: "flex",
+ paddingTop: 5,
+ paddingBottom: 5,
+ paddingLeft: SIDE_PADDING,
+ paddingRight: SIDE_PADDING,
+ backgroundColor: active ? "rgba(0, 0, 0, 0.1)" : "transparent",
+ }}
+ >
+ <div
+ style={{
+ fontFamily: "Helvetica",
+ fontSize: 30,
+ width: FIRST_COLUMN_WIDTH * usableWidth,
+ fontVariantNumeric: "tabular-nums",
+ color: "gray",
+ textAlign: "right",
+ paddingRight: 30,
+ }}
+ >
+ <Indent value={caption.startMs} digits={longestNumberLength} />
+ {String(caption.startMs)} :{" "}
+ <Indent value={caption.endMs} digits={longestNumberLength} />
+ {caption.endMs}
+ </div>
+ <div
+ style={{
+ width: SECOND_COLUMN_WIDTH * usableWidth,
+ whiteSpace: "pre",
+ }}
+ >
+ <input
+ type="text"
+ autoFocus={isInitialCaption}
+ style={{
+ fontSize: 30,
+ fontFamily: isMonospaced ? "monospace" : "Helvetica",
+ backgroundColor: "transparent",
+ border: "none",
+ color: isMonospaced ? COLORS[theme].ACCENT_COLOR : "black",
+ }}
+ value={caption.text}
+ onKeyDown={onInputKeyDown}
+ onChange={onChange}
+ />
+ </div>
+ <div>
+ <div
+ style={{
+ width: 30,
+ height: 30,
+ border: isMonospaced
+ ? "2px solid " + COLORS[theme].ACCENT_COLOR
+ : "2px solid gray",
+ borderRadius: 3,
+ cursor: "pointer",
+ background: isMonospaced
+ ? COLORS[theme].ACCENT_COLOR
+ : "transparent",
+ }}
+ onClick={toggleMonospace}
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/editor/Footer.tsx b/packages/template-recorder/remotion/captions/editor/Footer.tsx
new file mode 100644
index 0000000000..7a9c63f34a
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/editor/Footer.tsx
@@ -0,0 +1,69 @@
+import React, { useCallback } from "react";
+import { FOOTER_HEIGHT, SIDE_PADDING } from "./layout";
+import { useCaptionOverlay } from "./use-caption-overlay";
+
+export const SubsEditorFooter: React.FC<{
+ fileName: string;
+}> = ({ fileName }) => {
+ const overlay = useCaptionOverlay();
+
+ const onCloseSubEditor = useCallback(() => {
+ overlay.setOpen(false);
+ }, [overlay]);
+
+ return (
+ <div
+ style={{
+ display: "flex",
+ flexDirection: "row",
+ height: FOOTER_HEIGHT,
+ width: "100%",
+ backgroundImage: "linear-gradient(rgba(255, 255, 255, 0), white 20%)",
+ position: "absolute",
+ bottom: 0,
+ paddingTop: 20,
+ paddingLeft: SIDE_PADDING,
+ paddingRight: SIDE_PADDING,
+ alignItems: "center",
+ }}
+ >
+ <div
+ style={{
+ fontSize: 20,
+ fontFamily: "sans-serif",
+ color: "gray",
+ flex: 1,
+ }}
+ >
+ Changes will be auto-saved to {fileName}.
+ <br />
+ {"Don't"} edit the file manually while using this editor.
+ </div>
+ <div>
+ <button
+ style={{
+ backgroundColor: "black",
+ fontSize: 30,
+ color: "white",
+ borderRadius: 7,
+ padding: "12px 30px",
+ cursor: "pointer",
+ }}
+ type={"button"}
+ onClick={onCloseSubEditor}
+ >
+ Done{" "}
+ <kbd
+ style={{
+ color: "rgba(255, 255, 255, 0.4)",
+ fontSize: "0.9em",
+ marginLeft: 5,
+ }}
+ >
+ Esc
+ </kbd>
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/editor/Header.tsx b/packages/template-recorder/remotion/captions/editor/Header.tsx
new file mode 100644
index 0000000000..c7b28b259f
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/editor/Header.tsx
@@ -0,0 +1,67 @@
+import React from "react";
+import { useVideoConfig } from "remotion";
+import {
+ FIRST_COLUMN_WIDTH,
+ HEADER_HEIGHT,
+ SECOND_COLUMN_WIDTH,
+ SIDE_PADDING,
+} from "./layout";
+
+const cmdOrCtrlCharacter = window.navigator.platform.startsWith("Mac")
+ ? "⌘"
+ : "Ctrl";
+
+export const SubsEditorHeader: React.FC = () => {
+ const { width } = useVideoConfig();
+ const usableWidth = width - SIDE_PADDING * 2;
+
+ return (
+ <div
+ style={{
+ height: HEADER_HEIGHT,
+ width: "100%",
+ backgroundImage: "linear-gradient(white 60%, rgba(255, 255, 255, 0))",
+ position: "absolute",
+ paddingLeft: SIDE_PADDING,
+ paddingRight: SIDE_PADDING,
+ display: "flex",
+ flexDirection: "row",
+ }}
+ >
+ <div
+ style={{
+ fontFamily: "Helvetica",
+ fontSize: 20,
+ paddingTop: 30,
+ color: "gray",
+ textAlign: "right",
+ paddingRight: 30,
+ width: FIRST_COLUMN_WIDTH * usableWidth,
+ }}
+ >
+ MILLISECONDS
+ </div>
+ <div
+ style={{
+ fontFamily: "Helvetica",
+ fontSize: 20,
+ paddingTop: 30,
+ color: "gray",
+ width: SECOND_COLUMN_WIDTH * usableWidth,
+ }}
+ >
+ TEXT
+ </div>
+ <div
+ style={{
+ fontFamily: "Helvetica",
+ fontSize: 20,
+ paddingTop: 30,
+ color: "gray",
+ }}
+ >
+ MONOSPACE <kbd>({cmdOrCtrlCharacter}+I)</kbd>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/editor/captions-provider.tsx b/packages/template-recorder/remotion/captions/editor/captions-provider.tsx
new file mode 100644
index 0000000000..bdf3b50796
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/editor/captions-provider.tsx
@@ -0,0 +1,31 @@
+import { Caption } from "@remotion/captions";
+import React, { useContext } from "react";
+
+export type CaptionsContextType = {
+ captions: Caption[] | null;
+ setCaptions: (captions: Caption[] | null) => void;
+};
+
+const context = React.createContext<CaptionsContextType>({
+ captions: null,
+ setCaptions: () => {
+ throw new Error("React Context not initialized");
+ },
+});
+
+export const useCaptions = (): Caption[] => {
+ const ctx = useContext(context);
+
+ if (!ctx.captions) {
+ throw new Error("Should not render without a captions");
+ }
+
+ return ctx.captions;
+};
+
+export const CaptionsProvider: React.FC<{
+ children: React.ReactNode;
+ state: CaptionsContextType;
+}> = ({ children, state }) => {
+ return <context.Provider value={state}>{children}</context.Provider>;
+};
diff --git a/packages/template-recorder/remotion/captions/editor/layout.tsx b/packages/template-recorder/remotion/captions/editor/layout.tsx
new file mode 100644
index 0000000000..eeefff44a4
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/editor/layout.tsx
@@ -0,0 +1,11 @@
+import React from "react";
+
+export const captionEditorPortal = React.createRef<HTMLDivElement>();
+
+export const FIRST_COLUMN_WIDTH = 0.25;
+export const SECOND_COLUMN_WIDTH = 0.5;
+
+export const HEADER_HEIGHT = 100;
+export const FOOTER_HEIGHT = 100;
+
+export const SIDE_PADDING = 20;
diff --git a/packages/template-recorder/remotion/captions/editor/use-caption-overlay.tsx b/packages/template-recorder/remotion/captions/editor/use-caption-overlay.tsx
new file mode 100644
index 0000000000..d619009a84
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/editor/use-caption-overlay.tsx
@@ -0,0 +1,33 @@
+import { Caption } from "@remotion/captions";
+import React, { useContext, useMemo } from "react";
+
+type CaptionOverlayContext = {
+ open: Caption | false;
+ setOpen: React.Dispatch<React.SetStateAction<Caption | false>>;
+};
+
+const context = React.createContext<CaptionOverlayContext>({
+ open: false,
+ setOpen: () => {
+ throw new Error("React Context not initialized");
+ },
+});
+
+export const useCaptionOverlay = (): {
+ isOpen: Caption | false;
+ setOpen: React.Dispatch<React.SetStateAction<Caption | false>>;
+} => {
+ const ctx = useContext(context);
+
+ return useMemo(
+ () => ({ isOpen: ctx.open, setOpen: ctx.setOpen }),
+ [ctx.open, ctx.setOpen],
+ );
+};
+
+export const CaptionOverlayProvider: React.FC<{
+ children: React.ReactNode;
+ state: CaptionOverlayContext;
+}> = ({ children, state }) => {
+ return <context.Provider value={state}>{children}</context.Provider>;
+};
diff --git a/packages/template-recorder/remotion/captions/processing/fix-backticks.ts b/packages/template-recorder/remotion/captions/processing/fix-backticks.ts
new file mode 100644
index 0000000000..5951cfdc71
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/processing/fix-backticks.ts
@@ -0,0 +1,40 @@
+import { Caption } from "@remotion/captions";
+
+export const fixBackticks = (_captions: Caption[]): Caption[] => {
+ const newCaptions: Caption[] = [];
+
+ const captions = _captions.map((caption) => {
+ return {
+ ...caption,
+ text: caption.text.replaceAll(/`\s/g, " `"),
+ };
+ });
+
+ for (let i = 0; i < captions.length; i++) {
+ const caption = captions[i] as Caption;
+ const previousCaption = captions[i - 1] ?? null;
+
+ if (caption.text.startsWith(". ")) {
+ const lastAddedCaption = newCaptions[newCaptions.length - 1] as Caption;
+ lastAddedCaption.text += ".";
+ caption.text = caption.text.slice(1);
+ }
+
+ if (!caption.text.startsWith(" ") && previousCaption) {
+ const lastAddedCaption = newCaptions[newCaptions.length - 1] as Caption;
+ lastAddedCaption.text += caption.text;
+ lastAddedCaption.endMs = caption.endMs;
+ } else {
+ newCaptions.push(caption);
+ }
+ }
+
+ return newCaptions.map((w) => {
+ return {
+ ...w,
+ text:
+ // Remove double backticks: ` n``px`` rem``otion`` render`
+ w.text.replaceAll(/``/g, ""),
+ };
+ });
+};
diff --git a/packages/template-recorder/remotion/captions/processing/has-monospace-in-caption.ts b/packages/template-recorder/remotion/captions/processing/has-monospace-in-caption.ts
new file mode 100644
index 0000000000..1f288322be
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/processing/has-monospace-in-caption.ts
@@ -0,0 +1,9 @@
+import { Caption } from "@remotion/captions";
+
+export const hasMonoSpaceInCaption = (caption: Caption) => {
+ if (caption.text.split("").filter((char) => char === "`").length >= 2) {
+ return true;
+ }
+
+ return false;
+};
diff --git a/packages/template-recorder/remotion/captions/processing/join-backticks.ts b/packages/template-recorder/remotion/captions/processing/join-backticks.ts
new file mode 100644
index 0000000000..e5a8fec30b
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/processing/join-backticks.ts
@@ -0,0 +1,33 @@
+import { Caption } from "@remotion/captions";
+
+export const joinBackticks = (captions: Caption[]): Caption[] => {
+ const newCaptions: Caption[] = [];
+ for (let i = 0; i < captions.length; i++) {
+ const previousCaption = newCaptions[i - 1] ?? null;
+ const newCaption = captions[i] as Caption;
+
+ const previousCaptionEndsInMonospace = previousCaption?.text.endsWith("`");
+
+ if (previousCaption && previousCaptionEndsInMonospace) {
+ if (newCaption.text.startsWith("`")) {
+ previousCaption.text = previousCaption.text.substring(
+ 0,
+ previousCaption.text.length - 1,
+ );
+ newCaption.text = newCaption.text.slice(1);
+ }
+
+ if (newCaption.text.startsWith(" `")) {
+ previousCaption.text = previousCaption.text.substring(
+ 0,
+ previousCaption.text.length - 1,
+ );
+ newCaption.text = " " + newCaption.text.slice(2);
+ }
+ }
+
+ newCaptions.push(newCaption);
+ }
+
+ return newCaptions;
+};
diff --git a/packages/template-recorder/remotion/captions/processing/layout-captions.ts b/packages/template-recorder/remotion/captions/processing/layout-captions.ts
new file mode 100644
index 0000000000..1895d553c7
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/processing/layout-captions.ts
@@ -0,0 +1,158 @@
+import { Caption } from "@remotion/captions";
+import { fillTextBox } from "@remotion/layout-utils";
+import { MONOSPACE_FONT, REGULAR_FONT } from "../../../config/fonts";
+import { getSafeSpace } from "../../../config/layout";
+import { getBorderWidthForSubtitles } from "../boxed/components/CaptionSentence";
+import { CaptionPage, LayoutedCaptions } from "../types";
+import { hasMonoSpaceInCaption } from "./has-monospace-in-caption";
+import {
+ isCaptionMonospace,
+ removeMonospaceTicks,
+ splitCaptionIntoMonospaceSegments,
+} from "./split-caption-into-monospace-segments";
+
+const balanceCaptions = ({
+ captions,
+ captionsFitted,
+ boxWidth,
+ fontSize,
+ maxLines,
+}: {
+ captions: Caption[];
+ captionsFitted: number;
+ boxWidth: number;
+ maxLines: number;
+ fontSize: number;
+}) => {
+ let bestCut = captionsFitted;
+
+ if (captionsFitted / captions.length > 0.9) {
+ // Prevent a few hanging words at the end
+ bestCut = captions.length - 5;
+ }
+
+ for (let i = 1; i < 4; i++) {
+ const index = bestCut - i;
+ const caption = (captions[index] as Caption).text.trim();
+ if (caption.endsWith(",") || caption.endsWith(".")) {
+ bestCut = index + 1;
+ break;
+ }
+ }
+
+ while (
+ (bestCut > 1 && hasMonoSpaceInCaption(captions[bestCut - 1] as Caption)) ||
+ (captions[bestCut - 1] as Caption).text.trim() === ""
+ ) {
+ bestCut--;
+ }
+
+ const firstHalf = captions.slice(0, bestCut);
+ const secondHalf = captions.slice(bestCut);
+
+ return [
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ ...cutCaptions({
+ captions: firstHalf,
+ boxWidth,
+ maxLines,
+ fontSize,
+ }),
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ ...cutCaptions({
+ captions: secondHalf,
+ boxWidth,
+ maxLines,
+ fontSize,
+ }),
+ ];
+};
+
+const cutCaptions = ({
+ captions,
+ boxWidth,
+ maxLines,
+ fontSize,
+}: {
+ captions: Caption[];
+ boxWidth: number;
+ maxLines: number;
+ fontSize: number;
+}): CaptionPage[] => {
+ const { add } = fillTextBox({ maxBoxWidth: boxWidth, maxLines });
+ let captionsFitted = 0;
+
+ for (const caption of captions) {
+ const { fontFamily, fontWeight, ...additionalStyles } = isCaptionMonospace(
+ caption,
+ )
+ ? MONOSPACE_FONT
+ : REGULAR_FONT;
+
+ const { exceedsBox } = add({
+ text: removeMonospaceTicks(caption).text,
+ fontFamily: fontFamily as string,
+ fontWeight: fontWeight as string,
+ fontSize,
+ additionalStyles,
+ validateFontIsLoaded: true,
+ });
+
+ if (exceedsBox) {
+ break;
+ } else {
+ captionsFitted++;
+ }
+ }
+
+ if (captionsFitted === captions.length) {
+ return [{ captions: captions }];
+ }
+
+ return balanceCaptions({
+ captions: captions,
+ boxWidth,
+ fontSize,
+ maxLines,
+ captionsFitted: captionsFitted,
+ });
+};
+
+export const getHorizontalPaddingForSubtitles = () => {
+ return getSafeSpace("square");
+};
+
+export const layoutCaptions = ({
+ captions,
+ boxWidth,
+ fontSize,
+ maxLines,
+}: {
+ captions: Caption[];
+ boxWidth: number;
+ maxLines: number;
+ fontSize: number;
+}): LayoutedCaptions => {
+ const segments = cutCaptions({
+ captions: captions,
+ boxWidth:
+ boxWidth -
+ getHorizontalPaddingForSubtitles() * 2 -
+ getBorderWidthForSubtitles() * 2,
+ maxLines,
+ fontSize,
+ });
+
+ return {
+ segments: segments.map((segment) => {
+ return {
+ ...segment,
+ captions: segment.captions
+ .map((caption) => {
+ return splitCaptionIntoMonospaceSegments(caption);
+ })
+ .flat(1),
+ };
+ }),
+ };
+};
diff --git a/packages/template-recorder/remotion/captions/processing/postprocess-subs.ts b/packages/template-recorder/remotion/captions/processing/postprocess-subs.ts
new file mode 100644
index 0000000000..8080983a53
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/processing/postprocess-subs.ts
@@ -0,0 +1,63 @@
+import { Caption } from "@remotion/captions";
+import { autocorrectWords } from "../../../config/autocorrect";
+import { fixBackticks } from "./fix-backticks";
+import { removeBlankTokens } from "./remove-blank-tokens";
+
+const FILLER_WORDS = [
+ "[PAUSE]",
+ "[BLANK_AUDIO]",
+ "[Silence]",
+ "[silence]",
+ "[INAUDIBLE]",
+];
+
+const removeWhisperBlankWords = (original: Caption[]): Caption[] => {
+ let firstIdx = 0;
+ let concatenatedCaption = "";
+ let inBlank = false;
+
+ const captions = [...original];
+ captions.forEach((caption, index) => {
+ const captionCopy = { ...caption };
+ captionCopy.text = captionCopy.text.trim();
+ if (captionCopy.text.includes("[")) {
+ inBlank = true;
+ firstIdx = index;
+ }
+
+ if (inBlank && FILLER_WORDS.find((w) => w.includes(captionCopy.text))) {
+ concatenatedCaption += captionCopy.text;
+ }
+
+ if (inBlank && captionCopy.text.includes("]")) {
+ concatenatedCaption += captionCopy.text;
+ if (
+ FILLER_WORDS.find((caption) => concatenatedCaption.includes(caption))
+ ) {
+ for (let i = firstIdx; i <= index; i++) {
+ const currentCaption = captions[i];
+ if (currentCaption?.text !== undefined) {
+ captions[i] = {
+ ...currentCaption,
+ text: "",
+ };
+ }
+ }
+ }
+ }
+ });
+ return captions;
+};
+
+export const postprocessCaptions = (subTypes: Caption[]): Caption[] => {
+ const blankTokensRemoved = removeBlankTokens(subTypes);
+
+ const removeBlankAudioAndPause = removeWhisperBlankWords(blankTokensRemoved);
+ const removeBlankTokensAgain = removeBlankAudioAndPause.filter(
+ (w) => w.text.trim() !== "",
+ );
+
+ const correctedCaptions = autocorrectWords(removeBlankTokensAgain);
+
+ return fixBackticks(correctedCaptions);
+};
diff --git a/packages/template-recorder/remotion/captions/processing/remove-blank-tokens.ts b/packages/template-recorder/remotion/captions/processing/remove-blank-tokens.ts
new file mode 100644
index 0000000000..78bfea29df
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/processing/remove-blank-tokens.ts
@@ -0,0 +1,9 @@
+import { Caption } from "@remotion/captions";
+
+export const removeBlankTokens = (tokens: Caption[]): Caption[] => {
+ return tokens
+ .filter((t) => t.text.trim() !== "")
+ .filter((t) => {
+ return !t.text.match(/TT_(\d+)/);
+ });
+};
diff --git a/packages/template-recorder/remotion/captions/processing/split-caption-into-monospace-segments.ts b/packages/template-recorder/remotion/captions/processing/split-caption-into-monospace-segments.ts
new file mode 100644
index 0000000000..d8a96c24d7
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/processing/split-caption-into-monospace-segments.ts
@@ -0,0 +1,47 @@
+import { Caption } from "@remotion/captions";
+
+export const splitCaptionIntoMonospaceSegments = (
+ caption: Caption,
+): Caption[] => {
+ const result: Caption[] = [];
+
+ const regex = /`([^`]+)`/g; // regex pattern to find text enclosed in backticks
+ let lastIndex = 0;
+
+ let match;
+ while ((match = regex.exec(caption.text)) !== null) {
+ if (match.index > lastIndex) {
+ result.push({
+ ...caption,
+ text: caption.text.slice(lastIndex, match.index),
+ });
+ }
+
+ result.push({
+ ...caption,
+ text: `${("`" + match[1]) as string}\``,
+ });
+ lastIndex = regex.lastIndex;
+ }
+
+ if (lastIndex < caption.text.length) {
+ result.push({ ...caption, text: caption.text.slice(lastIndex) });
+ }
+
+ return result;
+};
+
+export const isCaptionMonospace = (caption: Caption) => {
+ return caption.text.startsWith("`") && caption.text.endsWith("`");
+};
+
+export const removeMonospaceTicks = (caption: Caption) => {
+ if (!isCaptionMonospace(caption)) {
+ return caption;
+ }
+
+ return {
+ ...caption,
+ text: caption.text.slice(1, -1),
+ };
+};
diff --git a/packages/template-recorder/remotion/captions/srt/EmitSrtFile.tsx b/packages/template-recorder/remotion/captions/srt/EmitSrtFile.tsx
new file mode 100644
index 0000000000..35da58900e
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/EmitSrtFile.tsx
@@ -0,0 +1,36 @@
+import React, { useMemo } from "react";
+import { Artifact, useCurrentFrame } from "remotion";
+import { FPS } from "../../../config/fps";
+import { SceneAndMetadata } from "../../../config/scenes";
+import { combineSrt } from "./helpers/combine-srt";
+import { serializeSrt } from "./helpers/serialize-srt";
+
+// Rendering this component will cause an `captions.srt` file to be generated
+// while rendering.
+export const EmitSrtFile: React.FC<{
+ scenesAndMetadata: SceneAndMetadata[];
+}> = ({ scenesAndMetadata }) => {
+ const frame = useCurrentFrame();
+
+ const srtFile = useMemo(() => {
+ const toCombine = scenesAndMetadata.map((scene) => {
+ return {
+ offsetInMs: Math.round((scene.from * 1000) / FPS),
+ srts: scene.type === "video-scene" ? scene.srt : [],
+ };
+ });
+
+ const combined = combineSrt(toCombine);
+ return serializeSrt(combined);
+ }, [scenesAndMetadata]);
+
+ if (!srtFile) {
+ return null;
+ }
+
+ if (frame !== 0) {
+ return null;
+ }
+
+ return <Artifact content={srtFile} filename="captions.srt" />;
+};
diff --git a/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SingleCaption.tsx b/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SingleCaption.tsx
new file mode 100644
index 0000000000..fee0017d5a
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SingleCaption.tsx
@@ -0,0 +1,41 @@
+import { Caption } from "@remotion/captions";
+import React, { useCallback, useMemo, useState } from "react";
+import { useCaptionOverlay } from "../../editor/use-caption-overlay";
+
+export const SrtSingleCaption: React.FC<{
+ caption: Caption;
+}> = ({ caption }) => {
+ const overlay = useCaptionOverlay();
+
+ const [hovered, setHovered] = useState(false);
+
+ const onPointerEnter = useCallback(() => {
+ setHovered(true);
+ }, []);
+
+ const onPointerLeave = useCallback(() => {
+ setHovered(false);
+ }, []);
+
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ cursor: "pointer",
+ color: hovered ? "gray" : "inherit",
+ };
+ }, [hovered]);
+
+ const onClick = useCallback(() => {
+ overlay.setOpen(caption);
+ }, [overlay, caption]);
+
+ return (
+ <span
+ style={style}
+ onPointerEnter={onPointerEnter}
+ onPointerLeave={onPointerLeave}
+ onClick={onClick}
+ >
+ {caption.text}
+ </span>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreview.tsx b/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreview.tsx
new file mode 100644
index 0000000000..93220e0bd0
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreview.tsx
@@ -0,0 +1,41 @@
+import React, { useMemo } from "react";
+import { Sequence, useVideoConfig } from "remotion";
+import { useCaptions } from "../../editor/captions-provider";
+import { calculateSrt } from "../helpers/calculate-srt";
+import { SrtPreviewLine } from "./SrtPreviewLine";
+
+export const SrtPreview: React.FC<{
+ startFrame: number;
+}> = ({ startFrame }) => {
+ const { fps } = useVideoConfig();
+ const captions = useCaptions();
+
+ const srt = useMemo(() => {
+ return calculateSrt({
+ captions,
+ startFrame,
+ });
+ }, [captions, startFrame]);
+
+ return (
+ <>
+ {srt.map((segment, index) => {
+ const durationInFrames =
+ ((segment.lastTimestampMs - segment.firstTimestampMs) / 1000) * fps;
+ const from = (segment.firstTimestampMs / 1000) * fps;
+
+ return (
+ <Sequence
+ key={index}
+ durationInFrames={durationInFrames}
+ from={from}
+ showInTimeline={false}
+ layout="none"
+ >
+ <SrtPreviewLine segment={segment} />
+ </Sequence>
+ );
+ })}
+ </>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreviewAndEditor.tsx b/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreviewAndEditor.tsx
new file mode 100644
index 0000000000..64aab31633
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreviewAndEditor.tsx
@@ -0,0 +1,23 @@
+import { StaticFile } from "@remotion/studio";
+import React from "react";
+import { getRemotionEnvironment } from "remotion";
+import { Theme } from "../../../../config/themes";
+import { CaptionOverlay } from "../../editor/CaptionOverlay";
+import { SrtPreview } from "./SrtPreview";
+
+export const SrtPreviewAndEditor: React.FC<{
+ captions: StaticFile;
+ theme: Theme;
+ startFrame: number;
+}> = ({ captions, startFrame, theme }) => {
+ // During rendering, you will get the actual .srt file instead of the preview.
+ if (getRemotionEnvironment().isRendering) {
+ return null;
+ }
+
+ return (
+ <CaptionOverlay file={captions} theme={theme} trimStart={startFrame}>
+ <SrtPreview startFrame={startFrame}></SrtPreview>
+ </CaptionOverlay>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreviewLine.tsx b/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreviewLine.tsx
new file mode 100644
index 0000000000..caa4ba478e
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/SrtPreviewAndEditor/SrtPreviewLine.tsx
@@ -0,0 +1,44 @@
+import React from "react";
+import { UnserializedSrt } from "../helpers/serialize-srt";
+import { SrtSingleCaption } from "./SingleCaption";
+
+const container: React.CSSProperties = {
+ justifyContent: "flex-end",
+ alignItems: "center",
+ position: "absolute",
+ bottom: 0,
+ width: "100%",
+ display: "flex",
+ flexDirection: "column",
+};
+
+const inner: React.CSSProperties = {
+ backgroundColor: "rgba(0, 0, 0, 0.8)",
+ padding: "12px 15px",
+ color: "white",
+ fontFamily: "Helvetica, Arial, sans-serif",
+ pointerEvents: "unset",
+ borderRadius: 10,
+ fontSize: 48,
+ bottom: 50,
+ position: "absolute",
+};
+
+export const SrtPreviewLine: React.FC<{
+ segment: UnserializedSrt;
+}> = ({ segment }) => {
+ return (
+ <div style={container}>
+ <div style={inner}>
+ {segment.captions.map((caption) => {
+ return (
+ <SrtSingleCaption
+ caption={caption}
+ key={caption.startMs}
+ ></SrtSingleCaption>
+ );
+ })}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/captions/srt/helpers/calculate-srt.ts b/packages/template-recorder/remotion/captions/srt/helpers/calculate-srt.ts
new file mode 100644
index 0000000000..b54b87771e
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/helpers/calculate-srt.ts
@@ -0,0 +1,95 @@
+import type { Caption } from "@remotion/captions";
+import { FPS } from "../../../../config/fps";
+import { joinBackticks } from "../../processing/join-backticks";
+import { postprocessCaptions } from "../../processing/postprocess-subs";
+import type { UnserializedSrt } from "./serialize-srt";
+
+// The SRT standard recommends not more than 42 characters per line
+
+const MAX_CHARS_PER_LINE = 42;
+
+const segmentCaptions = (caption: Caption[]) => {
+ const segments: Caption[][] = [];
+ let currentSegment: Caption[] = [];
+
+ for (let i = 0; i < caption.length; i++) {
+ const w = caption[i] as Caption;
+ const remainingCaptions = caption.slice(i + 1);
+ const filledCharactersInLine = currentSegment
+ .map((s) => s.text.length)
+ .reduce((a, b) => a + b, 0);
+
+ const preventOrphanCaption =
+ remainingCaptions.length < 4 &&
+ remainingCaptions.length > 1 &&
+ filledCharactersInLine > MAX_CHARS_PER_LINE / 2;
+
+ if (
+ filledCharactersInLine + w.text.length > MAX_CHARS_PER_LINE ||
+ preventOrphanCaption
+ ) {
+ segments.push(currentSegment);
+ currentSegment = [];
+ }
+ currentSegment.push(w);
+ }
+
+ segments.push(currentSegment);
+ return segments;
+};
+
+export const calculateSrt = ({
+ startFrame,
+ captions,
+}: {
+ captions: Caption[];
+ startFrame: number;
+}) => {
+ const postprocessed = joinBackticks(postprocessCaptions(captions));
+ const segments = segmentCaptions(postprocessed);
+
+ const srtSegments: UnserializedSrt[] = [];
+
+ for (let i = 0; i < segments.length; i++) {
+ const segment = segments[i];
+ if (!segment) {
+ throw new Error(`Segment with index ${i} is undefined`);
+ }
+
+ if (segment.length === 0) {
+ continue;
+ }
+
+ const firstSegment = segment[0];
+ const lastSegment = segment[segment.length - 1];
+
+ if (!firstSegment) {
+ throw new Error("lastSegment is undefined");
+ }
+ if (!lastSegment) {
+ throw new Error("lastSegment is undefined");
+ }
+
+ const offset = -(startFrame / FPS) * 1000;
+
+ const firstTimestampMs = Math.max(0, Math.round(firstSegment.startMs + offset));
+ if (lastSegment.endMs === null) {
+ throw new Error("Cannot serialize .srt file: lastTimestamp is null");
+ }
+
+ const lastTimestampMs = Math.max(0, lastSegment.endMs + offset);
+
+ const unserialized: UnserializedSrt = {
+ firstTimestampMs,
+ lastTimestampMs,
+ text: segment
+ .map((s) => s.text.trim())
+ .join(" ")
+ .trim(),
+ captions: segment,
+ };
+ srtSegments.push(unserialized);
+ }
+
+ return srtSegments;
+};
diff --git a/packages/template-recorder/remotion/captions/srt/helpers/combine-srt.ts b/packages/template-recorder/remotion/captions/srt/helpers/combine-srt.ts
new file mode 100644
index 0000000000..9ed43b6c8a
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/helpers/combine-srt.ts
@@ -0,0 +1,21 @@
+import { UnserializedSrt } from "./serialize-srt";
+
+export type SrtsToCombine = {
+ offsetInMs: number;
+ srts: UnserializedSrt[];
+};
+
+export const combineSrt = (srt: SrtsToCombine[]): UnserializedSrt[] => {
+ return srt
+ .map((line) => {
+ return line.srts.map((s): UnserializedSrt => {
+ return {
+ text: s.text,
+ firstTimestampMs: s.firstTimestampMs + line.offsetInMs,
+ lastTimestampMs: s.lastTimestampMs + line.offsetInMs,
+ captions: s.captions,
+ };
+ });
+ })
+ .flat(1);
+};
diff --git a/packages/template-recorder/remotion/captions/srt/helpers/parse-srt.ts b/packages/template-recorder/remotion/captions/srt/helpers/parse-srt.ts
new file mode 100644
index 0000000000..cb950a0b9e
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/helpers/parse-srt.ts
@@ -0,0 +1,67 @@
+export type ParsedSrtLine = {
+ index: number;
+ text: string;
+ startInSeconds: number;
+ endInSeconds: number;
+};
+
+export type ParsedSrt = ParsedSrtLine[];
+
+function toSeconds(time: string) {
+ const [first, second, third] = time.split(":");
+ if (!first) {
+ throw new Error(`Invalid timestamp:${time}`);
+ }
+ if (!second) {
+ throw new Error(`Invalid timestamp:${time}`);
+ }
+ if (!third) {
+ throw new Error(`Invalid timestamp:${time}`);
+ }
+
+ const [seconds, millis] = third.split(",");
+ if (!seconds) {
+ throw new Error(`Invalid timestamp:${time}`);
+ }
+ if (!millis) {
+ throw new Error(`Invalid timestamp:${time}`);
+ }
+
+ return (
+ parseInt(first, 10) * 3600 +
+ parseInt(second, 10) * 60 +
+ parseInt(seconds, 10) +
+ parseInt(millis, 10) / 1000
+ );
+}
+
+export const parseSrt = (input: string): ParsedSrt => {
+ const inputLines = input.split("\n");
+ const lines: ParsedSrtLine[] = [];
+
+ for (let i = 0; i < inputLines.length; i++) {
+ const line = inputLines[i];
+ const nextLine = inputLines[i + 1];
+ if (line?.match(/([0-9]+)/) && nextLine?.includes(" --> ")) {
+ const nextLineSplit = nextLine.split(" --> ");
+ const start = toSeconds(nextLineSplit[0] as string);
+ const end = toSeconds(nextLineSplit[1] as string);
+ lines.push({
+ index: Number(line),
+ text: "",
+ startInSeconds: start,
+ endInSeconds: end,
+ });
+ } else if (line?.includes(" --> ")) {
+ continue;
+ } else if (line?.trim() === "") {
+ (lines[lines.length - 1] as ParsedSrtLine).text = (
+ lines[lines.length - 1] as ParsedSrtLine
+ ).text.trim();
+ } else {
+ (lines[lines.length - 1] as ParsedSrtLine).text += line + "\n";
+ }
+ }
+
+ return lines;
+};
diff --git a/packages/template-recorder/remotion/captions/srt/helpers/serialize-srt.ts b/packages/template-recorder/remotion/captions/srt/helpers/serialize-srt.ts
new file mode 100644
index 0000000000..c808b4efb0
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/srt/helpers/serialize-srt.ts
@@ -0,0 +1,39 @@
+import { Caption } from "@remotion/captions";
+
+export type UnserializedSrt = {
+ firstTimestampMs: number;
+ lastTimestampMs: number;
+ text: string;
+ // Not effectively used for SRT serializing, but allows for clicking on a caption to jump to it
+ captions: Caption[];
+};
+
+const formatSingleSrtTimestamp = (timestamp: number) => {
+ const hours = Math.floor(timestamp / 3600000);
+ const minutes = Math.floor((timestamp % 3600000) / 60000);
+ const seconds = Math.floor((timestamp % 60000) / 1000);
+ const milliseconds = Math.floor(timestamp % 1000);
+
+ return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")},${String(milliseconds).padStart(3, "0")}`;
+};
+
+const formatSrtTimestamp = (startMs: number, endMs: number) => {
+ return `${formatSingleSrtTimestamp(startMs)} --> ${formatSingleSrtTimestamp(endMs)}`;
+};
+
+export const serializeSrt = (srt: UnserializedSrt[]) => {
+ let currentIndex = 0;
+
+ return srt
+ .map((s) => {
+ currentIndex++;
+ return [
+ // Index
+ currentIndex,
+ formatSrtTimestamp(s.firstTimestampMs, s.lastTimestampMs),
+ // Text
+ s.text,
+ ].join("\n");
+ })
+ .join("\n\n");
+};
diff --git a/packages/template-recorder/remotion/captions/types.ts b/packages/template-recorder/remotion/captions/types.ts
new file mode 100644
index 0000000000..73df47a365
--- /dev/null
+++ b/packages/template-recorder/remotion/captions/types.ts
@@ -0,0 +1,9 @@
+import { Caption } from "@remotion/captions";
+
+export type CaptionPage = {
+ captions: Caption[];
+};
+
+export type LayoutedCaptions = {
+ segments: CaptionPage[];
+};
diff --git a/packages/template-recorder/remotion/chapters/landscape/ChapterTimestamp.tsx b/packages/template-recorder/remotion/chapters/landscape/ChapterTimestamp.tsx
new file mode 100644
index 0000000000..dba599ccb5
--- /dev/null
+++ b/packages/template-recorder/remotion/chapters/landscape/ChapterTimestamp.tsx
@@ -0,0 +1,49 @@
+import { measureText } from "@remotion/layout-utils";
+import React, { useMemo } from "react";
+import { TITLE_FONT } from "../../../config/fonts";
+import { FPS } from "../../../config/fps";
+import { formatMilliseconds } from "../../../src/helpers/format-time";
+import { ChapterType } from "../make-chapters";
+
+const chapterFontSize = 32;
+
+const getChapterWidth = (text: string) => {
+ return measureText({
+ text,
+ fontFamily: TITLE_FONT.fontFamily as string,
+ fontWeight: TITLE_FONT.fontWeight as string,
+ fontSize: chapterFontSize,
+ }).width;
+};
+
+const PADDING_VERTICAL = 12;
+const PADDING_HORIZONTAL = 18;
+
+export const ChapterTimestamp: React.FC<{
+ chapter: ChapterType;
+ timestampOfLastChapter: number;
+}> = ({ chapter, timestampOfLastChapter }) => {
+ const biggestWidth = getChapterWidth(
+ formatMilliseconds((timestampOfLastChapter / FPS) * 1000),
+ );
+
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ backgroundColor: "black",
+ color: "white",
+ padding: `${PADDING_VERTICAL}px 0px`,
+ fontSize: chapterFontSize,
+ ...TITLE_FONT,
+ width: biggestWidth + PADDING_HORIZONTAL * 2,
+ textAlign: "center",
+ height: "100%",
+ justifyContent: "center",
+ alignItems: "center",
+ display: "flex",
+ };
+ }, [biggestWidth]);
+
+ return (
+ <div style={style}>{formatMilliseconds((chapter.start / FPS) * 1000)}</div>
+ );
+};
diff --git a/packages/template-recorder/remotion/chapters/landscape/ChapterTitle.tsx b/packages/template-recorder/remotion/chapters/landscape/ChapterTitle.tsx
new file mode 100644
index 0000000000..df66112d64
--- /dev/null
+++ b/packages/template-recorder/remotion/chapters/landscape/ChapterTitle.tsx
@@ -0,0 +1,40 @@
+import React, { useMemo } from "react";
+import { TITLE_FONT } from "../../../config/fonts";
+import { COLORS, Theme } from "../../../config/themes";
+import { ChapterType } from "../make-chapters";
+
+export const ChapterTitle: React.FC<{
+ rightAligned: boolean;
+ theme: Theme;
+ chapter: ChapterType;
+ activeIndex: number;
+}> = ({ rightAligned, theme, activeIndex, chapter }) => {
+ const isCurrent = chapter.index === activeIndex;
+
+ const textStyle: React.CSSProperties = useMemo(() => {
+ return {
+ padding: "0px 20px",
+ fontSize: 36,
+ ...TITLE_FONT,
+ height: "100%",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ right: rightAligned ? undefined : 0,
+ left: rightAligned ? 0 : undefined,
+ };
+ }, [rightAligned]);
+
+ return (
+ <div
+ style={{
+ ...textStyle,
+ backgroundColor: isCurrent ? COLORS[theme].ACCENT_COLOR : "white",
+ padding: "0px 20px",
+ color: isCurrent ? "white" : "black",
+ }}
+ >
+ {chapter.title}
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/chapters/landscape/LandscapeChapter.tsx b/packages/template-recorder/remotion/chapters/landscape/LandscapeChapter.tsx
new file mode 100644
index 0000000000..7122f18f4d
--- /dev/null
+++ b/packages/template-recorder/remotion/chapters/landscape/LandscapeChapter.tsx
@@ -0,0 +1,58 @@
+import React, { useMemo } from "react";
+import { type Theme } from "../../../config/themes";
+import type { ChapterType } from "../make-chapters";
+import { ChapterTimestamp } from "./ChapterTimestamp";
+import { ChapterTitle } from "./ChapterTitle";
+
+export const CHAPTER_HEIGHT = 80;
+export const CHAPTER_VERTICAL_MARGIN = 4;
+
+export const LandscapeChapter: React.FC<{
+ chapter: ChapterType;
+ activeIndex: number;
+ isFirstShown: boolean;
+ isLastShown: boolean;
+ rightAligned: boolean;
+ theme: Theme;
+ timestampOfLastChapter: number;
+}> = ({
+ chapter,
+ activeIndex,
+ isLastShown,
+ isFirstShown,
+ rightAligned,
+ theme,
+ timestampOfLastChapter,
+}) => {
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ display: "inline-flex",
+ borderRadius: 20,
+ border: "5px solid black",
+ marginTop: isFirstShown ? 0 : CHAPTER_VERTICAL_MARGIN,
+ marginBottom: isLastShown ? 0 : CHAPTER_VERTICAL_MARGIN,
+ overflow: "hidden",
+ height: CHAPTER_HEIGHT,
+ justifyContent: "center",
+ alignItems: "center",
+ flexDirection: rightAligned ? "row-reverse" : "row",
+ };
+ }, [isFirstShown, isLastShown, rightAligned]);
+
+ return (
+ <div>
+ <div style={style}>
+ <ChapterTimestamp
+ timestampOfLastChapter={timestampOfLastChapter}
+ chapter={chapter}
+ />
+ <ChapterTitle
+ chapter={chapter}
+ rightAligned={rightAligned}
+ theme={theme}
+ activeIndex={activeIndex}
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/chapters/landscape/LandscapeChapters.tsx b/packages/template-recorder/remotion/chapters/landscape/LandscapeChapters.tsx
new file mode 100644
index 0000000000..c9d256a103
--- /dev/null
+++ b/packages/template-recorder/remotion/chapters/landscape/LandscapeChapters.tsx
@@ -0,0 +1,110 @@
+import React, { useMemo } from "react";
+import {
+ AbsoluteFill,
+ interpolate,
+ spring,
+ useCurrentFrame,
+ useVideoConfig,
+} from "remotion";
+import type { VideoSceneAndMetadata } from "../../../config/scenes";
+import { isWebCamRight } from "../../animations/webcam-transitions/helpers";
+
+import { Theme } from "../../../config/themes";
+import { SCENE_TRANSITION_DURATION } from "../../../config/transitions";
+import type { ChapterType } from "../make-chapters";
+import {
+ CHAPTER_HEIGHT,
+ CHAPTER_VERTICAL_MARGIN,
+ LandscapeChapter,
+} from "./LandscapeChapter";
+import { getWidescreenChapterStyle } from "./layout";
+
+export const LandscapeChapters: React.FC<{
+ scene: VideoSceneAndMetadata;
+ chapters: ChapterType[];
+ didTransitionIn: boolean;
+ theme: Theme;
+}> = ({ chapters, scene, theme, didTransitionIn }) => {
+ const frame = useCurrentFrame();
+ const { fps, width } = useVideoConfig();
+ const chapterIndex = chapters.findIndex((c) => c.title === scene.chapter);
+
+ const shownChapters = useMemo(() => {
+ if (chapterIndex === 0) {
+ return chapters.slice(0, 3);
+ }
+
+ return chapters.slice(
+ Math.max(0, chapterIndex - 1),
+ Math.min(chapters.length, chapterIndex + 2),
+ );
+ }, [chapterIndex, chapters]);
+
+ const tableOfContentHeight =
+ (CHAPTER_HEIGHT + CHAPTER_VERTICAL_MARGIN * 2) * shownChapters.length -
+ CHAPTER_VERTICAL_MARGIN * 2;
+
+ const rightAligned = isWebCamRight(
+ scene.webcamPosition === "center" ? "top-left" : scene.webcamPosition,
+ );
+
+ const delay = didTransitionIn ? SCENE_TRANSITION_DURATION : 0;
+
+ const enter = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: delay,
+ });
+
+ const exit = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: 70 + delay,
+ });
+
+ const enterTranslation = interpolate(enter - exit, [0, 1], [-width / 2, 0]);
+
+ const styles = getWidescreenChapterStyle(scene, tableOfContentHeight);
+
+ return (
+ <AbsoluteFill
+ style={
+ rightAligned
+ ? { right: enterTranslation, left: undefined }
+ : { left: enterTranslation, right: undefined }
+ }
+ >
+ <AbsoluteFill
+ style={{
+ flexDirection: "column",
+ height: tableOfContentHeight,
+ flex: 1,
+ ...styles,
+ }}
+ >
+ {shownChapters.map((chapter, i) => {
+ return (
+ <LandscapeChapter
+ key={chapter.index}
+ activeIndex={chapterIndex}
+ chapter={chapter}
+ isFirstShown={i === 0}
+ isLastShown={i === shownChapters.length - 1}
+ rightAligned={rightAligned}
+ theme={theme}
+ timestampOfLastChapter={
+ (shownChapters[shownChapters.length - 1] as ChapterType).start
+ }
+ />
+ );
+ })}
+ </AbsoluteFill>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/chapters/landscape/layout.ts b/packages/template-recorder/remotion/chapters/landscape/layout.ts
new file mode 100644
index 0000000000..1944104a56
--- /dev/null
+++ b/packages/template-recorder/remotion/chapters/landscape/layout.ts
@@ -0,0 +1,81 @@
+import React from "react";
+import { getSafeSpace } from "../../../config/layout";
+import type { VideoSceneAndMetadata } from "../../../config/scenes";
+import {} from "../../animations/webcam-transitions";
+import {
+ isWebCamAtBottom,
+ isWebCamRight,
+} from "../../animations/webcam-transitions/helpers";
+import type { Layout } from "../../layout/layout-types";
+
+const getWidescreenChapterLayout = (
+ scene: VideoSceneAndMetadata,
+ tableOfContentHeight: number,
+): React.CSSProperties => {
+ const { layout, webcamPosition } = scene;
+
+ if (webcamPosition === "center") {
+ return {
+ height: 1000,
+ borderRadius: 0,
+ opacity: 1,
+ left: getSafeSpace("landscape"),
+ bottom: getSafeSpace("landscape"),
+ width: 10000,
+ top: undefined,
+ };
+ }
+
+ const rightAligned = isWebCamRight(webcamPosition);
+ const bottomAligned = isWebCamAtBottom(webcamPosition);
+
+ const chapterLayout: Layout = {
+ height: 1000,
+ borderRadius: 0,
+ opacity: 1,
+ ...(rightAligned
+ ? {
+ left: 0,
+ width: layout.webcamLayout.left + layout.webcamLayout.width,
+ }
+ : { left: layout.webcamLayout.left, width: 100000 }),
+ ...(bottomAligned
+ ? {
+ top:
+ layout.webcamLayout.top -
+ tableOfContentHeight -
+ getSafeSpace("landscape"),
+ bottom: undefined,
+ }
+ : {
+ top:
+ getSafeSpace("landscape") +
+ layout.webcamLayout.top +
+ layout.webcamLayout.height,
+ bottom: undefined,
+ }),
+ };
+
+ return chapterLayout;
+};
+
+export const getWidescreenChapterStyle = (
+ scene: VideoSceneAndMetadata,
+ tableOfContentHeight: number,
+): React.CSSProperties => {
+ const chapterLayout = getWidescreenChapterLayout(scene, tableOfContentHeight);
+
+ const rightAligned = isWebCamRight(
+ scene.webcamPosition === "center" ? "bottom-left" : scene.webcamPosition,
+ );
+
+ return {
+ ...chapterLayout,
+ ...(rightAligned
+ ? {
+ alignSelf: "flex-end",
+ alignItems: "flex-end",
+ }
+ : {}),
+ };
+};
diff --git a/packages/template-recorder/remotion/chapters/make-chapters.ts b/packages/template-recorder/remotion/chapters/make-chapters.ts
new file mode 100644
index 0000000000..f317e60b49
--- /dev/null
+++ b/packages/template-recorder/remotion/chapters/make-chapters.ts
@@ -0,0 +1,31 @@
+import type { SceneAndMetadata } from "../../config/scenes";
+
+export type ChapterType = {
+ title: string;
+ start: number;
+ index: number;
+};
+
+export const makeChapters = ({ scenes }: { scenes: SceneAndMetadata[] }) => {
+ const chapters: ChapterType[] = [];
+
+ for (let i = 0; i < scenes.length; i++) {
+ const scene = scenes[i] as SceneAndMetadata;
+
+ if (scene.type === "video-scene" && scene.scene.newChapter) {
+ const chapter: ChapterType = {
+ title: scene.scene.newChapter,
+ start: scene.from,
+ index: chapters.length,
+ };
+
+ chapters.push(chapter);
+ }
+
+ if (scene.type === "video-scene" && scene.scene.stopChapteringAfterThis) {
+ break;
+ }
+ }
+
+ return chapters;
+};
diff --git a/packages/template-recorder/remotion/chapters/square/SquareChapter.tsx b/packages/template-recorder/remotion/chapters/square/SquareChapter.tsx
new file mode 100644
index 0000000000..f7fd87d3b1
--- /dev/null
+++ b/packages/template-recorder/remotion/chapters/square/SquareChapter.tsx
@@ -0,0 +1,104 @@
+import React, { useMemo } from "react";
+import {
+ AbsoluteFill,
+ spring,
+ useCurrentFrame,
+ useVideoConfig,
+} from "remotion";
+import { TITLE_FONT } from "../../../config/fonts";
+import { getSafeSpace } from "../../../config/layout";
+import { SCENE_TRANSITION_DURATION } from "../../../config/transitions";
+import { borderRadius } from "../../layout/get-layout";
+import type { Layout } from "../../layout/layout-types";
+
+const HEIGHT = 78;
+
+const gradientSteps = [
+ 0, 0.013, 0.049, 0.104, 0.175, 0.259, 0.352, 0.45, 0.55, 0.648, 0.741, 0.825,
+ 0.896, 0.951, 0.987,
+];
+
+const gradientOpacities = [
+ 0, 8.1, 15.5, 22.5, 29, 35.3, 41.2, 47.1, 52.9, 58.8, 64.7, 71, 77.5, 84.5,
+ 91.9,
+];
+
+const globalGradientOpacity = 1 / 0.7;
+
+export const SquareChapter: React.FC<{
+ title: string;
+ didTransitionIn: boolean;
+ displayLayout: Layout | null;
+ webcamLayout: Layout;
+}> = ({ title, webcamLayout, didTransitionIn, displayLayout }) => {
+ const layout = useMemo(() => {
+ return displayLayout ?? webcamLayout;
+ }, [displayLayout, webcamLayout]);
+
+ const top = useMemo(() => {
+ return layout.height - HEIGHT - getSafeSpace("square");
+ }, [layout.height]);
+
+ const frame = useCurrentFrame();
+ const { fps, width } = useVideoConfig();
+
+ const enter = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: didTransitionIn ? SCENE_TRANSITION_DURATION : 0,
+ });
+
+ const exit = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: 70,
+ });
+ const toTop = (1 - enter) * (HEIGHT + getSafeSpace("square"));
+ const toLeft = exit * -width;
+
+ return (
+ <AbsoluteFill style={{ pointerEvents: "none" }}>
+ <div
+ style={{
+ ...layout,
+ backgroundImage: `linear-gradient(to bottom,${gradientSteps
+ .map((g, i) => {
+ return `hsla(0, 0%, 100%, ${g}) ${
+ (gradientOpacities[i] as number) * globalGradientOpacity
+ }%`;
+ })
+ .join(", ")}, hsl(0, 0%, 100%) 100%)`,
+ position: "absolute",
+ opacity: (enter - exit) * 0.2,
+ }}
+ />
+ <div style={{ ...layout, position: "absolute", overflow: "hidden" }}>
+ <div
+ style={{
+ color: "white",
+ padding: "0 30px",
+ background: "black",
+ position: "absolute",
+ top: top + toTop,
+ height: HEIGHT,
+ left: getSafeSpace("square"),
+ borderRadius,
+ fontSize: 40,
+ ...TITLE_FONT,
+ display: "flex",
+ alignItems: "center",
+ transform: `translateX(${toLeft}px)`,
+ }}
+ >
+ {title}
+ </div>{" "}
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/helpers/WaitForFonts.tsx b/packages/template-recorder/remotion/helpers/WaitForFonts.tsx
new file mode 100644
index 0000000000..1faab8a99e
--- /dev/null
+++ b/packages/template-recorder/remotion/helpers/WaitForFonts.tsx
@@ -0,0 +1,34 @@
+import React, { useEffect, useState } from "react";
+import { cancelRender, continueRender, delayRender } from "remotion";
+import { waitForFonts } from "../../config/fonts";
+
+// Missing fonts can influence the layout calculation
+// and cause the subtitles to be misaligned.
+
+// Use this component to only mount components once all fonts are loaded
+export const WaitForFonts: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
+ const [fontsLoaded, setFontsLoaded] = useState(false);
+ const [handle] = useState(() => delayRender());
+
+ useEffect(() => {
+ const delay = delayRender("Waiting for fonts to be loaded");
+
+ waitForFonts()
+ .then(() => {
+ continueRender(handle);
+ continueRender(delay);
+ setFontsLoaded(true);
+ })
+ .catch((err) => {
+ cancelRender(err);
+ });
+ }, [fontsLoaded, handle]);
+
+ if (!fontsLoaded) {
+ return null;
+ }
+
+ return <>{children}</>;
+};
diff --git a/packages/template-recorder/remotion/helpers/refresh-on-public-folder-change.ts b/packages/template-recorder/remotion/helpers/refresh-on-public-folder-change.ts
new file mode 100644
index 0000000000..d363b75352
--- /dev/null
+++ b/packages/template-recorder/remotion/helpers/refresh-on-public-folder-change.ts
@@ -0,0 +1,55 @@
+import {
+ getStaticFiles,
+ reevaluateComposition,
+ watchPublicFolder,
+} from "@remotion/studio";
+import { useEffect, useState } from "react";
+import { StaticFile } from "remotion";
+import {
+ ALTERNATIVE1_PREFIX,
+ ALTERNATIVE2_PREFIX,
+ DISPLAY_PREFIX,
+ WEBCAM_PREFIX,
+} from "../../config/cameras";
+
+const filterForCurrentComposition = (
+ files: StaticFile[],
+ compositionId: string,
+) => {
+ return files.filter((f) => {
+ const PREFIXES_TO_WATCH = [
+ `${compositionId}/${WEBCAM_PREFIX}`,
+ `${compositionId}/${DISPLAY_PREFIX}`,
+ `${compositionId}/${ALTERNATIVE1_PREFIX}`,
+ `${compositionId}/${ALTERNATIVE2_PREFIX}`,
+ ];
+
+ return PREFIXES_TO_WATCH.some((p) => f.name.startsWith(p));
+ });
+};
+
+export const useRefreshOnPublicFolderChange = (compositionId: string) => {
+ const [staticFiles, setStaticFiles] = useState(() =>
+ filterForCurrentComposition(getStaticFiles(), compositionId),
+ );
+
+ useEffect(() => {
+ const { cancel } = watchPublicFolder(() => {
+ const newStaticFiles = filterForCurrentComposition(
+ getStaticFiles(),
+ compositionId,
+ );
+
+ if (JSON.stringify(newStaticFiles) === JSON.stringify(staticFiles)) {
+ return;
+ }
+
+ setStaticFiles(newStaticFiles);
+ reevaluateComposition();
+ });
+
+ return () => {
+ cancel();
+ };
+ }, [compositionId, staticFiles]);
+};
diff --git a/packages/template-recorder/remotion/helpers/scroll-to-current-scene.ts b/packages/template-recorder/remotion/helpers/scroll-to-current-scene.ts
new file mode 100644
index 0000000000..cb10ca1115
--- /dev/null
+++ b/packages/template-recorder/remotion/helpers/scroll-to-current-scene.ts
@@ -0,0 +1,32 @@
+// In the props editor, scroll to the current scene
+
+import { focusDefaultPropsPath } from "@remotion/studio";
+import { useEffect } from "react";
+import { useCurrentFrame } from "remotion";
+
+export const useScrollToCurrentScene = ({
+ index,
+ fullyEntered,
+}: {
+ index: number;
+ fullyEntered: boolean;
+}) => {
+ const frame = useCurrentFrame();
+ const isPremountingAndOrFirstFrame = frame === 0;
+
+ useEffect(() => {
+ if (isPremountingAndOrFirstFrame) {
+ return;
+ }
+
+ if (!fullyEntered) {
+ return;
+ }
+
+ // Reveal the current scene in the props editor
+ focusDefaultPropsPath({
+ path: ["scenes", index],
+ scrollBehavior: "smooth",
+ });
+ }, [fullyEntered, index, isPremountingAndOrFirstFrame]);
+};
diff --git a/packages/template-recorder/remotion/helpers/truthy.ts b/packages/template-recorder/remotion/helpers/truthy.ts
new file mode 100644
index 0000000000..d0b895751d
--- /dev/null
+++ b/packages/template-recorder/remotion/helpers/truthy.ts
@@ -0,0 +1,5 @@
+type Truthy<T> = T extends false | "" | 0 | null | undefined ? never : T;
+
+export function truthy<T>(value: T): value is Truthy<T> {
+ return Boolean(value);
+}
diff --git a/packages/template-recorder/remotion/index.ts b/packages/template-recorder/remotion/index.ts
new file mode 100644
index 0000000000..e78af8ba34
--- /dev/null
+++ b/packages/template-recorder/remotion/index.ts
@@ -0,0 +1,4 @@
+import { registerRoot } from "remotion";
+import { Root } from "./Root";
+
+registerRoot(Root);
diff --git a/packages/template-recorder/remotion/layout/blur.ts b/packages/template-recorder/remotion/layout/blur.ts
new file mode 100644
index 0000000000..072af04055
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/blur.ts
@@ -0,0 +1,79 @@
+import type React from "react";
+import {
+ DIMENSIONS,
+ type CanvasLayout,
+ type Dimensions,
+} from "../../config/layout";
+import type { SceneAndMetadata } from "../../config/scenes";
+import { fitElementSizeInContainer } from "./fit-element";
+import type { Layout } from "./layout-types";
+
+// Background blur should only be enabled in landscape layout
+// when the webcam is in fullscreen
+export const shouldEnableSceneBackgroundBlur = (
+ scene: SceneAndMetadata,
+ canvasLayout: CanvasLayout,
+) => {
+ if (scene.type !== "video-scene") {
+ return false;
+ }
+
+ if (scene.layout.displayLayout) {
+ return false;
+ }
+
+ if (canvasLayout !== "landscape") {
+ return false;
+ }
+
+ const sameAspectRatio =
+ scene.layout.webcamLayout.width / scene.layout.webcamLayout.height ===
+ DIMENSIONS[canvasLayout].width / DIMENSIONS[canvasLayout].height;
+
+ return !sameAspectRatio;
+};
+
+export const getBlurLayout = ({
+ containerLayout,
+ assetSize,
+}: {
+ containerLayout: Layout;
+ assetSize: Dimensions;
+}) => {
+ const inner = fitElementSizeInContainer({
+ containerSize: containerLayout,
+ elementSize: assetSize,
+ });
+
+ const outerStyle: React.CSSProperties = {
+ ...containerLayout,
+ left: 0,
+ top: 0,
+ overflow: "hidden",
+ };
+
+ const innerStyle: React.CSSProperties = {
+ position: "absolute",
+ ...containerLayout,
+ ...inner,
+ };
+
+ const needsBlur = inner.left > 0.000001 || inner.top > 0.000001;
+
+ return {
+ needsBlur,
+ outerStyle,
+ innerStyle,
+ blurStyle: {
+ // Chrome has "blur bleed" where it does not blur the edges of the image.
+ // Fixing by making the image larger
+ width: "110%",
+ height: "110%",
+ objectFit: "cover",
+ filter: "blur(20px)",
+ top: "-5%",
+ left: "-5%",
+ position: "absolute",
+ } as React.CSSProperties,
+ };
+};
diff --git a/packages/template-recorder/remotion/layout/dimensions.ts b/packages/template-recorder/remotion/layout/dimensions.ts
new file mode 100644
index 0000000000..3021aa8340
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/dimensions.ts
@@ -0,0 +1,8 @@
+import type { CanvasLayout, Dimensions } from "../../config/layout";
+import { DIMENSIONS } from "../../config/layout";
+
+export const getDimensionsForLayout = (
+ canvasLayout: CanvasLayout,
+): Dimensions => {
+ return DIMENSIONS[canvasLayout];
+};
diff --git a/packages/template-recorder/remotion/layout/fit-element.ts b/packages/template-recorder/remotion/layout/fit-element.ts
new file mode 100644
index 0000000000..af6287e3c0
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/fit-element.ts
@@ -0,0 +1,36 @@
+import type { Dimensions } from "@remotion/layout-utils";
+import type { Rect } from "./layout-types";
+
+// Resize an aspect ratio to fit into a container
+// and center it
+export const fitElementSizeInContainer = ({
+ containerSize,
+ elementSize,
+}: {
+ containerSize: Dimensions;
+ elementSize: Dimensions;
+}): Rect => {
+ const heightRatio = containerSize.height / elementSize.height;
+ const widthRatio = containerSize.width / elementSize.width;
+
+ const ratio = Math.min(heightRatio, widthRatio);
+
+ const newWidth = elementSize.width * ratio;
+ const newHeight = elementSize.height * ratio;
+
+ if (
+ newWidth > containerSize.width + 0.000001 ||
+ newHeight > containerSize.height + 0.000001
+ ) {
+ throw new Error(
+ `Element is too big to fit into the container. Max size: ${containerSize.width}x${containerSize.height}, element size: ${newWidth}x${newHeight}`,
+ );
+ }
+
+ return {
+ width: newWidth,
+ height: newHeight,
+ top: (containerSize.height - newHeight) / 2,
+ left: (containerSize.width - newWidth) / 2,
+ };
+};
diff --git a/packages/template-recorder/remotion/layout/get-broll-dimensions.ts b/packages/template-recorder/remotion/layout/get-broll-dimensions.ts
new file mode 100644
index 0000000000..3bdd6521e5
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/get-broll-dimensions.ts
@@ -0,0 +1,56 @@
+import { parseMedia } from "@remotion/media-parser";
+import { getImageDimensions } from "@remotion/media-utils";
+import type { BRoll, BRollWithDimensions } from "../../config/scenes";
+
+const imageFileExtensions = [
+ "jpg",
+ "jpeg",
+ "png",
+ "gif",
+ "webp",
+ "bmp",
+ "svg",
+ "ico",
+];
+
+const videoFileExtensions = ["mp4", "webm", "mov", "mkv"];
+
+export const getBRollDimensions = async (
+ bRoll: BRoll,
+): Promise<BRollWithDimensions> => {
+ if (
+ imageFileExtensions.some((ext) => bRoll.source.toLowerCase().endsWith(ext))
+ ) {
+ const { width, height } = await getImageDimensions(bRoll.source);
+ return {
+ ...bRoll,
+ type: "image",
+ assetWidth: width,
+ assetHeight: height,
+ };
+ }
+
+ if (
+ videoFileExtensions.some((ext) => bRoll.source.toLowerCase().endsWith(ext))
+ ) {
+ const metadata = await parseMedia({
+ src: bRoll.source,
+ fields: { dimensions: true },
+ acknowledgeRemotionLicense: true
+ });
+ if (!metadata.dimensions) {
+ throw new Error("No dimensions found for bRoll: " + bRoll.source);
+ }
+
+ return {
+ ...bRoll,
+ type: "video",
+ assetWidth: metadata.dimensions.width,
+ assetHeight: metadata.dimensions.height,
+ };
+ }
+
+ throw new Error(
+ `Unsupported file extension for bRoll: ${bRoll.source}. Only ${[...imageFileExtensions, ...videoFileExtensions].join(", ")} are supported.`,
+ );
+};
diff --git a/packages/template-recorder/remotion/layout/get-captions-layout.ts b/packages/template-recorder/remotion/layout/get-captions-layout.ts
new file mode 100644
index 0000000000..136427834a
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/get-captions-layout.ts
@@ -0,0 +1,57 @@
+import type { CanvasLayout, Dimensions } from "../../config/layout";
+import { getSafeSpace } from "../../config/layout";
+import type { WebcamPosition } from "../../config/scenes";
+import {} from "../animations/webcam-transitions";
+import {
+ isWebCamAtBottom,
+ isWebCamRight,
+} from "../animations/webcam-transitions/helpers";
+import { borderRadius } from "./get-layout";
+import type { Layout } from "./layout-types";
+
+export const getCaptionsLayout = ({
+ canvasLayout,
+ canvasSize,
+ webcamLayout,
+ webcamPosition,
+ displayLayout,
+}: {
+ canvasLayout: CanvasLayout;
+ canvasSize: Dimensions;
+ webcamLayout: Layout;
+ webcamPosition: WebcamPosition;
+ displayLayout: Dimensions | null;
+}): Layout | null => {
+ if (canvasLayout !== "square") {
+ return null;
+ }
+ if (displayLayout === null) {
+ const isTopAligned = !isWebCamAtBottom(webcamPosition);
+
+ return {
+ height:
+ canvasSize.height -
+ webcamLayout.height -
+ getSafeSpace(canvasLayout) * 3,
+ top: isTopAligned
+ ? webcamLayout.height + getSafeSpace(canvasLayout) * 2
+ : getSafeSpace(canvasLayout),
+ left: getSafeSpace(canvasLayout),
+ width: canvasSize.width - getSafeSpace(canvasLayout) * 2,
+ borderRadius,
+ opacity: 1,
+ };
+ }
+
+ return {
+ height: webcamLayout.height,
+ top: webcamLayout.top,
+ left: isWebCamRight(webcamPosition)
+ ? getSafeSpace(canvasLayout)
+ : webcamLayout.width + getSafeSpace(canvasLayout) * 2,
+ width:
+ canvasSize.width - webcamLayout.width - getSafeSpace(canvasLayout) * 3,
+ borderRadius,
+ opacity: 1,
+ };
+};
diff --git a/packages/template-recorder/remotion/layout/get-display-layout.ts b/packages/template-recorder/remotion/layout/get-display-layout.ts
new file mode 100644
index 0000000000..fc3a01548b
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/get-display-layout.ts
@@ -0,0 +1,112 @@
+import type { CanvasLayout } from "../../config/layout";
+import { getSafeSpace, type Dimensions } from "../../config/layout";
+import type { WebcamPosition } from "../../config/scenes";
+import {
+ isWebCamAtBottom,
+ isWebCamRight,
+} from "../animations/webcam-transitions/helpers";
+import { borderRadius, fullscreenLayout } from "./get-layout";
+import type {
+ BRollEnterDirection,
+ Layout,
+ RecordingsLayout,
+} from "./layout-types";
+
+const getYForDisplayLayout = ({
+ webcamPosition,
+ canvasSize,
+ displayHeight,
+}: {
+ webcamPosition: WebcamPosition;
+ canvasSize: Dimensions;
+ displayHeight: number;
+}): number => {
+ if (isWebCamAtBottom(webcamPosition)) {
+ return getSafeSpace("square");
+ }
+
+ return canvasSize.height - displayHeight - getSafeSpace("square");
+};
+
+export const getSquareDisplayLayout = ({
+ canvasSize,
+ webcamPosition,
+ displaySize,
+}: {
+ canvasSize: Dimensions;
+ webcamPosition: WebcamPosition;
+ displaySize: Dimensions;
+}): Layout => {
+ return {
+ left: (canvasSize.width - displaySize.width) / 2,
+ top: getYForDisplayLayout({
+ webcamPosition,
+ canvasSize,
+ displayHeight: displaySize.height,
+ }),
+ width: displaySize.width,
+ height: displaySize.height,
+ borderRadius,
+ opacity: 1,
+ };
+};
+
+export const getSquareBRollLayout = ({
+ canvasSize,
+ webcamPosition,
+ displaySize,
+}: {
+ canvasSize: Dimensions;
+ webcamPosition: WebcamPosition;
+ displaySize: Dimensions;
+}): { bRollLayout: Layout; bRollEnterDirection: BRollEnterDirection } => {
+ return {
+ bRollEnterDirection: isWebCamAtBottom(webcamPosition) ? "top" : "bottom",
+ bRollLayout: {
+ left: getSafeSpace("square"),
+ top: getYForDisplayLayout({
+ webcamPosition,
+ canvasSize,
+ displayHeight: displaySize.height,
+ }),
+ width: canvasSize.width - getSafeSpace("square") * 2,
+ height: displaySize.height,
+ borderRadius,
+ opacity: 1,
+ },
+ };
+};
+
+export const getLandscapeDisplayAndWebcamLayout = ({
+ webcamSize,
+ canvasLayout,
+ canvasSize,
+ webcamPosition,
+}: {
+ webcamSize: Dimensions;
+ canvasLayout: CanvasLayout;
+ canvasSize: Dimensions;
+ webcamPosition: WebcamPosition;
+}): RecordingsLayout => {
+ const displayLayout: Layout = fullscreenLayout(canvasSize);
+
+ const webcamLayout: Layout = {
+ borderRadius,
+ height: webcamSize.height,
+ width: webcamSize.width,
+ opacity: 1,
+ left: isWebCamRight(webcamPosition)
+ ? canvasSize.width - webcamSize.width - getSafeSpace(canvasLayout)
+ : getSafeSpace("landscape"),
+ top: isWebCamAtBottom(webcamPosition)
+ ? canvasSize.height - webcamSize.height - getSafeSpace(canvasLayout)
+ : getSafeSpace("landscape"),
+ };
+
+ return {
+ displayLayout,
+ webcamLayout,
+ bRollLayout: displayLayout,
+ bRollEnterDirection: isWebCamAtBottom(webcamPosition) ? "top" : "bottom",
+ };
+};
diff --git a/packages/template-recorder/remotion/layout/get-display-size.ts b/packages/template-recorder/remotion/layout/get-display-size.ts
new file mode 100644
index 0000000000..6c2ec4e0e2
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/get-display-size.ts
@@ -0,0 +1,68 @@
+import type { CanvasLayout, Dimensions } from "../../config/layout";
+import {
+ getSafeSpace,
+ LANDSCAPE_DISPLAY_MAX_WIDTH_OF_CANVAS,
+} from "../../config/layout";
+import { fitElementSizeInContainer } from "./fit-element";
+import { getBottomSafeSpace } from "./get-safe-space";
+
+const getMaxHeight = ({
+ canvasSize,
+ canvasLayout,
+ bottomSafeSpace,
+}: {
+ canvasSize: Dimensions;
+ canvasLayout: CanvasLayout;
+ bottomSafeSpace: number;
+}) => {
+ const withoutSafeAreas =
+ canvasSize.height - bottomSafeSpace - getSafeSpace(canvasLayout);
+
+ if (canvasLayout === "square") {
+ const threeFifths = withoutSafeAreas * (3 / 5);
+
+ return threeFifths;
+ }
+
+ return withoutSafeAreas;
+};
+
+const getMaxWidth = ({
+ canvasSize,
+ canvasLayout,
+}: {
+ canvasSize: Dimensions;
+ canvasLayout: CanvasLayout;
+}) => {
+ const withoutSafeArea = canvasSize.width - getSafeSpace(canvasLayout) * 2;
+ const fourFifths = canvasSize.width * LANDSCAPE_DISPLAY_MAX_WIDTH_OF_CANVAS;
+ if (canvasLayout === "landscape") {
+ return fourFifths;
+ }
+
+ return withoutSafeArea;
+};
+
+export const getDisplaySize = ({
+ canvasLayout,
+ canvasSize,
+ videoHeight,
+ videoWidth,
+}: {
+ canvasLayout: CanvasLayout;
+ canvasSize: Dimensions;
+ videoWidth: number;
+ videoHeight: number;
+}): Dimensions => {
+ const bottomSafeSpace = getBottomSafeSpace(canvasLayout);
+
+ const maxHeight = getMaxHeight({ canvasSize, canvasLayout, bottomSafeSpace });
+ const maxWidth = getMaxWidth({ canvasSize, canvasLayout });
+
+ const { width, height } = fitElementSizeInContainer({
+ containerSize: { width: maxWidth, height: maxHeight },
+ elementSize: { width: videoWidth, height: videoHeight },
+ });
+
+ return { width, height };
+};
diff --git a/packages/template-recorder/remotion/layout/get-layout.ts b/packages/template-recorder/remotion/layout/get-layout.ts
new file mode 100644
index 0000000000..bde3490c7a
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/get-layout.ts
@@ -0,0 +1,316 @@
+import type { CanvasLayout, Dimensions } from "../../config/layout";
+import { getSafeSpace } from "../../config/layout";
+import type { SceneVideos, WebcamPosition } from "../../config/scenes";
+import { isWebCamAtBottom } from "../animations/webcam-transitions/helpers";
+import { getDimensionsForLayout } from "./dimensions";
+import { getCaptionsLayout } from "./get-captions-layout";
+import {
+ getLandscapeDisplayAndWebcamLayout,
+ getSquareBRollLayout,
+ getSquareDisplayLayout,
+} from "./get-display-layout";
+import { getDisplaySize } from "./get-display-size";
+import { getNonFullscreenWebcamSize } from "./get-webcam-size";
+import type {
+ BRollEnterDirection,
+ BRollType,
+ Layout,
+ RecordingsLayout,
+} from "./layout-types";
+
+export const borderRadius = 20;
+
+const squareFullscreenWebcamLayout = ({
+ canvasSize,
+ webcamSize,
+ webcamPosition,
+}: {
+ canvasSize: Dimensions;
+ webcamSize: Dimensions;
+ webcamPosition: WebcamPosition;
+}): {
+ webcamLayout: Layout;
+ bRollLayout: Layout;
+ bRollEnterDirection: BRollEnterDirection;
+} => {
+ const aspectRatio = webcamSize.width / webcamSize.height;
+
+ const maxWidth = canvasSize.width - getSafeSpace("square") * 2;
+ // Video can take up 75% of the height to leave place for the subtitles
+ const maxHeight = (canvasSize.height - getSafeSpace("square") * 2) * 0.75;
+
+ const provisionalHeight = maxWidth / aspectRatio;
+ const width =
+ provisionalHeight > maxHeight ? maxHeight * aspectRatio : maxWidth;
+ const height = width / aspectRatio;
+
+ const left = (canvasSize.width - width) / 2;
+ const top = isWebCamAtBottom(webcamPosition)
+ ? canvasSize.height - height - getSafeSpace("square")
+ : getSafeSpace("square");
+
+ const webcamLayout: Layout = {
+ left,
+ top,
+ width,
+ height,
+ borderRadius,
+ opacity: 1,
+ };
+
+ const bRollLayout: Layout = {
+ left: getSafeSpace("square"),
+ top,
+ width: canvasSize.width - getSafeSpace("square") * 2,
+ height,
+ borderRadius,
+ opacity: 1,
+ };
+
+ return {
+ webcamLayout,
+ bRollLayout,
+ bRollEnterDirection: isWebCamAtBottom(webcamPosition) ? "bottom" : "top",
+ };
+};
+
+export const fullscreenLayout = (canvasSize: Dimensions): Layout => {
+ return {
+ ...canvasSize,
+ left: 0,
+ top: 0,
+ borderRadius: 0,
+ opacity: 1,
+ };
+};
+
+const getSquareBentoBoxWebcamLayout = ({
+ webcamSize,
+ webcamPosition,
+ canvasSize,
+}: {
+ webcamSize: Dimensions;
+ webcamPosition: WebcamPosition;
+ canvasSize: Dimensions;
+}): Layout => {
+ if (webcamPosition === "bottom-right") {
+ return {
+ ...webcamSize,
+ left: canvasSize.width - webcamSize.width - getSafeSpace("square"),
+ top: canvasSize.height - webcamSize.height - getSafeSpace("square"),
+ borderRadius,
+ opacity: 1,
+ };
+ }
+
+ if (webcamPosition === "bottom-left") {
+ return {
+ ...webcamSize,
+ left: getSafeSpace("square"),
+ top: canvasSize.height - webcamSize.height - getSafeSpace("square"),
+ borderRadius,
+ opacity: 1,
+ };
+ }
+
+ if (webcamPosition === "top-left") {
+ return {
+ ...webcamSize,
+ left: getSafeSpace("square"),
+ top: getSafeSpace("square"),
+ borderRadius,
+ opacity: 1,
+ };
+ }
+
+ if (webcamPosition === "top-right") {
+ return {
+ ...webcamSize,
+ left: canvasSize.width - webcamSize.width - getSafeSpace("square"),
+ top: getSafeSpace("square"),
+ borderRadius,
+ opacity: 1,
+ };
+ }
+
+ return {
+ height: webcamSize.height,
+ width: webcamSize.width,
+ left: 0,
+ top: 0,
+ borderRadius,
+ opacity: 1,
+ };
+};
+
+const getFullScreenWebcamSize = ({
+ webcamVideoResolution,
+ canvasSize,
+ canvasLayout,
+}: {
+ webcamVideoResolution: Dimensions;
+ canvasSize: Dimensions;
+ canvasLayout: CanvasLayout;
+}) => {
+ const aspectRatio =
+ webcamVideoResolution.width / webcamVideoResolution.height;
+
+ const actualWidth = canvasSize.width - getSafeSpace(canvasLayout) * 2;
+
+ const actualHeight = actualWidth / aspectRatio;
+
+ return {
+ height: actualHeight,
+ width: actualWidth,
+ };
+};
+
+export type VideoSceneLayout = {
+ webcamLayout: Layout;
+ displayLayout: Layout | null;
+ bRollLayout: Layout;
+ bRollType: BRollType;
+ subtitleLayout: Layout | null;
+ bRollEnterDirection: BRollEnterDirection;
+};
+
+const getDisplayAndWebcamLayout = ({
+ canvasSize,
+ webcamPosition,
+ canvasLayout,
+ videos,
+}: {
+ canvasSize: Dimensions;
+ webcamPosition: WebcamPosition;
+ canvasLayout: CanvasLayout;
+ videos: SceneVideos;
+}): RecordingsLayout => {
+ if (!videos.display) {
+ if (canvasLayout === "square") {
+ const fullscreenWebcamSize = getFullScreenWebcamSize({
+ canvasSize,
+ canvasLayout,
+ webcamVideoResolution: videos.webcam,
+ });
+
+ const { webcamLayout, bRollLayout, bRollEnterDirection } =
+ squareFullscreenWebcamLayout({
+ canvasSize,
+ webcamPosition,
+ webcamSize: fullscreenWebcamSize,
+ });
+
+ return {
+ displayLayout: null,
+ webcamLayout,
+ bRollLayout,
+ bRollEnterDirection,
+ };
+ }
+
+ if (canvasLayout === "landscape") {
+ const webcamLayout = fullscreenLayout(canvasSize);
+ const bRollLayout = fullscreenLayout(canvasSize);
+
+ return {
+ displayLayout: null,
+ bRollLayout,
+ webcamLayout,
+ bRollEnterDirection: "top",
+ };
+ }
+
+ throw new Error(`Unknown canvas layout: ${canvasLayout satisfies never}`);
+ }
+
+ const displaySize = getDisplaySize({
+ canvasLayout,
+ canvasSize,
+ videoHeight: videos.display.height,
+ videoWidth: videos.display.width,
+ });
+
+ const webcamSize: Dimensions = getNonFullscreenWebcamSize({
+ canvasSize,
+ canvasLayout,
+ displaySize,
+ });
+
+ if (canvasLayout === "square") {
+ const displayLayout = getSquareDisplayLayout({
+ canvasSize,
+ webcamPosition,
+ displaySize,
+ });
+
+ const { bRollLayout, bRollEnterDirection } = getSquareBRollLayout({
+ canvasSize,
+ displaySize,
+ webcamPosition,
+ });
+
+ const webcamLayout = getSquareBentoBoxWebcamLayout({
+ webcamPosition,
+ canvasSize,
+ webcamSize,
+ });
+
+ return {
+ displayLayout,
+ webcamLayout,
+ bRollLayout,
+ bRollEnterDirection,
+ };
+ }
+
+ if (canvasLayout === "landscape") {
+ return getLandscapeDisplayAndWebcamLayout({
+ webcamSize,
+ canvasLayout,
+ canvasSize,
+ webcamPosition,
+ });
+ }
+
+ throw new Error(`Unknown canvas layout: ${canvasLayout satisfies never}`);
+};
+
+export const getVideoSceneLayout = ({
+ canvasLayout,
+ videos,
+ webcamPosition: webcamPosition,
+}: {
+ videos: SceneVideos;
+ canvasLayout: CanvasLayout;
+ webcamPosition: WebcamPosition;
+}): VideoSceneLayout => {
+ const canvasSize = getDimensionsForLayout(canvasLayout);
+
+ const { displayLayout, webcamLayout, bRollLayout, bRollEnterDirection } =
+ getDisplayAndWebcamLayout({
+ canvasSize,
+ webcamPosition,
+ canvasLayout,
+ videos,
+ });
+
+ const subtitleLayout = getCaptionsLayout({
+ canvasLayout,
+ canvasSize,
+ displayLayout,
+ webcamLayout,
+ webcamPosition: webcamPosition,
+ });
+
+ const bRollType =
+ canvasLayout === "landscape" && videos.display === null ? "fade" : "scale";
+
+ return {
+ displayLayout,
+ webcamLayout,
+ bRollLayout,
+ subtitleLayout,
+ bRollEnterDirection,
+ bRollType,
+ };
+};
diff --git a/packages/template-recorder/remotion/layout/get-safe-space.ts b/packages/template-recorder/remotion/layout/get-safe-space.ts
new file mode 100644
index 0000000000..d5d97156eb
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/get-safe-space.ts
@@ -0,0 +1,10 @@
+import type { CanvasLayout } from "../../config/layout";
+import { getSafeSpace } from "../../config/layout";
+
+export const getBottomSafeSpace = (canvasLayout: CanvasLayout) => {
+ if (canvasLayout === "landscape") {
+ return 140;
+ }
+
+ return getSafeSpace(canvasLayout);
+};
diff --git a/packages/template-recorder/remotion/layout/get-webcam-size.ts b/packages/template-recorder/remotion/layout/get-webcam-size.ts
new file mode 100644
index 0000000000..80e49e8f6a
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/get-webcam-size.ts
@@ -0,0 +1,41 @@
+import type { CanvasLayout, Dimensions } from "../../config/layout";
+import { getSafeSpace } from "../../config/layout";
+
+// TODO: Use this also in the recording interface
+const webcamRatio = 400 / 350;
+
+export const getNonFullscreenWebcamSize = ({
+ displaySize,
+ canvasSize,
+ canvasLayout,
+}: {
+ displaySize: Dimensions;
+ canvasSize: Dimensions;
+ canvasLayout: CanvasLayout;
+}): Dimensions => {
+ if (canvasLayout === "square") {
+ const remainingHeight =
+ canvasSize.height - displaySize.height - getSafeSpace(canvasLayout) * 3;
+
+ return {
+ height: remainingHeight,
+ width: remainingHeight * (1 / webcamRatio),
+ };
+ }
+
+ if (canvasLayout === "landscape") {
+ const remainingWidth =
+ canvasSize.width - displaySize.width - getSafeSpace(canvasLayout) * 3;
+ const maxWidth = 350;
+ const width = Math.min(remainingWidth, maxWidth);
+
+ const height = webcamRatio * width;
+
+ return {
+ width,
+ height,
+ };
+ }
+
+ throw new Error(`Invalid canvas layout ${canvasLayout satisfies never}`);
+};
diff --git a/packages/template-recorder/remotion/layout/layout-types.ts b/packages/template-recorder/remotion/layout/layout-types.ts
new file mode 100644
index 0000000000..127bdf3110
--- /dev/null
+++ b/packages/template-recorder/remotion/layout/layout-types.ts
@@ -0,0 +1,26 @@
+export type Rect = {
+ width: number;
+ height: number;
+ top: number;
+ left: number;
+};
+
+export type Layout = Rect & {
+ borderRadius: number;
+ opacity: number;
+};
+
+export type LayoutAndFade = {
+ layout: Layout;
+ shouldFadeRecording: boolean;
+};
+
+export type RecordingsLayout = {
+ displayLayout: Layout | null;
+ webcamLayout: Layout;
+ bRollLayout: Layout;
+ bRollEnterDirection: BRollEnterDirection;
+};
+
+export type BRollEnterDirection = "top" | "bottom";
+export type BRollType = "scale" | "fade";
diff --git a/packages/template-recorder/remotion/scenes/BRoll/BRoll.tsx b/packages/template-recorder/remotion/scenes/BRoll/BRoll.tsx
new file mode 100644
index 0000000000..0ed66731c4
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/BRoll/BRoll.tsx
@@ -0,0 +1,104 @@
+import React from "react";
+import { Sequence, spring, useCurrentFrame, useVideoConfig } from "remotion";
+import type { CanvasLayout } from "../../../config/layout";
+import type { BRollWithDimensions } from "../../../config/scenes";
+import { B_ROLL_TRANSITION_DURATION } from "../../../config/transitions";
+import type { BRollEnterDirection, Layout } from "../../layout/layout-types";
+import { Fade, FadeBRoll } from "./FadeBRoll";
+import { ScaleDownBRoll } from "./ScaleDownBRoll";
+
+const InnerBRoll: React.FC<{
+ bRoll: BRollWithDimensions;
+ bRollsBefore: BRollWithDimensions[];
+ bRollEnterDirection: BRollEnterDirection;
+ bRollLayout: Layout;
+ sceneFrame: number;
+ canvasLayout: CanvasLayout;
+}> = ({
+ bRoll,
+ bRollsBefore,
+ bRollLayout,
+ bRollEnterDirection,
+ sceneFrame,
+ canvasLayout,
+}) => {
+ const { fps } = useVideoConfig();
+ const frame = useCurrentFrame();
+
+ const bRollType = canvasLayout === "landscape" ? "fade" : "scale";
+
+ const appearProgress = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ durationInFrames: B_ROLL_TRANSITION_DURATION,
+ });
+
+ const disappearProgress = spring({
+ fps,
+ frame,
+ delay: bRoll.durationInFrames - B_ROLL_TRANSITION_DURATION,
+ config: {
+ damping: 200,
+ },
+ durationInFrames: B_ROLL_TRANSITION_DURATION,
+ });
+
+ if (bRollType === "fade") {
+ return (
+ <Fade
+ appearProgress={appearProgress}
+ disappearProgress={disappearProgress}
+ >
+ <FadeBRoll layout={bRollLayout} bRoll={bRoll} />
+ </Fade>
+ );
+ }
+
+ return (
+ <ScaleDownBRoll
+ bRoll={bRoll}
+ bRollsBefore={bRollsBefore}
+ bRollLayout={bRollLayout}
+ bRollEnterDirection={bRollEnterDirection}
+ sceneFrame={sceneFrame}
+ appearProgress={appearProgress}
+ disappearProgress={disappearProgress}
+ />
+ );
+};
+
+export const BRoll: React.FC<{
+ bRoll: BRollWithDimensions;
+ bRollsBefore: BRollWithDimensions[];
+ bRollEnterDirection: BRollEnterDirection;
+ sceneFrame: number;
+ bRollLayout: Layout;
+ canvasLayout: CanvasLayout;
+}> = ({
+ bRoll,
+ bRollsBefore,
+ sceneFrame,
+ bRollLayout,
+ bRollEnterDirection,
+ canvasLayout,
+}) => {
+ if (bRoll.durationInFrames <= 0) {
+ return null;
+ }
+
+ return (
+ <Sequence from={bRoll.from} durationInFrames={bRoll.durationInFrames}>
+ <InnerBRoll
+ sceneFrame={sceneFrame}
+ bRollsBefore={bRollsBefore}
+ bRoll={bRoll}
+ bRollLayout={bRollLayout}
+ bRollEnterDirection={bRollEnterDirection}
+ canvasLayout={canvasLayout}
+ />
+ </Sequence>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/BRoll/BRollStack.tsx b/packages/template-recorder/remotion/scenes/BRoll/BRollStack.tsx
new file mode 100644
index 0000000000..97672dca5e
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/BRoll/BRollStack.tsx
@@ -0,0 +1,33 @@
+import React from "react";
+import { useCurrentFrame } from "remotion";
+import type { CanvasLayout } from "../../../config/layout";
+import type { BRollWithDimensions } from "../../../config/scenes";
+import type { BRollEnterDirection, Layout } from "../../layout/layout-types";
+import { BRoll } from "./BRoll";
+
+export const BRollStack: React.FC<{
+ bRollLayout: Layout;
+ bRolls: BRollWithDimensions[];
+ bRollEnterDirection: BRollEnterDirection;
+ canvasLayout: CanvasLayout;
+}> = ({ bRollLayout, bRollEnterDirection, canvasLayout, bRolls }) => {
+ const frame = useCurrentFrame();
+
+ return (
+ <>
+ {bRolls.map((roll, i) => {
+ return (
+ <BRoll
+ key={i}
+ bRoll={roll}
+ bRollsBefore={bRolls.slice(i + 1)}
+ sceneFrame={frame}
+ bRollLayout={bRollLayout}
+ bRollEnterDirection={bRollEnterDirection}
+ canvasLayout={canvasLayout}
+ />
+ );
+ })}
+ </>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/BRoll/FadeBRoll.tsx b/packages/template-recorder/remotion/scenes/BRoll/FadeBRoll.tsx
new file mode 100644
index 0000000000..7666baadd8
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/BRoll/FadeBRoll.tsx
@@ -0,0 +1,56 @@
+import React, { useMemo } from "react";
+import { AbsoluteFill } from "remotion";
+import type { BRollWithDimensions } from "../../../config/scenes";
+import type { Layout } from "../../layout/layout-types";
+import { ImgWithBlur } from "../VideoScene/ImgWithBlur";
+import { VideoWithBlur } from "../VideoScene/VideoWithBlur";
+
+export const Fade: React.FC<{
+ appearProgress: number;
+ disappearProgress: number;
+ children: React.ReactNode;
+}> = ({ appearProgress, disappearProgress, children }) => {
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ opacity: appearProgress - disappearProgress,
+ };
+ }, [appearProgress, disappearProgress]);
+
+ return <AbsoluteFill style={style}>{children}</AbsoluteFill>;
+};
+
+export const FadeBRoll: React.FC<{
+ bRoll: BRollWithDimensions;
+ layout: Layout;
+}> = ({ bRoll, layout }) => {
+ const assetSize = useMemo(() => {
+ return {
+ height: bRoll.assetHeight,
+ width: bRoll.assetWidth,
+ };
+ }, [bRoll.assetHeight, bRoll.assetWidth]);
+
+ if (bRoll.type === "image") {
+ return (
+ <ImgWithBlur
+ src={bRoll.source}
+ containerLayout={layout}
+ imageSize={assetSize}
+ />
+ );
+ }
+
+ if (bRoll.type === "video") {
+ return (
+ <VideoWithBlur
+ src={bRoll.source}
+ muted
+ containerLayout={layout}
+ videoSize={assetSize}
+ enableBlur
+ />
+ );
+ }
+
+ throw new Error(`Invalid b-roll type ${bRoll.type satisfies never}`);
+};
diff --git a/packages/template-recorder/remotion/scenes/BRoll/ScaleDownBRoll.tsx b/packages/template-recorder/remotion/scenes/BRoll/ScaleDownBRoll.tsx
new file mode 100644
index 0000000000..97aaea2eec
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/BRoll/ScaleDownBRoll.tsx
@@ -0,0 +1,110 @@
+import React, { useMemo } from "react";
+import { Img, interpolate, OffthreadVideo, useVideoConfig } from "remotion";
+import type { BRollWithDimensions } from "../../../config/scenes";
+import { fitElementSizeInContainer } from "../../layout/fit-element";
+import type {
+ BRollEnterDirection,
+ Layout,
+ Rect,
+} from "../../layout/layout-types";
+import { ScaleDownIfBRollRequiresIt } from "./ScaleDownWithBRoll";
+
+export const ScaleDownBRoll: React.FC<{
+ bRollEnterDirection: BRollEnterDirection;
+ bRoll: BRollWithDimensions;
+ bRollsBefore: BRollWithDimensions[];
+ bRollLayout: Layout;
+ sceneFrame: number;
+ appearProgress: number;
+ disappearProgress: number;
+}> = ({
+ bRollEnterDirection,
+ bRollLayout,
+ sceneFrame,
+ bRoll,
+ bRollsBefore,
+ appearProgress,
+ disappearProgress,
+}) => {
+ const { height: canvasHeight } = useVideoConfig();
+
+ const bRollContainer: Layout = useMemo(() => {
+ return {
+ ...bRollLayout,
+ display: "flex",
+ };
+ }, [bRollLayout]);
+
+ const enterPosition = useMemo(() => {
+ if (bRollEnterDirection === "top") {
+ return -bRollLayout.height;
+ }
+
+ if (bRollEnterDirection === "bottom") {
+ return canvasHeight;
+ }
+
+ throw new Error(`Invalid direction ${bRollEnterDirection}`);
+ }, [bRollEnterDirection, bRollLayout.height, canvasHeight]);
+
+ const topOffset = interpolate(
+ appearProgress - disappearProgress,
+ [0, 1],
+ [enterPosition, bRollLayout.top],
+ { extrapolateLeft: "clamp", extrapolateRight: "clamp" },
+ );
+
+ const outerStyle: React.CSSProperties = useMemo(() => {
+ return {
+ ...bRollContainer,
+ position: "absolute",
+ top: topOffset,
+ justifyContent: "center",
+ alignItems: "center",
+ };
+ }, [bRollContainer, topOffset]);
+
+ const biggestLayout: Rect = useMemo(() => {
+ return fitElementSizeInContainer({
+ containerSize: bRollLayout,
+ elementSize: {
+ height: bRoll.assetHeight,
+ width: bRoll.assetWidth,
+ },
+ });
+ }, [bRoll.assetHeight, bRoll.assetWidth, bRollLayout]);
+
+ const style = useMemo(() => {
+ return {
+ borderRadius: bRollLayout.borderRadius,
+ overflow: "hidden",
+ boxShadow: "0 0 50px rgba(0, 0, 0, 0.2)",
+ height: biggestLayout.height,
+ width: biggestLayout.width,
+ aspectRatio: bRoll.assetWidth / bRoll.assetHeight,
+ };
+ }, [
+ bRoll.assetHeight,
+ bRoll.assetWidth,
+ bRollLayout.borderRadius,
+ biggestLayout.height,
+ biggestLayout.width,
+ ]);
+
+ return (
+ <div style={outerStyle}>
+ <ScaleDownIfBRollRequiresIt
+ frame={sceneFrame}
+ bRolls={bRollsBefore}
+ bRollType={"scale"}
+ >
+ {bRoll.type === "image" ? (
+ <Img src={bRoll.source} style={style} />
+ ) : null}
+ {bRoll.type === "video" ? (
+ <OffthreadVideo src={bRoll.source} muted style={style} />
+ ) : null}
+ </ScaleDownIfBRollRequiresIt>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/BRoll/ScaleDownWithBRoll.tsx b/packages/template-recorder/remotion/scenes/BRoll/ScaleDownWithBRoll.tsx
new file mode 100644
index 0000000000..bf4c82eebd
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/BRoll/ScaleDownWithBRoll.tsx
@@ -0,0 +1,74 @@
+import React, { useMemo } from "react";
+import { AbsoluteFill, spring, useVideoConfig } from "remotion";
+import type { BRoll } from "../../../config/scenes";
+import { B_ROLL_TRANSITION_DURATION } from "../../../config/transitions";
+import type { BRollType } from "../../layout/layout-types";
+
+// A value of 0.1 means that the original
+// video only has a 90% of its original size
+// when a b-roll is shown
+const SCALE_DOWN = 0.1;
+
+type Props = {
+ bRolls: BRoll[];
+ frame: number;
+ children: React.ReactNode;
+};
+
+const ScaleDownWithBRoll: React.FC<Props> = ({ bRolls, frame, children }) => {
+ const { fps } = useVideoConfig();
+
+ const springs = bRolls.map((roll) => {
+ const enter = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: roll.from,
+ durationInFrames: B_ROLL_TRANSITION_DURATION,
+ });
+ const exit = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: roll.from + roll.durationInFrames - B_ROLL_TRANSITION_DURATION,
+ durationInFrames: B_ROLL_TRANSITION_DURATION,
+ });
+ return enter - exit;
+ }, []);
+
+ const scale = useMemo(() => {
+ return springs.reduce((acc, instance) => {
+ return acc - instance * SCALE_DOWN;
+ }, 1);
+ }, [springs]);
+
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ scale: String(scale),
+ justifyContent: "center",
+ alignItems: "center",
+ };
+ }, [scale]);
+
+ return <AbsoluteFill style={style}>{children}</AbsoluteFill>;
+};
+
+export const ScaleDownIfBRollRequiresIt: React.FC<
+ Props & {
+ bRollType: BRollType;
+ }
+> = ({ bRollType, bRolls, frame, children }) => {
+ if (bRollType !== "scale") {
+ return <>{children}</>;
+ }
+
+ return (
+ <ScaleDownWithBRoll bRolls={bRolls} frame={frame}>
+ {children}
+ </ScaleDownWithBRoll>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/BRoll/apply-b-roll-rules.ts b/packages/template-recorder/remotion/scenes/BRoll/apply-b-roll-rules.ts
new file mode 100644
index 0000000000..5b160c4c44
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/BRoll/apply-b-roll-rules.ts
@@ -0,0 +1,81 @@
+import type { BRollWithDimensions } from "../../../config/scenes";
+import { SCENE_TRANSITION_DURATION } from "../../../config/transitions";
+
+const ensureNoBRollOverlaps = (
+ bRollsEnsureSceneEnds: BRollWithDimensions[],
+): BRollWithDimensions[] => {
+ let neededToCorrect = false;
+
+ const corrected = bRollsEnsureSceneEnds.map((bRoll, i) => {
+ const endPosition = bRoll.from + bRoll.durationInFrames;
+ const laterBRolls = bRollsEnsureSceneEnds.slice(i + 1);
+ const overlappingBRolls = laterBRolls
+ .filter((laterRoll) => {
+ return laterRoll.from < endPosition;
+ })
+ .map((laterBRoll) => {
+ return laterBRoll.from + laterBRoll.durationInFrames;
+ })
+ .filter((laterBRollEndPosition) => {
+ return laterBRollEndPosition > endPosition && bRoll.from;
+ });
+
+ if (overlappingBRolls.length === 0) {
+ return bRoll;
+ }
+
+ neededToCorrect = true;
+
+ const actualEndPosition = Math.max(...overlappingBRolls);
+ return {
+ ...bRoll,
+ durationInFrames: actualEndPosition - bRoll.from,
+ };
+ });
+ if (neededToCorrect) {
+ return ensureNoBRollOverlaps(corrected);
+ }
+
+ return corrected;
+};
+
+export const applyBRollRules = ({
+ bRolls,
+ sceneDurationInFrames,
+ willTransitionToNextScene,
+}: {
+ bRolls: BRollWithDimensions[];
+ sceneDurationInFrames: number;
+ willTransitionToNextScene: boolean;
+}): BRollWithDimensions[] => {
+ // The algorithm assumes the b-rolls are sorted by their start time
+ const sortedBRolls = bRolls.sort((a, b) => a.from - b.from);
+
+ // First rule: A b-roll must finish before the scene ends
+ // and must allow for enough times to transition to the next scene
+ // and hide itself
+
+ // The hide animation is already included in the b-roll duration
+ // we don't need to subtract it.
+
+ const mustEndAt =
+ sceneDurationInFrames -
+ (willTransitionToNextScene ? SCENE_TRANSITION_DURATION : 0);
+
+ const bRollsEnsureSceneEnds = sortedBRolls.map((bRoll) => {
+ if (bRoll.from + bRoll.durationInFrames > mustEndAt) {
+ return {
+ ...bRoll,
+ durationInFrames: mustEndAt - bRoll.from,
+ };
+ }
+
+ return bRoll;
+ });
+
+ // Second rule: If another b-roll overlaps the current one,
+ // the current one must stay at least as long
+ const bRollsEnsureNoOverlap = ensureNoBRollOverlaps(bRollsEnsureSceneEnds);
+
+ return bRollsEnsureNoOverlap;
+};
diff --git a/packages/template-recorder/remotion/scenes/EndCard/FollowButton.tsx b/packages/template-recorder/remotion/scenes/EndCard/FollowButton.tsx
new file mode 100644
index 0000000000..cbe465da5b
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/EndCard/FollowButton.tsx
@@ -0,0 +1,37 @@
+import type { Platform } from "../../../config/endcard";
+import { ENDCARD_FONT } from "../../../config/fonts";
+import type { Theme } from "../../../config/themes";
+import { COLORS } from "../../../config/themes";
+
+export const followButtonHeight = 140;
+
+export const FollowButton: React.FC<{
+ platform: Platform;
+ theme: Theme;
+ isLinkedInBusinessPage: boolean;
+}> = ({ platform, theme, isLinkedInBusinessPage }) => {
+ return (
+ <div
+ style={{
+ height: followButtonHeight,
+ borderRadius: followButtonHeight / 2,
+ width: 400,
+ backgroundColor: COLORS[theme].CTA_BUTTON_BACKGROUND_COLOR,
+ color: COLORS[theme].CTA_BUTTON_COLOR,
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ fontSize: 50,
+ ...ENDCARD_FONT,
+ }}
+ >
+ {platform === "youtube"
+ ? "Subscribe"
+ : platform === "linkedin"
+ ? isLinkedInBusinessPage
+ ? "Follow"
+ : "Connect"
+ : "Follow"}
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/EndCard/IconRow.tsx b/packages/template-recorder/remotion/scenes/EndCard/IconRow.tsx
new file mode 100644
index 0000000000..581f1b8bbd
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/EndCard/IconRow.tsx
@@ -0,0 +1,88 @@
+import { useMemo } from "react";
+import type { Platform } from "../../../config/endcard";
+import { ENDCARD_FONT } from "../../../config/fonts";
+import type { Theme } from "../../../config/themes";
+import { COLORS } from "../../../config/themes";
+import { followButtonHeight } from "./FollowButton";
+import {
+ GitHubIcon,
+ InstagramIcon,
+ LinkIcon,
+ LinkedInIcon,
+ XIcon,
+ YouTubeIcon,
+} from "./icons";
+
+const iconContainer: React.CSSProperties = {
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ height: 60,
+ width: followButtonHeight,
+};
+
+const iconRow: React.CSSProperties = {
+ display: "flex",
+ flexDirection: "row",
+ alignItems: "center",
+ paddingTop: 20,
+ paddingBottom: 20,
+};
+
+export const spaceBetweenImgAndText = 30;
+
+export const IconRow: React.FC<{
+ type: Platform | "link";
+ label: string;
+ opacity: number;
+ theme: Theme;
+}> = ({ type, label, opacity, theme }) => {
+ const labelStyle: React.CSSProperties = useMemo(
+ () => ({
+ fontSize: 50,
+ ...ENDCARD_FONT,
+ marginLeft: 20,
+ color: COLORS[theme].ENDCARD_TEXT_COLOR,
+ }),
+ [theme],
+ );
+
+ const finalLabel = useMemo(() => {
+ if (label.startsWith("https://github.com/")) {
+ return label.substring("https://github.com/".length);
+ }
+
+ return label;
+ }, [label]);
+
+ const finalType = useMemo(() => {
+ if (label.startsWith("https://github.com/")) {
+ return "github";
+ }
+
+ return type;
+ }, [label, type]);
+
+ return (
+ <div style={{ ...iconRow, opacity }}>
+ <div style={iconContainer}>
+ {finalType === "github" ? (
+ <GitHubIcon theme={theme} height={60} />
+ ) : null}
+ {finalType === "link" ? <LinkIcon theme={theme} height={60} /> : null}
+ {finalType === "youtube" ? (
+ <YouTubeIcon theme={theme} height={60} />
+ ) : null}
+ {finalType === "x" ? <XIcon theme={theme} height={60} /> : null}
+ {finalType === "instagram" ? (
+ <InstagramIcon theme={theme} height={70} />
+ ) : null}
+ {finalType === "linkedin" ? (
+ <LinkedInIcon theme={theme} height={60} />
+ ) : null}
+ </div>
+ <div style={{ width: spaceBetweenImgAndText }} />
+ <div style={labelStyle}>{finalLabel}</div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/EndCard/LeftSide.tsx b/packages/template-recorder/remotion/scenes/EndCard/LeftSide.tsx
new file mode 100644
index 0000000000..2061827c9b
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/EndCard/LeftSide.tsx
@@ -0,0 +1,218 @@
+import React, { useEffect, useMemo, useRef, useState } from "react";
+import {
+ AbsoluteFill,
+ Img,
+ continueRender,
+ delayRender,
+ interpolate,
+ spring,
+ useCurrentFrame,
+ useCurrentScale,
+ useVideoConfig,
+} from "remotion";
+import type { Brand, LinkType, Platform } from "../../../config/endcard";
+import { avatars, channels } from "../../../config/endcard";
+import type { Theme } from "../../../config/themes";
+import { SCENE_TRANSITION_DURATION } from "../../../config/transitions";
+import { FollowButton, followButtonHeight } from "./FollowButton";
+import { IconRow, spaceBetweenImgAndText } from "./IconRow";
+import { Links } from "./Links";
+
+const Avatar: React.FC<{
+ avatar: string;
+ theme: Theme;
+}> = ({ avatar, theme }) => {
+ return (
+ <Img
+ style={{
+ height: followButtonHeight,
+ width: followButtonHeight,
+ borderRadius: "50%",
+ boxShadow:
+ theme === "light"
+ ? "0px 0px 20px rgba(0, 0, 0, 0.2)"
+ : "0px 0px 50px rgba(255, 255, 255, 0.2)",
+ }}
+ src={avatar}
+ />
+ );
+};
+
+const style: React.CSSProperties = {
+ display: "flex",
+ alignItems: "center",
+};
+
+const FollowCTA: React.FC<{
+ platform: Platform;
+ avatar: string;
+ theme: Theme;
+ isLinkedInBusinessPage: boolean;
+}> = ({ platform, avatar, theme, isLinkedInBusinessPage }) => {
+ return (
+ <div style={style}>
+ <Avatar theme={theme} avatar={avatar} />
+ <div style={{ width: spaceBetweenImgAndText }} />
+ <FollowButton
+ theme={theme}
+ platform={platform}
+ isLinkedInBusinessPage={isLinkedInBusinessPage}
+ />
+ </div>
+ );
+};
+
+export const LeftSide: React.FC<{
+ platform: Platform;
+ channel: Brand;
+ links: LinkType[];
+ theme: Theme;
+}> = ({ platform, channel, links, theme }) => {
+ const ref = useRef<HTMLDivElement>(null);
+ const scaler = useRef<HTMLDivElement>(null);
+ const [handle] = useState(() => delayRender());
+ const [contentHeight, setHeight] = useState(0);
+
+ const { fps, width } = useVideoConfig();
+ const frame = useCurrentFrame();
+
+ const slideDelay = SCENE_TRANSITION_DURATION + 20;
+ const slideDuration = 30;
+
+ const scale = useCurrentScale();
+
+ const slideUp = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: slideDelay,
+ durationInFrames: slideDuration,
+ });
+
+ useEffect(() => {
+ const calc = () => {
+ const cb = window.requestAnimationFrame(() => {
+ const height = ref.current?.getBoundingClientRect().height as number;
+ if (height === 0) {
+ calc();
+ return;
+ }
+
+ const scaled = height / scale;
+
+ setHeight(scaled);
+ continueRender(handle);
+ });
+
+ return () => {
+ window.cancelAnimationFrame(cb);
+ };
+ };
+
+ const cleanup = calc();
+
+ return () => {
+ cleanup();
+ };
+ }, [handle, scale]);
+
+ const otherPlatforms = useMemo(() => {
+ const configs: {
+ name: string;
+ platform: Platform;
+ }[] = [];
+
+ for (const c in channels[channel]) {
+ const name = channels[channel][c as Platform];
+ if (!name) {
+ continue;
+ }
+
+ if (c === platform) {
+ continue;
+ }
+ if (c === "isLinkedInBusinessPage") {
+ continue;
+ }
+
+ configs.push({
+ name,
+ platform: c as Platform,
+ });
+ }
+
+ return configs;
+ }, [channel, platform]);
+
+ const totalLinks = links.length + otherPlatforms.length;
+
+ const padding = 80;
+ const maxWidth = width - padding * 2;
+
+ return (
+ <AbsoluteFill
+ style={{
+ left: 80,
+ justifyContent: "center",
+ maxWidth: Math.min(maxWidth, 1000),
+ }}
+ >
+ <div
+ ref={scaler}
+ style={{ height: 100, position: "absolute", top: -100000 }}
+ />
+ <div
+ style={{
+ transform: `translateY(${interpolate(
+ slideUp,
+ [0, 1],
+ [contentHeight / 2, 0],
+ )}px)`,
+ }}
+ >
+ <FollowCTA
+ theme={theme}
+ avatar={avatars[channel]}
+ platform={platform}
+ isLinkedInBusinessPage={channels[channel].isLinkedInBusinessPage}
+ />
+ </div>
+ <div ref={ref}>
+ <div style={{ height: 80 }} />
+ {otherPlatforms.map((p, i) => {
+ const indexFromLast = links.length + otherPlatforms.length - i;
+ const opacity = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay:
+ slideDelay +
+ ((indexFromLast - 1) / totalLinks) * (slideDuration - 15),
+ durationInFrames: 15,
+ });
+
+ return (
+ <IconRow
+ key={p.platform}
+ opacity={opacity}
+ type={p.platform}
+ label={p.name}
+ theme={theme}
+ />
+ );
+ })}
+ <Links
+ links={links}
+ slideDelay={slideDelay}
+ slideDuration={slideDuration}
+ theme={theme}
+ totalLinks={totalLinks}
+ />
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/EndCard/Links.tsx b/packages/template-recorder/remotion/scenes/EndCard/Links.tsx
new file mode 100644
index 0000000000..1480a7d412
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/EndCard/Links.tsx
@@ -0,0 +1,46 @@
+import React from "react";
+import { spring, useCurrentFrame, useVideoConfig } from "remotion";
+import type { LinkType } from "../../../config/endcard";
+import type { Theme } from "../../../config/themes";
+import { IconRow } from "./IconRow";
+
+export const Links: React.FC<{
+ links: LinkType[];
+ slideDelay: number;
+ totalLinks: number;
+ slideDuration: number;
+ theme: Theme;
+}> = ({ links, slideDelay, totalLinks, slideDuration, theme }) => {
+ const { fps } = useVideoConfig();
+ const frame = useCurrentFrame();
+
+ return (
+ <>
+ {links.length > 0 ? <div style={{ height: 80 }} /> : null}
+ {links.map((l, i) => {
+ const indexFromLast = links.length - i;
+ const opacity = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay:
+ slideDelay +
+ ((indexFromLast - 1) / totalLinks) * (slideDuration - 15),
+ durationInFrames: 15,
+ });
+
+ return (
+ <IconRow
+ key={l.link}
+ opacity={opacity}
+ type="link"
+ label={l.link}
+ theme={theme}
+ />
+ );
+ })}
+ </>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/EndCard/RightSide.tsx b/packages/template-recorder/remotion/scenes/EndCard/RightSide.tsx
new file mode 100644
index 0000000000..867251ec6f
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/EndCard/RightSide.tsx
@@ -0,0 +1,55 @@
+import React from "react";
+import { AbsoluteFill } from "remotion";
+import type { Theme } from "../../../config/themes";
+import { COLORS } from "../../../config/themes";
+
+const border = 6;
+
+// Assuming 1080p, values upscaled from 720p
+const YOUTUBE_END_SCREEN_SAFE_AREA_HEIGHT = 790;
+const YOUTUBE_END_SCREEN_SAFE_AREA_TOP = 135;
+
+const ThumbnailPreview: React.FC<{
+ theme: Theme;
+}> = ({ theme }) => {
+ return (
+ <div
+ style={{
+ width: 613 + border * 3,
+ height: 343 + border * 3,
+ border: `${border}px solid ${COLORS[theme].ENDCARD_TEXT_COLOR}`,
+ }}
+ />
+ );
+};
+
+export const ThumbnailContainers: React.FC<{
+ theme: Theme;
+}> = ({ theme }) => {
+ // These thumbnails are optimized for YouTube and fit perfectly if:
+ // - All thumbnails are made the minimum size
+ // - The upper thumbnail is positioned at the highest point allowed
+ // - The lower thumbnail is positioned a the lowest point allowed
+ // Use the endscreen editor in YouTube Studio to get a better feeling for this.
+ return (
+ <AbsoluteFill
+ style={{
+ alignItems: "flex-end",
+ paddingRight: 100,
+ top: YOUTUBE_END_SCREEN_SAFE_AREA_TOP,
+ }}
+ >
+ <div
+ style={{
+ height: YOUTUBE_END_SCREEN_SAFE_AREA_HEIGHT,
+ display: "flex",
+ flexDirection: "column",
+ }}
+ >
+ <ThumbnailPreview theme={theme} />
+ <div style={{ flex: 1 }} />
+ <ThumbnailPreview theme={theme} />
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/EndCard/icons.tsx b/packages/template-recorder/remotion/scenes/EndCard/icons.tsx
new file mode 100644
index 0000000000..96451d700a
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/EndCard/icons.tsx
@@ -0,0 +1,91 @@
+import React from "react";
+import type { Theme } from "../../../config/themes";
+import { COLORS } from "../../../config/themes";
+
+export const LinkedInIcon: React.FC<{
+ height: number;
+ theme: Theme;
+}> = ({ height, theme }) => {
+ return (
+ <svg height={height} viewBox="0 0 448 512">
+ <path
+ fill={COLORS[theme].ENDCARD_TEXT_COLOR}
+ d="M100.28 448H7.4V148.9h92.88zM53.79 108.1C24.09 108.1 0 83.5 0 53.8a53.79 53.79 0 0 1 107.58 0c0 29.7-24.1 54.3-53.79 54.3zM447.9 448h-92.68V302.4c0-34.7-.7-79.2-48.29-79.2-48.29 0-55.69 37.7-55.69 76.7V448h-92.78V148.9h89.08v40.8h1.3c12.4-23.5 42.69-48.3 87.88-48.3 94 0 111.28 61.9 111.28 142.3V448z"
+ />
+ </svg>
+ );
+};
+
+export const YouTubeIcon: React.FC<{
+ height: number;
+ theme: Theme;
+}> = ({ height, theme }) => {
+ return (
+ <svg height={height} viewBox="0 0 576 512">
+ <path
+ fill={COLORS[theme].ENDCARD_TEXT_COLOR}
+ d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"
+ />
+ </svg>
+ );
+};
+
+export const GitHubIcon: React.FC<{
+ height: number;
+ theme: Theme;
+}> = ({ height, theme }) => {
+ return (
+ <svg
+ height={height}
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 496 512"
+ >
+ <path
+ fill={COLORS[theme].ENDCARD_TEXT_COLOR}
+ d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3 .3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5 .3-6.2 2.3zm44.2-1.7c-2.9 .7-4.9 2.6-4.6 4.9 .3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3 .7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3 .3 2.9 2.3 3.9 1.6 1 3.6 .7 4.3-.7 .7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3 .7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3 .7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"
+ />
+ </svg>
+ );
+};
+
+export const LinkIcon: React.FC<{
+ height: number;
+ theme: Theme;
+}> = ({ height, theme }) => {
+ return (
+ <svg height={height} viewBox="0 0 640 512">
+ <path
+ fill={COLORS[theme].ENDCARD_TEXT_COLOR}
+ d="M580.2 267.3c56.2-56.2 56.2-147.4 0-203.6S432.8 7.4 376.6 63.7L365.3 75l45.3 45.3 11.3-11.3c31.2-31.2 81.9-31.2 113.1 0s31.2 81.9 0 113.1L421.8 335.2c-31.2 31.2-81.9 31.2-113.1 0c-25.6-25.6-30.3-64.3-13.8-94.6c1.8-3.4 3.9-6.7 6.3-9.8l-51.2-38.4c-4.3 5.7-8.1 11.6-11.4 17.8c-29.5 54.6-21.3 124.2 24.9 170.3c56.2 56.2 147.4 56.2 203.6 0L580.2 267.3zM59.8 244.7c-56.2 56.2-56.2 147.4 0 203.6s147.4 56.2 203.6 0L274.7 437l-45.3-45.3-11.3 11.3c-31.2 31.2-81.9 31.2-113.1 0s-31.2-81.9 0-113.1L218.2 176.8c31.2-31.2 81.9-31.2 113.1 0c25.6 25.6 30.3 64.3 13.8 94.6c-1.8 3.4-3.9 6.7-6.3 9.8l51.2 38.4c4.3-5.7 8.1-11.6 11.4-17.8c29.5-54.6 21.3-124.2-24.9-170.3c-56.2-56.2-147.4-56.2-203.6 0L59.8 244.7z"
+ />
+ </svg>
+ );
+};
+
+export const XIcon: React.FC<{
+ height: number;
+ theme: Theme;
+}> = ({ height, theme }) => {
+ return (
+ <svg height={height} viewBox="0 0 512 512">
+ <path
+ fill={COLORS[theme].ENDCARD_TEXT_COLOR}
+ d="M389.2 48h70.6L305.6 224.2 487 464H345L233.7 318.6 106.5 464H35.8L200.7 275.5 26.8 48H172.4L272.9 180.9 389.2 48zM364.4 421.8h39.1L151.1 88h-42L364.4 421.8z"
+ />
+ </svg>
+ );
+};
+
+export const InstagramIcon: React.FC<{
+ height: number;
+ theme: Theme;
+}> = ({ height, theme }) => {
+ return (
+ <svg height={height} viewBox="0 0 448 512">
+ <path
+ fill={COLORS[theme].ENDCARD_TEXT_COLOR}
+ d="M224.1 141c-63.6 0-114.9 51.3-114.9 114.9s51.3 114.9 114.9 114.9S339 319.5 339 255.9 287.7 141 224.1 141zm0 189.6c-41.1 0-74.7-33.5-74.7-74.7s33.5-74.7 74.7-74.7 74.7 33.5 74.7 74.7-33.6 74.7-74.7 74.7zm146.4-194.3c0 14.9-12 26.8-26.8 26.8-14.9 0-26.8-12-26.8-26.8s12-26.8 26.8-26.8 26.8 12 26.8 26.8zm76.1 27.2c-1.7-35.9-9.9-67.7-36.2-93.9-26.2-26.2-58-34.4-93.9-36.2-37-2.1-147.9-2.1-184.9 0-35.8 1.7-67.6 9.9-93.9 36.1s-34.4 58-36.2 93.9c-2.1 37-2.1 147.9 0 184.9 1.7 35.9 9.9 67.7 36.2 93.9s58 34.4 93.9 36.2c37 2.1 147.9 2.1 184.9 0 35.9-1.7 67.7-9.9 93.9-36.2 26.2-26.2 34.4-58 36.2-93.9 2.1-37 2.1-147.8 0-184.8zM398.8 388c-7.8 19.6-22.9 34.7-42.6 42.6-29.5 11.7-99.5 9-132.1 9s-102.7 2.6-132.1-9c-19.6-7.8-34.7-22.9-42.6-42.6-11.7-29.5-9-99.5-9-132.1s-2.6-102.7 9-132.1c7.8-19.6 22.9-34.7 42.6-42.6 29.5-11.7 99.5-9 132.1-9s102.7-2.6 132.1 9c19.6 7.8 34.7 22.9 42.6 42.6 11.7 29.5 9 99.5 9 132.1s2.7 102.7-9 132.1z"
+ />
+ </svg>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/EndCard/index.tsx b/packages/template-recorder/remotion/scenes/EndCard/index.tsx
new file mode 100644
index 0000000000..b3cd026a9d
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/EndCard/index.tsx
@@ -0,0 +1,34 @@
+import React from "react";
+import { AbsoluteFill } from "remotion";
+import type { Brand, LinkType, Platform } from "../../../config/endcard";
+import type { CanvasLayout } from "../../../config/layout";
+import type { Theme } from "../../../config/themes";
+import { COLORS } from "../../../config/themes";
+import { LeftSide } from "./LeftSide";
+import { ThumbnailContainers } from "./RightSide";
+
+export const EndCard: React.FC<{
+ channel: Brand;
+ canvasLayout: CanvasLayout;
+ platform: Platform;
+ links: LinkType[];
+ theme: Theme;
+}> = ({ canvasLayout, platform, channel, links, theme }) => {
+ return (
+ <AbsoluteFill
+ style={{
+ backgroundColor: COLORS[theme].BACKGROUND,
+ }}
+ >
+ <LeftSide
+ theme={theme}
+ links={links}
+ channel={channel}
+ platform={platform}
+ />
+ {canvasLayout === "landscape" ? (
+ <ThumbnailContainers theme={theme} />
+ ) : null}
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/Placeholders/NoRecordingsScene.tsx b/packages/template-recorder/remotion/scenes/Placeholders/NoRecordingsScene.tsx
new file mode 100644
index 0000000000..ff74323805
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/Placeholders/NoRecordingsScene.tsx
@@ -0,0 +1,67 @@
+import { AbsoluteFill, useVideoConfig } from "remotion";
+import { MONOSPACE_FONT, REGULAR_FONT } from "../../../config/fonts";
+import { SERVER_PORT } from "../../../config/server";
+import { COLORS } from "../../../config/themes";
+
+const container: React.CSSProperties = {
+ ...REGULAR_FONT,
+ fontSize: 36,
+ padding: 60,
+ flexDirection: "column",
+ lineHeight: 1.5,
+ width: 1080,
+ margin: "auto",
+ justifyContent: "center",
+};
+
+const accent: React.CSSProperties = {
+ ...MONOSPACE_FONT,
+ color: COLORS.light.ACCENT_COLOR,
+};
+
+const link: React.CSSProperties = {
+ color: COLORS.light.ACCENT_COLOR,
+ borderBottom: "4px solid " + COLORS.light.ACCENT_COLOR,
+ textDecoration: "none",
+};
+
+export const NoRecordingsScene: React.FC<{ type: "none" | "no-more" }> = ({
+ type,
+}) => {
+ const { id } = useVideoConfig();
+ const url = `http://localhost:${SERVER_PORT}?folder=${id}`;
+
+ return (
+ <AbsoluteFill style={container}>
+ <p>
+ This is a video scene but there are no{" "}
+ {type === "no-more" ? "more" : null} recordings in the
+ <span style={accent}> public/{id} </span>
+ folder.
+ </p>
+ <br />
+ <div>Possible solutions:</div>
+ <ol>
+ <li>
+ <a href={url} target="_blank" style={link}>
+ Make
+ </a>{" "}
+ a new recording or add a new video{" "}
+ <a
+ target="_blank"
+ href="https://www.remotion.dev/docs/recorder/external-recordings"
+ style={link}
+ >
+ manually
+ </a>
+ .
+ </li>
+ <li>
+ Switch this scene to a different type, e.g.{" "}
+ <code style={accent}>&quot;title&quot;</code>
+ </li>
+ <li>Delete this scene.</li>
+ </ol>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/Placeholders/NoScenes.tsx b/packages/template-recorder/remotion/scenes/Placeholders/NoScenes.tsx
new file mode 100644
index 0000000000..7a5b295683
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/Placeholders/NoScenes.tsx
@@ -0,0 +1,24 @@
+import { AbsoluteFill } from "remotion";
+import { REGULAR_FONT } from "../../../config/fonts";
+
+const container: React.CSSProperties = {
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ flex: 1,
+ ...REGULAR_FONT,
+ fontSize: 36,
+ gap: 10,
+ flexDirection: "column",
+};
+
+export const NoScenes: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <div style={container}>
+ <div>No scenes defined for this video.</div>
+ <div>Add a scene in the right sidebar -&gt;</div>
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/Recorder/index.tsx b/packages/template-recorder/remotion/scenes/Recorder/index.tsx
new file mode 100644
index 0000000000..e1397df422
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/Recorder/index.tsx
@@ -0,0 +1,583 @@
+import React from "react";
+import {
+ Easing,
+ interpolate,
+ Sequence,
+ spring,
+ useCurrentFrame,
+ useVideoConfig,
+} from "remotion";
+import type { Theme } from "../../../config/themes";
+
+import { Rect, Triangle } from "@remotion/shapes";
+import { AbsoluteFill, interpolateColors } from "remotion";
+import { REGULAR_FONT } from "../../../config/fonts";
+
+const getBackground = (theme: Theme) => {
+ return theme === "dark" ? "#2E2E2E" : "rgba(255, 255, 255, 1)";
+};
+
+const getOpacity = (theme: Theme) => {
+ return theme === "dark" ? 0.13 : 0.08;
+};
+
+const getBrand = (theme: Theme) => {
+ return theme === "dark" ? "white" : "#0C85F3";
+};
+
+const TriangleToSquare: React.FC<{
+ progress: number;
+ length: number;
+ style: React.CSSProperties;
+ opacity: number;
+ theme: Theme;
+}> = ({ progress, length, style, opacity, theme }) => {
+ const triangleEdgeRoundness = interpolate(
+ progress,
+ [0, 0.5],
+ [0.707, Math.sqrt(2) - 1],
+ );
+ const rectEdgeRoundness = interpolate(
+ progress,
+ [0.5, 1],
+ [(4 * (Math.sqrt(2) - 1)) / 3, 0.69],
+ );
+
+ const color = interpolateColors(
+ progress,
+ [0, 1],
+ [
+ interpolateColors(
+ opacity,
+ [0, 1],
+ [getBackground(theme), getBrand(theme)],
+ ),
+ interpolateColors(opacity, [0, 1], [getBackground(theme), "#F43B00"]),
+ ],
+ );
+
+ const correctCenter = interpolate(progress, [0.5, 1], [-80, 0]);
+
+ if (progress > 0.5) {
+ return (
+ <Rect
+ height={length * 0.58}
+ width={length * 0.58}
+ edgeRoundness={rectEdgeRoundness}
+ style={{ ...style, marginLeft: correctCenter }}
+ fill={color}
+ />
+ );
+ }
+
+ return (
+ <Triangle
+ direction="right"
+ fill={color}
+ length={length}
+ style={style}
+ edgeRoundness={triangleEdgeRoundness}
+ />
+ );
+};
+
+const O: React.FC = () => {
+ return (
+ <svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none">
+ <path
+ d="M660.364 539.204C660.364 560.42 643.645 577.067 623.694 577.067C603.742 577.067 587.024 560.42 587.024 539.204C587.024 517.989 603.742 501.342 623.694 501.342C643.645 501.342 660.364 517.989 660.364 539.204Z"
+ stroke="currentColor"
+ strokeWidth="27.4281"
+ />
+ </svg>
+ );
+};
+
+const R1: React.FC = () => {
+ return (
+ <svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none">
+ <path
+ d="M299 577.067V535.329C299 516.558 314.216 501.342 332.987 501.342V501.342"
+ stroke="currentColor"
+ strokeWidth="27.4281"
+ strokeLinecap="square"
+ />
+ </svg>
+ );
+};
+
+const R2: React.FC = () => {
+ return (
+ <svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none">
+ <path
+ d="M696.31 577.067V535.329C696.31 516.558 711.526 501.342 730.297 501.342V501.342"
+ stroke="currentColor"
+ strokeWidth="27.4281"
+ strokeLinecap="square"
+ />
+ </svg>
+ );
+};
+
+const R3: React.FC = () => {
+ return (
+ <svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none">
+ <path
+ d="M989.31 577.067V535.329C989.31 516.558 1004.53 501.342 1023.3 501.342V501.342"
+ stroke="currentColor"
+ strokeWidth="27.4281"
+ strokeLinecap="square"
+ />{" "}
+ </svg>
+ );
+};
+
+const D: React.FC = () => {
+ return (
+ <svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none">
+ <circle
+ cx="800.886"
+ cy="539.204"
+ r="37.8627"
+ stroke="currentColor"
+ strokeWidth="27.4281"
+ />
+ <path
+ d="M838.81 529.725V454"
+ stroke="currentColor"
+ strokeWidth="27"
+ strokeLinecap="square"
+ />
+ </svg>
+ );
+};
+
+const E: React.FC = () => {
+ return (
+ <svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none">
+ <mask
+ id="mask0_20_679"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x="351"
+ y="487"
+ width="104"
+ height="104"
+ >
+ <circle
+ cx="402.924"
+ cy="538.906"
+ r="39.3533"
+ fill="currentColor"
+ stroke="currentColor"
+ strokeWidth="23.8505"
+ />
+ </mask>
+ <g mask="url(#mask0_20_679)">
+ <path
+ d="M361.781 528.174H448.836C456.41 528.174 462.55 534.314 462.55 541.888V547.85H361.781V528.174Z"
+ fill="currentColor"
+ />
+ </g>
+ <mask
+ id="mask1_20_679"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x="336"
+ y="475"
+ width="126"
+ height="137"
+ >
+ <path
+ d="M417.234 539.503H456.289L461.357 478.982L441.979 475.702L342.403 478.982L336.738 611.65H426.774L457.78 557.689H417.234V539.503Z"
+ fill="currentColor"
+ />
+ </mask>
+ <g mask="url(#mask1_20_679)">
+ <path
+ d="M440.488 539.204C440.488 560.19 423.595 577.067 402.924 577.067C382.252 577.067 365.359 560.19 365.359 539.204C365.359 518.218 382.252 501.342 402.924 501.342C423.595 501.342 440.488 518.218 440.488 539.204Z"
+ stroke="currentColor"
+ strokeWidth="27.4281"
+ />
+ </g>
+ </svg>
+ );
+};
+
+const C: React.FC = () => {
+ return (
+ <svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none">
+ <g mask="url(#mask4_20_679)" />
+ <mask
+ id="mask5_20_679"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x="448"
+ y="475"
+ width="125"
+ height="137"
+ >
+ <path
+ d="M528.805 528H567.86L572.928 478.982L553.55 475.702L453.974 478.982L448.31 611.65H538.345L569.351 548H528.805V528Z"
+ fill="currentColor"
+ />
+ </mask>
+ <g mask="url(#mask5_20_679)">
+ <path
+ d="M552.059 539.204C552.059 560.19 535.166 577.067 514.495 577.067C493.823 577.067 476.93 560.19 476.93 539.204C476.93 518.218 493.823 501.342 514.495 501.342C535.166 501.342 552.059 518.218 552.059 539.204Z"
+ stroke="currentColor"
+ strokeWidth="27.4281"
+ />
+ </g>
+ </svg>
+ );
+};
+
+const E2: React.FC = () => {
+ return (
+ <svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none">
+ <mask
+ id="mask2_20_679"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x="861"
+ y="487"
+ width="103"
+ height="104"
+ >
+ <circle
+ cx="912.495"
+ cy="538.906"
+ r="39.3533"
+ fill="currentColor"
+ stroke="currentColor"
+ strokeWidth="23.8505"
+ />
+ </mask>
+ <g mask="url(#mask2_20_679)">
+ <path
+ d="M871.353 528.174H958.407C965.981 528.174 972.121 534.314 972.121 541.888V547.85H871.353V528.174Z"
+ fill="currentColor"
+ />
+ </g>
+ <mask
+ id="mask3_20_679"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x="846"
+ y="475"
+ width="125"
+ height="137"
+ >
+ <path
+ d="M926.805 539.503H965.86L970.928 478.982L951.55 475.702L851.974 478.982L846.31 611.65H936.345L967.351 557.689H926.805V539.503Z"
+ fill="currentColor"
+ />
+ </mask>
+ <g mask="url(#mask3_20_679)">
+ <path
+ d="M950.059 539.204C950.059 560.19 933.166 577.067 912.495 577.067C891.823 577.067 874.93 560.19 874.93 539.204C874.93 518.218 891.823 501.342 912.495 501.342C933.166 501.342 950.059 518.218 950.059 539.204Z"
+ stroke="currentColor"
+ strokeWidth="27.4281"
+ />
+ </g>
+ <mask
+ id="mask4_20_679"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x="463"
+ y="487"
+ width="103"
+ height="104"
+ >
+ <circle
+ cx="514.495"
+ cy="538.906"
+ r="39.3533"
+ fill="currentColor"
+ stroke="currentColor"
+ strokeWidth="23.8505"
+ />
+ </mask>
+ </svg>
+ );
+};
+
+const FromRight: React.FC<{
+ children: React.ReactNode;
+ delay: number;
+}> = ({ children, delay }) => {
+ const { fps } = useVideoConfig();
+ const frame = useCurrentFrame();
+
+ const spr = spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: Number(delay) + 28.2,
+ });
+
+ const rotation = interpolate(spr, [0, 1], [-Math.PI / 2, 0]);
+
+ return (
+ <AbsoluteFill
+ style={{
+ transform: `rotate(${rotation}rad)`,
+ transformOrigin: "150% 50%",
+ }}
+ >
+ {children}
+ </AbsoluteFill>
+ );
+};
+
+const getColor = (theme: Theme) => {
+ return theme === "dark" ? "white" : "black";
+};
+
+const Recorder: React.FC<{
+ theme: Theme;
+}> = ({ theme }) => {
+ return (
+ <AbsoluteFill
+ style={{
+ WebkitMaskImage: `linear-gradient(black 58%, transparent 74%)`,
+ }}
+ >
+ <AbsoluteFill style={{ overflow: "visible", color: getColor(theme) }}>
+ <FromRight delay={0}>
+ <R1 />
+ </FromRight>
+ <FromRight delay={1}>
+ <E />
+ </FromRight>
+ <FromRight delay={2}>
+ <C />
+ </FromRight>
+ <FromRight delay={3}>
+ <O />
+ </FromRight>
+ <FromRight delay={4}>
+ <R2 />
+ </FromRight>
+ <FromRight delay={5}>
+ <D />
+ </FromRight>
+ <FromRight delay={6}>
+ <E2 />
+ </FromRight>
+ <FromRight delay={7}>
+ <R3 />
+ </FromRight>
+ <AbsoluteFill
+ style={{
+ width: "160%",
+ height: "100.2%",
+ }}
+ />
+ </AbsoluteFill>
+ </AbsoluteFill>
+ );
+};
+
+const Logo: React.FC<{
+ theme: Theme;
+}> = ({ theme }) => {
+ const { fps } = useVideoConfig();
+ const frame = useCurrentFrame();
+
+ const toCircleProgress = spring({
+ fps,
+ frame,
+ config: { damping: 20 },
+ durationInFrames: 40,
+ delay: 25,
+ });
+
+ const breathe = (delay: number) => {
+ return spring({
+ fps,
+ frame,
+ reverse: true,
+ delay,
+ });
+ };
+
+ const anim = (delay: number) => {
+ return (
+ breathe(delay) -
+ 1 +
+ spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ delay: 36 + delay,
+ }) +
+ Math.sin(Math.max(frame - 36 - delay, 0) / 10) * 0.1
+ );
+ };
+
+ const progress = spring({
+ fps,
+ frame,
+ config: {
+ mass: 0.7,
+ damping: 200,
+ },
+ durationInFrames: 50,
+ delay: 24,
+ });
+
+ const progressWithEaseOut = interpolate(progress, [0, 1], [0, 1], {
+ easing: Easing.inOut(Easing.ease),
+ });
+
+ const rotation = interpolate(
+ progressWithEaseOut,
+ [0, 1],
+ [0, -Math.PI * 2.5],
+ {
+ easing: Easing.out(Easing.ease),
+ },
+ );
+
+ const translation = interpolate(progressWithEaseOut, [0, 1], [0, 540], {
+ easing: Easing.out(Easing.ease),
+ });
+
+ const posX = Math.sin(rotation) * translation;
+ const posY = Math.cos(rotation) * translation * 0.7;
+
+ return (
+ <Sequence
+ style={{
+ transformOrigin: "center center",
+ transform: `scale(0.68) translateX(${posX}px) translateY(${posY}px)`,
+ }}
+ >
+ <Sequence style={{}}>
+ <Sequence
+ style={{
+ justifyContent: "center",
+ alignItems: "center",
+ scale: String(1.2 + anim(2)),
+ }}
+ >
+ <TriangleToSquare
+ opacity={getOpacity(theme)}
+ progress={toCircleProgress}
+ style={{
+ marginLeft: 90,
+ }}
+ length={360}
+ theme={theme}
+ />
+ </Sequence>
+ <Sequence
+ style={{
+ justifyContent: "center",
+ alignItems: "center",
+ scale: String(1.2 + anim(1)),
+ }}
+ >
+ <TriangleToSquare
+ opacity={0.3}
+ progress={toCircleProgress}
+ style={{
+ marginLeft: 70,
+ }}
+ length={270}
+ theme={theme}
+ />
+ </Sequence>
+ <Sequence
+ style={{
+ justifyContent: "center",
+ alignItems: "center",
+ scale: String(1.2 + Math.max(anim(0), 0)),
+ }}
+ >
+ <TriangleToSquare
+ opacity={1}
+ progress={toCircleProgress}
+ style={{
+ marginLeft: 50,
+ }}
+ length={180}
+ theme={theme}
+ />
+ </Sequence>
+ </Sequence>
+ </Sequence>
+ );
+};
+
+const All: React.FC<{
+ theme: Theme;
+}> = ({ theme }) => {
+ return (
+ <Sequence>
+ <Recorder theme={theme} />
+ <Logo theme={theme} />
+ </Sequence>
+ );
+};
+
+const Attribution: React.FC<{
+ theme: Theme;
+}> = ({ theme }) => {
+ const frame = useCurrentFrame();
+ const opacity = interpolate(frame, [40, 50], [0, 1], {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp",
+ });
+
+ return (
+ <AbsoluteFill
+ style={{
+ justifyContent: "center",
+ alignItems: "center",
+ fontSize: 30,
+ ...REGULAR_FONT,
+ marginTop: 450,
+ color: getColor(theme),
+ opacity,
+ }}
+ >
+ <span>remotion.dev/recorder</span>
+ </AbsoluteFill>
+ );
+};
+
+export const RecorderScene: React.FC<{
+ theme: "light" | "dark";
+}> = ({ theme }) => {
+ const config = useVideoConfig();
+
+ return (
+ <Sequence
+ width={1080}
+ height={1080}
+ style={{
+ justifyContent: "center",
+ alignItems: "center",
+ left: (config.width - 1080) / 2,
+ }}
+ >
+ <AbsoluteFill
+ style={{
+ transform: `scale(0.7)`,
+ overflowY: "hidden",
+ overflowX: "hidden",
+ }}
+ >
+ <All theme={theme} />
+ </AbsoluteFill>
+ <Attribution theme={theme} />
+ </Sequence>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/Scene.tsx b/packages/template-recorder/remotion/scenes/Scene.tsx
new file mode 100644
index 0000000000..8ffa9167d2
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/Scene.tsx
@@ -0,0 +1,264 @@
+import { interpolateStyles } from "@remotion/animation-utils";
+import React, { useMemo } from "react";
+import {
+ AbsoluteFill,
+ Sequence,
+ spring,
+ useCurrentFrame,
+ useVideoConfig,
+} from "remotion";
+import type { Platform } from "../../config/endcard";
+import type { CanvasLayout } from "../../config/layout";
+import type { SceneAndMetadata } from "../../config/scenes";
+import type { Theme } from "../../config/themes";
+import { SCENE_TRANSITION_DURATION } from "../../config/transitions";
+import { getSceneEnter, getSceneExit } from "../animations/scene-transitions";
+import {
+ getShouldTransitionIn,
+ getShouldTransitionOut,
+} from "../animations/transitions";
+import type { ChapterType } from "../chapters/make-chapters";
+import { useRefreshOnPublicFolderChange } from "../helpers/refresh-on-public-folder-change";
+import { useScrollToCurrentScene } from "../helpers/scroll-to-current-scene";
+import { EndCard } from "./EndCard";
+import { NoRecordingsScene } from "./Placeholders/NoRecordingsScene";
+import { NoScenes } from "./Placeholders/NoScenes";
+import { RecorderScene } from "./Recorder";
+import { TableOfContents } from "./TableOfContents";
+import { Title } from "./Title/Title";
+import { SoundEffects } from "./VideoScene/SoundEffects";
+import { VideoScene } from "./VideoScene/VideoScene";
+
+type Props = {
+ sceneAndMetadata: SceneAndMetadata;
+ previousScene: SceneAndMetadata | null;
+ nextScene: SceneAndMetadata | null;
+ index: number;
+ canvasLayout: CanvasLayout;
+ chapters: ChapterType[];
+ theme: Theme;
+ platform: Platform;
+ hovered: boolean;
+};
+
+const InnerScene: React.FC<
+ Props & {
+ enterProgress: number;
+ exitProgress: number;
+ }
+> = ({
+ canvasLayout,
+ chapters,
+ nextScene,
+ previousScene,
+ sceneAndMetadata,
+ theme,
+ enterProgress,
+ exitProgress,
+ platform,
+ index,
+ hovered,
+}) => {
+ if (sceneAndMetadata.type === "video-scene") {
+ return (
+ <VideoScene
+ enterProgress={enterProgress}
+ canvasLayout={canvasLayout}
+ exitProgress={exitProgress}
+ nextScene={nextScene}
+ previousScene={previousScene}
+ sceneAndMetadata={sceneAndMetadata}
+ theme={theme}
+ chapters={chapters}
+ sceneIndex={index}
+ hovered={hovered}
+ />
+ );
+ }
+
+ if (sceneAndMetadata.scene.type === "title") {
+ return (
+ <Title
+ subtitle={sceneAndMetadata.scene.subtitle}
+ title={sceneAndMetadata.scene.title}
+ theme={theme}
+ />
+ );
+ }
+
+ if (sceneAndMetadata.scene.type === "recorder") {
+ return <RecorderScene theme={theme} />;
+ }
+
+ if (sceneAndMetadata.scene.type === "endcard") {
+ return (
+ <EndCard
+ theme={theme}
+ platform={platform}
+ canvasLayout={canvasLayout}
+ channel={sceneAndMetadata.scene.channel}
+ links={sceneAndMetadata.scene.links}
+ />
+ );
+ }
+
+ if (sceneAndMetadata.scene.type === "tableofcontents") {
+ return <TableOfContents theme={theme} chapters={chapters} />;
+ }
+
+ if (sceneAndMetadata.scene.type === "norecordings") {
+ return <NoRecordingsScene type="none" />;
+ }
+
+ if (sceneAndMetadata.scene.type === "nomorerecordings") {
+ return <NoRecordingsScene type="no-more" />;
+ }
+
+ if (sceneAndMetadata.scene.type === "noscenes") {
+ return <NoScenes />;
+ }
+ if (sceneAndMetadata.scene.type === "videoscene") {
+ throw new Error(
+ 'Video scene should be handled using sceneAndMetadata.type === "video-scene"',
+ );
+ }
+
+ throw new Error(
+ "Scene type not implemented in Scene.tsx: " +
+ // @ts-expect-error If this gives a TS error, then you need to implement a new scene type
+ sceneAndMetadata.scene.type,
+ );
+};
+
+const roundProgress = (progress: number) => {
+ if (progress > 0.999) {
+ return 1;
+ }
+ return progress;
+};
+
+const SceneWithTransition: React.FC<Props> = (props) => {
+ const { fps, durationInFrames, width, id } = useVideoConfig();
+ const frame = useCurrentFrame();
+
+ const shouldEnter = getShouldTransitionIn({
+ sceneAndMetadata: props.sceneAndMetadata,
+ previousSceneAndMetadata: props.previousScene,
+ canvasLayout: props.canvasLayout,
+ });
+ const shouldExit = getShouldTransitionOut({
+ sceneAndMetadata: props.sceneAndMetadata,
+ nextSceneAndMetadata: props.nextScene,
+ canvasLayout: props.canvasLayout,
+ });
+
+ const enter = shouldEnter
+ ? roundProgress(
+ spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ durationInFrames: SCENE_TRANSITION_DURATION,
+ durationRestThreshold: 0.001,
+ }),
+ )
+ : 1;
+
+ const exit = shouldExit
+ ? roundProgress(
+ spring({
+ fps,
+ frame,
+ config: {
+ damping: 200,
+ },
+ durationInFrames: SCENE_TRANSITION_DURATION,
+ durationRestThreshold: 0.001,
+ delay: durationInFrames - SCENE_TRANSITION_DURATION,
+ }),
+ )
+ : 0;
+
+ const startStyle = getSceneEnter({
+ currentScene: props.sceneAndMetadata,
+ previousScene: props.previousScene,
+ canvasWidth: width,
+ });
+ const endStyle = getSceneExit({
+ currentScene: props.sceneAndMetadata,
+ nextScene: props.nextScene,
+ canvasWidth: width,
+ });
+
+ const style = interpolateStyles(
+ enter + exit,
+ [0, 1, 2],
+ [startStyle, { left: 0 }, endStyle],
+ );
+
+ useRefreshOnPublicFolderChange(id);
+ useScrollToCurrentScene({ index: props.index, fullyEntered: enter === 1 });
+
+ return (
+ <AbsoluteFill style={style}>
+ <InnerScene {...props} enterProgress={enter} exitProgress={exit} />
+ {shouldEnter ? (
+ <SoundEffects
+ previousScene={props.previousScene}
+ sceneAndMetadata={props.sceneAndMetadata}
+ />
+ ) : null}
+ </AbsoluteFill>
+ );
+};
+
+export const Scene: React.FC<Props> = ({
+ index,
+ nextScene,
+ previousScene,
+ sceneAndMetadata,
+ canvasLayout,
+ chapters,
+ theme,
+ platform,
+ hovered,
+}) => {
+ const chapter = useMemo(() => {
+ if (sceneAndMetadata.scene.type === "videoscene") {
+ return sceneAndMetadata.scene.newChapter;
+ }
+
+ return undefined;
+ }, [sceneAndMetadata.scene]);
+
+ const sequenceName = useMemo(() => {
+ if (chapter) {
+ return `Scene ${index} (${chapter})`;
+ }
+
+ return `Scene ${index}`;
+ }, [index, chapter]);
+
+ return (
+ <Sequence
+ premountFor={30}
+ name={sequenceName}
+ from={sceneAndMetadata.from}
+ durationInFrames={Math.max(1, sceneAndMetadata.durationInFrames)}
+ >
+ <SceneWithTransition
+ canvasLayout={canvasLayout}
+ chapters={chapters}
+ nextScene={nextScene}
+ index={index}
+ previousScene={previousScene}
+ sceneAndMetadata={sceneAndMetadata}
+ theme={theme}
+ platform={platform}
+ hovered={hovered}
+ />
+ </Sequence>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/TableOfContents/index.tsx b/packages/template-recorder/remotion/scenes/TableOfContents/index.tsx
new file mode 100644
index 0000000000..c39c064d64
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/TableOfContents/index.tsx
@@ -0,0 +1,44 @@
+import React from "react";
+import { AbsoluteFill } from "remotion";
+import { REGULAR_FONT } from "../../../config/fonts";
+import type { Theme } from "../../../config/themes";
+import { COLORS } from "../../../config/themes";
+import type { ChapterType } from "../../chapters/make-chapters";
+import { TableOfContentItem } from "./item";
+
+export const TableOfContents: React.FC<{
+ chapters: ChapterType[];
+ theme: Theme;
+}> = ({ chapters, theme }) => {
+ return (
+ <AbsoluteFill
+ style={{
+ backgroundColor: COLORS[theme].BACKGROUND,
+
+ justifyContent: "center",
+ paddingLeft: 80,
+ paddingRight: 80,
+ color: COLORS[theme].ENDCARD_TEXT_COLOR,
+ }}
+ >
+ <strong
+ style={{
+ ...REGULAR_FONT,
+ fontSize: 46,
+ marginBottom: 30,
+ }}
+ >
+ Table of contents
+ </strong>
+ {chapters.map((chapter) => {
+ return (
+ <TableOfContentItem
+ key={chapter.index}
+ startTime={chapter.start}
+ title={chapter.title}
+ />
+ );
+ })}
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/TableOfContents/item.tsx b/packages/template-recorder/remotion/scenes/TableOfContents/item.tsx
new file mode 100644
index 0000000000..b09970ca06
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/TableOfContents/item.tsx
@@ -0,0 +1,39 @@
+import { useMemo } from "react";
+import { useVideoConfig } from "remotion";
+import { REGULAR_FONT } from "../../../config/fonts";
+import { formatMilliseconds } from "../../../src/helpers/format-time";
+
+export const TableOfContentItem: React.FC<{
+ title: string;
+ startTime: number;
+}> = ({ title, startTime }) => {
+ const { fps } = useVideoConfig();
+
+ const time = useMemo(() => {
+ return Math.floor(startTime / fps);
+ }, [fps, startTime]);
+
+ return (
+ <div
+ style={{
+ ...REGULAR_FONT,
+ fontSize: 46,
+ display: "flex",
+ flexDirection: "row",
+ width: "100%",
+ lineHeight: 1.5,
+ }}
+ >
+ <div style={{ flex: 1 }}>{title}</div>
+ <div
+ style={{
+ width: 150,
+ textAlign: "right",
+ fontVariantNumeric: "tabular-nums",
+ }}
+ >
+ {formatMilliseconds(time * 1000)}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/Title/Title.tsx b/packages/template-recorder/remotion/scenes/Title/Title.tsx
new file mode 100644
index 0000000000..9e91ddc660
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/Title/Title.tsx
@@ -0,0 +1,49 @@
+import React from "react";
+import { AbsoluteFill } from "remotion";
+import { TITLE_FONT } from "../../../config/fonts";
+import type { Theme } from "../../../config/themes";
+import { COLORS } from "../../../config/themes";
+
+export const Title: React.FC<{
+ title: string;
+ subtitle: string | null;
+ theme: Theme;
+}> = ({ subtitle, title, theme }) => {
+ return (
+ <AbsoluteFill
+ style={{
+ justifyContent: "center",
+ alignItems: "center",
+ paddingLeft: 30,
+ paddingRight: 30,
+ }}
+ >
+ <div
+ style={{
+ ...TITLE_FONT,
+ fontSize: 60,
+ color: COLORS[theme].WORD_COLOR_ON_BG_APPEARED,
+ textAlign: "center",
+ textWrap: "balance",
+ }}
+ >
+ {title}
+ </div>
+ {subtitle?.trim() === "" ? null : (
+ <div
+ style={{
+ fontSize: 40,
+ // TODO: Introduce a subtitle color in the theme
+ color: COLORS[theme].ENDCARD_TEXT_COLOR,
+ ...TITLE_FONT,
+ marginTop: 10,
+ textAlign: "center",
+ textWrap: "balance",
+ }}
+ >
+ {subtitle}
+ </div>
+ )}
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/Action.tsx b/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/Action.tsx
new file mode 100644
index 0000000000..3275841bfa
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/Action.tsx
@@ -0,0 +1,47 @@
+import React, { useCallback, useState } from "react";
+
+export const ActionContainer: React.FC<{
+ children: React.ReactNode;
+ onClick: () => void;
+}> = ({ children, onClick }) => {
+ const [hovered, setHovered] = useState(false);
+ const onPointerEnter = useCallback(() => {
+ setHovered(true);
+ }, []);
+
+ const onPointerLeave = useCallback(() => {
+ setHovered(false);
+ }, []);
+
+ return (
+ <button
+ onClick={onClick}
+ onPointerEnter={onPointerEnter}
+ onPointerLeave={onPointerLeave}
+ type="button"
+ style={{
+ height: 100,
+ width: 150,
+ fontSize: 16,
+ fontFamily: "sans-serif",
+ fontWeight: "bold",
+ display: "flex",
+ flexDirection: "column",
+ justifyContent: "flex-start",
+ alignItems: "center",
+ textAlign: "center",
+ paddingTop: 20,
+ gap: 10,
+ cursor: "pointer",
+ appearance: "none",
+ border: "none",
+ borderRadius: 0,
+ background: "none",
+ color: "black",
+ opacity: hovered ? 1 : 0.8,
+ }}
+ >
+ {children}
+ </button>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/Actions.tsx b/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/Actions.tsx
new file mode 100644
index 0000000000..3ceb7b6fdf
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/Actions.tsx
@@ -0,0 +1,51 @@
+import React, { useMemo } from "react";
+import { useVideoConfig } from "remotion";
+import { Cameras } from "../../../../config/scenes";
+import { DeleteRecordingAction } from "./DeleteRecordingAction";
+
+const gradientSteps = [
+ 0, 0.013, 0.049, 0.104, 0.175, 0.259, 0.352, 0.45, 0.55, 0.648, 0.741, 0.825,
+ 0.896, 0.951, 0.987,
+];
+
+const gradientOpacities = [
+ 0, 8.1, 15.5, 22.5, 29, 35.3, 41.2, 47.1, 52.9, 58.8, 64.7, 71, 77.5, 84.5,
+ 91.9,
+];
+
+const globalGradientOpacity = 1;
+
+export const container: React.CSSProperties = {
+ height: 100,
+ backgroundImage: `linear-gradient(to top,${gradientSteps
+ .map((g, i) => {
+ return `hsla(0, 100%, 100%, ${g}) ${
+ (gradientOpacities[i] as number) * globalGradientOpacity
+ }%`;
+ })
+ .join(", ")}, hsl(0, 0%, 0%) 100%)`,
+ top: 0,
+ position: "absolute",
+ justifyContent: "center",
+ color: "white",
+ display: "flex",
+ transition: "opacity 0.15s",
+};
+
+export const Actions: React.FC<{
+ cameras: Cameras;
+ sceneIndex: number;
+ visible: boolean;
+}> = ({ cameras, sceneIndex, visible }) => {
+ const { width } = useVideoConfig();
+
+ const style: React.CSSProperties = useMemo(() => {
+ return { width, ...container, opacity: visible ? 1 : 0 };
+ }, [visible, width]);
+
+ return (
+ <div style={style}>
+ <DeleteRecordingAction sceneIndex={sceneIndex} cameras={cameras} />
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/DeleteRecordingAction.tsx b/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/DeleteRecordingAction.tsx
new file mode 100644
index 0000000000..6ccc94361f
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/ActionOverlay/DeleteRecordingAction.tsx
@@ -0,0 +1,68 @@
+import { deleteStaticFile, saveDefaultProps } from "@remotion/studio";
+import React, { useCallback } from "react";
+import { useVideoConfig } from "remotion";
+import { z } from "zod";
+import { Cameras, videoConf } from "../../../../config/scenes";
+import { ActionContainer } from "./Action";
+
+export const DeleteRecordingAction: React.FC<{
+ cameras: Cameras;
+ sceneIndex: number;
+}> = ({ cameras, sceneIndex }) => {
+ const { id } = useVideoConfig();
+ const onClick = useCallback(async () => {
+ const filesToDelete = [
+ cameras.webcam.name,
+ cameras.display && cameras.display.name,
+ cameras.captions && cameras.captions.name,
+ cameras.alternative1 && cameras.alternative1.name,
+ cameras.alternative2 && cameras.alternative2.name,
+ ].filter(Boolean) as string[];
+ if (
+ !confirm(
+ `This will remove ${filesToDelete.join(", ")} from the file system and delete the scene. Do you want to proceed?`,
+ )
+ ) {
+ return;
+ }
+
+ await Promise.all(
+ [
+ ...filesToDelete.map((f) => deleteStaticFile(f)),
+ saveDefaultProps({
+ compositionId: id,
+ defaultProps: ({ unsavedDefaultProps }) => {
+ const typedProps = unsavedDefaultProps as z.infer<typeof videoConf>;
+ const returnValue: z.infer<typeof videoConf> = {
+ ...typedProps,
+ scenes: typedProps.scenes.filter((s, i) => i !== sceneIndex),
+ };
+ return returnValue;
+ },
+ }),
+ ].filter(Boolean),
+ );
+ }, [
+ cameras.alternative1,
+ cameras.alternative2,
+ cameras.captions,
+ cameras.display,
+ cameras.webcam.name,
+ id,
+ sceneIndex,
+ ]);
+
+ return (
+ <ActionContainer onClick={onClick}>
+ <svg
+ style={{
+ height: 24,
+ }}
+ viewBox="0 0 448 512"
+ >
+ <path d="M135.2 17.7L128 32 32 32C14.3 32 0 46.3 0 64S14.3 96 32 96l384 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-96 0-7.2-14.3C307.4 6.8 296.3 0 284.2 0L163.8 0c-12.1 0-23.2 6.8-28.6 17.7zM416 128L32 128 53.2 467c1.6 25.3 22.6 45 47.9 45l245.8 0c25.3 0 46.3-19.7 47.9-45L416 128z" />
+ </svg>
+ Delete recording
+ </ActionContainer>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/Display.tsx b/packages/template-recorder/remotion/scenes/VideoScene/Display.tsx
new file mode 100644
index 0000000000..1a8e5cd857
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/Display.tsx
@@ -0,0 +1,106 @@
+import React, { useMemo } from "react";
+import { OffthreadVideo, useCurrentFrame, useVideoConfig } from "remotion";
+import type { CanvasLayout } from "../../../config/layout";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import { getDisplayPosition } from "../../animations/display-transitions";
+import { BRollStack } from "../BRoll/BRollStack";
+import { ScaleDownIfBRollRequiresIt } from "../BRoll/ScaleDownWithBRoll";
+
+const outer: React.CSSProperties = {
+ position: "absolute",
+ display: "flex",
+};
+
+export const Display: React.FC<{
+ scene: VideoSceneAndMetadata;
+ enterProgress: number;
+ exitProgress: number;
+ nextScene: SceneAndMetadata | null;
+ previousScene: SceneAndMetadata | null;
+ startFrame: number;
+ endAt: number | undefined;
+ canvasLayout: CanvasLayout;
+}> = ({
+ scene,
+ enterProgress,
+ exitProgress,
+ nextScene,
+ canvasLayout,
+ previousScene,
+ endAt,
+ startFrame,
+}) => {
+ if (scene.layout.displayLayout === null) {
+ throw new Error("No display");
+ }
+
+ if (scene.cameras.display === null) {
+ throw new Error("No display");
+ }
+
+ const frame = useCurrentFrame();
+ const { width, height } = useVideoConfig();
+
+ const displayLayout = useMemo(() => {
+ return getDisplayPosition({
+ enterProgress,
+ exitProgress,
+ canvasWidth: width,
+ nextScene,
+ previousScene,
+ currentScene: scene,
+ canvasHeight: height,
+ canvasLayout,
+ });
+ }, [
+ canvasLayout,
+ enterProgress,
+ exitProgress,
+ height,
+ nextScene,
+ previousScene,
+ scene,
+ width,
+ ]);
+
+ const container: React.CSSProperties = useMemo(() => {
+ return {
+ position: "absolute",
+ ...displayLayout,
+ };
+ }, [displayLayout]);
+
+ return (
+ <div style={outer}>
+ <div style={container}>
+ <ScaleDownIfBRollRequiresIt
+ bRolls={scene.bRolls}
+ bRollType={scene.layout.bRollType}
+ frame={frame}
+ >
+ <OffthreadVideo
+ startFrom={startFrame}
+ endAt={endAt}
+ src={scene.cameras.display.src}
+ style={{
+ width: displayLayout.width,
+ height: displayLayout.height,
+ borderRadius: displayLayout.borderRadius,
+ objectFit: "cover",
+ }}
+ />
+ </ScaleDownIfBRollRequiresIt>
+ </div>
+
+ <BRollStack
+ bRollEnterDirection={scene.layout.bRollEnterDirection}
+ bRolls={scene.bRolls}
+ bRollLayout={scene.layout.bRollLayout}
+ canvasLayout={canvasLayout}
+ />
+ </div>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/DragDropBRoll.tsx b/packages/template-recorder/remotion/scenes/VideoScene/DragDropBRoll.tsx
new file mode 100644
index 0000000000..f10abb5d73
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/DragDropBRoll.tsx
@@ -0,0 +1,61 @@
+import { updateDefaultProps, writeStaticFile } from "@remotion/studio";
+import React from "react";
+import { staticFile } from "remotion";
+import {
+ BRoll,
+ SelectableScene,
+ SelectableVideoScene,
+} from "../../../config/scenes";
+
+export const onBRollDropHandler = async ({
+ e,
+ composition,
+ sceneIndex,
+ from,
+}: {
+ e: React.DragEvent<HTMLDivElement>;
+ composition: string;
+ sceneIndex: number;
+ from: number;
+}) => {
+ e.preventDefault();
+
+ const bRolls: BRoll[] = [];
+ for (const file of e.dataTransfer.files) {
+ await writeStaticFile({
+ contents: await file.arrayBuffer(),
+ filePath: `${composition}/${file.name}`,
+ });
+ bRolls.push({
+ source: staticFile(`${composition}/${file.name}`),
+ durationInFrames: 100,
+ from,
+ });
+ }
+
+ updateDefaultProps({
+ compositionId: composition,
+ defaultProps: ({ unsavedDefaultProps }) => {
+ const scenes = unsavedDefaultProps.scenes as SelectableScene[];
+ const scene = scenes[sceneIndex] as SelectableVideoScene;
+
+ const newScene: SelectableVideoScene = {
+ ...scene,
+ bRolls: bRolls,
+ };
+
+ return {
+ ...unsavedDefaultProps,
+ scenes: [
+ ...scenes.slice(0, sceneIndex),
+ newScene,
+ ...scenes.slice(sceneIndex + 1),
+ ],
+ };
+ },
+ });
+};
+
+export const onBRollDragOver = (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/ImgWithBlur.tsx b/packages/template-recorder/remotion/scenes/VideoScene/ImgWithBlur.tsx
new file mode 100644
index 0000000000..86aff127df
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/ImgWithBlur.tsx
@@ -0,0 +1,28 @@
+import React, { useMemo } from "react";
+import type { ImgProps } from "remotion";
+import { AbsoluteFill, Img } from "remotion";
+import type { Dimensions } from "../../../config/layout";
+import { getBlurLayout } from "../../layout/blur";
+import type { Layout } from "../../layout/layout-types";
+
+// An image that if it cannot fill out the canvas, will have a background-blurred replica
+export const ImgWithBlur: React.FC<
+ {
+ containerLayout: Layout;
+ imageSize: Dimensions;
+ } & Omit<ImgProps, "style">
+> = ({ containerLayout, imageSize, ...props }) => {
+ const { innerStyle, needsBlur, outerStyle, blurStyle } = useMemo(() => {
+ return getBlurLayout({
+ containerLayout,
+ assetSize: imageSize,
+ });
+ }, [containerLayout, imageSize]);
+
+ return (
+ <AbsoluteFill style={outerStyle}>
+ {needsBlur ? <Img style={blurStyle} {...props} /> : null}
+ <Img style={innerStyle} {...props} />
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/NoDataScene.tsx b/packages/template-recorder/remotion/scenes/VideoScene/NoDataScene.tsx
new file mode 100644
index 0000000000..1b6e855e5f
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/NoDataScene.tsx
@@ -0,0 +1,36 @@
+import { useMemo } from "react";
+import { AbsoluteFill } from "remotion";
+import { MONOSPACE_FONT, REGULAR_FONT } from "../../../config/fonts";
+import { COLORS } from "../../../config/themes";
+
+const textWrapper = {
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ height: "100%",
+ gap: 10,
+ ...REGULAR_FONT,
+ fontSize: 40,
+};
+
+export const NoDataScene: React.FC<{
+ theme: "light" | "dark";
+}> = ({ theme }) => {
+ const spanStyle: React.CSSProperties = useMemo(() => {
+ return {
+ color: COLORS[theme].ACCENT_COLOR,
+ ...MONOSPACE_FONT,
+ };
+ }, [theme]);
+
+ return (
+ <AbsoluteFill style={{ backgroundColor: COLORS[theme].BACKGROUND }}>
+ <div style={textWrapper}>
+ <div style={{ padding: 100 }}>
+ No <span style={spanStyle}>scene</span> defined yet?
+ <br /> Add a new one in the right side bar.
+ </div>
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/SoundEffects.tsx b/packages/template-recorder/remotion/scenes/VideoScene/SoundEffects.tsx
new file mode 100644
index 0000000000..317250f572
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/SoundEffects.tsx
@@ -0,0 +1,35 @@
+import { Audio, staticFile } from "remotion";
+import type { SceneAndMetadata } from "../../../config/scenes";
+import {
+ isGrowingFromMiniature,
+ isShrinkingToMiniature,
+} from "../../animations/webcam-transitions/helpers";
+
+export const SoundEffects: React.FC<{
+ previousScene: SceneAndMetadata | null;
+ sceneAndMetadata: SceneAndMetadata;
+}> = ({ previousScene, sceneAndMetadata }) => {
+ if (!previousScene) {
+ return null;
+ }
+
+ if (
+ isShrinkingToMiniature({
+ firstScene: previousScene,
+ secondScene: sceneAndMetadata,
+ })
+ ) {
+ return <Audio src={staticFile("sounds/shrink.m4a")} volume={0.2} />;
+ }
+
+ if (
+ isGrowingFromMiniature({
+ firstScene: previousScene,
+ secondScene: sceneAndMetadata,
+ })
+ ) {
+ return <Audio src={staticFile("sounds/grow.m4a")} volume={0.2} />;
+ }
+
+ return <Audio src={staticFile("sounds/whip.wav")} volume={0.1} />;
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/VideoScene.tsx b/packages/template-recorder/remotion/scenes/VideoScene/VideoScene.tsx
new file mode 100644
index 0000000000..ac50a4b9b3
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/VideoScene.tsx
@@ -0,0 +1,152 @@
+import React, { useCallback, useMemo } from "react";
+import {
+ AbsoluteFill,
+ getRemotionEnvironment,
+ useCurrentFrame,
+ useVideoConfig,
+} from "remotion";
+import type { CanvasLayout } from "../../../config/layout";
+import type {
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import type { Theme } from "../../../config/themes";
+import { B_ROLL_TRANSITION_DURATION } from "../../../config/transitions";
+import { getShouldTransitionIn } from "../../animations/transitions";
+import { BoxedCaptions } from "../../captions/boxed/BoxedCaptions";
+import { SrtPreviewAndEditor } from "../../captions/srt/SrtPreviewAndEditor/SrtPreviewAndEditor";
+import { LandscapeChapters } from "../../chapters/landscape/LandscapeChapters";
+import type { ChapterType } from "../../chapters/make-chapters";
+import { SquareChapter } from "../../chapters/square/SquareChapter";
+import { Actions } from "./ActionOverlay/Actions";
+import { Display } from "./Display";
+import { onBRollDragOver, onBRollDropHandler } from "./DragDropBRoll";
+import { Webcam } from "./Webcam";
+
+export const VideoScene: React.FC<{
+ enterProgress: number;
+ exitProgress: number;
+ canvasLayout: CanvasLayout;
+ sceneAndMetadata: VideoSceneAndMetadata;
+ nextScene: SceneAndMetadata | null;
+ previousScene: SceneAndMetadata | null;
+ theme: Theme;
+ chapters: ChapterType[];
+ sceneIndex: number;
+ hovered: boolean;
+}> = ({
+ enterProgress,
+ exitProgress,
+ sceneAndMetadata,
+ canvasLayout,
+ nextScene,
+ previousScene,
+ theme,
+ chapters,
+ sceneIndex,
+ hovered,
+}) => {
+ const startFrame = sceneAndMetadata.startFrame;
+ const endAt = sceneAndMetadata.endFrame;
+
+ if (sceneAndMetadata.type !== "video-scene") {
+ throw new Error("Not a camera scene");
+ }
+
+ const didTransitionIn = getShouldTransitionIn({
+ previousSceneAndMetadata: previousScene,
+ sceneAndMetadata: sceneAndMetadata,
+ canvasLayout,
+ });
+
+ const bRollsOnTopOfWebcam = useMemo(() => {
+ if (sceneAndMetadata.cameras.display !== null) {
+ return [];
+ }
+ return sceneAndMetadata.bRolls;
+ }, [sceneAndMetadata.bRolls, sceneAndMetadata.cameras.display]);
+
+ const { id } = useVideoConfig();
+ const frame = useCurrentFrame();
+
+ const onDrop = useCallback(
+ (e: React.DragEvent<HTMLDivElement>) => {
+ onBRollDropHandler({
+ e,
+ composition: id,
+ sceneIndex,
+ from: frame - B_ROLL_TRANSITION_DURATION,
+ });
+ },
+ [frame, id, sceneIndex],
+ );
+
+ return (
+ <AbsoluteFill onDragOver={onBRollDragOver} onDrop={onDrop}>
+ {sceneAndMetadata.cameras.display ? (
+ <Display
+ scene={sceneAndMetadata}
+ enterProgress={enterProgress}
+ exitProgress={exitProgress}
+ nextScene={nextScene}
+ previousScene={previousScene}
+ startFrame={startFrame}
+ endAt={endAt}
+ canvasLayout={canvasLayout}
+ />
+ ) : null}
+ <Webcam
+ bRolls={bRollsOnTopOfWebcam}
+ currentScene={sceneAndMetadata}
+ endAt={endAt}
+ enterProgress={enterProgress}
+ exitProgress={exitProgress}
+ startFrame={startFrame}
+ canvasLayout={canvasLayout}
+ nextScene={nextScene}
+ previousScene={previousScene}
+ />
+ {canvasLayout === "square" ? (
+ <BoxedCaptions
+ enterProgress={enterProgress}
+ exitProgress={exitProgress}
+ nextScene={nextScene}
+ previousScene={previousScene}
+ sceneAndMetadata={sceneAndMetadata}
+ startFrame={startFrame}
+ theme={theme}
+ />
+ ) : null}
+ {sceneAndMetadata.scene.newChapter && canvasLayout === "square" ? (
+ <SquareChapter
+ title={sceneAndMetadata.scene.newChapter}
+ displayLayout={sceneAndMetadata.layout.displayLayout}
+ webcamLayout={sceneAndMetadata.layout.webcamLayout}
+ didTransitionIn={didTransitionIn}
+ />
+ ) : null}
+ {sceneAndMetadata.scene.newChapter && canvasLayout === "landscape" ? (
+ <LandscapeChapters
+ scene={sceneAndMetadata}
+ theme={theme}
+ chapters={chapters}
+ didTransitionIn={didTransitionIn}
+ />
+ ) : null}
+ {canvasLayout === "landscape" && sceneAndMetadata.cameras.captions ? (
+ <SrtPreviewAndEditor
+ captions={sceneAndMetadata.cameras.captions}
+ startFrame={startFrame}
+ theme={theme}
+ ></SrtPreviewAndEditor>
+ ) : null}
+ {getRemotionEnvironment().isStudio ? (
+ <Actions
+ visible={hovered}
+ sceneIndex={sceneIndex}
+ cameras={sceneAndMetadata.cameras}
+ />
+ ) : null}
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/VideoWithBlur.tsx b/packages/template-recorder/remotion/scenes/VideoScene/VideoWithBlur.tsx
new file mode 100644
index 0000000000..335e6024ba
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/VideoWithBlur.tsx
@@ -0,0 +1,47 @@
+import React, { useMemo } from "react";
+import {
+ AbsoluteFill,
+ OffthreadVideo,
+ RemotionOffthreadVideoProps,
+} from "remotion";
+import type { Dimensions } from "../../../config/layout";
+import { getBlurLayout } from "../../layout/blur";
+import type { Layout } from "../../layout/layout-types";
+
+// An image that if it cannot fill out the canvas, will have a background-blurred replica
+export const VideoWithBlur: React.FC<
+ {
+ containerLayout: Layout;
+ videoSize: Dimensions;
+ enableBlur: boolean;
+ } & Omit<RemotionOffthreadVideoProps, "style">
+> = ({ containerLayout, videoSize, enableBlur, ...props }) => {
+ const { innerStyle, needsBlur, outerStyle, blurStyle } = useMemo(() => {
+ return getBlurLayout({
+ containerLayout,
+ assetSize: videoSize,
+ });
+ }, [containerLayout, videoSize]);
+
+ if (!enableBlur) {
+ return (
+ <AbsoluteFill>
+ <OffthreadVideo
+ style={{
+ objectFit: "cover",
+ ...outerStyle,
+ position: "absolute",
+ }}
+ {...props}
+ />
+ </AbsoluteFill>
+ );
+ }
+
+ return (
+ <AbsoluteFill style={outerStyle}>
+ {needsBlur ? <OffthreadVideo style={blurStyle} {...props} muted /> : null}
+ <OffthreadVideo style={innerStyle} {...props} />
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/remotion/scenes/VideoScene/Webcam.tsx b/packages/template-recorder/remotion/scenes/VideoScene/Webcam.tsx
new file mode 100644
index 0000000000..68489db39a
--- /dev/null
+++ b/packages/template-recorder/remotion/scenes/VideoScene/Webcam.tsx
@@ -0,0 +1,98 @@
+import React, { useMemo } from "react";
+import { useCurrentFrame, useVideoConfig } from "remotion";
+import type { CanvasLayout } from "../../../config/layout";
+import type {
+ BRollWithDimensions,
+ SceneAndMetadata,
+ VideoSceneAndMetadata,
+} from "../../../config/scenes";
+import { getWebcamLayout } from "../../animations/webcam-transitions";
+import { shouldEnableSceneBackgroundBlur } from "../../layout/blur";
+import { BRollStack } from "../BRoll/BRollStack";
+import { ScaleDownIfBRollRequiresIt } from "../BRoll/ScaleDownWithBRoll";
+import { VideoWithBlur } from "./VideoWithBlur";
+
+export const Webcam: React.FC<{
+ enterProgress: number;
+ exitProgress: number;
+ startFrame: number;
+ endAt: number | undefined;
+ canvasLayout: CanvasLayout;
+ nextScene: SceneAndMetadata | null;
+ previousScene: SceneAndMetadata | null;
+ currentScene: VideoSceneAndMetadata;
+ bRolls: BRollWithDimensions[];
+}> = ({
+ enterProgress,
+ exitProgress,
+ startFrame,
+ endAt,
+ nextScene,
+ previousScene,
+ canvasLayout,
+ currentScene,
+ bRolls,
+}) => {
+ const frame = useCurrentFrame();
+ const { height, width } = useVideoConfig();
+
+ const webcamLayout = useMemo(() => {
+ return getWebcamLayout({
+ enterProgress,
+ exitProgress,
+ canvasHeight: height,
+ canvasWidth: width,
+ currentScene,
+ nextScene,
+ previousScene,
+ canvasLayout,
+ });
+ }, [
+ canvasLayout,
+ currentScene,
+ enterProgress,
+ exitProgress,
+ height,
+ nextScene,
+ previousScene,
+ width,
+ ]);
+
+ const container: React.CSSProperties = useMemo(() => {
+ return {
+ overflow: "hidden",
+ position: "relative",
+ ...webcamLayout,
+ };
+ }, [webcamLayout]);
+
+ return (
+ <>
+ <div style={container}>
+ <ScaleDownIfBRollRequiresIt
+ bRolls={bRolls}
+ frame={frame}
+ bRollType={currentScene.layout.bRollType}
+ >
+ <VideoWithBlur
+ startFrom={startFrame}
+ endAt={endAt}
+ src={currentScene.cameras.webcam.src}
+ containerLayout={webcamLayout}
+ videoSize={currentScene.videos.webcam}
+ enableBlur={shouldEnableSceneBackgroundBlur(
+ currentScene,
+ canvasLayout,
+ )}
+ />
+ </ScaleDownIfBRollRequiresIt>
+ </div>
+ <BRollStack
+ canvasLayout={canvasLayout}
+ bRollEnterDirection={currentScene.layout.bRollEnterDirection}
+ bRolls={bRolls}
+ bRollLayout={currentScene.layout.bRollLayout}
+ />
+ </>
+ );
+};
diff --git a/packages/template-recorder/scripts/captions/caption-file.ts b/packages/template-recorder/scripts/captions/caption-file.ts
new file mode 100644
index 0000000000..d49734bac1
--- /dev/null
+++ b/packages/template-recorder/scripts/captions/caption-file.ts
@@ -0,0 +1,79 @@
+import { toCaptions, transcribe } from "@remotion/install-whisper-cpp";
+import { spawn } from "child_process";
+import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs";
+import { EOL, tmpdir } from "os";
+import path from "path";
+import {
+ TRANSCRIPTION_LANGUAGE,
+ WHISPER_MODEL,
+ WHISPER_PATH,
+ WHISPER_REF,
+} from "../../config/whisper";
+
+export const captionFile = async ({
+ file,
+ fileToTranscribe,
+ outPath,
+ onProgress,
+ signal,
+}: {
+ file: string;
+ fileToTranscribe: string;
+ outPath: string;
+ onProgress: (options: {
+ filename: string;
+ progressInPercent: number;
+ }) => void;
+ signal: AbortSignal;
+}): Promise<void> => {
+ const tmpDir = path.join(tmpdir(), "remotion-recorder");
+
+ if (!existsSync(tmpDir)) {
+ mkdirSync(tmpDir);
+ }
+
+ const wavFile = path.join(tmpDir, `${file.split(".")[0]}.wav`);
+
+ onProgress({ filename: file, progressInPercent: 0 });
+
+ // extracting audio from mp4 and save it as 16khz wav file
+ await new Promise<void>((resolve, reject) => {
+ const command = `bunx remotion ffmpeg -hide_banner -i ${fileToTranscribe} -ar 16000 -y ${wavFile}`;
+ const [bin, ...args] = command.split(" ");
+ const child = spawn(bin as string, args, {
+ stdio: "ignore",
+ signal: signal ?? undefined,
+ });
+
+ child.on("exit", (code, signal) => {
+ if (code !== 0) {
+ reject(new Error(`Exit code ${code} (signal ${signal})`));
+ return;
+ }
+ resolve();
+ });
+ });
+
+ const whisperCppOutput = await transcribe({
+ inputPath: wavFile,
+ model: WHISPER_MODEL,
+ tokenLevelTimestamps: true,
+ whisperPath: WHISPER_PATH,
+ translateToEnglish: false,
+ printOutput: true,
+ onProgress: (progress) => {
+ onProgress({
+ filename: file,
+ progressInPercent: Math.round(progress * 100),
+ });
+ },
+ signal: signal,
+ language: TRANSCRIPTION_LANGUAGE,
+ whisperCppVersion: WHISPER_REF,
+ });
+
+ const { captions } = toCaptions({ whisperCppOutput: whisperCppOutput });
+
+ rmSync(wavFile);
+ writeFileSync(outPath, JSON.stringify(captions, null, 2) + EOL);
+};
diff --git a/packages/template-recorder/scripts/captions/install-whisper.ts b/packages/template-recorder/scripts/captions/install-whisper.ts
new file mode 100644
index 0000000000..ba4247499b
--- /dev/null
+++ b/packages/template-recorder/scripts/captions/install-whisper.ts
@@ -0,0 +1,39 @@
+import {
+ downloadWhisperModel,
+ installWhisperCpp,
+} from "@remotion/install-whisper-cpp";
+import { WHISPER_MODEL, WHISPER_PATH, WHISPER_REF } from "../../config/whisper";
+
+export const ensureWhisper = async ({
+ onInstall,
+ onModelProgressInPercent,
+ signal,
+}: {
+ onInstall: () => void;
+ onModelProgressInPercent: (progress: number) => void;
+ signal: AbortSignal;
+}) => {
+ const installPromise = installWhisperCpp({
+ to: WHISPER_PATH,
+ version: WHISPER_REF,
+ printOutput: true,
+ signal,
+ });
+
+ const timeout = setTimeout(() => {
+ onInstall();
+ }, 1000);
+
+ await installPromise;
+ clearTimeout(timeout);
+
+ await downloadWhisperModel({
+ model: WHISPER_MODEL,
+ folder: WHISPER_PATH,
+ printOutput: true,
+ onProgress: (downloadedBytes: number, totalBytes: number) => {
+ onModelProgressInPercent((downloadedBytes / totalBytes) * 100);
+ },
+ signal,
+ });
+};
diff --git a/packages/template-recorder/scripts/convert-video.ts b/packages/template-recorder/scripts/convert-video.ts
new file mode 100644
index 0000000000..3f8d99d0e3
--- /dev/null
+++ b/packages/template-recorder/scripts/convert-video.ts
@@ -0,0 +1,140 @@
+import { spawn } from "node:child_process";
+import { existsSync, mkdirSync, renameSync, unlinkSync } from "node:fs";
+import os from "os";
+import path from "path";
+import { prefixes } from "../src/helpers/prefixes";
+import { getDownloadsFolder } from "./get-downloads-folder";
+import { parseFfmpegProgress } from "./server/parse-ffmpeg-progress";
+
+export const convertVideo = async ({
+ input,
+ output,
+ onProgress,
+ signal,
+ expectedFrames,
+}: {
+ input: string;
+ output: string;
+ onProgress: (options: {
+ framesEncoded: number;
+ progress: number;
+ filename: string;
+ }) => void;
+ signal: AbortSignal | undefined;
+ expectedFrames: number | null;
+}) => {
+ const tempFile = path.join(os.tmpdir(), `temp${Math.random()}.mp4`);
+ const proc = spawn(
+ "bunx",
+ [
+ "remotion",
+ "ffmpeg",
+ "-stats_period",
+ "0.1",
+ "-hide_banner",
+ "-i",
+ input,
+ "-movflags",
+ "+faststart",
+ "-r",
+ "30",
+ "-y",
+ tempFile,
+ ],
+ {
+ signal,
+ },
+ );
+
+ const ffmpegOutput: Buffer[] = [];
+
+ proc.stderr.on("data", (d) => {
+ ffmpegOutput.push(d);
+ const framesEncoded = parseFfmpegProgress(d.toString(), 30);
+ if (framesEncoded !== undefined) {
+ onProgress({
+ filename: path.basename(output),
+ framesEncoded: framesEncoded,
+ progress: expectedFrames === null ? 0 : framesEncoded / expectedFrames,
+ });
+ }
+ });
+ proc.stdout.on("data", (d) => {
+ ffmpegOutput.push(d);
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ return proc.on("close", (code, signal) => {
+ if (code !== 0) {
+ reject(
+ new Error(
+ `FFmpeg quit with code ${code} (signal ${signal}): ${Buffer.concat(ffmpegOutput).toString("utf8")}`,
+ ),
+ );
+ } else {
+ resolve();
+ }
+ });
+ });
+
+ if (expectedFrames) {
+ onProgress({
+ filename: path.basename(output),
+ framesEncoded: expectedFrames,
+ progress: 1,
+ });
+ }
+
+ if (!existsSync(path.dirname(output))) {
+ mkdirSync(path.dirname(output), { recursive: true });
+ }
+
+ renameSync(tempFile, output);
+ unlinkSync(input);
+};
+
+export const convertVideos = async ({
+ latestTimestamp,
+ onProgress,
+ expectedFrames,
+ compositionId,
+}: {
+ onProgress: (options: {
+ framesEncoded: number;
+ progress: number;
+ filename: string;
+ }) => void;
+ expectedFrames: number | null;
+ latestTimestamp: number;
+ compositionId: string;
+}) => {
+ const fileLocation = getDownloadsFolder();
+
+ for (const prefix of prefixes) {
+ const latestWebM = `${prefix}${latestTimestamp}.webm`;
+ const latestMP4 = `${prefix}${latestTimestamp}.mp4`;
+ const srcWebM = path.join(fileLocation, latestWebM);
+ const srcMP4 = path.join(fileLocation, latestMP4);
+ const folder = path.join("public", compositionId);
+
+ if (existsSync(srcWebM)) {
+ await convertVideo({
+ input: srcWebM,
+ output: path.join(folder, latestWebM),
+ onProgress,
+ signal: undefined,
+ expectedFrames,
+ });
+ }
+
+ if (existsSync(srcMP4)) {
+ await convertVideo({
+ input: srcMP4,
+ output: path.join(folder, latestMP4),
+ onProgress,
+ signal: undefined,
+ expectedFrames,
+ });
+ }
+ }
+};
diff --git a/packages/template-recorder/scripts/get-downloads-folder.ts b/packages/template-recorder/scripts/get-downloads-folder.ts
new file mode 100644
index 0000000000..63f9053a95
--- /dev/null
+++ b/packages/template-recorder/scripts/get-downloads-folder.ts
@@ -0,0 +1,49 @@
+import { execSync } from "child_process";
+import { statSync } from "fs";
+import os from "os";
+
+function darwin() {
+ return `${process.env.HOME}/Downloads`;
+}
+
+function unix() {
+ let dir;
+ try {
+ dir = execSync("xdg-user-dir DOWNLOAD", { encoding: "utf8" }).trim();
+ } catch (_) {
+ /* empty */
+ }
+
+ if (dir && dir !== process.env.HOME) return dir;
+
+ let stat;
+ const homeDownloads = `${process.env.HOME}/Downloads`;
+ try {
+ stat = statSync(homeDownloads);
+ } catch (_) {
+ /* empty */
+ }
+
+ if (stat) return homeDownloads;
+
+ return "/tmp/";
+}
+
+function windows() {
+ return process.env.USERPROFILE + "/Downloads";
+}
+
+export const getDownloadsFolder = () => {
+ switch (os.platform()) {
+ case "darwin":
+ return darwin();
+ case "freebsd":
+ case "linux":
+ case "sunos":
+ return unix();
+ case "win32":
+ return windows();
+ default:
+ throw new Error("Unsupported platform");
+ }
+};
diff --git a/packages/template-recorder/scripts/server/constants.ts b/packages/template-recorder/scripts/server/constants.ts
new file mode 100644
index 0000000000..11209f18fd
--- /dev/null
+++ b/packages/template-recorder/scripts/server/constants.ts
@@ -0,0 +1,5 @@
+export const GET_FOLDERS = "/api/projects";
+export const CREATE_FOLDER = "/api/create-folder";
+export const UPLOAD_VIDEO = "/api/upload-video";
+export const TRANSCRIBE_VIDEO = "/api/transcribe-video";
+export const CANCEL_TRANSCRIBE = "/api/cancel-transcribe";
diff --git a/packages/template-recorder/scripts/server/create-project.ts b/packages/template-recorder/scripts/server/create-project.ts
new file mode 100644
index 0000000000..a89fdc09da
--- /dev/null
+++ b/packages/template-recorder/scripts/server/create-project.ts
@@ -0,0 +1,67 @@
+import { existsSync, mkdirSync } from "fs";
+import { IncomingMessage, ServerResponse } from "http";
+import path from "path";
+
+export const createProject = async (
+ req: IncomingMessage,
+ res: ServerResponse,
+ rootDir: string,
+) => {
+ let data = "";
+
+ const { projectName } = await new Promise<{ projectName: string }>(
+ (resolve) => {
+ req.on("data", (chunk) => {
+ data += chunk;
+ });
+ req.on("end", () => {
+ resolve(JSON.parse(data));
+ });
+ },
+ );
+
+ if (projectName === "") {
+ res.statusCode = 500;
+ res.write(
+ JSON.stringify({
+ success: false,
+ message: "Empty string is an invalid project name",
+ }),
+ );
+ return res.end();
+ }
+
+ const finalPath = path.join(rootDir, "public", projectName);
+
+ if (existsSync(finalPath)) {
+ res.statusCode = 409;
+ res.write(
+ JSON.stringify({
+ success: false,
+ message: `Name conflict: A project named "${projectName}" already exists. Choose another name.`,
+ }),
+ );
+ return res.end();
+ }
+
+ try {
+ mkdirSync(finalPath);
+ res.statusCode = 201;
+ res.write(
+ JSON.stringify({
+ success: true,
+ message: `Project "${projectName}" created successfully.`,
+ }),
+ );
+ return res.end();
+ } catch (e) {
+ res.statusCode = 500;
+ res.write(
+ JSON.stringify({
+ success: false,
+ message: `Something went wrong while creating the new folder.`,
+ }),
+ );
+ return res.end();
+ }
+};
diff --git a/packages/template-recorder/scripts/server/express-server.ts b/packages/template-recorder/scripts/server/express-server.ts
new file mode 100644
index 0000000000..a9b8744723
--- /dev/null
+++ b/packages/template-recorder/scripts/server/express-server.ts
@@ -0,0 +1,67 @@
+import react from "@vitejs/plugin-react-swc";
+import connect from "connect";
+import { IncomingMessage, ServerResponse } from "node:http";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { createServer } from "vite";
+import { SERVER_PORT } from "../../config/server";
+import {
+ CANCEL_TRANSCRIBE,
+ CREATE_FOLDER,
+ GET_FOLDERS,
+ TRANSCRIBE_VIDEO,
+ UPLOAD_VIDEO,
+} from "./constants";
+import { createProject } from "./create-project";
+import { indexHtmlDev } from "./index-html";
+import { getProjectFolder } from "./projects";
+import {
+ handleCancelTranscription,
+ handleTranscribeVideo,
+ handleVideoUpload,
+} from "./upload-video";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+export const startServer = async () => {
+ const app = connect();
+
+ const rootDir = path.join(__dirname, "..", "..");
+ const publicDir = path.join(rootDir, "public");
+
+ const vite = await createServer({
+ configFile: false,
+ root: rootDir,
+ server: {
+ middlewareMode: true,
+ watch: {
+ ignored: [path.join(rootDir, "whisper.cpp/**")],
+ },
+ },
+ appType: "custom",
+ plugins: [react()],
+ publicDir,
+ });
+
+ app.use((req, res, next) => {
+ vite.middlewares.handle(req, res, next);
+ });
+
+ app.use(GET_FOLDERS, (req: IncomingMessage, res: ServerResponse) => {
+ getProjectFolder(req, res, rootDir);
+ });
+
+ app.use(CREATE_FOLDER, (req: IncomingMessage, res: ServerResponse) => {
+ createProject(req, res, rootDir);
+ });
+
+ app.use(UPLOAD_VIDEO, handleVideoUpload);
+ app.use(TRANSCRIBE_VIDEO, handleTranscribeVideo);
+ app.use(CANCEL_TRANSCRIBE, handleCancelTranscription);
+ app.use("/", indexHtmlDev(vite, rootDir));
+
+ const port = process.env.PORT || SERVER_PORT;
+
+ app.listen(port);
+ console.log(`Recording interface running on http://localhost:${port}`);
+};
diff --git a/packages/template-recorder/scripts/server/index-html.ts b/packages/template-recorder/scripts/server/index-html.ts
new file mode 100644
index 0000000000..2f0c7c74ed
--- /dev/null
+++ b/packages/template-recorder/scripts/server/index-html.ts
@@ -0,0 +1,30 @@
+import { readFileSync } from "node:fs";
+import { IncomingMessage, ServerResponse } from "node:http";
+import path from "path";
+import type { ViteDevServer } from "vite";
+
+declare global {
+ interface Window {
+ remotionServerEnabled: boolean | undefined;
+ }
+}
+
+export const indexHtmlDev = (vite: ViteDevServer, viteDir: string) => {
+ const index = path.join(viteDir, "index.html");
+ return async (req: IncomingMessage, response: ServerResponse) => {
+ const template = readFileSync(index, "utf-8");
+ const transformed = await vite.transformIndexHtml(
+ req.url as string,
+ template,
+ );
+ const injected = transformed.replace(
+ "<!--remotion-server-placeholder-->",
+ "<script>window.remotionServerEnabled = true</script>",
+ );
+ response.writeHead(200, {
+ "Content-Type": "text/html",
+ });
+ response.write(injected);
+ response.end();
+ };
+};
diff --git a/packages/template-recorder/scripts/server/index.ts b/packages/template-recorder/scripts/server/index.ts
new file mode 100644
index 0000000000..338acffe76
--- /dev/null
+++ b/packages/template-recorder/scripts/server/index.ts
@@ -0,0 +1,18 @@
+import { spawn } from "child_process";
+import { startServer } from "./express-server";
+
+export const startStudioAndServer = async () => {
+ await startServer();
+
+ const bunxProcess = spawn("bun", ["x", "remotion", "studio"], {
+ stdio: "inherit",
+ shell: process.platform === "win32" ? "cmd.exe" : undefined,
+ detached: false,
+ });
+
+ // Forces the process to crash in case of error
+ process.on("uncaughtException", (e) => {
+ console.error(e);
+ bunxProcess.kill();
+ });
+};
diff --git a/packages/template-recorder/scripts/server/parse-ffmpeg-progress.ts b/packages/template-recorder/scripts/server/parse-ffmpeg-progress.ts
new file mode 100644
index 0000000000..4210eb2f62
--- /dev/null
+++ b/packages/template-recorder/scripts/server/parse-ffmpeg-progress.ts
@@ -0,0 +1,20 @@
+export const parseFfmpegProgress = (
+ input: string,
+ fps: number,
+): number | undefined => {
+ const match = input.match(/frame=(\s+)?([0-9]+)\s/);
+ if (match) {
+ return Number(match[2]);
+ }
+
+ const match2 = input.match(/time=(\d+):(\d+):(\d+).(\d+)\s/);
+ if (match2) {
+ const [, hours, minutes, seconds, hundreds] = match2;
+ return (
+ (Number(hundreds) / 100) * fps +
+ Number(seconds) * fps +
+ Number(minutes) * fps * 60 +
+ Number(hours) * fps * 60 * 60
+ );
+ }
+};
diff --git a/packages/template-recorder/scripts/server/projects.ts b/packages/template-recorder/scripts/server/projects.ts
new file mode 100644
index 0000000000..602b59cb6a
--- /dev/null
+++ b/packages/template-recorder/scripts/server/projects.ts
@@ -0,0 +1,33 @@
+import { readdirSync } from "fs";
+import { IncomingMessage, ServerResponse } from "http";
+import path from "path";
+
+export type FolderResBody = {
+ folders: string[];
+};
+
+export const getProjectFolder = (
+ req: IncomingMessage,
+ res: ServerResponse,
+ rootDir: string,
+) => {
+ const publicDir = path.join(rootDir, "public");
+
+ try {
+ const files = readdirSync(publicDir, { withFileTypes: true });
+
+ const folders = files.filter((file) => file.isDirectory());
+
+ const folderNames = folders
+ .map((folder) => folder.name)
+ .filter((f) => f !== "sounds");
+
+ res.statusCode = 200;
+ res.setHeader("Content-Type", "application/json");
+ res.end(JSON.stringify({ folders: folderNames }));
+ } catch (e) {
+ res.statusCode = 500;
+ res.setHeader("Content-Type", "application/json");
+ res.end(JSON.stringify({ error: (e as Error).message }));
+ }
+};
diff --git a/packages/template-recorder/scripts/server/streaming.ts b/packages/template-recorder/scripts/server/streaming.ts
new file mode 100644
index 0000000000..6652dd755d
--- /dev/null
+++ b/packages/template-recorder/scripts/server/streaming.ts
@@ -0,0 +1,93 @@
+import { makeStreamPayloadMessage } from "@remotion/streaming";
+
+const transcribingProgress = "transcribing-progress" as const;
+const installWhisperProgress = "install-whisper-progress" as const;
+const downloadingWhisperModelProgress =
+ "downloading-whisper-model-progress" as const;
+const whisperAbort = "whisper-abort" as const;
+
+const messageTypes = {
+ "2": { type: transcribingProgress },
+ "3": { type: installWhisperProgress },
+ "4": { type: downloadingWhisperModelProgress },
+ "5": { type: whisperAbort },
+} as const;
+
+export type MessageTypeId = keyof typeof messageTypes;
+type MessageType = (typeof messageTypes)[MessageTypeId]["type"];
+
+export const formatMap: { [key in MessageType]: "json" | "binary" } = {
+ [transcribingProgress]: "json",
+ [installWhisperProgress]: "json",
+ [downloadingWhisperModelProgress]: "json",
+ [whisperAbort]: "json",
+};
+
+type StreamingPayload =
+ | {
+ type: typeof transcribingProgress;
+ payload: {
+ filename: string;
+ progress: number;
+ };
+ }
+ | {
+ type: typeof installWhisperProgress;
+ payload: Record<string, never>;
+ }
+ | {
+ type: typeof downloadingWhisperModelProgress;
+ payload: {
+ progressInPercent: number;
+ };
+ }
+ | {
+ type: typeof whisperAbort;
+ payload: Record<string, never>;
+ };
+
+export const messageTypeIdToMessageType = (
+ messageTypeId: MessageTypeId,
+): MessageType => {
+ const types = messageTypes[messageTypeId];
+ if (!types) {
+ throw new Error(`Unknown message type id ${messageTypeId}`);
+ }
+
+ return types.type;
+};
+
+const messageTypeToMessageId = (messageType: MessageType): MessageTypeId => {
+ const id = (Object.keys(messageTypes) as unknown as MessageTypeId[]).find(
+ (key) => messageTypes[key].type === messageType,
+ ) as MessageTypeId;
+
+ if (!id) {
+ throw new Error(`Unknown message type ${messageType}`);
+ }
+
+ return id;
+};
+
+export type StreamingMessage = {
+ successType: "error" | "success";
+ message: StreamingPayload;
+};
+
+export type OnMessage = (options: StreamingMessage) => void;
+
+export type OnStream = (payload: StreamingPayload) => void;
+
+export const makeStreamPayload = ({
+ message,
+}: {
+ message: StreamingPayload;
+}) => {
+ const body = new TextEncoder().encode(JSON.stringify(message.payload));
+
+ return makeStreamPayloadMessage({
+ body,
+ nonce: messageTypeToMessageId(message.type),
+ status: 0,
+ });
+};
diff --git a/packages/template-recorder/scripts/server/transcribe-video.ts b/packages/template-recorder/scripts/server/transcribe-video.ts
new file mode 100644
index 0000000000..46acb1f0d3
--- /dev/null
+++ b/packages/template-recorder/scripts/server/transcribe-video.ts
@@ -0,0 +1,70 @@
+import { existsSync, readdirSync } from "fs";
+import path from "path";
+import { CAPTIONS_PREFIX, WEBCAM_PREFIX } from "../../config/cameras";
+import { captionFile } from "../captions/caption-file";
+
+export const transcribeVideo = async ({
+ endDateAsString,
+ folder,
+ publicDir,
+ onProgress,
+ signal,
+}: {
+ endDateAsString: string;
+ folder: string;
+ publicDir: string;
+ onProgress: (options: {
+ filename: string;
+ progressInPercent: number;
+ }) => void;
+ signal: AbortSignal;
+}) => {
+ if (typeof endDateAsString !== "string") {
+ throw new Error("No `endDate` provided");
+ }
+
+ if (typeof folder !== "string") {
+ throw new Error("No `folder` provided");
+ }
+
+ const folderPath = path.join(publicDir, folder);
+
+ // get webcam file of provided end date
+ const webcamFiles = readdirSync(folderPath).filter((f) => {
+ return (
+ f !== ".DS_Store" &&
+ f.includes(endDateAsString) &&
+ f.startsWith(WEBCAM_PREFIX)
+ );
+ });
+
+ if (webcamFiles.length === 0) {
+ throw new Error(
+ `Webcam file ${WEBCAM_PREFIX}${endDateAsString}.mp4 not found.`,
+ );
+ }
+
+ if (webcamFiles.length > 1) {
+ throw new Error("Duplicate files found.");
+ }
+
+ const fileName = webcamFiles[0] as string;
+ const filePath = path.join(folderPath, fileName);
+
+ const outPath = path.join(
+ folderPath,
+ `${(fileName.split(".")[0] as string).replace(WEBCAM_PREFIX, CAPTIONS_PREFIX)}.json`,
+ );
+
+ if (existsSync(outPath)) {
+ return;
+ }
+
+ await captionFile({
+ file: fileName,
+ outPath,
+ fileToTranscribe: filePath,
+ onProgress,
+ signal,
+ });
+};
diff --git a/packages/template-recorder/scripts/server/upload-video.ts b/packages/template-recorder/scripts/server/upload-video.ts
new file mode 100644
index 0000000000..a1d45cc144
--- /dev/null
+++ b/packages/template-recorder/scripts/server/upload-video.ts
@@ -0,0 +1,168 @@
+import fs, { createWriteStream } from "fs";
+import { IncomingMessage, ServerResponse } from "http";
+import path from "path";
+import { ensureWhisper } from "../captions/install-whisper";
+import { makeStreamPayload } from "./streaming";
+import { transcribeVideo } from "./transcribe-video";
+
+let currentSignal = new AbortController();
+
+export const handleTranscribeVideo = async (
+ req: IncomingMessage,
+ res: ServerResponse,
+) => {
+ const url = req.url as string;
+ const params = new URLSearchParams(url.substring(1));
+ const endDateAsString = params.get("endDateAsString");
+ const folder = params.get("folder");
+ const publicDir = path.join(process.cwd(), "public");
+ currentSignal = new AbortController();
+
+ if (typeof endDateAsString !== "string") {
+ throw new Error("No `endDate` provided");
+ }
+
+ if (typeof folder !== "string") {
+ throw new Error("No `folder` provided");
+ }
+
+ try {
+ await ensureWhisper({
+ onInstall: () => {
+ res.write(
+ makeStreamPayload({
+ message: {
+ type: "install-whisper-progress",
+ payload: {},
+ },
+ }),
+ );
+ },
+ onModelProgressInPercent: (progress) => {
+ res.write(
+ makeStreamPayload({
+ message: {
+ type: "downloading-whisper-model-progress",
+ payload: {
+ progressInPercent: progress,
+ },
+ },
+ }),
+ );
+ },
+ signal: currentSignal.signal,
+ });
+
+ await transcribeVideo({
+ endDateAsString,
+ folder,
+ publicDir,
+ onProgress: ({ filename, progressInPercent: progress }) => {
+ const payload = makeStreamPayload({
+ message: {
+ type: "transcribing-progress",
+ payload: {
+ filename,
+ progress,
+ },
+ },
+ });
+ res.write(payload);
+ },
+ signal: currentSignal.signal,
+ });
+
+ res.statusCode = 200;
+ res.end();
+ } catch (e) {
+ if (
+ (e as Error).name === "AbortError" ||
+ (e as Error).message.includes("SIGTERM")
+ ) {
+ const payload = makeStreamPayload({
+ message: {
+ type: "whisper-abort",
+ payload: {},
+ },
+ });
+ res.write(payload);
+ res.statusCode = 200;
+ res.end();
+ return;
+ }
+ console.error(e);
+ res.statusCode = 500;
+ res.end(JSON.stringify({ error: (e as Error).message }));
+ }
+};
+
+export const handleCancelTranscription = async (
+ req: IncomingMessage,
+ res: ServerResponse,
+) => {
+ try {
+ currentSignal.abort();
+ res.statusCode = 200;
+ res.end();
+ } catch (e) {
+ console.error(e);
+ res.statusCode = 500;
+ res.end(JSON.stringify({ error: (e as Error).message }));
+ }
+};
+
+export const handleVideoUpload = async (
+ req: IncomingMessage,
+ res: ServerResponse,
+) => {
+ const url = req.url as string;
+ const params = new URLSearchParams(url.substring(1));
+ const endDateAsString = params.get("endDateAsString");
+ const folder = params.get("folder");
+ const prefix = params.get("prefix");
+ const extension = params.get("extension");
+ const expectedFrames = Number(params.get("expectedFrames"));
+ try {
+ if (typeof prefix !== "string") {
+ throw new Error("No `prefix` provided");
+ }
+
+ if (typeof endDateAsString !== "string") {
+ throw new Error("No `endDate` provided");
+ }
+
+ if (typeof folder !== "string") {
+ throw new Error("No `folder` provided");
+ }
+
+ if (typeof expectedFrames !== "number") {
+ throw new Error("No `expectedFrames` provided");
+ }
+
+ const file = `${prefix}${endDateAsString}.${extension}`;
+
+ const publicDir = path.join(process.cwd(), "public");
+ const folderPath = path.join(publicDir, folder);
+ const filePath = path.join(folderPath, file);
+
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+
+ const writeStream = createWriteStream(filePath);
+
+ req.pipe(writeStream);
+
+ await new Promise<void>((resolve) =>
+ writeStream.on("finish", () => {
+ resolve();
+ }),
+ );
+
+ res.statusCode = 200;
+ res.end();
+ } catch (e) {
+ console.error(e);
+ res.statusCode = 500;
+ res.end(JSON.stringify({ error: (e as Error).message }));
+ }
+};
diff --git a/packages/template-recorder/src/App.css b/packages/template-recorder/src/App.css
new file mode 100644
index 0000000000..b550f2b158
--- /dev/null
+++ b/packages/template-recorder/src/App.css
@@ -0,0 +1,46 @@
+* {
+ box-sizing: border-box;
+ color: white;
+}
+
+#root {
+ width: 100%;
+ height: 100%;
+ color: white;
+}
+
+.spinner {
+ display: flex;
+ position: absolute;
+}
+
+.spinner-item {
+ width: 5px;
+ height: 5px;
+ background-color: white; /* Change the color as needed */
+ border-radius: 50%;
+ margin: 0 5px;
+ animation: bounce 1.4s infinite ease-in-out;
+}
+
+@keyframes bounce {
+ 0%,
+ 100% {
+ transform: translateY(0);
+ }
+ 50% {
+ transform: translateY(-10px);
+ }
+}
+
+.loader {
+ width: 12px;
+ height: 12px;
+ border: 2px solid #fff;
+ border-bottom-color: transparent;
+ border-radius: 50%;
+ display: inline-block;
+ box-sizing: border-box;
+ animation: rotation 1.3s linear infinite;
+ margin-left: 4px;
+}
diff --git a/packages/template-recorder/src/App.tsx b/packages/template-recorder/src/App.tsx
new file mode 100644
index 0000000000..7dd1056699
--- /dev/null
+++ b/packages/template-recorder/src/App.tsx
@@ -0,0 +1,123 @@
+/* eslint-disable no-alert */
+import React, { useCallback, useMemo, useState } from "react";
+import {
+ ALTERNATIVE1_PREFIX,
+ ALTERNATIVE2_PREFIX,
+ DISPLAY_PREFIX,
+ WEBCAM_PREFIX,
+} from "../config/cameras";
+import "./App.css";
+import type { RecordingStatus } from "./RecordButton";
+import { RecordingView } from "./RecordingView";
+import { TopBar } from "./TopBar";
+import { WaitingForDevices } from "./WaitingForDevices";
+import { EnsureBrowserSupport } from "./components/EnsureBrowserSupport";
+import { Button } from "./components/ui/button";
+import { MediaSourcesProvider } from "./state/media-sources";
+
+const outer: React.CSSProperties = {
+ height: "100%",
+ display: "flex",
+ flexDirection: "column",
+};
+
+const gridContainer: React.CSSProperties = {
+ display: "grid",
+ gridTemplateColumns: "repeat(2, 1fr)",
+ alignItems: "center",
+ justifyItems: "center",
+ flex: 1,
+ minWidth: 0,
+ minHeight: 0,
+ gap: 10,
+ margin: 10,
+ marginTop: 2,
+};
+
+const App = () => {
+ const [recordingStatus, setRecordingStatus] = useState<RecordingStatus>({
+ type: "idle",
+ });
+
+ const [showAllViews, setShowAllViews] = useState<boolean>(
+ localStorage.getItem("showAlternativeViews") === "true",
+ );
+
+ const dynamicGridContainer = useMemo(() => {
+ if (showAllViews) {
+ return { ...gridContainer, gridTemplateRows: "repeat(2, 1fr)" };
+ }
+
+ return { ...gridContainer, maxHeight: "50%" };
+ }, [showAllViews]);
+
+ const handleShowMore = useCallback(() => {
+ setShowAllViews(true);
+ localStorage.setItem("showAlternativeViews", "true");
+ }, []);
+
+ const handleShowLess = useCallback(() => {
+ setShowAllViews(false);
+ localStorage.setItem("showAlternativeViews", "false");
+ }, []);
+
+ return (
+ <EnsureBrowserSupport>
+ <WaitingForDevices>
+ <MediaSourcesProvider>
+ <div style={outer}>
+ <TopBar
+ setRecordingStatus={setRecordingStatus}
+ recordingStatus={recordingStatus}
+ showAllViews={showAllViews}
+ />
+ <div style={dynamicGridContainer}>
+ <RecordingView
+ showAllViews={showAllViews}
+ recordingStatus={recordingStatus}
+ prefix={WEBCAM_PREFIX}
+ />
+ <RecordingView
+ showAllViews={showAllViews}
+ recordingStatus={recordingStatus}
+ prefix={DISPLAY_PREFIX}
+ />
+ <RecordingView
+ showAllViews={showAllViews}
+ recordingStatus={recordingStatus}
+ prefix={ALTERNATIVE1_PREFIX}
+ />
+ <RecordingView
+ showAllViews={showAllViews}
+ recordingStatus={recordingStatus}
+ prefix={ALTERNATIVE2_PREFIX}
+ />
+ </div>
+
+ <div style={{ marginBottom: 10, textAlign: "center" }}>
+ {showAllViews ? (
+ <Button
+ variant={"ghost"}
+ onClick={handleShowLess}
+ style={{ margin: "0px 10px", width: 100 }}
+ >
+ Show Less
+ </Button>
+ ) : (
+ <Button
+ variant={"ghost"}
+ onClick={handleShowMore}
+ style={{ margin: "0px 10px" }}
+ >
+ Show more views
+ </Button>
+ )}
+ </div>
+ </div>
+ </MediaSourcesProvider>
+ </WaitingForDevices>
+ </EnsureBrowserSupport>
+ );
+};
+
+export default App;
diff --git a/packages/template-recorder/src/BlinkingCircle.tsx b/packages/template-recorder/src/BlinkingCircle.tsx
new file mode 100644
index 0000000000..2cd95dc7eb
--- /dev/null
+++ b/packages/template-recorder/src/BlinkingCircle.tsx
@@ -0,0 +1,31 @@
+import React, { useEffect, useState } from "react";
+
+export const BlinkingCircle: React.FC = () => {
+ const [isVisible, setIsVisible] = useState(true);
+
+ useEffect(() => {
+ const intervalId = setInterval(() => {
+ setIsVisible((prev) => !prev);
+ }, 800);
+ return () => clearInterval(intervalId);
+ }, []);
+
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ height="10px"
+ viewBox="0 0 512 512"
+ style={{ visibility: isVisible ? "visible" : "hidden" }}
+ >
+ <path fill="red" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512z" />
+ </svg>
+ );
+};
+
+export const RecordCircle: React.FC = () => {
+ return (
+ <svg xmlns="http://www.w3.org/2000/svg" height="10px" viewBox="0 0 512 512">
+ <path fill="red" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512z" />
+ </svg>
+ );
+};
diff --git a/packages/template-recorder/src/CropIndicator.tsx b/packages/template-recorder/src/CropIndicator.tsx
new file mode 100644
index 0000000000..855cbc9c0c
--- /dev/null
+++ b/packages/template-recorder/src/CropIndicator.tsx
@@ -0,0 +1,50 @@
+import React, { useMemo } from "react";
+import { AbsoluteFill } from "remotion";
+import type { Dimensions } from "../config/layout";
+import { fitElementSizeInContainer } from "../remotion/layout/fit-element";
+import { useElementSize } from "./helpers/use-element-size";
+
+export const CropIndicator: React.FC<{
+ resolution: Dimensions;
+}> = ({ resolution }) => {
+ const ref = React.useRef<HTMLDivElement>(null);
+
+ const elementSize = useElementSize(ref);
+
+ const videoSize = useMemo(() => {
+ return elementSize
+ ? fitElementSizeInContainer({
+ containerSize: elementSize,
+ elementSize: resolution,
+ })
+ : null;
+ }, [elementSize, resolution]);
+
+ const cropIndicatorRect = useMemo(() => {
+ return videoSize
+ ? fitElementSizeInContainer({
+ containerSize: videoSize,
+ elementSize: {
+ width: 350,
+ height: 400,
+ },
+ })
+ : null;
+ }, [videoSize]);
+
+ const cropIndicator: React.CSSProperties = useMemo(() => {
+ return {
+ border: "2px solid #F7D449",
+ borderRadius: 10,
+ ...cropIndicatorRect,
+ };
+ }, [cropIndicatorRect]);
+
+ return (
+ <AbsoluteFill ref={ref}>
+ <AbsoluteFill style={videoSize ?? undefined}>
+ <AbsoluteFill style={cropIndicator} />
+ </AbsoluteFill>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/src/DeviceItem.tsx b/packages/template-recorder/src/DeviceItem.tsx
new file mode 100644
index 0000000000..7d6e297fa7
--- /dev/null
+++ b/packages/template-recorder/src/DeviceItem.tsx
@@ -0,0 +1,98 @@
+import React from "react";
+import styles from "./deviceitem.module.css";
+
+const deviceRow: React.CSSProperties = {
+ display: "flex",
+ flexDirection: "row",
+ alignItems: "center",
+ width: "100%",
+ paddingTop: 10,
+ paddingBottom: 10,
+ borderBottom: "1px solid #333",
+ cursor: "pointer",
+ paddingRight: 10,
+};
+
+const spacer: React.CSSProperties = {
+ width: 8,
+};
+
+const label: React.CSSProperties = {
+ fontSize: 14,
+};
+
+const iconStyle: React.CSSProperties = {
+ width: 16,
+ height: 16,
+};
+
+const CameraIcon: React.FC = () => {
+ return (
+ <svg style={iconStyle} viewBox="0 0 576 512">
+ <path
+ fill="#eee"
+ d="M0 128C0 92.7 28.7 64 64 64H320c35.3 0 64 28.7 64 64V384c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V128zM559.1 99.8c10.4 5.6 16.9 16.4 16.9 28.2V384c0 11.8-6.5 22.6-16.9 28.2s-23 5-32.9-1.6l-96-64L416 337.1V320 192 174.9l14.2-9.5 96-64c9.8-6.5 22.4-7.2 32.9-1.6z"
+ />
+ </svg>
+ );
+};
+
+const MicIcon: React.FC = () => {
+ return (
+ <svg style={iconStyle} viewBox="0 0 384 512">
+ <path
+ fill="#eee"
+ d="M192 0C139 0 96 43 96 96V256c0 53 43 96 96 96s96-43 96-96V96c0-53-43-96-96-96zM64 216c0-13.3-10.7-24-24-24s-24 10.7-24 24v40c0 89.1 66.2 162.7 152 174.4V464H120c-13.3 0-24 10.7-24 24s10.7 24 24 24h72 72c13.3 0 24-10.7 24-24s-10.7-24-24-24H216V430.4c85.8-11.7 152-85.3 152-174.4V216c0-13.3-10.7-24-24-24s-24 10.7-24 24v40c0 70.7-57.3 128-128 128s-128-57.3-128-128V216z"
+ />
+ </svg>
+ );
+};
+
+export const DisplayIcon: React.FC = () => {
+ return (
+ <svg style={iconStyle} viewBox="0 0 576 512">
+ <path
+ fill="#eee"
+ d="M64 0C28.7 0 0 28.7 0 64V352c0 35.3 28.7 64 64 64H240l-10.7 32H160c-17.7 0-32 14.3-32 32s14.3 32 32 32H416c17.7 0 32-14.3 32-32s-14.3-32-32-32H346.7L336 416H512c35.3 0 64-28.7 64-64V64c0-35.3-28.7-64-64-64H64zM512 64V352H64V64H512z"
+ />
+ </svg>
+ );
+};
+
+const CheckIcon: React.FC = () => {
+ return (
+ <svg style={iconStyle} viewBox="0 0 512 512">
+ <path
+ fill="#eee"
+ d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM241 337l-17 17-17-17-80-80L161 223l63 63L351 159 385 193 241 337z"
+ />
+ </svg>
+ );
+};
+
+export const DeviceItem: React.FC<{
+ deviceLabel: string;
+ type: "camera" | "microphone" | "screen";
+ handleClick: () => void;
+ selected: boolean;
+}> = ({ deviceLabel, type, handleClick, selected }) => {
+ return (
+ <div className={styles.item} onClick={handleClick} style={deviceRow}>
+ <div
+ style={{
+ width: 36,
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
+ {selected && <CheckIcon></CheckIcon>}
+ </div>
+ {type === "camera" ? <CameraIcon></CameraIcon> : null}
+ {type === "microphone" ? <MicIcon></MicIcon> : null}
+ {type === "screen" ? <DisplayIcon></DisplayIcon> : null}
+ <div style={spacer}></div> <span style={label}>{deviceLabel}</span>
+ <div style={{ flex: 1 }}></div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/DevicePermission.tsx b/packages/template-recorder/src/DevicePermission.tsx
new file mode 100644
index 0000000000..d32345be11
--- /dev/null
+++ b/packages/template-recorder/src/DevicePermission.tsx
@@ -0,0 +1,316 @@
+import type { ReactNode } from "react";
+import React, { useCallback, useEffect, useMemo, useState } from "react";
+import { PermissionError } from "./PermissionError";
+import { CircleSpinner } from "./components/Spinner";
+
+type PermissionState = "granted" | "denied" | "prompt" | "initial";
+
+const BORDERRADIUS = 10;
+const largeContainer: React.CSSProperties = {
+ display: "flex",
+ alignItems: "center",
+ flexDirection: "column",
+ justifyContent: "center",
+ height: "100%",
+};
+
+const explanationWrapper: React.CSSProperties = {
+ display: "flex",
+ textAlign: "start",
+ paddingLeft: 10,
+};
+
+const explanationContainer: React.CSSProperties = {
+ display: "flex",
+ justifyContent: "flex-start",
+ flexDirection: "column",
+ maxWidth: 800,
+ lineHeight: 2,
+};
+
+const innerContainer: React.CSSProperties = {
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ flexDirection: "row",
+};
+const container: React.CSSProperties = {
+ borderRadius: BORDERRADIUS,
+ padding: 12,
+ margin: 20,
+};
+
+const title: React.CSSProperties = {
+ display: "flex",
+ justifyContent: "center",
+ fontSize: "1rem",
+};
+
+const textContainer: React.CSSProperties = {
+ paddingLeft: 20,
+ paddingRight: 20,
+ paddingTop: 10,
+ paddingBottom: 10,
+ fontSize: 13,
+};
+
+const peripheralContainer: React.CSSProperties = {
+ display: "flex",
+ flexDirection: "column",
+ backgroundColor: "#242424",
+ borderRadius: BORDERRADIUS,
+ margin: 10,
+ padding: 16,
+ minWidth: 200,
+ minHeight: 150,
+};
+
+const Permission: React.FC<{
+ type: "audio" | "video";
+ deviceState: PermissionState;
+ setDeviceState: (newState: PermissionState) => void;
+ isInitialState: boolean;
+ onNoDevicesFound: () => void;
+}> = ({
+ type,
+ deviceState,
+ setDeviceState,
+ isInitialState,
+ onNoDevicesFound,
+}) => {
+ const dynamicStyle: React.CSSProperties = useMemo(() => {
+ return {
+ display: "flex",
+ justifyContent: "flex-end",
+ alignItems: "center",
+ color: deviceState === "denied" ? "red" : "white",
+ };
+ }, [deviceState]);
+
+ const microphoneIcon = (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 384 512"
+ style={{ maxHeight: 50 }}
+ >
+ <path
+ fill="white"
+ d="M192 0C139 0 96 43 96 96V256c0 53 43 96 96 96s96-43 96-96V96c0-53-43-96-96-96zM64 216c0-13.3-10.7-24-24-24s-24 10.7-24 24v40c0 89.1 66.2 162.7 152 174.4V464H120c-13.3 0-24 10.7-24 24s10.7 24 24 24h72 72c13.3 0 24-10.7 24-24s-10.7-24-24-24H216V430.4c85.8-11.7 152-85.3 152-174.4V216c0-13.3-10.7-24-24-24s-24 10.7-24 24v40c0 70.7-57.3 128-128 128s-128-57.3-128-128V216z"
+ />
+ </svg>
+ );
+
+ const cameraIcon = (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 576 512 "
+ style={{ maxHeight: 40 }}
+ >
+ <path
+ fill="white"
+ d="M0 128C0 92.7 28.7 64 64 64H320c35.3 0 64 28.7 64 64V384c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V128zM559.1 99.8c10.4 5.6 16.9 16.4 16.9 28.2V384c0 11.8-6.5 22.6-16.9 28.2s-23 5-32.9-1.6l-96-64L416 337.1V320 192 174.9l14.2-9.5 96-64c9.8-6.5 22.4-7.2 32.9-1.6z"
+ />
+ </svg>
+ );
+
+ const handleError = useCallback(
+ (error: Error) => {
+ if (
+ error.message.includes("Requested device not found") ||
+ error.message.includes("The object can not be found here")
+ ) {
+ onNoDevicesFound();
+ return;
+ }
+
+ setDeviceState("denied");
+ },
+ [onNoDevicesFound, setDeviceState],
+ );
+
+ const run = useCallback(async () => {
+ const name =
+ type === "audio"
+ ? ("microphone" as PermissionName)
+ : ("camera" as PermissionName);
+ const result = await navigator.permissions
+ .query({ name })
+ .then((res) => res)
+ .catch((e) => {
+ // firefox doesn't support microphone and camera as valid property
+ if (e instanceof TypeError) {
+ return null;
+ }
+
+ console.log(e);
+ return null;
+ });
+ // firefox case
+ if (!result && deviceState === "initial") {
+ // probe for permission
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({
+ audio: true,
+ video: true,
+ });
+ setDeviceState("prompt");
+ stream.getVideoTracks().forEach((track) => track.stop());
+ stream.getAudioTracks().forEach((track) => track.stop());
+ } catch (err) {
+ console.log("Error on getUserMedia(", err);
+ handleError(err as Error);
+ return;
+ }
+
+ setDeviceState("granted");
+ return;
+ }
+
+ if (!result) {
+ return;
+ }
+
+ setDeviceState(result.state);
+
+ if (result.state === "prompt" && type === "audio") {
+ try {
+ await navigator.mediaDevices.getUserMedia({
+ video: true,
+ audio: true,
+ });
+ } catch (err) {
+ console.log("Error on getUserMedia()", err);
+ handleError(err as Error);
+ return;
+ }
+ }
+
+ if (result.state === "granted") {
+ setDeviceState("granted");
+ } else if (result.state === "denied") {
+ setDeviceState("denied");
+ }
+ }, [deviceState, handleError, setDeviceState, type]);
+
+ useEffect(() => {
+ run();
+ }, [run]);
+
+ const accessInformation = useMemo(() => {
+ if (deviceState === "prompt") return "Access requested";
+ if (deviceState === "denied") return "Access denied";
+ if (deviceState === "granted") return "Access granted";
+ }, [deviceState]);
+
+ if (isInitialState) return null;
+ return (
+ <div style={peripheralContainer}>
+ <div
+ style={{
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ flex: 1,
+ }}
+ >
+ {type === "audio" ? microphoneIcon : cameraIcon}
+ </div>
+
+ <div
+ style={{
+ display: "flex",
+ flexDirection: "row",
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
+ <div style={{ width: 16 }} />
+ <div style={dynamicStyle}>{accessInformation} </div>
+ {deviceState === "prompt" ? (
+ <CircleSpinner />
+ ) : (
+ <div style={{ width: 16 }} />
+ )}
+ </div>
+ </div>
+ );
+};
+
+export const DevicePermission: React.FC<{ children: ReactNode }> = ({
+ children,
+}) => {
+ const [noDeviceFound, setNoDeviceFound] = useState(false);
+ const [audioState, setAudioState] = useState<PermissionState>("initial");
+ const [videoState, setVideoState] = useState<PermissionState>("initial");
+
+ const isInitialState = useMemo(() => {
+ return audioState === "initial" || videoState === "initial";
+ }, [audioState, videoState]);
+
+ const dynamicContainer: React.CSSProperties = useMemo(() => {
+ return {
+ ...container,
+ borderColor: isInitialState ? "black" : "white",
+ };
+ }, [isInitialState]);
+
+ const onNoDevicesFound = useCallback(() => {
+ setNoDeviceFound(true);
+ }, []);
+
+ if (noDeviceFound) {
+ return <PermissionError />;
+ }
+
+ if (audioState === "granted" && videoState === "granted") {
+ return <>{children}</>;
+ }
+
+ return (
+ <div style={largeContainer}>
+ <div style={dynamicContainer}>
+ <div style={innerContainer}>
+ <Permission
+ isInitialState={isInitialState}
+ type="audio"
+ deviceState={audioState}
+ setDeviceState={(newState) => setAudioState(newState)}
+ onNoDevicesFound={onNoDevicesFound}
+ />
+ <Permission
+ isInitialState={isInitialState}
+ type="video"
+ deviceState={videoState}
+ setDeviceState={(newState) => setVideoState(newState)}
+ onNoDevicesFound={onNoDevicesFound}
+ />
+ </div>
+ {isInitialState ? null : (
+ <div style={textContainer}>
+ <div style={explanationContainer}>
+ <div style={title}>
+ This app requires access to your microphone and camera.
+ </div>
+ <div style={explanationWrapper}>
+ 1. Click on the padlock/info icon next to the web address in
+ your browser&apos;s address bar.
+ </div>
+ <div style={explanationWrapper}>
+ 2. In the dropdown menu that appears, locate the
+ &apos;Permissions&apos; or &apos;Site settings&apos; option.
+ </div>
+ <div style={explanationWrapper}>
+ 3. Look for &apos;Camera&apos; and &apos;Microphone&apos;
+ settings and ensure they are set to &apos;Allow&apos; or
+ &apos;Ask&apos;
+ </div>
+ <div style={explanationWrapper}>
+ 4. Refresh the page if necessary to apply the changes.
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/Logo.tsx b/packages/template-recorder/src/Logo.tsx
new file mode 100644
index 0000000000..13807869d5
--- /dev/null
+++ b/packages/template-recorder/src/Logo.tsx
@@ -0,0 +1,10 @@
+import React from "react";
+
+const style: React.CSSProperties = {
+ height: 48 / 1.8,
+ width: 246 / 1.8,
+};
+
+export const Logo: React.FC = () => {
+ return <img style={style} src="/logo.png" />;
+};
diff --git a/packages/template-recorder/src/PermissionError.tsx b/packages/template-recorder/src/PermissionError.tsx
new file mode 100644
index 0000000000..e9e89bf74d
--- /dev/null
+++ b/packages/template-recorder/src/PermissionError.tsx
@@ -0,0 +1,21 @@
+import React from "react";
+
+const outer: React.CSSProperties = {
+ width: "100%",
+ position: "absolute",
+ height: "100%",
+ justifyContent: "center",
+ alignItems: "center",
+ display: "flex",
+ fontSize: "0.9em",
+ color: "#ddd",
+};
+
+export const PermissionError: React.FC = () => {
+ return (
+ <div style={outer}>
+ This device does not seem to be able to capture both video and audio.
+ <br /> Is there a camera and microphone connected?
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/PrefixAndResolution.tsx b/packages/template-recorder/src/PrefixAndResolution.tsx
new file mode 100644
index 0000000000..a73fb9367d
--- /dev/null
+++ b/packages/template-recorder/src/PrefixAndResolution.tsx
@@ -0,0 +1,42 @@
+import React from "react";
+import { ResolutionAndFps } from "./Stream";
+
+export const PrefixLabel: React.FC<{
+ prefix: string;
+}> = ({ prefix }) => {
+ return (
+ <div
+ style={{
+ fontSize: 13,
+ textAlign: "left",
+ }}
+ >
+ <span style={{ textTransform: "uppercase" }}>{prefix}</span>
+ </div>
+ );
+};
+
+export const Resolution: React.FC<{
+ resolution: ResolutionAndFps;
+}> = ({ resolution }) => {
+ return (
+ <>
+ <span
+ style={{
+ whiteSpace: "nowrap",
+ display: "inline-flex",
+ alignItems: "center",
+ }}
+ >
+ <span
+ style={{
+ color: "rgba(255, 255, 255, 0.5)",
+ }}
+ >
+ {resolution.width}x{resolution.height},{" "}
+ {Math.round(resolution.fps * 100) / 100} FPS
+ </span>
+ </span>
+ </>
+ );
+};
diff --git a/packages/template-recorder/src/RecordButton.tsx b/packages/template-recorder/src/RecordButton.tsx
new file mode 100644
index 0000000000..5131785704
--- /dev/null
+++ b/packages/template-recorder/src/RecordButton.tsx
@@ -0,0 +1,234 @@
+import { CameraIcon, MicIcon } from "lucide-react";
+import React, { useCallback, useEffect, useMemo } from "react";
+import { FPS } from "../config/fps";
+import { truthy } from "../remotion/helpers/truthy";
+import { RecordCircle } from "./BlinkingCircle";
+import { ProcessStatus } from "./components/ProcessingStatus";
+import { Button } from "./components/ui/button";
+import { Prefix } from "./helpers/prefixes";
+import {
+ FinishedRecording,
+ startMediaRecorder,
+} from "./helpers/start-media-recorder";
+import { useKeyPress } from "./helpers/use-key-press";
+import { useMediaSources } from "./state/media-sources";
+import { visibleByDefault } from "./state/visible-views";
+
+export type CurrentRecorder = {
+ recorder: MediaRecorder;
+ stopAndWaitUntilDone: () => Promise<FinishedRecording>;
+ mimeType: string;
+};
+
+export type RecordingStatus =
+ | {
+ type: "idle";
+ }
+ | {
+ type: "recording";
+ ongoing: OngoingRecording;
+ }
+ | {
+ type: "recording-finished";
+ blobs: FinishedRecording[];
+ expectedFrames: number;
+ endDate: number;
+ };
+
+type OngoingRecording = {
+ startDate: number;
+ recorders: CurrentRecorder[];
+};
+
+export const RecordButton: React.FC<{
+ recordingStatus: RecordingStatus;
+ setRecordingStatus: React.Dispatch<React.SetStateAction<RecordingStatus>>;
+ showAllViews: boolean;
+ processingStatus: ProcessStatus | null;
+}> = ({
+ setRecordingStatus,
+ recordingStatus,
+ showAllViews,
+ processingStatus,
+}) => {
+ const discardVideos = useCallback(async () => {
+ if (recordingStatus.type !== "recording-finished") {
+ throw new Error("Recording not finished");
+ }
+ for (const blob of recordingStatus.blobs) {
+ await blob.releaseData();
+ }
+
+ setRecordingStatus({ type: "idle" });
+ }, [recordingStatus, setRecordingStatus]);
+
+ const mediaSources = useMediaSources().mediaSources;
+
+ const activeSources = useMemo(() => {
+ return Object.entries(mediaSources).filter(([prefix, source]) => {
+ return (
+ (showAllViews || visibleByDefault[prefix as Prefix]) &&
+ source.streamState.type === "loaded"
+ );
+ });
+ }, [mediaSources, showAllViews]);
+
+ const videoDeviceCount = useMemo(() => {
+ return activeSources.filter(([, source]) => {
+ return source.videoDevice !== null;
+ }).length;
+ }, [activeSources]);
+ const audioDeviceCount = useMemo(() => {
+ return activeSources.filter(([, source]) => {
+ return source.audioDevice !== null;
+ }).length;
+ }, [activeSources]);
+
+ const start = useCallback(async () => {
+ const startDate = Date.now();
+ const recorders = (
+ await Promise.all(
+ activeSources.map(
+ ([prefix, source]): Promise<CurrentRecorder | null> => {
+ return startMediaRecorder({
+ prefix: prefix as Prefix,
+ source: source.streamState,
+ timestamp: startDate,
+ });
+ },
+ ),
+ )
+ ).filter(truthy);
+
+ return setRecordingStatus({
+ type: "recording",
+ ongoing: { recorders: recorders, startDate },
+ });
+ }, [activeSources, setRecordingStatus]);
+
+ const onStop = useCallback(async () => {
+ if (recordingStatus.type !== "recording") {
+ return;
+ }
+
+ const blobs = await Promise.all(
+ recordingStatus.ongoing.recorders.map((r) => r.stopAndWaitUntilDone()),
+ );
+
+ const endDate = Date.now();
+ const expectedFrames =
+ ((endDate - recordingStatus.ongoing.startDate) / 1000) * FPS;
+
+ setRecordingStatus({
+ type: "recording-finished",
+ blobs,
+ expectedFrames,
+ endDate,
+ });
+ }, [recordingStatus, setRecordingStatus]);
+
+ useEffect(() => {
+ return () => {
+ if (recordingStatus.type === "recording") {
+ recordingStatus.ongoing.recorders.forEach((r) => {
+ r.recorder.stop();
+ });
+ }
+ };
+ }, [recordingStatus]);
+
+ const disabled =
+ mediaSources.webcam.streamState.type !== "loaded" ||
+ mediaSources.webcam.streamState.stream.getAudioTracks().length === 0 ||
+ processingStatus !== null;
+
+ const onPressR = useCallback(() => {
+ if (disabled) {
+ return;
+ }
+
+ const dialog = document.querySelector('[role="dialog"]');
+
+ if (
+ (document.activeElement && document.activeElement.tagName === "input") ||
+ dialog
+ ) {
+ return;
+ }
+
+ if (recordingStatus.type === "recording") {
+ onStop();
+ } else if (recordingStatus.type === "idle") {
+ start();
+ }
+ }, [onStop, disabled, recordingStatus.type, start]);
+
+ const onDiscardAndRetake = useCallback(async () => {
+ await discardVideos();
+ start();
+ }, [discardVideos, start]);
+
+ useKeyPress({ keys: ["r"], callback: onPressR, metaKey: false });
+
+ if (recordingStatus.type === "recording") {
+ return (
+ <>
+ <Button
+ variant="outline"
+ type="button"
+ style={{ display: "flex", alignItems: "center", gap: 10 }}
+ title="Press R to stop recording"
+ onClick={onStop}
+ >
+ Stop recording
+ </Button>
+ </>
+ );
+ }
+
+ return (
+ <div
+ title={
+ disabled
+ ? "A webcam and an audio source have to be selected to start the recording"
+ : undefined
+ }
+ >
+ <Button
+ variant="outline"
+ type="button"
+ disabled={disabled}
+ title="Press R to start recording"
+ className="flex flex-row items-center pl-3 pr-0 py-0"
+ onClick={
+ recordingStatus.type === "recording-finished"
+ ? onDiscardAndRetake
+ : start
+ }
+ >
+ <RecordCircle />
+ <div className="w-2"></div>
+ <div>
+ {disabled
+ ? "Select audio+video to record"
+ : recordingStatus.type === "recording-finished"
+ ? "Discard and retake"
+ : "Start recording"}
+ </div>
+ <div className="w-3"></div>
+ {videoDeviceCount > 0 && !disabled && (
+ <div className="flex flex-row items-center gap-1 border-l-[1px] h-full px-2">
+ <CameraIcon className="w-5" />
+ <div>{videoDeviceCount}</div>
+ </div>
+ )}
+ {audioDeviceCount > 0 && !disabled && (
+ <div className="flex flex-row items-center gap-1 border-l-[1px] h-full px-2">
+ <MicIcon className="w-5" />
+ <div>{audioDeviceCount}</div>
+ </div>
+ )}
+ </Button>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/RecordingView.tsx b/packages/template-recorder/src/RecordingView.tsx
new file mode 100644
index 0000000000..29724f2d4e
--- /dev/null
+++ b/packages/template-recorder/src/RecordingView.tsx
@@ -0,0 +1,346 @@
+/* eslint-disable no-negated-condition */
+/* eslint-disable no-alert */
+import { useCallback, useMemo, useState } from "react";
+import { WEBCAM_PREFIX } from "../config/cameras";
+import { CropIndicator } from "./CropIndicator";
+import { PrefixLabel } from "./PrefixAndResolution";
+import { RecordingStatus } from "./RecordButton";
+import { ResolutionLimiter } from "./ResolutionLimiter";
+import { ToggleRotate } from "./Rotate";
+import { ResolutionAndFps, Stream } from "./Stream";
+import { ToggleCrop } from "./ToggleCrop";
+import { useDevices } from "./WaitingForDevices";
+import { ClearCurrentVideo } from "./components/ClearCurrentVideo";
+import { CurrentAudio } from "./components/CurrentAudio";
+import { CurrentVideo } from "./components/CurrentVideo";
+import { Divider } from "./components/Divider";
+import { StreamPicker, getDeviceLabel } from "./components/StreamPicker";
+import { VolumeMeter } from "./components/VolumeMeter";
+import { canRotateCamera } from "./helpers/can-rotate-camera";
+import {
+ MaxResolution,
+ getMaxResolutionOfDevice,
+} from "./helpers/get-max-resolution-of-device";
+import {
+ SizeConstraint,
+ getSelectedVideoSource,
+} from "./helpers/get-selected-video-source";
+import { Prefix } from "./helpers/prefixes";
+import { setPreferredDeviceForPrefix } from "./preferred-device-localstorage";
+import { getPreferredResolutionForDevice } from "./preferred-resolution";
+import { useMediaSources } from "./state/media-sources";
+import { visibleByDefault } from "./state/visible-views";
+const viewContainer: React.CSSProperties = {
+ display: "flex",
+ flexDirection: "column",
+ margin: 10,
+ backgroundColor: "#242424",
+ borderRadius: 10,
+ overflow: "hidden",
+ width: "100%",
+ height: "100%",
+ maxHeight: "100%",
+ maxWidth: "100%",
+ position: "relative",
+};
+
+const topBar: React.CSSProperties = {
+ display: "flex",
+ alignItems: "center",
+ paddingLeft: 10,
+};
+
+const streamViewport: React.CSSProperties = {
+ flex: 1,
+ position: "relative",
+};
+
+const localStorageKey = "showCropIndicator";
+
+const InnerRecordingView: React.FC<{
+ prefix: Prefix;
+ recordingStatus: RecordingStatus;
+}> = ({ prefix, recordingStatus }) => {
+ const { mediaSources, setAudioDevice, setVideoDevice } = useMediaSources();
+ const mediaStream = mediaSources[prefix];
+
+ const initialCropIndicatorState = useMemo(() => {
+ return (
+ localStorage.getItem(localStorageKey) === "true" &&
+ prefix === WEBCAM_PREFIX
+ );
+ }, [prefix]);
+
+ const [showCropIndicator, setShowCropIndicator] = useState(
+ initialCropIndicatorState,
+ );
+
+ const [showPickerPreference, setShowPicker] = useState(
+ () => !mediaStream.videoDevice && !mediaStream.audioDevice,
+ );
+
+ const recordAudio = prefix === WEBCAM_PREFIX;
+ const [resolution, setResolution] = useState<ResolutionAndFps | null>(null);
+ const [preferPortrait, setPreferPortrait] = useState(false);
+ const [sizeConstraint, setSizeConstraint] = useState<SizeConstraint>(() =>
+ getPreferredResolutionForDevice(mediaStream.videoDevice),
+ );
+
+ const onToggleCrop = useCallback(() => {
+ setShowCropIndicator((prev) => {
+ window.localStorage.setItem(localStorageKey, String(!prev));
+ return !prev;
+ });
+ }, []);
+
+ const onToggleRotate = useCallback(() => {
+ setPreferPortrait((prev) => {
+ return !prev;
+ });
+ }, []);
+
+ const selectScreenWithoutAudio = useCallback(async () => {
+ setVideoDevice(prefix, "display-without-audio");
+ setShowPicker(false);
+ }, [prefix, setVideoDevice]);
+ const selectScreenWithAudio = useCallback(async () => {
+ setVideoDevice(prefix, "display-with-audio");
+ setShowPicker(false);
+ }, [prefix, setVideoDevice]);
+
+ const devices = useDevices();
+
+ const activeVideoDevice = useMemo(() => {
+ return devices.find((d) => d.deviceId === mediaStream.videoDevice);
+ }, [devices, mediaStream.videoDevice]);
+ const activeAudioDevice = useMemo(() => {
+ return devices.find((d) => d.deviceId === mediaStream.audioDevice);
+ }, [devices, mediaStream.audioDevice]);
+
+ const maxResolution = useMemo(() => {
+ if (!activeVideoDevice) {
+ return null;
+ }
+
+ return getMaxResolutionOfDevice(activeVideoDevice);
+ }, [activeVideoDevice]);
+
+ const selectedVideoSource = useMemo(() => {
+ if (mediaStream.videoDevice === "display-without-audio") {
+ return { type: "display-without-audio" as const };
+ }
+ if (mediaStream.videoDevice === "display-with-audio") {
+ return { type: "display-with-audio" as const };
+ }
+
+ if (!activeVideoDevice) {
+ return null;
+ }
+
+ return getSelectedVideoSource({
+ device: activeVideoDevice,
+ resolutionConstraint: sizeConstraint,
+ maxResolution,
+ });
+ }, [
+ activeVideoDevice,
+ maxResolution,
+ mediaStream.videoDevice,
+ sizeConstraint,
+ ]);
+
+ const videoDeviceLabel = useMemo(() => {
+ if (mediaStream.videoDevice === "display-without-audio") {
+ return "Screen Share";
+ }
+ if (mediaStream.videoDevice === "display-with-audio") {
+ return "Screen Share with audio";
+ }
+
+ if (!activeVideoDevice) {
+ return null;
+ }
+
+ return getDeviceLabel(activeVideoDevice);
+ }, [activeVideoDevice, mediaStream.videoDevice]);
+
+ const audioDeviceLabel = useMemo(() => {
+ if (!activeAudioDevice) {
+ return null;
+ }
+
+ return getDeviceLabel(activeAudioDevice);
+ }, [activeAudioDevice]);
+
+ const cameraRotateable = useMemo(() => {
+ return canRotateCamera({
+ selectedSource: selectedVideoSource,
+ preferPortrait,
+ resolution,
+ });
+ }, [preferPortrait, resolution, selectedVideoSource]);
+
+ const onPickVideo = useCallback(
+ (device: MediaDeviceInfo) => {
+ setVideoDevice(prefix, device.deviceId);
+ setPreferredDeviceForPrefix(prefix, "video", device.deviceId);
+ if (recordAudio && !mediaStream.audioDevice) {
+ return;
+ }
+ setShowPicker(false);
+ },
+ [mediaStream.audioDevice, prefix, recordAudio, setVideoDevice],
+ );
+
+ const onPickAudio = useCallback(
+ (device: MediaDeviceInfo) => {
+ setAudioDevice(prefix, device.deviceId);
+ setPreferredDeviceForPrefix(prefix, "audio", device.deviceId);
+ if (!mediaStream.videoDevice) {
+ return;
+ }
+ setShowPicker(false);
+ },
+ [mediaStream.videoDevice, prefix, setAudioDevice],
+ );
+
+ const clear = useCallback(() => {
+ setVideoDevice(prefix, null);
+ setAudioDevice(prefix, null);
+ setPreferredDeviceForPrefix(prefix, "video", null);
+ setShowPicker(true);
+ setResolution(null);
+ }, [prefix, setAudioDevice, setVideoDevice]);
+
+ const [resolutionLimiterOpen, setResolutionLimiterOpen] = useState(false);
+
+ const canShowResolutionLimiter = Boolean(
+ selectedVideoSource?.type === "display-without-audio" ||
+ selectedVideoSource?.type === "display-with-audio"
+ ? false
+ : videoDeviceLabel && activeVideoDevice && maxResolution,
+ );
+
+ const hasSelectedVideoOrAudio = Boolean(
+ mediaStream.videoDevice || mediaStream.audioDevice,
+ );
+
+ const showPicker =
+ showPickerPreference && recordingStatus.type !== "recording";
+ const togglePicker = useCallback(() => {
+ setShowPicker((prev) => !prev);
+ }, []);
+
+ return (
+ <div
+ style={viewContainer}
+ data-recording={Boolean(
+ recordingStatus.type === "recording" &&
+ hasSelectedVideoOrAudio &&
+ mediaStream.streamState.type === "loaded",
+ )}
+ className="outline-red-600 outline-0 data-[recording=true]:outline-2 outline"
+ >
+ <div style={topBar}>
+ <div style={{ width: 10 }}></div>
+ <PrefixLabel prefix={prefix} />
+ <div style={{ width: 15 }}></div>
+ <Divider></Divider>
+ <CurrentVideo
+ resolution={resolution}
+ label={videoDeviceLabel ?? "No video selected"}
+ isScreenshare={
+ selectedVideoSource?.type === "display-without-audio" ||
+ selectedVideoSource?.type === "display-with-audio"
+ }
+ onClick={togglePicker}
+ setResolutionLimiterOpen={setResolutionLimiterOpen}
+ canShowResolutionLimiter={canShowResolutionLimiter}
+ disabled={recordingStatus.type === "recording"}
+ ></CurrentVideo>
+ {selectedVideoSource && recordingStatus.type !== "recording" ? (
+ <ClearCurrentVideo onClick={clear} />
+ ) : null}
+ {prefix === WEBCAM_PREFIX ? (
+ <>
+ <Divider></Divider>
+ <CurrentAudio
+ disabled={recordingStatus.type === "recording"}
+ onClick={togglePicker}
+ label={audioDeviceLabel}
+ />
+ </>
+ ) : null}
+ {prefix === WEBCAM_PREFIX ? (
+ <ToggleCrop
+ pressed={showCropIndicator}
+ onPressedChange={onToggleCrop}
+ />
+ ) : null}
+ {cameraRotateable ? (
+ <ToggleRotate
+ pressed={preferPortrait}
+ onPressedChange={onToggleRotate}
+ disabled={recordingStatus.type === "recording"}
+ />
+ ) : null}
+ </div>
+ {prefix === WEBCAM_PREFIX ? (
+ <VolumeMeter mediaStream={mediaStream.streamState} />
+ ) : null}
+ <div style={streamViewport}>
+ <Stream
+ selectedAudioSource={mediaStream.audioDevice}
+ selectedVideoSource={selectedVideoSource}
+ recordAudio={recordAudio}
+ setResolution={setResolution}
+ prefix={prefix}
+ preferPortrait={preferPortrait}
+ clear={clear}
+ />
+ {showCropIndicator && resolution && !showPicker ? (
+ <CropIndicator resolution={resolution} />
+ ) : null}
+ {showPicker ? (
+ <StreamPicker
+ onPickVideo={onPickVideo}
+ onPickAudio={onPickAudio}
+ canSelectAudio={recordAudio}
+ canSelectScreen={prefix !== WEBCAM_PREFIX}
+ onPickScreenWithoutAudio={selectScreenWithoutAudio}
+ onPickScreenWithAudio={selectScreenWithAudio}
+ selectedAudioDevice={mediaStream.audioDevice}
+ selectedVideoDevice={mediaStream.videoDevice}
+ clear={clear}
+ canClear={prefix !== WEBCAM_PREFIX}
+ />
+ ) : null}
+ {canShowResolutionLimiter ? (
+ <ResolutionLimiter
+ sizeConstraint={sizeConstraint}
+ setSizeConstraint={setSizeConstraint}
+ maxResolution={maxResolution as MaxResolution}
+ deviceName={videoDeviceLabel as string}
+ deviceId={(activeVideoDevice as MediaDeviceInfo).deviceId}
+ open={resolutionLimiterOpen}
+ setOpen={setResolutionLimiterOpen}
+ />
+ ) : null}
+ </div>
+ </div>
+ );
+};
+
+export const RecordingView: React.FC<{
+ prefix: Prefix;
+ recordingStatus: RecordingStatus;
+ showAllViews: boolean;
+}> = ({ prefix, recordingStatus, showAllViews }) => {
+ if (!visibleByDefault[prefix] && !showAllViews) {
+ return null;
+ }
+
+ return (
+ <InnerRecordingView prefix={prefix} recordingStatus={recordingStatus} />
+ );
+};
diff --git a/packages/template-recorder/src/ResolutionLimiter.tsx b/packages/template-recorder/src/ResolutionLimiter.tsx
new file mode 100644
index 0000000000..c8e1a06415
--- /dev/null
+++ b/packages/template-recorder/src/ResolutionLimiter.tsx
@@ -0,0 +1,231 @@
+import { DialogTitle } from "@radix-ui/react-dialog";
+import React, { useCallback, useMemo } from "react";
+import { Button } from "./components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+} from "./components/ui/dialog";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "./components/ui/select";
+import { MaxResolution } from "./helpers/get-max-resolution-of-device";
+import {
+ FPS_AVAILABLE,
+ SizeConstraint,
+ VIDEO_SIZES,
+ VideoSize,
+} from "./helpers/get-selected-video-source";
+import { setPreferredResolutionForDevice } from "./preferred-resolution";
+
+export const ResolutionLimiter: React.FC<{
+ maxResolution: MaxResolution;
+ sizeConstraint: SizeConstraint;
+ setSizeConstraint: React.Dispatch<React.SetStateAction<SizeConstraint>>;
+ deviceName: string;
+ deviceId: string;
+ open: boolean;
+ setOpen: React.Dispatch<React.SetStateAction<boolean>>;
+}> = ({
+ deviceName,
+ maxResolution,
+ sizeConstraint,
+ setSizeConstraint: setActiveVideoSize,
+ deviceId,
+ open,
+ setOpen,
+}) => {
+ const availableLowerResolutions = useMemo(() => {
+ return Object.entries(VIDEO_SIZES).filter(([, value]) => {
+ if (maxResolution === null) {
+ return true;
+ }
+ return (
+ (maxResolution.width === null || value.width <= maxResolution.width) &&
+ (maxResolution.height === null || value.height <= maxResolution.height)
+ );
+ });
+ }, [maxResolution]);
+
+ const availableHigherFps = useMemo(() => {
+ return FPS_AVAILABLE.filter((fps) => {
+ if (maxResolution === null || maxResolution.frameRate === null) {
+ return true;
+ }
+ return fps <= maxResolution.frameRate;
+ }).reverse();
+ }, [maxResolution]);
+
+ const onResolutionChange = useCallback(
+ (value: VideoSize | "full") => {
+ if (value === "full") {
+ setActiveVideoSize((v) => {
+ const newSize = {
+ ...v,
+ maxSize: null,
+ };
+ setPreferredResolutionForDevice(deviceId, newSize);
+ return newSize;
+ });
+ setPreferredResolutionForDevice(deviceId, null);
+ return;
+ }
+
+ setActiveVideoSize((v) => {
+ const newSize = {
+ ...v,
+ maxSize: value,
+ };
+ setPreferredResolutionForDevice(deviceId, newSize);
+ return newSize;
+ });
+ },
+ [deviceId, setActiveVideoSize],
+ );
+
+ const onFpsChange = useCallback(
+ (value: string | "any") => {
+ if (value === "any") {
+ setActiveVideoSize((v) => {
+ const newState: SizeConstraint = {
+ ...v,
+ minimumFps: null,
+ };
+ setPreferredResolutionForDevice(deviceId, newState);
+
+ return newState;
+ });
+ return;
+ }
+
+ setActiveVideoSize((v) => {
+ const newSize: SizeConstraint = {
+ ...v,
+ minimumFps: Number(value),
+ };
+ setPreferredResolutionForDevice(deviceId, newSize);
+
+ return newSize;
+ });
+ },
+ [deviceId, setActiveVideoSize],
+ );
+
+ const handleSubmit = useCallback(async () => {
+ setOpen(false);
+ }, [setOpen]);
+
+ const onOpenChange = useCallback(
+ (open: boolean) => {
+ setOpen(open);
+ },
+ [setOpen],
+ );
+
+ const fullResolutionLabel = useMemo(() => {
+ if (maxResolution === null) {
+ return "Full resolution";
+ }
+ const { width, height } = maxResolution;
+ if (width && !height) {
+ return `Full resolution (${width}p)`;
+ }
+
+ return "Full resolution";
+ }, [maxResolution]);
+
+ const labelForFps = useCallback((fps: number | null) => {
+ return fps === null ? "Default" : `At least ${fps} FPS`;
+ }, []);
+
+ return (
+ <>
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[460px]">
+ <DialogHeader>
+ <DialogTitle>Limit resolution</DialogTitle>
+ <DialogDescription>
+ Constrain the resolution of {deviceName} to a lower value if you
+ experience dropped frames.
+ </DialogDescription>
+ </DialogHeader>
+ <Select onValueChange={onResolutionChange}>
+ <SelectTrigger>
+ <SelectValue
+ placeholder={sizeConstraint.maxSize ?? fullResolutionLabel}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem key={"full"} value={"full"}>
+ <span
+ style={{
+ whiteSpace: "nowrap",
+ }}
+ >
+ {fullResolutionLabel}
+ </span>
+ </SelectItem>
+ {availableLowerResolutions.map(([key]) => (
+ <SelectItem key={key} value={key}>
+ <span style={{ whiteSpace: "nowrap" }}>Limit to {key}</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <br />
+ <DialogHeader>
+ <DialogTitle>Minimum frame rate</DialogTitle>
+ {maxResolution.frameRate === null ? (
+ <DialogDescription>
+ {deviceName} might be able to record in higher FPS, but the
+ resolution might drop.
+ </DialogDescription>
+ ) : (
+ <DialogDescription>
+ {deviceName} can record in up to{" "}
+ {Math.floor(maxResolution.frameRate * 100) / 100} FPS, but this
+ might drop the resolution.
+ </DialogDescription>
+ )}
+ </DialogHeader>
+ <Select onValueChange={onFpsChange}>
+ <SelectTrigger>
+ <SelectValue
+ placeholder={labelForFps(sizeConstraint.minimumFps ?? null)}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem key={"any"} value={"any"}>
+ <span
+ style={{
+ whiteSpace: "nowrap",
+ }}
+ >
+ Default
+ </span>
+ </SelectItem>
+ {availableHigherFps.map((key) => (
+ <SelectItem key={key} value={String(key)}>
+ <span style={{ whiteSpace: "nowrap" }}>
+ {labelForFps(key)}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <DialogFooter>
+ <Button type="submit" onClick={handleSubmit}>
+ Done
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
diff --git a/packages/template-recorder/src/Rotate.tsx b/packages/template-recorder/src/Rotate.tsx
new file mode 100644
index 0000000000..e6aa2cf4af
--- /dev/null
+++ b/packages/template-recorder/src/Rotate.tsx
@@ -0,0 +1,28 @@
+import React from "react";
+import { Toggle } from "./components/ui/toggle";
+
+export const ToggleRotate: React.FC<{
+ onPressedChange: (pressed: boolean) => void;
+ pressed: boolean;
+ disabled: boolean;
+}> = ({ onPressedChange, pressed, disabled }) => {
+ return (
+ <Toggle
+ data-disabled={disabled}
+ className="data-[disabled=true]:opacity-50 data-[disabled=true]:pointer-events-none"
+ onPressedChange={onPressedChange}
+ pressed={pressed}
+ >
+ <svg
+ style={{ height: 20, width: 20 }}
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 640 512"
+ >
+ <path
+ fill="currentcolor"
+ d="M213.1 64.8L202.7 96H128c-35.3 0-64 28.7-64 64V416c0 35.3 28.7 64 64 64H512c35.3 0 64-28.7 64-64V160c0-35.3-28.7-64-64-64H437.3L426.9 64.8C420.4 45.2 402.1 32 381.4 32H258.6c-20.7 0-39 13.2-45.5 32.8zM448 256c0 8.8-7.2 16-16 16H355.3c-6.2 0-11.3-5.1-11.3-11.3c0-3 1.2-5.9 3.3-8L371 229c-13.6-13.4-31.9-21-51-21c-19.2 0-37.7 7.6-51.3 21.3L249 249c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l19.7-19.7C257.4 172.7 288 160 320 160c31.8 0 62.4 12.6 85 35l23.7-23.7c2.1-2.1 5-3.3 8-3.3c6.2 0 11.3 5.1 11.3 11.3V256zM192 320c0-8.8 7.2-16 16-16h76.7c6.2 0 11.3 5.1 11.3 11.3c0 3-1.2 5.9-3.3 8L269 347c13.6 13.4 31.9 21 51 21c19.2 0 37.7-7.6 51.3-21.3L391 327c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-19.7 19.7C382.6 403.3 352 416 320 416c-31.8 0-62.4-12.6-85-35l-23.7 23.7c-2.1 2.1-5 3.3-8 3.3c-6.2 0-11.3-5.1-11.3-11.3V320z"
+ />
+ </svg>
+ </Toggle>
+ );
+};
diff --git a/packages/template-recorder/src/Stream.tsx b/packages/template-recorder/src/Stream.tsx
new file mode 100644
index 0000000000..16cc0f098a
--- /dev/null
+++ b/packages/template-recorder/src/Stream.tsx
@@ -0,0 +1,235 @@
+import React, { useCallback, useEffect, useMemo, useRef } from "react";
+import { AbsoluteFill } from "remotion";
+import { Spinner } from "./components/Spinner";
+import type { SelectedSource } from "./helpers/get-selected-video-source";
+import {
+ getCameraStreamConstraints,
+ getVideoStream,
+} from "./helpers/get-video-stream";
+import { Prefix } from "./helpers/prefixes";
+import { useMediaSources } from "./state/media-sources";
+
+const container: React.CSSProperties = {
+ flex: 1,
+ justifyContent: "center",
+ alignItems: "center",
+};
+
+export type ResolutionAndFps = {
+ width: number;
+ height: number;
+ fps: number;
+};
+
+export const Stream: React.FC<{
+ prefix: Prefix;
+ setResolution: React.Dispatch<React.SetStateAction<ResolutionAndFps | null>>;
+ recordAudio: boolean;
+ selectedVideoSource: SelectedSource | null;
+ selectedAudioSource: ConstrainDOMString | null;
+ preferPortrait: boolean;
+ clear: () => void;
+}> = ({
+ prefix,
+ setResolution,
+ recordAudio,
+ selectedVideoSource,
+ selectedAudioSource,
+ preferPortrait,
+ clear,
+}) => {
+ const { mediaSources, setMediaStream } = useMediaSources();
+ const mediaStream = mediaSources[prefix];
+
+ const sourceRef = useRef<HTMLVideoElement>(null);
+
+ const videoStyle: React.CSSProperties = useMemo(() => {
+ return {
+ opacity: mediaStream ? 1 : 0,
+ height: "100%",
+ };
+ }, [mediaStream]);
+
+ useEffect(() => {
+ if (mediaStream.streamState.type !== "loaded") {
+ return;
+ }
+
+ const track = mediaStream.streamState.stream.getVideoTracks()[0];
+ if (!track) {
+ return;
+ }
+
+ track.onended = () => {
+ setMediaStream(prefix, { type: "initial" });
+ };
+ }, [mediaStream, prefix, setMediaStream]);
+
+ useEffect(() => {
+ return () => {
+ if (mediaStream.streamState.type !== "loaded") {
+ return;
+ }
+
+ mediaStream.streamState.stream
+ .getAudioTracks()
+ .forEach((track) => track.stop());
+
+ mediaStream.streamState.stream
+ .getVideoTracks()
+ .forEach((track) => track.stop());
+ };
+ }, [mediaStream]);
+
+ useEffect(() => {
+ const { current } = sourceRef;
+ if (!current) {
+ return;
+ }
+
+ if (selectedVideoSource === null) {
+ setMediaStream(prefix, { type: "initial" });
+ return;
+ }
+
+ setMediaStream(prefix, { type: "loading" });
+
+ const cleanup: (() => void)[] = [];
+
+ getVideoStream({
+ preferPortrait,
+ recordAudio,
+ selectedAudioSource,
+ selectedVideoSource,
+ })
+ .then((stream) => {
+ const videoTrack = stream.getVideoTracks()[0];
+ if (!videoTrack) {
+ throw new Error("No video track");
+ }
+
+ videoTrack.addEventListener(
+ "ended",
+ () => {
+ clear();
+ setMediaStream(prefix, { type: "initial" });
+ },
+ { once: true },
+ );
+
+ const settings = videoTrack.getSettings();
+ if (!settings) {
+ throw new Error("No video settings");
+ }
+
+ setResolution({
+ width: settings.width as number,
+ height: settings.height as number,
+ fps: settings.frameRate as number,
+ });
+
+ if (current) {
+ current.srcObject = stream;
+ current.play();
+ }
+
+ cleanup.push(() => {
+ stream.getVideoTracks().forEach((track) => track.stop());
+ stream.getAudioTracks().forEach((track) => track.stop());
+ current.srcObject = null;
+ });
+
+ setMediaStream(prefix, { type: "loaded", stream });
+ })
+ .catch((e) => {
+ const errMessage =
+ e.name === "NotReadableError"
+ ? "The selected device is not readable. This could be due to another app using this camera."
+ : e.name === "OverconstrainedError"
+ ? `Could not find a resolution satisfying these constraints: ${JSON.stringify(
+ getCameraStreamConstraints(
+ selectedVideoSource,
+ preferPortrait,
+ ),
+ )}`
+ : e.message || e.name;
+
+ setMediaStream(prefix, {
+ type: "error",
+ error: errMessage,
+ });
+ });
+
+ return () => {
+ cleanup.forEach((f) => f());
+ };
+ }, [
+ clear,
+ preferPortrait,
+ prefix,
+ recordAudio,
+ selectedAudioSource,
+ selectedVideoSource,
+ setMediaStream,
+ setResolution,
+ ]);
+
+ useEffect(() => {
+ const { current } = sourceRef;
+
+ if (!current) {
+ return;
+ }
+
+ const onResize = () => {
+ setResolution((r) => {
+ if (r === null) {
+ return null;
+ }
+
+ return {
+ ...r,
+ width: current.videoWidth,
+ height: current.videoHeight,
+ };
+ });
+ };
+
+ current.addEventListener("resize", onResize);
+
+ return () => {
+ current.removeEventListener("resize", onResize);
+ };
+ }, [setResolution]);
+
+ const onReset = useCallback(() => {
+ setMediaStream(prefix, {
+ type: "initial",
+ });
+ clear();
+ }, [clear, prefix, setMediaStream]);
+
+ return (
+ <AbsoluteFill style={container} id={prefix + "-video-container"}>
+ <video ref={sourceRef} muted style={videoStyle} />
+ {mediaStream.streamState.type === "loading" ? <Spinner /> : null}
+ {mediaStream.streamState.type === "error" ? (
+ <AbsoluteFill
+ style={{
+ padding: 20,
+ textWrap: "balance",
+ color: "rgba(255, 255, 255, 0.5)",
+ fontSize: 14,
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
+ {mediaStream.streamState.error}
+ <a className="underline cursor-pointer" onClick={onReset}>
+ Try again
+ </a>
+ </AbsoluteFill>
+ ) : null}
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/src/Timer.tsx b/packages/template-recorder/src/Timer.tsx
new file mode 100644
index 0000000000..dc018cdf14
--- /dev/null
+++ b/packages/template-recorder/src/Timer.tsx
@@ -0,0 +1,19 @@
+import React, { useEffect, useState } from "react";
+import { formatMilliseconds } from "./helpers/format-time";
+
+export const Timer: React.FC<{
+ startDate: number;
+}> = ({ startDate }) => {
+ const [, setTime] = useState(0);
+ useEffect(() => {
+ const int = setInterval(() => {
+ setTime(Date.now() - startDate);
+ }, 1000);
+
+ return () => {
+ clearInterval(int);
+ };
+ }, [startDate]);
+
+ return <>{formatMilliseconds(Date.now() - startDate)}</>;
+};
diff --git a/packages/template-recorder/src/ToggleCrop.tsx b/packages/template-recorder/src/ToggleCrop.tsx
new file mode 100644
index 0000000000..d90da4428d
--- /dev/null
+++ b/packages/template-recorder/src/ToggleCrop.tsx
@@ -0,0 +1,29 @@
+import React from "react";
+import { Toggle } from "./components/ui/toggle";
+
+export const ToggleCrop: React.FC<{
+ onPressedChange: (pressed: boolean) => void;
+ pressed: boolean;
+}> = ({ onPressedChange, pressed }) => {
+ return (
+ <Toggle
+ aria-label="Toggle italic"
+ pressed={pressed}
+ onPressedChange={onPressedChange}
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ style={{ width: 16, height: 16 }}
+ viewBox="0 0 512 512"
+ >
+ {/**
+ * <!--!Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.-->
+ */}
+ <path
+ fill="currentcolor"
+ d="M128 32c0-17.7-14.3-32-32-32S64 14.3 64 32V64H32C14.3 64 0 78.3 0 96s14.3 32 32 32H64V384c0 35.3 28.7 64 64 64H352V384H128V32zM384 480c0 17.7 14.3 32 32 32s32-14.3 32-32V448h32c17.7 0 32-14.3 32-32s-14.3-32-32-32H448l0-256c0-35.3-28.7-64-64-64L160 64v64l224 0 0 352z"
+ />
+ </svg>
+ </Toggle>
+ );
+};
diff --git a/packages/template-recorder/src/TopBar.tsx b/packages/template-recorder/src/TopBar.tsx
new file mode 100644
index 0000000000..17c934819b
--- /dev/null
+++ b/packages/template-recorder/src/TopBar.tsx
@@ -0,0 +1,130 @@
+import React, { useCallback, useEffect, useMemo, useState } from "react";
+import { BlinkingCircle } from "./BlinkingCircle";
+import { Logo } from "./Logo";
+import type { RecordingStatus } from "./RecordButton";
+import { RecordButton } from "./RecordButton";
+import { Timer } from "./Timer";
+import { fetchProjectFolders } from "./actions/fetch-project-folders";
+import { NewFolderDialog } from "./components/NewFolderDialog";
+import { ProcessStatus, ProcessingStatus } from "./components/ProcessingStatus";
+import { SelectedFolder } from "./components/SelectedFolder";
+import { UseThisTake } from "./components/UseThisTake";
+import { Button } from "./components/ui/button";
+import {
+ loadFolderFromUrl,
+ loadSelectedFolder,
+ persistSelectedFolder,
+} from "./helpers/get-folders";
+
+const topBarContainer: React.CSSProperties = {
+ display: "flex",
+ gap: 10,
+ margin: 10,
+ alignItems: "center",
+ flexDirection: "row",
+ justifyContent: "center",
+};
+
+const recordWrapper: React.CSSProperties = {
+ display: "flex",
+ flexDirection: "row",
+ justifyContent: "center",
+ alignItems: "center",
+ gap: 10,
+};
+
+export const TopBar: React.FC<{
+ recordingStatus: RecordingStatus;
+ setRecordingStatus: React.Dispatch<React.SetStateAction<RecordingStatus>>;
+ showAllViews: boolean;
+}> = ({ recordingStatus, setRecordingStatus, showAllViews }) => {
+ const [folders, setFolders] = useState<string[] | null>(null);
+ const [processingStatus, setProcessingStatus] =
+ useState<ProcessStatus | null>(null);
+
+ const folderFromUrl: string | null = useMemo(() => {
+ return loadFolderFromUrl();
+ }, []);
+
+ const [preferredSelectedFolder, setSelectedFolder] = useState<string | null>(
+ folderFromUrl ?? loadSelectedFolder(),
+ );
+
+ const selectedFolder = useMemo(() => {
+ return preferredSelectedFolder ?? folders?.[0] ?? null;
+ }, [folders, preferredSelectedFolder]);
+
+ const refreshFoldersList = useCallback(async () => {
+ const json = await fetchProjectFolders();
+ setFolders(json.folders);
+ }, []);
+
+ useEffect(() => {
+ if (!window.remotionServerEnabled) {
+ return;
+ }
+
+ refreshFoldersList();
+ }, [refreshFoldersList]);
+
+ useEffect(() => {
+ if (!window.remotionServerEnabled) {
+ return;
+ }
+
+ persistSelectedFolder(selectedFolder ?? "");
+ }, [selectedFolder]);
+
+ return (
+ <div style={topBarContainer}>
+ <Logo></Logo>
+ <div style={recordWrapper}>
+ <RecordButton
+ recordingStatus={recordingStatus}
+ processingStatus={processingStatus}
+ setRecordingStatus={setRecordingStatus}
+ showAllViews={showAllViews}
+ />
+ {recordingStatus.type === "recording" ? (
+ <>
+ <BlinkingCircle />
+ <Timer startDate={recordingStatus.ongoing.startDate} />
+ </>
+ ) : null}
+ {recordingStatus.type === "recording-finished" ? (
+ <UseThisTake
+ selectedFolder={selectedFolder}
+ recordingStatus={recordingStatus}
+ setRecordingStatus={setRecordingStatus}
+ setStatus={setProcessingStatus}
+ />
+ ) : null}
+ {processingStatus && (
+ <ProcessingStatus status={processingStatus}></ProcessingStatus>
+ )}
+ </div>
+
+ <div style={{ flex: 1 }} />
+ {folders ? (
+ <>
+ <SelectedFolder
+ folders={folders}
+ selectedFolder={selectedFolder}
+ setSelectedFolder={setSelectedFolder}
+ />
+ <NewFolderDialog
+ refreshFoldersList={refreshFoldersList}
+ setSelectedFolder={setSelectedFolder}
+ />
+ </>
+ ) : null}
+ {window.remotionServerEnabled ? (
+ <Button asChild variant="outline">
+ <a href={`http://localhost:3000/${selectedFolder}`} target="_blank">
+ Go to Studio
+ </a>
+ </Button>
+ ) : null}
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/WaitingForDevices.tsx b/packages/template-recorder/src/WaitingForDevices.tsx
new file mode 100644
index 0000000000..6c1e4165f0
--- /dev/null
+++ b/packages/template-recorder/src/WaitingForDevices.tsx
@@ -0,0 +1,80 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { getDevices } from "./helpers/get-devices";
+
+export type DevicesContext = {
+ devices: MediaDeviceInfo[] | null;
+ rescan: () => Promise<void>;
+ isRescanning: boolean;
+};
+
+export const DevicesContext = createContext<DevicesContext | null>(null);
+
+export const WaitingForDevices: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
+ const [devices, setDevices] = useState<MediaDeviceInfo[] | null>(null);
+ const [isRescanning, setIsRescanning] = useState(false);
+
+ const checkDeviceLabels = useCallback(async () => {
+ try {
+ const fetchedDevices = await getDevices();
+ setDevices(fetchedDevices);
+ } catch (err) {
+ alert((err as Error).message);
+ console.log(err);
+ }
+ }, []);
+
+ useEffect(() => {
+ checkDeviceLabels();
+ }, [checkDeviceLabels]);
+
+ const value: DevicesContext = useMemo(
+ () => ({
+ devices,
+ rescan: async () => {
+ try {
+ setIsRescanning(true);
+ // Show scanning label for at least 250ms
+ // to indicate that rescanning was successful
+ await Promise.all([
+ checkDeviceLabels(),
+ new Promise((resolve) => setTimeout(resolve, 250)),
+ ]);
+ } finally {
+ setIsRescanning(false);
+ }
+ },
+ isRescanning,
+ }),
+ [devices, checkDeviceLabels, isRescanning],
+ );
+
+ if (devices === null) {
+ return (
+ <div className="absolute inset-0 flex justify-center items-center text-sm text-muted-foreground">
+ Finding devices...
+ </div>
+ );
+ }
+
+ return (
+ <DevicesContext.Provider value={value}>{children}</DevicesContext.Provider>
+ );
+};
+
+export const useDevices = (): MediaDeviceInfo[] => {
+ const context = useContext(DevicesContext);
+ if (!context?.devices) {
+ throw new Error("useDevices must be used within a DevicesContextProvider");
+ }
+
+ return context.devices;
+};
diff --git a/packages/template-recorder/src/actions/create-folder.ts b/packages/template-recorder/src/actions/create-folder.ts
new file mode 100644
index 0000000000..e43705c693
--- /dev/null
+++ b/packages/template-recorder/src/actions/create-folder.ts
@@ -0,0 +1,24 @@
+import { SERVER_PORT } from "../../config/server";
+import { CREATE_FOLDER } from "../../scripts/server/constants";
+
+type CreateProjectResBodyType = {
+ success: boolean;
+ message: string;
+};
+
+export const createFolder = async (folderName: string) => {
+ const payload = { projectName: folderName };
+ const res = await fetch(`http://localhost:${SERVER_PORT}${CREATE_FOLDER}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+
+ const jsn = (await res.json()) as CreateProjectResBodyType;
+
+ if (res.status === 201) {
+ return jsn;
+ }
+
+ throw new Error(jsn.message);
+};
diff --git a/packages/template-recorder/src/actions/fetch-project-folders.ts b/packages/template-recorder/src/actions/fetch-project-folders.ts
new file mode 100644
index 0000000000..ba2a180aae
--- /dev/null
+++ b/packages/template-recorder/src/actions/fetch-project-folders.ts
@@ -0,0 +1,13 @@
+import { SERVER_PORT } from "../../config/server";
+import { GET_FOLDERS } from "../../scripts/server/constants";
+import type { FolderResBody } from "../../scripts/server/projects";
+
+export const fetchProjectFolders = async () => {
+ const res = await fetch(`http://localhost:${SERVER_PORT}${GET_FOLDERS}`, {
+ method: "GET",
+ });
+
+ const projectFolders = (await res.json()) as FolderResBody;
+
+ return projectFolders;
+};
diff --git a/packages/template-recorder/src/components/ClearCurrentVideo.tsx b/packages/template-recorder/src/components/ClearCurrentVideo.tsx
new file mode 100644
index 0000000000..8600d19ad8
--- /dev/null
+++ b/packages/template-recorder/src/components/ClearCurrentVideo.tsx
@@ -0,0 +1,44 @@
+import React, { useCallback, useMemo, useState } from "react";
+
+export const ClearCurrentVideo: React.FC<{
+ onClick: () => void;
+}> = ({ onClick }) => {
+ const [hovered, setHovered] = useState(false);
+
+ const onPointerEnter = useCallback(() => {
+ setHovered(true);
+ }, []);
+
+ const onPointerLeave = useCallback(() => {
+ setHovered(false);
+ }, []);
+
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ background: hovered ? "rgba(0, 0, 0, 0.5)" : "transparent",
+ paddingLeft: 10,
+ paddingRight: 10,
+ height: "100%",
+ cursor: "pointer",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ };
+ }, [hovered]);
+
+ return (
+ <div
+ onClick={onClick}
+ style={style}
+ onPointerEnter={onPointerEnter}
+ onPointerLeave={onPointerLeave}
+ >
+ <svg viewBox="0 0 384 512" style={{ width: 13 }}>
+ <path
+ fill={hovered ? "white" : "rgba(255, 255, 255, 0.5)"}
+ d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"
+ />
+ </svg>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/components/CurrentAudio.tsx b/packages/template-recorder/src/components/CurrentAudio.tsx
new file mode 100644
index 0000000000..d7488d877f
--- /dev/null
+++ b/packages/template-recorder/src/components/CurrentAudio.tsx
@@ -0,0 +1,39 @@
+import { MicIcon } from "lucide-react";
+import React, { useMemo } from "react";
+
+const spacer: React.CSSProperties = {
+ width: 12,
+};
+
+export const CurrentAudio: React.FC<{
+ label: string | null;
+ onClick: () => void;
+ disabled: boolean;
+}> = ({ label, onClick, disabled }) => {
+ const container: React.CSSProperties = useMemo(() => {
+ return {
+ display: "flex",
+ flexDirection: "row",
+ fontSize: 13,
+ alignItems: "center",
+ flex: 1,
+ lineHeight: 1.4,
+ paddingLeft: 10,
+ cursor: "pointer",
+ height: "100%",
+ };
+ }, []);
+
+ return (
+ <div
+ data-disabled={disabled}
+ className="hover:bg-slate-950 data-[disabled=true]:opacity-50 data-[disabled=true]:pointer-events-none"
+ style={container}
+ onClick={onClick}
+ >
+ <MicIcon></MicIcon>
+ <div style={spacer}></div>
+ <div>{label ?? "No audio selected"}</div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/components/CurrentVideo.tsx b/packages/template-recorder/src/components/CurrentVideo.tsx
new file mode 100644
index 0000000000..23f23f2d5f
--- /dev/null
+++ b/packages/template-recorder/src/components/CurrentVideo.tsx
@@ -0,0 +1,94 @@
+import { CameraIcon } from "lucide-react";
+import React, { useCallback, useMemo } from "react";
+import { DisplayIcon } from "../DeviceItem";
+import { Resolution } from "../PrefixAndResolution";
+import { ResolutionAndFps } from "../Stream";
+
+const spacer: React.CSSProperties = {
+ width: 12,
+};
+
+const buttonStyle: React.CSSProperties = {
+ display: "inline",
+ color: "rgba(255, 255, 255, 0.5)",
+ borderBottom: "1px solid",
+};
+
+export const CurrentVideo: React.FC<{
+ label: string;
+ resolution: ResolutionAndFps | null;
+ isScreenshare: boolean;
+ onClick: () => void;
+ setResolutionLimiterOpen: React.Dispatch<React.SetStateAction<boolean>>;
+ canShowResolutionLimiter: boolean | null;
+ disabled: boolean;
+}> = ({
+ label,
+ resolution,
+ isScreenshare,
+ onClick,
+ setResolutionLimiterOpen,
+ canShowResolutionLimiter,
+ disabled,
+}) => {
+ const onOpen: React.MouseEventHandler<HTMLButtonElement> = useCallback(
+ (e) => {
+ e.stopPropagation();
+ setResolutionLimiterOpen(true);
+ },
+ [setResolutionLimiterOpen],
+ );
+
+ const container: React.CSSProperties = useMemo(() => {
+ return {
+ display: "flex",
+ flexDirection: "row",
+ fontSize: 13,
+ alignItems: "center",
+ flex: 1,
+ lineHeight: 1.4,
+ cursor: "pointer",
+ paddingTop: 4,
+ paddingBottom: 4,
+ paddingLeft: 10,
+ minHeight: 48,
+ };
+ }, []);
+
+ return (
+ <div
+ style={container}
+ data-disabled={disabled}
+ className="hover:bg-slate-950 data-[disabled=true]:opacity-50 data-[disabled=true]:pointer-events-none"
+ onClick={onClick}
+ >
+ {isScreenshare ? <DisplayIcon></DisplayIcon> : <CameraIcon></CameraIcon>}
+ <div style={spacer}></div>
+ <div>
+ <div>{label}</div>
+ <span
+ style={{
+ whiteSpace: "nowrap",
+ display: "flex",
+ flexDirection: "row",
+ }}
+ >
+ {resolution ? (
+ <>
+ <Resolution resolution={resolution} />
+ {canShowResolutionLimiter ? (
+ <>
+ <div style={{ width: 4 }}></div>
+ <button onClick={onOpen} style={buttonStyle}>
+ Settings
+ </button>
+ </>
+ ) : null}
+ </>
+ ) : null}
+ </span>
+ </div>
+ <div style={spacer}></div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/components/Divider.tsx b/packages/template-recorder/src/components/Divider.tsx
new file mode 100644
index 0000000000..cdb654cf37
--- /dev/null
+++ b/packages/template-recorder/src/components/Divider.tsx
@@ -0,0 +1,13 @@
+import React from "react";
+
+export const Divider: React.FC = () => {
+ return (
+ <div
+ style={{
+ width: 1,
+ height: 36,
+ backgroundColor: "#444",
+ }}
+ ></div>
+ );
+};
diff --git a/packages/template-recorder/src/components/EnsureBrowserSupport.tsx b/packages/template-recorder/src/components/EnsureBrowserSupport.tsx
new file mode 100644
index 0000000000..c408d52e46
--- /dev/null
+++ b/packages/template-recorder/src/components/EnsureBrowserSupport.tsx
@@ -0,0 +1,55 @@
+import { useEffect, useState } from "react";
+import { canUseWebFsWriter } from "../helpers/browser-support";
+
+type WebFsState = "loading" | "yes" | "no" | "security-error";
+
+export const EnsureBrowserSupport: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
+ const [canUseWebFs, setCanUseWebFs] = useState<WebFsState>("loading");
+ useEffect(() => {
+ canUseWebFsWriter()
+ .then((result) => {
+ setCanUseWebFs(result ? "yes" : "no");
+ })
+ .catch((err) => {
+ if ((err as Error).message.includes("Security")) {
+ setCanUseWebFs("security-error");
+ } else {
+ setCanUseWebFs("no");
+ console.log(err);
+ }
+ });
+ }, []);
+
+ if (canUseWebFs === "loading") {
+ return null;
+ }
+
+ if (canUseWebFs === "no") {
+ return (
+ <div className="justify-center text-white flex items-center flex-col absolute inset-0 text-sm">
+ <strong>Browser not supported</strong>
+ <p className="max-w-[500px] text-center text-balance">
+ Your browser does not support the Web FS API which is needed to use
+ this application. Please use a different browser.
+ </p>
+ </div>
+ );
+ }
+
+ if (canUseWebFs === "security-error") {
+ return (
+ <div className="justify-center text-white flex items-center flex-col absolute inset-0 text-sm">
+ <strong>Security error</strong>
+ <p className="max-w-[500px] text-center text-balance">
+ Got an error trying to use the Web File System API. This could be
+ because you are in an Private Window. Try opening this app in a
+ regular window.
+ </p>
+ </div>
+ );
+ }
+
+ return children;
+};
diff --git a/packages/template-recorder/src/components/NewFolderDialog.tsx b/packages/template-recorder/src/components/NewFolderDialog.tsx
new file mode 100644
index 0000000000..7786e38305
--- /dev/null
+++ b/packages/template-recorder/src/components/NewFolderDialog.tsx
@@ -0,0 +1,130 @@
+import type { ChangeEvent, SetStateAction } from "react";
+import React, {
+ createRef,
+ useCallback,
+ useImperativeHandle,
+ useMemo,
+ useState,
+} from "react";
+import { createFolder } from "../actions/create-folder";
+import { useKeyPress } from "../helpers/use-key-press";
+import { Button } from "./ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "./ui/dialog";
+import { Input } from "./ui/input";
+import { Label } from "./ui/label";
+
+export const createNewFolderRef = createRef<{
+ openDialog: () => void;
+}>();
+
+export const NewFolderDialog: React.FC<{
+ setSelectedFolder: React.Dispatch<SetStateAction<string | null>>;
+ refreshFoldersList: () => Promise<void>;
+}> = ({ refreshFoldersList, setSelectedFolder }) => {
+ const [newProject, setNewProject] = useState<string>("");
+ const [open, setOpen] = useState<boolean>(false);
+
+ const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
+ setNewProject(event.target.value);
+ };
+
+ const getRegex = () => /^([a-zA-Z0-9-\u4E00-\u9FFF])+$/g;
+
+ const invalidInput = useMemo(() => {
+ const match = newProject.match(getRegex());
+ if (newProject.length === 0) {
+ return null;
+ }
+
+ if (!match || match.length === 0) {
+ return "Project names can't contain spaces or special symbols.";
+ }
+
+ return null;
+ }, [newProject]);
+
+ const disabled = useMemo(() => {
+ return invalidInput !== null || newProject.length === 0;
+ }, [invalidInput, newProject.length]);
+
+ const handleSubmit = useCallback(async () => {
+ try {
+ const res = await createFolder(newProject);
+ if (!res.success) {
+ throw new Error(res.message);
+ }
+
+ setSelectedFolder(newProject);
+ setNewProject("");
+ refreshFoldersList();
+ setOpen(false);
+ } catch (e) {
+ // eslint-disable-next-line no-alert
+ alert((e as Error).stack);
+ }
+ }, [newProject, refreshFoldersList, setSelectedFolder]);
+
+ useImperativeHandle(
+ createNewFolderRef,
+ () => {
+ return {
+ openDialog: () => {
+ setOpen(true);
+ },
+ };
+ },
+ [],
+ );
+
+ const handlePressEnter = useCallback(() => {
+ if (!disabled) {
+ handleSubmit();
+ }
+ }, [disabled, handleSubmit]);
+
+ useKeyPress({ keys: ["Enter"], callback: handlePressEnter, metaKey: false });
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="sm:max-w-[460px]">
+ <DialogHeader>
+ <DialogTitle>New Folder</DialogTitle>
+ <DialogDescription>
+ Create a new subfolder in the <code>public/</code> directory. This
+ should map to the ID of your composition in the Remotion Studio.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 py-4">
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="name" className="text-right">
+ Folder Name
+ </Label>
+
+ <Input
+ id="remotion_video_name"
+ placeholder="my-video"
+ value={newProject}
+ className="col-span-3"
+ onChange={handleChange}
+ />
+ <Label className="col-start-2 col-end-5 text-red-600">
+ {invalidInput ?? null}
+ </Label>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button type="submit" disabled={disabled} onClick={handleSubmit}>
+ Create subfolder
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/packages/template-recorder/src/components/ProcessingStatus.tsx b/packages/template-recorder/src/components/ProcessingStatus.tsx
new file mode 100644
index 0000000000..58a3dee64e
--- /dev/null
+++ b/packages/template-recorder/src/components/ProcessingStatus.tsx
@@ -0,0 +1,39 @@
+import React from "react";
+
+export type ProcessStatus = {
+ title: string;
+ description: string;
+ abort: null | (() => void);
+};
+
+const statusStyle: React.CSSProperties = {
+ fontSize: 13,
+ color: "rgba(255, 255, 255, 0.8)",
+ display: "block",
+};
+
+const subtitle: React.CSSProperties = {
+ color: "rgba(255, 255, 255, 0.5)",
+ fontSize: 13,
+};
+
+export const ProcessingStatus: React.FC<{
+ readonly status: ProcessStatus;
+}> = ({ status }) => {
+ return (
+ <div style={statusStyle}>
+ <div>{status.title}</div>
+ <div style={subtitle}>
+ {status.description}{" "}
+ {status.abort !== null ? (
+ <a
+ className="underline cursor-pointer"
+ onClick={() => status.abort?.()}
+ >
+ Abort and discard
+ </a>
+ ) : null}{" "}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/components/RescanDevices.tsx b/packages/template-recorder/src/components/RescanDevices.tsx
new file mode 100644
index 0000000000..963787de2f
--- /dev/null
+++ b/packages/template-recorder/src/components/RescanDevices.tsx
@@ -0,0 +1,16 @@
+import { useContext } from "react";
+import { DevicesContext } from "../WaitingForDevices";
+
+export const RescanDevices = () => {
+ const ctx = useContext(DevicesContext);
+
+ return (
+ <div
+ onClick={() => ctx?.rescan()}
+ data-disabled={ctx?.isRescanning}
+ className="cursor-pointer hover:underline inline opacity-70 hover:opacity-100 transition-opacity data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-50"
+ >
+ {ctx?.isRescanning ? "Rescanning..." : "Rescan devices"}
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/components/SelectedFolder.tsx b/packages/template-recorder/src/components/SelectedFolder.tsx
new file mode 100644
index 0000000000..6b9ccc9cc1
--- /dev/null
+++ b/packages/template-recorder/src/components/SelectedFolder.tsx
@@ -0,0 +1,90 @@
+import type { SetStateAction } from "react";
+import React, { useCallback } from "react";
+import { createNewFolderRef } from "./NewFolderDialog";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectSeparator,
+ SelectTrigger,
+ SelectValue,
+} from "./ui/select";
+
+const NEW_FOLDER_TOKEN = "__remotion_new_folder";
+
+export const SelectedFolder: React.FC<{
+ readonly folders: string[];
+ readonly selectedFolder: string | null;
+ readonly setSelectedFolder: React.Dispatch<SetStateAction<string | null>>;
+}> = ({
+ folders,
+ selectedFolder: selectedProject,
+ setSelectedFolder: setSelectedProject,
+}) => {
+ const onValueChange = useCallback(
+ (value: string) => {
+ if (value === NEW_FOLDER_TOKEN) {
+ createNewFolderRef.current?.openDialog();
+ } else {
+ setSelectedProject(value);
+ }
+ },
+ [setSelectedProject],
+ );
+
+ const placeholder = (
+ <span
+ style={{
+ opacity: 0.5,
+ }}
+ >
+ None selected
+ </span>
+ );
+
+ return (
+ <div
+ style={{
+ display: "flex",
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 10,
+ }}
+ >
+ <div style={{ whiteSpace: "nowrap" }}>Save to:</div>
+ <Select
+ value={selectedProject ?? undefined}
+ onValueChange={onValueChange}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder={placeholder}>
+ <span
+ style={{
+ marginRight: 10,
+ display: "inline-block",
+ }}
+ >
+ {selectedProject ? (
+ <span>public/{selectedProject}</span>
+ ) : (
+ placeholder
+ )}
+ </span>
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent className="max-h-[var(--radix-select-content-available-height)]">
+ <SelectItem value={NEW_FOLDER_TOKEN}>New folder</SelectItem>
+ {folders.length !== 0 && <SelectSeparator />}
+ {folders.map((project, i) => {
+ const key = i + project;
+ return (
+ <SelectItem key={key} value={project}>
+ public/{project}
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/components/Spinner.tsx b/packages/template-recorder/src/components/Spinner.tsx
new file mode 100644
index 0000000000..5756b34a12
--- /dev/null
+++ b/packages/template-recorder/src/components/Spinner.tsx
@@ -0,0 +1,17 @@
+import type { ReactNode } from "react";
+
+export const Spinner: React.FC = () => {
+ return (
+ <div className="spinner">
+ <div className="spinner-item" />
+ <div className="spinner-item" />
+ <div className="spinner-item" />
+ </div>
+ );
+};
+
+export const CircleSpinner: React.FC<{ children?: ReactNode }> = ({
+ children,
+}) => {
+ return <span className="loader">{children} </span>;
+};
diff --git a/packages/template-recorder/src/components/StreamPicker.tsx b/packages/template-recorder/src/components/StreamPicker.tsx
new file mode 100644
index 0000000000..591b303b0e
--- /dev/null
+++ b/packages/template-recorder/src/components/StreamPicker.tsx
@@ -0,0 +1,149 @@
+import React, { useMemo } from "react";
+import { AbsoluteFill } from "remotion";
+import { DeviceItem } from "../DeviceItem";
+import { useDevices } from "../WaitingForDevices";
+import { Label, formatDeviceLabel } from "../helpers/format-device-label";
+import { RescanDevices } from "./RescanDevices";
+
+const title: React.CSSProperties = {
+ fontWeight: "bold",
+};
+
+const container: React.CSSProperties = {
+ display: "flex",
+ backgroundColor: "rgba(0, 0, 0, 0.9)",
+ padding: 20,
+ gap: 20,
+ overflowY: "auto",
+};
+
+const clearStyle: React.CSSProperties = {
+ borderBottom: "1px solid",
+ color: "rgba(255, 255, 255, 0.5)",
+ fontSize: 14,
+ marginTop: 10,
+ display: "inline-block",
+ cursor: "pointer",
+};
+
+export const getDeviceLabel = (device: MediaDeviceInfo): string => {
+ const labels: Label[] = JSON.parse(localStorage.getItem("labels") ?? "[]");
+ const found = labels.find((l) => l.id === device.deviceId);
+ if (found) {
+ return found.label;
+ }
+
+ return formatDeviceLabel(device.label);
+};
+
+export const StreamPicker: React.FC<{
+ canSelectAudio: boolean;
+ canSelectScreen: boolean;
+ onPickVideo: (device: MediaDeviceInfo) => void;
+ onPickAudio: (device: MediaDeviceInfo) => void;
+ onPickScreenWithoutAudio: () => void;
+ onPickScreenWithAudio: () => void;
+ selectedVideoDevice: string | null;
+ selectedAudioDevice: string | null;
+ clear: () => void;
+ canClear: boolean;
+}> = ({
+ canSelectAudio,
+ canSelectScreen,
+ onPickAudio,
+ onPickVideo,
+ onPickScreenWithoutAudio,
+ onPickScreenWithAudio,
+ selectedAudioDevice,
+ selectedVideoDevice,
+ clear,
+ canClear,
+}) => {
+ const devices = useDevices();
+ const videoInputs = useMemo(() => {
+ return devices.filter((d) => d.kind === "videoinput");
+ }, [devices]);
+ const audioInputs = useMemo(() => {
+ return devices.filter((d) => d.kind === "audioinput");
+ }, [devices]);
+
+ return (
+ <AbsoluteFill style={container}>
+ <div className="flex-1 flex-row flex">
+ <div
+ style={{
+ flex: 1,
+ opacity:
+ canSelectAudio && selectedVideoDevice && !selectedAudioDevice
+ ? 0.5
+ : 1,
+ }}
+ >
+ <div style={title}>Select video</div>
+ {canSelectScreen ? (
+ <DeviceItem
+ handleClick={() => {
+ onPickScreenWithoutAudio();
+ }}
+ deviceLabel={"Screen capture"}
+ type="screen"
+ selected={selectedVideoDevice === "display-without-audio"}
+ />
+ ) : null}
+ {canSelectScreen ? (
+ <DeviceItem
+ handleClick={() => {
+ onPickScreenWithAudio();
+ }}
+ deviceLabel={"Screen capture with audio"}
+ type="screen"
+ selected={selectedVideoDevice === "display-with-audio"}
+ />
+ ) : null}
+ {videoInputs.map((d) => {
+ return (
+ <DeviceItem
+ type="camera"
+ key={d.deviceId}
+ deviceLabel={getDeviceLabel(d)}
+ handleClick={() => {
+ onPickVideo(d);
+ }}
+ selected={selectedVideoDevice === d.deviceId}
+ />
+ );
+ })}
+ {selectedVideoDevice && canClear ? (
+ <a style={clearStyle} onClick={clear}>
+ Clear
+ </a>
+ ) : null}
+ </div>
+ {canSelectAudio ? (
+ <div
+ style={{
+ flex: 1,
+ opacity: !selectedVideoDevice && selectedAudioDevice ? 0.5 : 1,
+ }}
+ >
+ <div style={title}>Select audio</div>
+ {audioInputs.map((d) => {
+ return (
+ <DeviceItem
+ type="microphone"
+ key={d.deviceId}
+ deviceLabel={getDeviceLabel(d)}
+ handleClick={() => {
+ onPickAudio(d);
+ }}
+ selected={selectedAudioDevice === d.deviceId}
+ />
+ );
+ })}
+ </div>
+ ) : null}
+ </div>
+ <RescanDevices />
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/template-recorder/src/components/UseThisTake.tsx b/packages/template-recorder/src/components/UseThisTake.tsx
new file mode 100644
index 0000000000..eab94e7a60
--- /dev/null
+++ b/packages/template-recorder/src/components/UseThisTake.tsx
@@ -0,0 +1,261 @@
+import React, { useCallback } from "react";
+import { WEBCAM_PREFIX } from "../../config/cameras";
+import { RecordingStatus } from "../RecordButton";
+import { cancelTranscribeOnServer } from "../helpers/cancel-transcribe";
+import { convertInBrowser } from "../helpers/convert-in-browser";
+import { downloadVideo } from "../helpers/download-video";
+import { getExtension } from "../helpers/find-good-supported-codec";
+import { formatMilliseconds } from "../helpers/format-time";
+import { Prefix } from "../helpers/prefixes";
+import { transcribeVideoOnServer } from "../helpers/transcribe-video";
+import { uploadFileToServer } from "../helpers/upload-file";
+import { ProcessStatus } from "./ProcessingStatus";
+import { Button } from "./ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "./ui/dropdown-menu";
+let currentProcessing = Promise.resolve();
+
+export const UseThisTake: React.FC<{
+ readonly selectedFolder: string | null;
+ recordingStatus: RecordingStatus;
+ setRecordingStatus: React.Dispatch<React.SetStateAction<RecordingStatus>>;
+ setStatus: React.Dispatch<React.SetStateAction<ProcessStatus | null>>;
+}> = ({ selectedFolder, recordingStatus, setRecordingStatus, setStatus }) => {
+ const keepVideoOnServer = useCallback(async () => {
+ if (recordingStatus.type !== "recording-finished") {
+ throw new Error("Recording not finished");
+ }
+
+ if (selectedFolder === null) {
+ // eslint-disable-next-line no-alert
+ alert("Please select a folder first.");
+ return Promise.resolve();
+ }
+
+ let aborted = false;
+
+ for (const blob of recordingStatus.blobs) {
+ const extension = getExtension(blob.mimeType);
+ currentProcessing = currentProcessing
+ .then(() => {
+ setStatus({
+ title: `Converting ${blob.prefix}${blob.endDate}.${extension}`,
+ description: "Starting...",
+ abort: null,
+ });
+ return blob.data();
+ })
+ .then((src) => {
+ return convertInBrowser({
+ src: src,
+ mimeType: blob.mimeType,
+ onProgress: ({ millisecondsWritten }, abortFn) => {
+ setStatus({
+ title: `Converting ${blob.prefix}${blob.endDate}.${extension}`,
+ description: `${formatMilliseconds(millisecondsWritten)} processed`,
+ abort: abortFn,
+ });
+ },
+ });
+ })
+ .then((d) => d.save())
+ .then((convertedBlob) => {
+ setStatus({
+ title: `Copying to public folder ${blob.prefix}${blob.endDate}.${extension}`,
+ description: "Copying in progress",
+ abort: null,
+ });
+ return uploadFileToServer({
+ blob: convertedBlob,
+ endDate: recordingStatus.endDate,
+ prefix: blob.prefix,
+ selectedFolder,
+ expectedFrames: recordingStatus.expectedFrames,
+ mimeType: blob.mimeType,
+ });
+ })
+ .then(() => {
+ setStatus(null);
+ })
+ .catch((err) => {
+ // ⚠️ might come from @remotion/webcodecs or from transcribe-video.ts
+ if ((err as Error).message.includes("aborted by user")) {
+ aborted = true;
+ return;
+ }
+ alert(
+ "Failed to convert video. Downloaded original video for backup.",
+ );
+ console.log(err);
+ return blob.data();
+ })
+ .then((buffer) => {
+ if (buffer) {
+ const blobToDownload = new Blob([buffer], {
+ type: blob.mimeType.includes("webm") ? "video/webm" : "video/mp4",
+ });
+ const a = document.createElement("a");
+ const url = URL.createObjectURL(blobToDownload);
+ a.href = url;
+ a.download = `${blob.prefix}${blob.endDate}.${extension}`;
+ a.click();
+ blob.releaseData();
+ }
+ });
+ }
+ if (aborted) {
+ return;
+ }
+
+ currentProcessing = currentProcessing
+ .then(() => {
+ setStatus({
+ title: `Transcribing ${WEBCAM_PREFIX}${recordingStatus.endDate}.${recordingStatus.blobs.find((b) => b.prefix === WEBCAM_PREFIX)?.mimeType.includes("webm") ? "webm" : "mp4"}`,
+ description: "See Terminal for progress",
+ abort: () => cancelTranscribeOnServer(),
+ });
+ return transcribeVideoOnServer({
+ endDate: recordingStatus.endDate,
+ selectedFolder,
+ onProgress: (stat) => {
+ setStatus(stat);
+ },
+ });
+ })
+ .catch((err) => {
+ // ⚠️ might come from @remotion/webcodecs or from transcribe-video.ts
+ if ((err as Error).message.includes("aborted by user")) {
+ return;
+ }
+
+ console.log(err);
+ })
+ .then(() => {
+ setStatus(null);
+ });
+
+ setRecordingStatus({ type: "idle" });
+ }, [recordingStatus, selectedFolder, setRecordingStatus, setStatus]);
+
+ const keepVideosWithoutConverting = useCallback(async () => {
+ if (recordingStatus.type !== "recording-finished") {
+ throw new Error("Recording not finished");
+ }
+
+ for (const blob of recordingStatus.blobs) {
+ const buffer = await blob.data();
+ const extension = getExtension(blob.mimeType);
+
+ const blobToDownload = new Blob([buffer], {
+ type: blob.mimeType.includes("webm") ? "video/webm" : "video/mp4",
+ });
+ const a = document.createElement("a");
+ const url = URL.createObjectURL(blobToDownload);
+ a.href = url;
+ a.download = `${blob.prefix}${blob.endDate}-unprocessed.${extension}`;
+ a.click();
+ }
+ }, [recordingStatus]);
+
+ const keepVideoOnClient = useCallback(async () => {
+ if (recordingStatus.type !== "recording-finished") {
+ throw new Error("Recording not finished");
+ }
+
+ for (const blob of recordingStatus.blobs) {
+ await downloadVideo({
+ data: await blob.data(),
+ endDate: recordingStatus.endDate,
+ prefix: blob.prefix,
+ mimeType: blob.mimeType,
+ setStatus,
+ });
+ }
+ }, [recordingStatus, setStatus]);
+
+ const previewWebcam = useCallback(
+ async (prefix: Prefix) => {
+ if (recordingStatus.type !== "recording-finished") {
+ throw new Error("Recording not finished");
+ }
+
+ const webcamBlob = recordingStatus.blobs.find((b) => b.prefix === prefix);
+ if (!webcamBlob) {
+ throw new Error("No webcam blob");
+ }
+
+ // turn into blob url and open in new tab
+ const blob = new Blob([await webcamBlob.data()], {
+ type: webcamBlob.mimeType,
+ });
+ const url = URL.createObjectURL(blob);
+ window.open(url, "_blank");
+ },
+ [recordingStatus],
+ );
+
+ return (
+ <>
+ <div className="flex items-center">
+ {window.remotionServerEnabled ? (
+ <Button
+ variant="default"
+ className={"rounded-r-none"}
+ onClick={keepVideoOnServer}
+ >
+ {`Copy to public/${selectedFolder}`}
+ </Button>
+ ) : (
+ <Button
+ variant="default"
+ className={"rounded-r-none"}
+ onClick={keepVideoOnClient}
+ >
+ {`Download files`}
+ </Button>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="default"
+ className={"rounded-l-none border-l-2 px-2"}
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 448 512"
+ style={{ width: 12 }}
+ >
+ <path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z" />
+ </svg>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {window.remotionServerEnabled ? (
+ <DropdownMenuItem onClick={keepVideoOnClient}>
+ Download as file
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem onClick={keepVideosWithoutConverting}>
+ Download without conversion
+ </DropdownMenuItem>
+ {recordingStatus.type === "recording-finished" &&
+ recordingStatus.blobs.map((blob) => (
+ <DropdownMenuItem
+ key={blob.prefix}
+ onClick={() => {
+ previewWebcam(blob.prefix as Prefix);
+ }}
+ >
+ Preview {blob.prefix}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </>
+ );
+};
diff --git a/packages/template-recorder/src/components/VolumeMeter.tsx b/packages/template-recorder/src/components/VolumeMeter.tsx
new file mode 100644
index 0000000000..1092866270
--- /dev/null
+++ b/packages/template-recorder/src/components/VolumeMeter.tsx
@@ -0,0 +1,100 @@
+import { useEffect, useMemo, useState } from "react";
+import { StreamState } from "../state/media-sources";
+
+const GREEN = "#0b800b";
+const YELLOW = "#bda615";
+const RED = "#800b0b";
+
+const container: React.CSSProperties = {
+ display: "flex",
+ justifyContent: "center",
+ width: "100%",
+ alignItems: "center",
+ flexDirection: "row",
+};
+
+const gradientStyle: React.CSSProperties = {
+ display: "flex",
+ backgroundImage: `linear-gradient(to right, ${GREEN}, ${GREEN} 66% , ${YELLOW} 66%, ${YELLOW} 90%, ${RED} 90%,${RED} )`,
+ justifyContent: "flex-end",
+ height: 4,
+ flex: 1,
+};
+
+export const VolumeMeter: React.FC<{
+ mediaStream: StreamState;
+}> = ({ mediaStream }) => {
+ const [currentVolume, setCurrentVolume] = useState(0);
+
+ useEffect(() => {
+ if (mediaStream.type !== "loaded") {
+ return;
+ }
+
+ if (mediaStream.stream.getAudioTracks().length === 0) {
+ return;
+ }
+
+ const audioContext = new AudioContext();
+ const analyser = audioContext.createAnalyser();
+ const microphone = audioContext.createMediaStreamSource(mediaStream.stream);
+ const scriptProcessor = audioContext.createScriptProcessor(512, 1, 1); // (bufferSize, inputChannels, outputChannels).
+
+ analyser.smoothingTimeConstant = 0.9;
+ // An unsigned integer, representing the window size of the FFT, given in number of samples.
+ // A higher value will result in more details in the frequency domain but fewer details in the amplitude domain.
+ analyser.fftSize = 512; // FftSize 512 and minDecibels -123 seems to work pretty similar to OBS volume meter
+ analyser.minDecibels = -123;
+ analyser.maxDecibels = 0;
+
+ microphone.connect(analyser);
+ analyser.connect(scriptProcessor);
+ scriptProcessor.connect(audioContext.destination);
+ const onAudioProcess = () => {
+ const array = new Uint8Array(analyser.frequencyBinCount);
+ // Copies frequency data into array. Frequency data is composed of integers between 0 and 255, representing the volume of each frequency.
+ // Every item in the array represents the decibel value of a specific frequency.
+ analyser.getByteFrequencyData(array);
+ // Get the sum of all decibel values of each frequency in the array
+ const arraySum = array.reduce((a, value) => a + value, 0);
+ let currentAverageVolume = 0;
+ // Get the average volume by dividing the sum by the number of items in the array
+ currentAverageVolume = arraySum / array.length;
+ // Extra smoothing
+ setCurrentVolume((old) => (old + currentAverageVolume) / 2);
+ };
+
+ scriptProcessor.addEventListener("audioprocess", onAudioProcess);
+
+ return () => {
+ scriptProcessor.removeEventListener("audioprocess", onAudioProcess);
+ scriptProcessor.disconnect();
+ };
+ }, [mediaStream]);
+
+ const widthPercent = useMemo(() => {
+ return currentVolume < 100 ? 85 - currentVolume : 0;
+ }, [currentVolume]);
+
+ const dynamicCover: React.CSSProperties = useMemo(() => {
+ const widthPercentageString = widthPercent.toString() + "%";
+
+ return {
+ width: widthPercentageString,
+ height: 4,
+ backgroundColor: "#242424",
+ };
+ }, [widthPercent]);
+
+ if (mediaStream.type !== "loaded") {
+ return null;
+ }
+
+ return (
+ <div style={container}>
+ <div style={gradientStyle}>
+ <div style={dynamicCover} />
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-recorder/src/components/theme-provider.tsx b/packages/template-recorder/src/components/theme-provider.tsx
new file mode 100644
index 0000000000..ac4cfb5f00
--- /dev/null
+++ b/packages/template-recorder/src/components/theme-provider.tsx
@@ -0,0 +1,66 @@
+import { createContext, useEffect, useMemo, useState } from "react";
+
+type Theme = "dark" | "light" | "system";
+
+type ThemeProviderProps = {
+ readonly children: React.ReactNode;
+ readonly defaultTheme?: Theme;
+ readonly storageKey?: string;
+};
+
+type ThemeProviderState = {
+ theme: Theme;
+ setTheme: (theme: Theme) => void;
+};
+
+const initialState: ThemeProviderState = {
+ theme: "system",
+ setTheme: () => null,
+};
+
+const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
+
+export const ThemeProvider = ({
+ children,
+ defaultTheme = "system",
+ storageKey = "vite-ui-theme",
+ ...props
+}: ThemeProviderProps) => {
+ const [theme, setTheme] = useState<Theme>(
+ () => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
+ );
+
+ useEffect(() => {
+ const root = window.document.documentElement;
+
+ root.classList.remove("light", "dark");
+
+ if (theme === "system") {
+ const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
+ .matches
+ ? "dark"
+ : "light";
+
+ root.classList.add(systemTheme);
+ return;
+ }
+
+ root.classList.add(theme);
+ }, [theme]);
+
+ const value = useMemo(() => {
+ return {
+ theme,
+ setTheme: (newTheme: Theme) => {
+ localStorage.setItem(storageKey, newTheme);
+ setTheme(newTheme);
+ },
+ };
+ }, [storageKey, theme]);
+
+ return (
+ <ThemeProviderContext.Provider {...props} value={value}>
+ {children}
+ </ThemeProviderContext.Provider>
+ );
+};
diff --git a/packages/template-recorder/src/components/ui/button.tsx b/packages/template-recorder/src/components/ui/button.tsx
new file mode 100644
index 0000000000..8210d02f90
--- /dev/null
+++ b/packages/template-recorder/src/components/ui/button.tsx
@@ -0,0 +1,56 @@
+import { Slot } from "@radix-ui/react-slot";
+import { cva, type VariantProps } from "class-variance-authority";
+import * as React from "react";
+
+import { cn } from "../../helpers/utils";
+
+const buttonVariants = cva(
+ "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
+ {
+ variants: {
+ variant: {
+ default: "bg-primary text-primary-foreground hover:bg-primary/90",
+ destructive:
+ "bg-destructive text-destructive-foreground hover:bg-destructive/90",
+ outline:
+ "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
+ secondary:
+ "bg-secondary text-secondary-foreground hover:bg-secondary/80",
+ ghost: "hover:bg-accent hover:text-accent-foreground",
+ link: "text-primary underline-offset-4 hover:underline",
+ },
+ size: {
+ default: "h-10 px-4 py-2",
+ sm: "h-9 rounded-md px-3",
+ lg: "h-11 rounded-md px-8",
+ icon: "h-10 w-10",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+interface ButtonProps
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+ VariantProps<typeof buttonVariants> {
+ readonly asChild?: boolean;
+}
+
+const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : "button";
+ return (
+ <Comp
+ ref={ref}
+ className={cn(buttonVariants({ variant, size, className }))}
+ {...props}
+ />
+ );
+ },
+);
+Button.displayName = "Button";
+
+export { Button };
diff --git a/packages/template-recorder/src/components/ui/dialog.tsx b/packages/template-recorder/src/components/ui/dialog.tsx
new file mode 100644
index 0000000000..df8057d1e4
--- /dev/null
+++ b/packages/template-recorder/src/components/ui/dialog.tsx
@@ -0,0 +1,112 @@
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import { X } from "lucide-react";
+import * as React from "react";
+
+import { cn } from "../../helpers/utils";
+
+const Dialog = DialogPrimitive.Root;
+
+const DialogPortal = DialogPrimitive.Portal;
+
+const DialogOverlay = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Overlay
+ ref={ref}
+ className={cn(
+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className,
+ )}
+ {...props}
+ />
+));
+DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
+
+const DialogContent = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
+>(({ className, children, ...props }, ref) => (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ </DialogPrimitive.Content>
+ </DialogPortal>
+));
+DialogContent.displayName = DialogPrimitive.Content.displayName;
+
+const DialogHeader = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col space-y-1.5 text-center sm:text-left",
+ className,
+ )}
+ {...props}
+ />
+);
+DialogHeader.displayName = "DialogHeader";
+
+const DialogFooter = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
+ className,
+ )}
+ {...props}
+ />
+);
+DialogFooter.displayName = "DialogFooter";
+
+const DialogTitle = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Title
+ ref={ref}
+ className={cn(
+ "text-lg font-semibold leading-none tracking-tight",
+ className,
+ )}
+ {...props}
+ />
+));
+DialogTitle.displayName = DialogPrimitive.Title.displayName;
+
+const DialogDescription = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-muted-foreground", className)}
+ {...props}
+ />
+));
+DialogDescription.displayName = DialogPrimitive.Description.displayName;
+
+export {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogFooter,
+ DialogTitle,
+ DialogDescription,
+};
diff --git a/packages/template-recorder/src/components/ui/dropdown-menu.tsx b/packages/template-recorder/src/components/ui/dropdown-menu.tsx
new file mode 100644
index 0000000000..f9196eec5c
--- /dev/null
+++ b/packages/template-recorder/src/components/ui/dropdown-menu.tsx
@@ -0,0 +1,199 @@
+"use client";
+
+import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
+import { Check, ChevronRight, Circle } from "lucide-react";
+import * as React from "react";
+import { cn } from "../../helpers/utils";
+
+const DropdownMenu = DropdownMenuPrimitive.Root;
+
+const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
+
+const DropdownMenuGroup = DropdownMenuPrimitive.Group;
+
+const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
+
+const DropdownMenuSub = DropdownMenuPrimitive.Sub;
+
+const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
+
+const DropdownMenuSubTrigger = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
+ inset?: boolean;
+ }
+>(({ className, inset, children, ...props }, ref) => (
+ <DropdownMenuPrimitive.SubTrigger
+ ref={ref}
+ className={cn(
+ "flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
+ inset && "pl-8",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRight className="ml-auto" />
+ </DropdownMenuPrimitive.SubTrigger>
+));
+DropdownMenuSubTrigger.displayName =
+ DropdownMenuPrimitive.SubTrigger.displayName;
+
+const DropdownMenuSubContent = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
+>(({ className, ...props }, ref) => (
+ <DropdownMenuPrimitive.SubContent
+ ref={ref}
+ className={cn(
+ "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className,
+ )}
+ {...props}
+ />
+));
+DropdownMenuSubContent.displayName =
+ DropdownMenuPrimitive.SubContent.displayName;
+
+const DropdownMenuContent = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
+>(({ className, sideOffset = 4, ...props }, ref) => (
+ <DropdownMenuPrimitive.Portal>
+ <DropdownMenuPrimitive.Content
+ ref={ref}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className,
+ )}
+ {...props}
+ />
+ </DropdownMenuPrimitive.Portal>
+));
+DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
+
+const DropdownMenuItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
+ inset?: boolean;
+ }
+>(({ className, inset, ...props }, ref) => (
+ <DropdownMenuPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
+ inset && "pl-8",
+ className,
+ )}
+ {...props}
+ />
+));
+DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
+
+const DropdownMenuCheckboxItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
+>(({ className, children, checked, ...props }, ref) => (
+ <DropdownMenuPrimitive.CheckboxItem
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className,
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.ItemIndicator>
+ <Check className="h-4 w-4" />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.CheckboxItem>
+));
+DropdownMenuCheckboxItem.displayName =
+ DropdownMenuPrimitive.CheckboxItem.displayName;
+
+const DropdownMenuRadioItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
+>(({ className, children, ...props }, ref) => (
+ <DropdownMenuPrimitive.RadioItem
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className,
+ )}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.ItemIndicator>
+ <Circle className="h-2 w-2 fill-current" />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.RadioItem>
+));
+DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
+
+const DropdownMenuLabel = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Label>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
+ inset?: boolean;
+ }
+>(({ className, inset, ...props }, ref) => (
+ <DropdownMenuPrimitive.Label
+ ref={ref}
+ className={cn(
+ "px-2 py-1.5 text-sm font-semibold",
+ inset && "pl-8",
+ className,
+ )}
+ {...props}
+ />
+));
+DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
+
+const DropdownMenuSeparator = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
+>(({ className, ...props }, ref) => (
+ <DropdownMenuPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 my-1 h-px bg-muted", className)}
+ {...props}
+ />
+));
+DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
+
+const DropdownMenuShortcut = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLSpanElement>) => {
+ return (
+ <span
+ className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
+ {...props}
+ />
+ );
+};
+DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
+
+export {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuPortal,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+};
diff --git a/packages/template-recorder/src/components/ui/input.tsx b/packages/template-recorder/src/components/ui/input.tsx
new file mode 100644
index 0000000000..c2c312858f
--- /dev/null
+++ b/packages/template-recorder/src/components/ui/input.tsx
@@ -0,0 +1,23 @@
+import * as React from "react";
+import { cn } from "../../helpers/utils";
+
+interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
+
+const Input = React.forwardRef<HTMLInputElement, InputProps>(
+ ({ className, type, ...props }, ref) => {
+ return (
+ <input
+ ref={ref}
+ type={type}
+ className={cn(
+ "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ className,
+ )}
+ {...props}
+ />
+ );
+ },
+);
+Input.displayName = "Input";
+
+export { Input };
diff --git a/packages/template-recorder/src/components/ui/label.tsx b/packages/template-recorder/src/components/ui/label.tsx
new file mode 100644
index 0000000000..20a6730754
--- /dev/null
+++ b/packages/template-recorder/src/components/ui/label.tsx
@@ -0,0 +1,23 @@
+import * as LabelPrimitive from "@radix-ui/react-label";
+import { cva, type VariantProps } from "class-variance-authority";
+import * as React from "react";
+import { cn } from "../../helpers/utils";
+
+const labelVariants = cva(
+ "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
+);
+
+const Label = React.forwardRef<
+ React.ElementRef<typeof LabelPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
+ VariantProps<typeof labelVariants>
+>(({ className, ...props }, ref) => (
+ <LabelPrimitive.Root
+ ref={ref}
+ className={cn(labelVariants(), className)}
+ {...props}
+ />
+));
+Label.displayName = LabelPrimitive.Root.displayName;
+
+export { Label };
diff --git a/packages/template-recorder/src/components/ui/select.tsx b/packages/template-recorder/src/components/ui/select.tsx
new file mode 100644
index 0000000000..52bf47f2d9
--- /dev/null
+++ b/packages/template-recorder/src/components/ui/select.tsx
@@ -0,0 +1,115 @@
+import * as SelectPrimitive from "@radix-ui/react-select";
+import { Check, ChevronDown } from "lucide-react";
+import * as React from "react";
+
+import { cn } from "../../helpers/utils";
+
+const Select = SelectPrimitive.Root;
+
+const SelectValue = SelectPrimitive.Value;
+
+const SelectTrigger = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Trigger>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
+>(({ className, children, ...props }, ref) => (
+ <SelectPrimitive.Trigger
+ ref={ref}
+ className={cn(
+ "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <SelectPrimitive.Icon asChild>
+ <ChevronDown className="h-4 w-4 opacity-50" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+));
+SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
+
+const SelectContent = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
+>(({ className, children, position = "popper", ...props }, ref) => (
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ ref={ref}
+ className={cn(
+ "relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ position === "popper" &&
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
+ className,
+ )}
+ position={position}
+ {...props}
+ >
+ <SelectPrimitive.Viewport
+ className={cn(
+ "p-1",
+ position === "popper" &&
+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
+ )}
+ >
+ {children}
+ </SelectPrimitive.Viewport>
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+));
+SelectContent.displayName = SelectPrimitive.Content.displayName;
+
+const SelectLabel = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Label>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.Label
+ ref={ref}
+ className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
+ {...props}
+ />
+));
+SelectLabel.displayName = SelectPrimitive.Label.displayName;
+
+const SelectItem = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
+>(({ className, children, ...props }, ref) => (
+ <SelectPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className,
+ )}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <SelectPrimitive.ItemIndicator>
+ <Check className="h-4 w-4" />
+ </SelectPrimitive.ItemIndicator>
+ </span>
+
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ </SelectPrimitive.Item>
+));
+SelectItem.displayName = SelectPrimitive.Item.displayName;
+
+const SelectSeparator = React.forwardRef<
+ React.ElementRef<typeof SelectPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
+>(({ className, ...props }, ref) => (
+ <SelectPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 my-1 h-px bg-muted", className)}
+ {...props}
+ />
+));
+SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
+
+export {
+ Select,
+ SelectValue,
+ SelectTrigger,
+ SelectContent,
+ SelectItem,
+ SelectSeparator,
+};
diff --git a/packages/template-recorder/src/components/ui/toggle.tsx b/packages/template-recorder/src/components/ui/toggle.tsx
new file mode 100644
index 0000000000..51e0e15f41
--- /dev/null
+++ b/packages/template-recorder/src/components/ui/toggle.tsx
@@ -0,0 +1,43 @@
+import * as TogglePrimitive from "@radix-ui/react-toggle";
+import { cva, type VariantProps } from "class-variance-authority";
+import * as React from "react";
+
+import { cn } from "../../helpers/utils";
+
+const toggleVariants = cva(
+ "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ outline:
+ "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
+ },
+ size: {
+ default: "h-10 px-3",
+ sm: "h-9 px-2.5",
+ lg: "h-11 px-5",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+const Toggle = React.forwardRef<
+ React.ElementRef<typeof TogglePrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &
+ VariantProps<typeof toggleVariants>
+>(({ className, variant, size, ...props }, ref) => (
+ <TogglePrimitive.Root
+ ref={ref}
+ className={cn(toggleVariants({ variant, size, className }))}
+ {...props}
+ />
+));
+
+Toggle.displayName = TogglePrimitive.Root.displayName;
+
+export { Toggle };
diff --git a/packages/template-recorder/src/deviceitem.module.css b/packages/template-recorder/src/deviceitem.module.css
new file mode 100644
index 0000000000..db14e19b4d
--- /dev/null
+++ b/packages/template-recorder/src/deviceitem.module.css
@@ -0,0 +1,3 @@
+.item:hover {
+ background-color: rgba(255, 255, 255, 0.1);
+}
diff --git a/packages/template-recorder/src/helpers/browser-support.ts b/packages/template-recorder/src/helpers/browser-support.ts
new file mode 100644
index 0000000000..c022515d94
--- /dev/null
+++ b/packages/template-recorder/src/helpers/browser-support.ts
@@ -0,0 +1,20 @@
+export const canUseWebFsWriter = async () => {
+ if (!("storage" in navigator)) {
+ return false;
+ }
+
+ if (!("getDirectory" in navigator.storage)) {
+ return false;
+ }
+
+ const directoryHandle = await navigator.storage.getDirectory();
+ const fileHandle = await directoryHandle.getFileHandle(
+ "remotion-probe-web-fs-support",
+ {
+ create: true,
+ },
+ );
+
+ const canUse = fileHandle.createWritable !== undefined;
+ return canUse;
+};
diff --git a/packages/template-recorder/src/helpers/can-rotate-camera.ts b/packages/template-recorder/src/helpers/can-rotate-camera.ts
new file mode 100644
index 0000000000..9f79a39222
--- /dev/null
+++ b/packages/template-recorder/src/helpers/can-rotate-camera.ts
@@ -0,0 +1,36 @@
+import type { Dimensions } from "../../config/layout";
+import type { SelectedSource } from "./get-selected-video-source";
+
+export const canRotateCamera = ({
+ selectedSource,
+ preferPortrait,
+ resolution,
+}: {
+ selectedSource: SelectedSource | null;
+ preferPortrait: boolean;
+ resolution: Dimensions | null;
+}) => {
+ if (selectedSource === null) {
+ return false;
+ }
+
+ if (selectedSource.type !== "camera") {
+ return false;
+ }
+
+ if (resolution === null) {
+ return false;
+ }
+
+ if (preferPortrait) {
+ return (
+ selectedSource.maxWidth === null ||
+ selectedSource.maxWidth > resolution.width
+ );
+ }
+
+ return (
+ selectedSource.maxHeight === null ||
+ selectedSource.maxHeight > resolution.height
+ );
+};
diff --git a/packages/template-recorder/src/helpers/cancel-transcribe.ts b/packages/template-recorder/src/helpers/cancel-transcribe.ts
new file mode 100644
index 0000000000..db78fe83d4
--- /dev/null
+++ b/packages/template-recorder/src/helpers/cancel-transcribe.ts
@@ -0,0 +1,10 @@
+import { CANCEL_TRANSCRIBE } from "../../scripts/server/constants";
+
+export const cancelTranscribeOnServer = async () => {
+ const url = new URL(CANCEL_TRANSCRIBE, window.location.origin);
+
+ const res = await fetch(url);
+ if (!res.ok) {
+ throw new Error("Not OK");
+ }
+};
diff --git a/packages/template-recorder/src/helpers/convert-in-browser.ts b/packages/template-recorder/src/helpers/convert-in-browser.ts
new file mode 100644
index 0000000000..06f630765a
--- /dev/null
+++ b/packages/template-recorder/src/helpers/convert-in-browser.ts
@@ -0,0 +1,32 @@
+import { webReader } from "@remotion/media-parser/web";
+import {
+ ConvertMediaProgress,
+ convertMedia,
+ webcodecsController,
+} from "@remotion/webcodecs";
+import { getExtension } from "./find-good-supported-codec";
+export const convertInBrowser = ({
+ src,
+ onProgress,
+ mimeType,
+}: {
+ src: Blob;
+ onProgress: (progress: ConvertMediaProgress, abort: () => void) => void;
+ mimeType: string;
+}) => {
+ const controller = webcodecsController();
+
+ return convertMedia({
+ container: getExtension(mimeType),
+ src: new File([src.slice()], `temp`),
+ reader: webReader,
+ resize: {
+ maxHeight: 1080,
+ mode: "max-height",
+ },
+ onProgress: (progress) => {
+ onProgress?.(progress, () => controller.abort());
+ },
+ controller: controller,
+ });
+};
diff --git a/packages/template-recorder/src/helpers/download-video.ts b/packages/template-recorder/src/helpers/download-video.ts
new file mode 100644
index 0000000000..29ed5acfce
--- /dev/null
+++ b/packages/template-recorder/src/helpers/download-video.ts
@@ -0,0 +1,48 @@
+import { ProcessStatus } from "../components/ProcessingStatus";
+import { convertInBrowser } from "./convert-in-browser";
+import { getExtension } from "./find-good-supported-codec";
+import { formatMilliseconds } from "./format-time";
+
+export const downloadVideo = async ({
+ data,
+ endDate,
+ prefix,
+ setStatus,
+ mimeType,
+}: {
+ data: Blob;
+ endDate: number;
+ prefix: string;
+ mimeType: string;
+ setStatus: React.Dispatch<React.SetStateAction<ProcessStatus | null>>;
+}) => {
+ const webcamchunks: Blob[] = [];
+ if (data.size > 0) {
+ webcamchunks.push(data);
+ }
+
+ const result = await convertInBrowser({
+ src: data,
+ mimeType,
+ onProgress: ({ millisecondsWritten }, abortFn) => {
+ setStatus({
+ title: `Converting ${prefix}${endDate}.${getExtension(mimeType)}`,
+ description: `${formatMilliseconds(millisecondsWritten)} processed`,
+ abort: abortFn,
+ });
+ },
+ });
+
+ const saved = await result.save();
+
+ const link = document.createElement("a");
+ const blobUrl = URL.createObjectURL(saved);
+ link.href = blobUrl;
+ link.download = `${prefix}${endDate}.${getExtension(mimeType)}`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+
+ window.URL.revokeObjectURL(blobUrl);
+ setStatus(null);
+};
diff --git a/packages/template-recorder/src/helpers/enumerate-devices-or-time-out.ts b/packages/template-recorder/src/helpers/enumerate-devices-or-time-out.ts
new file mode 100644
index 0000000000..5efb7af31d
--- /dev/null
+++ b/packages/template-recorder/src/helpers/enumerate-devices-or-time-out.ts
@@ -0,0 +1,24 @@
+export const enumerateDevicesOrTimeOut = async () => {
+ let clear = () => undefined;
+
+ const timeOut = new Promise<MediaDeviceInfo[]>((_, reject) => {
+ const int = setTimeout(() => {
+ reject(
+ new Error(
+ "navigator.mediaDevices.enumerateDevices() has not responded within 10000ms. Usually this can be fixed by restarting your browser.",
+ ),
+ );
+ }, 10000);
+
+ clear = () => {
+ clearTimeout(int);
+ };
+ });
+
+ const result = await Promise.race<MediaDeviceInfo[]>([
+ timeOut,
+ navigator.mediaDevices.enumerateDevices(),
+ ]);
+ clear();
+ return result;
+};
diff --git a/packages/template-recorder/src/helpers/find-good-supported-codec.ts b/packages/template-recorder/src/helpers/find-good-supported-codec.ts
new file mode 100644
index 0000000000..b1e48a9a00
--- /dev/null
+++ b/packages/template-recorder/src/helpers/find-good-supported-codec.ts
@@ -0,0 +1,40 @@
+const MP4_WITH_AUDIO = "video/mp4;codecs=avc1,mp4a.40.2";
+const MP4_WITHOUT_AUDIO = "video/mp4;codecs=avc1";
+const WEBM_WITH_AUDIO = "video/webm;codecs=vp8,opus";
+const WEBM_WITHOUT_AUDIO = "video/webm;codecs=vp8";
+
+export const findGoodSupportedCodec = (withAudio: boolean) => {
+ if (withAudio) {
+ if (MediaRecorder.isTypeSupported(MP4_WITH_AUDIO)) {
+ return MP4_WITH_AUDIO;
+ }
+
+ if (MediaRecorder.isTypeSupported(WEBM_WITH_AUDIO)) {
+ return WEBM_WITH_AUDIO;
+ }
+
+ throw new Error("No supported codec found");
+ }
+
+ if (MediaRecorder.isTypeSupported(MP4_WITHOUT_AUDIO)) {
+ return MP4_WITHOUT_AUDIO;
+ }
+
+ if (MediaRecorder.isTypeSupported(WEBM_WITHOUT_AUDIO)) {
+ return WEBM_WITHOUT_AUDIO;
+ }
+
+ throw new Error("No supported codec found");
+};
+
+export const getExtension = (mimeType: string) => {
+ if (mimeType.includes("mp4")) {
+ return "mp4";
+ }
+
+ if (mimeType.includes("webm")) {
+ return "webm";
+ }
+
+ throw new Error("Unsupported mime type: " + mimeType);
+};
diff --git a/packages/template-recorder/src/helpers/format-device-label.ts b/packages/template-recorder/src/helpers/format-device-label.ts
new file mode 100644
index 0000000000..7b51a374ba
--- /dev/null
+++ b/packages/template-recorder/src/helpers/format-device-label.ts
@@ -0,0 +1,44 @@
+export type Label = { id: string; label: string };
+
+const removeUsbIdentifier = (label: string) => {
+ return label.replace(/\(\w{4}:\w{4}\)/, "").trim();
+};
+
+const removeBuiltIn = (label: string) => {
+ return label.replace(/\(Built-in\)/, "").trim();
+};
+
+const removeVirtual = (label: string) => {
+ return label.replace(/\(Virtual\)/, "").trim();
+};
+const removeMdevice = (label: string) => {
+ return label.replace(/\(m-de:vice\)/, "").trim();
+};
+
+const takeStringInBraces = (label: string): string => {
+ const match = label.match(/\((.*)\)/);
+ if (!match) {
+ return label;
+ }
+
+ if (match[1] === "Bluetooth") {
+ return label.replace(/\(Bluetooth\)/, "").trim();
+ }
+
+ return match[1] as string;
+};
+
+const removeLeadingNumber = (label: string) => {
+ return label.replace(/^\d+- /, "").trim();
+};
+
+export const formatDeviceLabel = (label: string) => {
+ const withoutUsb = removeUsbIdentifier(label);
+ const withoutBuiltIn = removeBuiltIn(withoutUsb);
+ const withoutVirtual = removeVirtual(withoutBuiltIn);
+ const withoutDevice = removeMdevice(withoutVirtual);
+ const stringFromBraces = takeStringInBraces(withoutDevice);
+ const withoutLeadingNumber = removeLeadingNumber(stringFromBraces);
+
+ return withoutLeadingNumber;
+};
diff --git a/packages/template-recorder/src/helpers/format-time.ts b/packages/template-recorder/src/helpers/format-time.ts
new file mode 100644
index 0000000000..eb829e05e0
--- /dev/null
+++ b/packages/template-recorder/src/helpers/format-time.ts
@@ -0,0 +1,19 @@
+export const formatMilliseconds = (ms: number) => {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+
+ const formattedSeconds = seconds % 60;
+ const formattedMinutes = minutes % 60;
+
+ const timeArray = [];
+
+ if (hours > 0) {
+ timeArray.push(hours.toString().padStart(2, "0"));
+ }
+
+ timeArray.push(formattedMinutes.toString().padStart(2, "0"));
+ timeArray.push(formattedSeconds.toString().padStart(2, "0"));
+
+ return timeArray.join(":");
+};
diff --git a/packages/template-recorder/src/helpers/get-devices.ts b/packages/template-recorder/src/helpers/get-devices.ts
new file mode 100644
index 0000000000..bc17133f5d
--- /dev/null
+++ b/packages/template-recorder/src/helpers/get-devices.ts
@@ -0,0 +1,51 @@
+import { enumerateDevicesOrTimeOut } from "./enumerate-devices-or-time-out";
+import { Label, formatDeviceLabel } from "./format-device-label";
+
+export const storeLabelsToLS = (devices: MediaDeviceInfo[]) => {
+ const labels: Label[] = JSON.parse(localStorage.getItem("labels") ?? "[]");
+ devices.forEach((device) => {
+ const id = device.deviceId;
+ const cleanLabel = formatDeviceLabel(device.label);
+
+ if (!labels.some((l) => l.id === id) && cleanLabel !== "") {
+ labels.push({ id, label: cleanLabel });
+ }
+ });
+
+ localStorage.setItem("labels", JSON.stringify(labels));
+};
+
+export const hasNewDevices = (devices: MediaDeviceInfo[]): boolean => {
+ const labels: Label[] = JSON.parse(localStorage.getItem("labels") || "[]");
+
+ const hasNew = !devices.every((device) => {
+ return labels.some((l) => l.id === device.deviceId);
+ });
+
+ return hasNew;
+};
+
+export const getDevices = async () => {
+ const fetchedDevices = await enumerateDevicesOrTimeOut();
+
+ const hasEmptyLabels = fetchedDevices.some((device) => device.label === "");
+ const hasNew = hasNewDevices(fetchedDevices);
+ if (hasNew && hasEmptyLabels) {
+ const stream = await navigator.mediaDevices.getUserMedia({
+ video: true,
+ audio: true,
+ });
+ const _devices = await navigator.mediaDevices.enumerateDevices();
+ storeLabelsToLS(_devices);
+ stream.getAudioTracks().forEach((track) => track.stop());
+ stream.getVideoTracks().forEach((track) => track.stop());
+
+ return _devices;
+ }
+
+ if (hasNew) {
+ storeLabelsToLS(fetchedDevices);
+ }
+
+ return fetchedDevices;
+};
diff --git a/packages/template-recorder/src/helpers/get-folders.ts b/packages/template-recorder/src/helpers/get-folders.ts
new file mode 100644
index 0000000000..ae664b07f1
--- /dev/null
+++ b/packages/template-recorder/src/helpers/get-folders.ts
@@ -0,0 +1,31 @@
+const KEY = "remotionrecorder.selectedFolder";
+
+const params = new URLSearchParams(window.location.search);
+const folderFromUrl = params.get("folder");
+
+export const loadFolderFromUrl = () => {
+ if (!folderFromUrl) {
+ return null;
+ }
+
+ const newUrl = window.location.origin + window.location.pathname;
+ window.history.replaceState({}, "", newUrl);
+ return folderFromUrl;
+};
+
+export const loadSelectedFolder = () => {
+ if (!window.remotionServerEnabled) {
+ return null;
+ }
+
+ const projectFromLS = window.localStorage.getItem(KEY);
+ if (projectFromLS === "") {
+ return null;
+ }
+
+ return projectFromLS;
+};
+
+export const persistSelectedFolder = (folder: string) => {
+ window.localStorage.setItem(KEY, folder);
+};
diff --git a/packages/template-recorder/src/helpers/get-max-resolution-of-device.ts b/packages/template-recorder/src/helpers/get-max-resolution-of-device.ts
new file mode 100644
index 0000000000..7879298009
--- /dev/null
+++ b/packages/template-recorder/src/helpers/get-max-resolution-of-device.ts
@@ -0,0 +1,33 @@
+export type MaxResolution = {
+ width: number | null;
+ height: number | null;
+ frameRate: number | null;
+};
+
+export const getMaxResolutionOfDevice = (
+ device: MediaDeviceInfo,
+): MaxResolution | null => {
+ if (typeof InputDeviceInfo === "undefined") {
+ return null;
+ }
+
+ if (!(device instanceof InputDeviceInfo)) {
+ return null;
+ }
+
+ const capabilities = device.getCapabilities();
+
+ const width = capabilities.width?.max ?? null;
+ const height = capabilities.height?.max ?? null;
+ const frameRate = capabilities.frameRate?.max ?? null;
+
+ if (width === null && height === null) {
+ return null;
+ }
+
+ return {
+ width,
+ height,
+ frameRate,
+ } as MaxResolution;
+};
diff --git a/packages/template-recorder/src/helpers/get-selected-video-source.ts b/packages/template-recorder/src/helpers/get-selected-video-source.ts
new file mode 100644
index 0000000000..a621a130c4
--- /dev/null
+++ b/packages/template-recorder/src/helpers/get-selected-video-source.ts
@@ -0,0 +1,84 @@
+import { Dimensions } from "../../config/layout";
+import { DEFAULT_MINIMUM_FPS } from "../preferred-resolution";
+import { MaxResolution } from "./get-max-resolution-of-device";
+
+export type SelectedSource =
+ | {
+ type: "camera";
+ deviceId: string;
+ maxWidth: number | null;
+ maxHeight: number | null;
+ minFps: number | null;
+ }
+ | {
+ type: "display-without-audio";
+ }
+ | {
+ type: "display-with-audio";
+ };
+
+export type VideoSize = "4K" | "1080p" | "720p" | "480p";
+
+export type SizeConstraint = {
+ maxSize: VideoSize | null;
+ minimumFps: number | null;
+};
+
+export const FPS_AVAILABLE = [240, 120, 60, 30];
+
+export const VIDEO_SIZES: { [key in VideoSize]: Dimensions } = {
+ "4K": { width: 3840, height: 2160 },
+ "1080p": { width: 1920, height: 1080 },
+ "720p": { width: 1280, height: 720 },
+ "480p": { width: 640, height: 480 },
+};
+
+export const getSelectedVideoSource = ({
+ resolutionConstraint,
+ maxResolution,
+ device,
+}: {
+ resolutionConstraint: SizeConstraint;
+ maxResolution: MaxResolution | null;
+ device: MediaDeviceInfo;
+}): SelectedSource | null => {
+ const constrainedWidth =
+ resolutionConstraint.maxSize === null
+ ? null
+ : VIDEO_SIZES[resolutionConstraint.maxSize].width;
+ const constrainedHeight =
+ resolutionConstraint.maxSize === null
+ ? null
+ : VIDEO_SIZES[resolutionConstraint.maxSize].height;
+
+ if (maxResolution === null) {
+ return {
+ type: "camera",
+ deviceId: device.deviceId,
+ maxWidth: constrainedWidth,
+ maxHeight: constrainedHeight,
+ minFps: null,
+ };
+ }
+
+ const maxWidth =
+ constrainedWidth === null
+ ? maxResolution.width
+ : Math.min(constrainedWidth, maxResolution.width ?? Infinity);
+ const maxHeight =
+ constrainedHeight === null
+ ? maxResolution.height
+ : Math.min(constrainedHeight, maxResolution.height ?? Infinity);
+ const minFps = Math.min(
+ maxResolution.frameRate ?? Infinity,
+ resolutionConstraint.minimumFps ?? DEFAULT_MINIMUM_FPS,
+ );
+
+ return {
+ type: "camera",
+ deviceId: device.deviceId,
+ maxWidth: maxWidth,
+ maxHeight: maxHeight,
+ minFps: minFps,
+ };
+};
diff --git a/packages/template-recorder/src/helpers/get-video-stream.ts b/packages/template-recorder/src/helpers/get-video-stream.ts
new file mode 100644
index 0000000000..1d01fab149
--- /dev/null
+++ b/packages/template-recorder/src/helpers/get-video-stream.ts
@@ -0,0 +1,106 @@
+import { DEFAULT_MINIMUM_FPS } from "../preferred-resolution";
+import { SelectedSource } from "./get-selected-video-source";
+
+const getDisplayStream = async (selectedVideoSource: SelectedSource) => {
+ if (
+ selectedVideoSource.type !== "display-without-audio" &&
+ selectedVideoSource.type !== "display-with-audio"
+ ) {
+ throw new Error("Unknown video source type");
+ }
+
+ const stream = await window.navigator.mediaDevices
+ // GetDisplayMedia asks the user for permission to capture the screen
+ .getDisplayMedia({
+ video: {
+ height: {
+ ideal: 1080,
+ },
+ },
+ audio: selectedVideoSource.type === "display-with-audio",
+ });
+
+ return stream;
+};
+
+export const getCameraStreamConstraints = (
+ selectedVideoSource: SelectedSource,
+ preferPortrait: boolean,
+) => {
+ if (selectedVideoSource.type !== "camera") {
+ return null;
+ }
+ const video: MediaTrackConstraints = {
+ deviceId: selectedVideoSource.deviceId,
+ width: preferPortrait
+ ? undefined
+ : selectedVideoSource.maxWidth
+ ? { ideal: selectedVideoSource.maxWidth }
+ : undefined,
+ height: preferPortrait
+ ? selectedVideoSource.maxHeight
+ ? { ideal: selectedVideoSource.maxHeight }
+ : undefined
+ : undefined,
+ frameRate: {
+ min: selectedVideoSource.minFps ?? DEFAULT_MINIMUM_FPS,
+ },
+ };
+ return video;
+};
+
+const getCameraStram = ({
+ selectedVideoSource,
+ preferPortrait,
+ recordAudio,
+ selectedAudioSource,
+}: {
+ selectedVideoSource: SelectedSource;
+ preferPortrait: boolean;
+ recordAudio: boolean;
+ selectedAudioSource: ConstrainDOMString | null;
+}): Promise<MediaStream> => {
+ if (selectedVideoSource.type !== "camera") {
+ throw new Error("Unknown video source type");
+ }
+ const video = getCameraStreamConstraints(selectedVideoSource, preferPortrait);
+
+ const mediaStreamConstraints: MediaStreamConstraints = {
+ video: video ?? undefined,
+ audio:
+ recordAudio && selectedAudioSource
+ ? { deviceId: selectedAudioSource }
+ : undefined,
+ };
+
+ return window.navigator.mediaDevices.getUserMedia(mediaStreamConstraints);
+};
+
+export const getVideoStream = async ({
+ selectedVideoSource,
+ preferPortrait,
+ recordAudio,
+ selectedAudioSource,
+}: {
+ selectedVideoSource: SelectedSource;
+ preferPortrait: boolean;
+ recordAudio: boolean;
+ selectedAudioSource: ConstrainDOMString | null;
+}): Promise<MediaStream> => {
+ if (selectedVideoSource.type === "display-with-audio") {
+ return getDisplayStream(selectedVideoSource);
+ }
+ if (selectedVideoSource.type === "display-without-audio") {
+ return getDisplayStream(selectedVideoSource);
+ }
+ if (selectedVideoSource.type === "camera") {
+ return getCameraStram({
+ selectedVideoSource,
+ preferPortrait,
+ recordAudio,
+ selectedAudioSource,
+ });
+ }
+
+ throw new Error("Unknown video source type");
+};
diff --git a/packages/template-recorder/src/helpers/prefixes.ts b/packages/template-recorder/src/helpers/prefixes.ts
new file mode 100644
index 0000000000..87e61eea65
--- /dev/null
+++ b/packages/template-recorder/src/helpers/prefixes.ts
@@ -0,0 +1,15 @@
+import {
+ ALTERNATIVE1_PREFIX,
+ ALTERNATIVE2_PREFIX,
+ DISPLAY_PREFIX,
+ WEBCAM_PREFIX,
+} from "../../config/cameras";
+
+export const prefixes = [
+ WEBCAM_PREFIX,
+ DISPLAY_PREFIX,
+ ALTERNATIVE1_PREFIX,
+ ALTERNATIVE2_PREFIX,
+] as const;
+
+export type Prefix = (typeof prefixes)[number];
diff --git a/packages/template-recorder/src/helpers/start-media-recorder.ts b/packages/template-recorder/src/helpers/start-media-recorder.ts
new file mode 100644
index 0000000000..c020ff3c65
--- /dev/null
+++ b/packages/template-recorder/src/helpers/start-media-recorder.ts
@@ -0,0 +1,124 @@
+import { CurrentRecorder } from "../RecordButton";
+import { StreamState } from "../state/media-sources";
+import {
+ findGoodSupportedCodec,
+ getExtension,
+} from "./find-good-supported-codec";
+import { Prefix } from "./prefixes";
+import { createFileStorage } from "./store-file";
+
+const mediaRecorderOptions: MediaRecorderOptions = {
+ audioBitsPerSecond: 128000,
+ videoBitsPerSecond: 8 * 4000000,
+ // @ts-expect-error - not in the types yet
+ videoKeyFrameIntervalDuration: 2 * 1000,
+};
+
+export type FinishedRecording = {
+ prefix: string;
+ data: () => Promise<Blob>;
+ releaseData: () => Promise<void>;
+ endDate: number;
+ mimeType: string;
+};
+
+export const startMediaRecorder = async ({
+ prefix,
+ timestamp,
+ source,
+}: {
+ prefix: Prefix;
+ timestamp: number;
+ source: StreamState;
+}): Promise<CurrentRecorder | null> => {
+ if (source.type !== "loaded") {
+ throw new Error(`Source not loaded for ${prefix}`);
+ }
+
+ const mimeType = findGoodSupportedCodec(
+ source.stream.getAudioTracks().length > 0,
+ );
+
+ const completeMediaRecorderOptions = {
+ ...mediaRecorderOptions,
+ mimeType,
+ };
+
+ const extension = getExtension(mimeType);
+ const filename = `${prefix}${timestamp}.${extension}`;
+
+ const recorder = new MediaRecorder(
+ source.stream,
+ completeMediaRecorderOptions,
+ );
+ const writer = await createFileStorage(`${filename}`);
+
+ const periodicSaveController = new AbortController();
+
+ recorder.addEventListener(
+ "dataavailable",
+ ({ data }) => {
+ writer.write(data).then(() => {
+ console.log("Data written", filename, writer.getBytesWritten());
+ });
+ },
+ {
+ signal: periodicSaveController.signal,
+ },
+ );
+
+ const stopAndWaitUntilDone = () => {
+ periodicSaveController.abort();
+ const { resolve, reject, promise } =
+ Promise.withResolvers<FinishedRecording>();
+ const controller = new AbortController();
+
+ recorder.stop();
+ recorder.addEventListener(
+ "error",
+ (event) => {
+ console.log(event);
+ reject(new Error(`Error recording ${prefix}`));
+ },
+ {
+ once: true,
+ signal: controller.signal,
+ },
+ );
+ recorder.addEventListener(
+ "dataavailable",
+ ({ data }) => {
+ writer
+ .write(data)
+ .then(() => {
+ console.log(
+ "Final Data written",
+ filename,
+ writer.getBytesWritten(),
+ );
+ resolve({
+ prefix,
+ data: () => writer.save(),
+ endDate: Date.now(),
+ releaseData: () => writer.release(),
+ mimeType,
+ });
+ })
+ .catch((err) => reject(err));
+ },
+ {
+ once: true,
+ signal: controller.signal,
+ },
+ );
+
+ promise.finally(() => controller.abort());
+
+ return promise;
+ };
+
+ // Trigger a save every 10 seconds
+ recorder.start(10_000);
+
+ return { recorder, stopAndWaitUntilDone, mimeType };
+};
diff --git a/packages/template-recorder/src/helpers/store-file.ts b/packages/template-recorder/src/helpers/store-file.ts
new file mode 100644
index 0000000000..af9407d7ec
--- /dev/null
+++ b/packages/template-recorder/src/helpers/store-file.ts
@@ -0,0 +1,53 @@
+export const createFileStorage = async (filename: string) => {
+ const directoryHandle = await navigator.storage.getDirectory();
+
+ const fileHandle = await directoryHandle.getFileHandle(filename, {
+ create: true,
+ });
+ const writable = await fileHandle.createWritable();
+
+ let written = 0;
+ let writPromise = Promise.resolve();
+
+ const write = async (data: Uint8Array | Blob) => {
+ await writable.write({
+ type: "write",
+ position: written,
+ data: data,
+ });
+ written += data instanceof Blob ? data.size : data.byteLength;
+ };
+
+ return {
+ write: async (data: Blob) => {
+ writPromise = writPromise.then(() => write(data));
+ return writPromise;
+ },
+ save: async () => {
+ await writPromise;
+
+ try {
+ await writable.close();
+ } catch {
+ // Ignore, could already be closed
+ }
+
+ const newHandle = await directoryHandle.getFileHandle(filename, {
+ create: true,
+ });
+ const newFile = await newHandle.getFile();
+ return newFile;
+ },
+ getBytesWritten: () => written,
+ release: async () => {
+ try {
+ await writable.close();
+ } catch {
+ // Ignore, could already be closed
+ }
+ await directoryHandle.removeEntry(filename, {
+ recursive: true,
+ });
+ },
+ };
+};
diff --git a/packages/template-recorder/src/helpers/transcribe-video.ts b/packages/template-recorder/src/helpers/transcribe-video.ts
new file mode 100644
index 0000000000..b48ab72212
--- /dev/null
+++ b/packages/template-recorder/src/helpers/transcribe-video.ts
@@ -0,0 +1,87 @@
+import { makeStreamer } from "@remotion/streaming";
+import { TRANSCRIBE_VIDEO } from "../../scripts/server/constants";
+import {
+ MessageTypeId,
+ StreamingMessage,
+ formatMap,
+ messageTypeIdToMessageType,
+} from "../../scripts/server/streaming";
+import { ProcessStatus } from "../components/ProcessingStatus";
+import { cancelTranscribeOnServer } from "./cancel-transcribe";
+import { parseJsonOrThrowSource } from "./upload-file";
+
+export const transcribeVideoOnServer = async ({
+ onProgress,
+ endDate,
+ selectedFolder,
+}: {
+ onProgress: (status: ProcessStatus) => void;
+ endDate: number;
+ selectedFolder: string;
+}) => {
+ const url = new URL(TRANSCRIBE_VIDEO, window.location.origin);
+
+ url.search = new URLSearchParams({
+ folder: selectedFolder,
+ endDateAsString: endDate.toString(),
+ }).toString();
+
+ const streamer = makeStreamer((status, messageTypeId, data) => {
+ const messageType = messageTypeIdToMessageType(
+ messageTypeId as MessageTypeId,
+ );
+ const innerPayload =
+ formatMap[messageType] === "json"
+ ? parseJsonOrThrowSource(data, messageType)
+ : data;
+
+ const { message }: StreamingMessage = {
+ successType: status,
+ message: {
+ type: messageType,
+ payload: innerPayload,
+ },
+ };
+
+ if (message.type === "transcribing-progress") {
+ onProgress({
+ title: `Transcribing ${message.payload.filename}`,
+ description: `${message.payload.progress}%`,
+ abort: () => cancelTranscribeOnServer(),
+ });
+ }
+ if (message.type === "install-whisper-progress") {
+ onProgress({
+ title: `Installing Whisper`,
+ description: `See console for progress`,
+ abort: () => cancelTranscribeOnServer(),
+ });
+ }
+ if (message.type === "downloading-whisper-model-progress") {
+ onProgress({
+ title: `Downloading Whisper model`,
+ description: `${Math.round(message.payload.progressInPercent)}%`,
+ abort: () => cancelTranscribeOnServer(),
+ });
+ }
+ if (message.type === "whisper-abort") {
+ throw new Error("aborted by user");
+ }
+ });
+
+ const res = await fetch(url, {});
+ if (!res.body) {
+ throw new Error("No body");
+ }
+
+ const reader = res.body.getReader();
+
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const { value, done } = await reader.read();
+ if (value) {
+ streamer.onData(value);
+ }
+ if (done) break;
+ }
+};
diff --git a/packages/template-recorder/src/helpers/upload-file.ts b/packages/template-recorder/src/helpers/upload-file.ts
new file mode 100644
index 0000000000..05778c27c6
--- /dev/null
+++ b/packages/template-recorder/src/helpers/upload-file.ts
@@ -0,0 +1,51 @@
+import { UPLOAD_VIDEO } from "../../scripts/server/constants";
+import { getExtension } from "./find-good-supported-codec";
+
+export const parseJsonOrThrowSource = (data: Uint8Array, type: string) => {
+ const asString = new TextDecoder("utf-8").decode(data);
+ try {
+ return JSON.parse(asString);
+ } catch (err) {
+ throw new Error(`Invalid JSON (${type}): ${asString}`);
+ }
+};
+
+export const uploadFileToServer = async ({
+ blob,
+ endDate,
+ prefix,
+ selectedFolder,
+ expectedFrames,
+ mimeType,
+}: {
+ blob: Blob;
+ endDate: number;
+ prefix: string;
+ selectedFolder: string;
+ expectedFrames: number;
+ mimeType: string;
+}) => {
+ const extension = getExtension(mimeType);
+ const videoFile = new File([blob], `${prefix}${endDate}.${extension}`, {
+ type: mimeType,
+ });
+
+ const url = new URL(UPLOAD_VIDEO, window.location.origin);
+
+ url.search = new URLSearchParams({
+ folder: selectedFolder,
+ prefix,
+ endDateAsString: endDate.toString(),
+ expectedFrames: String(expectedFrames),
+ extension,
+ }).toString();
+
+ const res = await fetch(url, {
+ method: "POST",
+ body: videoFile,
+ });
+ if (!res.body) {
+ throw new Error("No body");
+ }
+ await res.text();
+};
diff --git a/packages/template-recorder/src/helpers/use-element-size.ts b/packages/template-recorder/src/helpers/use-element-size.ts
new file mode 100644
index 0000000000..d7f7c4d1d2
--- /dev/null
+++ b/packages/template-recorder/src/helpers/use-element-size.ts
@@ -0,0 +1,111 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import type { Rect } from "../../remotion/layout/layout-types";
+
+// If a pane has been moved, it will cause a layout shift without
+// the window having been resized. Those UI elements can call this API to
+// force an update
+
+type ElementSizeForceUpdate = () => void;
+
+let elementSizeHooks: ElementSizeForceUpdate[] = [];
+
+export const useElementSize = (
+ ref: React.RefObject<HTMLElement>,
+): Rect | null => {
+ const [size, setSize] = useState<Rect | null>(() => {
+ if (!ref.current) {
+ return null;
+ }
+
+ const [rect] = ref.current.getClientRects();
+
+ return rect ?? null;
+ });
+
+ const observer = useMemo(() => {
+ if (typeof ResizeObserver === "undefined") {
+ return null;
+ }
+
+ return new ResizeObserver(([entry]) => {
+ if (!entry) {
+ return;
+ }
+
+ // The contentRect returns the width without any `scale()`'s being applied. The height is wrong
+ const { target } = entry;
+ // The clientRect returns the size with `scale()` being applied.
+ const [newSize] = target.getClientRects();
+
+ if (!newSize) {
+ setSize(null);
+ return;
+ }
+
+ setSize(newSize);
+ });
+ }, []);
+
+ const updateSize = useCallback(() => {
+ if (!ref.current) {
+ return;
+ }
+
+ const [rect] = ref.current.getClientRects();
+
+ if (!rect) {
+ setSize(null);
+ return;
+ }
+
+ setSize((prevState) => {
+ const isSame =
+ prevState &&
+ prevState.width === rect.width &&
+ prevState.height === rect.height &&
+ prevState.left === rect.left &&
+ prevState.top === rect.top;
+
+ if (isSame) {
+ return prevState;
+ }
+
+ return rect;
+ });
+ }, [ref]);
+
+ useEffect(() => {
+ if (!observer) {
+ return;
+ }
+
+ const { current } = ref;
+ if (ref.current) {
+ observer.observe(ref.current);
+ }
+
+ return (): void => {
+ if (current) {
+ observer.unobserve(current);
+ }
+ };
+ }, [observer, ref, updateSize]);
+
+ useEffect(() => {
+ window.addEventListener("resize", updateSize);
+
+ return () => {
+ window.removeEventListener("resize", updateSize);
+ };
+ }, [updateSize]);
+
+ useEffect(() => {
+ elementSizeHooks.push(updateSize);
+
+ return () => {
+ elementSizeHooks = elementSizeHooks.filter((e) => e !== updateSize);
+ };
+ }, [updateSize]);
+
+ return size;
+};
diff --git a/packages/template-recorder/src/helpers/use-key-press.ts b/packages/template-recorder/src/helpers/use-key-press.ts
new file mode 100644
index 0000000000..58ec947df3
--- /dev/null
+++ b/packages/template-recorder/src/helpers/use-key-press.ts
@@ -0,0 +1,35 @@
+import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
+
+export const useKeyPress = ({
+ keys,
+ callback,
+ metaKey,
+}: {
+ keys: string[];
+ callback: (event: KeyboardEvent) => void;
+ metaKey: boolean;
+}) => {
+ const callbackRef = useRef(callback);
+ useLayoutEffect(() => {
+ callbackRef.current = callback;
+ });
+
+ const handleKeyPress = useCallback(
+ (event: KeyboardEvent) => {
+ if (
+ keys.some(
+ (key: string) => event.key === key && event.metaKey === metaKey,
+ )
+ ) {
+ callbackRef.current(event);
+ }
+ },
+ [keys, metaKey],
+ );
+
+ useEffect(() => {
+ document.addEventListener("keydown", handleKeyPress);
+
+ return () => document.removeEventListener("keydown", handleKeyPress);
+ }, [handleKeyPress]);
+};
diff --git a/packages/template-recorder/src/helpers/utils.ts b/packages/template-recorder/src/helpers/utils.ts
new file mode 100644
index 0000000000..ec79801fe9
--- /dev/null
+++ b/packages/template-recorder/src/helpers/utils.ts
@@ -0,0 +1,6 @@
+import { type ClassValue, clsx } from "clsx"
+import { twMerge } from "tailwind-merge"
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs))
+}
diff --git a/packages/template-recorder/src/index.css b/packages/template-recorder/src/index.css
new file mode 100644
index 0000000000..9afce4dc4a
--- /dev/null
+++ b/packages/template-recorder/src/index.css
@@ -0,0 +1,50 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+@layer base {
+ :root {
+ --background: 222.2 84% 4.9%;
+ --foreground: 210 40% 98%;
+
+ --card: 222.2 84% 4.9%;
+ --card-foreground: 210 40% 98%;
+
+ --popover: 222.2 84% 4.9%;
+ --popover-foreground: 210 40% 98%;
+
+ --primary: 210 40% 98%;
+ --primary-foreground: 222.2 47.4% 11.2%;
+
+ --secondary: 217.2 32.6% 17.5%;
+ --secondary-foreground: 210 40% 98%;
+
+ --muted: 217.2 32.6% 17.5%;
+ --muted-foreground: 215 20.2% 65.1%;
+
+ --accent: 217.2 32.6% 17.5%;
+ --accent-foreground: 210 40% 98%;
+
+ --destructive: 0 62.8% 30.6%;
+ --destructive-foreground: 210 40% 98%;
+
+ --border: 217.2 32.6% 17.5%;
+ --input: 217.2 32.6% 17.5%;
+ --ring: 212.7 26.8% 83.9%;
+
+ --radius: 0.5rem;
+ }
+
+ * {
+ @apply border-border;
+ }
+}
+
+html {
+ background-color: #000;
+}
+
+body {
+ height: 100vh;
+ margin: 0;
+}
diff --git a/packages/template-recorder/src/main.tsx b/packages/template-recorder/src/main.tsx
new file mode 100644
index 0000000000..b9e12bfc1a
--- /dev/null
+++ b/packages/template-recorder/src/main.tsx
@@ -0,0 +1,13 @@
+import React from "react";
+import ReactDOM from "react-dom/client";
+import App from "./App";
+import { DevicePermission } from "./DevicePermission";
+import "./index.css";
+
+ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
+ <React.StrictMode>
+ <DevicePermission>
+ <App />
+ </DevicePermission>
+ </React.StrictMode>,
+);
diff --git a/packages/template-recorder/src/preferred-device-localstorage.ts b/packages/template-recorder/src/preferred-device-localstorage.ts
new file mode 100644
index 0000000000..eb27be716c
--- /dev/null
+++ b/packages/template-recorder/src/preferred-device-localstorage.ts
@@ -0,0 +1,40 @@
+import { Prefix } from "./helpers/prefixes";
+
+const getPreferredDeviceForPrefix = (
+ prefix: Prefix,
+ type: "video" | "audio",
+) => {
+ return window.localStorage.getItem(
+ `recorder.preferredDevice.${type}.${prefix}`,
+ );
+};
+
+export const setPreferredDeviceForPrefix = (
+ prefix: Prefix,
+ type: "video" | "audio",
+ deviceId: string | null,
+) => {
+ window.localStorage.setItem(
+ `recorder.preferredDevice.${type}.${prefix}`,
+ String(deviceId),
+ );
+};
+
+export const getPreferredDeviceIfExists = (
+ prefix: Prefix,
+ type: "video" | "audio",
+ devices: MediaDeviceInfo[],
+) => {
+ const deviceId = getPreferredDeviceForPrefix(prefix, type);
+ if (deviceId === "" || deviceId === null) {
+ return null;
+ }
+
+ const device = devices.find((d) => d.deviceId === deviceId);
+
+ if (device === undefined) {
+ return null;
+ }
+
+ return device.deviceId;
+};
diff --git a/packages/template-recorder/src/preferred-resolution.ts b/packages/template-recorder/src/preferred-resolution.ts
new file mode 100644
index 0000000000..f2ec06b3fa
--- /dev/null
+++ b/packages/template-recorder/src/preferred-resolution.ts
@@ -0,0 +1,36 @@
+import { SizeConstraint } from "./helpers/get-selected-video-source";
+
+export const setPreferredResolutionForDevice = (
+ deviceId: string,
+ videoSize: SizeConstraint | null,
+) => {
+ localStorage.setItem(
+ `preferred-constraint-${deviceId}`,
+ JSON.stringify(videoSize),
+ );
+};
+
+// The Recorder only records at frame rates at least of 23.976 FPS.
+// This is the lowest frame rate that is common, ignoring all frame rates lower than that.
+export const DEFAULT_MINIMUM_FPS = 23.976;
+
+export const getPreferredResolutionForDevice = (
+ deviceId: string | null,
+): SizeConstraint => {
+ if (deviceId === null) {
+ return {
+ maxSize: null,
+ minimumFps: null,
+ };
+ }
+
+ const stored = localStorage.getItem(`preferred-constraint-${deviceId}`);
+ if (stored === null || stored === "null") {
+ return {
+ maxSize: null,
+ minimumFps: null,
+ };
+ }
+
+ return JSON.parse(stored) as SizeConstraint;
+};
diff --git a/packages/template-recorder/src/state/media-sources.tsx b/packages/template-recorder/src/state/media-sources.tsx
new file mode 100644
index 0000000000..a3704f7aff
--- /dev/null
+++ b/packages/template-recorder/src/state/media-sources.tsx
@@ -0,0 +1,103 @@
+import React, { useCallback, useMemo, useState } from "react";
+import { useDevices } from "../WaitingForDevices";
+import { Prefix } from "../helpers/prefixes";
+import { getPreferredDeviceIfExists } from "../preferred-device-localstorage";
+
+export type StreamState =
+ | { type: "initial" }
+ | { type: "loading" }
+ | { type: "loaded"; stream: MediaStream }
+ | { type: "error"; error: string };
+
+type PrefixState = {
+ streamState: StreamState;
+ videoDevice: string | null;
+ audioDevice: string | null;
+};
+
+export type MediaSources = {
+ [key in Prefix]: PrefixState;
+};
+
+export type MediaSourcesContextType = {
+ mediaSources: MediaSources;
+ setMediaStream: (prefix: Prefix, source: StreamState) => void;
+ setAudioDevice: (prefix: Prefix, deviceId: string | null) => void;
+ setVideoDevice: (prefix: Prefix, deviceId: string | null) => void;
+};
+
+const MediaSourcesContext = React.createContext<MediaSourcesContextType | null>(
+ null,
+);
+
+const makeInitialState = (
+ prefix: Prefix,
+ devices: MediaDeviceInfo[],
+): PrefixState => {
+ return {
+ streamState: { type: "initial" },
+ audioDevice: getPreferredDeviceIfExists(prefix, "audio", devices),
+ videoDevice: getPreferredDeviceIfExists(prefix, "video", devices),
+ };
+};
+
+export const MediaSourcesProvider: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
+ const devices = useDevices();
+ const [mediaSources, setMediaSources] = useState<MediaSources>({
+ alternative1: makeInitialState("alternative1", devices),
+ alternative2: makeInitialState("alternative2", devices),
+ display: makeInitialState("display", devices),
+ webcam: makeInitialState("webcam", devices),
+ });
+
+ const setMediaStream = useCallback((prefix: Prefix, source: StreamState) => {
+ setMediaSources((prevMediaSources) => ({
+ ...prevMediaSources,
+ [prefix]: { ...prevMediaSources[prefix], streamState: source },
+ }));
+ }, []);
+
+ const setAudioDevice = useCallback(
+ (prefix: Prefix, deviceId: string | null) => {
+ setMediaSources((prevMediaSources) => ({
+ ...prevMediaSources,
+ [prefix]: { ...prevMediaSources[prefix], audioDevice: deviceId },
+ }));
+ },
+ [],
+ );
+
+ const setVideoDevice = useCallback(
+ (prefix: Prefix, deviceId: string | null) => {
+ setMediaSources((prevMediaSources) => ({
+ ...prevMediaSources,
+ [prefix]: { ...prevMediaSources[prefix], videoDevice: deviceId },
+ }));
+ },
+ [],
+ );
+
+ const value: MediaSourcesContextType = useMemo(
+ () => ({ mediaSources, setMediaStream, setAudioDevice, setVideoDevice }),
+ [mediaSources, setMediaStream, setAudioDevice, setVideoDevice],
+ );
+
+ return (
+ <MediaSourcesContext.Provider value={value}>
+ {children}
+ </MediaSourcesContext.Provider>
+ );
+};
+
+export const useMediaSources = () => {
+ const context = React.useContext(MediaSourcesContext);
+ if (!context) {
+ throw new Error(
+ "useMediaSources must be used within a MediaSourcesProvider",
+ );
+ }
+
+ return context;
+};
diff --git a/packages/template-recorder/src/state/visible-views.ts b/packages/template-recorder/src/state/visible-views.ts
new file mode 100644
index 0000000000..413a7b9276
--- /dev/null
+++ b/packages/template-recorder/src/state/visible-views.ts
@@ -0,0 +1,8 @@
+import { Prefix } from "../helpers/prefixes";
+
+export const visibleByDefault: { [key in Prefix]: boolean } = {
+ webcam: true,
+ alternative1: false,
+ alternative2: false,
+ display: true,
+};
diff --git a/packages/template-recorder/studio.ts b/packages/template-recorder/studio.ts
new file mode 100644
index 0000000000..b48fa7dbf5
--- /dev/null
+++ b/packages/template-recorder/studio.ts
@@ -0,0 +1,17 @@
+import { startStudioAndServer } from "./scripts/server";
+
+if (typeof Bun === "undefined") {
+ console.log("Run this script with Bun: `bun studio.ts`");
+ process.exit(1);
+}
+
+if (
+ typeof Bun !== "undefined" &&
+ !Bun.semver.satisfies(Bun.version, ">=1.1.11")
+) {
+ throw new Error(
+ "Bun >=1.1.11 is required to run the Remotion Recorder. Previous versions had a bug which would break long recordings.",
+ );
+}
+
+startStudioAndServer();
diff --git a/packages/template-recorder/sub.ts b/packages/template-recorder/sub.ts
new file mode 100644
index 0000000000..d89772e721
--- /dev/null
+++ b/packages/template-recorder/sub.ts
@@ -0,0 +1,51 @@
+import { existsSync, lstatSync, readdirSync } from "node:fs";
+import path from "path";
+import { CAPTIONS_PREFIX, WEBCAM_PREFIX } from "./config/cameras";
+import { captionFile } from "./scripts/captions/caption-file";
+import { ensureWhisper } from "./scripts/captions/install-whisper";
+
+await ensureWhisper({
+ onInstall: () => undefined,
+ onModelProgressInPercent: () => undefined,
+ signal: new AbortController().signal,
+});
+
+const publicFolder = path.join(process.cwd(), "public");
+const foldersInPublicFolder = readdirSync(publicFolder).filter((f) => {
+ return lstatSync(path.join(publicFolder, f)).isDirectory();
+});
+
+for (const folder of foldersInPublicFolder) {
+ const absoluteFolder = path.join(publicFolder, folder);
+
+ const files = readdirSync(absoluteFolder).filter((f) => f !== ".DS_Store");
+
+ for (const file of files) {
+ if (!file.startsWith(WEBCAM_PREFIX)) {
+ continue;
+ }
+
+ const fileToTranscribe = path.join(absoluteFolder, file);
+
+ const outPath = path.join(
+ absoluteFolder,
+ `${(file.split(".")[0] as string).replace(WEBCAM_PREFIX, CAPTIONS_PREFIX)}.json`,
+ );
+
+ if (existsSync(outPath)) {
+ console.log("Already transcribed", outPath);
+ } else {
+ console.log("Transcribing", fileToTranscribe);
+ await captionFile({
+ file,
+ outPath,
+ fileToTranscribe,
+ onProgress(progress) {
+ console.log(`${progress.progressInPercent}%`);
+ },
+ signal: new AbortController().signal,
+ });
+ console.log("Transcribed to", outPath);
+ }
+ }
+}
diff --git a/packages/template-recorder/tailwind.config.js b/packages/template-recorder/tailwind.config.js
new file mode 100644
index 0000000000..0377ea1ded
--- /dev/null
+++ b/packages/template-recorder/tailwind.config.js
@@ -0,0 +1,76 @@
+/** @type {import('tailwindcss').Config} */
+module.exports = {
+ darkMode: ["class"],
+ content: [
+ './pages/**/*.{ts,tsx}',
+ './components/**/*.{ts,tsx}',
+ './app/**/*.{ts,tsx}',
+ './src/**/*.{ts,tsx}',
+ ],
+ theme: {
+ container: {
+ center: true,
+ padding: "2rem",
+ screens: {
+ "2xl": "1400px",
+ },
+ },
+ extend: {
+ colors: {
+ border: "hsl(var(--border))",
+ input: "hsl(var(--input))",
+ ring: "hsl(var(--ring))",
+ background: "hsl(var(--background))",
+ foreground: "hsl(var(--foreground))",
+ primary: {
+ DEFAULT: "hsl(var(--primary))",
+ foreground: "hsl(var(--primary-foreground))",
+ },
+ secondary: {
+ DEFAULT: "hsl(var(--secondary))",
+ foreground: "hsl(var(--secondary-foreground))",
+ },
+ destructive: {
+ DEFAULT: "hsl(var(--destructive))",
+ foreground: "hsl(var(--destructive-foreground))",
+ },
+ muted: {
+ DEFAULT: "hsl(var(--muted))",
+ foreground: "hsl(var(--muted-foreground))",
+ },
+ accent: {
+ DEFAULT: "hsl(var(--accent))",
+ foreground: "hsl(var(--accent-foreground))",
+ },
+ popover: {
+ DEFAULT: "hsl(var(--popover))",
+ foreground: "hsl(var(--popover-foreground))",
+ },
+ card: {
+ DEFAULT: "hsl(var(--card))",
+ foreground: "hsl(var(--card-foreground))",
+ },
+ },
+ borderRadius: {
+ lg: "var(--radius)",
+ md: "calc(var(--radius) - 2px)",
+ sm: "calc(var(--radius) - 4px)",
+ },
+ keyframes: {
+ "accordion-down": {
+ from: { height: 0 },
+ to: { height: "var(--radix-accordion-content-height)" },
+ },
+ "accordion-up": {
+ from: { height: "var(--radix-accordion-content-height)" },
+ to: { height: 0 },
+ },
+ },
+ animation: {
+ "accordion-down": "accordion-down 0.2s ease-out",
+ "accordion-up": "accordion-up 0.2s ease-out",
+ },
+ },
+ },
+ plugins: [require("tailwindcss-animate")],
+}
\ No newline at end of file
diff --git a/packages/template-recorder/tests/device-names-windows.test.ts b/packages/template-recorder/tests/device-names-windows.test.ts
new file mode 100644
index 0000000000..d5d832255a
--- /dev/null
+++ b/packages/template-recorder/tests/device-names-windows.test.ts
@@ -0,0 +1,132 @@
+import { expect, test } from "bun:test";
+import { formatDeviceLabel } from "../src/helpers/format-device-label";
+
+const logiStreamCamDefault =
+ "Default - Microphone (Logitech StreamCam) (046d:0893)";
+
+const logiStreamCamCommunicationMic =
+ "Communications - Microphone (Logitech StreamCam) (046d:0893)";
+
+const hdmiMicrophone = "HDMI (2- Cam Link 4K) (0fd9:007b)";
+
+const elgatoSoundCapture = "Line (Elgato Sound Capture)";
+
+const gameCaptureMicrophone =
+ "Game Capture HD60 X (Game Capture HD60 X) (0fd9:0082)";
+
+const rodeNtUsbMicrophone = "Microphone (6- RODE NT-USB) (19f7:0003)";
+
+const logitechStreamCamMicrophone =
+ "Microphone (Logitech StreamCam) (046d:0893)";
+
+const logitechStreamCamVideo = "Logitech StreamCam (046d:0893)";
+
+const gameCaptureHD60XVideo = "Game Capture HD60 X (0fd9:0082)";
+
+const camLink4KVideo = "Cam Link 4K (0fd9:007b)";
+
+const logiCaptureVideo = "Logi Capture";
+
+const lumixWebcamVideo = "LUMIX Webcam Software";
+
+const obsVirtualCameraVideo = "OBS Virtual Camera";
+
+const elgatoScreenLinkVideo = "Elgato Screen Link";
+
+const p27q20Default =
+ "Default - 4 - P27q-20 (AMD High Definition Audio Device)";
+
+const communicationsSpeakers =
+ "Communications - Speakers (6- RODE NT-USB) (19f7:0003)";
+
+const realtekDigitalOutput = "Realtek Digital Output (Realtek(R) Audio)";
+
+const speakersRodeNtUsb = "Speakers (6- RODE NT-USB) (19f7:0003)";
+
+test("Test for logiStreamCamDefault", () => {
+ expect(formatDeviceLabel(logiStreamCamDefault)).toEqual("Logitech StreamCam");
+});
+
+test("Test for logiStreamCamCommunicationMic", () => {
+ expect(formatDeviceLabel(logiStreamCamCommunicationMic)).toEqual(
+ "Logitech StreamCam",
+ );
+});
+
+test("Test for HDMI Microphone", () => {
+ expect(formatDeviceLabel(hdmiMicrophone)).toEqual("Cam Link 4K");
+});
+
+test("Test for Line Microphone", () => {
+ expect(formatDeviceLabel(elgatoSoundCapture)).toEqual("Elgato Sound Capture");
+});
+
+test("Test for Game Capture HD60 X Microphone", () => {
+ expect(formatDeviceLabel(gameCaptureMicrophone)).toEqual(
+ "Game Capture HD60 X",
+ );
+});
+
+test("Test for RODE NT-USB Microphone", () => {
+ expect(formatDeviceLabel(rodeNtUsbMicrophone)).toEqual("RODE NT-USB");
+});
+
+test("Test for Logitech StreamCam Microphone", () => {
+ expect(formatDeviceLabel(logitechStreamCamMicrophone)).toEqual(
+ "Logitech StreamCam",
+ );
+});
+
+test("Test for Logitech StreamCam Video", () => {
+ expect(formatDeviceLabel(logitechStreamCamVideo)).toEqual(
+ "Logitech StreamCam",
+ );
+});
+
+test("Test for Game Capture HD60 X Video", () => {
+ expect(formatDeviceLabel(gameCaptureHD60XVideo)).toEqual(
+ "Game Capture HD60 X",
+ );
+});
+
+test("Test for Cam Link 4K Video", () => {
+ expect(formatDeviceLabel(camLink4KVideo)).toEqual("Cam Link 4K");
+});
+
+test("Test for Logi Capture Video", () => {
+ expect(formatDeviceLabel(logiCaptureVideo)).toEqual("Logi Capture");
+});
+
+test("Test for LUMIX Webcam Video", () => {
+ expect(formatDeviceLabel(lumixWebcamVideo)).toEqual("LUMIX Webcam Software");
+});
+
+test("Test for OBS Virtual Camera Video", () => {
+ expect(formatDeviceLabel(obsVirtualCameraVideo)).toEqual(
+ "OBS Virtual Camera",
+ );
+});
+
+test("Test for Elgato Screen Link Video", () => {
+ expect(formatDeviceLabel(elgatoScreenLinkVideo)).toEqual(
+ "Elgato Screen Link",
+ );
+});
+
+test("Test for Default Audio Output", () => {
+ expect(formatDeviceLabel(p27q20Default)).toEqual(
+ "AMD High Definition Audio Device",
+ );
+});
+
+test("Test for Communications Speakers", () => {
+ expect(formatDeviceLabel(communicationsSpeakers)).toEqual("RODE NT-USB");
+});
+
+test("Test for Realtek Digital Output", () => {
+ expect(formatDeviceLabel(realtekDigitalOutput)).toEqual("Realtek(R) Audio");
+});
+
+test("Test for Speakers RODE NT-USB", () => {
+ expect(formatDeviceLabel(speakersRodeNtUsb)).toEqual("RODE NT-USB");
+});
diff --git a/packages/template-recorder/tests/device-names.test.ts b/packages/template-recorder/tests/device-names.test.ts
new file mode 100644
index 0000000000..699a1eac6d
--- /dev/null
+++ b/packages/template-recorder/tests/device-names.test.ts
@@ -0,0 +1,42 @@
+import { expect, test } from "bun:test";
+import { formatDeviceLabel } from "../src/helpers/format-device-label";
+
+test("remove usb identifier ", () => {
+ expect(formatDeviceLabel("FaceTime HD Camera (1C1C:B782)")).toEqual(
+ "FaceTime HD Camera",
+ );
+});
+
+test("remove Speaker tag ", () => {
+ expect(formatDeviceLabel("6- RODE NT-USB (19f7:0003)")).toEqual(
+ "RODE NT-USB",
+ );
+});
+
+test("remove (Built-in) ", () => {
+ expect(
+ formatDeviceLabel("Default - MacBook Pro Microphone (Built-in)"),
+ ).toEqual("Default - MacBook Pro Microphone");
+});
+
+test("remove (Virtual) ", () => {
+ expect(formatDeviceLabel("Microsoft Teams Audio Device (Virtual)")).toEqual(
+ "Microsoft Teams Audio Device",
+ );
+});
+
+test("Simple label should stay unaffected ", () => {
+ expect(formatDeviceLabel("LUMIX Webcam Software")).toEqual(
+ "LUMIX Webcam Software",
+ );
+});
+
+test("Linkbuds S test ", () => {
+ expect(formatDeviceLabel("LinkBuds S (Bluetooth)")).toEqual("LinkBuds S");
+});
+
+test("OBS Virtual Camera test", () => {
+ expect(formatDeviceLabel("OBS Virtual Camera (m-de:vice)")).toEqual(
+ "OBS Virtual Camera",
+ );
+});
diff --git a/packages/template-recorder/tests/fix-backticks.test.ts b/packages/template-recorder/tests/fix-backticks.test.ts
new file mode 100644
index 0000000000..bd3cd42a9e
--- /dev/null
+++ b/packages/template-recorder/tests/fix-backticks.test.ts
@@ -0,0 +1,84 @@
+// eslint-disable-next-line @typescript-eslint/triple-slash-reference
+
+import { Caption } from "@remotion/captions";
+import { expect, test } from "bun:test";
+import { fixBackticks } from "../remotion/captions/processing/fix-backticks";
+
+const example: Caption[] = [
+ {
+ text: " `bun`",
+ endMs: 5.94,
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ text: " `run`",
+ endMs: 6.54,
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ text: " `dev`",
+ endMs: 6.96,
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ text: ". It",
+ endMs: 8.36,
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ text: " looks",
+ endMs: 8.62,
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+];
+
+test("join captions correctly", () => {
+ const captions = fixBackticks(example);
+ expect(captions).toEqual([
+ {
+ endMs: 5.94,
+ text: " `bun`",
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ endMs: 6.54,
+ text: " `run`",
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ endMs: 6.96,
+ text: " `dev`.",
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ endMs: 8.36,
+ text: " It",
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ endMs: 8.62,
+ text: " looks",
+ startMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ ]);
+});
diff --git a/packages/template-recorder/tests/make-monospace-captions.test.ts b/packages/template-recorder/tests/make-monospace-captions.test.ts
new file mode 100644
index 0000000000..d99c88ea25
--- /dev/null
+++ b/packages/template-recorder/tests/make-monospace-captions.test.ts
@@ -0,0 +1,39 @@
+// eslint-disable-next-line @typescript-eslint/triple-slash-reference
+
+import { Caption } from "@remotion/captions";
+import { expect, test } from "bun:test";
+import { splitCaptionIntoMonospaceSegments } from "../remotion/captions/processing/split-caption-into-monospace-segments";
+
+test("Should split up into monospace words", () => {
+ const caption: Caption = {
+ text: "This is a `monospace` word",
+ startMs: 0,
+ endMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ };
+
+ expect(splitCaptionIntoMonospaceSegments(caption)).toEqual([
+ {
+ text: "This is a ",
+ startMs: 0,
+ confidence: null,
+ endMs: 0,
+ timestampMs: 0,
+ },
+ {
+ text: "`monospace`",
+ startMs: 0,
+ endMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ {
+ text: " word",
+ startMs: 0,
+ endMs: 0,
+ confidence: null,
+ timestampMs: 0,
+ },
+ ]);
+});
diff --git a/packages/template-recorder/tsconfig.json b/packages/template-recorder/tsconfig.json
new file mode 100644
index 0000000000..3a443948dd
--- /dev/null
+++ b/packages/template-recorder/tsconfig.json
@@ -0,0 +1,32 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "useDefineForClassFields": true,
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
+ "allowJs": false,
+ "skipLibCheck": true,
+ "esModuleInterop": false,
+ "allowSyntheticDefaultImports": true,
+ "strict": true,
+ "forceConsistentCasingInFileNames": true,
+ "module": "ESNext",
+ "moduleResolution": "Node",
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "strictNullChecks": true,
+ "alwaysStrict": true,
+ "noUncheckedIndexedAccess": true
+ },
+ "include": [
+ "src",
+ "remotion",
+ "sub.ts",
+ "scripts",
+ "config",
+ "studio.ts",
+ "tests"
+ ],
+ "references": [{ "path": "./tsconfig.node.json" }]
+}
diff --git a/packages/template-recorder/tsconfig.node.json b/packages/template-recorder/tsconfig.node.json
new file mode 100644
index 0000000000..9d31e2aed9
--- /dev/null
+++ b/packages/template-recorder/tsconfig.node.json
@@ -0,0 +1,9 @@
+{
+ "compilerOptions": {
+ "composite": true,
+ "module": "ESNext",
+ "moduleResolution": "Node",
+ "allowSyntheticDefaultImports": true
+ },
+ "include": ["vite.config.ts"]
+}
diff --git a/packages/template-recorder/update.ts b/packages/template-recorder/update.ts
new file mode 100644
index 0000000000..d81723744d
--- /dev/null
+++ b/packages/template-recorder/update.ts
@@ -0,0 +1,93 @@
+import { $ } from "bun";
+import { cpSync, existsSync, rmdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const tmp = path.join(tmpdir(), "recorder");
+
+if ((await $`git status --porcelain`.quiet()).exitCode !== 0) {
+ console.error(
+ "Your Git status is dirty. Please commit or stash your changes before running this script.",
+ );
+ process.exit(1);
+}
+
+await $`git clone https://github.com/remotion-dev/recorder.git ${tmp} --depth=1`.env(
+ {
+ GIT_LFS_SKIP_SMUDGE: "1",
+ },
+);
+
+const getFilesInGit = async (folder: string) => {
+ return (await $`git ls-files`.quiet().cwd(folder)).stdout
+ .toString("utf-8")
+ .split("\n")
+ .filter(Boolean)
+ .filter((file) => {
+ if (file.startsWith("public")) {
+ return false;
+ }
+
+ if (file === ".gitattributes") {
+ return false;
+ }
+
+ if (file.startsWith("config")) {
+ const knownConfigs = [
+ "endcard.ts",
+ "fonts.ts",
+ "fps.ts",
+ "layout.ts",
+ "scenes.ts",
+ "server.ts",
+ "sounds.ts",
+ "themes.ts",
+ "transitions.ts",
+ "autocorrect.ts",
+ "whisper.ts",
+ "cameras.ts",
+ ];
+
+ // Don't override config files with defaults
+ if (knownConfigs.some((f) => file.endsWith(f))) {
+ return false;
+ }
+
+ return true;
+ }
+
+ if (file.endsWith("Root.tsx")) {
+ return false;
+ }
+
+ return true;
+ });
+};
+
+const filesInUpstream = await getFilesInGit(tmp);
+const filesInCurrent = await getFilesInGit(process.cwd());
+
+const filesNotInUpstream = filesInCurrent.filter(
+ (file) => !filesInUpstream.includes(file),
+);
+
+for (const file of filesInUpstream) {
+ const fullPath = path.join(tmp, file);
+ cpSync(fullPath, path.join(process.cwd(), file));
+}
+
+for (const file of filesNotInUpstream) {
+ const fullPath = path.join(process.cwd(), file);
+ if (existsSync(fullPath)) {
+ rmSync(fullPath);
+ }
+}
+
+rmdirSync(tmp, { recursive: true });
+
+await $`git status`;
+
+console.log(
+ "Pulled files from the current main branch of the Recorder (except public, config and Root.tsx)",
+);
+console.log("Please review the changes and commit them.");
diff --git a/packages/template-recorder/vite.config.ts b/packages/template-recorder/vite.config.ts
new file mode 100644
index 0000000000..1cab6418b9
--- /dev/null
+++ b/packages/template-recorder/vite.config.ts
@@ -0,0 +1,12 @@
+import react from "@vitejs/plugin-react";
+import path from "path";
+import { defineConfig } from "vite";
+
+export default defineConfig({
+ plugins: [react()],
+ resolve: {
+ alias: {
+ "@": path.resolve(__dirname, "./src"),
+ },
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 71001b7f37..c7d8361fae 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2937,6 +2937,172 @@ importers:
specifier: 5.8.2
version: 5.8.2
+ packages/template-recorder:
+ dependencies:
+ '@radix-ui/react-dialog':
+ specifier: ^1.0.5
+ '@radix-ui/react-dropdown-menu':
+ specifier: 2.1.4
+ '@radix-ui/react-label':
+ specifier: ^2.0.2
+ '@radix-ui/react-select':
+ specifier: ^2.0.0
+ '@radix-ui/react-slot':
+ specifier: ^1.0.2
+ version: 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-toggle':
+ specifier: ^1.0.3
+ '@remotion/animation-utils':
+ specifier: workspace:*
+ version: link:../animation-utils
+ '@remotion/lambda':
+ specifier: workspace:*
+ version: link:../lambda
+ '@remotion/layout-utils':
+ specifier: workspace:*
+ version: link:../layout-utils
+ '@remotion/shapes':
+ specifier: workspace:*
+ version: link:../shapes
+ '@remotion/streaming':
+ specifier: workspace:*
+ version: link:../streaming
+ '@remotion/studio':
+ specifier: workspace:*
+ version: link:../studio
+ '@remotion/studio-server':
+ specifier: workspace:*
+ version: link:../studio-server
+ '@remotion/zod-types':
+ specifier: workspace:*
+ version: link:../zod-types
+ class-variance-authority:
+ specifier: ^0.7.0
+ version: 0.7.0
+ clsx:
+ specifier: ^2.0.0
+ version: 2.1.1
+ connect:
+ specifier: 3.7.0
+ version: 3.7.0
+ eslint:
+ specifier: 9.19.0
+ version: 9.19.0
+ eslint-plugin-react-hooks:
+ specifier: 4.6.2
+ version: 4.6.2([email protected])
+ lucide-react:
+ specifier: ^0.290.0
+ version: 0.290.0([email protected])
+ react:
+ specifier: 19.0.0
+ version: 19.0.0
+ react-dom:
+ specifier: 19.0.0
+ version: 19.0.0([email protected])
+ tailwind-merge:
+ specifier: ^1.14.0
+ version: 1.14.0
+ tailwindcss-animate:
+ specifier: ^1.0.7
+ version: 1.0.7([email protected])
+ zod:
+ specifier: ^3.21.4
+ version: 3.24.2
+ devDependencies:
+ '@remotion/captions':
+ specifier: workspace:*
+ version: link:../captions
+ '@remotion/cli':
+ specifier: workspace:*
+ version: link:../cli
+ '@remotion/eslint-config':
+ specifier: workspace:*
+ version: link:../eslint-config
+ '@remotion/eslint-plugin':
+ specifier: workspace:*
+ version: link:../eslint-plugin
+ '@remotion/google-fonts':
+ specifier: workspace:*
+ version: link:../google-fonts
+ '@remotion/install-whisper-cpp':
+ specifier: workspace:*
+ version: link:../install-whisper-cpp
+ '@remotion/media-parser':
+ specifier: workspace:*
+ version: link:../media-parser
+ '@remotion/media-utils':
+ specifier: workspace:*
+ version: link:../media-utils
+ '@remotion/renderer':
+ specifier: workspace:*
+ version: link:../renderer
+ '@remotion/webcodecs':
+ specifier: workspace:*
+ version: link:../webcodecs
+ '@types/bun':
+ specifier: ^1.0.0
+ version: 1.2.8
+ '@types/connect':
+ specifier: 3.4.38
+ version: 3.4.38
+ '@types/dom-mediacapture-record':
+ specifier: 1.0.21
+ version: 1.0.21
+ '@types/react':
+ specifier: 19.0.0
+ version: 19.0.0
+ '@types/react-dom':
+ specifier: 19.0.0
+ version: 19.0.0
+ '@types/web':
+ specifier: 0.0.187
+ version: 0.0.187
+ '@types/webrtc':
+ specifier: 0.0.44
+ version: 0.0.44
+ '@typescript-eslint/eslint-plugin':
+ specifier: ^7.8.0
+ version: 7.18.0(@typescript-eslint/[email protected])([email protected])([email protected])
+ '@typescript-eslint/parser':
+ specifier: ^7.8.0
+ '@vitejs/plugin-react':
+ specifier: ^4.1.0
+ version: 4.3.4([email protected])
+ '@vitejs/plugin-react-swc':
+ specifier: ^3.0.0
+ version: 3.10.2([email protected])
+ autoprefixer:
+ specifier: ^10.4.16
+ version: 10.4.20([email protected])
+ postcss:
+ specifier: ^8.4.31
+ version: 8.5.1
+ prettier:
+ specifier: 3.3.3
+ version: 3.3.3
+ prettier-plugin-organize-imports:
+ specifier: ^3.2.3
+ remotion:
+ specifier: workspace:*
+ version: link:../core
+ tailwindcss:
+ specifier: ^3.3.5
+ version: 3.4.13
+ typescript:
+ specifier: 5.8.2
+ version: 5.8.2
+ vite:
+ specifier: 5.2.11
+ version: 5.2.11
+
packages/template-render-server:
dependencies:
'@remotion/bundler':
@@ -6413,7 +6579,6 @@ packages:
dependencies:
'@babel/core': 7.26.0
'@babel/helper-plugin-utils': 7.25.9
- dev: false
resolution: {integrity: sha512-+iqjT8xmXhhYv4/uiYd8FNQsraMFZIfxVSqxxVSZP0WbbSAWvBXAul0m/zu+7Vv4O/3WtApy9pmaTMiumEZgfg==}
@@ -6423,7 +6588,6 @@ packages:
dependencies:
'@babel/core': 7.26.0
'@babel/helper-plugin-utils': 7.25.9
- dev: false
resolution: {integrity: sha512-s5XwpQYCqGerXl+Pu6VDL3x0j2d82eiV77UJ8a2mDHAW7j9SWRqQ2y1fNo1Z74CdcYipl5Z41zvjj4Nfzq36rw==}
@@ -9289,6 +9453,15 @@ packages:
resolution: {integrity: sha512-KOEGMu6dmJZtpadb476IsZBclKvILjopjUii3V+7MnXIQCYh8W3NgNcgwo21n9LXZX6EDIKvqfjYxXebDwxKmQ==}
dev: false
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==}
+ engines: {node: '>=12'}
+ cpu: [ppc64]
+ os: [aix]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==}
engines: {node: '>=12'}
@@ -9330,6 +9503,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [android]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==}
engines: {node: '>=12'}
@@ -9371,6 +9553,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w==}
+ engines: {node: '>=12'}
+ cpu: [arm]
+ os: [android]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==}
engines: {node: '>=12'}
@@ -9412,6 +9603,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [android]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==}
engines: {node: '>=12'}
@@ -9453,6 +9653,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [darwin]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==}
engines: {node: '>=12'}
@@ -9494,6 +9703,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [darwin]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==}
engines: {node: '>=12'}
@@ -9535,6 +9753,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [freebsd]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==}
engines: {node: '>=12'}
@@ -9576,6 +9803,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [freebsd]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==}
engines: {node: '>=12'}
@@ -9617,6 +9853,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==}
engines: {node: '>=12'}
@@ -9658,6 +9903,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg==}
+ engines: {node: '>=12'}
+ cpu: [arm]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==}
engines: {node: '>=12'}
@@ -9699,6 +9953,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig==}
+ engines: {node: '>=12'}
+ cpu: [ia32]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==}
engines: {node: '>=12'}
@@ -9740,6 +10003,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ==}
+ engines: {node: '>=12'}
+ cpu: [loong64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==}
engines: {node: '>=12'}
@@ -9781,6 +10053,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA==}
+ engines: {node: '>=12'}
+ cpu: [mips64el]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==}
engines: {node: '>=12'}
@@ -9822,6 +10103,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg==}
+ engines: {node: '>=12'}
+ cpu: [ppc64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==}
engines: {node: '>=12'}
@@ -9863,6 +10153,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg==}
+ engines: {node: '>=12'}
+ cpu: [riscv64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==}
engines: {node: '>=12'}
@@ -9904,6 +10203,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ==}
+ engines: {node: '>=12'}
+ cpu: [s390x]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==}
engines: {node: '>=12'}
@@ -9945,6 +10253,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==}
engines: {node: '>=12'}
@@ -10003,6 +10320,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [netbsd]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==}
engines: {node: '>=12'}
@@ -10061,6 +10387,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [openbsd]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==}
engines: {node: '>=12'}
@@ -10102,6 +10437,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [sunos]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==}
engines: {node: '>=12'}
@@ -10143,6 +10487,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ==}
+ engines: {node: '>=12'}
+ cpu: [arm64]
+ os: [win32]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==}
engines: {node: '>=12'}
@@ -10184,6 +10537,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ==}
+ engines: {node: '>=12'}
+ cpu: [ia32]
+ os: [win32]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==}
engines: {node: '>=12'}
@@ -10225,6 +10587,15 @@ packages:
requiresBuild: true
optional: true
+ /@esbuild/[email protected]:
+ resolution: {integrity: sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ==}
+ engines: {node: '>=12'}
+ cpu: [x64]
+ os: [win32]
+ requiresBuild: true
+ dev: true
+ optional: true
+
/@esbuild/[email protected]:
resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==}
engines: {node: '>=12'}
@@ -11910,6 +12281,10 @@ packages:
resolution: {integrity: sha512-SJ31y+Q/zAyShtXJc8x83i9TYdbAfHZ++tUZnvjJJqFjzsdUnKsxPL6IEtBlxKkU7yzer//GQtZSV4GbldL3YA==}
dev: false
+ /@radix-ui/[email protected]:
+ resolution: {integrity: sha512-XnbHrrprsNqZKQhStrSwgRUQzoCI1glLzdw79xiZPoofhGICeZRSQ3dIxAKH1gb3OHfNf4d6f+vAv3kil2eggA==}
+ dev: false
+
resolution: {integrity: sha512-FmlW1rCg7hBpEBwFbjHwCW6AmWLQM6g/v0Sn8XbP9NvmSZ2San1FpQeyPtufzOMSIx7Y4dzjlHoifhp+7NkZhw==}
peerDependencies:
@@ -11930,6 +12305,26 @@ packages:
react-dom: 19.0.0([email protected])
dev: false
+ resolution: {integrity: sha512-NaVpZfmv8SKeZbn4ijN2V3jlHA9ngBG16VnIIm22nUR0Yk8KUALyBxT3KYEUnNuch9sTE8UTsS3whzBgKOL30w==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ dependencies:
+ '@radix-ui/react-primitive': 2.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@types/react': 19.0.0
+ '@types/react-dom': 19.0.0
+ react: 19.0.0
+ react-dom: 19.0.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-/i0fl686zaJbDQLNKrkCbMyDm6FQMt4jg323k7HuqitoANm9sE23Ql8yOK3Wusk34HSLKDChhMux05FnP6KUkw==}
peerDependencies:
@@ -12029,6 +12424,19 @@ packages:
react: 19.0.0
dev: false
+ resolution: {integrity: sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ dependencies:
+ '@types/react': 19.0.0
+ react: 19.0.0
+ dev: false
+
resolution: {integrity: sha512-OKrckBy+sMEgYM/sMmqmErVn0kZqrHPJze+Ql3DzYsDDp0hl0L62nx/2122/Bvps1qz645jlcu2tD9lrRSdf8A==}
peerDependencies:
@@ -12149,6 +12557,32 @@ packages:
react-dom: 19.0.0([email protected])
dev: false
+ resolution: {integrity: sha512-iXU1Ab5ecM+yEepGAWK8ZhMyKX4ubFdCNtol4sT9D0OVErG9PNElfx3TQhjw7n7BC5nFVz68/5//clWy+8TXzA==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ dependencies:
+ '@radix-ui/primitive': 1.1.1
+ '@radix-ui/react-compose-refs': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-menu': 2.1.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
+ '@types/react': 19.0.0
+ '@types/react-dom': 19.0.0
+ react: 19.0.0
+ react-dom: 19.0.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-w6XZNUPVv6xCpZUqb/yN9DL6auvpGX3C/ee6Hdi16v2UUy25HV2Q5bcflsiDyT/g5RwbPQ/GIT1vLkeRb+ITBw==}
peerDependencies:
@@ -12253,6 +12687,43 @@ packages:
react-dom: 19.0.0([email protected])
dev: false
+ resolution: {integrity: sha512-BnOgVoL6YYdHAG6DtXONaR29Eq4nvbi8rutrV/xlr3RQCMMb3yqP85Qiw/3NReozrSW+4dfLkK+rc1hb4wPU/A==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ dependencies:
+ '@radix-ui/primitive': 1.1.1
+ '@radix-ui/react-collection': 1.1.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-compose-refs': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-focus-guards': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-focus-scope': 1.1.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-popper': 1.2.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-portal': 1.1.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-presence': 1.1.2(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-roving-focus': 1.1.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-slot': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ '@types/react': 19.0.0
+ '@types/react-dom': 19.0.0
+ aria-hidden: 1.2.4
+ react: 19.0.0
+ react-dom: 19.0.0([email protected])
+ react-remove-scroll: 2.6.2(@types/[email protected])([email protected])
+ dev: false
+
resolution: {integrity: sha512-ZnRMshKF43aBxVWPWvbj21+7TQCvhuULWJ4gNIKYpRlQt5xGRhLx66tMp8pya2UkGHTSlhpXwmjqltDYHhw7Vg==}
peerDependencies:
@@ -12282,6 +12753,35 @@ packages:
react-dom: 19.0.0([email protected])
dev: false
+ resolution: {integrity: sha512-3kn5Me69L+jv82EKRuQCXdYyf1DqHwD2U/sxoNgBGCB7K9TRc3bQamQ+5EPM9EvyPdli0W41sROd+ZU1dTCztw==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ dependencies:
+ '@floating-ui/react-dom': 2.1.1([email protected])([email protected])
+ '@radix-ui/react-arrow': 1.1.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-compose-refs': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-rect': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-size': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/rect': 1.1.0
+ '@types/react': 19.0.0
+ '@types/react-dom': 19.0.0
+ react: 19.0.0
+ react-dom: 19.0.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-A3UtLk85UtqhzFqtoC8Q0KvR2GbXF3mtPgACSazajqq6A41mEQgo53iPzY4i6BwDxlIFqWIhiQ2G729n+2aw/g==}
peerDependencies:
@@ -12427,6 +12927,26 @@ packages:
react-dom: 19.0.0([email protected])
dev: false
+ resolution: {integrity: sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ dependencies:
+ '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])
+ '@types/react': 19.0.0
+ '@types/react-dom': 19.0.0
+ react: 19.0.0
+ react-dom: 19.0.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-E0MLLGfOP0l8P/NxgVzfXJ8w3Ch8cdO6UDzJfDChu4EJDy+/WdO5LqpdY8PYnCErkmZH3gZhDL1K7kQ41fAHuQ==}
peerDependencies:
@@ -12600,6 +13120,42 @@ packages:
react: 19.0.0
dev: false
+ resolution: {integrity: sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])
+ '@types/react': 19.0.0
+ react: 19.0.0
+ dev: false
+
+ resolution: {integrity: sha512-ZoFkBBz9zv9GWer7wIjvdRxmh2wyc2oKWw6C6CseWd6/yq1DK/l5lJ+wnsmFwJZbBYqr02mrf8A2q/CVCuM3ZA==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ dependencies:
+ '@radix-ui/primitive': 1.1.2
+ '@radix-ui/react-primitive': 2.1.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])
+ '@types/react': 19.0.0
+ '@types/react-dom': 19.0.0
+ react: 19.0.0
+ react-dom: 19.0.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-CasTfvsy+frcFkbXtSJ2Zu9JHpN8TYKxkgJGWbjiZhFivxaeW7rMeZt7QELGVLaYVfFMsKHjb7Ak0nMEe+2Vfw==}
peerDependencies:
@@ -12627,6 +13183,35 @@ packages:
react: 19.0.0
dev: false
+ resolution: {integrity: sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ dependencies:
+ '@radix-ui/react-use-effect-event': 0.0.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
+ '@types/react': 19.0.0
+ react: 19.0.0
+ dev: false
+
+ resolution: {integrity: sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ dependencies:
+ '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])
+ '@types/react': 19.0.0
+ react: 19.0.0
+ dev: false
+
resolution: {integrity: sha512-L7vwWlR1kTTQ3oh7g1O0CBF3YCyyTj8NmhLR+phShpyA50HCfBFKVJTpshm9PzLiKmehsrQzTYTpX9HvmC9rhw==}
peerDependencies:
@@ -12654,6 +13239,19 @@ packages:
react: 19.0.0
dev: false
+ resolution: {integrity: sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ dependencies:
+ '@types/react': 19.0.0
+ react: 19.0.0
+ dev: false
+
resolution: {integrity: sha512-Z/e78qg2YFnnXcW88A4JmTtm4ADckLno6F7OXotmkQfeuCVaKuYzqAATPhVzl3delXE7CxIV8shofPn3jPc5Og==}
peerDependencies:
@@ -13150,6 +13748,10 @@ packages:
resolution: {integrity: sha512-JzgY8aSvWbuigoJ+8x1lHW8or0syQz8hxpRdPijkCCp/GJYRPvBstYdJPbHk2nbv5+BV+8Rv4zRw96wKFVsvKQ==}
dev: false
+ /@rolldown/[email protected]:
+ resolution: {integrity: sha512-L/gAA/hyCSuzTF1ftlzUSI/IKr2POHsv1Dd78GfqkR83KMNuswWD61JxGV2L7nRwBBBSDr6R1gCkdTmoN7W4ag==}
+ dev: true
+
resolution: {integrity: sha512-Pnsb6f32CD2W3uCaLZIzDmeFyQ2b8UWMFI7xtwUezpcGBDVDW6y9XgAWIlARiGAo6eNF5FK5aQTr0LFyNyqq5A==}
engines: {node: '>=14.0.0'}
@@ -14135,6 +14737,15 @@ packages:
- typescript
dev: false
+ resolution: {integrity: sha512-nUjWVcJ3YS2N40ZbKwYO2RJ4+o2tWYRzNOcIQp05FqW0+aoUCVMdAUUzQinPDynfgwVshDAXCKemY8X7nN5MaA==}
+ engines: {node: '>=10'}
+ cpu: [arm64]
+ os: [darwin]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-TIus1/SE/Ud4g84hCnchcagu+LfyndSDy5r5qf64nflojejDidPU9Fp1InzQhQpEgIpntnZID/KFCP5rQnvsIw==}
engines: {node: '>=10'}
@@ -14143,6 +14754,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-OGm4a4d3OeJn+tRt8H/eiHgTFrJbS6r8mi/Ob65tAEXZGHN900T2kR7c5ALr0V2hBOQ8BfhexwPoQlGQP/B95w==}
+ engines: {node: '>=10'}
+ cpu: [x64]
+ os: [darwin]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-yCb1FHCX/HUmNRGB1X3CFJ1WPKXMosZVUe3K2TrosCGvytwgaLoW5FS0bZg5Qv6cEUERQBg75cJnOUPwLLRCVg==}
engines: {node: '>=10'}
@@ -14151,6 +14771,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-76YeeQKyK0EtNkQiNBZ0nbVGooPf9IucY0WqVXVpaU4wuG7ZyLEE2ZAIgXafIuzODGQoLfetue7I8boMxh1/MA==}
+ engines: {node: '>=10'}
+ cpu: [arm]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-6TdjVdiLaSW+eGiHKEojMDlx673nowrPHa6nM6toWgRzy8tIZgjPOguVKJDoMnoHuvO7SkOLCUiMRw0rTskypA==}
engines: {node: '>=10'}
@@ -14159,6 +14788,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-BxJDIJPq1+aCh9UsaSAN6wo3tuln8UhNXruOrzTI8/ElIig/3sAueDM6Eq7GvZSGGSA7ljhNATMJ0elD7lFatQ==}
+ engines: {node: '>=10'}
+ cpu: [arm64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-TU2YcTornnyZiJUabRuk7Xtvzaep11FwK77IkFomjN9/Os5s25B8ea652c2fAQMe9RsM84FPVmX303ohxavjKQ==}
engines: {node: '>=10'}
@@ -14167,6 +14805,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-NhLdbffSXvY0/FwUSAl4hKBlpe5GHQGXK8DxTo3HHjLsD9sCPYieo3vG0NQoUYAy4ZUY1WeGjyxeq4qZddJzEQ==}
+ engines: {node: '>=10'}
+ cpu: [arm64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-2CdPTEKxx2hJIj/B0fn8L8k2coo/FDS95smzXyi2bov5FcrP6Ohboq8roFBYgj38fkHusXjY8qt+cCH7yXWAdg==}
engines: {node: '>=10'}
@@ -14175,6 +14822,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-CrYnV8SZIgArQ9LKH0xEF95PKXzX9WkRSc5j55arOSBeDCeDUQk1Bg/iKdnDiuj5HC1hZpvzwMzSBJjv+Z70jA==}
+ engines: {node: '>=10'}
+ cpu: [x64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-14StQBifCs/AMsySdU95OmwNJr9LOVqo6rcTFt2b7XaWpe/AyeuMJFxcndLgUewksJHpfepzCTwNdbcYmuNo6A==}
engines: {node: '>=10'}
@@ -14183,6 +14839,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-BQMl3d0HaGB0/h2xcKlGtjk/cGRn2tnbsaChAKcjFdCepblKBCz1pgO/mL7w5iXq3s57wMDUn++71/a5RAkZOA==}
+ engines: {node: '>=10'}
+ cpu: [x64]
+ os: [linux]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-qemJnAQlYqKCfWNqVv5SG8uGvw8JotwU86cuFUkq35oTB+dsSFM3b83+B1giGTKKFOh2nfWT7bvPXTKk+aUjew==}
engines: {node: '>=10'}
@@ -14191,6 +14856,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-b7NeGnpqTfmIGtUqXBl0KqoSmOnH64nRZoT5l4BAGdvwY7nxitWR94CqZuwyLPty/bLywmyDA9uO12Kvgb3+gg==}
+ engines: {node: '>=10'}
+ cpu: [arm64]
+ os: [win32]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-fXt5vZbnrVdXZzGj2qRnZtY3uh+NtLCaFjS2uD9w8ssdbjhbDZYlJCj2JINOjv35ttEfAD2goiYmVa5P/Ypl+g==}
engines: {node: '>=10'}
@@ -14199,6 +14873,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-iU/29X2D7cHBp1to62cUg/5Xk8K+lyOJiKIGGW5rdzTW/c2zz3d/ehgpzVP/rqC4NVr88MXspqHU4il5gmDajw==}
+ engines: {node: '>=10'}
+ cpu: [ia32]
+ os: [win32]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-W4FA2vSJ+bGYiTj6gspxghSdKQNLfLMo65AH07u797x7I+YJj8amnFY/fQRlroDv5Dez/FHTv14oPlTlNFUpIw==}
engines: {node: '>=10'}
@@ -14207,6 +14890,15 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-+Zh+JKDwiFqV5N9yAd2DhYVGPORGh9cfenu1ptr9yge+eHAf7vZJcC3rnj6QMR1QJh0Y5VC9+YBjRFjZVA7XDw==}
+ engines: {node: '>=10'}
+ cpu: [x64]
+ os: [win32]
+ requiresBuild: true
+ dev: true
+ optional: true
+
resolution: {integrity: sha512-Il4y8XwKDV0Bnk0IpA00kGcSQC6I9XOIinW5egTutnwIDfDE+qsD0j+0isW5H76GetY3/Ze0lVxeOXLAUgpegA==}
engines: {node: '>=10'}
@@ -14215,6 +14907,31 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-aKXdDTqxTVFl/bKQZ3EQUjEMBEoF6JBv29moMZq0kbVO43na6u/u+3Vcbhbrh+A2N0X5OL4RaveuWfAjEgOmeA==}
+ engines: {node: '>=10'}
+ requiresBuild: true
+ peerDependencies:
+ '@swc/helpers': '>=0.5.17'
+ peerDependenciesMeta:
+ '@swc/helpers':
+ optional: true
+ dependencies:
+ '@swc/counter': 0.1.3
+ '@swc/types': 0.1.23
+ optionalDependencies:
+ '@swc/core-darwin-arm64': 1.12.1
+ '@swc/core-darwin-x64': 1.12.1
+ '@swc/core-linux-arm-gnueabihf': 1.12.1
+ '@swc/core-linux-arm64-gnu': 1.12.1
+ '@swc/core-linux-arm64-musl': 1.12.1
+ '@swc/core-linux-x64-gnu': 1.12.1
+ '@swc/core-linux-x64-musl': 1.12.1
+ '@swc/core-win32-arm64-msvc': 1.12.1
+ '@swc/core-win32-ia32-msvc': 1.12.1
+ '@swc/core-win32-x64-msvc': 1.12.1
+ dev: true
+
resolution: {integrity: sha512-EF8C5lp1RKMp3426tAKwQyVbg4Zcn/2FDax3cz8EcOXYQJM/ctB687IvBm9Ciej1wMcQ/dMRg+OB4Xl8BGLBoA==}
engines: {node: '>=10'}
@@ -14360,6 +15077,12 @@ packages:
dependencies:
'@swc/counter': 0.1.3
+ resolution: {integrity: sha512-u1iIVZV9Q0jxY+yM2vw/hZGDNudsN85bBpTqzAQ9rzkxW9D+e3aEM4Han+ow518gSewkXgjmEK0BD79ZcNVgPw==}
+ dependencies:
+ '@swc/counter': 0.1.3
+ dev: true
+
/@szmarczak/[email protected]:
resolution: {integrity: sha512-+PmQX0PiAYPMeVYe237LJAYvOMYW1j2rH5YROyS3b4CTVJum34HfRvKvAzozHAQG0TnHNdUfY9nCeUyRAs//cw==}
engines: {node: '>=14.16'}
@@ -14604,31 +15327,27 @@ packages:
'@types/babel__generator': 7.6.3
'@types/babel__template': 7.4.1
'@types/babel__traverse': 7.14.2
- dev: false
resolution: {integrity: sha512-/GWCmzJWqV7diQW54smJZzWbSFf4QYtF71WCKhcx6Ru/tFyQIY2eiiITcCAeuPbNSvT9YCGkVMqqvSk2Z0mXiA==}
dependencies:
'@babel/types': 7.24.0
- dev: false
resolution: {integrity: sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==}
dependencies:
'@babel/parser': 7.24.1
'@babel/types': 7.24.0
- dev: false
resolution: {integrity: sha512-K2waXdXBi2302XUdcHcR1jCeU0LL4TD9HRs/gk0N2Xvrht+G/BfJa4QObBQZfhMdxiCpV3COl5Nfq4uKTeTnJA==}
dependencies:
'@babel/types': 7.24.0
- dev: false
resolution: {integrity: sha512-a6bTJ21vFOGIkwM0kzh9Yr89ziVxq4vYH2fQ6N8AeipEzai/cFK6aGMArIkUeIdRIgpwQa+2bXiLuUJCpSf2Cg==}
dependencies:
- '@types/connect': 3.4.35
+ '@types/connect': 3.4.38
'@types/node': 20.12.14
@@ -14672,8 +15391,8 @@ packages:
'@types/node': 20.12.14
dev: false
- resolution: {integrity: sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==}
+ resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}
dependencies:
'@types/node': 20.12.14
@@ -14699,6 +15418,10 @@ packages:
resolution: {integrity: sha512-O9/jRVlq93kqfkl4sYR5N7+Pz4ukzXVIbMnE/VgvpauNHsvjQ9iBVnJ3X0gAvMa2khcoFD8DSO7mQVCuiuDMPg==}
dev: true
+ resolution: {integrity: sha512-JwJc6MRVy5xnOUKUgzgGRZA/DOZO14x+4B4hJNZ8c4T5Cs+U00ca62RJHXaj4F9NWZoorKT2PxW5Cq+ENT+E7w==}
+ dev: true
+
resolution: {integrity: sha512-yPEZ3z7EohrmOxbk/QTAa0yonMFkNkjnVXqbGb7D4rMr+F1dGQ8ZUFxXkyLLJuiICPejZ0AZE9Rrk9wUCczx4A==}
@@ -15156,6 +15879,14 @@ packages:
resolution: {integrity: sha512-qvY/TzK1WuxfeACL3Zzw+gMivGiIynRKH98nLET7ACzTRTX8CWMA6LQJ9WayIHvTBU1JeFCBRIBjsxhGz4TfHQ==}
+ resolution: {integrity: sha512-PNvOlIo9AkUA8dvdqJHrvvIZG40Qi37QHNyl1qOD1m/4Lj+2thAtwJM2N9UmtGBtkhb3x9mP/6JlXYtQcZ3uFg==}
+ dev: true
+
+ resolution: {integrity: sha512-4BJZdzrApNFeuXgucyqs24k69f7oti3wUcGEbFbaV08QBh7yEe3tnRRuYXlyXJNXiumpZujiZqUZZ2/gMSeO0g==}
+ dev: true
+
resolution: {integrity: sha512-szL74BnIcok9m7QwYtVmQ+EdIKwbjPANudfuvDrAF8Cljg9MKUlIoc1w5tjj9PMpeSH3U1Xnx//czQybJ0EfSw==}
@@ -15215,6 +15946,33 @@ packages:
- supports-color
dev: true
+ /@typescript-eslint/[email protected](@typescript-eslint/[email protected])([email protected])([email protected]):
+ resolution: {integrity: sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==}
+ engines: {node: ^18.18.0 || >=20.0.0}
+ peerDependencies:
+ '@typescript-eslint/parser': ^7.0.0
+ eslint: ^8.56.0
+ typescript: '*'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+ dependencies:
+ '@eslint-community/regexpp': 4.12.1
+ '@typescript-eslint/parser': 7.18.0([email protected])([email protected])
+ '@typescript-eslint/scope-manager': 7.18.0
+ '@typescript-eslint/type-utils': 7.18.0([email protected])([email protected])
+ '@typescript-eslint/utils': 7.18.0([email protected])([email protected])
+ '@typescript-eslint/visitor-keys': 7.18.0
+ eslint: 9.19.0
+ graphemer: 1.4.0
+ ignore: 5.3.2
+ natural-compare: 1.4.0
+ ts-api-utils: 1.4.0([email protected])
+ typescript: 5.8.2
+ transitivePeerDependencies:
+ - supports-color
+ dev: true
+
resolution: {integrity: sha512-gQxbxM8mcxBwaEmWdtLCIGLfixBMHhQjBqR8sVWNTPpcj45WlYL2IObS/DNMLH1DBP0n8qz+aiiLTGfopPEebw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -15286,6 +16044,27 @@ packages:
- supports-color
dev: true
+ resolution: {integrity: sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==}
+ engines: {node: ^18.18.0 || >=20.0.0}
+ peerDependencies:
+ eslint: ^8.56.0
+ typescript: '*'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+ dependencies:
+ '@typescript-eslint/scope-manager': 7.18.0
+ '@typescript-eslint/types': 7.18.0
+ '@typescript-eslint/typescript-estree': 7.18.0([email protected])
+ '@typescript-eslint/visitor-keys': 7.18.0
+ debug: 4.4.0
+ eslint: 9.19.0
+ typescript: 5.8.2
+ transitivePeerDependencies:
+ - supports-color
+ dev: true
+
resolution: {integrity: sha512-MrvlXNfGPLH3Z+r7Tk+Z5moZAc0dzdVjTgUgwsdGweH7lydysQsnSww3nAmsq8blFuRD5VRlAr9YdEFw3e6PBw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -15340,6 +16119,14 @@ packages:
'@typescript-eslint/visitor-keys': 6.21.0
dev: true
+ /@typescript-eslint/[email protected]:
+ resolution: {integrity: sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==}
+ engines: {node: ^18.18.0 || >=20.0.0}
+ dependencies:
+ '@typescript-eslint/types': 7.18.0
+ '@typescript-eslint/visitor-keys': 7.18.0
+ dev: true
+
/@typescript-eslint/[email protected]:
resolution: {integrity: sha512-gPLpLtrj9aMHOvxJkSbDBmbRuYdtiEbnvO25bCMza3DhMjTQw0u7Y1M+YR5JPbMsXXnSPuCf5hfq0nEkQDL/JQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -15375,6 +16162,26 @@ packages:
- supports-color
dev: true
+ resolution: {integrity: sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==}
+ engines: {node: ^18.18.0 || >=20.0.0}
+ peerDependencies:
+ eslint: ^8.56.0
+ typescript: '*'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+ dependencies:
+ '@typescript-eslint/typescript-estree': 7.18.0([email protected])
+ '@typescript-eslint/utils': 7.18.0([email protected])([email protected])
+ debug: 4.4.0
+ eslint: 9.19.0
+ ts-api-utils: 1.4.0([email protected])
+ typescript: 5.8.2
+ transitivePeerDependencies:
+ - supports-color
+ dev: true
+
resolution: {integrity: sha512-bwuU4TAogPI+1q/IJSKuD4shBLc/d2vGcRT588q+jzayQyjVK2X6v/fbR4InY2U2sgf8MEvVCqEWUzYzgBNcGQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -15420,6 +16227,11 @@ packages:
engines: {node: ^16.0.0 || >=18.0.0}
dev: true
+ /@typescript-eslint/[email protected]:
+ resolution: {integrity: sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==}
+ engines: {node: ^18.18.0 || >=20.0.0}
+ dev: true
+
/@typescript-eslint/[email protected]:
resolution: {integrity: sha512-VwDwMF1SZ7wPBUZwmMdnDJ6sIFk4K4s+ALKLP6aIQsISkPv8jhiw65sAK6SuWODN/ix+m+HgbYDkH+zLjrzvOA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -15472,6 +16284,28 @@ packages:
- supports-color
dev: true
+ /@typescript-eslint/[email protected]([email protected]):
+ resolution: {integrity: sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==}
+ engines: {node: ^18.18.0 || >=20.0.0}
+ peerDependencies:
+ typescript: '*'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+ dependencies:
+ '@typescript-eslint/types': 7.18.0
+ '@typescript-eslint/visitor-keys': 7.18.0
+ debug: 4.4.0
+ globby: 11.1.0
+ is-glob: 4.0.3
+ minimatch: 9.0.5
+ semver: 7.6.3
+ ts-api-utils: 1.4.0([email protected])
+ typescript: 5.8.2
+ transitivePeerDependencies:
+ - supports-color
+ dev: true
+
/@typescript-eslint/[email protected]([email protected]):
resolution: {integrity: sha512-mME5MDwGe30Pq9zKPvyduyU86PH7aixwqYR2grTglAdB+AN8xXQ1vFGpYaUSJ5o5P/5znsSBeNcs5g5/2aQwow==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -15549,6 +16383,22 @@ packages:
- typescript
dev: true
+ resolution: {integrity: sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==}
+ engines: {node: ^18.18.0 || >=20.0.0}
+ peerDependencies:
+ eslint: ^8.56.0
+ dependencies:
+ '@eslint-community/eslint-utils': 4.4.0([email protected])
+ '@typescript-eslint/scope-manager': 7.18.0
+ '@typescript-eslint/types': 7.18.0
+ '@typescript-eslint/typescript-estree': 7.18.0([email protected])
+ eslint: 9.19.0
+ transitivePeerDependencies:
+ - supports-color
+ - typescript
+ dev: true
+
resolution: {integrity: sha512-UTTuDIX3fkfAz6iSVa5rTuSfWIYZ6ATtEocQ/umkRSyC9O919lbZ8dcH7mysshrCdrAM03skJOEYaBugxN+M6A==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -15597,6 +16447,14 @@ packages:
eslint-visitor-keys: 3.4.3
dev: true
+ /@typescript-eslint/[email protected]:
+ resolution: {integrity: sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==}
+ engines: {node: ^18.18.0 || >=20.0.0}
+ dependencies:
+ '@typescript-eslint/types': 7.18.0
+ eslint-visitor-keys: 3.4.3
+ dev: true
+
/@typescript-eslint/[email protected]:
resolution: {integrity: sha512-PChz8UaKQAVNHghsHcPyx1OMHoFRUEA7rJSK/mDhdq85bk+PLsUHUBqTQTFt18VJZbmxBovM65fezlheQRsSDA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -15767,6 +16625,34 @@ packages:
ts-morph: 12.0.0
dev: false
+ resolution: {integrity: sha512-xD3Rdvrt5LgANug7WekBn1KhcvLn1H3jNBfJRL3reeOIua/WnZOEV5qi5qIBq5T8R0jUDmRtxuvk4bPhzGHDWw==}
+ peerDependencies:
+ vite: ^4 || ^5 || ^6 || ^7.0.0-beta.0
+ dependencies:
+ '@rolldown/pluginutils': 1.0.0-beta.11
+ '@swc/core': 1.12.1
+ vite: 5.2.11
+ transitivePeerDependencies:
+ - '@swc/helpers'
+ dev: true
+
+ resolution: {integrity: sha512-SCCPBJtYLdE8PX/7ZQAs1QAZ8Jqwih+0VBLum1EGqmCCQal+MIUqLCzj3ZUy8ufbC0cAM4LRlSTm7IQJwWT4ug==}
+ engines: {node: ^14.18.0 || >=16.0.0}
+ peerDependencies:
+ vite: ^4.2.0 || ^5.0.0 || ^6.0.0
+ dependencies:
+ '@babel/core': 7.26.0
+ '@babel/plugin-transform-react-jsx-self': 7.25.9(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-source': 7.25.9(@babel/[email protected])
+ '@types/babel__core': 7.20.5
+ react-refresh: 0.14.2
+ vite: 5.2.11
+ transitivePeerDependencies:
+ - supports-color
+ dev: true
+
resolution: {integrity: sha512-SCCPBJtYLdE8PX/7ZQAs1QAZ8Jqwih+0VBLum1EGqmCCQal+MIUqLCzj3ZUy8ufbC0cAM4LRlSTm7IQJwWT4ug==}
engines: {node: ^14.18.0 || >=16.0.0}
@@ -16459,7 +17345,6 @@ packages:
picocolors: 1.1.1
postcss: 8.5.1
postcss-value-parser: 4.2.0
- dev: false
resolution: {integrity: sha512-XY25y5xSv/wEoqzDyXXME4AFfkZI0P23z6Fs3YgymDnKJkCGOnkL0iTxCa85UTqaSgfcqyf3UA6+c7wUvx/16g==}
@@ -17467,6 +18352,18 @@ packages:
engines: {node: '>=0.8'}
dev: false
+ resolution: {integrity: sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==}
+ engines: {node: '>= 0.10.0'}
+ dependencies:
+ debug: 2.6.9
+ finalhandler: 1.1.2
+ parseurl: 1.3.3
+ utils-merge: 1.0.1
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-I5qxpzLv+sJhTVEoLYNcTW+bThDCPsit0vLNKShZx6rLtpilNpmmeTPaeqJb9ZE9dV3DGaeby6Vuhrw38WjeyQ==}
engines: {node: ^14.18.0 || >=16.10.0}
@@ -18787,6 +19684,37 @@ packages:
'@esbuild/win32-ia32': 0.18.20
'@esbuild/win32-x64': 0.18.20
+ resolution: {integrity: sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==}
+ engines: {node: '>=12'}
+ hasBin: true
+ requiresBuild: true
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.20.2
+ '@esbuild/android-arm': 0.20.2
+ '@esbuild/android-arm64': 0.20.2
+ '@esbuild/android-x64': 0.20.2
+ '@esbuild/darwin-arm64': 0.20.2
+ '@esbuild/darwin-x64': 0.20.2
+ '@esbuild/freebsd-arm64': 0.20.2
+ '@esbuild/freebsd-x64': 0.20.2
+ '@esbuild/linux-arm': 0.20.2
+ '@esbuild/linux-arm64': 0.20.2
+ '@esbuild/linux-ia32': 0.20.2
+ '@esbuild/linux-loong64': 0.20.2
+ '@esbuild/linux-mips64el': 0.20.2
+ '@esbuild/linux-ppc64': 0.20.2
+ '@esbuild/linux-riscv64': 0.20.2
+ '@esbuild/linux-s390x': 0.20.2
+ '@esbuild/linux-x64': 0.20.2
+ '@esbuild/netbsd-x64': 0.20.2
+ '@esbuild/openbsd-x64': 0.20.2
+ '@esbuild/sunos-x64': 0.20.2
+ '@esbuild/win32-arm64': 0.20.2
+ '@esbuild/win32-ia32': 0.20.2
+ '@esbuild/win32-x64': 0.20.2
+ dev: true
+
resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}
engines: {node: '>=12'}
@@ -19103,6 +20031,15 @@ packages:
eslint: 9.19.0
dev: true
+ resolution: {integrity: sha512-QzliNJq4GinDBcD8gPB5v0wh6g8q3SUi6EFF0x8N/BL9PoVs0atuGc47ozMRyOWAKdwaZ5OnbOEa3WR+dSGKuQ==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0
+ dependencies:
+ eslint: 9.19.0
+ dev: false
+
resolution: {integrity: sha512-hIOwI+5hYGpJEc4uPRmz2ulCjAGD/N13Lukkh8cLV0i2IRk/bdZDYjgLVHj+U9Z704kLIdIO6iueGvxNur0sgw==}
engines: {node: '>=10'}
@@ -19770,6 +20707,21 @@ packages:
dependencies:
to-regex-range: 5.0.1
+ resolution: {integrity: sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==}
+ engines: {node: '>= 0.8'}
+ dependencies:
+ debug: 2.6.9
+ encodeurl: 1.0.2
+ escape-html: 1.0.3
+ on-finished: 2.3.0
+ parseurl: 1.3.3
+ statuses: 1.5.0
+ unpipe: 1.0.0
+ transitivePeerDependencies:
+ - supports-color
+ dev: false
+
resolution: {integrity: sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==}
engines: {node: '>= 0.8'}
@@ -22073,6 +23025,14 @@ packages:
resolution: {integrity: sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-CBDPRLOPjdo+bVlxhaa7FVWaB8OrZZQ34mwm0Fsz9ut6JltN/Td55640ur8bRWSJuz6+nX2klKrpBpV7ktwD3Q==}
+ peerDependencies:
+ react: ^16.5.1 || ^17.0.0 || ^18.0.0
+ dependencies:
+ react: 19.0.0
+ dev: false
+
resolution: {integrity: sha512-PafSWvDTpxdtNEndS2HIHxcNAbd54OaqSYJO90/b63rab2HWYqDbH194j0i82ZFdWOAcf0AHinRykXRRK2PJbw==}
peerDependencies:
@@ -28405,6 +29365,10 @@ packages:
webpack: 5.96.1(@swc/[email protected])
dev: false
+ resolution: {integrity: sha512-3mFKyCo/MBcgyOTlrY8T7odzZFx+w+qKSMAmdFzRvqBfLlSigU6TZnlFHK0lkMwj9Bj8OYU+9yW9lmGuS0QEnQ==}
+ dev: false
+
resolution: {integrity: sha512-kjEBm+pvD+6eAwzJL2Bi+02/9LFLal1Gs61+QB7HvTfQQ0aXwC5LGT8PEt1gS0CWKktKe6ysPTAy3cBC5MeiIg==}
@@ -29741,6 +30705,41 @@ packages:
fsevents: 2.3.3
dev: true
+ resolution: {integrity: sha512-HndV31LWW05i1BLPMUCE1B9E9GFbOu1MbenhS58FuK6owSO5qHm7GiCotrNY1YE5rMeQSFBGmT5ZaLEjFizgiQ==}
+ engines: {node: ^18.0.0 || >=20.0.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^18.0.0 || >=20.0.0
+ less: '*'
+ lightningcss: ^1.21.0
+ sass: '*'
+ stylus: '*'
+ sugarss: '*'
+ terser: ^5.4.0
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ less:
+ optional: true
+ lightningcss:
+ optional: true
+ sass:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ dependencies:
+ esbuild: 0.20.2
+ postcss: 8.5.1
+ rollup: 4.40.1
+ optionalDependencies:
+ fsevents: 2.3.3
+ dev: true
+
resolution: {integrity: sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==}
engines: {node: ^18.0.0 || >=20.0.0}