Multi-source model + segmented multi-file audio
Browse files at this commit5593a9ffa9395d1e9526d6a6dde5cead18028c3cParent: e994c12- feat
- multi-source model + segmented multi-file audio
5 changed files +787 -155
- crates/engine/src/audio.rs +292 -132
- crates/engine/src/export.rs +8 -1
- crates/engine/src/playback.rs +15 -4
- crates/engine/src/project.rs +209 -18
- crates/engine/tests/audio_multi.rs +263 -0
crates/engine/src/audio.rsmodified+292 -132
| @@ -4,7 +4,7 @@ | |||
| 4 | 4 | ||
| 5 | use std::fs::File; | 5 | use std::fs::File; |
| 6 | use std::io::BufReader; | 6 | use std::io::BufReader; |
| 7 | -use std::path::Path; | 7 | +use std::path::{Path, PathBuf}; |
| 8 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; | 8 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; |
| 9 | use std::thread; | 9 | use std::thread; |
| 10 | 10 | ||
| @@ -65,6 +65,14 @@ pub struct AacPacket { | |||
| 65 | pub samples: u32, | 65 | pub samples: u32, |
| 66 | } | 66 | } |
| 67 | 67 | ||
| 68 | +/// Everything an import check needs from a candidate file's audio track. Two | ||
| 69 | +/// files may share a timeline only when their probes are equal (or both `None`). | ||
| 70 | +#[derive(Debug, Clone, Copy, PartialEq)] | ||
| 71 | +pub struct AudioProbe { | ||
| 72 | + pub params: AacTrackParams, | ||
| 73 | + pub channels: u16, | ||
| 74 | +} | ||
| 75 | + | ||
| 68 | pub struct AudioSession; | 76 | pub struct AudioSession; |
| 69 | 77 | ||
| 70 | impl AudioSession { | 78 | impl AudioSession { |
| @@ -101,80 +109,82 @@ impl AudioSession { | |||
| 101 | path: impl AsRef<Path>, | 109 | path: impl AsRef<Path>, |
| 102 | segs: &[(f64, f64)], | 110 | segs: &[(f64, f64)], |
| 103 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 111 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 104 | - let file = File::open(path.as_ref())?; | 112 | + let segs: Vec<_> = segs.iter().map(|&(s, e)| (0, s, e)).collect(); |
| 105 | - let size = file.metadata()?.len(); | 113 | + Self::open_multi_segments(&[path.as_ref().to_path_buf()], &segs) |
| 106 | - let reader = Mp4Reader::read_header(BufReader::new(file), size)?; | 114 | + } |
| 107 | 115 | ||
| 108 | - let Some(track) = reader | 116 | + /// [`open_segments`](Self::open_segments) over several files: a segment names |
| 109 | - .tracks() | 117 | + /// its source by index into `sources`, and a source join behaves exactly like |
| 110 | - .values() | 118 | + /// a cut inside one file — `start_sample` stays continuous, the decoder is |
| 111 | - .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) | 119 | + /// fresh either way. Each source contributes *its own* priming, packet table |
| 112 | - else { | 120 | + /// and length, which is the whole reason the resolution is per source. |
| 121 | + /// | ||
| 122 | + /// Only the sources some segment names are opened. `Ok(None)` when `sources` | ||
| 123 | + /// is empty or its first entry has no AAC track; a later source that is | ||
| 124 | + /// missing audio or disagrees on rate/layout is an `Err` — import refuses | ||
| 125 | + /// those up front (one timeline, one output device), this is the backstop. | ||
| 126 | + pub fn open_multi_segments( | ||
| 127 | + sources: &[PathBuf], | ||
| 128 | + segs: &[(usize, f64, f64)], | ||
| 129 | + ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | ||
| 130 | + let Some(first) = sources.first() else { | ||
| 113 | return Ok(None); | 131 | return Ok(None); |
| 114 | }; | 132 | }; |
| 115 | - | 133 | + let Some(first) = Track::open(first)? else { |
| 116 | - // AacDecoder only does plain LC, mono/stereo; refuse early with a | 134 | + return Ok(None); |
| 117 | - // message instead of letting it fail packet by packet. | 135 | + }; |
| 118 | - match track.audio_profile()? { | 136 | + // The timeline's meta is the first source's: policy makes every other |
| 119 | - AudioObjectType::AacLowComplexity => {} | 137 | + // source match it, and the checks below hold them to that. |
| 120 | - other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()), | 138 | + let meta = AudioMeta { |
| 121 | - } | 139 | + sample_rate: first.sample_rate, |
| 122 | - let channels: u16 = match track.channel_config()? { | 140 | + channels: first.channels()?, |
| 123 | - ChannelConfig::Mono => 1, | 141 | + total_samples: first.total_samples, |
| 124 | - ChannelConfig::Stereo => 2, | ||
| 125 | - other => { | ||
| 126 | - return Err(format!("unsupported channel layout: {other:?} (max stereo)").into()); | ||
| 127 | - } | ||
| 128 | }; | 142 | }; |
| 129 | - | ||
| 130 | - let track_id = track.track_id(); | ||
| 131 | - let sample_rate = track.sample_freq_index()?.freq(); | ||
| 132 | - let priming = priming_samples(track, sample_rate); | ||
| 133 | - let total_samples = scale( | ||
| 134 | - track.trak.mdia.mdhd.duration, | ||
| 135 | - sample_rate, | ||
| 136 | - track.timescale(), | ||
| 137 | - ) | ||
| 138 | - .map(|d| d.saturating_sub(priming)); | ||
| 139 | - | ||
| 140 | - let mut params = AudioCodecParameters::new(); | ||
| 141 | - params | ||
| 142 | - .for_codec(CODEC_ID_AAC) | ||
| 143 | - .with_sample_rate(sample_rate) | ||
| 144 | - .with_extra_data(audio_specific_config(track)?); | ||
| 145 | // Built here only so an undecodable stream is an `Err` from the opener | 143 | // Built here only so an undecodable stream is an `Err` from the opener |
| 146 | // rather than a silently empty channel; the worker makes its own. | 144 | // rather than a silently empty channel; the worker makes its own. |
| 147 | - AacDecoder::try_new(¶ms, &AudioDecoderOptions::default())?; | 145 | + AacDecoder::try_new(&first.params, &AudioDecoderOptions::default())?; |
| 146 | + | ||
| 147 | + let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); | ||
| 148 | + tracks[0] = Some(first); | ||
| 149 | + for &(source, ..) in segs { | ||
| 150 | + let slot = tracks | ||
| 151 | + .get_mut(source) | ||
| 152 | + .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; | ||
| 153 | + if slot.is_some() { | ||
| 154 | + continue; // already opened, and the checks below already ran | ||
| 155 | + } | ||
| 156 | + let track = Track::open(&sources[source])? | ||
| 157 | + .ok_or_else(|| format!("source {source} has no audio track"))?; | ||
| 158 | + if (track.sample_rate, track.channels()?) != (meta.sample_rate, meta.channels) { | ||
| 159 | + return Err(format!( | ||
| 160 | + "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch", | ||
| 161 | + track.sample_rate, | ||
| 162 | + track.channels()?, | ||
| 163 | + meta.sample_rate, | ||
| 164 | + meta.channels | ||
| 165 | + ) | ||
| 166 | + .into()); | ||
| 167 | + } | ||
| 168 | + AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())?; | ||
| 169 | + *slot = Some(track); | ||
| 170 | + } | ||
| 148 | 171 | ||
| 149 | - // Segment bounds in media samples (priming included, so they compare | ||
| 150 | - // directly against the decoded position). `f64::INFINITY` saturates. | ||
| 151 | - let media = |secs: f64| ((secs * f64::from(sample_rate)) as u64).saturating_add(priming); | ||
| 152 | let segments: Vec<Segment> = segs | 172 | let segments: Vec<Segment> = segs |
| 153 | .iter() | 173 | .iter() |
| 154 | - .map(|&(start_secs, end_secs)| { | 174 | + .map(|&(source, start_secs, end_secs)| { |
| 155 | - let media_target = media(start_secs); | 175 | + tracks[source] |
| 156 | - let target_ts = unscale(media_target, sample_rate, track.timescale()); | 176 | + .as_ref() |
| 157 | - // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the | 177 | + .expect("opened above") |
| 158 | - // previous packet to cancel aliasing, plus one more to warm the | 178 | + .segment(source, start_secs, end_secs) |
| 159 | - // decoder up. Their output is discarded below, so this only | ||
| 160 | - // costs decode time. | ||
| 161 | - let (start_id, start_ts) = packet_at(stts_pairs(track), target_ts, PRE_ROLL); | ||
| 162 | - Segment { | ||
| 163 | - start_id, | ||
| 164 | - start_pos: scale(start_ts, sample_rate, track.timescale()).unwrap_or(0), | ||
| 165 | - media_target, | ||
| 166 | - // An inverted segment is an empty one, never a backwards run. | ||
| 167 | - media_end: media(end_secs).max(media_target), | ||
| 168 | - } | ||
| 169 | }) | 179 | }) |
| 170 | .collect(); | 180 | .collect(); |
| 181 | + // Chunk numbering is continuous across every join, counted from the first | ||
| 182 | + // segment's audible start in its own source (see `open_segments`). | ||
| 183 | + let timeline = segments.first().map_or(0, |s| { | ||
| 184 | + s.media_target | ||
| 185 | + .saturating_sub(tracks[s.source].as_ref().expect("opened above").priming) | ||
| 186 | + }); | ||
| 171 | 187 | ||
| 172 | - let sample_count = reader.sample_count(track_id)?; | ||
| 173 | - let meta = AudioMeta { | ||
| 174 | - sample_rate, | ||
| 175 | - channels, | ||
| 176 | - total_samples, | ||
| 177 | - }; | ||
| 178 | // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so | 188 | // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so |
| 179 | // this bound is ~0.75 s of lookahead — enough to ride out decode jitter | 189 | // this bound is ~0.75 s of lookahead — enough to ride out decode jitter |
| 180 | // without making a pause take a second to bite. | 190 | // without making a pause take a second to bite. |
| @@ -183,19 +193,30 @@ impl AudioSession { | |||
| 183 | .name("audio-decode".into()) | 193 | .name("audio-decode".into()) |
| 184 | .spawn(move || { | 194 | .spawn(move || { |
| 185 | run(Worker { | 195 | run(Worker { |
| 186 | - reader, | 196 | + tracks, |
| 187 | - params, | 197 | + channels: meta.channels as usize, |
| 188 | - track_id, | ||
| 189 | - sample_count, | ||
| 190 | - channels: channels as usize, | ||
| 191 | - priming, | ||
| 192 | segments, | 198 | segments, |
| 199 | + timeline, | ||
| 193 | tx, | 200 | tx, |
| 194 | }) | 201 | }) |
| 195 | })?; | 202 | })?; |
| 196 | Ok(Some((meta, rx))) | 203 | Ok(Some((meta, rx))) |
| 197 | } | 204 | } |
| 198 | 205 | ||
| 206 | + /// The audio parameters of `path`, for checking an import against the | ||
| 207 | + /// timeline's first source: header only, no decoder and no worker. | ||
| 208 | + /// `Ok(None)` means no AAC track — an audio-less file, which import pairs | ||
| 209 | + /// only with other audio-less files. | ||
| 210 | + pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> { | ||
| 211 | + let Some(track) = Track::open(path.as_ref())? else { | ||
| 212 | + return Ok(None); | ||
| 213 | + }; | ||
| 214 | + Ok(Some(AudioProbe { | ||
| 215 | + params: track.track_params(), | ||
| 216 | + channels: track.channels()?, | ||
| 217 | + })) | ||
| 218 | + } | ||
| 219 | + | ||
| 199 | /// The raw AAC packets covering `segs` — the same half-open source-second | 220 | /// The raw AAC packets covering `segs` — the same half-open source-second |
| 200 | /// windows [`open_segments`](Self::open_segments) decodes — copied out | 221 | /// windows [`open_segments`](Self::open_segments) decodes — copied out |
| 201 | /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go | 222 | /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go |
| @@ -221,12 +242,119 @@ impl AudioSession { | |||
| 221 | path: impl AsRef<Path>, | 242 | path: impl AsRef<Path>, |
| 222 | segs: &[(f64, f64)], | 243 | segs: &[(f64, f64)], |
| 223 | ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { | 244 | ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { |
| 224 | - if segs.is_empty() { | 245 | + let segs: Vec<_> = segs.iter().map(|&(s, e)| (0, s, e)).collect(); |
| 246 | + Self::copy_multi_segments(&[path.as_ref().to_path_buf()], &segs) | ||
| 247 | + } | ||
| 248 | + | ||
| 249 | + /// [`copy_segments`](Self::copy_segments) over several files, segments naming | ||
| 250 | + /// their source by index into `sources`. The rounding debt is carried across | ||
| 251 | + /// a source join exactly as across a cut inside one file, so the bound stays | ||
| 252 | + /// half a packet over the whole list however many files it spans, and the | ||
| 253 | + /// extra priming packet is still the very first segment's alone. | ||
| 254 | + /// | ||
| 255 | + /// Every source must declare the same [`AacTrackParams`]: the copy becomes | ||
| 256 | + /// one output track with one esds. Import refuses a mismatch up front; the | ||
| 257 | + /// check here is the backstop, as is the missing-track `Err`. | ||
| 258 | + pub fn copy_multi_segments( | ||
| 259 | + sources: &[PathBuf], | ||
| 260 | + segs: &[(usize, f64, f64)], | ||
| 261 | + ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> { | ||
| 262 | + let Some(&(first, ..)) = segs.first() else { | ||
| 225 | return Ok(None); | 263 | return Ok(None); |
| 264 | + }; | ||
| 265 | + let path = sources | ||
| 266 | + .get(first) | ||
| 267 | + .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; | ||
| 268 | + let Some(track) = Track::open(path)? else { | ||
| 269 | + return Ok(None); // silent source, silent export | ||
| 270 | + }; | ||
| 271 | + let params = track.track_params(); | ||
| 272 | + let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); | ||
| 273 | + tracks[first] = Some(track); | ||
| 274 | + | ||
| 275 | + let mut err = 0i64; | ||
| 276 | + let mut packets = Vec::new(); | ||
| 277 | + for (i, &(source, start_secs, end_secs)) in segs.iter().enumerate() { | ||
| 278 | + let track = source_at(&mut tracks, sources, source)?; | ||
| 279 | + if track.track_params() != params { | ||
| 280 | + return Err(format!( | ||
| 281 | + "source {source} audio is {:?}, the timeline's is {params:?}", | ||
| 282 | + track.track_params() | ||
| 283 | + ) | ||
| 284 | + .into()); | ||
| 285 | + } | ||
| 286 | + let target_ts = unscale(track.media(start_secs), track.sample_rate, track.timescale); | ||
| 287 | + let (start_id, _) = packet_at(track.stts.iter().copied(), target_ts, 0); | ||
| 288 | + let ideal = ((end_secs - start_secs).max(0.0) * f64::from(track.sample_rate)) as i64; | ||
| 289 | + let available = track.sample_count.saturating_sub(start_id - 1); | ||
| 290 | + // The head packet is the priming of the first segment only: a reader | ||
| 291 | + // drops exactly one, so an interior join must not add another. | ||
| 292 | + let head = (i == 0 && start_id > 1).then(|| start_id - 1); | ||
| 293 | + let ids = head | ||
| 294 | + .into_iter() | ||
| 295 | + .chain(start_id..start_id + packet_run(&mut err, ideal, available)); | ||
| 296 | + for id in ids { | ||
| 297 | + let Some(sample) = track.reader.read_sample(track.track_id, id)? else { | ||
| 298 | + let count = track.sample_count; | ||
| 299 | + return Err(format!("audio sample {id} of {count} is missing").into()); | ||
| 300 | + }; | ||
| 301 | + packets.push(AacPacket { | ||
| 302 | + bytes: sample.bytes.to_vec(), | ||
| 303 | + samples: SAMPLES_PER_PACKET, | ||
| 304 | + }); | ||
| 305 | + } | ||
| 226 | } | 306 | } |
| 227 | - let file = File::open(path.as_ref())?; | 307 | + Ok(Some((params, packets))) |
| 308 | + } | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +/// The source at `index`, opened on first use. Sources a segment list never | ||
| 312 | +/// names are never touched: a project's list only grows. | ||
| 313 | +fn source_at<'a>( | ||
| 314 | + tracks: &'a mut [Option<Track>], | ||
| 315 | + sources: &[PathBuf], | ||
| 316 | + index: usize, | ||
| 317 | +) -> crate::Result<&'a mut Track> { | ||
| 318 | + let slot = tracks | ||
| 319 | + .get_mut(index) | ||
| 320 | + .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; | ||
| 321 | + if slot.is_none() { | ||
| 322 | + *slot = Some( | ||
| 323 | + Track::open(&sources[index])? | ||
| 324 | + .ok_or_else(|| format!("source {index} has no audio track"))?, | ||
| 325 | + ); | ||
| 326 | + } | ||
| 327 | + Ok(slot.as_mut().expect("just opened")) | ||
| 328 | +} | ||
| 329 | + | ||
| 330 | +/// One source's AAC track, resolved once: the reader plus everything the header | ||
| 331 | +/// has to say about it. `stts` is copied out because every other field would | ||
| 332 | +/// otherwise keep a borrow alive on the reader the worker needs mutably — a real | ||
| 333 | +/// AAC track has one entry, so it is two `u32`s. | ||
| 334 | +struct Track { | ||
| 335 | + reader: Mp4Reader<BufReader<File>>, | ||
| 336 | + track_id: u32, | ||
| 337 | + sample_count: u32, | ||
| 338 | + sample_rate: u32, | ||
| 339 | + timescale: u32, | ||
| 340 | + /// Encoder delay of *this* file. Sources are joined, priming is not shared. | ||
| 341 | + priming: u64, | ||
| 342 | + total_samples: Option<u64>, | ||
| 343 | + stts: Vec<(u32, u32)>, | ||
| 344 | + config: ChannelConfig, | ||
| 345 | + freq_index: u8, | ||
| 346 | + chan_conf: u8, | ||
| 347 | + /// A fresh decoder is built from these per segment: seeking mid-stream | ||
| 348 | + /// leaves MDCT and PNS state that belongs to the packets we skipped. | ||
| 349 | + params: AudioCodecParameters, | ||
| 350 | +} | ||
| 351 | + | ||
| 352 | +impl Track { | ||
| 353 | + /// `Ok(None)` for a file with no AAC track, which is a valid silent source. | ||
| 354 | + fn open(path: &Path) -> crate::Result<Option<Self>> { | ||
| 355 | + let file = File::open(path)?; | ||
| 228 | let size = file.metadata()?.len(); | 356 | let size = file.metadata()?.len(); |
| 229 | - let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?; | 357 | + let reader = Mp4Reader::read_header(BufReader::new(file), size)?; |
| 230 | 358 | ||
| 231 | let Some(track) = reader | 359 | let Some(track) = reader |
| 232 | .tracks() | 360 | .tracks() |
| @@ -235,9 +363,10 @@ impl AudioSession { | |||
| 235 | else { | 363 | else { |
| 236 | return Ok(None); | 364 | return Ok(None); |
| 237 | }; | 365 | }; |
| 238 | - // The copy carries no profile of its own: the writer rebuilds the | 366 | + // Refuse early with a message instead of failing packet by packet — and |
| 367 | + // a copy carries no profile of its own: the writer rebuilds the | ||
| 239 | // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a | 368 | // AudioSpecificConfig from `freq_index`/`chan_conf` and calls it LC, so a |
| 240 | - // non-LC source would be mislabelled rather than merely unplayable here. | 369 | + // non-LC source would be mislabelled rather than merely unplayable. |
| 241 | match track.audio_profile()? { | 370 | match track.audio_profile()? { |
| 242 | AudioObjectType::AacLowComplexity => {} | 371 | AudioObjectType::AacLowComplexity => {} |
| 243 | other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()), | 372 | other => return Err(format!("unsupported AAC profile: {other:?} (only AAC-LC)").into()), |
| @@ -248,43 +377,71 @@ impl AudioSession { | |||
| 248 | let timescale = track.timescale(); | 377 | let timescale = track.timescale(); |
| 249 | let priming = priming_samples(track, sample_rate); | 378 | let priming = priming_samples(track, sample_rate); |
| 250 | let (_, freq_index, chan_conf) = asc_fields(track)?; | 379 | let (_, freq_index, chan_conf) = asc_fields(track)?; |
| 251 | - let sample_count = reader.sample_count(track_id)?; | 380 | + let mut params = AudioCodecParameters::new(); |
| 381 | + params | ||
| 382 | + .for_codec(CODEC_ID_AAC) | ||
| 383 | + .with_sample_rate(sample_rate) | ||
| 384 | + .with_extra_data(audio_specific_config(track)?); | ||
| 385 | + let this = Self { | ||
| 386 | + track_id, | ||
| 387 | + sample_count: reader.sample_count(track_id)?, | ||
| 388 | + sample_rate, | ||
| 389 | + timescale, | ||
| 390 | + priming, | ||
| 391 | + total_samples: scale(track.trak.mdia.mdhd.duration, sample_rate, timescale) | ||
| 392 | + .map(|d| d.saturating_sub(priming)), | ||
| 393 | + stts: stts_pairs(track).collect(), | ||
| 394 | + config: track.channel_config()?, | ||
| 395 | + freq_index, | ||
| 396 | + chan_conf, | ||
| 397 | + params, | ||
| 398 | + reader, | ||
| 399 | + }; | ||
| 400 | + Ok(Some(this)) | ||
| 401 | + } | ||
| 252 | 402 | ||
| 253 | - // Resolve every packet id first: `read_sample` needs the reader mutably, | 403 | + /// Channel count. `AacDecoder` only does mono and stereo, so anything else |
| 254 | - // which ends the borrow `track` holds. | 404 | + /// is refused here rather than one packet at a time. |
| 255 | - let media = |secs: f64| ((secs * f64::from(sample_rate)) as u64).saturating_add(priming); | 405 | + fn channels(&self) -> crate::Result<u16> { |
| 256 | - let mut err = 0i64; | 406 | + match self.config { |
| 257 | - let mut ids: Vec<u32> = Vec::new(); | 407 | + ChannelConfig::Mono => Ok(1), |
| 258 | - for (i, &(start_secs, end_secs)) in segs.iter().enumerate() { | 408 | + ChannelConfig::Stereo => Ok(2), |
| 259 | - let target_ts = unscale(media(start_secs), sample_rate, timescale); | 409 | + other => Err(format!("unsupported channel layout: {other:?} (max stereo)").into()), |
| 260 | - let (start_id, _) = packet_at(stts_pairs(track), target_ts, 0); | ||
| 261 | - let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64; | ||
| 262 | - let available = sample_count.saturating_sub(start_id - 1); | ||
| 263 | - if i == 0 && start_id > 1 { | ||
| 264 | - ids.push(start_id - 1); // priming, see the doc comment | ||
| 265 | - } | ||
| 266 | - ids.extend(start_id..start_id + packet_run(&mut err, ideal, available)); | ||
| 267 | } | 410 | } |
| 411 | + } | ||
| 268 | 412 | ||
| 269 | - let packets = ids | 413 | + fn track_params(&self) -> AacTrackParams { |
| 270 | - .into_iter() | 414 | + AacTrackParams { |
| 271 | - .map(|id| match reader.read_sample(track_id, id)? { | 415 | + freq_index: self.freq_index, |
| 272 | - Some(sample) => Ok(AacPacket { | 416 | + chan_conf: self.chan_conf, |
| 273 | - bytes: sample.bytes.to_vec(), | 417 | + sample_rate: self.sample_rate, |
| 274 | - samples: SAMPLES_PER_PACKET, | 418 | + } |
| 275 | - }), | 419 | + } |
| 276 | - None => Err(format!("audio sample {id} of {sample_count} is missing").into()), | 420 | + |
| 277 | - }) | 421 | + /// `secs` on this source's audible timeline into media samples (priming |
| 278 | - .collect::<crate::Result<Vec<_>>>()?; | 422 | + /// included, so it compares directly against a decoded position). |
| 279 | - | 423 | + /// `f64::INFINITY` saturates. |
| 280 | - Ok(Some(( | 424 | + fn media(&self, secs: f64) -> u64 { |
| 281 | - AacTrackParams { | 425 | + ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming) |
| 282 | - freq_index, | 426 | + } |
| 283 | - chan_conf, | 427 | + |
| 284 | - sample_rate, | 428 | + /// One `[start, end)` window of this source's seconds, resolved to its own |
| 285 | - }, | 429 | + /// packets and media samples. |
| 286 | - packets, | 430 | + fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { |
| 287 | - ))) | 431 | + let media_target = self.media(start_secs); |
| 432 | + let target_ts = unscale(media_target, self.sample_rate, self.timescale); | ||
| 433 | + // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous | ||
| 434 | + // packet to cancel aliasing, plus one more to warm the decoder up. Their | ||
| 435 | + // output is discarded below, so this only costs decode time. | ||
| 436 | + let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, PRE_ROLL); | ||
| 437 | + Segment { | ||
| 438 | + source, | ||
| 439 | + start_id, | ||
| 440 | + start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0), | ||
| 441 | + media_target, | ||
| 442 | + // An inverted segment is an empty one, never a backwards run. | ||
| 443 | + media_end: self.media(end_secs).max(media_target), | ||
| 444 | + } | ||
| 288 | } | 445 | } |
| 289 | } | 446 | } |
| 290 | 447 | ||
| @@ -429,8 +586,11 @@ fn packet_at( | |||
| 429 | last | 586 | last |
| 430 | } | 587 | } |
| 431 | 588 | ||
| 432 | -/// One window of the source to decode, resolved to media samples and packets. | 589 | +/// One window of a source to decode, resolved to media samples and packets. |
| 433 | struct Segment { | 590 | struct Segment { |
| 591 | + /// Index into the worker's tracks; the media positions below are that | ||
| 592 | + /// source's, not the timeline's. | ||
| 593 | + source: usize, | ||
| 434 | /// First packet to feed the decoder, 1-based; includes the pre-roll. | 594 | /// First packet to feed the decoder, 1-based; includes the pre-roll. |
| 435 | start_id: u32, | 595 | start_id: u32, |
| 436 | /// Media position of `start_id`'s first frame, in samples-per-channel. | 596 | /// Media position of `start_id`'s first frame, in samples-per-channel. |
| @@ -443,29 +603,29 @@ struct Segment { | |||
| 443 | } | 603 | } |
| 444 | 604 | ||
| 445 | struct Worker { | 605 | struct Worker { |
| 446 | - reader: Mp4Reader<BufReader<File>>, | 606 | + /// Indexed by [`Segment::source`]; only the sources some segment names are |
| 447 | - /// A fresh decoder is built from these per segment: seeking mid-stream | 607 | + /// `Some`, the rest were never opened. |
| 448 | - /// leaves MDCT and PNS state that belongs to the packets we skipped. | 608 | + tracks: Vec<Option<Track>>, |
| 449 | - params: AudioCodecParameters, | ||
| 450 | - track_id: u32, | ||
| 451 | - sample_count: u32, | ||
| 452 | channels: usize, | 609 | channels: usize, |
| 453 | - priming: u64, | ||
| 454 | segments: Vec<Segment>, | 610 | segments: Vec<Segment>, |
| 611 | + /// `start_sample` of the first chunk. | ||
| 612 | + timeline: u64, | ||
| 455 | tx: SyncSender<AudioChunk>, | 613 | tx: SyncSender<AudioChunk>, |
| 456 | } | 614 | } |
| 457 | 615 | ||
| 458 | fn run(mut w: Worker) { | 616 | fn run(mut w: Worker) { |
| 459 | let mut interleaved = Vec::new(); | 617 | let mut interleaved = Vec::new(); |
| 460 | - // Chunk numbering is continuous across the segment joins, counted from the | 618 | + let channels = w.channels; |
| 461 | - // first segment's audible start (see `open_segments`). | 619 | + // Chunk numbering is continuous across every join, source ones included. |
| 462 | - let mut timeline = w | 620 | + let mut timeline = w.timeline; |
| 463 | - .segments | 621 | + let segments = std::mem::take(&mut w.segments); |
| 464 | - .first() | 622 | + |
| 465 | - .map_or(0, |s| s.media_target.saturating_sub(w.priming)); | 623 | + for seg in &segments { |
| 466 | - | 624 | + let Some(track) = w.tracks[seg.source].as_mut() else { |
| 467 | - for seg in &w.segments { | 625 | + continue; // opener fills every named source; nothing to decode |
| 468 | - let mut decoder = match AacDecoder::try_new(&w.params, &AudioDecoderOptions::default()) { | 626 | + }; |
| 627 | + let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) | ||
| 628 | + { | ||
| 469 | Ok(decoder) => decoder, | 629 | Ok(decoder) => decoder, |
| 470 | Err(e) => { | 630 | Err(e) => { |
| 471 | eprintln!("audio decoder init failed: {e}"); | 631 | eprintln!("audio decoder init failed: {e}"); |
| @@ -474,11 +634,11 @@ fn run(mut w: Worker) { | |||
| 474 | }; | 634 | }; |
| 475 | let mut pos = seg.start_pos; | 635 | let mut pos = seg.start_pos; |
| 476 | 636 | ||
| 477 | - for id in seg.start_id..=w.sample_count { | 637 | + for id in seg.start_id..=track.sample_count { |
| 478 | if pos >= seg.media_end { | 638 | if pos >= seg.media_end { |
| 479 | break; // segment done, on to the next one | 639 | break; // segment done, on to the next one |
| 480 | } | 640 | } |
| 481 | - let sample = match w.reader.read_sample(w.track_id, id) { | 641 | + let sample = match track.reader.read_sample(track.track_id, id) { |
| 482 | Ok(Some(sample)) => sample, | 642 | Ok(Some(sample)) => sample, |
| 483 | Ok(None) => break, | 643 | Ok(None) => break, |
| 484 | Err(e) => { | 644 | Err(e) => { |
| @@ -487,7 +647,7 @@ fn run(mut w: Worker) { | |||
| 487 | } | 647 | } |
| 488 | }; | 648 | }; |
| 489 | let packet = Packet::new( | 649 | let packet = Packet::new( |
| 490 | - w.track_id, | 650 | + track.track_id, |
| 491 | units::Timestamp::new(sample.start_time as i64), | 651 | units::Timestamp::new(sample.start_time as i64), |
| 492 | units::Duration::new(u64::from(sample.duration)), | 652 | units::Duration::new(u64::from(sample.duration)), |
| 493 | &sample.bytes[..], | 653 | &sample.bytes[..], |
| @@ -500,7 +660,7 @@ fn run(mut w: Worker) { | |||
| 500 | } | 660 | } |
| 501 | }; | 661 | }; |
| 502 | buf.copy_to_vec_interleaved::<f32>(&mut interleaved); | 662 | buf.copy_to_vec_interleaved::<f32>(&mut interleaved); |
| 503 | - let next = pos + (interleaved.len() / w.channels) as u64; | 663 | + let next = pos + (interleaved.len() / channels) as u64; |
| 504 | 664 | ||
| 505 | // Everything before the target is encoder priming and/or decoder | 665 | // Everything before the target is encoder priming and/or decoder |
| 506 | // pre-roll, not audio the caller asked for: drop it, splitting the | 666 | // pre-roll, not audio the caller asked for: drop it, splitting the |
| @@ -510,13 +670,13 @@ fn run(mut w: Worker) { | |||
| 510 | continue; | 670 | continue; |
| 511 | } | 671 | } |
| 512 | if pos < seg.media_target { | 672 | if pos < seg.media_target { |
| 513 | - interleaved.drain(..(seg.media_target - pos) as usize * w.channels); | 673 | + interleaved.drain(..(seg.media_target - pos) as usize * channels); |
| 514 | pos = seg.media_target; | 674 | pos = seg.media_target; |
| 515 | } | 675 | } |
| 516 | // And the tail past the segment end goes too — on a short segment | 676 | // And the tail past the segment end goes too — on a short segment |
| 517 | // that is this same buffer, trimmed at both ends. | 677 | // that is this same buffer, trimmed at both ends. |
| 518 | if next > seg.media_end { | 678 | if next > seg.media_end { |
| 519 | - interleaved.truncate((seg.media_end - pos) as usize * w.channels); | 679 | + interleaved.truncate((seg.media_end - pos) as usize * channels); |
| 520 | } | 680 | } |
| 521 | pos = next; | 681 | pos = next; |
| 522 | if interleaved.is_empty() { | 682 | if interleaved.is_empty() { |
| @@ -526,7 +686,7 @@ fn run(mut w: Worker) { | |||
| 526 | start_sample: timeline, | 686 | start_sample: timeline, |
| 527 | samples: std::mem::take(&mut interleaved), | 687 | samples: std::mem::take(&mut interleaved), |
| 528 | }; | 688 | }; |
| 529 | - timeline += (chunk.samples.len() / w.channels) as u64; | 689 | + timeline += (chunk.samples.len() / channels) as u64; |
| 530 | if w.tx.send(chunk).is_err() { | 690 | if w.tx.send(chunk).is_err() { |
| 531 | return; // consumer went away | 691 | return; // consumer went away |
| 532 | } | 692 | } |
crates/engine/src/export.rsmodified+8 -1
| @@ -131,7 +131,14 @@ fn run( | |||
| 131 | // ponytail: this holds the whole exported AAC track in memory (~3 kB per | 131 | // ponytail: this holds the whole exported AAC track in memory (~3 kB per |
| 132 | // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming | 132 | // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming |
| 133 | // `copy_segments` that yields packets instead of collecting them. | 133 | // `copy_segments` that yields packets instead of collecting them. |
| 134 | - let audio = AudioSession::copy_segments(source, &project.segments_from(0, meta.frame_rate))?; | 134 | + // Source indexes dropped: every clip is still source 0 until multi-source |
| 135 | + // export lands, and `copy_segments` takes the one path above. | ||
| 136 | + let segs: Vec<(f64, f64)> = project | ||
| 137 | + .segments_from(0, meta.frame_rate) | ||
| 138 | + .into_iter() | ||
| 139 | + .map(|(_, start, end)| (start, end)) | ||
| 140 | + .collect(); | ||
| 141 | + let audio = AudioSession::copy_segments(source, &segs)?; | ||
| 135 | let audio_params = audio.as_ref().map(|(track, _)| AudioParams { | 142 | let audio_params = audio.as_ref().map(|(track, _)| AudioParams { |
| 136 | freq_index: track.freq_index, | 143 | freq_index: track.freq_index, |
| 137 | chan_conf: track.chan_conf, | 144 | chan_conf: track.chan_conf, |
crates/engine/src/playback.rsmodified+15 -4
| @@ -118,7 +118,7 @@ impl PlaybackSession { | |||
| 118 | }; | 118 | }; |
| 119 | // One clip covering the file, so timeline == source until the first | 119 | // One clip covering the file, so timeline == source until the first |
| 120 | // edit -- and `open_at(_, 0)` is exactly that clip's range. | 120 | // edit -- and `open_at(_, 0)` is exactly that clip's range. |
| 121 | - let project = Project::single(meta.frame_count); | 121 | + let project = Project::single(&path, meta.frame_count); |
| 122 | let range = project.clips()[0]; | 122 | let range = project.clips()[0]; |
| 123 | Ok(Self { | 123 | Ok(Self { |
| 124 | path, | 124 | path, |
| @@ -182,7 +182,8 @@ impl PlaybackSession { | |||
| 182 | let Some((idx, source)) = self.project.map_timeline(next) else { | 182 | let Some((idx, source)) = self.project.map_timeline(next) else { |
| 183 | return false; | 183 | return false; |
| 184 | }; | 184 | }; |
| 185 | - let out = self.project.clips()[idx].out_frame; | 185 | + let clip = self.project.clips()[idx]; |
| 186 | + let out = clip.out_frame; | ||
| 186 | match DecodeSession::open_range(&self.path, source, out) { | 187 | match DecodeSession::open_range(&self.path, source, out) { |
| 187 | Ok((_, frames, cancel)) => { | 188 | Ok((_, frames, cancel)) => { |
| 188 | self.frames = frames; | 189 | self.frames = frames; |
| @@ -195,6 +196,7 @@ impl PlaybackSession { | |||
| 195 | self.range = Clip { | 196 | self.range = Clip { |
| 196 | in_frame: source, | 197 | in_frame: source, |
| 197 | out_frame: out, | 198 | out_frame: out, |
| 199 | + ..clip | ||
| 198 | }; | 200 | }; |
| 199 | self.timeline_start = next; | 201 | self.timeline_start = next; |
| 200 | true | 202 | true |
| @@ -336,7 +338,8 @@ impl PlaybackSession { | |||
| 336 | // `target` is inside the timeline (never empty), so this always maps; | 338 | // `target` is inside the timeline (never empty), so this always maps; |
| 337 | // the range runs from there to the end of the clip it landed in. | 339 | // the range runs from there to the end of the clip it landed in. |
| 338 | if let Some((idx, source)) = self.project.map_timeline(target) { | 340 | if let Some((idx, source)) = self.project.map_timeline(target) { |
| 339 | - let out = self.project.clips()[idx].out_frame; | 341 | + let clip = self.project.clips()[idx]; |
| 342 | + let out = clip.out_frame; | ||
| 340 | match DecodeSession::open_range(&self.path, source, out) { | 343 | match DecodeSession::open_range(&self.path, source, out) { |
| 341 | Ok((_, frames, cancel)) => { | 344 | Ok((_, frames, cancel)) => { |
| 342 | self.frames = frames; | 345 | self.frames = frames; |
| @@ -350,6 +353,7 @@ impl PlaybackSession { | |||
| 350 | self.range = Clip { | 353 | self.range = Clip { |
| 351 | in_frame: source, | 354 | in_frame: source, |
| 352 | out_frame: out, | 355 | out_frame: out, |
| 356 | + ..clip | ||
| 353 | }; | 357 | }; |
| 354 | self.timeline_start = target; | 358 | self.timeline_start = target; |
| 355 | } | 359 | } |
| @@ -367,7 +371,14 @@ impl PlaybackSession { | |||
| 367 | // One worker for the whole rest of the timeline, so the joins | 371 | // One worker for the whole rest of the timeline, so the joins |
| 368 | // between clips are gapless: the video reopens at a boundary, the | 372 | // between clips are gapless: the video reopens at a boundary, the |
| 369 | // ear never hears it. | 373 | // ear never hears it. |
| 370 | - let segs = self.project.segments_from(target, fps); | 374 | + // Every source index is 0 until multi-source playback lands; the |
| 375 | + // audio worker still takes one path plus bare `(start, end)`. | ||
| 376 | + let segs: Vec<(f64, f64)> = self | ||
| 377 | + .project | ||
| 378 | + .segments_from(target, fps) | ||
| 379 | + .into_iter() | ||
| 380 | + .map(|(_, start, end)| (start, end)) | ||
| 381 | + .collect(); | ||
| 371 | audio_running = match AudioSession::open_segments(&self.path, &segs) { | 382 | audio_running = match AudioSession::open_segments(&self.path, &segs) { |
| 372 | Ok(Some((_, rx))) => audio.spawn_feeder(rx), | 383 | Ok(Some((_, rx))) => audio.spawn_feeder(rx), |
| 373 | _ => false, | 384 | _ => false, |
crates/engine/src/project.rsmodified+209 -18
| @@ -15,12 +15,23 @@ | |||
| 15 | //! across a cut; [`Project::delete`] does change the mapping and the caller | 15 | //! across a cut; [`Project::delete`] does change the mapping and the caller |
| 16 | //! must reseek. Every successful edit snapshots the clip list, so | 16 | //! must reseek. Every successful edit snapshots the clip list, so |
| 17 | //! [`Project::undo`] is an exact restore. | 17 | //! [`Project::undo`] is an exact restore. |
| 18 | +//! | ||
| 19 | +//! A clip names its file by *index* into [`Project::sources`], which is | ||
| 20 | +//! append-only: an index handed out once stays valid forever, so a clip on the | ||
| 21 | +//! clipboard or inside an undo snapshot can never dangle. An index -- not an | ||
| 22 | +//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a | ||
| 23 | +//! plain assignment. | ||
| 24 | + | ||
| 25 | +use std::path::{Path, PathBuf}; | ||
| 18 | 26 | ||
| 19 | -/// A half-open `[in_frame, out_frame)` range of source frames. Never empty. | 27 | +/// A half-open `[in_frame, out_frame)` range of frames of source |
| 28 | +/// [`source`](Clip::source). Never empty. | ||
| 20 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] | 29 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 21 | pub struct Clip { | 30 | pub struct Clip { |
| 22 | pub in_frame: u32, | 31 | pub in_frame: u32, |
| 23 | pub out_frame: u32, | 32 | pub out_frame: u32, |
| 33 | + /// Index into [`Project::sources`]. | ||
| 34 | + pub source: usize, | ||
| 24 | } | 35 | } |
| 25 | 36 | ||
| 26 | impl Clip { | 37 | impl Clip { |
| @@ -33,20 +44,24 @@ impl Clip { | |||
| 33 | /// The edit list plus its undo history. | 44 | /// The edit list plus its undo history. |
| 34 | #[derive(Clone, Debug)] | 45 | #[derive(Clone, Debug)] |
| 35 | pub struct Project { | 46 | pub struct Project { |
| 47 | + /// Append-only: never popped, never reordered. See the module docs. | ||
| 48 | + sources: Vec<PathBuf>, | ||
| 36 | clips: Vec<Clip>, | 49 | clips: Vec<Clip>, |
| 37 | /// Snapshots pushed *before* each successful edit; `undo` pops one. | 50 | /// Snapshots pushed *before* each successful edit; `undo` pops one. |
| 38 | history: Vec<Vec<Clip>>, | 51 | history: Vec<Vec<Clip>>, |
| 39 | } | 52 | } |
| 40 | 53 | ||
| 41 | impl Project { | 54 | impl Project { |
| 42 | - /// One clip covering the whole file -- the state of a freshly opened video, | 55 | + /// One clip covering the whole of `path` -- the state of a freshly opened |
| 43 | - /// where the timeline is the source. `frame_count` of 0 would break the | 56 | + /// video, where the timeline is the source. `frame_count` of 0 would break |
| 44 | - /// never-empty invariant, so it is clamped to one frame. | 57 | + /// the never-empty invariant, so it is clamped to one frame. |
| 45 | - pub fn single(frame_count: u32) -> Self { | 58 | + pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self { |
| 46 | Self { | 59 | Self { |
| 60 | + sources: vec![canonical(path.as_ref())], | ||
| 47 | clips: vec![Clip { | 61 | clips: vec![Clip { |
| 48 | in_frame: 0, | 62 | in_frame: 0, |
| 49 | out_frame: frame_count.max(1), | 63 | out_frame: frame_count.max(1), |
| 64 | + source: 0, | ||
| 50 | }], | 65 | }], |
| 51 | history: Vec::new(), | 66 | history: Vec::new(), |
| 52 | } | 67 | } |
| @@ -56,6 +71,44 @@ impl Project { | |||
| 56 | &self.clips | 71 | &self.clips |
| 57 | } | 72 | } |
| 58 | 73 | ||
| 74 | + /// The files the clips index into, in import order; index 0 is the file the | ||
| 75 | + /// project was opened with. | ||
| 76 | + pub fn sources(&self) -> &[PathBuf] { | ||
| 77 | + &self.sources | ||
| 78 | + } | ||
| 79 | + | ||
| 80 | + /// Index for `path`, appending it if it is new. Deduped by | ||
| 81 | + /// `fs::canonicalize`, so the same file reached by two paths imports once. | ||
| 82 | + /// The clip list is untouched -- see [`Project::append_clip`] -- so this | ||
| 83 | + /// pushes no history: a source entry alone changes nothing playable. | ||
| 84 | + pub fn import(&mut self, path: impl AsRef<Path>) -> usize { | ||
| 85 | + let path = canonical(path.as_ref()); | ||
| 86 | + match self.sources.iter().position(|s| *s == path) { | ||
| 87 | + Some(idx) => idx, | ||
| 88 | + None => { | ||
| 89 | + self.sources.push(path); | ||
| 90 | + self.sources.len() - 1 | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + /// Append a whole-file clip of `source` to the end of the timeline. One | ||
| 96 | + /// history snapshot, so an import is one undo step -- and undoing it leaves | ||
| 97 | + /// the (harmless) source entry behind, because indexes are forever. | ||
| 98 | + /// Refused for an unknown source index. | ||
| 99 | + pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool { | ||
| 100 | + if source >= self.sources.len() { | ||
| 101 | + return false; | ||
| 102 | + } | ||
| 103 | + self.history.push(self.clips.clone()); | ||
| 104 | + self.clips.push(Clip { | ||
| 105 | + in_frame: 0, | ||
| 106 | + out_frame: frame_count.max(1), | ||
| 107 | + source, | ||
| 108 | + }); | ||
| 109 | + true | ||
| 110 | + } | ||
| 111 | + | ||
| 59 | /// Length of the timeline in frames. | 112 | /// Length of the timeline in frames. |
| 60 | pub fn timeline_frames(&self) -> u32 { | 113 | pub fn timeline_frames(&self) -> u32 { |
| 61 | self.clips.iter().map(Clip::len).sum() | 114 | self.clips.iter().map(Clip::len).sum() |
| @@ -106,6 +159,7 @@ impl Project { | |||
| 106 | Clip { | 159 | Clip { |
| 107 | in_frame: source, | 160 | in_frame: source, |
| 108 | out_frame: out, | 161 | out_frame: out, |
| 162 | + ..self.clips[idx] | ||
| 109 | }, | 163 | }, |
| 110 | ); | 164 | ); |
| 111 | true | 165 | true |
| @@ -138,6 +192,7 @@ impl Project { | |||
| 138 | Clip { | 192 | Clip { |
| 139 | in_frame: source, | 193 | in_frame: source, |
| 140 | out_frame: out, | 194 | out_frame: out, |
| 195 | + ..self.clips[idx] | ||
| 141 | }, | 196 | }, |
| 142 | ], | 197 | ], |
| 143 | ); | 198 | ); |
| @@ -172,51 +227,70 @@ impl Project { | |||
| 172 | } | 227 | } |
| 173 | } | 228 | } |
| 174 | 229 | ||
| 175 | - /// Half-open `(start, end)` segments in *source* seconds, from | 230 | + /// Half-open `(source, start, end)` segments in *source* seconds, from |
| 176 | /// `timeline_frame` to the end of the timeline -- the play list for the | 231 | /// `timeline_frame` to the end of the timeline -- the play list for the |
| 177 | /// audio worker. The first entry is partial when the position is mid-clip. | 232 | /// audio worker. The first entry is partial when the position is mid-clip. |
| 178 | /// Empty when the position is past the end or `fps` is not usable. | 233 | /// Empty when the position is past the end or `fps` is not usable. |
| 179 | - pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(f64, f64)> { | 234 | + pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(usize, f64, f64)> { |
| 180 | if !(fps.is_finite() && fps > 0.0) { | 235 | if !(fps.is_finite() && fps > 0.0) { |
| 181 | return Vec::new(); | 236 | return Vec::new(); |
| 182 | } | 237 | } |
| 183 | let Some((idx, source)) = self.map_timeline(timeline_frame) else { | 238 | let Some((idx, source)) = self.map_timeline(timeline_frame) else { |
| 184 | return Vec::new(); | 239 | return Vec::new(); |
| 185 | }; | 240 | }; |
| 186 | - let mut segs = vec![(source as f64 / fps, self.clips[idx].out_frame as f64 / fps)]; | 241 | + let head = self.clips[idx]; |
| 242 | + let mut segs = vec![( | ||
| 243 | + head.source, | ||
| 244 | + source as f64 / fps, | ||
| 245 | + head.out_frame as f64 / fps, | ||
| 246 | + )]; | ||
| 187 | segs.extend( | 247 | segs.extend( |
| 188 | self.clips[idx + 1..] | 248 | self.clips[idx + 1..] |
| 189 | .iter() | 249 | .iter() |
| 190 | - .map(|c| (c.in_frame as f64 / fps, c.out_frame as f64 / fps)), | 250 | + .map(|c| (c.source, c.in_frame as f64 / fps, c.out_frame as f64 / fps)), |
| 191 | ); | 251 | ); |
| 192 | segs | 252 | segs |
| 193 | } | 253 | } |
| 194 | } | 254 | } |
| 195 | 255 | ||
| 256 | +/// Absolute, symlink-resolved when the file is reachable; the path as given | ||
| 257 | +/// when it is not -- an unreadable path still deserves an index, it simply | ||
| 258 | +/// dedups by spelling. | ||
| 259 | +fn canonical(path: &Path) -> PathBuf { | ||
| 260 | + std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) | ||
| 261 | +} | ||
| 262 | + | ||
| 196 | #[cfg(test)] | 263 | #[cfg(test)] |
| 197 | mod tests { | 264 | mod tests { |
| 198 | use super::*; | 265 | use super::*; |
| 199 | 266 | ||
| 200 | const FPS: f64 = 30.0; | 267 | const FPS: f64 = 30.0; |
| 268 | + /// Never opened -- `Project` is pure data, so a path that does not exist is | ||
| 269 | + /// simply a path that dedups by spelling. | ||
| 270 | + const FILE: &str = "/nonexistent/a.mp4"; | ||
| 271 | + const FILE2: &str = "/nonexistent/b.mp4"; | ||
| 201 | 272 | ||
| 202 | /// Source clips [0,3) [3,5) [5,9) -- the ledger's off-by-one fixture. Built | 273 | /// Source clips [0,3) [3,5) [5,9) -- the ledger's off-by-one fixture. Built |
| 203 | /// through `cut` so the constructor path is exercised too. | 274 | /// through `cut` so the constructor path is exercised too. |
| 204 | fn three() -> Project { | 275 | fn three() -> Project { |
| 205 | - let mut p = Project::single(9); | 276 | + let mut p = Project::single(FILE, 9); |
| 206 | assert!(p.cut(3)); | 277 | assert!(p.cut(3)); |
| 207 | assert!(p.cut(5)); | 278 | assert!(p.cut(5)); |
| 208 | assert_eq!( | 279 | assert_eq!( |
| 209 | p.clips(), | 280 | p.clips(), |
| 210 | [ | 281 | [ |
| 211 | Clip { | 282 | Clip { |
| 283 | + source: 0, | ||
| 212 | in_frame: 0, | 284 | in_frame: 0, |
| 213 | out_frame: 3 | 285 | out_frame: 3 |
| 214 | }, | 286 | }, |
| 215 | Clip { | 287 | Clip { |
| 288 | + source: 0, | ||
| 216 | in_frame: 3, | 289 | in_frame: 3, |
| 217 | out_frame: 5 | 290 | out_frame: 5 |
| 218 | }, | 291 | }, |
| 219 | Clip { | 292 | Clip { |
| 293 | + source: 0, | ||
| 220 | in_frame: 5, | 294 | in_frame: 5, |
| 221 | out_frame: 9 | 295 | out_frame: 9 |
| 222 | }, | 296 | }, |
| @@ -227,7 +301,7 @@ mod tests { | |||
| 227 | 301 | ||
| 228 | #[test] | 302 | #[test] |
| 229 | fn single_is_the_whole_file() { | 303 | fn single_is_the_whole_file() { |
| 230 | - let p = Project::single(150); | 304 | + let p = Project::single(FILE, 150); |
| 231 | assert_eq!(p.clips().len(), 1); | 305 | assert_eq!(p.clips().len(), 1); |
| 232 | assert_eq!(p.timeline_frames(), 150); | 306 | assert_eq!(p.timeline_frames(), 150); |
| 233 | assert_eq!(p.clip_spans(), vec![(0, 150)]); | 307 | assert_eq!(p.clip_spans(), vec![(0, 150)]); |
| @@ -236,21 +310,23 @@ mod tests { | |||
| 236 | assert_eq!(p.map_timeline(149), Some((0, 149))); | 310 | assert_eq!(p.map_timeline(149), Some((0, 149))); |
| 237 | assert_eq!(p.map_timeline(150), None); | 311 | assert_eq!(p.map_timeline(150), None); |
| 238 | // never-empty invariant survives a bogus frame count | 312 | // never-empty invariant survives a bogus frame count |
| 239 | - assert_eq!(Project::single(0).timeline_frames(), 1); | 313 | + assert_eq!(Project::single(FILE, 0).timeline_frames(), 1); |
| 240 | } | 314 | } |
| 241 | 315 | ||
| 242 | #[test] | 316 | #[test] |
| 243 | fn cut_mid_clip_splits() { | 317 | fn cut_mid_clip_splits() { |
| 244 | - let mut p = Project::single(9); | 318 | + let mut p = Project::single(FILE, 9); |
| 245 | assert!(p.cut(4)); | 319 | assert!(p.cut(4)); |
| 246 | assert_eq!( | 320 | assert_eq!( |
| 247 | p.clips(), | 321 | p.clips(), |
| 248 | [ | 322 | [ |
| 249 | Clip { | 323 | Clip { |
| 324 | + source: 0, | ||
| 250 | in_frame: 0, | 325 | in_frame: 0, |
| 251 | out_frame: 4 | 326 | out_frame: 4 |
| 252 | }, | 327 | }, |
| 253 | Clip { | 328 | Clip { |
| 329 | + source: 0, | ||
| 254 | in_frame: 4, | 330 | in_frame: 4, |
| 255 | out_frame: 9 | 331 | out_frame: 9 |
| 256 | }, | 332 | }, |
| @@ -310,6 +386,7 @@ mod tests { | |||
| 310 | /// The clip a copy would hand back: source `[100, 102)`, unrelated to | 386 | /// The clip a copy would hand back: source `[100, 102)`, unrelated to |
| 311 | /// anything in `three()` so it is recognisable wherever it lands. | 387 | /// anything in `three()` so it is recognisable wherever it lands. |
| 312 | const PASTED: Clip = Clip { | 388 | const PASTED: Clip = Clip { |
| 389 | + source: 0, | ||
| 313 | in_frame: 100, | 390 | in_frame: 100, |
| 314 | out_frame: 102, | 391 | out_frame: 102, |
| 315 | }; | 392 | }; |
| @@ -323,19 +400,23 @@ mod tests { | |||
| 323 | p.clips(), | 400 | p.clips(), |
| 324 | [ | 401 | [ |
| 325 | Clip { | 402 | Clip { |
| 403 | + source: 0, | ||
| 326 | in_frame: 0, | 404 | in_frame: 0, |
| 327 | out_frame: 3 | 405 | out_frame: 3 |
| 328 | }, | 406 | }, |
| 329 | Clip { | 407 | Clip { |
| 408 | + source: 0, | ||
| 330 | in_frame: 3, | 409 | in_frame: 3, |
| 331 | out_frame: 5 | 410 | out_frame: 5 |
| 332 | }, | 411 | }, |
| 333 | Clip { | 412 | Clip { |
| 413 | + source: 0, | ||
| 334 | in_frame: 5, | 414 | in_frame: 5, |
| 335 | out_frame: 6 | 415 | out_frame: 6 |
| 336 | }, | 416 | }, |
| 337 | PASTED, | 417 | PASTED, |
| 338 | Clip { | 418 | Clip { |
| 419 | + source: 0, | ||
| 339 | in_frame: 6, | 420 | in_frame: 6, |
| 340 | out_frame: 9 | 421 | out_frame: 9 |
| 341 | }, | 422 | }, |
| @@ -372,6 +453,7 @@ mod tests { | |||
| 372 | assert!(!p.paste( | 453 | assert!(!p.paste( |
| 373 | 4, | 454 | 4, |
| 374 | Clip { | 455 | Clip { |
| 456 | + source: 0, | ||
| 375 | in_frame: 7, | 457 | in_frame: 7, |
| 376 | out_frame: 7 | 458 | out_frame: 7 |
| 377 | } | 459 | } |
| @@ -444,6 +526,7 @@ mod tests { | |||
| 444 | assert_eq!( | 526 | assert_eq!( |
| 445 | p.clips(), | 527 | p.clips(), |
| 446 | [Clip { | 528 | [Clip { |
| 529 | + source: 0, | ||
| 447 | in_frame: 0, | 530 | in_frame: 0, |
| 448 | out_frame: 9 | 531 | out_frame: 9 |
| 449 | }] | 532 | }] |
| @@ -452,6 +535,7 @@ mod tests { | |||
| 452 | assert_eq!( | 535 | assert_eq!( |
| 453 | p.clips(), | 536 | p.clips(), |
| 454 | [Clip { | 537 | [Clip { |
| 538 | + source: 0, | ||
| 455 | in_frame: 0, | 539 | in_frame: 0, |
| 456 | out_frame: 9 | 540 | out_frame: 9 |
| 457 | }] | 541 | }] |
| @@ -464,31 +548,138 @@ mod tests { | |||
| 464 | // mid-clip: partial first segment, whole clips after it | 548 | // mid-clip: partial first segment, whole clips after it |
| 465 | assert_eq!( | 549 | assert_eq!( |
| 466 | p.segments_from(4, FPS), | 550 | p.segments_from(4, FPS), |
| 467 | - vec![(4.0 / 30.0, 5.0 / 30.0), (5.0 / 30.0, 9.0 / 30.0)] | 551 | + vec![(0, 4.0 / 30.0, 5.0 / 30.0), (0, 5.0 / 30.0, 9.0 / 30.0)] |
| 468 | ); | 552 | ); |
| 469 | // on a boundary: nothing partial | 553 | // on a boundary: nothing partial |
| 470 | assert_eq!( | 554 | assert_eq!( |
| 471 | p.segments_from(3, FPS), | 555 | p.segments_from(3, FPS), |
| 472 | - vec![(3.0 / 30.0, 5.0 / 30.0), (5.0 / 30.0, 9.0 / 30.0)] | 556 | + vec![(0, 3.0 / 30.0, 5.0 / 30.0), (0, 5.0 / 30.0, 9.0 / 30.0)] |
| 473 | ); | 557 | ); |
| 474 | // from the top: one entry per clip | 558 | // from the top: one entry per clip |
| 475 | assert_eq!(p.segments_from(0, FPS).len(), 3); | 559 | assert_eq!(p.segments_from(0, FPS).len(), 3); |
| 476 | // last clip only | 560 | // last clip only |
| 477 | - assert_eq!(p.segments_from(8, FPS), vec![(8.0 / 30.0, 0.3)]); | 561 | + assert_eq!(p.segments_from(8, FPS), vec![(0, 8.0 / 30.0, 0.3)]); |
| 478 | // past the end / unusable fps | 562 | // past the end / unusable fps |
| 479 | assert!(p.segments_from(9, FPS).is_empty()); | 563 | assert!(p.segments_from(9, FPS).is_empty()); |
| 480 | assert!(p.segments_from(0, 0.0).is_empty()); | 564 | assert!(p.segments_from(0, 0.0).is_empty()); |
| 481 | assert!(p.segments_from(0, f64::NAN).is_empty()); | 565 | assert!(p.segments_from(0, f64::NAN).is_empty()); |
| 482 | } | 566 | } |
| 483 | 567 | ||
| 568 | + /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9) | ||
| 569 | + /// of source 0 then [0,4) of source 1. | ||
| 570 | + fn two_sources() -> Project { | ||
| 571 | + let mut p = three(); | ||
| 572 | + let s = p.import(FILE2); | ||
| 573 | + assert_eq!(s, 1); | ||
| 574 | + assert!(p.append_clip(s, 4)); | ||
| 575 | + p | ||
| 576 | + } | ||
| 577 | + | ||
| 578 | + #[test] | ||
| 579 | + fn import_dedups_and_appends() { | ||
| 580 | + let mut p = Project::single(FILE, 9); | ||
| 581 | + assert_eq!(p.sources().len(), 1, "the opened file is source 0"); | ||
| 582 | + assert_eq!(p.import(FILE), 0, "reimporting the open file reuses 0"); | ||
| 583 | + assert_eq!(p.import(FILE2), 1); | ||
| 584 | + assert_eq!(p.import(FILE2), 1, "second import of the same path"); | ||
| 585 | + assert_eq!(p.sources().len(), 2); | ||
| 586 | + assert!(!p.append_clip(2, 5), "unknown source index"); | ||
| 587 | + assert_eq!(p.clips().len(), 1, "a refusal changes nothing"); | ||
| 588 | + | ||
| 589 | + // Two spellings of one real file are one source: this is the case the | ||
| 590 | + // raw-path comparison above would get wrong. | ||
| 591 | + let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs"); | ||
| 592 | + let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs"); | ||
| 593 | + let mut p = Project::single(here, 9); | ||
| 594 | + assert_eq!(p.import(detour), 0); | ||
| 595 | + assert_eq!(p.sources().len(), 1); | ||
| 596 | + } | ||
| 597 | + | ||
| 598 | + #[test] | ||
| 599 | + fn append_clip_is_one_undo_step() { | ||
| 600 | + let mut p = two_sources(); | ||
| 601 | + assert_eq!(p.timeline_frames(), 13); | ||
| 602 | + assert_eq!( | ||
| 603 | + p.clips()[3], | ||
| 604 | + Clip { | ||
| 605 | + in_frame: 0, | ||
| 606 | + out_frame: 4, | ||
| 607 | + source: 1 | ||
| 608 | + } | ||
| 609 | + ); | ||
| 610 | + assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9"); | ||
| 611 | + assert!(p.undo()); | ||
| 612 | + assert_eq!(p.clips(), three().clips(), "one step back to one source"); | ||
| 613 | + assert_eq!( | ||
| 614 | + p.sources().len(), | ||
| 615 | + 2, | ||
| 616 | + "the orphan source entry stays -- indexes are forever" | ||
| 617 | + ); | ||
| 618 | + // ...and it is still usable, so a redo-by-hand costs no reimport. | ||
| 619 | + assert!(p.append_clip(1, 0)); | ||
| 620 | + assert_eq!(p.clips()[3].len(), 1, "clamped like `single`"); | ||
| 621 | + } | ||
| 622 | + | ||
| 623 | + #[test] | ||
| 624 | + fn edits_carry_the_source_along() { | ||
| 625 | + let mut p = two_sources(); | ||
| 626 | + // A cut inside the second source splits into two source-1 clips. | ||
| 627 | + assert!(p.cut(11)); | ||
| 628 | + assert_eq!( | ||
| 629 | + p.clips()[3], | ||
| 630 | + Clip { | ||
| 631 | + in_frame: 0, | ||
| 632 | + out_frame: 2, | ||
| 633 | + source: 1 | ||
| 634 | + } | ||
| 635 | + ); | ||
| 636 | + assert_eq!( | ||
| 637 | + p.clips()[4], | ||
| 638 | + Clip { | ||
| 639 | + in_frame: 2, | ||
| 640 | + out_frame: 4, | ||
| 641 | + source: 1 | ||
| 642 | + } | ||
| 643 | + ); | ||
| 644 | + | ||
| 645 | + // A source-1 clip pasted into source-0 territory keeps its file, and so | ||
| 646 | + // does the source-0 half that got split off around it. | ||
| 647 | + let copied = p.clips()[4]; | ||
| 648 | + assert!(p.paste(1, copied)); | ||
| 649 | + assert_eq!(p.clips()[1], copied); | ||
| 650 | + assert_eq!(p.clips()[2].source, 0); | ||
| 651 | + assert!(p.undo()); | ||
| 652 | + assert_eq!(p.clips()[1].source, 0, "undo restores sources too"); | ||
| 653 | + } | ||
| 654 | + | ||
| 655 | + #[test] | ||
| 656 | + fn segments_from_names_the_source() { | ||
| 657 | + let p = two_sources(); | ||
| 658 | + // Mid-clip in source 0, then the rest of source 0, then source 1 whole. | ||
| 659 | + assert_eq!( | ||
| 660 | + p.segments_from(4, FPS), | ||
| 661 | + vec![ | ||
| 662 | + (0, 4.0 / 30.0, 5.0 / 30.0), | ||
| 663 | + (0, 5.0 / 30.0, 9.0 / 30.0), | ||
| 664 | + (1, 0.0, 4.0 / 30.0), | ||
| 665 | + ] | ||
| 666 | + ); | ||
| 667 | + // Mid-clip in source 1: only that source is left. | ||
| 668 | + assert_eq!(p.segments_from(10, FPS), vec![(1, 1.0 / 30.0, 4.0 / 30.0)]); | ||
| 669 | + assert!(p.segments_from(13, FPS).is_empty()); | ||
| 670 | + // Segments still cover exactly the timeline across the join. | ||
| 671 | + let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum(); | ||
| 672 | + assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9); | ||
| 673 | + } | ||
| 674 | + | ||
| 484 | #[test] | 675 | #[test] |
| 485 | fn segments_follow_deletes_and_fps() { | 676 | fn segments_follow_deletes_and_fps() { |
| 486 | let mut p = three(); | 677 | let mut p = three(); |
| 487 | assert!(p.delete(0)); | 678 | assert!(p.delete(0)); |
| 488 | // source seconds, not timeline: deleting the head does not shift them | 679 | // source seconds, not timeline: deleting the head does not shift them |
| 489 | let segs = p.segments_from(0, 25.0); | 680 | let segs = p.segments_from(0, 25.0); |
| 490 | - assert_eq!(segs, vec![(3.0 / 25.0, 0.2), (0.2, 9.0 / 25.0)]); | 681 | + assert_eq!(segs, vec![(0, 3.0 / 25.0, 0.2), (0, 0.2, 9.0 / 25.0)]); |
| 491 | - let played: f64 = segs.iter().map(|(a, b)| b - a).sum(); | 682 | + let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum(); |
| 492 | assert!( | 683 | assert!( |
| 493 | (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9, | 684 | (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9, |
| 494 | "segments must cover exactly the timeline: {played}" | 685 | "segments must cover exactly the timeline: {played}" |
crates/engine/tests/audio_multi.rsadded+263 -0
| @@ -0,0 +1,263 @@ | |||
| 1 | +//! Multi-source audio: two files poured into one stream. A source join has to | ||
| 2 | +//! behave exactly like a cut inside one file — no gap in `start_sample`, no | ||
| 3 | +//! second priming packet, one shared rounding debt — while each source still | ||
| 4 | +//! contributes its own content, its own packet table and its own length. | ||
| 5 | + | ||
| 6 | +use std::fs::File; | ||
| 7 | +use std::io::BufReader; | ||
| 8 | +use std::path::PathBuf; | ||
| 9 | +use std::sync::mpsc::Receiver; | ||
| 10 | + | ||
| 11 | +use engine::audio::{AacPacket, AudioChunk, AudioSession}; | ||
| 12 | +use mp4::{MediaType, Mp4Reader}; | ||
| 13 | + | ||
| 14 | +const RATE: u64 = 44100; | ||
| 15 | +const CHANNELS: usize = 2; | ||
| 16 | +/// Frames per channel in one AAC-LC packet. | ||
| 17 | +const PACKET: u64 = 1024; | ||
| 18 | + | ||
| 19 | +fn asset(name: &str) -> PathBuf { | ||
| 20 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 21 | + .join("../../assets") | ||
| 22 | + .join(name) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +/// The import-policy pair: same 1280x720@30 / AAC-LC 44.1k stereo, plainly | ||
| 26 | +/// different content (440/880 Hz vs 660/1320 Hz, 5 s vs 4 s). | ||
| 27 | +fn sources() -> Vec<PathBuf> { | ||
| 28 | + vec![asset("test_av.mp4"), asset("test_av2.mp4")] | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +/// Drains a session flat, asserting chunks are contiguous, and reports the | ||
| 32 | +/// first chunk's `start_sample` plus how many chunks arrived. | ||
| 33 | +fn drain(rx: Receiver<AudioChunk>) -> (Vec<f32>, u64, usize) { | ||
| 34 | + let (mut samples, mut first, mut chunks) = (Vec::new(), None, 0usize); | ||
| 35 | + for AudioChunk { | ||
| 36 | + start_sample, | ||
| 37 | + samples: s, | ||
| 38 | + } in rx | ||
| 39 | + { | ||
| 40 | + assert!(!s.is_empty(), "empty chunk {chunks}"); | ||
| 41 | + let want = first.unwrap_or(start_sample) + (samples.len() / CHANNELS) as u64; | ||
| 42 | + assert_eq!(start_sample, want, "gap or overlap before chunk {chunks}"); | ||
| 43 | + first.get_or_insert(start_sample); | ||
| 44 | + samples.extend(s); | ||
| 45 | + chunks += 1; | ||
| 46 | + } | ||
| 47 | + (samples, first.unwrap_or(0), chunks) | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +fn multi(segs: &[(usize, f64, f64)]) -> (Vec<f32>, u64, usize) { | ||
| 51 | + let (_, rx) = AudioSession::open_multi_segments(&sources(), segs) | ||
| 52 | + .expect("open") | ||
| 53 | + .expect("the first source has an audio track"); | ||
| 54 | + drain(rx) | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// The first `frames` per channel of a plain single-file `open_at(start)`. | ||
| 58 | +fn window(name: &str, start: f64, frames: u64) -> Vec<f32> { | ||
| 59 | + let (_, rx) = AudioSession::open_at(asset(name), start).unwrap().unwrap(); | ||
| 60 | + let (mut samples, _, _) = drain(rx); | ||
| 61 | + assert!(samples.len() >= frames as usize * CHANNELS, "short window"); | ||
| 62 | + samples.truncate(frames as usize * CHANNELS); | ||
| 63 | + samples | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// Perceptual noise substitution reseeds per decoder, so a segment can never be | ||
| 67 | +/// promised bit-exact against another run (engine/src/audio.rs docs, ledger). | ||
| 68 | +fn assert_close(got: &[f32], want: &[f32], what: &str) { | ||
| 69 | + assert_eq!(got.len(), want.len(), "{what}: length"); | ||
| 70 | + let (diff, at) = got | ||
| 71 | + .iter() | ||
| 72 | + .zip(want) | ||
| 73 | + .enumerate() | ||
| 74 | + .map(|(i, (x, y))| ((x - y).abs(), i)) | ||
| 75 | + .fold((0.0f32, 0), |m, d| if d.0 > m.0 { d } else { m }); | ||
| 76 | + eprintln!( | ||
| 77 | + "{what}: max abs diff {diff:e} at sample {at} of {}", | ||
| 78 | + got.len() | ||
| 79 | + ); | ||
| 80 | + assert!(diff < 1e-3, "{what}: max abs diff {diff} at sample {at}"); | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// Cycles of the left channel: rising edges through a deadband, so the coding | ||
| 84 | +/// noise around the fixture's 1 Hz volume dip is not counted as a cycle. One | ||
| 85 | +/// second of the 440 Hz source reads ~440, of the 660 Hz one ~660. | ||
| 86 | +fn cycles(samples: &[f32]) -> usize { | ||
| 87 | + let (mut n, mut high) = (0usize, false); | ||
| 88 | + for &s in samples.iter().step_by(CHANNELS) { | ||
| 89 | + if !high && s > 0.05 { | ||
| 90 | + high = true; | ||
| 91 | + n += 1; | ||
| 92 | + } else if high && s < -0.05 { | ||
| 93 | + high = false; | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | + n | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// The AAC sample bytes for 1-based `ids` of `name`, read straight from the | ||
| 100 | +/// demuxer — the reference a copy must match byte for byte. | ||
| 101 | +fn raw(name: &str, ids: impl IntoIterator<Item = u32>) -> Vec<Vec<u8>> { | ||
| 102 | + let file = File::open(asset(name)).unwrap(); | ||
| 103 | + let size = file.metadata().unwrap().len(); | ||
| 104 | + let mut reader = Mp4Reader::read_header(BufReader::new(file), size).unwrap(); | ||
| 105 | + let track = reader | ||
| 106 | + .tracks() | ||
| 107 | + .values() | ||
| 108 | + .find(|t| matches!(t.media_type(), Ok(MediaType::AAC))) | ||
| 109 | + .unwrap() | ||
| 110 | + .track_id(); | ||
| 111 | + ids.into_iter() | ||
| 112 | + .map(|id| { | ||
| 113 | + reader | ||
| 114 | + .read_sample(track, id) | ||
| 115 | + .unwrap() | ||
| 116 | + .unwrap_or_else(|| panic!("no sample {id} in {name}")) | ||
| 117 | + .bytes | ||
| 118 | + .to_vec() | ||
| 119 | + }) | ||
| 120 | + .collect() | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +fn assert_same_bytes(got: &[AacPacket], want: &[Vec<u8>], what: &str) { | ||
| 124 | + assert_eq!(got.len(), want.len(), "{what}: packet count"); | ||
| 125 | + for (i, (p, w)) in got.iter().zip(want).enumerate() { | ||
| 126 | + assert_eq!(&p.bytes, w, "{what}: packet {i} ({} bytes)", p.bytes.len()); | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +fn copy(segs: &[(usize, f64, f64)]) -> Vec<AacPacket> { | ||
| 131 | + AudioSession::copy_multi_segments(&sources(), segs) | ||
| 132 | + .expect("copy") | ||
| 133 | + .expect("the first source has an audio track") | ||
| 134 | + .1 | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +#[test] | ||
| 138 | +fn two_sources_join_without_a_gap() { | ||
| 139 | + let (got, first, chunks) = multi(&[(0, 1.0, 2.0), (1, 0.0, 1.0)]); | ||
| 140 | + // `drain` already proved every chunk butts against the previous one, so a | ||
| 141 | + // full-length run is a joint with no gap and no overlap. | ||
| 142 | + assert_eq!(first, RATE, "numbering starts at the first segment's start"); | ||
| 143 | + assert_eq!( | ||
| 144 | + got.len() as u64 / CHANNELS as u64, | ||
| 145 | + 2 * RATE, | ||
| 146 | + "{chunks} chunks" | ||
| 147 | + ); | ||
| 148 | + | ||
| 149 | + let half = RATE as usize * CHANNELS; | ||
| 150 | + assert_close(&got[..half], &window("test_av.mp4", 1.0, RATE), "source 0"); | ||
| 151 | + assert_close(&got[half..], &window("test_av2.mp4", 0.0, RATE), "source 1"); | ||
| 152 | + | ||
| 153 | + // And the two halves are audibly different files, not the same one twice: | ||
| 154 | + // an octave-and-a-fifth apart, 440 -> 660 Hz. | ||
| 155 | + let (c0, c1) = (cycles(&got[..half]), cycles(&got[half..])); | ||
| 156 | + eprintln!("cycles: {c0} then {c1}"); | ||
| 157 | + assert!( | ||
| 158 | + (c1 as f64 / c0 as f64 - 1.5).abs() < 0.1, | ||
| 159 | + "{c0} then {c1} cycles: expected the 440 Hz source then the 660 Hz one" | ||
| 160 | + ); | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +#[test] | ||
| 164 | +fn each_source_ends_where_its_own_track_does() { | ||
| 165 | + // test_av2 is 4 s: the ask runs a second past it and must simply stop there, | ||
| 166 | + // then the next segment continues the numbering (`drain` checks that). | ||
| 167 | + let (got, first, _) = multi(&[(1, 3.5, 5.0), (0, 0.0, 0.5)]); | ||
| 168 | + assert_eq!(first, 3 * RATE + RATE / 2); | ||
| 169 | + let frames = got.len() as u64 / CHANNELS as u64; | ||
| 170 | + assert!( | ||
| 171 | + (RATE..=RATE + PACKET).contains(&frames), | ||
| 172 | + "{frames} frames for 0.5 s of a 4 s source plus 0.5 s of the next \ | ||
| 173 | + (+0..={PACKET} tail padding)" | ||
| 174 | + ); | ||
| 175 | + let tail = got.len() - RATE as usize / 2 * CHANNELS; | ||
| 176 | + assert_close( | ||
| 177 | + &got[tail..], | ||
| 178 | + &window("test_av.mp4", 0.0, RATE / 2), | ||
| 179 | + "back to source 0", | ||
| 180 | + ); | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +#[test] | ||
| 184 | +fn probe_reads_the_import_policy_fields() { | ||
| 185 | + let av = AudioSession::probe(asset("test_av.mp4")) | ||
| 186 | + .expect("probe") | ||
| 187 | + .expect("test_av.mp4 has audio"); | ||
| 188 | + assert_eq!(av.channels, 2); | ||
| 189 | + assert_eq!(av.params.sample_rate, RATE as u32); | ||
| 190 | + assert_eq!( | ||
| 191 | + AudioSession::probe(asset("test_av2.mp4")).unwrap().unwrap(), | ||
| 192 | + av, | ||
| 193 | + "the fixtures are the matching pair import must accept" | ||
| 194 | + ); | ||
| 195 | + for silent in ["test_baseline.mp4", "test_mismatch.mp4"] { | ||
| 196 | + assert!( | ||
| 197 | + AudioSession::probe(asset(silent)).unwrap().is_none(), | ||
| 198 | + "{silent} has no audio track" | ||
| 199 | + ); | ||
| 200 | + } | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +#[test] | ||
| 204 | +fn one_rounding_debt_is_carried_across_the_source_joins() { | ||
| 205 | + // A second is 43.07 packets, so seven seconds copy 43 each and owe 68 | ||
| 206 | + // samples apiece; the eighth crosses half a packet and copies 44 (the unit | ||
| 207 | + // test `packet_run_rounds_against_the_running_debt` pins that arithmetic). | ||
| 208 | + // Per segment rounding would copy 43 eight times and start drifting out of | ||
| 209 | + // sync — and every one of these joins is a *source* join. | ||
| 210 | + let segs: Vec<_> = (0..8).map(|i| (i % 2, 0.0, 1.0)).collect(); | ||
| 211 | + let packets = copy(&segs); | ||
| 212 | + assert_eq!( | ||
| 213 | + packets.len(), | ||
| 214 | + 1 + 7 * 43 + 44, | ||
| 215 | + "priming packet + seven seconds owing 68 each + the eighth repaying" | ||
| 216 | + ); | ||
| 217 | + let audible = (packets.len() as u64 - 1) * PACKET; | ||
| 218 | + assert!( | ||
| 219 | + (audible as i64 - 8 * RATE as i64).unsigned_abs() < PACKET, | ||
| 220 | + "{audible} samples for 8 s over seven source joins" | ||
| 221 | + ); | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +#[test] | ||
| 225 | +fn the_join_carries_no_second_priming_packet() { | ||
| 226 | + let packets = copy(&[(0, 0.0, 1.0), (1, 0.0, 1.0)]); | ||
| 227 | + let split = 1 + 43; | ||
| 228 | + assert_eq!(packets.len(), split + 43); | ||
| 229 | + for p in &packets { | ||
| 230 | + assert_eq!(p.samples as u64, PACKET, "AAC-LC packets are 1024 frames"); | ||
| 231 | + } | ||
| 232 | + // Source 0 from id 1 — its own priming packet, the one the reader drops. | ||
| 233 | + assert_same_bytes(&packets[..split], &raw("test_av.mp4", 1..=44), "source 0"); | ||
| 234 | + // Source 1 from id 2: 0.0 s is media 1024 (its priming), which packet 2 | ||
| 235 | + // holds. Starting at id 1 here would insert a packet the reader keeps. | ||
| 236 | + assert_same_bytes( | ||
| 237 | + &packets[split..], | ||
| 238 | + &raw("test_av2.mp4", 2..45), | ||
| 239 | + "source 1 at the join", | ||
| 240 | + ); | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +#[test] | ||
| 244 | +fn a_source_without_the_timeline_audio_is_refused() { | ||
| 245 | + // Import refuses these up front (same rate, same layout, or both silent); | ||
| 246 | + // the copy and the decode paths refuse them again rather than mislabel one | ||
| 247 | + // esds for two different tracks. | ||
| 248 | + let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; | ||
| 249 | + let segs = [(0, 0.0, 1.0), (1, 0.0, 1.0)]; | ||
| 250 | + // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.) | ||
| 251 | + for e in [ | ||
| 252 | + AudioSession::copy_multi_segments(&mixed, &segs).err(), | ||
| 253 | + AudioSession::open_multi_segments(&mixed, &segs).err(), | ||
| 254 | + ] | ||
| 255 | + .map(|e| e.expect("a source with no audio track must be refused")) | ||
| 256 | + { | ||
| 257 | + let msg = e.to_string(); | ||
| 258 | + assert!(msg.contains("source 1"), "{msg}"); | ||
| 259 | + } | ||
| 260 | + // An out-of-range index is an error, not a panic. | ||
| 261 | + assert!(AudioSession::copy_multi_segments(&sources(), &[(2, 0.0, 1.0)]).is_err()); | ||
| 262 | + assert!(AudioSession::open_multi_segments(&sources(), &[(2, 0.0, 1.0)]).is_err()); | ||
| 263 | +} | ||