diff --git a/crates/ec-aac/src/encode.rs b/crates/ec-aac/src/encode.rs index cbab94c1..c172cb25 100644 --- a/crates/ec-aac/src/encode.rs +++ b/crates/ec-aac/src/encode.rs @@ -199,6 +199,9 @@ impl AacEncoder { format!("{channels} channels has no channelConfiguration"), )); } + if self.config.bitrate_bps == 0 { + return Err(Error::corrupt("aac: bitrate of zero")); + } self.sf_index = sf_index; self.sample_rate = sample_rate; self.channels = usize::from(channels); diff --git a/crates/ec-av1/src/encoder/mod.rs b/crates/ec-av1/src/encoder/mod.rs index f221b88a..c95b9542 100644 --- a/crates/ec-av1/src/encoder/mod.rs +++ b/crates/ec-av1/src/encoder/mod.rs @@ -1591,8 +1591,8 @@ impl Av1Encoder { /// /// # Errors /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be - /// left between the anchor and the hidden frame) or above `config.gop` - /// (the group would straddle a key frame). + /// left between the anchor and the hidden frame). A `mini_gop` above + /// `config.gop` is clamped to the run before the next key frame. pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result { if pyramid.mini_gop < 2 { return Err(Error::unsupported( diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index 526c028e..d03c5238 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -229,7 +229,13 @@ impl Encoder { } let mb_w = cfg.width.div_ceil(16); let mb_h = cfg.height.div_ceil(16); - let fps = f64::from(cfg.framerate.max(1.0)); + if !(cfg.framerate.is_finite() && cfg.framerate > 0.0) { + return Err(Error::unsupported( + "non-positive frame rate", + "the VUI timing and the rate control need a positive frame rate", + )); + } + let fps = f64::from(cfg.framerate); // A rational tick close to the requested rate; time_scale is twice the // frame rate for progressive frames (E.2.1). let timing = rational_timing(fps); diff --git a/crates/ec-image/src/gif_encode.rs b/crates/ec-image/src/gif_encode.rs index ede33930..8e38995d 100644 --- a/crates/ec-image/src/gif_encode.rs +++ b/crates/ec-image/src/gif_encode.rs @@ -6,11 +6,12 @@ //! Alpha below 128 maps to one reserved transparent index. //! //! The file is built so that the canvas a decoder composites is what the frames -//! show. Every frame uses disposal "do not dispose", so a pixel equal to the -//! previous frame is encoded as transparent and keeps the value already on the -//! canvas, and each image is cropped to the bounding box of the changed pixels. -//! A frame with no change folds its delay into the previous frame, so a static -//! run costs one picture and no extra frames. +//! show. Frames use disposal "do not dispose", so a pixel equal to the previous +//! frame is encoded as transparent and keeps the value already on the canvas, and +//! each image is cropped to the bounding box of the changed pixels. A pixel that +//! turns transparent re-emits the previous frame with disposal "restore to +//! background" over the cleared area. A frame with no change folds its delay into +//! the previous frame, so a static run costs one picture and no extra frames. //! //! Output decodes through [`crate::gif::decode_animation`]. No unsafe, no dependencies. @@ -52,11 +53,22 @@ pub struct Encoder { prev: Option>, /// Offset of the last frame's delay field in `out`, and that delay in 1/100 s. last: Option<(usize, u16)>, + last_frame: Option, frames: usize, } +type Rect = (usize, usize, usize, usize); + +struct LastFrame { + start: usize, + rect: Rect, + prev: Option>, + pixels: Vec, +} + /// Graphic Control disposal 1: "do not dispose", leave the frame on the canvas. const DISPOSE_KEEP: u8 = 1 << 2; +const DISPOSE_RESTORE: u8 = 2 << 2; impl Encoder { /// Start a `width` x `height` animation with the given options. @@ -93,6 +105,7 @@ impl Encoder { out, prev: None, last: None, + last_frame: None, frames: 0, }) } @@ -113,40 +126,59 @@ impl Encoder { ), )); } - let prev = self.prev.as_deref(); - - let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); - let mut any = false; - for y in 0..h { - for x in 0..w { - if differs(prev, pixels, y * w + x) { - any = true; - x0 = x0.min(x); - y0 = y0.min(y); - x1 = x1.max(x); - y1 = y1.max(y); - } - } + let mut canvas = self.prev.take(); + let mut restored_now = false; + if let Some(clear) = bounds(w, h, |i| cleared(canvas.as_deref(), pixels, i)) + && let (Some(last), Some((_, delay))) = (self.last_frame.take(), self.last) + { + let rect = join_rect(last.rect, clear); + self.out.truncate(last.start); + self.emit( + last.prev.as_deref(), + &last.pixels, + rect, + delay, + DISPOSE_RESTORE, + ); + let mut restored = last.pixels; + clear_rect(&mut restored, w, rect); + canvas = Some(restored); + restored_now = true; } - let (x0, y0, x1, y1) = if any { - (x0, y0, x1, y1) - } else { - // Nothing changed: fold the delay into the previous frame when it fits. - if let Some((at, last)) = self.last { - let merged = u32::from(last) + u32::from(delay_cs); - if merged <= u32::from(u16::MAX) { - let bytes = (merged as u16).to_le_bytes(); - self.out[at..at + 2].copy_from_slice(&bytes); - self.last = Some((at, merged as u16)); - return Ok(()); + let prev = canvas.as_deref(); + let rect = match bounds(w, h, |i| differs(prev, pixels, i)) { + Some(rect) => rect, + None => { + if let (false, Some((at, last))) = (restored_now, self.last) { + let merged = u32::from(last) + u32::from(delay_cs); + if merged <= u32::from(u16::MAX) { + self.out[at..at + 2].copy_from_slice(&(merged as u16).to_le_bytes()); + self.last = Some((at, merged as u16)); + self.prev = Some(pixels.to_vec()); + return Ok(()); + } } + (0, 0, 0, 0) } - // Too long to merge: a 1x1 transparent frame carries the delay. - (0, 0, 0, 0) }; + self.emit(prev, pixels, rect, delay_cs, DISPOSE_KEEP); + self.prev = Some(pixels.to_vec()); + self.frames += 1; + Ok(()) + } + + fn emit( + &mut self, + prev: Option<&[u8]>, + pixels: &[u8], + rect: Rect, + delay_cs: u16, + disposal: u8, + ) { + let w = usize::from(self.width); + let (x0, y0, x1, y1) = rect; let (rw, rh) = (x1 - x0 + 1, y1 - y0 + 1); - // Source of each pixel in the cropped rectangle: None is the transparent index. let mut src: Vec> = Vec::with_capacity(rw * rh); for y in y0..=y1 { for x in x0..=x1 { @@ -176,11 +208,17 @@ impl Encoder { // The transparent index sits right after the opaque palette. let tidx = palette_len as u8; let delay = delay_cs.to_le_bytes(); - let packed = DISPOSE_KEEP | u8::from(transparent); - let at = self.out.len() + 4; + let packed = disposal | u8::from(transparent); + let start = self.out.len(); self.out .extend_from_slice(&[0x21, 0xf9, 0x04, packed, delay[0], delay[1], tidx, 0]); - self.last = Some((at, delay_cs)); + self.last = Some((start + 4, delay_cs)); + self.last_frame = Some(LastFrame { + start, + rect, + prev: prev.map(<[u8]>::to_vec), + pixels: pixels.to_vec(), + }); self.out.push(0x2c); for v in [x0, y0, rw, rh] { @@ -192,10 +230,6 @@ impl Encoder { } self.out.push(min_code); put_sub_blocks(&mut self.out, &lzw(&indices, min_code)); - - self.prev = Some(pixels.to_vec()); - self.frames += 1; - Ok(()) } /// 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 { } } +fn bounds(w: usize, h: usize, hit: impl Fn(usize) -> bool) -> Option { + let mut found: Option = None; + for y in 0..h { + for x in 0..w { + if hit(y * w + x) { + found = Some(match found { + None => (x, y, x, y), + Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x), y1.max(y)), + }); + } + } + } + found +} + +fn cleared(prev: Option<&[u8]>, pixels: &[u8], i: usize) -> bool { + prev.is_some_and(|p| p[i * 4 + 3] >= 128 && pixels[i * 4 + 3] < 128) +} + +fn join_rect(a: Rect, b: Rect) -> Rect { + (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)) +} + +fn clear_rect(canvas: &mut [u8], w: usize, (x0, y0, x1, y1): Rect) { + for y in y0..=y1 { + for x in x0..=x1 { + canvas[(y * w + x) * 4..(y * w + x) * 4 + 4].fill(0); + } + } +} + fn pack(c: [u8; 3]) -> u32 { (u32::from(c[0]) << 16) | (u32::from(c[1]) << 8) | u32::from(c[2]) } @@ -253,12 +318,10 @@ fn quantize(mut colors: Vec, budget: usize) -> Vec<[u8; 3]> { continue; } for ch in 0..3 { - let (lo, hi) = b - .iter() - .fold((u32::MAX, 0), |(lo, hi), &(k, _)| { - let v = chan(k, ch); - (lo.min(v), hi.max(v)) - }); + let (lo, hi) = b.iter().fold((u32::MAX, 0), |(lo, hi), &(k, _)| { + let v = chan(k, ch); + (lo.min(v), hi.max(v)) + }); let range = hi - lo; match pick { Some((_, _, r)) if r >= range => {} @@ -461,7 +524,7 @@ fn put_sub_blocks(out: &mut Vec, data: &[u8]) { #[cfg(test)] mod tests { use super::*; - use crate::{gif, AnimationFrame, Limits}; + use crate::{AnimationFrame, Limits, gif}; fn encode_frames(w: u16, h: u16, opts: GifOptions, frames: &[(&[u8], u16)]) -> Vec { let mut enc = Encoder::new(w, h, opts).unwrap(); @@ -531,7 +594,8 @@ mod tests { let a: Vec = (0..w * h) .flat_map(|i| { let (x, y) = (i % w, i / w); - let c = [[200, 30, 30], [30, 200, 30], [30, 30, 200], [220, 220, 40]][(x / 8 + y / 8) % 4]; + let c = [[200, 30, 30], [30, 200, 30], [30, 30, 200], [220, 220, 40]] + [(x / 8 + y / 8) % 4]; [c[0], c[1], c[2], 255] }) .collect(); @@ -666,16 +730,25 @@ mod tests { let mut enc = Encoder::new(2, 2, GifOptions::default()).unwrap(); assert!(enc.push_rgba8(&[0; 15], 1).is_err()); assert!(enc.push_rgba8(&[0; 17], 1).is_err()); - assert!(Encoder::new(2, 2, GifOptions::default()).unwrap().finish().is_err()); + assert!( + Encoder::new(2, 2, GifOptions::default()) + .unwrap() + .finish() + .is_err() + ); } #[test] fn ffprobe_reads_the_output_when_it_is_installed() { - let probe = std::process::Command::new("ffprobe").arg("-version").output(); + let probe = std::process::Command::new("ffprobe") + .arg("-version") + .output(); if probe.is_err() { return; } - let px: Vec = (0..8 * 4).flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255]).collect(); + let px: Vec = (0..8 * 4) + .flat_map(|i: u8| [i * 8, 128, 255 - i * 8, 255]) + .collect(); let gif = encode_frames(8, 4, GifOptions::default(), &[(&px, 5), (&px, 5)]); let path = std::env::temp_dir().join(format!("ec-gif-encode-{}.gif", std::process::id())); std::fs::write(&path, &gif).unwrap(); diff --git a/crates/ec-mp3/src/encode.rs b/crates/ec-mp3/src/encode.rs index a0544533..2eea5984 100644 --- a/crates/ec-mp3/src/encode.rs +++ b/crates/ec-mp3/src/encode.rs @@ -162,6 +162,10 @@ pub struct Mp3Encode { /// is smooth from one frame to the next, so the candidate search below /// starts here instead of blind-bisecting the whole table every frame. vbr_index: usize, + /// Fractional-slot accumulator in units of the sample rate: each emitted + /// frame takes its slot remainder off it, and a negative balance is paid + /// back with one padding byte. + padding_lag: i64, } #[derive(Clone, Debug)] @@ -239,18 +243,19 @@ impl Mp3Encode { .min_by_key(|&(_, &k)| k.abs_diff(target)) .map_or(0, |(i, _)| i) }, + padding_lag: 0, }) } /// The header every frame of this stream carries, at `bitrate_kbps`. - fn header(&self, bitrate_kbps: u32) -> FrameHeader { + fn header(&self, bitrate_kbps: u32, padding: bool) -> FrameHeader { FrameHeader { version: self.version, layer: 3, crc: false, bitrate_kbps, sample_rate: self.sample_rate, - padding: false, + padding, private: false, mode: self.mode, mode_ext: self.mode_ext, @@ -260,9 +265,34 @@ impl Mp3Encode { } } + /// The slot remainder a frame at `kbps` leaves over the sample rate. + fn slot_remainder(&self, kbps: u32) -> i64 { + let per_kbps: u64 = if self.version == Version::Mpeg1 { + 144_000 + } else { + 72_000 + }; + (per_kbps * u64::from(kbps) % u64::from(self.sample_rate)) as i64 + } + + /// Whether the next emitted frame at `kbps` carries a padding byte. + fn pads_next(&self, kbps: u32) -> bool { + self.padding_lag - self.slot_remainder(kbps) < 0 + } + + /// Advances the padding accumulator for one emitted frame at `kbps`. + fn next_padding(&mut self, kbps: u32) -> bool { + let padding = self.pads_next(kbps); + self.padding_lag -= self.slot_remainder(kbps); + if padding { + self.padding_lag += i64::from(self.sample_rate); + } + padding + } + /// Granules per frame for this stream. pub fn granules(&self) -> usize { - self.header(self.bitrate_kbps).granules() + self.header(self.bitrate_kbps, false).granules() } /// Samples per channel one frame codes. @@ -460,14 +490,14 @@ fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec { } else { &BITRATES_V2 }; - let side = core.header(core.bitrate_kbps).side_info_len(); + let side = core.header(core.bitrate_kbps, false).side_info_len(); let kbps = table .iter() .copied() .filter(|&k| k >= core.bitrate_kbps) - .find(|&k| core.header(k).frame_len().unwrap_or(0) >= 4 + side + INFO_TAG_LEN) + .find(|&k| core.header(k, false).frame_len().unwrap_or(0) >= 4 + side + INFO_TAG_LEN) .unwrap_or(table[table.len() - 1]); - let header = core.header(kbps); + let header = core.header(kbps, false); let frame_len = header.frame_len().unwrap_or(417); let mut out = vec![0u8; frame_len]; out[..4].copy_from_slice(&header.to_bytes()); @@ -836,7 +866,7 @@ impl Mp3Encode { // so the cheapest candidate at or under 1.0 is found by // bisection over the table (four codings, not fourteen). let code_at = |candidate: u32| -> (Vec, f64) { - let header = self.header(candidate); + let header = self.header(candidate, self.pads_next(candidate)); let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); let mut frame_coded = Vec::with_capacity(granules * channels); let mut ratio = 0.0; @@ -890,7 +920,7 @@ impl Mp3Encode { (best.0, table[best_index]) } None => { - let header = self.header(self.bitrate_kbps); + let header = self.header(self.bitrate_kbps, self.pads_next(self.bitrate_kbps)); let frame_len = header.frame_len().unwrap_or(0); let capacity = frame_len - 4 - header.side_info_len(); let budget_bits = (self.assigned + capacity - self.used) * 8; @@ -917,7 +947,8 @@ impl Mp3Encode { } }; - let header = self.header(kbps); + let padding = self.next_padding(kbps); + let header = self.header(kbps, padding); let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); let side_info_len = header.side_info_len(); diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 3d42baad..2f35a5ee 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -151,6 +151,23 @@ pub struct Encoder { bw_detect: bool, } +fn toc_bandwidth(toc: u8) -> Bandwidth { + const BW: [Bandwidth; 5] = [ + Bandwidth::Narrow, + Bandwidth::Medium, + Bandwidth::Wide, + Bandwidth::SuperWide, + Bandwidth::Full, + ]; + let config = usize::from(toc >> 3); + match config { + 0..=11 => BW[config / 4], + 12 | 13 => Bandwidth::SuperWide, + 14 | 15 => Bandwidth::Full, + _ => [BW[0], BW[2], BW[3], BW[4]][(config - 16) / 4], + } +} + /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, /// Medium → 12, Wide/SuperWide/Full → 16. SILK only runs at 8/12/16 kHz; /// for SuperWide/Full the top bands are CELT (Hybrid), so SILK itself is 16. @@ -654,6 +671,9 @@ impl Encoder { cap: usize, ) -> Result<(u8, &[u8])> { let frame_48k = frame_size * self.upsample; + if frame_48k > 960 && self.silk_choice(frame_48k).is_none() { + return self.encode_multiframe(pcm, frame_size, cap); + } // libopus `opus_encode_native`: `run_analysis()` runs on the API frame // before the mode/bandwidth decisions, so the estimator state advances // on every frame, SILK ones included. 24 is libopus's float-API @@ -725,6 +745,65 @@ impl Encoder { Ok((toc, &self.range.data()[..n])) } + fn encode_multiframe( + &mut self, + pcm: &[f32], + frame_size: usize, + cap: usize, + ) -> Result<(u8, &[u8])> { + let count = frame_size * self.upsample / 960; + if !matches!(count, 2 | 3) || frame_size * self.upsample != count * 960 { + return Err(Error::unsupported( + format!("opus frame of {frame_size} samples at {} Hz", self.sample_rate), + "frames are 2.5, 5, 10, 20, 40 or 60 ms", + )); + } + let sub = frame_size / count; + let (mode, bandwidth) = (self.mode, self.bandwidth); + self.mode = Some(if self.hybrid_choice(960).is_some() { + Mode::Hybrid + } else { + Mode::Celt + }); + let per = cap.saturating_sub(1 + 2 * (count - 1)) / count; + let mut frames: Vec> = Vec::with_capacity(count); + let mut toc = 0u8; + let mut result = Ok(()); + for i in 0..count { + let chunk = &pcm[i * sub * self.channels..(i + 1) * sub * self.channels]; + match self.encode_toc_and_payload(chunk, sub, per) { + Ok((t, payload)) => { + frames.push(payload.to_vec()); + if i == 0 { + toc = t; + self.bandwidth = Some(toc_bandwidth(t)); + } + } + Err(e) => { + result = Err(e); + break; + } + } + } + self.mode = mode; + self.bandwidth = bandwidth; + result?; + let mut pos = 0usize; + self.silk_buf[pos] = 0x80 | count as u8; + pos += 1; + for frame in &frames[..count - 1] { + Self::write_frame_len(&mut self.silk_buf[..], &mut pos, frame.len())?; + } + for frame in &frames { + if pos + frame.len() > self.silk_buf.len() { + return Err(Error::corrupt("opus encode: multi-frame packet overflows its buffer")); + } + self.silk_buf[pos..pos + frame.len()].copy_from_slice(frame); + pos += frame.len(); + } + Ok(((toc & !3) | 3, &self.silk_buf[..pos])) + } + /// The TOC byte, the frame size in 48 kHz samples and the CELT end band /// for a frame of `frame_size` input samples per channel. fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { @@ -980,25 +1059,41 @@ impl Encoder { let r = match self.encode_toc_and_payload(input, frame_size, out.len().saturating_sub(3)) { Err(e) => Err(e), Ok((toc, payload)) => { - let n = payload.len(); - let len_bytes = if n < 252 { 1 } else { 2 }; - if out.len() < 1 + len_bytes + n { - Err(Error::corrupt(format!( - "opus encode: self-delimited packet needs {} bytes, buffer holds {}", - 1 + len_bytes + n, - out.len() - ))) + let (head, last) = if toc & 3 == 3 { + let count = usize::from(payload[0] & 0x3F); + let mut pos = 1; + let mut sum = 0; + for _ in 1..count { + let b0 = usize::from(payload[pos]); + let (len, used) = if b0 < 252 { + (b0, 1) + } else { + (b0 + 4 * usize::from(payload[pos + 1]), 2) + }; + sum += len; + pos += used; + } + (pos, payload.len() - pos - sum) } else { - out[0] = toc; - if n < 252 { - out[1] = n as u8; - } else { - let b0 = 252 + ((n - 252) & 3); - out[1] = b0 as u8; - out[2] = ((n - b0) / 4) as u8; + (0, payload.len()) + }; + let mut len = [0u8; 2]; + let mut len_bytes = 0; + let r = Self::write_frame_len(&mut len, &mut len_bytes, last); + let total = 1 + len_bytes + payload.len(); + match r { + Err(e) => Err(e), + Ok(()) if out.len() < total => Err(Error::corrupt(format!( + "opus encode: self-delimited packet needs {total} bytes, buffer holds {}", + out.len() + ))), + Ok(()) => { + out[0] = toc; + out[1..1 + head].copy_from_slice(&payload[..head]); + out[1 + head..1 + head + len_bytes].copy_from_slice(&len[..len_bytes]); + out[1 + head + len_bytes..total].copy_from_slice(&payload[head..]); + Ok(total) } - out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload); - Ok(1 + len_bytes + n) } } }; diff --git a/crates/ec-opus/src/multistream_enc.rs b/crates/ec-opus/src/multistream_enc.rs index dfe8f9a7..c477d6ee 100644 --- a/crates/ec-opus/src/multistream_enc.rs +++ b/crates/ec-opus/src/multistream_enc.rs @@ -72,7 +72,7 @@ impl MultistreamEncoder { coupled, mapping: mapping.to_vec(), channels: mapping.len(), - buf: vec![0.0; 2 * 960], + buf: vec![0.0; 2 * 2880], }) } diff --git a/crates/ec-vorbis/src/encode.rs b/crates/ec-vorbis/src/encode.rs index bf3f1223..307fb2c8 100644 --- a/crates/ec-vorbis/src/encode.rs +++ b/crates/ec-vorbis/src/encode.rs @@ -360,6 +360,9 @@ impl VorbisEncoder { if config.sample_rate == 0 { return Err(Error::corrupt("encoder sample rate of zero")); } + if !config.quality.is_finite() { + return Err(Error::corrupt("encoder quality must be finite")); + } let (layout, to_ec) = channel_map(channels); let mut to_vorbis = vec![0usize; channels]; for (vorbis, &ec) in to_ec.iter().enumerate() {