forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

look.rs2675 lines, 108.9 KiBHistoryRawDownload
1//! Look tools: timeline text and one clip's full description.
2//!
3//! `timeline` is the agent's main "screen" (MCP.md section 4.3). `clip_info`
4//! describes one clip in full. Both answer in text first and in
5//! `structuredContent` second.
6
7use serde_json::{json, Value};
8
9use engine::decode::{viz_style, VIZ_FAST};
10use engine::duck::Duck;
11use engine::eq::BandKind;
12use engine::project::{Edge, Lane, LaneKind, Title, TrimWalls};
13use engine::scale::FitPolicy;
14use engine::color::ColorKey;
15use engine::transform::{OpacityKey, TransformKey};
16use engine::effects::Effect;
17use engine::{Clip, PlaybackSession};
18
19use super::edit::audio_tracks;
20use super::edit_fx::{place_word, timeline_of, title_name};
21use crate::parse;
22use crate::server::{opt_str, tri, Reply, Server, Tool};
23
24/// Brief-mode text cap, in bytes (MCP.md section 3.3).
25const BRIEF_CAP: usize = 4096;
26/// Bytes kept free in a truncated lane for its "… N more clips" line.
27const MORE_RESERVE: usize = 48;
28/// Clips a lane lists in brief mode, and clips on one `page` of a lane.
29const CLIPS_PER_PAGE: usize = 40;
30const VIZ_STYLES: [&str; 4] = ["fill", "ribbon", "ring", "wave"];
31
32const TIME_DOC: &str = "A time: 450f (frames), 15.0s or 15 (seconds), 01:02.500 (MM:SS.fff), \
3300:00:15:00 (timecode at the project frame rate), or end.";
34
35const TIMELINE_DOC: &str = "The timeline as text: one block per lane, one line per clip with its \
36address (LANE@START), timeline span, source file and in/out frames, and any effect flags. \
37Also lists lane gain and pan, mute/hide/lock state, and the gap count per media lane. \
38Use range to read a stretch, and clip_info for everything about one clip.";
39
40const CLIP_INFO_DOC: &str = "Everything about one clip: its lane and address, timeline span, source \
41file and in/out frames, speed (a speed ramp lists every key, in clip time), reverse, gain and its \
42volume envelope (every gain key), pan, pitch, deinterlace, fades, dissolve, fit, visualizer, EQ bands, \
43colour, transform, link-group members, and how far each edge can be trimmed. With `at` (a timeline time inside the clip) it also answers match frame: the source file, its src:N number and the source time shown on that frame.";
44
45pub fn tools() -> Vec<Tool> {
46 vec![
47 Tool {
48 name: "timeline",
49 description: TIMELINE_DOC,
50 schema: timeline_schema,
51 run: timeline,
52 },
53 Tool {
54 name: "clip_info",
55 description: CLIP_INFO_DOC,
56 schema: clip_info_schema,
57 run: clip_info,
58 },
59 ]
60}
61
62// ---- schemas --------------------------------------------------------------
63
64fn timeline_schema() -> Value {
65 json!({
66 "type": "object",
67 "description": TIMELINE_DOC,
68 "properties": {
69 "sequence": super::sequence::prop(),
70 "range": {
71 "type": "object",
72 "description": "Only clips that overlap this stretch are listed. Omit for the whole timeline.",
73 "properties": {
74 "from": {
75 "type": ["string", "number"],
76 "description": format!("Start of the stretch. Defaults to 0. {TIME_DOC}")
77 },
78 "to": {
79 "type": ["string", "number"],
80 "description": format!("End of the stretch, exclusive. Defaults to end. {TIME_DOC}")
81 }
82 }
83 },
84 "lanes": {
85 "type": "array",
86 "items": { "type": "string" },
87 "description": "Lanes to show, such as [\"V1\", \"A2\", \"S1\"]. Omit for every lane. V1.. are video, A1.. audio, S1.. subtitles."
88 },
89 "detail": {
90 "type": "string",
91 "enum": ["brief", "full"],
92 "description": "brief (default) caps the text at about 4 KB, shared out equally among the lanes that have clips: each lane lists as many clips as its share holds, never more than 40 (a lane of few clips lists them all), and says how many clips were cut from it (use range, or lanes [one lane] with page, to see them). full lists every clip, with its pan, pitch and deinterlace even at their defaults. brief shows those three only when they are set. structuredContent follows it: brief gives each clip's address, span, link and track; full gives every field (source, in/out, effects, pan, pitch, deinterlace) as clip_info does."
93 },
94 "page": {
95 "type": "integer",
96 "minimum": 1,
97 "description": "Lists one page of 40 clips of the one lane named in lanes, such as lanes [\"V1\"] with page 2 for clips 41 to 80. Lists every clip on the page, whatever the size cap. Needs exactly one lane."
98 }
99 }
100 })
101}
102
103fn clip_info_schema() -> Value {
104 json!({
105 "type": "object",
106 "description": CLIP_INFO_DOC,
107 "properties": {
108 "sequence": super::sequence::prop(),
109 "clip": {
110 "type": "string",
111 "description": "A clip address. LANE@START names the clip starting at that time, such as V1@450, A2@15.0s or S1@00:00:30:00. LANE#INDEX names the clip by its position on the lane, such as V1#0 for the first clip. Lanes are V1.., A1.., S1.."
112 },
113 "at": {
114 "type": "string",
115 "description": "Match frame: a timeline time (450f, 15.0s, 00:00:15:00) inside the clip. The reply adds the source (src:N and file) and the source time and frame shown at that moment. Default: the clip's first frame."
116 }
117 },
118 "required": ["clip"]
119 })
120}
121
122// ---- timeline -------------------------------------------------------------
123
124/// One clip or caption as the timeline shows it.
125struct Row {
126 /// Address column, `@450`. The lane name is printed by the lane header.
127 addr: String,
128 /// Everything after the address column.
129 body: String,
130 json: Value,
131}
132
133struct LaneView {
134 lane: Lane,
135 /// The name the user gave the lane, if any.
136 name: Option<String>,
137 gain_db: f32,
138 /// The lane's pan, `-1.0..=1.0`; 0 for the middle and for a lane with no sound.
139 pan: f32,
140 hidden: bool,
141 muted: bool,
142 locked: bool,
143 /// Every duck on the lane (a lane can hold several), in the order the engine keeps them.
144 ducks: Vec<Duck>,
145 /// The lane's voice processors ([`engine::voice`]); all off for a lane nobody has cleaned.
146 voice: engine::voice::VoiceFx,
147 rows: Vec<Row>,
148 /// Set when `page` lists one page of the lane's clips.
149 page: Option<LanePage>,
150 /// Clips on the lane (in the range) that carry a colour grade, out of `rows` before a page is cut.
151 coloured: usize,
152 /// Clips on the lane in the range, before a page is cut.
153 clips: usize,
154}
155
156/// Where one page of a lane sits among the lane's clips (in the range asked for).
157#[derive(Clone, Copy)]
158struct LanePage {
159 /// Index of the page's first clip.
160 first: usize,
161 /// Clips on the lane in the range.
162 total: usize,
163 /// This page's number (from 1) and how many pages there are.
164 number: usize,
165 pages: usize,
166}
167
168impl LanePage {
169 fn of(number: usize, total: usize) -> Self {
170 let pages = total.div_ceil(CLIPS_PER_PAGE).max(1);
171 Self { first: (number - 1) * CLIPS_PER_PAGE, total, number, pages }
172 }
173
174 fn json(&self, shown: usize) -> Value {
175 json!({
176 "page": self.number,
177 "pages": self.pages,
178 "first_clip": self.first + 1,
179 "last_clip": self.first + shown,
180 "clips": self.total,
181 })
182 }
183}
184
185impl LaneView {
186 /// The header extras: only non-default state is shown.
187 fn flags(&self) -> Vec<String> {
188 let mut f = Vec::new();
189 if let Some(n) = &self.name {
190 f.push(format!("\"{n}\""));
191 }
192 if self.gain_db != 0.0 {
193 f.push(format!("gain {}dB", num(f64::from(self.gain_db))));
194 }
195 if self.pan != 0.0 {
196 f.push(format!("pan {}", num(f64::from(self.pan))));
197 }
198 for d in &self.ducks {
199 f.push(duck_text(d));
200 }
201 if self.voice.is_active() {
202 f.push(format!("voice: {}", self.voice.summary()));
203 }
204 // A batch of grades can sit past the rows shown, so the header counts them all.
205 if self.coloured > 0 {
206 f.push(format!("color on {} of {} clips", self.coloured, self.clips));
207 }
208 if self.hidden {
209 f.push("hidden".into());
210 }
211 if self.muted {
212 f.push("muted".into());
213 }
214 if self.locked {
215 f.push("locked".into());
216 }
217 f
218 }
219}
220
221/// A clip's brief structuredContent: its address, span, link and (on a subtitle lane)
222/// track. The source, edits and effects are left to `detail: full` and `clip_info`.
223fn compact_clip(clip: &Value) -> Value {
224 const KEEP: [&str; 5] = ["addr", "start", "end", "link", "track"];
225 Value::Object(
226 KEEP.iter()
227 .filter_map(|k| clip.get(*k).map(|v| ((*k).to_string(), v.clone())))
228 .collect(),
229 )
230}
231
232fn timeline(server: &mut Server, args: &Value) -> Reply {
233 let s = tri!(server.session_ref());
234 let fps = parse::session_fps(s);
235 let end = parse::session_end(s);
236 let range = tri!(range_arg(args, fps, end));
237 let full = match opt_str(args, "detail") {
238 None | Some("brief") => false,
239 Some("full") => true,
240 Some(other) => {
241 return Reply::err(format!("argument `detail`: `{other}` is not brief or full"))
242 }
243 };
244 let page = tri!(page_arg(args));
245 let known = all_lanes(s);
246 let wanted = tri!(lanes_arg(args, &known));
247 if page.is_some() && wanted.as_ref().is_none_or(|w| w.len() != 1) {
248 return Reply::err(
249 "argument `page` pages one lane: give it alone in `lanes`, such as lanes [\"V1\"] with page 2",
250 );
251 }
252 let shown: Vec<Lane> = match wanted {
253 None => known.clone(),
254 Some(w) => known.iter().copied().filter(|l| w.contains(l)).collect(),
255 };
256
257 let mut views: Vec<LaneView> = shown.iter().map(|&l| lane_view(s, l, fps, range, full)).collect();
258 if let (Some(number), [view]) = (page, views.as_mut_slice()) {
259 let lp = LanePage::of(number, view.rows.len());
260 if number > lp.pages {
261 return Reply::err(format!(
262 "page {number} is past the end: {} has {} page(s) of {CLIPS_PER_PAGE} clips",
263 parse::lane_name(view.lane),
264 lp.pages
265 ));
266 }
267 let rows = std::mem::take(&mut view.rows);
268 view.rows = rows.into_iter().skip(lp.first).take(CLIPS_PER_PAGE).collect();
269 view.page = Some(lp);
270 }
271 let (w, h) = s.resolution();
272 // The agent-visible steps (the ledger), the same count project_status reports.
273 let undo = server.ledger.len();
274 let redo = server.redo_ledger.len();
275 let name = server
276 .path
277 .as_ref()
278 .and_then(|p| p.file_name())
279 .map(|n| n.to_string_lossy().into_owned())
280 .unwrap_or_else(|| "untitled".to_string());
281 let mut head = format!(
282 "{name} · {w}x{h} @{} · {} ({end}f) · undo {undo} · redo {redo}",
283 fps_text(fps),
284 parse::clock(end, fps)
285 );
286 if let Some((from, to)) = range {
287 head.push_str(&format!(" · range {}–{}", fmt_secs(from, fps), fmt_secs(to, fps)));
288 }
289
290 let gaps: Vec<String> = shown
291 .iter()
292 .filter(|l| l.kind != LaneKind::Subtitle)
293 .map(|&l| {
294 // The count includes a lead-in gap before the lane's first clip; say so.
295 let lead = s.lane_clips(l).first().map_or(0, |c| c.start);
296 let note = lead_in_note(lead, fps);
297 format!("{} {}{note}", parse::lane_name(l), s.gap_count(l))
298 })
299 .collect();
300 let gaps_line = if gaps.is_empty() {
301 String::new()
302 } else {
303 format!("gaps: {}", gaps.join(" · "))
304 };
305
306 let budget = BRIEF_CAP
307 .saturating_sub(head.len() + gaps_line.len() + 32 * views.len() + 64);
308 let mut lines = vec![head];
309 // Each offline source is named once, with its fix; its clips are marked OFFLINE in their rows.
310 for (i, p) in s.offline_sources() {
311 lines.push(format!("OFFLINE: src:{i} {} (relink with media_relink)", p.display()));
312 }
313 if views.is_empty() {
314 lines.push("no lanes in this project yet".into());
315 }
316 lines.extend(lane_lines(&views, full, budget, range));
317 let room = BRIEF_CAP.saturating_sub(lines.iter().map(|l| l.len() + 1).sum::<usize>() + gaps_line.len());
318 let (title_text, titles_json) = title_rows(s, fps, range, full, room);
319 lines.extend(title_text);
320 let chapters = chapter_block(s, fps, end);
321 if let Some(line) = &chapters.line {
322 lines.push(line.clone());
323 }
324 for w in &chapters.warnings {
325 lines.push(format!("chapters: {w}"));
326 }
327 let (marker_line, markers_json) = marker_block(s, fps);
328 if let Some(line) = marker_line {
329 lines.push(line);
330 }
331 if !gaps_line.is_empty() {
332 lines.push(gaps_line);
333 }
334 let text = lines.join("\n");
335
336 let lanes_json: Vec<Value> = views
337 .iter()
338 .map(|v| {
339 json!({
340 "lane": parse::lane_name(v.lane),
341 "name": v.name,
342 "gain_db": v.gain_db,
343 "pan": v.pan,
344 "hidden": v.hidden,
345 "muted": v.muted,
346 "locked": v.locked,
347 "duck": duck_json(v.ducks.first()),
348 "ducks": ducks_json(&v.ducks),
349 "voice": voice_json_of(&v.voice),
350 "page": v.page.map_or(Value::Null, |p| p.json(v.rows.len())),
351 "coloured_clips": v.coloured,
352 "clips": v
353 .rows
354 .iter()
355 .map(|r| if full { r.json.clone() } else { compact_clip(&r.json) })
356 .collect::<Vec<_>>(),
357 })
358 })
359 .collect();
360 let structured = json!({
361 "fps": fps,
362 "width": w,
363 "height": h,
364 "duration_frames": end,
365 "lanes": lanes_json,
366 "titles": titles_json,
367 "chapters": chapters.json,
368 "chapters_text": chapters.listing,
369 "chapter_warnings": chapters.warnings,
370 "markers": markers_json,
371 });
372 Reply::ok(text).with(structured)
373}
374
375/// The comment markers of the whole timeline as the `markers:` line and the structured list.
376fn marker_block(s: &PlaybackSession, fps: f64) -> (Option<String>, Vec<Value>) {
377 let markers = s.markers();
378 if markers.is_empty() {
379 return (None, Vec::new());
380 }
381 let json: Vec<Value> = markers
382 .iter()
383 .enumerate()
384 .map(|(i, m)| {
385 json!({
386 "addr": format!("M@{}", m.frame),
387 "index": i + 1,
388 "frame": m.frame,
389 "time": parse::secs(m.frame, fps),
390 "length": m.length,
391 "name": m.name,
392 "note": m.note,
393 "color": m.color.name(),
394 })
395 })
396 .collect();
397 let names: Vec<String> = markers
398 .iter()
399 .map(|m| {
400 let range = if m.length > 0 { format!("–{}f", m.end()) } else { String::new() };
401 let note = if m.note.is_empty() { String::new() } else { format!(" — {}", m.note.replace('\n', " ")) };
402 format!("M@{}{range} {} [{}]{note}", m.frame, m.name, m.color.name())
403 })
404 .collect();
405 (Some(format!("markers: {}", names.join(" · "))), json)
406}
407
408/// The chapters of the whole timeline (never cut to `range`: a description lists them all) as the
409/// timeline's `chapters:` line, the structured list, the plain text a video description takes, and
410/// the warnings YouTube's rules call for.
411struct ChapterBlock {
412 line: Option<String>,
413 json: Vec<Value>,
414 listing: String,
415 warnings: Vec<String>,
416}
417
418fn chapter_block(s: &PlaybackSession, fps: f64, end: u32) -> ChapterBlock {
419 let chapters: Vec<(u32, String)> = s.chapters().iter().map(|c| (c.frame, c.title.clone())).collect();
420 let (listing, warnings) = chapter_listing(&chapters, fps, end);
421 if chapters.is_empty() {
422 return ChapterBlock { line: None, json: Vec::new(), listing, warnings };
423 }
424 let json: Vec<Value> = chapters
425 .iter()
426 .enumerate()
427 .map(|(i, (frame, title))| {
428 json!({
429 "addr": format!("C@{frame}"),
430 "index": i + 1,
431 "start_f": frame,
432 "time": youtube_time(*frame, fps),
433 "title": title,
434 })
435 })
436 .collect();
437 let names: Vec<String> = chapters.iter().map(|(f, t)| format!("C@{f} {t} ({})", youtube_time(*f, fps))).collect();
438 let line = format!("chapters: {}", names.join(" · "));
439 ChapterBlock { line: Some(line), json, listing, warnings }
440}
441
442/// The YouTube chapter listing lives in the engine ([`engine::playback::chapter_listing`]), so the
443/// GUI's Copy chapters button and this tool write the same text.
444pub(crate) use engine::playback::{chapter_listing, youtube_time};
445
446/// The title lines of the timeline text, after the lanes, and the titles as JSON.
447/// Only titles that overlap `range` are shown. Brief output stops the lines at
448/// `room` bytes and says how many were left out; the JSON is always complete.
449fn title_rows(s: &PlaybackSession, fps: f64, range: Option<(u32, u32)>, full: bool, room: usize) -> (Vec<String>, Vec<Value>) {
450 let shown: Vec<(usize, &Title)> = s
451 .titles()
452 .iter()
453 .enumerate()
454 .filter(|(_, t)| overlaps(t.start, t.end(), range))
455 .collect();
456 let json: Vec<Value> = shown
457 .iter()
458 .map(|(i, t)| {
459 json!({
460 "name": title_name(*i),
461 "start_f": t.start,
462 "end_f": t.end(),
463 "text": t.text,
464 "place": place_word(t.style.place),
465 "size": t.style.size,
466 "outline": super::edit_fx::outline_word(t.style.outline),
467 "boxed": t.style.boxed,
468 "fade_in": t.fade_in,
469 "fade_out": t.fade_out,
470 "in_anim": t.in_anim.name(),
471 "out_anim": t.out_anim.name(),
472 "keys": super::edit_fx::title_keys_json(t, fps),
473 })
474 })
475 .collect();
476 let mut lines = Vec::new();
477 let mut used = 0;
478 for (k, (i, t)) in shown.iter().enumerate() {
479 let line = format!(
480 "T {} {:.3}–{:.3} \"{}\" {}{}",
481 title_name(*i),
482 parse::secs(t.start, fps),
483 parse::secs(t.end(), fps),
484 short_text(&t.text),
485 place_word(t.style.place),
486 super::edit_fx::title_keys_text(t, fps)
487 );
488 if !full && k > 0 && used + line.len() + 1 > room {
489 lines.push(format!("T … {} more titles (use range)", shown.len() - k));
490 break;
491 }
492 used += line.len() + 1;
493 lines.push(line);
494 }
495 (lines, json)
496}
497
498/// A title's text for a timeline line: newlines as ` / `, cut to 40 characters.
499fn short_text(text: &str) -> String {
500 let flat = text.replace('\n', " / ");
501 if flat.chars().count() <= 40 {
502 return flat;
503 }
504 let mut cut: String = flat.chars().take(39).collect();
505 cut.push('…');
506 cut
507}
508
509/// The `range` argument as `[from, to)` frames, or `None` for the whole timeline.
510fn range_arg(args: &Value, fps: f64, end: u32) -> Result<Option<(u32, u32)>, Reply> {
511 let r = match args.get("range") {
512 None | Some(Value::Null) => return Ok(None),
513 Some(r) => r,
514 };
515 if !r.is_object() {
516 return Err(Reply::err(
517 "argument `range` must be an object such as {\"from\": \"0\", \"to\": \"end\"}",
518 ));
519 }
520 let from = parse::opt_frame_arg(r, "from", fps, end)?.unwrap_or(0);
521 let to = parse::opt_frame_arg(r, "to", fps, end)?.unwrap_or(end);
522 if to < from {
523 return Err(Reply::err(format!(
524 "argument `range`: it ends at {to}f, before it starts at {from}f"
525 )));
526 }
527 Ok(Some((from, to)))
528}
529
530/// The `page` argument: a page number from 1, or `None` when it is not given.
531fn page_arg(args: &Value) -> Result<Option<usize>, Reply> {
532 match args.get("page") {
533 None | Some(Value::Null) => Ok(None),
534 Some(v) => match v.as_u64() {
535 Some(p) if p >= 1 => Ok(Some(p as usize)),
536 _ => Err(Reply::err("argument `page` must be a page number from 1 up, such as 2")),
537 },
538 }
539}
540
541/// The `lanes` argument, each name checked against the project's lanes.
542fn lanes_arg(args: &Value, known: &[Lane]) -> Result<Option<Vec<Lane>>, Reply> {
543 let items = match args.get("lanes") {
544 None | Some(Value::Null) => return Ok(None),
545 Some(Value::Array(a)) => a,
546 Some(_) => {
547 return Err(Reply::err(
548 "argument `lanes` must be a list of lane names, such as [\"V1\", \"A2\"]",
549 ))
550 }
551 };
552 let mut wanted = Vec::new();
553 for item in items {
554 let text = item
555 .as_str()
556 .ok_or_else(|| Reply::err("argument `lanes`: each entry must be a lane name such as \"V1\""))?;
557 // Titles are drawn on the picture, not on a lane, so they cannot be filtered.
558 if matches!(text.trim().to_ascii_uppercase().as_str(), "T" | "TITLE" | "TITLES") {
559 return Err(Reply::err(
560 "argument `lanes`: titles are not a lane; they always show in the timeline, so drop T from lanes",
561 ));
562 }
563 let lane = parse::lane(text).map_err(|e| Reply::err(format!("argument `lanes`: {e}")))?;
564 if !known.contains(&lane) {
565 return Err(Reply::err(format!(
566 "argument `lanes`: {} is not a lane in this project; the lanes are {}",
567 parse::lane_name(lane),
568 lane_names(known)
569 )));
570 }
571 wanted.push(lane);
572 }
573 Ok(Some(wanted))
574}
575
576fn lane_view(s: &PlaybackSession, lane: Lane, fps: f64, range: Option<(u32, u32)>, full: bool) -> LaneView {
577 let rows = match lane.kind {
578 LaneKind::Subtitle => sub_rows(s, lane, fps, range),
579 _ => media_rows(s, lane, fps, range, full),
580 };
581 LaneView {
582 lane,
583 name: s.lane_name(lane).map(str::to_string),
584 gain_db: s.lane_gain_db(lane),
585 pan: s.lane_pan(lane),
586 hidden: s.lane_hidden(lane),
587 muted: s.lane_muted(lane),
588 locked: s.lane_locked(lane),
589 ducks: s.lane_duck_list(lane),
590 voice: s.lane_voice(lane),
591 coloured: rows.iter().filter(|r| r.json["color"].as_bool() == Some(true)).count(),
592 clips: rows.len(),
593 rows,
594 page: None,
595 }
596}
597
598/// `duck under A1 -12dB`: the key lane's name and the depth. `under` is the key's lane
599/// ordinal, which is how `set_lane_duck` reads it.
600fn duck_text(d: &Duck) -> String {
601 format!("duck under {} {}dB", key_name(d), num(f64::from(d.depth_db)))
602}
603
604fn key_name(d: &Duck) -> String {
605 parse::lane_name(Lane::new(LaneKind::Audio, d.under))
606}
607
608/// A lane's voice processors for the structured reply: `null` when none is on.
609fn voice_json_of(fx: &engine::voice::VoiceFx) -> Value {
610 if fx.is_active() { super::voice::voice_json(fx) } else { Value::Null }
611}
612
613/// Every duck on a lane, as the structured reply lists them.
614fn ducks_json(ds: &[Duck]) -> Value {
615 Value::Array(ds.iter().map(|d| duck_json(Some(d))).collect())
616}
617
618fn duck_json(d: Option<&Duck>) -> Value {
619 d.map_or(Value::Null, |d| {
620 json!({
621 "under": key_name(d),
622 "depth_db": d.depth_db,
623 "threshold_db": d.threshold_db,
624 "attack_ms": d.attack_ms,
625 "release_ms": d.release_ms,
626 })
627 })
628}
629
630fn media_rows(s: &PlaybackSession, lane: Lane, fps: f64, range: Option<(u32, u32)>, full: bool) -> Vec<Row> {
631 let mut rows = Vec::new();
632 // Sources whose file is not on disk: a clip on one is marked, since its picture or sound is missing.
633 let offline: Vec<usize> = s.offline_sources().iter().map(|(i, _)| *i).collect();
634 for (idx, c) in s.lane_clips(lane).iter().enumerate() {
635 let end = c.end();
636 if !overlaps(c.start, end, range) {
637 continue;
638 }
639 let is_offline = offline.contains(&c.source);
640 // in and out are stored at the timeline's rate; they are shown as the source frames they
641 // play, in the source's own time (as edit replies print them). The JSON keeps stored frames.
642 let src_fps = source_fps(s, c.source, fps);
643 let (src_in, src_out) = src_range_secs(c.in_frame, c.out_frame, fps, src_fps, file_secs(s, c.source));
644 let mut body = format!(
645 "{}–{} {} {} src {}–{}",
646 fmt_secs(c.start, fps),
647 fmt_secs(end, fps),
648 source_tag(c.source),
649 source_name(s, c.source),
650 src_secs_text(src_in),
651 src_secs_text(src_out),
652 );
653 if let Some((_, names)) = s.multicam_at(lane, idx) {
654 let shown = usize::from(c.angle.of(lane.kind));
655 body.push_str(&format!(" angle {} \"{}\"", shown + 1, names.get(shown).map_or("", String::as_str)));
656 if lane.kind == LaneKind::Video
657 && let Some(a) = c.angle.audio
658 {
659 body.push_str(&format!(" (sound: angle {})", usize::from(a) + 1));
660 }
661 }
662 if let Some(id) = c.link {
663 body.push_str(&link_tag(s, id, (lane, c.start)));
664 }
665 let opacity = s.transform_of(lane, idx).map(|t| t.opacity);
666 // A dissolve overlaps the next clip on its lane: the row names where the overlap runs into.
667 let into = s.lane_clips(lane).get(idx + 1).map(|n| parse::addr(lane, n.start));
668 for flag in media_flags(c, opacity, into.as_deref()) {
669 body.push_str(" ");
670 body.push_str(&flag);
671 }
672 let keys = s.transform_keys_of(lane, idx).len();
673 if keys > 0 {
674 body.push_str(&format!(" keys {keys}"));
675 }
676 // Pan and pitch belong to audio clips, deinterlace to video clips. Full detail shows them
677 // always; brief shows only the ones set off their default.
678 let (pan, pitch, deint) = (
679 s.clip_pan_of(lane, idx).unwrap_or(0.0),
680 s.clip_pitch_of(lane, idx).unwrap_or(0.0),
681 s.deinterlace_of(lane, idx),
682 );
683 if lane.kind == LaneKind::Audio && (full || pan != 0.0) {
684 body.push_str(&format!(" pan {}", num(f64::from(pan))));
685 }
686 if lane.kind == LaneKind::Audio && (full || pitch != 0.0) {
687 body.push_str(&format!(" pitch {pitch:+}"));
688 }
689 if lane.kind == LaneKind::Video && (full || deint != engine::project::Deinterlace::Frame) {
690 body.push_str(&format!(" deinterlace {}", deint.name()));
691 }
692 let (okeys, ckeys) = (s.opacity_keys_of(lane, idx).len(), s.color_keys_of(lane, idx).len());
693 if okeys > 0 {
694 body.push_str(&format!(" opacity keys {okeys}"));
695 }
696 if ckeys > 0 {
697 body.push_str(&format!(" color keys {ckeys}"));
698 }
699 if is_offline {
700 body.push_str(" OFFLINE");
701 }
702 let mark = c.mark;
703 if let Some(n) = engine::project::label_name(mark.label) {
704 body.push_str(&format!(" label {n}"));
705 }
706 if mark.off {
707 body.push_str(" disabled");
708 }
709 let json = json!({
710 "label": engine::project::label_name(mark.label),
711 "disabled": mark.off,
712 "generator": s.generator_of(lane, idx).map(|g| super::generated::describe(&g)),
713 "addr": parse::addr(lane, c.start),
714 "start": c.start,
715 "end": end,
716 "source": c.source,
717 "offline": is_offline,
718 "in": c.in_frame,
719 "out": c.out_frame,
720 "link": c.link,
721 "speed": c.speed.as_f64(),
722 "reversed": c.reversed,
723 "fade_in": c.fade_in,
724 "fade_out": c.fade_out,
725 "transition_out": c.transition_out,
726 "transition_kind": c.transition_kind.name(),
727 "fit": fit_name(c.fit).unwrap_or("fit"),
728 "eq": c.eq.is_some(),
729 "color": c.color.is_some(),
730 "transform": c.transform.is_some(),
731 "transform_keys": keys,
732 "opacity_keys": okeys,
733 "color_keys": ckeys,
734 "env": !c.gain_keys.is_empty(),
735 "pan": pan,
736 "pitch": pitch,
737 "deinterlace": deint.name(),
738 "visualizer": c.visualizer != 0,
739 });
740 rows.push(Row {
741 addr: format!("@{}", c.start),
742 body,
743 json,
744 });
745 }
746 rows
747}
748
749fn sub_rows(s: &PlaybackSession, lane: Lane, fps: f64, range: Option<(u32, u32)>) -> Vec<Row> {
750 let mut rows = Vec::new();
751 for c in s.sub_lane(lane) {
752 let end = c.end();
753 if !overlaps(c.start, end, range) {
754 continue;
755 }
756 let label = s
757 .subtitles()
758 .get(c.track)
759 .map(|t| t.label.clone())
760 .unwrap_or_default();
761 let mut body = format!(
762 "{}–{} track {}",
763 fmt_secs(c.start, fps),
764 fmt_secs(end, fps),
765 c.track
766 );
767 if !label.is_empty() {
768 body.push(' ');
769 body.push_str(&label);
770 }
771 if let Some(id) = c.link {
772 body.push_str(&link_tag(s, id, (lane, c.start)));
773 }
774 let json = json!({
775 "addr": parse::addr(lane, c.start),
776 "start": c.start,
777 "end": end,
778 "source": null,
779 "in": null,
780 "out": null,
781 "link": c.link,
782 "speed": null,
783 "fade_in": null,
784 "fade_out": null,
785 "transition_out": null,
786 "track": c.track,
787 "label": label,
788 });
789 rows.push(Row {
790 addr: format!("@{}", c.start),
791 body,
792 json,
793 });
794 }
795 rows
796}
797
798/// Text lines for every lane. In brief mode each lane with clips gets an equal
799/// share of `budget` bytes; a lane that cannot fit all its clips says how many
800/// it cut. Full mode never cuts.
801fn lane_lines(views: &[LaneView], full: bool, budget: usize, range: Option<(u32, u32)>) -> Vec<String> {
802 let with_rows = views.iter().filter(|v| !v.rows.is_empty()).count().max(1);
803 let per_lane = budget / with_rows;
804 let mut out = Vec::new();
805 for v in views {
806 let name = parse::lane_name(v.lane);
807 let flags = v.flags();
808 // A paged lane always has its page line, so its first clip starts below it.
809 let inline = flags.is_empty() && v.page.is_none();
810 if !flags.is_empty() {
811 out.push(format!("{name:<4}{}", flags.join(" ")));
812 }
813 if v.rows.is_empty() {
814 if flags.is_empty() {
815 let none = if range.is_some() { "no clips in range" } else { "no clips" };
816 out.push(format!("{name:<4}{none}"));
817 }
818 continue;
819 }
820 if let Some(p) = v.page {
821 let (a, b) = (p.first + 1, p.first + v.rows.len());
822 out.push(format!("{name:<4}clips {a}–{b} of {} · page {} of {}", p.total, p.number, p.pages));
823 }
824 // With no header extras the first clip shares the lane's line.
825 let first_prefix = if inline { format!("{name:<4}") } else { " ".to_string() };
826 let lines: Vec<String> = v
827 .rows
828 .iter()
829 .enumerate()
830 .map(|(i, r)| {
831 let prefix = if i == 0 { first_prefix.as_str() } else { " " };
832 format!("{prefix}{:<8}{}", r.addr, r.body)
833 })
834 .collect();
835 let total: usize = lines.iter().map(|l| l.len() + 1).sum();
836 // A page is listed whole: it is at most CLIPS_PER_PAGE clips.
837 if full || v.page.is_some() || (total <= per_lane && lines.len() <= CLIPS_PER_PAGE) {
838 out.extend(lines);
839 continue;
840 }
841 let mut used = 0;
842 let mut keep = 0;
843 for l in &lines {
844 if keep > 0 && (keep == CLIPS_PER_PAGE || used + l.len() + 1 + MORE_RESERVE > per_lane) {
845 break;
846 }
847 used += l.len() + 1;
848 keep += 1;
849 }
850 let cut = lines.len() - keep;
851 out.extend(lines.into_iter().take(keep));
852 out.push(format!(" … {cut} more clips (use range, or lanes [\"{name}\"] with page)"));
853 }
854 out
855}
856
857impl LaneView {
858 #[cfg(test)]
859 fn for_test(lane: Lane, rows: Vec<Row>) -> Self {
860 Self {
861 lane,
862 name: None,
863 gain_db: 0.0,
864 pan: 0.0,
865 hidden: false,
866 muted: false,
867 locked: false,
868 ducks: Vec::new(),
869 voice: engine::voice::VoiceFx::default(),
870 coloured: rows.iter().filter(|r| r.json["color"].as_bool() == Some(true)).count(),
871 clips: rows.len(),
872 rows,
873 page: None,
874 }
875 }
876}
877
878// ---- clip_info ------------------------------------------------------------
879
880/// What a clip's source says about its sound: the audio stream it plays from with that track's
881/// language, e.g. `audio stream 1 (fra)`, or `audio: none` when the file has no sound stream at
882/// all (a picture alone).
883fn source_sound(path: Option<&std::path::Path>, audio_stream: usize) -> String {
884 let Some(path) = path else {
885 return format!("audio stream {audio_stream}");
886 };
887 let tracks = audio_tracks(path);
888 if tracks.is_empty() {
889 return "audio: none".to_string();
890 }
891 match tracks.iter().find(|(t, _)| *t == audio_stream) {
892 Some((_, lang)) => format!("audio stream {audio_stream} ({lang})"),
893 None => format!("audio stream {audio_stream}"),
894 }
895}
896
897/// A clip's transform keys, one line each, with the time both ways: the clip time is what the
898/// transform_keys op's `at` takes, the timeline time is where the key sits on the timeline:
899/// `at clip 1.000s (timeline 7.000s) x 0.1 y 0 scale 1.20 rotate 0 opacity 1 ease linear`.
900fn transform_key_lines(c: &Clip, fps: f64, keys: &[TransformKey]) -> Vec<String> {
901 keys.iter()
902 .map(|k| {
903 let p = &k.params;
904 let ease = k.ease.name();
905 let at = timeline_of(c, k.at);
906 format!(
907 " at clip {:.3}s (timeline {:.3}s) x {} y {} scale {} rotate {} opacity {} ease {ease}",
908 (at - f64::from(c.start)) / fps,
909 at / fps,
910 num(f64::from(p.pos_x)),
911 num(f64::from(p.pos_y)),
912 num(f64::from(p.scale)),
913 num(f64::from(p.rotate)),
914 num(f64::from(p.opacity)),
915 )
916 })
917 .collect()
918}
919
920/// A clip's opacity keys, one line each, in the shape of [`transform_key_lines`].
921fn opacity_key_lines(c: &Clip, fps: f64, keys: &[OpacityKey]) -> Vec<String> {
922 keys.iter()
923 .map(|k| {
924 let at = timeline_of(c, k.at);
925 format!(
926 " at clip {:.3}s (timeline {:.3}s) opacity {} ease {}",
927 (at - f64::from(c.start)) / fps,
928 at / fps,
929 num(f64::from(k.opacity)),
930 k.ease.name()
931 )
932 })
933 .collect()
934}
935
936/// The look part of a grade (wheels, curves, LUT) as one line, or `None` when it is neutral.
937fn look_line(l: &engine::color::Look) -> Option<String> {
938 let mut parts = Vec::new();
939 for (name, w) in [("lift", l.wheels.lift), ("gamma", l.wheels.gamma), ("gain", l.wheels.gain)] {
940 if w.iter().any(|&v| v != 0.0) {
941 parts.push(format!("{name} [{}]", w.iter().map(|&v| num(f64::from(v))).collect::<Vec<_>>().join(", ")));
942 }
943 }
944 for (name, c) in engine::color::CHANNELS.iter().zip(&l.curves) {
945 if !c.points().is_empty() {
946 let pts: Vec<String> = c.points().iter().map(|p| format!("{}:{}", num(f64::from(p[0])), num(f64::from(p[1])))).collect();
947 parts.push(format!("{name} curve {}", pts.join(",")));
948 }
949 }
950 if let Some(r) = l.lut {
951 let state = match r.problem() {
952 Some(e) => format!(" — NOT APPLIED: {e}; relink with lut {{relink, path}}"),
953 None => String::new(),
954 };
955 parts.push(format!("lut {} mix {}{state}", r.path().display(), num(f64::from(l.lut_mix))));
956 }
957 (!parts.is_empty()).then(|| format!("look: {}", parts.join("; ")))
958}
959
960/// A clip's colour keys, one line each, in the shape of [`transform_key_lines`].
961fn color_key_lines(c: &Clip, fps: f64, keys: &[ColorKey]) -> Vec<String> {
962 keys.iter()
963 .map(|k| {
964 let p = &k.params;
965 let at = timeline_of(c, k.at);
966 format!(
967 " at clip {:.3}s (timeline {:.3}s) brightness {} contrast {} saturation {} tint {} ease {}",
968 (at - f64::from(c.start)) / fps,
969 at / fps,
970 num(f64::from(p.brightness)),
971 num(f64::from(p.contrast)),
972 num(f64::from(p.saturation)),
973 num(f64::from(p.tint)),
974 k.ease.name()
975 )
976 })
977 .collect()
978}
979
980/// An effect's keys, one line each: the clip time and the timeline time, then each keyed
981/// parameter by name with its value, and the ease that leaves the key.
982fn effect_key_lines(c: &Clip, fps: f64, e: &Effect) -> Vec<String> {
983 e.keys
984 .iter()
985 .map(|k| {
986 let at = timeline_of(c, k.at);
987 let values: String = e
988 .kind
989 .params()
990 .iter()
991 .enumerate()
992 .filter(|(_, p)| p.keyable())
993 .map(|(i, p)| format!(" {} {}", p.name, num(f64::from(k.values[i]))))
994 .collect();
995 format!(
996 " at clip {:.3}s (timeline {:.3}s){values} ease {}",
997 (at - f64::from(c.start)) / fps,
998 at / fps,
999 k.ease.name()
1000 )
1001 })
1002 .collect()
1003}
1004
1005/// The keyed effects as JSON: each one's stack position and kind, then its keys with the
1006/// timeline time, the source frame, every keyed parameter by name, and the ease.
1007fn effect_keys_json(c: &Clip, fps: f64, effects: &[Effect]) -> Value {
1008 Value::Array(
1009 effects
1010 .iter()
1011 .enumerate()
1012 .filter(|(_, e)| !e.keys.is_empty())
1013 .map(|(slot, e)| {
1014 let keys: Vec<Value> = e
1015 .keys
1016 .iter()
1017 .map(|k| {
1018 let mut v = json!({
1019 "time": timeline_of(c, k.at) / fps,
1020 "source_frame": k.at,
1021 "ease": k.ease.name(),
1022 });
1023 for (i, p) in e.kind.params().iter().enumerate().filter(|(_, p)| p.keyable()) {
1024 v[p.name] = json!(k.values[i]);
1025 }
1026 v
1027 })
1028 .collect();
1029 json!({ "index": slot, "kind": e.kind.name(), "keys": keys })
1030 })
1031 .collect(),
1032 )
1033}
1034
1035/// A speed ramp's keys, one line each: the clip-relative time they sit at, which is the time the
1036/// speed_ramp op's `at` takes, and the speed there.
1037fn speed_key_lines(fps: f64, keys: &[engine::project::SpeedKey]) -> Vec<String> {
1038 keys.iter()
1039 .map(|k| format!(" at clip {:.3}s speed {}x", f64::from(k.at) / fps, num(k.speed.as_f64())))
1040 .collect()
1041}
1042
1043/// The speed ramp as JSON, every key: its clip-relative time in seconds and its speed.
1044fn speed_keys_json(fps: f64, keys: &[engine::project::SpeedKey]) -> Value {
1045 Value::Array(
1046 keys.iter()
1047 .map(|k| json!({"clip_time": f64::from(k.at) / fps, "speed": k.speed.as_f64()}))
1048 .collect(),
1049 )
1050}
1051
1052/// The volume envelope as JSON, every point (the text cuts it short): its timeline time, its
1053/// source frame, its dB and the ease that leaves it.
1054fn gain_keys_json(c: &Clip, fps: f64) -> Value {
1055 Value::Array(
1056 c.gain_keys
1057 .iter()
1058 .map(|k| {
1059 json!({
1060 "time": timeline_of(c, k.at) / fps,
1061 "source_frame": k.at,
1062 "db": k.db,
1063 "ease": k.ease.name(),
1064 })
1065 })
1066 .collect(),
1067 )
1068}
1069
1070fn opacity_keys_json(c: &Clip, fps: f64, keys: &[OpacityKey]) -> Value {
1071 Value::Array(
1072 keys.iter()
1073 .map(|k| {
1074 json!({
1075 "time": timeline_of(c, k.at) / fps,
1076 "source_frame": k.at,
1077 "opacity": k.opacity,
1078 "ease": k.ease.name(),
1079 })
1080 })
1081 .collect(),
1082 )
1083}
1084
1085fn color_keys_json(c: &Clip, fps: f64, keys: &[ColorKey]) -> Value {
1086 Value::Array(
1087 keys.iter()
1088 .map(|k| {
1089 json!({
1090 "time": timeline_of(c, k.at) / fps,
1091 "source_frame": k.at,
1092 "brightness": k.params.brightness,
1093 "contrast": k.params.contrast,
1094 "saturation": k.params.saturation,
1095 "tint": k.params.tint,
1096 "ease": k.ease.name(),
1097 })
1098 })
1099 .collect(),
1100 )
1101}
1102
1103/// The same keys as JSON: the timeline time in seconds, the source frame they sit on, and the placement.
1104fn transform_keys_json(c: &Clip, fps: f64, keys: &[TransformKey]) -> Value {
1105 Value::Array(
1106 keys.iter()
1107 .map(|k| {
1108 json!({
1109 "time": timeline_of(c, k.at) / fps,
1110 "source_frame": k.at,
1111 "x": k.params.pos_x,
1112 "y": k.params.pos_y,
1113 "scale": k.params.scale,
1114 "rotate": k.params.rotate,
1115 "opacity": k.params.opacity,
1116 "ease": k.ease.name(),
1117 })
1118 })
1119 .collect(),
1120 )
1121}
1122
1123fn clip_info(server: &mut Server, args: &Value) -> Reply {
1124 let Some(addr) = opt_str(args, "clip") else {
1125 return Reply::err(
1126 "missing argument `clip`: give a clip address such as V1@450 (lane and start) or V1#0 (lane and index)",
1127 );
1128 };
1129 let s = tri!(server.session_ref());
1130 let fps = parse::session_fps(s);
1131 let (lane, idx) = match parse::clip(s, addr) {
1132 Ok(v) => v,
1133 Err(e) => return Reply::err(e),
1134 };
1135 match lane.kind {
1136 LaneKind::Subtitle => sub_info(s, lane, idx, fps),
1137 _ => {
1138 let mut reply = media_info(s, lane, idx, fps);
1139 if let Some(v) = args.get("at").filter(|v| !v.is_null()) {
1140 match match_frame_line(s, lane, idx, v, fps) {
1141 Ok((line, json)) => {
1142 reply.text.push('\n');
1143 reply.text.push_str(&line);
1144 if let Some(Value::Object(o)) = reply.structured.as_deref_mut() {
1145 o.insert("match_frame".into(), json);
1146 }
1147 }
1148 Err(e) => return Reply::err(e),
1149 }
1150 }
1151 reply
1152 }
1153 }
1154}
1155
1156/// Match frame: the source and source time the clip shows at timeline time `at`.
1157fn match_frame_line(s: &PlaybackSession, lane: Lane, idx: usize, at: &Value, fps: f64) -> Result<(String, Value), String> {
1158 let c = &s.lane_clips(lane)[idx];
1159 let frame = parse::frame(at, fps, c.end()).map_err(|e| format!("`at`: {e}"))?;
1160 if frame < c.start || frame >= c.end() {
1161 return Err(format!(
1162 "`at` {} is outside {} (it covers {}f–{}f)",
1163 parse::tc(frame, fps), parse::addr(lane, c.start), c.start, c.end()
1164 ));
1165 }
1166 let Some((path, stream, secs)) = engine::editkeys::matched_source(s, (lane, idx), frame, fps) else {
1167 return Err("match frame: a compound clip plays a sequence, not a file".into());
1168 };
1169 let n = c.source;
1170 let line = format!(
1171 "match frame at {}f: src:{n} {} (audio stream {stream}), source time {secs:.3}s",
1172 frame,
1173 path.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default()
1174 );
1175 let json = json!({ "frame": frame, "source": n, "path": path.display().to_string(), "audio_stream": stream, "source_seconds": secs });
1176 Ok((line, json))
1177}
1178
1179fn media_info(s: &PlaybackSession, lane: Lane, idx: usize, fps: f64) -> Reply {
1180 let c: &Clip = &s.lane_clips(lane)[idx];
1181 let start = c.start;
1182 let end = c.end();
1183 let length = end - start;
1184 let addr = parse::addr(lane, start);
1185 let lane_nm = parse::lane_name(lane);
1186 let kind = match lane.kind {
1187 LaneKind::Audio => "audio",
1188 _ => "video",
1189 };
1190
1191 let src = s.sources().get(c.source);
1192 let src_name = source_name(s, c.source);
1193 let generated = s.generator_of(lane, idx);
1194 let src_path = match (&generated, src) {
1195 (Some(_), _) => "generated, no file".to_string(),
1196 (None, Some(x)) => x.path.display().to_string(),
1197 (None, None) => "(missing)".to_string(),
1198 };
1199 let audio_stream = src.map(|x| x.audio_stream).unwrap_or(0);
1200 // The source's own rate, for its in/out times; the timeline's rate if unknown.
1201 let src_fps = src
1202 .map(|x| s.file_fps(&x.path))
1203 .filter(|f| *f > 0.0)
1204 .unwrap_or(fps);
1205
1206 let members = link_members(s, c.link, (lane, start));
1207 let link_line = match c.link {
1208 None => "link: none".to_string(),
1209 Some(_) if members.is_empty() => "detached (ungrouped)".to_string(),
1210 Some(id) => format!("link {id}: {}", members.join(", ")),
1211 };
1212
1213 let eq = s.eq_of(lane, idx);
1214 let eq_line = match eq {
1215 None => "eq: none (plays flat)".to_string(),
1216 Some(e) => {
1217 let mut t = format!("eq: {} bands", e.bands.len());
1218 for b in &e.bands {
1219 t.push_str(&format!(
1220 "\n {} {} Hz gain {} dB q {}",
1221 band_kind(b.kind),
1222 num(f64::from(b.freq_hz)),
1223 num(f64::from(b.gain_db)),
1224 num(f64::from(b.q))
1225 ));
1226 }
1227 t
1228 }
1229 };
1230 let eq_json = match eq {
1231 None => Value::Null,
1232 Some(e) => Value::Array(
1233 e.bands
1234 .iter()
1235 .map(|b| {
1236 json!({
1237 "freq_hz": b.freq_hz,
1238 "gain_db": b.gain_db,
1239 "q": b.q,
1240 "kind": band_kind(b.kind),
1241 })
1242 })
1243 .collect(),
1244 ),
1245 };
1246
1247 let color = s.color_of(lane, idx);
1248 let color_line = match color {
1249 None => "color: none".to_string(),
1250 Some(k) => format!(
1251 "color: brightness {} contrast {} saturation {} tint {}",
1252 num(f64::from(k.brightness)),
1253 num(f64::from(k.contrast)),
1254 num(f64::from(k.saturation)),
1255 num(f64::from(k.tint))
1256 ),
1257 };
1258 let color_line = match color.map(|k| look_line(&k.look)) {
1259 Some(Some(look)) => format!("{color_line}\n{look}"),
1260 _ => color_line,
1261 };
1262 let color_json = color.map_or(Value::Null, |k| {
1263 let mut j = json!({
1264 "brightness": k.brightness,
1265 "contrast": k.contrast,
1266 "saturation": k.saturation,
1267 "tint": k.tint,
1268 });
1269 let l = &k.look;
1270 if *l != engine::color::Look::default() {
1271 j["wheels"] = json!({"lift": l.wheels.lift, "gamma": l.wheels.gamma, "gain": l.wheels.gain});
1272 j["curves"] = json!(engine::color::CHANNELS
1273 .iter()
1274 .zip(&l.curves)
1275 .map(|(n, c)| (n.to_string(), json!(c.points())))
1276 .collect::<serde_json::Map<String, Value>>());
1277 j["lut"] = l.lut.map_or(Value::Null, |r| {
1278 json!({"path": r.path().display().to_string(), "mix": l.lut_mix, "problem": r.problem()})
1279 });
1280 }
1281 j
1282 });
1283
1284 let xf = s.transform_of(lane, idx);
1285 let keys = s.transform_keys_of(lane, idx);
1286 let transform_line = match xf {
1287 None => "transform: none".to_string(),
1288 Some(t) => format!(
1289 "transform: pos {} {} scale {} rotate {} crop left {} right {} top {} bottom {}{}",
1290 num(f64::from(t.pos_x)),
1291 num(f64::from(t.pos_y)),
1292 num(f64::from(t.scale)),
1293 num(f64::from(t.rotate)),
1294 num(f64::from(t.crop_l)),
1295 num(f64::from(t.crop_r)),
1296 num(f64::from(t.crop_t)),
1297 num(f64::from(t.crop_b)),
1298 opacity_suffix(t.opacity)
1299 ),
1300 };
1301 let transform_json = xf.map_or(Value::Null, |t| {
1302 let mut v = json!({
1303 "pos_x": t.pos_x,
1304 "pos_y": t.pos_y,
1305 "scale": t.scale,
1306 "rotate": t.rotate,
1307 "crop_l": t.crop_l,
1308 "crop_r": t.crop_r,
1309 "crop_t": t.crop_t,
1310 "crop_b": t.crop_b,
1311 });
1312 // Opacity is listed only when the clip is not fully opaque, as in the text.
1313 if t.opacity != 1.0 {
1314 v["opacity"] = json!(t.opacity);
1315 }
1316 v
1317 });
1318
1319 let viz_part = match shown_by(s, c, lane) {
1320 Some(addr) => format!("visualizer: shown by {addr}"),
1321 None => format!("visualizer {}", viz_text(c.visualizer)),
1322 };
1323 let walls_start = s.trim_walls(lane, idx, Edge::Start);
1324 let walls_end = s.trim_walls(lane, idx, Edge::End);
1325
1326 let mut lines = vec![
1327 format!("{addr} · lane {lane_nm} · {kind}"),
1328 format!(
1329 "timeline {} to {} · {} to {} · length {}",
1330 parse::tc(start, fps),
1331 parse::tc(end, fps),
1332 parse::clock(start, fps),
1333 parse::clock(end, fps),
1334 parse::tc(length, fps)
1335 ),
1336 format!(
1337 "{} {src_name} · {} · {src_path}",
1338 source_tag(c.source),
1339 source_sound(src.map(|x| x.path.as_path()), audio_stream)
1340 ),
1341 source_span_line(c.in_frame, c.out_frame, src.map(|x| x.path.as_path()), fps, src_fps),
1342 format!(
1343 "speed {}{} · fade_in {}f · fade_out {}f · {} {}f · fit {} · {}",
1344 speed_text(c),
1345 if c.reversed { " · reversed" } else { "" },
1346 c.fade_in,
1347 c.fade_out,
1348 c.transition_kind.name(),
1349 c.transition_out,
1350 fit_name(c.fit).unwrap_or("fit"),
1351 viz_part
1352 ),
1353 link_line,
1354 eq_line,
1355 color_line,
1356 ];
1357 // A keyed clip's placement is its keys, so its keys take the place of the single transform line.
1358 if keys.is_empty() {
1359 lines.push(transform_line);
1360 } else {
1361 lines.push(format!("transform keys: {}", keys.len()));
1362 lines.extend(transform_key_lines(c, fps, keys));
1363 }
1364 let (okeys, ckeys) = (s.opacity_keys_of(lane, idx), s.color_keys_of(lane, idx));
1365 if !okeys.is_empty() {
1366 lines.push(format!("opacity keys: {}", okeys.len()));
1367 lines.extend(opacity_key_lines(c, fps, okeys));
1368 }
1369 if !ckeys.is_empty() {
1370 lines.push(format!("color keys: {}", ckeys.len()));
1371 lines.extend(color_key_lines(c, fps, ckeys));
1372 }
1373 // Each effect with keys: its keyed values at every key, with the ease that leaves it.
1374 for (slot, e) in s.effects_of(lane, idx).iter().enumerate().filter(|(_, e)| !e.keys.is_empty()) {
1375 lines.push(format!("effect {slot} {} keys: {}", e.kind.name(), e.keys.len()));
1376 lines.extend(effect_key_lines(c, fps, e));
1377 }
1378 if let Some(n) = engine::project::label_name(c.mark.label) {
1379 lines.push(format!("label {n}"));
1380 }
1381 if c.mark.off {
1382 lines.push("disabled (switched off: skipped by playback, frames and export)".to_string());
1383 }
1384 lines.push(format!("trim start: {}", walls_text(walls_start, fps)));
1385 lines.push(format!("trim end: {}", walls_text(walls_end, fps)));
1386 // A clip's own gain, shown only when it is off unity.
1387 if c.gain_db != 0.0 {
1388 lines.push(format!("gain {}dB", num(f64::from(c.gain_db))));
1389 }
1390 // Pan, pitch and deinterlace, each shown only when it is off its default.
1391 let (pan, pitch, deint) = (
1392 s.clip_pan_of(lane, idx).unwrap_or(0.0),
1393 s.clip_pitch_of(lane, idx).unwrap_or(0.0),
1394 s.deinterlace_of(lane, idx),
1395 );
1396 let mut tweaks = Vec::new();
1397 if pan != 0.0 {
1398 tweaks.push(format!("pan {}", num(f64::from(pan))));
1399 }
1400 if pitch != 0.0 {
1401 tweaks.push(format!("pitch {pitch:+} semitones"));
1402 }
1403 if deint != engine::project::Deinterlace::Frame {
1404 tweaks.push(format!("deinterlace {}", deint.name()));
1405 }
1406 if !tweaks.is_empty() {
1407 lines.push(tweaks.join(" · "));
1408 }
1409 // Every key of a speed ramp, so the ramp can be read and edited key by key.
1410 if !c.speed_keys.is_empty() {
1411 lines.push(format!("speed keys: {}", c.speed_keys.len()));
1412 lines.extend(speed_key_lines(fps, &c.speed_keys));
1413 }
1414 // The volume envelope, in timeline times; only an audio clip can have one.
1415 if !c.gain_keys.is_empty() {
1416 lines.push(format!(
1417 "gain keys: {}",
1418 super::edit_fx::points_text(c, fps, &c.gain_keys)
1419 ));
1420 }
1421 // A duck belongs to the audio lane, so only an audio clip shows it; so do the voice processors.
1422 let voice = s.lane_voice(lane);
1423 if lane.kind == LaneKind::Audio {
1424 lines.push(match voice.summary() {
1425 t if t.is_empty() => "voice: none".to_string(),
1426 t => format!("voice: {t}"),
1427 });
1428 }
1429 let ducks = s.lane_duck_list(lane);
1430 if lane.kind == LaneKind::Audio {
1431 if ducks.is_empty() {
1432 lines.push("duck: none".to_string());
1433 }
1434 for d in &ducks {
1435 lines.push(format!(
1436 "{} · threshold {}dB · attack {}ms · release {}ms",
1437 duck_text(d),
1438 num(f64::from(d.threshold_db)),
1439 num(f64::from(d.attack_ms)),
1440 num(f64::from(d.release_ms))
1441 ));
1442 }
1443 }
1444
1445 let structured = json!({
1446 "addr": addr,
1447 "lane": lane_nm,
1448 "kind": kind,
1449 "start": start,
1450 "end": end,
1451 "length": length,
1452 "clock_start": parse::clock(start, fps),
1453 "clock_end": parse::clock(end, fps),
1454 "source": src.map_or(Value::Null, |x| json!({
1455 "index": c.source,
1456 "name": src_name,
1457 "path": x.path.display().to_string(),
1458 "audio_stream": x.audio_stream,
1459 })),
1460 "generator": generated.map(|g| super::generated::describe(&g)),
1461 "label": engine::project::label_name(c.mark.label),
1462 "disabled": c.mark.off,
1463 "in": c.in_frame,
1464 "out": c.out_frame,
1465 "link": c.link,
1466 "link_members": members,
1467 "speed": c.speed.as_f64(),
1468 "reversed": c.reversed,
1469 "fade_in": c.fade_in,
1470 "fade_out": c.fade_out,
1471 "transition_out": c.transition_out,
1472 "transition_kind": c.transition_kind.name(),
1473 "fit": fit_name(c.fit).unwrap_or("fit"),
1474 "visualizer": viz_json(c.visualizer),
1475 "eq": eq_json,
1476 "color": color_json,
1477 "transform": transform_json,
1478 "transform_keys": transform_keys_json(c, fps, keys),
1479 "opacity_keys": opacity_keys_json(c, fps, okeys),
1480 "color_keys": color_keys_json(c, fps, ckeys),
1481 "effect_keys": effect_keys_json(c, fps, s.effects_of(lane, idx)),
1482 "trim_walls": {
1483 "start": walls_json(walls_start),
1484 "end": walls_json(walls_end),
1485 },
1486 "duck": duck_json(ducks.first()),
1487 "ducks": ducks_json(&ducks),
1488 "voice": voice_json_of(&voice),
1489 "pan": pan,
1490 "pitch": pitch,
1491 "deinterlace": deint.name(),
1492 "speed_keys": speed_keys_json(fps, &c.speed_keys),
1493 "gain_db": c.gain_db,
1494 "gain_keys": gain_keys_json(c, fps),
1495 });
1496 Reply::ok(lines.join("\n")).with(structured)
1497}
1498
1499fn sub_info(s: &PlaybackSession, lane: Lane, idx: usize, fps: f64) -> Reply {
1500 let c = s.sub_lane(lane)[idx];
1501 let start = c.start;
1502 let end = c.end();
1503 let addr = parse::addr(lane, start);
1504 let lane_nm = parse::lane_name(lane);
1505 let track = s.subtitles().get(c.track);
1506 let label = track.map(|t| t.label.clone()).unwrap_or_default();
1507 let path = track
1508 .map(|t| t.path.display().to_string())
1509 .unwrap_or_else(|| "(missing)".to_string());
1510 let members = link_members(s, c.link, (lane, start));
1511 let link_line = match c.link {
1512 None => "link: none".to_string(),
1513 Some(_) if members.is_empty() => "detached (ungrouped)".to_string(),
1514 Some(id) => format!("link {id}: {}", members.join(", ")),
1515 };
1516 let room = s.trim_sub_room(lane, idx, Edge::Start);
1517 let room_end = s.trim_sub_room(lane, idx, Edge::End);
1518
1519 let lines = [
1520 format!("{addr} · lane {lane_nm} · subtitle"),
1521 format!(
1522 "timeline {} to {} · {} to {} · length {}",
1523 parse::tc(start, fps),
1524 parse::tc(end, fps),
1525 parse::clock(start, fps),
1526 parse::clock(end, fps),
1527 parse::tc(c.frames, fps)
1528 ),
1529 format!("track {} {label} · {path}", c.track),
1530 format!(
1531 "window {:.3}s to {:.3}s of the track",
1532 c.in_us as f64 / 1e6,
1533 c.out_us as f64 / 1e6
1534 ),
1535 link_line,
1536 format!("trim start: {}", room_text(room, fps)),
1537 format!("trim end: {}", room_text(room_end, fps)),
1538 ];
1539
1540 let structured = json!({
1541 "addr": addr,
1542 "lane": lane_nm,
1543 "kind": "subtitle",
1544 "start": start,
1545 "end": end,
1546 "length": c.frames,
1547 "clock_start": parse::clock(start, fps),
1548 "clock_end": parse::clock(end, fps),
1549 "track": c.track,
1550 "label": label,
1551 "path": path,
1552 "in_us": c.in_us,
1553 "out_us": c.out_us,
1554 "link": c.link,
1555 "link_members": members,
1556 "trim_walls": {
1557 "start": room.map(|(lo, hi)| json!({"lo": lo, "hi": hi})),
1558 "end": room_end.map(|(lo, hi)| json!({"lo": lo, "hi": hi})),
1559 },
1560 });
1561 Reply::ok(lines.join("\n")).with(structured)
1562}
1563
1564/// Addresses of the other clips and captions sharing `id`, across every lane.
1565/// The timeline's mark for a placement's link id: `link N` while another placement
1566/// shares it, and `detached (ungrouped)` when none does -- the same
1567/// words `clip_info` uses, so the two reads agree.
1568/// A linked clip's row tag: the partners' addresses, so the row says where its other half is.
1569fn link_tag(s: &PlaybackSession, id: u32, me: (Lane, u32)) -> String {
1570 let members = link_members(s, Some(id), me);
1571 if members.is_empty() {
1572 " detached (ungrouped)".to_string()
1573 } else {
1574 format!(" linked to {}", members.join(", "))
1575 }
1576}
1577
1578fn link_members(s: &PlaybackSession, id: Option<u32>, me: (Lane, u32)) -> Vec<String> {
1579 let Some(id) = id else {
1580 return Vec::new();
1581 };
1582 let mut out = Vec::new();
1583 for lane in all_lanes(s) {
1584 let starts: Vec<(u32, Option<u32>)> = match lane.kind {
1585 LaneKind::Subtitle => s.sub_lane(lane).iter().map(|c| (c.start, c.link)).collect(),
1586 _ => s.lane_clips(lane).iter().map(|c| (c.start, c.link)).collect(),
1587 };
1588 for (start, link) in starts {
1589 if link == Some(id) && (lane, start) != me {
1590 out.push(parse::addr(lane, start));
1591 }
1592 }
1593 }
1594 out
1595}
1596
1597fn walls_text(w: Option<TrimWalls>, fps: f64) -> String {
1598 match w {
1599 None => "none (this edge cannot move)".to_string(),
1600 Some(w) => {
1601 let limit = match (w.lo_media, w.hi_media) {
1602 (true, true) => " · both walls are the source's limits",
1603 (true, false) => " · lower wall is the source's limit",
1604 (false, true) => " · upper wall is the source's limit",
1605 (false, false) => " · walls are neighbouring clips or the timeline",
1606 };
1607 format!("{} to {}{limit}", parse::tc(w.lo, fps), parse::tc(w.hi, fps))
1608 }
1609 }
1610}
1611
1612fn walls_json(w: Option<TrimWalls>) -> Value {
1613 w.map_or(Value::Null, |w| {
1614 json!({
1615 "lo": w.lo,
1616 "hi": w.hi,
1617 "lo_media": w.lo_media,
1618 "hi_media": w.hi_media,
1619 })
1620 })
1621}
1622
1623fn room_text(room: Option<(u32, u32)>, fps: f64) -> String {
1624 match room {
1625 None => "none (this edge cannot move)".to_string(),
1626 Some((lo, hi)) => format!("{} to {}", parse::tc(lo, fps), parse::tc(hi, fps)),
1627 }
1628}
1629
1630/// The address of the grouped video clip whose visualizer draws a sound clip's waveform, when the
1631/// sound clip has none of its own (the picture is placed on a video lane grouped with it).
1632fn shown_by(s: &PlaybackSession, c: &Clip, lane: Lane) -> Option<String> {
1633 let id = c.link?;
1634 if lane.kind != LaneKind::Audio || c.visualizer != 0 {
1635 return None;
1636 }
1637 all_lanes(s)
1638 .into_iter()
1639 .filter(|l| l.kind == LaneKind::Video)
1640 .find_map(|l| s.lane_clips(l).iter().find(|p| p.link == Some(id) && p.visualizer != 0).map(|p| parse::addr(l, p.start)))
1641}
1642
1643fn viz_text(flags: u8) -> String {
1644 if flags == 0 {
1645 return "off".to_string();
1646 }
1647 let mut t = format!("on (style {}", VIZ_STYLES[usize::from(viz_style(flags)) & 3]);
1648 if flags & VIZ_FAST != 0 {
1649 t.push_str(", fast");
1650 }
1651 t.push(')');
1652 t
1653}
1654
1655fn viz_json(flags: u8) -> Value {
1656 json!({
1657 "on": flags != 0,
1658 "style": VIZ_STYLES[usize::from(viz_style(flags)) & 3],
1659 "fast": flags & VIZ_FAST != 0,
1660 "flags": flags,
1661 })
1662}
1663
1664// ---- helpers --------------------------------------------------------------
1665
1666/// The opacity phrase a transform line ends with: nothing at 1, otherwise
1667/// ` opacity 0.5`.
1668fn opacity_suffix(opacity: f32) -> String {
1669 if opacity == 1.0 {
1670 String::new()
1671 } else {
1672 format!(" opacity {}", num(f64::from(opacity)))
1673 }
1674}
1675
1676/// The timeline's flags for a clip; `opacity` is its transform's, when it has one, and `into` the
1677/// address of the clip a dissolve overlaps.
1678fn media_flags(c: &Clip, opacity: Option<f32>, into: Option<&str>) -> Vec<String> {
1679 let mut f = Vec::new();
1680 if c.speed_keys.is_empty() {
1681 if !c.speed.is_normal() {
1682 f.push(format!("speed {}x", num(c.speed.as_f64())));
1683 }
1684 } else {
1685 f.push(format!("speed ramp {}", ramp_text(c)));
1686 }
1687 if c.reversed {
1688 f.push("reversed".into());
1689 }
1690 if c.fade_in > 0 {
1691 f.push(format!("fade_in {}f", c.fade_in));
1692 }
1693 if c.fade_out > 0 {
1694 f.push(format!("fade_out {}f", c.fade_out));
1695 }
1696 if c.transition_out > 0 {
1697 match into {
1698 Some(next) => f.push(format!("{} {}f into {next}", c.transition_kind.name(), c.transition_out)),
1699 None => f.push(format!("{} {}f", c.transition_kind.name(), c.transition_out)),
1700 }
1701 }
1702 if c.eq.is_some() {
1703 f.push("eq".into());
1704 }
1705 if c.color.is_some() {
1706 f.push("color".into());
1707 }
1708 if c.transform.is_some() {
1709 f.push("transform".into());
1710 }
1711 if let Some(o) = opacity.filter(|o| *o != 1.0) {
1712 f.push(format!("opacity {}", num(f64::from(o))));
1713 }
1714 if c.gain_db != 0.0 {
1715 f.push(format!("gain {} dB", num(f64::from(c.gain_db))));
1716 }
1717 if !c.gain_keys.is_empty() {
1718 f.push("env".into());
1719 }
1720 if let Some(name) = fit_name(c.fit) {
1721 f.push(format!("fit {name}"));
1722 }
1723 if c.visualizer != 0 {
1724 f.push("viz".into());
1725 }
1726 f
1727}
1728
1729/// The fit name, or `None` for the default fit (which is not shown).
1730fn fit_name(fit: FitPolicy) -> Option<&'static str> {
1731 match fit {
1732 FitPolicy::Fit => None,
1733 FitPolicy::Fill => Some("fill"),
1734 FitPolicy::Stretch => Some("stretch"),
1735 FitPolicy::Center => Some("center"),
1736 }
1737}
1738
1739fn band_kind(kind: BandKind) -> &'static str {
1740 match kind {
1741 BandKind::LowShelf => "low shelf",
1742 BandKind::Peak => "peak",
1743 BandKind::HighShelf => "high shelf",
1744 BandKind::LowCut => "low cut",
1745 BandKind::HighCut => "high cut",
1746 }
1747}
1748
1749/// Every lane in display order: media lanes first, then subtitle lanes.
1750fn all_lanes(s: &PlaybackSession) -> Vec<Lane> {
1751 let mut v = s.lanes();
1752 for l in s.subtitle_lanes() {
1753 if !v.contains(&l) {
1754 v.push(l);
1755 }
1756 }
1757 v
1758}
1759
1760fn lane_names(lanes: &[Lane]) -> String {
1761 if lanes.is_empty() {
1762 return "none".to_string();
1763 }
1764 lanes
1765 .iter()
1766 .map(|&l| parse::lane_name(l))
1767 .collect::<Vec<_>>()
1768 .join(", ")
1769}
1770
1771fn overlaps(start: u32, end: u32, range: Option<(u32, u32)>) -> bool {
1772 match range {
1773 None => true,
1774 Some((from, to)) => start < to && end > from,
1775 }
1776}
1777
1778/// `src:3` for a file, `seq:1` for a compound clip's sequence.
1779fn source_tag(source: usize) -> String {
1780 match engine::project::sequence_id_of(source) {
1781 Some(id) => format!("seq:{id}"),
1782 None => format!("src:{source}"),
1783 }
1784}
1785
1786fn source_name(s: &PlaybackSession, idx: usize) -> String {
1787 if let Some(id) = engine::project::sequence_id_of(idx) {
1788 let kind = if s.angle_names(id).is_some() { "multicam" } else { "compound" };
1789 return format!("{kind} \"{}\"", s.sequence_name(id).unwrap_or_default());
1790 }
1791 if let Some(g) = s.sources().get(idx).and_then(|src| engine::generate::Gen::parse(&src.path)) {
1792 return super::generated::describe(&g);
1793 }
1794 s.sources()
1795 .get(idx)
1796 .and_then(|src| src.path.file_name())
1797 .map(|n| n.to_string_lossy().into_owned())
1798 .unwrap_or_else(|| "?".to_string())
1799}
1800
1801/// The source frame a timeline-rate frame shows, in the file's own frames: frame `c` shows
1802/// `floor(c * file / session)`. The same mapping as edit.rs `Base::native` and see.rs `clip_desc`,
1803/// with fps in micro-frames so 23.976 stays exact.
1804fn native_frame(timeline: u32, file_fps: f64, session_fps: f64) -> u32 {
1805 let micro = |fps: f64| (fps * 1e6).round().max(1.0) as u128;
1806 (u128::from(timeline) * micro(file_fps) / micro(session_fps)) as u32
1807}
1808
1809/// A source's own rate, or the timeline's when the file's rate is not known.
1810fn source_fps(s: &PlaybackSession, source: usize, fps: f64) -> f64 {
1811 s.sources()
1812 .get(source)
1813 .map(|x| s.file_fps(&x.path))
1814 .filter(|f| *f > 0.0)
1815 .unwrap_or(fps)
1816}
1817
1818/// The source range a clip plays, in source time. Clip in and out are stored at the
1819/// timeline's rate and shown as the source frames they play (`native_frame`), in the file's
1820/// own clock at `src_fps`. A still has no frames to count.
1821fn source_span_line(in_frame: u32, out_frame: u32, path: Option<&std::path::Path>, fps: f64, src_fps: f64) -> String {
1822 let in_src = native_frame(in_frame, src_fps, fps);
1823 // The out is exclusive: the clip plays its length at source speed from its in, so a 2 s clip
1824 // ends at 2.0 s of source, the same end the replies give. Both are capped at the file's real end.
1825 let dur = path.and_then(|p| engine::probe_media(p).duration_secs).filter(|d| *d > 0.0);
1826 let (_, out_secs) = src_range_secs(in_frame, out_frame, fps, src_fps, dur);
1827 let span = format!(
1828 "source in {} to out {}",
1829 parse::clock(in_src, src_fps),
1830 parse::clock((out_secs * 1000.0).round() as u32, 1000.0)
1831 );
1832 if path.is_some_and(engine::is_image) {
1833 return format!("{span} · still");
1834 }
1835 // The count is the source frames from the in to the out, so it stops at the file's own frame count.
1836 let src_frames = ((out_secs * src_fps).round() as u64).saturating_sub(u64::from(in_src));
1837 format!("{span} · {src_frames} source frames at {}", fps_text(src_fps))
1838}
1839
1840fn fmt_secs(frame: u32, fps: f64) -> String {
1841 format!("{:.3}", parse::secs(frame, fps))
1842}
1843
1844/// The lead-in a lane's gap count includes, named with the clip times' precision: ` (incl. 7.967s lead-in)`.
1845fn lead_in_note(lead: u32, fps: f64) -> String {
1846 if lead > 0 {
1847 format!(" (incl. {:.3}s lead-in)", parse::secs(lead, fps))
1848 } else {
1849 String::new()
1850 }
1851}
1852
1853/// A source's real duration in seconds, when it is known.
1854fn file_secs(s: &PlaybackSession, source: usize) -> Option<f64> {
1855 s.sources().get(source).and_then(|x| engine::probe_media(&x.path).duration_secs).filter(|d| *d > 0.0)
1856}
1857
1858/// A clip's source range in source seconds. Both ends are the source frames they show (in and out
1859/// are stored at the timeline's rate), counted at the file's own rate. The out is exclusive: it is
1860/// the frame after the last source frame the clip's last timeline frame shows, so the range has the
1861/// frame count the edit replies give (a 2 s clip of a 23.976 fps file is 48 frames, ending at
1862/// 2.002s; a 601-frame clip ends at 480 frames, 20.020s). Both ends are capped at the file's real
1863/// duration.
1864fn src_range_secs(in_frame: u32, out_frame: u32, fps: f64, src_fps: f64, dur: Option<f64>) -> (f64, f64) {
1865 let start = parse::secs(native_frame(in_frame, src_fps, fps), src_fps);
1866 let end = parse::secs(native_frame(out_frame.saturating_sub(1), src_fps, fps) + 1, src_fps);
1867 dur.map_or((start, end), |d| (start.min(d), end.min(d)))
1868}
1869
1870/// A source time in the timeline's compact text: `4.0s`, `2.033s`, `0.5s`.
1871fn src_secs_text(secs: f64) -> String {
1872 let s = format!("{secs:.3}");
1873 let t = s.trim_end_matches('0');
1874 let t = if t.ends_with('.') { format!("{t}0") } else { t.to_string() };
1875 format!("{t}s")
1876}
1877
1878fn fps_text(fps: f64) -> String {
1879 if (fps - fps.round()).abs() < 1e-6 {
1880 format!("{}", fps.round() as i64)
1881 } else {
1882 num(fps)
1883 }
1884}
1885
1886/// A clip's speed as the look shows it: `1.50x`, or the ramp's `1.00x→2.00x (3 keys)` when it has one.
1887fn speed_text(c: &Clip) -> String {
1888 if c.speed_keys.is_empty() {
1889 format!("{}x", num(c.speed.as_f64()))
1890 } else {
1891 ramp_text(c)
1892 }
1893}
1894
1895/// A speed ramp's first and last speeds and its key count: `1.00x→2.00x (3 keys)`.
1896fn ramp_text(c: &Clip) -> String {
1897 let (first, last) = (c.speed_keys.first(), c.speed_keys.last());
1898 let speed = |k: Option<&engine::project::SpeedKey>| k.map_or(0.0, |k| k.speed.as_f64());
1899 format!("{:.2}x→{:.2}x ({} keys)", speed(first), speed(last), c.speed_keys.len())
1900}
1901
1902/// A number with trailing zeros dropped: `-14`, `1.5`, `0`.
1903fn num(v: f64) -> String {
1904 let s = format!("{v:.3}");
1905 let t = s.trim_end_matches('0').trim_end_matches('.');
1906 match t {
1907 "" | "-0" => "0".to_string(),
1908 _ => t.to_string(),
1909 }
1910}
1911
1912#[cfg(test)]
1913mod tests {
1914 use super::*;
1915 use std::path::Path;
1916
1917 fn server() -> Server {
1918 engine::ao::set_silent_output();
1919 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
1920 let mut srv = Server::new();
1921 srv.session = Some(PlaybackSession::open(p).expect("open test asset"));
1922 srv
1923 }
1924
1925 fn sess(srv: &Server) -> &PlaybackSession {
1926 match srv.session_ref() {
1927 Ok(s) => s,
1928 Err(e) => panic!("{}", e.text),
1929 }
1930 }
1931
1932 fn call(srv: &mut Server, name: &str, args: Value) -> Reply {
1933 let tool = tools().into_iter().find(|t| t.name == name).expect("tool exists");
1934 (tool.run)(srv, &args)
1935 }
1936
1937 fn row(i: u32, body: &str) -> Row {
1938 Row {
1939 addr: format!("@{i}"),
1940 body: body.to_string(),
1941 json: Value::Null,
1942 }
1943 }
1944
1945 #[test]
1946 fn schemas_describe_every_property() {
1947 for tool in tools() {
1948 let schema = (tool.schema)();
1949 assert_eq!(schema["type"], "object", "{}", tool.name);
1950 assert!(schema["description"].as_str().is_some(), "{} top description", tool.name);
1951 let props = schema["properties"].as_object().expect("properties");
1952 for (key, p) in props {
1953 assert!(p["description"].as_str().is_some(), "{}.{key} has no description", tool.name);
1954 }
1955 }
1956 let t = (timeline_schema)();
1957 assert!(t["properties"]["range"]["properties"]["from"]["description"].as_str().unwrap().contains("450f"));
1958 assert_eq!((clip_info_schema)()["required"][0], "clip");
1959 }
1960
1961 #[test]
1962 fn num_drops_trailing_zeros() {
1963 assert_eq!(num(-14.0), "-14");
1964 assert_eq!(num(1.5), "1.5");
1965 assert_eq!(num(0.0), "0");
1966 assert_eq!(num(100.0), "100");
1967 assert_eq!(num(-0.0001), "0");
1968 }
1969
1970 #[test]
1971 fn brief_cuts_a_long_lane_and_says_so() {
1972 let body = "0.000–1.000 src:0 interview_long_name.mp4 in 0 out 30 link 1";
1973 let mk = || LaneView::for_test(Lane::V1, (0..400).map(|i| row(i, body)).collect());
1974 let brief = lane_lines(&[mk()], false, 3000, None).join("\n");
1975 assert!(brief.contains("more clips (use range, or lanes [\"V1\"] with page)"), "{brief}");
1976 assert!(brief.len() < 3200, "brief text is {} bytes", brief.len());
1977 let full = lane_lines(&[mk()], true, 3000, None).join("\n");
1978 assert!(!full.contains("more clips"));
1979 assert_eq!(full.lines().count(), 400);
1980 }
1981
1982 #[test]
1983 fn brief_lists_at_most_forty_clips_a_lane_even_when_bytes_allow_more() {
1984 let body = "0.000–1.000 src:0 a.mp4 in 0 out 30";
1985 let v = LaneView::for_test(Lane::V1, (0..68).map(|i| row(i, body)).collect());
1986 let brief = lane_lines(&[v], false, 100_000, None);
1987 assert_eq!(brief.iter().filter(|l| l.contains("@")).count(), CLIPS_PER_PAGE);
1988 assert!(brief.last().unwrap().contains("… 28 more clips"), "{brief:?}");
1989 }
1990
1991 #[test]
1992 fn a_page_lists_its_clips_with_a_page_line() {
1993 let body = "0.000–1.000 src:0 a.mp4 in 0 out 30";
1994 let mut v = LaneView::for_test(Lane::V1, (40..68).map(|i| row(i, body)).collect());
1995 v.page = Some(LanePage::of(2, 68));
1996 let lines = lane_lines(&[v], false, 100, None);
1997 assert_eq!(lines[0], "V1 clips 41–68 of 68 · page 2 of 2");
1998 assert_eq!(lines.len(), 29, "the page is listed whole, with no cut line");
1999 assert!(!lines.iter().any(|l| l.contains("more clips")));
2000 }
2001
2002 #[test]
2003 fn a_lane_header_counts_its_graded_clips_past_the_cut() {
2004 let body = "0.000–1.000 src:0 a.mp4 in 0 out 30 color";
2005 let graded = |i: u32| Row { addr: format!("@{i}"), body: body.into(), json: json!({"color": true}) };
2006 let plain = |i: u32| Row { addr: format!("@{i}"), body: body.into(), json: json!({"color": false}) };
2007 let mut rows: Vec<Row> = (0..50).map(graded).collect();
2008 rows.extend((50..68).map(plain));
2009 let v = LaneView::for_test(Lane::V1, rows);
2010 assert_eq!(v.coloured, 50);
2011 let lines = lane_lines(&[v], false, 100_000, None);
2012 assert_eq!(lines[0], "V1 color on 50 of 68 clips");
2013 assert_eq!(lines.iter().filter(|l| l.contains("@")).count(), CLIPS_PER_PAGE);
2014 }
2015
2016 #[test]
2017 fn page_arg_wants_a_number_from_one() {
2018 assert_eq!(page_arg(&json!({})).ok(), Some(None));
2019 assert_eq!(page_arg(&json!({"page": 2})).ok(), Some(Some(2)));
2020 assert!(page_arg(&json!({"page": 0})).is_err());
2021 assert!(page_arg(&json!({"page": "two"})).is_err());
2022 }
2023
2024 #[test]
2025 fn timeline_pages_one_lane_and_refuses_a_page_without_one() {
2026 let mut srv = server();
2027 let n = sess(&srv).lane_clips(Lane::V1).len();
2028 let pages = n.div_ceil(CLIPS_PER_PAGE).max(1);
2029 let r = call(&mut srv, "timeline", json!({"lanes": ["V1"], "page": 1}));
2030 assert!(!r.is_error, "{}", r.text);
2031 assert!(r.text.contains(&format!("of {n} · page 1 of {pages}")), "{}", r.text);
2032 let past = call(&mut srv, "timeline", json!({"lanes": ["V1"], "page": pages + 1}));
2033 assert!(past.is_error);
2034 assert!(
2035 past.text.contains(&format!("page {} is past the end: V1 has {pages} page(s)", pages + 1)),
2036 "{}",
2037 past.text
2038 );
2039 let none = call(&mut srv, "timeline", json!({"page": 1}));
2040 assert!(none.is_error);
2041 assert!(none.text.contains("pages one lane"), "{}", none.text);
2042 }
2043
2044 #[test]
2045 fn timeline_shows_a_lane_name_on_the_header() {
2046 let mut srv = server();
2047 let plain = call(&mut srv, "timeline", json!({}));
2048 assert!(plain.structured.as_ref().unwrap()["lanes"][0]["name"].is_null());
2049 assert_eq!(srv.session.as_mut().unwrap().set_lane_name(Lane::V1, "Cam A"), Ok(true));
2050 let r = call(&mut srv, "timeline", json!({}));
2051 assert!(r.text.contains("V1 \"Cam A\""), "{}", r.text);
2052 let v1 = &r.structured.as_ref().unwrap()["lanes"][0];
2053 assert_eq!((v1["lane"].as_str(), v1["name"].as_str()), (Some("V1"), Some("Cam A")));
2054 }
2055
2056 #[test]
2057 fn timeline_lists_the_test_asset() {
2058 let mut srv = server();
2059 let first = sess(&srv).lane_clips(Lane::V1)[0].start;
2060 let r = call(&mut srv, "timeline", json!({}));
2061 assert!(!r.is_error, "{}", r.text);
2062 assert!(r.text.starts_with("untitled · "), "{}", r.text);
2063 assert!(r.text.contains(" undo "), "{}", r.text);
2064 assert!(r.text.contains(&format!("V1 @{first} ")), "{}", r.text);
2065 assert!(r.text.contains("src:0 test_av.mp4"), "{}", r.text);
2066 assert!(r.text.contains("gaps: V1 "), "{}", r.text);
2067 let v1 = &r.structured.as_ref().expect("structured")["lanes"][0];
2068 assert_eq!(v1["lane"], "V1");
2069 assert_eq!(v1["clips"][0]["addr"], format!("V1@{first}"));
2070 // Brief structuredContent is compact: no source, edits or effect flags per clip.
2071 let brief = v1["clips"][0].as_object().expect("clip object");
2072 assert!(brief.contains_key("start") && brief.contains_key("end"), "{brief:?}");
2073 assert!(!brief.contains_key("source") && !brief.contains_key("fade_in"), "{brief:?}");
2074 let full = call(&mut srv, "timeline", json!({"detail": "full"}));
2075 let v1 = &full.structured.as_ref().expect("structured")["lanes"][0];
2076 assert!(v1["clips"][0].get("source").is_some() && v1["clips"][0].get("fade_in").is_some());
2077 }
2078
2079 #[test]
2080 fn timeline_refuses_an_unknown_lane() {
2081 let mut srv = server();
2082 let r = call(&mut srv, "timeline", json!({"lanes": ["V9"]}));
2083 assert!(r.is_error);
2084 assert!(r.text.contains("is not a lane in this project"), "{}", r.text);
2085 let bad = call(&mut srv, "timeline", json!({"detail": "loud"}));
2086 assert!(bad.is_error && bad.text.contains("brief or full"), "{}", bad.text);
2087 }
2088
2089 #[test]
2090 fn timeline_range_keeps_only_overlapping_clips() {
2091 let mut srv = server();
2092 let r = call(&mut srv, "timeline", json!({"range": {"from": "0f", "to": "0f"}}));
2093 assert!(!r.is_error, "{}", r.text);
2094 assert!(r.text.contains("V1 no clips in range"), "{}", r.text);
2095 assert!(!r.text.contains("src:"), "{}", r.text);
2096 let back = call(&mut srv, "timeline", json!({"range": {"from": 5, "to": 1}}));
2097 assert!(back.is_error);
2098 }
2099
2100 /// A source with no sound says `audio: none` where a sound source names its stream.
2101 #[test]
2102 fn clip_info_at_answers_match_frame() {
2103 let mut srv = server();
2104 let r = call(&mut srv, "clip_info", json!({"clip": "V1@0", "at": "1s"}));
2105 assert!(!r.is_error, "{}", r.text);
2106 assert!(r.text.contains("match frame at 30f: src:0 test_av.mp4") && r.text.contains("source time 1.000s"), "{}", r.text);
2107 assert_eq!(r.structured.as_ref().unwrap()["match_frame"]["source"], 0);
2108 let r = call(&mut srv, "clip_info", json!({"clip": "V1@0", "at": "100s"}));
2109 assert!(r.is_error && r.text.contains("outside V1@0"), "{}", r.text);
2110 }
2111
2112 #[test]
2113 fn clip_info_says_when_a_source_has_no_sound() {
2114 let root = env!("CARGO_MANIFEST_DIR");
2115 let silent = std::path::PathBuf::from(format!("{root}/../../assets/test_rotation90.mp4"));
2116 let with_sound = std::path::PathBuf::from(format!("{root}/../../assets/test_h264.mkv"));
2117 assert_eq!(source_sound(Some(&silent), 0), "audio: none");
2118 // The stream names its language, as the probe reads it (`und` where the file names none).
2119 let lang = audio_tracks(&with_sound)[0].1.clone();
2120 assert_eq!(source_sound(Some(&with_sound), 0), format!("audio stream 0 ({lang})"));
2121 assert_eq!(source_sound(None, 2), "audio stream 2");
2122 }
2123
2124 /// A lone link id is a detach by the user, not a removed partner: the words say `ungrouped`.
2125 #[test]
2126 fn an_ungrouped_clip_reads_as_ungrouped_not_as_a_removed_partner() {
2127 let mut srv = server();
2128 {
2129 let s = srv.session.as_mut().expect("session");
2130 // The test asset's first take (V1 and A1) is linked already; ungroup leaves the
2131 // partner with an id of its own, which nothing else shares.
2132 assert!(s.ungroup(Lane::V1, 0));
2133 }
2134 let r = call(&mut srv, "clip_info", json!({"clip": "A1#0"}));
2135 assert!(!r.is_error, "{}", r.text);
2136 assert!(r.text.contains("detached (ungrouped)"), "{}", r.text);
2137 assert!(!r.text.contains("partner was removed"), "{}", r.text);
2138 let t = call(&mut srv, "timeline", json!({}));
2139 assert!(!t.text.contains("partner was removed"), "{}", t.text);
2140 }
2141
2142 /// A sound clip whose waveform picture sits on a grouped video lane says so, not "visualizer off".
2143 #[test]
2144 fn sound_clip_names_the_grouped_visualizer_that_shows_it() {
2145 let mut srv = server();
2146 let r = super::super::edit::run_edit(&mut srv, &json!({"ops": [{"op": "visualizer", "clip": "A1#0", "on": true}]}));
2147 assert!(!r.is_error, "{}", r.text);
2148 // The picture lands on a video lane grouped with the sound clip (V2 here, V1 is busy at 0).
2149 let info = call(&mut srv, "clip_info", json!({"clip": "A1#0"}));
2150 assert!(info.text.contains("visualizer: shown by V"), "{}", info.text);
2151 assert!(!info.text.contains("visualizer off"), "{}", info.text);
2152 }
2153
2154 /// The timeline row of a dissolving clip names the clip its overlap runs into.
2155 #[test]
2156 fn timeline_marks_the_dissolve_overlap_into_the_next_clip() {
2157 let mut srv = server();
2158 let r = super::super::edit::run_edit(
2159 &mut srv,
2160 &json!({"ops": [{"op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": false, "overwrite": true}]}),
2161 );
2162 assert!(!r.is_error, "{}", r.text);
2163 let len = sess(&srv).lane_clips(Lane::V1)[0].frames();
2164 let r = super::super::edit::run_edit(
2165 &mut srv,
2166 &json!({"ops": [
2167 {"op": "place", "source": 0, "lane": "V1", "at": format!("{len}f"), "audio": false, "overwrite": true},
2168 {"op": "dissolve", "clip": "V1@0", "frames": 12}
2169 ]}),
2170 );
2171 assert!(!r.is_error, "{}", r.text);
2172 let tl = call(&mut srv, "timeline", json!({}));
2173 assert!(tl.text.contains(&format!("dissolve 12f into V1@{len}")), "{}", tl.text);
2174 }
2175
2176 /// A transition's kind shows in the timeline row and in clip_info, text and JSON.
2177 #[test]
2178 fn timeline_and_clip_info_name_the_transition_kind() {
2179 let mut srv = server();
2180 let r = super::super::edit::run_edit(
2181 &mut srv,
2182 &json!({"ops": [{"op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": false, "overwrite": true}]}),
2183 );
2184 assert!(!r.is_error, "{}", r.text);
2185 let len = sess(&srv).lane_clips(Lane::V1)[0].frames();
2186 let r = super::super::edit::run_edit(
2187 &mut srv,
2188 &json!({"ops": [
2189 {"op": "place", "source": 0, "lane": "V1", "at": format!("{len}f"), "audio": false, "overwrite": true},
2190 {"op": "transition", "clip": "V1@0", "kind": "wipe", "direction": "down", "frames": 12}
2191 ]}),
2192 );
2193 assert!(!r.is_error, "{}", r.text);
2194 let tl = call(&mut srv, "timeline", json!({}));
2195 assert!(tl.text.contains(&format!("wipe-down 12f into V1@{len}")), "{}", tl.text);
2196 let info = call(&mut srv, "clip_info", json!({"clip": "V1@0"}));
2197 assert!(info.text.contains("wipe-down 12f"), "{}", info.text);
2198 let st = info.structured.as_ref().expect("structured");
2199 assert_eq!(st["transition_kind"], "wipe-down", "{st:?}");
2200 }
2201
2202 /// A keyed clip shows its keys in text, JSON and the timeline row, and no single transform line.
2203 #[test]
2204 fn clip_info_and_timeline_show_transform_keys() {
2205 let mut srv = server();
2206 let s = srv.session.as_mut().expect("session");
2207 let r = super::super::edit_fx::apply(
2208 s,
2209 &json!({"op": "transform_keys", "clip": "V1#0", "keys": [
2210 {"at": "0s", "scale": 1.0},
2211 {"at": "end", "scale": 1.2, "x": 0.1, "ease": "ease"}
2212 ]}),
2213 30.0,
2214 )
2215 .expect("transform_keys is an edit_fx op");
2216 assert!(r.is_ok(), "{:?}", r.err());
2217
2218 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2219 assert!(!info.is_error, "{}", info.text);
2220 assert!(info.text.contains("transform keys: 2"), "{}", info.text);
2221 assert!(!info.text.contains("transform: none"), "{}", info.text);
2222 assert!(info.text.contains("scale 1.2 "), "{}", info.text);
2223 // The first key sits at the clip's start: its clip time and its timeline time both read 0.
2224 assert!(info.text.contains("at clip 0.000s (timeline 0.000s) x 0 y 0"), "{}", info.text);
2225 assert!(info.text.contains(" ease ease_in_out"), "{}", info.text);
2226 let st = info.structured.expect("structured");
2227 let keys = st["transform_keys"].as_array().expect("keys array");
2228 assert_eq!(keys.len(), 2, "{st}");
2229 assert!((keys[1]["scale"].as_f64().expect("scale") - 1.2).abs() < 1e-5, "{st}");
2230 assert_eq!(keys[1]["ease"].as_str(), Some("ease_in_out"), "{st}");
2231 assert!(keys[0]["time"].as_f64().is_some(), "{st}");
2232
2233 let tl = call(&mut srv, "timeline", json!({}));
2234 assert!(tl.text.contains("keys 2"), "{}", tl.text);
2235 }
2236
2237 /// A clip with no keys says `transform: none` and an empty key list.
2238 #[test]
2239 fn clip_info_without_keys_has_no_key_lines() {
2240 let mut srv = server();
2241 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2242 assert!(info.text.contains("transform: none"), "{}", info.text);
2243 assert!(!info.text.contains("transform keys"), "{}", info.text);
2244 assert_eq!(info.structured.expect("structured")["transform_keys"], json!([]));
2245 }
2246
2247 #[test]
2248 fn clip_info_describes_the_first_clip() {
2249 let mut srv = server();
2250 let first = sess(&srv).lane_clips(Lane::V1)[0].start;
2251 for addr in [format!("V1@{first}"), "V1#0".to_string()] {
2252 let r = call(&mut srv, "clip_info", json!({"clip": addr}));
2253 assert!(!r.is_error, "{}", r.text);
2254 assert!(r.text.starts_with(&format!("V1@{first} · lane V1 · video")), "{}", r.text);
2255 assert!(r.text.contains("test_av.mp4"), "{}", r.text);
2256 assert!(r.text.contains("trim start:"), "{}", r.text);
2257 assert!(r.text.contains("eq: none"), "{}", r.text);
2258 let st = r.structured.expect("structured");
2259 assert_eq!(st["lane"], "V1");
2260 assert_eq!(st["kind"], "video");
2261 assert_eq!(st["start"], first);
2262 }
2263 }
2264
2265 #[test]
2266 fn clip_info_and_timeline_show_the_volume_envelope() {
2267 let mut srv = server();
2268 let r = crate::tools::edit::run_edit(
2269 &mut srv,
2270 &json!({"ops": [
2271 {"op": "move", "clip": "A1#0", "at": "2s"},
2272 {"op": "trim", "clip": "A1#0", "edge": "in", "to": "3s"},
2273 {"op": "gain_keys", "clip": "A1#0", "keys": [["3.5s", -12], ["4s", -3]]}
2274 ]}),
2275 );
2276 assert!(!r.is_error, "{}", r.text);
2277 // The points read back as timeline times, not the source frames they are stored on.
2278 let info = call(&mut srv, "clip_info", json!({"clip": "A1#0"}));
2279 assert!(!info.is_error, "{}", info.text);
2280 assert!(info.text.contains("gain keys: 3.500s -12.0 dB · 4.000s -3.0 dB"), "{}", info.text);
2281 // The timeline marks the clip with an envelope.
2282 let tl = call(&mut srv, "timeline", json!({}));
2283 assert!(!tl.is_error, "{}", tl.text);
2284 assert!(tl.text.contains(" env"), "{}", tl.text);
2285 }
2286
2287 #[test]
2288 fn clip_info_and_timeline_show_the_speed_ramp() {
2289 let mut srv = server();
2290 let r = crate::tools::edit::run_edit(
2291 &mut srv,
2292 &json!({"ops": [
2293 {"op": "speed_ramp", "clip": "V1#0", "keys": [
2294 {"at": "0s", "speed": 1.0}, {"at": "1s", "speed": 1.5}, {"at": "2s", "speed": 2.0}
2295 ]}
2296 ]}),
2297 );
2298 assert!(!r.is_error, "{}", r.text);
2299 // The first and last speeds and the key count replace the constant speed.
2300 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2301 assert!(!info.is_error, "{}", info.text);
2302 assert!(info.text.contains("speed 1.00x→2.00x (3 keys) ·"), "{}", info.text);
2303 assert!(!info.text.lines().any(|l| l.starts_with("speed 1x")), "{}", info.text);
2304 let tl = call(&mut srv, "timeline", json!({}));
2305 assert!(!tl.is_error, "{}", tl.text);
2306 assert!(tl.text.contains("speed ramp 1.00x→2.00x (3 keys)"), "{}", tl.text);
2307 }
2308
2309 #[test]
2310 fn clip_info_reads_back_pan_pitch_deinterlace_and_every_ramp_key() {
2311 let mut srv = server();
2312 let r = crate::tools::edit::run_edit(
2313 &mut srv,
2314 &json!({"ops": [
2315 {"op": "pan", "clip": "A1#0", "pan": -0.5},
2316 {"op": "pitch", "clip": "A1#0", "semitones": 3},
2317 {"op": "deinterlace", "clip": "V1#0", "mode": "field"},
2318 {"op": "speed_ramp", "clip": "V1#0", "keys": [
2319 {"at": "0s", "speed": 1.0}, {"at": "1s", "speed": 1.5}, {"at": "2s", "speed": 2.0}
2320 ]}
2321 ]}),
2322 );
2323 assert!(!r.is_error, "{}", r.text);
2324 let audio = call(&mut srv, "clip_info", json!({"clip": "A1#0"}));
2325 assert!(audio.text.contains("pan -0.5 · pitch +3 semitones"), "{}", audio.text);
2326 assert_eq!(audio.structured.as_ref().unwrap()["pan"], -0.5);
2327 assert_eq!(audio.structured.as_ref().unwrap()["pitch"], 3.0);
2328 let video = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2329 assert!(video.text.contains("deinterlace field"), "{}", video.text);
2330 assert!(video.text.contains("speed keys: 3\n at clip 0.000s speed 1x\n at clip 1.000s speed 1.5x\n at clip 2.000s speed 2x"), "{}", video.text);
2331 let v = video.structured.as_ref().unwrap();
2332 assert_eq!(v["deinterlace"], "field");
2333 assert_eq!(v["speed_keys"].as_array().unwrap().len(), 3);
2334 assert_eq!(v["speed_keys"][1]["clip_time"], 1.0);
2335 // Brief timeline rows name a pitch that is set, and leave out a deinterlace at its default.
2336 let tl = call(&mut srv, "timeline", json!({}));
2337 assert!(tl.text.contains("pitch +3"), "{}", tl.text);
2338 assert!(!tl.text.contains("deinterlace frame"), "{}", tl.text);
2339 }
2340
2341 #[test]
2342 fn reverse_toggles_with_on_and_shows_in_clip_info_and_timeline() {
2343 let mut srv = server();
2344 let edit = |srv: &mut Server, op: Value| crate::tools::edit::run_edit(srv, &json!({"ops": [op]}));
2345 // Forward clips say nothing.
2346 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2347 assert!(!info.text.contains("reversed"), "{}", info.text);
2348 // No `on` toggles.
2349 let r = edit(&mut srv, json!({"op": "reverse", "clip": "V1#0"}));
2350 assert!(!r.is_error, "{}", r.text);
2351 assert!(r.text.contains("plays backward"), "{}", r.text);
2352 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2353 assert!(info.text.contains("· reversed ·"), "{}", info.text);
2354 let tl = call(&mut srv, "timeline", json!({}));
2355 assert!(tl.text.contains("reversed"), "{}", tl.text);
2356 // The take goes with it.
2357 let sound = call(&mut srv, "clip_info", json!({"clip": "A1#0"}));
2358 assert!(sound.text.contains("reversed"), "{}", sound.text);
2359 // An explicit `on` that already holds changes nothing and says so.
2360 let r = edit(&mut srv, json!({"op": "reverse", "clip": "V1#0", "on": true}));
2361 assert!(!r.is_error && r.text.contains("already reversed"), "{}", r.text);
2362 // on:false puts it back; a bad `on` refuses; undo takes a step back.
2363 let r = edit(&mut srv, json!({"op": "reverse", "clip": "V1#0", "on": false}));
2364 assert!(!r.is_error && r.text.contains("forward again"), "{}", r.text);
2365 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2366 assert!(!info.text.contains("reversed"), "{}", info.text);
2367 let r = edit(&mut srv, json!({"op": "reverse", "clip": "V1#0", "on": "yes"}));
2368 assert!(r.is_error && r.text.contains("`on` must be true or false"), "{}", r.text);
2369 let u = crate::tools::edit::run_undo(&mut srv, &json!({}));
2370 assert!(!u.is_error, "{}", u.text);
2371 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2372 assert!(info.text.contains("reversed"), "{}", info.text);
2373 }
2374
2375 #[test]
2376 fn reverse_composes_with_speed_in_clip_info() {
2377 let mut srv = server();
2378 let r = crate::tools::edit::run_edit(
2379 &mut srv,
2380 &json!({"ops": [
2381 {"op": "reverse", "clip": "V1#0"},
2382 {"op": "speed", "clip": "V1#0", "x": 2.0}
2383 ]}),
2384 );
2385 assert!(!r.is_error, "{}", r.text);
2386 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2387 assert!(info.text.contains("speed 2x · reversed"), "{}", info.text);
2388 }
2389
2390 #[test]
2391 fn clip_info_and_timeline_show_opacity_only_when_it_is_partial() {
2392 let mut srv = server();
2393 let set = |srv: &mut Server, op: Value| {
2394 let s = srv.session.as_mut().expect("session");
2395 let r = super::super::edit_fx::apply(s, &op, 30.0).expect("transform is an edit_fx op");
2396 assert!(r.is_ok(), "{:?}", r.err());
2397 };
2398 // A placement at full opacity says nothing about opacity.
2399 set(&mut srv, json!({"op": "transform", "clip": "V1#0", "x": 0.1}));
2400 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2401 assert!(!info.is_error, "{}", info.text);
2402 assert!(info.text.contains("transform: pos 0.1 0 "), "{}", info.text);
2403 assert!(!info.text.contains("opacity"), "{}", info.text);
2404 assert!(info.structured.expect("structured")["transform"].get("opacity").is_none());
2405 // Half opacity shows in the text, the JSON and the timeline row.
2406 set(&mut srv, json!({"op": "transform", "clip": "V1#0", "opacity": 0.5}));
2407 let info = call(&mut srv, "clip_info", json!({"clip": "V1#0"}));
2408 assert!(info.text.contains("bottom 0 opacity 0.5"), "{}", info.text);
2409 let st = info.structured.expect("structured");
2410 assert_eq!(st["transform"]["opacity"].as_f64(), Some(0.5), "{st}");
2411 let tl = call(&mut srv, "timeline", json!({}));
2412 assert!(tl.text.contains("opacity 0.5"), "{}", tl.text);
2413 }
2414
2415 #[test]
2416 fn clip_info_refusals_say_what_to_do() {
2417 let mut srv = server();
2418 let no_clip = call(&mut srv, "clip_info", json!({"clip": "V1@999999"}));
2419 assert!(no_clip.is_error && no_clip.text.contains("no clip at"), "{}", no_clip.text);
2420 let not_addr = call(&mut srv, "clip_info", json!({"clip": "V1"}));
2421 assert!(not_addr.is_error && not_addr.text.contains("not a clip address"), "{}", not_addr.text);
2422 let missing = call(&mut srv, "clip_info", json!({}));
2423 assert!(missing.is_error && missing.text.contains("missing argument `clip`"), "{}", missing.text);
2424 let caption = call(&mut srv, "clip_info", json!({"clip": "S1@0"}));
2425 assert!(caption.is_error && caption.text.contains("no clips"), "{}", caption.text);
2426 }
2427
2428 #[test]
2429 fn chapter_listing_is_youtube_text_with_its_warnings() {
2430 // Three chapters, each over 10 s, the first at 00:00: no warnings, MM:SS (and H:MM:SS past an hour).
2431 let good = vec![(0, "Intro".to_string()), (4500, "Setup".to_string()), (9000, "Done".to_string())];
2432 let (text, warnings) = chapter_listing(&good, 30.0, 9000 + 3000);
2433 assert_eq!(text, "00:00 Intro\n02:30 Setup\n05:00 Done");
2434 assert!(warnings.is_empty(), "{warnings:?}");
2435 let (hours, _) = chapter_listing(&[(0, "A".into()), (3600 * 30, "B".into()), (3600 * 30 + 900 * 30, "C".into())], 30.0, 3600 * 30 + 1800 * 30);
2436 assert!(hours.contains("1:00:00 B"), "{hours}");
2437 // Two chapters, the first not at 0, both 1 s long: four warnings, one per rule broken.
2438 let bad = vec![(30, "A".to_string()), (60, "B".to_string())];
2439 let (_, warnings) = chapter_listing(&bad, 30.0, 90);
2440 assert_eq!(warnings.len(), 4, "{warnings:?}");
2441 assert!(warnings[0].contains("not 00:00"), "{warnings:?}");
2442 assert!(warnings[1].contains("\"A\"") && warnings[2].contains("\"B\""), "{warnings:?}");
2443 assert!(warnings[3].contains("at least 3 chapters; this timeline has 2"), "{warnings:?}");
2444 assert_eq!(chapter_listing(&[], 30.0, 90), (String::new(), Vec::new()));
2445 }
2446
2447 #[test]
2448 fn timeline_lists_chapters_on_a_chapters_line() {
2449 let mut server = Server::new();
2450 let mut sess = PlaybackSession::empty(1280, 720, 30.0).unwrap();
2451 sess.add_chapter(0, "Intro").unwrap();
2452 sess.add_chapter(900, "Setup").unwrap();
2453 server.session = Some(sess);
2454 let r = timeline(&mut server, &json!({}));
2455 assert!(!r.is_error, "{}", r.text);
2456 assert!(r.text.contains("chapters: C@0 Intro (00:00) · C@900 Setup (00:30)"), "{}", r.text);
2457 assert!(r.text.contains("chapters: first chapter") || r.text.contains("chapters: YouTube needs at least 3"), "{}", r.text);
2458 let structured = r.structured.as_ref().expect("structured output");
2459 assert_eq!(structured["chapters"][1]["addr"], "C@900");
2460 assert_eq!(structured["chapters_text"], "00:00 Intro\n00:30 Setup");
2461 }
2462
2463 #[test]
2464 fn timeline_lists_markers_on_a_markers_line() {
2465 use engine::project::{Marker, MarkerColor};
2466 let mut server = Server::new();
2467 let mut sess = PlaybackSession::empty(1280, 720, 30.0).unwrap();
2468 let mk = |frame, length, name: &str, note: &str, color| Marker { frame, length, name: name.into(), note: note.into(), color };
2469 sess.add_marker(mk(900, 0, "Fix", "tighten", MarkerColor::Red)).unwrap();
2470 sess.add_marker(mk(30, 60, "Range", "", MarkerColor::Green)).unwrap();
2471 server.session = Some(sess);
2472 let r = timeline(&mut server, &json!({}));
2473 assert!(!r.is_error, "{}", r.text);
2474 assert!(r.text.contains("markers: M@30–90f Range [green] · M@900 Fix [red] — tighten"), "{}", r.text);
2475 let structured = r.structured.as_ref().expect("structured output");
2476 assert_eq!(structured["markers"][1]["addr"], "M@900");
2477 assert_eq!(structured["markers"][0]["length"], 60);
2478 assert_eq!(structured["markers"][1]["note"], "tighten");
2479 }
2480
2481 #[test]
2482 fn undo_header_counts_ledger_steps() {
2483 let mut server = Server::new();
2484 server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap());
2485 server.ledger = vec![crate::server::Entry::new(1, "a"), crate::server::Entry::new(1, "b"), crate::server::Entry::new(1, "c")];
2486 server.redo_ledger = vec![crate::server::Entry::new(1, "d")];
2487 let r = timeline(&mut server, &json!({}));
2488 assert!(!r.is_error, "{}", r.text);
2489 assert!(r.text.contains("undo 3 · redo 1"), "{}", r.text);
2490 }
2491
2492 #[test]
2493 fn source_span_is_source_time_at_the_source_rate() {
2494 // A clip at timeline frames 125..275 at 30 fps: source time 4.167 s to 9.167 s.
2495 let same = source_span_line(125, 275, Some(Path::new("/x/a.mp4")), 30.0, 30.0);
2496 assert_eq!(same, "source in 00:04.167 to out 00:09.167 · 150 source frames at 30");
2497 let slower = source_span_line(125, 275, Some(Path::new("/x/a.mp4")), 30.0, 23.976);
2498 assert!(slower.ends_with("· 120 source frames at 23.976"), "{slower}");
2499 let still = source_span_line(125, 275, Some(Path::new("/x/a.png")), 30.0, 30.0);
2500 assert!(still.ends_with("· still"), "{still}");
2501 }
2502
2503 /// A lead-in is named with three decimals, as clip times are: 7.967 s is not 8.0 s.
2504 #[test]
2505 fn a_lead_in_is_named_to_the_clip_time_precision() {
2506 assert_eq!(lead_in_note(0, 30.0), "");
2507 assert_eq!(lead_in_note(239, 30.0), " (incl. 7.967s lead-in)");
2508 }
2509
2510 /// The source end is capped at the file's real duration, and a whole second reads as itself.
2511 #[test]
2512 fn a_source_time_past_the_real_duration_reads_the_duration() {
2513 assert_eq!(src_secs_text(6.0), "6.0s");
2514 assert_eq!(src_secs_text(5.968), "5.968s");
2515 let (_, end) = src_range_secs(0, 150, 25.0, 25.0, Some(5.968));
2516 assert_eq!(src_secs_text(end), "5.968s");
2517 let (start, end) = src_range_secs(0, 125, 25.0, 25.0, Some(5.968));
2518 assert_eq!((src_secs_text(start), src_secs_text(end)), ("0.0s".to_string(), "5.0s".to_string()));
2519 }
2520
2521 /// A 2 s clip at 30 fps on a 23.976 fps source reads its source range in the source's own
2522 /// frames: its last timeline frame shows source frame 47, so the range is 48 frames and ends at
2523 /// 2.002s (48 / 23.976), as the edit reply says, and not at the clip's 2.0 s length.
2524 #[test]
2525 fn a_two_second_clip_reads_its_source_frames_in_source_time() {
2526 let (start, end) = src_range_secs(0, 60, 30.0, 23.976, None);
2527 assert_eq!((src_secs_text(start), src_secs_text(end)), ("0.0s".to_string(), "2.002s".to_string()));
2528 }
2529
2530 /// The timeline's label for a 601-frame clip at 30 fps on a 23.976 fps source is the source's
2531 /// own 480 frames: `0.0s–20.02s` (480 / 23.976), not the clip's 20.033 s length at 30 fps.
2532 #[test]
2533 fn a_clip_of_480_source_frames_ends_at_their_own_time() {
2534 let (start, end) = src_range_secs(0, 601, 30.0, 23.976, None);
2535 assert_eq!((src_secs_text(start), src_secs_text(end)), ("0.0s".to_string(), "20.02s".to_string()));
2536 }
2537
2538 /// A whole 23.976 fps file (48 frames) placed at 30 fps: its out rounds up to timeline frame 61,
2539 /// which is past the file's last frame, so the count is the file's 48, not 49.
2540 #[test]
2541 fn a_whole_file_counts_its_own_frames() {
2542 let asset = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_23976fps.mp4");
2543 let whole = source_span_line(0, 61, Some(&asset), 30.0, 23.976);
2544 assert!(whole.ends_with("· 48 source frames at 23.976"), "{whole}");
2545 }
2546
2547 /// A 25 fps source in a 30 fps project: `place` reports the source time it plays, and the
2548 /// timeline row, clip_info and the source-span line must agree with it.
2549 #[test]
2550 fn a_25_fps_source_reads_the_same_in_place_timeline_and_clip_info() {
2551 engine::ao::set_silent_output();
2552 // in 0.52s and in 0.5s both round to source frame 13 (0.5s is 12.5, ties up), stored as
2553 // timeline frame 16, which shows floor(16 * 25 / 30) = 13 at 0.520s. A one second clip
2554 // (30 timeline frames) then ends on frame 46, which shows 1.520s.
2555 let cases = [("0.52s", "0.520s", "1.520s", "00:00.520", "00:01.520"), ("0.5s", "0.520s", "1.520s", "00:00.520", "00:01.520")];
2556 for (input, src_in, src_out, clock_in, clock_out) in cases {
2557 let mut sess = engine::PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
2558 sess.import(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_25fps.mp4"))
2559 .expect("import 25 fps asset");
2560 let mut srv = Server { session: Some(sess), ..Server::default() };
2561 let ed = crate::help::catalogue().into_iter().find(|t| t.name == "edit").expect("edit tool");
2562 let args = json!({"ops": [{"op": "place", "source": 0, "lane": "V1", "at": "0s", "in": input, "length": "1s"}]});
2563 let placed = (ed.run)(&mut srv, &args);
2564 assert!(!placed.is_error, "{}", placed.text);
2565 assert!(placed.text.contains(&format!("src {src_in}")), "place reply: {}", placed.text);
2566
2567 let t = call(&mut srv, "timeline", json!({"lanes": ["V1"]}));
2568 assert!(!t.is_error, "timeline: {}", t.text);
2569 // The timeline prints the compact form of the same time: 0.520s is `0.52s`.
2570 let compact = |t: &str| format!("{}s", t.trim_end_matches('s').trim_end_matches('0'));
2571 let want = format!("src {}–{}", compact(src_in), compact(src_out));
2572 assert!(t.text.contains(&want), "timeline: {}", t.text);
2573
2574 let info = call(&mut srv, "clip_info", json!({"clip": "V1@0"}));
2575 assert!(!info.is_error, "clip_info: {}", info.text);
2576 assert!(info.text.contains(&format!("source in {clock_in} to out {clock_out}")), "clip_info: {}", info.text);
2577 }
2578 }
2579
2580 /// A lane holding two ducks (one per key) shows both in its header, in timeline and in the
2581 /// project status, with the structured lists carrying each and `duck` the first.
2582 #[test]
2583 fn every_duck_on_a_lane_is_shown() {
2584 use engine::duck::Duck;
2585 use engine::project::LaneKind;
2586 let mut srv = server();
2587 let s = srv.session.as_mut().unwrap();
2588 s.add_lane(LaneKind::Audio);
2589 s.add_lane(LaneKind::Audio);
2590 let duck = |under| Duck { under, depth_db: -12.0, threshold_db: -40.0, attack_ms: 80.0, release_ms: 400.0 };
2591 assert!(s.set_lane_duck(Lane::A1, Some(duck(1))), "duck under A2 set");
2592 assert!(s.set_lane_duck(Lane::A1, Some(duck(2))), "duck under A3 set");
2593 assert_eq!(s.lane_duck_list(Lane::A1).len(), 2);
2594
2595 let t = call(&mut srv, "timeline", json!({}));
2596 assert!(t.text.contains("duck under A2 -12dB") && t.text.contains("duck under A3 -12dB"), "{}", t.text);
2597 let lanes = t.structured.as_ref().unwrap()["lanes"].as_array().unwrap().clone();
2598 let a1 = lanes.iter().find(|l| l["lane"] == "A1").expect("A1 listed");
2599 assert_eq!(a1["duck"]["under"], "A2", "duck is the first one");
2600 let ducks = a1["ducks"].as_array().expect("ducks list");
2601 assert_eq!(ducks.len(), 2);
2602 assert_eq!(ducks[1]["under"], "A3");
2603
2604 let status = crate::server::tools().into_iter().find(|t| t.name == "project_status").expect("project_status is registered");
2605 let st = (status.run)(&mut srv, &json!({}));
2606 assert!(st.text.contains("ducks: A1 under A2 -12dB · A1 under A3 -12dB"), "{}", st.text);
2607 let listed = st.structured.as_ref().unwrap()["ducks"].as_array().unwrap().clone();
2608 assert_eq!(listed.len(), 2);
2609 assert_eq!(listed[1]["under"], "A3");
2610 }
2611
2612 #[test]
2613 fn duck_shows_in_the_lane_header_and_on_the_clip() {
2614 use engine::duck::Duck;
2615 use engine::project::LaneKind;
2616 let mut srv = server();
2617 let key = srv.session.as_mut().unwrap().add_lane(LaneKind::Audio);
2618 assert_eq!(key, Lane::new(LaneKind::Audio, 1));
2619 let duck = Duck {
2620 under: 1,
2621 depth_db: -12.0,
2622 threshold_db: -40.0,
2623 attack_ms: 80.0,
2624 release_ms: 400.0,
2625 };
2626 assert!(srv.session.as_mut().unwrap().set_lane_duck(Lane::A1, Some(duck)), "duck set");
2627
2628 let t = call(&mut srv, "timeline", json!({}));
2629 assert!(!t.is_error, "{}", t.text);
2630 assert!(t.text.contains("duck under A2 -12dB"), "{}", t.text);
2631 let lanes = t.structured.as_ref().unwrap()["lanes"].as_array().unwrap().clone();
2632 let a1 = lanes.iter().find(|l| l["lane"] == "A1").expect("A1 listed");
2633 assert_eq!(a1["duck"]["under"], "A2");
2634 assert_eq!(a1["duck"]["depth_db"], -12.0);
2635 assert_eq!(a1["duck"]["attack_ms"], 80.0);
2636 let v1 = lanes.iter().find(|l| l["lane"] == "V1").expect("V1 listed");
2637 assert!(v1["duck"].is_null(), "only the ducked lane carries a duck");
2638
2639 let first = sess(&srv).lane_clips(Lane::A1)[0].start;
2640 let info = call(&mut srv, "clip_info", json!({"clip": format!("A1@{first}")}));
2641 assert!(!info.is_error, "{}", info.text);
2642 assert!(info.text.contains("duck under A2 -12dB"), "{}", info.text);
2643 assert_eq!(info.structured.as_ref().unwrap()["duck"]["under"], "A2");
2644 }
2645
2646 #[test]
2647 fn timeline_lists_titles_after_the_lanes_and_in_json() {
2648 use engine::project::Title;
2649 use engine::text::{Outline, Place, TextStyle};
2650 let mut srv = server();
2651 let fps = parse::session_fps(srv.session.as_ref().unwrap());
2652 let style = TextStyle { size: 80, outline: Outline::Thin, boxed: false, place: Place::Centre, ..TextStyle::default() };
2653 let sess = srv.session.as_mut().unwrap();
2654 let long = "x".repeat(60);
2655 sess.add_title(Title { start: 0, frames: 90, text: "Episode 17".into(), style: style.clone(), fade_in: 0, fade_out: 0, in_anim: Default::default(), out_anim: Default::default(), anim_frames: 0, keys: Vec::new() })
2656 .unwrap();
2657 sess.add_title(Title { start: 150, frames: 30, text: long.clone(), style, fade_in: 0, fade_out: 0, in_anim: Default::default(), out_anim: Default::default(), anim_frames: 0, keys: Vec::new() }).unwrap();
2658
2659 let r = call(&mut srv, "timeline", json!({}));
2660 let t1 = format!("T T1 0.000–{:.3} \"Episode 17\" centre", 90.0 / fps);
2661 assert!(r.text.contains(&t1), "{}", r.text);
2662 assert!(r.text.contains(&format!("\"{}…\"", "x".repeat(39))), "{}", r.text);
2663 let lane_at = r.text.find("V1").expect("a lane line");
2664 assert!(r.text.find("T T1").unwrap() > lane_at, "titles come after the lanes");
2665 let titles = r.structured.as_ref().unwrap()["titles"].as_array().unwrap().clone();
2666 assert_eq!(titles.len(), 2);
2667 assert_eq!(titles[1]["text"], long.as_str());
2668 assert_eq!(titles[0]["place"], "centre");
2669
2670 // the range filter applies to titles too: only T1 overlaps the first second
2671 let r = call(&mut srv, "timeline", json!({"range": {"from": "0", "to": "1.0s"}}));
2672 assert_eq!(r.structured.as_ref().unwrap()["titles"].as_array().unwrap().len(), 1);
2673 assert!(!r.text.contains("T T2"), "{}", r.text);
2674 }
2675}