| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | use ec_core::{Error, Result}; |
| 20 | |
| 21 | use crate::celt_enc::CeltEncoder; |
| 22 | use crate::packet::Bandwidth; |
| 23 | use crate::range::RangeEncoder; |
| 24 | |
| 25 | |
| 26 | const MAX_FRAME_BYTES: usize = 1275; |
| 27 | |
| 28 | |
| 29 | |
| 30 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 31 | pub enum Application { |
| 32 | |
| 33 | |
| 34 | Voip, |
| 35 | |
| 36 | Audio, |
| 37 | |
| 38 | LowDelay, |
| 39 | } |
| 40 | |
| 41 | |
| 42 | #[derive(Clone, Debug)] |
| 43 | pub struct Encoder { |
| 44 | celt: CeltEncoder, |
| 45 | range: RangeEncoder, |
| 46 | sample_rate: u32, |
| 47 | |
| 48 | upsample: usize, |
| 49 | channels: usize, |
| 50 | bitrate: u32, |
| 51 | vbr: bool, |
| 52 | application: Application, |
| 53 | bandwidth: Option<Bandwidth>, |
| 54 | final_range: u32, |
| 55 | } |
| 56 | |
| 57 | impl Encoder { |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result<Encoder> { |
| 63 | let upsample = match sample_rate { |
| 64 | 48000 => 1, |
| 65 | 24000 => 2, |
| 66 | 16000 => 3, |
| 67 | 12000 => 4, |
| 68 | 8000 => 6, |
| 69 | _ => { |
| 70 | return Err(Error::unsupported( |
| 71 | format!("opus encode at {sample_rate} Hz"), |
| 72 | "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first", |
| 73 | )); |
| 74 | } |
| 75 | }; |
| 76 | if !(1..=2).contains(&channels) { |
| 77 | return Err(Error::unsupported( |
| 78 | format!("{channels}-channel Opus stream"), |
| 79 | "one stream carries at most two channels; use MultistreamEncoder", |
| 80 | )); |
| 81 | } |
| 82 | Ok(Encoder { |
| 83 | celt: CeltEncoder::new(channels, upsample), |
| 84 | range: RangeEncoder::new(), |
| 85 | sample_rate, |
| 86 | upsample, |
| 87 | channels, |
| 88 | bitrate: 64_000 * channels as u32, |
| 89 | vbr: false, |
| 90 | application, |
| 91 | bandwidth: None, |
| 92 | final_range: 0, |
| 93 | }) |
| 94 | } |
| 95 | |
| 96 | |
| 97 | pub fn channels(&self) -> usize { |
| 98 | self.channels |
| 99 | } |
| 100 | |
| 101 | |
| 102 | pub fn sample_rate(&self) -> u32 { |
| 103 | self.sample_rate |
| 104 | } |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | pub fn look_ahead(&self) -> usize { |
| 110 | 120 / self.upsample |
| 111 | } |
| 112 | |
| 113 | |
| 114 | |
| 115 | pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) { |
| 116 | self.bandwidth = bandwidth; |
| 117 | } |
| 118 | |
| 119 | |
| 120 | |
| 121 | pub fn set_bitrate(&mut self, bps: u32) { |
| 122 | self.bitrate = bps.clamp(500, 510_000); |
| 123 | } |
| 124 | |
| 125 | |
| 126 | pub fn bitrate(&self) -> u32 { |
| 127 | self.bitrate |
| 128 | } |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | pub fn set_vbr_constrained(&mut self, vbr: bool) { |
| 134 | self.vbr = vbr; |
| 135 | } |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | pub fn final_range(&self) -> u32 { |
| 141 | self.final_range |
| 142 | } |
| 143 | |
| 144 | |
| 145 | pub fn reset(&mut self) { |
| 146 | self.celt.reset(); |
| 147 | self.final_range = 0; |
| 148 | } |
| 149 | |
| 150 | |
| 151 | |
| 152 | fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { |
| 153 | let frame_48k = frame_size * self.upsample; |
| 154 | let fs_idx: u8 = match frame_48k { |
| 155 | 120 => 0, |
| 156 | 240 => 1, |
| 157 | 480 => 2, |
| 158 | 960 => 3, |
| 159 | _ => { |
| 160 | return Err(Error::unsupported( |
| 161 | format!( |
| 162 | "opus frame of {frame_size} samples at {} Hz", |
| 163 | self.sample_rate |
| 164 | ), |
| 165 | "CELT frames are 2.5, 5, 10 or 20 ms", |
| 166 | )); |
| 167 | } |
| 168 | }; |
| 169 | let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); |
| 170 | let bw_idx: u8 = match bandwidth { |
| 171 | Bandwidth::Narrow => 0, |
| 172 | |
| 173 | Bandwidth::Medium | Bandwidth::Wide => 1, |
| 174 | Bandwidth::SuperWide => 2, |
| 175 | Bandwidth::Full => 3, |
| 176 | }; |
| 177 | let config = 16 + 4 * bw_idx + fs_idx; |
| 178 | Ok(( |
| 179 | (config << 3) | (u8::from(self.channels == 2) << 2), |
| 180 | frame_48k, |
| 181 | bandwidth.celt_end_band(), |
| 182 | )) |
| 183 | } |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | fn auto_bandwidth(&self) -> Bandwidth { |
| 192 | let equiv = if self.channels == 2 { |
| 193 | (self.bitrate as f32 * 0.62) as u32 |
| 194 | } else { |
| 195 | self.bitrate |
| 196 | }; |
| 197 | let equiv = if self.application == Application::Voip { |
| 198 | (equiv as f32 * 0.7) as u32 |
| 199 | } else { |
| 200 | equiv |
| 201 | }; |
| 202 | let ceiling = match self.sample_rate { |
| 203 | 48000 => Bandwidth::Full, |
| 204 | 24000 => Bandwidth::SuperWide, |
| 205 | 16000 => Bandwidth::Wide, |
| 206 | _ => Bandwidth::Narrow, |
| 207 | }; |
| 208 | let wanted = if equiv < 9000 { |
| 209 | Bandwidth::Narrow |
| 210 | } else if equiv < 13000 { |
| 211 | Bandwidth::Wide |
| 212 | } else if equiv < 20000 { |
| 213 | Bandwidth::SuperWide |
| 214 | } else { |
| 215 | Bandwidth::Full |
| 216 | }; |
| 217 | wanted.min(ceiling) |
| 218 | } |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | pub fn encode_float( |
| 224 | &mut self, |
| 225 | pcm: &[f32], |
| 226 | frame_size: usize, |
| 227 | out: &mut [u8], |
| 228 | ) -> Result<usize> { |
| 229 | let (toc, frame_48k, end) = self.toc(frame_size)?; |
| 230 | let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(1))?; |
| 231 | if out.len() < 1 + n { |
| 232 | return Err(Error::corrupt(format!( |
| 233 | "opus encode: packet needs {} bytes, buffer holds {}", |
| 234 | 1 + n, |
| 235 | out.len() |
| 236 | ))); |
| 237 | } |
| 238 | out[0] = toc; |
| 239 | out[1..1 + n].copy_from_slice(&self.range.data()[..n]); |
| 240 | Ok(1 + n) |
| 241 | } |
| 242 | |
| 243 | |
| 244 | pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> { |
| 245 | let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect(); |
| 246 | self.encode_float(&float, frame_size, out) |
| 247 | } |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | pub fn encode_self_delimited( |
| 253 | &mut self, |
| 254 | pcm: &[f32], |
| 255 | frame_size: usize, |
| 256 | out: &mut [u8], |
| 257 | ) -> Result<usize> { |
| 258 | let (toc, frame_48k, end) = self.toc(frame_size)?; |
| 259 | let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(3))?; |
| 260 | let len_bytes = if n < 252 { 1 } else { 2 }; |
| 261 | if out.len() < 1 + len_bytes + n { |
| 262 | return Err(Error::corrupt(format!( |
| 263 | "opus encode: self-delimited packet needs {} bytes, buffer holds {}", |
| 264 | 1 + len_bytes + n, |
| 265 | out.len() |
| 266 | ))); |
| 267 | } |
| 268 | out[0] = toc; |
| 269 | if n < 252 { |
| 270 | out[1] = n as u8; |
| 271 | } else { |
| 272 | let b0 = 252 + ((n - 252) & 3); |
| 273 | out[1] = b0 as u8; |
| 274 | out[2] = ((n - b0) / 4) as u8; |
| 275 | } |
| 276 | out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(&self.range.data()[..n]); |
| 277 | Ok(1 + len_bytes + n) |
| 278 | } |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | fn encode_frame( |
| 284 | &mut self, |
| 285 | pcm: &[f32], |
| 286 | frame_size: usize, |
| 287 | end: usize, |
| 288 | cap: usize, |
| 289 | ) -> Result<usize> { |
| 290 | let cap = cap.min(MAX_FRAME_BYTES); |
| 291 | if cap < 2 { |
| 292 | return Err(Error::corrupt( |
| 293 | "opus encode: output buffer smaller than the minimum packet", |
| 294 | )); |
| 295 | } |
| 296 | |
| 297 | let toc_bps = 8 * 48000 / frame_size as u32; |
| 298 | let (budget, vbr_rate) = if self.vbr { |
| 299 | (cap, self.bitrate.saturating_sub(toc_bps).max(500)) |
| 300 | } else { |
| 301 | let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize; |
| 302 | (b.saturating_sub(1).clamp(2, cap), 0) |
| 303 | }; |
| 304 | self.range.reset(budget); |
| 305 | let n = self |
| 306 | .celt |
| 307 | .encode(&mut self.range, pcm, frame_size, end, vbr_rate)?; |
| 308 | self.final_range = self.range.range(); |
| 309 | Ok(n) |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | #[cfg(test)] |
| 314 | mod tests { |
| 315 | use super::*; |
| 316 | |
| 317 | |
| 318 | |
| 319 | #[test] |
| 320 | fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() { |
| 321 | let mut e = Encoder::new(48000, 1, Application::Audio).unwrap(); |
| 322 | e.set_bitrate(64000); |
| 323 | assert_eq!(e.auto_bandwidth(), Bandwidth::Full); |
| 324 | e.set_bitrate(16000); |
| 325 | assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); |
| 326 | e.set_bitrate(10000); |
| 327 | assert_eq!(e.auto_bandwidth(), Bandwidth::Wide); |
| 328 | e.set_bitrate(8000); |
| 329 | assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow); |
| 330 | |
| 331 | let mut v = Encoder::new(48000, 1, Application::Voip).unwrap(); |
| 332 | v.set_bitrate(16000); |
| 333 | assert_eq!(v.auto_bandwidth(), Bandwidth::Wide); |
| 334 | |
| 335 | let mut e = Encoder::new(24000, 2, Application::Audio).unwrap(); |
| 336 | e.set_bitrate(256_000); |
| 337 | assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); |
| 338 | assert_eq!(e.look_ahead(), 60); |
| 339 | } |
| 340 | } |