forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

beats.rs201 lines, 7.9 KiBHistoryRawDownload
1//! Mark the beats: the card that listens to a sound clip and puts a comment marker on each
2//! beat, so a cut can be made on the music. The listening runs on the background executor
3//! the way a silence scan does; the markers land in one undo step.
4
5use crate::export_ui::audio_half;
6use crate::*;
7use engine::beats::{self, Found};
8use std::time::{Duration, Instant};
9
10/// What the card's three choices mean: every beat, every second beat, every fourth beat.
11pub(crate) const BEAT_EVERY: [usize; 3] = [1, 2, 4];
12
13impl Player {
14 /// Opens the mark-the-beats card on the sound of the clip the hand is on, or the one under
15 /// the playhead. A picture with no sound says so and opens nothing.
16 pub(crate) fn open_beats(&mut self, cx: &mut Context<Self>) {
17 if self.exporting().is_some() {
18 return;
19 }
20 let Some(session) = &self.session else {
21 self.notify_user("Nothing to mark — no file open".into());
22 cx.notify();
23 return;
24 };
25 let anchor = self
26 .selected
27 .anchor()
28 .or_else(|| session.video_clip_at(session.now()));
29 let Some(anchor) = anchor else {
30 self.notify_user("No clip is picked or under the playhead, so there is no sound to mark".into());
31 cx.notify();
32 return;
33 };
34 let (lane, idx) = audio_half(session, anchor);
35 let has_sound = session.lane_clips(lane).get(idx).and_then(|clip| {
36 let source = session.sources().get(clip.source)?;
37 Some(!engine::is_image(&source.path))
38 });
39 if has_sound != Some(true) {
40 self.notify_user("The clip has no sound, so it has no beats to mark".into());
41 cx.notify();
42 return;
43 }
44 self.close_other_cards();
45 self.beats_open = Some((lane, idx));
46 self.beats_scan = None;
47 self.context_menu = None;
48 cx.notify();
49 }
50
51 /// Whether the selected clip (or the sound half of a picture) has a sound to listen to.
52 pub(crate) fn beats_available(&self) -> bool {
53 let Some(session) = &self.session else {
54 return false;
55 };
56 let anchor = self
57 .selected
58 .anchor()
59 .or_else(|| session.video_clip_at(session.now()));
60 let Some(anchor) = anchor else {
61 return false;
62 };
63 let (lane, idx) = audio_half(session, anchor);
64 session
65 .lane_clips(lane)
66 .get(idx)
67 .and_then(|clip| session.sources().get(clip.source))
68 .is_some_and(|source| !engine::is_image(&source.path))
69 }
70
71 /// Takes the section down. A listening that is still running lands into nothing.
72 pub(crate) fn close_beats(&mut self) {
73 self.beats_open = None;
74 self.beats_scan = None;
75 }
76
77 /// Starts listening to the clip the card is on. The analysis is off the UI thread; the card
78 /// shows its clock until it lands.
79 pub(crate) fn start_beats(&mut self, cx: &mut Context<Self>) {
80 let Some((lane, idx)) = self.beats_open else {
81 return;
82 };
83 if self.beats_scan.is_some() {
84 return;
85 }
86 let fps = self.fps;
87 let found = self.session.as_ref().and_then(|session| {
88 let clip = session.lane_clips(lane).get(idx)?.clone();
89 let source = session.sources().get(clip.source)?.clone();
90 Some((clip, source))
91 });
92 let Some((clip, source)) = found else {
93 self.close_beats();
94 self.notify_user("The clip is gone, so there is no sound to mark".into());
95 cx.notify();
96 return;
97 };
98 let every = BEAT_EVERY[self.beats_every.min(BEAT_EVERY.len() - 1)];
99 let range = (f64::from(clip.in_frame) / fps, f64::from(clip.out_frame) / fps);
100 self.beats_scan = Some(Instant::now());
101 let task = cx.background_executor().spawn(async move {
102 beats::detect(&source.path, source.audio_stream, range)
103 });
104 cx.spawn(async move |this, cx| {
105 let landed = task.await;
106 this.update(cx, |this, cx| {
107 this.land_beats(lane, idx, every, fps, landed, cx);
108 })
109 .ok();
110 })
111 .detach();
112 // The card's clock: a repaint a quarter second while the listening runs, and none after.
113 cx.spawn(async move |this, cx| {
114 loop {
115 cx.background_executor().timer(Duration::from_millis(250)).await;
116 let running = this
117 .update(cx, |this, cx| {
118 cx.notify();
119 this.beats_scan.is_some()
120 })
121 .unwrap_or(false);
122 if !running {
123 break;
124 }
125 }
126 })
127 .detach();
128 cx.notify();
129 }
130
131 /// Puts the beats the analysis found on the clip, replacing the clip's earlier beat markers,
132 /// in one undo step, and says what it did.
133 fn land_beats(
134 &mut self,
135 lane: Lane,
136 idx: usize,
137 every: usize,
138 fps: f64,
139 landed: engine::Result<Found>,
140 cx: &mut Context<Self>,
141 ) {
142 // Closed while listening: the result is for a card nobody has now.
143 if self.beats_scan.take().is_none() {
144 return;
145 }
146 self.beats_last = Some(match &landed {
147 Ok(Found::Beats { bpm, times }) => {
148 let n = beats::every_nth(times, every).len();
149 format!("Last run: {n} beats at {bpm:.0} BPM")
150 }
151 Ok(Found::NoAudio) | Ok(Found::Silent) => "Last run: no sound to mark".to_string(),
152 Ok(Found::NoPulse) => "Last run: no steady beat found".to_string(),
153 Err(_) => "Last run: failed".to_string(),
154 });
155 match landed {
156 Ok(Found::Beats { bpm, times }) => {
157 let Some(session) = self.session.as_mut() else {
158 cx.notify();
159 return;
160 };
161 let Some(clip) = session.lane_clips(lane).get(idx).cloned() else {
162 self.beats_last = Some("Last run: the clip is gone".to_string());
163 self.notify_user("The clip is gone; no markers were added".into());
164 cx.notify();
165 return;
166 };
167 let frames = beats::timeline_beats(&clip, fps, &beats::every_nth(&times, every));
168 session.begin_batch();
169 let old = beats::beat_marker_indices(session.markers(), clip.start, clip.end());
170 for &i in old.iter().rev() {
171 session.remove_marker(i);
172 }
173 let mut refused = None;
174 for &frame in &frames {
175 if let Err(e) = session.add_marker(beats::beat_marker(frame)) {
176 refused = Some(e);
177 break;
178 }
179 }
180 session.end_batch();
181 if let Some(e) = refused {
182 self.notify_user(format!("Marking the beats failed — {e}").into());
183 } else if frames.is_empty() {
184 self.notify_user("No beat falls inside this clip".into());
185 } else {
186 self.notify_user_action(
187 format!("Marked {} beats at {:.0} BPM", frames.len(), bpm).into(),
188 ToastAction::Undo,
189 );
190 }
191 }
192 Ok(Found::NoAudio) => self.notify_user("The clip has no sound, so it has no beats to mark".into()),
193 Ok(Found::Silent) => self.notify_user("No beat to mark — the sound is silent".into()),
194 Ok(Found::NoPulse) => {
195 self.notify_user("No steady beat found in this sound to mark".into())
196 }
197 Err(e) => self.notify_user(format!("Marking the beats failed — {e}").into()),
198 }
199 cx.notify();
200 }
201}