edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | use std::path::PathBuf; |
| 2 | use std::time::{Instant, SystemTime}; |
| 3 | |
| 4 | use serde_json::Value; |
| 5 | |
| 6 | use crate::tools; |
| 7 | |
| 8 | #[derive(Default)] |
| 9 | #[allow(dead_code)] |
| 10 | pub struct Server { |
| 11 | pub session: Option<engine::PlaybackSession>, |
| 12 | pub path: Option<PathBuf>, |
| 13 | pub saved_mtime: Option<SystemTime>, |
| 14 | pub saved_depth: Option<usize>, |
| 15 | /// The engine's `history_pushes` at the last save or open; with `saved_depth` |
| 16 | /// it says whether the project differs from what is on disk. |
| 17 | pub saved_pushes: Option<u64>, |
| 18 | /// The serial of the undo ledger's top entry at the last save or open (0 when the ledger |
| 19 | /// was empty). Undoing back to it is clean; a new edit after undoing past it is not, since |
| 20 | /// it leaves the ledger without that entry and no undo or redo can reach it again. |
| 21 | pub saved_top: u64, |
| 22 | /// How many sources the project had at the last save or open. An import moves |
| 23 | /// neither depth nor pushes, so only this says a library row was added. |
| 24 | pub saved_sources: Option<usize>, |
| 25 | /// The open project as the engine writes it (playhead line left out), taken when the |
| 26 | /// file was opened or saved. An autosave is written only when the session differs from |
| 27 | /// this, so a project nobody changed leaves nothing beside it. |
| 28 | pub saved_body: Option<Vec<u8>>, |
| 29 | /// The take in progress, from `record {action:"start"}` until its stop. |
| 30 | pub recording: Option<tools::record::Active>, |
| 31 | pub ledger: Vec<Entry>, |
| 32 | pub redo_ledger: Vec<Entry>, |
| 33 | /// Motion tracks running or finished but not yet written onto their masks (`track`). |
| 34 | pub tracks: Vec<engine::playback::TrackJob>, |
| 35 | /// Set once the ledger has lost an entry to the engine's undo cap, so `undo` |
| 36 | /// can say why it has nothing left. Cleared wherever the ledger is. |
| 37 | pub history_capped: bool, |
| 38 | /// Set when opening a project dropped a ledger that still held steps, so `undo` can say |
| 39 | /// the history did not survive the open. Cleared wherever a new edit lands. |
| 40 | pub history_lost_on_open: bool, |
| 41 | pub jobs: Vec<Job>, |
| 42 | /// Set by `export_queue {action:"pause"}`: a queued export does not start while it is set, so |
| 43 | /// the running one finishes and the rest wait for `export_queue {action:"start"}`. |
| 44 | pub queue_paused: bool, |
| 45 | /// Editing copies (proxies) being made or settled, one per source (`proxies`). |
| 46 | pub proxy_runs: Vec<crate::tools::media::ProxyRun>, |
| 47 | /// The speech model download running or finished (`speech_model`). |
| 48 | pub speech_download: Option<crate::tools::listen::SpeechDownload>, |
| 49 | /// The render preview being made, and the frames it covers ([`engine::render_cache`]). |
| 50 | pub render: Option<(engine::render_cache::Job, (u32, u32))>, |
| 51 | /// Set when the open project came from a file with a newer autosave beside it that was |
| 52 | /// not recovered. A save then keeps that autosave under a dated name instead of removing it. |
| 53 | pub unrecovered_autosave: bool, |
| 54 | /// The autosave this session recovered (`project_open {recover: true}`): its contents are |
| 55 | /// the session's own, so the session's next autosave may replace it. Any other autosave |
| 56 | /// beside the project holds edits this session never loaded and is moved aside first. |
| 57 | pub recovered_autosave: Option<PathBuf>, |
| 58 | /// Every project file this session opened or saved, canonical path and the mtime it was |
| 59 | /// left with. A save to one of these is this project's own file, with no force needed. |
| 60 | pub own_files: Vec<(PathBuf, Option<SystemTime>)>, |
| 61 | /// Set while the open project is a media file started as a project and has no project |
| 62 | /// file yet: (undo depth, history pushes, sources) as it opened. Its autosave goes to the |
| 63 | /// cache, and only once an edit moves those counts, so a look at a file writes nothing. |
| 64 | pub media_open: Option<(usize, u64, usize)>, |
| 65 | /// What the open had to change to load (a clip past its source, clamped): the file on disk |
| 66 | /// still has the problem, so the project counts as unsaved until a save writes the fix. |
| 67 | pub load_fixes: Vec<String>, |
| 68 | /// Each source's frame rate and playing length as its file read when last seen on disk, by |
| 69 | /// path. A relink compares the new file with it when the old file is offline and cannot be read. |
| 70 | pub source_shape: std::collections::HashMap<PathBuf, crate::tools::media::Shape>, |
| 71 | /// The data folder templates and untitled projects' tones are kept under (`$XDG_DATA_HOME` |
| 72 | /// or `~/.local/share`). `None` is the user's own; tests set a temporary folder here. |
| 73 | pub data_home: Option<PathBuf>, |
| 74 | } |
| 75 | |
| 76 | impl Server { |
| 77 | /// The folder templates are kept in, under this server's data folder. |
| 78 | pub fn templates_dir(&self) -> Option<PathBuf> { |
| 79 | match &self.data_home { |
| 80 | Some(data) => Some(engine::templates::dir_in(data)), |
| 81 | None => engine::templates::dir(), |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// The folder a tone of the project at `project` is kept in: beside the project file when that |
| 87 | /// file exists (the project is saved), else under the data folder `data` (the user's when `None`). |
| 88 | pub fn tone_folder(project: Option<&std::path::Path>, data: Option<&std::path::Path>) -> Option<PathBuf> { |
| 89 | if let Some(p) = project |
| 90 | && p.is_file() |
| 91 | && let Some(parent) = p.parent() |
| 92 | && !parent.as_os_str().is_empty() |
| 93 | { |
| 94 | return Some(parent.to_path_buf()); |
| 95 | } |
| 96 | match data { |
| 97 | Some(data) => Some(engine::generate::Tone::dir_in(data)), |
| 98 | None => engine::generate::Tone::dir(), |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// One undo-ledger entry: a batch's engine steps, and the name undo and redo report for it. |
| 103 | #[derive(Clone, Debug)] |
| 104 | pub struct Entry { |
| 105 | /// Engine undo steps the batch pushed; `undo` takes this many back. |
| 106 | pub steps: usize, |
| 107 | /// The batch's `label`, else a summary of its ops (`split @45 + fade V1@0 (+2 more)`). |
| 108 | pub label: String, |
| 109 | /// Unique per entry, never reused, and kept when undo or redo moves the entry between |
| 110 | /// the two ledgers. The project's saved position is the serial of the entry on top. |
| 111 | pub serial: u64, |
| 112 | } |
| 113 | |
| 114 | impl Entry { |
| 115 | pub fn new(steps: usize, label: impl Into<String>) -> Self { |
| 116 | static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); |
| 117 | let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 118 | Self { steps, label: label.into(), serial } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /// What an exported file measures, read back from the file: integrated loudness (LUFS, the |
| 123 | /// same EBU R128 measurement `loudness` reports) and the highest true peak (dBTP). |
| 124 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 125 | pub struct FileLevels { |
| 126 | pub lufs: f64, |
| 127 | pub true_peak_dbtp: f64, |
| 128 | } |
| 129 | |
| 130 | /// What a queued export needs to start later: the timeline as it was when queued. |
| 131 | pub struct Pending { |
| 132 | pub project: engine::Project, |
| 133 | pub meta: engine::VideoMeta, |
| 134 | pub settings: engine::export::ExportSettings, |
| 135 | pub sample_rate: Option<u32>, |
| 136 | pub length_secs: f64, |
| 137 | } |
| 138 | |
| 139 | #[allow(dead_code)] |
| 140 | pub struct Job { |
| 141 | pub out: PathBuf, |
| 142 | /// The running worker; `None` while the job waits in the queue (`pending`) and for a |
| 143 | /// queued job cancelled before it started. |
| 144 | pub handle: Option<engine::ExportHandle>, |
| 145 | /// A queued job's own copy of the timeline and settings, taken when it was queued; it starts |
| 146 | /// when every job before it has finished (see `tools::export::advance`). |
| 147 | pub pending: Option<Box<Pending>>, |
| 148 | pub started: Instant, |
| 149 | pub outcome: Option<Result<(), String>>, |
| 150 | /// The picture encoder planned at start (`SW encode (rav1e)`, `copy (source packets)`, ...); |
| 151 | /// empty for an audio-only export. |
| 152 | pub picture: String, |
| 153 | /// The format the export writes, for the codec and container words the replies use. |
| 154 | pub format: engine::export::Format, |
| 155 | /// The finished file's loudness and true peak, measured once from the file itself (the encoder |
| 156 | /// can add overshoot above the mix). `None` until measured; `Some(None)` for a file with no sound. |
| 157 | pub measured: Option<Option<FileLevels>>, |
| 158 | } |
| 159 | |
| 160 | impl Job { |
| 161 | /// Whether the job is waiting in the queue and has not started. |
| 162 | pub fn waiting(&self) -> bool { |
| 163 | self.pending.is_some() |
| 164 | } |
| 165 | |
| 166 | pub fn progress(&self) -> f32 { |
| 167 | self.handle.as_ref().map_or(0.0, engine::ExportHandle::progress) |
| 168 | } |
| 169 | |
| 170 | /// A job with no worker yet is not finished; one whose waiting was cancelled has an outcome. |
| 171 | pub fn is_finished(&self) -> bool { |
| 172 | self.handle.as_ref().is_some_and(engine::ExportHandle::is_finished) |
| 173 | } |
| 174 | |
| 175 | pub fn is_cancelling(&self) -> bool { |
| 176 | self.handle.as_ref().is_some_and(engine::ExportHandle::is_cancelling) |
| 177 | } |
| 178 | |
| 179 | pub fn encoders(&self) -> Option<String> { |
| 180 | self.handle.as_ref().and_then(engine::ExportHandle::encoders) |
| 181 | } |
| 182 | |
| 183 | pub fn stage(&self) -> Option<(&'static str, f32)> { |
| 184 | self.handle.as_ref().and_then(engine::ExportHandle::stage) |
| 185 | } |
| 186 | |
| 187 | pub fn length_secs(&self) -> f64 { |
| 188 | match (&self.handle, &self.pending) { |
| 189 | (Some(h), _) => h.length_secs(), |
| 190 | (None, Some(p)) => p.length_secs, |
| 191 | _ => 0.0, |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | pub fn result(&self) -> Option<engine::Result<()>> { |
| 196 | self.handle.as_ref().and_then(engine::ExportHandle::result) |
| 197 | } |
| 198 | |
| 199 | /// Stops the job: a running one at its next checkpoint, a waiting one at once (it never starts). |
| 200 | pub fn cancel(&mut self) { |
| 201 | match &self.handle { |
| 202 | Some(h) => h.cancel(), |
| 203 | None => { |
| 204 | if self.pending.take().is_some() { |
| 205 | self.outcome = Some(Err("cancelled".to_string())); |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | pub struct Reply { |
| 213 | pub text: String, |
| 214 | /// Boxed so `Reply` stays small: with serde_json's `preserve_order` (unified in by the |
| 215 | /// workspace build) an inline `Value` is 72 bytes and `Reply` crosses clippy's `result_large_err` |
| 216 | /// limit wherever it is the `Err` of a `Result`. |
| 217 | pub structured: Option<Box<Value>>, |
| 218 | pub is_error: bool, |
| 219 | /// Image content blocks after the text: `(mime, base64)` pairs. |
| 220 | pub images: Vec<(String, String)>, |
| 221 | } |
| 222 | |
| 223 | #[allow(dead_code)] |
| 224 | impl Reply { |
| 225 | pub fn ok(text: impl Into<String>) -> Self { |
| 226 | Self { text: text.into(), structured: None, is_error: false, images: Vec::new() } |
| 227 | } |
| 228 | |
| 229 | pub fn err(text: impl Into<String>) -> Self { |
| 230 | Self { text: text.into(), structured: None, is_error: true, images: Vec::new() } |
| 231 | } |
| 232 | |
| 233 | pub fn with(mut self, v: Value) -> Self { |
| 234 | self.structured = Some(Box::new(v)); |
| 235 | self |
| 236 | } |
| 237 | |
| 238 | /// Adds one PNG-or-other image block after the text. `b64` is standard base64. |
| 239 | pub fn image(mut self, mime: impl Into<String>, b64: impl Into<String>) -> Self { |
| 240 | self.images.push((mime.into(), b64.into())); |
| 241 | self |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | pub type ToolFn = fn(&mut Server, &Value) -> Reply; |
| 246 | |
| 247 | pub struct Tool { |
| 248 | pub name: &'static str, |
| 249 | pub description: &'static str, |
| 250 | pub schema: fn() -> Value, |
| 251 | pub run: ToolFn, |
| 252 | } |
| 253 | |
| 254 | pub fn tools() -> Vec<Tool> { |
| 255 | let mut all = Vec::new(); |
| 256 | all.extend(tools::project::tools()); |
| 257 | all.extend(tools::media::tools()); |
| 258 | all.extend(tools::look::tools()); |
| 259 | all.extend(tools::edit::tools()); |
| 260 | all.extend(tools::edit_subs::tools()); |
| 261 | all.extend(tools::export::tools()); |
| 262 | all.extend(tools::render::tools()); |
| 263 | all.extend(tools::see::tools()); |
| 264 | all.extend(tools::hear::tools()); |
| 265 | all.extend(tools::listen::tools()); |
| 266 | all.extend(tools::scan::tools()); |
| 267 | all.extend(tools::speak::tools()); |
| 268 | all.extend(tools::record::tools()); |
| 269 | all.extend(tools::voice::tools()); |
| 270 | all.extend(tools::effects::tools()); |
| 271 | all.extend(tools::stabilise::tools()); |
| 272 | all.extend(tools::track::tools()); |
| 273 | all.extend(tools::sequence::tools()); |
| 274 | all.extend(tools::multicam::tools()); |
| 275 | all |
| 276 | } |
| 277 | |
| 278 | /// Early-returns the `Err(Reply)` of a `Result<_, Reply>` from a tool fn. |
| 279 | #[allow(unused_macros)] |
| 280 | macro_rules! tri { |
| 281 | ($e:expr) => { |
| 282 | match $e { |
| 283 | Ok(v) => v, |
| 284 | Err(r) => return r, |
| 285 | } |
| 286 | }; |
| 287 | } |
| 288 | #[allow(unused_imports)] |
| 289 | pub(crate) use tri; |
| 290 | |
| 291 | #[allow(dead_code)] |
| 292 | const NO_PROJECT: &str = "no project open — call project_open or project_new first"; |
| 293 | |
| 294 | #[allow(dead_code)] |
| 295 | impl Server { |
| 296 | pub fn new() -> Self { |
| 297 | Self::default() |
| 298 | } |
| 299 | |
| 300 | pub fn session(&mut self) -> Result<&mut engine::PlaybackSession, Reply> { |
| 301 | self.session.as_mut().ok_or_else(|| Reply::err(NO_PROJECT)) |
| 302 | } |
| 303 | |
| 304 | pub fn session_ref(&self) -> Result<&engine::PlaybackSession, Reply> { |
| 305 | self.session.as_ref().ok_or_else(|| Reply::err(NO_PROJECT)) |
| 306 | } |
| 307 | |
| 308 | /// Drops the oldest ledger entries until their steps fit in the engine's undo |
| 309 | /// history. The engine keeps 100 steps and drops the oldest past that, so a |
| 310 | /// batch with a step gone cannot be undone whole, and undoing it would take |
| 311 | /// steps off the batches after it. Sets `history_capped` when it drops one. |
| 312 | pub fn trim_ledger(&mut self) { |
| 313 | let Some(depth) = self.session.as_ref().map(|s| s.undo_depth()) else { |
| 314 | return; |
| 315 | }; |
| 316 | let mut total: usize = self.ledger.iter().map(|e| e.steps).sum(); |
| 317 | while total > depth { |
| 318 | total -= self.ledger.remove(0).steps; |
| 319 | self.history_capped = true; |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | /// The serial of the undo ledger's top entry, 0 when nothing can be undone. |
| 324 | pub fn ledger_top(&self) -> u64 { |
| 325 | self.ledger.last().map_or(0, |e| e.serial) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | #[allow(dead_code)] |
| 330 | pub fn arg_str<'a>(args: &'a Value, name: &str) -> Result<&'a str, Reply> { |
| 331 | opt_str(args, name) |
| 332 | .ok_or_else(|| Reply::err(format!("missing/invalid argument `{name}`: expected a string"))) |
| 333 | } |
| 334 | |
| 335 | #[allow(dead_code)] |
| 336 | pub fn opt_str<'a>(args: &'a Value, name: &str) -> Option<&'a str> { |
| 337 | args.get(name)?.as_str() |
| 338 | } |
| 339 | |
| 340 | #[allow(dead_code)] |
| 341 | pub fn opt_bool(args: &Value, name: &str) -> Option<bool> { |
| 342 | args.get(name)?.as_bool() |
| 343 | } |
| 344 | |
| 345 | #[allow(dead_code)] |
| 346 | pub fn opt_f64(args: &Value, name: &str) -> Option<f64> { |
| 347 | args.get(name)?.as_f64() |
| 348 | } |
| 349 | |
| 350 | #[allow(dead_code)] |
| 351 | pub fn opt_u64(args: &Value, name: &str) -> Option<u64> { |
| 352 | args.get(name)?.as_u64() |
| 353 | } |
| 354 | |
| 355 | #[cfg(test)] |
| 356 | mod tests { |
| 357 | use super::*; |
| 358 | use serde_json::json; |
| 359 | |
| 360 | #[test] |
| 361 | fn reply_stays_under_clippy_large_err_limit() { |
| 362 | // clippy::result_large_err fires at 128 bytes; `Reply` is the Err of most tool helpers. |
| 363 | assert!(std::mem::size_of::<Reply>() < 128, "Reply is {} bytes", std::mem::size_of::<Reply>()); |
| 364 | } |
| 365 | |
| 366 | #[test] |
| 367 | fn with_keeps_the_structured_value() { |
| 368 | let r = Reply::ok("done").with(json!({"placed": true})); |
| 369 | assert_eq!(r.structured.as_deref(), Some(&json!({"placed": true}))); |
| 370 | assert!(Reply::err("no").structured.is_none()); |
| 371 | } |
| 372 | } |