FERRETGame engine over Babylon.js
Ferret

@ferret/media

Audio: buses, sounds in the world, synthesised sounds as recipes with live parameters, pass-bys, presets, mute and a limiter; ambient zones, video surfaces (HLS/MP4 to texture) and HTML surfaces; recording, and frame-by-frame capture on simulated time to WebM or PNG.

123 exports · source in packages/media/src

Classes

AmbientZones class

class AmbientZones implements Service

Ambient sound by zone. map({ Yard: 'wind', Hall: 'room-tone' }) names the sound each zone plays (sounds defined in the AudioService, on the ambient bus); when the player's zone changes the old one fades out and the new one fades in. A zone with no entry keeps what was playing; map it to null for silence.

readonly name: "ambient"
constructor(readonly opts: AmbientOptions = {})
init(world: World)
map(table: Record<string, string | null>): this
get playing(): { zone: string; sound: string | null } | nullThe zone whose ambience is playing and the sound.
dispose()

packages/media/src/ambient.ts:17

AudioPlayer class

class AudioPlayer extends MediaComponent<AudioPlayerParams>

A sound that plays, pauses and seeks, with a queue of tracks (next, previous, repeat, shuffle): a radio, a jukebox, the music of a place. Streams from its source, so long tracks do not sit decoded in memory. Goes through the music bus by default, positioned at the entity when spatial is given. Controlled through the MediaPlayer API and reports through the media:* events; nothing here is bound to a key or a button. (Short sounds that fire and are done stay AudioService.play.)

audio: HTMLAudioElement
onAttach()
onDetach()

packages/media/src/audio-player.ts:15

AudioService class

class AudioService implements Service

Sound for a game: a master gain and four buses (music, sfx, ambient, voice) with their own volumes, buffers decoded once, sounds that sit in the world (a panner that follows a node, the listener follows the active camera). Browsers refuse sound before the first user action, so the context is made and resumed then (audio:unlocked); loops asked for earlier start at that moment, one-shots asked for earlier are dropped. sound:play events { name, entity? } play registered sounds.

