| author | |
| committer | |
| log | ad4bb44659c9b2a8780f96640438f8cfcb0464e4 |
| tree | 934ea8a1fc967bf5cd53adfa752fccde883f6fae |
| parent | c5419749a0015e50c5727e409ed98a19c988a996 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
3 files changed, 872 insertions(+), 29 deletions(-)
crates/engine/src/audio.rs+432-12| ... | @@ -4,7 +4,7 @@ | ... | @@ -4,7 +4,7 @@ |
| 4 | use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; | 4 | use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; |
| 5 | use cpal::{FromSample, Sample, SampleFormat, Stream}; | 5 | use cpal::{FromSample, Sample, SampleFormat, Stream}; |
| 6 | use std::fs::File; | 6 | use std::fs::File; |
| 7 | use std::io::ErrorKind; | 7 | use std::io::{Cursor, ErrorKind}; |
| 8 | use std::path::{Path, PathBuf}; | 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; | 9 | use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; |
| 10 | use std::sync::{Arc, Mutex}; | 10 | use std::sync::{Arc, Mutex}; |
| ... | @@ -26,14 +26,288 @@ pub struct AudioTrack { | ... | @@ -26,14 +26,288 @@ pub struct AudioTrack { |
| 26 | pub duration_secs: f64, | 26 | pub duration_secs: f64, |
| 27 | } | 27 | } |
| 28 | 28 | ||
| 29 | #[derive(Clone, Copy)] | ||
| 30 | enum WavSampleFormat { | ||
| 31 | U8, | ||
| 32 | I16, | ||
| 33 | I24, | ||
| 34 | I32, | ||
| 35 | F32, | ||
| 36 | F64, | ||
| 37 | } | ||
| 38 | |||
| 39 | #[inline] | ||
| 40 | fn decode_wav_mono<const N: usize>( | ||
| 41 | data: &[u8], | ||
| 42 | out: &mut [f32], | ||
| 43 | mut conv: impl FnMut([u8; N]) -> f32, | ||
| 44 | ) { | ||
| 45 | let (src_chunks, _) = data.as_chunks::<N>(); | ||
| 46 | let (dst_frames, _) = out.as_chunks_mut::<2>(); | ||
| 47 | for (&bytes, dst) in src_chunks.iter().zip(dst_frames) { | ||
| 48 | let s = conv(bytes); | ||
| 49 | *dst = [s, s]; | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | #[inline] | ||
| 54 | fn decode_wav_stereo<const N: usize>( | ||
| 55 | data: &[u8], | ||
| 56 | out: &mut [f32], | ||
| 57 | mut conv: impl FnMut([u8; N]) -> f32, | ||
| 58 | ) { | ||
| 59 | let (src_chunks, _) = data.as_chunks::<N>(); | ||
| 60 | for (dst, &bytes) in out.iter_mut().zip(src_chunks) { | ||
| 61 | *dst = conv(bytes); | ||
| 62 | } | ||
| 63 | } | ||
| 64 | |||
| 65 | /// Fast contiguous WAV loader for standard 1/2-channel PCM & IEEE-float RIFF/WAVE files. | ||
| 66 | /// Returns `Ok(None)` for non-WAV, >2-channel, RF64, compressed, or unusual files so | ||
| 67 | /// callers fall back cleanly to `symphonia`. | ||
| 68 | fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, String> { | ||
| 69 | if bytes.len() < 12 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" { | ||
| 70 | return Ok(None); | ||
| 71 | } | ||
| 72 | |||
| 73 | const WAVE_FORMAT_PCM: u16 = 0x0001; | ||
| 74 | const WAVE_FORMAT_IEEE_FLOAT: u16 = 0x0003; | ||
| 75 | const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; | ||
| 76 | const KSDATAFORMAT_SUBTYPE_PCM: [u8; 16] = [ | ||
| 77 | 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, | ||
| 78 | 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71, | ||
| 79 | ]; | ||
| 80 | const KSDATAFORMAT_SUBTYPE_IEEE_FLOAT: [u8; 16] = [ | ||
| 81 | 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, | ||
| 82 | 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71, | ||
| 83 | ]; | ||
| 84 | |||
| 85 | let mut fmt: Option<(u16, u32, u16, WavSampleFormat)> = None; | ||
| 86 | let mut data_slice: Option<&[u8]> = None; | ||
| 87 | let mut pos = 12usize; | ||
| 88 | |||
| 89 | while pos + 8 <= bytes.len() { | ||
| 90 | let chunk_id = &bytes[pos..pos + 4]; | ||
| 91 | let chunk_size = u32::from_le_bytes([ | ||
| 92 | bytes[pos + 4], | ||
| 93 | bytes[pos + 5], | ||
| 94 | bytes[pos + 6], | ||
| 95 | bytes[pos + 7], | ||
| 96 | ]) as usize; | ||
| 97 | let payload_start = pos + 8; | ||
| 98 | let Some(payload_end) = payload_start.checked_add(chunk_size) else { | ||
| 99 | return Ok(None); | ||
| 100 | }; | ||
| 101 | if payload_end > bytes.len() { | ||
| 102 | return Ok(None); | ||
| 103 | } | ||
| 104 | let payload = &bytes[payload_start..payload_end]; | ||
| 105 | |||
| 106 | if chunk_id == b"fmt " { | ||
| 107 | if fmt.is_some() || payload.len() < 16 { | ||
| 108 | return Ok(None); | ||
| 109 | } | ||
| 110 | let format_tag = u16::from_le_bytes([payload[0], payload[1]]); | ||
| 111 | let channels = u16::from_le_bytes([payload[2], payload[3]]); | ||
| 112 | let sample_rate = u32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]]); | ||
| 113 | let block_align = u16::from_le_bytes([payload[12], payload[13]]); | ||
| 114 | let bits_per_sample = u16::from_le_bytes([payload[14], payload[15]]); | ||
| 115 | |||
| 116 | if sample_rate == 0 || (channels != 1 && channels != 2) { | ||
| 117 | return Ok(None); | ||
| 118 | } | ||
| 119 | |||
| 120 | let sample_fmt = match format_tag { | ||
| 121 | WAVE_FORMAT_PCM => { | ||
| 122 | if !matches!(payload.len(), 16 | 18 | 40) { | ||
| 123 | return Ok(None); | ||
| 124 | } | ||
| 125 | match bits_per_sample { | ||
| 126 | 8 => WavSampleFormat::U8, | ||
| 127 | 16 => WavSampleFormat::I16, | ||
| 128 | 24 => WavSampleFormat::I24, | ||
| 129 | 32 => WavSampleFormat::I32, | ||
| 130 | _ => return Ok(None), | ||
| 131 | } | ||
| 132 | } | ||
| 133 | WAVE_FORMAT_IEEE_FLOAT => { | ||
| 134 | if !matches!(payload.len(), 16 | 18 | 40) { | ||
| 135 | return Ok(None); | ||
| 136 | } | ||
| 137 | match bits_per_sample { | ||
| 138 | 32 => WavSampleFormat::F32, | ||
| 139 | 64 => WavSampleFormat::F64, | ||
| 140 | _ => return Ok(None), | ||
| 141 | } | ||
| 142 | } | ||
| 143 | WAVE_FORMAT_EXTENSIBLE => { | ||
| 144 | if payload.len() < 40 { | ||
| 145 | return Ok(None); | ||
| 146 | } | ||
| 147 | let extra_size = u16::from_le_bytes([payload[16], payload[17]]); | ||
| 148 | let valid_bits = u16::from_le_bytes([payload[18], payload[19]]); | ||
| 149 | if extra_size != 22 || valid_bits != bits_per_sample { | ||
| 150 | return Ok(None); | ||
| 151 | } | ||
| 152 | let guid = &payload[24..40]; | ||
| 153 | if guid == KSDATAFORMAT_SUBTYPE_PCM { | ||
| 154 | match bits_per_sample { | ||
| 155 | 8 => WavSampleFormat::U8, | ||
| 156 | 16 => WavSampleFormat::I16, | ||
| 157 | 24 => WavSampleFormat::I24, | ||
| 158 | 32 => WavSampleFormat::I32, | ||
| 159 | _ => return Ok(None), | ||
| 160 | } | ||
| 161 | } else if guid == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT { | ||
| 162 | match bits_per_sample { | ||
| 163 | 32 => WavSampleFormat::F32, | ||
| 164 | 64 => WavSampleFormat::F64, | ||
| 165 | _ => return Ok(None), | ||
| 166 | } | ||
| 167 | } else { | ||
| 168 | return Ok(None); | ||
| 169 | } | ||
| 170 | } | ||
| 171 | _ => return Ok(None), | ||
| 172 | }; | ||
| 173 | |||
| 174 | let expected_block_align = channels.saturating_mul(bits_per_sample / 8); | ||
| 175 | if block_align != expected_block_align || block_align == 0 { | ||
| 176 | return Ok(None); | ||
| 177 | } | ||
| 178 | fmt = Some((channels, sample_rate, block_align, sample_fmt)); | ||
| 179 | } else if chunk_id == b"data" { | ||
| 180 | if data_slice.is_some() { | ||
| 181 | return Ok(None); | ||
| 182 | } | ||
| 183 | data_slice = Some(payload); | ||
| 184 | } | ||
| 185 | |||
| 186 | pos = payload_end + (chunk_size & 1); | ||
| 187 | } | ||
| 188 | |||
| 189 | let (Some((channels, sample_rate, block_align, sample_fmt)), Some(data)) = (fmt, data_slice) | ||
| 190 | else { | ||
| 191 | return Ok(None); | ||
| 192 | }; | ||
| 193 | |||
| 194 | let block_align = block_align as usize; | ||
| 195 | let total_frames = data.len() / block_align; | ||
| 196 | let usable_bytes = total_frames * block_align; | ||
| 197 | let data = &data[..usable_bytes]; | ||
| 198 | let mut stereo_samples = vec![0.0_f32; total_frames * 2]; | ||
| 199 | |||
| 200 | match (channels, sample_fmt) { | ||
| 201 | (1, WavSampleFormat::U8) => { | ||
| 202 | decode_wav_mono::<1>(data, &mut stereo_samples, |[b]| (b as f32 / 128.0) - 1.0); | ||
| 203 | } | ||
| 204 | (1, WavSampleFormat::I16) => { | ||
| 205 | decode_wav_mono::<2>(data, &mut stereo_samples, |b| { | ||
| 206 | i16::from_le_bytes(b) as f32 * (1.0 / 32_768.0) | ||
| 207 | }); | ||
| 208 | } | ||
| 209 | (1, WavSampleFormat::I24) => { | ||
| 210 | decode_wav_mono::<3>(data, &mut stereo_samples, |b| { | ||
| 211 | (i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) as f32 * (1.0 / 8_388_608.0) | ||
| 212 | }); | ||
| 213 | } | ||
| 214 | (1, WavSampleFormat::I32) => { | ||
| 215 | decode_wav_mono::<4>(data, &mut stereo_samples, |b| { | ||
| 216 | (i32::from_le_bytes(b) as f64 / 2_147_483_648.0) as f32 | ||
| 217 | }); | ||
| 218 | } | ||
| 219 | (1, WavSampleFormat::F32) => { | ||
| 220 | decode_wav_mono::<4>(data, &mut stereo_samples, f32::from_le_bytes); | ||
| 221 | } | ||
| 222 | (1, WavSampleFormat::F64) => { | ||
| 223 | decode_wav_mono::<8>(data, &mut stereo_samples, |b| f64::from_le_bytes(b) as f32); | ||
| 224 | } | ||
| 225 | (2, WavSampleFormat::U8) => { | ||
| 226 | decode_wav_stereo::<1>(data, &mut stereo_samples, |[b]| (b as f32 / 128.0) - 1.0); | ||
| 227 | } | ||
| 228 | (2, WavSampleFormat::I16) => { | ||
| 229 | decode_wav_stereo::<2>(data, &mut stereo_samples, |b| { | ||
| 230 | i16::from_le_bytes(b) as f32 * (1.0 / 32_768.0) | ||
| 231 | }); | ||
| 232 | } | ||
| 233 | (2, WavSampleFormat::I24) => { | ||
| 234 | decode_wav_stereo::<3>(data, &mut stereo_samples, |b| { | ||
| 235 | (i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) as f32 * (1.0 / 8_388_608.0) | ||
| 236 | }); | ||
| 237 | } | ||
| 238 | (2, WavSampleFormat::I32) => { | ||
| 239 | decode_wav_stereo::<4>(data, &mut stereo_samples, |b| { | ||
| 240 | (i32::from_le_bytes(b) as f64 / 2_147_483_648.0) as f32 | ||
| 241 | }); | ||
| 242 | } | ||
| 243 | (2, WavSampleFormat::F32) => { | ||
| 244 | decode_wav_stereo::<4>(data, &mut stereo_samples, f32::from_le_bytes); | ||
| 245 | } | ||
| 246 | (2, WavSampleFormat::F64) => { | ||
| 247 | decode_wav_stereo::<8>(data, &mut stereo_samples, |b| f64::from_le_bytes(b) as f32); | ||
| 248 | } | ||
| 249 | _ => return Ok(None), | ||
| 250 | } | ||
| 251 | |||
| 252 | let duration_secs = total_frames as f64 / sample_rate as f64; | ||
| 253 | Ok(Some(AudioTrack { | ||
| 254 | path: path.to_path_buf(), | ||
| 255 | sample_rate, | ||
| 256 | channels: 2, | ||
| 257 | samples: Arc::new(stereo_samples), | ||
| 258 | duration_secs, | ||
| 259 | })) | ||
| 260 | } | ||
| 261 | |||
| 262 | #[inline] | ||
| 263 | fn slice_peak_abs(slice: &[f32]) -> f32 { | ||
| 264 | let mut acc = [0.0_f32; 8]; | ||
| 265 | let (chunks, rem) = slice.as_chunks::<8>(); | ||
| 266 | for c in chunks { | ||
| 267 | for (m, &s) in acc.iter_mut().zip(c.iter()) { | ||
| 268 | *m = m.max(s.abs()); | ||
| 269 | } | ||
| 270 | } | ||
| 271 | let mut max_amp = acc[0] | ||
| 272 | .max(acc[1]) | ||
| 273 | .max(acc[2]) | ||
| 274 | .max(acc[3]) | ||
| 275 | .max(acc[4]) | ||
| 276 | .max(acc[5]) | ||
| 277 | .max(acc[6]) | ||
| 278 | .max(acc[7]); | ||
| 279 | for &s in rem { | ||
| 280 | max_amp = max_amp.max(s.abs()); | ||
| 281 | } | ||
| 282 | max_amp.clamp(0.0, 1.0) | ||
| 283 | } | ||
| 284 | |||
| 29 | impl AudioTrack { | 285 | impl AudioTrack { |
| 30 | /// Decodes an audio file (`.wav`, `.mp3`, `.flac`, `.ogg`, `.m4a`, `.aac`) into | 286 | /// Decodes an audio file (`.wav`, `.mp3`, `.flac`, `.ogg`, `.m4a`, `.aac`) into |
| 31 | /// interleaved stereo `f32` samples. | 287 | /// interleaved stereo `f32` samples. |
| 32 | pub fn load(path: impl AsRef<Path>) -> Result<Self, String> { | 288 | pub fn load(path: impl AsRef<Path>) -> Result<Self, String> { |
| 33 | let path_ref = path.as_ref(); | 289 | let path_ref = path.as_ref(); |
| 34 | let file = File::open(path_ref) | 290 | let is_wav = path_ref |
| 35 | .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?; | 291 | .extension() |
| 36 | let mss = MediaSourceStream::new(Box::new(file), Default::default()); | 292 | .and_then(|e| e.to_str()) |
| 293 | .is_some_and(|ext| ext.eq_ignore_ascii_case("wav")); | ||
| 294 | |||
| 295 | let mss = if is_wav { | ||
| 296 | let bytes = std::fs::read(path_ref) | ||
| 297 | .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?; | ||
| 298 | if let Some(track) = try_load_wav_fast(path_ref, &bytes)? { | ||
| 299 | return Ok(track); | ||
| 300 | } | ||
| 301 | MediaSourceStream::new(Box::new(Cursor::new(bytes)), Default::default()) | ||
| 302 | } else { | ||
| 303 | let file = File::open(path_ref) | ||
| 304 | .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?; | ||
| 305 | MediaSourceStream::new(Box::new(file), Default::default()) | ||
| 306 | }; | ||
| 307 | Self::load_via_symphonia(path_ref, mss) | ||
| 308 | } | ||
| 309 | |||
| 310 | fn load_via_symphonia(path_ref: &Path, mss: MediaSourceStream) -> Result<Self, String> { | ||
| 37 | 311 | ||
| 38 | let mut hint = Hint::new(); | 312 | let mut hint = Hint::new(); |
| 39 | if let Some(ext) = path_ref.extension().and_then(|e| e.to_str()) { | 313 | if let Some(ext) = path_ref.extension().and_then(|e| e.to_str()) { |
| ... | @@ -195,15 +469,8 @@ impl AudioTrack { | ... | @@ -195,15 +469,8 @@ impl AudioTrack { |
| 195 | if s0 >= total_frames || s0 >= s1 { | 469 | if s0 >= total_frames || s0 >= s1 { |
| 196 | continue; | 470 | continue; |
| 197 | } | 471 | } |
| 198 | let mut max_amp = 0.0_f32; | ||
| 199 | let slice = &self.samples[(s0 * 2)..(s1 * 2)]; | 472 | let slice = &self.samples[(s0 * 2)..(s1 * 2)]; |
| 200 | for &s in slice { | 473 | *peak_out = slice_peak_abs(slice); |
| 201 | let a = s.abs(); | ||
| 202 | if a > max_amp { | ||
| 203 | max_amp = a; | ||
| 204 | } | ||
| 205 | } | ||
| 206 | *peak_out = max_amp.clamp(0.0, 1.0); | ||
| 207 | } | 474 | } |
| 208 | peaks | 475 | peaks |
| 209 | } | 476 | } |
| ... | @@ -835,4 +1102,157 @@ mod tests { | ... | @@ -835,4 +1102,157 @@ mod tests { |
| 835 | "RT callback overwrote final seek {final_target} backward -> {observed}" | 1102 | "RT callback overwrote final seek {final_target} backward -> {observed}" |
| 836 | ); | 1103 | ); |
| 837 | } | 1104 | } |
| 1105 | |||
| 1106 | #[test] | ||
| 1107 | fn test_fast_wav_and_peaks_match_symphonia_bit_for_bit() { | ||
| 1108 | fn build_wav(format_tag: u16, channels: u16, sr: u32, bps: u16, data: &[u8]) -> Vec<u8> { | ||
| 1109 | let block_align = channels * (bps / 8); | ||
| 1110 | let byte_rate = sr * block_align as u32; | ||
| 1111 | let mut wav = Vec::with_capacity(44 + data.len()); | ||
| 1112 | wav.extend_from_slice(b"RIFF"); | ||
| 1113 | wav.extend_from_slice(&((36 + 12 + data.len()) as u32).to_le_bytes()); | ||
| 1114 | wav.extend_from_slice(b"WAVEfmt "); | ||
| 1115 | wav.extend_from_slice(&16u32.to_le_bytes()); | ||
| 1116 | wav.extend_from_slice(&format_tag.to_le_bytes()); | ||
| 1117 | wav.extend_from_slice(&channels.to_le_bytes()); | ||
| 1118 | wav.extend_from_slice(&sr.to_le_bytes()); | ||
| 1119 | wav.extend_from_slice(&byte_rate.to_le_bytes()); | ||
| 1120 | wav.extend_from_slice(&block_align.to_le_bytes()); | ||
| 1121 | wav.extend_from_slice(&bps.to_le_bytes()); | ||
| 1122 | wav.extend_from_slice(b"JUNK"); | ||
| 1123 | wav.extend_from_slice(&3u32.to_le_bytes()); // odd size tests RIFF 2-byte alignment | ||
| 1124 | wav.extend_from_slice(&[1, 2, 3, 0]); | ||
| 1125 | wav.extend_from_slice(b"data"); | ||
| 1126 | wav.extend_from_slice(&(data.len() as u32).to_le_bytes()); | ||
| 1127 | wav.extend_from_slice(data); | ||
| 1128 | wav | ||
| 1129 | } | ||
| 1130 | |||
| 1131 | fn naive_peaks( | ||
| 1132 | track: &AudioTrack, | ||
| 1133 | fps: f64, | ||
| 1134 | offset_frames: f64, | ||
| 1135 | start_frame: i64, | ||
| 1136 | end_frame: i64, | ||
| 1137 | ) -> Vec<f32> { | ||
| 1138 | let count = (end_frame - start_frame + 1) as usize; | ||
| 1139 | let mut peaks = vec![0.0_f32; count]; | ||
| 1140 | let total_frames = track.samples.len() / 2; | ||
| 1141 | let sr = track.sample_rate as f64; | ||
| 1142 | for (i, peak_out) in peaks.iter_mut().enumerate() { | ||
| 1143 | let f = start_frame + i as i64; | ||
| 1144 | let t0 = (f as f64 - offset_frames) / fps; | ||
| 1145 | let t1 = ((f + 1) as f64 - offset_frames) / fps; | ||
| 1146 | if t1 <= 0.0 { | ||
| 1147 | continue; | ||
| 1148 | } | ||
| 1149 | let s0 = (t0.max(0.0) * sr).floor() as usize; | ||
| 1150 | let s1 = ((t1.max(0.0) * sr).ceil() as usize).min(total_frames); | ||
| 1151 | if s0 >= total_frames || s0 >= s1 { | ||
| 1152 | continue; | ||
| 1153 | } | ||
| 1154 | let mut max_amp = 0.0_f32; | ||
| 1155 | for &s in &track.samples[(s0 * 2)..(s1 * 2)] { | ||
| 1156 | let a = s.abs(); | ||
| 1157 | if a > max_amp { | ||
| 1158 | max_amp = a; | ||
| 1159 | } | ||
| 1160 | } | ||
| 1161 | *peak_out = max_amp.clamp(0.0, 1.0); | ||
| 1162 | } | ||
| 1163 | peaks | ||
| 1164 | } | ||
| 1165 | |||
| 1166 | let cases: Vec<(&str, Vec<u8>)> = vec![ | ||
| 1167 | ( | ||
| 1168 | "mono_u8", | ||
| 1169 | build_wav(1, 1, 22050, 8, &(0..400).map(|i| ((i * 19) % 256) as u8).collect::<Vec<_>>()), | ||
| 1170 | ), | ||
| 1171 | ( | ||
| 1172 | "stereo_s16", | ||
| 1173 | build_wav( | ||
| 1174 | 1, | ||
| 1175 | 2, | ||
| 1176 | 44100, | ||
| 1177 | 16, | ||
| 1178 | &(0..800) | ||
| 1179 | .flat_map(|i| (((i as i32 * 7919) % 65536 - 32768) as i16).to_le_bytes()) | ||
| 1180 | .collect::<Vec<_>>(), | ||
| 1181 | ), | ||
| 1182 | ), | ||
| 1183 | ( | ||
| 1184 | "mono_s24", | ||
| 1185 | build_wav( | ||
| 1186 | 1, | ||
| 1187 | 1, | ||
| 1188 | 48000, | ||
| 1189 | 24, | ||
| 1190 | &(0..600) | ||
| 1191 | .flat_map(|i| { | ||
| 1192 | let v = ((i as i32 * 131_071) % 16_777_216) - 8_388_608; | ||
| 1193 | let b = v.to_le_bytes(); | ||
| 1194 | [b[0], b[1], b[2]] | ||
| 1195 | }) | ||
| 1196 | .collect::<Vec<_>>(), | ||
| 1197 | ), | ||
| 1198 | ), | ||
| 1199 | ( | ||
| 1200 | "stereo_s24", | ||
| 1201 | build_wav( | ||
| 1202 | 1, | ||
| 1203 | 2, | ||
| 1204 | 44100, | ||
| 1205 | 24, | ||
| 1206 | &(0..800) | ||
| 1207 | .flat_map(|i| { | ||
| 1208 | let v = ((i as i32 * 262_139) % 16_777_216) - 8_388_608; | ||
| 1209 | let b = v.to_le_bytes(); | ||
| 1210 | [b[0], b[1], b[2]] | ||
| 1211 | }) | ||
| 1212 | .collect::<Vec<_>>(), | ||
| 1213 | ), | ||
| 1214 | ), | ||
| 1215 | ( | ||
| 1216 | "stereo_s32", | ||
| 1217 | build_wav( | ||
| 1218 | 1, | ||
| 1219 | 2, | ||
| 1220 | 48000, | ||
| 1221 | 32, | ||
| 1222 | &(0..600) | ||
| 1223 | .flat_map(|i| (i as i32).wrapping_mul(17_895_697).to_le_bytes()) | ||
| 1224 | .collect::<Vec<_>>(), | ||
| 1225 | ), | ||
| 1226 | ), | ||
| 1227 | ( | ||
| 1228 | "stereo_f32", | ||
| 1229 | build_wav( | ||
| 1230 | 3, | ||
| 1231 | 2, | ||
| 1232 | 48000, | ||
| 1233 | 32, | ||
| 1234 | &(0..600) | ||
| 1235 | .flat_map(|i| (((i % 200) as f32 - 100.0) / 80.0).to_le_bytes()) | ||
| 1236 | .collect::<Vec<_>>(), | ||
| 1237 | ), | ||
| 1238 | ), | ||
| 1239 | ]; | ||
| 1240 | |||
| 1241 | for (label, bytes) in cases { | ||
| 1242 | let p = PathBuf::from(format!("{label}.wav")); | ||
| 1243 | let fast = try_load_wav_fast(&p, &bytes) | ||
| 1244 | .unwrap_or_else(|e| panic!("{label}: {e}")) | ||
| 1245 | .unwrap_or_else(|| panic!("{label}: expected fast path")); | ||
| 1246 | let mss = MediaSourceStream::new(Box::new(Cursor::new(bytes)), Default::default()); | ||
| 1247 | let ref_track = AudioTrack::load_via_symphonia(&p, mss).expect("symphonia fallback"); | ||
| 1248 | assert_eq!(fast.sample_rate, ref_track.sample_rate, "{label} sr"); | ||
| 1249 | assert_eq!(fast.channels, ref_track.channels, "{label} ch"); | ||
| 1250 | assert_eq!(fast.duration_secs, ref_track.duration_secs, "{label} dur"); | ||
| 1251 | assert_eq!(fast.samples, ref_track.samples, "{label} samples mismatch"); | ||
| 1252 | |||
| 1253 | let got_peaks = fast.waveform_peaks(24.0, 2.5, -2, 30); | ||
| 1254 | let exp_peaks = naive_peaks(&fast, 24.0, 2.5, -2, 30); | ||
| 1255 | assert_eq!(got_peaks, exp_peaks, "{label} peaks mismatch"); | ||
| 1256 | } | ||
| 1257 | } | ||
| 838 | } | 1258 | } |
crates/engine/src/eval/dispatch.rs+90-8| ... | @@ -52,12 +52,17 @@ pub struct PendingReadback { | ... | @@ -52,12 +52,17 @@ pub struct PendingReadback { |
| 52 | } | 52 | } |
| 53 | 53 | ||
| 54 | impl PendingReadback { | 54 | impl PendingReadback { |
| 55 | /// Waits for the in-flight GPU readback to complete, reads back tightly packed RGBA8 bytes, | 55 | /// Waits for the in-flight GPU readback to complete, writes tightly packed RGBA8 bytes into |
| 56 | /// unmaps the staging buffer, and returns it to `engine`'s reusable pool. | 56 | /// `dst` (reusing `dst`'s existing heap allocation), unmaps the staging buffer, and returns |
| 57 | pub fn finish(self, engine: &Engine) -> Result<Vec<u8>, Box<dyn std::error::Error>> { | 57 | /// it to `engine`'s reusable pool. |
| 58 | pub fn finish_into( | ||
| 59 | self, | ||
| 60 | engine: &Engine, | ||
| 61 | dst: &mut Vec<u8>, | ||
| 62 | ) -> Result<(), Box<dyn std::error::Error>> { | ||
| 58 | #[cfg(target_arch = "wasm32")] | 63 | #[cfg(target_arch = "wasm32")] |
| 59 | { | 64 | { |
| 60 | let _ = engine; | 65 | let _ = (engine, dst); |
| 61 | Err("synchronous GPU readback is unavailable on wasm32".into()) | 66 | Err("synchronous GPU readback is unavailable on wasm32".into()) |
| 62 | } | 67 | } |
| 63 | #[cfg(not(target_arch = "wasm32"))] | 68 | #[cfg(not(target_arch = "wasm32"))] |
| ... | @@ -79,21 +84,30 @@ impl PendingReadback { | ... | @@ -79,21 +84,30 @@ impl PendingReadback { |
| 79 | let slice = self.buf.slice(..self.required_bytes); | 84 | let slice = self.buf.slice(..self.required_bytes); |
| 80 | let data = slice.get_mapped_range()?; | 85 | let data = slice.get_mapped_range()?; |
| 81 | let total_bytes = (self.width * self.height * 4) as usize; | 86 | let total_bytes = (self.width * self.height * 4) as usize; |
| 82 | let mut out = Vec::with_capacity(total_bytes); | 87 | dst.clear(); |
| 88 | dst.reserve(total_bytes); | ||
| 83 | if self.padded_bpr == self.unpadded_bpr { | 89 | if self.padded_bpr == self.unpadded_bpr { |
| 84 | out.extend_from_slice(&data[..total_bytes]); | 90 | dst.extend_from_slice(&data[..total_bytes]); |
| 85 | } else { | 91 | } else { |
| 86 | for row in 0..self.height as usize { | 92 | for row in 0..self.height as usize { |
| 87 | let start = row * self.padded_bpr as usize; | 93 | let start = row * self.padded_bpr as usize; |
| 88 | out.extend_from_slice(&data[start..start + self.unpadded_bpr as usize]); | 94 | dst.extend_from_slice(&data[start..start + self.unpadded_bpr as usize]); |
| 89 | } | 95 | } |
| 90 | } | 96 | } |
| 91 | drop(data); | 97 | drop(data); |
| 92 | self.buf.unmap(); | 98 | self.buf.unmap(); |
| 93 | engine.pipelines.borrow_mut().readback_pool.return_buffer(self.buf); | 99 | engine.pipelines.borrow_mut().readback_pool.return_buffer(self.buf); |
| 94 | Ok(out) | 100 | Ok(()) |
| 95 | } | 101 | } |
| 96 | } | 102 | } |
| 103 | |||
| 104 | /// Waits for the in-flight GPU readback to complete, reads back tightly packed RGBA8 bytes, | ||
| 105 | /// unmaps the staging buffer, and returns it to `engine`'s reusable pool. | ||
| 106 | pub fn finish(self, engine: &Engine) -> Result<Vec<u8>, Box<dyn std::error::Error>> { | ||
| 107 | let mut out = Vec::new(); | ||
| 108 | self.finish_into(engine, &mut out)?; | ||
| 109 | Ok(out) | ||
| 110 | } | ||
| 97 | } | 111 | } |
| 98 | 112 | ||
| 99 | impl Engine { | 113 | impl Engine { |
| ... | @@ -816,4 +830,72 @@ mod tests { | ... | @@ -816,4 +830,72 @@ mod tests { |
| 816 | assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0); | 830 | assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0); |
| 817 | assert_eq!(eng.pipelines.borrow().bg_misses, misses_before); | 831 | assert_eq!(eng.pipelines.borrow().bg_misses, misses_before); |
| 818 | } | 832 | } |
| 833 | |||
| 834 | #[test] | ||
| 835 | fn pending_readback_finish_into_reuses_allocation_and_matches_finish() { | ||
| 836 | let Ok(eng) = Engine::new_headless() else { | ||
| 837 | return; | ||
| 838 | }; | ||
| 839 | let fill = |tex: &CachedTexture, rgba: [f32; 4]| { | ||
| 840 | let mut enc = eng.device.create_command_encoder(&Default::default()); | ||
| 841 | let mut u = UniformParams::default(); | ||
| 842 | u.p[0] = rgba; | ||
| 843 | u.p[1] = rgba; | ||
| 844 | u.p[2] = rgba; | ||
| 845 | u.p[3] = rgba; | ||
| 846 | eng.dispatch_op( | ||
| 847 | &mut enc, | ||
| 848 | ShaderOp::Bg, | ||
| 849 | &eng.dummy.view, | ||
| 850 | &eng.dummy.view, | ||
| 851 | &eng.dummy.view, | ||
| 852 | tex, | ||
| 853 | &u, | ||
| 854 | ); | ||
| 855 | eng.queue.submit(Some(enc.finish())); | ||
| 856 | eng.reset_uniform_cursors(); | ||
| 857 | }; | ||
| 858 | |||
| 859 | // Test both padded (unaligned width 37) and unpadded (aligned width 64) readbacks. | ||
| 860 | let tex_a = eng.alloc_tex([37, 13], BitDepth::Int8, 0); | ||
| 861 | let tex_b = eng.alloc_tex([37, 13], BitDepth::Int8, 0); | ||
| 862 | let tex_c = eng.alloc_tex([64, 16], BitDepth::Float16, 0); | ||
| 863 | fill(&tex_a, [0.25, 0.5, 0.75, 1.0]); | ||
| 864 | fill(&tex_b, [0.8, 0.2, 0.4, 0.9]); | ||
| 865 | fill(&tex_c, [0.1, 0.6, 0.3, 1.0]); | ||
| 866 | |||
| 867 | let expected_a = eng.readback_rgba(&tex_a).expect("finish a"); | ||
| 868 | let expected_b = eng.readback_rgba(&tex_b).expect("finish b"); | ||
| 869 | let expected_c = eng.readback_rgba(&tex_c).expect("finish c"); | ||
| 870 | |||
| 871 | let mut dst = Vec::with_capacity(64 * 16 * 4); | ||
| 872 | let ptr_initial = dst.as_ptr(); | ||
| 873 | let cap_initial = dst.capacity(); | ||
| 874 | |||
| 875 | for _ in 0..3 { | ||
| 876 | eng.begin_readback_rgba(&tex_a) | ||
| 877 | .expect("begin a") | ||
| 878 | .finish_into(&eng, &mut dst) | ||
| 879 | .expect("finish_into a"); | ||
| 880 | assert_eq!(dst.as_ptr(), ptr_initial, "dst must not reallocate"); | ||
| 881 | assert_eq!(dst.capacity(), cap_initial); | ||
| 882 | assert_eq!(dst, expected_a); | ||
| 883 | |||
| 884 | eng.begin_readback_rgba(&tex_b) | ||
| 885 | .expect("begin b") | ||
| 886 | .finish_into(&eng, &mut dst) | ||
| 887 | .expect("finish_into b"); | ||
| 888 | assert_eq!(dst.as_ptr(), ptr_initial, "dst must not reallocate"); | ||
| 889 | assert_eq!(dst.capacity(), cap_initial); | ||
| 890 | assert_eq!(dst, expected_b); | ||
| 891 | |||
| 892 | eng.begin_readback_rgba(&tex_c) | ||
| 893 | .expect("begin c") | ||
| 894 | .finish_into(&eng, &mut dst) | ||
| 895 | .expect("finish_into c"); | ||
| 896 | assert_eq!(dst.as_ptr(), ptr_initial, "dst must not reallocate"); | ||
| 897 | assert_eq!(dst.capacity(), cap_initial); | ||
| 898 | assert_eq!(dst, expected_c); | ||
| 899 | } | ||
| 900 | } | ||
| 819 | } | 901 | } |
crates/engine/src/media.rs+350-9| ... | @@ -129,21 +129,189 @@ fn path_exists(path: &Path) -> bool { | ... | @@ -129,21 +129,189 @@ fn path_exists(path: &Path) -> bool { |
| 129 | virtual_bytes(path).is_some() || path.exists() | 129 | virtual_bytes(path).is_some() || path.exists() |
| 130 | } | 130 | } |
| 131 | 131 | ||
| 132 | fn open_image(path: &Path) -> Option<image::DynamicImage> { | 132 | #[inline(always)] |
| 133 | fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 { | ||
| 134 | ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8 | ||
| 135 | } | ||
| 136 | |||
| 137 | fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>( | ||
| 138 | reader: &mut png::Reader<R>, | ||
| 139 | w: u32, | ||
| 140 | out_len: usize, | ||
| 141 | row_out_bytes: usize, | ||
| 142 | mut convert_row: F, | ||
| 143 | ) -> Option<Vec<u8>> | ||
| 144 | where | ||
| 145 | F: FnMut(&[u8], &mut [u8]), | ||
| 146 | { | ||
| 147 | let mut rgba = vec![0u8; out_len]; | ||
| 148 | let line_size = reader.output_line_size(w)?; | ||
| 149 | let mut row_buf = vec![0u8; line_size]; | ||
| 150 | for dst_row in rgba.chunks_exact_mut(row_out_bytes) { | ||
| 151 | reader.read_row(&mut row_buf).ok()??; | ||
| 152 | convert_row(&row_buf, dst_row); | ||
| 153 | } | ||
| 154 | Some(rgba) | ||
| 155 | } | ||
| 156 | |||
| 157 | /// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit. | ||
| 158 | /// Returns `None` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the | ||
| 159 | /// caller falls back cleanly to `image::load_from_memory`. | ||
| 160 | fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> { | ||
| 161 | const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10]; | ||
| 162 | if !bytes.starts_with(&PNG_SIGNATURE) { | ||
| 163 | return None; | ||
| 164 | } | ||
| 165 | |||
| 166 | let mut decoder = png::Decoder::new_with_limits( | ||
| 167 | std::io::Cursor::new(bytes), | ||
| 168 | png::Limits { | ||
| 169 | bytes: 512 * 1024 * 1024, | ||
| 170 | }, | ||
| 171 | ); | ||
| 172 | decoder.set_ignore_text_chunk(true); | ||
| 173 | decoder.set_transformations(png::Transformations::EXPAND); | ||
| 174 | |||
| 175 | let mut reader = decoder.read_info().ok()?; | ||
| 176 | let info = reader.info(); | ||
| 177 | if info.interlaced | ||
| 178 | || info.icc_profile.is_some() | ||
| 179 | || info.animation_control.is_some() | ||
| 180 | || info.frame_control.is_some() | ||
| 181 | { | ||
| 182 | return None; | ||
| 183 | } | ||
| 184 | let (w, h) = info.size(); | ||
| 185 | if w == 0 || h == 0 { | ||
| 186 | return None; | ||
| 187 | } | ||
| 188 | |||
| 189 | let (color_type, bit_depth) = reader.output_color_type(); | ||
| 190 | let pixel_count = (w as usize).checked_mul(h as usize)?; | ||
| 191 | let out_len = pixel_count.checked_mul(4)?; | ||
| 192 | let row_out_bytes = (w as usize).checked_mul(4)?; | ||
| 193 | |||
| 194 | match (color_type, bit_depth) { | ||
| 195 | (png::ColorType::Rgba, png::BitDepth::Eight) => { | ||
| 196 | let mut rgba = vec![0u8; out_len]; | ||
| 197 | reader.next_frame(&mut rgba).ok()?; | ||
| 198 | Some(([w, h], rgba, true)) | ||
| 199 | } | ||
| 200 | (png::ColorType::Rgb, png::BitDepth::Eight) => { | ||
| 201 | let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| { | ||
| 202 | let (src_chunks, _) = src.as_chunks::<3>(); | ||
| 203 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); | ||
| 204 | for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) { | ||
| 205 | *dst_px = [r, g, b, 255]; | ||
| 206 | } | ||
| 207 | })?; | ||
| 208 | Some(([w, h], rgba, false)) | ||
| 209 | } | ||
| 210 | (png::ColorType::Grayscale, png::BitDepth::Eight) => { | ||
| 211 | let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| { | ||
| 212 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); | ||
| 213 | for (&g, dst_px) in src.iter().zip(dst_chunks) { | ||
| 214 | *dst_px = [g, g, g, 255]; | ||
| 215 | } | ||
| 216 | })?; | ||
| 217 | Some(([w, h], rgba, false)) | ||
| 218 | } | ||
| 219 | (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => { | ||
| 220 | let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| { | ||
| 221 | let (src_chunks, _) = src.as_chunks::<2>(); | ||
| 222 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); | ||
| 223 | for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) { | ||
| 224 | *dst_px = [g, g, g, a]; | ||
| 225 | } | ||
| 226 | })?; | ||
| 227 | Some(([w, h], rgba, true)) | ||
| 228 | } | ||
| 229 | (png::ColorType::Rgba, png::BitDepth::Sixteen) => { | ||
| 230 | let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| { | ||
| 231 | let (src_chunks, _) = src.as_chunks::<8>(); | ||
| 232 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); | ||
| 233 | for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { | ||
| 234 | *dst_px = [ | ||
| 235 | u16_be_to_u8_rounded(s[0], s[1]), | ||
| 236 | u16_be_to_u8_rounded(s[2], s[3]), | ||
| 237 | u16_be_to_u8_rounded(s[4], s[5]), | ||
| 238 | u16_be_to_u8_rounded(s[6], s[7]), | ||
| 239 | ]; | ||
| 240 | } | ||
| 241 | })?; | ||
| 242 | Some(([w, h], rgba, true)) | ||
| 243 | } | ||
| 244 | (png::ColorType::Rgb, png::BitDepth::Sixteen) => { | ||
| 245 | let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| { | ||
| 246 | let (src_chunks, _) = src.as_chunks::<6>(); | ||
| 247 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); | ||
| 248 | for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { | ||
| 249 | *dst_px = [ | ||
| 250 | u16_be_to_u8_rounded(s[0], s[1]), | ||
| 251 | u16_be_to_u8_rounded(s[2], s[3]), | ||
| 252 | u16_be_to_u8_rounded(s[4], s[5]), | ||
| 253 | 255, | ||
| 254 | ]; | ||
| 255 | } | ||
| 256 | })?; | ||
| 257 | Some(([w, h], rgba, false)) | ||
| 258 | } | ||
| 259 | (png::ColorType::Grayscale, png::BitDepth::Sixteen) => { | ||
| 260 | let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| { | ||
| 261 | let (src_chunks, _) = src.as_chunks::<2>(); | ||
| 262 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); | ||
| 263 | for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) { | ||
| 264 | let g = u16_be_to_u8_rounded(hi, lo); | ||
| 265 | *dst_px = [g, g, g, 255]; | ||
| 266 | } | ||
| 267 | })?; | ||
| 268 | Some(([w, h], rgba, false)) | ||
| 269 | } | ||
| 270 | (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => { | ||
| 271 | let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| { | ||
| 272 | let (src_chunks, _) = src.as_chunks::<4>(); | ||
| 273 | let (dst_chunks, _) = dst.as_chunks_mut::<4>(); | ||
| 274 | for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) { | ||
| 275 | let g = u16_be_to_u8_rounded(s[0], s[1]); | ||
| 276 | *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])]; | ||
| 277 | } | ||
| 278 | })?; | ||
| 279 | Some(([w, h], rgba, true)) | ||
| 280 | } | ||
| 281 | _ => None, | ||
| 282 | } | ||
| 283 | } | ||
| 284 | |||
| 285 | fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> { | ||
| 286 | if let Some(decoded) = decode_png_bytes(bytes) { | ||
| 287 | return Some(decoded); | ||
| 288 | } | ||
| 289 | let dyn_img = image::load_from_memory(bytes).ok()?; | ||
| 290 | let has_alpha = dyn_img.color().has_alpha(); | ||
| 291 | let size = [dyn_img.width(), dyn_img.height()]; | ||
| 292 | let raw = dyn_img.into_rgba8().into_raw(); | ||
| 293 | Some((size, raw, has_alpha)) | ||
| 294 | } | ||
| 295 | |||
| 296 | fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec<u8>, bool)> { | ||
| 133 | if let Some(bytes) = virtual_bytes(path) { | 297 | if let Some(bytes) = virtual_bytes(path) { |
| 134 | return image::load_from_memory(&bytes).ok(); | 298 | return decode_raster_bytes(&bytes); |
| 135 | } | 299 | } |
| 136 | // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares. | 300 | // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares. |
| 137 | match std::fs::read(path) { | 301 | match std::fs::read(path) { |
| 138 | Ok(bytes) => { | 302 | Ok(bytes) => { |
| 139 | if let Ok(img) = image::load_from_memory(&bytes) { | 303 | if let Some(decoded) = decode_raster_bytes(&bytes) { |
| 140 | return Some(img); | 304 | return Some(decoded); |
| 141 | } | 305 | } |
| 142 | } | 306 | } |
| 143 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, | 307 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, |
| 144 | Err(_) => {} | 308 | Err(_) => {} |
| 145 | } | 309 | } |
| 146 | image::open(path).ok() | 310 | let dyn_img = image::open(path).ok()?; |
| 311 | let has_alpha = dyn_img.color().has_alpha(); | ||
| 312 | let size = [dyn_img.width(), dyn_img.height()]; | ||
| 313 | let raw = dyn_img.into_rgba8().into_raw(); | ||
| 314 | Some((size, raw, has_alpha)) | ||
| 147 | } | 315 | } |
| 148 | 316 | ||
| 149 | fn decode_raster_image( | 317 | fn decode_raster_image( |
| ... | @@ -151,10 +319,7 @@ fn decode_raster_image( | ... | @@ -151,10 +319,7 @@ fn decode_raster_image( |
| 151 | post_multiply: bool, | 319 | post_multiply: bool, |
| 152 | allow_parallel_premult: bool, | 320 | allow_parallel_premult: bool, |
| 153 | ) -> Option<DecodedImage> { | 321 | ) -> Option<DecodedImage> { |
| 154 | let dyn_img = open_image(path)?; | 322 | let (size, mut raw, has_alpha) = open_raster_rgba(path)?; |
| 155 | let has_alpha = dyn_img.color().has_alpha(); | ||
| 156 | let size = [dyn_img.width(), dyn_img.height()]; | ||
| 157 | let mut raw = dyn_img.into_rgba8().into_raw(); | ||
| 158 | if post_multiply && has_alpha { | 323 | if post_multiply && has_alpha { |
| 159 | apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult); | 324 | apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult); |
| 160 | } | 325 | } |
| ... | @@ -3564,4 +3729,180 @@ mod tests { | ... | @@ -3564,4 +3729,180 @@ mod tests { |
| 3564 | handle.cancel(); | 3729 | handle.cancel(); |
| 3565 | let _ = std::fs::remove_dir_all(&dir); | 3730 | let _ = std::fs::remove_dir_all(&dir); |
| 3566 | } | 3731 | } |
| 3732 | |||
| 3733 | #[test] | ||
| 3734 | fn direct_png_decode_matches_image_crate_bit_for_bit_all_color_types() { | ||
| 3735 | fn encode_png( | ||
| 3736 | w: u32, | ||
| 3737 | h: u32, | ||
| 3738 | color: png::ColorType, | ||
| 3739 | depth: png::BitDepth, | ||
| 3740 | palette: Option<&[u8]>, | ||
| 3741 | trns: Option<&[u8]>, | ||
| 3742 | data: &[u8], | ||
| 3743 | ) -> Vec<u8> { | ||
| 3744 | let mut out = Vec::new(); | ||
| 3745 | { | ||
| 3746 | let mut enc = png::Encoder::new(&mut out, w, h); | ||
| 3747 | enc.set_color(color); | ||
| 3748 | enc.set_depth(depth); | ||
| 3749 | if let Some(p) = palette { | ||
| 3750 | enc.set_palette(p); | ||
| 3751 | } | ||
| 3752 | if let Some(t) = trns { | ||
| 3753 | enc.set_trns(t); | ||
| 3754 | } | ||
| 3755 | let mut writer = enc.write_header().unwrap(); | ||
| 3756 | writer.write_image_data(data).unwrap(); | ||
| 3757 | } | ||
| 3758 | out | ||
| 3759 | } | ||
| 3760 | |||
| 3761 | let (w, h) = (17u32, 11u32); | ||
| 3762 | let n = (w * h) as usize; | ||
| 3763 | let cases: Vec<(&str, Vec<u8>)> = vec![ | ||
| 3764 | ( | ||
| 3765 | "rgba8", | ||
| 3766 | encode_png( | ||
| 3767 | w, | ||
| 3768 | h, | ||
| 3769 | png::ColorType::Rgba, | ||
| 3770 | png::BitDepth::Eight, | ||
| 3771 | None, | ||
| 3772 | None, | ||
| 3773 | &(0..n * 4).map(|i| ((i * 37 + 13) % 256) as u8).collect::<Vec<_>>(), | ||
| 3774 | ), | ||
| 3775 | ), | ||
| 3776 | ( | ||
| 3777 | "rgb8", | ||
| 3778 | encode_png( | ||
| 3779 | w, | ||
| 3780 | h, | ||
| 3781 | png::ColorType::Rgb, | ||
| 3782 | png::BitDepth::Eight, | ||
| 3783 | None, | ||
| 3784 | None, | ||
| 3785 | &(0..n * 3).map(|i| ((i * 53 + 7) % 256) as u8).collect::<Vec<_>>(), | ||
| 3786 | ), | ||
| 3787 | ), | ||
| 3788 | ( | ||
| 3789 | "gray8", | ||
| 3790 | encode_png( | ||
| 3791 | w, | ||
| 3792 | h, | ||
| 3793 | png::ColorType::Grayscale, | ||
| 3794 | png::BitDepth::Eight, | ||
| 3795 | None, | ||
| 3796 | None, | ||
| 3797 | &(0..n).map(|i| ((i * 29 + 3) % 256) as u8).collect::<Vec<_>>(), | ||
| 3798 | ), | ||
| 3799 | ), | ||
| 3800 | ( | ||
| 3801 | "gray_alpha8", | ||
| 3802 | encode_png( | ||
| 3803 | w, | ||
| 3804 | h, | ||
| 3805 | png::ColorType::GrayscaleAlpha, | ||
| 3806 | png::BitDepth::Eight, | ||
| 3807 | None, | ||
| 3808 | None, | ||
| 3809 | &(0..n * 2).map(|i| ((i * 41 + 19) % 256) as u8).collect::<Vec<_>>(), | ||
| 3810 | ), | ||
| 3811 | ), | ||
| 3812 | ( | ||
| 3813 | "palette_trns", | ||
| 3814 | encode_png( | ||
| 3815 | w, | ||
| 3816 | h, | ||
| 3817 | png::ColorType::Indexed, | ||
| 3818 | png::BitDepth::Eight, | ||
| 3819 | Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128, 255, 255, 255]), | ||
| 3820 | Some(&[0, 128, 255]), | ||
| 3821 | &(0..n).map(|i| (i % 4) as u8).collect::<Vec<_>>(), | ||
| 3822 | ), | ||
| 3823 | ), | ||
| 3824 | ( | ||
| 3825 | "palette_opaque", | ||
| 3826 | encode_png( | ||
| 3827 | w, | ||
| 3828 | h, | ||
| 3829 | png::ColorType::Indexed, | ||
| 3830 | png::BitDepth::Eight, | ||
| 3831 | Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128]), | ||
| 3832 | None, | ||
| 3833 | &(0..n).map(|i| (i % 3) as u8).collect::<Vec<_>>(), | ||
| 3834 | ), | ||
| 3835 | ), | ||
| 3836 | ( | ||
| 3837 | "rgba16", | ||
| 3838 | encode_png( | ||
| 3839 | w, | ||
| 3840 | h, | ||
| 3841 | png::ColorType::Rgba, | ||
| 3842 | png::BitDepth::Sixteen, | ||
| 3843 | None, | ||
| 3844 | None, | ||
| 3845 | // Include boundary values like 0x01ff (511 -> rounds to 2, not 1). | ||
| 3846 | &(0..n * 4) | ||
| 3847 | .flat_map(|i| (((i * 1021 + 255) % 65536) as u16).to_be_bytes()) | ||
| 3848 | .collect::<Vec<_>>(), | ||
| 3849 | ), | ||
| 3850 | ), | ||
| 3851 | ( | ||
| 3852 | "rgb16", | ||
| 3853 | encode_png( | ||
| 3854 | w, | ||
| 3855 | h, | ||
| 3856 | png::ColorType::Rgb, | ||
| 3857 | png::BitDepth::Sixteen, | ||
| 3858 | None, | ||
| 3859 | None, | ||
| 3860 | &(0..n * 3) | ||
| 3861 | .flat_map(|i| (((i * 997 + 511) % 65536) as u16).to_be_bytes()) | ||
| 3862 | .collect::<Vec<_>>(), | ||
| 3863 | ), | ||
| 3864 | ), | ||
| 3865 | ( | ||
| 3866 | "gray16", | ||
| 3867 | encode_png( | ||
| 3868 | w, | ||
| 3869 | h, | ||
| 3870 | png::ColorType::Grayscale, | ||
| 3871 | png::BitDepth::Sixteen, | ||
| 3872 | None, | ||
| 3873 | None, | ||
| 3874 | &(0..n) | ||
| 3875 | .flat_map(|i| (((i * 773 + 128) % 65536) as u16).to_be_bytes()) | ||
| 3876 | .collect::<Vec<_>>(), | ||
| 3877 | ), | ||
| 3878 | ), | ||
| 3879 | ( | ||
| 3880 | "gray_alpha16", | ||
| 3881 | encode_png( | ||
| 3882 | w, | ||
| 3883 | h, | ||
| 3884 | png::ColorType::GrayscaleAlpha, | ||
| 3885 | png::BitDepth::Sixteen, | ||
| 3886 | None, | ||
| 3887 | None, | ||
| 3888 | &(0..n * 2) | ||
| 3889 | .flat_map(|i| (((i * 613 + 384) % 65536) as u16).to_be_bytes()) | ||
| 3890 | .collect::<Vec<_>>(), | ||
| 3891 | ), | ||
| 3892 | ), | ||
| 3893 | ]; | ||
| 3894 | |||
| 3895 | for (label, bytes) in cases { | ||
| 3896 | let dyn_img = image::load_from_memory(&bytes).expect("image crate decode"); | ||
| 3897 | let expected_has_alpha = dyn_img.color().has_alpha(); | ||
| 3898 | let expected_size = [dyn_img.width(), dyn_img.height()]; | ||
| 3899 | let expected_rgba = dyn_img.into_rgba8().into_raw(); | ||
| 3900 | |||
| 3901 | let (got_size, got_rgba, got_has_alpha) = | ||
| 3902 | decode_png_bytes(&bytes).unwrap_or_else(|| panic!("direct decode failed for {label}")); | ||
| 3903 | assert_eq!(got_size, expected_size, "size mismatch for {label}"); | ||
| 3904 | assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}"); | ||
| 3905 | assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}"); | ||
| 3906 | } | ||
| 3907 | } | ||
| 3567 | } | 3908 | } |