Video and streams
Updated
A Video entity (ent-video) plays moving pictures in the world: a cinema screen, a looping backdrop behind a stage, a 360 film around the player. Its Video component plays a file or an HLS stream. Two companion components extend it: a Chroma Key makes a green or blue screen transparent, so a filmed presenter stands in the scene, and a Media Stream replaces the file with something live, such as a player’s camera, a shared screen or frames a script draws. This page explains all three, the rules browsers apply to video playback, and how scripts control them.
Before you start
Section titled “Before you start”- Surfaces and sizing. A video uses the same plane or 360 sphere as an image, with the same
width,height,sizing,projectionandside. See Images. - Signals. Video events reach scripts through a Signal Emitter on the Video entity. See Events and signals.
- Async hooks. Several examples
awaitinsideasync function startup(). See Scripting. - Input devices. Publishing a camera uses
Input.camera. See Input and interaction.
For a video inside a UI panel, use a UI Video instead (see UI). Chroma Key and Media Stream work on both.
Key concepts
Section titled “Key concepts”HLS. HTTP Live Streaming: a video delivered as a playlist (.m3u8) of short segments. It is how most live and long-form web video is served. A Video plays HLS as easily as a file.
Autoplay policy. Browsers do not let a page start a video with sound until the user has clicked, tapped or pressed a key. MIRA handles this for you: a blocked start waits for the next press instead of failing. Muted video can start at once.
Chroma key. Making one colour of a video transparent. Footage filmed in front of a green or blue screen then shows only the subject.
Media stream. A live source of video and audio frames, published under a name (a string such as 'me/camera'). Anything can publish a stream; a Media Stream component plays the one with the name it is given.
comp-video, script class VideoComponent.
| Prop | Type | Default | Description |
|---|---|---|---|
src |
string | none | The video: a file URL, an HLS playlist (.m3u8) or an asset from the project. |
width |
number | 1.6 |
Plane width in metres. For equirectangular, the sphere’s radius. |
height |
number | 0.9 |
Plane height in metres. |
sizing |
'manual' | 'auto' |
none (manual) | auto fits the video’s own proportions inside width × height, and follows resolution changes. |
autoplay |
boolean | true |
Play once enough is buffered. Play mode only. |
repeat |
'once' | 'repeat' |
'repeat' |
once plays to the end; repeat starts again from the beginning. |
muted |
boolean | true |
Whether the sound is muted. |
volume |
number | 1 |
Gain, 0 to 1. 0 is silent. |
playsInline |
boolean | true |
Play inside the world on mobile rather than going fullscreen. |
crossOrigin |
string | 'anonymous' |
The cross-origin mode used to fetch the video. |
controls |
boolean | false |
A control bar under the plane with play/pause and a volume slider. Planar only. |
restart |
boolean | true |
Start again from the beginning each time the scene is entered; false resumes where it stopped. |
projection |
'planar' | 'equirectangular' |
'planar' |
A flat plane, or a sphere for 360 video. |
side |
'double' | 'front' | 'back' |
'double' |
Which faces are drawn. Use back to watch a 360 video from inside its sphere. |
Changing src or crossOrigin with setProps reloads the video. Other props apply to the playing video.
Methods
Section titled “Methods”| Method | What it does |
|---|---|
play() |
Start or resume. A start the browser blocks waits for the next user gesture. |
pause() |
Pause, keeping the position. |
stop() |
Stop and go back to the start; an HLS stream also stops loading. |
setVolume(v) |
Set the gain, 0 to 1, without reloading. 0 is silent. |
getVolume() |
The gain heard, 0 when muted. |
isPlaying() |
Whether it is playing now. |
whenReady() |
A promise that resolves once the first frame shows, or the video fails. Resolves at once when nothing is loading. |
Playback rules
Section titled “Playback rules”- Autoplay runs in play mode only, once the video can play. An unmuted video the browser refuses to start begins on the next pointer press, touch or key press.
- In the editor nothing autoplays. The control bar, when
controlsis on, can play it while you author. - Leaving the scene pauses the video. Entering it again restarts or resumes it, as
restartsays. - No black flash. The picture stays hidden until its first frame is ready, and a scene waits behind its loading screen for the first frame of each enabled video. A video that fails, has no source or waits for a live stream does not hold the scene.
- Unlit. Video shows its own colours, untouched by scene lighting.
Events
Section titled “Events”Sent through the Signal Emitters on the entity. They report what the video element did, whoever caused it: a script, autoplay or the control bar.
| Event | EventType |
Data | When |
|---|---|---|---|
Video::ready |
Event |
{ duration }, in seconds (Infinity for a live stream) |
The first frame has loaded. |
Video::error |
Event |
{ message } |
The video or its stream fails. |
Video::play |
Event |
{} |
Playback starts; not again after a buffering stall. |
Video::pause |
Event |
{} |
Playback pauses. |
Video::stop |
Event |
{} |
stop() stopped a playing video. |
Video::end |
Event |
{} |
A video that plays once reaches its end. |
Chroma Key
Section titled “Chroma Key”comp-chroma-key, script class ChromaKeyComponent. Add it to a Video or UI Video entity to make one colour transparent.
| Prop | Type | Default | Description |
|---|---|---|---|
color |
'auto', string or number |
'auto' |
The colour made transparent. auto measures the screen from the video; a hex colour keys exactly that one. |
similarity |
number | 0.4 |
How close to the key colour a pixel must be to vanish, 0 to 1. |
smoothness |
number | 0.15 |
Width of the soft edge past similarity, 0 to 1. |
spill |
number | 0.6 |
How much green or blue light reflected onto the subject is removed, 0 to 1. 0 turns it off. |
edgeShrink |
number | 0.5 |
Shrinks the subject’s edge, in video pixels, 0 to 2. 0 turns it off. |
edgeCleanup |
number | 0.25 |
Restores the subject’s colour on half-transparent edges, 0 to 1. |
| Member | What it is |
|---|---|
detectedColor |
The colour auto measured, as a hex string, or undefined before it has been measured. Read-only. |
autolooks at the edges of the first frames for the most common green or blue. It works when the screen covers more than half of the frame’s edges. For any other colour, or a close-up where the subject touches the edges, setcoloryourself.- White, grey and black keys are supported too.
- It shows in the editor and in play, so you can tune it while authoring.
- Changing a prop never reloads or restarts the video. Off or removed, the video looks exactly as before.
- An Outline or Silhouette on a keyed video is skipped.
Media Stream
Section titled “Media Stream”comp-media-stream, script class MediaStreamComponent. Add it to a Video, UI Video, Audio or Positional Audio entity to play a live stream in place of its src.
| Prop | Type | Default | Description |
|---|---|---|---|
stream |
string | '' |
The name of the published stream to play. Empty plays nothing. |
While it is enabled:
- The source waits silently, showing nothing, while the name is empty or nothing is published under it. Playback starts as soon as the stream appears.
- The source keeps its other settings: volume,
autoplay, events, and a Video’s size, projection and frame. - A live stream has no position:
repeat,restartand seeking do nothing. - On a Video, the stream’s sound plays through the video, which is muted by default. For sound placed in space, give a Positional Audio entity a Media Stream with the same name and leave the video muted.
Disable or remove the component to go back to src.
| Event | EventType |
Data | When |
|---|---|---|---|
Media |
Event |
{ stream }, the name |
A stream started playing through the component. |
Media |
Event |
{ stream }, the name |
That stream stopped: unpublished, replaced, or the stream prop changed. |
Publishing streams with Streams
Section titled “Publishing streams with Streams”The Streams global is where streams are published and found by name.
| Call | What it does |
|---|---|
Streams. |
Publish a browser MediaStream under id, such as Input.. Returns a function that unpublishes it. |
Streams. |
Make a stream from data a script writes, published under id. Returns a writer. video is { width, height }; audio is { sample. |
writer. |
Send one frame: RGBA pixels at the stream’s size, an ImageData, or a canvas or image drawn to fill it. |
writer. |
Send one chunk of interleaved PCM samples, a Float32Array (-1 to 1) or Int16Array. |
writer. |
Unpublish it and stop it. |
Streams.ids() |
The names published now, by anyone. |
Streams. |
Whether something is published under id. |
Streams. |
Call listener(live) at once and each time a stream under id appears or goes. Returns a function that stops listening. |
- A stream from
Input.camera.stream(),Input.microphone.stream()orInput.screen.stream()follows its device: republished when the camera switches, unpublished when the device stops. - A script can replace or unpublish only names it published itself.
- Everything a script published, created or followed is released with the script.
Examples
Section titled “Examples”1. A cinema screen with a play button
Section titled “1. A cinema screen with a play button”A screen that plays and pauses from a button in the world, and shows its state on a sign. The scene has:
- A Video entity named
Screenwith a Signal Emitter whose signal iscinema. - A Primitive Mesh named
Play Buttonwith a Selectable and a Signal Emitter whose signal iscinema/button. - A Text entity named
Status.
#pragma lifecycle(startup)
let screen;let status;
function startup() { screen = findEntity('Screen').getComponent(VideoComponent); status = findEntity('Status').getComponent(TextComponent); screen.setProps({ autoplay: false, muted: false, repeat: 'once' }); status.setProps({ text: 'Loading…' });
on('cinema/button', (event) => { if (event.eventType !== EventType.Selectable.Select) return; findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again if (screen.isPlaying()) screen.pause(); else screen.play(); });
on('cinema', (event) => { switch (event.eventType) { case EventType.Video.Ready: status.setProps({ text: `Ready: ${Math.round(event.data.duration)} s` }); break; case EventType.Video.Play: status.setProps({ text: 'Now playing' }); break; case EventType.Video.Pause: status.setProps({ text: 'Paused' }); break; case EventType.Video.End: status.setProps({ text: 'The end' }); screen.stop(); break; case EventType.Video.Error: status.setProps({ text: 'This film cannot play' }); break; } });}A button in the world plays and pauses a Video screen, and a Text sign follows its ready, play, pause and end events.
Click the amber button to play the film, and again to pause it. Drag elsewhere to orbit the camera, scroll to zoom.
- The Video entity does not accept a Selectable, so a separate button entity takes the clicks.
muted: falsewithautoplay: falsemeans the film starts only from the button. Because that start follows a click, the browser allows the sound.- The status text follows the video’s events, not the script’s calls, so it stays right if the player uses the control bar instead.
stop()at the end rewinds, so the next press plays from the start.
2. A green-screen presenter
Section titled “2. A green-screen presenter”A presenter filmed on a green screen, keyed into the scene. Pressing K turns the key on and off, B switches to a blue screen, and A lets the key measure the screen colour itself. The Behavior entity is a child of a Video entity named Presenter that has a Chroma Key.
#pragma lifecycle(startup, update)
const SCREEN = '#3f7a30'; // the green of this video's screenlet key;
function startup() { key = self.parent.getComponent(ChromaKeyComponent); key.setProps({ color: SCREEN, similarity: 0.4, spill: 0.6 });
#if IS_MOBILE || IS_HEADSET key.setProps({ edgeShrink: 0 }); // the cheapest key#endif
log('Keying out', SCREEN);}
function update() { if (Input.keyboard.isKeyReleased(Key.K)) key.setEnabled(!key.enabled); if (Input.keyboard.isKeyReleased(Key.B)) key.setProps({ color: '#1d4ed8' }); if (Input.keyboard.isKeyReleased(Key.A)) { key.setProps({ color: 'auto' }); delay(() => log('Measured screen colour:', key.detectedColor ?? 'not measured yet'), 1500); }}A presenter filmed on a green screen is keyed into the scene by a Chroma Key on the Video entity; a script sets the key colour and switches the key, a blue key or automatic measurement from the keyboard.
Click the scene, then press K to turn the key off and on, B to key a blue screen instead, and A to let the key measure the screen colour itself. Drag to orbit the camera, scroll to zoom.
- A hex
colorkeys exactly that colour. Picking it from the video once is the most predictable key. edgeShrink: 0makes the key cheaper on phones and standalone headsets.setEnabled(!key.enabled)toggles the key. With it off, the video looks exactly as filmed.color: 'auto'measures the screen colour from the video’s frames instead;detectedColorreports what it found, orundefineduntil it has measured, so the script reads it a moment later.
3. Show your camera on a screen
Section titled “3. Show your camera on a screen”A “mirror” screen that shows the player’s own camera once they click it, and a second screen that shows a clock a script draws. The scene has:
- A Video entity named
Mirrorwith a Media Stream whosestreamisme/camera, and a Signal Emitter whose signal ismirror. - A Primitive Mesh named
Mirror Buttonwith a Selectable and a Signal Emitter whose signal ismirror/button. - A Video entity named
Clock Screenwith a Media Stream whosestreamisclock.
#pragma lifecycle(startup, update)
let canvas;let writer;
// Draw at most 4 frames a second: the clock changes once a second.const drawClock = throttle(() => { const ctx = canvas.getContext('2d'); ctx.fillStyle = '#0f172a'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#f8fafc'; ctx.font = '64px sans-serif'; ctx.fillText(new Date().toLocaleTimeString(), 24, 110); writer.writeVideoFrame(canvas);}, 250);
function startup() { canvas = Canvas.create(320, 180); writer = Streams.create('clock', { video: { width: 320, height: 180 } });
on('mirror/button', async (event) => { if (event.eventType !== EventType.Selectable.Select) return; findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again if (Streams.has('me/camera')) return; if (await Input.camera.start({ facing: 'user' })) { Streams.publish('me/camera', Input.camera.stream()); } });
on('mirror', (event) => { if (event.eventType === EventType.MediaStream.Connected) log('Mirror showing', event.data.stream); if (event.eventType === EventType.MediaStream.Disconnected) log('Mirror lost', event.data.stream); });}
function update() { drawClock();}A script draws a clock on a canvas and writes it into a stream that one screen plays; clicking the button publishes your camera to the mirror screen.
Watch the clock screen tick. Click the amber button and allow the camera to see yourself on the mirror. Drag elsewhere to orbit the camera.
- The Media Stream on each screen names the stream it waits for. Each screen shows nothing until something is published under that name.
Input.camera.startasks the player’s permission the first time and resolvestrueonce the camera streams. Starting it from a click follows the browser’s rules for permission prompts.Streams.createmakes a stream the script fills itself.writeVideoFrame(canvas)sends the canvas as one frame.throttlelimits the drawing to four times a second: the clock does not need sixty.- The stream, the camera use and the canvas are all released with the script.
Snippets
Section titled “Snippets”1. A playlist of clips
Section titled “1. A playlist of clips”A screen that plays a list of clips one after the other and loops the list. The Behavior entity is a child of a Video entity with a Signal Emitter whose signal is playlist.
#pragma lifecycle(startup)
const CLIPS = [ 'https://example.com/clips/intro.mp4', 'https://example.com/clips/tour.mp4', 'https://example.com/clips/outro.mp4',];
let video;let index = 0;
function startup() { video = self.parent.getComponent(VideoComponent); video.setProps({ src: CLIPS[0], repeat: 'once', muted: true, sizing: 'auto' });
on('playlist', (event) => { if (event.eventType === EventType.Video.Ready) { video.play(); } if (event.eventType === EventType.Video.End || event.eventType === EventType.Video.Error) { index = (index + 1) % CLIPS.length; video.setProps({ src: CLIPS[index] }); } });}repeat: 'once'makes each clip end and sendVideo::endinstead of looping.- A new
srcreloads the video;Video::readyfires for each clip, and the script starts it there. - Treating
Video::errorlikeVideo::endskips a broken clip instead of stopping the playlist. muted: truelets each clip start without waiting for a user gesture.
2. Sound that follows distance
Section titled “2. Sound that follows distance”A screen whose sound fades with distance from the player and that pauses when the player walks away, so it uploads no frames while out of sight. The Behavior entity is a child of the Video entity.
#pragma lifecycle(startup, update)
const FULL_VOLUME_WITHIN = 3; // metresconst SILENT_BEYOND = 15;const PAUSE_BEYOND = 25;const RESUME_WITHIN = 20;
let screenEntity;let video;const screenPos = new THREE.Vector3();const viewerPos = new THREE.Vector3();
function startup() { screenEntity = self.parent; video = screenEntity.getComponent(VideoComponent); video.setProps({ muted: false });}
function update() { if (!camera) return; screenEntity.getWorldPosition(screenPos); camera.getWorldPosition(viewerPos); const distance = screenPos.distanceTo(viewerPos);
const t = (distance - FULL_VOLUME_WITHIN) / (SILENT_BEYOND - FULL_VOLUME_WITHIN); video.setVolume(1 - Math.min(Math.max(t, 0), 1));
if (distance > PAUSE_BEYOND && video.isPlaying()) video.pause(); else if (distance < RESUME_WITHIN && !video.isPlaying()) video.play();}camerais the camera the player sees through. It isundefineduntil rendering starts, hence the guard.- The two vectors are made once and reused, so the script creates nothing new each frame.
setVolumechanges the gain directly and is meant to be called often.- Pausing beyond 25 m and resuming within 20 m leaves a gap, so the video does not flicker between states at the boundary.
Performance tips
Section titled “Performance tips”- Pause what is out of sight. Each playing video uploads a texture every frame it advances. Several large videos at once are costly, especially on phones and standalone headsets.
- Prefer muted autoplay for backdrops and loops: it starts at once and needs no user gesture.
- Use
setVolumefor frequent volume changes. - Throttle generated streams. Write frames only as often as the content changes.
- On phones and headsets, set Chroma Key
edgeShrinkto0for the cheapest key.
Common mistakes
Section titled “Common mistakes”- Expecting sound before a click. An unmuted video waits for the first user gesture. Start it from a click, or keep it muted.
- Changing
srcto resume. A newsrcreloads from the beginning. Useplay()andpause(). - Adding a Selectable to the Video entity. Videos do not accept one; use a separate button entity, a UI button or a key press.
- Keying with
autoon a close-up. When the subject fills the edges of the frame,autocannot find the screen. Setcolorto the screen’s hex colour. - Hearing a stream twice. A Video with a Media Stream plays the stream’s sound; a Positional Audio with the same stream plays it again. Keep the video muted when you add positional sound.
- Publishing over another script’s name. A name someone else published cannot be taken; pick unique names such as
'me/camera'or'lobby/clock'.