diff --git a/crates/lxst-core/src/lib.rs b/crates/lxst-core/src/lib.rs index f548d06..b873046 100644 --- a/crates/lxst-core/src/lib.rs +++ b/crates/lxst-core/src/lib.rs @@ -12,7 +12,11 @@ mod synthetic; mod telephony; mod wire; -pub use opus::{OpusCodecError, OpusDecoderState, OpusEncoderState}; +pub use opus::{ + OPUS_ENCODED_FRAME_MAX_BYTES, OPUS_ENCODED_PACKET_MAX_BYTES, OPUS_MONO_DECODE_SAMPLE_RATE_HZ, + OpusCodecError, OpusDecoderState, OpusEncoderState, OpusMonoDecoder, + opus_packet_duration_samples_48k, +}; pub use profile::{AudioCodec, OpusApplication, OpusProfile, Profile, SignallingStatus}; pub use raw::RawAudioFrame; pub use stream::{ diff --git a/crates/lxst-core/src/opus.rs b/crates/lxst-core/src/opus.rs index 8020018..e473e47 100644 --- a/crates/lxst-core/src/opus.rs +++ b/crates/lxst-core/src/opus.rs @@ -3,6 +3,18 @@ use thiserror::Error; use crate::{AudioCodec, CodecKind, Frame, OpusApplication, OpusProfile, Profile, RawAudioFrame}; +/// The fixed output clock used by the interoperable Opus packet decoder. +pub const OPUS_MONO_DECODE_SAMPLE_RATE_HZ: u32 = 48_000; + +/// The maximum encoded size of one frame contained in an Opus packet. +pub const OPUS_ENCODED_FRAME_MAX_BYTES: usize = 1_275; + +/// The maximum encoded Opus packet accepted by the interoperable decoder. +/// +/// RFC 7845 bounds one Opus packet at 61,440 encoded bytes. This is distinct from the 1,275-byte +/// limit for each frame inside the packet and from the bounded decoded PCM allocation. +pub const OPUS_ENCODED_PACKET_MAX_BYTES: usize = 61_440; + #[derive(Debug, Error, PartialEq, Eq)] pub enum OpusCodecError { #[error("profile {0:?} does not use Opus")] @@ -26,6 +38,20 @@ pub enum OpusCodecError { UnsupportedSubpacketLayout, #[error("malformed Opus packet: {0}")] MalformedPacket(&'static str), + #[error("encoded Opus packet length {actual} exceeds the {maximum}-byte ceiling")] + EncodedPacketTooLarge { actual: usize, maximum: usize }, + #[error("encoded Opus frame {index} length {actual} exceeds the {maximum}-byte ceiling")] + EncodedFrameTooLarge { + index: usize, + actual: usize, + maximum: usize, + }, + #[error("unsupported Opus packet duration: {samples_48k} samples at 48 kHz")] + UnsupportedPacketDuration { samples_48k: usize }, + #[error( + "Opus decoder returned {actual} sample frames for a packet frame containing {expected}" + )] + DecodedPacketDurationMismatch { expected: usize, actual: usize }, #[error("Opus codec error: {0}")] Codec(String), #[error("LXST wire error: {0}")] @@ -310,6 +336,271 @@ impl OpusDecoderState { } } +/// A stateful decoder for interoperable mono Opus packets at the Opus 48 kHz clock. +/// +/// Unlike [`OpusDecoderState`], this decoder is not tied to an LXST call profile. It accepts +/// every structurally legal packet duration from 2.5 through 120 milliseconds and preserves +/// decoder state across calls. The returned [`RawAudioFrame`] is always mono at 48 kHz. +pub struct OpusMonoDecoder { + decoder: OpusDecoder, +} + +impl OpusMonoDecoder { + pub fn new() -> Result { + let decoder = OpusDecoder::new(OPUS_MONO_DECODE_SAMPLE_RATE_HZ as i32, 1) + .map_err(|err| OpusCodecError::Codec(err.to_string()))?; + Ok(Self { decoder }) + } + + pub const fn sample_rate_hz(&self) -> u32 { + OPUS_MONO_DECODE_SAMPLE_RATE_HZ + } + + pub const fn channels(&self) -> u8 { + 1 + } + + /// Decodes one complete Opus packet to mono PCM at 48 kHz. + pub fn decode_packet(&mut self, packet: &[u8]) -> Result { + let inspected = inspect_opus_packet(packet)?; + if inspected.channels != 1 { + return Err(OpusCodecError::ChannelMismatch { + expected: 1, + actual: inspected.channels, + }); + } + + let mut samples = Vec::with_capacity(inspected.duration_samples_48k); + let direct_toc = inspected.toc & !0x03; + for payload in inspected.frames { + let mut direct_packet = Vec::with_capacity(payload.len() + 1); + direct_packet.push(direct_toc); + direct_packet.extend_from_slice(payload); + + let output_start = samples.len(); + samples.resize(output_start + inspected.samples_per_frame_48k, 0.0); + let decoded = self + .decoder + .decode( + &direct_packet, + inspected.samples_per_frame_48k, + &mut samples[output_start..], + ) + .map_err(|err| OpusCodecError::Codec(err.to_string()))?; + if decoded != inspected.samples_per_frame_48k { + return Err(OpusCodecError::DecodedPacketDurationMismatch { + expected: inspected.samples_per_frame_48k, + actual: decoded, + }); + } + } + + debug_assert_eq!(samples.len(), inspected.duration_samples_48k); + Ok(RawAudioFrame::new(1, samples)?) + } +} + +/// Returns a supported packet's total duration in samples at the Opus 48 kHz clock. +/// +/// The packet is structurally inspected using the framing rules from RFC 6716. Every legal +/// duration from 2.5 through 120 milliseconds is accepted in 2.5 millisecond increments. +pub fn opus_packet_duration_samples_48k(packet: &[u8]) -> Result { + Ok(inspect_opus_packet(packet)?.duration_samples_48k) +} + +#[derive(Debug)] +struct InspectedOpusPacket<'a> { + toc: u8, + channels: u8, + samples_per_frame_48k: usize, + duration_samples_48k: usize, + frames: Vec<&'a [u8]>, +} + +fn inspect_opus_packet(packet: &[u8]) -> Result, OpusCodecError> { + if packet.is_empty() { + return Err(OpusCodecError::MalformedPacket("packet is empty")); + } + if packet.len() > OPUS_ENCODED_PACKET_MAX_BYTES { + return Err(OpusCodecError::EncodedPacketTooLarge { + actual: packet.len(), + maximum: OPUS_ENCODED_PACKET_MAX_BYTES, + }); + } + + let toc = packet[0]; + let samples_per_frame_48k = opus_samples_per_frame_48k(toc); + let frames = parse_opus_packet_frames(packet)?; + for (index, frame) in frames.iter().enumerate() { + if frame.len() > OPUS_ENCODED_FRAME_MAX_BYTES { + return Err(OpusCodecError::EncodedFrameTooLarge { + index, + actual: frame.len(), + maximum: OPUS_ENCODED_FRAME_MAX_BYTES, + }); + } + } + let duration_samples_48k = samples_per_frame_48k + .checked_mul(frames.len()) + .ok_or(OpusCodecError::MalformedPacket("packet duration overflows"))?; + if duration_samples_48k > 5_760 { + return Err(OpusCodecError::MalformedPacket( + "packet duration exceeds 120 milliseconds", + )); + } + if duration_samples_48k == 0 || duration_samples_48k % 120 != 0 { + return Err(OpusCodecError::UnsupportedPacketDuration { + samples_48k: duration_samples_48k, + }); + } + + Ok(InspectedOpusPacket { + toc, + channels: if toc & 0x04 == 0 { 1 } else { 2 }, + samples_per_frame_48k, + duration_samples_48k, + frames, + }) +} + +// Straight from libopus opus_packet_get_samples_per_frame() for the fixed 48 kHz clock. +fn opus_samples_per_frame_48k(toc: u8) -> usize { + if toc & 0x80 != 0 { + let config = usize::from((toc >> 3) & 0x03); + ((OPUS_MONO_DECODE_SAMPLE_RATE_HZ as usize) << config) / 400 + } else if toc & 0x60 == 0x60 { + if toc & 0x08 != 0 { 960 } else { 480 } + } else { + let config = usize::from((toc >> 3) & 0x03); + if config == 3 { + 2_880 + } else { + ((OPUS_MONO_DECODE_SAMPLE_RATE_HZ as usize) << config) / 100 + } + } +} + +fn parse_opus_packet_frames(packet: &[u8]) -> Result, OpusCodecError> { + let toc = packet[0]; + let body = &packet[1..]; + match toc & 0x03 { + 0 => Ok(vec![body]), + 1 => { + if body.len() % 2 != 0 { + return Err(OpusCodecError::MalformedPacket( + "code 1 CBR payload has odd length", + )); + } + let frame_len = body.len() / 2; + Ok(vec![&body[..frame_len], &body[frame_len..]]) + } + 2 => { + let (first_len, length_bytes) = read_subframe_payload_len(body)?; + let payload = &body[length_bytes..]; + if first_len > payload.len() { + return Err(OpusCodecError::MalformedPacket( + "code 2 first frame exceeds packet payload", + )); + } + Ok(vec![&payload[..first_len], &payload[first_len..]]) + } + 3 => parse_code3_packet_frames(packet), + _ => unreachable!(), + } +} + +fn parse_code3_packet_frames(packet: &[u8]) -> Result, OpusCodecError> { + let count_byte = *packet.get(1).ok_or(OpusCodecError::MalformedPacket( + "code 3 packet is too short", + ))?; + let frame_count = usize::from(count_byte & 0x3F); + if frame_count == 0 { + return Err(OpusCodecError::MalformedPacket( + "code 3 frame count is zero", + )); + } + if frame_count > 48 { + return Err(OpusCodecError::MalformedPacket( + "code 3 frame count exceeds 48", + )); + } + + let mut cursor = 2usize; + let mut payload_end = packet.len(); + if count_byte & 0x40 != 0 { + let mut padding = 0usize; + loop { + let byte = usize::from(*packet.get(cursor).ok_or(OpusCodecError::MalformedPacket( + "code 3 padding exceeds packet", + ))?); + cursor += 1; + padding = padding + .checked_add(if byte == 255 { 254 } else { byte }) + .ok_or(OpusCodecError::MalformedPacket( + "code 3 padding length overflows", + ))?; + if byte != 255 { + break; + } + } + payload_end = packet + .len() + .checked_sub(padding) + .ok_or(OpusCodecError::MalformedPacket( + "code 3 padding exceeds packet", + ))?; + if cursor > payload_end { + return Err(OpusCodecError::MalformedPacket( + "code 3 padding exceeds payload", + )); + } + } + + if count_byte & 0x80 == 0 { + let payload = &packet[cursor..payload_end]; + if payload.len() % frame_count != 0 { + return Err(OpusCodecError::MalformedPacket( + "code 3 CBR payload is not evenly divisible", + )); + } + let frame_len = payload.len() / frame_count; + return Ok((0..frame_count) + .map(|index| { + let start = index * frame_len; + &payload[start..start + frame_len] + }) + .collect()); + } + + let mut lengths = Vec::with_capacity(frame_count); + for _ in 0..frame_count - 1 { + let (frame_len, length_bytes) = read_subframe_payload_len(&packet[cursor..payload_end])?; + cursor += length_bytes; + lengths.push(frame_len); + } + let declared = lengths.iter().sum::(); + let remaining = payload_end + .checked_sub(cursor) + .ok_or(OpusCodecError::MalformedPacket( + "code 3 payload cursor exceeds packet", + ))?; + if declared > remaining { + return Err(OpusCodecError::MalformedPacket( + "code 3 declared frame lengths exceed packet payload", + )); + } + lengths.push(remaining - declared); + + let mut frames = Vec::with_capacity(frame_count); + let mut payload_cursor = cursor; + for frame_len in lengths { + let next = payload_cursor + frame_len; + frames.push(&packet[payload_cursor..next]); + payload_cursor = next; + } + Ok(frames) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct PacketLayout { subframe_count: usize, @@ -574,6 +865,81 @@ mod tests { .unwrap() } + fn encoded_mono_packet(sample_frames: usize, bitrate_bps: i32) -> Vec { + let samples = (0..sample_frames) + .map(|index| { + let phase = std::f32::consts::TAU * 440.0 * index as f32 + / OPUS_MONO_DECODE_SAMPLE_RATE_HZ as f32; + phase.sin() * 0.2 + }) + .collect::>(); + let mut encoder = OpusEncoder::new( + OPUS_MONO_DECODE_SAMPLE_RATE_HZ as i32, + 1, + Application::RestrictedLowDelay, + ) + .unwrap(); + encoder.bitrate_bps = bitrate_bps; + encoder.use_cbr = true; + let mut packet = vec![0u8; OPUS_ENCODED_FRAME_MAX_BYTES + 1]; + let written = encoder + .encode(&samples, sample_frames, &mut packet) + .unwrap(); + packet.truncate(written); + assert_eq!(packet[0] & 0x03, 0); + assert_eq!(opus_samples_per_frame_48k(packet[0]), sample_frames); + packet + } + + fn encoded_twenty_ms_mono_packet() -> Vec { + encoded_mono_packet(960, 16_000) + } + + fn repacketize_cbr(packet: &[u8], frame_count: usize) -> Vec { + assert!((1..=48).contains(&frame_count)); + let toc = packet[0] & !0x03; + let payload = &packet[1..]; + let mut combined = Vec::new(); + match frame_count { + 1 => combined.push(toc), + 2 => combined.push(toc | 0x01), + _ => { + combined.push(toc | 0x03); + combined.push(frame_count as u8); + } + } + for _ in 0..frame_count { + combined.extend_from_slice(payload); + } + combined + } + + fn repacketize_vbr(packet: &[u8], frame_count: usize, padding: usize) -> Vec { + assert!((2..=48).contains(&frame_count)); + assert!(padding < 255); + let toc = packet[0] & !0x03; + let payload = &packet[1..]; + let mut combined = Vec::new(); + if frame_count == 2 && padding == 0 { + combined.push(toc | 0x02); + push_subframe_payload_len(&mut combined, payload.len()).unwrap(); + } else { + combined.push(toc | 0x03); + combined.push(0x80 | (frame_count as u8) | if padding == 0 { 0 } else { 0x40 }); + if padding != 0 { + combined.push(padding as u8); + } + for _ in 0..frame_count - 1 { + push_subframe_payload_len(&mut combined, payload.len()).unwrap(); + } + } + for _ in 0..frame_count { + combined.extend_from_slice(payload); + } + combined.resize(combined.len() + padding, 0); + combined + } + #[test] fn opus_encoder_rejects_codec2_profiles() { assert!(matches!( @@ -692,4 +1058,217 @@ mod tests { Profile::QualityMedium.sample_frames_per_packet() ); } + + #[test] + fn interoperable_packet_inspection_follows_rfc_vbr_lengths_and_padding() { + let toc = 0xF8; + + let mut code_two = vec![toc | 0x02, 252, 0]; + code_two.extend(std::iter::repeat_n(0, 253)); + assert_eq!(opus_packet_duration_samples_48k(&code_two).unwrap(), 1_920); + + let padded_code_three = [toc | 0x03, 0x43, 1, 0, 0, 0, 0]; + assert_eq!( + opus_packet_duration_samples_48k(&padded_code_three).unwrap(), + 2_880 + ); + } + + #[test] + fn interoperable_packet_inspection_accepts_every_two_and_half_ms_quantum() { + let toc = 0x80; + for frame_count in 1..=48 { + let packet = match frame_count { + 1 => vec![toc], + 2 => vec![toc | 0x01], + _ => vec![toc | 0x03, frame_count as u8], + }; + assert_eq!( + opus_packet_duration_samples_48k(&packet), + Ok(frame_count * 120) + ); + } + } + + #[test] + fn interoperable_decoder_decodes_rfc_duration_range_at_the_48khz_clock() { + let two_and_half = encoded_mono_packet(120, 64_000); + let five = encoded_mono_packet(240, 64_000); + let ten = encoded_mono_packet(480, 64_000); + let twenty = encoded_twenty_ms_mono_packet(); + let packets = [ + (two_and_half, 120), + (five, 240), + (ten.clone(), 480), + (twenty.clone(), 960), + (repacketize_cbr(&ten, 3), 1_440), + (repacketize_cbr(&twenty, 2), 1_920), + (repacketize_cbr(&twenty, 3), 2_880), + (repacketize_cbr(&twenty, 4), 3_840), + (repacketize_cbr(&twenty, 5), 4_800), + (repacketize_cbr(&twenty, 6), 5_760), + ]; + let mut decoder = OpusMonoDecoder::new().unwrap(); + assert_eq!(decoder.sample_rate_hz(), 48_000); + assert_eq!(decoder.channels(), 1); + + for (packet, expected_sample_frames) in packets { + assert!(packet.len() <= OPUS_ENCODED_PACKET_MAX_BYTES); + assert_eq!( + opus_packet_duration_samples_48k(&packet), + Ok(expected_sample_frames) + ); + let decoded = decoder.decode_packet(&packet).unwrap(); + assert_eq!(decoded.channels, 1); + assert_eq!(decoded.sample_frames(), expected_sample_frames); + } + } + + #[test] + fn interoperable_decoder_accepts_mixed_rfc_packet_framing() { + let direct = encoded_twenty_ms_mono_packet(); + let packets = [ + (direct.clone(), 960), + (repacketize_cbr(&direct, 2), 1_920), + (repacketize_vbr(&direct, 2, 0), 1_920), + (repacketize_cbr(&direct, 3), 2_880), + (repacketize_vbr(&direct, 3, 7), 2_880), + ]; + let mut decoder = OpusMonoDecoder::new().unwrap(); + + for (packet, expected_sample_frames) in packets { + assert_eq!( + opus_packet_duration_samples_48k(&packet), + Ok(expected_sample_frames) + ); + assert_eq!( + decoder.decode_packet(&packet).unwrap().sample_frames(), + expected_sample_frames + ); + } + } + + #[test] + fn interoperable_decoder_accepts_code3_zero_byte_plc_frames() { + let toc = encoded_twenty_ms_mono_packet()[0] & !0x03; + let packets = [vec![toc | 0x03, 0x03], vec![toc | 0x03, 0x83, 0, 0]]; + let mut decoder = OpusMonoDecoder::new().unwrap(); + + for packet in packets { + assert_eq!(opus_packet_duration_samples_48k(&packet), Ok(2_880)); + assert_eq!( + decoder.decode_packet(&packet).unwrap().sample_frames(), + 2_880 + ); + } + } + + #[test] + fn interoperable_decoder_accepts_compound_packets_above_one_frame_ceiling() { + let direct = encoded_mono_packet(960, 510_000); + assert!(direct.len() - 1 <= OPUS_ENCODED_FRAME_MAX_BYTES); + + let compound = repacketize_cbr(&direct, 2); + assert!(compound.len() > OPUS_ENCODED_FRAME_MAX_BYTES); + assert!(compound.len() <= OPUS_ENCODED_PACKET_MAX_BYTES); + assert_eq!(opus_packet_duration_samples_48k(&compound), Ok(1_920)); + + let decoded = OpusMonoDecoder::new() + .unwrap() + .decode_packet(&compound) + .unwrap(); + assert_eq!(decoded.sample_frames(), 1_920); + } + + #[test] + fn interoperable_decoder_accepts_current_quality_medium_packets() { + let profile = Profile::QualityMedium; + let frame = source_for(profile).next_raw_frame().unwrap(); + let packet = OpusEncoderState::new(profile) + .unwrap() + .encode_frame(&frame) + .unwrap(); + + let decoded = OpusMonoDecoder::new() + .unwrap() + .decode_packet(&packet.payload) + .unwrap(); + + assert_eq!(opus_packet_duration_samples_48k(&packet.payload), Ok(2_880)); + assert_eq!(decoded.channels, 1); + assert_eq!(decoded.sample_frames(), 2_880); + } + + #[test] + fn interoperable_decoder_rejects_stereo_packets_before_decoding() { + let stereo_twenty_ms = [0xFC, 0]; + assert_eq!(opus_packet_duration_samples_48k(&stereo_twenty_ms), Ok(960)); + assert!(matches!( + OpusMonoDecoder::new() + .unwrap() + .decode_packet(&stereo_twenty_ms), + Err(OpusCodecError::ChannelMismatch { + expected: 1, + actual: 2 + }) + )); + } + + #[test] + fn interoperable_packet_policy_enforces_frame_packet_and_duration_bounds() { + let oversize = vec![0xF8; OPUS_ENCODED_PACKET_MAX_BYTES + 1]; + assert_eq!( + opus_packet_duration_samples_48k(&oversize), + Err(OpusCodecError::EncodedPacketTooLarge { + actual: OPUS_ENCODED_PACKET_MAX_BYTES + 1, + maximum: OPUS_ENCODED_PACKET_MAX_BYTES, + }) + ); + + let oversized_direct_frame = vec![0xF8; OPUS_ENCODED_FRAME_MAX_BYTES + 2]; + assert_eq!( + opus_packet_duration_samples_48k(&oversized_direct_frame), + Err(OpusCodecError::EncodedFrameTooLarge { + index: 0, + actual: OPUS_ENCODED_FRAME_MAX_BYTES + 1, + maximum: OPUS_ENCODED_FRAME_MAX_BYTES, + }) + ); + + let overlong_twenty_ms = [0xFB, 0x07, 0, 0, 0, 0, 0, 0, 0]; + assert!(matches!( + opus_packet_duration_samples_48k(&overlong_twenty_ms), + Err(OpusCodecError::MalformedPacket( + "packet duration exceeds 120 milliseconds" + )) + )); + + let too_many_two_and_half_ms = [0x83, 49]; + assert!(matches!( + opus_packet_duration_samples_48k(&too_many_two_and_half_ms), + Err(OpusCodecError::MalformedPacket( + "code 3 frame count exceeds 48" + )) + )); + } + + #[test] + fn interoperable_packet_inspection_rejects_malformed_framing() { + let malformed = [ + Vec::new(), + vec![0xFB], + vec![0xF9, 0], + vec![0xFA, 252], + vec![0xFB, 0], + vec![0xFB, 0x03, 0, 0], + vec![0xFB, 0x43, 2, 0], + ]; + + for packet in malformed { + assert!(matches!( + opus_packet_duration_samples_48k(&packet), + Err(OpusCodecError::MalformedPacket(_)) + )); + } + } }