| 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 | |
| 129 | |
| 130 | |
| 131 | pub fn look_ahead(&self) -> usize { |
| 132 | self.inner.look_ahead(self.inner.sample_rate() as usize / 50) |
| 133 | } |
| 134 | |
| 135 | |
| 136 | |
| 137 | pub fn final_range(&self) -> u32 { |
| 138 | self.inner.final_range() |
| 139 | } |
| 140 | |
| 141 | |
| 142 | |
| 143 | pub fn encode( |
| 144 | &mut self, |
| 145 | pcm: &[f32], |
| 146 | frame_size: usize, |
| 147 | out: &mut [u8], |
| 148 | ) -> Result<usize, OpusError> { |
| 149 | if pcm.len() < frame_size * self.channels { |
| 150 | return Err(OpusError(format!( |
| 151 | "{} samples is short of {} channels x {frame_size}", |
| 152 | pcm.len(), |
| 153 | self.channels |
| 154 | ))); |
| 155 | } |
| 156 | self.sync_settings(); |
| 157 | self.inner |
| 158 | .encode_float(pcm, frame_size, out) |
| 159 | .map_err(|e| OpusError(e.to_string())) |
| 160 | } |
| 161 | |
| 162 | |
| 163 | pub fn encode_i16( |
| 164 | &mut self, |
| 165 | pcm: &[i16], |
| 166 | frame_size: usize, |
| 167 | out: &mut [u8], |
| 168 | ) -> Result<usize, OpusError> { |
| 169 | if pcm.len() < frame_size * self.channels { |
| 170 | return Err(OpusError(format!( |
| 171 | "{} samples is short of {} channels x {frame_size}", |
| 172 | pcm.len(), |
| 173 | self.channels |
| 174 | ))); |
| 175 | } |
| 176 | self.sync_settings(); |
| 177 | self.inner |
| 178 | .encode(pcm, frame_size, out) |
| 179 | .map_err(|e| OpusError(e.to_string())) |
| 180 | } |
| 181 | |
| 182 | |
| 183 | pub fn reset(&mut self) { |
| 184 | self.inner.reset(); |
| 185 | } |
| 186 | |
| 187 | |
| 188 | fn sync_settings(&mut self) { |
| 189 | self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); |
| 190 | if self.bandwidth != self.applied_bandwidth { |
| 191 | self.inner.set_bandwidth(match self.bandwidth { |
| 192 | Bandwidth::Auto => None, |
| 193 | Bandwidth::Narrowband => Some(ec_opus::Bandwidth::Narrow), |
| 194 | Bandwidth::Mediumband | Bandwidth::Wideband => Some(ec_opus::Bandwidth::Wide), |
| 195 | Bandwidth::SuperWideband => Some(ec_opus::Bandwidth::SuperWide), |
| 196 | Bandwidth::Fullband => Some(ec_opus::Bandwidth::Full), |
| 197 | }); |
| 198 | self.applied_bandwidth = self.bandwidth; |
| 199 | } |
| 200 | if self.vbr != self.applied_vbr { |
| 201 | self.inner.set_vbr_constrained(self.vbr); |
| 202 | self.applied_vbr = self.vbr; |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | |
| 208 | #[derive(Debug)] |
| 209 | pub struct OpusDecoder { |
| 210 | inner: ec_opus::Decoder, |
| 211 | } |
| 212 | |
| 213 | impl OpusDecoder { |
| 214 | |
| 215 | pub fn new(sample_rate: i32, channels: i32) -> Result<OpusDecoder, OpusError> { |
| 216 | if sample_rate < 0 || channels < 0 { |
| 217 | return Err(OpusError(format!( |
| 218 | "invalid decoder arguments: {sample_rate} Hz, {channels} channels" |
| 219 | ))); |
| 220 | } |
| 221 | Ok(OpusDecoder { |
| 222 | inner: ec_opus::Decoder::new(sample_rate as u32, channels as usize) |
| 223 | .map_err(|e| OpusError(e.to_string()))?, |
| 224 | }) |
| 225 | } |
| 226 | |
| 227 | |
| 228 | |
| 229 | pub fn decode( |
| 230 | &mut self, |
| 231 | packet: &[u8], |
| 232 | frame_size: usize, |
| 233 | out: &mut [f32], |
| 234 | ) -> Result<usize, OpusError> { |
| 235 | let _ = frame_size; |
| 236 | self.inner |
| 237 | .decode_float(packet, out) |
| 238 | .map_err(|e| OpusError(e.to_string())) |
| 239 | } |
| 240 | |
| 241 | |
| 242 | pub fn final_range(&self) -> u32 { |
| 243 | self.inner.final_range() |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | |
| 248 | |
| 249 | #[derive(Debug)] |
| 250 | pub struct MultistreamEncoder { |
| 251 | |
| 252 | pub bitrate_bps: i32, |
| 253 | inner: ec_opus::MultistreamEncoder, |
| 254 | channels: usize, |
| 255 | } |
| 256 | |
| 257 | impl MultistreamEncoder { |
| 258 | |
| 259 | |
| 260 | |
| 261 | pub fn surround( |
| 262 | sample_rate: i32, |
| 263 | channels: usize, |
| 264 | application: Application, |
| 265 | ) -> Result<MultistreamEncoder, OpusError> { |
| 266 | if sample_rate < 0 { |
| 267 | return Err(OpusError(format!("invalid sample rate {sample_rate}"))); |
| 268 | } |
| 269 | let inner = |
| 270 | ec_opus::MultistreamEncoder::surround(sample_rate as u32, channels, application.into()) |
| 271 | .map_err(|e| OpusError(e.to_string()))?; |
| 272 | Ok(MultistreamEncoder { |
| 273 | bitrate_bps: 96_000 * channels as i32 / 2, |
| 274 | inner, |
| 275 | channels, |
| 276 | }) |
| 277 | } |
| 278 | |
| 279 | |
| 280 | pub fn mapping(&self) -> &[u8] { |
| 281 | self.inner.layout().2 |
| 282 | } |
| 283 | |
| 284 | |
| 285 | pub fn stream_counts(&self) -> (usize, usize) { |
| 286 | let (streams, coupled, _) = self.inner.layout(); |
| 287 | (streams, coupled) |
| 288 | } |
| 289 | |
| 290 | |
| 291 | pub fn encode( |
| 292 | &mut self, |
| 293 | pcm: &[f32], |
| 294 | frame_size: usize, |
| 295 | out: &mut [u8], |
| 296 | ) -> Result<usize, OpusError> { |
| 297 | if pcm.len() < frame_size * self.channels { |
| 298 | return Err(OpusError(format!( |
| 299 | "{} samples is short of {} channels x {frame_size}", |
| 300 | pcm.len(), |
| 301 | self.channels |
| 302 | ))); |
| 303 | } |
| 304 | self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); |
| 305 | self.inner |
| 306 | .encode_float(pcm, frame_size, out) |
| 307 | .map_err(|e| OpusError(e.to_string())) |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | #[cfg(test)] |
| 312 | mod tests { |
| 313 | use super::*; |
| 314 | |
| 315 | |
| 316 | #[test] |
| 317 | fn edith_call_shape_compiles_and_encodes() { |
| 318 | let mut encoder = OpusEncoder::new(48000, 2, Application::Audio) |
| 319 | .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}")) |
| 320 | .unwrap(); |
| 321 | encoder.bitrate_bps = 256_000; |
| 322 | encoder.complexity = 10; |
| 323 | let frame = vec![0.1f32; 960 * 2]; |
| 324 | let mut out = vec![0u8; 1500]; |
| 325 | let len = encoder |
| 326 | .encode(&frame, 960, &mut out) |
| 327 | .map_err(|e| format!("Opus encode failed: {e}")) |
| 328 | .unwrap(); |
| 329 | assert!(len > 2 && len <= 1276); |
| 330 | |
| 331 | let mut mono = OpusEncoder::new(48000, 1, Application::Audio).unwrap(); |
| 332 | mono.bitrate_bps = 96_000; |
| 333 | let frame = vec![0.1f32; 960]; |
| 334 | let len = mono.encode(&frame, 960, &mut out).unwrap(); |
| 335 | assert!(len > 2); |
| 336 | } |
| 337 | |
| 338 | fn tone(n: usize, channels: usize) -> Vec<f32> { |
| 339 | (0..n * channels) |
| 340 | .map(|i| { |
| 341 | let t = (i / channels) as f32; |
| 342 | 0.5 * (t * 0.07).sin() + 0.25 * (t * 0.23).sin() |
| 343 | }) |
| 344 | .collect() |
| 345 | } |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | #[test] |
| 351 | fn the_shim_decodes_what_it_encodes_and_the_ranges_agree() { |
| 352 | const FRAME: usize = 960; |
| 353 | let mut enc = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); |
| 354 | enc.bitrate_bps = 256_000; |
| 355 | let mut dec = OpusDecoder::new(48_000, 2).unwrap(); |
| 356 | let pcm = tone(FRAME * 8, 2); |
| 357 | let mut out = vec![0u8; 1500]; |
| 358 | let mut back = vec![0.0f32; FRAME * 2]; |
| 359 | let mut total = 0; |
| 360 | for block in pcm.chunks_exact(FRAME * 2) { |
| 361 | let len = enc.encode(block, FRAME, &mut out).unwrap(); |
| 362 | assert!(len > 1 && len <= 1276, "packet of {len} bytes"); |
| 363 | total += len; |
| 364 | assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); |
| 365 | assert_eq!(dec.final_range(), enc.final_range()); |
| 366 | } |
| 367 | |
| 368 | |
| 369 | let want = 256_000 / 8 / 50 * 8; |
| 370 | assert!( |
| 371 | (total as f64 - want as f64).abs() < 0.2 * want as f64, |
| 372 | "{total} bytes vs {want} at 256 kbps" |
| 373 | ); |
| 374 | } |
| 375 | |
| 376 | |
| 377 | |
| 378 | #[test] |
| 379 | fn slower_input_rates_encode_and_report_their_own_delay() { |
| 380 | for &(rate, frame, look) in &[ |
| 381 | (48_000i32, 960usize, 120usize), |
| 382 | (24_000, 480, 60), |
| 383 | (16_000, 320, 40), |
| 384 | (12_000, 240, 30), |
| 385 | (8_000, 160, 20), |
| 386 | ] { |
| 387 | let mut enc = OpusEncoder::new(rate, 1, Application::Voip).unwrap(); |
| 388 | enc.bitrate_bps = 32_000; |
| 389 | assert_eq!(enc.look_ahead(), look, "{rate} Hz look-ahead"); |
| 390 | let pcm = tone(frame * 4, 1); |
| 391 | let mut out = vec![0u8; 1500]; |
| 392 | |
| 393 | let mut dec = OpusDecoder::new(48_000, 1).unwrap(); |
| 394 | let mut back = vec![0.0f32; 960]; |
| 395 | for block in pcm.chunks_exact(frame) { |
| 396 | let len = enc.encode(block, frame, &mut out).unwrap(); |
| 397 | assert!(len > 2, "{rate} Hz packet of {len} bytes"); |
| 398 | assert_eq!(dec.decode(&out[..len], 960, &mut back).unwrap(), 960); |
| 399 | assert_eq!(dec.final_range(), enc.final_range(), "{rate} Hz range"); |
| 400 | } |
| 401 | } |
| 402 | assert!(OpusEncoder::new(44_100, 2, Application::Audio).is_err()); |
| 403 | } |
| 404 | |
| 405 | |
| 406 | |
| 407 | #[test] |
| 408 | fn forced_bandwidth_and_i16_input_round_trip() { |
| 409 | const FRAME: usize = 960; |
| 410 | let mut enc = OpusEncoder::new(48_000, 1, Application::Audio).unwrap(); |
| 411 | enc.bitrate_bps = 64_000; |
| 412 | enc.bandwidth = Bandwidth::Wideband; |
| 413 | enc.vbr = true; |
| 414 | let pcm: Vec<i16> = tone(FRAME * 4, 1) |
| 415 | .iter() |
| 416 | .map(|v| (v * 16_000.0) as i16) |
| 417 | .collect(); |
| 418 | let mut out = vec![0u8; 1500]; |
| 419 | let mut dec = OpusDecoder::new(48_000, 1).unwrap(); |
| 420 | let mut back = vec![0.0f32; FRAME]; |
| 421 | for block in pcm.chunks_exact(FRAME) { |
| 422 | let len = enc.encode_i16(block, FRAME, &mut out).unwrap(); |
| 423 | |
| 424 | assert_eq!(out[0] >> 3, 23, "wideband CELT config"); |
| 425 | assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); |
| 426 | assert_eq!(dec.final_range(), enc.final_range()); |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | |
| 431 | #[test] |
| 432 | fn surround_encodes_five_one() { |
| 433 | const FRAME: usize = 960; |
| 434 | let mut e = MultistreamEncoder::surround(48_000, 6, Application::Audio).unwrap(); |
| 435 | e.bitrate_bps = 384_000; |
| 436 | assert_eq!(e.stream_counts(), (4, 2)); |
| 437 | assert_eq!(e.mapping(), &[0, 4, 1, 2, 3, 5]); |
| 438 | let pcm = tone(FRAME * 3, 6); |
| 439 | let mut out = vec![0u8; 8 * 1500]; |
| 440 | for block in pcm.chunks_exact(FRAME * 6) { |
| 441 | assert!(e.encode(block, FRAME, &mut out).unwrap() > 8); |
| 442 | } |
| 443 | assert!(MultistreamEncoder::surround(48_000, 9, Application::Audio).is_err()); |
| 444 | } |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | #[test] |
| 451 | fn voip_below_20kbps_reaches_silk() { |
| 452 | let mut enc = OpusEncoder::new(48_000, 1, Application::Voip).unwrap(); |
| 453 | enc.bitrate_bps = 12_000; |
| 454 | let pcm = tone(960, 1); |
| 455 | let mut out = vec![0u8; 1500]; |
| 456 | let len = enc.encode(&pcm, 960, &mut out).unwrap(); |
| 457 | assert!(len > 1); |
| 458 | assert!(out[0] >> 3 <= 11, "TOC config {} is not SILK", out[0] >> 3); |
| 459 | } |
| 460 | } |