Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Set inserted asset durations (#9439)

Jonny Burger217ff85364ad
diff --git a/packages/core/src/animated-image/create-image-decoder.ts b/packages/core/src/animated-image/create-image-decoder.ts
new file mode 100644
index 0000000000..945afd722a
--- /dev/null
+++ b/packages/core/src/animated-image/create-image-decoder.ts
@@ -0,0 +1,37 @@
+export const createImageDecoder = async ({
+ resolvedSrc,
+ signal,
+ requestInit,
+ contentType,
+}: {
+ resolvedSrc: string;
+ signal: AbortSignal;
+ requestInit?: RequestInit;
+ contentType: string | null;
+}) => {
+ if (typeof ImageDecoder === 'undefined') {
+ throw new Error(
+ 'Your browser does not support the WebCodecs ImageDecoder API.',
+ );
+ }
+
+ const response = await fetch(resolvedSrc, {...requestInit, signal});
+ const {body} = response;
+ if (!body) {
+ throw new Error('Got no body');
+ }
+
+ const decoder = new ImageDecoder({
+ data: body,
+ type: contentType ?? response.headers.get('Content-Type') ?? 'image/gif',
+ });
+ await Promise.all([decoder.completed, decoder.tracks.ready]);
+
+ const {selectedTrack} = decoder.tracks;
+ if (!selectedTrack) {
+ decoder.close();
+ throw new Error('No selected track');
+ }
+
+ return {decoder, selectedTrack};
+};
diff --git a/packages/core/src/animated-image/decode-image.ts b/packages/core/src/animated-image/decode-image.ts
index 17dc7a50ac..72f3bc3c12 100644
--- a/packages/core/src/animated-image/decode-image.ts
+++ b/packages/core/src/animated-image/decode-image.ts
@@ -1,3 +1,4 @@
+import {createImageDecoder} from './create-image-decoder';
import type {RemotionAnimatedImageLoopBehavior} from './props';
export type AnimatedImageCacheItem = {
@@ -46,29 +47,12 @@ export const decodeImage = async ({
currentTime: number;
initialLoopBehavior: RemotionAnimatedImageLoopBehavior;
}): Promise<RemotionImageDecoder> => {
- if (typeof ImageDecoder === 'undefined') {
- throw new Error(
- 'Your browser does not support the WebCodecs ImageDecoder API.',
- );
- }
-
- const res = await fetch(resolvedSrc, {...requestInit, signal});
- const {body} = res;
-
- if (!body) {
- throw new Error('Got no body');
- }
-
- const decoder = new ImageDecoder({
- data: body,
- type: res.headers.get('Content-Type') || 'image/gif',
+ const {decoder, selectedTrack} = await createImageDecoder({
+ resolvedSrc,
+ signal,
+ requestInit,
+ contentType: null,
});
- const {tracks} = decoder;
- await Promise.all([decoder.completed, tracks.ready]);
- const {selectedTrack} = tracks;
- if (!selectedTrack) {
- throw new Error('No selected track');
- }
const cache: AnimatedImageCacheItem[] = [];
diff --git a/packages/core/src/animated-image/get-duration-in-seconds.ts b/packages/core/src/animated-image/get-duration-in-seconds.ts
new file mode 100644
index 0000000000..6bff1a03a6
--- /dev/null
+++ b/packages/core/src/animated-image/get-duration-in-seconds.ts
@@ -0,0 +1,39 @@
+import {createImageDecoder} from './create-image-decoder';
+
+export const getAnimatedImageDurationInSeconds = async ({
+ resolvedSrc,
+ signal,
+ requestInit,
+ contentType,
+}: {
+ resolvedSrc: string;
+ signal: AbortSignal;
+ requestInit?: RequestInit;
+ contentType: string | null;
+}) => {
+ const {decoder, selectedTrack} = await createImageDecoder({
+ resolvedSrc,
+ signal,
+ requestInit,
+ contentType,
+ });
+
+ try {
+ const {image} = await decoder.decode({
+ frameIndex: selectedTrack.frameCount - 1,
+ completeFramesOnly: true,
+ });
+
+ try {
+ if (image.duration === null) {
+ throw new Error('Could not determine animated image duration');
+ }
+
+ return (image.timestamp + image.duration) / 1_000_000;
+ } finally {
+ image.close();
+ }
+ } finally {
+ decoder.close();
+ }
+};
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index a85642cce7..ca5cfde4a1 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -1,5 +1,6 @@
import {createRef} from 'react';
import {getAbsoluteSrc} from './absolute-src.js';
+import {getAnimatedImageDurationInSeconds} from './animated-image/get-duration-in-seconds.js';
import {AudioForPreview} from './audio/AudioForPreview.js';
import type {ScheduleAudioNodeResult} from './audio/shared-audio-tags.js';
import {
@@ -285,6 +286,7 @@ export const Internals = {
useAbsoluteTimelinePosition: TimelinePosition.useAbsoluteTimelinePosition,
evaluateVolume,
getAbsoluteSrc,
+ getAnimatedImageDurationInSeconds,
getAssetDisplayName,
Timeline: TimelinePosition,
validateMediaTrimProps,
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index 97d80fabd0..ff8997afa7 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -997,6 +997,7 @@ const createSequenceWrappedElement = ({
const createAssetElement = ({
addPositionStyle,
+ durationInFrames,
localName,
staticFileLocalName,
src,
@@ -1004,6 +1005,7 @@ const createAssetElement = ({
position,
}: {
addPositionStyle: boolean;
+ durationInFrames: number | null;
localName: string;
staticFileLocalName: string | null;
src: string;
@@ -1017,6 +1019,9 @@ const createAssetElement = ({
staticFileLocalName === null
? createStringSrcAttribute(src)
: createStaticFileSrcAttribute({staticFileLocalName, src}),
+ ...(durationInFrames === null
+ ? []
+ : [createNumberAttribute('durationInFrames', durationInFrames)]),
...(addPositionStyle
? [createAssetStyleAttribute({dimensions, position})]
: []),
@@ -2217,7 +2222,10 @@ const createInsertableJsxElement = ({
}
return createAssetElement({
- addPositionStyle: element.assetType !== 'audio',
+ addPositionStyle:
+ addPositionStyleToComponent && element.assetType !== 'audio',
+ durationInFrames:
+ element.assetType === 'image' ? null : element.durationInFrames,
localName,
staticFileLocalName,
src: element.src,
diff --git a/packages/studio-server/src/preview-server/routes/download-remote-asset.ts b/packages/studio-server/src/preview-server/routes/download-remote-asset.ts
index 9547607dd8..dd93abd34d 100644
--- a/packages/studio-server/src/preview-server/routes/download-remote-asset.ts
+++ b/packages/studio-server/src/preview-server/routes/download-remote-asset.ts
@@ -346,6 +346,7 @@ export const downloadRemoteAssetHandler: ApiHandler<
src: assetPath,
srcType: 'static',
dimensions: fileType.dimensions,
+ durationInFrames: null,
position: null,
};
diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
index 17df2712db..df196633d7 100644
--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
@@ -112,6 +112,10 @@ const validateElement = (
validateDimension('height', element.dimensions.height);
}
+ if (element.durationInFrames !== null) {
+ validateDimension('durationInFrames', element.durationInFrames);
+ }
+
return;
}
diff --git a/packages/studio-server/src/test/download-remote-asset.test.ts b/packages/studio-server/src/test/download-remote-asset.test.ts
index d6a59924c8..5958b03e2b 100644
--- a/packages/studio-server/src/test/download-remote-asset.test.ts
+++ b/packages/studio-server/src/test/download-remote-asset.test.ts
@@ -99,6 +99,7 @@ test('follows validated redirects for remote assets', async () => {
height: 600,
width: 800,
},
+ durationInFrames: null,
position: null,
src: 'raw-link.gif',
srcType: 'static',
diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.ts
index e128246105..1f71726845 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -378,6 +378,7 @@ test('wraps a self-closing root in a Sequence before inserting', async () => {
src: 'music.mp3',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -436,6 +437,7 @@ test('removes parentheses when wrapping a self-closing root in a Sequence', asyn
src: 'foreground.png',
srcType: 'static',
dimensions: {width: 1920, height: 1080},
+ durationInFrames: null,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -966,6 +968,7 @@ test('inserts a CanvasImage asset into the resolved composition component', asyn
width: 800,
height: 600,
},
+ durationInFrames: null,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -1025,6 +1028,7 @@ test('inserts a CanvasImage asset with a translate style', async () => {
width: 800,
height: 600,
},
+ durationInFrames: null,
position: {
x: 100,
y: 150,
@@ -1083,6 +1087,7 @@ test('inserts an AnimatedImage asset into the resolved composition component', a
width: 320,
height: 180,
},
+ durationInFrames: 37.52,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -1093,6 +1098,7 @@ test('inserts an AnimatedImage asset into the resolved composition component', a
);
expect(result.output).toContain('<AnimatedImage');
expect(result.output).toContain("src={staticFile('animated-png.png')}");
+ expect(result.output).toContain('durationInFrames={37.52}');
expect(result.output).toContain('width: 320');
expect(result.output).toContain('height: 180');
expect(result.output).not.toContain('width={320}');
@@ -1102,7 +1108,7 @@ test('inserts an AnimatedImage asset into the resolved composition component', a
}
});
-test('inserts a Video asset with CSS dimensions', async () => {
+test('inserts a Video asset with its duration and CSS dimensions', async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));
try {
await fs.writeFile(
@@ -1141,6 +1147,7 @@ test('inserts a Video asset with CSS dimensions', async () => {
width: 1920,
height: 1080,
},
+ durationInFrames: 37.52,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -1150,13 +1157,13 @@ test('inserts a Video asset with CSS dimensions', async () => {
expect(result.output).toContain(
"import { AbsoluteFill, staticFile } from 'remotion';",
);
+ expect(result.output).toContain('durationInFrames={37.52}');
expect(result.output).toContain('<Video');
expect(result.output).toContain("src={staticFile('clip.mp4')}");
expect(result.output).toContain("position: 'absolute'");
expect(result.output).toContain('width: 1920');
expect(result.output).toContain('height: 1080');
- expect(result.output).not.toContain('width={1920}');
- expect(result.output).not.toContain('height={1080}');
+ expect(result.output).not.toContain('<Sequence');
} finally {
await fs.rm(tempDir, {recursive: true, force: true});
}
@@ -1201,6 +1208,7 @@ test('rejects inserting a Video asset if Video is already defined', async () =>
src: 'clip.mp4',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -1250,6 +1258,7 @@ test('inserts a Gif asset into the resolved composition component', async () =>
width: 320,
height: 180,
},
+ durationInFrames: 37.52,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -1261,6 +1270,7 @@ test('inserts a Gif asset into the resolved composition component', async () =>
);
expect(result.output).toContain('<Gif');
expect(result.output).toContain("src={staticFile('animation.gif')}");
+ expect(result.output).toContain('durationInFrames={37.52}');
expect(result.output).toContain('width: 320');
expect(result.output).toContain('height: 180');
expect(result.output).not.toContain('width={320}');
@@ -1306,6 +1316,7 @@ test('inserts an Audio asset into the resolved composition component', async ()
src: 'audio.mp3',
srcType: 'static',
dimensions: null,
+ durationInFrames: 37.52,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -1317,6 +1328,7 @@ test('inserts an Audio asset into the resolved composition component', async ()
);
expect(result.output).toContain('<Audio');
expect(result.output).toContain("src={staticFile('audio.mp3')}");
+ expect(result.output).toContain('durationInFrames={37.52}');
expect(result.output).not.toContain("position: 'absolute'");
} finally {
await fs.rm(tempDir, {recursive: true, force: true});
@@ -1359,6 +1371,7 @@ test('inserts a remote audio asset with a literal URL', async () => {
src: 'https://example.com/whip.wav',
srcType: 'remote',
dimensions: null,
+ durationInFrames: null,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
@@ -1415,6 +1428,7 @@ test('rejects inserting an Audio asset if Audio is already defined', async () =>
src: 'audio.mp3',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
},
prettierConfigOverride: {singleQuote: true, useTabs: true},
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 0008ef1f01..116c9fc75f 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -715,6 +715,7 @@ export type InsertableCompositionElement =
width: number;
height: number;
} | null;
+ durationInFrames: number | null;
position: InsertableCompositionElementPosition | null;
}
| {
diff --git a/packages/studio-shared/src/test/required-package.test.ts b/packages/studio-shared/src/test/required-package.test.ts
index 4fe915b46a..1c9aaf879a 100644
--- a/packages/studio-shared/src/test/required-package.test.ts
+++ b/packages/studio-shared/src/test/required-package.test.ts
@@ -28,6 +28,7 @@ test('gets required package for insertable elements', () => {
src: 'image.png',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
}),
).toBe(null);
@@ -38,6 +39,7 @@ test('gets required package for insertable elements', () => {
src: 'video.mp4',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
}),
).toBe('@remotion/media');
@@ -48,6 +50,7 @@ test('gets required package for insertable elements', () => {
src: 'audio.mp3',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
}),
).toBe('@remotion/media');
@@ -58,6 +61,7 @@ test('gets required package for insertable elements', () => {
src: 'animation.gif',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
}),
).toBe('@remotion/gif');
@@ -68,6 +72,7 @@ test('gets required package for insertable elements', () => {
src: 'animated.png',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
}),
).toBe(null);
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index 8e20315d90..982cbdbd0b 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -1121,7 +1121,8 @@ export const Canvas: React.FC<{
if (
!canDropAssets ||
compositionFile === null ||
- currentCompositionId === null
+ currentCompositionId === null ||
+ config === null
) {
return;
}
@@ -1163,6 +1164,7 @@ export const Canvas: React.FC<{
await importAssets({
files,
+ fps: config.fps,
compositionFile,
compositionId: currentCompositionId,
destinationDimensions:
@@ -1178,6 +1180,7 @@ export const Canvas: React.FC<{
await insertExistingAssets({
assetPaths: [assetPath],
+ fps: config.fps,
compositionFile,
compositionId: currentCompositionId,
destinationDimensions:
@@ -1192,6 +1195,7 @@ export const Canvas: React.FC<{
await insertRemoteAudio({
url,
+ fps: config.fps,
compositionFile,
compositionId: currentCompositionId,
});
@@ -1239,6 +1243,7 @@ export const Canvas: React.FC<{
await importRemoteAsset({
url,
+ fps: config.fps,
compositionFile,
compositionId: currentCompositionId,
destinationDimensions:
@@ -1256,6 +1261,7 @@ export const Canvas: React.FC<{
cannotAddSequence,
chooseSvgImportMode,
compositionFile,
+ config,
contentDimensions,
currentCompositionId,
previewSize,
@@ -1270,6 +1276,7 @@ export const Canvas: React.FC<{
!canDropAssets ||
compositionFile === null ||
currentCompositionId === null ||
+ config === null ||
event.clipboardData === null ||
activeElement instanceof HTMLInputElement ||
activeElement instanceof HTMLTextAreaElement ||
@@ -1346,6 +1353,7 @@ export const Canvas: React.FC<{
try {
await importAssets({
files,
+ fps: config.fps,
compositionFile,
compositionId: currentCompositionId,
destinationDimensions:
@@ -1361,6 +1369,7 @@ export const Canvas: React.FC<{
canDropAssets,
chooseSvgImportMode,
compositionFile,
+ config,
contentDimensions,
currentCompositionId,
],
diff --git a/packages/studio/src/components/InspectorPanel/use-composition-actions.ts b/packages/studio/src/components/InspectorPanel/use-composition-actions.ts
index 75b129da71..7c85daaa08 100644
--- a/packages/studio/src/components/InspectorPanel/use-composition-actions.ts
+++ b/packages/studio/src/components/InspectorPanel/use-composition-actions.ts
@@ -97,7 +97,8 @@ export const useCompositionActions = () => {
if (
!canInsertAsset ||
currentCompositionId === null ||
- compositionFile === null
+ compositionFile === null ||
+ videoConfig === null
) {
return;
}
@@ -111,6 +112,7 @@ export const useCompositionActions = () => {
try {
await importAssets({
files,
+ fps: videoConfig.fps,
compositionFile,
compositionId: currentCompositionId,
destinationDimensions: null,
@@ -120,7 +122,7 @@ export const useCompositionActions = () => {
} finally {
setIsAddingAsset(false);
}
- }, [canInsertAsset, compositionFile, currentCompositionId]);
+ }, [canInsertAsset, compositionFile, currentCompositionId, videoConfig]);
return {
canInsertAsset,
diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsx
index 61c21db555..c968f07269 100644
--- a/packages/studio/src/components/Timeline/Timeline.tsx
+++ b/packages/studio/src/components/Timeline/Timeline.tsx
@@ -146,7 +146,8 @@ const TimelineContextMenuArea: React.FC<{
if (
!canInsertAsset ||
currentCompositionId === null ||
- compositionFile === null
+ compositionFile === null ||
+ videoConfig === null
) {
return;
}
@@ -160,6 +161,7 @@ const TimelineContextMenuArea: React.FC<{
try {
await importAssets({
files,
+ fps: videoConfig.fps,
compositionFile,
compositionId: currentCompositionId,
destinationDimensions: null,
@@ -169,7 +171,7 @@ const TimelineContextMenuArea: React.FC<{
} finally {
setIsAddingAsset(false);
}
- }, [canInsertAsset, compositionFile, currentCompositionId]);
+ }, [canInsertAsset, compositionFile, currentCompositionId, videoConfig]);
const contextMenuItems = useMemo((): ComboboxValue[] => {
return [
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index a8bc61eabe..9b9dc02653 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -1,4 +1,3 @@
-import {getVideoMetadata} from '@remotion/media-utils';
import {
detectFileType,
getRequiredPackageForInsertableElement,
@@ -19,6 +18,7 @@ import {writeStaticFile} from '../api/write-static-file';
import {formatFigmaClipboardErrorNotification} from '../helpers/clipboard-figma';
import {installRequiredPackages} from '../helpers/install-required-package';
import type {Dimensions} from '../helpers/is-current-selected-still';
+import {getMediaMetadata} from '../helpers/use-media-metadata';
import {callApi} from './call-api';
import {showNotification} from './Notifications/NotificationCenter';
@@ -46,6 +46,7 @@ export const getAssetElement = ({
src,
srcType: 'static',
dimensions: fileType.dimensions,
+ durationInFrames: null,
position: null,
};
}
@@ -62,6 +63,7 @@ export const getAssetElement = ({
src,
srcType: 'static',
dimensions: fileType.dimensions,
+ durationInFrames: null,
position: null,
};
}
@@ -73,6 +75,7 @@ export const getAssetElement = ({
src,
srcType: 'static',
dimensions: fileType.dimensions,
+ durationInFrames: null,
position: null,
};
}
@@ -84,6 +87,7 @@ export const getAssetElement = ({
src,
srcType: 'static',
dimensions: fileType.dimensions,
+ durationInFrames: null,
position: null,
};
}
@@ -100,6 +104,7 @@ export const getAssetElement = ({
src,
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
};
}
@@ -116,6 +121,7 @@ export const getAssetElement = ({
src,
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
};
}
@@ -142,6 +148,7 @@ export const getAssetElementFromPath = (
src: assetPath,
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
};
}
@@ -153,6 +160,7 @@ export const getAssetElementFromPath = (
src: assetPath,
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
};
}
@@ -164,6 +172,7 @@ export const getAssetElementFromPath = (
src: assetPath,
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
};
}
@@ -175,6 +184,7 @@ export const getAssetElementFromPath = (
src: assetPath,
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
};
}
@@ -186,6 +196,7 @@ export const getAssetElementFromPath = (
src: assetPath,
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
};
}
@@ -386,21 +397,54 @@ const getImageDimensions = ({
});
};
-const getVideoDimensions = async (src: string): Promise<Dimensions> => {
- const metadata = await getVideoMetadata(src);
- return {width: metadata.width, height: metadata.height};
+type AssetMetadataForInsertion = {
+ dimensions: Dimensions | null;
+ durationInSeconds: number | null;
+};
+
+const getMediaAssetMetadata = async (
+ src: string,
+): Promise<AssetMetadataForInsertion> => {
+ const metadata = await getMediaMetadata(src);
+ return {
+ dimensions:
+ metadata?.width === null || metadata?.height === null || !metadata
+ ? null
+ : {width: metadata.width, height: metadata.height},
+ durationInSeconds: metadata?.duration ?? null,
+ };
+};
+
+const getAnimatedImageAssetDuration = (
+ src: string,
+ contentType: string | null,
+) => {
+ return Internals.getAnimatedImageDurationInSeconds({
+ resolvedSrc: src,
+ signal: new AbortController().signal,
+ contentType,
+ });
};
-const getFileDimensions = async ({
+const assetTypeHasDuration = (assetType: InsertableAssetElement['assetType']) =>
+ assetType !== 'image';
+
+const getFileMetadata = async ({
file,
fileType,
}: {
file: File;
fileType: FileType;
-}): Promise<Dimensions | null> => {
+}): Promise<AssetMetadataForInsertion> => {
if (fileType.type === 'unknown' && file.name.toLowerCase().endsWith('.svg')) {
const objectUrl = URL.createObjectURL(file);
- return getImageDimensions({revokeObjectUrl: true, src: objectUrl});
+ return {
+ dimensions: await getImageDimensions({
+ revokeObjectUrl: true,
+ src: objectUrl,
+ }),
+ durationInSeconds: null,
+ };
}
if (
@@ -409,7 +453,12 @@ const getFileDimensions = async ({
fileType.type === 'aac' ||
fileType.type === 'flac'
) {
- return null;
+ const objectUrl = URL.createObjectURL(file);
+ try {
+ return await getMediaAssetMetadata(objectUrl);
+ } finally {
+ URL.revokeObjectURL(objectUrl);
+ }
}
if (
@@ -420,12 +469,32 @@ const getFileDimensions = async ({
fileType.type === 'apng' ||
fileType.type === 'gif'
) {
- if (fileType.dimensions) {
- return fileType.dimensions;
- }
-
const objectUrl = URL.createObjectURL(file);
- return getImageDimensions({revokeObjectUrl: true, src: objectUrl});
+ try {
+ const dimensions =
+ fileType.dimensions ??
+ (await getImageDimensions({revokeObjectUrl: false, src: objectUrl}));
+ const isAnimated =
+ fileType.type === 'gif' ||
+ fileType.type === 'apng' ||
+ (fileType.type === 'webp' && fileType.animated);
+
+ return {
+ dimensions,
+ durationInSeconds: isAnimated
+ ? await getAnimatedImageAssetDuration(
+ objectUrl,
+ fileType.type === 'gif'
+ ? 'image/gif'
+ : fileType.type === 'webp'
+ ? 'image/webp'
+ : 'image/png',
+ )
+ : null,
+ };
+ } finally {
+ URL.revokeObjectURL(objectUrl);
+ }
}
if (
@@ -436,18 +505,19 @@ const getFileDimensions = async ({
) {
const objectUrl = URL.createObjectURL(file);
try {
- return await getVideoDimensions(objectUrl);
+ return await getMediaAssetMetadata(objectUrl);
} finally {
URL.revokeObjectURL(objectUrl);
}
}
- return null;
+ return {dimensions: null, durationInSeconds: null};
};
-const getStaticAssetDimensions = (
+const getStaticAssetMetadata = (
assetPath: string,
-): Dimensions | Promise<Dimensions> | null => {
+ assetType: InsertableAssetElement['assetType'],
+): AssetMetadataForInsertion | Promise<AssetMetadataForInsertion> => {
const extension = assetPath.split('.').pop()?.toLowerCase();
const src = staticFile(assetPath);
@@ -457,41 +527,73 @@ const getStaticAssetDimensions = (
extension,
)
) {
- return getImageDimensions({revokeObjectUrl: false, src});
+ return Promise.all([
+ getImageDimensions({revokeObjectUrl: false, src}),
+ assetType === 'gif' || assetType === 'animated-image'
+ ? getAnimatedImageAssetDuration(
+ src,
+ extension === 'gif'
+ ? 'image/gif'
+ : extension === 'webp'
+ ? 'image/webp'
+ : 'image/png',
+ )
+ : null,
+ ]).then(([dimensions, durationInSeconds]) => ({
+ dimensions,
+ durationInSeconds,
+ }));
}
- if (
- extension &&
- ['mp4', 'm4v', 'mov', 'avi', 'webm', 'ts', 'm2ts'].includes(extension)
- ) {
- return getVideoDimensions(src);
+ if (assetType === 'video' || assetType === 'audio') {
+ return getMediaAssetMetadata(src);
}
- return null;
+ return {dimensions: null, durationInSeconds: null};
};
-const getFileDimensionsOrNull = async ({
+const getFileMetadataOrNull = async ({
file,
fileType,
}: {
file: File;
fileType: FileType;
-}): Promise<Dimensions | null> => {
+}): Promise<AssetMetadataForInsertion> => {
try {
- return await getFileDimensions({file, fileType});
+ return await getFileMetadata({file, fileType});
} catch {
- return null;
+ return {dimensions: null, durationInSeconds: null};
}
};
-const getStaticAssetDimensionsOrNull = async (
+const getStaticAssetMetadataOrNull = async (
assetPath: string,
-): Promise<Dimensions | null> => {
+ assetType: InsertableAssetElement['assetType'],
+): Promise<AssetMetadataForInsertion> => {
try {
- return await getStaticAssetDimensions(assetPath);
+ return await getStaticAssetMetadata(assetPath, assetType);
} catch {
+ return {dimensions: null, durationInSeconds: null};
+ }
+};
+
+export const getDurationInFrames = ({
+ durationInSeconds,
+ fps,
+}: {
+ durationInSeconds: number | null;
+ fps: number;
+}): number | null => {
+ if (
+ durationInSeconds === null ||
+ !Number.isFinite(durationInSeconds) ||
+ durationInSeconds <= 0
+ ) {
return null;
}
+
+ const durationInFrames = Math.round(durationInSeconds * fps * 100) / 100;
+ return durationInFrames > 0 ? durationInFrames : null;
};
const getStaticAssetFileType = async (
@@ -625,6 +727,7 @@ export const importAssets = async ({
destinationDimensions,
dropPosition,
files,
+ fps,
svgImportMode,
}: {
compositionFile: string;
@@ -632,6 +735,7 @@ export const importAssets = async ({
destinationDimensions: Dimensions | null;
dropPosition: InsertElementDropPosition | null;
files: File[];
+ fps: number;
svgImportMode: 'image' | 'inline';
}) => {
if (files.length === 0) {
@@ -678,7 +782,7 @@ export const importAssets = async ({
for (const file of files) {
const contents = await file.arrayBuffer();
const fileType = detectFileType(new Uint8Array(contents));
- const dimensions = await getFileDimensionsOrNull({file, fileType});
+ const metadata = await getFileMetadataOrNull({file, fileType});
if (isSvgFile(file) && svgImportMode === 'inline') {
const svgInserted = await insertCompositionElement({
@@ -688,7 +792,7 @@ export const importAssets = async ({
type: 'svg',
markup: new TextDecoder().decode(contents),
position: getAssetPositionForDrop({
- assetDimensions: dimensions,
+ assetDimensions: metadata.dimensions,
destinationDimensions,
dropPosition,
}),
@@ -728,7 +832,7 @@ export const importAssets = async ({
addedStaticFiles.push(file.name);
}
- const resolvedDimensions = element.dimensions ?? dimensions;
+ const resolvedDimensions = element.dimensions ?? metadata.dimensions;
const inserted = await insertCompositionElement({
compositionFile,
@@ -736,6 +840,12 @@ export const importAssets = async ({
element: {
...element,
dimensions: resolvedDimensions,
+ durationInFrames: assetTypeHasDuration(element.assetType)
+ ? getDurationInFrames({
+ durationInSeconds: metadata.durationInSeconds,
+ fps,
+ })
+ : null,
position: getAssetPositionForDrop({
assetDimensions: resolvedDimensions,
destinationDimensions,
@@ -866,12 +976,14 @@ export const importRemoteAsset = async ({
compositionId,
destinationDimensions,
dropPosition,
+ fps,
url,
}: {
compositionFile: string;
compositionId: string;
destinationDimensions: Dimensions | null;
dropPosition: InsertElementDropPosition | null;
+ fps: number;
url: string;
}) => {
try {
@@ -886,13 +998,26 @@ export const importRemoteAsset = async ({
return;
}
+ const metadata = await getStaticAssetMetadataOrNull(
+ assetPath,
+ element.assetType,
+ );
+ const dimensions = element.dimensions ?? metadata.dimensions;
+
const inserted = await insertCompositionElement({
compositionFile,
compositionId,
element: {
...element,
+ dimensions,
+ durationInFrames: assetTypeHasDuration(element.assetType)
+ ? getDurationInFrames({
+ durationInSeconds: metadata.durationInSeconds,
+ fps,
+ })
+ : null,
position: getAssetPositionForDrop({
- assetDimensions: element.dimensions,
+ assetDimensions: dimensions,
destinationDimensions,
dropPosition,
}),
@@ -917,10 +1042,12 @@ export const importRemoteAsset = async ({
export const insertRemoteAudio = async ({
compositionFile,
compositionId,
+ fps,
url,
}: {
compositionFile: string;
compositionId: string;
+ fps: number;
url: string;
}) => {
if (!isUrl(url)) {
@@ -928,16 +1055,21 @@ export const insertRemoteAudio = async ({
return;
}
- const element: InsertableCompositionElement = {
- type: 'asset',
- assetType: 'audio',
- src: url,
- srcType: 'remote',
- dimensions: null,
- position: null,
- };
-
try {
+ const metadata = await getMediaAssetMetadata(url);
+ const element: InsertableCompositionElement = {
+ type: 'asset',
+ assetType: 'audio',
+ src: url,
+ srcType: 'remote',
+ dimensions: null,
+ durationInFrames: getDurationInFrames({
+ durationInSeconds: metadata.durationInSeconds,
+ fps,
+ }),
+ position: null,
+ };
+
const inserted = await insertCompositionElement({
compositionFile,
compositionId,
@@ -965,12 +1097,14 @@ export const insertExistingAssets = async ({
compositionId,
destinationDimensions,
dropPosition,
+ fps,
}: {
assetPaths: string[];
compositionFile: string;
compositionId: string;
destinationDimensions: Dimensions | null;
dropPosition: InsertElementDropPosition | null;
+ fps: number;
}) => {
if (assetPaths.length === 0) {
return;
@@ -987,8 +1121,11 @@ export const insertExistingAssets = async ({
continue;
}
- const dimensions =
- element.dimensions ?? (await getStaticAssetDimensionsOrNull(assetPath));
+ const metadata = await getStaticAssetMetadataOrNull(
+ assetPath,
+ element.assetType,
+ );
+ const dimensions = element.dimensions ?? metadata.dimensions;
const inserted = await insertCompositionElement({
compositionFile,
@@ -996,6 +1133,12 @@ export const insertExistingAssets = async ({
element: {
...element,
dimensions,
+ durationInFrames: assetTypeHasDuration(element.assetType)
+ ? getDurationInFrames({
+ durationInSeconds: metadata.durationInSeconds,
+ fps,
+ })
+ : null,
position: getAssetPositionForDrop({
assetDimensions: dimensions,
destinationDimensions,
diff --git a/packages/studio/src/test/import-assets.test.ts b/packages/studio/src/test/import-assets.test.ts
index 04b58ff795..2af88617e0 100644
--- a/packages/studio/src/test/import-assets.test.ts
+++ b/packages/studio/src/test/import-assets.test.ts
@@ -6,10 +6,22 @@ import {
getAssetElementFromPath,
getComponentDimensions,
getCompositionPositionForDrop,
+ getDurationInFrames,
getElementPositionForDrop,
hasSvgFile,
} from '../components/import-assets';
+test('converts media duration to composition frames with two decimals', () => {
+ expect(getDurationInFrames({durationInSeconds: 1.2345, fps: 30})).toBe(37.03);
+ expect(getDurationInFrames({durationInSeconds: 2, fps: 29.97})).toBe(59.94);
+ expect(getDurationInFrames({durationInSeconds: null, fps: 30})).toBe(null);
+ expect(getDurationInFrames({durationInSeconds: 0, fps: 30})).toBe(null);
+ expect(getDurationInFrames({durationInSeconds: -1, fps: 30})).toBe(null);
+ expect(getDurationInFrames({durationInSeconds: Number.NaN, fps: 30})).toBe(
+ null,
+ );
+});
+
test('maps audio file types to Audio assets', () => {
for (const type of ['wav', 'mp3', 'aac', 'flac'] as const) {
expect(
@@ -23,6 +35,7 @@ test('maps audio file types to Audio assets', () => {
src: `sound.${type}`,
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
});
}
@@ -52,6 +65,7 @@ test('maps animated PNG file types to AnimatedImage assets', () => {
src: 'animated-png.png',
srcType: 'static',
dimensions: {width: 320, height: 180},
+ durationInFrames: null,
position: null,
});
});
@@ -72,6 +86,7 @@ test('maps animated WebP file types to AnimatedImage assets', () => {
src: 'animated.webp',
srcType: 'static',
dimensions: {width: 480, height: 290},
+ durationInFrames: null,
position: null,
});
});
@@ -92,6 +107,7 @@ test('maps static WebP file types to static image assets', () => {
src: 'static.webp',
srcType: 'static',
dimensions: {width: 480, height: 290},
+ durationInFrames: null,
position: null,
});
});
@@ -103,6 +119,7 @@ test('maps existing static file paths to insertable assets', () => {
src: 'nested/photo.JPG',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
});
expect(getAssetElementFromPath('movie.webm')).toEqual({
@@ -111,6 +128,7 @@ test('maps existing static file paths to insertable assets', () => {
src: 'movie.webm',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
});
expect(getAssetElementFromPath('audio.flac')).toEqual({
@@ -119,6 +137,7 @@ test('maps existing static file paths to insertable assets', () => {
src: 'audio.flac',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
});
expect(getAssetElementFromPath('animation.apng')).toEqual({
@@ -127,6 +146,7 @@ test('maps existing static file paths to insertable assets', () => {
src: 'animation.apng',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
});
expect(getAssetElementFromPath('animation.gif')).toEqual({
@@ -135,6 +155,7 @@ test('maps existing static file paths to insertable assets', () => {
src: 'animation.gif',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
});
expect(getAssetElementFromPath('vector.SVG')).toEqual({
@@ -143,6 +164,7 @@ test('maps existing static file paths to insertable assets', () => {
src: 'vector.SVG',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
});
});
@@ -159,6 +181,7 @@ test('maps dropped SVG files to image assets', () => {
src: 'vector.svg',
srcType: 'static',
dimensions: null,
+ durationInFrames: null,
position: null,
});
});