forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-ad755bbe2a8af9c0c'

Browse files at this commit

610e3b60573dbe35c8b04c7cdc8646ac136c9f62Ahmet Kaan GümüşParent: cb80597a2e4154
# Conflicts:
#	crates/app/src/main.rs
crates/app/src/main.rsmodified+341 -69
@@ -369,6 +369,39 @@ impl Import {
369 }369 }
370 }370 }
371 371
372+/// The silence scan a worker is running, as the card shows it. Same two clocks
373+/// as an [`Import`] and for the same reason -- one proves the window answers,
374+/// one says the read has stopped moving -- over a progress that *can* move:
375+/// a decode knows how far into the sound it has come, so the card says so.
376+struct SilenceScan {
377+ /// Source and stream being scanned, which is the cache key the levels land
378+ /// under and what tells a second open of the same clip from a new one.
379+ key: (PathBuf, usize),
380+ /// When the worker started, for the elapsed clock.
381+ started: Instant,
382+ /// Written by the worker, read here every repaint. The cancel flag in it is
383+ /// this side's only word to a scan already running.
384+ progress: Arc<engine::silence::Progress>,
385+ /// The tenths-of-a-second mark the line last saw and when it last changed:
386+ /// the stall detector, exactly [`Import::poll`]'s.
387+ seen: u64,
388+ since: Instant,
389+}
390+
391+impl SilenceScan {
392+ /// Reads the worker's mark and keeps the stall clock, restarting it only
393+ /// when the mark actually moves -- [`Import::poll`]'s contract, over a
394+ /// number instead of a stage.
395+ fn poll(&mut self) -> f32 {
396+ let scanned = self.progress.scanned.load(std::sync::atomic::Ordering::Relaxed);
397+ if scanned != self.seen {
398+ self.seen = scanned;
399+ self.since = Instant::now();
400+ }
401+ self.since.elapsed().as_secs_f32()
402+ }
403+}
404+
372 /// A library row being dragged: the file and which of its audio streams that405 /// A library row being dragged: the file and which of its audio streams that
373 /// row is, which is the whole of what a row names. Where it lands does not406 /// row is, which is the whole of what a row names. Where it lands does not
374 /// change what is inserted.407 /// change what is inserted.
@@ -1307,10 +1340,15 @@ struct Player {
1307 /// over and what an apply acts on -- *exactly* the previewed set, never a1340 /// over and what an apply acts on -- *exactly* the previewed set, never a
1308 /// second scan at the moment of the press.1341 /// second scan at the moment of the press.
1309 silence_marks: Vec<(u32, u32)>,1342 silence_marks: Vec<(u32, u32)>,
1310- /// The levels of the last source scanned, kept so moving a threshold is1343+ /// The levels of every source scanned this session, kept so moving a
1311- /// arithmetic rather than another decode. One entry: a card is open on one1344+ /// threshold is arithmetic rather than another decode. Keyed by source and
1312- /// clip, and the next one it opens on is the next thing worth holding.1345+ /// stream, and not one entry: two films on one timeline would otherwise
1313- silence_levels: Option<(PathBuf, usize, Arc<Vec<f32>>)>,1346+ /// evict each other, and the decode being paid twice is the fifty seconds
1347+ /// this card exists to not spend.
1348+ silence_levels: HashMap<(PathBuf, usize), Arc<Vec<f32>>>,
1349+ /// The scan a worker is running for the card, if one is. `None` means the
1350+ /// card is drawing numbers it already has.
1351+ silence_scan: Option<SilenceScan>,
1314 /// Which of the card's four sliders the arrow keys and a drag move. The1352 /// Which of the card's four sliders the arrow keys and a drag move. The
1315 /// card's own focus, since nothing in it takes gpui's (ledger:182).1353 /// card's own focus, since nothing in it takes gpui's (ledger:182).
1316 color_band: usize,1354 color_band: usize,
@@ -2177,9 +2215,12 @@ impl Player {
2177 /// Either half of a take will do: the scan reads the *source*, and both2215 /// Either half of a take will do: the scan reads the *source*, and both
2178 /// halves of an A/V take name the same file.2216 /// halves of an A/V take name the same file.
2179 ///2217 ///
2180- /// The scan runs at once, so the card is never up saying nothing: a clip2218+ /// The card is up on the next frame whatever the file is: a still is
2181- /// whose source has no audio track at all is refused by name instead, and2219+ /// refused by name here, where the answer costs a look at the path, and
2182- /// the card does not open on it.2220+ /// everything the decoder has to open the file to know -- a track that is
2221+ /// not there, a read that fails -- is refused the same way when the scan
2222+ /// lands, because a fifty-second decode is not a thing to open a card
2223+ /// behind ([`Player::start_silence_scan`]).
2183 fn open_silence(&mut self, cx: &mut Context<Self>) {2224 fn open_silence(&mut self, cx: &mut Context<Self>) {
2184 if self.exporting().is_some() {2225 if self.exporting().is_some() {
2185 return;2226 return;
@@ -2194,8 +2235,26 @@ impl Player {
2194 .or_else(|| session.video_clip_at(session.now()))2235 .or_else(|| session.video_clip_at(session.now()))
2195 .map(|clip| audio_half(session, clip))2236 .map(|clip| audio_half(session, clip))
2196 {2237 {
2197- Some(clip) => {2238+ Some((lane, idx)) => {
2198- self.silence_open = Some(clip);2239+ let source = self.session.as_ref().and_then(|session| {
2240+ let clip = session.lane_clips(lane).get(idx)?;
2241+ session.sources().get(clip.source).cloned()
2242+ });
2243+ // A still is asked *before* the decoder is: handing a png to the
2244+ // mp4 demuxer answers "a box with a larger size than it", which
2245+ // is a true sentence about a container and nothing a person can
2246+ // act on. A picture has no sound for the same reason a silent
2247+ // video has none, so it is refused in the same words.
2248+ let Some(source) = source else {
2249+ cx.notify();
2250+ return;
2251+ };
2252+ if engine::is_image(&source.path) {
2253+ self.notice = Some(unscannable(lane, idx, &source.path).into());
2254+ cx.notify();
2255+ return;
2256+ }
2257+ self.silence_open = Some((lane, idx));
2199 self.silence_field = 0;2258 self.silence_field = 0;
2200 // One card at a time, the rule the other four follow.2259 // One card at a time, the rule the other four follow.
2201 self.keys_open = false;2260 self.keys_open = false;
@@ -2204,7 +2263,16 @@ impl Player {
2204 self.color_open = None;2263 self.color_open = None;
2205 self.speed_open = None;2264 self.speed_open = None;
2206 self.context_menu = None;2265 self.context_menu = None;
2207- self.scan_silences();2266+ let key = (source.path.clone(), source.audio_stream);
2267+ match scan_plan(
2268+ self.silence_levels.contains_key(&key),
2269+ self.silence_scan.as_ref().map(|scan| &scan.key),
2270+ &key,
2271+ ) {
2272+ ScanPlan::Marks => self.scan_silences(),
2273+ ScanPlan::Start => self.start_silence_scan(key, cx),
2274+ ScanPlan::Wait => {}
2275+ }
2208 }2276 }
2209 None => self.notice = Some("no clip under the playhead to scan".into()),2277 None => self.notice = Some("no clip under the playhead to scan".into()),
2210 }2278 }
@@ -2295,20 +2363,97 @@ impl Player {
2295 fn close_silence(&mut self) {2363 fn close_silence(&mut self) {
2296 self.silence_open = None;2364 self.silence_open = None;
2297 self.silence_marks.clear();2365 self.silence_marks.clear();
2366+ self.cancel_silence_scan();
2367+ }
2368+
2369+ /// Tells the worker nobody is waiting any more. It gives up at its next
2370+ /// chunk and the levels it had are dropped: half a track is not an answer,
2371+ /// and the flag stays set on the [`Arc`] the landing closure holds, which is
2372+ /// how that closure knows to keep its hands off the card.
2373+ fn cancel_silence_scan(&mut self) {
2374+ if let Some(scan) = self.silence_scan.take() {
2375+ scan.progress
2376+ .cancel
2377+ .store(true, std::sync::atomic::Ordering::Relaxed);
2378+ }
2298 }2379 }
2299 2380
2300- /// Runs the scan and replaces the preview -- never stacks on it. The decode2381+ /// Hands the decode to a worker and returns at once -- the card is drawn by
2301- /// happens once per source ([`engine::silence::levels`] is cached here), so2382+ /// the very next frame, saying it is scanning. Fifty-one seconds on a 25 GB
2302- /// every later run is the settings applied to numbers already in hand,2383+ /// film is what this used to cost on the render thread, with the card
2303- /// which is what makes moving a threshold feel like moving a slider.2384+ /// marked open and nothing on screen.
2385+ ///
2386+ /// Whatever was scanning is cancelled first: one card, one scan, and the
2387+ /// clip that has just been asked about is the one worth the disk.
2388+ fn start_silence_scan(&mut self, key: (PathBuf, usize), cx: &mut Context<Self>) {
2389+ self.cancel_silence_scan();
2390+ self.silence_marks.clear();
2391+ let progress = Arc::new(engine::silence::Progress::default());
2392+ let scan = cx.background_executor().spawn({
2393+ let (key, progress) = (key.clone(), Arc::clone(&progress));
2394+ async move { engine::silence::levels_with_progress(&key.0, key.1, &progress) }
2395+ });
2396+ let now = Instant::now();
2397+ self.silence_scan = Some(SilenceScan {
2398+ key: key.clone(),
2399+ started: now,
2400+ progress: Arc::clone(&progress),
2401+ seen: 0,
2402+ since: now,
2403+ });
2404+ cx.spawn(async move |this, cx| {
2405+ let landed = scan.await;
2406+ this.update(cx, |this, cx| {
2407+ // Cancelled means the card moved on or closed: the levels are a
2408+ // prefix of a track nobody asked about any more.
2409+ if progress.cancel.load(std::sync::atomic::Ordering::Relaxed) {
2410+ return;
2411+ }
2412+ this.silence_scan = None;
2413+ match landed {
2414+ Ok(Some(levels)) => {
2415+ this.silence_levels.insert(key.clone(), Arc::new(levels));
2416+ this.scan_silences();
2417+ }
2418+ // A source with no audio track is not one long silence: it
2419+ // is a clip this card has nothing to say about, named so the
2420+ // user knows which one it meant.
2421+ Ok(None) => {
2422+ if let Some((lane, idx)) = this.silence_open {
2423+ this.notice = Some(unscannable(lane, idx, &key.0).into());
2424+ }
2425+ this.close_silence();
2426+ }
2427+ Err(e) => {
2428+ this.close_silence();
2429+ this.notice = Some(format!("SCAN FAILED: {e}").into());
2430+ }
2431+ }
2432+ cx.notify();
2433+ })
2434+ .ok();
2435+ })
2436+ .detach();
2437+ cx.notify();
2438+ }
2439+
2440+ /// Keeps the scanning line's stall clock, for [`Player::poll_import`]'s
2441+ /// reason: sampled once per frame rather than while drawing.
2442+ fn poll_silence(&mut self) {
2443+ if let Some(scan) = &mut self.silence_scan {
2444+ scan.poll();
2445+ }
2446+ }
2447+
2448+ /// Applies the settings to levels already in hand and replaces the preview
2449+ /// -- never stacks on it. Arithmetic only: the decode is
2450+ /// [`Player::start_silence_scan`]'s and happens once per source, so every
2451+ /// run here is numbers already read, which is what makes moving a threshold
2452+ /// feel like moving a slider. A source still being scanned has no marks yet
2453+ /// and says so on the card.
2304 ///2454 ///
2305 /// Changes nothing about the project: a preview is not an edit, and no undo2455 /// Changes nothing about the project: a preview is not an edit, and no undo
2306 /// step is spent until a button is pressed.2456 /// step is spent until a button is pressed.
2307- ///
2308- /// ponytail: the first scan for a source runs on the render thread -- ~1700x
2309- /// realtime, so a ten-minute take is well under a second and an hour-long
2310- /// one would be felt. Upgrade path is the waveform's: hand it to
2311- /// `cx.background_spawn` and repaint when it lands.
2312 fn scan_silences(&mut self) {2457 fn scan_silences(&mut self) {
2313 let Some((lane, idx)) = self.silence_open else {2458 let Some((lane, idx)) = self.silence_open else {
2314 return;2459 return;
@@ -2322,44 +2467,14 @@ impl Player {
2322 }) else {2467 }) else {
2323 return;2468 return;
2324 };2469 };
2325- // A still is asked *before* the decoder is: handing a png to the mp42470+ // Nothing read yet: the worker is running and the card is drawing its
2326- // demuxer answers "a box with a larger size than it", which is a true2471+ // line. The marks arrive with the levels.
2327- // sentence about a container and nothing a person can act on. A picture2472+ let Some(levels) = self
2328- // has no sound for the same reason a silent video has none, so it is
2329- // refused in the same words.
2330- if engine::is_image(&source.path) {
2331- self.silence_open = None;
2332- self.notice = Some(unscannable(lane, idx, &source.path).into());
2333- return;
2334- }
2335- let cached = self
2336 .silence_levels2473 .silence_levels
2337- .as_ref()2474+ .get(&(source.path.clone(), source.audio_stream))
2338- .filter(|(path, stream, _)| *path == source.path && *stream == source.audio_stream)2475+ .cloned()
2339- .map(|(_, _, levels)| levels.clone());2476+ else {
2340- let levels = match cached {2477+ return;
2341- Some(levels) => levels,
2342- None => match engine::silence::levels(&source.path, source.audio_stream) {
2343- Ok(Some(levels)) => {
2344- let levels = Arc::new(levels);
2345- self.silence_levels =
2346- Some((source.path.clone(), source.audio_stream, levels.clone()));
2347- levels
2348- }
2349- // A source with no audio track is not one long silence: it is a
2350- // clip this card has nothing to say about, named so the user
2351- // knows which one it meant.
2352- Ok(None) => {
2353- self.silence_open = None;
2354- self.notice = Some(unscannable(lane, idx, &source.path).into());
2355- return;
2356- }
2357- Err(e) => {
2358- self.silence_open = None;
2359- self.notice = Some(format!("SCAN FAILED: {e}").into());
2360- return;
2361- }
2362- },
2363 };2478 };
2364 self.silence_marks = engine::silence::timeline_regions(2479 self.silence_marks = engine::silence::timeline_regions(
2365 &clip,2480 &clip,
@@ -3694,8 +3809,8 @@ impl Player {
3694 self.waves.clear();3809 self.waves.clear();
3695 self.streams.clear();3810 self.streams.clear();
3696 self.sizes.clear();3811 self.sizes.clear();
3697- // Scanned off a source that is not in the library any more.3812+ // Scanned off sources that are not in the library any more.
3698- self.silence_levels = None;3813+ self.silence_levels.clear();
3699 // Every gesture in flight, dropped for `reset_after_reseek`'s reason3814 // Every gesture in flight, dropped for `reset_after_reseek`'s reason
3700 // (it drops the trim below): a drag holds a bar, a clip or a band of a3815 // (it drops the trim below): a drag holds a bar, a clip or a band of a
3701 // timeline that has just stopped existing.3816 // timeline that has just stopped existing.
@@ -4558,6 +4673,7 @@ impl Render for Player {
4558 }4673 }
4559 self.poll_export();4674 self.poll_export();
4560 self.poll_import(cx);4675 self.poll_import(cx);
4676+ self.poll_silence();
4561 // Every way a source can arrive -- argv, an import, a project load --4677 // Every way a source can arrive -- argv, an import, a project load --
4562 // has been through a repaint by the time its clips are drawn, so this4678 // has been through a repaint by the time its clips are drawn, so this
4563 // is the one place that has to notice a new one.4679 // is the one place that has to notice a new one.
@@ -4588,6 +4704,10 @@ impl Render for Player {
4588 || self.seek_since.is_some()4704 || self.seek_since.is_some()
4589 || self.export.is_some()4705 || self.export.is_some()
4590 || self.importing.is_some()4706 || self.importing.is_some()
4707+ // A silence scan too: its progress and its two clocks only reach
4708+ // the screen on a repaint, and a still line is the very thing this
4709+ // card was rewritten to disprove.
4710+ || self.silence_scan.is_some()
4591 {4711 {
4592 window.request_animation_frame();4712 window.request_animation_frame();
4593 }4713 }
@@ -8266,6 +8386,22 @@ impl Player {
8266 let found = self.silence_marks.len();8386 let found = self.silence_marks.len();
8267 let secs =8387 let secs =
8268 f64::from(self.silence_marks.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;8388 f64::from(self.silence_marks.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;
8389+ // The line under the rows: where a scan still running has got to -- a
8390+ // card is up from the frame it is asked for, numbers or no numbers --
8391+ // or what the settings found in levels already read.
8392+ let status = match &self.silence_scan {
8393+ Some(scan) => silence_line(
8394+ scan.seen as f32 / 10.,
8395+ scan.progress.total.load(std::sync::atomic::Ordering::Relaxed) as f32 / 10.,
8396+ scan.started.elapsed().as_secs_f32(),
8397+ scan.since.elapsed().as_secs_f32(),
8398+ ),
8399+ None => match found {
8400+ 0 => "nothing quiet enough for long enough".to_string(),
8401+ 1 => format!("1 silence, {secs:.1}s"),
8402+ n => format!("{n} silences, {secs:.1}s"),
8403+ },
8404+ };
8269 let rows: Vec<_> = rows8405 let rows: Vec<_> = rows
8270 .into_iter()8406 .into_iter()
8271 .enumerate()8407 .enumerate()
@@ -8393,15 +8529,11 @@ impl Player {
8393 div()8529 div()
8394 .flex_none()8530 .flex_none()
8395 .px(px(6.))8531 .px(px(6.))
8396- .text_color(rgb(match found {8532+ .text_color(rgb(match (&self.silence_scan, found) {
8397- 0 => INK_DIM,8533+ (None, 1..) => ACCENT,
8398- _ => ACCENT,8534+ _ => INK_DIM,
8399 }))8535 }))
8400- .child(match found {8536+ .child(status),
8401- 0 => "nothing quiet enough for long enough".to_string(),
8402- 1 => format!("1 silence, {secs:.1}s"),
8403- n => format!("{n} silences, {secs:.1}s"),
8404- }),
8405 )8537 )
8406 .child(div().flex().gap(px(4.)).children([8538 .child(div().flex().gap(px(4.)).children([
8407 button(0, "Cut them out (enter)".into(), Self::cut_silences),8539 button(0, "Cut them out (enter)".into(), Self::cut_silences),
@@ -12739,6 +12871,54 @@ fn import_line(name: &str, stage: ImportStage, elapsed: f32, since: f32, waiting
12739 }12871 }
12740 }12872 }
12741 12873
12874+/// What opening the silence card on a source costs.
12875+#[derive(PartialEq, Eq, Debug)]
12876+enum ScanPlan {
12877+ /// Its levels are already read: the marks are arithmetic on this frame.
12878+ Marks,
12879+ /// Nothing read: a worker, and a card that says so meanwhile.
12880+ Start,
12881+ /// A worker is already reading this very source -- the other half of a take
12882+ /// names the same file, and a second card on it waits for the first read
12883+ /// rather than throwing away the minute already spent.
12884+ Wait,
12885+}
12886+
12887+/// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole
12888+/// of the cache policy, and the reason a second film does not cost the first
12889+/// one its levels: what is cached is asked per source, never "the last one".
12890+fn scan_plan(cached: bool, running: Option<&(PathBuf, usize)>, key: &(PathBuf, usize)) -> ScanPlan {
12891+ match (cached, running) {
12892+ (true, _) => ScanPlan::Marks,
12893+ (false, Some(at)) if at == key => ScanPlan::Wait,
12894+ _ => ScanPlan::Start,
12895+ }
12896+}
12897+
12898+/// What the silence card says while its worker reads. Unlike an import this
12899+/// one *has* a fraction -- a decode knows how far into the sound it has come --
12900+/// so the line is where it is up to, out of what the header claims the track is
12901+/// (`total` of 0 for a header that does not say, drawn as nothing rather than
12902+/// as a guess). Both in seconds.
12903+///
12904+/// The stall clock is [`IMPORT_STALL`]'s, for its reason: past five seconds
12905+/// without the mark moving, a line that cannot move and a line that has stopped
12906+/// look identical, and only one of them is worth words.
12907+fn silence_line(scanned: f32, total: f32, elapsed: f32, since: f32) -> String {
12908+ let far = match total > 0. {
12909+ true => format!("{} of ~{} scanned", clock(scanned), clock(total)),
12910+ false => format!("{} scanned", clock(scanned)),
12911+ };
12912+ match since >= IMPORT_STALL {
12913+ true => format!(
12914+ "SCANNING · still reading the sound — a big film is minutes of decoding, and the \
12915+ window is not frozen · {far} · {} elapsed",
12916+ clock(elapsed)
12917+ ),
12918+ false => format!("SCANNING · {far} · {} elapsed", clock(elapsed)),
12919+ }
12920+}
12921+
12742 /// How often a progress mark is worth keeping, how far back the rate is12922 /// How often a progress mark is worth keeping, how far back the rate is
12743 /// measured, and the least span that may answer at all. An export crosses12923 /// measured, and the least span that may answer at all. An export crosses
12744 /// hardware and software segments that run at different speeds, so the12924 /// hardware and software segments that run at different speeds, so the
@@ -12816,8 +12996,8 @@ mod tests {
12816 ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,12996 ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,
12817 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,12997 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,
12818 note_progress, px_along,12998 note_progress, px_along,
12819- IMPORT_STALL, Import, ImportStage, SEEK_STALL, import_line, read_ahead, seek_line,12999+ IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanPlan, SilenceScan, import_line,
12820- stash_or_write,13000+ read_ahead, scan_plan, seek_line, silence_line, stash_or_write,
12821 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,13001 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
12822 trimmed_clip, unscannable,13002 trimmed_clip, unscannable,
12823 visible_slice,13003 visible_slice,
@@ -16178,6 +16358,97 @@ mod tests {
16178 assert!(line.contains("0:09 elapsed"), "{line}");16358 assert!(line.contains("0:09 elapsed"), "{line}");
16179 }16359 }
16180 16360
16361+ /// The silence card's own state machine, driven the way a repaint drives
16362+ /// it: a worker moves its mark, the poll notices and restarts the stall
16363+ /// clock, and the line says a read has stopped only when it actually has.
16364+ /// The card is up through all of it -- that is the whole change, since the
16365+ /// same decode used to run on the render thread and hold the frame for
16366+ /// fifty-one seconds on a 25 GB film.
16367+ #[test]
16368+ fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() {
16369+ use std::sync::Arc;
16370+ use std::sync::atomic::Ordering::Relaxed;
16371+ let progress = Arc::new(engine::silence::Progress::default());
16372+ // Two hours and eight minutes, as the header claims it.
16373+ progress.total.store(7680, Relaxed);
16374+ let started = Instant::now() - Duration::from_secs(9);
16375+ let mut scan = SilenceScan {
16376+ key: (PathBuf::from("/films/A Film.mkv"), 0),
16377+ started,
16378+ progress: Arc::clone(&progress),
16379+ seen: 0,
16380+ since: started,
16381+ };
16382+ // Nine seconds and the mark has not moved: past the wait a person
16383+ // tolerates, so the line stops pretending it is a progress line.
16384+ let since = scan.poll();
16385+ assert!(since > IMPORT_STALL, "{since}");
16386+ let stalled = silence_line(0., 768., 9., since);
16387+ assert!(stalled.contains("still reading the sound"), "{stalled}");
16388+ assert!(stalled.contains("not frozen"), "{stalled}");
16389+ assert!(stalled.contains("0:00 of ~12:48 scanned"), "{stalled}");
16390+ assert!(stalled.contains("0:09 elapsed"), "{stalled}");
16391+ // The worker reports, and the stall clock restarts even though the
16392+ // elapsed one does not -- the two clocks' whole distinction.
16393+ let mut last = 0;
16394+ for deci in [83, 1_140, 4_002] {
16395+ progress.scanned.store(deci, Relaxed);
16396+ let since = scan.poll();
16397+ assert!(since < IMPORT_STALL, "{since}");
16398+ assert!(scan.seen > last, "{} after {last}", scan.seen);
16399+ last = scan.seen;
16400+ }
16401+ let moving = silence_line(scan.seen as f32 / 10., 768., 9., 0.2);
16402+ assert_eq!(moving, "SCANNING · 6:40 of ~12:48 scanned · 0:09 elapsed");
16403+ assert!(!moving.contains("still"), "{moving}");
16404+ // A header that does not say how long the track is says nothing rather
16405+ // than guessing at it.
16406+ let unknown = silence_line(60., 0., 61., 0.2);
16407+ assert_eq!(unknown, "SCANNING · 1:00 scanned · 1:01 elapsed");
16408+ // A mark that comes back the same is not the same fact as one that
16409+ // moved: the poll only restarts on a change.
16410+ let held = scan.since;
16411+ scan.poll();
16412+ assert_eq!(scan.since, held, "an unchanged mark must not reset it");
16413+ }
16414+
16415+ /// The cache is per source, which is what stops two films thrashing each
16416+ /// other's fifty seconds: A, then B, then A again is *one* decode of A.
16417+ /// And a source already being read is waited for rather than read twice --
16418+ /// both halves of an A/V take name the same file.
16419+ #[test]
16420+ fn a_second_film_does_not_cost_the_first_one_its_levels() {
16421+ let (a, b) = (
16422+ (PathBuf::from("/films/a.mkv"), 0),
16423+ (PathBuf::from("/films/b.mkv"), 0),
16424+ );
16425+ let mut cache: std::collections::HashMap<(PathBuf, usize), ()> =
16426+ std::collections::HashMap::new();
16427+ let mut started = Vec::new();
16428+ // What a card open does, three times over, with the worker landing
16429+ // between each: plan, and start what the plan says to start.
16430+ for key in [&a, &b, &a] {
16431+ match scan_plan(cache.contains_key(key), None, key) {
16432+ ScanPlan::Start => {
16433+ started.push(key.clone());
16434+ cache.insert(key.clone(), ());
16435+ }
16436+ ScanPlan::Marks => {}
16437+ ScanPlan::Wait => unreachable!("nothing is running"),
16438+ }
16439+ }
16440+ assert_eq!(started, vec![a.clone(), b.clone()], "A was decoded twice");
16441+ // The single-slot cache this replaced would have evicted A when B
16442+ // landed; both are held.
16443+ assert!(cache.contains_key(&a) && cache.contains_key(&b));
16444+ // A scan in flight on the same source is joined, not restarted -- and
16445+ // one on another source is not waited for.
16446+ assert_eq!(scan_plan(false, Some(&a), &a), ScanPlan::Wait);
16447+ assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start);
16448+ // Levels in hand beat a worker either way: the marks are arithmetic.
16449+ assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks);
16450+ }
16451+
16181 /// The read-ahead is a *cache warmer* and nothing else: whatever it did or16452 /// The read-ahead is a *cache warmer* and nothing else: whatever it did or
16182 /// failed to do, the import that follows lands exactly the rows, lengths16453 /// failed to do, the import that follows lands exactly the rows, lengths
16183 /// and refusals it landed before there was a worker at all.16454 /// and refusals it landed before there was a worker at all.
@@ -17713,7 +17984,8 @@ fn main() {
17713 // there was a choice about it.17984 // there was a choice about it.
17714 silence_dbfs: true,17985 silence_dbfs: true,
17715 silence_marks: Vec::new(),17986 silence_marks: Vec::new(),
17716- silence_levels: None,17987+ silence_levels: HashMap::new(),
17988+ silence_scan: None,
17717 color_open: None,17989 color_open: None,
17718 color_band: 0,17990 color_band: 0,
17719 color_dragging: false,17991 color_dragging: false,
crates/engine/src/silence.rsmodified+77 -0
@@ -15,6 +15,7 @@
15 //! apart.15 //! apart.
16 16
17 use std::path::Path;17 use std::path::Path;
18+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
18 19
19 use crate::AudioSession;20 use crate::AudioSession;
20 use crate::project::{Clip, Speed};21 use crate::project::{Clip, Speed};
@@ -73,12 +74,50 @@ impl Default for Settings {
73 /// settings above are all applied to the result and none of them needs a second74 /// settings above are all applied to the result and none of them needs a second
74 /// decode.75 /// decode.
75 pub fn levels(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<Vec<f32>>> {76 pub fn levels(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<Vec<f32>>> {
77+ levels_with_progress(path, stream, &Progress::default())
78+}
79+
80+/// What a running [`levels_with_progress`] says about itself while it runs, and
81+/// the one word that stops it. Tenths of a second rather than a fraction: how
82+/// far into the sound the decode has come is a fact the moment it starts, where
83+/// a percentage needs a duration the header does not always carry.
84+///
85+/// Shared by an [`Arc`](std::sync::Arc) between the worker and whatever is
86+/// drawing it, the way an export's progress is.
87+#[derive(Default, Debug)]
88+pub struct Progress {
89+ /// Source time decoded so far, in tenths of a second. Only ever grows.
90+ pub scanned: AtomicU64,
91+ /// What the header claims the whole track is, in tenths of a second, or `0`
92+ /// for a file that does not say -- the estimate is drawn as `~` and a `0`
93+ /// is drawn as nothing rather than as a lie.
94+ pub total: AtomicU64,
95+ /// Set by whoever asked for the scan when nobody is waiting for it any
96+ /// more. The loop below reads it once per chunk and gives up there; the
97+ /// decoder behind it stops with the dropped receiver.
98+ pub cancel: AtomicBool,
99+}
100+
101+/// [`levels`] reporting where it has come to and stopping when it is told to.
102+///
103+/// A **cancelled scan returns what it had got to**, which is a prefix of the
104+/// track and not an answer: the caller sets [`Progress::cancel`], so the caller
105+/// is the one that must check it before believing the result.
106+pub fn levels_with_progress(
107+ path: impl AsRef<Path>,
108+ stream: usize,
109+ progress: &Progress,
110+) -> crate::Result<Option<Vec<f32>>> {
76 let sources = [(path.as_ref().to_path_buf(), stream)];111 let sources = [(path.as_ref().to_path_buf(), stream)];
77 let Some((meta, rx)) =112 let Some((meta, rx)) =
78 AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?113 AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?
79 else {114 else {
80 return Ok(None);115 return Ok(None);
81 };116 };
117+ let rate = f64::from(meta.sample_rate).max(1.);
118+ if let Some(total) = meta.total_samples {
119+ progress.total.store((total as f64 / rate * 10.) as u64, Relaxed);
120+ }
82 // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not,121 // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not,
83 // and a rounded window drifts a bucket every few seconds over a long take.122 // and a rounded window drifts a bucket every few seconds over a long take.
84 let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC);123 let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC);
@@ -87,6 +126,14 @@ pub fn levels(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<Vec
87 // mean square, kept in f64 because a loud minute is millions of terms.126 // mean square, kept in f64 because a loud minute is millions of terms.
88 let mut sums: Vec<(f64, u64)> = Vec::new();127 let mut sums: Vec<(f64, u64)> = Vec::new();
89 for chunk in rx {128 for chunk in rx {
129+ // Once per chunk, not per sample: a cancelled scan may run one block
130+ // longer, and a progress line moves in blocks anyway.
131+ if progress.cancel.load(Relaxed) {
132+ break;
133+ }
134+ progress
135+ .scanned
136+ .store((chunk.start_sample as f64 / rate * 10.) as u64, Relaxed);
90 for (frame, values) in chunk.samples.chunks(channels).enumerate() {137 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
91 let window = ((chunk.start_sample + frame as u64) as f64 / per_window) as usize;138 let window = ((chunk.start_sample + frame as u64) as f64 / per_window) as usize;
92 if window >= sums.len() {139 if window >= sums.len() {
@@ -289,6 +336,36 @@ mod tests {
289 );336 );
290 }337 }
291 338
339+ /// Reporting where a scan has got to changes nothing about what it finds,
340+ /// and the word that stops one is heard: the numbers are the plain scan's
341+ /// to the last window, the header's duration reaches the card, and a scan
342+ /// cancelled before its first chunk comes back with a prefix instead of a
343+ /// track -- which is why a cancelled scan is never cached.
344+ #[test]
345+ fn a_scan_that_reports_itself_finds_exactly_what_the_plain_one_does() {
346+ use super::{Progress, levels_with_progress};
347+ use std::sync::atomic::Ordering::Relaxed;
348+ let progress = Progress::default();
349+ let watched = levels_with_progress(asset("test_av.mp4"), 0, &progress)
350+ .expect("open")
351+ .expect("test_av.mp4 has an audio track");
352+ let plain = levels(asset("test_av.mp4"), 0).expect("open").expect("audio");
353+ assert_eq!(watched, plain, "a watched scan must find the same levels");
354+ // Five seconds of fixture, in tenths, from the header and from the last
355+ // chunk the loop saw.
356+ assert_eq!(progress.total.load(Relaxed), 50);
357+ assert!(progress.scanned.load(Relaxed) > 0);
358+ assert!(progress.scanned.load(Relaxed) <= progress.total.load(Relaxed));
359+ // Cancelled at the door: the loop gives up at its first chunk, the
360+ // receiver is dropped and the decoder behind it stops with it.
361+ let stopped = Progress::default();
362+ stopped.cancel.store(true, Relaxed);
363+ let partial = levels_with_progress(asset("test_av.mp4"), 0, &stopped)
364+ .expect("open")
365+ .expect("audio");
366+ assert!(partial.len() < plain.len(), "{} windows", partial.len());
367+ }
368+
292 /// The three settings, each one visible on its own: a quiet run shorter369 /// The three settings, each one visible on its own: a quiet run shorter
293 /// than `min_silence` is forgiven, `padding` shrinks what is left at both370 /// than `min_silence` is forgiven, `padding` shrinks what is left at both
294 /// ends, and a kept sliver shorter than `min_keep` joins the silences371 /// ends, and a kept sliver shorter than `min_keep` joins the silences