# @ferret/media: API

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. Generated from the source (`packages/media/src`), so it matches the code.

## Classes

### AmbientZones

*class* · `packages/media/src/ambient.ts:17`

```ts
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 } | null` — The zone whose ambience is playing and the sound.
- `dispose()`

### AudioPlayer

*class* · `packages/media/src/audio-player.ts:15`

```ts
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()`

### AudioService

*class* · `packages/media/src/audio.ts:111`

```ts
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: number` — one-shots not played because they would not be heard (`cull`)
- `constructor(readonly opts: AudioOptions = {})`
- `init(world: World)`
- `get unlocked(): boolean`
- `unlock(): void` — Make 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(): boolean` — All sound off and on again; the volumes stay as they were.
- `setMuted(m: boolean): void`
- `tap(): MediaStream | null` — What 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 | null` — The 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 | undefined` — a defined sound's definition
- `has(name: string): boolean`
- `load(url: string): Promise<AudioBuffer>` — Decode a sound file once.
- `addFile(key: string, data: ArrayBuffer | Uint8Array): this` — Hand 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): this` — Forget the bytes and the decoded buffer of a file handed over by `addFile` (sounds playing it play on).
- `fileInfo(url: string): SoundInfo | undefined` — What 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 = {}): SoundHandle` — Play 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 = {}): number` — The 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()`

### HtmlScreen

*class* · `packages/media/src/html.ts:121`

```ts
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()`

### LampSounds

*class* · `packages/media/src/lamp-sounds.ts:35`

```ts
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: number` — starts 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 | undefined` — the player of lamp `i`, if it sounds
- `apply(start: readonly number[], stop: readonly number[])`
- `dispose()`

### MediaComponent

*class* · `packages/media/src/player.ts:82`

```ts
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(): number` — seconds; `duration` is NaN until known and Infinity for a live stream
- `get duration(): number`
- `play(): void`
- `pause(): void`
- `toggle(): void`
- `stop(): void` — pause and go back to the start
- `seek(seconds: number): void`
- `get volume(): number` — 0..1
- `set volume(v: number)` — 0..1
- `get muted(): boolean`
- `set muted(m: boolean)`
- `get rate(): number` — playback speed, 1 = normal
- `set rate(r: number)` — playback speed, 1 = normal
- `get tracks(): readonly string[]`
- `get index(): number` — index 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()`

### Mp3Decoder

*class* · `packages/media/src/mp3.ts:386`

```ts
class Mp3Decoder
```

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

- `lost: number` — frames 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.

### PassBy

*class* · `packages/media/src/pass-by.ts:34`

```ts
class PassBy extends Component<PassByParams>
```

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

- `onAttach()`
- `onUpdate()`

### PassByTrigger

*class* · `packages/media/src/pass-by.ts:10`

```ts
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): boolean` — Feed the distance each frame; true on the frame it passes inside `near`.
- `get isArmed(): boolean`

### SceneRecorder

*class* · `packages/media/src/recorder.ts:137`

```ts
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(): number` — milliseconds recorded so far, pauses left out
- `static get supported(): boolean` — Whether 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()`

### SoundFileError

*class* · `packages/media/src/sound-file.ts:19`

```ts
class SoundFileError extends Error
```

- `constructor(public readonly code: 'format' | 'truncated' | 'unsupported' | 'corrupt', message: string)`

### VideoScreen

*class* · `packages/media/src/video.ts:18`

```ts
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()`

### WorldText

*class* · `packages/media/src/text.ts:32`

```ts
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)

## Functions

### airCutoff

*function* · `packages/media/src/audio.ts:24`

```ts
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.

### attachSource

*function* · `packages/media/src/source.ts:24`

```ts
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`.

### bufferFromPcm

*function* · `packages/media/src/sound-io.ts:70`

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

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

### captureFrames

*function* · `packages/media/src/capture.ts:175`

```ts
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.

### captureSupported

*function* · `packages/media/src/capture.ts:153`

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

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

### decodeMp3

*function* · `packages/media/src/mp3.ts:786`

```ts
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.

### decodeSound

*function* · `packages/media/src/sound-io.ts:45`

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

The samples of a WAV or MP3 file.

### decodeWav

*function* · `packages/media/src/sound-file.ts:175`

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

All the samples of a WAV file.

### defaultMimeTypes

*function* · `packages/media/src/recorder.ts:36`

```ts
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.

### defineSynthPresets

*function* · `packages/media/src/synth-presets.ts:117`

```ts
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).

### distanceGain

*function* · `packages/media/src/audio.ts:354`

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

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

### drawPage

*function* · `packages/media/src/html.ts:105`

