| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::fs::File; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::process::Command; |
| 11 | |
| 12 | use ec_core::{Buf, Decoder, Demuxer, Frame, Packet, TimeBase}; |
| 13 | use ec_ogg::{OggDemuxer, granule_of, granule_side_data}; |
| 14 | use ec_vorbis::VorbisDecoder; |
| 15 | |
| 16 | fn scratch() -> PathBuf { |
| 17 | let dir = std::env::temp_dir().join(format!("ec-vorbis-trim-{}", std::process::id())); |
| 18 | std::fs::create_dir_all(&dir).expect("scratch dir"); |
| 19 | dir |
| 20 | } |
| 21 | |
| 22 | |
| 23 | |
| 24 | fn encode(path: &Path, rate: u32, channels: u32, seconds: f64) -> usize { |
| 25 | let status = Command::new("ffmpeg") |
| 26 | .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) |
| 27 | .arg(format!( |
| 28 | "sine=frequency=440:sample_rate={rate}:duration={seconds}" |
| 29 | )) |
| 30 | .args([ |
| 31 | "-ac", |
| 32 | &channels.to_string(), |
| 33 | "-c:a", |
| 34 | "libvorbis", |
| 35 | "-q:a", |
| 36 | "4", |
| 37 | ]) |
| 38 | .arg(path) |
| 39 | .status() |
| 40 | .expect("ffmpeg"); |
| 41 | assert!( |
| 42 | status.success(), |
| 43 | "ffmpeg could not encode {}", |
| 44 | path.display() |
| 45 | ); |
| 46 | (f64::from(rate) * seconds).round() as usize |
| 47 | } |
| 48 | |
| 49 | |
| 50 | fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> { |
| 51 | let out = Command::new("ffmpeg") |
| 52 | .args(["-nostdin", "-v", "error", "-i"]) |
| 53 | .arg(path) |
| 54 | .args(["-map", "0:a:0", "-f", "f32le", "-"]) |
| 55 | .output() |
| 56 | .expect("ffmpeg"); |
| 57 | assert!(out.status.success(), "ffmpeg refused {}", path.display()); |
| 58 | deinterleave(&out.stdout, channels) |
| 59 | } |
| 60 | |
| 61 | fn deinterleave(bytes: &[u8], channels: usize) -> Vec<Vec<f32>> { |
| 62 | let mut planes = vec![Vec::new(); channels]; |
| 63 | for (i, chunk) in bytes.as_chunks::<4>().0.iter().enumerate() { |
| 64 | planes[i % channels].push(f32::from_le_bytes(*chunk)); |
| 65 | } |
| 66 | planes |
| 67 | } |
| 68 | |
| 69 | |
| 70 | |
| 71 | struct Stream { |
| 72 | extradata: Buf, |
| 73 | channels: usize, |
| 74 | packets: Vec<(Vec<u8>, Option<i64>)>, |
| 75 | } |
| 76 | |
| 77 | fn open(path: &Path) -> Stream { |
| 78 | let mut demuxer = OggDemuxer::open(File::open(path).expect("open")).expect("ogg"); |
| 79 | let stream = demuxer |
| 80 | .streams() |
| 81 | .iter() |
| 82 | .find(|s| s.params.codec == ec_core::CodecId::Vorbis) |
| 83 | .expect("a Vorbis stream") |
| 84 | .clone(); |
| 85 | let extradata = stream.params.extradata.clone().expect("headers"); |
| 86 | let channels = stream.params.audio().expect("audio").layout.channel_count(); |
| 87 | let mut packets = Vec::new(); |
| 88 | loop { |
| 89 | let packet = match demuxer.next_packet() { |
| 90 | Ok(packet) => packet, |
| 91 | Err(e) if e.is_eof() => break, |
| 92 | Err(e) => panic!("demux {}: {e}", path.display()), |
| 93 | }; |
| 94 | if packet.stream == stream.index { |
| 95 | packets.push((packet.data.to_vec(), granule_of(&packet))); |
| 96 | } |
| 97 | } |
| 98 | Stream { |
| 99 | extradata, |
| 100 | channels, |
| 101 | packets, |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | |
| 106 | |
| 107 | fn decode_through_trait(stream: &Stream, packets: &[(Vec<u8>, Option<i64>)]) -> Vec<Vec<f32>> { |
| 108 | let mut decoder = VorbisDecoder::from_extradata(&stream.extradata).expect("headers"); |
| 109 | let mut planes = vec![Vec::new(); stream.channels]; |
| 110 | let take = |decoder: &mut VorbisDecoder, planes: &mut Vec<Vec<f32>>| loop { |
| 111 | match decoder.receive_frame() { |
| 112 | Ok(Frame::Audio(frame)) => { |
| 113 | for (channel, plane) in planes.iter_mut().enumerate() { |
| 114 | let bytes = &frame.data[channel]; |
| 115 | plane.extend( |
| 116 | bytes |
| 117 | .as_chunks::<4>() |
| 118 | .0 |
| 119 | .iter() |
| 120 | .take(frame.samples) |
| 121 | .map(|c| f32::from_le_bytes(*c)), |
| 122 | ); |
| 123 | } |
| 124 | } |
| 125 | Ok(Frame::Video(_)) => unreachable!("Vorbis decodes to audio only"), |
| 126 | Err(e) if e.is_need_more() || e.is_eof() => break, |
| 127 | Err(e) => panic!("receive_frame: {e}"), |
| 128 | } |
| 129 | }; |
| 130 | let base = TimeBase::new(1, 1); |
| 131 | for (data, granule) in packets { |
| 132 | let mut packet = Packet::new(0, base, data.clone()); |
| 133 | if let Some(granule) = granule { |
| 134 | packet.side_data.push(granule_side_data(*granule)); |
| 135 | } |
| 136 | decoder.send_packet(&packet).expect("send_packet"); |
| 137 | take(&mut decoder, &mut planes); |
| 138 | } |
| 139 | decoder.flush().expect("flush"); |
| 140 | take(&mut decoder, &mut planes); |
| 141 | planes |
| 142 | } |
| 143 | |
| 144 | |
| 145 | fn correlation(a: &[f32], b: &[f32]) -> f64 { |
| 146 | let (mut dot, mut na, mut nb) = (0.0f64, 0.0f64, 0.0f64); |
| 147 | for (&x, &y) in a.iter().zip(b) { |
| 148 | let (x, y) = (f64::from(x), f64::from(y)); |
| 149 | dot += x * y; |
| 150 | na += x * x; |
| 151 | nb += y * y; |
| 152 | } |
| 153 | if na == 0.0 || nb == 0.0 { |
| 154 | return if na == nb { 1.0 } else { 0.0 }; |
| 155 | } |
| 156 | dot / (na.sqrt() * nb.sqrt()) |
| 157 | } |
| 158 | |
| 159 | fn encoded(name: &str, rate: u32, channels: u32, seconds: f64) -> (PathBuf, usize) { |
| 160 | let path = scratch().join(name); |
| 161 | let len = encode(&path, rate, channels, seconds); |
| 162 | (path, len) |
| 163 | } |
| 164 | |
| 165 | |
| 166 | |
| 167 | #[test] |
| 168 | fn whole_file_length_and_samples_match_ffmpeg() { |
| 169 | let mut failures = Vec::new(); |
| 170 | for (rate, channels, seconds) in [ |
| 171 | (44_100u32, 1u32, 1.234f64), |
| 172 | (44_100, 2, 2.5), |
| 173 | (48_000, 1, 2.5), |
| 174 | (48_000, 2, 3.0), |
| 175 | (48_000, 1, 1.234), |
| 176 | (44_100, 2, 1.234), |
| 177 | ] { |
| 178 | let name = format!("multi-{rate}-{channels}ch-{seconds}s.ogg"); |
| 179 | let (path, _) = encoded(&name, rate, channels, seconds); |
| 180 | let stream = open(&path); |
| 181 | let theirs = ffmpeg_decode(&path, channels as usize); |
| 182 | let ours = decode_through_trait(&stream, &stream.packets); |
| 183 | if ours[0].len() != theirs[0].len() { |
| 184 | failures.push(format!( |
| 185 | "{name}: {} frames, ffmpeg {}", |
| 186 | ours[0].len(), |
| 187 | theirs[0].len() |
| 188 | )); |
| 189 | continue; |
| 190 | } |
| 191 | for (channel, (mine, reference)) in ours.iter().zip(theirs.iter()).enumerate() { |
| 192 | let corr = correlation(mine, reference); |
| 193 | if corr < 0.999 { |
| 194 | failures.push(format!("{name}: ch{channel} correlation {corr:.6}")); |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | assert!(failures.is_empty(), "{}", failures.join("\n")); |
| 199 | } |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | #[test] |
| 209 | fn single_page_file_ends_at_its_granule() { |
| 210 | let mut failures = Vec::new(); |
| 211 | for (rate, channels) in [(44_100u32, 1usize), (48_000, 2)] { |
| 212 | let name = format!("single-{rate}-{channels}ch.ogg"); |
| 213 | let (path, want) = encoded(&name, rate, channels as u32, 1.0); |
| 214 | let stream = open(&path); |
| 215 | let theirs = ffmpeg_decode(&path, channels); |
| 216 | let ours = decode_through_trait(&stream, &stream.packets); |
| 217 | if ours[0].len() != want { |
| 218 | failures.push(format!( |
| 219 | "{name}: {} frames, granule states {want}", |
| 220 | ours[0].len() |
| 221 | )); |
| 222 | } |
| 223 | for (channel, (mine, reference)) in ours.iter().zip(theirs.iter()).enumerate() { |
| 224 | let corr = correlation(&mine[..reference.len().min(mine.len())], reference); |
| 225 | if corr < 0.999 { |
| 226 | failures.push(format!("{name}: ch{channel} correlation {corr:.6}")); |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | assert!(failures.is_empty(), "{}", failures.join("\n")); |
| 231 | } |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | #[test] |
| 238 | fn granule_behind_the_first_output_trims_the_head() { |
| 239 | const K: i64 = 300; |
| 240 | let (path, want) = encoded("head-44100-2ch.ogg", 44_100, 2, 2.5); |
| 241 | let stream = open(&path); |
| 242 | let mut raw = VorbisDecoder::from_extradata(&stream.extradata).expect("headers"); |
| 243 | let mut untrimmed = vec![Vec::new(); stream.channels]; |
| 244 | let mut counts = Vec::new(); |
| 245 | for (data, _) in &stream.packets { |
| 246 | let samples = raw.decode_audio(data).expect("decode"); |
| 247 | counts.push(samples[0].len() as i64); |
| 248 | for (channel, plane) in samples.iter().enumerate() { |
| 249 | untrimmed[channel].extend_from_slice(plane); |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | let first_output = counts.iter().position(|&c| c > 0).expect("some output"); |
| 254 | let decoded_through: i64 = counts[..=first_output].iter().sum(); |
| 255 | assert!( |
| 256 | decoded_through > K, |
| 257 | "first output packet too short to trim {K} from" |
| 258 | ); |
| 259 | |
| 260 | let mut packets = stream.packets.clone(); |
| 261 | packets[first_output].1 = Some(decoded_through - K); |
| 262 | let ours = decode_through_trait(&stream, &packets); |
| 263 | |
| 264 | assert_eq!(ours[0].len(), want, "head trim changed the length"); |
| 265 | for (channel, plane) in ours.iter().enumerate() { |
| 266 | let expect = &untrimmed[channel][K as usize..K as usize + want]; |
| 267 | assert!( |
| 268 | plane == expect, |
| 269 | "ch{channel}: output is not the untrimmed decode from sample {K}" |
| 270 | ); |
| 271 | } |
| 272 | } |