| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | #![forbid(unsafe_code)] |
| 24 | #![warn(missing_docs)] |
| 25 | |
| 26 | use std::fmt; |
| 27 | |
| 28 | |
| 29 | |
| 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 31 | pub enum Application { |
| 32 | |
| 33 | Voip, |
| 34 | |
| 35 | Audio, |
| 36 | |
| 37 | RestrictedLowdelay, |
| 38 | } |
| 39 | |
| 40 | impl From<Application> for ec_opus::Application { |
| 41 | fn from(a: Application) -> ec_opus::Application { |
| 42 | match a { |
| 43 | Application::Voip => ec_opus::Application::Voip, |
| 44 | Application::Audio => ec_opus::Application::Audio, |
| 45 | Application::RestrictedLowdelay => ec_opus::Application::LowDelay, |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | |
| 51 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 52 | pub enum Bandwidth { |
| 53 | |
| 54 | Auto = -1000, |
| 55 | |
| 56 | Narrowband = 1101, |
| 57 | |
| 58 | Mediumband = 1102, |
| 59 | |
| 60 | Wideband = 1103, |
| 61 | |
| 62 | SuperWideband = 1104, |
| 63 | |
| 64 | Fullband = 1105, |
| 65 | } |
| 66 | |
| 67 | |
| 68 | #[derive(Debug, Clone)] |
| 69 | pub struct OpusError(String); |
| 70 | |
| 71 | impl fmt::Display for OpusError { |
| 72 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 73 | f.write_str(&self.0) |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | impl std::error::Error for OpusError {} |
| 78 | |
| 79 | |
| 80 | #[derive(Debug)] |
| 81 | pub struct OpusEncoder { |
| 82 | |
| 83 | |
| 84 | pub bitrate_bps: i32, |
| 85 | |
| 86 | pub complexity: i32, |
| 87 | |
| 88 | pub bandwidth: Bandwidth, |
| 89 | |
| 90 | pub vbr: bool, |
| 91 | inner: ec_opus::Encoder, |
| 92 | channels: usize, |
| 93 | applied_bandwidth: Bandwidth, |
| 94 | applied_vbr: bool, |
| 95 | } |
| 96 | |
| 97 | impl OpusEncoder { |
| 98 | |
| 99 | |
| 100 | pub fn new( |
| 101 | sample_rate: i32, |
| 102 | channels: i32, |
| 103 | application: Application, |
| 104 | ) -> Result<OpusEncoder, OpusError> { |
| 105 | if sample_rate < 0 || channels < 0 { |
| 106 | return Err(OpusError(format!( |
| 107 | "invalid encoder arguments: {sample_rate} Hz, {channels} channels" |
| 108 | ))); |
| 109 | } |
| 110 | let inner = |
| 111 | ec_opus::Encoder::new(sample_rate as u32, channels as usize, application.into()) |
| 112 | .map_err(|e| OpusError(e.to_string()))?; |
| 113 | Ok(OpusEncoder { |
| 114 | bitrate_bps: 64_000 * channels, |
| 115 | complexity: 10, |
| 116 | bandwidth: Bandwidth::Auto, |
| 117 | vbr: false, |
| 118 | inner, |
| 119 | channels: channels as usize, |
| 120 | applied_bandwidth: Bandwidth::Auto, |
| 121 | applied_vbr: false, |
| 122 | }) |
| 123 | } |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | pub fn look_ahead(&self) -> usize { |
| 129 | self.inner.look_ahead() |
| 130 | } |
| 131 | |
| 132 | |
| 133 | |
| 134 | pub fn final_range(&self) -> u32 { |
| 135 | self.inner.final_range() |
| 136 | } |
| 137 | |
| 138 | |
| 139 | |
| 140 | pub fn encode( |
| 141 | &mut self, |
| 142 | pcm: &[f32], |
| 143 | frame_size: usize, |
| 144 | out: &mut [u8], |
| 145 | ) -> Result<usize, OpusError> { |
| 146 | if pcm.len() < frame_size * self.channels { |
| 147 | return Err(OpusError(format!( |
| 148 | "{} samples is short of {} channels x {frame_size}", |
| 149 | pcm.len(), |
| 150 | self.channels |
| 151 | ))); |
| 152 | } |
| 153 | self.sync_settings(); |
| 154 | self.inner |
| 155 | .encode_float(pcm, frame_size, out) |
| 156 | .map_err(|e| OpusError(e.to_string())) |
| 157 | } |
| 158 | |
| 159 | |
| 160 | pub fn encode_i16( |
| 161 | &mut self, |
| 162 | pcm: &[i16], |
| 163 | frame_size: usize, |
| 164 | out: &mut [u8], |
| 165 | ) -> Result<usize, OpusError> { |
| 166 | if pcm.len() < frame_size * self.channels { |
| 167 | return Err(OpusError(format!( |
| 168 | "{} samples is short of {} channels x {frame_size}", |
| 169 | pcm.len(), |
| 170 | self.channels |
| 171 | ))); |
| 172 | } |
| 173 | self.sync_settings(); |
| 174 | self.inner |
| 175 | .encode(pcm, frame_size, out) |
| 176 | .map_err(|e| OpusError(e.to_string())) |
| 177 | } |
| 178 | |
| 179 | |
| 180 | pub fn reset(&mut self) { |
| 181 | self.inner.reset(); |
| 182 | } |
| 183 | |
| 184 | |
| 185 | fn sync_settings(&mut self) { |
| 186 | self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); |
| 187 | if self.bandwidth != self.applied_bandwidth { |
| 188 | self.inner.set_bandwidth(match self.bandwidth { |
| 189 | Bandwidth::Auto => None, |
| 190 | Bandwidth::Narrowband => Some(ec_opus::Bandwidth::Narrow), |
| 191 | Bandwidth::Mediumband | Bandwidth::Wideband => Some(ec_opus::Bandwidth::Wide), |
| 192 | Bandwidth::SuperWideband => Some(ec_opus::Bandwidth::SuperWide), |
| 193 | Bandwidth::Fullband => Some(ec_opus::Bandwidth::Full), |
| 194 | }); |
| 195 | self.applied_bandwidth = self.bandwidth; |
| 196 | } |
| 197 | if self.vbr != self.applied_vbr { |
| 198 | self.inner.set_vbr_constrained(self.vbr); |
| 199 | self.applied_vbr = self.vbr; |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | |
| 205 | #[derive(Debug)] |
| 206 | pub struct OpusDecoder { |
| 207 | inner: ec_opus::Decoder, |
| 208 | } |
| 209 | |
| 210 | impl OpusDecoder { |
| 211 | |
| 212 | pub fn new(sample_rate: i32, channels: i32) -> Result<OpusDecoder, OpusError> { |
| 213 | if sample_rate < 0 || channels < 0 { |
| 214 | return Err(OpusError(format!( |
| 215 | "invalid decoder arguments: {sample_rate} Hz, {channels} channels" |
| 216 | ))); |
| 217 | } |
| 218 | Ok(OpusDecoder { |
| 219 | inner: ec_opus::Decoder::new(sample_rate as u32, channels as usize) |
| 220 | .map_err(|e| OpusError(e.to_string()))?, |
| 221 | }) |
| 222 | } |
| 223 | |
| 224 | |
| 225 | |
| 226 | pub fn decode( |
| 227 | &mut self, |
| 228 | packet: &[u8], |
| 229 | frame_size: usize, |
| 230 | out: &mut [f32], |
| 231 | ) -> Result<usize, OpusError> { |
| 232 | let _ = frame_size; |
| 233 | self.inner |
| 234 | .decode_float(packet, out) |
| 235 | .map_err(|e| OpusError(e.to_string())) |
| 236 | } |
| 237 | |
| 238 | |
| 239 | pub fn final_range(&self) -> u32 { |
| 240 | self.inner.final_range() |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | #[derive(Debug)] |
| 247 | pub struct MultistreamEncoder { |
| 248 | |
| 249 | pub bitrate_bps: i32, |
| 250 | inner: ec_opus::MultistreamEncoder, |
| 251 | channels: usize, |
| 252 | } |
| 253 | |
| 254 | impl MultistreamEncoder { |
| 255 | |
| 256 | |
| 257 | |
| 258 | pub fn surround( |
| 259 | sample_rate: i32, |
| 260 | channels: usize, |
| 261 | application: Application, |
| 262 | ) -> Result<MultistreamEncoder, OpusError> { |
| 263 | if sample_rate < 0 { |
| 264 | return Err(OpusError(format!("invalid sample rate {sample_rate}"))); |
| 265 | } |
| 266 | let inner = |
| 267 | ec_opus::MultistreamEncoder::surround(sample_rate as u32, channels, application.into()) |
| 268 | .map_err(|e| OpusError(e.to_string()))?; |
| 269 | Ok(MultistreamEncoder { |
| 270 | bitrate_bps: 96_000 * channels as i32 / 2, |
| 271 | inner, |
| 272 | channels, |
| 273 | }) |
| 274 | } |
| 275 | |
| 276 | |
| 277 | pub fn mapping(&self) -> &[u8] { |
| 278 | self.inner.layout().2 |
| 279 | } |
| 280 | |
| 281 | |
| 282 | pub fn stream_counts(&self) -> (usize, usize) { |
| 283 | let (streams, coupled, _) = self.inner.layout(); |
| 284 | (streams, coupled) |
| 285 | } |
| 286 | |
| 287 | |
| 288 | pub fn encode( |
| 289 | &mut self, |
| 290 | pcm: &[f32], |
| 291 | frame_size: usize, |
| 292 | out: &mut [u8], |
| 293 | ) -> Result<usize, OpusError> { |
| 294 | if pcm.len() < frame_size * self.channels { |
| 295 | return Err(OpusError(format!( |
| 296 | "{} samples is short of {} channels x {frame_size}", |
| 297 | pcm.len(), |
| 298 | self.channels |
| 299 | ))); |
| 300 | } |
| 301 | self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); |
| 302 | self.inner |
| 303 | .encode_float(pcm, frame_size, out) |
| 304 | .map_err(|e| OpusError(e.to_string())) |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | #[cfg(test)] |
| 309 | mod tests { |
| 310 | use super::*; |
| 311 | |
| 312 | |
| 313 | #[test] |
| 314 | fn edith_call_shape_compiles_and_encodes() { |
| 315 | let mut encoder = OpusEncoder::new(48000, 2, Application::Audio) |
| 316 | .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}")) |
| 317 | .unwrap(); |
| 318 | encoder.bitrate_bps = 256_000; |
| 319 | encoder.complexity = 10; |
| 320 | let frame = vec![0.1f32; 960 * 2]; |
| 321 | let mut out = vec![0u8; 1500]; |
| 322 | let len = encoder |
| 323 | .encode(&frame, 960, &mut out) |
| 324 | .map_err(|e| format!("Opus encode failed: {e}")) |
| 325 | .unwrap(); |
| 326 | assert!(len > 2 && len <= 1276); |
| 327 | |
| 328 | let mut mono = OpusEncoder::new(48000, 1, Application::Audio).unwrap(); |
| 329 | mono.bitrate_bps = 96_000; |
| 330 | let frame = vec![0.1f32; 960]; |
| 331 | let len = mono.encode(&frame, 960, &mut out).unwrap(); |
| 332 | assert!(len > 2); |
| 333 | } |
| 334 | |
| 335 | fn tone(n: usize, channels: usize) -> Vec<f32> { |
| 336 | (0..n * channels) |
| 337 | .map(|i| { |
| 338 | let t = (i / channels) as f32; |
| 339 | 0.5 * (t * 0.07).sin() + 0.25 * (t * 0.23).sin() |
| 340 | }) |
| 341 | .collect() |
| 342 | } |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | #[test] |
| 348 | fn the_shim_decodes_what_it_encodes_and_the_ranges_agree() { |
| 349 | const FRAME: usize = 960; |
| 350 | let mut enc = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); |
| 351 | enc.bitrate_bps = 256_000; |
| 352 | let mut dec = OpusDecoder::new(48_000, 2).unwrap(); |
| 353 | let pcm = tone(FRAME * 8, 2); |
| 354 | let mut out = vec![0u8; 1500]; |
| 355 | let mut back = vec![0.0f32; FRAME * 2]; |
| 356 | let mut total = 0; |
| 357 | for block in pcm.chunks_exact(FRAME * 2) { |
| 358 | let len = enc.encode(block, FRAME, &mut out).unwrap(); |
| 359 | assert!(len > 1 && len <= 1276, "packet of {len} bytes"); |
| 360 | total += len; |
| 361 | assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); |
| 362 | assert_eq!(dec.final_range(), enc.final_range()); |
| 363 | } |
| 364 | |
| 365 | |
| 366 | let want = 256_000 / 8 / 50 * 8; |
| 367 | assert!( |
| 368 | (total as f64 - want as f64).abs() < 0.2 * want as f64, |
| 369 | "{total} bytes vs {want} at 256 kbps" |
| 370 | ); |
| 371 | } |
| 372 | |
| 373 | |
| 374 | |
| 375 | #[test] |
| 376 | fn slower_input_rates_encode_and_report_their_own_delay() { |
| 377 | for &(rate, frame, look) in &[ |
| 378 | (48_000i32, 960usize, 120usize), |
| 379 | (24_000, 480, 60), |
| 380 | (16_000, 320, 40), |
| 381 | (12_000, 240, 30), |
| 382 | (8_000, 160, 20), |
| 383 | ] { |
| 384 | let mut enc = OpusEncoder::new(rate, 1, Application::Voip).unwrap(); |
| 385 | enc.bitrate_bps = 32_000; |
| 386 | assert_eq!(enc.look_ahead(), look, "{rate} Hz look-ahead"); |
| 387 | let pcm = tone(frame * 4, 1); |
| 388 | let mut out = vec![0u8; 1500]; |
| 389 | |
| 390 | let mut dec = OpusDecoder::new(48_000, 1).unwrap(); |
| 391 | let mut back = vec![0.0f32; 960]; |
| 392 | for block in pcm.chunks_exact(frame) { |
| 393 | let len = enc.encode(block, frame, &mut out).unwrap(); |
| 394 | assert!(len > 2, "{rate} Hz packet of {len} bytes"); |
| 395 | assert_eq!(dec.decode(&out[..len], 960, &mut back).unwrap(), 960); |
| 396 | assert_eq!(dec.final_range(), enc.final_range(), "{rate} Hz range"); |
| 397 | } |
| 398 | } |
| 399 | assert!(OpusEncoder::new(44_100, 2, Application::Audio).is_err()); |
| 400 | } |
| 401 | |
| 402 | |
| 403 | |
| 404 | #[test] |
| 405 | fn forced_bandwidth_and_i16_input_round_trip() { |
| 406 | const FRAME: usize = 960; |
| 407 | let mut enc = OpusEncoder::new(48_000, 1, Application::Audio).unwrap(); |
| 408 | enc.bitrate_bps = 64_000; |
| 409 | enc.bandwidth = Bandwidth::Wideband; |
| 410 | enc.vbr = true; |
| 411 | let pcm: Vec<i16> = tone(FRAME * 4, 1) |
| 412 | .iter() |
| 413 | .map(|v| (v * 16_000.0) as i16) |
| 414 | .collect(); |
| 415 | let mut out = vec![0u8; 1500]; |
| 416 | let mut dec = OpusDecoder::new(48_000, 1).unwrap(); |
| 417 | let mut back = vec![0.0f32; FRAME]; |
| 418 | for block in pcm.chunks_exact(FRAME) { |
| 419 | let len = enc.encode_i16(block, FRAME, &mut out).unwrap(); |
| 420 | |
| 421 | assert_eq!(out[0] >> 3, 23, "wideband CELT config"); |
| 422 | assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); |
| 423 | assert_eq!(dec.final_range(), enc.final_range()); |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | |
| 428 | #[test] |
| 429 | fn surround_encodes_five_one() { |
| 430 | const FRAME: usize = 960; |
| 431 | let mut e = MultistreamEncoder::surround(48_000, 6, Application::Audio).unwrap(); |
| 432 | e.bitrate_bps = 384_000; |
| 433 | assert_eq!(e.stream_counts(), (4, 2)); |
| 434 | assert_eq!(e.mapping(), &[0, 4, 1, 2, 3, 5]); |
| 435 | let pcm = tone(FRAME * 3, 6); |
| 436 | let mut out = vec![0u8; 8 * 1500]; |
| 437 | for block in pcm.chunks_exact(FRAME * 6) { |
| 438 | assert!(e.encode(block, FRAME, &mut out).unwrap() > 8); |
| 439 | } |
| 440 | assert!(MultistreamEncoder::surround(48_000, 9, Application::Audio).is_err()); |
| 441 | } |
| 442 | } |