forge
Explore
Log in

Don't you dare go Hollow

The card is up on the next frame and reads the film behind it

Browse files at this commit

a2e41540874ce0d04e6fecaf29bd6c8ea161f544Ahmet Kaan GümüşParent: 734ca14
  • perf
    • the card is up on the next frame and reads the film behind it
Show full message
⚡ perf(silence): the card is up on the next frame and reads the film behind it

Pressing Silence decoded the whole audio track on the render thread -- 51 s
of dead window on a 25 GB film, with the card marked open and nothing drawn.
The decode is a worker now: the card paints at once and says where the read
has got to, out of what the header claims the track is, with the import
line's two clocks and its stall wording when the mark stops moving.

Closing the card, or opening it on another source, cancels the read at its
next chunk; a cancelled scan is never cached, since half a track is not an
answer. The levels cache is keyed per source and stream instead of holding
the last one only, so two films on a timeline stop paying each other's
decode -- A, B, A again is one decode of A.

What a scan finds is unchanged: 1393 silences at the shipped defaults on the
same film, and the nudges after it lands are the arithmetic they always were.
crates/app/src/main.rsmodified+341 -68
@@ -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.
@@ -1300,10 +1333,15 @@ struct Player {
1300 /// over and what an apply acts on -- *exactly* the previewed set, never a1333 /// over and what an apply acts on -- *exactly* the previewed set, never a
1301 /// second scan at the moment of the press.1334 /// second scan at the moment of the press.
1302 silence_marks: Vec<(u32, u32)>,1335 silence_marks: Vec<(u32, u32)>,
1303- /// The levels of the last source scanned, kept so moving a threshold is1336+ /// The levels of every source scanned this session, kept so moving a
1304- /// arithmetic rather than another decode. One entry: a card is open on one1337+ /// threshold is arithmetic rather than another decode. Keyed by source and
1305- /// clip, and the next one it opens on is the next thing worth holding.1338+ /// stream, and not one entry: two films on one timeline would otherwise
1306- silence_levels: Option<(PathBuf, usize, Arc<Vec<f32>>)>,1339+ /// evict each other, and the decode being paid twice is the fifty seconds
1340+ /// this card exists to not spend.
1341+ silence_levels: HashMap<(PathBuf, usize), Arc<Vec<f32>>>,
1342+ /// The scan a worker is running for the card, if one is. `None` means the
1343+ /// card is drawing numbers it already has.
1344+ silence_scan: Option<SilenceScan>,
1307 /// Which of the card's four sliders the arrow keys and a drag move. The1345 /// Which of the card's four sliders the arrow keys and a drag move. The
1308 /// card's own focus, since nothing in it takes gpui's (ledger:182).1346 /// card's own focus, since nothing in it takes gpui's (ledger:182).
1309 color_band: usize,1347 color_band: usize,
@@ -2111,9 +2149,12 @@ impl Player {
2111 /// Either half of a take will do: the scan reads the *source*, and both2149 /// Either half of a take will do: the scan reads the *source*, and both
2112 /// halves of an A/V take name the same file.2150 /// halves of an A/V take name the same file.
2113 ///2151 ///
2114- /// The scan runs at once, so the card is never up saying nothing: a clip2152+ /// The card is up on the next frame whatever the file is: a still is
2115- /// whose source has no audio track at all is refused by name instead, and2153+ /// refused by name here, where the answer costs a look at the path, and
2116- /// the card does not open on it.2154+ /// everything the decoder has to open the file to know -- a track that is
2155+ /// not there, a read that fails -- is refused the same way when the scan
2156+ /// lands, because a fifty-second decode is not a thing to open a card
2157+ /// behind ([`Player::start_silence_scan`]).
2117 fn open_silence(&mut self, cx: &mut Context<Self>) {2158 fn open_silence(&mut self, cx: &mut Context<Self>) {
2118 if self.exporting().is_some() {2159 if self.exporting().is_some() {
2119 return;2160 return;
@@ -2128,8 +2169,26 @@ impl Player {
2128 .or_else(|| session.video_clip_at(session.now()))2169 .or_else(|| session.video_clip_at(session.now()))
2129 .map(|clip| audio_half(session, clip))2170 .map(|clip| audio_half(session, clip))
2130 {2171 {
2131- Some(clip) => {2172+ Some((lane, idx)) => {
2132- self.silence_open = Some(clip);2173+ let source = self.session.as_ref().and_then(|session| {
2174+ let clip = session.lane_clips(lane).get(idx)?;
2175+ session.sources().get(clip.source).cloned()
2176+ });
2177+ // A still is asked *before* the decoder is: handing a png to the
2178+ // mp4 demuxer answers "a box with a larger size than it", which
2179+ // is a true sentence about a container and nothing a person can
2180+ // act on. A picture has no sound for the same reason a silent
2181+ // video has none, so it is refused in the same words.
2182+ let Some(source) = source else {
2183+ cx.notify();
2184+ return;
2185+ };
2186+ if engine::is_image(&source.path) {
2187+ self.notice = Some(unscannable(lane, idx, &source.path).into());
2188+ cx.notify();
2189+ return;
2190+ }
2191+ self.silence_open = Some((lane, idx));
2133 self.silence_field = 0;2192 self.silence_field = 0;
2134 // One card at a time, the rule the other four follow.2193 // One card at a time, the rule the other four follow.
2135 self.keys_open = false;2194 self.keys_open = false;
@@ -2138,7 +2197,16 @@ impl Player {
2138 self.color_open = None;2197 self.color_open = None;
2139 self.speed_open = None;2198 self.speed_open = None;
2140 self.context_menu = None;2199 self.context_menu = None;
2141- self.scan_silences();2200+ let key = (source.path.clone(), source.audio_stream);
2201+ match scan_plan(
2202+ self.silence_levels.contains_key(&key),
2203+ self.silence_scan.as_ref().map(|scan| &scan.key),
2204+ &key,
2205+ ) {
2206+ ScanPlan::Marks => self.scan_silences(),
2207+ ScanPlan::Start => self.start_silence_scan(key, cx),
2208+ ScanPlan::Wait => {}
2209+ }
2142 }2210 }
2143 None => self.notice = Some("no clip under the playhead to scan".into()),2211 None => self.notice = Some("no clip under the playhead to scan".into()),
2144 }2212 }
@@ -2229,20 +2297,97 @@ impl Player {
2229 fn close_silence(&mut self) {2297 fn close_silence(&mut self) {
2230 self.silence_open = None;2298 self.silence_open = None;
2231 self.silence_marks.clear();2299 self.silence_marks.clear();
2300+ self.cancel_silence_scan();
2301+ }
2302+
2303+ /// Tells the worker nobody is waiting any more. It gives up at its next
2304+ /// chunk and the levels it had are dropped: half a track is not an answer,
2305+ /// and the flag stays set on the [`Arc`] the landing closure holds, which is
2306+ /// how that closure knows to keep its hands off the card.
2307+ fn cancel_silence_scan(&mut self) {
2308+ if let Some(scan) = self.silence_scan.take() {
2309+ scan.progress
2310+ .cancel
2311+ .store(true, std::sync::atomic::Ordering::Relaxed);
2312+ }
2232 }2313 }
2233 2314
2234- /// Runs the scan and replaces the preview -- never stacks on it. The decode2315+ /// Hands the decode to a worker and returns at once -- the card is drawn by
2235- /// happens once per source ([`engine::silence::levels`] is cached here), so2316+ /// the very next frame, saying it is scanning. Fifty-one seconds on a 25 GB
2236- /// every later run is the settings applied to numbers already in hand,2317+ /// film is what this used to cost on the render thread, with the card
2237- /// which is what makes moving a threshold feel like moving a slider.2318+ /// marked open and nothing on screen.
2319+ ///
2320+ /// Whatever was scanning is cancelled first: one card, one scan, and the
2321+ /// clip that has just been asked about is the one worth the disk.
2322+ fn start_silence_scan(&mut self, key: (PathBuf, usize), cx: &mut Context<Self>) {
2323+ self.cancel_silence_scan();
2324+ self.silence_marks.clear();
2325+ let progress = Arc::new(engine::silence::Progress::default());
2326+ let scan = cx.background_executor().spawn({
2327+ let (key, progress) = (key.clone(), Arc::clone(&progress));
2328+ async move { engine::silence::levels_with_progress(&key.0, key.1, &progress) }
2329+ });
2330+ let now = Instant::now();
2331+ self.silence_scan = Some(SilenceScan {
2332+ key: key.clone(),
2333+ started: now,
2334+ progress: Arc::clone(&progress),
2335+ seen: 0,
2336+ since: now,
2337+ });
2338+ cx.spawn(async move |this, cx| {
2339+ let landed = scan.await;
2340+ this.update(cx, |this, cx| {
2341+ // Cancelled means the card moved on or closed: the levels are a
2342+ // prefix of a track nobody asked about any more.
2343+ if progress.cancel.load(std::sync::atomic::Ordering::Relaxed) {
2344+ return;
2345+ }
2346+ this.silence_scan = None;
2347+ match landed {
2348+ Ok(Some(levels)) => {
2349+ this.silence_levels.insert(key.clone(), Arc::new(levels));
2350+ this.scan_silences();
2351+ }
2352+ // A source with no audio track is not one long silence: it
2353+ // is a clip this card has nothing to say about, named so the
2354+ // user knows which one it meant.
2355+ Ok(None) => {
2356+ if let Some((lane, idx)) = this.silence_open {
2357+ this.notice = Some(unscannable(lane, idx, &key.0).into());
2358+ }
2359+ this.close_silence();
2360+ }
2361+ Err(e) => {
2362+ this.close_silence();
2363+ this.notice = Some(format!("SCAN FAILED: {e}").into());
2364+ }
2365+ }
2366+ cx.notify();
2367+ })
2368+ .ok();
2369+ })
2370+ .detach();
2371+ cx.notify();
2372+ }
2373+
2374+ /// Keeps the scanning line's stall clock, for [`Player::poll_import`]'s
2375+ /// reason: sampled once per frame rather than while drawing.
2376+ fn poll_silence(&mut self) {
2377+ if let Some(scan) = &mut self.silence_scan {
2378+ scan.poll();
2379+ }
2380+ }
2381+
2382+ /// Applies the settings to levels already in hand and replaces the preview
2383+ /// -- never stacks on it. Arithmetic only: the decode is
2384+ /// [`Player::start_silence_scan`]'s and happens once per source, so every
2385+ /// run here is numbers already read, which is what makes moving a threshold
2386+ /// feel like moving a slider. A source still being scanned has no marks yet
2387+ /// and says so on the card.
2238 ///2388 ///
2239 /// Changes nothing about the project: a preview is not an edit, and no undo2389 /// Changes nothing about the project: a preview is not an edit, and no undo
2240 /// step is spent until a button is pressed.2390 /// step is spent until a button is pressed.
2241- ///
2242- /// ponytail: the first scan for a source runs on the render thread -- ~1700x
2243- /// realtime, so a ten-minute take is well under a second and an hour-long
2244- /// one would be felt. Upgrade path is the waveform's: hand it to
2245- /// `cx.background_spawn` and repaint when it lands.
2246 fn scan_silences(&mut self) {2391 fn scan_silences(&mut self) {
2247 let Some((lane, idx)) = self.silence_open else {2392 let Some((lane, idx)) = self.silence_open else {
2248 return;2393 return;
@@ -2256,44 +2401,14 @@ impl Player {
2256 }) else {2401 }) else {
2257 return;2402 return;
2258 };2403 };
2259- // A still is asked *before* the decoder is: handing a png to the mp42404+ // Nothing read yet: the worker is running and the card is drawing its
2260- // demuxer answers "a box with a larger size than it", which is a true2405+ // line. The marks arrive with the levels.
2261- // sentence about a container and nothing a person can act on. A picture2406+ let Some(levels) = self
2262- // has no sound for the same reason a silent video has none, so it is
2263- // refused in the same words.
2264- if engine::is_image(&source.path) {
2265- self.silence_open = None;
2266- self.notice = Some(unscannable(lane, idx, &source.path).into());
2267- return;
2268- }
2269- let cached = self
2270 .silence_levels2407 .silence_levels
2271- .as_ref()2408+ .get(&(source.path.clone(), source.audio_stream))
2272- .filter(|(path, stream, _)| *path == source.path && *stream == source.audio_stream)2409+ .cloned()
2273- .map(|(_, _, levels)| levels.clone());2410+ else {
2274- let levels = match cached {2411+ return;
2275- Some(levels) => levels,
2276- None => match engine::silence::levels(&source.path, source.audio_stream) {
2277- Ok(Some(levels)) => {
2278- let levels = Arc::new(levels);
2279- self.silence_levels =
2280- Some((source.path.clone(), source.audio_stream, levels.clone()));
2281- levels
2282- }
2283- // A source with no audio track is not one long silence: it is a
2284- // clip this card has nothing to say about, named so the user
2285- // knows which one it meant.
2286- Ok(None) => {
2287- self.silence_open = None;
2288- self.notice = Some(unscannable(lane, idx, &source.path).into());
2289- return;
2290- }
2291- Err(e) => {
2292- self.silence_open = None;
2293- self.notice = Some(format!("SCAN FAILED: {e}").into());
2294- return;
2295- }
2296- },
2297 };2412 };
2298 self.silence_marks = engine::silence::timeline_regions(2413 self.silence_marks = engine::silence::timeline_regions(
2299 &clip,2414 &clip,
@@ -3628,8 +3743,8 @@ impl Player {
3628 self.waves.clear();3743 self.waves.clear();
3629 self.streams.clear();3744 self.streams.clear();
3630 self.sizes.clear();3745 self.sizes.clear();
3631- // Scanned off a source that is not in the library any more.3746+ // Scanned off sources that are not in the library any more.
3632- self.silence_levels = None;3747+ self.silence_levels.clear();
3633 // Every gesture in flight, dropped for `reset_after_reseek`'s reason3748 // Every gesture in flight, dropped for `reset_after_reseek`'s reason
3634 // (it drops the trim below): a drag holds a bar, a clip or a band of a3749 // (it drops the trim below): a drag holds a bar, a clip or a band of a
3635 // timeline that has just stopped existing.3750 // timeline that has just stopped existing.
@@ -4485,6 +4600,7 @@ impl Render for Player {
4485 self.pump(window);4600 self.pump(window);
4486 self.poll_export();4601 self.poll_export();
4487 self.poll_import(cx);4602 self.poll_import(cx);
4603+ self.poll_silence();
4488 // Every way a source can arrive -- argv, an import, a project load --4604 // Every way a source can arrive -- argv, an import, a project load --
4489 // has been through a repaint by the time its clips are drawn, so this4605 // has been through a repaint by the time its clips are drawn, so this
4490 // is the one place that has to notice a new one.4606 // is the one place that has to notice a new one.
@@ -4515,6 +4631,10 @@ impl Render for Player {
4515 || self.pending_seek4631 || self.pending_seek
4516 || self.export.is_some()4632 || self.export.is_some()
4517 || self.importing.is_some()4633 || self.importing.is_some()
4634+ // A silence scan too: its progress and its two clocks only reach
4635+ // the screen on a repaint, and a still line is the very thing this
4636+ // card was rewritten to disprove.
4637+ || self.silence_scan.is_some()
4518 {4638 {
4519 window.request_animation_frame();4639 window.request_animation_frame();
4520 }4640 }
@@ -8165,6 +8285,22 @@ impl Player {
8165 let found = self.silence_marks.len();8285 let found = self.silence_marks.len();
8166 let secs =8286 let secs =
8167 f64::from(self.silence_marks.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;8287 f64::from(self.silence_marks.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;
8288+ // The line under the rows: where a scan still running has got to -- a
8289+ // card is up from the frame it is asked for, numbers or no numbers --
8290+ // or what the settings found in levels already read.
8291+ let status = match &self.silence_scan {
8292+ Some(scan) => silence_line(
8293+ scan.seen as f32 / 10.,
8294+ scan.progress.total.load(std::sync::atomic::Ordering::Relaxed) as f32 / 10.,
8295+ scan.started.elapsed().as_secs_f32(),
8296+ scan.since.elapsed().as_secs_f32(),
8297+ ),
8298+ None => match found {
8299+ 0 => "nothing quiet enough for long enough".to_string(),
8300+ 1 => format!("1 silence, {secs:.1}s"),
8301+ n => format!("{n} silences, {secs:.1}s"),
8302+ },
8303+ };
8168 let rows: Vec<_> = rows8304 let rows: Vec<_> = rows
8169 .into_iter()8305 .into_iter()
8170 .enumerate()8306 .enumerate()
@@ -8292,15 +8428,11 @@ impl Player {
8292 div()8428 div()
8293 .flex_none()8429 .flex_none()
8294 .px(px(6.))8430 .px(px(6.))
8295- .text_color(rgb(match found {8431+ .text_color(rgb(match (&self.silence_scan, found) {
8296- 0 => INK_DIM,8432+ (None, 1..) => ACCENT,
8297- _ => ACCENT,8433+ _ => INK_DIM,
8298 }))8434 }))
8299- .child(match found {8435+ .child(status),
8300- 0 => "nothing quiet enough for long enough".to_string(),
8301- 1 => format!("1 silence, {secs:.1}s"),
8302- n => format!("{n} silences, {secs:.1}s"),
8303- }),
8304 )8436 )
8305 .child(div().flex().gap(px(4.)).children([8437 .child(div().flex().gap(px(4.)).children([
8306 button(0, "Cut them out (enter)".into(), Self::cut_silences),8438 button(0, "Cut them out (enter)".into(), Self::cut_silences),
@@ -12593,6 +12725,54 @@ fn import_line(name: &str, stage: ImportStage, elapsed: f32, since: f32, waiting
12593 }12725 }
12594 }12726 }
12595 12727
12728+/// What opening the silence card on a source costs.
12729+#[derive(PartialEq, Eq, Debug)]
12730+enum ScanPlan {
12731+ /// Its levels are already read: the marks are arithmetic on this frame.
12732+ Marks,
12733+ /// Nothing read: a worker, and a card that says so meanwhile.
12734+ Start,
12735+ /// A worker is already reading this very source -- the other half of a take
12736+ /// names the same file, and a second card on it waits for the first read
12737+ /// rather than throwing away the minute already spent.
12738+ Wait,
12739+}
12740+
12741+/// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole
12742+/// of the cache policy, and the reason a second film does not cost the first
12743+/// one its levels: what is cached is asked per source, never "the last one".
12744+fn scan_plan(cached: bool, running: Option<&(PathBuf, usize)>, key: &(PathBuf, usize)) -> ScanPlan {
12745+ match (cached, running) {
12746+ (true, _) => ScanPlan::Marks,
12747+ (false, Some(at)) if at == key => ScanPlan::Wait,
12748+ _ => ScanPlan::Start,
12749+ }
12750+}
12751+
12752+/// What the silence card says while its worker reads. Unlike an import this
12753+/// one *has* a fraction -- a decode knows how far into the sound it has come --
12754+/// so the line is where it is up to, out of what the header claims the track is
12755+/// (`total` of 0 for a header that does not say, drawn as nothing rather than
12756+/// as a guess). Both in seconds.
12757+///
12758+/// The stall clock is [`IMPORT_STALL`]'s, for its reason: past five seconds
12759+/// without the mark moving, a line that cannot move and a line that has stopped
12760+/// look identical, and only one of them is worth words.
12761+fn silence_line(scanned: f32, total: f32, elapsed: f32, since: f32) -> String {
12762+ let far = match total > 0. {
12763+ true => format!("{} of ~{} scanned", clock(scanned), clock(total)),
12764+ false => format!("{} scanned", clock(scanned)),
12765+ };
12766+ match since >= IMPORT_STALL {
12767+ true => format!(
12768+ "SCANNING · still reading the sound — a big film is minutes of decoding, and the \
12769+ window is not frozen · {far} · {} elapsed",
12770+ clock(elapsed)
12771+ ),
12772+ false => format!("SCANNING · {far} · {} elapsed", clock(elapsed)),
12773+ }
12774+}
12775+
12596 /// How often a progress mark is worth keeping, how far back the rate is12776 /// How often a progress mark is worth keeping, how far back the rate is
12597 /// measured, and the least span that may answer at all. An export crosses12777 /// measured, and the least span that may answer at all. An export crosses
12598 /// hardware and software segments that run at different speeds, so the12778 /// hardware and software segments that run at different speeds, so the
@@ -12670,7 +12850,8 @@ mod tests {
12670 ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,12850 ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,
12671 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,12851 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,
12672 note_progress, px_along,12852 note_progress, px_along,
12673- IMPORT_STALL, Import, ImportStage, import_line, read_ahead,12853+ IMPORT_STALL, Import, ImportStage, ScanPlan, SilenceScan, import_line, read_ahead,
12854+ scan_plan, silence_line,
12674 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,12855 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
12675 trimmed_clip, unscannable,12856 trimmed_clip, unscannable,
12676 visible_slice,12857 visible_slice,
@@ -15967,6 +16148,97 @@ mod tests {
15967 assert_eq!(import.since, held, "an unchanged stage must not reset it");16148 assert_eq!(import.since, held, "an unchanged stage must not reset it");
15968 }16149 }
15969 16150
16151+ /// The silence card's own state machine, driven the way a repaint drives
16152+ /// it: a worker moves its mark, the poll notices and restarts the stall
16153+ /// clock, and the line says a read has stopped only when it actually has.
16154+ /// The card is up through all of it -- that is the whole change, since the
16155+ /// same decode used to run on the render thread and hold the frame for
16156+ /// fifty-one seconds on a 25 GB film.
16157+ #[test]
16158+ fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() {
16159+ use std::sync::Arc;
16160+ use std::sync::atomic::Ordering::Relaxed;
16161+ let progress = Arc::new(engine::silence::Progress::default());
16162+ // Two hours and eight minutes, as the header claims it.
16163+ progress.total.store(7680, Relaxed);
16164+ let started = Instant::now() - Duration::from_secs(9);
16165+ let mut scan = SilenceScan {
16166+ key: (PathBuf::from("/films/A Film.mkv"), 0),
16167+ started,
16168+ progress: Arc::clone(&progress),
16169+ seen: 0,
16170+ since: started,
16171+ };
16172+ // Nine seconds and the mark has not moved: past the wait a person
16173+ // tolerates, so the line stops pretending it is a progress line.
16174+ let since = scan.poll();
16175+ assert!(since > IMPORT_STALL, "{since}");
16176+ let stalled = silence_line(0., 768., 9., since);
16177+ assert!(stalled.contains("still reading the sound"), "{stalled}");
16178+ assert!(stalled.contains("not frozen"), "{stalled}");
16179+ assert!(stalled.contains("0:00 of ~12:48 scanned"), "{stalled}");
16180+ assert!(stalled.contains("0:09 elapsed"), "{stalled}");
16181+ // The worker reports, and the stall clock restarts even though the
16182+ // elapsed one does not -- the two clocks' whole distinction.
16183+ let mut last = 0;
16184+ for deci in [83, 1_140, 4_002] {
16185+ progress.scanned.store(deci, Relaxed);
16186+ let since = scan.poll();
16187+ assert!(since < IMPORT_STALL, "{since}");
16188+ assert!(scan.seen > last, "{} after {last}", scan.seen);
16189+ last = scan.seen;
16190+ }
16191+ let moving = silence_line(scan.seen as f32 / 10., 768., 9., 0.2);
16192+ assert_eq!(moving, "SCANNING · 6:40 of ~12:48 scanned · 0:09 elapsed");
16193+ assert!(!moving.contains("still"), "{moving}");
16194+ // A header that does not say how long the track is says nothing rather
16195+ // than guessing at it.
16196+ let unknown = silence_line(60., 0., 61., 0.2);
16197+ assert_eq!(unknown, "SCANNING · 1:00 scanned · 1:01 elapsed");
16198+ // A mark that comes back the same is not the same fact as one that
16199+ // moved: the poll only restarts on a change.
16200+ let held = scan.since;
16201+ scan.poll();
16202+ assert_eq!(scan.since, held, "an unchanged mark must not reset it");
16203+ }
16204+
16205+ /// The cache is per source, which is what stops two films thrashing each
16206+ /// other's fifty seconds: A, then B, then A again is *one* decode of A.
16207+ /// And a source already being read is waited for rather than read twice --
16208+ /// both halves of an A/V take name the same file.
16209+ #[test]
16210+ fn a_second_film_does_not_cost_the_first_one_its_levels() {
16211+ let (a, b) = (
16212+ (PathBuf::from("/films/a.mkv"), 0),
16213+ (PathBuf::from("/films/b.mkv"), 0),
16214+ );
16215+ let mut cache: std::collections::HashMap<(PathBuf, usize), ()> =
16216+ std::collections::HashMap::new();
16217+ let mut started = Vec::new();
16218+ // What a card open does, three times over, with the worker landing
16219+ // between each: plan, and start what the plan says to start.
16220+ for key in [&a, &b, &a] {
16221+ match scan_plan(cache.contains_key(key), None, key) {
16222+ ScanPlan::Start => {
16223+ started.push(key.clone());
16224+ cache.insert(key.clone(), ());
16225+ }
16226+ ScanPlan::Marks => {}
16227+ ScanPlan::Wait => unreachable!("nothing is running"),
16228+ }
16229+ }
16230+ assert_eq!(started, vec![a.clone(), b.clone()], "A was decoded twice");
16231+ // The single-slot cache this replaced would have evicted A when B
16232+ // landed; both are held.
16233+ assert!(cache.contains_key(&a) && cache.contains_key(&b));
16234+ // A scan in flight on the same source is joined, not restarted -- and
16235+ // one on another source is not waited for.
16236+ assert_eq!(scan_plan(false, Some(&a), &a), ScanPlan::Wait);
16237+ assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start);
16238+ // Levels in hand beat a worker either way: the marks are arithmetic.
16239+ assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks);
16240+ }
16241+
15970 /// The read-ahead is a *cache warmer* and nothing else: whatever it did or16242 /// The read-ahead is a *cache warmer* and nothing else: whatever it did or
15971 /// failed to do, the import that follows lands exactly the rows, lengths16243 /// failed to do, the import that follows lands exactly the rows, lengths
15972 /// and refusals it landed before there was a worker at all.16244 /// and refusals it landed before there was a worker at all.
@@ -17501,7 +17773,8 @@ fn main() {
17501 // there was a choice about it.17773 // there was a choice about it.
17502 silence_dbfs: true,17774 silence_dbfs: true,
17503 silence_marks: Vec::new(),17775 silence_marks: Vec::new(),
17504- silence_levels: None,17776+ silence_levels: HashMap::new(),
17777+ silence_scan: None,
17505 color_open: None,17778 color_open: None,
17506 color_band: 0,17779 color_band: 0,
17507 color_dragging: false,17780 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