486 lines
17 KiB
Rust
486 lines
17 KiB
Rust
use crate::model::{Playback, Report};
|
|
use anyhow::{Result, bail};
|
|
use serde_json::{Value, json};
|
|
use uuid::Uuid;
|
|
|
|
const HEADERS: [&str; 8] = [
|
|
"Slide(s)",
|
|
"Duration",
|
|
"Video",
|
|
"Size",
|
|
"Resolution",
|
|
"Codec",
|
|
"Original",
|
|
"Playback",
|
|
];
|
|
pub fn time(value: Option<f64>) -> String {
|
|
let Some(v) = value.filter(|v| v.is_finite() && *v >= 0.0) else {
|
|
return "Unknown".into();
|
|
};
|
|
let ms = (v * 1000.0).round_ties_even() as u64;
|
|
format!(
|
|
"{:02}:{:02}:{:02}.{:03}",
|
|
ms / 3600000,
|
|
(ms / 60000) % 60,
|
|
(ms / 1000) % 60,
|
|
ms % 1000
|
|
)
|
|
}
|
|
pub fn size(value: u64) -> String {
|
|
let mut n = value as f64;
|
|
for unit in ["B", "KiB", "MiB", "GiB", "TiB"] {
|
|
if n < 1024.0 || unit == "TiB" {
|
|
return if unit == "B" {
|
|
format!("{n:.0} {unit}")
|
|
} else {
|
|
format!("{n:.2} {unit}")
|
|
};
|
|
}
|
|
n /= 1024.0;
|
|
}
|
|
unreachable!()
|
|
}
|
|
pub fn escape(s: &str) -> String {
|
|
s.replace('&', "&")
|
|
.replace('<', "<")
|
|
.replace('>', ">")
|
|
.replace('"', """)
|
|
.replace('\'', "'")
|
|
}
|
|
pub fn url(s: &str) -> String {
|
|
s.bytes()
|
|
.map(|b| {
|
|
if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) {
|
|
(b as char).to_string()
|
|
} else {
|
|
format!("%{b:02X}")
|
|
}
|
|
})
|
|
.collect()
|
|
}
|
|
pub fn typst_string(s: &str) -> String {
|
|
let mut result = String::from("\"");
|
|
for c in s.chars() {
|
|
match c {
|
|
'"' | '\\' => {
|
|
result.push('\\');
|
|
result.push(c);
|
|
}
|
|
c if c.is_control() => result.push_str(&format!("\\u{{{:x}}}", c as u32)),
|
|
c => result.push(c),
|
|
}
|
|
}
|
|
result.push('"');
|
|
result
|
|
}
|
|
fn slides(p: &Playback) -> String {
|
|
if p.video.slides.is_empty() {
|
|
"Unreferenced".into()
|
|
} else {
|
|
p.video
|
|
.slides
|
|
.iter()
|
|
.map(usize::to_string)
|
|
.collect::<Vec<_>>()
|
|
.join(", ")
|
|
}
|
|
}
|
|
fn duration(p: &Playback) -> String {
|
|
match p.settings.playback_status.as_str() {
|
|
"looping" => "Looping".into(),
|
|
"custom-timing" => "Custom timing".into(),
|
|
"invalid-trim" => "Invalid trim".into(),
|
|
_ => time(p.video.duration_seconds),
|
|
}
|
|
}
|
|
fn trim(p: &Playback) -> String {
|
|
let s = &p.settings;
|
|
if s.trim_start_seconds == 0.0 && s.trim_end_seconds == 0.0 {
|
|
return String::new();
|
|
}
|
|
format!(
|
|
"Trim removed · start {} · end {}",
|
|
time(Some(s.trim_start_seconds)),
|
|
time(Some(s.trim_end_seconds))
|
|
)
|
|
}
|
|
fn notes(r: &Report) -> Vec<String> {
|
|
let mut notes = r.notes.clone();
|
|
if !r.external_media_slides.is_empty() {
|
|
notes.push(format!(
|
|
"Slides with external media links: {} (not extracted).",
|
|
r.external_media_slides
|
|
.iter()
|
|
.map(usize::to_string)
|
|
.collect::<Vec<_>>()
|
|
.join(", ")
|
|
));
|
|
}
|
|
notes
|
|
}
|
|
fn cells(p: &Playback) -> Vec<String> {
|
|
vec![
|
|
slides(p),
|
|
duration(p),
|
|
p.video.name.clone(),
|
|
size(p.video.size_bytes),
|
|
p.video.resolution.clone(),
|
|
p.video.codec.clone(),
|
|
time(p.original_duration_seconds),
|
|
p.settings.playback_status.clone(),
|
|
]
|
|
}
|
|
fn metrics(r: &Report) -> Vec<(&'static str, String)> {
|
|
vec![
|
|
("Embedded videos", r.embedded_videos.to_string()),
|
|
("Total duration", time(Some(r.total_duration_seconds))),
|
|
("Total size", size(r.total_size_bytes)),
|
|
(
|
|
"Durations available",
|
|
format!("{} / {}", r.known_playback_durations, r.playbacks.len()),
|
|
),
|
|
]
|
|
}
|
|
pub fn render(r: &Report, format: &str) -> Result<String> {
|
|
Ok(match format {
|
|
"json" => serde_json::to_string_pretty(r)? + "\n",
|
|
"ontime" => serde_json::to_string_pretty(&ontime(r))? + "\n",
|
|
"html" => html(r),
|
|
"md" => text(r, true),
|
|
"txt" => text(r, false),
|
|
"typst" | "pdf" => typst(r, false),
|
|
"pdf-dense" => typst(r, true),
|
|
_ => bail!("Unknown format: {format}"),
|
|
})
|
|
}
|
|
pub fn text(r: &Report, markdown: bool) -> String {
|
|
let mut rows: Vec<Vec<String>> = vec![HEADERS.iter().map(|s| (*s).into()).collect()];
|
|
for p in &r.playbacks {
|
|
let mut row = cells(p);
|
|
let detail = trim(p);
|
|
if !detail.is_empty() {
|
|
row[7].push_str(&format!("; {detail}"));
|
|
}
|
|
for cell in &mut row {
|
|
*cell = cell.replace('\n', " ");
|
|
if markdown {
|
|
*cell = cell.replace('|', "\\|");
|
|
}
|
|
}
|
|
if markdown && let Some(link) = &p.video.extracted_file {
|
|
row[2] = format!("[{}]({})", row[2], url(link));
|
|
}
|
|
rows.push(row);
|
|
}
|
|
let widths: Vec<usize> = (0..8)
|
|
.map(|i| {
|
|
rows.iter()
|
|
.map(|r| r[i].chars().count())
|
|
.max()
|
|
.unwrap_or(3)
|
|
.max(3)
|
|
})
|
|
.collect();
|
|
let line = |row: &[String]| -> String {
|
|
format!(
|
|
"| {} |",
|
|
row.iter()
|
|
.enumerate()
|
|
.map(|(i, s)| {
|
|
let padding = " ".repeat(widths[i].saturating_sub(s.chars().count()));
|
|
if [1, 3, 6].contains(&i) {
|
|
format!("{padding}{s}")
|
|
} else {
|
|
format!("{s}{padding}")
|
|
}
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join(" | ")
|
|
)
|
|
};
|
|
let sep: Vec<String> = widths
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, w)| {
|
|
if markdown && [1, 3, 6].contains(&i) {
|
|
format!("{}:", "-".repeat(w - 1))
|
|
} else {
|
|
"-".repeat(*w)
|
|
}
|
|
})
|
|
.collect();
|
|
let mut out = format!(
|
|
"{}Video timings — {}\n\n- Embedded videos: {}\n- Total size: {}\n- Total duration: {} ({}/{} occurrences with known playback duration)\n\n{}\n{}\n",
|
|
if markdown { "# " } else { "" },
|
|
r.presentation,
|
|
r.embedded_videos,
|
|
size(r.total_size_bytes),
|
|
time(Some(r.total_duration_seconds)),
|
|
r.known_playback_durations,
|
|
r.playbacks.len(),
|
|
line(&rows[0]),
|
|
line(&sep)
|
|
);
|
|
for row in &rows[1..] {
|
|
out.push_str(&line(row));
|
|
out.push('\n');
|
|
}
|
|
for note in notes(r) {
|
|
out.push_str(&format!("\n{}{note}", if markdown { "> " } else { "" }));
|
|
}
|
|
out + "\n"
|
|
}
|
|
pub fn html(r: &Report) -> String {
|
|
let mut out = format!(
|
|
r#"<!doctype html>
|
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>Video timings — {}</title><style>{}</style></head><body>
|
|
<header><div class="eyebrow">Presentation media report</div><h1>Video timings</h1><p class="subtitle">{}</p></header>
|
|
<section class="metrics">"#,
|
|
escape(&r.presentation),
|
|
include_str!("../assets/report.css"),
|
|
escape(&r.presentation)
|
|
);
|
|
for (label, value) in metrics(r) {
|
|
out.push_str(&format!(
|
|
"<div class=\"metric\"><span>{label}</span><strong>{}</strong></div>",
|
|
escape(&value)
|
|
));
|
|
}
|
|
out.push_str("</section><div class=\"table\"><table><thead><tr>");
|
|
for h in HEADERS {
|
|
out.push_str(&format!("<th scope=\"col\">{h}</th>"));
|
|
}
|
|
out.push_str("</tr></thead><tbody>");
|
|
for p in &r.playbacks {
|
|
let mut row: Vec<String> = cells(p).iter().map(|s| escape(s)).collect();
|
|
row[0] = format!("<span class=\"pill slide\">{}</span>", row[0]);
|
|
row[1] = format!(
|
|
"<span class=\"pill {}\">{}</span>",
|
|
if p.video.duration_seconds.is_some() {
|
|
"duration"
|
|
} else {
|
|
"warning"
|
|
},
|
|
row[1]
|
|
);
|
|
row[5] = format!("<span class=\"pill muted\">{}</span>", row[5]);
|
|
if let Some(link) = &p.video.extracted_file {
|
|
row[2] = format!("<a href=\"{}\">{}</a>", escape(&url(link)), row[2]);
|
|
}
|
|
if p.settings.playback_status == "looping" {
|
|
row[1] = "—".into();
|
|
row[2].push_str(" <span class=\"pill warning\">Looping</span>");
|
|
}
|
|
let detail = trim(p);
|
|
if !detail.is_empty() {
|
|
row[2].push_str(&format!(
|
|
"<small class=\"trim\">{}</small>",
|
|
escape(&detail)
|
|
));
|
|
}
|
|
out.push_str(&format!(
|
|
"<tr>{}</tr>",
|
|
row.iter()
|
|
.map(|v| format!("<td>{v}</td>"))
|
|
.collect::<String>()
|
|
));
|
|
}
|
|
out.push_str("</tbody></table></div><footer>");
|
|
for note in notes(r) {
|
|
out.push_str(&format!("<p>{}</p>", escape(¬e)));
|
|
}
|
|
out + "</footer></body></html>\n"
|
|
}
|
|
pub fn typst(r: &Report, dense: bool) -> String {
|
|
let mut out = format!(
|
|
r##"#set page(paper: "a4", flipped: {}, margin: {}mm,
|
|
footer: context align(right, text(size: 7pt, fill: rgb("#626b80"), counter(page).display("1"))))
|
|
#set text(font: "DejaVu Sans", size: 9pt, fill: rgb("#172033"))
|
|
#set par(justify: false)
|
|
#let pill(body, bg: "#eeeafd", fg: "#49359b") = box(fill: rgb(bg), radius: 20pt,
|
|
inset: (x: 7pt, y: 2pt), text(size: 8pt, fill: rgb(fg), body))
|
|
"##,
|
|
!dense,
|
|
if dense { 14 } else { 16 }
|
|
);
|
|
if dense {
|
|
out.push_str(&format!(
|
|
"#par(text(size: 10pt, fill: rgb(\"#626b80\"), {}))\n#v(4pt)\n",
|
|
typst_string(&format!("Video timings — {}", r.presentation))
|
|
));
|
|
} else {
|
|
out.push_str(r##"#text(size: 8pt, weight: "bold", fill: rgb("#5744b5"), tracking: 1pt)[PRESENTATION MEDIA REPORT]
|
|
#v(5pt)
|
|
#text(size: 28pt, weight: "bold")[Video timings]
|
|
"##);
|
|
out.push_str(&format!("#par(text(fill: rgb(\"#626b80\"), {}))\n#v(8pt)\n#grid(columns: (1fr, 1fr, 1fr, 1fr), gutter: 10pt,\n",typst_string(&r.presentation)));
|
|
for (label, value) in metrics(r) {
|
|
out.push_str(&format!("block(width: 100%, fill: rgb(\"#f3f1fc\"), radius: 8pt, inset: 12pt)[#text(size: 8pt, {}) #v(5pt) #text(size: 17pt, weight: \"bold\", fill: rgb(\"#49359b\"), {})],\n",typst_string(label),typst_string(&value)));
|
|
}
|
|
out.push_str(")\n#v(16pt)\n");
|
|
}
|
|
out.push_str("#table(\n");
|
|
if dense {
|
|
out.push_str("columns: (30mm, 1fr, auto),\nalign: (left + horizon, left + horizon, right + horizon),\ninset: (x: 8pt, y: 4pt),\n");
|
|
} else {
|
|
out.push_str("columns: (22mm, auto, 1fr, auto, auto, auto, auto, auto),\nalign: (left + horizon, right + horizon, left + horizon, right + horizon, left + horizon, left + horizon, right + horizon, left + horizon),\ninset: 5pt,\n");
|
|
}
|
|
out.push_str(
|
|
r##"stroke: (top: none, left: none, right: none, bottom: 0.4pt + rgb("#e2e6f0")),
|
|
fill: (x, y) => if y == 0 { rgb("#eeeafd") } else if calc.even(y) { rgb("#f8f9fc") },
|
|
table.header("##,
|
|
);
|
|
let headers = if dense {
|
|
vec!["Slide(s)", "Media", "Duration"]
|
|
} else {
|
|
HEADERS.to_vec()
|
|
};
|
|
out.push_str(
|
|
&headers
|
|
.iter()
|
|
.map(|h| format!("strong({})", typst_string(h)))
|
|
.collect::<Vec<_>>()
|
|
.join(", "),
|
|
);
|
|
out.push_str("),\n");
|
|
for p in &r.playbacks {
|
|
let raw = cells(p);
|
|
let mut row: Vec<String> = raw.iter().map(|s| typst_string(s)).collect();
|
|
let (bg, fg) = if p.video.duration_seconds.is_some() {
|
|
("#e3f4ee", "#176349")
|
|
} else {
|
|
("#fff0ce", "#805300")
|
|
};
|
|
row[1] = format!("pill({}, bg: \"{bg}\", fg: \"{fg}\")", row[1]);
|
|
row[2] = format!("[#{}", row[2]);
|
|
if p.settings.playback_status == "looping" {
|
|
row[1] = "\"—\"".into();
|
|
row[2].push_str(" #pill(\"Looping\", bg: \"#fff0ce\", fg: \"#805300\")");
|
|
}
|
|
let detail = trim(p);
|
|
if !detail.is_empty() {
|
|
row[2].push_str(&format!(
|
|
"\n#par(leading: 2pt, text(size: 7pt, fill: rgb(\"#626b80\"), {}))",
|
|
typst_string(&detail)
|
|
));
|
|
}
|
|
row[2].push(']');
|
|
if dense {
|
|
out.push_str(&format!("{}, {}, {},\n", row[0], row[2], row[1]));
|
|
} else {
|
|
row[0] = format!("pill({})", row[0]);
|
|
row[5] = format!("pill({}, bg: \"#edf0f6\", fg: \"#566176\")", row[5]);
|
|
out.push_str(&(row.join(", ") + ",\n"));
|
|
}
|
|
}
|
|
out.push_str(")\n#v(6pt)\n");
|
|
for note in notes(r) {
|
|
out.push_str(&format!(
|
|
"#par(text(size: 7pt, fill: rgb(\"#626b80\"), {}))\n",
|
|
typst_string(¬e)
|
|
));
|
|
}
|
|
out
|
|
}
|
|
pub fn ontime(r: &Report) -> Value {
|
|
let mut entries = serde_json::Map::new();
|
|
let mut order = vec![];
|
|
let mut flat_order = vec![];
|
|
let mut elapsed = 0u64;
|
|
let mut previous = false;
|
|
for (index, p) in r
|
|
.playbacks
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, p)| p.ontime_eligible)
|
|
{
|
|
let group = r
|
|
.groups
|
|
.iter()
|
|
.enumerate()
|
|
.find(|(_, g)| index >= g.start && index < g.end);
|
|
let parent = group.map(|(i, _)| {
|
|
Uuid::new_v5(
|
|
&Uuid::NAMESPACE_URL,
|
|
format!("{}/group/{i}", r.presentation).as_bytes(),
|
|
)
|
|
.simple()
|
|
.to_string()
|
|
});
|
|
if let (Some(id), Some((_, group))) = (&parent, group)
|
|
&& !entries.contains_key(id)
|
|
{
|
|
entries.insert(id.clone(), json!({"id":id,"type":"group","title":group.title,"note":"","entries":[],"targetDuration":null,"colour":"#5744b5","custom":{},"revision":0,"timeStart":null,"timeEnd":null,"duration":0,"isFirstLinked":previous}));
|
|
order.push(id.clone());
|
|
flat_order.push(id.clone());
|
|
}
|
|
let seconds = p
|
|
.video
|
|
.duration_seconds
|
|
.filter(|d| d.is_finite() && *d >= 0.0 && *d <= 86399.0);
|
|
let duration = seconds.map_or(0, |d| (d * 1000.0).round_ties_even() as u64);
|
|
let skipped = seconds.is_none() || p.settings.slide.is_none();
|
|
let cue = p
|
|
.settings
|
|
.slide
|
|
.map_or("Unreferenced".into(), |s| format!("Slide {s}"));
|
|
let mut note = format!("{} — {}.", r.presentation, p.video.archive_path);
|
|
if seconds.is_none() {
|
|
note.push_str(" Duration unknown or outside Ontime limits; review before enabling.");
|
|
}
|
|
if p.settings.slide.is_none() {
|
|
note.push_str(" No slide reference; review before enabling.");
|
|
}
|
|
let key = format!(
|
|
"{}/{}#{}:{}",
|
|
r.presentation,
|
|
p.video.archive_path,
|
|
p.settings.slide.map_or("None".into(), |s| s.to_string()),
|
|
p.settings.shape_id.as_deref().unwrap_or("None")
|
|
);
|
|
let id = Uuid::new_v5(&Uuid::NAMESPACE_URL, key.as_bytes())
|
|
.simple()
|
|
.to_string();
|
|
entries.insert(id.clone(),json!({
|
|
"id":id,"type":"event","cue":cue,"title":p.video.name,"note":note,"duration":duration,
|
|
"timeStart":elapsed%86400000,"timeEnd":(elapsed+duration)%86400000,
|
|
"timeStrategy":"lock-duration","linkStart":previous,"timerType":"count-down","endAction":"none",
|
|
"skip":skipped,"colour":if skipped {"#b7791f"} else {"#5744b5"},
|
|
"timeWarning":120000.min(duration/5),"timeDanger":60000.min(duration/10),
|
|
"countToEnd":false,"flag":false,"custom":{},"triggers":[]
|
|
}));
|
|
if let Some(parent) = parent {
|
|
entries.get_mut(&id).unwrap()["parent"] = json!(parent);
|
|
entries.get_mut(&parent).unwrap()["entries"]
|
|
.as_array_mut()
|
|
.unwrap()
|
|
.push(json!(id));
|
|
} else {
|
|
order.push(id.clone());
|
|
}
|
|
flat_order.push(id);
|
|
if !skipped {
|
|
elapsed += duration;
|
|
previous = true;
|
|
}
|
|
}
|
|
let mut description = String::from(
|
|
"Video cues in slide order, one per supported video occurrence. Times start at midnight and are linked; set the first cue to your show start. PowerPoint trims are applied. Loops and unsupported timing are omitted. Unknown durations and unreferenced media are skipped pending review.",
|
|
);
|
|
if !r.external_media_slides.is_empty() {
|
|
description.push_str(&format!(
|
|
" External media was not exported (slides: {}).",
|
|
r.external_media_slides
|
|
.iter()
|
|
.map(usize::to_string)
|
|
.collect::<Vec<_>>()
|
|
.join(", ")
|
|
));
|
|
}
|
|
json!({"settings":{"version":"4.0.0"},"project":{"title":r.presentation,"description":description},
|
|
"rundowns":{"default":{"id":"default","title":"Video timings","entries":entries,"order":order,"flatOrder":flat_order,"revision":0}},
|
|
"customFields":{},"urlPresets":[],"viewSettings":{},
|
|
"automation":{"enabledAutomations":false,"enabledOscIn":false,"triggers":[],"automations":{}}})
|
|
}
|