Skip to content

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.

  • Surfaces and sizing. A video uses the same plane or 360 sphere as an image, with the same width, height, sizing, projection and side. See Images.
  • Signals. Video events reach scripts through a Signal Emitter on the Video entity. See Events and signals.
  • Async hooks. Several examples await inside async 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.

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.

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.
  • 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 controls is on, can play it while you author.
  • Leaving the scene pauses the video. Entering it again restarts or resumes it, as restart says.
  • 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.

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 EventType.Video.Ready { duration }, in seconds (Infinity for a live stream) The first frame has loaded.
Video::error EventType.Video.Error { message } The video or its stream fails.
Video::play EventType.Video.Play {} Playback starts; not again after a buffering stall.
Video::pause EventType.Video.Pause {} Playback pauses.
Video::stop EventType.Video.Stop {} stop() stopped a playing video.
Video::end EventType.Video.End {} A video that plays once reaches its end.

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.
  • auto looks 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, set color yourself.
  • 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.

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, restart and 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
MediaStream::connected EventType.MediaStream.Connected { stream }, the name A stream started playing through the component.
MediaStream::disconnected EventType.MediaStream.Disconnected { stream }, the name That stream stopped: unpublished, replaced, or the stream prop changed.

The Streams global is where streams are published and found by name.

Call What it does
Streams.publish(id, stream) Publish a browser MediaStream under id, such as Input.camera.stream(). Returns a function that unpublishes it.
Streams.create(id, { video?, audio? }) Make a stream from data a script writes, published under id. Returns a writer. video is { width, height }; audio is { sampleRate, channels }.
writer.writeVideoFrame(source) Send one frame: RGBA pixels at the stream’s size, an ImageData, or a canvas or image drawn to fill it.
writer.writeAudioFrame(samples) Send one chunk of interleaved PCM samples, a Float32Array (-1 to 1) or Int16Array.
writer.close() Unpublish it and stop it.
Streams.ids() The names published now, by anyone.
Streams.has(id) Whether something is published under id.
Streams.on(id, listener) 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() or Input.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.

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 Screen with a Signal Emitter whose signal is cinema.
  • A Primitive Mesh named Play Button with a Selectable and a Signal Emitter whose signal is cinema/button.
  • A Text entity named Status.
CinemaScreen.jx
#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;
}
});
}
  • The Video entity does not accept a Selectable, so a separate button entity takes the clicks.
  • muted: false with autoplay: false means 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.

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.

PresenterKey.jx
#pragma lifecycle(startup, update)
const SCREEN = '#3f7a30'; // the green of this video's screen
let 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 hex color keys exactly that colour. Picking it from the video once is the most predictable key.
  • edgeShrink: 0 makes 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; detectedColor reports what it found, or undefined until it has measured, so the script reads it a moment later.

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 Mirror with a Media Stream whose stream is me/camera, and a Signal Emitter whose signal is mirror.
  • A Primitive Mesh named Mirror Button with a Selectable and a Signal Emitter whose signal is mirror/button.
  • A Video entity named Clock Screen with a Media Stream whose stream is clock.
LiveScreens.jx
#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();
}
  • 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.start asks the player’s permission the first time and resolves true once the camera streams. Starting it from a click follows the browser’s rules for permission prompts.
  • Streams.create makes a stream the script fills itself. writeVideoFrame(canvas) sends the canvas as one frame.
  • throttle limits 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.

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.

Playlist.jx
#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 send Video::end instead of looping.
  • A new src reloads the video; Video::ready fires for each clip, and the script starts it there.
  • Treating Video::error like Video::end skips a broken clip instead of stopping the playlist.
  • muted: true lets each clip start without waiting for a user gesture.

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.

NearbyScreen.jx
#pragma lifecycle(startup, update)
const FULL_VOLUME_WITHIN = 3; // metres
const 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();
}
  • camera is the camera the player sees through. It is undefined until rendering starts, hence the guard.
  • The two vectors are made once and reused, so the script creates nothing new each frame.
  • setVolume changes 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.
  • 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 setVolume for frequent volume changes.
  • Throttle generated streams. Write frames only as often as the content changes.
  • On phones and headsets, set Chroma Key edgeShrink to 0 for the cheapest key.
  • Expecting sound before a click. An unmuted video waits for the first user gesture. Start it from a click, or keep it muted.
  • Changing src to resume. A new src reloads from the beginning. Use play() and pause().
  • 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 auto on a close-up. When the subject fills the edges of the frame, auto cannot find the screen. Set color to 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'.