forge
Explore
Log in

Don't you dare go Hollow

B11: ec-alac encoder validates input, no panics

Browse files at this commit

4aa9f94cdcb643e4849a48d0eab962b5365c27baAhmet Kaan GümüşParent: 22f0f3f
send_frame checked neither channel count nor plane length: a short or
missing plane panicked on indexing (planar) or was silently truncated
(interleaved). Now channel count and every sample read go through
sample_at(), returning Corrupt/Unsupported.

encode_frame returns Result and rejects n > frame_length (spec B11; the
cookie declares frame_length as the per-frame maximum, so a larger frame
is a non-conformant stream). Output for valid input is unchanged; callers
in tools/golden and tools/ec-bench updated.
Verify: ec-alac encode/round-trip tests and alac golden (orchestrator).
crates/ec-alac/src/encode.rsmodified+38 -31
@@ -453,6 +453,14 @@ fn plan_of(c: Candidate) -> ChannelPlan {
453453 }
454454 }
455455
456+/// The sample at byte offset `at` of one plane, or `None` past its end.
457+fn sample_at(plane: &[u8], at: usize, format: SampleFormat) -> Option<i32> {
458+ match format {
459+ SampleFormat::S16 => Some(i32::from(i16::from_ne_bytes(plane.get(at..at + 2)?.try_into().ok()?))),
460+ _ => Some(i32::from_ne_bytes(plane.get(at..at + 4)?.try_into().ok()?)),
461+ }
462+}
463+
456464 /// `n` low bits set, for masking a two's-complement value into an escape's
457465 /// raw field.
458466 fn mask(n: u32) -> u32 {
@@ -543,9 +551,15 @@ impl AlacEncoder {
543551 /// container-shifted range [`AlacDecoder::decode`] hands back), up to
544552 /// `frame_length` samples per channel — a shorter slice writes a partial
545553 /// frame, exactly as a stream's last frame does.
546- pub fn encode_frame(&self, samples: &[i32]) -> Vec<u8> {
554+ pub fn encode_frame(&self, samples: &[i32]) -> Result<Vec<u8>> {
547555 let channels = self.channels;
548556 let n = samples.len() / channels;
557+ if n > self.cookie.frame_length as usize {
558+ return Err(Error::unsupported(
559+ format!("ALAC frame of {n} samples"),
560+ format!("frame length is {}", self.cookie.frame_length),
561+ ));
562+ }
549563 let mut planes: Vec<Vec<i32>> = vec![Vec::with_capacity(n); channels];
550564 for chunk in samples.chunks_exact(channels) {
551565 for (c, plane) in planes.iter_mut().enumerate() {
@@ -556,7 +570,7 @@ impl AlacEncoder {
556570 w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3);
557571 write_element(&self.cookie, &mut w, &planes, n, self.allow_shift);
558572 w.put(ID_END, 3);
559- w.finish()
573+ Ok(w.finish())
560574 }
561575 }
562576
@@ -572,40 +586,32 @@ impl Encoder for AlacEncoder {
572586 let channels = self.channels;
573587 let shift = self.cookie.container_shift();
574588 let want = self.cookie.sample_format();
589+ if audio.channels() != channels {
590+ return Err(Error::unsupported(
591+ format!("{}-channel input", audio.channels()),
592+ format!("this encoder was opened for {channels} channels"),
593+ ));
594+ }
575595 if audio.format != want {
576596 return Err(Error::unsupported(
577597 format!("{:?} input", audio.format),
578598 "this encoder takes samples in the cookie's own sample format",
579599 ));
580600 }
601+ let width = match want {
602+ SampleFormat::S16 => 2,
603+ _ => 4,
604+ };
605+ let short = || Error::corrupt("ALAC: audio plane shorter than its sample count");
581606 let mut interleaved = Vec::with_capacity(audio.samples * channels);
582- match (audio.planar, want) {
583- (false, SampleFormat::S16) => {
584- for pair in audio.data[0].as_chunks::<2>().0.iter().take(audio.samples * channels) {
585- interleaved.push(i32::from(i16::from_ne_bytes([pair[0], pair[1]])) >> shift);
586- }
587- }
588- (false, _) => {
589- for word in audio.data[0].as_chunks::<4>().0.iter().take(audio.samples * channels) {
590- interleaved.push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> shift);
591- }
592- }
593- (true, SampleFormat::S16) => {
594- for i in 0..audio.samples {
595- for plane in audio.data.iter().take(channels) {
596- let at = i * 2;
597- interleaved.push(i32::from(i16::from_ne_bytes([plane[at], plane[at + 1]])) >> shift);
598- }
599- }
600- }
601- (true, _) => {
602- for i in 0..audio.samples {
603- for plane in audio.data.iter().take(channels) {
604- let at = i * 4;
605- let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]];
606- interleaved.push(i32::from_ne_bytes(w) >> shift);
607- }
608- }
607+ for i in 0..audio.samples {
608+ for c in 0..channels {
609+ let (plane, at) = match audio.planar {
610+ true => (audio.data.get(c), i * width),
611+ false => (audio.data.first(), (i * channels + c) * width),
612+ };
613+ let sample = plane.and_then(|p| sample_at(p, at, want)).ok_or_else(short)?;
614+ interleaved.push(sample >> shift);
609615 }
610616 }
611617 self.pending.extend(interleaved);
@@ -613,7 +619,7 @@ impl Encoder for AlacEncoder {
613619 let rest = self.pending.split_off(self.pending.len() / per_frame * per_frame);
614620 let full = std::mem::replace(&mut self.pending, rest);
615621 for frame in full.chunks_exact(per_frame) {
616- let packet = self.encode_frame(frame);
622+ let packet = self.encode_frame(frame)?;
617623 self.packets.push_back(packet);
618624 }
619625 Ok(())
@@ -630,7 +636,8 @@ impl Encoder for AlacEncoder {
630636 fn flush(&mut self) -> Result<()> {
631637 if !self.pending.is_empty() {
632638 let frame = std::mem::take(&mut self.pending);
633- self.packets.push_back(self.encode_frame(&frame));
639+ let packet = self.encode_frame(&frame)?;
640+ self.packets.push_back(packet);
634641 }
635642 self.eof = true;
636643 Ok(())
crates/ec-alac/tests/encode.rsmodified+7 -7
@@ -34,7 +34,7 @@ fn round_trip(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32,
3434 let per_frame = frame_length as usize * channels as usize;
3535 let mut decoded = Vec::with_capacity(samples.len());
3636 for chunk in samples.chunks(per_frame) {
37- let packet = enc.encode_frame(chunk);
37+ let packet = enc.encode_frame(chunk).expect("frame");
3838 let out = dec.decode(&packet).expect("decode");
3939 // decode() shifts into the PCM container; undo that to compare
4040 // against the true-range input encode_frame took.
@@ -55,7 +55,7 @@ fn mux_to_m4a(enc: &AlacEncoder, channels: usize, sample_rate: u32, samples: &[i
5555 let mut pts = 0i64;
5656 for chunk in samples.chunks(4096 * channels) {
5757 let n = chunk.len() / channels;
58- let data = enc.encode_frame(chunk);
58+ let data = enc.encode_frame(chunk).expect("frame");
5959 let mut packet = Packet::new(stream, time_base, data).with_pts(pts);
6060 packet.duration = Some(n as i64);
6161 mp4.write_packet(&packet).expect("write_packet");
@@ -107,11 +107,11 @@ fn twenty_four_bit_uses_byte_shift_when_cheaper() {
107107
108108 let per_frame = 4096 * channels as usize;
109109 let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder");
110- let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).len()).sum();
110+ let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).expect("frame").len()).sum();
111111
112112 let mut without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder");
113113 without_shift.set_byte_shift(false);
114- let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).len()).sum();
114+ let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).expect("frame").len()).sum();
115115
116116 eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes");
117117 assert!(
@@ -141,7 +141,7 @@ fn twenty_four_bit_tonal_content_round_trips_bit_exactly() {
141141 let shift = enc.cookie().container_shift();
142142 let mut decoded = Vec::new();
143143 for chunk in samples.chunks(4096 * channels as usize) {
144- decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift));
144+ decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift));
145145 }
146146 assert_eq!(&decoded, samples, "{channels}ch 24-bit tone, shift={allow_shift}");
147147
@@ -180,7 +180,7 @@ fn real_audio_round_trips_and_compresses() {
180180 let per_frame = 4096 * spec.channels as usize;
181181 let mut coded_bytes = 0usize;
182182 for chunk in samples.chunks(per_frame) {
183- coded_bytes += enc.encode_frame(chunk).len();
183+ coded_bytes += enc.encode_frame(chunk).expect("frame").len();
184184 }
185185 let raw_bytes = samples.len() * 2;
186186 let ratio = coded_bytes as f64 / raw_bytes as f64;
@@ -257,7 +257,7 @@ fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, wh
257257 let shift = enc.cookie().container_shift();
258258 let mut decoded = Vec::new();
259259 for chunk in samples.chunks(4096 * channels as usize) {
260- decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift));
260+ decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift));
261261 }
262262 assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}");
263263
tools/ec-bench/src/main.rsmodified+1 -1
@@ -828,7 +828,7 @@ fn bench_audio_encode(rows: &mut Vec<Row>) {
828828 let per_frame = 4096 * channels;
829829 let start = Instant::now();
830830 for chunk in samples.chunks(per_frame) {
831- let _ = enc.encode_frame(chunk);
831+ enc.encode_frame(chunk).expect("alac frame");
832832 }
833833 let wall = start.elapsed().as_secs_f64();
834834 rows.push(Row {
tools/golden/src/encode_audio.rsmodified+1 -1
@@ -283,7 +283,7 @@ fn alac_encode(channels: u8, bits: u8, frame: u32) -> ec_core::Result<Vec<u8>> {
283283 let samples = to_int(&synth(usize::from(channels), 48_000, FRAMES), u32::from(bits));
284284 let mut out = enc.cookie().to_bytes().to_vec();
285285 for chunk in samples.chunks(frame as usize * usize::from(channels)) {
286- out.extend(enc.encode_frame(chunk));
286+ out.extend(enc.encode_frame(chunk)?);
287287 }
288288 Ok(out)
289289 }