| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 24 | |
| 25 | use crate::captionanim::{CaptionAnim, CaptionStyle}; |
| 26 | use crate::project::{Lane, LaneKind}; |
| 27 | use crate::PlaybackSession; |
| 28 | |
| 29 | |
| 30 | const MAGIC: &str = "edith-template 1"; |
| 31 | |
| 32 | pub const NAME_MAX: usize = 40; |
| 33 | |
| 34 | pub const MATCH_PROJECT: &str = "match_project"; |
| 35 | |
| 36 | |
| 37 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 38 | pub struct Builtin { |
| 39 | pub name: &'static str, |
| 40 | pub width: u32, |
| 41 | pub height: u32, |
| 42 | pub fps: f64, |
| 43 | |
| 44 | pub export: Option<&'static str>, |
| 45 | } |
| 46 | |
| 47 | |
| 48 | pub const BUILTINS: [Builtin; 3] = [ |
| 49 | Builtin { name: "YouTube 1080p 30", width: 1920, height: 1080, fps: 30.0, export: Some("youtube_1080p") }, |
| 50 | Builtin { name: "Vertical 1080\u{d7}1920 30", width: 1080, height: 1920, fps: 30.0, export: Some("shorts_reels") }, |
| 51 | Builtin { name: "Square 1080 30", width: 1080, height: 1080, fps: 30.0, export: None }, |
| 52 | ]; |
| 53 | |
| 54 | |
| 55 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 56 | pub struct Info { |
| 57 | pub name: String, |
| 58 | |
| 59 | pub builtin: bool, |
| 60 | |
| 61 | pub clips: bool, |
| 62 | } |
| 63 | |
| 64 | |
| 65 | pub struct Opened { |
| 66 | pub session: PlaybackSession, |
| 67 | pub export: Option<String>, |
| 68 | } |
| 69 | |
| 70 | |
| 71 | pub fn dir() -> Option<PathBuf> { |
| 72 | Some(dir_in(&data_home()?)) |
| 73 | } |
| 74 | |
| 75 | |
| 76 | pub fn dir_in(data: &Path) -> PathBuf { |
| 77 | data.join("edith").join("templates") |
| 78 | } |
| 79 | |
| 80 | |
| 81 | pub fn data_home() -> Option<PathBuf> { |
| 82 | std::env::var_os("XDG_DATA_HOME") |
| 83 | .filter(|v| !v.is_empty() && Path::new(v).is_absolute()) |
| 84 | .map(PathBuf::from) |
| 85 | .or_else(|| std::env::var_os("HOME").filter(|h| !h.is_empty()).map(|h| PathBuf::from(h).join(".local").join("share"))) |
| 86 | } |
| 87 | |
| 88 | |
| 89 | |
| 90 | pub fn valid_name(name: &str) -> bool { |
| 91 | let n = name.trim(); |
| 92 | !n.is_empty() |
| 93 | && n.chars().count() <= NAME_MAX |
| 94 | && !n.starts_with('.') |
| 95 | && !n.chars().any(|c| matches!(c, '/' | '\\' | '\0') || c.is_control()) |
| 96 | && !BUILTINS.iter().any(|b| b.name.eq_ignore_ascii_case(n)) |
| 97 | } |
| 98 | |
| 99 | |
| 100 | pub fn file(dir: &Path, name: &str) -> PathBuf { |
| 101 | dir.join(format!("{}.edith", name.trim())) |
| 102 | } |
| 103 | |
| 104 | |
| 105 | |
| 106 | pub fn list(dir: &Path) -> Vec<Info> { |
| 107 | let mut out: Vec<Info> = BUILTINS.iter().map(|b| Info { name: b.name.to_string(), builtin: true, clips: false }).collect(); |
| 108 | let Ok(rd) = std::fs::read_dir(dir) else { |
| 109 | return out; |
| 110 | }; |
| 111 | let mut saved: Vec<Info> = rd |
| 112 | .filter_map(|e| e.ok().map(|e| e.path())) |
| 113 | .filter(|p| p.extension().is_some_and(|x| x == "edith")) |
| 114 | .filter_map(|p| { |
| 115 | let name = p.file_stem()?.to_string_lossy().into_owned(); |
| 116 | let text = std::fs::read_to_string(&p).ok()?; |
| 117 | let (head, _) = parse(&text).ok()?; |
| 118 | Some(Info { name, builtin: false, clips: head.clips }) |
| 119 | }) |
| 120 | .collect(); |
| 121 | saved.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.name.cmp(&b.name))); |
| 122 | out.extend(saved); |
| 123 | out |
| 124 | } |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | pub fn save(dir: &Path, s: &PlaybackSession, name: &str, keep_clips: bool, export: Option<&str>) -> crate::Result<bool> { |
| 131 | if !valid_name(name) { |
| 132 | return Err(format!("template name `{}` is not usable: 1 to 40 characters, no slashes, not a built-in's name", name.trim()).into()); |
| 133 | } |
| 134 | if let Some(id) = export |
| 135 | && id != MATCH_PROJECT |
| 136 | && crate::export_presets::by_id(id).is_none() |
| 137 | { |
| 138 | return Err(format!("export preset `{id}` is not one edith has").into()); |
| 139 | } |
| 140 | let clips = keep_clips && !s.sources().is_empty(); |
| 141 | let (w, h) = s.resolution(); |
| 142 | let lanes = s |
| 143 | .lanes() |
| 144 | .into_iter() |
| 145 | .filter(|l| l.kind != LaneKind::Subtitle) |
| 146 | .map(|l| (l.kind, s.lane_name(l).unwrap_or("").to_string())) |
| 147 | .collect(); |
| 148 | let head = Head { |
| 149 | export: export.map(str::to_string), |
| 150 | clips, |
| 151 | width: w, |
| 152 | height: h, |
| 153 | fps: s.meta().frame_rate, |
| 154 | lanes, |
| 155 | caption: s.caption_style(), |
| 156 | }; |
| 157 | let mut text = render(&head).into_bytes(); |
| 158 | if clips { |
| 159 | text.extend_from_slice(&project_bytes(s, dir)?); |
| 160 | } |
| 161 | std::fs::create_dir_all(dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?; |
| 162 | let path = file(dir, name); |
| 163 | let replaced = path.exists(); |
| 164 | crate::edith::write_atomic(&path, &text)?; |
| 165 | Ok(replaced) |
| 166 | } |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | pub fn open(dir: &Path, name: &str) -> crate::Result<Opened> { |
| 172 | let (head, body) = load(dir, name)?; |
| 173 | let session = match body { |
| 174 | Some(bytes) => { |
| 175 | let work = scratch_dir(dir); |
| 176 | std::fs::create_dir_all(&work).map_err(|e| format!("cannot make {}: {e}", work.display()))?; |
| 177 | let scratch = work.join("body.edith"); |
| 178 | let opened = std::fs::write(&scratch, &bytes) |
| 179 | .map_err(|e| format!("cannot read template {}: {e}", name.trim())) |
| 180 | .and_then(|()| PlaybackSession::open_project(&scratch).map_err(|e| e.to_string())); |
| 181 | let _ = std::fs::remove_dir_all(&work); |
| 182 | opened.map_err(|e| format!("template {} does not open: {e}", name.trim()))? |
| 183 | } |
| 184 | None => { |
| 185 | let mut s = PlaybackSession::empty(head.width, head.height, head.fps)?; |
| 186 | apply_lanes(&mut s, &head); |
| 187 | s.set_caption_style(head.caption); |
| 188 | s |
| 189 | } |
| 190 | }; |
| 191 | Ok(Opened { session, export: head.export }) |
| 192 | } |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | pub fn apply(dir: &Path, name: &str, s: &mut PlaybackSession) -> crate::Result<Option<String>> { |
| 199 | let (head, body) = load(dir, name)?; |
| 200 | if body.is_some() { |
| 201 | return Err(format!("template {} has clips, so it starts a project of its own", name.trim()).into()); |
| 202 | } |
| 203 | apply_lanes(s, &head); |
| 204 | s.set_caption_style(head.caption); |
| 205 | Ok(head.export) |
| 206 | } |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | pub fn write_project(dir: &Path, name: &str, target: &Path) -> crate::Result<Option<String>> { |
| 212 | let (head, body) = load(dir, name)?; |
| 213 | let Some(body) = body else { |
| 214 | return Err(format!("template {} has no clips: its project is made with the first footage", name.trim()).into()); |
| 215 | }; |
| 216 | crate::edith::write_atomic(target, &body)?; |
| 217 | Ok(head.export) |
| 218 | } |
| 219 | |
| 220 | |
| 221 | struct Head { |
| 222 | export: Option<String>, |
| 223 | clips: bool, |
| 224 | width: u32, |
| 225 | height: u32, |
| 226 | fps: f64, |
| 227 | lanes: Vec<(LaneKind, String)>, |
| 228 | caption: CaptionStyle, |
| 229 | } |
| 230 | |
| 231 | fn render(h: &Head) -> String { |
| 232 | let mut out = format!( |
| 233 | "{MAGIC}\nexport {}\nclips {}\nsettings {} {} {}\n", |
| 234 | h.export.as_deref().unwrap_or("-"), |
| 235 | if h.clips { "yes" } else { "no" }, |
| 236 | h.width, |
| 237 | h.height, |
| 238 | h.fps |
| 239 | ); |
| 240 | for (kind, name) in &h.lanes { |
| 241 | |
| 242 | let name: String = name.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); |
| 243 | let line = if name.is_empty() { format!("lane {}\n", kind_word(*kind)) } else { format!("lane {} {name}\n", kind_word(*kind)) }; |
| 244 | out.push_str(&line); |
| 245 | } |
| 246 | let [r, g, b] = h.caption.highlight; |
| 247 | out.push_str(&format!( |
| 248 | "capstyle {} {r:02x}{g:02x}{b:02x} {} {} {}\n", |
| 249 | h.caption.anim.name(), |
| 250 | u8::from(h.caption.hl_box), |
| 251 | u8::from(h.caption.uppercase), |
| 252 | h.caption.words_per_line |
| 253 | )); |
| 254 | out |
| 255 | } |
| 256 | |
| 257 | fn kind_word(kind: LaneKind) -> &'static str { |
| 258 | match kind { |
| 259 | LaneKind::Video => "video", |
| 260 | LaneKind::Audio => "audio", |
| 261 | LaneKind::Subtitle => "subtitle", |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | |
| 266 | fn parse(text: &str) -> Result<(Head, Option<usize>), String> { |
| 267 | let mut lines = Vec::new(); |
| 268 | let mut body_at = None; |
| 269 | let mut at = 0usize; |
| 270 | for line in text.split_inclusive('\n') { |
| 271 | if line.starts_with("edith ") { |
| 272 | body_at = Some(at); |
| 273 | break; |
| 274 | } |
| 275 | lines.push(line.trim_end_matches(['\n', '\r'])); |
| 276 | at += line.len(); |
| 277 | } |
| 278 | let mut it = lines.into_iter(); |
| 279 | if it.next() != Some(MAGIC) { |
| 280 | return Err("not an edith template".into()); |
| 281 | } |
| 282 | let export = it.next().and_then(|l| l.strip_prefix("export ")).ok_or("no export line")?; |
| 283 | let clips = match it.next().and_then(|l| l.strip_prefix("clips ")) { |
| 284 | Some("yes") => true, |
| 285 | Some("no") => false, |
| 286 | _ => return Err("no clips line".into()), |
| 287 | }; |
| 288 | if clips != body_at.is_some() { |
| 289 | return Err("its clips line and its project do not agree".into()); |
| 290 | } |
| 291 | let mut head = Head { |
| 292 | export: Some(export).filter(|e| *e != "-").map(str::to_string), |
| 293 | clips, |
| 294 | width: 0, |
| 295 | height: 0, |
| 296 | fps: 0.0, |
| 297 | lanes: Vec::new(), |
| 298 | caption: CaptionStyle::default(), |
| 299 | }; |
| 300 | let mut have_settings = false; |
| 301 | for line in it { |
| 302 | if let Some(rest) = line.strip_prefix("settings ") { |
| 303 | let f: Vec<&str> = rest.split(' ').collect(); |
| 304 | let (Some(w), Some(h), Some(fps)) = (f.first(), f.get(1), f.get(2)) else { |
| 305 | return Err("a settings line needs a width, height and rate".into()); |
| 306 | }; |
| 307 | head.width = w.parse().map_err(|_| "bad width")?; |
| 308 | head.height = h.parse().map_err(|_| "bad height")?; |
| 309 | head.fps = fps.parse().map_err(|_| "bad rate")?; |
| 310 | have_settings = true; |
| 311 | } else if let Some(rest) = line.strip_prefix("lane ") { |
| 312 | let (kind, name) = rest.split_once(' ').unwrap_or((rest, "")); |
| 313 | let kind = match kind { |
| 314 | "video" => LaneKind::Video, |
| 315 | "audio" => LaneKind::Audio, |
| 316 | other => return Err(format!("a lane of kind {other} is not one a template holds")), |
| 317 | }; |
| 318 | head.lanes.push((kind, name.to_string())); |
| 319 | } else if let Some(rest) = line.strip_prefix("capstyle ") { |
| 320 | let f: Vec<&str> = rest.split(' ').collect(); |
| 321 | let (Some(anim), Some(hex), Some(bx), Some(up), Some(wpl)) = (f.first(), f.get(1), f.get(2), f.get(3), f.get(4)) else { |
| 322 | return Err("a capstyle line needs five fields".into()); |
| 323 | }; |
| 324 | let channel = |i: usize| hex.get(i..i + 2).and_then(|c| u8::from_str_radix(c, 16).ok()); |
| 325 | let (Some(r), Some(g), Some(b)) = (channel(0), channel(2), channel(4)) else { |
| 326 | return Err("a capstyle colour is six hex digits".into()); |
| 327 | }; |
| 328 | head.caption = CaptionStyle { |
| 329 | anim: CaptionAnim::from_name(anim).ok_or("unknown caption animation")?, |
| 330 | highlight: [r, g, b], |
| 331 | hl_box: *bx == "1", |
| 332 | uppercase: *up == "1", |
| 333 | words_per_line: wpl.parse().map_err(|_| "bad words per line")?, |
| 334 | }; |
| 335 | } |
| 336 | } |
| 337 | if !have_settings { |
| 338 | return Err("no settings line".into()); |
| 339 | } |
| 340 | Ok((head, body_at)) |
| 341 | } |
| 342 | |
| 343 | |
| 344 | fn load(dir: &Path, name: &str) -> crate::Result<(Head, Option<Vec<u8>>)> { |
| 345 | if let Some(b) = BUILTINS.iter().find(|b| b.name == name) { |
| 346 | let head = Head { |
| 347 | export: b.export.map(str::to_string), |
| 348 | clips: false, |
| 349 | width: b.width, |
| 350 | height: b.height, |
| 351 | fps: b.fps, |
| 352 | lanes: vec![(LaneKind::Video, String::new()), (LaneKind::Audio, String::new())], |
| 353 | caption: CaptionStyle::default(), |
| 354 | }; |
| 355 | return Ok((head, None)); |
| 356 | } |
| 357 | let path = file(dir, name); |
| 358 | let bytes = std::fs::read(&path).map_err(|e| format!("no template named {}: {e}", name.trim()))?; |
| 359 | let text = String::from_utf8_lossy(&bytes); |
| 360 | let (head, body_at) = parse(&text).map_err(|e| format!("template {}: {e}", name.trim()))?; |
| 361 | Ok((head, body_at.map(|at| bytes[at..].to_vec()))) |
| 362 | } |
| 363 | |
| 364 | |
| 365 | |
| 366 | fn apply_lanes(s: &mut PlaybackSession, h: &Head) { |
| 367 | for (i, (kind, name)) in h.lanes.iter().enumerate() { |
| 368 | let ord = h.lanes[..i].iter().filter(|(k, _)| k == kind).count(); |
| 369 | let lane = Lane::new(*kind, ord); |
| 370 | if !s.lanes().contains(&lane) { |
| 371 | let _ = s.add_lane(*kind); |
| 372 | } |
| 373 | if !name.is_empty() { |
| 374 | let _ = s.set_lane_name(lane, name); |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | fn project_bytes(s: &PlaybackSession, dir: &Path) -> crate::Result<Vec<u8>> { |
| 385 | let work = scratch_dir(dir); |
| 386 | std::fs::create_dir_all(&work).map_err(|e| format!("cannot make {}: {e}", work.display()))?; |
| 387 | let path = work.join("body.edith"); |
| 388 | let written = s.save_project(&path); |
| 389 | let bytes = written.and_then(|()| std::fs::read(&path).map_err(Into::into)); |
| 390 | let _ = std::fs::remove_dir_all(&work); |
| 391 | bytes |
| 392 | } |
| 393 | |
| 394 | |
| 395 | |
| 396 | fn scratch_dir(dir: &Path) -> PathBuf { |
| 397 | static N: AtomicU64 = AtomicU64::new(0); |
| 398 | dir.join(format!(".work-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))) |
| 399 | } |
| 400 | |
| 401 | #[cfg(test)] |
| 402 | mod tests { |
| 403 | use super::*; |
| 404 | use crate::scratch::Scratch; |
| 405 | |
| 406 | fn media() -> PathBuf { |
| 407 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4") |
| 408 | } |
| 409 | |
| 410 | |
| 411 | |
| 412 | #[test] |
| 413 | fn a_template_keeps_its_settings_and_clips_and_refuses_bad_input() { |
| 414 | let dir = Scratch::dir("tpl_round"); |
| 415 | let vertical = open(&dir, "Vertical 1080×1920 30").expect("built-in opens"); |
| 416 | assert_eq!((vertical.session.resolution(), vertical.session.meta().frame_rate), ((1080, 1920), 30.0)); |
| 417 | assert!(open(&dir, "Nope").is_err()); |
| 418 | |
| 419 | let mut s = PlaybackSession::open(media()).expect("open test asset"); |
| 420 | s.set_lane_name(Lane::A1, "Voice").expect("names a lane"); |
| 421 | let _ = s.add_lane(LaneKind::Audio); |
| 422 | let styled = CaptionStyle { anim: CaptionAnim::Pop, uppercase: true, ..CaptionStyle::default() }; |
| 423 | assert!(s.set_caption_style(styled)); |
| 424 | let clips = crate::versions::clip_count(&s); |
| 425 | assert!(!save(&dir, &s, "Voices", false, Some("podcast")).expect("saves")); |
| 426 | let o = open(&dir, "Voices").expect("opens"); |
| 427 | assert!(o.session.is_empty() && o.export.as_deref() == Some("podcast")); |
| 428 | assert_eq!(o.session.caption_style(), styled); |
| 429 | let mut fresh = PlaybackSession::open(media()).expect("open test asset"); |
| 430 | apply(&dir, "Voices", &mut fresh).expect("applies"); |
| 431 | assert_eq!(fresh.lane_name(Lane::A1), Some("Voice")); |
| 432 | assert_eq!(crate::versions::clip_count(&fresh), clips); |
| 433 | |
| 434 | save(&dir, &s, "Full", true, None).expect("saves with clips"); |
| 435 | let text = std::fs::read_to_string(file(&dir, "Full")).expect("reads"); |
| 436 | let media_path = media().canonicalize().expect("media"); |
| 437 | assert!(text.contains(&media_path.display().to_string()), "{text}"); |
| 438 | let target = dir.join("Full-copy.edith"); |
| 439 | write_project(&dir, "Full", &target).expect("writes"); |
| 440 | assert_eq!(crate::versions::clip_count(&PlaybackSession::open_project(&target).expect("opens")), clips); |
| 441 | |
| 442 | assert!(save(&dir, &s, "a/b", false, None).is_err()); |
| 443 | assert!(save(&dir, &s, "Ok", false, Some("no_such_preset")).is_err()); |
| 444 | std::fs::write(file(&dir, "junk"), "edith 51\n").unwrap(); |
| 445 | assert!(!list(&dir).iter().any(|i| i.name == "junk")); |
| 446 | } |
| 447 | } |