forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_cards.rs410 lines, 17.6 KiBHistoryRawDownload
1//! The equalizer, speed, silence and mixer cards' numbers.
2
3use crate::*;
4
5/// How far a band may be pushed either way, in dB. The engine clamps nothing
6/// here -- it will filter whatever it is given -- so this is a UI decision:
7/// past about this a peaking band stops sounding like tone and starts sounding
8/// like a fault.
9pub(crate) const EQ_GAIN_LIMIT: f32 = 12.;
10
11/// One dB per keystroke, which is roughly the smallest step anyone hears on a
12/// single band.
13pub(crate) const EQ_STEP: f32 = 1.;
14
15/// A twentieth of real time per keystroke, in the thousandths a [`Speed`] is
16/// held in: fine enough to creep up on a rate, coarse enough that the whole
17/// range is eighty presses and not eight hundred -- and it divides 1000, so
18/// stepping from anywhere lands on exactly 1.00x on the way past.
19pub(crate) const SPEED_STEP: i32 = 50;
20
21/// The rates the card's buttons offer, so the ones people actually name are one
22/// click and not a drag. Real time is among them: it is the reset.
23pub(crate) const SPEED_PRESETS: [u16; 6] = [250, 500, 1000, 1500, 2000, 4000];
24
25/// A rate from a number of thousandths that may have run off either end -- what
26/// a keystroke and a drag both produce. Clamped, not refused: a hand pushing
27/// past the limit means "as far as it goes", exactly as a trim does.
28pub(crate) fn speed_at(permille: i32) -> Speed {
29 Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16)
30}
31
32/// How far a ramp key's speed moves per press of its stepper: a quarter of real
33/// time, the same quarter the bar's lowest rate is.
34pub(crate) const RAMP_KEY_STEP: i32 = 250;
35
36/// The ramp shapes the speed card and the palette offer, each laid across the clip's
37/// own length on the timeline.
38#[derive(Clone, Copy, PartialEq, Eq, Debug)]
39pub(crate) enum RampPreset {
40 /// Real time easing up to double.
41 Up,
42 /// Double easing down to real time.
43 Down,
44 /// Slow, then fast through the middle, then slow: the classic speed ramp.
45 SlowFastSlow,
46 /// Fast, then slow through the middle, then fast: the hero shot.
47 FastSlowFast,
48}
49
50impl RampPreset {
51 pub(crate) const ALL: [RampPreset; 4] = [
52 RampPreset::Up,
53 RampPreset::Down,
54 RampPreset::SlowFastSlow,
55 RampPreset::FastSlowFast,
56 ];
57
58 /// The chip's face on the card.
59 pub(crate) fn label(self) -> &'static str {
60 match self {
61 RampPreset::Up => "Speed up",
62 RampPreset::Down => "Slow down",
63 RampPreset::SlowFastSlow => "Fast in the middle",
64 RampPreset::FastSlowFast => "Slow in the middle",
65 }
66 }
67
68 /// The keys of the shape over a clip `frames` timeline frames long. `None` when the
69 /// clip is too short to hold the shape's keys one frame apart.
70 pub(crate) fn keys(self, frames: u32) -> Option<Vec<engine::project::SpeedKey>> {
71 self.shape().keys(frames)
72 }
73
74 /// The engine's shape this chip lays: the same four, named there so the MCP can take them too.
75 pub(crate) fn shape(self) -> engine::project::SpeedRampShape {
76 use engine::project::SpeedRampShape as Shape;
77 match self {
78 RampPreset::Up => Shape::SpeedUp,
79 RampPreset::Down => Shape::SlowDown,
80 RampPreset::SlowFastSlow => Shape::FastMiddle,
81 RampPreset::FastSlowFast => Shape::SlowMiddle,
82 }
83 }
84}
85
86/// `keys` with a key of `speed` at clip frame `at`: one already there is replaced,
87/// else the new one is slotted in order. `None` when the ramp is full
88/// ([`engine::project::MAX_SPEED_KEYS`]) and `at` is a new frame.
89pub(crate) fn ramp_with_key(
90 keys: &[engine::project::SpeedKey],
91 at: u32,
92 speed: Speed,
93) -> Option<Vec<engine::project::SpeedKey>> {
94 let mut out = keys.to_vec();
95 match out.iter().position(|k| k.at >= at) {
96 Some(i) if out[i].at == at => out[i].speed = speed,
97 _ if out.len() >= engine::project::MAX_SPEED_KEYS => return None,
98 Some(i) => out.insert(i, engine::project::SpeedKey { at, speed }),
99 None => out.push(engine::project::SpeedKey { at, speed }),
100 }
101 Some(out)
102}
103
104/// `keys` without the `i`th; the last key out leaves no ramp at all.
105pub(crate) fn ramp_without_key(
106 keys: &[engine::project::SpeedKey],
107 i: usize,
108) -> Vec<engine::project::SpeedKey> {
109 let mut out = keys.to_vec();
110 if i < out.len() {
111 out.remove(i);
112 }
113 out
114}
115
116/// `keys` with the `i`th key's speed moved by `steps` of [`RAMP_KEY_STEP`], clamped to
117/// what a [`Speed`] holds.
118pub(crate) fn ramp_key_stepped(
119 keys: &[engine::project::SpeedKey],
120 i: usize,
121 steps: i32,
122) -> Vec<engine::project::SpeedKey> {
123 let mut out = keys.to_vec();
124 if let Some(k) = out.get_mut(i) {
125 k.speed = speed_at(i32::from(k.speed.permille()) + steps * RAMP_KEY_STEP);
126 }
127 out
128}
129
130/// The speed curve of a ramp as the card draws it: `n + 1` points across the clip's
131/// `frames`, x the fraction of the way along and y the speed's place on the speed bar
132/// (log scale, real time mid-height), so the card's curve and its bar read alike. A
133/// clip without a ramp draws its constant speed as a level line.
134pub(crate) fn ramp_curve(
135 keys: &[engine::project::SpeedKey],
136 constant: Speed,
137 frames: u32,
138 n: usize,
139) -> Vec<(f32, f32)> {
140 let n = n.max(1);
141 (0..=n)
142 .map(|i| {
143 let x = i as f32 / n as f32;
144 let at = (x * frames as f32).round() as u32;
145 let speed = match keys.is_empty() {
146 true => constant,
147 false => engine::project::ramp_speed_at(keys, at),
148 };
149 (x, crate::player::cards::speed_fraction(f32::from(speed.permille())))
150 })
151 .collect()
152}
153
154/// A clip's speed as its box wears it: `2×` for a constant one, the ramp's keys joined
155/// by arrows (`1×→2×→1×`) for a ramp, and only its two ends and a count once it has more
156/// than three keys. `None` for a clip at real time with no ramp.
157pub(crate) fn speed_chip_text(clip: &Clip) -> Option<String> {
158 if clip.speed_keys.is_empty() {
159 return (!clip.speed.is_normal()).then(|| crate::ui::cards::speed_text(clip.speed));
160 }
161 let at = |k: &engine::project::SpeedKey| crate::ui::cards::speed_text(k.speed);
162 let keys = &clip.speed_keys;
163 Some(match keys.as_slice() {
164 [only] => at(only),
165 [a, b] => format!("{}→{}", at(a), at(b)),
166 [a, b, c] => format!("{}→{}→{}", at(a), at(b), at(c)),
167 [first, .., last] => format!("{}→{} ({} keys)", at(first), at(last), keys.len()),
168 [] => return None,
169 })
170}
171
172/// The silence card's rows, in the order it lists them: how wide the apply
173/// reaches, the threshold and the unit it is read in, the three durations a
174/// scan is told, and the rate the speed-up plays at. What `silence_field`
175/// indexes and what [`Player::nudge_silence`] moves.
176pub(crate) const SILENCE_ROWS: usize = 7;
177
178/// How wide a jumpcut reaches. A ripple used to be the whole timeline's
179/// business and nothing else; it is a *choice* now, because a podcast track's
180/// silences are not the music track's business -- and the choice has to be on
181/// screen, because "everything after this moved" is not a thing to discover
182/// afterwards.
183#[derive(Clone, Copy, PartialEq, Eq, Debug)]
184pub(crate) enum Scope {
185 /// The lanes of the take the scanned clip belongs to: its picture and its
186 /// sound stay one take, and nothing else moves. The default, because a clip
187 /// picked on screen is what a person means by "this".
188 Take,
189 /// That clip's lane, alone. Refused by the engine, by name, while the take
190 /// has a half elsewhere -- detaching is how a person says they mean it.
191 Track,
192 /// Every lane, which is what a ripple always was and what the timeline-wide
193 /// jumpcut still is.
194 Everything,
195}
196
197/// The order the card cycles them in.
198pub(crate) const SCOPES: [Scope; 3] = [Scope::Take, Scope::Track, Scope::Everything];
199
200impl Scope {
201 /// What the row says, given the lanes it works out to: the *names* of the
202 /// tracks, because "this take" means nothing until it says which two.
203 pub(crate) fn label(self, lanes: &[Lane]) -> String {
204 let named = lanes
205 .iter()
206 .map(|l| l.label())
207 .collect::<Vec<_>>()
208 .join("+");
209 match self {
210 Scope::Take => format!("this clip ({named})"),
211 Scope::Track => format!("this track ({named})"),
212 Scope::Everything => "the whole timeline".to_string(),
213 }
214 }
215}
216
217/// One press of a nudge key on each kind of row: a dB on the threshold, a
218/// twentieth of a second on the three durations, and the speed card's own step
219/// on the rate.
220pub(crate) const SILENCE_DB_STEP: f32 = 1.;
221pub(crate) const SILENCE_SECS_STEP: f64 = 0.05;
222
223/// How far each of them may be pushed. UI decisions, all of them: the engine
224/// takes any finite number, but a forgiveness of ten seconds finds nothing in a
225/// talking head. The threshold reaches full scale, which calls a whole take
226/// silent -- that is a thing someone may want to ask for (the preview on the
227/// lane says what it would cost before anything is cut), so the top is 0 rather
228/// than a number this card picked for them.
229pub(crate) const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.);
230pub(crate) const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.);
231
232/// One press of a nudge key on the mix card, in dB: the step every fader and
233/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone
234/// hears as a move -- and it lands on round numbers, so a track set by ear
235/// still reads as a number a person would say.
236pub(crate) const MIX_DB_STEP: f32 = 1.;
237
238/// The mix card's rows below the faders: the limiter's ceiling and its switch.
239/// One fader per audio track comes first, however many there are.
240pub(crate) const MIX_MASTER_ROWS: usize = 2;
241
242/// The speed-up rate is bounded *below* by real time: a "speed-up" that slows
243/// the silence down would make the timeline longer, which is the one thing
244/// neither button may do. The top is [`Speed::MAX`].
245pub(crate) fn silence_rate(permille: i32) -> Speed {
246 speed_at(permille.clamp(
247 i32::from(Speed::NORMAL.permille()) + SPEED_STEP,
248 i32::from(Speed::MAX.permille()),
249 ))
250}
251
252/// The graph's frequency axis: the range an ear works in, and the range every
253/// band a file can carry sits inside. Log-spaced, so an octave is an octave
254/// wherever it falls.
255pub(crate) const EQ_FREQ_LOW: f32 = 20.;
256pub(crate) const EQ_FREQ_HIGH: f32 = 20_000.;
257
258/// The curve box, docked: a 140 px plot with the knob room above and below it
259/// (the strip for "Play to see sound" over the plot, the frequency labels under).
260/// Tall enough that 1 dB is a visible move at the ±12 dB axis, and the card scrolls
261/// in a 360 px window.
262pub(crate) const EQ_GRAPH_H: f32 = 182.;
263
264/// The curve box maximized: 1 dB and a semitone-ish band of frequency both
265/// read as more pixels than the docked floor spends on them -- the same
266/// curve, the same ±12 dB axis and the same 20 Hz-20 kHz sweep, just spread
267/// over more of the vertical resolution a maximized card borrows from the
268/// bench/ledger rows below the picture ([`crate::ui::stance::below_picture_floor`]).
269pub(crate) const EQ_GRAPH_MAX_H: f32 = 320.;
270
271/// The graph's own height for the card's current size: the docked floor, or
272/// the maximized card's own taller box -- never a CSS scale of the same
273/// pixels, an actually taller curve with more room per decibel and per
274/// decade.
275pub(crate) fn eq_graph_h(maximized: bool) -> f32 {
276 if maximized {
277 EQ_GRAPH_MAX_H
278 } else {
279 EQ_GRAPH_H
280 }
281}
282
283/// How wide the equalizer card is allowed to get. It is the one card that is a
284/// *graph*: every pixel across is frequency resolution, and at the 320 px the
285/// other cards use, a third of an octave was a couple of pixels. Past this the
286/// curve stops gaining anything and the card starts reading as a wall.
287pub(crate) const EQ_W_MAX: f32 = 720.;
288
289/// The gap the card leaves either side of it, so it reads as a card on a scrim
290/// rather than as a second window: it takes the width it can get inside that.
291pub(crate) const EQ_W_MARGIN: f32 = 32.;
292
293pub(crate) const EQ_BANDS_MAX: usize = engine::eq::MAX_BANDS;
294
295/// One press of the frequency keys, as a factor: a sixth of an octave, so a
296/// band walks the whole axis in about sixty presses and still lands close
297/// enough to a named frequency to aim at one.
298pub(crate) const EQ_FREQ_STEP: f32 = 1.122_462;
299
300/// One press of the Q keys, as a factor, and the range they move in. Below the
301/// bottom a peak is barely a peak any more; above the top it is a whistle on
302/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside
303/// them, so nothing a file carries has to be dragged into range first.
304pub(crate) const EQ_Q_STEP: f32 = 1.25;
305pub(crate) const EQ_Q_LOW: f32 = 0.3;
306pub(crate) const EQ_Q_HIGH: f32 = 12.;
307
308/// How many points the curve is drawn from. One per ~3 px across the card:
309/// past that the line is smooth and the extra biquad evaluations are wasted.
310pub(crate) const EQ_CURVE_STEPS: usize = 96;
311
312/// A band's handle on the curve. Only the dot -- what is *grabbed* is the whole
313/// graph (the nearest band along the frequency axis), so the target is the box.
314pub(crate) const EQ_HANDLE: f32 = 10.;
315
316/// A band's hit area on the curve: 24 px ([`crate::layout::HIT_MIN`], WCAG
317/// 2.5.8) centred on the dot, so the point is found by aim alone. The dot is
318/// drawn [`EQ_HANDLE`] wide inside it; the rest is a target, not a drawing.
319pub(crate) const EQ_HIT: f32 = crate::layout::HIT_MIN;
320
321/// The frequencies the graph names, so the curve can be read as a curve *of
322/// something*. The two ends label themselves at the edges.
323pub(crate) const EQ_TICKS: [(f32, &str); 5] = [
324 (20., "20 Hz"),
325 (100., "100"),
326 (1000., "1k"),
327 (10000., "10k"),
328 (20000., "20k"),
329];
330
331/// The gains the graph rules a line across, besides the 0 dB one it already
332/// had: half way to each limit, so a boost can be read as "about six" without
333/// counting pixels. The limits themselves are the box's own edges and are
334/// named at the corners instead.
335pub(crate) const EQ_DB_GRID: [f32; 2] = [6., -6.];
336
337/// How wide an end tick's own label box has to be so "20 Hz" reads as one
338/// line rather than wrapping onto two ("20" over "Hz") -- driven live and
339/// found doing exactly that at a fixed 24 px box once the end ticks were
340/// anchored to the graph's edge instead of centred on it (the anchor alone
341/// was not the whole fix). Sized off the label's own character count at the
342/// size it is actually drawn, using the list-truncation ladder's already
343/// -calibrated characters-to-pixels ratio ([`crate::layout::LIST_CHAR_W`] at
344/// [`crate::ui::type_scale::CHORD_METADATA_MIN_PX`]) rather than a second
345/// magic pixel count -- so a future type-scale bump (this one already moved
346/// once this session) widens the box along with the text instead of
347/// re-wrapping it.
348pub(crate) fn eq_tick_end_w(label: &str, text_px: f32) -> f32 {
349 label.chars().count() as f32 * crate::layout::LIST_CHAR_W
350 / crate::ui::type_scale::CHORD_METADATA_MIN_PX
351 * text_px
352}
353
354#[cfg(test)]
355mod eq_graph_maximize_tests {
356 use super::*;
357
358 /// D2's regression class: the maximized card revealed LESS than docked
359 /// at the same bench, because the graph claimed a fixed slice (a flat
360 /// `EQ_GRAPH_MAX_H`) that left nothing for the rows below it, forcing a
361 /// scroll docked never needed at the same bench. This binary has no
362 /// `TestAppContext`, so it cannot read the flex layout gpui actually
363 /// paints back -- this is a value-level pin on the two numbers the fix
364 /// (`crates/app/src/ui/cards.rs`'s `graph_maximized` branch, `flex_1()`
365 /// between a floor and a ceiling rather than a fixed height) depends on,
366 /// not a substitute for driving a maximize at a small bench: the
367 /// maximized graph's floor must be the *same* constant docked draws its
368 /// fixed height at (so maximized can never show less graph than docked,
369 /// whatever room is left over for the graph to grow into), and that
370 /// floor must not exceed its own ceiling (an inverted `min_h`/`max_h`
371 /// clamp is a layout-time panic, not a compile-time one).
372 #[test]
373 fn maximized_graph_floor_matches_docked_and_never_exceeds_its_own_ceiling() {
374 assert_eq!(
375 eq_graph_h(false),
376 EQ_GRAPH_H,
377 "docked height must be the floor maximized also uses"
378 );
379 const { assert!(EQ_GRAPH_H <= EQ_GRAPH_MAX_H) };
380 }
381}
382
383#[cfg(test)]
384mod eq_tick_end_w_tests {
385 use super::*;
386
387 /// The defect measured live: a fixed 24 px box wrapped "20 Hz" (5 chars)
388 /// at the dark theme's 13 px end-tick size. The derived width must clear
389 /// that box, and must grow, not shrink, if a future scale bump raises
390 /// the size fed in.
391 #[test]
392 fn wide_enough_for_the_widest_end_label_and_grows_with_the_type_scale() {
393 let dark_w = eq_tick_end_w("20 Hz", crate::ui::type_scale::CHORD_METADATA_MIN_PX);
394 assert!(dark_w > 24., "{dark_w} must clear the old fixed box");
395 let bumped_w = eq_tick_end_w("20 Hz", crate::ui::type_scale::CHORD_METADATA_MIN_PX + 4.);
396 assert!(bumped_w > dark_w);
397 }
398}
399
400/// How many played samples one spectrum frame is transformed from. A power of
401/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz
402/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough
403/// (21 ms) that the analyser moves with the music.
404pub(crate) const EQ_FFT: usize = 1024;
405
406/// The level range the analyser is drawn across, floor to ceiling in dBFS: the
407/// bottom of the box is silence and the top is a bin at -12 dBFS, which is
408/// about where a mixed track's loudest band sits. A look, not a measurement --
409/// the numbers on the axis are the curve's dB, never the analyser's.
410pub(crate) const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.);