```ts
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).

### encodeMp3

*function* · `packages/media/src/mp3.ts:1018`

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

Encode PCM as an MP3 file.

### encodeSound

*function* · `packages/media/src/sound-io.ts:58`

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

A file of the given format from samples.

### encodeWav

*function* · `packages/media/src/sound-file.ts:211`

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

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

### id3v2Size

*function* · `packages/media/src/mp3.ts:73`

```ts
function id3v2Size(b: Uint8Array): number
```

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

### inlinePage

*function* · `packages/media/src/html.ts:43`

```ts
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).

### loadHls

*function* · `packages/media/src/source.ts:6`

```ts
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.

### normalize

*function* · `packages/media/src/sound-file.ts:348`

```ts
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.

### pageSvg

*function* · `packages/media/src/html.ts:100`

```ts
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>).

### parseMp3Header

*function* · `packages/media/src/mp3.ts:50`

```ts
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.

### pcmDuration

*function* · `packages/media/src/sound-file.ts:24`

```ts
function pcmDuration: (a: PcmAudio) => number
```

### pcmFrames

*function* · `packages/media/src/sound-file.ts:23`

```ts
function pcmFrames: (a: PcmAudio) => number
```

### pcmFromBuffer

*function* · `packages/media/src/sound-io.ts:63`

```ts
function pcmFromBuffer(b: AudioBuffer): PcmAudio
```

The samples of a Web Audio buffer (copied).

### peakOf

*function* · `packages/media/src/sound-file.ts:341`

```ts
function peakOf(a: PcmAudio): number
```

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

### pickMime

*function* · `packages/media/src/recorder.ts:43`

```ts
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).

### playSynth

*function* · `packages/media/src/synth.ts:130`

```ts
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.

### readMp3Info

*function* · `packages/media/src/mp3.ts:206`

```ts
function readMp3Info(b: Uint8Array): Mp3Info
```

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

### readWavInfo

*function* · `packages/media/src/sound-file.ts:75`

```ts
function readWavInfo(bytes: Uint8Array): WavInfo
```

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

### renderSynth

*function* · `packages/media/src/sound-io.ts:106`

```ts
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.

### resample

*function* · `packages/media/src/sound-file.ts:314`

```ts
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).

### scanMp3

*function* · `packages/media/src/mp3.ts:129`

```ts
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).

### setWebmDuration

*function* · `packages/media/src/recorder.ts:77`

```ts
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.

### sliceSound

*function* · `packages/media/src/sound-file.ts:369`

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

A part of the sound by frames.

### sniffSound

*function* · `packages/media/src/sound-file.ts:27`

```ts
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.

### soundFormatOf

*function* · `packages/media/src/sound-file.ts:35`

```ts
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`...).

### soundInfo

*function* · `packages/media/src/sound-io.ts:29`

```ts
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.

### spatialFromUnreal

*function* · `packages/media/src/lamp-sounds.ts:104`

```ts
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.

### synthParams

*function* · `packages/media/src/synth.ts:90`

```ts
function synthParams(r: SynthRecipe): string[]
```

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

### synthSeconds

*function* · `packages/media/src/sound-io.ts:92`

```ts
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).

### textOffset

*function* · `packages/media/src/text.ts:22`

```ts
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).

### toMono

*function* · `packages/media/src/sound-file.ts:295`

```ts
function toMono(a: PcmAudio): PcmAudio
```

Mix to one channel (the mean).

### toStereo

*function* · `packages/media/src/sound-file.ts:303`

```ts
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).

### trimSilence

*function* · `packages/media/src/sound-file.ts:356`

```ts
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.

### validateSynth

*function* · `packages/media/src/synth.ts:100`

```ts
function validateSynth(r: SynthRecipe): string[]
```

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

### waveform

*function* · `packages/media/src/sound-file.ts:374`

```ts
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.

### writeWebm

*function* · `packages/media/src/capture.ts:57`

```ts
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.

## Interfaces

### AmbientOptions

*interface* · `packages/media/src/ambient.ts:5`

```ts
interface AmbientOptions
```

- `tag?: string` — the zones' tag for the listener: the entity whose zone picks the ambience (default "player")
- `fade?: number` — seconds of cross-fade between ambiences (default 1.5)

### AudioOptions

*interface* · `packages/media/src/audio.ts:78`

```ts
interface AudioOptions
```

- `createContext?: () => AudioContext` — make the context (tests pass a fake; default `new AudioContext()`)
- `gestureTarget?: EventTarget | false` — where 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?: number` — a 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?: number` — At 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`

### AudioPlayerParams

*interface* · `packages/media/src/audio-player.ts:4`

```ts
interface AudioPlayerParams extends MediaPlayerParams
```

- `audio?: HTMLAudioElement` — an audio element you made (a MediaStream, a test double)

### Capture

*interface* · `packages/media/src/capture.ts:128`