readonly name: "audio"
ctx: AudioContext | null
culled: numberone-shots not played because they would not be heard (cull)
constructor(readonly opts: AudioOptions = {})
init(world: World)
get unlocked(): boolean
unlock(): voidMake the context and resume it. Call from a user action (the service does it on the first key, click or touch).
volume(bus: Bus | 'master'): number
setVolume(bus: Bus | 'master', v: number): void
get muted(): booleanAll sound off and on again; the volumes stay as they were.
setMuted(m: boolean): void
tap(): MediaStream | nullWhat the player hears (after the master gain) as a MediaStream with one audio track, for a recording. Null until the context is running: a suspended context delivers no data, and a recorder given such a track writes nothing at all.
busNode(bus: Bus): AudioNode | nullThe bus node for routing other sources (a video's sound) through the same volume control.
define(name: string, def: SoundDef): this
definition(name: string): SoundDef | undefineda defined sound's definition
has(name: string): boolean
load(url: string): Promise<AudioBuffer>Decode a sound file once.
addFile(key: string, data: ArrayBuffer | Uint8Array): thisHand the service the bytes of a sound file under a key (a package file read from the library): define(name, { url: key }) then plays it with no fetch.
removeFile(key: string): thisForget the bytes and the decoded buffer of a file handed over by addFile (sounds playing it play on).
fileInfo(url: string): SoundInfo | undefinedWhat a loaded file is (format, length, the loops it carries); undefined for a file the engine cannot read the header of, or one not loaded yet.
play(nameOrUrl: string, o: PlayOptions = {}): SoundHandlePlay a defined sound (by name) or a file (by url). Returns a handle at once; the sound starts when decoded.
reach(at: BABYLON.TransformNode | BABYLON.Vector3 | undefined, spatial: Spatial = {}): numberThe gain a positioned sound would reach the listener with (1 for one that is not positioned).
update()Called once per rendered frame.
_bus(b: Bus): AudioNode
listenerAt(): BABYLON.Vector3 | null
_register(v: Voice)
_unregister(v: Voice)
get activeVoices(): number
dispose()

packages/media/src/audio.ts:111

HtmlScreen class

class HtmlScreen extends Component<HtmlScreenParams>

A web page drawn onto a 3D plane, as a texture: the screen lies in the world like any mesh (hidden behind walls, seen from any angle, many of them are cheap), but it is a picture: no scripts run and nothing can be clicked. For notice boards and posters. Make it again with refresh() when the page changed. Events: html:ready { entity }, html:error { entity, message }. The page is fetched and made self-contained (see inlinePage), then the browser draws it through an SVG <foreignObject>.

schema: { readonly url: { readonly type: "string"; }; readonly html: { readonly type: "string"; }; readonly base: { readonly type: "string"; }; readonly width: { readonly type: "number"; readonly min: 0.01; }; readonly height: { readonly type: "number"; readonly min: 0.01; }; readonly pxWidth: { readonly type: "number"; readonly min: 16; readonly max: 4096; }; readonly pxHeight: { readonly type: "number"; readonly min: 16; readonly max: 4096; }; readonly pixelsPerMetre: { readonly type: "number"; readonly min: 1; readonly max: 4096; }; readonly pixelRatio: { readonly type: "number"; readonly min: 0.25; readonly max: 4; }; readonly lit: { readonly type: "boolean"; }; }
screen: BABYLON.Mesh
texture: BABYLON.DynamicTexture
state: 'loading' | 'ready' | 'error'
warnings: string[]
error: string
onAttach()
async refresh(): Promise<void>Fetch the page again and redraw it. Resolves when it is on the screen (or has failed: see state).
onDetach()

packages/media/src/html.ts:121

LampSounds class

class LampSounds

Positional sounds for the lamps a light budget says are near the viewer (a torch's crackle): a small pool of looping AudioPlayer entities that is moved from lamp to lamp. Only the nearest few lamps sound at a time (LightBudgetDef.sounds.budget), so a village of hundreds of torches costs a handful of audio elements. A player that is let go is paused and kept for the next lamp; its Web Audio graph is built once, not per lamp. Nothing is bound to a key; the sound goes through the AudioService (bus, master volume, panner that follows the entity) like every AudioPlayer.

dropped: numberstarts that found no free player (the pool is at max)
constructor(readonly world: World, readonly source: LampSoundSource, readonly opts: LampSoundsOptions = {})
get active(): number[]the lamps that sound now
get players(): readonly Entity[]the players made so far
playerOf(i: number): AudioPlayer | undefinedthe player of lamp i, if it sounds
apply(start: readonly number[], stop: readonly number[])
dispose()

packages/media/src/lamp-sounds.ts:35

MediaComponent class

abstract class MediaComponent<P extends MediaPlayerParams = MediaPlayerParams> extends Component<P> implements MediaPlayer

Shared by the media components: owns an HTMLMediaElement, routes its sound through the AudioService (bus volume, master, positional falloff), keeps a queue, and emits on world.events, always with { entity }: media:state { state }, media:play, media:pause, media:ended (the queue ran out), media:track { index, src }, media:error { message }.

get state(): PlayerState
get playing(): boolean
get currentTime(): numberseconds; duration is NaN until known and Infinity for a live stream
get duration(): number
play(): void
pause(): void
toggle(): void
stop(): voidpause and go back to the start
seek(seconds: number): void
get volume(): number0..1
set volume(v: number)0..1
get muted(): boolean
set muted(m: boolean)
get rate(): numberplayback speed, 1 = normal
set rate(r: number)playback speed, 1 = normal
get tracks(): readonly string[]
get index(): numberindex into tracks of the one that is current, -1 for none
get track(): string | null
get repeat(): Repeat
set repeat(r: Repeat)
get shuffle(): boolean
set shuffle(s: boolean)
async setTracks(tracks: string[], start = 0): Promise<void>replace the queue and make start current
async select(index: number): Promise<void>make this one current (it plays if autoplay or it was playing)
async next(): Promise<boolean>the next track; false when the queue is at its end (and repeat is not 'all')
async previous(): Promise<boolean>back to the one before when the current is near its start (true); otherwise back to its start (false)
onUpdate()

packages/media/src/player.ts:82

Mp3Decoder class

class Mp3Decoder

Decodes frames one at a time; decodeMp3 is this over a whole file.

lost: numberframes dropped because the bit reservoir did not hold the data they point back to (the first frame after a seek, or a damaged stream)
decodeFrame(buf: Uint8Array, pos: number, h: Mp3FrameHeader): Float32Array[]Decode one frame (size bytes at pos, header included) to its PCM: one array of samples per channel. A frame that cannot be decoded gives silence.

packages/media/src/mp3.ts:386

PassBy class

class PassBy extends Component<PassByParams>

Plays sound from the entity when it passes close to the listener. Event sound:passby { entity, sound }.

onAttach()
onUpdate()

packages/media/src/pass-by.ts:34

PassByTrigger class

class PassByTrigger

A pass-by: something comes close to the listener and goes away again (a fighter's howl, a shell's whistle, a car going by). It fires once when the distance falls below near, and is armed again only when it has grown past far, so circling at the edge does not repeat it. PassByTrigger is the rule alone, for code that keeps its own positions; PassBy is the component that plays a sound from its entity.

constructor(public near: number, public far = near * 2.5)
check(distance: number): booleanFeed the distance each frame; true on the frame it passes inside near.
get isArmed(): boolean

packages/media/src/pass-by.ts:10

SceneRecorder class

class SceneRecorder implements Service

Records the scene: the engine's canvas through captureStream and MediaRecorder, with the sound the player hears when the AudioService is unlocked. Results as one file (MP4 where the browser writes it, else WebM with its Duration put in). Events on world.events: record:start { mime, audio }, record:stop { mime, bytes, durationMs, audio }, record:error { message }. Bound to no key or button. Sound cannot join a recording that is running: a locked audio context delivers nothing, and a recorder given such a track writes an empty file, so a recording that started before the first user action has no sound. With software rendering and encoding (the simulators, a headless browser) the first data comes about a second after the start, so a recording shorter than that can be empty: stop() then rejects with a message saying so.

readonly name: "recorder"
constructor(readonly opts: RecorderOptions = {})
init(world: World)
get state(): RecorderState
get elapsedMs(): numbermilliseconds recorded so far, pauses left out
static get supported(): booleanWhether this browser can record a canvas at all.
start(o: { fps?: number; audio?: boolean; videoBitsPerSecond?: number } = {}): { mime: string; audio: boolean }
pause()
resume()
stop(): Promise<Recording>Ends the recording and resolves with the file. Rejects when the recorder failed or delivered nothing.
dispose()

packages/media/src/recorder.ts:137

SoundFileError class

class SoundFileError extends Error
constructor(public readonly code: 'format' | 'truncated' | 'unsupported' | 'corrupt', message: string)

packages/media/src/sound-file.ts:19

VideoScreen class

class VideoScreen extends MediaComponent<VideoScreenParams>

A video on a flat screen in the world: a plane with the video as an emissive texture. The picture starts at once (muted: browsers allow that); the sound begins on the first user action, through the AudioService's bus so the volume control and the positional falloff apply. Controlled through the MediaPlayer API (play, pause, seek, volume, a queue of sources) and reports through the media:* events; nothing here is bound to a key or a button.

video: HTMLVideoElement
screen: BABYLON.Mesh
texture: BABYLON.VideoTexture
onAttach()
onDetach()

packages/media/src/video.ts:18

WorldText class

class WorldText extends Component<WorldTextParams>

Text in the world: a plane with the text drawn on it, readable from the entity's +Z side (the entity's forward is the way the text faces, as an Unreal TextRender faces its +X). Unlit, with alpha; no collision. Draws with a canvas font (default Arial), so the letter shapes are the browser's.

schema: { readonly text: { readonly type: "string"; readonly required: true; }; readonly size: { readonly type: "number"; readonly min: 0.001; }; readonly xScale: { readonly type: "number"; readonly min: 0.01; }; readonly yScale: { readonly type: "number"; readonly min: 0.01; }; readonly color: { readonly type: "array"; }; readonly align: { readonly type: "string"; }; readonly valign: { readonly type: "string"; }; readonly font: { readonly type: "string"; }; readonly bold: { readonly type: "boolean"; }; }
plane?: BABYLON.Mesh
onAttach()
onDetach()the plane, its material and its texture all go with the entity (the material was left behind: every level change kept one per text in the scene)

packages/media/src/text.ts:32

Functions

airCutoff function

function airCutoff(d: number): number

The cutoff of the lowpass that stands for the air between a source and the listener d metres apart: the frequency whose absorption over that path is 3 dB (interpolated on the octave table in log-log), at most 20 kHz.

packages/media/src/audio.ts:24

attachSource function

async function attachSource(media: HTMLMediaElement, src: string, hlsUrl?: string, onError?: (m: string) => void): Promise<SourceResult>

Point a media element (video or audio) at a source. HLS plays natively where the browser can (Safari, iOS, WPE WebKit, the Android WebView) and through hls.js elsewhere; any other file is just set as src.

packages/media/src/source.ts:24

bufferFromPcm function

function bufferFromPcm(ctx: Pick<BaseAudioContext, 'createBuffer'>, pcm: PcmAudio): AudioBuffer

A Web Audio buffer of the samples, in the given context.

packages/media/src/sound-io.ts:70

captureFrames function

async function captureFrames(engine: BABYLON.AbstractEngine, scene: BABYLON.Scene, world: World | null, o: CaptureOptions = {}): Promise<Capture>

Captures the scene frame by frame on simulated time, not on the wall clock: before every frame the simulation moves exactly 1/fps seconds (the world's fixed steps), and the engine's frame time reads 1/fps, so animations, physics and per-frame code all see the same steady clock however slowly a frame is drawn. Nothing is dropped and a loop closes exactly. The render loop is held for the length of the capture and given back after; the canvas is drawn at supersample times the size and scaled down. Video is encoded in the browser (WebCodecs) into WebM; pictures come as PNG. The scene's sound is not captured.

packages/media/src/capture.ts:175

captureSupported function

function captureSupported(): { webm: boolean; png: boolean }

Whether this browser can capture video files (WebCodecs); pictures need only a canvas.

packages/media/src/capture.ts:153

decodeMp3 function

function decodeMp3(bytes: Uint8Array, o: Mp3DecodeOptions = {}): PcmAudio & { info: Mp3Info }

The whole file as PCM. With gapless (the default) the encoder's delay and padding are dropped when the LAME/Xing header gives them.

packages/media/src/mp3.ts:786

decodeSound function

function decodeSound(bytes: Uint8Array, o: Mp3DecodeOptions = {}): DecodedSound

The samples of a WAV or MP3 file.

packages/media/src/sound-io.ts:45

decodeWav function

function decodeWav(bytes: Uint8Array): PcmAudio & { info: WavInfo }

All the samples of a WAV file.

packages/media/src/sound-file.ts:175

defaultMimeTypes function

function defaultMimeTypes(audio: boolean): string[]

MP4 first (it plays and seeks everywhere), then WebM; with sound the codecs are named so the audio is not dropped.

packages/media/src/recorder.ts:36

defineSynthPresets function

function defineSynthPresets(audio: AudioService, o: { names?: string[]; prefix?: string; def?: Partial<SoundDef> } = {}): string[]

Register the presets (all, or the names given) in an AudioService; prefix goes before each name (and before the names a preset's then starts), def adds to every definition (a bus, a spatial default).

packages/media/src/synth-presets.ts:117

distanceGain function

function distanceGain(d: number, s: Spatial = {}): number

The gain of Web Audio's distance models at distance d (what a PannerNode applies).

packages/media/src/audio.ts:354

drawPage function

async function drawPage(xhtml: string, ctx: CanvasRenderingContext2D, viewport: { width: number; height: number }, size: { width: number; height: number }): Promise<void>

Draw a self-contained page into a canvas context at the given texture size. Throws when the browser refuses (it taints or fails).

packages/media/src/html.ts:105

encodeMp3 function

function encodeMp3(pcmIn: PcmAudio, o: Mp3EncodeOptions = {}): Uint8Array

Encode PCM as an MP3 file.

packages/media/src/mp3.ts:1018

encodeSound function

function encodeSound(pcm: PcmAudio, format: SoundFormat, o: SoundWriteOptions = {}): Uint8Array

A file of the given format from samples.

packages/media/src/sound-io.ts:58

encodeWav function

function encodeWav(pcm: PcmAudio, o: WavWriteOptions = {}): Uint8Array

A WAV file of the sound. Samples beyond -1..1 are clipped for the integer widths.

packages/media/src/sound-file.ts:211

id3v2Size function

function id3v2Size(b: Uint8Array): number

Bytes of an ID3v2 tag at the start (with its footer), 0 when there is none.

packages/media/src/mp3.ts:73

inlinePage function

async function inlinePage(html: string, base: string, get: HtmlFetch): Promise<{ xhtml: string; warnings: string[] }>

Make a page self-contained: stylesheets become <style>, url(...) in CSS and <img src> become data URIs, scripts, frames and media are dropped. Returns the XHTML of the page and the problems (a resource that could not be fetched is left out, not fatal).

packages/media/src/html.ts:43

loadHls function

function loadHls(url = ((globalThis as any).FERRET_LIB ?? 'lib/ferret/') + 'hls/hls.min.js'): Promise<HlsLike | null>

Load hls.js once from a script URL (it sets the global Hls). Resolves null if it cannot be loaded.

packages/media/src/source.ts:6

normalize function

function normalize(a: PcmAudio, peak = 0.891): PcmAudio

The sound scaled so its peak is peak (default 0.891, -1 dB); silence is left alone.

packages/media/src/sound-file.ts:348

pageSvg function

function pageSvg(xhtml: string, width: number, height: number): string

The page inside an SVG image of the viewport's size (the browser lays it out in a <foreignObject>).

packages/media/src/html.ts:100

parseMp3Header function

function parseMp3Header(b: Uint8Array, pos: number): Mp3FrameHeader | null

The header at pos, or null when the four bytes are not a valid MPEG audio header.

packages/media/src/mp3.ts:50

pcmDuration function

function pcmDuration: (a: PcmAudio) => number

packages/media/src/sound-file.ts:24

pcmFrames function

function pcmFrames: (a: PcmAudio) => number

packages/media/src/sound-file.ts:23

pcmFromBuffer function

function pcmFromBuffer(b: AudioBuffer): PcmAudio

The samples of a Web Audio buffer (copied).

packages/media/src/sound-io.ts:63

peakOf function

function peakOf(a: PcmAudio): number

The largest sample, 0..: before a conversion (peak 1 means it just touches full scale).

packages/media/src/sound-file.ts:341

pickMime function

function pickMime(types: string[], isSupported: (m: string) => boolean): string | undefined

The first of types that isSupported accepts, or undefined (then the browser picks its own).

packages/media/src/recorder.ts:43

playSynth function

function playSynth(ctx: SynthContext, r: SynthRecipe, dest: AudioNode, when: number, params: Record<string, number> = {}): SynthVoice

Build a recipe's graph into dest, starting at audio time when. Returns the voice: its live parameters, its stop, its end.

packages/media/src/synth.ts:130

readMp3Info function

function readMp3Info(b: Uint8Array): Mp3Info

Rate, channels, length and the encoder's delay of an MP3 file, from its frames (nothing is decoded).

packages/media/src/mp3.ts:206

readWavInfo function

function readWavInfo(bytes: Uint8Array): WavInfo

The header of a WAV file: format, length, loop points and cue marks, without reading the samples.

packages/media/src/sound-file.ts:75

renderSynth function

async function renderSynth(recipe: SynthRecipe, o: RenderSynthOptions = {}): Promise<PcmAudio>

A synthesised sound rendered to samples with an offline Web Audio context: the recipe made into a file (encodeSound) that plays anywhere.

packages/media/src/sound-io.ts:106

resample function

function resample(a: PcmAudio, rate: number): PcmAudio

The sound at another rate (windowed-sinc interpolation, 16 taps each side, with the cut-off lowered when going down so nothing folds back).

packages/media/src/sound-file.ts:314

scanMp3 function

function scanMp3(b: Uint8Array): Mp3Scan

All the frames of a stream, by walking header to header (a header that is not followed by another one is skipped as noise).

packages/media/src/mp3.ts:129

setWebmDuration function

function setWebmDuration(data: Uint8Array, durationMs: number): Uint8Array

MediaRecorder writes WebM with no Duration, so players show a nonsense length and cannot seek. Puts the Duration element into the Segment's Info. Returns the bytes unchanged when the file is not a WebM this can read, or already has a Duration.

packages/media/src/recorder.ts:77

sliceSound function

function sliceSound(a: PcmAudio, start: number, end: number): PcmAudio

A part of the sound by frames.

packages/media/src/sound-file.ts:369

sniffSound function

function sniffSound(bytes: Uint8Array): SoundFormat | undefined

Which format the bytes are, by what they start with (a RIFF/WAVE header, or an ID3 tag / an MPEG frame header); undefined when neither.

packages/media/src/sound-file.ts:27

soundFormatOf function

function soundFormatOf(nameOrMime: string): SoundFormat | undefined

The format a file name or MIME type says (the extension, or audio/mpeg, audio/wav, audio/x-wav...).

packages/media/src/sound-file.ts:35

soundInfo function

function soundInfo(bytes: Uint8Array): SoundInfo

What a sound file is, from its header and frames (nothing is decoded). Throws SoundFileError for anything that is not WAV or MP3.

packages/media/src/sound-io.ts:29

spatialFromUnreal function

function spatialFromUnreal(att: { attenuation_shape_extents?: number[]; falloff_distance?: number; distance_algorithm?: string; attenuate?: boolean }): { min: number; max: number; exact: boolean } | undefined

Unreal's sound attenuation (Linear distance algorithm, sphere shape) as the metres of spatial: full volume inside the inner radius (attenuation_shape_extents.x), silent after the falloff distance beyond it. Centimetres in, metres out. The panner falls off linearly, so another algorithm (Logarithmic, Inverse) is only approximated (exact: false). Undefined when the sound does not attenuate.

packages/media/src/lamp-sounds.ts:104

synthParams function

function synthParams(r: SynthRecipe): string[]

Every parameter a recipe names (for a check, or an editor's sliders).

packages/media/src/synth.ts:90

synthSeconds function

function synthSeconds(r: SynthRecipe, sounds: Record<string, SynthRecipe> = {}, at = 0): number | undefined

The length of a recipe with the sounds it chains, in seconds (undefined when one of them runs until stopped).

packages/media/src/sound-io.ts:92

textOffset function

function textOffset(w: number, h: number, align: WorldTextParams['align'] = 'left', valign: WorldTextParams['valign'] = 'bottom'): [number, number]

Where a block of text of the given measured size sits so that the anchor is at the entity's origin: the plane's centre in the reader's frame (x to the reader's right, y up).

packages/media/src/text.ts:22

toMono function

function toMono(a: PcmAudio): PcmAudio

Mix to one channel (the mean).

packages/media/src/sound-file.ts:295

toStereo function

function toStereo(a: PcmAudio): PcmAudio

Two channels from one (the same in both); more than two are mixed down to left and right (the odd ones left, the even ones right).

packages/media/src/sound-file.ts:303

trimSilence function

function trimSilence(a: PcmAudio, threshold = 0.001, keep = 0.005): PcmAudio

The quiet at both ends cut off (below threshold, default -60 dB), leaving keep seconds of it (default 0.005) so nothing is clipped.

packages/media/src/sound-file.ts:356

validateSynth function

function validateSynth(r: SynthRecipe): string[]

What is wrong with a recipe, as sentences (empty when it can play).

packages/media/src/synth.ts:100

waveform function

function waveform(a: PcmAudio, bins: number): Float32Array

The peaks of a sound for a picture of it: bins pairs of (lowest, highest) sample over equal parts of the whole sound, all channels together.

packages/media/src/sound-file.ts:374

writeWebm function

function writeWebm(frames: EncodedFrame[], t: WebmTrack): Uint8Array

One WebM file from encoded video frames: header, Info with the Duration, one track, the Cues (before the clusters, so a player can seek at once), and a cluster at every key frame (and at least every 30 s). The first frame must be a key frame.

packages/media/src/capture.ts:57

Interfaces

AmbientOptions interface

interface AmbientOptions
tag?: stringthe zones' tag for the listener: the entity whose zone picks the ambience (default "player")
fade?: numberseconds of cross-fade between ambiences (default 1.5)

packages/media/src/ambient.ts:5

AudioOptions interface

interface AudioOptions
createContext?: () => AudioContextmake the context (tests pass a fake; default new AudioContext())
gestureTarget?: EventTarget | falsewhere to wait for the first user action; false = do not listen (the game calls unlock() itself)
fetch?: (url: string) => Promise<{ ok: boolean; arrayBuffer(): Promise<ArrayBuffer> }>replace fetch (tests, a Platform file API)
limiter?: boolean | { threshold?: number; knee?: number; ratio?: number; attack?: number; release?: number }a limiter after the master gain, so that many loud sounds at once do not clip (default on: it acts only near full scale); or a compressor's settings
cull?: numbera positioned one-shot that would reach the listener below this gain is not played at all (default 0.01; 0 plays everything)
decode?: 'browser' | 'engine' | 'auto'who decodes sound files: browser (decodeAudioData, which also plays what the browser knows beyond WAV and MP3), engine (the engine's own WAV and MP3 decoders: the same samples on every platform, the MP3 cut gapless by its encoder tag), or auto (default): the browser, and the engine's when the browser refuses a WAV or MP3 or has no decoder at all)
maxOneShots?: numberAt most this many one-shots sound at once (default 32), and at most maxPerSound of one sound (default 6): a new one-shot over a limit takes the place of the quietest at the listener, or is not played when it is the quietest itself (counted in culled). A battle's hundred far bangs a second cost the audio thread a graph each and are not heard apart; 0 lifts a limit.
maxPerSound?: number

packages/media/src/audio.ts:78

AudioPlayerParams interface

interface AudioPlayerParams extends MediaPlayerParams
audio?: HTMLAudioElementan audio element you made (a MediaStream, a test double)

packages/media/src/audio-player.ts:4

Capture interface

interface Capture
format: 'webm' | 'png'
mime: stringe.g. video/webm;codecs=vp9, or image/png
frames: number
fps: number
width: number
height: number
durationMs: numbersimulated time covered, ms (frames / fps)
blob?: Blobthe video (webm)
pngs?: Blob[]the pictures (png without onFrame)
aborted: booleantrue when signal stopped it early

packages/media/src/capture.ts:128

CaptureOptions interface

interface CaptureOptions
fps?: numberframes per second of the result, and the simulated time between frames (default 30)
seconds?: numberhow long to capture, simulated seconds (default 1); or frames
frames?: number
width?: numbersize of the result (default: the canvas's render size)
height?: number
supersample?: numberrender at this many times the size and scale down: smooth edges and fine detail (1 to 4, default 1)
format?: 'webm' | 'png'webm: one video file (WebCodecs); png: a picture per frame (default webm)
codecs?: ('vp9' | 'vp8' | 'av1')[]video codec, the first the browser encodes is used (default vp9, then vp8)
bitrate?: numberbits per second (default about 0.12 bit per pixel and frame)
keyEvery?: numbera key frame every this many frames (default 2 s of frames)
advance?: (dt: number) => voidmove the simulation by dt seconds (default: the world's advance, which runs its fixed steps)
render?: () => voiddraw one frame (default: scene.render())
beforeFrame?: (i: number, t: number) => voidcalled before frame i is advanced and drawn, at simulated time t since the start (a turntable turns the camera here)
onFrame?: (i: number, png: Blob) => void | Promise<void>with png: each picture as it is made (else they are returned together)
signal?: AbortSignalstops the capture between two frames; what was made so far is returned
grab?: (canvas: HTMLCanvasElement, width: number, height: number) => CanvasImageSource & { convertToBlob?: (o: { type: string }) => Promise<Blob> }replace the browser parts (tests)
createEncoder?: (init: VideoEncoderInit) => VideoEncoder
isConfigSupported?: (c: VideoEncoderConfig) => Promise<{ supported?: boolean }>
makeFrame?: (source: CanvasImageSource, init: VideoFrameInit) => VideoFrame

packages/media/src/capture.ts:92

CuePoint interface

interface CuePoint
id: number
frame: number
label?: string

packages/media/src/sound-file.ts:15

DecodedSound interface

interface DecodedSound extends PcmAudio
info: SoundInfo

packages/media/src/sound-io.ts:42

EncodedFrame interface

interface EncodedFrame
data: Uint8Array
timeMs: numberpresentation time of the frame, ms
key: boolean

packages/media/src/capture.ts:36

FilterSpec interface

interface FilterSpec
type: 'lowpass' | 'highpass' | 'bandpass' | 'notch' | 'lowshelf' | 'highshelf' | 'peaking' | 'allpass'
freq: Value
q?: Value

packages/media/src/synth.ts:18

HtmlScreenParams interface

interface HtmlScreenParams
url?: stringthe page to show (its stylesheets, images and fonts are fetched too: they need CORS, or fetch that gets around it)
html?: stringor the page as text; base then resolves its relative links
base?: string
width?: numbersize of the screen in metres (default 4 x 2.25)
height?: number
pxWidth?: numberthe page's window in CSS pixels: the page lays out as in a browser of exactly this size. Give both, or one (the other follows the screen's shape), or none (see pixelsPerMetre)
pxHeight?: number
pixelsPerMetre?: numberwhen the window size is not given: window = screen size in metres x this (default 256), the larger side capped at 2048 with the shape kept
pixelRatio?: numbertexture size = viewport x this (default 1; 2 for sharper text on a screen seen close)
fetch?: HtmlFetchreplace fetch
lit?: booleanlit by the scene like a poster (default false: it glows like a screen)

packages/media/src/html.ts:7

LampSoundsOptions interface

interface LampSoundsOptions
spatial?: { min?: number; max?: number }the sound comes from the lamp: full volume inside min metres, silent beyond max (see spatialFromUnreal). Default 2 / 30
volume?: number0..1, default 1 (Unreal: the cue's volume multiplier x the component's)
bus?: NonNullable<MediaPlayerParams['bus']>default 'ambient'
offset?: Vec3metres added to a lamp's position (Unreal: the audio component's offset from the actor)
max?: numberhow many players at most (default: no limit, but the source's own sound budget keeps it small); a start beyond it is dropped
makeAudio?: () => HTMLAudioElement | undefinedthe element a player plays through (a test double); default a new Audio

packages/media/src/lamp-sounds.ts:14

LampSoundSource interface

interface LampSoundSource

What LampSounds needs of a light budget (LightBudget from

def: { items: readonly { position: Vec3; sound?: string; id?: string }[] }
onSounds?: (start: number[], stop: number[]) => void

packages/media/src/lamp-sounds.ts:9

LoopPoints interface

interface LoopPoints

A stretch of a sound that repeats, in frames. end is the first frame after the loop (as in a WAV smpl chunk's end + 1).

start: number
end: number
count?: number

packages/media/src/sound-file.ts:14

MediaPlayer interface

interface MediaPlayer

What a game controls. Every media component (a video screen, an audio player) has this same surface, and the engine binds it to nothing: no key, button or gesture. A game calls it from its own code, from a stock behaviour's wiring or from its UI.

readonly state: PlayerState
readonly playing: boolean
readonly currentTime: numberseconds; duration is NaN until known and Infinity for a live stream
readonly duration: number
volume: number0..1
muted: boolean
rate: numberplayback speed, 1 = normal
play(): void
pause(): void
toggle(): void
stop(): voidpause and go back to the start
seek(seconds: number): void
readonly tracks: readonly string[]
readonly index: numberindex into tracks of the one that is current, -1 for none
readonly track: string | null
repeat: Repeat
shuffle: boolean
setTracks(tracks: string[], start?: number): Promise<void>replace the queue and make start current
select(index: number): Promise<void>make this one current (it plays if autoplay or it was playing)
next(): Promise<boolean>the next track; false when the queue is at its end (and repeat is not 'all')
previous(): Promise<boolean>back to the one before when the current is near its start (true); otherwise back to its start (false)

packages/media/src/player.ts:13

MediaPlayerParams interface

interface MediaPlayerParams
src?: stringone source: a file or an HLS playlist (.m3u8)
tracks?: string[]or a queue of them
start?: numberindex of the track to start with
repeat?: Repeat
loop?: booleanshorthand for repeat: 'one'
shuffle?: boolean
volume?: number0..1 (default 1)
muted?: boolean
rate?: number
bus?: Busthe bus its sound goes through (video 'sfx', audio 'music')
spatial?: { min?: number; max?: number }the sound comes from the entity: louder near it. min/max distances in metres
hlsUrl?: stringwhere hls.js is, for browsers that cannot play HLS themselves (default hls/hls.min.js under the library folder)
autoplay?: booleanstart by itself (default true; the sound waits for the first user action)
random?: () => numberreplaces Math.random for the shuffle (a seeded one for tests, replays)

packages/media/src/player.ts:49

Mp3DecodeOptions interface

interface Mp3DecodeOptions
gapless?: booleandrop the encoder's delay and padding (from the LAME/Xing header) so the sound is exactly the length that was encoded; default true

packages/media/src/mp3.ts:380

Mp3EncodeOptions interface

interface Mp3EncodeOptions
bitrate?: numberkbit/s (a Layer III rate of the version the sample rate belongs to); default 128 for MPEG-1 stereo, 64 for MPEG-1 mono, 64 / 32 for the lower rates
mode?: 'auto' | 'stereo' | 'joint' | 'mono'auto (default): joint stereo for two channels, mono for one
lowpass?: numberHz above which nothing is kept; default by bitrate
rate?: numbera rate that is not an MPEG one (44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000) is converted to the nearest above it, unless this says which
encoder?: stringthe encoder name written to the Info header (up to 9 characters), default "Ferret"

packages/media/src/mp3.ts:810

Mp3Frame interface

interface Mp3Frame
pos: number
size: number
header: Mp3FrameHeader

packages/media/src/mp3.ts:80

Mp3FrameHeader interface

interface Mp3FrameHeader
version: MpegVersion
layer: 1 | 2 | 3
bitrate: numberkbit/s; 0 for a free-format stream (the size is then found from the next frame)
rate: number
mode: ChannelMode
modeExt: numberjoint stereo: bit 0 intensity, bit 1 mid/side
channels: 1 | 2
size: numberbytes of the frame with its header
samples: numberPCM frames one frame decodes to (1152, or 576 for MPEG-2 and 2.5 Layer III)
crc: boolean
padding: boolean

packages/media/src/mp3.ts:15

Mp3Info interface

interface Mp3Info
version: MpegVersion
layer: 1 | 2 | 3
rate: number
channels: 1 | 2
mode: ChannelMode
frames: numberframes in the file
samples: numberPCM frames per channel the file decodes to, with the encoder's delay and padding taken off when the file says them (gapless)
duration: number
bitrate: numberaverage kbit/s
vbr: booleanvariable bitrate (a Xing header, or frames of different bitrates)
delay?: numberthe encoder's delay and padding in PCM frames from the LAME header, when there is one
padding?: number
skip: numberhow many PCM frames of the start the decoder drops to get the gapless result (the encoder delay + 529 of the decoder)
encoder?: stringthe encoder's own name from the LAME/Xing header, e.g. "LAME3.100"
dataStart: numberwhere the first frame is (after an ID3v2 tag) and where the last ends (before an ID3v1 tag)
dataEnd: number

packages/media/src/mp3.ts:82

Mp3Scan interface

interface Mp3Scan
info: Mp3Info
frames: Mp3Frame[]

packages/media/src/mp3.ts:110

ParamRef interface

interface ParamRef

a value the game sets while the sound plays: base + scale * value, followed with a time constant of smooth seconds

param: string
base?: number
scale?: number
smooth?: number

packages/media/src/synth.ts:13

PassByParams interface

interface PassByParams
sound: stringa sound defined in the AudioService
near: numbermetres from the listener (the active camera) that fire it
far?: numbermetres it must go past before it can fire again (default 2.5 x near)
volume?: number
spatial?: Spatial

packages/media/src/pass-by.ts:22

PcmAudio interface

interface PcmAudio

Sound as numbers: one Float32Array of samples (-1..1) per channel, all the same length.

rate: numberframes per second
channels: Float32Array[]

packages/media/src/sound-file.ts:7

PlayOptions interface

interface PlayOptions
at?: BABYLON.TransformNode | BABYLON.Vector3where the sound comes from; a node it follows. Without it the sound is not positioned (UI, music)
volume?: number
loop?: boolean
bus?: Bus
fadeIn?: numberseconds to fade in
spatial?: Spatial
delay?: numberseconds from now on the audio clock (exact, unlike a timer)
params?: Record<string, number>a synthesised sound's live parameters at its start
lowpass?: numbera lowpass in the path, Hz: the highs a far sound has lost to the air (below 20 kHz only)
pan?: numberleft (-1) to right (1) for a sound that is not positioned (a gun of the player's own ship a little to one side)
onEnded?: () => voidcalled once when the sound is over: it ended, was stopped, or never started (audio locked, culled, a file that would not load)

packages/media/src/audio.ts:49

RecorderOptions interface

interface RecorderOptions
canvas?: HTMLCanvasElementthe canvas to record (default: the engine's rendering canvas)
fps?: numberframes per second asked of the capture (default 30)
videoBitsPerSecond?: numbervideo bit rate (default: the browser's)
audio?: booleanadd the sound the player hears when the audio is unlocked (default true)
mimeTypes?: string[]formats in order of preference; the first the browser can write is used
timeslice?: numberask for a data chunk this often, ms (default 1000): a long recording is not held back in the encoder
createRecorder?: (stream: MediaStream, o: { mimeType?: string; videoBitsPerSecond?: number }) => MediaRecorderreplace the browser's MediaRecorder (tests)
isTypeSupported?: (mime: string) => boolean

packages/media/src/recorder.ts:7

Recording interface

interface Recording
blob: Blob
mime: stringthe container and codecs the file was written with, e.g. video/mp4;codecs=avc1.42E01E
durationMs: number
bytes: number
audio: booleanfalse when the audio was still locked at the start (the file has no sound) or not asked for

packages/media/src/recorder.ts:25

RenderSynthOptions interface

interface RenderSynthOptions
rate?: numberframes per second, default 44100
seconds?: numberseconds to render; default the recipe's dur (and its chained sounds' ends), required for a recipe that runs until stopped
params?: Record<string, number>live parameters at the start
sounds?: Record<string, SynthRecipe & { volume?: number }>the recipes the then chain names (for example the presets)
volume?: numberthe volume of the sound, default 1
createContext?: (channels: number, length: number, rate: number) => OfflineAudioContextreplace new OfflineAudioContext(...) (Node has none; tests)

packages/media/src/sound-io.ts:76

SoundDef interface

interface SoundDef
url?: stringa recording; or synth, a recipe played live (see synth.ts)
synth?: SynthRecipe
bus?: Bus
volume?: number0..1, default 1
loop?: boolean
loopPoints?: 'file' | { start: number; end: number }where a looping recording repeats: file takes the first loop the WAV file carries (its smpl chunk, as a sound editor writes it), or { start, end } in seconds; default the whole sound
spatial?: Spatialspatial: louder near the source; min is the distance of full volume, max where it is silent (metres)

packages/media/src/audio.ts:35

SoundHandle interface

interface SoundHandle
readonly playing: boolean
setVolume(v: number, fade?: number): void
stop(fade?: number): void
set(param: string, value: number): voidset a live parameter of a synthesised sound (an engine's throttle); nothing for a recording

packages/media/src/audio.ts:70

SoundInfo interface

interface SoundInfo
format: SoundFormat
rate: number
channels: number
frames: numberframes per channel
duration: number
bitrate: numberkbit/s as stored (MP3: the average) or what the WAV sample format makes: rate channels bits
bits?: numberWAV: bits per sample and encoding; MP3: variable bitrate and the encoder's name
encoding?: string
vbr?: boolean
encoder?: string
loops: LoopPoints[]WAV smpl loops; an MP3 has none (it is cut gapless instead)
cues: CuePoint[]

packages/media/src/sound-io.ts:9

SoundWriteOptions interface

interface SoundWriteOptions

packages/media/src/sound-io.ts:52

SourceResult interface

interface SourceResult
mode: 'native' | 'hls.js' | 'none'
destroy(): void

packages/media/src/source.ts:18

Spatial interface

interface Spatial

How loudness falls with distance (Web Audio's models): linear from full at min to silent at max; inverse min / (min + rolloff * (d - min)), never silent (the far guns of a battle); exponential (d / min) ^ -rolloff.

min?: number
max?: number
model?: 'linear' | 'inverse' | 'exponential'
rolloff?: number
air?: booleanthe air takes the highs of a far sound (ISO 9613-1 absorption, 20 C, 70 % humidity): a lowpass that follows the distance to the listener, so a far source is duller as well as quieter

packages/media/src/audio.ts:12

SynthContext interface

interface SynthContext

The part of an AudioContext a recipe needs (tests pass a fake).

currentTime: number
sampleRate: number
createOscillator(): OscillatorNode
createBufferSource(): AudioBufferSourceNode
createBiquadFilter(): BiquadFilterNode
createGain(): GainNode
createBuffer(channels: number, length: number, rate: number): AudioBuffer

packages/media/src/synth.ts:51

SynthLayer interface

interface SynthLayer
osc?: OscTypean oscillator (osc with freq in Hz) or white noise (noise: true)
freq?: Value
noise?: boolean
filter?: FilterSpec
gain?: Valuethe layer's gain (default 1)
start?: numberseconds after the sound's start the layer begins (default 0) and how long it lasts (default the recipe's dur)
dur?: number

packages/media/src/synth.ts:24

SynthRecipe interface

interface SynthRecipe
layers: SynthLayer[]
dur?: numberseconds; a recipe without it plays until it is stopped (a loop: an engine, a wind)
filter?: FilterSpecafter the layers are mixed: one filter and one envelope for all of them
gain?: Value
params?: Record<string, number>the parameters' values before the game sets them
then?: Array<{ at: number; sound: string; volume?: number }>more sounds started from this one, at seconds after it on the audio clock (a boom after a roar)

packages/media/src/synth.ts:37

SynthVoice interface

interface SynthVoice
set(param: string, value: number): voidset a live parameter
stop(when: number): voidstop every source at that audio time
readonly end: numberthe audio time it ends by itself (Infinity for a loop)
onended: (() => void) | nullcalled once when every source has ended

packages/media/src/synth.ts:61

VideoScreenParams interface

interface VideoScreenParams extends MediaPlayerParams
video?: HTMLVideoElementor a video element you made (a MediaStream, a canvas capture)
width?: numbersize of the screen in metres (default 4 x 2.25)
height?: number

packages/media/src/video.ts:4

WavInfo interface

interface WavInfo
encoding: WavEncoding
bits: numberbits per sample as stored
channels: number
rate: number
frames: number
duration: number
loops: LoopPoints[]the loops of the smpl chunk (sampler loops: what a sound editor writes for a sound that repeats)
cues: CuePoint[]the cue marks (cue chunk) with the labels of an adtl list
note?: numberthe MIDI unity note of the smpl chunk, when there is one
dataOffset: numberwhere the sample data is in the file
dataBytes: number

packages/media/src/sound-file.ts:53

WavWriteOptions interface

interface WavWriteOptions
bits?: 8 | 16 | 24 | 32 | 'float32'float32 is IEEE float; default 16
loops?: LoopPoints[]written as smpl loops (frames, end the first frame after the loop)
cues?: CuePoint[]written as cue marks (with adtl labels)
dither?: booleanadd triangular noise of one step before rounding to 8/16/24 bits (hides the rounding of quiet sounds); deterministic

packages/media/src/sound-file.ts:199

WebmTrack interface

interface WebmTrack
codec: 'V_VP9' | 'V_VP8' | 'V_AV1'Matroska codec id: V_VP9, V_VP8 or V_AV1
width: number
height: number
fps: number
durationMs?: numberthe length of the video, ms (default: the last frame's time plus one frame)

packages/media/src/capture.ts:43

WorldTextParams interface

interface WorldTextParams
text: stringthe text; \n starts a new line
size?: numberheight of a letter's em box in metres (Unreal's TextRender WorldSize / 100)
xScale?: numberextra scale across and along the lines (Unreal's XScale, YScale)
yScale?: number
color?: number[]colour as [r, g, b] or [r, g, b, a], 0..1
align?: 'left' | 'center' | 'right'how the text sits on the entity's origin, as a reader sees it
valign?: 'top' | 'center' | 'bottom'
font?: string
bold?: boolean

packages/media/src/text.ts:4

Types

Bus type

type Bus = 'music' | 'sfx' | 'ambient' | 'voice'

packages/media/src/audio.ts:6

ChannelMode type

type ChannelMode = 'stereo' | 'joint' | 'dual' | 'mono'

packages/media/src/mp3.ts:13

CurvePoint type

type CurvePoint = [t: number, v: number, ramp?: Ramp]

a point of a curve: seconds from the sound's start, the value, how the value gets there from the point before (default 'lin')

packages/media/src/synth.ts:11

HlsLike type

type HlsLike = { isSupported(): boolean; new (cfg?: unknown): { loadSource(u: string): void; attachMedia(v: HTMLMediaElement): void; destroy(): void; on(ev: string, fn: (...a: any[]) => void): void } }

packages/media/src/source.ts:2

HtmlFetch type

type HtmlFetch = (url: string) => Promise<{ ok: boolean; status: number; text(): Promise<string>; blob(): Promise<Blob> }>

What HtmlScreen needs from fetch (a Platform file API or a proxy fits): the page and its pieces come through it.

packages/media/src/html.ts:5

MpegVersion type

type MpegVersion = 1 | 2 | 2.5

packages/media/src/mp3.ts:12

OscType type

type OscType = 'sine' | 'square' | 'sawtooth' | 'triangle'

packages/media/src/synth.ts:16

PlayerState type

type PlayerState = 'idle' | 'loading' | 'playing' | 'paused' | 'ended' | 'error'

packages/media/src/player.ts:6

Ramp type

type Ramp = 'lin' | 'exp' | 'set'

Synthesised sounds: a recipe of plain data instead of a recording. A recipe is a few layers (an oscillator or noise, an optional filter, a gain envelope) mixed into an optional shared filter and envelope; every number of it is a constant, a curve over time (points with a ramp to each) or a live parameter the game sets while the sound plays (an engine's throttle). The same recipes run in any game and can be stored in a level, edited and written by an agent, since they are only data. AudioService.define(name, { synth }) registers one; it then plays like any other sound: buses, the world position, the unlock, the mute.

packages/media/src/synth.ts:9

RecorderState type

type RecorderState = 'idle' | 'recording' | 'paused'

packages/media/src/recorder.ts:5

Repeat type

type Repeat = 'none' | 'one' | 'all'

packages/media/src/player.ts:7

SoundFormat type

type SoundFormat = 'wav' | 'mp3'

packages/media/src/sound-file.ts:17

Value type

type Value = number | CurvePoint[] | ParamRef

packages/media/src/synth.ts:14

WavEncoding type

type WavEncoding = 'pcm' | 'float' | 'alaw' | 'mulaw'

packages/media/src/sound-file.ts:51

Constants

FX_SYNTH_PRESETS const

const FX_SYNTH_PRESETS: Record<string, Preset>

packages/media/src/synth-presets-fx.ts:15

MP3_BITRATES_V1 const

const MP3_BITRATES_V1: number[]

the bitrates of MPEG-1 Layer III, kbit/s

packages/media/src/mp3.ts:45

MP3_BITRATES_V2 const

const MP3_BITRATES_V2: number[]

the bitrates of MPEG-2 and 2.5 Layer III

packages/media/src/mp3.ts:47

MP3_ENCODER_DELAY const

const MP3_ENCODER_DELAY: 528

samples between the sound and its first output sample through the encoder's filter bank and transform (written to the header so a decoder can cut them)

packages/media/src/mp3.ts:825

SOUND_MIME const

const SOUND_MIME: Record<SoundFormat, string>

packages/media/src/sound-file.ts:42

SYNTH_PRESETS const

const SYNTH_PRESETS: Record<string, { recipe: SynthRecipe; volume?: number | undefined; }>

packages/media/src/synth-presets.ts:13