diff --git a/crates/ec-alac/src/encode.rs b/crates/ec-alac/src/encode.rs index f5525bd8..d0aab98e 100644 --- a/crates/ec-alac/src/encode.rs +++ b/crates/ec-alac/src/encode.rs @@ -453,6 +453,13 @@ fn plan_of(c: Candidate) -> ChannelPlan { } } +fn sample_at(plane: &[u8], at: usize, format: SampleFormat) -> Option { + match format { + SampleFormat::S16 => Some(i32::from(i16::from_ne_bytes(plane.get(at..at + 2)?.try_into().ok()?))), + _ => Some(i32::from_ne_bytes(plane.get(at..at + 4)?.try_into().ok()?)), + } +} + /// `n` low bits set, for masking a two's-complement value into an escape's /// raw field. fn mask(n: u32) -> u32 { @@ -543,9 +550,15 @@ impl AlacEncoder { /// container-shifted range [`AlacDecoder::decode`] hands back), up to /// `frame_length` samples per channel — a shorter slice writes a partial /// frame, exactly as a stream's last frame does. - pub fn encode_frame(&self, samples: &[i32]) -> Vec { + pub fn encode_frame(&self, samples: &[i32]) -> Result> { let channels = self.channels; let n = samples.len() / channels; + if n > self.cookie.frame_length as usize { + return Err(Error::unsupported( + format!("ALAC frame of {n} samples"), + format!("frame length is {}", self.cookie.frame_length), + )); + } let mut planes: Vec> = vec![Vec::with_capacity(n); channels]; for chunk in samples.chunks_exact(channels) { for (c, plane) in planes.iter_mut().enumerate() { @@ -556,7 +569,7 @@ impl AlacEncoder { w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3); write_element(&self.cookie, &mut w, &planes, n, self.allow_shift); w.put(ID_END, 3); - w.finish() + Ok(w.finish()) } } @@ -572,40 +585,32 @@ impl Encoder for AlacEncoder { let channels = self.channels; let shift = self.cookie.container_shift(); let want = self.cookie.sample_format(); + if audio.channels() != channels { + return Err(Error::unsupported( + format!("{}-channel input", audio.channels()), + format!("this encoder was opened for {channels} channels"), + )); + } if audio.format != want { return Err(Error::unsupported( format!("{:?} input", audio.format), "this encoder takes samples in the cookie's own sample format", )); } + let width = match want { + SampleFormat::S16 => 2, + _ => 4, + }; + let short = || Error::corrupt("ALAC: audio plane shorter than its sample count"); let mut interleaved = Vec::with_capacity(audio.samples * channels); - match (audio.planar, want) { - (false, SampleFormat::S16) => { - for pair in audio.data[0].as_chunks::<2>().0.iter().take(audio.samples * channels) { - interleaved.push(i32::from(i16::from_ne_bytes([pair[0], pair[1]])) >> shift); - } - } - (false, _) => { - for word in audio.data[0].as_chunks::<4>().0.iter().take(audio.samples * channels) { - interleaved.push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> shift); - } - } - (true, SampleFormat::S16) => { - for i in 0..audio.samples { - for plane in audio.data.iter().take(channels) { - let at = i * 2; - interleaved.push(i32::from(i16::from_ne_bytes([plane[at], plane[at + 1]])) >> shift); - } - } - } - (true, _) => { - for i in 0..audio.samples { - for plane in audio.data.iter().take(channels) { - let at = i * 4; - let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]]; - interleaved.push(i32::from_ne_bytes(w) >> shift); - } - } + for i in 0..audio.samples { + for c in 0..channels { + let (plane, at) = match audio.planar { + true => (audio.data.get(c), i * width), + false => (audio.data.first(), (i * channels + c) * width), + }; + let sample = plane.and_then(|p| sample_at(p, at, want)).ok_or_else(short)?; + interleaved.push(sample >> shift); } } self.pending.extend(interleaved); @@ -613,7 +618,7 @@ impl Encoder for AlacEncoder { let rest = self.pending.split_off(self.pending.len() / per_frame * per_frame); let full = std::mem::replace(&mut self.pending, rest); for frame in full.chunks_exact(per_frame) { - let packet = self.encode_frame(frame); + let packet = self.encode_frame(frame)?; self.packets.push_back(packet); } Ok(()) @@ -630,7 +635,8 @@ impl Encoder for AlacEncoder { fn flush(&mut self) -> Result<()> { if !self.pending.is_empty() { let frame = std::mem::take(&mut self.pending); - self.packets.push_back(self.encode_frame(&frame)); + let packet = self.encode_frame(&frame)?; + self.packets.push_back(packet); } self.eof = true; Ok(()) diff --git a/crates/ec-alac/tests/encode.rs b/crates/ec-alac/tests/encode.rs index 19b5ea91..5ea11fff 100644 --- a/crates/ec-alac/tests/encode.rs +++ b/crates/ec-alac/tests/encode.rs @@ -34,7 +34,7 @@ fn round_trip(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32, let per_frame = frame_length as usize * channels as usize; let mut decoded = Vec::with_capacity(samples.len()); for chunk in samples.chunks(per_frame) { - let packet = enc.encode_frame(chunk); + let packet = enc.encode_frame(chunk).expect("frame"); let out = dec.decode(&packet).expect("decode"); // decode() shifts into the PCM container; undo that to compare // 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 let mut pts = 0i64; for chunk in samples.chunks(4096 * channels) { let n = chunk.len() / channels; - let data = enc.encode_frame(chunk); + let data = enc.encode_frame(chunk).expect("frame"); let mut packet = Packet::new(stream, time_base, data).with_pts(pts); packet.duration = Some(n as i64); mp4.write_packet(&packet).expect("write_packet"); @@ -107,11 +107,11 @@ fn twenty_four_bit_uses_byte_shift_when_cheaper() { let per_frame = 4096 * channels as usize; let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); - let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).len()).sum(); + let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).expect("frame").len()).sum(); let mut without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); without_shift.set_byte_shift(false); - let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).len()).sum(); + let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).expect("frame").len()).sum(); eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes"); assert!( @@ -141,7 +141,7 @@ fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { let shift = enc.cookie().container_shift(); let mut decoded = Vec::new(); for chunk in samples.chunks(4096 * channels as usize) { - decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift)); + decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift)); } assert_eq!(&decoded, samples, "{channels}ch 24-bit tone, shift={allow_shift}"); @@ -180,7 +180,7 @@ fn real_audio_round_trips_and_compresses() { let per_frame = 4096 * spec.channels as usize; let mut coded_bytes = 0usize; for chunk in samples.chunks(per_frame) { - coded_bytes += enc.encode_frame(chunk).len(); + coded_bytes += enc.encode_frame(chunk).expect("frame").len(); } let raw_bytes = samples.len() * 2; 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 let shift = enc.cookie().container_shift(); let mut decoded = Vec::new(); for chunk in samples.chunks(4096 * channels as usize) { - decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift)); + decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift)); } assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}"); diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index c9bd9d50..6f736766 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -828,7 +828,7 @@ fn bench_audio_encode(rows: &mut Vec) { let per_frame = 4096 * channels; let start = Instant::now(); for chunk in samples.chunks(per_frame) { - let _ = enc.encode_frame(chunk); + enc.encode_frame(chunk).expect("alac frame"); } let wall = start.elapsed().as_secs_f64(); rows.push(Row { diff --git a/tools/golden/src/encode_audio.rs b/tools/golden/src/encode_audio.rs index bd4ebec7..f2e89074 100644 --- a/tools/golden/src/encode_audio.rs +++ b/tools/golden/src/encode_audio.rs @@ -283,7 +283,7 @@ fn alac_encode(channels: u8, bits: u8, frame: u32) -> ec_core::Result> { let samples = to_int(&synth(usize::from(channels), 48_000, FRAMES), u32::from(bits)); let mut out = enc.cookie().to_bytes().to_vec(); for chunk in samples.chunks(frame as usize * usize::from(channels)) { - out.extend(enc.encode_frame(chunk)); + out.extend(enc.encode_frame(chunk)?); } Ok(out) }