```ts
interface Capture
```

- `format: 'webm' | 'png'`
- `mime: string` — e.g. `video/webm;codecs=vp9`, or `image/png`
- `frames: number`
- `fps: number`
- `width: number`
- `height: number`
- `durationMs: number` — simulated time covered, ms (frames / fps)
- `blob?: Blob` — the video (webm)
- `pngs?: Blob[]` — the pictures (png without `onFrame`)
- `aborted: boolean` — true when `signal` stopped it early

### CaptureOptions

*interface* · `packages/media/src/capture.ts:92`

```ts
interface CaptureOptions
```

- `fps?: number` — frames per second of the result, and the simulated time between frames (default 30)
- `seconds?: number` — how long to capture, simulated seconds (default 1); or `frames`
- `frames?: number`
- `width?: number` — size of the result (default: the canvas's render size)
- `height?: number`
- `supersample?: number` — render 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?: number` — bits per second (default about 0.12 bit per pixel and frame)
- `keyEvery?: number` — a key frame every this many frames (default 2 s of frames)
- `advance?: (dt: number) => void` — move the simulation by dt seconds (default: the world's `advance`, which runs its fixed steps)
- `render?: () => void` — draw one frame (default: `scene.render()`)
- `beforeFrame?: (i: number, t: number) => void` — called 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?: AbortSignal` — stops 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`

### CuePoint

*interface* · `packages/media/src/sound-file.ts:15`

```ts
interface CuePoint
```

- `id: number`
- `frame: number`
- `label?: string`

### DecodedSound

*interface* · `packages/media/src/sound-io.ts:42`

```ts
interface DecodedSound extends PcmAudio
```

- `info: SoundInfo`

### EncodedFrame

*interface* · `packages/media/src/capture.ts:36`

```ts
interface EncodedFrame
```

- `data: Uint8Array`
- `timeMs: number` — presentation time of the frame, ms
- `key: boolean`

### FilterSpec

*interface* · `packages/media/src/synth.ts:18`

```ts
interface FilterSpec
```

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

### HtmlScreenParams

*interface* · `packages/media/src/html.ts:7`

```ts
interface HtmlScreenParams
```

- `url?: string` — the page to show (its stylesheets, images and fonts are fetched too: they need CORS, or `fetch` that gets around it)
- `html?: string` — or the page as text; `base` then resolves its relative links
- `base?: string`
- `width?: number` — size of the screen in metres (default 4 x 2.25)
- `height?: number`
- `pxWidth?: number` — the 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?: number` — when 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?: number` — texture size = viewport x this (default 1; 2 for sharper text on a screen seen close)
- `fetch?: HtmlFetch` — replace `fetch`
- `lit?: boolean` — lit by the scene like a poster (default false: it glows like a screen)

### LampSoundsOptions

*interface* · `packages/media/src/lamp-sounds.ts:14`

```ts
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?: number` — 0..1, default 1 (Unreal: the cue's volume multiplier x the component's)
- `bus?: NonNullable<MediaPlayerParams['bus']>` — default 'ambient'
- `offset?: Vec3` — metres added to a lamp's position (Unreal: the audio component's offset from the actor)
- `max?: number` — how 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 | undefined` — the element a player plays through (a test double); default a new `Audio`

### LampSoundSource

*interface* · `packages/media/src/lamp-sounds.ts:9`

```ts
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`

### LoopPoints

*interface* · `packages/media/src/sound-file.ts:14`

```ts
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`

### MediaPlayer

*interface* · `packages/media/src/player.ts:13`

```ts
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: number` — seconds; `duration` is NaN until known and Infinity for a live stream
- `readonly duration: number`
- `volume: number` — 0..1
- `muted: boolean`
- `rate: number` — playback speed, 1 = normal
- `play(): void`
- `pause(): void`
- `toggle(): void`
- `stop(): void` — pause and go back to the start
- `seek(seconds: number): void`
- `readonly tracks: readonly string[]`
- `readonly index: number` — index 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)

### MediaPlayerParams

*interface* · `packages/media/src/player.ts:49`

```ts
interface MediaPlayerParams
```

