1use crate::{Error, Result};
4
5use super::codec::pcm;
6
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum AudioCodec {
11 #[default]
13 PcmS16,
14}
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct AudioEncodeProfile {
19 pub codec: AudioCodec,
21 pub sample_rate: u32,
23 pub channel_count: u32,
25 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#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct EncodedAudioPacket {
43 pub bitstream: Vec<u8>,
45 pub presentation_frame: i64,
47 pub duration_frames: u32,
49}
50
51#[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 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 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 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 pub fn close(&mut self) {
155 self.state = None;
156 }
157
158 #[must_use]
160 pub const fn is_open(&self) -> bool {
161 self.state.is_some()
162 }
163
164 #[must_use]
166 pub fn profile(&self) -> Option<&AudioEncodeProfile> {
167 self.state.as_ref().map(|state| &state.profile)
168 }
169
170 #[must_use]
174 pub const fn codec_config(&self) -> &[u8] {
175 &[]
176 }
177
178 #[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}