Skip to content

πŸŽ₯ Make videos programmatically with React

cool

Jonny Burger78515d5a3944
diff --git a/packages/docs/src/components/Demo/Demo.tsx b/packages/docs/src/components/Demo/Demo.tsx
index a411fbe60d..5c6281efa9 100644
--- a/packages/docs/src/components/Demo/Demo.tsx
+++ b/packages/docs/src/components/Demo/Demo.tsx
@@ -8,6 +8,7 @@ import {
getDataAndProps,
} from '../../remotion/HomepageVideo/Comp';
import {ActionRow} from './ActionRow';
+import {PlayerControls} from './PlayerControls';
export const Demo: React.FC = () => {
const {colorMode} = useColorMode();
@@ -29,33 +30,35 @@ export const Demo: React.FC = () => {
<br />
<h1>Try it out</h1>
{data ? (
- <Player
- ref={ref}
- component={HomepageVideoComp}
- compositionWidth={640}
- compositionHeight={360}
- durationInFrames={120}
- fps={30}
- autoPlay
- controls
- clickToPlay={false}
- style={{
- border: '2px solid ' + strokeColor,
- borderBottom: '4px solid ' + strokeColor,
- borderRadius: 8,
- width: '100%',
- }}
- inputProps={{
- theme: colorMode,
- onToggle: () => {
- ref.current?.toggle();
- },
- ...data,
- }}
- loop
- />
+ <>
+ <Player
+ ref={ref}
+ component={HomepageVideoComp}
+ compositionWidth={640}
+ compositionHeight={360}
+ durationInFrames={120}
+ fps={30}
+ autoPlay
+ controls
+ clickToPlay={false}
+ style={{
+ border: '2px solid ' + strokeColor,
+ borderBottom: '4px solid ' + strokeColor,
+ borderRadius: 8,
+ width: '100%',
+ }}
+ inputProps={{
+ theme: colorMode,
+ onToggle: () => {
+ ref.current?.toggle();
+ },
+ ...data,
+ }}
+ loop
+ />
+ <PlayerControls playerRef={ref} durationInFrames={120} fps={30} />
+ </>
) : null}
-
<ActionRow />
</div>
);
diff --git a/packages/docs/src/components/Demo/PlayerControls.tsx b/packages/docs/src/components/Demo/PlayerControls.tsx
new file mode 100644
index 0000000000..3b040794ac
--- /dev/null
+++ b/packages/docs/src/components/Demo/PlayerControls.tsx
@@ -0,0 +1,111 @@
+import type {PlayerRef} from '@remotion/player';
+import React, {useCallback, useEffect} from 'react';
+import {PlayerSeekBar} from './PlayerSeekBar';
+
+const formatTime = (timeInSeconds: number) => {
+ const minutes = Math.floor(timeInSeconds / 60);
+ const seconds = Math.floor(timeInSeconds - minutes * 60);
+ return `${String(minutes)}:${String(seconds).padStart(2, '0')}`;
+};
+
+const PlayButton: React.FC<{
+ playerRef: React.RefObject<PlayerRef>;
+}> = ({playerRef}) => {
+ const [playing, setPlaying] = React.useState(true);
+
+ useEffect(() => {
+ const {current} = playerRef;
+ if (!current) {
+ return;
+ }
+
+ const onPlay = () => {
+ setPlaying(true);
+ };
+
+ const onPause = () => {
+ setPlaying(false);
+ };
+
+ current.addEventListener('play', onPlay);
+ current.addEventListener('pause', onPause);
+
+ return () => {
+ current.removeEventListener('play', onPlay);
+ current.removeEventListener('pause', onPause);
+ };
+ }, [playerRef]);
+
+ const onToggle = useCallback(() => {
+ playerRef.current?.toggle();
+ }, [playerRef]);
+
+ return (
+ <button type="button" onClick={onToggle}>
+ {playing ? 'β–Ά' : '❚❚'}
+ </button>
+ );
+};
+
+const TimeDisplay: React.FC<{
+ durationInFrames: number;
+ fps: number;
+ playerRef: React.RefObject<PlayerRef>;
+}> = ({durationInFrames, fps, playerRef}) => {
+ const [time, setTime] = React.useState(0);
+
+ useEffect(() => {
+ const {current} = playerRef;
+ if (!current) {
+ return;
+ }
+
+ const onTimeUpdate = () => {
+ setTime(current.getCurrentFrame());
+ };
+
+ current.addEventListener('frameupdate', onTimeUpdate);
+
+ return () => {
+ current.removeEventListener('frameupdate', onTimeUpdate);
+ };
+ }, [playerRef]);
+
+ return (
+ <div>
+ {formatTime(time / fps)} / {formatTime(durationInFrames / fps)}
+ </div>
+ );
+};
+
+const row: React.CSSProperties = {
+ display: 'flex',
+ flexDirection: 'row',
+};
+
+export const PlayerControls: React.FC<{
+ playerRef: React.RefObject<PlayerRef>;
+ durationInFrames: number;
+ fps: number;
+}> = ({playerRef, durationInFrames, fps}) => {
+ return (
+ <div style={row}>
+ <PlayButton playerRef={playerRef} />
+ <TimeDisplay
+ playerRef={playerRef}
+ durationInFrames={durationInFrames}
+ fps={fps}
+ />
+ <div style={{width: 500, height: 200}}>
+ <PlayerSeekBar
+ durationInFrames={durationInFrames}
+ playerRef={playerRef}
+ inFrame={null}
+ outFrame={null}
+ onSeekEnd={() => undefined}
+ onSeekStart={() => undefined}
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/packages/docs/src/components/Demo/PlayerSeekBar.tsx b/packages/docs/src/components/Demo/PlayerSeekBar.tsx
new file mode 100644
index 0000000000..bd2f8c4a73
--- /dev/null
+++ b/packages/docs/src/components/Demo/PlayerSeekBar.tsx
@@ -0,0 +1,325 @@
+import type {PlayerRef} from '@remotion/player';
+import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import {interpolate} from 'remotion';
+import {useElementSize} from './use-element-size';
+
+const getFrameFromX = (
+ clientX: number,
+ durationInFrames: number,
+ width: number,
+) => {
+ const pos = clientX;
+ const frame = Math.round(
+ interpolate(pos, [0, width], [0, durationInFrames - 1 ?? 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ }),
+ );
+ return frame;
+};
+
+const BAR_HEIGHT = 5;
+const KNOB_SIZE = 12;
+const VERTICAL_PADDING = 4;
+
+const containerStyle: React.CSSProperties = {
+ userSelect: 'none',
+ WebkitUserSelect: 'none',
+ paddingTop: VERTICAL_PADDING,
+ paddingBottom: VERTICAL_PADDING,
+ boxSizing: 'border-box',
+ cursor: 'pointer',
+ position: 'relative',
+ touchAction: 'none',
+};
+
+const barBackground: React.CSSProperties = {
+ height: BAR_HEIGHT,
+ backgroundColor: 'rgba(0, 0, 0, 0.25)',
+ width: '100%',
+ borderRadius: BAR_HEIGHT / 2,
+};
+
+const findBodyInWhichDivIsLocated = (div: HTMLElement) => {
+ let current = div;
+
+ while (current.parentElement) {
+ current = current.parentElement;
+ }
+
+ return current;
+};
+
+export const useHoverState = (
+ ref: React.RefObject<HTMLDivElement>,
+ hideControlsWhenPointerDoesntMove: boolean | number,
+) => {
+ const [hovered, setHovered] = useState(false);
+
+ useEffect(() => {
+ const {current} = ref;
+ if (!current) {
+ return;
+ }
+
+ let hoverTimeout: Timer;
+ const addHoverTimeout = () => {
+ if (hideControlsWhenPointerDoesntMove) {
+ clearTimeout(hoverTimeout);
+ hoverTimeout = setTimeout(
+ () => {
+ setHovered(false);
+ },
+ hideControlsWhenPointerDoesntMove === true
+ ? 3000
+ : hideControlsWhenPointerDoesntMove,
+ );
+ }
+ };
+
+ const onHover = () => {
+ setHovered(true);
+ addHoverTimeout();
+ };
+
+ const onLeave = () => {
+ setHovered(false);
+ clearTimeout(hoverTimeout);
+ };
+
+ const onMove = () => {
+ setHovered(true);
+ addHoverTimeout();
+ };
+
+ current.addEventListener('mouseenter', onHover);
+ current.addEventListener('mouseleave', onLeave);
+ current.addEventListener('mousemove', onMove);
+
+ return () => {
+ current.removeEventListener('mouseenter', onHover);
+ current.removeEventListener('mouseleave', onLeave);
+ current.removeEventListener('mousemove', onMove);
+ clearTimeout(hoverTimeout);
+ };
+ }, [hideControlsWhenPointerDoesntMove, ref]);
+ return hovered;
+};
+
+export const PlayerSeekBar: React.FC<{
+ durationInFrames: number;
+ onSeekStart: () => void;
+ onSeekEnd: () => void;
+ inFrame: number | null;
+ outFrame: number | null;
+ playerRef: React.RefObject<PlayerRef>;
+}> = ({
+ durationInFrames,
+ onSeekEnd,
+ onSeekStart,
+ inFrame,
+ outFrame,
+ playerRef,
+}) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const barHovered = useHoverState(containerRef, false);
+ const size = useElementSize(containerRef, {
+ triggerOnWindowResize: true,
+ shouldApplyCssTransforms: true,
+ });
+ const [playing, setPlaying] = useState(false);
+
+ const [frame, setFrame] = useState(0);
+
+ useEffect(() => {
+ const {current} = playerRef;
+ if (!current) {
+ return;
+ }
+
+ const onFrameUpdate = () => {
+ setFrame(playerRef.current.getCurrentFrame());
+ };
+
+ current.addEventListener('frameupdate', onFrameUpdate);
+
+ return () => {
+ current.removeEventListener('frameupdate', onFrameUpdate);
+ };
+ }, [playerRef]);
+
+ useEffect(() => {
+ const {current} = playerRef;
+ if (!current) {
+ return;
+ }
+
+ const onPlay = () => {
+ setPlaying(true);
+ };
+
+ const onPause = () => {
+ setPlaying(false);
+ };
+
+ current.addEventListener('play', onPlay);
+ current.addEventListener('pause', onPause);
+
+ return () => {
+ current.removeEventListener('play', onPlay);
+ current.removeEventListener('pause', onPause);
+ };
+ }, [playerRef]);
+
+ const [dragging, setDragging] = useState<
+ | {
+ dragging: false;
+ }
+ | {
+ dragging: true;
+ wasPlaying: boolean;
+ }
+ >({
+ dragging: false,
+ });
+
+ const width = size?.width ?? 0;
+
+ const onPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (e.button !== 0) {
+ return;
+ }
+
+ const posLeft = containerRef.current?.getBoundingClientRect()
+ .left as number;
+
+ const _frame = getFrameFromX(
+ e.clientX - posLeft,
+ durationInFrames,
+ width,
+ );
+ playerRef.current.pause();
+ playerRef.current.seekTo(_frame);
+ setDragging({
+ dragging: true,
+ wasPlaying: playing,
+ });
+ onSeekStart();
+ },
+ [durationInFrames, width, playerRef, playing, onSeekStart],
+ );
+
+ const onPointerMove = useCallback(
+ (e: PointerEvent) => {
+ if (!size) {
+ throw new Error('Player has no size');
+ }
+
+ if (!dragging.dragging) {
+ return;
+ }
+
+ const posLeft = containerRef.current?.getBoundingClientRect()
+ .left as number;
+
+ const _frame = getFrameFromX(
+ e.clientX - posLeft,
+ durationInFrames,
+ size.width,
+ );
+ playerRef.current.seekTo(_frame);
+ },
+ [dragging.dragging, durationInFrames, playerRef, size],
+ );
+
+ const onPointerUp = useCallback(() => {
+ setDragging({
+ dragging: false,
+ });
+ if (!dragging.dragging) {
+ return;
+ }
+
+ if (dragging.wasPlaying) {
+ playerRef.current.play();
+ } else {
+ playerRef.current.pause();
+ }
+
+ onSeekEnd();
+ }, [dragging, onSeekEnd, playerRef]);
+
+ useEffect(() => {
+ if (!dragging.dragging) {
+ return;
+ }
+
+ const body = findBodyInWhichDivIsLocated(
+ containerRef.current as HTMLElement,
+ );
+
+ body.addEventListener('pointermove', onPointerMove);
+ body.addEventListener('pointerup', onPointerUp);
+ return () => {
+ body.removeEventListener('pointermove', onPointerMove);
+ body.removeEventListener('pointerup', onPointerUp);
+ };
+ }, [dragging.dragging, onPointerMove, onPointerUp]);
+
+ const knobStyle: React.CSSProperties = useMemo(() => {
+ return {
+ height: KNOB_SIZE,
+ width: KNOB_SIZE,
+ borderRadius: KNOB_SIZE / 2,
+ position: 'absolute',
+ top: VERTICAL_PADDING - KNOB_SIZE / 2 + 5 / 2,
+ backgroundColor: 'black',
+ left: Math.max(
+ 0,
+ (frame / Math.max(1, durationInFrames - 1)) * width - KNOB_SIZE / 2,
+ ),
+ boxShadow: '0 0 2px black',
+ opacity: Number(barHovered),
+ };
+ }, [barHovered, durationInFrames, frame, width]);
+
+ const fillStyle: React.CSSProperties = useMemo(() => {
+ return {
+ height: BAR_HEIGHT,
+ backgroundColor: 'rgba(0, 0, 0, 1)',
+ width: ((frame - (inFrame ?? 0)) / (durationInFrames - 1)) * 100 + '%',
+ marginLeft: ((inFrame ?? 0) / (durationInFrames - 1)) * 100 + '%',
+ borderRadius: BAR_HEIGHT / 2,
+ };
+ }, [durationInFrames, frame, inFrame]);
+
+ const active: React.CSSProperties = useMemo(() => {
+ return {
+ height: BAR_HEIGHT,
+ backgroundColor: 'rgba(255, 255, 255, 0.25)',
+ width:
+ (((outFrame ?? durationInFrames - 1) - (inFrame ?? 0)) /
+ (durationInFrames - 1)) *
+ 100 +
+ '%',
+ marginLeft: ((inFrame ?? 0) / (durationInFrames - 1)) * 100 + '%',
+ borderRadius: BAR_HEIGHT / 2,
+ position: 'absolute',
+ };
+ }, [durationInFrames, inFrame, outFrame]);
+
+ return (
+ <div
+ ref={containerRef}
+ onPointerDown={onPointerDown}
+ style={containerStyle}
+ >
+ <div style={barBackground}>
+ <div style={active} />
+ <div style={fillStyle} />
+ </div>
+ <div style={knobStyle} />
+ </div>
+ );
+};
diff --git a/packages/docs/src/components/Demo/use-element-size.ts b/packages/docs/src/components/Demo/use-element-size.ts
new file mode 100644
index 0000000000..71d12e7ff8
--- /dev/null
+++ b/packages/docs/src/components/Demo/use-element-size.ts
@@ -0,0 +1,178 @@
+import {useCallback, useEffect, useMemo, useState} from 'react';
+
+export type Size = {
+ width: number;
+ height: number;
+ left: number;
+ top: number;
+ windowSize: {
+ width: number;
+ height: number;
+ };
+ refresh: () => void;
+};
+
+// If a pane has been moved, it will cause a layout shift without
+// the window having been resized. Those UI elements can call this API to
+// force an update
+
+type ElementSizeForceUpdate = () => void;
+
+let elementSizeHooks: ElementSizeForceUpdate[] = [];
+
+export const updateAllElementsSizes = () => {
+ for (const listener of elementSizeHooks) {
+ listener();
+ }
+};
+
+export const useElementSize = (
+ ref: React.RefObject<HTMLElement>,
+ options: {
+ triggerOnWindowResize: boolean;
+ shouldApplyCssTransforms: boolean;
+ },
+): Size | null => {
+ const [size, setSize] = useState<Omit<Size, 'refresh'> | null>(() => {
+ if (!ref.current) {
+ return null;
+ }
+
+ const rect = ref.current.getClientRects();
+ if (!rect[0]) {
+ return null;
+ }
+
+ return {
+ width: rect[0].width as number,
+ height: rect[0].height as number,
+ left: rect[0].x as number,
+ top: rect[0].y as number,
+ windowSize: {
+ height: window.innerHeight,
+ width: window.innerWidth,
+ },
+ };
+ });
+
+ const observer = useMemo(() => {
+ if (typeof ResizeObserver === 'undefined') {
+ return null;
+ }
+
+ return new ResizeObserver((entries) => {
+ // The contentRect returns the width without any `scale()`'s being applied. The height is wrong
+ const {contentRect, target} = entries[0];
+ // The clientRect returns the size with `scale()` being applied.
+ const newSize = target.getClientRects();
+
+ if (!newSize?.[0]) {
+ setSize(null);
+ return;
+ }
+
+ const probableCssParentScale =
+ contentRect.width === 0 ? 1 : newSize[0].width / contentRect.width;
+
+ const width = options.shouldApplyCssTransforms
+ ? newSize[0].width
+ : newSize[0].width * (1 / probableCssParentScale);
+ const height = options.shouldApplyCssTransforms
+ ? newSize[0].height
+ : newSize[0].height * (1 / probableCssParentScale);
+
+ setSize({
+ width,
+ height,
+ left: newSize[0].x,
+ top: newSize[0].y,
+ windowSize: {
+ height: window.innerHeight,
+ width: window.innerWidth,
+ },
+ });
+ });
+ }, [options.shouldApplyCssTransforms]);
+
+ const updateSize = useCallback(() => {
+ if (!ref.current) {
+ return;
+ }
+
+ const rect = ref.current.getClientRects();
+ if (!rect[0]) {
+ setSize(null);
+ return;
+ }
+
+ setSize((prevState) => {
+ const isSame =
+ prevState &&
+ prevState.width === rect[0].width &&
+ prevState.height === rect[0].height &&
+ prevState.left === rect[0].x &&
+ prevState.top === rect[0].y &&
+ prevState.windowSize.height === window.innerHeight &&
+ prevState.windowSize.width === window.innerWidth;
+ if (isSame) {
+ return prevState;
+ }
+
+ return {
+ width: rect[0].width as number,
+ height: rect[0].height as number,
+ left: rect[0].x as number,
+ top: rect[0].y as number,
+ windowSize: {
+ height: window.innerHeight,
+ width: window.innerWidth,
+ },
+ };
+ });
+ }, [ref]);
+
+ useEffect(() => {
+ if (!observer) {
+ return;
+ }
+
+ const {current} = ref;
+ if (current) {
+ observer.observe(current);
+ }
+
+ return (): void => {
+ if (current) {
+ observer.unobserve(current);
+ }
+ };
+ }, [observer, ref, updateSize]);
+
+ useEffect(() => {
+ if (!options.triggerOnWindowResize) {
+ return;
+ }
+
+ window.addEventListener('resize', updateSize);
+
+ return () => {
+ window.removeEventListener('resize', updateSize);
+ };
+ }, [options.triggerOnWindowResize, updateSize]);
+
+ useEffect(() => {
+ elementSizeHooks.push(updateSize);
+
+ return () => {
+ elementSizeHooks = elementSizeHooks.filter((e) => e !== updateSize);
+ };
+ }, [updateSize]);
+
+ return useMemo(() => {
+ if (!size) {
+ return null;
+ }
+
+ return {...size, refresh: updateSize};
+ }, [size, updateSize]);
+};