forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

library_meta.rs590 lines, 23.6 KiBHistoryRawDownload
1//! What a library row is and what it says about its file.
2
3use crate::*;
4
5/// What is left on the clipboard after the library row at `removed` was taken
6/// out. A copied clip names its file by *index* into the source list
7/// (`engine::Clip::source`) and a removal renumbers that list
8/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste
9/// **a different file** -- the next one along -- over the range it was copied
10/// from.
11///
12/// An entry whose own file is gone drops out of the clipboard rather than
13/// pasting some other take down in its place; a set with even one such
14/// member is trimmed, not emptied whole, the way a lane keeps every clip a
15/// removal did not touch. Every index past `removed` moves down by one,
16/// exactly as the lanes' clips do.
17pub(crate) fn clipboard_after_remove(
18 clipboard: Vec<(Lane, Clip)>,
19 removed: usize,
20) -> Vec<(Lane, Clip)> {
21 clipboard
22 .into_iter()
23 .filter_map(|(lane, mut clip)| match clip.source.cmp(&removed) {
24 std::cmp::Ordering::Equal => None,
25 std::cmp::Ordering::Greater => {
26 clip.source -= 1;
27 Some((lane, clip))
28 }
29 std::cmp::Ordering::Less => Some((lane, clip)),
30 })
31 .collect()
32}
33
34/// One library row: a file and one of its audio streams. Plain data, planned
35/// before anything is drawn -- which rows exist at all is the branchy part.
36#[derive(Debug, PartialEq)]
37pub(crate) struct Row {
38 pub(crate) path: PathBuf,
39 pub(crate) stream: usize,
40 /// The file, plus which stream this is when the file has several.
41 pub(crate) name: String,
42 /// What the stream is, or blank for a file with a single one.
43 pub(crate) detail: String,
44 /// Why it cannot be put on this timeline, for a row that cannot: shown in
45 /// place of the length and the only thing that greys a row out.
46 pub(crate) unusable: Option<String>,
47 /// Frames of the *file*, for the length line.
48 pub(crate) frames: u32,
49 /// Index into `SOURCE_TINTS`, shared by every stream of one file: the
50 /// swatch says which file, and the lanes tint their clips the same way.
51 pub(crate) tint: usize,
52}
53
54/// Every row the library shows: one per source entry, plus one for each further
55/// audio stream those files have that no clip plays yet -- a remux with a track
56/// per language lists them all, the ones this engine cannot use greyed out
57/// rather than hidden. Streams a file has not been probed for yet simply are
58/// not there; the row for what *is* on the timeline is always there.
59///
60/// `timeline_audio` is the rate and layout of source 0's stream, which every
61/// other source must match: one output device and one copied AAC track for the
62/// whole timeline (`PlaybackSession::place_stream_at`). `None` while unknown,
63/// and then nothing is greyed for it -- the engine still refuses.
64pub(crate) fn library_rows(
65 sources: &[Source],
66 streams: &HashMap<PathBuf, Vec<StreamInfo>>,
67 decoders: &HashMap<PathBuf, Decoder>,
68 timeline_audio: Option<(u32, u16)>,
69 frames: impl Fn(&Path) -> u32,
70) -> Vec<Row> {
71 let mut rows = Vec::new();
72 for (i, source) in sources.iter().enumerate() {
73 let of_file = streams.get(&source.path).map_or(&[][..], Vec::as_slice);
74 let info = of_file.iter().find(|s| s.index == source.audio_stream);
75 let tint = sources
76 .iter()
77 .position(|s| s.path == source.path)
78 .expect("a source finds itself");
79 rows.push(Row {
80 path: source.path.clone(),
81 stream: source.audio_stream,
82 name: row_name(&source.path, source.audio_stream, of_file.len() > 1),
83 // The decoder first: it is the same for every row of a file and
84 // it is what a person opening the panel is asking about. The
85 // stream half only where there is a choice to describe -- a file
86 // with one audio track is the row it has always been, name and
87 // length, and the length is what would be squeezed out at the
88 // panel's least width.
89 detail: join_detail(
90 &decoders
91 .get(&source.path)
92 .map_or_else(|| Decoder::Pending.detail(), Decoder::detail),
93 &info
94 .filter(|_| of_file.len() > 1)
95 .map_or_else(String::new, stream_detail),
96 ),
97 // A stream already on the timeline is playing: whatever a probe
98 // would say about it now, it is usable by demonstration.
99 unusable: None,
100 frames: frames(&source.path),
101 tint,
102 });
103 // The file's other streams, listed once, right after the last entry
104 // that names the file -- so a file's rows sit together.
105 if sources[i + 1..].iter().any(|s| s.path == source.path) {
106 continue;
107 }
108 for info in of_file {
109 if sources
110 .iter()
111 .any(|s| s.path == source.path && s.audio_stream == info.index)
112 {
113 continue; // it has a row of its own above
114 }
115 rows.push(Row {
116 path: source.path.clone(),
117 stream: info.index,
118 name: row_name(&source.path, info.index, true),
119 detail: stream_detail(info),
120 unusable: unusable(info, timeline_audio),
121 frames: frames(&source.path),
122 tint,
123 });
124 }
125 }
126 disambiguate(&mut rows);
127 rows
128}
129
130/// Two files whose rows read the same word ("2026-09-09 18-05-50" twice, user
131/// 2026-09-10 -- two screen recordings) are told apart on the metadata line
132/// rather than left as a pair of identical rows: the folder they came out of
133/// when that differs, and a `#n` in arrival order when even the folder is
134/// shared. Compared on the stem, because the stem is what the row draws.
135fn disambiguate(rows: &mut [Row]) {
136 let named: Vec<(String, PathBuf)> = rows
137 .iter()
138 .map(|row| (crate::files::stem(&row.path), row.path.clone()))
139 .collect();
140 for i in 0..rows.len() {
141 let mut twins: Vec<&PathBuf> = Vec::new();
142 for (name, path) in &named {
143 if *name == named[i].0 && !twins.contains(&path) {
144 twins.push(path);
145 }
146 }
147 if twins.len() < 2 {
148 continue;
149 }
150 let folder = rows[i]
151 .path
152 .parent()
153 .and_then(Path::file_name)
154 .map(|f| f.to_string_lossy().to_string())
155 .unwrap_or_default();
156 let alone_in_it = twins
157 .iter()
158 .filter(|p| p.parent() == rows[i].path.parent())
159 .count()
160 == 1;
161 let mark = match alone_in_it && !folder.is_empty() {
162 true => folder,
163 false => format!(
164 "#{}",
165 twins
166 .iter()
167 .position(|p| **p == rows[i].path)
168 .expect("a row finds itself")
169 + 1
170 ),
171 };
172 rows[i].detail = join_detail(&rows[i].detail, &mark);
173 }
174}
175
176/// The row's second line: what the stream is and then either how long it is or
177/// why it cannot be used, with the separator only where both halves exist (a
178/// single-stream file says nothing about its stream).
179pub(crate) fn join_detail(detail: &str, tail: &str) -> String {
180 match (detail.is_empty(), tail.is_empty()) {
181 (true, _) => tail.to_string(),
182 (false, true) => detail.to_string(),
183 (false, false) => format!("{detail} · {tail}"),
184 }
185}
186
187/// How a source's decoder reads: the codec and which seat has it, or the seat
188/// alone for a still, which has no coded stream to name. The one place either
189/// answer is spelled, so a row, a transport line and a card cannot disagree.
190pub(crate) fn decode_label(codec: Option<Codec>, backend: Backend) -> String {
191 match codec {
192 Some(codec) => format!("{} · {}", codec.name(), backend.label()),
193 None => backend.label().to_string(),
194 }
195}
196
197/// What the one-shot probe said about a file: the seat it will open on, or --
198/// when the decoder itself refused -- the refusal, in the decoder's own words.
199///
200/// Three answers, not two, because "asked" and "refused" are not the same
201/// answer. Both used to be a missing entry, and a missing entry drew an empty
202/// second line -- the same line a song draws -- so a file this machine cannot
203/// decode was indistinguishable from one that needs no word at all.
204#[derive(Debug, Clone, PartialEq)]
205pub(crate) enum Decoder {
206 /// Asked and not yet answered: the probe is still walking the file. A
207 /// real wait, and one that claims nothing while it lasts.
208 Pending,
209 /// The codec (`None` for a still, which has no coded stream) and the seat
210 /// the engine picked for it.
211 Seat(Option<Codec>, Backend),
212 /// The decoder refused this file, and these are its words. Not a message
213 /// of this program's own making: the probe is `engine::decode::probe`,
214 /// and the refusal is the one opening the file would give.
215 Refused(String),
216}
217
218impl From<engine::Result<(Option<Codec>, Backend)>> for Decoder {
219 fn from(probed: engine::Result<(Option<Codec>, Backend)>) -> Self {
220 match probed {
221 Ok((codec, backend)) => Self::Seat(codec, backend),
222 Err(why) => Self::Refused(why.to_string()),
223 }
224 }
225}
226
227impl Decoder {
228 /// What the row's second line says about the file's decoder: the seat for
229 /// a file that opens, the refusal for one that does not, and nothing for a
230 /// probe still running.
231 pub(crate) fn detail(&self) -> String {
232 match self {
233 Self::Pending => String::new(),
234 Self::Seat(codec, backend) => decode_label(*codec, *backend),
235 Self::Refused(why) => why.clone(),
236 }
237 }
238}
239
240/// How a row names its file: the file alone when it has one audio stream or
241/// none, and the file plus which stream this row is when it has several --
242/// counted from 1, the way a player numbers tracks.
243pub(crate) fn row_name(path: &Path, stream: usize, several: bool) -> String {
244 match several {
245 false => file_name(path),
246 true => format!("{} [audio {}]", file_name(path), stream + 1),
247 }
248}
249
250/// What a stream is, for the row's second line: the language if the file says
251/// one, then rate and layout. A field the header does not give is left out
252/// rather than shown as a zero -- a stream we cannot parse says nothing about
253/// itself, and saying "0 Hz" would be saying something.
254pub(crate) fn stream_detail(info: &StreamInfo) -> String {
255 let mut parts: Vec<String> = Vec::new();
256 if let Some(lang) = &info.lang {
257 parts.push(lang_human(lang).to_string());
258 }
259 if info.sample_rate > 0 {
260 parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.));
261 }
262 parts.extend(layout(info.channels));
263 parts.join(" ")
264}
265
266/// How big a file is, for a person: the largest unit that keeps the figure to
267/// one decimal (`1.2 GB`, `840 MB`), bytes below a kilobyte.
268pub(crate) fn size_human(bytes: u64) -> String {
269 for (unit, per) in [("GB", 1e9), ("MB", 1e6), ("kB", 1e3)] {
270 if bytes as f64 >= per {
271 let n = bytes as f64 / per;
272 return match n >= 10. {
273 true => format!("{n:.0} {unit}"),
274 false => format!("{n:.1} {unit}"),
275 };
276 }
277 }
278 format!("{bytes} B")
279}
280
281/// A picture's height as a person names it: `1080p`, and `4K` for the 2160
282/// line, which is the one name people use for it.
283pub(crate) fn resolution_label(height: u32) -> String {
284 match height {
285 2160 => "4K".to_string(),
286 h => format!("{h}p"),
287 }
288}
289
290/// One stream's rate in the unit its size asks for: bits a second below a
291/// kilobit, kilobits below a megabit, megabits above. One track's own rate, so
292/// there is no shared unit to keep across a line of them.
293pub(crate) fn bits_label(bits: u64) -> String {
294 match bits {
295 0..1_000 => format!("{bits} b/s"),
296 1_000..1_000_000 => format!("{} kb/s", scaled(bits, 1_000.)),
297 _ => format!("{} Mb/s", scaled(bits, 1_000_000.)),
298 }
299}
300
301/// A picture track as the properties plate says it: codec, size, rate, depth
302/// and its own bitrate, each left out where the file does not state it.
303pub(crate) fn video_detail(video: &engine::VideoFacts, bitrate: Option<u64>) -> String {
304 let mut parts = vec![video.codec.name().to_string()];
305 if video.width > 0 && video.height > 0 {
306 parts.push(format!("{}×{}", video.width, video.height));
307 }
308 if let Some(fps) = video.frame_rate {
309 parts.push(format!("{} fps", crate::export_ui::fps_label(fps)));
310 }
311 if let Some(depth) = video.bit_depth {
312 parts.push(format!("{depth}-bit"));
313 }
314 if let Some(bits) = bitrate {
315 parts.push(bits_label(bits));
316 }
317 parts.join(" · ")
318}
319
320/// A sound track as the properties plate says it: codec, rate, layout, depth
321/// and its own bitrate. The codec is `"unknown"` only where the header will not
322/// name it, which says nothing and is left out.
323pub(crate) fn audio_detail(info: &StreamInfo) -> String {
324 let mut parts: Vec<String> = Vec::new();
325 if !info.codec.is_empty() && info.codec != "unknown" {
326 parts.push(info.codec.clone());
327 }
328 if info.sample_rate > 0 {
329 parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.));
330 }
331 parts.extend(layout(info.channels));
332 if let Some(depth) = info.bit_depth {
333 parts.push(format!("{depth}-bit"));
334 }
335 if let Some(bits) = info.bitrate {
336 parts.push(bits_label(bits));
337 }
338 parts.join(" · ")
339}
340
341/// What the properties plate says about a file, top to bottom: the file and its
342/// path, its container and size, then one line per picture and sound track.
343/// Rows the probe has not answered for are simply not there -- the plate fills
344/// in as the header reads, and never says "unknown".
345pub(crate) fn file_properties(
346 path: &Path,
347 facts: Option<&engine::MediaFacts>,
348 streams: &[StreamInfo],
349 rate: Option<MediaBitrate>,
350) -> Vec<(String, String)> {
351 let mut out = vec![
352 ("File".to_string(), file_name(path)),
353 ("Path".to_string(), path.display().to_string()),
354 ];
355 if let Some(container) = facts.and_then(|f| f.container.clone()) {
356 out.push(("Container".to_string(), container));
357 }
358 if let Some(bytes) = facts.and_then(|f| f.bytes) {
359 out.push((
360 "Size".to_string(),
361 match rate.and_then(|r| r.total) {
362 Some(total) => format!("{} · {}", size_human(bytes), bits_label(total)),
363 None => size_human(bytes),
364 },
365 ));
366 }
367 if let Some(video) = facts.and_then(|f| f.video.as_ref()) {
368 out.push((
369 "Video".to_string(),
370 video_detail(video, rate.and_then(|r| r.video)),
371 ));
372 }
373 for info in streams {
374 let label = match streams.len() > 1 {
375 true => format!("Audio {} of {}", info.index + 1, streams.len()),
376 false => "Audio".to_string(),
377 };
378 out.push((label, audio_detail(info)));
379 }
380 out
381}
382
383/// The plate's Copy button: the full path on the clipboard, and a toast that
384/// says so. Shared by both properties plates so the two cannot word it apart.
385pub(crate) fn copy_path_button(path: &Path, cx: &mut Context<Player>) -> AnyElement {
386 let text = path.display().to_string();
387 control(
388 "properties-copy-path",
389 0.,
390 BG_RAISED(),
391 None,
392 "Copy",
393 "copies the full path of this file".to_string(),
394 true,
395 cx.listener(move |this, _: &ClickEvent, _, cx| {
396 cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone()));
397 this.notify_user("Path copied".into());
398 cx.notify();
399 }),
400 )
401 .into_any_element()
402}
403
404impl Player {
405 /// Read each source's header once for the properties plates: container,
406 /// size, picture and track. Off the render thread like the bitrate probe
407 /// beside it, and filled the same way -- presence means "asked", and the
408 /// inner `None` is "asked, not answered yet".
409 pub(crate) fn cache_facts(&mut self, cx: &mut Context<Self>) {
410 let Some(session) = &self.session else {
411 return;
412 };
413 for path in unseen_paths(session.sources(), &self.facts) {
414 self.facts.insert(path.clone(), None);
415 let probed = cx.background_executor().spawn({
416 let path = path.clone();
417 async move { engine::probe_media(&path) }
418 });
419 cx.spawn(async move |this, cx| {
420 let probed = probed.await;
421 this.update(cx, |this, cx| {
422 this.facts.insert(path, Some(probed));
423 cx.notify();
424 })
425 .ok();
426 })
427 .detach();
428 }
429 }
430}
431
432/// A rate in the line's unit as a person reads it: one decimal above 1 of it,
433/// two below -- a 128 kbps song rounded to one decimal is "0.1", which reads as
434/// a guess where "0.13" reads as a measurement.
435///
436/// Never `0.00`: [`bits_label`] only asks for this in a unit where the number
437/// is at least 0.001 of it, so two decimals always reach it. Every rate that
438/// gets here is one the container really stated (the probe leaves out what it
439/// does not state, it never zeroes it), and a "0.00 sound" would be this card
440/// saying a track that plays is silent.
441pub(crate) fn scaled(bits: u64, per: f64) -> String {
442 let n = bits as f64 / per;
443 match n >= 1. {
444 true => format!("{n:.1}"),
445 false => format!("{n:.2}"),
446 }
447}
448
449/// A language tag as a person reads it. Everything a file writes is passed
450/// through untouched bar the one tag that is not a language: "und" is what a
451/// muxer writes when nobody said, and a row showing it verbatim names a
452/// language nobody speaks.
453pub(crate) fn lang_human(lang: &str) -> &str {
454 match lang {
455 "und" => "unknown language",
456 lang => lang,
457 }
458}
459
460pub(crate) fn layout(channels: u16) -> Option<String> {
461 match channels {
462 0 => None,
463 1 => Some("mono".to_string()),
464 2 => Some("stereo".to_string()),
465 n => Some(format!("{n} ch")),
466 }
467}
468
469/// Why a stream cannot go on this timeline, or `None` if it can. Both answers
470/// are shown: a stream nothing can be done with is listed greyed with the
471/// reason, never dropped from the list -- a file has the tracks it has, and a
472/// picker that hides them is a picker that lies.
473pub(crate) fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<String> {
474 if !info.decodable {
475 // AAC and AC-3 name themselves (`StreamInfo::codec`, which reads the
476 // stsd fourcc by hand); anything else mp4 0.14 does not parse has no
477 // name to give, and a row with no name still says why it is greyed.
478 return Some(match info.codec.as_str() {
479 "unknown" => "unsupported codec".to_string(),
480 codec => format!("{codec} is not supported"),
481 });
482 }
483 // The **layout** and not the rate, which is what the engine's own gate now
484 // asks (`PlaybackSession::import`): a stream written at another sample rate
485 // is resampled onto the timeline's at the decoder's door, so greying its row
486 // would be this picker refusing what the timeline accepts.
487 let (_, channels) = timeline_audio?;
488 (info.channels != channels).then(|| {
489 format!(
490 "the timeline is {}",
491 layout(channels).unwrap_or_else(|| "silent".to_string())
492 )
493 })
494}
495
496/// How wide the equalizer card is drawn in a window this wide: all of it bar a
497/// margin, up to [`EQ_W_MAX`]. The card is a graph, and a graph of twenty
498/// thousand hertz on 320 px spends four pixels on the octave below middle C --
499/// so it takes the room a big window has and stays inside a small one. Floored
500/// at the other cards' width, which is the last size the rows still read at.
501pub(crate) fn eq_card_w(window_w: f32, maximized: bool) -> f32 {
502 let raw = window_w - EQ_W_MARGIN;
503 if maximized {
504 // Maximized drops the [`EQ_W_MAX`] ceiling: every pixel across is
505 // frequency resolution (the doc comment above), and a maximized card
506 // is asking for exactly the room a big window has to give it.
507 raw.max(KEYS_W)
508 } else {
509 raw.clamp(KEYS_W, EQ_W_MAX)
510 }
511}
512
513/// How wide a non-EQ param card is drawn: its usual fixed width, or (when
514/// maximized) all of the window bar the same margin the EQ card gives
515/// itself -- never narrower than its own floor, so a small window's
516/// maximize is a no-op rather than a shrink.
517pub(crate) fn card_max_w(base_w: f32, maximized: bool, window_w: f32) -> f32 {
518 if maximized {
519 (window_w - EQ_W_MARGIN).max(base_w)
520 } else {
521 base_w
522 }
523}
524
525/// What the media list is given of the window. A share of it, so a narrow
526/// window gives the panel less rather than giving the picture nothing, floored
527/// where a name stops being readable and capped at a third of the window --
528/// the picture is what the program is for and keeps the majority at every size.
529pub(crate) fn library_w(window_w: f32) -> f32 {
530 (window_w * LIBRARY_FRAC)
531 .clamp(LIBRARY_MIN_W, LIBRARY_MAX_W)
532 .min(window_w / 3.)
533}
534
535/// What the window is called: the program, and what is open in it. The name is
536/// what the header shows, so an empty window says the program alone rather than
537/// "no file open — edith".
538pub(crate) fn window_title(name: &str) -> String {
539 if name == NO_FILE {
540 "edith".to_string()
541 } else {
542 format!("{name} — edith")
543 }
544}
545
546/// What the window is called once a project is in play: the same name the
547/// header bar shows (`ui::menubar::bar`), so the title and the bar never
548/// disagree. A project started or saved answers with its own name; an unsaved
549/// one is "Untitled"; with no project at all the window keeps `name`, which is
550/// the media's.
551pub(crate) fn shown_title(name: &str, project: &Path, new_project: Option<&Path>, armed: bool) -> String {
552 let project_name = match (project.as_os_str().is_empty(), new_project) {
553 (_, Some(path)) => Some(crate::files::stem(path)),
554 (true, None) => None,
555 (false, None) if armed => Some(crate::files::stem(project)),
556 (false, None) => Some("Untitled".to_string()),
557 };
558 window_title(&project_name.unwrap_or_else(|| name.to_string()))
559}
560
561/// The tint a clip from source `n` wears. Cycled rather than extended: past the
562/// palette two sources share a colour, which is a smaller lie than a fifth tint
563/// bright enough to leave the family.
564pub(crate) fn source_tint(source: usize) -> u32 {
565 SOURCE_TINTS()[source % SOURCE_TINTS().len()]
566}
567
568/// The tint of a *file*, which is what a library row is named by: the first
569/// source entry naming it, since two audio streams of one file are two sources
570/// and one colour.
571///
572/// `None` for a path no source names -- a standalone `.srt` is on nobody's
573/// timeline, and painting it with the first file's colour would say it came out
574/// of that file. No swatch says what is true: it belongs to itself.
575pub(crate) fn file_tint(sources: &[Source], path: &Path) -> Option<u32> {
576 sources
577 .iter()
578 .position(|s| s.path == path)
579 .or_else(|| {
580 // A source entry is stored symlink-resolved (`Source::new`) and a
581 // path from anywhere else -- a subtitle track, a file being
582 // dragged -- is stored as it was spelled. `edith assets/film.mkv`
583 // is one file under two spellings, and matching by spelling alone
584 // said the film had no colour. Only asked when the spellings
585 // differ, so the common paint costs no syscall.
586 let path = std::fs::canonicalize(path).ok()?;
587 sources.iter().position(|s| s.path == path)
588 })
589 .map(source_tint)
590}