Skip to main content

oa/audio/
encoder.rs

1//! Stateful native audio encoding.
2
3use crate::{Error, Result};
4
5use super::codec::pcm;
6
7/// Elementary audio representation produced by [`AudioEncoder`].
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum AudioCodec {
11	/// Signed little-endian 16-bit PCM samples.
12	#[default]
13	PcmS16,
14}
15
16/// Configuration for one streaming audio encoder.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct AudioEncodeProfile {
19	/// Elementary codec written into each packet.
20	pub codec: AudioCodec,
21	/// Input sample rate in hertz.
22	pub sample_rate: u32,
23	/// Number of interleaved input channels.
24	pub channel_count: u32,
25	/// Preferred number of frames emitted per packet.
26	pub frames_per_packet: u32,
27}
28
29impl Default for AudioEncodeProfile {
30	fn default() -> Self {
31		Self {
32			codec: AudioCodec::PcmS16,
33			sample_rate: 48_000,
34			channel_count: 2,
35			frames_per_packet: 1_024,
36		}
37	}
38}
39
40/// One encoded elementary-stream packet with frame-domain timing.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct EncodedAudioPacket {
43	/// Encoded packet bytes.
44	pub bitstream: Vec<u8>,
45	/// Zero-based input frame corresponding to the packet's first sample.
46	pub presentation_frame: i64,
47	/// Number of interleaved frames represented by the packet.
48	pub duration_frames: u32,
49}
50
51/// Stateful deterministic PCM-S16 audio encoder.
52///
53/// Input is interleaved FP32. Complete configured packets are emitted by
54/// [`encode`](Self::encode); [`flush`](Self::flush) emits a final partial
55/// packet. [`close`](Self::close) deliberately discards an unflushed partial
56/// packet, matching the donor lifecycle contract. Dropping the encoder only
57/// releases host state and never flushes implicitly.
58#[derive(Debug)]
59pub struct AudioEncoder {
60	state: Option<EncoderState>,
61}
62
63#[derive(Debug)]
64struct EncoderState {
65	profile: AudioEncodeProfile,
66	channels: usize,
67	packet_samples: usize,
68	pending: Vec<f32>,
69	next_input_frame: i64,
70}
71
72impl AudioEncoder {
73	/// Create one open encoder with a checked profile.
74	///
75	/// # Errors
76	///
77	/// Returns an error unless the profile has a nonzero sample rate, one to
78	/// eight channels, a nonzero packet size, and an addressable packet shape.
79	pub fn new(profile: AudioEncodeProfile) -> Result<Self> {
80		if profile.sample_rate == 0
81			|| !(1..=8).contains(&profile.channel_count)
82			|| profile.frames_per_packet == 0
83		{
84			return Err(Error::invalid_argument(
85				"audio encoder requires a sample rate, 1..=8 channels, and a packet size",
86			));
87		}
88		let channels = usize::try_from(profile.channel_count)
89			.map_err(|_| Error::invalid_argument("audio channel count exceeds usize"))?;
90		let packet_samples = usize::try_from(profile.frames_per_packet)
91			.ok()
92			.and_then(|frames| frames.checked_mul(channels))
93			.ok_or_else(|| Error::invalid_argument("audio packet shape exceeds usize"))?;
94		packet_samples
95			.checked_mul(size_of::<i16>())
96			.ok_or_else(|| Error::invalid_argument("audio packet byte size exceeds usize"))?;
97		Ok(Self {
98			state: Some(EncoderState {
99				profile,
100				channels,
101				packet_samples,
102				pending: Vec::new(),
103				next_input_frame: 0,
104			}),
105		})
106	}
107
108	/// Append complete interleaved frames and emit every full packet now ready.
109	///
110	/// # Errors
111	///
112	/// Returns an error when the encoder is closed, the input is empty or does
113	/// not contain complete frames, buffered allocation fails, or timing exceeds
114	/// the signed frame domain.
115	pub fn encode(&mut self, interleaved: &[f32]) -> Result<Vec<EncodedAudioPacket>> {
116		let state = self
117			.state
118			.as_mut()
119			.ok_or_else(|| Error::failed_precondition("audio encoder is closed"))?;
120		if interleaved.is_empty() || !interleaved.len().is_multiple_of(state.channels) {
121			return Err(Error::invalid_argument(
122				"audio encoder input must contain complete non-empty interleaved frames",
123			));
124		}
125		state
126			.pending
127			.try_reserve(interleaved.len())
128			.map_err(|_| Error::resource_exhausted("audio encoder input allocation failed"))?;
129		state.pending.extend_from_slice(interleaved);
130		emit_complete_packets(state)
131	}
132
133	/// Emit the final partial packet, if any.
134	///
135	/// Calling `flush` on a closed encoder is idempotent and returns no packets.
136	///
137	/// # Errors
138	///
139	/// Returns an error when packet allocation fails or timing exceeds the
140	/// signed frame domain.
141	pub fn flush(&mut self) -> Result<Vec<EncodedAudioPacket>> {
142		let Some(state) = self.state.as_mut() else {
143			return Ok(Vec::new());
144		};
145		if state.pending.is_empty() {
146			return Ok(Vec::new());
147		}
148		let frames = u32::try_from(state.pending.len() / state.channels)
149			.map_err(|_| Error::out_of_range("audio flush frame count exceeds u32"))?;
150		Ok(vec![emit_packet(state, frames)?])
151	}
152
153	/// Discard any unflushed partial packet and close the encoder.
154	pub fn close(&mut self) {
155		self.state = None;
156	}
157
158	/// Return whether this encoder still accepts input.
159	#[must_use]
160	pub const fn is_open(&self) -> bool {
161		self.state.is_some()
162	}
163
164	/// Return the active profile, or `None` after close.
165	#[must_use]
166	pub fn profile(&self) -> Option<&AudioEncodeProfile> {
167		self.state.as_ref().map(|state| &state.profile)
168	}
169
170	/// Return codec initialization bytes.
171	///
172	/// PCM-S16 has no codec configuration record.
173	#[must_use]
174	pub const fn codec_config(&self) -> &[u8] {
175		&[]
176	}
177
178	/// Return encoder-delay frames.
179	///
180	/// PCM-S16 introduces no priming delay.
181	#[must_use]
182	pub const fn priming_frames(&self) -> u32 {
183		0
184	}
185}
186
187fn emit_complete_packets(state: &mut EncoderState) -> Result<Vec<EncodedAudioPacket>> {
188	let packet_count = state.pending.len() / state.packet_samples;
189	let mut packets = Vec::new();
190	packets
191		.try_reserve_exact(packet_count)
192		.map_err(|_| Error::resource_exhausted("audio packet list allocation failed"))?;
193	for _ in 0..packet_count {
194		packets.push(emit_packet(state, state.profile.frames_per_packet)?);
195	}
196	Ok(packets)
197}
198
199fn emit_packet(state: &mut EncoderState, frames: u32) -> Result<EncodedAudioPacket> {
200	let samples = usize::try_from(frames)
201		.ok()
202		.and_then(|frames| frames.checked_mul(state.channels))
203		.ok_or_else(|| Error::invalid_argument("audio packet sample count exceeds usize"))?;
204	let bitstream = match state.profile.codec {
205		AudioCodec::PcmS16 => pcm::encode_s16(&state.pending[..samples])?,
206	};
207	let packet = EncodedAudioPacket {
208		bitstream,
209		presentation_frame: state.next_input_frame,
210		duration_frames: frames,
211	};
212	state.next_input_frame = state
213		.next_input_frame
214		.checked_add(i64::from(frames))
215		.ok_or_else(|| Error::out_of_range("audio presentation frame exceeds i64"))?;
216	state.pending.drain(..samples);
217	Ok(packet)
218}