- `src?: string` — one source: a file or an HLS playlist (.m3u8)
- `tracks?: string[]` — or a queue of them
- `start?: number` — index of the track to start with
- `repeat?: Repeat`
- `loop?: boolean` — shorthand for `repeat: 'one'`
- `shuffle?: boolean`
- `volume?: number` — 0..1 (default 1)
- `muted?: boolean`
- `rate?: number`
- `bus?: Bus` — the 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?: string` — where hls.js is, for browsers that cannot play HLS themselves (default `hls/hls.min.js` under the library folder)
- `autoplay?: boolean` — start by itself (default true; the sound waits for the first user action)
- `random?: () => number` — replaces Math.random for the shuffle (a seeded one for tests, replays)

### Mp3DecodeOptions

*interface* · `packages/media/src/mp3.ts:380`

```ts
interface Mp3DecodeOptions
```

- `gapless?: boolean` — drop the encoder's delay and padding (from the LAME/Xing header) so the sound is exactly the length that was encoded; default true

### Mp3EncodeOptions

*interface* · `packages/media/src/mp3.ts:810`

```ts
interface Mp3EncodeOptions
```

- `bitrate?: number` — kbit/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?: number` — Hz above which nothing is kept; default by bitrate
- `rate?: number` — a 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?: string` — the encoder name written to the Info header (up to 9 characters), default "Ferret"

### Mp3Frame

*interface* · `packages/media/src/mp3.ts:80`

```ts
interface Mp3Frame
```

- `pos: number`
- `size: number`
- `header: Mp3FrameHeader`

### Mp3FrameHeader

*interface* · `packages/media/src/mp3.ts:15`

```ts
interface Mp3FrameHeader
```

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

### Mp3Info

*interface* · `packages/media/src/mp3.ts:82`

```ts
interface Mp3Info
```

- `version: MpegVersion`
- `layer: 1 | 2 | 3`
- `rate: number`
- `channels: 1 | 2`
- `mode: ChannelMode`
- `frames: number` — frames in the file
- `samples: number` — PCM 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: number` — average kbit/s
- `vbr: boolean` — variable bitrate (a Xing header, or frames of different bitrates)
- `delay?: number` — the encoder's delay and padding in PCM frames from the LAME header, when there is one
- `padding?: number`
- `skip: number` — how many PCM frames of the start the decoder drops to get the gapless result (the encoder delay + 529 of the decoder)
- `encoder?: string` — the encoder's own name from the LAME/Xing header, e.g. "LAME3.100"
- `dataStart: number` — where the first frame is (after an ID3v2 tag) and where the last ends (before an ID3v1 tag)
- `dataEnd: number`

### Mp3Scan

*interface* · `packages/media/src/mp3.ts:110`

```ts
interface Mp3Scan
```

- `info: Mp3Info`
- `frames: Mp3Frame[]`

### ParamRef

*interface* · `packages/media/src/synth.ts:13`

```ts
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`

### PassByParams

*interface* · `packages/media/src/pass-by.ts:22`

```ts
interface PassByParams
```

- `sound: string` — a sound defined in the AudioService
- `near: number` — metres from the listener (the active camera) that fire it
- `far?: number` — metres it must go past before it can fire again (default 2.5 x near)
- `volume?: number`
- `spatial?: Spatial`

### PcmAudio

*interface* · `packages/media/src/sound-file.ts:7`

```ts
interface PcmAudio
```

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

- `rate: number` — frames per second
- `channels: Float32Array[]`

### PlayOptions

*interface* · `packages/media/src/audio.ts:49`

```ts
interface PlayOptions
```

- `at?: BABYLON.TransformNode | BABYLON.Vector3` — where the sound comes from; a node it follows. Without it the sound is not positioned (UI, music)
- `volume?: number`
- `loop?: boolean`
- `bus?: Bus`
- `fadeIn?: number` — seconds to fade in
- `spatial?: Spatial`
- `delay?: number` — seconds from now on the audio clock (exact, unlike a timer)
- `params?: Record<string, number>` — a synthesised sound's live parameters at its start
- `lowpass?: number` — a lowpass in the path, Hz: the highs a far sound has lost to the air (below 20 kHz only)
- `pan?: number` — left (-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?: () => void` — called once when the sound is over: it ended, was stopped, or never started (audio locked, culled, a file that would not load)

### RecorderOptions

*interface* · `packages/media/src/recorder.ts:7`

```ts
interface RecorderOptions
```

- `canvas?: HTMLCanvasElement` — the canvas to record (default: the engine's rendering canvas)
- `fps?: number` — frames per second asked of the capture (default 30)
- `videoBitsPerSecond?: number` — video bit rate (default: the browser's)
- `audio?: boolean` — add 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?: number` — ask 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 }) => MediaRecorder` — replace the browser's MediaRecorder (tests)
- `isTypeSupported?: (mime: string) => boolean`

### Recording

*interface* · `packages/media/src/recorder.ts:25`

```ts
interface Recording
```

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

### RenderSynthOptions

*interface* · `packages/media/src/sound-io.ts:76`

```ts
interface RenderSynthOptions
```

- `rate?: number` — frames per second, default 44100
- `seconds?: number` — seconds 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?: number` — the volume of the sound, default 1
- `createContext?: (channels: number, length: number, rate: number) => OfflineAudioContext` — replace `new OfflineAudioContext(...)` (Node has none; tests)

