# Audio Peripheral Domain: virtual hardware: audio Function: normative Didactic companion: [Audio admission and lifecycle delivery](../../../discussion/lessons/DSC-0055-guest-audio-voice-control/LSN-0069-audio-admission-needs-a-delivery-boundary-and-independent-lifecycle-control.md). ## 1 Scope and machine limits The AUDIO peripheral provides command-driven PCM playback on **16 explicitly selected voices**. Each voice plays one immutable mono PCM16 sample, with independent volume, stereo pan, playback rate and optional looping. The output target is **48,000 Hz stereo**, with saturating mixing. Hosts may use normalized floating-point device buffers to represent that output. The guest controls playback at logical-frame boundaries. The host renders samples independently of the 60 Hz game loop. These are separate clocks: a successful syscall admits a command, without promising that sound has already reached the device or a fixed latency in milliseconds. This surface does not define playback handles, completion queries/events, automatic voice allocation, music sequencing, synthesis, streaming, envelopes or background audio producers. ## 2 Guest ABI v1 Every entry requires capability `AUDIO`, returns exactly one `status:int`, and has fixed syscall cost **5 cycles**, including operational rejection. Structural ABI misuse follows the VM trap policy. Mixing time is host work, not the syscall's logical cycle charge. | Identity | ID | Arguments in order | | --- | --- | --- | | `audio.play_sample` | `0x3001` | `sample:int, voice:int, volume:int, pan:int, pitch:number` | | `audio.play` | `0x3002` | `bank:int, sample:int, voice:int, volume:int, pan:int, pitch:number, loop:int` | | `audio.stop` | `0x3003` | `voice:int` | | `audio.set_volume` | `0x3004` | `voice:int, volume:int` | | `audio.set_pan` | `0x3005` | `voice:int, pan:int` | | `audio.set_pitch` | `0x3006` | `voice:int, pitch:number` | `number` means the existing VM numeric carriers accepted by audio playback, including integer and floating-point values; it is not a new ABI type. `play_sample` uses bank 0 and looping off. Both plays use internal priority 0. The public API has no priority argument. ### 2.1 Ranges and validation - Voice: integer **0..15**. - Bank: integer **0..15**, referring to an installed sound bank. Validate before narrowing; 256 must never alias bank 0. - Sample index: integer **0..65535**; the sample must exist in the selected bank. - Volume: integer **0..255**. Zero silences output while playback position continues advancing. - Pan: integer **0..255**, from fully left to fully right. The mixer uses equal-power gains `sqrt(1-pan/255)` and `sqrt(pan/255)`. - Pitch: **finite and strictly positive**; 1 means original speed. NaN, infinity, zero and negative values are rejected. No 0.25..4 restriction is imposed. Setters and plays use the same range. - Loop: integer **0 or 1**, meaning off or on. Other values are rejected, without normalization. Structural type/shape/capability checks precede operational validation. Validate voice first, then other arguments/resources, then command admission. Rejection must not alter playback state or enqueue a command. When multiple operational errors exist, voice takes precedence; bank validity precedes sample lookup for bank playback. ### 2.2 Status values | Value | Name | Meaning | | --- | --- | --- | | 0 | `OK` | Command admitted; application is asynchronous | | 1 | `VOICE_INVALID` | Voice outside 0..15 | | 2 | `SAMPLE_NOT_FOUND` | Sample absent from the selected installed bank | | 3 | `ARG_RANGE_INVALID` | Invalid sample index, volume, pan, pitch or loop value | | 4 | `ASSET_NOT_FOUND` | Reserved existing status | | 5 | `NO_EFFECT` | Reserved existing status; inactive-voice controls do not use it | | 6 | `BANK_INVALID` | Invalid or uninstalled sound bank | | 7 | `COMMAND_LIMIT` | Current guest batch already admitted 1,024 commands | Stop and setters can return 0, 1, 3 where applicable, or 7. Stopping an inactive voice or changing its parameters succeeds. No helper based on the driver's former activity mirror is exposed as a playback-completion query. ## 3 Ordering and voice reuse Commands in a published batch apply in emission order before a subsequent output buffer. The API does not promise sample offsets within a buffer. A play explicitly replaces the selected voice, resets its position, and supplies every playback parameter. There is no automatic stealing of another voice. `play(A), stop, play(B)` on one voice leaves B playing. A setter following play changes that playback without resetting position. Stop is idempotent, releases the sample and silences the voice. Setters on inactive voices do not establish defaults for future plays. ## 4 Admission, publication and backpressure A logical frame admits at most **1,024 commands**, shared by both plays and all four controls. Invalid calls do not consume quota. An excess call returns `COMMAND_LIMIT`; a rejected stop requires a guest retry. Quota depends on the logical frame, not the device callback speed or number of physical host ticks. Except for the lifecycle prefix publication defined below, commands remain staged until successful logical-frame completion: explicit `FRAME_SYNC` or the runtime's implicit frame end when the entry function returns (`EndOfRom`). An aborted/faulted frame or `HALT` cancels its unpublished commands. Debugger stepping preserves staging and publishes at either successful completion boundary. The transport holds **one pending frame batch**, in addition to producer staging and a batch already taken by the mixer. The guest waits for pending publication to be consumed before advancing further; the host continues handling events. Accepted commands must not be silently dropped because a device queue is full. The audio callback must not wait on a producer lock: if a short publication critical section is busy, it retries on a later buffer. Lifecycle callbacks have independent staging and one independent pending publication slot. Callback admission is bounded to **1,024 guest commands per callback**. This prevents an occupied frame slot or exhausted frame quota from blocking callback controls. A successful callback publishes without requiring `FRAME_SYNC`; a failed callback cancels its staged commands. Pending frame publication precedes subsequent lifecycle publication; guest frames do not advance while either publication slot is occupied. A successful lifecycle boundary publishes the interrupted frame's staged prefix **before** the callback commands, together in the lifecycle delivery. This explicit early-publication boundary preserves emission order: `play` before Home followed by `stop` in the callback must remain stopped after resume. An absent optional callback still completes this boundary. The combined delivery holds at most **2,048 commands**: up to 1,024 from the interrupted frame plus 1,024 from the callback. Flushing a prefix does **not** replenish that frame's admission quota. The resumed frame retains its admitted-command count across repeated pause/resume transitions until normal frame completion, abort or session reset. The prefix is not published again when the frame completes. Failed callbacks cancel their unpublished commands and prefix. A later fault in the resumed frame cannot roll back a prefix already published at the earlier lifecycle boundary. ## 5 Pause, reset and sessions Home and debugger pause stop progression of Game voices, preserving their position. Resume continues from that position. Callback commands are applied before resumed PCM generation. Pause state and session invalidation are internal controls independent of guest quota and pending batch capacity. Reset, termination, crash or cartridge replacement ends the audio session, stops all its voices and invalidates its pending/staged commands. Internal session generations prevent old deliveries from restarting playback. Ending a session may cancel previously admitted commands. Silence is guaranteed from processing the transition in the mixer; buffers already submitted to a physical device cannot be recalled. ## 6 Samples, interpolation and ownership Samples are immutable PCM16 mono, with a source sample rate and optional loop bounds. With looping off, playback ignores all loop markers and ends at the full sample length. With looping on, both markers must be present and satisfy `start < end <= sample length`; otherwise the loop interval is the full sample `[0, length)`. Playback starts at position zero, preserving the intro before the selected loop start, and wraps at the exclusive loop end. Empty samples terminate without reading PCM data. Linear interpolation uses fractional playback position. With looping off, the next value is the next actual sample frame, or zero beyond the full sample length. With looping on, interpolation across the selected loop end uses the loop-start frame. Playback rate combines source/output sample-rate ratio and pitch. Loop steps may cross multiple repetitions; finite positive pitch, including `f64::MAX`, must not accidentally terminate a short loop or produce an infinite position. Unloading or replacing a bank does not interrupt a sample already retained by an admitted command or mixer voice. New plays resolve the current bank. Memory can remain retained until the command is cancelled or the playback ends, stops, is replaced, or its session ends. The driver must not retain a second sample reference indefinitely after the mixer observes natural completion. ## 7 Host responsibilities and evidence The desktop host consumes batches, mixes PCM and schedules the physical output. If no output device is available, it consumes committed batches silently. A failed or stalled device is diagnosed and detached so pending publication cannot block the guest indefinitely. The desktop implementation treats two seconds without callback progress as a stalled output. Headless execution consumes committed batches silently and preserves incomplete frame/callback staging. It validates admission and runtime behavior, without proving audible output. Synthetic mixer tests establish signal behavior; a real device smoke establishes stream initialization and callback consumption, while listening remains a separate observation. Bit-identical PCM across physical devices is not required.