forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/b11' into simplify/w1a

Browse files at this commit

8fc2fda1d57b26fd94be52b0b116ce9e9f10311eAhmet Kaan GümüşParent: 8d9577ea0267da
crates/ec-alac/src/encode.rsmodified+37 -31
@@ -453,6 +453,13 @@ fn plan_of(c: Candidate) -> ChannelPlan {
453453 }
454454 }
455455
456+fn sample_at(plane: &[u8], at: usize, format: SampleFormat) -> Option<i32> {
457+ match format {
458+ SampleFormat::S16 => Some(i32::from(i16::from_ne_bytes(plane.get(at..at + 2)?.try_into().ok()?))),
459+ _ => Some(i32::from_ne_bytes(plane.get(at..at + 4)?.try_into().ok()?)),
460+ }
461+}
462+
456463 /// `n` low bits set, for masking a two's-complement value into an escape's
457464 /// raw field.
458465 fn mask(n: u32) -> u32 {
@@ -543,9 +550,15 @@ impl AlacEncoder {
543550 /// container-shifted range [`AlacDecoder::decode`] hands back), up to
544551 /// `frame_length` samples per channel — a shorter slice writes a partial
545552 /// frame, exactly as a stream's last frame does.
546- pub fn encode_frame(&self, samples: &[i32]) -> Vec<u8> {
553+ pub fn encode_frame(&self, samples: &[i32]) -> Result<Vec<u8>> {
547554 let channels = self.channels;
548555 let n = samples.len() / channels;
556+ if n > self.cookie.frame_length as usize {
557+ return Err(Error::unsupported(
558+ format!("ALAC frame of {n} samples"),
559+ format!("frame length is {}", self.cookie.frame_length),
560+ ));
561+ }
549562 let mut planes: Vec<Vec<i32>> = vec![Vec::with_capacity(n); channels];
550563 for chunk in samples.chunks_exact(channels) {
551564 for (c, plane) in planes.iter_mut().enumerate() {
@@ -556,7 +569,7 @@ impl AlacEncoder {
556569 w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3);
557570 write_element(&self.cookie, &mut w, &planes, n, self.allow_shift);
558571 w.put(ID_END, 3);
559- w.finish()
572+ Ok(w.finish())
560573 }
561574 }
562575
@@ -572,40 +585,32 @@ impl Encoder for AlacEncoder {
572585 let channels = self.channels;
573586 let shift = self.cookie.container_shift();
574587 let want = self.cookie.sample_format();
588+ if audio.channels() != channels {
589+ return Err(Error::unsupported(
590+ format!("{}-channel input", audio.channels()),
591+ format!("this encoder was opened for {channels} channels"),
592+ ));
593+ }
575594 if audio.format != want {
576595 return Err(Error::unsupported(
577596 format!("{:?} input", audio.format),
578597 "this encoder takes samples in the cookie's own sample format",
579598 ));
580599 }
600+ let width = match want {
601+ SampleFormat::S16 => 2,
602+ _ => 4,
603+ };
604+ let short = || Error::corrupt("ALAC: audio plane shorter than its sample count");
581605 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- }
606+ for i in 0..audio.samples {
607+ for c in 0..channels {
608+ let (plane, at) = match audio.planar {
609+ true => (audio.data.get(c), i * width),
610+ false => (audio.data.first(), (i * channels + c) * width),
611+ };
612+ let sample = plane.and_then(|p| sample_at(p, at, want)).ok_or_else(short)?;
613+ interleaved.push(sample >> shift);
609614 }
610615 }
611616 self.pending.extend(interleaved);
@@ -613,7 +618,7 @@ impl Encoder for AlacEncoder {
613618 let rest = self.pending.split_off(self.pending.len() / per_frame * per_frame);
614619 let full = std::mem::replace(&mut self.pending, rest);
615620 for frame in full.chunks_exact(per_frame) {
616- let packet = self.encode_frame(frame);
621+ let packet = self.encode_frame(frame)?;
617622 self.packets.push_back(packet);
618623 }
619624 Ok(())
@@ -630,7 +635,8 @@ impl Encoder for AlacEncoder {
630635 fn flush(&mut self) -> Result<()> {
631636 if !self.pending.is_empty() {
632637 let frame = std::mem::take(&mut self.pending);
633- self.packets.push_back(self.encode_frame(&frame));
638+ let packet = self.encode_frame(&frame)?;
639+ self.packets.push_back(packet);
634640 }
635641 self.eof = true;
636642 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 }