Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Open assets in Remotion Convert (#10695)

Jonny Burger77354de4c955
diff --git a/packages/convert/app/components/use-probe.ts b/packages/convert/app/components/use-probe.ts
index b5a8f6d59d..6871b275fe 100644
--- a/packages/convert/app/components/use-probe.ts
+++ b/packages/convert/app/components/use-probe.ts
@@ -157,11 +157,7 @@ export const useProbe = ({src}: {src: Source}) => {
}, [getStart]);
const fps =
- frameRate === undefined || frameRate === null
- ? frameRate
- : frameRate.type === 'constant'
- ? frameRate.rate
- : frameRate.max;
+ frameRate === undefined || frameRate === null ? frameRate : frameRate.rate;
return useMemo(() => {
return {
diff --git a/packages/convert/app/lib/get-video-frame-rate.ts b/packages/convert/app/lib/get-video-frame-rate.ts
index 3dc45e81de..4a128d9e31 100644
--- a/packages/convert/app/lib/get-video-frame-rate.ts
+++ b/packages/convert/app/lib/get-video-frame-rate.ts
@@ -1,4 +1,3 @@
-import {EncodedPacketSink} from 'mediabunny';
import type {Input} from 'mediabunny';
export type VideoFrameRate =
@@ -8,29 +7,9 @@ export type VideoFrameRate =
}
| {
type: 'variable';
- max: number;
- average: number;
+ rate: number;
};
-const commonFpsValues = [
- 24000 / 1001,
- 24,
- 25,
- 30000 / 1001,
- 30,
- 50,
- 60000 / 1001,
- 60,
- 120,
-];
-
-const snapToCommonFps = (fps: number) => {
- return (
- commonFpsValues.find((commonFps) => Math.abs(fps - commonFps) < 0.01) ??
- fps
- );
-};
-
export const getVideoFrameRate = async (
input: Input,
): Promise<VideoFrameRate | null> => {
@@ -39,54 +18,13 @@ export const getVideoFrameRate = async (
return null;
}
- const packetSampleCount = 121;
- const timestamps = new Set<number>();
- const sink = new EncodedPacketSink(videoTrack);
- let endTimestamp = -Infinity;
-
- for await (const packet of sink.packets(undefined, undefined, {
- metadataOnly: true,
- })) {
- if (
- timestamps.size >= packetSampleCount &&
- packet.timestamp >= endTimestamp
- ) {
- break;
- }
-
- timestamps.add(packet.timestamp);
- endTimestamp = Math.max(
- endTimestamp,
- packet.timestamp + packet.duration,
- );
- }
-
- if (timestamps.size < 2) {
+ const metrics = await videoTrack.computeFrameRateMetrics();
+ if (metrics.probedPacketCount < 2) {
return null;
}
- const sortedTimestamps = [...timestamps].sort((a, b) => a - b);
- sortedTimestamps.splice(packetSampleCount);
-
- const intervals = sortedTimestamps.slice(1).map((timestamp, index) => {
- return timestamp - sortedTimestamps[index];
- });
- const averageInterval =
- intervals.reduce((sum, interval) => sum + interval, 0) / intervals.length;
- const toleranceInSeconds = 1.01 / 1000;
- const intervalSpread = Math.max(...intervals) - Math.min(...intervals);
- const isConstant = intervalSpread <= toleranceInSeconds;
-
- if (isConstant) {
- return {
- type: 'constant',
- rate: snapToCommonFps(1 / averageInterval),
- };
- }
-
return {
- type: 'variable',
- max: 1 / Math.min(...intervals),
- average: 1 / averageInterval,
+ type: metrics.frameRateIsConstant ? 'constant' : 'variable',
+ rate: metrics.bestGuessFrameRate,
};
};
diff --git a/packages/convert/test/frame-rate.test.tsx b/packages/convert/test/frame-rate.test.tsx
index 19921c489f..c32799b94e 100644
--- a/packages/convert/test/frame-rate.test.tsx
+++ b/packages/convert/test/frame-rate.test.tsx
@@ -7,24 +7,27 @@ import {useProbe} from '../app/components/use-probe';
afterEach(cleanup);
const FrameRateProbe: React.FC<{file: File}> = ({file}) => {
- const {frameRate} = useProbe({
+ const {fps, frameRate} = useProbe({
src: {type: 'file', file},
});
return (
- <ContainerOverview
- dimensions={null}
- durationInSeconds={null}
- videoCodec={null}
- audioCodec={null}
- size={0}
- frameRate={frameRate}
- container={null}
- isHdr={false}
- metadata={null}
- isAudioOnly={false}
- sampleRate={null}
- />
+ <>
+ <ContainerOverview
+ dimensions={null}
+ durationInSeconds={null}
+ videoCodec={null}
+ audioCodec={null}
+ size={0}
+ frameRate={frameRate}
+ container={null}
+ isHdr={false}
+ metadata={null}
+ isAudioOnly={false}
+ sampleRate={null}
+ />
+ <div data-testid="timeline-fps">{fps}</div>
+ </>
);
};
@@ -39,11 +42,13 @@ test('probes constant and variable frame rates for the player and metadata', asy
);
const variable = render(<FrameRateProbe file={variableFile} />);
expect(await screen.findByText('Variable')).toBeTruthy();
+ expect((await screen.findByTestId('timeline-fps')).textContent).toBe('60');
variable.unmount();
const constantFile = await loadFixture('../example/public/framer.webm');
render(<FrameRateProbe file={constantFile} />);
expect(await screen.findByText('30.00 FPS')).toBeTruthy();
+ expect((await screen.findByTestId('timeline-fps')).textContent).toBe('30');
});
test('can unmount while probing a file', async () => {
diff --git a/packages/studio-server/src/preview-server/serve-static.ts b/packages/studio-server/src/preview-server/serve-static.ts
index c81f7ecf61..d3fe3c503d 100644
--- a/packages/studio-server/src/preview-server/serve-static.ts
+++ b/packages/studio-server/src/preview-server/serve-static.ts
@@ -12,19 +12,69 @@ import {RenderInternals} from '@remotion/renderer';
import {getValueContentRangeHeader} from './dev-middleware/middleware';
import {parseRange} from './dev-middleware/range-parser';
+const remotionConvertOrigins = [
+ 'https://remotion.dev',
+ 'https://www.remotion.dev',
+ 'https://convert.remotion.dev',
+];
+
+const applyRemotionConvertCorsHeaders = ({
+ req,
+ res,
+}: {
+ req: IncomingMessage;
+ res: ServerResponse;
+}) => {
+ const {origin} = req.headers;
+ if (!origin || !remotionConvertOrigins.includes(origin)) {
+ return false;
+ }
+
+ res.setHeader('Access-Control-Allow-Origin', origin);
+ res.setHeader(
+ 'Vary',
+ 'Origin, Access-Control-Request-Headers, Access-Control-Request-Private-Network',
+ );
+ res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Range, Content-Type');
+ res.setHeader(
+ 'Access-Control-Expose-Headers',
+ 'Accept-Ranges, Content-Length, Content-Range',
+ );
+ res.setHeader('Access-Control-Max-Age', '600');
+
+ if (req.headers['access-control-request-private-network']) {
+ res.setHeader('Access-Control-Allow-Private-Network', 'true');
+ }
+
+ return true;
+};
+
export const serveStatic = async function ({
root,
path,
req,
res,
allowOutsidePublicFolder,
+ allowRemotionConvertCors,
}: {
root: string;
path: string;
req: IncomingMessage;
res: ServerResponse;
allowOutsidePublicFolder: boolean;
+ allowRemotionConvertCors: boolean;
}): Promise<void> {
+ const remotionConvertCorsAllowed = allowRemotionConvertCors
+ ? applyRemotionConvertCorsHeaders({req, res})
+ : false;
+
+ if (req.method === 'OPTIONS' && remotionConvertCorsAllowed) {
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
// method not allowed
res.statusCode = 405;
@@ -58,6 +108,7 @@ export const serveStatic = async function ({
req,
res,
allowOutsidePublicFolder: true,
+ allowRemotionConvertCors,
});
}
diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.ts
index ed96c0b02e..671e84b28c 100644
--- a/packages/studio-server/src/routes.ts
+++ b/packages/studio-server/src/routes.ts
@@ -589,6 +589,7 @@ export const handleRoutes = ({
req: request,
res: response,
allowOutsidePublicFolder: false,
+ allowRemotionConvertCors: true,
});
}
@@ -609,6 +610,7 @@ export const handleRoutes = ({
req: request,
res: response,
allowOutsidePublicFolder: false,
+ allowRemotionConvertCors: false,
});
}
diff --git a/packages/studio-server/src/test/serve-static-cors.test.ts b/packages/studio-server/src/test/serve-static-cors.test.ts
new file mode 100644
index 0000000000..a008209ecb
--- /dev/null
+++ b/packages/studio-server/src/test/serve-static-cors.test.ts
@@ -0,0 +1,82 @@
+import {expect, test} from 'bun:test';
+import {mkdtempSync, rmSync, writeFileSync} from 'node:fs';
+import {createServer} from 'node:http';
+import {tmpdir} from 'node:os';
+import path from 'node:path';
+import {serveStatic} from '../preview-server/serve-static';
+
+test('allows Remotion Convert to read public assets only', async () => {
+ const directory = mkdtempSync(path.join(tmpdir(), 'remotion-convert-cors-'));
+ const asset = path.join(directory, 'video.mp4');
+ writeFileSync(asset, 'video');
+
+ const server = createServer((request, response) => {
+ serveStatic({
+ root: directory,
+ path: asset,
+ req: request,
+ res: response,
+ allowOutsidePublicFolder: false,
+ allowRemotionConvertCors: request.url === '/asset',
+ }).catch((error) => response.destroy(error));
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+
+ try {
+ const address = server.address();
+ if (address === null || typeof address === 'string') {
+ throw new Error('Expected an HTTP server address');
+ }
+
+ const origin = `http://127.0.0.1:${address.port}`;
+ const preflight = await fetch(`${origin}/asset`, {
+ method: 'OPTIONS',
+ headers: {
+ Origin: 'https://www.remotion.dev',
+ 'Access-Control-Request-Headers': 'range',
+ 'Access-Control-Request-Method': 'GET',
+ 'Access-Control-Request-Private-Network': 'true',
+ },
+ });
+ expect(preflight.status).toBe(204);
+ expect(preflight.headers.get('access-control-allow-origin')).toBe(
+ 'https://www.remotion.dev',
+ );
+ expect(preflight.headers.get('access-control-allow-private-network')).toBe(
+ 'true',
+ );
+
+ const assetResponse = await fetch(`${origin}/asset`, {
+ headers: {
+ Origin: 'https://www.remotion.dev',
+ Range: 'bytes=0-1',
+ },
+ });
+ expect(assetResponse.status).toBe(206);
+ expect(await assetResponse.text()).toBe('vi');
+ expect(assetResponse.headers.get('access-control-allow-origin')).toBe(
+ 'https://www.remotion.dev',
+ );
+
+ const outputResponse = await fetch(`${origin}/output`, {
+ headers: {Origin: 'https://www.remotion.dev'},
+ });
+ expect(outputResponse.status).toBe(200);
+ expect(
+ outputResponse.headers.get('access-control-allow-origin'),
+ ).toBeNull();
+
+ const unrelatedOriginResponse = await fetch(`${origin}/asset`, {
+ headers: {Origin: 'https://example.com'},
+ });
+ expect(unrelatedOriginResponse.status).toBe(200);
+ expect(
+ unrelatedOriginResponse.headers.get('access-control-allow-origin'),
+ ).toBeNull();
+ } finally {
+ await new Promise<void>((resolve, reject) => {
+ server.close((error) => (error ? reject(error) : resolve()));
+ });
+ rmSync(directory, {recursive: true});
+ }
+});
diff --git a/packages/studio/src/components/AssetSelectorItem.tsx b/packages/studio/src/components/AssetSelectorItem.tsx
index de3af0cf7b..5a6d0b552a 100644
--- a/packages/studio/src/components/AssetSelectorItem.tsx
+++ b/packages/studio/src/components/AssetSelectorItem.tsx
@@ -9,7 +9,6 @@ import React, {
} from 'react';
import {Internals, staticFile, type StaticFile} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
-import {deleteStaticFile} from '../api/delete-static-file';
import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {
@@ -24,6 +23,7 @@ import {copyText} from '../helpers/copy-text';
import type {AssetFolder, AssetStructure} from '../helpers/create-folder-tree';
import {getFileManagerName} from '../helpers/get-file-manager-name';
import {getPreviewFileType} from '../helpers/get-preview-file-type';
+import {openInRemotionConvert} from '../helpers/open-in-remotion-convert';
import {
markAssetSidebarScrollFromRowClick,
maybeScrollAssetSidebarRowIntoView,
@@ -38,17 +38,16 @@ import {ClipboardIcon} from '../icons/clipboard';
import {CollapsedFolderIcon, ExpandedFolderIcon} from '../icons/folder';
import {SetSelectedModalContext} from '../state/modals';
import {AssetFileIcon} from './AssetFileIcon';
-import {useConfirmationDialog} from './ConfirmationDialog';
import {ContextMenu} from './ContextMenu';
import {getAssetElementFromPath} from './import-assets';
import type {RenderInlineAction} from './InlineAction';
import {InlineAction} from './InlineAction';
import {COMPACT_CONTROL_ROW_HEIGHT, Row, Spacing} from './layout';
-import {inlineCodeSnippet} from './Menu/styles';
import type {ComboboxValue} from './NewComposition/ComboBox';
import {showNotification} from './Notifications/NotificationCenter';
import {getOpenInNewWindowMenuItem} from './open-in-new-window';
import {openInFileExplorer} from './RenderQueue/actions';
+import {useDeleteAsset} from './use-delete-asset';
const iconStyle: React.CSSProperties = {
width: 18,
@@ -130,6 +129,7 @@ export const getAssetContextMenuItems = ({
fileManagerName,
copyFileName,
copyStaticFilePath,
+ openAssetInConvert,
openAssetInExplorer,
renameAsset,
deleteAsset,
@@ -141,6 +141,7 @@ export const getAssetContextMenuItems = ({
fileManagerName: string;
copyFileName: () => void;
copyStaticFilePath: () => void;
+ openAssetInConvert: () => void;
openAssetInExplorer: () => void;
renameAsset: () => void;
deleteAsset: () => void;
@@ -148,8 +149,24 @@ export const getAssetContextMenuItems = ({
fileExplorerDisabled: boolean;
mutationsDisabled: boolean;
}): ComboboxValue[] => {
+ const previewFileType = getPreviewFileType(relativePath);
+ const canOpenInConvert =
+ previewFileType === 'audio' || previewFileType === 'video';
const items: (ComboboxValue | null)[] = [
getOpenInNewWindowMenuItem(`/assets/${relativePath}`),
+ canOpenInConvert
+ ? {
+ id: 'open-asset-in-convert',
+ keyHint: null,
+ label: 'Open in Remotion Convert',
+ leftItem: null,
+ onClick: openAssetInConvert,
+ quickSwitcherLabel: 'Open asset in Remotion Convert',
+ subMenu: null,
+ type: 'item',
+ value: 'open-asset-in-convert',
+ }
+ : null,
{
type: 'divider',
id: 'open-in-new-window-divider',
@@ -418,7 +435,6 @@ const AssetSelectorItem: React.FC<{
const [hovered, setHovered] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const {setSelectedModal} = useContext(SetSelectedModalContext);
- const confirm = useConfirmationDialog();
const connectionStatus = useContext(StudioServerConnectionCtx)
.previewServerState.type;
const onPointerEnter = useCallback(() => {
@@ -559,6 +575,10 @@ const AssetSelectorItem: React.FC<{
});
}, [relativePath]);
+ const openAssetInConvert = useCallback(() => {
+ openInRemotionConvert({relativePath});
+ }, [relativePath]);
+
const openAssetInExplorer = useCallback(() => {
if (!window.remotion_publicFolderExists) {
showNotification('Could not find the public folder', 2000);
@@ -580,46 +600,7 @@ const AssetSelectorItem: React.FC<{
publicFolderExists: window.remotion_publicFolderExists,
});
- const deleteAsset = useCallback(() => {
- confirm({
- title: 'Delete asset',
- message: (
- <>
- Do you want to delete the asset{' '}
- <code style={inlineCodeSnippet}>{relativePath}</code> from your public
- folder?
- </>
- ),
- confirmLabel: 'Delete',
- })
- .then((confirmed) => {
- if (!confirmed) {
- return;
- }
-
- const notification = showNotification(
- `Deleting ${relativePath}...`,
- null,
- );
-
- deleteStaticFile(relativePath)
- .then(() => {
- notification.replaceContent(`Deleted ${relativePath}`, 2000);
- })
- .catch((err) => {
- notification.replaceContent(
- `Could not delete ${relativePath}: ${(err as Error).message}`,
- 3000,
- );
- });
- })
- .catch((err) => {
- showNotification(
- `Could not delete ${relativePath}: ${(err as Error).message}`,
- 3000,
- );
- });
- }, [confirm, relativePath]);
+ const deleteAsset = useDeleteAsset(relativePath);
const renameAsset = useCallback(() => {
setSelectedModal({
@@ -634,6 +615,7 @@ const AssetSelectorItem: React.FC<{
fileManagerName,
copyFileName,
copyStaticFilePath,
+ openAssetInConvert,
openAssetInExplorer,
renameAsset,
deleteAsset,
@@ -648,6 +630,7 @@ const AssetSelectorItem: React.FC<{
fileExplorerDisabled,
fileManagerName,
mutationsDisabled,
+ openAssetInConvert,
openAssetInExplorer,
renameAsset,
relativePath,
diff --git a/packages/studio/src/components/CurrentAsset.tsx b/packages/studio/src/components/CurrentAsset.tsx
index 597ba82629..91707207e0 100644
--- a/packages/studio/src/components/CurrentAsset.tsx
+++ b/packages/studio/src/components/CurrentAsset.tsx
@@ -3,8 +3,11 @@ import React, {useCallback, useContext, useMemo} from 'react';
import {Internals, staticFile} from 'remotion';
import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
import {StudioServerConnectionCtx} from '../helpers/client-id';
+import {CURRENT_COLOR, LIGHT_TEXT} from '../helpers/colors';
import {formatMediaDuration} from '../helpers/format-media-duration';
+import {getFileManagerName} from '../helpers/get-file-manager-name';
import {getPreviewFileType} from '../helpers/get-preview-file-type';
+import {openInRemotionConvert} from '../helpers/open-in-remotion-convert';
import {
renderHumanReadableAudioCodec,
renderHumanReadableVideoCodec,
@@ -12,20 +15,65 @@ import {
import {useImageMetadata} from '../helpers/use-image-metadata';
import type {MediaMetadata} from '../helpers/use-media-metadata';
import {useMediaMetadata} from '../helpers/use-media-metadata';
+import {ExpandedFolderIcon} from '../icons/folder';
+import {RemotionConvertIcon} from '../icons/remotion-convert';
+import {TrashIcon} from '../icons/trash';
import {InlineEditableTitle} from './InlineEditableTitle';
import {
- INSPECTOR_INFO_HEADER_MIN_HEIGHT,
InspectorInfoHeader,
InspectorInfoSubtitle,
} from './InspectorInfoHeader';
+import {
+ InspectorDetailRow,
+ InspectorQuickActionsSection,
+ InspectorQuickAction,
+ InspectorSection,
+} from './InspectorPanel/common';
import {INSPECTOR_PANEL_HORIZONTAL_PADDING} from './InspectorPanelLayout';
+import {COMPACT_INLINE_ROW_HEIGHT} from './layout';
import {
getStaticFileRenameSelection,
useRenameStaticFile,
} from './NewComposition/use-rename-static-file';
+import {showNotification} from './Notifications/NotificationCenter';
+import {openInFileExplorer} from './RenderQueue/actions';
+import {useDeleteAsset} from './use-delete-asset';
import {useStaticFiles} from './use-static-files';
-export const CURRENT_ASSET_HEIGHT = INSPECTOR_INFO_HEADER_MIN_HEIGHT;
+export const CURRENT_ASSET_HEIGHT = COMPACT_INLINE_ROW_HEIGHT + 8;
+
+const quickActionIconStyle: React.CSSProperties = {
+ display: 'block',
+ height: 18,
+ width: 18,
+};
+
+const convertArrowStyle: React.CSSProperties = {
+ display: 'inline-block',
+ height: 12,
+ marginLeft: 4,
+ verticalAlign: -2,
+ width: 12,
+};
+
+const assetMetadataStyle: React.CSSProperties = {
+ padding: `0 ${INSPECTOR_PANEL_HORIZONTAL_PADDING}px`,
+};
+
+const assetMetadataValueStyle: React.CSSProperties = {
+ color: LIGHT_TEXT,
+ fontFamily: 'sans-serif',
+ fontSize: 13,
+ lineHeight: '20px',
+};
+
+const assetEmptyStateStyle: React.CSSProperties = {
+ color: LIGHT_TEXT,
+ fontFamily: 'sans-serif',
+ fontSize: 12,
+ lineHeight: 1.4,
+ padding: `0 ${INSPECTOR_PANEL_HORIZONTAL_PADDING}px`,
+};
export const getCurrentAssetMetadataSource = (assetName: string | null) => {
if (!assetName) {
@@ -52,42 +100,80 @@ export const getCurrentAssetImageMetadataSource = (
const formatFps = (fps: number) => `${fps.toFixed(2)} FPS`;
-export const getCurrentAssetMediaDetailLines = (
- mediaMetadata: MediaMetadata,
-) => {
- const detailLines: string[] = [];
+type CurrentAssetDetail = {
+ readonly label: string;
+ readonly value: string;
+};
- if (mediaMetadata.hasVideoTrack === true) {
- const videoParts = [
- renderHumanReadableVideoCodec(mediaMetadata.videoCodec),
- ];
+export const getCurrentAssetMediaSections = (mediaMetadata: MediaMetadata) => {
+ const hasVideo =
+ mediaMetadata.hasVideoTrack === true ||
+ mediaMetadata.width !== null ||
+ mediaMetadata.height !== null ||
+ mediaMetadata.videoCodec !== null ||
+ mediaMetadata.fps !== null ||
+ mediaMetadata.isHdr !== null;
+ const hasAudio =
+ mediaMetadata.hasAudioTrack === true ||
+ mediaMetadata.audioCodec !== null ||
+ mediaMetadata.sampleRate !== null;
+ const video: CurrentAssetDetail[] = [];
+ const audio: CurrentAssetDetail[] = [];
+
+ if (hasVideo) {
+ if (mediaMetadata.width !== null && mediaMetadata.height !== null) {
+ video.push({
+ label: 'Dimensions',
+ value: `${mediaMetadata.width} × ${mediaMetadata.height}`,
+ });
+ }
if (mediaMetadata.fps !== null) {
- videoParts.push(formatFps(mediaMetadata.fps));
+ video.push({label: 'Frame rate', value: formatFps(mediaMetadata.fps)});
}
+ video.push({
+ label: 'Duration',
+ value: formatMediaDuration(mediaMetadata.duration),
+ });
+ video.push({
+ label: 'Codec',
+ value: renderHumanReadableVideoCodec(mediaMetadata.videoCodec),
+ });
+
if (mediaMetadata.isHdr !== null) {
- videoParts.push(`HDR: ${mediaMetadata.isHdr ? 'Yes' : 'No'}`);
+ video.push({
+ label: 'HDR',
+ value: mediaMetadata.isHdr ? 'Yes' : 'No',
+ });
}
-
- detailLines.push(`Video: ${videoParts.join(' · ')}`);
}
- if (mediaMetadata.hasAudioTrack === true) {
- const audioParts = [
- renderHumanReadableAudioCodec(mediaMetadata.audioCodec),
- ];
+ if (hasAudio) {
+ audio.push({
+ label: 'Duration',
+ value: formatMediaDuration(mediaMetadata.duration),
+ });
+ audio.push({
+ label: 'Codec',
+ value: renderHumanReadableAudioCodec(mediaMetadata.audioCodec),
+ });
if (mediaMetadata.sampleRate !== null) {
- audioParts.push(`${mediaMetadata.sampleRate} Hz`);
+ audio.push({
+ label: 'Sample rate',
+ value: `${mediaMetadata.sampleRate} Hz`,
+ });
}
-
- detailLines.push(`Audio: ${audioParts.join(' · ')}`);
- } else if (mediaMetadata.hasAudioTrack === false) {
- detailLines.push('Audio: No audio');
}
- return detailLines;
+ return {
+ audio:
+ hasAudio || (hasVideo && mediaMetadata.hasAudioTrack === false)
+ ? audio
+ : null,
+ video: hasVideo ? video : null,
+ };
};
export const AssetInfo: React.FC<{
@@ -98,6 +184,7 @@ export const AssetInfo: React.FC<{
}> = ({assetName, contentSized = false, onAssetClick, readOnlyStudio}) => {
const connectionStatus = useContext(StudioServerConnectionCtx)
.previewServerState.type;
+ const browserStudioOperations = getBrowserStudioOperations();
const staticFiles = useStaticFiles();
const renameFile = useRenameStaticFile({
@@ -120,7 +207,7 @@ export const AssetInfo: React.FC<{
const imageMetadata = useImageMetadata(imageSrc);
const canRename =
onAssetClick === undefined &&
- (getBrowserStudioOperations() !== null ||
+ (browserStudioOperations !== null ||
(connectionStatus === 'connected' && !readOnlyStudio));
const onRename = useCallback(
(newName: string) => {
@@ -128,72 +215,173 @@ export const AssetInfo: React.FC<{
},
[renameFile],
);
+ const onOpenConvert = useCallback(() => {
+ if (assetName === null) {
+ return;
+ }
+
+ openInRemotionConvert({relativePath: assetName});
+ }, [assetName]);
+ const onShowInFileManager = useCallback(() => {
+ if (assetName === null || !window.remotion_publicFolderExists) {
+ showNotification('Could not find the public folder', 2000);
+ return;
+ }
+
+ openInFileExplorer({
+ directory: window.remotion_publicFolderExists + '/' + assetName,
+ }).catch((err) => {
+ showNotification(`Could not open file: ${err.message}`, 2000);
+ });
+ }, [assetName]);
+ const onDelete = useDeleteAsset(assetName);
if (!assetName) {
- return <InspectorInfoHeader contentSized={contentSized} />;
+ return (
+ <InspectorInfoHeader
+ contentSized={contentSized}
+ minHeight={CURRENT_ASSET_HEIGHT}
+ />
+ );
}
const fileName = assetName.split('/').pop() ?? assetName;
-
- const subtitleParts: string[] = [];
- if (sizeInBytes !== null) {
- subtitleParts.push(formatBytes(sizeInBytes));
+ const fileDetails: CurrentAssetDetail[] = [];
+ const container = mediaMetadata?.format ?? imageMetadata?.format ?? null;
+ if (container !== null) {
+ fileDetails.push({label: 'Container', value: container});
}
- if (mediaMetadata) {
- if (mediaMetadata.format) {
- subtitleParts.push(mediaMetadata.format);
- }
-
- if (mediaMetadata.width !== null && mediaMetadata.height !== null) {
- subtitleParts.push(`${mediaMetadata.width}x${mediaMetadata.height}`);
- }
- } else if (imageMetadata) {
- subtitleParts.push(imageMetadata.format);
- subtitleParts.push(`${imageMetadata.width}x${imageMetadata.height}`);
+ if (sizeInBytes !== null) {
+ fileDetails.push({label: 'Size', value: formatBytes(sizeInBytes)});
}
- const mediaDetailLines = mediaMetadata
- ? getCurrentAssetMediaDetailLines(mediaMetadata)
- : [];
+ const mediaSections = mediaMetadata
+ ? getCurrentAssetMediaSections(mediaMetadata)
+ : null;
+ const fileManagerAvailable = browserStudioOperations === null;
+ const fileManagerDisabled =
+ window.remotion_publicFolderExists === null ||
+ readOnlyStudio ||
+ connectionStatus !== 'connected';
+ const fileManagerName = getFileManagerName(
+ window.remotion_fileSystemPlatform,
+ );
+ const mutationsDisabled =
+ browserStudioOperations === null &&
+ (readOnlyStudio || connectionStatus !== 'connected');
return (
- <InspectorInfoHeader
- contentSized={contentSized}
- padding={
- contentSized ? `0 ${INSPECTOR_PANEL_HORIZONTAL_PADDING}px 6px` : '4px 0'
- }
- >
- <InlineEditableTitle
- value={fileName}
- canRename={canRename}
- getInitialSelection={getStaticFileRenameSelection}
- onClick={onAssetClick}
- onCommit={onRename}
- size={contentSized ? 'default' : 'inspector'}
- title={assetName}
- />
- {subtitleParts.length > 0 ? (
- <InspectorInfoSubtitle size={contentSized ? 'default' : 'inspector'}>
- {subtitleParts.join(' · ')}
- </InspectorInfoSubtitle>
+ <>
+ <InspectorInfoHeader
+ contentSized={contentSized}
+ minHeight={CURRENT_ASSET_HEIGHT}
+ padding={
+ contentSized
+ ? `0 ${INSPECTOR_PANEL_HORIZONTAL_PADDING}px 6px`
+ : '4px 0'
+ }
+ >
+ <InlineEditableTitle
+ value={fileName}
+ canRename={canRename}
+ getInitialSelection={getStaticFileRenameSelection}
+ onClick={onAssetClick}
+ onCommit={onRename}
+ size={contentSized ? 'default' : 'inspector'}
+ title={assetName}
+ />
+ {imageMetadata ? (
+ <InspectorInfoSubtitle size={contentSized ? 'default' : 'inspector'}>
+ {imageMetadata.width} × {imageMetadata.height}
+ </InspectorInfoSubtitle>
+ ) : null}
+ </InspectorInfoHeader>
+ {fileDetails.length > 0 ? (
+ <InspectorSection header="File">
+ <div style={assetMetadataStyle}>
+ {fileDetails.map((detail) => (
+ <InspectorDetailRow key={detail.label} label={detail.label}>
+ <span style={assetMetadataValueStyle}>{detail.value}</span>
+ </InspectorDetailRow>
+ ))}
+ </div>
+ </InspectorSection>
+ ) : null}
+ {mediaSections && mediaSections.video ? (
+ <InspectorSection header="Video">
+ <div style={assetMetadataStyle}>
+ {mediaSections.video.map((detail) => (
+ <InspectorDetailRow key={detail.label} label={detail.label}>
+ <span style={assetMetadataValueStyle}>{detail.value}</span>
+ </InspectorDetailRow>
+ ))}
+ </div>
+ </InspectorSection>
) : null}
- {mediaMetadata ? (
- <InspectorInfoSubtitle size={contentSized ? 'default' : 'inspector'}>
- {formatMediaDuration(mediaMetadata.duration)}
- </InspectorInfoSubtitle>
+ {mediaSections && mediaSections.audio !== null ? (
+ <InspectorSection header="Audio">
+ {mediaSections.audio.length === 0 ? (
+ <div style={assetEmptyStateStyle}>None</div>
+ ) : (
+ <div style={assetMetadataStyle}>
+ {mediaSections.audio.map((detail) => (
+ <InspectorDetailRow key={detail.label} label={detail.label}>
+ <span style={assetMetadataValueStyle}>{detail.value}</span>
+ </InspectorDetailRow>
+ ))}
+ </div>
+ )}
+ </InspectorSection>
) : null}
- {mediaDetailLines.map((line) => {
- return (
- <InspectorInfoSubtitle
- key={line}
- size={contentSized ? 'default' : 'inspector'}
+ <InspectorQuickActionsSection>
+ {src ? (
+ <InspectorQuickAction
+ disabled={false}
+ onClick={onOpenConvert}
+ renderIcon={(color) => (
+ <RemotionConvertIcon color={color} style={quickActionIconStyle} />
+ )}
>
- {line}
- </InspectorInfoSubtitle>
- );
- })}
- </InspectorInfoHeader>
+ Convert
+ <svg
+ aria-hidden="true"
+ viewBox="0 0 16 16"
+ style={convertArrowStyle}
+ >
+ <path
+ d="M4 12 12 4M6 4h6v6"
+ fill="none"
+ stroke={CURRENT_COLOR}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ </svg>
+ </InspectorQuickAction>
+ ) : null}
+ {fileManagerAvailable ? (
+ <InspectorQuickAction
+ disabled={fileManagerDisabled}
+ onClick={onShowInFileManager}
+ renderIcon={(color) => (
+ <ExpandedFolderIcon color={color} style={quickActionIconStyle} />
+ )}
+ >
+ Show in {fileManagerName}
+ </InspectorQuickAction>
+ ) : null}
+ <InspectorQuickAction
+ disabled={mutationsDisabled}
+ onClick={onDelete}
+ renderIcon={(color) => (
+ <TrashIcon color={color} style={quickActionIconStyle} />
+ )}
+ >
+ Delete
+ </InspectorQuickAction>
+ </InspectorQuickActionsSection>
+ </>
);
};
diff --git a/packages/studio/src/components/use-delete-asset.tsx b/packages/studio/src/components/use-delete-asset.tsx
new file mode 100644
index 0000000000..0b97b9bb09
--- /dev/null
+++ b/packages/studio/src/components/use-delete-asset.tsx
@@ -0,0 +1,54 @@
+import {useCallback} from 'react';
+import {deleteStaticFile} from '../api/delete-static-file';
+import {useConfirmationDialog} from './ConfirmationDialog';
+import {inlineCodeSnippet} from './Menu/styles';
+import {showNotification} from './Notifications/NotificationCenter';
+
+export const useDeleteAsset = (relativePath: string | null) => {
+ const confirm = useConfirmationDialog();
+
+ return useCallback(() => {
+ if (relativePath === null) {
+ return;
+ }
+
+ confirm({
+ title: 'Delete asset',
+ message: (
+ <>
+ Do you want to delete the asset{' '}
+ <code style={inlineCodeSnippet}>{relativePath}</code> from your public
+ folder?
+ </>
+ ),
+ confirmLabel: 'Delete',
+ })
+ .then((confirmed) => {
+ if (!confirmed) {
+ return;
+ }
+
+ const notification = showNotification(
+ `Deleting ${relativePath}...`,
+ null,
+ );
+
+ deleteStaticFile(relativePath)
+ .then(() => {
+ notification.replaceContent(`Deleted ${relativePath}`, 2000);
+ })
+ .catch((err) => {
+ notification.replaceContent(
+ `Could not delete ${relativePath}: ${(err as Error).message}`,
+ 3000,
+ );
+ });
+ })
+ .catch((err) => {
+ showNotification(
+ `Could not delete ${relativePath}: ${(err as Error).message}`,
+ 3000,
+ );
+ });
+ }, [confirm, relativePath]);
+};
diff --git a/packages/studio/src/helpers/open-in-remotion-convert.ts b/packages/studio/src/helpers/open-in-remotion-convert.ts
new file mode 100644
index 0000000000..9bac11287b
--- /dev/null
+++ b/packages/studio/src/helpers/open-in-remotion-convert.ts
@@ -0,0 +1,29 @@
+import {staticFile} from 'remotion';
+
+export const getRemotionConvertUrl = ({
+ relativePath,
+ studioOrigin,
+}: {
+ relativePath: string;
+ studioOrigin: string;
+}) => {
+ const convertUrl = new URL('https://www.remotion.dev/convert');
+ const assetUrl = new URL(staticFile(relativePath), studioOrigin);
+ convertUrl.searchParams.set('url', assetUrl.toString());
+ return convertUrl.toString();
+};
+
+export const openInRemotionConvert = ({
+ relativePath,
+}: {
+ relativePath: string;
+}) => {
+ window.open(
+ getRemotionConvertUrl({
+ relativePath,
+ studioOrigin: window.location.origin,
+ }),
+ '_blank',
+ 'noopener,noreferrer',
+ );
+};
diff --git a/packages/studio/src/helpers/use-media-metadata.ts b/packages/studio/src/helpers/use-media-metadata.ts
index b2a442354c..8b248882cb 100644
--- a/packages/studio/src/helpers/use-media-metadata.ts
+++ b/packages/studio/src/helpers/use-media-metadata.ts
@@ -1,5 +1,9 @@
import {getVideoMetadata} from '@remotion/media-utils';
-import type {InputAudioTrack, InputVideoTrack} from 'mediabunny';
+import type {
+ FrameRateMetrics,
+ InputAudioTrack,
+ InputVideoTrack,
+} from 'mediabunny';
import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
import {useEffect, useState} from 'react';
import {Internals} from 'remotion';
@@ -22,6 +26,19 @@ export type MediaMetadata = {
const cache = new Map<string, MediaMetadata>();
const pendingRequests = new Map<string, Promise<MediaMetadata | null>>();
+export const getFrameRateFromMetrics = (
+ metrics: Pick<
+ FrameRateMetrics,
+ 'bestGuessFrameRate' | 'probedPacketCount'
+ > | null,
+) => {
+ if (metrics === null || metrics.probedPacketCount < 2) {
+ return null;
+ }
+
+ return metrics.bestGuessFrameRate;
+};
+
export const getCachedMediaMetadata = (src: string) => {
return cache.get(src) ?? null;
};
@@ -89,7 +106,7 @@ const getMediabunnyMetadata = async (
width,
height,
videoCodec,
- packetStats,
+ frameRateMetrics,
isHdr,
audioCodec,
sampleRate,
@@ -97,7 +114,7 @@ const getMediabunnyMetadata = async (
videoTrack ? safeCall(() => videoTrack.getDisplayWidth()) : null,
videoTrack ? safeCall(() => videoTrack.getDisplayHeight()) : null,
videoTrack ? safeCall(() => videoTrack.getCodec()) : null,
- videoTrack ? safeCall(() => videoTrack.computePacketStats(50)) : null,
+ videoTrack ? safeCall(() => videoTrack.computeFrameRateMetrics()) : null,
videoTrack ? safeCall(() => videoTrack.hasHighDynamicRange()) : null,
audioTrack ? safeCall(() => audioTrack.getCodec()) : null,
audioTrack ? safeCall(() => audioTrack.getSampleRate()) : null,
@@ -110,7 +127,7 @@ const getMediabunnyMetadata = async (
height,
videoCodec,
audioCodec,
- fps: packetStats?.averagePacketRate ?? null,
+ fps: getFrameRateFromMetrics(frameRateMetrics),
isHdr,
sampleRate,
hasVideoTrack: Boolean(videoTrack),
diff --git a/packages/studio/src/icons/remotion-convert.tsx b/packages/studio/src/icons/remotion-convert.tsx
new file mode 100644
index 0000000000..5f991b9712
--- /dev/null
+++ b/packages/studio/src/icons/remotion-convert.tsx
@@ -0,0 +1,16 @@
+import type {SVGProps} from 'react';
+
+// Font Awesome Pro v7.3.1, Copyright 2026 Fonticons, Inc.
+// https://fontawesome.com/license (Commercial License)
+export const RemotionConvertIcon: React.FC<
+ SVGProps<SVGSVGElement> & {readonly color: string}
+> = ({color, ...props}) => {
+ return (
+ <svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
+ <path
+ fill={color}
+ d="M427.3 36.7c-6.2-6.2-16.4-6.2-22.6 0s-6.2 16.4 0 22.6l52.7 52.7-97.4 0c-30.2 0-58.7 14.2-76.8 38.4l-29.2 38.9 20 26.7 34.8-46.4C320.9 153.5 339.9 144 360 144l97.4 0-52.7 52.7c-6.2 6.2-6.2 16.4 0 22.6s16.4 6.2 22.6 0l80-80c6.2-6.2 6.2-16.4 0-22.6l-80-80zM139.2 342.4C127.1 358.5 108.1 368 88 368l-72 0c-8.8 0-16 7.2-16 16s7.2 16 16 16l72 0c30.2 0 58.7-14.2 76.8-38.4l29.2-38.9-20-26.7-34.8 46.4zM404.7 475.3c6.2 6.2 16.4 6.2 22.6 0l80-80c6.2-6.2 6.2-16.4 0-22.6l-80-80c-6.2-6.2-16.4-6.2-22.6 0s-6.2 16.4 0 22.6l52.7 52.7-93.4 0c-22.7 0-44-10.7-57.6-28.8L167.2 153.6C147.6 127.4 116.7 112 84 112l-68 0c-8.8 0-16 7.2-16 16s7.2 16 16 16l68 0c22.7 0 44 10.7 57.6 28.8L280.8 358.4C300.4 384.6 331.3 400 364 400l93.4 0-52.7 52.7c-6.2 6.2-6.2 16.4 0 22.6z"
+ />
+ </svg>
+ );
+};
diff --git a/packages/studio/src/test/asset-context-menu.test.ts b/packages/studio/src/test/asset-context-menu.test.ts
index f325bd82f6..7caf72d770 100644
--- a/packages/studio/src/test/asset-context-menu.test.ts
+++ b/packages/studio/src/test/asset-context-menu.test.ts
@@ -31,6 +31,7 @@ test('keeps copy and open-in-new-window asset actions enabled in read-only Studi
fileManagerName: 'Finder',
copyFileName: noop,
copyStaticFilePath: noop,
+ openAssetInConvert: noop,
openAssetInExplorer: noop,
renameAsset: noop,
deleteAsset: noop,
@@ -39,6 +40,7 @@ test('keeps copy and open-in-new-window asset actions enabled in read-only Studi
});
expect(getItem(items, 'open-in-new-window').disabled).not.toBe(true);
+ expect(getItem(items, 'open-asset-in-convert').disabled).not.toBe(true);
expect(getItem(items, 'copy-asset-file-name').disabled).not.toBe(true);
expect(getItem(items, 'copy-asset-static-file-path').disabled).not.toBe(true);
expect(getItem(items, 'open-asset-in-explorer').disabled).toBe(true);
@@ -52,6 +54,7 @@ test('hides file-manager asset actions in Browser Studio', () => {
fileManagerName: 'Finder',
copyFileName: noop,
copyStaticFilePath: noop,
+ openAssetInConvert: noop,
openAssetInExplorer: noop,
renameAsset: noop,
deleteAsset: noop,
@@ -65,6 +68,29 @@ test('hides file-manager asset actions in Browser Studio', () => {
);
});
+test('only offers Remotion Convert for audio and video assets', () => {
+ const getItems = (relativePath: string) =>
+ getAssetContextMenuItems({
+ relativePath,
+ fileManagerName: 'Finder',
+ copyFileName: noop,
+ copyStaticFilePath: noop,
+ openAssetInConvert: noop,
+ openAssetInExplorer: noop,
+ renameAsset: noop,
+ deleteAsset: noop,
+ fileExplorerAvailable: true,
+ fileExplorerDisabled: false,
+ mutationsDisabled: false,
+ });
+
+ expect(getItem(getItems('video.mp4'), 'open-asset-in-convert')).toBeDefined();
+ expect(getItem(getItems('audio.wav'), 'open-asset-in-convert')).toBeDefined();
+ expect(
+ getItems('image.png').find((item) => item.id === 'open-asset-in-convert'),
+ ).toBeUndefined();
+});
+
test('only offers file-manager actions when a local public folder is available', () => {
const availability = getAssetActionAvailability({
browserStudioCanMutateAssets: null,
diff --git a/packages/studio/src/test/current-asset.test.ts b/packages/studio/src/test/current-asset.test.ts
index 17f9de79f6..db3d5b27be 100644
--- a/packages/studio/src/test/current-asset.test.ts
+++ b/packages/studio/src/test/current-asset.test.ts
@@ -1,6 +1,6 @@
import {expect, test} from 'bun:test';
import {
- getCurrentAssetMediaDetailLines,
+ getCurrentAssetMediaSections,
getCurrentAssetImageMetadataSource,
getCurrentAssetMetadataSource,
} from '../components/CurrentAsset';
@@ -34,9 +34,9 @@ test('requests media metadata for audio and video assets', () => {
);
});
-test('formats multimedia details for current assets', () => {
+test('formats video and audio sections for current assets', () => {
expect(
- getCurrentAssetMediaDetailLines({
+ getCurrentAssetMediaSections({
duration: 10,
format: 'QuickTime / MOV',
width: 1920,
@@ -49,12 +49,25 @@ test('formats multimedia details for current assets', () => {
hasVideoTrack: true,
hasAudioTrack: true,
}),
- ).toEqual(['Video: H.264 · 29.97 FPS · HDR: No', 'Audio: AAC · 48000 Hz']);
+ ).toEqual({
+ audio: [
+ {label: 'Duration', value: '00:10.00'},
+ {label: 'Codec', value: 'AAC'},
+ {label: 'Sample rate', value: '48000 Hz'},
+ ],
+ video: [
+ {label: 'Dimensions', value: '1920 × 1080'},
+ {label: 'Frame rate', value: '29.97 FPS'},
+ {label: 'Duration', value: '00:10.00'},
+ {label: 'Codec', value: 'H.264'},
+ {label: 'HDR', value: 'No'},
+ ],
+ });
});
-test('formats missing audio for current asset videos', () => {
+test('returns an empty audio section for videos without audio', () => {
expect(
- getCurrentAssetMediaDetailLines({
+ getCurrentAssetMediaSections({
duration: 10,
format: 'MP4',
width: 1920,
@@ -67,7 +80,41 @@ test('formats missing audio for current asset videos', () => {
hasVideoTrack: true,
hasAudioTrack: false,
}),
- ).toEqual(['Video: H.264 · 30.00 FPS · HDR: Yes', 'Audio: No audio']);
+ ).toEqual({
+ audio: [],
+ video: [
+ {label: 'Dimensions', value: '1920 × 1080'},
+ {label: 'Frame rate', value: '30.00 FPS'},
+ {label: 'Duration', value: '00:10.00'},
+ {label: 'Codec', value: 'H.264'},
+ {label: 'HDR', value: 'Yes'},
+ ],
+ });
+});
+
+test('formats audio-only assets', () => {
+ expect(
+ getCurrentAssetMediaSections({
+ duration: 125.5,
+ format: 'MP3',
+ width: null,
+ height: null,
+ videoCodec: null,
+ audioCodec: 'mp3',
+ fps: null,
+ isHdr: null,
+ sampleRate: 44100,
+ hasVideoTrack: false,
+ hasAudioTrack: true,
+ }),
+ ).toEqual({
+ audio: [
+ {label: 'Duration', value: '02:05.50'},
+ {label: 'Codec', value: 'MP3'},
+ {label: 'Sample rate', value: '44100 Hz'},
+ ],
+ video: null,
+ });
});
test('keeps renamed assets in their current folder', () => {
diff --git a/packages/studio/src/test/open-in-remotion-convert.test.ts b/packages/studio/src/test/open-in-remotion-convert.test.ts
new file mode 100644
index 0000000000..82f035e4d6
--- /dev/null
+++ b/packages/studio/src/test/open-in-remotion-convert.test.ts
@@ -0,0 +1,16 @@
+import {expect, test} from 'bun:test';
+import {getRemotionConvertUrl} from '../helpers/open-in-remotion-convert';
+
+test('creates a Remotion Convert URL for a Studio asset', () => {
+ const url = new URL(
+ getRemotionConvertUrl({
+ relativePath: 'nested/My Video.mp4',
+ studioOrigin: 'http://localhost:3000',
+ }),
+ );
+
+ expect(url.origin + url.pathname).toBe('https://www.remotion.dev/convert');
+ expect(url.searchParams.get('url')).toBe(
+ 'http://localhost:3000/nested/My%20Video.mp4',
+ );
+});
diff --git a/packages/studio/src/test/use-media-metadata.test.ts b/packages/studio/src/test/use-media-metadata.test.ts
new file mode 100644
index 0000000000..f827bf56db
--- /dev/null
+++ b/packages/studio/src/test/use-media-metadata.test.ts
@@ -0,0 +1,15 @@
+import {expect, test} from 'bun:test';
+import {getFrameRateFromMetrics} from '../helpers/use-media-metadata';
+
+test('uses Mediabunny bestGuessFrameRate when enough packets were probed', () => {
+ expect(getFrameRateFromMetrics(null)).toBe(null);
+ expect(
+ getFrameRateFromMetrics({bestGuessFrameRate: 30, probedPacketCount: 1}),
+ ).toBe(null);
+ expect(
+ getFrameRateFromMetrics({
+ bestGuessFrameRate: 59.94005994005994,
+ probedPacketCount: 2,
+ }),
+ ).toBe(59.94005994005994);
+});