🎥 Make videos programmatically with React
alright
JonnyBurgerf30dad55c65c
diff --git a/packages/convert/app/components/AlternativePickFileOptions.tsx b/packages/convert/app/components/AlternativePickFileOptions.tsxindex d1228b8e1a..9d4d267137 100644--- a/packages/convert/app/components/AlternativePickFileOptions.tsx+++ b/packages/convert/app/components/AlternativePickFileOptions.tsx@@ -1,6 +1,5 @@import React from 'react';import {LoadFromUrl} from './LoadFromUrl';-import {LoadFromX} from './LoadFromX';export const AlternativePickFileOptions: React.FC<{readonly onSampleFile: () => void;@@ -15,8 +14,6 @@ export const AlternativePickFileOptions: React.FC<{</a><div className="w-4" /><LoadFromUrl />- <div className="w-4" />- <LoadFromX /></div>);};diff --git a/packages/convert/app/components/ConvertProgress.tsx b/packages/convert/app/components/ConvertProgress.tsxindex 29b6fd3a16..ab8d4268e4 100644--- a/packages/convert/app/components/ConvertProgress.tsx+++ b/packages/convert/app/components/ConvertProgress.tsx@@ -1,12 +1,10 @@-import type {- ConvertMediaContainer,- ConvertMediaProgress,-} from '@remotion/webcodecs';+import type {ConvertMediaContainer} from '@remotion/webcodecs';import React, {createRef} from 'react';import {formatBytes} from '~/lib/format-bytes';import {formatElapsedTime} from '~/lib/format-elapsed-time';import {formatSeconds} from '~/lib/format-seconds';import {getNewName} from '~/lib/generate-new-name';+import type {ConvertProgressType} from '~/lib/progress';import {useAddOutputFilenameToTitle,useAddProgressToTitle,@@ -20,7 +18,7 @@ import {VideoThumbnail} from './VideoThumbnail';export const convertProgressRef = createRef<VideoThumbnailRef>();export const ConvertProgress: React.FC<{- readonly state: ConvertMediaProgress;+ readonly state: ConvertProgressType;readonly name: string | null;readonly container: ConvertMediaContainer;readonly done: boolean;@@ -42,11 +40,7 @@ export const ConvertProgress: React.FC<{startTime,completedTime,}) => {- const progress = done- ? 1- : duration === null- ? null- : state.millisecondsWritten / 1000 / duration;+ const progress = done ? 1 : state.overallProgress;useAddProgressToTitle(progress);const newName = name ? getNewName(name, container) : null;diff --git a/packages/convert/app/components/ConvertUi.tsx b/packages/convert/app/components/ConvertUi.tsxindex fe95b41324..1845deb15e 100644--- a/packages/convert/app/components/ConvertUi.tsx+++ b/packages/convert/app/components/ConvertUi.tsx@@ -3,41 +3,35 @@ import type {M3uStream,MediaParserAudioCodec,MediaParserContainer,- MediaParserController,MediaParserDimensions,- MediaParserLogLevel,MediaParserTrack,MediaParserVideoCodec,} from '@remotion/media-parser';+import type {ResizeOperation, WebCodecsController} from '@remotion/webcodecs';+import {webcodecsController, WebCodecsInternals} from '@remotion/webcodecs';+import type {Rotation} from 'mediabunny';import {- defaultSelectM3uAssociatedPlaylists,- hasBeenAborted,- MediaParserInternals,-} from '@remotion/media-parser';-import type {- ConvertMediaContainer,- ResizeOperation,- WebCodecsController,-} from '@remotion/webcodecs';-import {- convertMedia,- webcodecsController,- WebCodecsInternals,-} from '@remotion/webcodecs';+ ALL_FORMATS,+ BlobSource,+ BufferTarget,+ Conversion,+ Input,+ Output,+ UrlSource,+} from 'mediabunny';import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';import {canRotateOrMirror} from '~/lib/can-rotate-or-mirror';import type {ConvertState, Source} from '~/lib/convert-state';import type {ConvertSections, RotateOrMirrorState} from '~/lib/default-ui';import {getOrderOfSections, isConvertEnabledByDefault} from '~/lib/default-ui';-import {- getActualAudioConfigIndex,- getActualVideoOperation,-} from '~/lib/get-audio-video-config-index';+import {getActualVideoOperation} from '~/lib/get-audio-video-config-index';import {getInitialResizeSuggestion} from '~/lib/get-initial-resize-suggestion';import {isReencoding} from '~/lib/is-reencoding';import {isSubmitDisabled} from '~/lib/is-submit-enabled';+import {getMediabunnyOutput} from '~/lib/output-container';+import type {ConvertProgressType} from '~/lib/progress';import {makeWaveformVisualizer} from '~/lib/waveform-visualizer';-import type {RouteAction} from '~/seo';+import type {OutputContainer, RouteAction} from '~/seo';import {ConversionDone} from './ConversionDone';import {ConvertForm} from './ConvertForm';import {ConvertProgress, convertProgressRef} from './ConvertProgress';@@ -61,8 +55,6 @@ const ConvertUI = ({tracks,setSrc,durationInSeconds,- fps,- logLevel,action,enableRotateOrMirror,setEnableRotateOrMirror,@@ -78,7 +70,6 @@ const ConvertUI = ({rotation,dimensions,m3uStreams,- probeController,sampleRate,}: {readonly src: Source;@@ -93,7 +84,6 @@ const ConvertUI = ({readonly fps: number | null;readonly rotation: number | null;readonly inputContainer: MediaParserContainer | null;- readonly logLevel: MediaParserLogLevel;readonly m3uStreams: M3uStream[] | null;readonly action: RouteAction;readonly enableRotateOrMirror: RotateOrMirrorState;@@ -106,10 +96,9 @@ const ConvertUI = ({readonly flipVertical: boolean;readonly setFlipHorizontal: React.Dispatch<React.SetStateAction<boolean>>;readonly setFlipVertical: React.Dispatch<React.SetStateAction<boolean>>;- readonly probeController: MediaParserController;readonly sampleRate: number | null;}) => {- const [outputContainer, setContainer] = useState<ConvertMediaContainer>(() =>+ const [outputContainer, setContainer] = useState<OutputContainer>(() =>getDefaultContainerForConversion(src, action),);const [videoOperationSelection, setVideoOperationKey] = useState<@@ -119,7 +108,8 @@ const ConvertUI = ({Record<number, string>>({});const [state, setState] = useState<ConvertState>({type: 'idle'});- const [name, setName] = useState<string | null>(null);+ // TODO: Set name+ const [name] = useState<string | null>(null);const [selectedM3uId, setSelectedM3uId] = useState<number | null>(null);const [selectAssociatedPlaylistId, setSelectedAssociatedPlaylistId] =useState<number | null>(null);@@ -209,25 +199,47 @@ const ConvertUI = ({const controller = webcodecsController();controllerRef.current = controller;- let videoFrames = 0;+ const progress: ConvertProgressType = {+ bytesWritten: 0,+ millisecondsWritten: 0,+ overallProgress: 0,+ };+const waveform = makeWaveformVisualizer({onWaveformBars,});- if (durationInSeconds) {- waveform.setDuration(durationInSeconds);- }- const startTime = Date.now();+ const input = new Input({+ formats: ALL_FORMATS,+ source:+ src.type === 'file' ? new BlobSource(src.file) : new UrlSource(src.url),+ });++ const output = new Output({+ format: getMediabunnyOutput(outputContainer),+ // TODO: File System API+ target: new BufferTarget(),+ });++ let cancelConversion = () => {};++ const run = async () => {+ // TODO: .setName()++ const duration = await input.computeDuration();+ waveform.setDuration(duration);++ let videoFrames = 0;++ const startTime = Date.now();- probeController- .getSeekingHints()- .then((seekingHints) => {- return convertMedia({- src: src.type === 'url' ? src.url : src.file,- seekingHints,- onVideoFrame: ({frame}) => {+ const conversion = await Conversion.init({+ input,+ output,+ video: {+ process(sample) {const flipped = flipVideoFrame({- frame,+ frame: sample.toVideoFrame(),horizontal: flipHorizontal && enableRotateOrMirror === 'mirror',vertical: flipVertical && enableRotateOrMirror === 'mirror',});@@ -235,137 +247,75 @@ const ConvertUI = ({convertProgressRef.current?.draw(flipped);}+ progress.millisecondsWritten = sample.timestamp * 1000;+videoFrames++;return flipped;},- onAudioData: ({audioData}) => {- waveform.add(audioData);- return audioData;- },- expectedDurationInSeconds: durationInSeconds,- expectedFrameRate: fps,- rotate: userRotation,- logLevel,- onProgress: (s) => {- setState({- type: 'in-progress',- controller,- state: s,- startTime,- });- },- container: outputContainer,- controller,- fields: {- name: true,- },- onName: (n) => {- setName(n);- },- onAudioTrack: ({track}) => {- const options = supportedConfigs?.audioTrackOptions.find((trk) => {- return trk.trackId === track.trackId;- });- if (!options) {- throw new Error('Found no options for audio track');- }-- const operation = getActualAudioConfigIndex({- enableConvert,- audioConfigIndexSelection: audioOperationSelection,- trackNumber: track.trackId,- operations: options.operations,- });-- MediaParserInternals.Log.info(- 'info',- `Selected operation for audio track ${track.trackId}`,- operation,- );-- return operation;+ rotate: userRotation as Rotation,+ // TODO: Support resize+ // TODO: Support discard+ // TODO: Support force transcode+ },+ audio: {+ process(sample) {+ // TODO: Only do this if it is an audio-only conversion+ waveform.add(sample.toAudioBuffer());++ return sample;},- onVideoTrack: ({track}) => {- const options = supportedConfigs?.videoTrackOptions.find((trk) => {- return trk.trackId === track.trackId;- });- if (!options) {- throw new Error('Found no options for video track');- }+ },+ });- const operation = getActualVideoOperation({- enableConvert,- videoConfigIndexSelection: videoOperationSelection,- trackNumber: track.trackId,- operations: options.operations,- });+ cancelConversion = () => {+ conversion.cancel();+ };- MediaParserInternals.Log.info(- 'info',- `Selected operation for video track ${track.trackId}`,- operation,- );- return operation;- },- selectM3uStream: ({streams}) => {- return selectedM3uId ?? streams[0].id;- },- selectM3uAssociatedPlaylists: ({associatedPlaylists}) => {- if (selectAssociatedPlaylistId === null) {- return defaultSelectM3uAssociatedPlaylists({associatedPlaylists});- }+ if (input.disposed) {+ throw new Error('Input disposed');+ }- return associatedPlaylists.filter(- (playlist) => selectAssociatedPlaylistId === playlist.id,- );- },- // Remotion team can see usage on https://www.remotion.pro/projects/remotiondevconvert/- apiKey: 'rm_pub_9a996d341238eaa34e696b099968d8510420b9f6ba4aa0ee',- });- })+ conversion.onProgress = (newProg) => {+ progress.overallProgress = newProg;+ progress.bytesWritten = output.target.buffer?.byteLength ?? 0;- .then(({save, finalState}) => {- const completedTime = Date.now();setState({- type: 'done',- download: save,- state: finalState,+ type: 'in-progress',+ controller,+ state: progress,startTime,- completedTime,});- })- .catch((e) => {- if (hasBeenAborted(e)) {- setState({type: 'idle'});- return;- }-- MediaParserInternals.Log.error(logLevel, e);- setState({type: 'error', error: e as Error});+ };++ await conversion.execute();++ setState({+ type: 'done',+ download: () => {+ // TODO: Download+ return Promise.resolve(new Blob());+ },+ state: progress,+ startTime,+ completedTime: Date.now(),});+ };++ run();++ // TODO: Check if aborted, special errorreturn () => {- controller.abort();+ cancelConversion();};}, [+ enableRotateOrMirror,+ flipHorizontal,+ flipVertical,onWaveformBars,- durationInSeconds,- fps,+ outputContainer,src,userRotation,- logLevel,- outputContainer,- flipHorizontal,- enableRotateOrMirror,- flipVertical,- supportedConfigs?.audioTrackOptions,- supportedConfigs?.videoTrackOptions,- enableConvert,- audioOperationSelection,- videoOperationSelection,- selectedM3uId,- selectAssociatedPlaylistId,- probeController,]);const dimissError = useCallback(() => {diff --git a/packages/convert/app/components/FileAvailable.tsx b/packages/convert/app/components/FileAvailable.tsxindex 48e0978ea5..d27e95cef3 100644--- a/packages/convert/app/components/FileAvailable.tsx+++ b/packages/convert/app/components/FileAvailable.tsx@@ -106,7 +106,6 @@ export const FileAvailable: React.FC<{dimensions={probeResult.dimensions}durationInSeconds={probeResult.durationInSeconds ?? null}fps={probeResult.fps ?? null}- logLevel="verbose"action={routeAction}enableRotateOrMirror={enableRotateOrMirrow}setEnableRotateOrMirror={setEnableRotateOrMirror}@@ -118,7 +117,6 @@ export const FileAvailable: React.FC<{setFlipVertical={setFlipVertical}videoThumbnailRef={videoThumbnailRef}rotation={probeResult.rotation}- probeController={probeResult.controller}sampleRate={probeResult.sampleRate}/></div>diff --git a/packages/convert/app/components/LoadFromX.tsx b/packages/convert/app/components/LoadFromX.tsxdeleted file mode 100644index 2b9cf62f13..0000000000--- a/packages/convert/app/components/LoadFromX.tsx+++ /dev/null@@ -1,118 +0,0 @@-import React, {useCallback, useMemo} from 'react';-import {extractTweetId} from '~/lib/extract-tweet-id';-import {Button} from './ui/button';-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from './ui/dialog';-import {Input} from './ui/input';--export const LoadFromX: React.FC = () => {- const [open, setOpen] = React.useState(false);- const [value, setValue] = React.useState('');- const [loading, setLoading] = React.useState(false);- const [error, setError] = React.useState<string | null>(null);-- const onOpenChange = React.useCallback(() => {- setOpen((prev) => !prev);- setError(null);- }, []);-- const isValid = useMemo(() => {- try {- return extractTweetId(value) !== null;- } catch {- return false;- }- }, [value]);-- const onOpenUrl = React.useCallback(() => {- setOpen(true);- }, []);-- const set = useCallback(async () => {- setLoading(true);- setError(null);- try {- const res = await fetch(- 'https://lzpqleuj7axkrgoxsa3h7ecynq0vveim.lambda-url.eu-central-1.on.aws/?id=' +- extractTweetId(value),- );- const json = await res.json();- if (json.type !== 'success') {- setError(json.error || 'Failed to load from X');- return;- }-- const urls = json.urls as string[];- if (!urls.length) {- setError('No videos found in this post');- return;- }-- const [firstUrl] = urls;- const currentUrl = new URL(window.location.href);- currentUrl.searchParams.set('url', firstUrl);-- window.location.href = currentUrl.toString();- } catch {- setError('An unexpected error occurred');- } finally {- setLoading(false);- }- }, [value]);-- const onKeydown = useCallback(- (e: React.KeyboardEvent<HTMLInputElement>) => {- if (!isValid || loading) {- return;- }-- if (e.key === 'Enter') {- set();- }- },- [isValid, loading, set],- );-- return (- <>- <a- className="font-brand text-brand cursor cursor-pointer hover:underline"- onClick={onOpenUrl}- >- Load from x.com- </a>- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle className="font-brand">Load from x.com</DialogTitle>- <div className="h-1" />- <DialogDescription>- Enter a post URL to load a video from x.com.- </DialogDescription>- <div className="h-2" />- <Input- onKeyDown={onKeydown}- value={value}- onChange={(e) => setValue(e.target.value)}- placeholder="For example: https://x.com/JNYBGR/status/1859650265021817143"- />- {error && <p className="text-red-500 text-sm mt-2">{error}</p>}- <div className="h-2" />- <Button- disabled={!isValid || loading}- variant="brand"- onClick={set}- >- {loading ? 'Loading...' : 'Load'}- </Button>- </DialogHeader>- </DialogContent>- </Dialog>- </>- );-};diff --git a/packages/convert/app/components/tests/RunAll.tsx b/packages/convert/app/components/tests/RunAll.tsxdeleted file mode 100644index ee83da5f53..0000000000--- a/packages/convert/app/components/tests/RunAll.tsx+++ /dev/null@@ -1,21 +0,0 @@-import {useCallback} from 'react';-import type {TestStructure} from '~/tests/test-structure';-import {Button} from '../ui/button';--export const RunAll: React.FC<{- tests: TestStructure[];-}> = ({tests}) => {- const runTests = useCallback(async () => {- for (const test of tests) {- await test.run();- }- }, [tests]);-- return (- <div className="flex flex-row items-center justify-center font-bold font-brand">- <div className="text-2xl">@remotion/webcodecs Tests</div>- <div className="flex-1" />- <Button onClick={runTests}>Run all</Button>- </div>- );-};diff --git a/packages/convert/app/components/tests/TestStateDisplay.tsx b/packages/convert/app/components/tests/TestStateDisplay.tsxdeleted file mode 100644index d7676b76eb..0000000000--- a/packages/convert/app/components/tests/TestStateDisplay.tsx+++ /dev/null@@ -1,37 +0,0 @@-import {formatSeconds} from '~/lib/format-seconds';-import type {TestState} from '~/tests/test-structure';-import {ErrorState} from '../ErrorState';--export const TestStateDisplay: React.FC<{- testState: TestState;-}> = ({testState}) => {- if (testState.type === 'succeeded') {- return (- <div className="text-green-700 text-sm font-bold">- Succeeded in {testState.timeInMilliseconds}ms- </div>- );- }-- if (testState.type === 'failed') {- return (- <div className="text-red-500 text-sm w-full font-bold overflow-x-hidden">- <ErrorState error={testState.error} />- </div>- );- }-- if (testState.type === 'running') {- if (testState.state) {- return (- <div className="text-sm">- {formatSeconds(testState.state.millisecondsWritten / 1000)}- </div>- );- }-- return <div className="text-sm">Running...</div>;- }-- return null;-};diff --git a/packages/convert/app/lib/convert-state.ts b/packages/convert/app/lib/convert-state.tsindex ab29222d06..427528b174 100644--- a/packages/convert/app/lib/convert-state.ts+++ b/packages/convert/app/lib/convert-state.ts@@ -1,7 +1,5 @@-import type {- ConvertMediaProgress,- WebCodecsController,-} from '@remotion/webcodecs';+import type {WebCodecsController} from '@remotion/webcodecs';+import type {ConvertProgressType} from './progress';export type Source =| {@@ -20,13 +18,13 @@ export type ConvertState =| {type: 'in-progress';controller: WebCodecsController;- state: ConvertMediaProgress;+ state: ConvertProgressType;startTime: number;}| {type: 'done';download: () => Promise<Blob>;- state: ConvertMediaProgress;+ state: ConvertProgressType;startTime: number;completedTime: number;}diff --git a/packages/convert/app/lib/output-container.ts b/packages/convert/app/lib/output-container.tsnew file mode 100644index 0000000000..5f755ea94d--- /dev/null+++ b/packages/convert/app/lib/output-container.ts@@ -0,0 +1,34 @@+import {Mp4OutputFormat, WavOutputFormat, WebMOutputFormat} from 'mediabunny';+import type {OutputContainer} from '~/seo';++export const getMediabunnyOutput = (container: OutputContainer) => {+ if (container === 'mp4') {+ return new Mp4OutputFormat();+ }++ if (container === 'webm') {+ return new WebMOutputFormat();+ }++ if (container === 'wav') {+ return new WavOutputFormat();+ }++ throw new Error('Unsupported mime type: ' + container);+};++export const getExtension = (container: OutputContainer) => {+ if (container === 'mp4') {+ return 'mp4';+ }++ if (container === 'webm') {+ return 'webm';+ }++ if (container === 'wav') {+ return 'wav';+ }++ throw new Error('Unsupported container: ' + container);+};diff --git a/packages/convert/app/lib/progress.ts b/packages/convert/app/lib/progress.tsnew file mode 100644index 0000000000..c98e16b527--- /dev/null+++ b/packages/convert/app/lib/progress.ts@@ -0,0 +1,5 @@+export type ConvertProgressType = {+ overallProgress: number;+ bytesWritten: number;+ millisecondsWritten: number;+};diff --git a/packages/convert/app/routes/test._index.tsx b/packages/convert/app/routes/test._index.tsxdeleted file mode 100644index 986c80980c..0000000000--- a/packages/convert/app/routes/test._index.tsx+++ /dev/null@@ -1,19 +0,0 @@-import React from 'react';-import {RunAll} from '~/components/tests/RunAll';-import {testList} from '~/tests/test-list';-import {TestComponent} from '~/tests/TestComponent';--const TestSuite: React.FC = () => {- return (- <div className="bg-slate-50 min-h-screen w-screen">- <div className="w-full max-w-[900px] pt-16 m-auto gap-4 flex flex-col px-5 pb-20">- <RunAll tests={testList} />- {testList.map((t) => {- return <TestComponent key={t.name} test={t} />;- })}- </div>- </div>- );-};--export default TestSuite;diff --git a/packages/convert/app/seo.ts b/packages/convert/app/seo.tsindex 01e74b2732..cde089f94e 100644--- a/packages/convert/app/seo.ts+++ b/packages/convert/app/seo.ts@@ -1,10 +1,11 @@import type {MediaParserContainer} from '@remotion/media-parser';import type {ConvertMediaContainer} from '@remotion/webcodecs';-import {getAvailableContainers} from '@remotion/webcodecs';import {renderHumanReadableContainer} from './lib/render-codec-label';export const inputContainers: MediaParserContainer[] = ['mp4', 'webm', 'avi'];-export const outputContainers = getAvailableContainers();+export const outputContainers = ['mp4', 'webm', 'wav'] as const;++export type OutputContainer = (typeof outputContainers)[number];export const parseConvertRouteAction = (action: string) => {const split = action.split('-to-');diff --git a/packages/convert/app/tests/TestComponent.tsx b/packages/convert/app/tests/TestComponent.tsxdeleted file mode 100644index c7f429f9f0..0000000000--- a/packages/convert/app/tests/TestComponent.tsx+++ /dev/null@@ -1,37 +0,0 @@-import {Link} from '@remix-run/react';-import React from 'react';-import {TestStateDisplay} from '~/components/tests/TestStateDisplay';-import {Button} from '~/components/ui/button';-import type {TestStructure} from './test-structure';-import {useTest} from './test-structure';--export const TestComponent: React.FC<{- readonly test: TestStructure;-}> = ({test}) => {- const {state, run} = useTest(test);-- return (- <div className="border-black rounded border-2 p-4 bg-white">- <div className="flex flex-row">- <div>- <div className="font-brand font-bold text-xl">- {test.name}{' '}- <Link- className="text-brand font-brand text-sm font-medium"- to={`/convert?url=${encodeURIComponent(test.src)}`}- >- Try in UI- </Link>- </div>- <div className="w-full overflow-x-auto">- <TestStateDisplay testState={state} />- </div>- </div>- <div className="flex-1" />- {state.type === 'not-run' ? (- <Button onClick={run}>Run test</Button>- ) : null}- </div>- </div>- );-};diff --git a/packages/convert/app/tests/test-list.tsx b/packages/convert/app/tests/test-list.tsxdeleted file mode 100644index 14d7d1bc74..0000000000--- a/packages/convert/app/tests/test-list.tsx+++ /dev/null@@ -1,308 +0,0 @@-import {convertMedia} from '@remotion/webcodecs';-import {flipVideoFrame} from '~/components/flip-video';-import type {TestStructure} from './test-structure';-import {addTestWatcher, isSafari, makeProgressReporter} from './test-structure';--const basicMp4ToWebM = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/bigbuckbunny.mp4';-- return addTestWatcher({- name: 'Basic MP4 to WebM',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const av1WebmToMp4 = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/av1-bbb.webm';-- return addTestWatcher({- name: 'AV1 WebM to MP4',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'mp4',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const av1WebmToMp4H265 = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/av1-bbb.webm';-- return addTestWatcher({- name: 'AV1 WebM to MP4 (H.265)',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'mp4',- videoCodec: 'h265',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const weirdMp4aConfig = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/riverside.mp4';-- return addTestWatcher({- name: 'weird mp4a config',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- audioCodec: 'opus',- videoCodec: 'vp8',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const convertToWav = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/riverside.mp4';-- return addTestWatcher({- name: 'convert to wav',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'wav',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const lpcmLivePhoto = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/livephoto-lpcm-audio.mov';- return addTestWatcher({- name: 'HEVC Live Photo + LPCM audio codec',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const aviToMp4ReEncode = (): TestStructure => {- const src = 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/example.avi';- return addTestWatcher({- name: 'AVI to MP4 (Re-Encode)',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'mp4',- onProgress: makeProgressReporter(onUpdate),- onVideoTrack: () => {- return {type: 'reencode', videoCodec: 'h264'};- },- onAudioTrack: () => {- if (isSafari()) {- return {- type: 'drop',- };- }-- return {- type: 'reencode',- audioCodec: 'aac',- bitrate: 128000,- sampleRate: null,- };- },- });- },- });-};--const aviToMp4 = (): TestStructure => {- const src = 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/example.avi';- return addTestWatcher({- name: 'AVI to MP4',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'mp4',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const rotatedVideo = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/iphone-hevc.mov';-- return addTestWatcher({- name: 'Rotated video',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const vpxEncodingError = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/vpx-encoding-error.mp4';- return addTestWatcher({- name: 'Flipping a video',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- onProgress: makeProgressReporter(onUpdate),- onVideoFrame: ({frame}) => {- return flipVideoFrame({frame, horizontal: true, vertical: false});- },- });- },- });-};--const offsetTimestamps = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/very-offset-timestamps.mp4';-- return addTestWatcher({- name: 'Convert a video with offset video and audio timestamps',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const transportStream = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/transportstream.ts';-- return addTestWatcher({- name: 'Convert a .ts file to .webm',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const remuxUnevenDim = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/unevendim.webm';-- return addTestWatcher({- name: 'Remux uneven dim',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- onAudioTrack: () => {- return {type: 'copy'};- },- onVideoCodec: () => {- return {type: 'copy'};- },- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const remuxToughTimestamps = (): TestStructure => {- const src =- 'https://pub-646d808d9cb240cea53bedc76dd3cd0c.r2.dev/tough-timestamps.mp4';-- return addTestWatcher({- name: 'Resize Recorder WebM with tough timestamps',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'webm',- resize: {- maxHeight: 1080,- mode: 'max-height',- },- onAudioTrack: () => {- return {type: 'copy'};- },- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--const tsWithSmallAudioOnEend = (): TestStructure => {- const src =- 'https://test-streams.mux.dev/x36xhzz/url_0/url_525/193039199_mp4_h264_aac_hd_7.ts';-- return addTestWatcher({- name: '.ts with 16 Byte audio sample at the end',- src,- async execute(onUpdate) {- await convertMedia({- src,- container: 'mp4',- onVideoTrack: () => ({type: 'drop'}),- onProgress: makeProgressReporter(onUpdate),- });- },- });-};--export const testList: TestStructure[] = [- basicMp4ToWebM(),- av1WebmToMp4(),- aviToMp4(),- aviToMp4ReEncode(),- av1WebmToMp4H265(),- convertToWav(),- weirdMp4aConfig(),- rotatedVideo(),- lpcmLivePhoto(),- vpxEncodingError(),- offsetTimestamps(),- transportStream(),- remuxUnevenDim(),- remuxToughTimestamps(),- tsWithSmallAudioOnEend(),-];diff --git a/packages/convert/app/tests/test-structure.ts b/packages/convert/app/tests/test-structure.tsdeleted file mode 100644index 320d870a51..0000000000--- a/packages/convert/app/tests/test-structure.ts+++ /dev/null@@ -1,100 +0,0 @@-import type {- ConvertMediaOnProgress,- ConvertMediaProgress,-} from '@remotion/webcodecs';-import React from 'react';--export type TestState =- | {- type: 'not-run';- }- | {- type: 'running';- state: ConvertMediaProgress | null;- }- | {- type: 'failed';- error: Error;- }- | {- type: 'succeeded';- timeInMilliseconds: number;- };--type TestUpdater = (up: TestState) => void;--export const makeProgressReporter = (- testUpdater: TestUpdater,-): ConvertMediaOnProgress => {- return (progress) => {- testUpdater({- type: 'running',- state: progress,- });- };-};--export type TestStructure = {- name: string;- execute: (onUpdate: (up: TestState) => void) => Promise<void>;- run: () => Promise<void>;- watchState: (cb: (state: TestState) => void) => void;- src: string;-};--export const addTestWatcher = (- test: Omit<TestStructure, 'watchState' | 'run'>,-): TestStructure => {- const watchers = new Set<(state: TestState) => void>();-- return {- ...test,- watchState: (cb) => {- watchers.add(cb);- },- async run() {- try {- const startTime = Date.now();- for (const watcher of watchers) {- watcher({type: 'running', state: null});- }-- await test.execute((stateUpdate) => {- for (const watcher of watchers) {- watcher(stateUpdate);- }- });- for (const watcher of watchers) {- watcher({- type: 'succeeded',- timeInMilliseconds: Date.now() - startTime,- });- }- } catch (e) {- for (const watcher of watchers) {- watcher({type: 'failed', error: e as Error});- }- }- },- };-};--export const useTest = (test: TestStructure) => {- const [state, setState] = React.useState<TestState>({type: 'not-run'});-- React.useEffect(() => {- test.watchState((up) => {- setState(up);- });- }, [test]);-- const run = React.useCallback(async () => {- await test.run();- }, [test]);-- return {state, run};-};--export const isSafari = () => {- return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);-};