forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

parse.rs682 lines, 26.0 KiBHistoryRawDownload
1//! Time, lane and clip-address parsing and formatting for the MCP tools.
2//!
3//! Frames are the truth; seconds are for the reader (MCP.md section 3).
4#![allow(dead_code)]
5
6use engine::project::{Lane, LaneKind};
7use engine::PlaybackSession;
8use serde_json::Value;
9
10use crate::server::Reply;
11
12const TIME_FORMS: &str =
13 "450f (frames), 15.0s or 15 (seconds), MM:SS.fff, HH:MM:SS.fff, HH:MM:SS:FF (timecode at the project fps), or end";
14
15/// Parses one time argument into a timeline frame.
16///
17/// A JSON number is seconds. A string is one of `450f`, `15.0s`, `15`, `1.5`,
18/// `MM:SS(.fff)`, `HH:MM:SS(.fff)`, `HH:MM:SS:FF` or `end`. Seconds round to the
19/// nearest frame. Negative times are refused.
20pub fn frame(v: &Value, fps: f64, end: u32) -> Result<u32, String> {
21 if !(fps > 0.0 && fps.is_finite()) {
22 return Err(format!("the project has no usable frame rate ({fps})"));
23 }
24 match v {
25 Value::Number(n) => {
26 let shown = n.to_string();
27 from_secs(n.as_f64().unwrap_or(f64::NAN), fps, &shown)
28 }
29 Value::String(s) => parse_str(s, fps, end),
30 Value::Null => Err("a time is required, not null".to_string()),
31 Value::Bool(_) => Err("a time must be a number of seconds or a string such as 450f, 15.0s or end; got a boolean".to_string()),
32 Value::Array(_) => Err("a time must be a number of seconds or a string such as 450f, 15.0s or end; got a list".to_string()),
33 Value::Object(_) => Err("a time must be a number of seconds or a string such as 450f, 15.0s or end; got an object".to_string()),
34 }
35}
36
37/// A signed time distance, for `by` arguments: the same forms as [`frame`], with a leading `-` or
38/// `+` on a string (`-15f`, `+0.5s`, `-00:00:01:00`) or a negative JSON number (seconds).
39/// `end` is not a distance. Returns the signed frame count.
40pub fn delta(v: &Value, fps: f64) -> Result<i64, String> {
41 let (neg, rest) = match v {
42 Value::Number(n) => {
43 let x = n.as_f64().unwrap_or(f64::NAN);
44 (x < 0.0, Value::from(x.abs()))
45 }
46 Value::String(s) => {
47 let t = s.trim();
48 match t.strip_prefix('-') {
49 Some(r) => (true, Value::from(r.trim())),
50 None => (false, Value::from(t.strip_prefix('+').unwrap_or(t).trim())),
51 }
52 }
53 other => (false, other.clone()),
54 };
55 if rest.as_str().is_some_and(|t| t.eq_ignore_ascii_case("end")) {
56 return Err("`end` is a place on the timeline, not a distance: give a time such as 15f or -0.5s".to_string());
57 }
58 let n = i64::from(frame(&rest, fps, 0)?);
59 Ok(if neg { -n } else { n })
60}
61
62/// A required time argument. Missing or null is an error naming the argument.
63pub fn frame_arg(args: &Value, name: &str, fps: f64, end: u32) -> Result<u32, Reply> {
64 match opt_frame_arg(args, name, fps, end)? {
65 Some(f) => Ok(f),
66 None => Err(Reply::err(format!(
67 "missing argument `{name}`: give a time such as 450f, 15.0s, 00:00:15:00 or end"
68 ))),
69 }
70}
71
72/// An optional time argument. Missing or null is `None`.
73pub fn opt_frame_arg(args: &Value, name: &str, fps: f64, end: u32) -> Result<Option<u32>, Reply> {
74 match args.get(name) {
75 None | Some(Value::Null) => Ok(None),
76 Some(v) => frame(v, fps, end)
77 .map(Some)
78 .map_err(|e| Reply::err(format!("argument `{name}`: {e}"))),
79 }
80}
81
82/// `V1`, `v1`, `A2`, `S1` to a lane. Numbering starts at 1, so `V1` is ord 0.
83pub fn lane(s: &str) -> Result<Lane, String> {
84 let t = s.trim();
85 let mut chars = t.chars();
86 let kind = match chars.next().map(|c| c.to_ascii_uppercase()) {
87 Some('V') => LaneKind::Video,
88 Some('A') => LaneKind::Audio,
89 Some('S') => LaneKind::Subtitle,
90 _ => return Err(not_lane(s)),
91 };
92 let n: usize = chars.as_str().parse().map_err(|_| not_lane(s))?;
93 if n == 0 {
94 return Err(format!("`{s}` is not a lane: lanes are numbered from 1, so V1 is the first video lane"));
95 }
96 Ok(Lane::new(kind, n - 1))
97}
98
99/// The inverse of [`lane`]: `Lane{Audio, 1}` to `"A2"`.
100pub fn lane_name(l: Lane) -> String {
101 let p = match l.kind {
102 LaneKind::Video => 'V',
103 LaneKind::Audio => 'A',
104 LaneKind::Subtitle => 'S',
105 };
106 format!("{p}{}", l.ord + 1)
107}
108
109/// Resolves a clip address to its lane and index into that lane.
110///
111/// `V1@450` names the clip starting at frame 450 (a bare number is frames).
112/// `V1@15.0s` and the other time forms also work. `V1#0` is the first clip's index (0-based),
113/// bounds checked. Subtitle lanes resolve through their own placements.
114pub fn clip(s: &PlaybackSession, addr: &str) -> Result<(Lane, usize), String> {
115 let a = addr.trim();
116 let split = a
117 .find(['@', '#'])
118 .ok_or_else(|| format!("`{addr}` is not a clip address: write LANE@START (e.g. V1@450) or LANE#INDEX (e.g. V1#0)"))?;
119 let ln = lane(&a[..split])?;
120 let rest = a[split + 1..].trim();
121 let all = spans(s, ln);
122
123 if a.as_bytes()[split] == b'#' {
124 let idx: usize = rest.parse().map_err(|_| {
125 format!("`{rest}` is not a clip index: use {}#0 for the first clip", lane_name(ln))
126 })?;
127 if idx >= all.len() {
128 return Err(format!(
129 "{}#{idx} is out of range: {}",
130 lane_name(ln),
131 starts_hint(ln, &all)
132 ));
133 }
134 return Ok((ln, idx));
135 }
136
137 let bare = rest.parse::<u32>();
138 let start = match bare {
139 Ok(f) => f,
140 Err(_) => frame(&Value::String(rest.to_string()), session_fps(s), session_end(s))
141 .map_err(|e| format!("{a}: {e}"))?,
142 };
143 if let Some(i) = all.iter().position(|&(st, _)| st == start) {
144 return Ok((ln, i));
145 }
146 let frame_note = if bare.is_ok() { frame_hint(s, ln, start, &all) } else { String::new() };
147 if let Some(&(st, en)) = all.iter().find(|&&(st, en)| st <= start && start < en) {
148 return Err(format!(
149 "no clip starts at {}; {}@{st} spans {st}–{en} — use that address{frame_note}",
150 addr_of(ln, start),
151 lane_name(ln),
152 ));
153 }
154 Err(format!("no clip at {}; {}{frame_note}", addr_of(ln, start), nearest_starts(ln, &all, start)))
155}
156
157/// `V1@450`: the address of a clip starting at `start` on `lane`.
158pub fn addr(lane: Lane, start: u32) -> String {
159 addr_of(lane, start)
160}
161
162/// `450f (15.000s)`: a frame in both forms, as responses give it.
163pub fn tc(frame: u32, fps: f64) -> String {
164 format!("{frame}f ({:.3}s)", secs(frame, fps))
165}
166
167/// Seconds of a frame at `fps`.
168pub fn secs(frame: u32, fps: f64) -> f64 {
169 f64::from(frame) / fps
170}
171
172/// `00:15.000`, or `1:02:03.500` once it reaches an hour.
173pub fn clock(frame: u32, fps: f64) -> String {
174 let ms = (secs(frame, fps) * 1000.0).round() as u64;
175 let h = ms / 3_600_000;
176 let m = (ms / 60_000) % 60;
177 let s = (ms / 1000) % 60;
178 let milli = ms % 1000;
179 if h > 0 {
180 format!("{h}:{m:02}:{s:02}.{milli:03}")
181 } else {
182 format!("{m:02}:{s:02}.{milli:03}")
183 }
184}
185
186/// The project frame rate.
187pub fn session_fps(s: &PlaybackSession) -> f64 {
188 s.meta().frame_rate
189}
190
191/// The timeline end in frames.
192pub fn session_end(s: &PlaybackSession) -> u32 {
193 (s.timeline_duration() * session_fps(s)).round() as u32
194}
195
196// ---- helpers --------------------------------------------------------------
197
198fn addr_of(lane: Lane, start: u32) -> String {
199 format!("{}@{start}", lane_name(lane))
200}
201
202fn not_lane(s: &str) -> String {
203 format!("`{s}` is not a lane: write V1.. for video, A1.. for audio, S1.. for subtitles")
204}
205
206fn bad(raw: &str) -> String {
207 format!("`{raw}` is not a time: accepted forms are {TIME_FORMS}")
208}
209
210fn spans(s: &PlaybackSession, lane: Lane) -> Vec<(u32, u32)> {
211 match lane.kind {
212 LaneKind::Subtitle => s
213 .sub_lane(lane)
214 .iter()
215 .map(|c| (c.start, c.start.saturating_add(c.frames)))
216 .collect(),
217 _ => s.lane_clips(lane).iter().map(|c| (c.start, c.end())).collect(),
218 }
219}
220
221/// The three clip starts on a lane nearest a frame that has no clip, in time order.
222fn nearest_starts(lane: Lane, all: &[(u32, u32)], start: u32) -> String {
223 if all.is_empty() {
224 return format!("{} has no clips", lane_name(lane));
225 }
226 let mut near: Vec<u32> = all.iter().map(|&(st, _)| st).collect();
227 near.sort_by_key(|&st| (st.abs_diff(start), st));
228 near.truncate(3);
229 near.sort_unstable();
230 let shown: Vec<String> = near.iter().map(|&st| addr_of(lane, st)).collect();
231 format!("{} has {} clip(s), nearest starts {}", lane_name(lane), all.len(), shown.join(", "))
232}
233
234/// Why a bare `@N` with no clip is probably a mix-up: addresses count frames, so a clip that
235/// starts at N seconds is named by its frame. Names that clip when one starts there.
236fn frame_hint(s: &PlaybackSession, lane: Lane, n: u32, all: &[(u32, u32)]) -> String {
237 let fps = session_fps(s);
238 let as_secs = (f64::from(n) * fps).round() as u32;
239 if all.iter().any(|&(st, _)| st == as_secs) {
240 return format!(" (addresses are frames: {n} s is {} at {fps} fps)", addr_of(lane, as_secs));
241 }
242 format!(" (addresses are frames: {} is {:.3} s in)", addr_of(lane, n), secs(n, fps))
243}
244
245/// What a lane holds, for an error to list: at most eight addresses.
246fn starts_hint(lane: Lane, all: &[(u32, u32)]) -> String {
247 const MAX: usize = 8;
248 if all.is_empty() {
249 return format!("{} has no clips", lane_name(lane));
250 }
251 let shown: Vec<String> = all.iter().take(MAX).map(|&(st, _)| addr_of(lane, st)).collect();
252 let more = if all.len() > MAX {
253 format!(", … {} more", all.len() - MAX)
254 } else {
255 String::new()
256 };
257 format!(
258 "{} has {} clip(s), starting at {}{more}",
259 lane_name(lane),
260 all.len(),
261 shown.join(", ")
262 )
263}
264
265fn strip_suffix_ci(s: &str, suffix: char) -> Option<&str> {
266 let last = s.chars().last()?;
267 if last.eq_ignore_ascii_case(&suffix) {
268 Some(&s[..s.len() - last.len_utf8()])
269 } else {
270 None
271 }
272}
273
274fn parse_str(raw: &str, fps: f64, end: u32) -> Result<u32, String> {
275 let s = raw.trim();
276 if s.eq_ignore_ascii_case("end") {
277 return Ok(end);
278 }
279 if s.is_empty() {
280 return Err(bad(raw));
281 }
282 if let Some(num) = strip_suffix_ci(s, 'f') {
283 return frames_form(num, raw);
284 }
285 if let Some(num) = strip_suffix_ci(s, 's') {
286 return seconds_form(num, fps, raw);
287 }
288 if s.contains(':') {
289 return clock_form(s, fps, raw);
290 }
291 seconds_form(s, fps, raw)
292}
293
294fn frames_form(num: &str, raw: &str) -> Result<u32, String> {
295 let t = num.trim();
296 if t.starts_with('-') {
297 return Err(format!("`{raw}` is negative; a time cannot be before the start of the timeline"));
298 }
299 t.parse::<u32>().map_err(|_| {
300 if !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit()) {
301 format!("`{raw}` is too large: frames go up to {}", u32::MAX)
302 } else {
303 format!("`{raw}` is not a frame count: write whole frames as 450f")
304 }
305 })
306}
307
308fn seconds_form(num: &str, fps: f64, raw: &str) -> Result<u32, String> {
309 let t = num.trim();
310 if t.starts_with('-') {
311 return Err(format!("`{raw}` is negative; a time cannot be before the start of the timeline"));
312 }
313 match t.parse::<f64>() {
314 Ok(v) if v.is_finite() => from_secs(v, fps, raw),
315 _ => Err(bad(raw)),
316 }
317}
318
319/// `MM:SS(.fff)`, `HH:MM:SS(.fff)` or the timecode `HH:MM:SS:FF`.
320fn clock_form(s: &str, fps: f64, raw: &str) -> Result<u32, String> {
321 let parts: Vec<&str> = s.split(':').collect();
322 match parts.len() {
323 4 => timecode_form(&parts, fps, raw),
324 2 | 3 => {
325 let (h, m, sec) = if parts.len() == 3 {
326 (whole(parts[0], raw)?, whole(parts[1], raw)?, parts[2])
327 } else {
328 (0, whole(parts[0], raw)?, parts[1])
329 };
330 if m >= 60 {
331 return Err(format!("`{raw}`: minutes must be below 60 (use HH:MM:SS for longer times)"));
332 }
333 let sec_v = fraction_secs(sec, raw)?;
334 if sec_v >= 60.0 {
335 return Err(format!("`{raw}`: seconds must be below 60"));
336 }
337 from_secs(h as f64 * 3600.0 + m as f64 * 60.0 + sec_v, fps, raw)
338 }
339 _ => Err(bad(raw)),
340 }
341}
342
343/// `HH:MM:SS:FF`, FF counted in whole frames at the project fps.
344fn timecode_form(parts: &[&str], fps: f64, raw: &str) -> Result<u32, String> {
345 let h = whole(parts[0], raw)?;
346 let m = whole(parts[1], raw)?;
347 let s = whole(parts[2], raw)?;
348 let f = whole(parts[3], raw)?;
349 if m >= 60 || s >= 60 {
350 return Err(format!("`{raw}`: minutes and seconds must be below 60"));
351 }
352 let per_second = fps.ceil() as u64;
353 if f >= per_second {
354 return Err(format!(
355 "`{raw}`: the frame field FF must be below {per_second} at this project's frame rate"
356 ));
357 }
358 let base = ((h * 3600 + m * 60 + s) as f64 * fps).round();
359 from_secs(base + f as f64, 1.0, raw)
360}
361
362fn whole(p: &str, raw: &str) -> Result<u64, String> {
363 let t = p.trim();
364 if t.starts_with('-') {
365 return Err(format!("`{raw}` is negative; a time cannot be before the start of the timeline"));
366 }
367 t.parse::<u64>()
368 .map_err(|_| format!("`{raw}`: `{p}` should be a whole number"))
369}
370
371fn fraction_secs(p: &str, raw: &str) -> Result<f64, String> {
372 let t = p.trim();
373 if t.starts_with('-') {
374 return Err(format!("`{raw}` is negative; a time cannot be before the start of the timeline"));
375 }
376 match t.parse::<f64>() {
377 Ok(v) if v.is_finite() => Ok(v),
378 _ => Err(format!("`{raw}`: `{p}` should be seconds, such as 03 or 03.500")),
379 }
380}
381
382/// Seconds to a frame, rounded to the nearest. `shown` names the input in errors.
383fn from_secs(secs: f64, fps: f64, shown: &str) -> Result<u32, String> {
384 if !secs.is_finite() {
385 return Err(format!("`{shown}` is not a finite time"));
386 }
387 if secs < 0.0 {
388 return Err(format!("`{shown}` is negative; a time cannot be before the start of the timeline"));
389 }
390 let f = (secs * fps).round();
391 if f > f64::from(u32::MAX) {
392 // Plain digits, never an exponent: the seconds to the nearest whole second. Past 1e15 s
393 // the digits would run on, so the reply says only that it is far past the end.
394 let days = f64::from(u32::MAX) / fps / 86_400.0;
395 if secs < 1e15 {
396 return Err(format!(
397 "{secs:.0} s is past the longest timeline edith supports (about {days:.0} days at {fps} fps)"
398 ));
399 }
400 return Err(format!(
401 "that is far past the longest timeline edith supports (about {days:.0} days at {fps} fps)"
402 ));
403 }
404 Ok(f as u32)
405}
406
407/// The JSON kind of an argument, for the `got …` in a refusal.
408pub fn kind_of(v: &Value) -> &'static str {
409 match v {
410 Value::Null => "null",
411 Value::Bool(_) => "a boolean",
412 Value::Number(_) => "number",
413 Value::String(_) => "string",
414 Value::Array(_) => "a list",
415 Value::Object(_) => "an object",
416 }
417}
418
419/// The address argument `key` as text. A missing key names the example form; a value
420/// that is not a string says what it was: `` `clip` must be an address like "V1@0", got number ``.
421pub fn addr_str<'a>(op: &'a Value, key: &str, example: &str) -> Result<&'a str, String> {
422 match op.get(key) {
423 None | Some(Value::Null) => Err(format!("missing `{key}`: give an address such as {example}")),
424 Some(Value::String(t)) => Ok(t.trim()),
425 Some(v) => Err(format!("`{key}` must be an address like \"{}\", got {}", example.trim_matches('"'), kind_of(v))),
426 }
427}
428
429#[cfg(test)]
430mod tests {
431 use super::*;
432 use serde_json::json;
433 use std::path::Path;
434
435 const FPS: f64 = 30.0;
436 const END: u32 = 9000;
437
438 #[test]
439 fn a_signed_distance_takes_every_time_form() {
440 let d = |v: Value| delta(&v, FPS);
441 assert_eq!(d(json!("15f")), Ok(15));
442 assert_eq!(d(json!("-15f")), Ok(-15));
443 assert_eq!(d(json!("+0.5s")), Ok(15));
444 assert_eq!(d(json!("-0.5s")), Ok(-15));
445 assert_eq!(d(json!(-1.0)), Ok(-30));
446 assert_eq!(d(json!(2)), Ok(60));
447 assert_eq!(d(json!("-00:00:01:00")), Ok(-30));
448 assert_eq!(d(json!("- 3f")), Ok(-3));
449 assert!(d(json!("end")).unwrap_err().contains("not a distance"));
450 assert!(d(json!("-end")).unwrap_err().contains("not a distance"));
451 assert!(d(json!("abc")).unwrap_err().contains("not a time"));
452 assert!(d(json!(null)).is_err());
453 }
454
455 fn t(v: Value, fps: f64) -> Result<u32, String> {
456 frame(&v, fps, END)
457 }
458
459 fn s(text: &str, fps: f64) -> Result<u32, String> {
460 t(Value::String(text.to_string()), fps)
461 }
462
463 #[test]
464 fn frames_form() {
465 assert_eq!(s("450f", FPS), Ok(450));
466 assert_eq!(s("0f", FPS), Ok(0));
467 assert_eq!(s("450F", FPS), Ok(450));
468 assert_eq!(s(" 12f ", FPS), Ok(12));
469 assert!(s("1.5f", FPS).unwrap_err().contains("whole frames"));
470 assert!(s("-2f", FPS).unwrap_err().contains("negative"));
471 assert!(s("f", FPS).is_err());
472 // Whole but past the frame range: too large, not "not a frame count".
473 let big = s("99999999999f", FPS).unwrap_err();
474 assert!(big.contains("too large: frames go up to 4294967295"), "{big}");
475 assert!(!big.contains("whole frames"), "{big}");
476 }
477
478 #[test]
479 fn huge_seconds_say_how_far_past_the_timeline() {
480 let far = s("1e9s", FPS).unwrap_err();
481 assert_eq!(
482 far,
483 "1000000000 s is past the longest timeline edith supports (about 1657 days at 30 fps)"
484 );
485 // Never an exponent, in a string or a JSON number; past 1e15 s the digits are not run on.
486 let near = s("9.9999999999e10", FPS).unwrap_err();
487 assert!(near.starts_with("99999999999 s is past the longest timeline"), "{near}");
488 let json_far = t(json!(1e300), FPS).unwrap_err();
489 assert!(!json_far.contains("1e300") && json_far.len() < 160, "{json_far}");
490 assert!(json_far.starts_with("that is far past the longest timeline"), "{json_far}");
491 }
492
493 #[test]
494 fn seconds_forms() {
495 assert_eq!(s("15.0s", FPS), Ok(450));
496 assert_eq!(s("15s", FPS), Ok(450));
497 assert_eq!(s("15", FPS), Ok(450));
498 assert_eq!(s("1.5", FPS), Ok(45));
499 assert_eq!(s("15.0s", 24.0), Ok(360));
500 // Rounds to the nearest frame: 0.01s is 0.3 frames at 30 fps, 0.02s is 0.6.
501 assert_eq!(s("0.01", FPS), Ok(0));
502 assert_eq!(s("0.02", FPS), Ok(1));
503 }
504
505 #[test]
506 fn json_number_is_seconds() {
507 assert_eq!(t(json!(15), FPS), Ok(450));
508 assert_eq!(t(json!(1.5), FPS), Ok(45));
509 assert_eq!(t(json!(0), FPS), Ok(0));
510 assert!(t(json!(-1.0), FPS).unwrap_err().contains("negative"));
511 }
512
513 #[test]
514 fn end_form() {
515 assert_eq!(s("end", FPS), Ok(END));
516 assert_eq!(s("END", FPS), Ok(END));
517 assert_eq!(t(json!("end"), 25.0), Ok(END));
518 }
519
520 #[test]
521 fn minutes_seconds_forms() {
522 assert_eq!(s("01:02", FPS), Ok(62 * 30));
523 assert_eq!(s("01:02.500", 25.0), Ok(1563));
524 assert_eq!(s("00:15.5", FPS), Ok(465));
525 assert!(s("99:00", FPS).unwrap_err().contains("minutes must be below 60"));
526 assert!(s("01:75", FPS).unwrap_err().contains("seconds must be below 60"));
527 assert!(s("01:", FPS).is_err());
528 }
529
530 #[test]
531 fn hours_minutes_seconds_forms() {
532 assert_eq!(s("1:00:00", FPS), Ok(108_000));
533 assert_eq!(s("00:00:15.5", FPS), Ok(465));
534 assert!(s("00:61:00", FPS).unwrap_err().contains("minutes must be below 60"));
535 assert!(s("-1:00:00", FPS).unwrap_err().contains("negative"));
536 }
537
538 #[test]
539 fn timecode_form() {
540 assert_eq!(s("00:00:15:00", FPS), Ok(450));
541 assert_eq!(s("00:01:00:12", 25.0), Ok(1512));
542 assert_eq!(s("00:00:00:24", 25.0), Ok(24));
543 assert!(s("00:00:00:25", 25.0).unwrap_err().contains("FF must be below 25"));
544 assert!(s("00:00:00:30", FPS).is_err());
545 assert!(s("00:60:00:00", FPS).is_err());
546 }
547
548 #[test]
549 fn refusals() {
550 assert!(s("", FPS).unwrap_err().contains("not a time"));
551 assert!(s("abc", FPS).unwrap_err().contains("accepted forms"));
552 assert!(s("-1", FPS).unwrap_err().contains("negative"));
553 assert!(s("-1s", FPS).unwrap_err().contains("negative"));
554 assert!(s("nan", FPS).is_err());
555 assert!(s("inf", FPS).is_err());
556 assert!(t(json!(true), FPS).unwrap_err().contains("boolean"));
557 assert!(t(json!([1]), FPS).unwrap_err().contains("list"));
558 assert!(t(Value::Null, FPS).is_err());
559 assert!(frame(&json!(1), 0.0, END).is_err());
560 }
561
562 #[test]
563 fn frame_arg_missing_and_present() {
564 let args = json!({ "at": "450f", "nothing": null });
565 assert_eq!(frame_arg(&args, "at", FPS, END).ok(), Some(450));
566 let missing = frame_arg(&args, "gone", FPS, END).unwrap_err();
567 assert!(missing.is_error);
568 assert!(missing.text.contains("missing argument `gone`"), "{}", missing.text);
569 assert!(frame_arg(&args, "nothing", FPS, END).is_err());
570 let bad = frame_arg(&json!({ "at": "x" }), "at", FPS, END).unwrap_err();
571 assert!(bad.text.contains("argument `at`"), "{}", bad.text);
572 }
573
574 #[test]
575 fn opt_frame_arg_missing_is_none() {
576 let args = json!({ "at": "end", "nothing": null });
577 assert_eq!(opt_frame_arg(&args, "at", FPS, END).ok(), Some(Some(END)));
578 assert_eq!(opt_frame_arg(&args, "gone", FPS, END).ok(), Some(None));
579 assert_eq!(opt_frame_arg(&args, "nothing", FPS, END).ok(), Some(None));
580 assert!(opt_frame_arg(&json!({ "at": [] }), "at", FPS, END).is_err());
581 }
582
583 #[test]
584 fn lanes_round_trip() {
585 assert_eq!(lane("V1"), Ok(Lane::V1));
586 assert_eq!(lane("v1"), Ok(Lane::V1));
587 assert_eq!(lane("A1"), Ok(Lane::A1));
588 assert_eq!(lane("S1"), Ok(Lane::S1));
589 assert_eq!(lane("A2"), Ok(Lane::new(LaneKind::Audio, 1)));
590 assert_eq!(lane("v12"), Ok(Lane::new(LaneKind::Video, 11)));
591 for name in ["V1", "V3", "A2", "S1", "S9", "V12"] {
592 assert_eq!(lane_name(lane(name).unwrap()), name);
593 }
594 assert_eq!(lane_name(lane("a2").unwrap()), "A2");
595 assert_eq!(lane_name(Lane::new(LaneKind::Subtitle, 0)), "S1");
596 }
597
598 #[test]
599 fn lane_errors() {
600 assert!(lane("V0").unwrap_err().contains("numbered from 1"));
601 assert!(lane("X1").unwrap_err().contains("not a lane"));
602 assert!(lane("V").unwrap_err().contains("not a lane"));
603 assert!(lane("").unwrap_err().contains("not a lane"));
604 assert!(lane("V-1").unwrap_err().contains("not a lane"));
605 assert!(lane("1V").unwrap_err().contains("not a lane"));
606 }
607
608 #[test]
609 fn addr_and_formatting() {
610 assert_eq!(addr(Lane::V1, 450), "V1@450");
611 assert_eq!(addr(Lane::new(LaneKind::Audio, 1), 0), "A2@0");
612 assert_eq!(addr(Lane::new(LaneKind::Subtitle, 0), 900), "S1@900");
613 assert_eq!(tc(450, FPS), "450f (15.000s)");
614 assert_eq!(secs(45, FPS), 1.5);
615 assert_eq!(clock(450, FPS), "00:15.000");
616 assert_eq!(clock(0, FPS), "00:00.000");
617 // 1h 2m 3.5s at 30 fps.
618 assert_eq!(clock(111_705, FPS), "1:02:03.500");
619 }
620
621 fn session() -> PlaybackSession {
622 engine::ao::set_silent_output();
623 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
624 PlaybackSession::open(p).expect("open test asset")
625 }
626
627 #[test]
628 fn no_clip_hint_names_frames_and_nearest_starts() {
629 let sess = session();
630 let fps = session_fps(&sess);
631 let lane = Lane::V1;
632 // Clips start at 0, 240, 900, 1200 and 5000; 8 s is frame 240 at 30 fps.
633 let all = [(0, 100), (240, 500), (900, 1000), (1200, 1300), (5000, 5100)];
634 let hit = frame_hint(&sess, lane, 8, &all);
635 assert!(hit.contains(&format!("addresses are frames: 8 s is V1@240 at {fps} fps")), "{hit}");
636 let miss = frame_hint(&sess, lane, 7, &all);
637 assert!(miss.contains("addresses are frames: V1@7 is"), "{miss}");
638 // The three starts nearest frame 1000, in time order.
639 assert_eq!(
640 nearest_starts(lane, &all, 1000),
641 "V1 has 5 clip(s), nearest starts V1@240, V1@900, V1@1200"
642 );
643 assert_eq!(nearest_starts(Lane::new(LaneKind::Audio, 5), &[], 0), "A6 has no clips");
644 }
645
646 #[test]
647 fn clip_addresses() {
648 let sess = session();
649 assert!(session_fps(&sess) > 0.0);
650 assert!(session_end(&sess) > 0);
651 let first = sess.lane_clips(Lane::V1).first().expect("V1 has a clip");
652
653 assert_eq!(clip(&sess, "V1#0"), Ok((Lane::V1, 0)));
654 assert_eq!(clip(&sess, &format!("V1@{}", first.start)), Ok((Lane::V1, 0)));
655 assert_eq!(clip(&sess, &format!("v1@{}", first.start)), Ok((Lane::V1, 0)));
656 let sec_form = format!("V1@{}s", secs(first.start, session_fps(&sess)));
657 assert_eq!(clip(&sess, &sec_form), Ok((Lane::V1, 0)));
658
659 let out = clip(&sess, "V1#999").unwrap_err();
660 assert!(out.contains("out of range"), "{out}");
661 assert!(out.contains("V1@"), "{out}");
662
663 assert!(clip(&sess, "V1").unwrap_err().contains("not a clip address"));
664 assert!(clip(&sess, "V1#x").unwrap_err().contains("not a clip index"));
665 assert!(clip(&sess, "Q1@0").unwrap_err().contains("not a lane"));
666 assert!(clip(&sess, "A9@0").unwrap_err().contains("no clips"));
667
668 // A frame inside the first clip, past its start, names the clip that spans it.
669 if first.end() > first.start + 1 {
670 let inside = first.start + 1;
671 let msg = clip(&sess, &format!("V1@{inside}")).unwrap_err();
672 assert!(msg.contains("no clip starts at"), "{msg}");
673 assert!(msg.contains(&format!("V1@{}", first.start)), "{msg}");
674 assert!(msg.contains("use that address"), "{msg}");
675 // A bare frame inside a clip is named as a frame too.
676 assert!(msg.contains("addresses are frames"), "{msg}");
677 }
678
679 let beyond = clip(&sess, &format!("V1@{}", session_end(&sess) + 1000)).unwrap_err();
680 assert!(beyond.contains("no clip at"), "{beyond}");
681 }
682}