Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ts-sdk] Add Blob as MP4 input #1007

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions ts/examples/vite-example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import WhipExample from './examples/WhipExample';
import DemoExample from './examples/Demo';
import MultipleOutputs from './examples/MultipleOutputs';
import MediaStreamInput from './examples/MediaStreamExample';
import UploadMp4Example from './examples/UploadMp4Example';

setWasmBundleUrl('/assets/smelter.wasm');

Expand All @@ -25,6 +26,7 @@ function App() {
camera: <Camera />,
screenCapture: <ScreenCapture />,
mediaStream: <MediaStreamInput />,
uploadMp4: <UploadMp4Example />,
home: <Home />,
demo: <DemoExample />,
};
Expand All @@ -49,6 +51,7 @@ function App() {
<button onClick={() => setCurrentExample('camera')}>Camera</button>
<button onClick={() => setCurrentExample('screenCapture')}>Screen Capture</button>
<button onClick={() => setCurrentExample('mediaStream')}>MediaStream</button>
<button onClick={() => setCurrentExample('uploadMp4')}>Upload MP4</button>

<h3>Smelter rendering engine examples</h3>
<button onClick={() => setCurrentExample('counter')}>Counter</button>
Expand Down
38 changes: 10 additions & 28 deletions ts/examples/vite-example/src/components/SmelterVideo.tsx
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was not used by any example, but MultipleOutputs had pretty much the same implementation so I put everything here

Original file line number Diff line number Diff line change
@@ -1,36 +1,32 @@
import React, { useCallback, useEffect, useState } from 'react';
import Smelter from '@swmansion/smelter-web-wasm';
import React, { useCallback } from 'react';
import type Smelter from '@swmansion/smelter-web-wasm';

type VideoProps = React.DetailedHTMLProps<
React.VideoHTMLAttributes<HTMLVideoElement>,
HTMLVideoElement
>;

type CompositorVideoProps = {
onVideoCreate?: (smelter: Smelter) => Promise<void>;
onVideoStarted?: (smelter: Smelter) => Promise<void>;
outputId: string;
onVideoCreated?: (smelter: Smelter) => Promise<void>;
smelter: Smelter;
children: React.ReactElement;
} & VideoProps;

export default function CompositorVideo(props: CompositorVideoProps) {
const { onVideoCreate, onVideoStarted, children, ...videoProps } = props;
const [smelter, setSmelter] = useState<Smelter | undefined>(undefined);
const { outputId, onVideoCreated, children, smelter, ...videoProps } = props;

const videoRef = useCallback(
async (video: HTMLVideoElement | null) => {
if (!video) {
return;
}

const smelter = new Smelter({});

await smelter.init();

if (onVideoCreate) {
await onVideoCreate(smelter);
if (onVideoCreated) {
await onVideoCreated(smelter);
}

const { stream } = await smelter.registerOutput('output', children, {
const { stream } = await smelter.registerOutput(outputId, children, {
type: 'stream',
video: {
resolution: {
Expand All @@ -41,27 +37,13 @@ export default function CompositorVideo(props: CompositorVideoProps) {
audio: true,
});

await smelter.start();
setSmelter(smelter);

if (onVideoStarted) {
await onVideoStarted(smelter);
}
if (stream) {
video.srcObject = stream;
await video.play();
}
},
[onVideoCreate, onVideoStarted, videoProps.width, videoProps.height, children]
[onVideoCreated, videoProps.width, videoProps.height, smelter, outputId]
);

useEffect(() => {
return () => {
if (smelter) {
void smelter.terminate();
}
};
}, [smelter]);

return <video ref={videoRef} {...videoProps} />;
}
51 changes: 2 additions & 49 deletions ts/examples/vite-example/src/examples/MultipleOutputs.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { useCallback, useEffect, useState } from 'react';
import { useEffect, useState } from 'react';
import Smelter from '@swmansion/smelter-web-wasm';
import { InputStream, Rescaler, Text, Tiles, useInputStreams, View } from '@swmansion/smelter';
import NotoSansFont from '../../assets/NotoSans.ttf';
import CompositorVideo from '../components/SmelterVideo';

const FIRST_MP4_URL =
'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4';
Expand Down Expand Up @@ -138,52 +139,4 @@ function useSmelter(): Smelter | undefined {
return smelter;
}

type VideoProps = React.DetailedHTMLProps<
React.VideoHTMLAttributes<HTMLVideoElement>,
HTMLVideoElement
>;

type CompositorVideoProps = {
outputId: string;
onVideoCreated?: (smelter: Smelter) => Promise<void>;
smelter: Smelter;
children: React.ReactElement;
} & VideoProps;

function CompositorVideo(props: CompositorVideoProps) {
const { outputId, onVideoCreated, children, smelter: initialSmelter, ...videoProps } = props;
const [smelter, _setSmelter] = useState<Smelter>(initialSmelter);

const videoRef = useCallback(
async (video: HTMLVideoElement | null) => {
if (!video) {
return;
}

if (onVideoCreated) {
await onVideoCreated(smelter);
}

const { stream } = await smelter.registerOutput(outputId, children, {
type: 'stream',
video: {
resolution: {
width: Number(videoProps.width ?? video.width),
height: Number(videoProps.height ?? video.height),
},
},
audio: true,
});

if (stream) {
video.srcObject = stream;
await video.play();
}
},
[onVideoCreated, videoProps.width, videoProps.height, smelter, outputId]
);

return <video ref={videoRef} {...videoProps} />;
}

export default MultipleOutputs;
99 changes: 99 additions & 0 deletions ts/examples/vite-example/src/examples/UploadMp4Example.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import React, { useCallback, useEffect, useState } from 'react';
import Smelter from '@swmansion/smelter-web-wasm';
import { InputStream, Rescaler, useInputStreams, View, Text } from '@swmansion/smelter';
import CompositorVideo from '../components/SmelterVideo';
import NotoSansFont from '../../assets/NotoSans.ttf';

function UploadMp4Example() {
const smelter = useSmelter();

const onCreate = useCallback(async (smelter: Smelter) => {
await smelter.registerFont(NotoSansFont);
}, []);
const onUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) {
console.error('No files were uploaded');
return;
}

let file = e.target.files[0];

if (!smelter) {
console.error('Smelter has not been initialized yet');
return;
}

await smelter.unregisterInput('file');
await smelter.registerInput('file', { type: 'mp4', blob: file });
};

if (!smelter) {
return <div className="card" />;
}

return (
<div className="card">
<div style={{ margin: 20 }}>
<label htmlFor="upload-input" style={{ padding: 10 }}>
Upload MP4
</label>
<input id="upload-input" type="file" onChange={onUpload} accept="video/mp4" />
</div>
<CompositorVideo
outputId="output"
width={1280}
height={720}
smelter={smelter}
onVideoCreated={onCreate}>
<Scene />
</CompositorVideo>
</div>
);
}

function Scene() {
const inputs = useInputStreams();
if (!inputs['file']) {
return (
<View style={{ backgroundColor: 'black' }}>
<View style={{ top: 340, left: 560 }}>
<Text style={{ fontSize: 24, color: 'white' }}>Upload an MP4 file</Text>
</View>
</View>
);
}
return (
<View style={{ backgroundColor: 'black' }}>
<Rescaler>
<InputStream inputId="file" />
</Rescaler>
</View>
);
}

function useSmelter(): Smelter | undefined {
const [smelter, setSmelter] = useState<Smelter>();
useEffect(() => {
const smelter = new Smelter();

let cancel = false;
const promise = (async () => {
await smelter.init();
await smelter.start();
if (!cancel) {
setSmelter(smelter);
}
})();

return () => {
cancel = true;
void (async () => {
await promise.catch(() => {});
await smelter.terminate();
})();
};
}, []);
return smelter;
}

export default UploadMp4Example;
8 changes: 8 additions & 0 deletions ts/smelter-core/src/api/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { _smelterInternals } from '@swmansion/smelter';
*/
export type RegisterInputRequest =
| Api.RegisterInput
| { type: 'mp4_blob'; blob: any }
Comment on lines 15 to +16
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Api.RegisterInput is a generated type and already contains definitions for mp4; hence, the new type mp4_blob

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like adding new type just for that, it might make sense if it was more generic to handle some other cases types in the future, but not in this form

| { type: 'camera' }
| { type: 'screen_capture' }
| { type: 'stream'; stream: any };
Expand Down Expand Up @@ -52,6 +53,13 @@ export function intoRegisterInput(input: RegisterInput): RegisterInputRequest {
}

function intoMp4RegisterInput(input: Inputs.RegisterMp4Input): RegisterInputRequest {
if (input.blob) {
return {
type: 'mp4_blob',
blob: input.blob,
};
}

return {
type: 'mp4',
url: input.url,
Expand Down
4 changes: 3 additions & 1 deletion ts/smelter-web-wasm/src/compositor/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ export function intoRegisterOutputRequest(request: RegisterOutput): Output.Regis
}

export type RegisterInput =
| { type: 'mp4'; url: string }
| ({ type: 'mp4' } & RegisterMP4Input)
| { type: 'camera' }
| { type: 'screen_capture' }
| { type: 'stream'; stream: MediaStream };

type RegisterMP4Input = { url: string } | { blob: Blob };
8 changes: 6 additions & 2 deletions ts/smelter-web-wasm/src/mainContext/input.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Input as CoreInput } from '@swmansion/smelter-core';
import type { WorkerMessage } from '../workerApi';
import { assert } from '../utils';
import { assert, downloadToArrayBuffer } from '../utils';
import { handleRegisterCameraInput } from './input/camera';
import { handleRegisterScreenCaptureInput } from './input/screenCapture';
import { handleRegisterStreamInput } from './input/stream';
Expand All @@ -23,7 +23,11 @@ export async function handleRegisterInputRequest(
): Promise<RegisterInputResult> {
if (body.type === 'mp4') {
assert(body.url, 'mp4 URL is required');
return handleRegisterMp4Input(ctx, inputId, body.url);
const arrayBuffer = await downloadToArrayBuffer(body.url);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the whole point of having functions like handleRegisterMp4Input is to separate mp4-specific code from common code.

Preparing an array buffer here only unnecessarily complicates this function which should be only a simple if-else tree to call appropriate handlers. Additionally, it spreads potential functions that can throw an error all over the place.

return await handleRegisterMp4Input(ctx, inputId, arrayBuffer);
} else if (body.type === 'mp4_blob') {
const arrayBuffer = await (body.blob as Blob).arrayBuffer();
return await handleRegisterMp4Input(ctx, inputId, arrayBuffer);
} else if (body.type === 'camera') {
return await handleRegisterCameraInput(ctx, inputId);
} else if (body.type === 'screen_capture') {
Expand Down
5 changes: 1 addition & 4 deletions ts/smelter-web-wasm/src/mainContext/input/mp4.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,8 @@ export class Mp4Input implements Input {
export async function handleRegisterMp4Input(
ctx: InstanceContext,
inputId: string,
url: string
arrayBuffer: ArrayBuffer
): Promise<RegisterInputResult> {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();

const metadata = await parseMp4(arrayBuffer);

let messagePort;
Expand Down
5 changes: 5 additions & 0 deletions ts/smelter-web-wasm/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,8 @@ export async function sleep(timeoutMs: number): Promise<void> {
export function framerateToDurationMs(framerate: Framerate): number {
return (1000 * framerate.den) / framerate.num;
}

export async function downloadToArrayBuffer(url: string): Promise<ArrayBuffer> {
const response = await fetch(url);
return await response.arrayBuffer();
}
Comment on lines +28 to +31
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in my opinion this util is not helpful

4 changes: 4 additions & 0 deletions ts/smelter/src/types/registerInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export type RegisterMp4Input = {
* Path to the MP4 file (location on the server where Smelter server is deployed).
*/
serverPath?: string | null;
/**
* Blob of the MP4 file (available only in smelter-web-wasm).
*/
blob?: any | null;
/**
* (**default=`false`**) If input should be played in the loop. <span class="badge badge--primary">Added in v0.4.0</span>
*/
Expand Down