Skip to content

🎥 Make videos programmatically with React

`@remotion/media`: Support transparent videos in preview, fallback to <OffthreadVideo> if WebGL2 is not available

JonnyBurgere443a8931d1a
diff --git a/packages/media/src/audio/audio-for-rendering.tsx b/packages/media/src/audio/audio-for-rendering.tsx
index f0aaee9711..241405dc4f 100644
--- a/packages/media/src/audio/audio-for-rendering.tsx
+++ b/packages/media/src/audio/audio-for-rendering.tsx
@@ -151,6 +151,12 @@ export const AudioForRendering: React.FC<AudioProps> = ({
return;
}
+ if (result.type === 'cannot-decode-alpha') {
+ throw new Error(
+ `Cannot decode alpha component for ${src}, and 'disallowFallbackToHtml5Audio' was set. But this should never happen, since you used the <Audio> tag. Please report this as a bug.`,
+ );
+ }
+
if (result.type === 'network-error') {
if (disallowFallbackToHtml5Audio) {
cancelRender(
diff --git a/packages/media/src/browser-can-use-webgl2.ts b/packages/media/src/browser-can-use-webgl2.ts
new file mode 100644
index 0000000000..42f3558d9e
--- /dev/null
+++ b/packages/media/src/browser-can-use-webgl2.ts
@@ -0,0 +1,16 @@
+let browserCanUseWebGl2: null | boolean = null;
+
+const browserCanUseWebGl2Uncached = () => {
+ const canvas = new OffscreenCanvas(1, 1);
+ const context = canvas.getContext('webgl2');
+ return context !== null;
+};
+
+export const canBrowserUseWebGl2 = () => {
+ if (browserCanUseWebGl2 !== null) {
+ return browserCanUseWebGl2;
+ }
+
+ browserCanUseWebGl2 = browserCanUseWebGl2Uncached();
+ return browserCanUseWebGl2;
+};
diff --git a/packages/media/src/extract-frame-and-audio.ts b/packages/media/src/extract-frame-and-audio.ts
index ac4fe02bd1..c33b48a892 100644
--- a/packages/media/src/extract-frame-and-audio.ts
+++ b/packages/media/src/extract-frame-and-audio.ts
@@ -72,6 +72,13 @@ export const extractFrameAndAudio = async ({
return {type: 'unknown-container-format'};
}
+ if (frame?.type === 'cannot-decode-alpha') {
+ return {
+ type: 'cannot-decode-alpha',
+ durationInSeconds: frame.durationInSeconds,
+ };
+ }
+
if (audio === 'unknown-container-format') {
if (frame !== null) {
frame?.frame?.close();
diff --git a/packages/media/src/test/browser.test.ts b/packages/media/src/test/browser.test.ts
index 475dc17dd8..b66a14cdf4 100644
--- a/packages/media/src/test/browser.test.ts
+++ b/packages/media/src/test/browser.test.ts
@@ -33,6 +33,10 @@ test('Should be able to extract a frame', async () => {
throw new Error('Unknown container format');
}
+ if (result.type === 'cannot-decode-alpha') {
+ throw new Error('Cannot decode alpha');
+ }
+
const {audio, frame} = result;
assert(audio);
@@ -83,6 +87,10 @@ test('Should be able to extract the last frame', async () => {
throw new Error('Unknown container format');
}
+ if (result.type === 'cannot-decode-alpha') {
+ throw new Error('Cannot decode alpha');
+ }
+
const {audio, frame} = result;
assert(frame);
@@ -149,6 +157,10 @@ test('Should be apply volume correctly', async () => {
throw new Error('Unknown container format');
}
+ if (result.type === 'cannot-decode-alpha') {
+ throw new Error('Cannot decode alpha');
+ }
+
const {audio: audioAtFullVolume, frame} = result;
const totalAudioAtFullVolume = audioAtFullVolume?.data.reduce((acc, curr) => {
@@ -198,6 +210,10 @@ test('Should be able to loop', async () => {
throw new Error('Unknown container format');
}
+ if (result.type === 'cannot-decode-alpha') {
+ throw new Error('Cannot decode alpha');
+ }
+
const {frame} = result;
expect((frame as VideoFrame)?.timestamp).toBe(41_000_000);
diff --git a/packages/media/src/video-extraction/extract-frame-via-broadcast-channel.ts b/packages/media/src/video-extraction/extract-frame-via-broadcast-channel.ts
index 9b04b0c7b7..0011377cdc 100644
--- a/packages/media/src/video-extraction/extract-frame-via-broadcast-channel.ts
+++ b/packages/media/src/video-extraction/extract-frame-via-broadcast-channel.ts
@@ -37,6 +37,11 @@ type ExtractFrameResponse =
id: string;
durationInSeconds: number | null;
}
+ | {
+ type: 'response-cannot-decode-alpha';
+ id: string;
+ durationInSeconds: number | null;
+ }
| {
type: 'response-network-error';
id: string;
@@ -80,6 +85,19 @@ if (window.remotion_broadcastChannel && window.remotion_isMainTab) {
return;
}
+ if (result.type === 'cannot-decode-alpha') {
+ const cannotDecodeAlphaResponse: ExtractFrameResponse = {
+ type: 'response-cannot-decode-alpha',
+ id: data.id,
+ durationInSeconds: result.durationInSeconds,
+ };
+
+ window.remotion_broadcastChannel!.postMessage(
+ cannotDecodeAlphaResponse,
+ );
+ return;
+ }
+
if (result.type === 'network-error') {
const networkErrorResponse: ExtractFrameResponse = {
type: 'response-network-error',
@@ -146,6 +164,7 @@ export type ExtractFrameViaBroadcastChannelResult =
durationInSeconds: number | null;
}
| {type: 'cannot-decode'; durationInSeconds: number | null}
+ | {type: 'cannot-decode-alpha'; durationInSeconds: number | null}
| {type: 'network-error'}
| {type: 'unknown-container-format'};
@@ -205,6 +224,7 @@ export const extractFrameViaBroadcastChannel = ({
durationInSeconds: number | null;
}
| {type: 'cannot-decode'; durationInSeconds: number | null}
+ | {type: 'cannot-decode-alpha'; durationInSeconds: number | null}
| {type: 'network-error'}
| {type: 'unknown-container-format'}
>((resolve, reject) => {
@@ -274,6 +294,18 @@ export const extractFrameViaBroadcastChannel = ({
return;
}
+ if (data.type === 'response-cannot-decode-alpha') {
+ resolve({
+ type: 'cannot-decode-alpha',
+ durationInSeconds: data.durationInSeconds,
+ });
+ window.remotion_broadcastChannel!.removeEventListener(
+ 'message',
+ onMessage,
+ );
+ return;
+ }
+
throw new Error(
`Invalid message: ${JSON.stringify(data satisfies never)}`,
);
diff --git a/packages/media/src/video-extraction/extract-frame.ts b/packages/media/src/video-extraction/extract-frame.ts
index 901c6337ee..c62c3b650c 100644
--- a/packages/media/src/video-extraction/extract-frame.ts
+++ b/packages/media/src/video-extraction/extract-frame.ts
@@ -11,6 +11,7 @@ type ExtractFrameResult =
durationInSeconds: number | null;
}
| {type: 'cannot-decode'; durationInSeconds: number | null}
+ | {type: 'cannot-decode-alpha'; durationInSeconds: number | null}
| {type: 'unknown-container-format'};
type ExtractFrameParams = {
@@ -84,6 +85,13 @@ const extractFrameInternal = async ({
logLevel,
});
+ if (keyframeBank === 'has-alpha') {
+ return {
+ type: 'cannot-decode-alpha',
+ durationInSeconds: await sink.getDuration(),
+ };
+ }
+
if (!keyframeBank) {
return {
type: 'success',
diff --git a/packages/media/src/video-extraction/keyframe-manager.ts b/packages/media/src/video-extraction/keyframe-manager.ts
index 70ace6c3aa..38082af78c 100644
--- a/packages/media/src/video-extraction/keyframe-manager.ts
+++ b/packages/media/src/video-extraction/keyframe-manager.ts
@@ -1,5 +1,6 @@
import type {EncodedPacketSink, VideoSampleSink} from 'mediabunny';
import {Internals, type LogLevel} from 'remotion';
+import {canBrowserUseWebGl2} from '../browser-can-use-webgl2';
import {
getMaxVideoCacheSize,
getTotalCacheStats,
@@ -173,10 +174,14 @@ export const makeKeyframeManager = () => {
videoSampleSink: VideoSampleSink;
src: string;
logLevel: LogLevel;
- }): Promise<KeyframeBank | null> => {
+ }): Promise<KeyframeBank | 'has-alpha' | null> => {
const startPacket = await packetSink.getKeyPacket(timestamp, {
verifyKeyPackets: true,
});
+ const hasAlpha = startPacket?.sideData.alpha;
+ if (hasAlpha && !canBrowserUseWebGl2()) {
+ return 'has-alpha';
+ }
if (!startPacket) {
// e.g. https://discord.com/channels/809501355504959528/809501355504959531/1424400511070765086
@@ -302,7 +307,7 @@ export const makeKeyframeManager = () => {
logLevel,
}),
);
- return queue as Promise<KeyframeBank | null>;
+ return queue as Promise<KeyframeBank | 'has-alpha' | null>;
},
getCacheStats,
clearAll,
diff --git a/packages/media/src/video/media-player.ts b/packages/media/src/video/media-player.ts
index f77f29022c..dce430a417 100644
--- a/packages/media/src/video/media-player.ts
+++ b/packages/media/src/video/media-player.ts
@@ -201,6 +201,7 @@ export class MediaPlayer {
this.canvasSink = new CanvasSink(videoTrack, {
poolSize: 2,
fit: 'contain',
+ alpha: true,
});
this.canvas.width = videoTrack.displayWidth;
@@ -502,6 +503,7 @@ export class MediaPlayer {
private drawCurrentFrame(): void {
if (this.context && this.nextFrame) {
+ this.context.clearRect(0, 0, this.canvas!.width, this.canvas!.height);
this.context.drawImage(this.nextFrame.canvas, 0, 0);
}
diff --git a/packages/media/src/video/video-for-rendering.tsx b/packages/media/src/video/video-for-rendering.tsx
index fe9bb30a47..9b91c53a82 100644
--- a/packages/media/src/video/video-for-rendering.tsx
+++ b/packages/media/src/video/video-for-rendering.tsx
@@ -201,6 +201,28 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
return;
}
+ if (result.type === 'cannot-decode-alpha') {
+ if (disallowFallbackToOffthreadVideo) {
+ cancelRender(
+ new Error(
+ `Cannot decode alpha component for ${src}, and 'disallowFallbackToOffthreadVideo' was set. Failing the render.`,
+ ),
+ );
+ }
+
+ if (window.remotion_isMainTab) {
+ Internals.Log.info(
+ {logLevel, tag: '@remotion/media'},
+ `Cannot decode alpha component for ${src}, falling back to <OffthreadVideo>`,
+ );
+ }
+
+ setReplaceWithOffthreadVideo({
+ durationInSeconds: result.durationInSeconds,
+ });
+ return;
+ }
+
if (result.type === 'network-error') {
if (disallowFallbackToOffthreadVideo) {
cancelRender(
@@ -228,7 +250,9 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
} = result;
if (imageBitmap) {
onVideoFrame?.(imageBitmap);
- const context = canvasRef.current?.getContext('2d');
+ const context = canvasRef.current?.getContext('2d', {
+ alpha: true,
+ });
if (!context) {
return;
}
@@ -249,7 +273,9 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
// In the case of https://discord.com/channels/809501355504959528/809501355504959531/1424400511070765086
// A video that only starts at time 0.033sec
// we shall not crash here but clear the canvas
- const context = canvasRef.current?.getContext('2d');
+ const context = canvasRef.current?.getContext('2d', {
+ alpha: true,
+ });
if (context) {
context.clearRect(
0,
@@ -351,7 +377,7 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
}
style={style}
allowAmplificationDuringRender
- transparent={fallbackOffthreadVideoProps?.transparent ?? false}
+ transparent={fallbackOffthreadVideoProps?.transparent ?? true}
toneMapped={fallbackOffthreadVideoProps?.toneMapped ?? true}
audioStreamIndex={audioStreamIndex ?? 0}
name={name}