Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add "Split video from audio" quick action (#10583)

Jonny Burger70ca777ae51e
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 66f1404c4e..362142fb0f 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -13,6 +13,7 @@ import {
makeInMemoryInsertJsxElementCodemodEnvironment,
resolveCompositionComponentWithFile,
simpleDiff,
+ splitVideoFromAudio as splitVideoFromAudioCodemod,
} from '@remotion/studio-codemods';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
import {
@@ -510,6 +511,44 @@ export const createBrowserStudioOperations = ({
}
};
+ const splitVideoFromAudio: BrowserStudioOperations['splitVideoFromAudio'] =
+ async ({fileName, nodePath}) => {
+ try {
+ const project = getProject();
+ const absolutePath = findProjectFile({filePath: fileName, project});
+ const result = await splitVideoFromAudioCodemod({
+ input: project.files[absolutePath],
+ nodePath,
+ formatFile: formatCodemodFile,
+ });
+ const nodePathMutation = controller.applyMutation({
+ fileName: absolutePath,
+ mutate: () => ({
+ ...project,
+ files: {...project.files, [absolutePath]: result.output},
+ }),
+ nodePathMutationFiles: [
+ {
+ absolutePath,
+ remappings: result.nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ],
+ });
+ if (nodePathMutation === null) {
+ throw new Error('Could not split video from audio');
+ }
+
+ return {success: true, nodePathMutation};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error && error.stack ? error.stack : '',
+ };
+ }
+ };
+
const insertJsxElement: BrowserStudioOperations['insertJsxElement'] = async (
request,
) => {
@@ -777,6 +816,7 @@ export const createBrowserStudioOperations = ({
refreshDefaultPropsSubscriptions();
refreshSequencePropsSubscriptions();
},
+ splitVideoFromAudio,
subscribeToDefaultProps: ({clientId, compositionId}) => {
const clients =
defaultPropsSubscriptions.get(compositionId) ?? new Set<string>();
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index 7b2b23eaf9..d10f5ffbd6 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -282,6 +282,84 @@ export const Root = () => <Composition id="MyComp" component={Component} duratio
).toBe(false);
});
+test('splits video from audio, broadcasts remappings and supports undo', async () => {
+ const fileName = '/project/src/Composition.tsx';
+ const initialSource = `import {Video} from '@remotion/media';
+export const Component = () => <Video src="video.mp4" from={10} durationInFrames={20} volume={0.5} style={{opacity: 0.5}} />;`;
+ let currentProject: VirtualProject = {
+ rootDir: '/project',
+ entryPoint: '/project/src/index.tsx',
+ files: {
+ '/project/src/index.tsx': `import {registerRoot} from 'remotion';
+import {Root} from './Composition';
+registerRoot(Root);`,
+ [fileName]: initialSource,
+ },
+ };
+ const operations = createBrowserStudioOperations({
+ dependencyVersions: {},
+ getStaticFiles: null,
+ getProject: () => currentProject,
+ onProjectChange: (nextProject) => {
+ currentProject = nextProject;
+ },
+ resolveDependencies: null,
+ });
+ const events: EventSourceEvent[] = [];
+ operations.subscribeToEvent((event) => events.push(event));
+ const subscription = await operations.subscribeToSequenceProps({
+ fileName: 'src/Composition.tsx',
+ line: 2,
+ column: 31,
+ nodePath: null,
+ componentIdentity: 'dev.remotion.media.Video',
+ keys: ['from', 'durationInFrames'],
+ assetKeys: [],
+ effects: [],
+ clientId: 'browser-studio',
+ videoConfigValues: {
+ durationInFrames: 60,
+ fps: 30,
+ height: 720,
+ width: 1280,
+ },
+ });
+ if (!subscription.success) {
+ throw new Error('Expected sequence props subscription to succeed');
+ }
+
+ events.length = 0;
+ const result = await operations.splitVideoFromAudio({
+ fileName: 'src/Composition.tsx',
+ nodePath: subscription.nodePath.nodePath,
+ });
+ if (!result.success) {
+ throw new Error(result.reason);
+ }
+
+ const output = currentProject.files[fileName];
+ const singleLine = output.replace(/\s+/g, ' ');
+ expect(output).toContain(`import {Video, Audio} from '@remotion/media';`);
+ expect(singleLine).toContain(
+ '<Video src="video.mp4" from={10} durationInFrames={20} volume={0.5} style={{opacity: 0.5}} muted />',
+ );
+ expect(singleLine).toContain(
+ '<Audio src="video.mp4" from={10} durationInFrames={20} volume={0.5} />',
+ );
+ expect(
+ events.filter((event) => event.type === 'sequence-node-paths-remapped'),
+ ).toEqual([
+ {
+ type: 'sequence-node-paths-remapped',
+ mutation: result.nodePathMutation,
+ },
+ ]);
+
+ const undoResult = await operations.undo();
+ expect(undoResult.success).toBe(true);
+ expect(currentProject.files[fileName]).toBe(initialSource);
+});
+
test('reports invalid timeline Solid input without changing the project', async () => {
const project = createBlankTemplateProject();
let currentProject = project;
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index b6bc5c930e..bb70562b42 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -37,6 +37,7 @@ export {
export {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
export {simpleDiff} from './simple-diff';
+export {splitVideoFromAudio} from './split-video-from-audio';
export {updateInlineCaptionPatches} from './update-inline-caption-patches';
export {
type RemovedProp,
diff --git a/packages/studio-codemods/src/split-video-from-audio.ts b/packages/studio-codemods/src/split-video-from-audio.ts
new file mode 100644
index 0000000000..568f3b139b
--- /dev/null
+++ b/packages/studio-codemods/src/split-video-from-audio.ts
@@ -0,0 +1,311 @@
+import type {
+ ArrowFunctionExpression,
+ Expression,
+ File,
+ JSXAttribute,
+ JSXElement,
+ JSXFragment,
+ Node,
+ ReturnStatement,
+} from '@babel/types';
+import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import {
+ findJsxElementPathForDeletion,
+ getJsxElementTagLabel,
+} from './delete-jsx-node';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
+import {ensureNamedImport} from './sequence-props/imports';
+import {parseAst, serializeAst} from './sequence-props/parse-ast';
+
+const {namedTypes} = recast.types;
+
+// Props that are valid on <Audio> and should carry over so the extracted
+// audio keeps the same timing as the video it was split from.
+const audioProps = [
+ 'src',
+ 'from',
+ 'durationInFrames',
+ 'trimBefore',
+ 'trimAfter',
+ 'playbackRate',
+ 'volume',
+ 'loop',
+];
+
+/*
+ * Deep-clones an AST subtree while sharing `loc` objects by reference, like
+ * Babel's `cloneNode`. A runtime import of `@babel/types` is avoided because
+ * it reads `process.env` at module load, which breaks browser bundles.
+ */
+const cloneAstValue = <T>(value: T): T => {
+ if (Array.isArray(value)) {
+ return value.map((item) => cloneAstValue(item)) as T;
+ }
+
+ if (value !== null && typeof value === 'object') {
+ const clone: Record<string, unknown> = {};
+ for (const [key, item] of Object.entries(value)) {
+ clone[key] = key === 'loc' ? item : cloneAstValue(item);
+ }
+
+ return clone as T;
+ }
+
+ return value;
+};
+
+const getAttributeName = (
+ attribute: JSXElement['openingElement']['attributes'][number],
+): string | null => {
+ if (
+ attribute.type !== 'JSXAttribute' ||
+ attribute.name.type !== 'JSXIdentifier'
+ ) {
+ return null;
+ }
+
+ return attribute.name.name;
+};
+
+const findImportSourceOfLocalName = (
+ ast: File,
+ localName: string,
+): string | null => {
+ for (const stmt of ast.program.body) {
+ if (
+ stmt.type !== 'ImportDeclaration' ||
+ stmt.source.type !== 'StringLiteral' ||
+ stmt.importKind === 'type'
+ ) {
+ continue;
+ }
+
+ for (const specifier of stmt.specifiers ?? []) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ specifier.local?.name === localName
+ ) {
+ return stmt.source.value;
+ }
+ }
+ }
+
+ return null;
+};
+
+const importsLocalNameFromOtherSource = ({
+ ast,
+ localName,
+ sourcePath,
+}: {
+ ast: File;
+ localName: string;
+ sourcePath: string;
+}): string | null => {
+ for (const stmt of ast.program.body) {
+ if (
+ stmt.type !== 'ImportDeclaration' ||
+ stmt.source.type !== 'StringLiteral' ||
+ stmt.source.value === sourcePath
+ ) {
+ continue;
+ }
+
+ for (const specifier of stmt.specifiers ?? []) {
+ if (specifier.local?.name === localName) {
+ return stmt.source.value;
+ }
+ }
+ }
+
+ return null;
+};
+
+const setBareMutedAttribute = (element: JSXElement) => {
+ const {
+ openingElement: {attributes},
+ } = element;
+ const muted: JSXAttribute = {
+ type: 'JSXAttribute',
+ name: {type: 'JSXIdentifier', name: 'muted'},
+ value: null,
+ };
+ const index = attributes.findIndex(
+ (attribute) => getAttributeName(attribute) === 'muted',
+ );
+
+ if (index === -1) {
+ attributes.push(muted);
+ } else {
+ attributes[index] = muted;
+ }
+};
+
+const makeFragment = (first: JSXElement, second: JSXElement): JSXFragment => ({
+ type: 'JSXFragment',
+ openingFragment: {type: 'JSXOpeningFragment'},
+ closingFragment: {type: 'JSXClosingFragment'},
+ children: [first, second],
+});
+
+const insertAfter = (
+ parentNode: Node,
+ node: JSXElement,
+ sibling: JSXElement,
+): boolean => {
+ if (
+ namedTypes.JSXElement.check(parentNode) ||
+ namedTypes.JSXFragment.check(parentNode)
+ ) {
+ const idx = parentNode.children.indexOf(node);
+ if (idx !== -1) {
+ parentNode.children.splice(idx + 1, 0, sibling);
+ return true;
+ }
+ }
+
+ if (namedTypes.ReturnStatement.check(parentNode)) {
+ const parent = parentNode as ReturnStatement;
+ if (parent.argument === node) {
+ parent.argument = makeFragment(node, sibling) as unknown as Expression;
+ return true;
+ }
+ }
+
+ if (namedTypes.ArrowFunctionExpression.check(parentNode)) {
+ const parent = parentNode as ArrowFunctionExpression;
+ if (parent.body === node) {
+ parent.body = makeFragment(
+ node,
+ sibling,
+ ) as ArrowFunctionExpression['body'];
+ return true;
+ }
+ }
+
+ return false;
+};
+
+export const splitVideoFromAudio = async ({
+ input,
+ nodePath,
+ formatFile,
+ prettierConfigOverride,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ formatFile: (input: {
+ contents: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+ }) => Promise<{output: string; formatted: boolean}>;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ formatted: boolean;
+ nodeLabel: string;
+ logLine: number;
+ nodePathRemappings: Array<{
+ oldNodePath: SequenceNodePath;
+ newNodePath: SequenceNodePath | null;
+ }>;
+}> => {
+ const ast = parseAst(input);
+ const capturedNodePaths = captureJsxNodePaths(ast);
+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
+ if (!jsxPath) {
+ throw new Error(
+ 'Could not find a JSX element at the specified location to split audio from',
+ );
+ }
+
+ const jsxElement = jsxPath.node as JSXElement;
+ const nodeLabel = getJsxElementTagLabel(jsxElement);
+
+ if (jsxElement.openingElement.name.type !== 'JSXIdentifier') {
+ throw new Error(`Cannot split audio from <${nodeLabel}>`);
+ }
+
+ const tagName = jsxElement.openingElement.name.name;
+ const importSource = findImportSourceOfLocalName(ast, tagName);
+ if (!importSource) {
+ throw new Error(`Could not find the import of <${tagName}>`);
+ }
+
+ const hasSrc = jsxElement.openingElement.attributes.some(
+ (attribute) => getAttributeName(attribute) === 'src',
+ );
+ if (!hasSrc) {
+ throw new Error(`<${tagName}> has no src attribute`);
+ }
+
+ const conflictingSource = importsLocalNameFromOtherSource({
+ ast,
+ localName: 'Audio',
+ sourcePath: importSource,
+ });
+ if (conflictingSource) {
+ throw new Error(
+ `Audio is already imported from "${conflictingSource}", expected "${importSource}"`,
+ );
+ }
+
+ const audioLocalName = ensureNamedImport({
+ ast,
+ importedName: 'Audio',
+ sourcePath: importSource,
+ localName: 'Audio',
+ });
+ const audioElement: JSXElement = {
+ type: 'JSXElement',
+ openingElement: {
+ type: 'JSXOpeningElement',
+ name: {type: 'JSXIdentifier', name: audioLocalName},
+ attributes: jsxElement.openingElement.attributes
+ .filter((attribute) => {
+ const name = getAttributeName(attribute);
+ return name !== null && audioProps.includes(name);
+ })
+ .map((attribute) => cloneAstValue(attribute)),
+ selfClosing: true,
+ },
+ closingElement: null,
+ children: [],
+ };
+
+ setBareMutedAttribute(jsxElement);
+
+ const {parentPath} = jsxPath;
+ if (!parentPath) {
+ throw new Error('Cannot split audio from a JSX element with no parent');
+ }
+
+ if (!insertAfter(parentPath.node, jsxElement, audioElement)) {
+ jsxPath.replace(makeFragment(jsxElement, audioElement));
+ }
+
+ const finalFile = serializeAst(ast);
+ const {output, formatted} = await formatFile({
+ contents: finalFile,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ });
+ const {nodePathRemappings} = getNodePathRemappings({
+ ast,
+ captured: capturedNodePaths,
+ output,
+ });
+
+ return {
+ output,
+ formatted,
+ nodeLabel,
+ logLine:
+ jsxElement.openingElement.loc?.start.line ??
+ jsxElement.loc?.start.line ??
+ 1,
+ nodePathRemappings,
+ };
+};
diff --git a/packages/studio-server/src/codemods/split-video-from-audio.ts b/packages/studio-server/src/codemods/split-video-from-audio.ts
new file mode 100644
index 0000000000..f359c2ea15
--- /dev/null
+++ b/packages/studio-server/src/codemods/split-video-from-audio.ts
@@ -0,0 +1,23 @@
+import {splitVideoFromAudio as splitVideoFromAudioCodemod} from '@remotion/studio-codemods';
+import type {SequenceNodePath} from 'remotion';
+import {formatFileContent} from './format-file-content';
+
+export const splitVideoFromAudio = ({
+ input,
+ nodePath,
+ prettierConfigOverride,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}) =>
+ splitVideoFromAudioCodemod({
+ input,
+ nodePath,
+ formatFile: ({contents, prettierConfigOverride: override}) =>
+ formatFileContent({
+ input: contents,
+ prettierConfigOverride: override,
+ }),
+ prettierConfigOverride,
+ });
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.ts
index baf4a4f7ab..cf0ff23361 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -49,6 +49,7 @@ import {saveEffectPropsHandler} from './routes/save-effect-props';
import {saveMultipleEffectPropsHandler} from './routes/save-multiple-effect-props';
import {saveSequencePropsHandler} from './routes/save-sequence-props';
import {splitJsxSequenceHandler} from './routes/split-jsx-sequence';
+import {splitVideoFromAudioHandler} from './routes/split-video-from-audio';
import {subscribeToDefaultProps} from './routes/subscribe-to-default-props';
import {subscribeToFileExistence} from './routes/subscribe-to-file-existence';
import {subscribeToSequenceProps} from './routes/subscribe-to-sequence-props';
@@ -114,6 +115,7 @@ export const allApiRoutes: {
'/api/delete-jsx-node': deleteJsxNodeHandler,
'/api/duplicate-jsx-node': duplicateJsxNodeHandler,
'/api/split-jsx-sequence': splitJsxSequenceHandler,
+ '/api/split-video-from-audio': splitVideoFromAudioHandler,
'/api/update-available': handleUpdate,
'/api/remotion-skills-info': remotionSkillsInfoHandler,
'/api/project-info': projectInfoHandler,
diff --git a/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts b/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts
new file mode 100644
index 0000000000..55b3835924
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts
@@ -0,0 +1,113 @@
+import {readFileSync} from 'node:fs';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ SplitVideoFromAudioRequest,
+ SplitVideoFromAudioResponse,
+} from '@remotion/studio-shared';
+import {splitVideoFromAudio} from '../../codemods/split-video-from-audio';
+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
+import type {ApiHandler} from '../api-types';
+import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
+import {
+ printUndoHint,
+ pushToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {warnAboutPrettierOnce} from './log-updates/log-update';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const splitVideoFromAudioHandler: ApiHandler<
+ SplitVideoFromAudioRequest,
+ SplitVideoFromAudioResponse
+> = ({input: {fileName, nodePath}, remotionRoot, logLevel}) =>
+ withSourceFileWriteQueue(async () => {
+ try {
+ RenderInternals.Log.trace(
+ {indent: false, logLevel},
+ `[split-video-from-audio] Received request for fileName="${fileName}"`,
+ );
+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
+ remotionRoot,
+ fileName,
+ action: 'modify',
+ });
+
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+
+ const {output, formatted, nodeLabel, logLine, nodePathRemappings} =
+ await splitVideoFromAudio({
+ input: fileContents,
+ nodePath,
+ });
+ const nodePathMutation = broadcastSequenceNodePathMutation([
+ {
+ absolutePath,
+ remappings: nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ]);
+
+ pushToUndoStack({
+ filePath: absolutePath,
+ oldContents: fileContents,
+ newContents: null,
+ logLevel,
+ remotionRoot,
+ logLine,
+ description: {
+ undoMessage: `↩️ Split of audio from ${nodeLabel}`,
+ redoMessage: `↪️ Split of audio from ${nodeLabel}`,
+ },
+ entryType: 'split-video-from-audio',
+ suppressHmrOnFileRestore: false,
+ nodePathRemappings,
+ });
+ suppressUndoStackInvalidation(absolutePath);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: undefined,
+ metadata: {skipSequencePropsUpdate: true},
+ });
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(
+ `${locationLabel}`,
+ )} Split audio from ${nodeLabel}`,
+ );
+ if (!formatted) {
+ warnAboutPrettierOnce(logLevel);
+ }
+
+ RenderInternals.Log.verbose(
+ {indent: false, logLevel},
+ `[split-video-from-audio] Wrote ${fileRelativeToRoot}${
+ formatted ? ' (formatted)' : ''
+ }`,
+ );
+
+ printUndoHint(logLevel);
+
+ return {
+ success: true,
+ nodePathMutation,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ reason: (err as Error).message,
+ stack: (err as Error).stack as string,
+ };
+ }
+ });
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index a7c3e63f35..026b19bd43 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -41,6 +41,7 @@ type UndoEntryType =
| 'delete-jsx-node'
| 'duplicate-jsx-node'
| 'split-jsx-sequence'
+ | 'split-video-from-audio'
| 'insert-jsx-element'
| 'delete-composition'
| 'rename-composition'
@@ -69,33 +70,8 @@ type UndoEntry = {
description: UndoEntryDescription;
/** When true, undo/redo file restores call `suppressBundlerUpdateForFile` (skip HMR refresh). */
suppressHmrOnFileRestore: boolean;
-} & (
- | {entryType: 'visual-control'}
- | {entryType: 'default-props'}
- | {entryType: 'sequence-props'}
- | {entryType: 'effect-props'}
- | {entryType: 'keyframe-add'}
- | {entryType: 'keyframe-delete'}
- | {entryType: 'add-effect'}
- | {entryType: 'delete-effect'}
- | {entryType: 'duplicate-effect'}
- | {entryType: 'paste-effects'}
- | {entryType: 'reorder-effect'}
- | {entryType: 'reorder-sequence'}
- | {entryType: 'delete-jsx-node'}
- | {entryType: 'duplicate-jsx-node'}
- | {entryType: 'split-jsx-sequence'}
- | {entryType: 'insert-jsx-element'}
- | {entryType: 'delete-composition'}
- | {entryType: 'rename-composition'}
- | {entryType: 'update-composition-metadata'}
- | {entryType: 'new-composition'}
- | {entryType: 'duplicate-composition'}
- | {entryType: 'move-composition-to-folder'}
- | {entryType: 'new-folder'}
- | {entryType: 'delete-folder'}
- | {entryType: 'rename-folder'}
-);
+ entryType: UndoEntryType;
+};
const MAX_ENTRIES = 100;
const undoStack: UndoEntry[] = [];
diff --git a/packages/studio-server/src/test/split-video-from-audio.test.ts b/packages/studio-server/src/test/split-video-from-audio.test.ts
new file mode 100644
index 0000000000..4901cbc079
--- /dev/null
+++ b/packages/studio-server/src/test/split-video-from-audio.test.ts
@@ -0,0 +1,216 @@
+import {expect, test} from 'bun:test';
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
+import {tmpdir} from 'node:os';
+import path from 'node:path';
+import {splitVideoFromAudio} from '../codemods/split-video-from-audio';
+import {
+ createFileWatcherRegistry,
+ setFileWatcherRegistry,
+} from '../file-watcher';
+import {setLiveEventsListener} from '../preview-server/live-events';
+import {splitVideoFromAudioHandler} from '../preview-server/routes/split-video-from-audio';
+import {getUndoStack} from '../preview-server/undo-stack';
+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
+
+const wrap = (
+ element: string,
+ imports = `import {Video} from '@remotion/media';`,
+) => `${imports}
+
+export const Comp = () => {
+ return (
+ <>
+ ${element}
+ </>
+ );
+};
+`;
+
+const elementLine = 6;
+
+const split = async (element: string, imports?: string) => {
+ const input = wrap(element, imports);
+ const {output} = await splitVideoFromAudio({
+ input,
+ nodePath: lineContainingToNodePath(input, element),
+ });
+
+ return output;
+};
+
+test('splitVideoFromAudio mutes the video and adds an Audio with the same timing', async () => {
+ const output = await split(
+ '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} />',
+ );
+
+ const singleLine = output.replace(/\s+/g, ' ');
+
+ expect(output).toContain(`import {Video, Audio} from '@remotion/media';`);
+ expect(singleLine).toContain(
+ '<Video src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} style={{opacity: 0.5}} muted />',
+ );
+ expect(singleLine).toContain(
+ '<Audio src="video.mp4" from={10} durationInFrames={50} trimBefore={5} playbackRate={2} volume={0.5} />',
+ );
+});
+
+test('splitVideoFromAudio does not copy non-audio props', async () => {
+ const output = await split(
+ '<Video src="video.mp4" name="my video" freeze={20} crop={{x: 0, y: 0, width: 100, height: 100}} />',
+ );
+
+ expect(output).toContain('<Audio src="video.mp4" />');
+});
+
+test('splitVideoFromAudio replaces an existing muted prop', async () => {
+ const output = await split('<Video src="video.mp4" muted={false} />');
+
+ expect(output).toContain('<Video src="video.mp4" muted />');
+ expect(output).not.toContain('muted={false}');
+});
+
+test('splitVideoFromAudio reuses an existing Audio import', async () => {
+ const output = await split(
+ '<Video src="video.mp4" />',
+ `import {Audio, Video} from '@remotion/media';`,
+ );
+
+ expect(output).toContain(`import {Audio, Video} from '@remotion/media';`);
+ expect(output.match(/from '@remotion\/media'/g)?.length).toBe(1);
+});
+
+test('splitVideoFromAudio imports Audio from the same module as the tag', async () => {
+ const output = await split(
+ '<OffthreadVideo src="video.mp4" from={5} />',
+ `import {OffthreadVideo} from 'remotion';`,
+ );
+
+ expect(output).toContain(`import {OffthreadVideo, Audio} from 'remotion';`);
+ expect(output).toContain('<OffthreadVideo src="video.mp4" from={5} muted />');
+ expect(output).toContain('<Audio src="video.mp4" from={5} />');
+});
+
+test('splitVideoFromAudio follows import aliases', async () => {
+ const output = await split(
+ '<V src="video.mp4" />',
+ `import {Video as V} from '@remotion/media';`,
+ );
+
+ expect(output).toContain(
+ `import {Video as V, Audio} from '@remotion/media';`,
+ );
+ expect(output).toContain('<Audio src="video.mp4" />');
+});
+
+test('splitVideoFromAudio rejects elements without a src attribute', async () => {
+ await expect(split('<Video from={0} />')).rejects.toThrow(
+ '<Video> has no src attribute',
+ );
+});
+
+test('splitVideoFromAudio rejects unimported tags', async () => {
+ await expect(split('<video src="video.mp4" />')).rejects.toThrow(
+ 'Could not find the import of <video>',
+ );
+});
+
+test('splitVideoFromAudio rejects an Audio import from another module', async () => {
+ await expect(
+ split(
+ '<Video src="video.mp4" />',
+ `import {Video} from '@remotion/media';\nimport {Audio} from 'remotion';`,
+ ),
+ ).rejects.toThrow('Audio is already imported from "remotion"');
+});
+
+const clearUndoStack = () => {
+ (getUndoStack() as unknown as unknown[]).length = 0;
+};
+
+const getHandlerOptions = <T>({
+ input,
+ entryPoint,
+ remotionRoot,
+}: {
+ input: T;
+ entryPoint: string;
+ remotionRoot: string;
+}) => ({
+ input,
+ entryPoint,
+ remotionRoot,
+ request: {} as never,
+ response: {} as never,
+ logLevel: 'error' as const,
+ methods: {
+ removeJob: () => undefined,
+ cancelJob: () => undefined,
+ addJob: () => undefined,
+ },
+ publicDir: remotionRoot,
+ binariesDirectory: null,
+ configFile: null,
+ getDefaultCodingAgent: () => null,
+ getDefaultEditor: () => null,
+});
+
+test('splitVideoFromAudioHandler writes success and failure responses', async () => {
+ const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-split-av-'));
+ const cleanupFileWatcher = setFileWatcherRegistry(
+ createFileWatcherRegistry(),
+ );
+ const cleanupLiveEvents = setLiveEventsListener({
+ sendEventToClient: () => undefined,
+ sendEventToClientId: () => true,
+ router: () => Promise.resolve(),
+ closeConnections: () => Promise.resolve(),
+ addNewClientListener: () => () => undefined,
+ });
+
+ try {
+ clearUndoStack();
+ const entryPoint = path.join(remotionRoot, 'Root.tsx');
+ const input = wrap('<Video src="video.mp4" from={0} trimBefore={10} />');
+ writeFileSync(entryPoint, input);
+
+ const success = await splitVideoFromAudioHandler(
+ getHandlerOptions({
+ input: {
+ fileName: entryPoint,
+ nodePath: lineColumnToNodePath(input, elementLine),
+ },
+ entryPoint,
+ remotionRoot,
+ }),
+ );
+
+ expect(success.success).toBe(true);
+ const written = readFileSync(entryPoint, 'utf-8');
+ expect(written).toContain(
+ '<Video src="video.mp4" from={0} trimBefore={10} muted />',
+ );
+ expect(written).toContain(
+ '<Audio src="video.mp4" from={0} trimBefore={10} />',
+ );
+ expect(getUndoStack().length).toBe(1);
+
+ const failureInput = wrap('<Video from={0} />');
+ writeFileSync(entryPoint, failureInput);
+ const failure = await splitVideoFromAudioHandler(
+ getHandlerOptions({
+ input: {
+ fileName: entryPoint,
+ nodePath: lineColumnToNodePath(failureInput, elementLine),
+ },
+ entryPoint,
+ remotionRoot,
+ }),
+ );
+
+ expect(failure.success).toBe(false);
+ } finally {
+ cleanupFileWatcher();
+ cleanupLiveEvents();
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index b32a7e58e5..902a3c71b6 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -834,6 +834,22 @@ export type SplitJsxSequenceResponse =
stack: string;
};
+export type SplitVideoFromAudioRequest = {
+ fileName: string;
+ nodePath: SequenceNodePath;
+};
+
+export type SplitVideoFromAudioResponse =
+ | {
+ success: true;
+ nodePathMutation: SequenceNodePathMutation;
+ }
+ | {
+ success: false;
+ reason: string;
+ stack: string;
+ };
+
export type InsertableCompositionElement =
| {
type: 'solid';
@@ -1270,6 +1286,10 @@ export type ApiRoutes = {
SplitJsxSequenceRequest,
SplitJsxSequenceResponse
>;
+ '/api/split-video-from-audio': ReqAndRes<
+ SplitVideoFromAudioRequest,
+ SplitVideoFromAudioResponse
+ >;
'/api/insert-jsx-element': ReqAndRes<
InsertJsxElementRequest,
InsertJsxElementResponse
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
index ab6becd43a..efcae14791 100644
--- a/packages/studio-shared/src/browser-studio-operations.ts
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -19,6 +19,8 @@ import type {
SaveSequencePropsRequest,
SaveSequencePropsResponse,
SimpleDiff,
+ SplitVideoFromAudioRequest,
+ SplitVideoFromAudioResponse,
SubscribeToDefaultPropsRequest,
SubscribeToDefaultPropsResponse,
SubscribeToSequencePropsRequest,
@@ -90,6 +92,9 @@ export type BrowserStudioOperations = {
saveSequenceProps: (
request: SaveSequencePropsRequest,
) => Promise<SaveSequencePropsResponse>;
+ splitVideoFromAudio: (
+ request: SplitVideoFromAudioRequest,
+ ) => Promise<SplitVideoFromAudioResponse>;
subscribeToDefaultProps: (
request: SubscribeToDefaultPropsRequest,
) => Promise<SubscribeToDefaultPropsResponse>;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 2e728110ce..b4e851b157 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -122,6 +122,8 @@ export {
SimpleDiff,
SplitJsxSequenceRequest,
SplitJsxSequenceResponse,
+ SplitVideoFromAudioRequest,
+ SplitVideoFromAudioResponse,
SubscribeToDefaultPropsRequest,
SubscribeToDefaultPropsResponse,
SubscribeToFileExistenceRequest,
diff --git a/packages/studio/src/components/InspectorPanel/CompositionInspector.tsx b/packages/studio/src/components/InspectorPanel/CompositionInspector.tsx
index 01442305a5..d11596ac32 100644
--- a/packages/studio/src/components/InspectorPanel/CompositionInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/CompositionInspector.tsx
@@ -30,9 +30,9 @@ import type {SegmentedControlItem} from '../SegmentedControl';
import {SegmentedControl} from '../SegmentedControl';
import {VisualControlsContent} from '../VisualControls/VisualControlsContent';
import {
- InspectorActionSection,
+ InspectorQuickActionsSection,
InspectorDefaultPropsWarnings,
- InspectorInlineAction,
+ InspectorQuickAction,
InspectorSectionDivider,
InspectorSectionHeader,
} from './common';
@@ -99,9 +99,9 @@ const CompositionActions: React.FC<{
}
return (
- <InspectorActionSection>
+ <InspectorQuickActionsSection>
{canShowInsertSolid ? (
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={!canInsertSolid}
onClick={insertSolid}
renderIcon={(color) => (
@@ -109,10 +109,10 @@ const CompositionActions: React.FC<{
)}
>
Add Solid
- </InspectorInlineAction>
+ </InspectorQuickAction>
) : null}
{canShowInsertAsset ? (
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={!canInsertAsset}
onClick={insertAsset}
renderIcon={(color) => (
@@ -120,10 +120,10 @@ const CompositionActions: React.FC<{
)}
>
Add asset...
- </InspectorInlineAction>
+ </InspectorQuickAction>
) : null}
{canShowInsertComposition ? (
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={!canInsertComposition}
onClick={insertComposition}
renderIcon={(color) => (
@@ -131,10 +131,10 @@ const CompositionActions: React.FC<{
)}
>
Add composition...
- </InspectorInlineAction>
+ </InspectorQuickAction>
) : null}
{canShowInsertAsset ? (
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={false}
iconContainerStyle={browseElementsIconContainerStyle}
onClick={openElementsLibrary}
@@ -144,9 +144,9 @@ const CompositionActions: React.FC<{
title="Open the Remotion Elements library in a new tab. Install an Element there to send it to this composition."
>
Browse Elements...
- </InspectorInlineAction>
+ </InspectorQuickAction>
) : null}
- </InspectorActionSection>
+ </InspectorQuickActionsSection>
);
};
diff --git a/packages/studio/src/components/InspectorPanel/CompositionInspectorHeader.tsx b/packages/studio/src/components/InspectorPanel/CompositionInspectorHeader.tsx
index 9dde0fc33d..c5ab60cee3 100644
--- a/packages/studio/src/components/InspectorPanel/CompositionInspectorHeader.tsx
+++ b/packages/studio/src/components/InspectorPanel/CompositionInspectorHeader.tsx
@@ -156,7 +156,7 @@ export const CompositionInspectorHeader = () => {
canOpen={validatedLocation !== null && canOpenInEditor}
onOpen={openFileLocation}
renderIcon={renderCompositionIcon}
- size="inline-action"
+ size="quick-action"
/>
{compositionComponentInfo === null &&
compositionFile !== null &&
@@ -168,7 +168,7 @@ export const CompositionInspectorHeader = () => {
canOpen={componentLocation !== null && canOpenInEditor}
onOpen={openComponentLocation}
renderIcon={renderReactIcon}
- size="inline-action"
+ size="quick-action"
/>
)}
</InspectorLocationCopy>
diff --git a/packages/studio/src/components/InspectorPanel/ConnectedCompositionsSection.tsx b/packages/studio/src/components/InspectorPanel/ConnectedCompositionsSection.tsx
index 9f6485541e..0eb3cab7d4 100644
--- a/packages/studio/src/components/InspectorPanel/ConnectedCompositionsSection.tsx
+++ b/packages/studio/src/components/InspectorPanel/ConnectedCompositionsSection.tsx
@@ -12,7 +12,7 @@ import {ContextMenu} from '../ContextMenu';
import {useSelectComposition} from '../InitialCompositionLoader';
import {useResolvedStack} from '../Timeline/use-resolved-stack';
import {useEditorOpening} from '../use-default-editor-info';
-import {InspectorInlineAction} from './common';
+import {InspectorQuickAction} from './common';
const compositionIconStyle: React.CSSProperties = {
height: 18,
@@ -99,7 +99,7 @@ const ConnectedCompositionRow: React.FC<{
getItems={getContextMenuItems}
style={compositionContextMenuStyle}
>
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={false}
onClick={() => selectComposition(composition, true)}
renderIcon={(color) => (
@@ -111,7 +111,7 @@ const ConnectedCompositionRow: React.FC<{
)}
>
{composition.id}
- </InspectorInlineAction>
+ </InspectorQuickAction>
</ContextMenu>
);
};
diff --git a/packages/studio/src/components/InspectorPanel/EasingInspector.tsx b/packages/studio/src/components/InspectorPanel/EasingInspector.tsx
index ff29cf5bee..976cf601e2 100644
--- a/packages/studio/src/components/InspectorPanel/EasingInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/EasingInspector.tsx
@@ -26,9 +26,9 @@ import {
type EasingSelection,
} from '../Timeline/update-selected-easing';
import {
- InspectorActionSection,
+ InspectorQuickActionsSection,
InspectorBackAction,
- InspectorInlineAction,
+ InspectorQuickAction,
InspectorMessage,
InspectorSectionDivider,
} from './common';
@@ -343,8 +343,8 @@ export const EasingInspector: React.FC<{
<InspectorSectionDivider />
<KeyframeSettings update={easingUpdate} />
{canAddKeyframeAtPlayhead ? (
- <InspectorActionSection>
- <InspectorInlineAction
+ <InspectorQuickActionsSection>
+ <InspectorQuickAction
disabled={addKeyframeDisabled}
onClick={onAddKeyframeAtPlayhead}
renderIcon={(color) => (
@@ -352,8 +352,8 @@ export const EasingInspector: React.FC<{
)}
>
{`Add keyframe at ${addKeyframeTime}`}
- </InspectorInlineAction>
- </InspectorActionSection>
+ </InspectorQuickAction>
+ </InspectorQuickActionsSection>
) : null}
</div>
);
diff --git a/packages/studio/src/components/InspectorPanel/KeyframeInspector.tsx b/packages/studio/src/components/InspectorPanel/KeyframeInspector.tsx
index 9ace147241..18aefb5711 100644
--- a/packages/studio/src/components/InspectorPanel/KeyframeInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/KeyframeInspector.tsx
@@ -45,10 +45,10 @@ import {
import {TimelineSequenceKeyframedValue} from '../Timeline/TimelineSequencePropItem';
import {canEditEasingForInterpolationFunction} from '../Timeline/update-selected-easing';
import {
- InspectorActionSection,
+ InspectorQuickActionsSection,
InspectorBackAction,
InspectorDetailRow,
- InspectorInlineAction,
+ InspectorQuickAction,
InspectorMessage,
InspectorSectionDivider,
} from './common';
@@ -590,15 +590,15 @@ export const KeyframeInspector: React.FC<{
</InspectorDetailRow>
</div>
</div>
- <InspectorActionSection>
- <InspectorInlineAction
+ <InspectorQuickActionsSection>
+ <InspectorQuickAction
disabled={removeDisabled}
onClick={onRemoveKeyframe}
renderIcon={(color) => <TrashIcon color={color} />}
>
Remove keyframe
- </InspectorInlineAction>
- </InspectorActionSection>
+ </InspectorQuickAction>
+ </InspectorQuickActionsSection>
</div>
</div>
);
diff --git a/packages/studio/src/components/InspectorPanel/SequenceInspectorHeader.tsx b/packages/studio/src/components/InspectorPanel/SequenceInspectorHeader.tsx
index a4993bba21..6bb6a3d487 100644
--- a/packages/studio/src/components/InspectorPanel/SequenceInspectorHeader.tsx
+++ b/packages/studio/src/components/InspectorPanel/SequenceInspectorHeader.tsx
@@ -11,7 +11,7 @@ import {COMPACT_INLINE_ROW_HEIGHT} from '../layout';
import {useOpenSequenceInApps} from '../Timeline/use-open-sequence-in-apps';
import {useRenameSequence} from '../Timeline/use-rename-sequence';
import {
- InspectorInlineAction,
+ InspectorQuickAction,
InspectorSection,
InspectorSectionDivider,
} from './common';
@@ -145,7 +145,7 @@ export const SequenceInspectorHeader: React.FC<{
size="inspector"
/>
{documentationLink ? (
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={false}
style={defaultCursor}
size="compact"
@@ -153,7 +153,7 @@ export const SequenceInspectorHeader: React.FC<{
onClick={openDocumentationLink}
>
{componentName}
- </InspectorInlineAction>
+ </InspectorQuickAction>
) : (
<div style={subtitleStyle}>{componentName}</div>
)}
@@ -162,7 +162,7 @@ export const SequenceInspectorHeader: React.FC<{
canOpen={sourceLocation.canOpenInEditor}
onOpen={sourceLocation.openFileLocation}
renderIcon={renderReactIcon}
- size="inline-action"
+ size="quick-action"
/>
</InspectorLocationCopy>
</InspectorInfoHeader>
diff --git a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
index d5ab2cf150..c4df7ff4f8 100644
--- a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
@@ -3,6 +3,7 @@ import {Internals} from 'remotion';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import type {TimelineTrackData} from '../../helpers/get-timeline-sequence-sort-key';
import {isStudioInteractivityEnabled} from '../../helpers/interactivity-enabled';
+import {AudioIcon} from '../../icons/audio';
import {DuplicateIcon} from '../../icons/duplicate';
import {ScissorsIcon} from '../../icons/scissors';
import {SnowflakeIcon} from '../../icons/snowflake';
@@ -13,6 +14,8 @@ import {
InspectorSequenceSection,
} from '../InspectorSequenceSection';
import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';
+import {showNotification} from '../Notifications/NotificationCenter';
+import {splitVideoFromAudio} from '../split-video-from-audio-api';
import {deleteSequencesFromSource} from '../Timeline/delete-selected-timeline-item';
import {duplicateSequencesFromSource} from '../Timeline/duplicate-selected-timeline-item';
import {
@@ -27,8 +30,8 @@ import {
import {getSequenceFreezeFrameMenuItem} from '../Timeline/use-sequence-freeze-frame-menu-item';
import {AlignmentControls} from './AlignmentControls';
import {
- InspectorActionSection,
- InspectorInlineAction,
+ InspectorQuickActionsSection,
+ InspectorQuickAction,
InspectorMessage,
InspectorSectionDivider,
} from './common';
@@ -57,7 +60,7 @@ const largeActionIconStyle: React.CSSProperties = {
width: 20,
};
-const SplitSequenceAction: React.FC<{
+const SplitSequenceQuickAction: React.FC<{
readonly selection: Extract<TimelineSelection, {type: 'sequence'}>;
readonly track: TimelineTrackData;
}> = ({selection, track}) => {
@@ -104,7 +107,7 @@ const SplitSequenceAction: React.FC<{
: eligibility.reason;
return (
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={!canSplit}
onClick={onSplit}
title={disabledReason}
@@ -113,11 +116,11 @@ const SplitSequenceAction: React.FC<{
)}
>
Split clip
- </InspectorInlineAction>
+ </InspectorQuickAction>
);
};
-const SequenceSourceActions: React.FC<{
+const SequenceSourceQuickActions: React.FC<{
readonly selection: Extract<TimelineSelection, {type: 'sequence'}>;
readonly track: TimelineTrackData;
readonly validatedSource: string;
@@ -168,11 +171,37 @@ const SequenceSourceActions: React.FC<{
() => undefined,
);
}, [confirm, selection.nodePathInfo, sourceActionsDisabled]);
+ const splitVideoFromAudioDisabledReason = sourceActionsDisabled
+ ? 'Studio is read-only'
+ : selection.nodePathInfo.numberOfSequencesWithThisNodePath > 1
+ ? 'Programmatically duplicated sequences cannot be split from source'
+ : undefined;
+ const onSplitVideoFromAudio = useCallback(() => {
+ if (splitVideoFromAudioDisabledReason !== undefined) {
+ return;
+ }
+
+ const nodePath = selection.nodePathInfo.sequenceSubscriptionKey;
+ splitVideoFromAudio({
+ fileName: nodePath.absolutePath,
+ nodePath: nodePath.nodePath,
+ })
+ .then((result) => {
+ if (result.success) {
+ showNotification('Split video from audio', 2000);
+ } else {
+ showNotification(result.reason, 4000);
+ }
+ })
+ .catch((err) => {
+ showNotification((err as Error).message, 4000);
+ });
+ }, [selection.nodePathInfo, splitVideoFromAudioDisabledReason]);
return (
<>
{freezeFrameMenuItem?.type === 'item' ? (
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={Boolean(freezeFrameMenuItem.disabled)}
onClick={() =>
freezeFrameMenuItem.onClick(freezeFrameMenuItem.id, null)
@@ -182,9 +211,21 @@ const SequenceSourceActions: React.FC<{
)}
>
{freezeFrameMenuItem.label}
- </InspectorInlineAction>
+ </InspectorQuickAction>
) : null}
- <InspectorInlineAction
+ {track.sequence.type === 'video' ? (
+ <InspectorQuickAction
+ disabled={splitVideoFromAudioDisabledReason !== undefined}
+ onClick={onSplitVideoFromAudio}
+ title={splitVideoFromAudioDisabledReason}
+ renderIcon={(color) => (
+ <AudioIcon style={actionIconStyle} color={color} />
+ )}
+ >
+ Split video from audio
+ </InspectorQuickAction>
+ ) : null}
+ <InspectorQuickAction
disabled={sourceActionsDisabled}
onClick={onDuplicate}
renderIcon={(color) => (
@@ -192,8 +233,8 @@ const SequenceSourceActions: React.FC<{
)}
>
Duplicate
- </InspectorInlineAction>
- <InspectorInlineAction
+ </InspectorQuickAction>
+ <InspectorQuickAction
disabled={sourceActionsDisabled}
onClick={onDelete}
renderIcon={(color) => (
@@ -201,7 +242,7 @@ const SequenceSourceActions: React.FC<{
)}
>
Delete
- </InspectorInlineAction>
+ </InspectorQuickAction>
</>
);
};
@@ -300,14 +341,17 @@ const SequenceExpandedInspector: React.FC<{
keyframeDisplayOffset={track.keyframeDisplayOffset}
renderTransformControls={() => <AlignmentControls track={track} />}
/>
- <InspectorActionSection>
- <SplitSequenceAction selection={sequenceSelection} track={track} />
- <SequenceSourceActions
+ <InspectorQuickActionsSection>
+ <SplitSequenceQuickAction
+ selection={sequenceSelection}
+ track={track}
+ />
+ <SequenceSourceQuickActions
selection={sequenceSelection}
track={track}
validatedSource={validatedLocation.source}
/>
- </InspectorActionSection>
+ </InspectorQuickActionsSection>
</>
) : (
<InspectorMessage>Source controls unavailable</InspectorMessage>
diff --git a/packages/studio/src/components/InspectorPanel/common.tsx b/packages/studio/src/components/InspectorPanel/common.tsx
index 114c23e301..68f5b8b279 100644
--- a/packages/studio/src/components/InspectorPanel/common.tsx
+++ b/packages/studio/src/components/InspectorPanel/common.tsx
@@ -22,7 +22,7 @@ import {
detailLabel,
detailRow,
detailValue,
- inspectorActionSection,
+ inspectorQuickActionsSection,
inspectorSectionBody,
inspectorSectionDivider,
resolveLinkStyle,
@@ -37,12 +37,12 @@ export const InspectorSectionDivider: React.FC = () => (
<div style={inspectorSectionDivider} />
);
-export const InspectorActionSection: React.FC<{
+export const InspectorQuickActionsSection: React.FC<{
readonly children: React.ReactNode;
}> = ({children}) => (
<>
<InspectorSectionDivider />
- <div style={inspectorActionSection}>{children}</div>
+ <div style={inspectorQuickActionsSection}>{children}</div>
</>
);
@@ -87,15 +87,15 @@ export const InspectorBackAction: React.FC<{
readonly title: string;
}> = ({children, disabled, onClick, title}) => {
return (
- <div style={inspectorActionSection}>
- <InspectorInlineAction
+ <div style={inspectorQuickActionsSection}>
+ <InspectorQuickAction
disabled={disabled}
onClick={onClick}
renderIcon={(color) => <BackArrow color={color} />}
title={title}
>
{children}
- </InspectorInlineAction>
+ </InspectorQuickAction>
</div>
);
};
@@ -202,14 +202,14 @@ const segmentedTrailingAction: React.CSSProperties = {
width: 28,
};
-export type InspectorInlineActionSegment = {
+export type InspectorQuickActionSegment = {
readonly disabled: boolean;
readonly onClick: React.MouseEventHandler<HTMLButtonElement>;
readonly renderIcon: (color: string) => React.ReactNode;
readonly title?: string;
};
-export type InspectorInlineActionProps = {
+export type InspectorQuickActionProps = {
readonly children: React.ReactNode;
readonly disabled: boolean;
readonly iconContainerStyle?: React.CSSProperties;
@@ -222,11 +222,11 @@ export type InspectorInlineActionProps = {
| {readonly type: 'single'}
| {
readonly type: 'segmented';
- readonly trailing: InspectorInlineActionSegment;
+ readonly trailing: InspectorQuickActionSegment;
};
};
-export const InspectorInlineAction: React.FC<InspectorInlineActionProps> = ({
+export const InspectorQuickAction: React.FC<InspectorQuickActionProps> = ({
children,
disabled,
iconContainerStyle,
@@ -272,7 +272,7 @@ export const InspectorInlineAction: React.FC<InspectorInlineActionProps> = ({
);
const mainAction = onClick ? (
<button
- className={`__remotion-inspector-inline-action ${HOVERABLE_CLASS_NAME}`}
+ className={`__remotion-inspector-quick-action ${HOVERABLE_CLASS_NAME}`}
type="button"
disabled={disabled}
style={buttonStyle}
diff --git a/packages/studio/src/components/InspectorPanel/styles.ts b/packages/studio/src/components/InspectorPanel/styles.ts
index 0da017946b..404b55aa50 100644
--- a/packages/studio/src/components/InspectorPanel/styles.ts
+++ b/packages/studio/src/components/InspectorPanel/styles.ts
@@ -171,7 +171,7 @@ export const detailsWithInlineAction: React.CSSProperties = {
paddingBottom: INSPECTOR_PANEL_HORIZONTAL_PADDING,
};
-export const inspectorActionSection: React.CSSProperties = {
+export const inspectorQuickActionsSection: React.CSSProperties = {
padding: '4px 0',
};
diff --git a/packages/studio/src/components/InspectorSourceLocation.tsx b/packages/studio/src/components/InspectorSourceLocation.tsx
index 96245e35b7..685d679e85 100644
--- a/packages/studio/src/components/InspectorSourceLocation.tsx
+++ b/packages/studio/src/components/InspectorSourceLocation.tsx
@@ -2,7 +2,7 @@ import React, {useCallback, useMemo, useState} from 'react';
import type {OriginalPosition} from '../error-overlay/react-overlay/utils/get-source-map';
import {BACKGROUND, LIGHT_COLOR, LIGHT_TEXT} from '../helpers/colors';
import {formatFileLocation} from '../helpers/format-file-location';
-import {InspectorInlineAction} from './InspectorPanel/common';
+import {InspectorQuickAction} from './InspectorPanel/common';
import {getOriginalSourceAttribution} from './Timeline/TimelineStack/source-attribution';
const sourceLocationStyle: React.CSSProperties = {
@@ -46,7 +46,7 @@ export const InspectorSourceLocation: React.FC<{
readonly canOpen: boolean;
readonly onOpen: () => void;
readonly renderIcon?: (color: string) => React.ReactNode;
- readonly size?: 'default' | 'inline-action';
+ readonly size?: 'default' | 'quick-action';
}> = ({location, canOpen, onOpen, renderIcon, size = 'default'}) => {
const [hovered, setHovered] = useState(false);
@@ -98,9 +98,9 @@ export const InspectorSourceLocation: React.FC<{
return null;
}
- if (size === 'inline-action') {
+ if (size === 'quick-action') {
return (
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={!canOpen}
onClick={onClick}
renderIcon={(iconColor) => renderIcon?.(iconColor)}
@@ -108,7 +108,7 @@ export const InspectorSourceLocation: React.FC<{
title={fileLocation ?? undefined}
>
{label}
- </InspectorInlineAction>
+ </InspectorQuickAction>
);
}
diff --git a/packages/studio/src/components/LicenseKeyValidation.tsx b/packages/studio/src/components/LicenseKeyValidation.tsx
index 71db244512..c3b40efc0e 100644
--- a/packages/studio/src/components/LicenseKeyValidation.tsx
+++ b/packages/studio/src/components/LicenseKeyValidation.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import {FAIL_COLOR} from '../helpers/colors';
import {CheckCircleFilled} from '../icons/check-circle-filled';
-import {InspectorInlineAction} from './InspectorPanel/common';
+import {InspectorQuickAction} from './InspectorPanel/common';
const LICENSE_KEY_LENGTH = 55;
const LICENSE_KEY_PREFIX = 'rm_pub_';
@@ -140,7 +140,7 @@ export const LicenseKeyDetailsDisplay: React.FC<{
return (
<div>
- <InspectorInlineAction
+ <InspectorQuickAction
disabled={false}
onClick={() => window.open(usageUrl, '_blank', 'noopener,noreferrer')}
renderIcon={(color) => (
@@ -153,8 +153,8 @@ export const LicenseKeyDetailsDisplay: React.FC<{
<span style={actionText}>Belongs to {details.projectName}</span>
<span style={actionLabel}>View usage</span>
</span>
- </InspectorInlineAction>
- <InspectorInlineAction
+ </InspectorQuickAction>
+ <InspectorQuickAction
disabled={false}
onClick={() => window.open(projectUrl, '_blank', 'noopener,noreferrer')}
renderIcon={(color) =>
@@ -175,7 +175,7 @@ export const LicenseKeyDetailsDisplay: React.FC<{
</span>
<span style={actionLabel}>Manage</span>
</span>
- </InspectorInlineAction>
+ </InspectorQuickAction>
</div>
);
};
diff --git a/packages/studio/src/components/Timeline/TimelineAssetField.tsx b/packages/studio/src/components/Timeline/TimelineAssetField.tsx
index 9cdbbbb376..b6c6cc492b 100644
--- a/packages/studio/src/components/Timeline/TimelineAssetField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineAssetField.tsx
@@ -12,8 +12,8 @@ import {SetSelectedModalContext} from '../../state/modals';
import {pickFilesToImport} from '../import-assets';
import {InlineAction} from '../InlineAction';
import {
- InspectorInlineAction,
- type InspectorInlineActionProps,
+ InspectorQuickAction,
+ type InspectorQuickActionProps,
} from '../InspectorPanel/common';
import {showNotification} from '../Notifications/NotificationCenter';
import {useStaticFiles} from '../use-static-files';
@@ -24,7 +24,7 @@ const penIcon: React.CSSProperties = {
width: 14,
};
-export type InspectorSourceAction = Omit<InspectorInlineActionProps, 'variant'>;
+export type InspectorSourceAction = Omit<InspectorQuickActionProps, 'variant'>;
type AssetSelectionContextValue = {
readonly initialQuery: string;
@@ -166,7 +166,7 @@ export const TimelineAssetField: React.FC<TimelineAssetFieldProps> = ({
}
return (
- <InspectorInlineAction
+ <InspectorQuickAction
{...inlineSourceAction}
size="compact"
variant={{
diff --git a/packages/studio/src/components/split-video-from-audio-api.ts b/packages/studio/src/components/split-video-from-audio-api.ts
new file mode 100644
index 0000000000..48642dbb0c
--- /dev/null
+++ b/packages/studio/src/components/split-video-from-audio-api.ts
@@ -0,0 +1,15 @@
+import type {
+ SplitVideoFromAudioRequest,
+ SplitVideoFromAudioResponse,
+} from '@remotion/studio-shared';
+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
+import {callApi} from './call-api';
+
+export const splitVideoFromAudio = (
+ request: SplitVideoFromAudioRequest,
+): Promise<SplitVideoFromAudioResponse> => {
+ const browserStudioOperations = getBrowserStudioOperations();
+ return browserStudioOperations
+ ? browserStudioOperations.splitVideoFromAudio(request)
+ : callApi('/api/split-video-from-audio', request);
+};
diff --git a/packages/studio/src/helpers/inject-css.ts b/packages/studio/src/helpers/inject-css.ts
index 1442b9ab91..95490812d7 100644
--- a/packages/studio/src/helpers/inject-css.ts
+++ b/packages/studio/src/helpers/inject-css.ts
@@ -71,14 +71,14 @@ const makeDefaultGlobalCSS = () => {
}
.__remotion-composition-selector-item:focus,
- .__remotion-inspector-inline-action:focus,
+ .__remotion-inspector-quick-action:focus,
.__remotion-inspector-section-title:focus {
outline: none;
box-shadow: none;
}
.__remotion-composition-selector-item:focus-visible,
- .__remotion-inspector-inline-action:focus-visible,
+ .__remotion-inspector-quick-action:focus-visible,
.__remotion-inspector-section-title:focus-visible {
box-shadow: ${FOCUS_BOX_SHADOW};
}
diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.ts
index cc0fd10552..ac25a9c2d8 100644
--- a/packages/studio/src/test/make-browser-studio-operations.ts
+++ b/packages/studio/src/test/make-browser-studio-operations.ts
@@ -24,6 +24,7 @@ export const makeBrowserStudioOperations = (
redo: () => unusedOperation('redo'),
renameStaticFile: () => unusedOperation('renameStaticFile'),
saveSequenceProps: () => unusedOperation('saveSequenceProps'),
+ splitVideoFromAudio: () => unusedOperation('splitVideoFromAudio'),
subscribeToDefaultProps: () => unusedOperation('subscribeToDefaultProps'),
subscribeToEvent: () => unusedOperation('subscribeToEvent'),
subscribeToSequenceProps: () => unusedOperation('subscribeToSequenceProps'),