Encoder fixes from round-trip sweep follow-up
Browse files at this commitf849ee91f16fa13e6bc53afb7df4dbe3db89ab90Parent: c561bfe8 changed files +292 -81
- crates/ec-aac/src/encode.rs +3 -0
- crates/ec-av1/src/encoder/mod.rs +2 -2
- crates/ec-h264/src/enc/mod.rs +7 -1
- crates/ec-image/src/gif_encode.rs +124 -51
- crates/ec-mp3/src/encode.rs +40 -9
- crates/ec-opus/src/encoder.rs +112 -17
- crates/ec-opus/src/multistream_enc.rs +1 -1
- crates/ec-vorbis/src/encode.rs +3 -0
crates/ec-aac/src/encode.rsmodified+3 -0
| @@ -199,6 +199,9 @@ impl AacEncoder { | |||
| 199 | format!("{channels} channels has no channelConfiguration"), | 199 | format!("{channels} channels has no channelConfiguration"), |
| 200 | )); | 200 | )); |
| 201 | } | 201 | } |
| 202 | + if self.config.bitrate_bps == 0 { | ||
| 203 | + return Err(Error::corrupt("aac: bitrate of zero")); | ||
| 204 | + } | ||
| 202 | self.sf_index = sf_index; | 205 | self.sf_index = sf_index; |
| 203 | self.sample_rate = sample_rate; | 206 | self.sample_rate = sample_rate; |
| 204 | self.channels = usize::from(channels); | 207 | self.channels = usize::from(channels); |
crates/ec-av1/src/encoder/mod.rsmodified+2 -2
| @@ -1591,8 +1591,8 @@ impl Av1Encoder { | |||
| 1591 | /// | 1591 | /// |
| 1592 | /// # Errors | 1592 | /// # Errors |
| 1593 | /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be | 1593 | /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be |
| 1594 | - /// left between the anchor and the hidden frame) or above `config.gop` | 1594 | + /// left between the anchor and the hidden frame). A `mini_gop` above |
| 1595 | - /// (the group would straddle a key frame). | 1595 | + /// `config.gop` is clamped to the run before the next key frame. |
| 1596 | pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> { | 1596 | pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> { |
| 1597 | if pyramid.mini_gop < 2 { | 1597 | if pyramid.mini_gop < 2 { |
| 1598 | return Err(Error::unsupported( | 1598 | return Err(Error::unsupported( |
crates/ec-h264/src/enc/mod.rsmodified+7 -1
| @@ -229,7 +229,13 @@ impl Encoder { | |||
| 229 | } | 229 | } |
| 230 | let mb_w = cfg.width.div_ceil(16); | 230 | let mb_w = cfg.width.div_ceil(16); |
| 231 | let mb_h = cfg.height.div_ceil(16); | 231 | let mb_h = cfg.height.div_ceil(16); |
| 232 | - let fps = f64::from(cfg.framerate.max(1.0)); | 232 | + if !(cfg.framerate.is_finite() && cfg.framerate > 0.0) { |
| 233 | + return Err(Error::unsupported( | ||
| 234 | + "non-positive frame rate", | ||
| 235 | + "the VUI timing and the rate control need a positive frame rate", | ||
| 236 | + )); | ||
| 237 | + } | ||
| 238 | + let fps = f64::from(cfg.framerate); | ||
| 233 | // A rational tick close to the requested rate; time_scale is twice the | 239 | // A rational tick close to the requested rate; time_scale is twice the |
| 234 | // frame rate for progressive frames (E.2.1). | 240 | // frame rate for progressive frames (E.2.1). |
| 235 | let timing = rational_timing(fps); | 241 | let timing = rational_timing(fps); |
crates/ec-image/src/gif_encode.rsmodified+124 -51
| @@ -6,11 +6,12 @@ | |||
| 6 | //! Alpha below 128 maps to one reserved transparent index. | 6 | //! Alpha below 128 maps to one reserved transparent index. |
| 7 | //! | 7 | //! |
| 8 | //! The file is built so that the canvas a decoder composites is what the frames | 8 | //! The file is built so that the canvas a decoder composites is what the frames |
| 9 | -//! show. Every frame uses disposal "do not dispose", so a pixel equal to the | 9 | +//! show. Frames use disposal "do not dispose", so a pixel equal to the previous |
| 10 | -//! previous frame is encoded as transparent and keeps the value already on the | 10 | +//! frame is encoded as transparent and keeps the value already on the canvas, and |
| 11 | -//! canvas, and each image is cropped to the bounding box of the changed pixels. | 11 | +//! each image is cropped to the bounding box of the changed pixels. A pixel that |
| 12 | -//! A frame with no change folds its delay into the previous frame, so a static | 12 | +//! turns transparent re-emits the previous frame with disposal "restore to |
| 13 | -//! run costs one picture and no extra frames. | 13 | +//! background" over the cleared area. A frame with no change folds its delay into |
| 14 | +//! the previous frame, so a static run costs one picture and no extra frames. | ||
| 14 | //! | 15 | //! |
| 15 | //! Output decodes through [`crate::gif::decode_animation`]. No unsafe, no dependencies. | 16 | //! Output decodes through [`crate::gif::decode_animation`]. No unsafe, no dependencies. |
| 16 | 17 | ||
| @@ -52,11 +53,22 @@ pub struct Encoder { | |||
| 52 | prev: Option<Vec<u8>>, | 53 | prev: Option<Vec<u8>>, |
| 53 | /// Offset of the last frame's delay field in `out`, and that delay in 1/100 s. | 54 | /// Offset of the last frame's delay field in `out`, and that delay in 1/100 s. |
| 54 | last: Option<(usize, u16)>, | 55 | last: Option<(usize, u16)>, |
| 56 | + last_frame: Option<LastFrame>, | ||
| 55 | frames: usize, | 57 | frames: usize, |
| 56 | } | 58 | } |
| 57 | 59 | ||
| 60 | +type Rect = (usize, usize, usize, usize); | ||
| 61 | + | ||
| 62 | +struct LastFrame { | ||
| 63 | + start: usize, | ||
| 64 | + rect: Rect, | ||
| 65 | + prev: Option<Vec<u8>>, | ||
| 66 | + pixels: Vec<u8>, | ||
| 67 | +} | ||
| 68 | + | ||
| 58 | /// Graphic Control disposal 1: "do not dispose", leave the frame on the canvas. | 69 | /// Graphic Control disposal 1: "do not dispose", leave the frame on the canvas. |
| 59 | const DISPOSE_KEEP: u8 = 1 << 2; | 70 | const DISPOSE_KEEP: u8 = 1 << 2; |
| 71 | +const DISPOSE_RESTORE: u8 = 2 << 2; | ||
| 60 | 72 | ||
| 61 | impl Encoder { | 73 | impl Encoder { |
| 62 | /// Start a `width` x `height` animation with the given options. | 74 | /// Start a `width` x `height` animation with the given options. |
| @@ -93,6 +105,7 @@ impl Encoder { | |||
| 93 | out, | 105 | out, |
| 94 | prev: None, | 106 | prev: None, |
| 95 | last: None, | 107 | last: None, |
| 108 | + last_frame: None, | ||
| 96 | frames: 0, | 109 | frames: 0, |
| 97 | }) | 110 | }) |
| 98 | } | 111 | } |
| @@ -113,40 +126,59 @@ impl Encoder { | |||
| 113 | ), | 126 | ), |
| 114 | )); | 127 | )); |
| 115 | } | 128 | } |
| 116 | - let prev = self.prev.as_deref(); | 129 | + let mut canvas = self.prev.take(); |
| 117 | - | 130 | + let mut restored_now = false; |
| 118 | - let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); | 131 | + if let Some(clear) = bounds(w, h, |i| cleared(canvas.as_deref(), pixels, i)) |
| 119 | - let mut any = false; | 132 | + && let (Some(last), Some((_, delay))) = (self.last_frame.take(), self.last) |
| 120 | - for y in 0..h { | 133 | + { |
| 121 | - for x in 0..w { | 134 | + let rect = join_rect(last.rect, clear); |
| 122 | - if differs(prev, pixels, y * w + x) { | 135 | + self.out.truncate(last.start); |
| 123 | - any = true; | 136 | + self.emit( |
| 124 | - x0 = x0.min(x); | 137 | + last.prev.as_deref(), |
| 125 | - y0 = y0.min(y); | 138 | + &last.pixels, |
| 126 | - x1 = x1.max(x); | 139 | + rect, |
| 127 | - y1 = y1.max(y); | 140 | + delay, |
| 128 | - } | 141 | + DISPOSE_RESTORE, |
| 129 | - } | 142 | + ); |
| 143 | + let mut restored = last.pixels; | ||
| 144 | + clear_rect(&mut restored, w, rect); | ||
| 145 | + canvas = Some(restored); | ||
| 146 | + restored_now = true; | ||
| 130 | } | 147 | } |
| 131 | - let (x0, y0, x1, y1) = if any { | 148 | + let prev = canvas.as_deref(); |
| 132 | - (x0, y0, x1, y1) | 149 | + let rect = match bounds(w, h, |i| differs(prev, pixels, i)) { |
| 133 | - } else { | 150 | + Some(rect) => rect, |
| 134 | - // Nothing changed: fold the delay into the previous frame when it fits. | 151 | + None => { |
| 135 | - if let Some((at, last)) = self.last { | 152 | + if let (false, Some((at, last))) = (restored_now, self.last) { |
| 136 | - let merged = u32::from(last) + u32::from(delay_cs); | 153 | + let merged = u32::from(last) + u32::from(delay_cs); |
| 137 | - if merged <= u32::from(u16::MAX) { | 154 | + if merged <= u32::from(u16::MAX) { |
| 138 | - let bytes = (merged as u16).to_le_bytes(); | 155 | + self.out[at..at + 2].copy_from_slice(&(merged as u16).to_le_bytes()); |
| 139 | - self.out[at..at + 2].copy_from_slice(&bytes); | 156 | + self.last = Some((at, merged as u16)); |
| 140 | - self.last = Some((at, merged as u16)); | 157 | + self.prev = Some(pixels.to_vec()); |
| 141 | - return Ok(()); | 158 | + return Ok(()); |
| 159 | + } | ||
| 142 | } | 160 | } |
| 161 | + (0, 0, 0, 0) | ||
| 143 | } | 162 | } |
| 144 | - // Too long to merge: a 1x1 transparent frame carries the delay. | ||
| 145 | - (0, 0, 0, 0) | ||
| 146 | }; | 163 | }; |
| 164 | + self.emit(prev, pixels, rect, delay_cs, DISPOSE_KEEP); | ||
| 165 | + self.prev = Some(pixels.to_vec()); | ||
| 166 | + self.frames += 1; | ||
| 167 | + Ok(()) | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + fn emit( | ||
| 171 | + &mut self, | ||
| 172 | + prev: Option<&[u8]>, | ||
| 173 | + pixels: &[u8], | ||
| 174 | + rect: Rect, | ||
| 175 | + delay_cs: u16, | ||
| 176 | + disposal: u8, | ||
| 177 | + ) { | ||
| 178 | + let w = usize::from(self.width); | ||
| 179 | + let (x0, y0, x1, y1) = rect; | ||
| 147 | let (rw, rh) = (x1 - x0 + 1, y1 - y0 + 1); | 180 | let (rw, rh) = (x1 - x0 + 1, y1 - y0 + 1); |
| 148 | 181 | ||
| 149 | - // Source of each pixel in the cropped rectangle: None is the transparent index. | ||
| 150 | let mut src: Vec<Option<[u8; 3]>> = Vec::with_capacity(rw * rh); | 182 | let mut src: Vec<Option<[u8; 3]>> = Vec::with_capacity(rw * rh); |
| 151 | for y in y0..=y1 { | 183 | for y in y0..=y1 { |
| 152 | for x in x0..=x1 { | 184 | for x in x0..=x1 { |
| @@ -176,11 +208,17 @@ impl Encoder { | |||
| 176 | // The transparent index sits right after the opaque palette. | 208 | // The transparent index sits right after the opaque palette. |
| 177 | let tidx = palette_len as u8; | 209 | let tidx = palette_len as u8; |
| 178 | let delay = delay_cs.to_le_bytes(); | 210 | let delay = delay_cs.to_le_bytes(); |
| 179 | - let packed = DISPOSE_KEEP | u8::from(transparent); | 211 | + let packed = disposal | u8::from(transparent); |
| 180 | - let at = self.out.len() + 4; | 212 | + let start = self.out.len(); |
| 181 | self.out | 213 | self.out |
| 182 | .extend_from_slice(&[0x21, 0xf9, 0x04, packed, delay[0], delay[1], tidx, 0]); | 214 | .extend_from_slice(&[0x21, 0xf9, 0x04, packed, delay[0], delay[1], tidx, 0]); |
| 183 | - self.last = Some((at, delay_cs)); | 215 | + self.last = Some((start + 4, delay_cs)); |
| 216 | + self.last_frame = Some(LastFrame { | ||
| 217 | + start, | ||
| 218 | + rect, | ||
| 219 | + prev: prev.map(<[u8]>::to_vec), | ||
| 220 | + pixels: pixels.to_vec(), | ||
| 221 | + }); | ||
| 184 | 222 | ||
| 185 | self.out.push(0x2c); | 223 | self.out.push(0x2c); |
| 186 | for v in [x0, y0, rw, rh] { | 224 | for v in [x0, y0, rw, rh] { |
| @@ -192,10 +230,6 @@ impl Encoder { | |||
| 192 | } | 230 | } |
| 193 | self.out.push(min_code); | 231 | self.out.push(min_code); |
| 194 | put_sub_blocks(&mut self.out, &lzw(&indices, min_code)); | 232 | put_sub_blocks(&mut self.out, &lzw(&indices, min_code)); |
| 195 | - | ||
| 196 | - self.prev = Some(pixels.to_vec()); | ||
| 197 | - self.frames += 1; | ||
| 198 | - Ok(()) | ||
| 199 | } | 233 | } |
| 200 | 234 | ||
| 201 | /// Close the file and return its bytes. Fails when no frame was pushed. | 235 | /// Close the file and return its bytes. Fails when no frame was pushed. |
| @@ -216,6 +250,37 @@ fn differs(prev: Option<&[u8]>, pixels: &[u8], i: usize) -> bool { | |||
| 216 | } | 250 | } |
| 217 | } | 251 | } |
| 218 | 252 | ||
| 253 | +fn bounds(w: usize, h: usize, hit: impl Fn(usize) -> bool) -> Option<Rect> { | ||
| 254 | + let mut found: Option<Rect> = None; | ||
| 255 | + for y in 0..h { | ||
| 256 | + for x in 0..w { | ||
| 257 | + if hit(y * w + x) { | ||
| 258 | + found = Some(match found { | ||
| 259 | + None => (x, y, x, y), | ||
| 260 | + Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x), y1.max(y)), | ||
| 261 | + }); | ||
| 262 | + } | ||
| 263 | + } | ||
| 264 | + } | ||
| 265 | + found | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +fn cleared(prev: Option<&[u8]>, pixels: &[u8], i: usize) -> bool { | ||
| 269 | + prev.is_some_and(|p| p[i * 4 + 3] >= 128 && pixels[i * 4 + 3] < 128) | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +fn join_rect(a: Rect, b: Rect) -> Rect { | ||
| 273 | + (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)) | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +fn clear_rect(canvas: &mut [u8], w: usize, (x0, y0, x1, y1): Rect) { | ||
| 277 | + for y in y0..=y1 { | ||
| 278 | + for x in x0..=x1 { | ||
| 279 | + canvas[(y * w + x) * 4..(y * w + x) * 4 + 4].fill(0); | ||
| 280 | + } | ||
| 281 | + } | ||
| 282 | +} | ||
| 283 | + | ||
| 219 | fn pack(c: [u8; 3]) -> u32 { | 284 | fn pack(c: [u8; 3]) -> u32 { |
| 220 | (u32::from(c[0]) << 16) | (u32::from(c[1]) << 8) | u32::from(c[2]) | 285 | (u32::from(c[0]) << 16) | (u32::from(c[1]) << 8) | u32::from(c[2]) |
| 221 | } | 286 | } |
| @@ -253,12 +318,10 @@ fn quantize(mut colors: Vec<u32>, budget: usize) -> Vec<[u8; 3]> { | |||
| 253 | continue; | 318 | continue; |
| 254 | } | 319 | } |
| 255 | for ch in 0..3 { | 320 | for ch in 0..3 { |
| 256 | - let (lo, hi) = b | 321 | + let (lo, hi) = b.iter().fold((u32::MAX, 0), |(lo, hi), &(k, _)| { |
| 257 | - .iter() | 322 | + let v = chan(k, ch); |
| 258 | - .fold((u32::MAX, 0), |(lo, hi), &(k, _)| { | 323 | + (lo.min(v), hi.max(v)) |
| 259 | - let v = chan(k, ch); | 324 | + }); |
| 260 | - (lo.min(v), hi.max(v)) | ||
| 261 | - }); | ||
| 262 | let range = hi - lo; | 325 | let range = hi - lo; |
| 263 | match pick { | 326 | match pick { |
| 264 | Some((_, _, r)) if r >= range => {} | 327 | Some((_, _, r)) if r >= range => {} |
| @@ -461,7 +524,7 @@ fn put_sub_blocks(out: &mut Vec<u8>, data: &[u8]) { | |||
| 461 | #[cfg(test)] | 524 | #[cfg(test)] |
| 462 | mod tests { | 525 | mod tests { |
| 463 | use super::*; | 526 | use super::*; |
| 464 | - use crate::{gif, AnimationFrame, Limits}; | 527 | + use crate::{AnimationFrame, Limits, gif}; |
| 465 | 528 | ||
| 466 | fn encode_frames(w: u16, h: u16, opts: GifOptions, frames: &[(&[u8], u16)]) -> Vec<u8> { | 529 | fn encode_frames(w: u16, h: u16, opts: GifOptions, frames: &[(&[u8], u16)]) -> Vec<u8> { |
| 467 | let mut enc = Encoder::new(w, h, opts).unwrap(); | 530 | let mut enc = Encoder::new(w, h, opts).unwrap(); |
| @@ -531,7 +594,8 @@ mod tests { | |||
| 531 | let a: Vec<u8> = (0..w * h) | 594 | let a: Vec<u8> = (0..w * h) |
| 532 | .flat_map(|i| { | 595 | .flat_map(|i| { |
| 533 | let (x, y) = (i % w, i / w); | 596 | let (x, y) = (i % w, i / w); |
| 534 | - let c = [[200, 30, 30], [30, 200, 30], [30, 30, 200], [220, 220, 40]][(x / 8 + y / 8) % 4]; | 597 | + let c = [[200, 30, 30], [30, 200, 30], [30, 30, 200], [220, 220, 40]] |
| 598 | + [(x / 8 + y / 8) % 4]; | ||
| 535 | [c[0], c[1], c[2], 255] | 599 | [c[0], c[1], c[2], 255] |
| 536 | }) | 600 | }) |
| 537 | .collect(); | 601 | .collect(); |
| @@ -666,16 +730,25 @@ mod tests { | |||
| 666 | let mut enc = Encoder::new(2, 2, GifOptions::default()).unwrap(); | 730 | let mut enc = Encoder::new(2, 2, GifOptions::default()).unwrap(); |
| 667 | assert!(enc.push_rgba8(&[0; 15], 1).is_err()); | 731 | assert!(enc.push_rgba8(&[0; 15], 1).is_err()); |
| 668 | assert!(enc.push_rgba8(&[0; 17], 1).is_err()); | 732 | assert!(enc.push_rgba8(&[0; 17], 1).is_err()); |
| 669 | - assert!(Encoder::new(2, 2, GifOptions::default()).unwrap().finish().is_err()); | 733 | + assert!( |
| 734 | + Encoder::new(2, 2, GifOptions::default()) | ||
| 735 | + .unwrap() | ||
| 736 | + .finish() | ||
| 737 | + .is_err() | ||
| 738 | + ); | ||
| 670 | } | 739 | } |
| 671 | 740 | ||
| 672 | #[test] | 741 | #[test] |
| 673 | fn ffprobe_reads_the_output_when_it_is_installed() { | 742 | fn ffprobe_reads_the_output_when_it_is_installed() { |
| 674 | - let probe = std::process::Command::new("ffprobe").arg("-version").output(); | 743 | + let probe = std::process::Command::new("ffprobe") |
| 744 | + .arg("-version") | ||
| 745 | + .output(); | ||
| 675 | if probe.is_err() { | 746 | if probe.is_err() { |
| 676 | return; | 747 | return; |
| 677 | } | 748 | } |
| 678 | - let px: Vec<u8> = (0..8 * 4).flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255]).collect(); | 749 | + let px: Vec<u8> = (0..8 * 4) |
| 750 | + .flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255]) | ||
| 751 | + .collect(); | ||
| 679 | let gif = encode_frames(8, 4, GifOptions::default(), &[(&px, 5), (&px, 5)]); | 752 | let gif = encode_frames(8, 4, GifOptions::default(), &[(&px, 5), (&px, 5)]); |
| 680 | let path = std::env::temp_dir().join(format!("ec-gif-encode-{}.gif", std::process::id())); | 753 | let path = std::env::temp_dir().join(format!("ec-gif-encode-{}.gif", std::process::id())); |
| 681 | std::fs::write(&path, &gif).unwrap(); | 754 | std::fs::write(&path, &gif).unwrap(); |
crates/ec-mp3/src/encode.rsmodified+40 -9
| @@ -162,6 +162,10 @@ pub struct Mp3Encode { | |||
| 162 | /// is smooth from one frame to the next, so the candidate search below | 162 | /// is smooth from one frame to the next, so the candidate search below |
| 163 | /// starts here instead of blind-bisecting the whole table every frame. | 163 | /// starts here instead of blind-bisecting the whole table every frame. |
| 164 | vbr_index: usize, | 164 | vbr_index: usize, |
| 165 | + /// Fractional-slot accumulator in units of the sample rate: each emitted | ||
| 166 | + /// frame takes its slot remainder off it, and a negative balance is paid | ||
| 167 | + /// back with one padding byte. | ||
| 168 | + padding_lag: i64, | ||
| 165 | } | 169 | } |
| 166 | 170 | ||
| 167 | #[derive(Clone, Debug)] | 171 | #[derive(Clone, Debug)] |
| @@ -239,18 +243,19 @@ impl Mp3Encode { | |||
| 239 | .min_by_key(|&(_, &k)| k.abs_diff(target)) | 243 | .min_by_key(|&(_, &k)| k.abs_diff(target)) |
| 240 | .map_or(0, |(i, _)| i) | 244 | .map_or(0, |(i, _)| i) |
| 241 | }, | 245 | }, |
| 246 | + padding_lag: 0, | ||
| 242 | }) | 247 | }) |
| 243 | } | 248 | } |
| 244 | 249 | ||
| 245 | /// The header every frame of this stream carries, at `bitrate_kbps`. | 250 | /// The header every frame of this stream carries, at `bitrate_kbps`. |
| 246 | - fn header(&self, bitrate_kbps: u32) -> FrameHeader { | 251 | + fn header(&self, bitrate_kbps: u32, padding: bool) -> FrameHeader { |
| 247 | FrameHeader { | 252 | FrameHeader { |
| 248 | version: self.version, | 253 | version: self.version, |
| 249 | layer: 3, | 254 | layer: 3, |
| 250 | crc: false, | 255 | crc: false, |
| 251 | bitrate_kbps, | 256 | bitrate_kbps, |
| 252 | sample_rate: self.sample_rate, | 257 | sample_rate: self.sample_rate, |
| 253 | - padding: false, | 258 | + padding, |
| 254 | private: false, | 259 | private: false, |
| 255 | mode: self.mode, | 260 | mode: self.mode, |
| 256 | mode_ext: self.mode_ext, | 261 | mode_ext: self.mode_ext, |
| @@ -260,9 +265,34 @@ impl Mp3Encode { | |||
| 260 | } | 265 | } |
| 261 | } | 266 | } |
| 262 | 267 | ||
| 268 | + /// The slot remainder a frame at `kbps` leaves over the sample rate. | ||
| 269 | + fn slot_remainder(&self, kbps: u32) -> i64 { | ||
| 270 | + let per_kbps: u64 = if self.version == Version::Mpeg1 { | ||
| 271 | + 144_000 | ||
| 272 | + } else { | ||
| 273 | + 72_000 | ||
| 274 | + }; | ||
| 275 | + (per_kbps * u64::from(kbps) % u64::from(self.sample_rate)) as i64 | ||
| 276 | + } | ||
| 277 | + | ||
| 278 | + /// Whether the next emitted frame at `kbps` carries a padding byte. | ||
| 279 | + fn pads_next(&self, kbps: u32) -> bool { | ||
| 280 | + self.padding_lag - self.slot_remainder(kbps) < 0 | ||
| 281 | + } | ||
| 282 | + | ||
| 283 | + /// Advances the padding accumulator for one emitted frame at `kbps`. | ||
| 284 | + fn next_padding(&mut self, kbps: u32) -> bool { | ||
| 285 | + let padding = self.pads_next(kbps); | ||
| 286 | + self.padding_lag -= self.slot_remainder(kbps); | ||
| 287 | + if padding { | ||
| 288 | + self.padding_lag += i64::from(self.sample_rate); | ||
| 289 | + } | ||
| 290 | + padding | ||
| 291 | + } | ||
| 292 | + | ||
| 263 | /// Granules per frame for this stream. | 293 | /// Granules per frame for this stream. |
| 264 | pub fn granules(&self) -> usize { | 294 | pub fn granules(&self) -> usize { |
| 265 | - self.header(self.bitrate_kbps).granules() | 295 | + self.header(self.bitrate_kbps, false).granules() |
| 266 | } | 296 | } |
| 267 | 297 | ||
| 268 | /// Samples per channel one frame codes. | 298 | /// Samples per channel one frame codes. |
| @@ -460,14 +490,14 @@ fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> { | |||
| 460 | } else { | 490 | } else { |
| 461 | &BITRATES_V2 | 491 | &BITRATES_V2 |
| 462 | }; | 492 | }; |
| 463 | - let side = core.header(core.bitrate_kbps).side_info_len(); | 493 | + let side = core.header(core.bitrate_kbps, false).side_info_len(); |
| 464 | let kbps = table | 494 | let kbps = table |
| 465 | .iter() | 495 | .iter() |
| 466 | .copied() | 496 | .copied() |
| 467 | .filter(|&k| k >= core.bitrate_kbps) | 497 | .filter(|&k| k >= core.bitrate_kbps) |
| 468 | - .find(|&k| core.header(k).frame_len().unwrap_or(0) >= 4 + side + INFO_TAG_LEN) | 498 | + .find(|&k| core.header(k, false).frame_len().unwrap_or(0) >= 4 + side + INFO_TAG_LEN) |
| 469 | .unwrap_or(table[table.len() - 1]); | 499 | .unwrap_or(table[table.len() - 1]); |
| 470 | - let header = core.header(kbps); | 500 | + let header = core.header(kbps, false); |
| 471 | let frame_len = header.frame_len().unwrap_or(417); | 501 | let frame_len = header.frame_len().unwrap_or(417); |
| 472 | let mut out = vec![0u8; frame_len]; | 502 | let mut out = vec![0u8; frame_len]; |
| 473 | out[..4].copy_from_slice(&header.to_bytes()); | 503 | out[..4].copy_from_slice(&header.to_bytes()); |
| @@ -836,7 +866,7 @@ impl Mp3Encode { | |||
| 836 | // so the cheapest candidate at or under 1.0 is found by | 866 | // so the cheapest candidate at or under 1.0 is found by |
| 837 | // bisection over the table (four codings, not fourteen). | 867 | // bisection over the table (four codings, not fourteen). |
| 838 | let code_at = |candidate: u32| -> (Vec<CodedGranule>, f64) { | 868 | let code_at = |candidate: u32| -> (Vec<CodedGranule>, f64) { |
| 839 | - let header = self.header(candidate); | 869 | + let header = self.header(candidate, self.pads_next(candidate)); |
| 840 | let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); | 870 | let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); |
| 841 | let mut frame_coded = Vec::with_capacity(granules * channels); | 871 | let mut frame_coded = Vec::with_capacity(granules * channels); |
| 842 | let mut ratio = 0.0; | 872 | let mut ratio = 0.0; |
| @@ -890,7 +920,7 @@ impl Mp3Encode { | |||
| 890 | (best.0, table[best_index]) | 920 | (best.0, table[best_index]) |
| 891 | } | 921 | } |
| 892 | None => { | 922 | None => { |
| 893 | - let header = self.header(self.bitrate_kbps); | 923 | + let header = self.header(self.bitrate_kbps, self.pads_next(self.bitrate_kbps)); |
| 894 | let frame_len = header.frame_len().unwrap_or(0); | 924 | let frame_len = header.frame_len().unwrap_or(0); |
| 895 | let capacity = frame_len - 4 - header.side_info_len(); | 925 | let capacity = frame_len - 4 - header.side_info_len(); |
| 896 | let budget_bits = (self.assigned + capacity - self.used) * 8; | 926 | let budget_bits = (self.assigned + capacity - self.used) * 8; |
| @@ -917,7 +947,8 @@ impl Mp3Encode { | |||
| 917 | } | 947 | } |
| 918 | }; | 948 | }; |
| 919 | 949 | ||
| 920 | - let header = self.header(kbps); | 950 | + let padding = self.next_padding(kbps); |
| 951 | + let header = self.header(kbps, padding); | ||
| 921 | let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); | 952 | let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); |
| 922 | let side_info_len = header.side_info_len(); | 953 | let side_info_len = header.side_info_len(); |
| 923 | 954 | ||
crates/ec-opus/src/encoder.rsmodified+112 -17
| @@ -151,6 +151,23 @@ pub struct Encoder { | |||
| 151 | bw_detect: bool, | 151 | bw_detect: bool, |
| 152 | } | 152 | } |
| 153 | 153 | ||
| 154 | +fn toc_bandwidth(toc: u8) -> Bandwidth { | ||
| 155 | + const BW: [Bandwidth; 5] = [ | ||
| 156 | + Bandwidth::Narrow, | ||
| 157 | + Bandwidth::Medium, | ||
| 158 | + Bandwidth::Wide, | ||
| 159 | + Bandwidth::SuperWide, | ||
| 160 | + Bandwidth::Full, | ||
| 161 | + ]; | ||
| 162 | + let config = usize::from(toc >> 3); | ||
| 163 | + match config { | ||
| 164 | + 0..=11 => BW[config / 4], | ||
| 165 | + 12 | 13 => Bandwidth::SuperWide, | ||
| 166 | + 14 | 15 => Bandwidth::Full, | ||
| 167 | + _ => [BW[0], BW[2], BW[3], BW[4]][(config - 16) / 4], | ||
| 168 | + } | ||
| 169 | +} | ||
| 170 | + | ||
| 154 | /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, | 171 | /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, |
| 155 | /// Medium → 12, Wide/SuperWide/Full → 16. SILK only runs at 8/12/16 kHz; | 172 | /// Medium → 12, Wide/SuperWide/Full → 16. SILK only runs at 8/12/16 kHz; |
| 156 | /// for SuperWide/Full the top bands are CELT (Hybrid), so SILK itself is 16. | 173 | /// for SuperWide/Full the top bands are CELT (Hybrid), so SILK itself is 16. |
| @@ -654,6 +671,9 @@ impl Encoder { | |||
| 654 | cap: usize, | 671 | cap: usize, |
| 655 | ) -> Result<(u8, &[u8])> { | 672 | ) -> Result<(u8, &[u8])> { |
| 656 | let frame_48k = frame_size * self.upsample; | 673 | let frame_48k = frame_size * self.upsample; |
| 674 | + if frame_48k > 960 && self.silk_choice(frame_48k).is_none() { | ||
| 675 | + return self.encode_multiframe(pcm, frame_size, cap); | ||
| 676 | + } | ||
| 657 | // libopus `opus_encode_native`: `run_analysis()` runs on the API frame | 677 | // libopus `opus_encode_native`: `run_analysis()` runs on the API frame |
| 658 | // before the mode/bandwidth decisions, so the estimator state advances | 678 | // before the mode/bandwidth decisions, so the estimator state advances |
| 659 | // on every frame, SILK ones included. 24 is libopus's float-API | 679 | // on every frame, SILK ones included. 24 is libopus's float-API |
| @@ -725,6 +745,65 @@ impl Encoder { | |||
| 725 | Ok((toc, &self.range.data()[..n])) | 745 | Ok((toc, &self.range.data()[..n])) |
| 726 | } | 746 | } |
| 727 | 747 | ||
| 748 | + fn encode_multiframe( | ||
| 749 | + &mut self, | ||
| 750 | + pcm: &[f32], | ||
| 751 | + frame_size: usize, | ||
| 752 | + cap: usize, | ||
| 753 | + ) -> Result<(u8, &[u8])> { | ||
| 754 | + let count = frame_size * self.upsample / 960; | ||
| 755 | + if !matches!(count, 2 | 3) || frame_size * self.upsample != count * 960 { | ||
| 756 | + return Err(Error::unsupported( | ||
| 757 | + format!("opus frame of {frame_size} samples at {} Hz", self.sample_rate), | ||
| 758 | + "frames are 2.5, 5, 10, 20, 40 or 60 ms", | ||
| 759 | + )); | ||
| 760 | + } | ||
| 761 | + let sub = frame_size / count; | ||
| 762 | + let (mode, bandwidth) = (self.mode, self.bandwidth); | ||
| 763 | + self.mode = Some(if self.hybrid_choice(960).is_some() { | ||
| 764 | + Mode::Hybrid | ||
| 765 | + } else { | ||
| 766 | + Mode::Celt | ||
| 767 | + }); | ||
| 768 | + let per = cap.saturating_sub(1 + 2 * (count - 1)) / count; | ||
| 769 | + let mut frames: Vec<Vec<u8>> = Vec::with_capacity(count); | ||
| 770 | + let mut toc = 0u8; | ||
| 771 | + let mut result = Ok(()); | ||
| 772 | + for i in 0..count { | ||
| 773 | + let chunk = &pcm[i * sub * self.channels..(i + 1) * sub * self.channels]; | ||
| 774 | + match self.encode_toc_and_payload(chunk, sub, per) { | ||
| 775 | + Ok((t, payload)) => { | ||
| 776 | + frames.push(payload.to_vec()); | ||
| 777 | + if i == 0 { | ||
| 778 | + toc = t; | ||
| 779 | + self.bandwidth = Some(toc_bandwidth(t)); | ||
| 780 | + } | ||
| 781 | + } | ||
| 782 | + Err(e) => { | ||
| 783 | + result = Err(e); | ||
| 784 | + break; | ||
| 785 | + } | ||
| 786 | + } | ||
| 787 | + } | ||
| 788 | + self.mode = mode; | ||
| 789 | + self.bandwidth = bandwidth; | ||
| 790 | + result?; | ||
| 791 | + let mut pos = 0usize; | ||
| 792 | + self.silk_buf[pos] = 0x80 | count as u8; | ||
| 793 | + pos += 1; | ||
| 794 | + for frame in &frames[..count - 1] { | ||
| 795 | + Self::write_frame_len(&mut self.silk_buf[..], &mut pos, frame.len())?; | ||
| 796 | + } | ||
| 797 | + for frame in &frames { | ||
| 798 | + if pos + frame.len() > self.silk_buf.len() { | ||
| 799 | + return Err(Error::corrupt("opus encode: multi-frame packet overflows its buffer")); | ||
| 800 | + } | ||
| 801 | + self.silk_buf[pos..pos + frame.len()].copy_from_slice(frame); | ||
| 802 | + pos += frame.len(); | ||
| 803 | + } | ||
| 804 | + Ok(((toc & !3) | 3, &self.silk_buf[..pos])) | ||
| 805 | + } | ||
| 806 | + | ||
| 728 | /// The TOC byte, the frame size in 48 kHz samples and the CELT end band | 807 | /// The TOC byte, the frame size in 48 kHz samples and the CELT end band |
| 729 | /// for a frame of `frame_size` input samples per channel. | 808 | /// for a frame of `frame_size` input samples per channel. |
| 730 | fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { | 809 | fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { |
| @@ -980,25 +1059,41 @@ impl Encoder { | |||
| 980 | let r = match self.encode_toc_and_payload(input, frame_size, out.len().saturating_sub(3)) { | 1059 | let r = match self.encode_toc_and_payload(input, frame_size, out.len().saturating_sub(3)) { |
| 981 | Err(e) => Err(e), | 1060 | Err(e) => Err(e), |
| 982 | Ok((toc, payload)) => { | 1061 | Ok((toc, payload)) => { |
| 983 | - let n = payload.len(); | 1062 | + let (head, last) = if toc & 3 == 3 { |
| 984 | - let len_bytes = if n < 252 { 1 } else { 2 }; | 1063 | + let count = usize::from(payload[0] & 0x3F); |
| 985 | - if out.len() < 1 + len_bytes + n { | 1064 | + let mut pos = 1; |
| 986 | - Err(Error::corrupt(format!( | 1065 | + let mut sum = 0; |
| 987 | - "opus encode: self-delimited packet needs {} bytes, buffer holds {}", | 1066 | + for _ in 1..count { |
| 988 | - 1 + len_bytes + n, | 1067 | + let b0 = usize::from(payload[pos]); |
| 989 | - out.len() | 1068 | + let (len, used) = if b0 < 252 { |
| 990 | - ))) | 1069 | + (b0, 1) |
| 1070 | + } else { | ||
| 1071 | + (b0 + 4 * usize::from(payload[pos + 1]), 2) | ||
| 1072 | + }; | ||
| 1073 | + sum += len; | ||
| 1074 | + pos += used; | ||
| 1075 | + } | ||
| 1076 | + (pos, payload.len() - pos - sum) | ||
| 991 | } else { | 1077 | } else { |
| 992 | - out[0] = toc; | 1078 | + (0, payload.len()) |
| 993 | - if n < 252 { | 1079 | + }; |
| 994 | - out[1] = n as u8; | 1080 | + let mut len = [0u8; 2]; |
| 995 | - } else { | 1081 | + let mut len_bytes = 0; |
| 996 | - let b0 = 252 + ((n - 252) & 3); | 1082 | + let r = Self::write_frame_len(&mut len, &mut len_bytes, last); |
| 997 | - out[1] = b0 as u8; | 1083 | + let total = 1 + len_bytes + payload.len(); |
| 998 | - out[2] = ((n - b0) / 4) as u8; | 1084 | + match r { |
| 1085 | + Err(e) => Err(e), | ||
| 1086 | + Ok(()) if out.len() < total => Err(Error::corrupt(format!( | ||
| 1087 | + "opus encode: self-delimited packet needs {total} bytes, buffer holds {}", | ||
| 1088 | + out.len() | ||
| 1089 | + ))), | ||
| 1090 | + Ok(()) => { | ||
| 1091 | + out[0] = toc; | ||
| 1092 | + out[1..1 + head].copy_from_slice(&payload[..head]); | ||
| 1093 | + out[1 + head..1 + head + len_bytes].copy_from_slice(&len[..len_bytes]); | ||
| 1094 | + out[1 + head + len_bytes..total].copy_from_slice(&payload[head..]); | ||
| 1095 | + Ok(total) | ||
| 999 | } | 1096 | } |
| 1000 | - out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload); | ||
| 1001 | - Ok(1 + len_bytes + n) | ||
| 1002 | } | 1097 | } |
| 1003 | } | 1098 | } |
| 1004 | }; | 1099 | }; |
crates/ec-opus/src/multistream_enc.rsmodified+1 -1
| @@ -72,7 +72,7 @@ impl MultistreamEncoder { | |||
| 72 | coupled, | 72 | coupled, |
| 73 | mapping: mapping.to_vec(), | 73 | mapping: mapping.to_vec(), |
| 74 | channels: mapping.len(), | 74 | channels: mapping.len(), |
| 75 | - buf: vec![0.0; 2 * 960], | 75 | + buf: vec![0.0; 2 * 2880], |
| 76 | }) | 76 | }) |
| 77 | } | 77 | } |
| 78 | 78 | ||
crates/ec-vorbis/src/encode.rsmodified+3 -0
| @@ -360,6 +360,9 @@ impl VorbisEncoder { | |||
| 360 | if config.sample_rate == 0 { | 360 | if config.sample_rate == 0 { |
| 361 | return Err(Error::corrupt("encoder sample rate of zero")); | 361 | return Err(Error::corrupt("encoder sample rate of zero")); |
| 362 | } | 362 | } |
| 363 | + if !config.quality.is_finite() { | ||
| 364 | + return Err(Error::corrupt("encoder quality must be finite")); | ||
| 365 | + } | ||
| 363 | let (layout, to_ec) = channel_map(channels); | 366 | let (layout, to_ec) = channel_map(channels); |
| 364 | let mut to_vorbis = vec![0usize; channels]; | 367 | let mut to_vorbis = vec![0usize; channels]; |
| 365 | for (vorbis, &ec) in to_ec.iter().enumerate() { | 368 | for (vorbis, &ec) in to_ec.iter().enumerate() { |