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 | //! Media tools: probe, import, list. |
| 2 | //! |
| 3 | //! `media_probe` reads headers only and never touches the open project. |
| 4 | //! `media_import` adds sources to the open project; it places nothing. |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 7 | use std::sync::Arc; |
| 8 | use std::thread::{self, JoinHandle}; |
| 9 | |
| 10 | use engine::{probe_bitrate, probe_media, MediaFacts}; |
| 11 | use serde_json::{json, Value}; |
| 12 | |
| 13 | use crate::parse; |
| 14 | use crate::server::{opt_str, tri, Entry, Reply, Server, Tool}; |
| 15 | use crate::tools::project::expand_home; |
| 16 | |
| 17 | /// Most files one probe call reads. |
| 18 | const CAP: usize = 200; |
| 19 | |
| 20 | pub fn tools() -> Vec<Tool> { |
| 21 | vec![ |
| 22 | Tool { |
| 23 | name: "media_relink", |
| 24 | description: "Point an offline source (its file was moved or deleted) at a new file. The new file must be the same kind (picture, sound or still) and long enough for the clips on it; a length that differs from the old file by more than a frame is a warning. Clips are unchanged. The project is unsaved until project_save.", |
| 25 | schema: || { |
| 26 | schema( |
| 27 | json!({ |
| 28 | "source": {"type": "string", "description": "The source to relink, as media_list names it, e.g. src:3."}, |
| 29 | "path": {"type": "string", "description": "The file the source now is."} |
| 30 | }), |
| 31 | &["source", "path"], |
| 32 | ) |
| 33 | }, |
| 34 | run: relink, |
| 35 | }, |
| 36 | Tool { |
| 37 | name: "media_probe", |
| 38 | description: "Read a media file's header without importing it: container, codec, size, frame rate, duration and bitrate, then each audio and subtitle track with its language, channel layout (mono, stereo, 5.1, 7.1) and sample rate. A track of more than two channels is noted as mixed to stereo on export. Give paths, a glob, or both. Up to 200 files per call.", |
| 39 | schema: || { |
| 40 | schema( |
| 41 | json!({ |
| 42 | "paths": { |
| 43 | "type": ["array", "string"], |
| 44 | "items": {"type": "string"}, |
| 45 | "description": "File paths to probe: a list, or one path as a string. A path whose last component has * ? or [ is expanded as a glob." |
| 46 | }, |
| 47 | "glob": { |
| 48 | "type": "string", |
| 49 | "description": "A glob such as ~/clips/*.mp4. Wildcards * and ? apply to the last path component only." |
| 50 | } |
| 51 | }), |
| 52 | &[], |
| 53 | ) |
| 54 | }, |
| 55 | run: probe, |
| 56 | }, |
| 57 | Tool { |
| 58 | name: "media_import", |
| 59 | description: "Add media files to the open project as sources (src:<n>). Places nothing on the timeline. Importing a file twice registers it once.", |
| 60 | schema: || { |
| 61 | schema( |
| 62 | json!({ |
| 63 | "paths": { |
| 64 | "type": ["array", "string"], |
| 65 | "items": {"type": "string"}, |
| 66 | "description": "Media file paths to import into the open project: a list, or one path as a string. A path whose last component has * ? or [ is expanded as a glob." |
| 67 | } |
| 68 | }), |
| 69 | &["paths"], |
| 70 | ) |
| 71 | }, |
| 72 | run: import, |
| 73 | }, |
| 74 | Tool { |
| 75 | name: "proxies", |
| 76 | description: "The editing copies (proxies) of the sources: a smaller re-encode of a heavy film that the editor plays and cuts on. action status (the default) shows each source's state and the progress of a stand-in being made; action make with source starts one in the background (it turns the film's switch back on); action cancel stops one being made (the film stays off, as the Proxies switch on a library row leaves it); action delete removes the stand-in and keeps the film off. source is src:<n>, a list, or \"all\". A film that plays at speed on this machine needs none, and says so. With project_settings auto_proxies on, every import starts its stand-in the same way. Example: proxies {action:\"make\", source:\"src:2\"}.", |
| 77 | schema: proxies_schema, |
| 78 | run: proxies, |
| 79 | }, |
| 80 | Tool { |
| 81 | name: "media_remove", |
| 82 | description: "Drop an unused source (src:<n>) from the open project. Refused, naming the clips, while any clip plays from it. The undo history is kept when the source is the last one; any other source renumbers the sources after it, which clears the undo history, so that is refused unless force is true. The project is left unsaved until project_save.", |
| 83 | schema: || { |
| 84 | schema( |
| 85 | json!({ |
| 86 | "source": { |
| 87 | "type": "string", |
| 88 | "description": "The source to drop, as media_list names it: src:<n>." |
| 89 | }, |
| 90 | "force": { |
| 91 | "type": "boolean", |
| 92 | "description": "Remove it even though that clears the undo history (any source but the last renumbers the ones after it)." |
| 93 | } |
| 94 | }), |
| 95 | &["source"], |
| 96 | ) |
| 97 | }, |
| 98 | run: remove, |
| 99 | }, |
| 100 | Tool { |
| 101 | name: "media_bin", |
| 102 | description: "Organise the media library into bins (named folders, one level of nesting) and star favourites. action \"create\" {name, parent?} makes a bin; \"rename\" {bin, name}; \"remove\" {bin} deletes a bin and keeps what it held (its sources go up one level, bins inside it come out to the top); \"move\" {sources, bin?} files sources in a bin, and no bin takes them out of every bin; \"favourite\" {sources, on?=true} stars or unstars sources. A bin is written bin:<n> (as media_list shows it) or by its name; Parent/Child names a bin inside another. Sources are src:<n>, a list of them, or \"all\". Each call is one undo step; the project is unsaved until project_save.", |
| 103 | schema: || { |
| 104 | schema( |
| 105 | json!({ |
| 106 | "action": {"type": "string", "enum": ["create", "rename", "remove", "move", "favourite"], "description": "What to do."}, |
| 107 | "name": {"type": "string", "description": "create: the new bin's name. rename: its new name."}, |
| 108 | "parent": {"type": ["string", "number"], "description": "create: the bin to make it inside (bin:<n> or a name). Omit for the top level."}, |
| 109 | "bin": {"type": ["string", "number"], "description": "rename, remove, move: the bin, as bin:<n> or by name. move without it takes the sources out of their bin."}, |
| 110 | "sources": {"type": ["array", "string", "number"], "items": {"type": ["string", "number"]}, "description": "move, favourite: src:<n>, a list of them, or \"all\"."}, |
| 111 | "on": {"type": "boolean", "description": "favourite: true stars (default), false unstars."} |
| 112 | }), |
| 113 | &["action"], |
| 114 | ) |
| 115 | }, |
| 116 | run: bin, |
| 117 | }, |
| 118 | Tool { |
| 119 | name: "media_list", |
| 120 | description: "List the open project's sources: src:<n>, name, duration, and video size, codec and frame rate, then the bin each is filed in and a star if it is a favourite. Bins are listed first as bin:<n>. kind keeps only one kind of source: video (a picture with motion), audio (sound only) or image (a still); offline sources are kept only when no kind is asked for.", |
| 121 | schema: || schema(json!({"kind": {"type": "string", "enum": ["video", "audio", "image"], "description": "Only sources of this kind: video, audio or image (a still). Omitted: every source."}}), &[]), |
| 122 | run: list, |
| 123 | }, |
| 124 | ] |
| 125 | } |
| 126 | |
| 127 | fn schema(properties: Value, required: &[&str]) -> Value { |
| 128 | json!({ |
| 129 | "type": "object", |
| 130 | "properties": properties, |
| 131 | "required": required, |
| 132 | "additionalProperties": false |
| 133 | }) |
| 134 | } |
| 135 | |
| 136 | // ---- gathering paths ------------------------------------------------------- |
| 137 | |
| 138 | /// Expands one argument: a glob if its last component has a wildcard, else the path itself. |
| 139 | fn expand_glob(raw: &str) -> Result<Vec<PathBuf>, String> { |
| 140 | let path = expand_home(raw); |
| 141 | let name = match path.file_name().and_then(|n| n.to_str()) { |
| 142 | Some(n) if n.contains(['*', '?', '[']) => n.to_string(), |
| 143 | _ => return Ok(vec![path]), |
| 144 | }; |
| 145 | let dir = match path.parent() { |
| 146 | Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), |
| 147 | _ => PathBuf::from("."), |
| 148 | }; |
| 149 | let entries = std::fs::read_dir(&dir).map_err(|e| format!("cannot read {}: {e}", dir.display()))?; |
| 150 | let mut hits: Vec<PathBuf> = entries |
| 151 | .filter_map(|e| e.ok()) |
| 152 | .map(|e| e.path()) |
| 153 | .filter(|p| p.is_file()) |
| 154 | .filter(|p| { |
| 155 | p.file_name() |
| 156 | .and_then(|n| n.to_str()) |
| 157 | .is_some_and(|n| (!n.starts_with('.') || name.starts_with('.')) && wild(&name, n)) |
| 158 | }) |
| 159 | .collect(); |
| 160 | hits.sort(); |
| 161 | Ok(hits) |
| 162 | } |
| 163 | |
| 164 | /// Matches `name` against `pat`, where `*` is any run, `?` one character, and |
| 165 | /// `[abc]`, `[a-z]` or `[!abc]` one character from (or outside) a set. A `[` with no |
| 166 | /// closing `]` is an ordinary character. |
| 167 | fn wild(pat: &str, name: &str) -> bool { |
| 168 | let p: Vec<char> = pat.chars().collect(); |
| 169 | let n: Vec<char> = name.chars().collect(); |
| 170 | let (mut pi, mut ni) = (0, 0); |
| 171 | let mut star: Option<usize> = None; |
| 172 | let mut mark = 0; |
| 173 | while ni < n.len() { |
| 174 | match one(&p, pi, n[ni]) { |
| 175 | Some(next) => { |
| 176 | pi = next; |
| 177 | ni += 1; |
| 178 | } |
| 179 | None if pi < p.len() && p[pi] == '*' => { |
| 180 | star = Some(pi); |
| 181 | mark = ni; |
| 182 | pi += 1; |
| 183 | } |
| 184 | None => match star { |
| 185 | Some(s) => { |
| 186 | pi = s + 1; |
| 187 | mark += 1; |
| 188 | ni = mark; |
| 189 | } |
| 190 | None => return false, |
| 191 | }, |
| 192 | } |
| 193 | } |
| 194 | while pi < p.len() && p[pi] == '*' { |
| 195 | pi += 1; |
| 196 | } |
| 197 | pi == p.len() |
| 198 | } |
| 199 | |
| 200 | /// The pattern index just past the one-character item at `pi`, when that item matches `c`. |
| 201 | fn one(p: &[char], pi: usize, c: char) -> Option<usize> { |
| 202 | match *p.get(pi)? { |
| 203 | '?' => Some(pi + 1), |
| 204 | '[' => match p[pi + 1..].iter().position(|&x| x == ']') { |
| 205 | Some(off) => set_matches(&p[pi + 1..pi + 1 + off], c).then_some(pi + off + 2), |
| 206 | None => (c == '[').then_some(pi + 1), |
| 207 | }, |
| 208 | item if item == c => Some(pi + 1), |
| 209 | _ => None, |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /// Whether `c` is in a bracket set's body (the text between `[` and `]`): listed |
| 214 | /// characters, `a-z` ranges, and a leading `!` for "none of these". |
| 215 | fn set_matches(body: &[char], c: char) -> bool { |
| 216 | let (negate, body) = match body.first() { |
| 217 | Some('!') => (true, &body[1..]), |
| 218 | _ => (false, body), |
| 219 | }; |
| 220 | let mut hit = false; |
| 221 | let mut i = 0; |
| 222 | while i < body.len() { |
| 223 | if i + 2 < body.len() && body[i + 1] == '-' { |
| 224 | hit |= body[i] <= c && c <= body[i + 2]; |
| 225 | i += 3; |
| 226 | } else { |
| 227 | hit |= body[i] == c; |
| 228 | i += 1; |
| 229 | } |
| 230 | } |
| 231 | hit != negate |
| 232 | } |
| 233 | |
| 234 | /// The files named by `paths` and `glob` arguments, in order, without repeats. |
| 235 | /// `glob_arg` says whether the tool takes a `glob` argument of its own, which only media_probe does; |
| 236 | /// the wording of its refusals names it, and media_import's names the pattern inside `paths`. |
| 237 | fn gather(args: &Value, glob_arg: bool) -> Result<Vec<PathBuf>, Reply> { |
| 238 | gather_listed(args, glob_arg).map(|(files, _)| files) |
| 239 | } |
| 240 | |
| 241 | /// The files `paths` and `glob` name, each once, and the repeats: the later entries that |
| 242 | /// named a file already in the list (so an import can say so). |
| 243 | fn gather_listed(args: &Value, glob_arg: bool) -> Result<(Vec<PathBuf>, Vec<PathBuf>), Reply> { |
| 244 | let mut raw: Vec<String> = Vec::new(); |
| 245 | // Set when `paths` was given but names nothing: an empty list, or a blank string. |
| 246 | let mut empty = false; |
| 247 | match args.get("paths") { |
| 248 | None | Some(Value::Null) => {} |
| 249 | Some(Value::String(s)) if s.trim().is_empty() => empty = true, |
| 250 | Some(Value::String(s)) => raw.push(s.clone()), |
| 251 | Some(Value::Array(items)) => { |
| 252 | empty = items.is_empty(); |
| 253 | for item in items { |
| 254 | match item.as_str() { |
| 255 | Some(s) => raw.push(s.to_string()), |
| 256 | None => return Err(Reply::err("every entry of `paths` must be a string")), |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | Some(_) => return Err(Reply::err("argument `paths` must be a file path, or a list of file paths")), |
| 261 | } |
| 262 | if let Some(g) = opt_str(args, "glob") { |
| 263 | raw.push(g.to_string()); |
| 264 | } |
| 265 | if raw.is_empty() { |
| 266 | let pattern = "~/clips/*.mp4"; |
| 267 | if empty { |
| 268 | return Err(Reply::err(match glob_arg { |
| 269 | true => format!("the list `paths` is empty: give at least one file path, or a `glob` such as {pattern}"), |
| 270 | false => format!("the list `paths` is empty: give at least one file path, or a pattern such as {pattern} inside it"), |
| 271 | })); |
| 272 | } |
| 273 | return Err(Reply::err(match glob_arg { |
| 274 | true => format!("give `paths` or `glob`: a list of file paths, or a pattern such as {pattern}"), |
| 275 | false => format!("give `paths`: a list of file paths, or a pattern such as {pattern}"), |
| 276 | })); |
| 277 | } |
| 278 | let mut out: Vec<PathBuf> = Vec::new(); |
| 279 | let mut repeats: Vec<PathBuf> = Vec::new(); |
| 280 | for r in &raw { |
| 281 | let found = expand_glob(r).map_err(Reply::err)?; |
| 282 | for p in found { |
| 283 | if out.contains(&p) { |
| 284 | repeats.push(p); |
| 285 | } else { |
| 286 | out.push(p); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | Ok((out, repeats)) |
| 291 | } |
| 292 | |
| 293 | // ---- formatting ------------------------------------------------------------ |
| 294 | |
| 295 | /// `29.97`, `30`, `23.976`: a frame rate with no trailing zeros. |
| 296 | fn fmt_fps(f: f64) -> String { |
| 297 | let s = format!("{f:.3}"); |
| 298 | s.trim_end_matches('0').trim_end_matches('.').to_string() |
| 299 | } |
| 300 | |
| 301 | /// `00:15.000` from seconds. Milliseconds are the frame count at a rate of 1000. |
| 302 | fn clock_secs(secs: f64) -> String { |
| 303 | parse::clock((secs * 1000.0).round() as u32, 1000.0) |
| 304 | } |
| 305 | |
| 306 | /// A file's playing time for a row: `00:05.000` when its header states one, `still` |
| 307 | /// for a picture (which has no playing time to state), else `duration unknown`. |
| 308 | /// |
| 309 | /// Read from the header and never from frame counts: a source's frames are counted at |
| 310 | /// the timeline's rate, so dividing them by either rate is how a 5 s clip came out 4.167 s. |
| 311 | fn duration_label(path: &Path, secs: Option<f64>) -> String { |
| 312 | match secs { |
| 313 | Some(s) => clock_secs(s), |
| 314 | None if engine::is_image(path) => "still".to_string(), |
| 315 | None => "duration unknown".to_string(), |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | /// The audio stream's own length, when it is not the picture's: a 2 s clip with a |
| 320 | /// 60 s commentary plays 2 s of picture and 60 s of sound. Only a picture file |
| 321 | /// can differ, so a song or a still never asks. |
| 322 | fn audio_only_secs(path: &Path, facts: &MediaFacts) -> Option<f64> { |
| 323 | facts.video?; |
| 324 | let picture = facts.duration_secs?; |
| 325 | let audio = engine::AudioSession::duration_secs(path).ok().flatten()?; |
| 326 | ((audio - picture).abs() > 0.01).then_some(audio) |
| 327 | } |
| 328 | |
| 329 | /// A row's playing time, in the clock form every row uses: the picture's length as the |
| 330 | /// timeline counts it, and the audio's own length after a semicolon when it runs on past it (or stops short), |
| 331 | /// in seconds so the two lengths never nest in brackets: `2.000 s; audio 2.027 s`. |
| 332 | fn duration_text(path: &Path, facts: &MediaFacts) -> String { |
| 333 | match (facts.duration_secs, audio_only_secs(path, facts)) { |
| 334 | (Some(picture), Some(audio)) => format!("{picture:.3} s; audio {audio:.3} s"), |
| 335 | _ => duration_label(path, facts.duration_secs), |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | fn bitrate_text(bps: u64) -> String { |
| 340 | if bps >= 1_000_000 { |
| 341 | format!("{:.2} Mb/s", bps as f64 / 1e6) |
| 342 | } else { |
| 343 | format!("{:.0} kb/s", bps as f64 / 1e3) |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /// The message for a path that is not there, the same in every tool that takes paths. |
| 348 | pub fn not_found(path: &Path) -> String { |
| 349 | format!("not found: {}", path.display()) |
| 350 | } |
| 351 | |
| 352 | fn file_name(path: &Path) -> String { |
| 353 | path.file_name() |
| 354 | .map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()) |
| 355 | } |
| 356 | |
| 357 | /// Why `path` cannot be read as a file, or `None` when it can: a folder is named as |
| 358 | /// one, and so is anything else that is not a regular file (a device, a pipe, a socket), |
| 359 | /// which is never opened. |
| 360 | pub fn not_a_file(path: &Path) -> Option<String> { |
| 361 | if path.is_file() { |
| 362 | None |
| 363 | } else if path.is_dir() { |
| 364 | Some(format!("is a directory, not a file: {}", path.display())) |
| 365 | } else { |
| 366 | Some(format!("is not a regular file: {}", path.display())) |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | // ---- media_probe ----------------------------------------------------------- |
| 371 | |
| 372 | /// One probed file. `error` is set when the file cannot be read as media. |
| 373 | struct Row { |
| 374 | path: PathBuf, |
| 375 | facts: Option<MediaFacts>, |
| 376 | bitrate_bps: Option<u64>, |
| 377 | /// The sound and subtitle streams beside the picture, in container order. |
| 378 | streams: Vec<Stream>, |
| 379 | /// Why the file is refused. A refused picture keeps its facts and streams beside it. |
| 380 | error: Option<String>, |
| 381 | /// What the file's sound will do that the person should know: a codec nothing decodes. |
| 382 | warnings: Vec<String>, |
| 383 | /// The picture as stored, when the picture was read: its coded size and pixel aspect. |
| 384 | coded: Option<Coded>, |
| 385 | /// A still's size as shown (turn applied), when the file is a still that reads. |
| 386 | still: Option<(u32, u32)>, |
| 387 | } |
| 388 | |
| 389 | /// A picture as its header stores it, before the display stretch: the coded size and the |
| 390 | /// sample aspect ratio (`sar`, `(1, 1)` for square pixels), and the turn the header's display |
| 391 | /// matrix asks for. Also what the picture's samples mean: the colour the import path resolves |
| 392 | /// and the chroma layout, where the engine states one. |
| 393 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 394 | struct Coded { |
| 395 | w: u32, |
| 396 | h: u32, |
| 397 | sar: (u32, u32), |
| 398 | turn: engine::demux::Rotation, |
| 399 | colour: engine::colorspace::ColorDescription, |
| 400 | /// The chroma layout the bitstream states (gray, 4:2:0, 4:2:2, 4:4:4); `None` where the |
| 401 | /// engine reads none. |
| 402 | chroma: Option<engine::colorspace::Chroma>, |
| 403 | } |
| 404 | |
| 405 | impl Coded { |
| 406 | /// `(stored 1280x640, turned 90° counter-clockwise to stand upright; ffprobe rotation 90)` for a |
| 407 | /// picture the header turns, `None` for an upright one. The turn is what edith applies to show the |
| 408 | /// picture upright; ffprobe's `rotation` is the same turn with the opposite sign, as its tag reads. |
| 409 | fn turn_text(&self) -> Option<String> { |
| 410 | let (turn, ffprobe) = match self.turn { |
| 411 | engine::demux::Rotation::None => return None, |
| 412 | engine::demux::Rotation::Cw90 => ("90° clockwise", "-90"), |
| 413 | engine::demux::Rotation::Cw180 => ("180°", "180"), |
| 414 | engine::demux::Rotation::Cw270 => ("90° counter-clockwise", "90"), |
| 415 | }; |
| 416 | Some(format!("(stored {}x{}, turned {turn} to stand upright; ffprobe rotation {ffprobe})", self.w, self.h)) |
| 417 | } |
| 418 | |
| 419 | /// `1440x1080 (shown 1920x1080, pixel aspect 4:3)` for a picture whose pixels are not square, |
| 420 | /// `None` for square pixels, which show the size alone. |
| 421 | fn text(&self, shown: (u32, u32)) -> Option<String> { |
| 422 | let (h, v) = self.sar; |
| 423 | if v == 0 || h == v { |
| 424 | return None; |
| 425 | } |
| 426 | let g = gcd(h, v).max(1); |
| 427 | Some(format!( |
| 428 | "{}x{} (shown {}x{}, pixel aspect {}:{})", |
| 429 | self.w, |
| 430 | self.h, |
| 431 | shown.0, |
| 432 | shown.1, |
| 433 | h / g, |
| 434 | v / g |
| 435 | )) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | fn gcd(a: u32, b: u32) -> u32 { |
| 440 | if b == 0 { a } else { gcd(b, a % b) } |
| 441 | } |
| 442 | |
| 443 | /// The picture's coded size and pixel aspect, read from its header (`Demuxer::open` reads the |
| 444 | /// header only). `None` when the file will not open as a picture. |
| 445 | fn coded_of(path: &Path) -> Option<Coded> { |
| 446 | let (meta, demuxer) = engine::demux::Demuxer::open(path).ok()?; |
| 447 | let chroma = demuxer.chroma(); |
| 448 | Some(Coded { |
| 449 | w: meta.coded_width, |
| 450 | h: meta.coded_height, |
| 451 | sar: (meta.pixel_aspect.h, meta.pixel_aspect.v), |
| 452 | turn: meta.rotation, |
| 453 | colour: meta.color, |
| 454 | chroma, |
| 455 | }) |
| 456 | } |
| 457 | |
| 458 | /// The colour a picture's samples are on, in the words a person knows it by: the matrix, then |
| 459 | /// the curve where it is not SDR (`BT.2020 PQ`), then the range where it is full. An HDR curve |
| 460 | /// says what export does with it, since the file written is SDR. A matrix the file does not tag |
| 461 | /// (`assumed`, the size rule's guess) says so: `BT.709 (assumed, untagged)`. |
| 462 | fn colour_text(c: engine::colorspace::ColorDescription, assumed: bool) -> String { |
| 463 | use engine::colorspace::{Matrix, Transfer}; |
| 464 | let matrix = match c.matrix { |
| 465 | Matrix::Bt601 => "BT.601", |
| 466 | Matrix::Bt709 => "BT.709", |
| 467 | Matrix::Bt2020Ncl => "BT.2020", |
| 468 | }; |
| 469 | let matrix = if assumed { format!("{matrix} (assumed, untagged)") } else { matrix.to_string() }; |
| 470 | let mut text = match c.transfer { |
| 471 | Transfer::Sdr => matrix, |
| 472 | Transfer::Pq => format!("{matrix} PQ"), |
| 473 | Transfer::Hlg => format!("{matrix} HLG"), |
| 474 | }; |
| 475 | if c.full_range { |
| 476 | text.push_str(" full range"); |
| 477 | } |
| 478 | if c.transfer != Transfer::Sdr { |
| 479 | text.push_str(" (HDR: exports tone-mapped to 8-bit SDR)"); |
| 480 | } |
| 481 | text |
| 482 | } |
| 483 | |
| 484 | /// The picture's bit depth, chroma layout and colour, each only where the engine states it, |
| 485 | /// joined as one line: `10-bit 4:2:0 · BT.2020 PQ (HDR: ...)`. `None` when none is known. |
| 486 | fn picture_info(bit_depth: Option<u8>, matrix_assumed: bool, coded: Option<&Coded>) -> Option<String> { |
| 487 | // The depth and the chroma are one part (`10-bit 4:2:0`); the colour is the other. |
| 488 | let mut layout = Vec::new(); |
| 489 | if let Some(d) = bit_depth { |
| 490 | layout.push(format!("{d}-bit")); |
| 491 | } |
| 492 | layout.extend(coded.and_then(|c| c.chroma).map(|c| c.to_string())); |
| 493 | let mut parts = Vec::new(); |
| 494 | if !layout.is_empty() { |
| 495 | parts.push(layout.join(" ")); |
| 496 | } |
| 497 | if let Some(c) = coded { |
| 498 | parts.push(colour_text(c.colour, matrix_assumed)); |
| 499 | } |
| 500 | (!parts.is_empty()).then(|| parts.join(" · ")) |
| 501 | } |
| 502 | |
| 503 | /// The refusal for a `.edith` project given where media goes: it is the editor's own file, not |
| 504 | /// a container, so the probe and the import both say how to open it instead of calling it |
| 505 | /// truncated. The probe says it as a plain line, not a refusal. |
| 506 | const EDITH_PROJECT: &str = "an edith project (open it with project_open)"; |
| 507 | |
| 508 | fn is_edith_project(path: &Path) -> bool { |
| 509 | path.extension().is_some_and(|e| e.eq_ignore_ascii_case("edith")) |
| 510 | } |
| 511 | |
| 512 | /// A subtitle file (`.srt`, `.vtt`, `.ass`, `.ssa`): text, not media, and imported with subtitles_import. |
| 513 | fn is_subtitle_file(path: &Path) -> bool { |
| 514 | path.extension().is_some_and(|e| ["srt", "vtt", "ass", "ssa"].iter().any(|x| e.eq_ignore_ascii_case(x))) |
| 515 | } |
| 516 | |
| 517 | /// The sentence a subtitle file gets from the probe and the import: not a refusal, and not truncated media. |
| 518 | fn subtitle_file_text(path: &Path) -> String { |
| 519 | format!("{} is a subtitle file: import it with subtitles_import", file_name(path)) |
| 520 | } |
| 521 | |
| 522 | /// The plain words for a file the engine cannot read as media. An empty file says so. A file whose |
| 523 | /// boxes do not add up (a truncated copy, or a text file given an .mp4 name) may be truncated or not |
| 524 | /// an MP4 at all: the engine's detail is kept, and the next step is named. `None` for any other |
| 525 | /// refusal, which keeps its own words. |
| 526 | fn plain_refusal(path: &Path, engine_msg: &str) -> Option<String> { |
| 527 | if is_subtitle_file(path) { |
| 528 | return Some(subtitle_file_text(path)); |
| 529 | } |
| 530 | let name = file_name(path); |
| 531 | if std::fs::metadata(path).is_ok_and(|m| m.len() == 0) { |
| 532 | return Some(format!("{name} is empty (0 bytes)")); |
| 533 | } |
| 534 | if engine_msg.contains("larger size") || engine_msg.contains("ftyp not found") { |
| 535 | return Some(format!( |
| 536 | "{name} looks truncated or is not a valid MP4 ({engine_msg}); re-copy or re-export the file from its source" |
| 537 | )); |
| 538 | } |
| 539 | None |
| 540 | } |
| 541 | |
| 542 | /// Whether two paths name the same file: by their canonical form where both resolve, else as written. |
| 543 | fn same_file(a: &Path, b: &Path) -> bool { |
| 544 | match (std::fs::canonicalize(a), std::fs::canonicalize(b)) { |
| 545 | (Ok(a), Ok(b)) => a == b, |
| 546 | _ => a == b, |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | /// One stream of a file that is not its picture, as media_probe lists it. |
| 551 | #[derive(Debug, Clone, PartialEq)] |
| 552 | struct Stream { |
| 553 | /// `audio` or `subtitle`. |
| 554 | kind: &'static str, |
| 555 | /// Position among all the file's streams, video included, as ffprobe numbers them (0-based). |
| 556 | index: usize, |
| 557 | /// The container's track number (Matroska `TrackNumber`, mp4 track id); `None` when the |
| 558 | /// engine's reader does not give one. |
| 559 | track: Option<u64>, |
| 560 | /// The codec in plain words (`aac`, `opus`, `srt`, `mov_text`); `None` when the file says none. |
| 561 | codec: Option<String>, |
| 562 | /// The codec as the file spells it (a Matroska CodecID or an mp4 sample-entry fourcc). |
| 563 | codec_id: Option<String>, |
| 564 | /// Audio AAC: the profile the engine reads, spelled as ffprobe does (`LC`, `HE-AAC`, `HE-AACv2`); |
| 565 | /// `None` for other codecs and where the engine states none. |
| 566 | profile: Option<String>, |
| 567 | /// Audio lossless (FLAC, ALAC, PCM): the sample depth the header states, in bits; `None` otherwise. |
| 568 | bit_depth: Option<u32>, |
| 569 | /// ISO 639-2, `und` when the file states none. |
| 570 | language: String, |
| 571 | /// Audio: the channel count the header states; `None` where it states none, and for subtitles. |
| 572 | channels: Option<u16>, |
| 573 | /// Audio: the sample rate in Hz the header states; `None` where it states none. |
| 574 | sample_rate: Option<u32>, |
| 575 | /// The track's title (`Signs`), empty when it has none. |
| 576 | name: String, |
| 577 | } |
| 578 | |
| 579 | /// The codec in plain words, from a Matroska CodecID or an mp4 sample-entry fourcc. A spelling |
| 580 | /// not listed here is returned as the file gives it. |
| 581 | fn plain_codec(raw: &str) -> String { |
| 582 | let name = match raw { |
| 583 | "A_OPUS" | "Opus" => "opus", |
| 584 | "A_VORBIS" => "vorbis", |
| 585 | "A_FLAC" | "fLaC" => "flac", |
| 586 | "mp4a" => "aac", |
| 587 | "A_ALAC" | "alac" => "alac", |
| 588 | "A_AC3" | "ac-3" => "ac3", |
| 589 | "A_EAC3" | "ec-3" => "eac3", |
| 590 | "A_DTS" | "dtsc" | "dtsh" | "dtse" => "dts", |
| 591 | "A_TRUEHD" | "mlpa" => "truehd", |
| 592 | "A_MPEG/L3" | ".mp3" => "mp3", |
| 593 | "A_MPEG/L2" => "mp2", |
| 594 | "lpcm" | "sowt" | "twos" | "in24" | "in32" | "fl32" | "fl64" => "pcm", |
| 595 | "V_VP8" | "vp08" => "vp8", |
| 596 | "V_VP9" | "vp09" => "vp9", |
| 597 | "V_AV1" | "av01" => "av1", |
| 598 | "V_MPEG4/ISO/AVC" | "avc1" | "avc3" => "h264", |
| 599 | "V_MPEGH/ISO/HEVC" | "hvc1" | "hev1" => "hevc", |
| 600 | "apco" | "apcs" | "apcn" | "apch" | "ap4h" | "ap4x" => "prores", |
| 601 | "AVdn" => "dnxhd", |
| 602 | "AVdh" => "dnxhr", |
| 603 | "V_MJPEG" | "jpeg" | "mjpa" => "mjpeg", |
| 604 | "dvc " | "dvcp" | "dvpp" | "dvcs" | "dvis" | "dv5n" | "dv5p" | "dv5q" | "dvhq" | "dvh1" | "dvh2" |
| 605 | | "dvh3" | "dvh4" | "dvh5" | "dvh6" | "dvhp" | "dvhs" | "dvhn" | "dvhr" => "dv", |
| 606 | "V_MPEG4/ISO/SP" | "V_MPEG4/ISO/ASP" | "V_MPEG4/ISO/AP" | "mp4v" => "mpeg4", |
| 607 | "s263" | "h263" => "h263", |
| 608 | "S_TEXT/UTF8" => "srt", |
| 609 | "S_TEXT/ASS" | "S_ASS" => "ass", |
| 610 | "S_TEXT/SSA" | "S_SSA" => "ssa", |
| 611 | "S_TEXT/WEBVTT" | "wvtt" => "webvtt", |
| 612 | "tx3g" => "mov_text", |
| 613 | "stpp" => "ttml", |
| 614 | "S_VOBSUB" => "vobsub", |
| 615 | "S_HDMV/PGS" | "hdmv_pgs_subtitle" => "pgs", |
| 616 | other if other.starts_with("A_AAC") => "aac", |
| 617 | other if other.starts_with("A_PCM") => "pcm", |
| 618 | other => return other.to_string(), |
| 619 | }; |
| 620 | name.to_string() |
| 621 | } |
| 622 | |
| 623 | /// A stream's language as a person reads it: the tag the header states, else the `fallback`, and |
| 624 | /// `und` when neither says anything. A blank tag is no language, and neither is a tag of |
| 625 | /// unprintable bytes: test_qt.mov's mdhd packs its unset language as 0x7fff, which the engine |
| 626 | /// hands on as three DEL bytes. Both read `und` like a missing one. |
| 627 | fn language_of(stated: Option<&str>, fallback: &str) -> String { |
| 628 | [stated, Some(fallback)] |
| 629 | .into_iter() |
| 630 | .flatten() |
| 631 | .map(str::trim) |
| 632 | .find(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_graphic())) |
| 633 | .unwrap_or("und") |
| 634 | .to_string() |
| 635 | } |
| 636 | |
| 637 | /// The audio and subtitle streams of a file, in ffprobe's index order. The engine's stream list |
| 638 | /// is in file order for mp4 (its position is the index), and it names each stream's codec by |
| 639 | /// fourcc; the subtitle walk gives the mp4 track number, language and title, in the same order. |
| 640 | /// Matroska keeps its own walks, which name the language and title; its track numbers are |
| 641 | /// taken as the index (`TrackNumber` minus one, the usual order). |
| 642 | fn other_streams(path: &Path, facts: &MediaFacts) -> Vec<Stream> { |
| 643 | // The engine's stream list is the source of every stream's codec and language, and of the audio |
| 644 | // numbering: an audio stream's index is the audio track `audio_track` takes (0-based). A subtitle |
| 645 | // track's number, title and, where the engine states none (Matroska subtitles), its language come |
| 646 | // from the container walk, which numbers them. |
| 647 | let mkv = engine::demux::is_matroska(path); |
| 648 | let walk: Vec<(u64, String, String)> = if mkv { |
| 649 | engine::demux::matroska_subtitles(path) |
| 650 | .unwrap_or_default() |
| 651 | .into_iter() |
| 652 | .map(|t| (t.number, t.language, t.name)) |
| 653 | .collect() |
| 654 | } else if engine::demux::is_mpeg_system(path) { |
| 655 | // A transport stream numbers its PGS tracks by the engine's stream list alone. |
| 656 | Vec::new() |
| 657 | } else { |
| 658 | engine::demux::mp4_subtitles(path) |
| 659 | .unwrap_or_default() |
| 660 | .into_iter() |
| 661 | .map(|t| (t.number, t.language, t.name)) |
| 662 | .collect() |
| 663 | }; |
| 664 | let mut subs = walk.into_iter(); |
| 665 | let mut out = Vec::new(); |
| 666 | for (index, st) in facts.streams.iter().enumerate() { |
| 667 | match st.kind { |
| 668 | engine::demux::StreamKind::Video => continue, |
| 669 | engine::demux::StreamKind::Audio => out.push(Stream { |
| 670 | kind: "audio", |
| 671 | index: st.index, |
| 672 | track: None, |
| 673 | codec: st.codec_id.as_deref().map(plain_codec), |
| 674 | codec_id: st.codec_id.clone(), |
| 675 | profile: st.profile.clone(), |
| 676 | bit_depth: st.bit_depth, |
| 677 | language: language_of(st.language.as_deref(), ""), |
| 678 | channels: st.channels, |
| 679 | sample_rate: st.sample_rate, |
| 680 | name: String::new(), |
| 681 | }), |
| 682 | engine::demux::StreamKind::Subtitle => { |
| 683 | let (track, walk_language, name) = match subs.next() { |
| 684 | Some((number, language, name)) => (Some(number), language, name), |
| 685 | None => (None, "und".to_string(), String::new()), |
| 686 | }; |
| 687 | let index = match (mkv, track) { |
| 688 | (true, Some(number)) => (number as usize).saturating_sub(1), |
| 689 | _ => index, |
| 690 | }; |
| 691 | out.push(Stream { |
| 692 | kind: "subtitle", |
| 693 | index, |
| 694 | track, |
| 695 | codec: st.codec_id.as_deref().map(plain_codec), |
| 696 | codec_id: st.codec_id.clone(), |
| 697 | profile: None, |
| 698 | bit_depth: None, |
| 699 | language: language_of(st.language.as_deref(), &walk_language), |
| 700 | channels: None, |
| 701 | sample_rate: None, |
| 702 | name, |
| 703 | }); |
| 704 | } |
| 705 | } |
| 706 | } |
| 707 | // Sound the engine could not list by kind (a file with no header streams) is still named. |
| 708 | if !out.iter().any(|s| s.kind == "audio") && engine::AudioSession::duration_secs(path).ok().flatten().is_some() { |
| 709 | out.insert(0, Stream { kind: "audio", index: 0, track: None, codec: None, codec_id: None, profile: None, bit_depth: None, language: "und".into(), channels: None, sample_rate: None, name: String::new() }); |
| 710 | } |
| 711 | // Closed captions ride inside the picture: listed (from the first seconds of it) beside the |
| 712 | // container's own subtitle tracks, and imported with them by subtitles_import. |
| 713 | if facts.streams.iter().any(|s| s.kind == engine::demux::StreamKind::Video) { |
| 714 | let base = facts.streams.len(); |
| 715 | for (k, c) in engine::demux::captions::present(path).iter().enumerate() { |
| 716 | let cc708 = c.number == engine::demux::captions::TRACK_BASE + 5; |
| 717 | out.push(Stream { |
| 718 | kind: "subtitle", |
| 719 | index: base + k, |
| 720 | track: Some(c.number), |
| 721 | codec: Some(if cc708 { "eia_708" } else { "eia_608" }.to_string()), |
| 722 | codec_id: Some(if cc708 { "cea708" } else { "cea608" }.to_string()), |
| 723 | profile: None, |
| 724 | bit_depth: None, |
| 725 | language: "und".into(), |
| 726 | channels: None, |
| 727 | sample_rate: None, |
| 728 | name: c.name.clone(), |
| 729 | }); |
| 730 | } |
| 731 | } |
| 732 | out |
| 733 | } |
| 734 | |
| 735 | /// A channel count in plain words: `mono`, `stereo`, `5.1`, `7.1`, and `N ch` for any other. |
| 736 | fn channels_text(n: u16) -> String { |
| 737 | match n { |
| 738 | 1 => "mono".to_string(), |
| 739 | 2 => "stereo".to_string(), |
| 740 | 6 => "5.1".to_string(), |
| 741 | 8 => "7.1".to_string(), |
| 742 | n => format!("{n} ch"), |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | /// A sample rate as `48 kHz` or `44.1 kHz`. |
| 747 | fn rate_text(hz: u32) -> String { |
| 748 | format!("{} kHz", fmt_fps(f64::from(hz) / 1000.0)) |
| 749 | } |
| 750 | |
| 751 | /// The picture codec with its profile: `ProRes 422 HQ`, `HEVC Main 10`. Avid's profile names |
| 752 | /// already begin with the family (`DNxHD 145`, `DNxHR HQX`), so they stand alone. |
| 753 | fn codec_phrase(codec: engine::demux::Codec, profile: Option<&str>) -> String { |
| 754 | match profile { |
| 755 | Some(p) if codec == engine::demux::Codec::Dnxhd && p.starts_with("DNx") => p.to_string(), |
| 756 | // H.263 is MPEG-4 Part 2's baseline decoder; its profile is its name. |
| 757 | Some("H.263") if codec == engine::demux::Codec::Mpeg4 => "H.263".to_string(), |
| 758 | _ => format!("{}{}", codec.name(), profile_text(profile)), |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | /// A profile after its codec name, with the leading space; empty where the stream states none. |
| 763 | fn profile_text(profile: Option<&str>) -> String { |
| 764 | profile.map(|p| format!(" {p}")).unwrap_or_default() |
| 765 | } |
| 766 | |
| 767 | /// A stream as one short phrase: `audio track 1 opus (fra) 5.1, 48 kHz "Commentary"`, or `subtitle #3 srt (eng)`. |
| 768 | /// An audio track's number is the one `audio_track` takes (0-based); a subtitle's is the index ffprobe gives it. |
| 769 | /// The channel layout and rate follow the language where the header states them. A lossless track's |
| 770 | /// depth follows the codec: `audio track 0 flac 24-bit (und) stereo, 48 kHz`. |
| 771 | fn stream_text(st: &Stream) -> String { |
| 772 | let codec = st.codec.as_deref().unwrap_or("codec unknown"); |
| 773 | let profile = profile_text(st.profile.as_deref()); |
| 774 | let depth = st.bit_depth.map(|d| format!(" {d}-bit")).unwrap_or_default(); |
| 775 | let name = if st.name.is_empty() { String::new() } else { format!(" \"{}\"", st.name) }; |
| 776 | let number = match st.kind { |
| 777 | "audio" => format!("track {}", st.index), |
| 778 | _ => format!("#{}", st.index), |
| 779 | }; |
| 780 | let spec: Vec<String> = [st.channels.map(channels_text), st.sample_rate.map(rate_text)].into_iter().flatten().collect(); |
| 781 | let spec = if spec.is_empty() { String::new() } else { format!(" {}", spec.join(", ")) }; |
| 782 | format!("{} {number} {codec}{profile}{depth} ({}){spec}{name}", st.kind, st.language) |
| 783 | } |
| 784 | |
| 785 | /// The note for each audio track of more than two channels: the export mixes all sound to stereo, |
| 786 | /// so the surround layout does not reach the file. Said where the layout is shown. |
| 787 | fn surround_notes(streams: &[Stream]) -> Vec<String> { |
| 788 | streams |
| 789 | .iter() |
| 790 | .filter(|s| s.kind == "audio") |
| 791 | .filter_map(|s| { |
| 792 | s.channels |
| 793 | .filter(|c| *c > 2) |
| 794 | .map(|c| format!("note: audio track {} is {}; mixed to stereo on export", s.index, channels_text(c))) |
| 795 | }) |
| 796 | .collect() |
| 797 | } |
| 798 | |
| 799 | /// Why a file with no picture and no playing time is refused. The words are |
| 800 | /// the ones `media_import` gives for the same file (`PlaybackSession::import` |
| 801 | /// reads the same demuxer, then the audio header), so a probe and an import |
| 802 | /// never disagree about a broken file. |
| 803 | fn unrecognised_reason(path: &Path) -> String { |
| 804 | match engine::AudioSession::duration_secs(path) { |
| 805 | Err(e) => e.to_string(), |
| 806 | Ok(_) => "not a recognised media file (no picture track and no playing time)".to_string(), |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | /// Warnings about a file's sound that the picture does not show: a sound codec nothing here |
| 811 | /// decodes plays silent, and the person is told so at probe and import. |
| 812 | fn audio_warnings(path: &Path) -> Vec<String> { |
| 813 | // The engine's own rule: a codec is named only for a file whose sound came up silent. A |
| 814 | // file that opens with sound is never warned, whatever its header says. |
| 815 | if matches!(engine::AudioSession::open(path), Ok(Some(_))) { |
| 816 | return Vec::new(); |
| 817 | } |
| 818 | match engine::AudioSession::unsupported(path) { |
| 819 | Ok(Some(why)) => vec![match codec_named_in(&why) { |
| 820 | Some(codec) => format!("warning: audio: {codec} is not supported; this file's sound will be silent"), |
| 821 | None => format!("warning: audio: {why}; this file's sound will be silent"), |
| 822 | }], |
| 823 | _ => Vec::new(), |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | /// The codec a refusal names, in the words a person knows it by. The engine's reason names it |
| 828 | /// as `the WavPack track of …` (already friendly, see `codec_display_name`), and a reason that |
| 829 | /// still carries a Matroska id names it as `A_DTS` (says `DTS`). `None` when the reason names |
| 830 | /// no codec at all. |
| 831 | fn codec_named_in(why: &str) -> Option<String> { |
| 832 | let friendly = why |
| 833 | .find(" track of") |
| 834 | .and_then(|end| why[..end].rsplit_once("the ").map(|(_, name)| name.trim())) |
| 835 | .filter(|name| !name.is_empty() && !name.starts_with("A_") && !name.contains(' ')); |
| 836 | if let Some(name) = friendly { |
| 837 | return Some(name.to_string()); |
| 838 | } |
| 839 | why.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '/' || c == '-' || c == '.')) |
| 840 | .find_map(|t| t.strip_prefix("A_")) |
| 841 | .map(|t| t.split('/').next().unwrap_or(t).to_ascii_uppercase()) |
| 842 | .filter(|t| !t.is_empty()) |
| 843 | } |
| 844 | |
| 845 | fn probe_one(path: &Path) -> Row { |
| 846 | let fail = |msg: String| Row { |
| 847 | path: path.to_path_buf(), |
| 848 | facts: None, |
| 849 | bitrate_bps: None, |
| 850 | streams: Vec::new(), |
| 851 | error: Some(msg), |
| 852 | warnings: Vec::new(), |
| 853 | coded: None, |
| 854 | still: None, |
| 855 | }; |
| 856 | if !path.exists() { |
| 857 | return fail(not_found(path)); |
| 858 | } |
| 859 | if let Some(why) = not_a_file(path) { |
| 860 | return fail(why); |
| 861 | } |
| 862 | if is_edith_project(path) { |
| 863 | return fail(EDITH_PROJECT.to_string()); |
| 864 | } |
| 865 | let facts = probe_media(path); |
| 866 | let streams = other_streams(path, &facts); |
| 867 | let mut warnings = audio_warnings(path); |
| 868 | warnings.extend(surround_notes(&streams)); |
| 869 | // The engine's word for a picture it refuses (`picture_refusal`). The container comes from the |
| 870 | // extension, so a file that only looks like media shows up as having no picture and no playing |
| 871 | // time; stills are the exception. A refused picture keeps its streams: the reason and the |
| 872 | // streams are shown together. |
| 873 | let refusal = engine::demux::picture_refusal(path).or_else(|| picture_refusal_at_import(path, &facts)); |
| 874 | if refusal.is_some() || (facts.video.is_none() && facts.duration_secs.is_none() && !engine::is_image(path)) { |
| 875 | return Row { |
| 876 | path: path.to_path_buf(), |
| 877 | facts: Some(facts), |
| 878 | bitrate_bps: None, |
| 879 | streams, |
| 880 | error: Some(refusal.unwrap_or_else(|| unrecognised_reason(path))), |
| 881 | warnings, |
| 882 | coded: None, |
| 883 | still: None, |
| 884 | }; |
| 885 | } |
| 886 | let bitrate_bps = probe_bitrate(path).total; |
| 887 | let coded = facts.video.as_ref().and_then(|_| coded_of(path)); |
| 888 | // A still's size comes from its header (`decode::image_size`, the turn applied), not a decode. |
| 889 | let still = engine::is_image(path).then(|| engine::decode::image_size(path).ok()).flatten(); |
| 890 | Row { |
| 891 | path: path.to_path_buf(), |
| 892 | facts: Some(facts), |
| 893 | bitrate_bps, |
| 894 | streams, |
| 895 | error: None, |
| 896 | warnings, |
| 897 | coded, |
| 898 | still, |
| 899 | } |
| 900 | } |
| 901 | |
| 902 | /// The refusal import gives a picture that opens but that the decoder will not take (an HEVC |
| 903 | /// range-extensions stream, say), in the engine's own words: `decode::probe` runs the very check |
| 904 | /// import runs. Asked only of the codecs whose check it makes (HEVC, VP9, VP8), since for H.264 |
| 905 | /// and AV1 it would start a decoder for every file probed. |
| 906 | fn picture_refusal_at_import(path: &Path, facts: &MediaFacts) -> Option<String> { |
| 907 | let codec = facts.video.as_ref()?.codec; |
| 908 | if !matches!(codec, engine::demux::Codec::Hevc | engine::demux::Codec::Vp9 | engine::demux::Codec::Vp8) { |
| 909 | return None; |
| 910 | } |
| 911 | engine::decode::probe(path).err().map(|e| e.to_string()) |
| 912 | } |
| 913 | |
| 914 | /// A file with subtitle tracks and no picture or sound: not a refusal, since its tracks import as captions. |
| 915 | fn subtitles_only(row: &Row) -> bool { |
| 916 | row.facts.as_ref().is_some_and(|f| f.video.is_none()) |
| 917 | && row.streams.iter().any(|st| st.kind == "subtitle") |
| 918 | && !row.streams.iter().any(|st| st.kind == "audio") |
| 919 | } |
| 920 | |
| 921 | fn row_line(row: &Row) -> String { |
| 922 | let name = file_name(&row.path); |
| 923 | let mut warn = String::new(); |
| 924 | for w in &row.warnings { |
| 925 | warn.push_str(&format!("\n {w}")); |
| 926 | } |
| 927 | if let Some(e) = &row.error { |
| 928 | if is_edith_project(&row.path) { |
| 929 | return format!("{name} · {EDITH_PROJECT}"); |
| 930 | } |
| 931 | if is_subtitle_file(&row.path) { |
| 932 | return subtitle_file_text(&row.path); |
| 933 | } |
| 934 | // A refused picture: the reason, then the streams the header still names. |
| 935 | let Some(f) = row.facts.as_ref() else { |
| 936 | return format!("{name} · error: {e}{warn}"); |
| 937 | }; |
| 938 | let head = plain_refusal(&row.path, e).unwrap_or_else(|| { |
| 939 | if subtitles_only(row) { |
| 940 | format!("{name} · subtitles only: import with subtitles_import") |
| 941 | } else { |
| 942 | format!("{name} · refused: {e}") |
| 943 | } |
| 944 | }); |
| 945 | let mut list: Vec<String> = f |
| 946 | .streams |
| 947 | .iter() |
| 948 | .filter(|st| st.kind == engine::demux::StreamKind::Video) |
| 949 | .map(|st| format!("video #{} {}", st.index, st.codec_id.as_deref().unwrap_or("codec unknown"))) |
| 950 | .collect(); |
| 951 | list.extend(row.streams.iter().map(stream_text)); |
| 952 | if list.is_empty() { |
| 953 | return format!("{head}{warn}"); |
| 954 | } |
| 955 | return format!("{head}\n streams: {}{warn}", list.join(" · ")); |
| 956 | } |
| 957 | let Some(f) = &row.facts else { |
| 958 | return format!("{name} · error: no facts"); |
| 959 | }; |
| 960 | let container = f.container.as_deref().unwrap_or("unknown container"); |
| 961 | let picture = match &f.video { |
| 962 | Some(v) => { |
| 963 | let rate = v.frame_rate.map_or("@?".to_string(), |r| format!("@{}", fmt_fps(r))); |
| 964 | // The size the picture is stored at, and the shown size when the pixels are not square. |
| 965 | let size = row |
| 966 | .coded |
| 967 | .as_ref() |
| 968 | .and_then(|c| c.text((v.width, v.height))) |
| 969 | .unwrap_or_else(|| format!("{}x{}", v.width, v.height)); |
| 970 | // A turned picture shows its displayed size; the stored one is said beside it. |
| 971 | let size = match row.coded.as_ref().and_then(Coded::turn_text) { |
| 972 | Some(turn) => format!("{size} {turn}"), |
| 973 | None => size, |
| 974 | }; |
| 975 | let text = format!("{} {size} {rate}", codec_phrase(v.codec, v.profile)); |
| 976 | // Cover art beside a picture track is said, since it is not one of the video streams. |
| 977 | if f.attached_pic { |
| 978 | format!("{text} · cover art attached") |
| 979 | } else { |
| 980 | text |
| 981 | } |
| 982 | } |
| 983 | None if engine::is_image(&row.path) => match row.still { |
| 984 | Some((w, h)) => format!("still image {w}x{h}"), |
| 985 | None => "still image".to_string(), |
| 986 | }, |
| 987 | // A song with a cover: its picture is not a track to play or export. |
| 988 | None if f.attached_pic => "cover art only (not a picture track)".to_string(), |
| 989 | None => "no picture".to_string(), |
| 990 | }; |
| 991 | let duration = duration_text(&row.path, f); |
| 992 | let size = f |
| 993 | .bytes |
| 994 | .map_or("size unknown".to_string(), |b| format!("{:.1} MB", b as f64 / 1e6)); |
| 995 | let rate = row.bitrate_bps.map_or("bitrate unknown".to_string(), bitrate_text); |
| 996 | let mut line = format!("{name} · {container} · {picture} · {duration} · {size} · {rate}"); |
| 997 | if let Some(info) = picture_info(f.video.and_then(|v| v.bit_depth), f.video.is_some_and(|v| v.matrix_assumed), row.coded.as_ref()) { |
| 998 | line.push_str(&format!("\n picture: {info}")); |
| 999 | } |
| 1000 | if !row.streams.is_empty() { |
| 1001 | let list: Vec<String> = row.streams.iter().map(stream_text).collect(); |
| 1002 | line.push_str(&format!("\n streams: {}", list.join(" · "))); |
| 1003 | } |
| 1004 | line.push_str(&warn); |
| 1005 | line |
| 1006 | } |
| 1007 | |
| 1008 | fn row_json(row: &Row) -> Value { |
| 1009 | let path = row.path.display().to_string(); |
| 1010 | // An edith project is not a failed probe: its line is plain, and it has no error. |
| 1011 | if let Some(e) = row.error.as_ref().filter(|_| !is_edith_project(&row.path)) { |
| 1012 | return json!({ |
| 1013 | "path": path, |
| 1014 | "name": file_name(&row.path), |
| 1015 | "error": plain_refusal(&row.path, e).unwrap_or_else(|| e.clone()), |
| 1016 | "streams": row.streams.iter().map(stream_json).collect::<Vec<_>>(), |
| 1017 | "warnings": row.warnings, |
| 1018 | }); |
| 1019 | } |
| 1020 | let f = row.facts.as_ref(); |
| 1021 | let video = f.and_then(|f| f.video); |
| 1022 | json!({ |
| 1023 | "still_width": row.still.map(|s| s.0), |
| 1024 | "still_height": row.still.map(|s| s.1), |
| 1025 | "colour": row.coded.map(|c| colour_text(c.colour, video.is_some_and(|v| v.matrix_assumed))), |
| 1026 | "matrix_assumed": video.map(|v| v.matrix_assumed), |
| 1027 | "chroma": row.coded.and_then(|c| c.chroma).map(|c| c.to_string()), |
| 1028 | "path": path, |
| 1029 | "name": file_name(&row.path), |
| 1030 | "container": f.and_then(|f| f.container.clone()), |
| 1031 | "codec": video.map(|v| v.codec.name()), |
| 1032 | "width": video.map(|v| v.width), |
| 1033 | "height": video.map(|v| v.height), |
| 1034 | "coded_width": row.coded.map(|c| c.w), |
| 1035 | "coded_height": row.coded.map(|c| c.h), |
| 1036 | "frame_rate": video.and_then(|v| v.frame_rate), |
| 1037 | "bit_depth": video.and_then(|v| v.bit_depth), |
| 1038 | "profile": video.and_then(|v| v.profile), |
| 1039 | "interlaced": video.and_then(|v| v.interlaced), |
| 1040 | "duration_secs": f.and_then(|f| f.duration_secs), |
| 1041 | "audio_duration_secs": f.and_then(|f| audio_only_secs(&row.path, f)), |
| 1042 | "bytes": f.and_then(|f| f.bytes), |
| 1043 | "bitrate_bps": row.bitrate_bps, |
| 1044 | "streams": row.streams.iter().map(stream_json).collect::<Vec<_>>(), |
| 1045 | "warnings": row.warnings, |
| 1046 | "error": null, |
| 1047 | }) |
| 1048 | } |
| 1049 | |
| 1050 | fn stream_json(st: &Stream) -> Value { |
| 1051 | json!({ |
| 1052 | "kind": st.kind, |
| 1053 | "index": st.index, |
| 1054 | "track": st.track, |
| 1055 | "codec": st.codec, |
| 1056 | "codec_id": st.codec_id, |
| 1057 | "profile": st.profile, |
| 1058 | "bit_depth": st.bit_depth, |
| 1059 | "language": st.language, |
| 1060 | "channels": st.channels, |
| 1061 | "sample_rate": st.sample_rate, |
| 1062 | "name": st.name, |
| 1063 | }) |
| 1064 | } |
| 1065 | |
| 1066 | fn probe(_server: &mut Server, args: &Value) -> Reply { |
| 1067 | let mut files = tri!(gather(args, true)); |
| 1068 | let total = files.len(); |
| 1069 | let clipped = total > CAP; |
| 1070 | files.truncate(CAP); |
| 1071 | if files.is_empty() { |
| 1072 | return Reply::err("no files matched"); |
| 1073 | } |
| 1074 | |
| 1075 | let rows: Vec<Row> = files.iter().map(|p| probe_one(p)).collect(); |
| 1076 | let failed = rows.iter().filter(|r| r.error.is_some() && !subtitles_only(r) && !is_edith_project(&r.path)).count(); |
| 1077 | let mut text: Vec<String> = rows.iter().map(row_line).collect(); |
| 1078 | if clipped { |
| 1079 | text.push(format!( |
| 1080 | "showing the first {CAP} of {total} files; narrow the glob to see the rest" |
| 1081 | )); |
| 1082 | } |
| 1083 | let structured = json!({ |
| 1084 | "files": rows.iter().map(row_json).collect::<Vec<_>>(), |
| 1085 | "total_matched": total, |
| 1086 | "shown": rows.len(), |
| 1087 | "failed": failed, |
| 1088 | }); |
| 1089 | let reply = if failed == rows.len() { |
| 1090 | Reply::err(text.join("\n")) |
| 1091 | } else { |
| 1092 | Reply::ok(text.join("\n")) |
| 1093 | }; |
| 1094 | reply.with(structured) |
| 1095 | } |
| 1096 | |
| 1097 | // ---- media_import ---------------------------------------------------------- |
| 1098 | |
| 1099 | /// Plain successes an import reply shows before it counts the rest: a call with thousands |
| 1100 | /// of paths must not send thousands of lines back. Refusals and warnings are never counted. |
| 1101 | const IMPORT_SHOWN: usize = 20; |
| 1102 | |
| 1103 | /// One line of an import reply: a plain success (the only kind that may be folded into a |
| 1104 | /// count) or a refusal, a not-found, or a warning (always shown in full). |
| 1105 | enum ImportLine { |
| 1106 | Imported(String), |
| 1107 | Note(String), |
| 1108 | } |
| 1109 | |
| 1110 | /// The reply lines: every note in full and in order, the first `keep` successes in order, |
| 1111 | /// and one summary line counting the successes left out. |
| 1112 | fn cap_successes(lines: Vec<ImportLine>, keep: usize) -> Vec<String> { |
| 1113 | let mut out = Vec::new(); |
| 1114 | let mut shown = 0usize; |
| 1115 | let mut hidden = 0usize; |
| 1116 | for line in lines { |
| 1117 | match line { |
| 1118 | ImportLine::Imported(s) if shown < keep => { |
| 1119 | shown += 1; |
| 1120 | out.push(s); |
| 1121 | } |
| 1122 | ImportLine::Imported(_) => hidden += 1, |
| 1123 | ImportLine::Note(s) => out.push(s), |
| 1124 | } |
| 1125 | } |
| 1126 | if hidden > 0 { |
| 1127 | out.push(format!("…and {hidden} more imported")); |
| 1128 | } |
| 1129 | out |
| 1130 | } |
| 1131 | |
| 1132 | fn import(server: &mut Server, args: &Value) -> Reply { |
| 1133 | let (files, repeats) = tri!(gather_listed(args, false)); |
| 1134 | let start = tri!(server.session_ref()).history_pushes(); |
| 1135 | let mut lines: Vec<ImportLine> = Vec::new(); |
| 1136 | let mut imported: Vec<Value> = Vec::new(); |
| 1137 | let mut failed = 0usize; |
| 1138 | // The sources this call added: with auto_proxies on, each starts its stand-in below. |
| 1139 | let mut added: Vec<usize> = Vec::new(); |
| 1140 | { |
| 1141 | let s = tri!(server.session()); |
| 1142 | for path in &files { |
| 1143 | let name = file_name(path); |
| 1144 | if !path.exists() { |
| 1145 | failed += 1; |
| 1146 | lines.push(ImportLine::Note(not_found(path))); |
| 1147 | continue; |
| 1148 | } |
| 1149 | if let Some(why) = not_a_file(path) { |
| 1150 | failed += 1; |
| 1151 | lines.push(ImportLine::Note(why)); |
| 1152 | continue; |
| 1153 | } |
| 1154 | // A file already on the timeline as a whole-file source is not added twice. |
| 1155 | if let Some(n) = s.sources().iter().position(|src| src.audio_stream == 0 && same_file(&src.path, path)) { |
| 1156 | failed += 1; |
| 1157 | lines.push(ImportLine::Note(format!("{name} is already imported as src:{n}; nothing was added"))); |
| 1158 | continue; |
| 1159 | } |
| 1160 | if is_edith_project(path) { |
| 1161 | failed += 1; |
| 1162 | lines.push(ImportLine::Note(format!("{name} is an edith project, not media: open it with project_open"))); |
| 1163 | continue; |
| 1164 | } |
| 1165 | match s.import(path) { |
| 1166 | Ok(n) => { |
| 1167 | // A numbered run is one source named for the whole run: said as a sequence, with its frames. |
| 1168 | let run = engine::sequence::Run::parse(&s.sources()[n].path); |
| 1169 | let (shown, dur) = match &run { |
| 1170 | Some(r) => (file_name(&r.spelled()), format!("image sequence, {} frames", r.count)), |
| 1171 | None => (name.clone(), duration_text(path, &probe_media(path))), |
| 1172 | }; |
| 1173 | added.push(n); |
| 1174 | lines.push(ImportLine::Imported(format!("src:{n} {shown} ({dur})"))); |
| 1175 | lines.extend(audio_warnings(path).into_iter().map(|w| ImportLine::Note(format!(" {name}: {w}")))); |
| 1176 | imported.push(json!({ |
| 1177 | "src": n, "name": shown, "path": path.display().to_string(), "duration": dur, |
| 1178 | "sequence": run.as_ref().map(|r| r.count), |
| 1179 | })); |
| 1180 | } |
| 1181 | Err(e) => { |
| 1182 | failed += 1; |
| 1183 | // A subtitles-only file has no audio track for the engine to open: say where it goes. |
| 1184 | let msg = if subtitles_only(&probe_one(path)) { |
| 1185 | format!("{name} · subtitles only: import with subtitles_import") |
| 1186 | } else { |
| 1187 | plain_refusal(path, &e.to_string()).unwrap_or_else(|| format!("{name}: refused: {e}")) |
| 1188 | }; |
| 1189 | lines.push(ImportLine::Note(msg)); |
| 1190 | } |
| 1191 | } |
| 1192 | } |
| 1193 | } |
| 1194 | // A file named twice in one call is imported once; the repeat is said, not taken for a second import. |
| 1195 | for path in &repeats { |
| 1196 | lines.push(ImportLine::Note(format!( |
| 1197 | "{} is listed twice: the second entry is a duplicate and nothing was added", |
| 1198 | file_name(path) |
| 1199 | ))); |
| 1200 | } |
| 1201 | remember_sources(server); |
| 1202 | // The GUI import path: with Auto proxies on, every import starts its stand-in (the engine |
| 1203 | // decides per file whether one is wanted, and a switched-off film gets none). |
| 1204 | let auto = server.session.as_ref().is_some_and(|s| s.auto_proxies()); |
| 1205 | if auto { |
| 1206 | let paths: Vec<PathBuf> = server.session.as_ref().map(|s| added.iter().map(|&n| s.sources()[n].path.clone()).collect()).unwrap_or_default(); |
| 1207 | for p in paths { |
| 1208 | start_run(server, p); |
| 1209 | } |
| 1210 | } |
| 1211 | // Counted by the engine's push count, so an import at the undo cap still lands |
| 1212 | // on the ledger; one ledger entry for the whole call. |
| 1213 | if let Some(s) = server.session.as_ref() { |
| 1214 | let n = s.history_pushes().saturating_sub(start) as usize; |
| 1215 | if n > 0 { |
| 1216 | let label = format!("media_import {} file(s)", imported.len()); |
| 1217 | server.ledger.push(Entry::new(n, label)); |
| 1218 | server.history_lost_on_open = false; |
| 1219 | server.redo_ledger.clear(); |
| 1220 | server.trim_ledger(); |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | let mut lines = cap_successes(lines, IMPORT_SHOWN); |
| 1225 | let reply = if imported.is_empty() { |
| 1226 | // Said outright, so a refused file is not taken for a file that went in. |
| 1227 | lines.push("nothing was imported".to_string()); |
| 1228 | Reply::err(lines.join("\n")) |
| 1229 | } else { |
| 1230 | Reply::ok(lines.join("\n")) |
| 1231 | }; |
| 1232 | reply.with(json!({"imported": imported, "failed": failed})) |
| 1233 | } |
| 1234 | |
| 1235 | // ---- media_remove --------------------------------------------------------- |
| 1236 | |
| 1237 | /// Drops one source nothing plays. The engine refuses a source a clip uses; this |
| 1238 | /// names the clips first, in the terms `project_status` uses, so the refusal says |
| 1239 | /// what to remove or move. A removal is not an undo step and leaves the project |
| 1240 | /// unsaved; it keeps the undo history when it can (the last source), and clears |
| 1241 | /// it, with the ledger, when the sources after it have to renumber. |
| 1242 | /// `media_relink {source, path}`: points an offline source at a file the person |
| 1243 | /// found. The engine checks the kind and the length against the clips on it. |
| 1244 | pub(crate) fn relink(server: &mut Server, args: &Value) -> Reply { |
| 1245 | let raw = match args.get("source") { |
| 1246 | Some(Value::String(s)) => s.trim().to_string(), |
| 1247 | Some(Value::Number(n)) => n.to_string(), |
| 1248 | _ => return Reply::err("argument `source` is required: a source as media_list names it, e.g. src:3"), |
| 1249 | }; |
| 1250 | let digits = raw.strip_prefix("src:").unwrap_or(&raw); |
| 1251 | let Ok(idx) = digits.parse::<usize>() else { |
| 1252 | return Reply::err(format!("`{raw}` is not a source: write src:<n>, e.g. src:3")); |
| 1253 | }; |
| 1254 | let Some(path) = opt_str(args, "path").map(|p| expand_home(p.trim())) else { |
| 1255 | return Reply::err("argument `path` is required: the file the source now is"); |
| 1256 | }; |
| 1257 | // The noted shapes are read before the session is borrowed mutably below. |
| 1258 | let known = server.source_shape.clone(); |
| 1259 | let s = tri!(server.session()); |
| 1260 | let Some(old) = s.sources().get(idx).map(|src| src.path.clone()) else { |
| 1261 | return Reply::err(format!("there is no src:{idx}; media_list shows the sources")); |
| 1262 | }; |
| 1263 | // Read before the relink: what the file it replaces was, against the one it becomes. An |
| 1264 | // offline file cannot be read, so its shape is the one noted when the project last saw it. |
| 1265 | let old_shape = if old.is_file() { Some(shape_of(&probe_media(&old))) } else { known.get(&old).copied() }; |
| 1266 | let new_shape = shape_of(&probe_media(&path)); |
| 1267 | let shift = relink_shift_warnings(s, idx, old_shape, new_shape); |
| 1268 | let before = s.history_pushes(); |
| 1269 | let relinked = s.relink_source(idx, &path); |
| 1270 | let steps = s.history_pushes().saturating_sub(before); |
| 1271 | match relinked { |
| 1272 | Ok(warnings) => { |
| 1273 | // A relink is an unsaved change: the saved source count stops matching, which is |
| 1274 | // what makes the project read as dirty. |
| 1275 | server.saved_sources = None; |
| 1276 | server.source_shape.insert(path.clone(), new_shape); |
| 1277 | // One ledger entry, as an import is: undo puts the old file back and redo points it at |
| 1278 | // the new one. A relink to the file the source already plays pushes nothing. |
| 1279 | if steps > 0 { |
| 1280 | let label = format!("media_relink src:{idx} to {}", file_name(&path)); |
| 1281 | crate::tools::project::note_pushes_as(server, before, &label); |
| 1282 | } |
| 1283 | let mut lines = vec![format!("src:{idx} relinked: {} -> {}", old.display(), path.display())]; |
| 1284 | lines.extend(shift.into_iter().map(|w| format!("warning: {w}"))); |
| 1285 | lines.extend(warnings.into_iter().map(|w| format!("warning: {w}"))); |
| 1286 | if steps > 0 { |
| 1287 | lines.push("undo takes it back".to_string()); |
| 1288 | } |
| 1289 | lines.push("unsaved until project_save".to_string()); |
| 1290 | Reply::ok(lines.join("\n")) |
| 1291 | } |
| 1292 | Err(e) => { |
| 1293 | let why = plain_refusal(&path, &e.to_string()).unwrap_or_else(|| e.to_string()); |
| 1294 | Reply::err(format!("src:{idx} not relinked: {why}")) |
| 1295 | } |
| 1296 | } |
| 1297 | } |
| 1298 | |
| 1299 | /// A source file's frame rate and playing length: the two figures a relink compares. |
| 1300 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 1301 | pub struct Shape { |
| 1302 | pub fps: Option<f64>, |
| 1303 | pub secs: Option<f64>, |
| 1304 | } |
| 1305 | |
| 1306 | fn shape_of(facts: &MediaFacts) -> Shape { |
| 1307 | Shape { |
| 1308 | fps: facts.video.as_ref().and_then(|v| v.frame_rate), |
| 1309 | secs: facts.duration_secs, |
| 1310 | } |
| 1311 | } |
| 1312 | |
| 1313 | /// Notes the shape of every source whose file is on disk and not yet noted. Called wherever the |
| 1314 | /// open project's sources change (import, open, relink), so an offline source still has the shape |
| 1315 | /// its file had when the project last saw it. |
| 1316 | pub(crate) fn remember_sources(server: &mut Server) { |
| 1317 | let Some(s) = server.session.as_ref() else { |
| 1318 | return; |
| 1319 | }; |
| 1320 | let fresh: Vec<PathBuf> = s |
| 1321 | .sources() |
| 1322 | .iter() |
| 1323 | .map(|src| src.path.clone()) |
| 1324 | .filter(|p| p.is_file() && !server.source_shape.contains_key(p)) |
| 1325 | .collect(); |
| 1326 | for p in fresh { |
| 1327 | let shape = shape_of(&probe_media(&p)); |
| 1328 | server.source_shape.insert(p, shape); |
| 1329 | } |
| 1330 | } |
| 1331 | |
| 1332 | /// What relinking source `idx` from a file of `old` shape to one of `new` does to the clips on it. |
| 1333 | /// The engine checks only the frame count, which a 25 fps clip and a 23.976 fps file of the same |
| 1334 | /// length pass, so the rate and the length are compared here and the clips named. `old` is `None` |
| 1335 | /// when the file it replaces was never read: then nothing is compared, and the reply says so. |
| 1336 | fn relink_shift_warnings(s: &engine::PlaybackSession, idx: usize, old: Option<Shape>, new: Shape) -> Vec<String> { |
| 1337 | let Some(old) = old else { |
| 1338 | return vec![format!( |
| 1339 | "the file src:{idx} replaces is offline and its frame rate and length were never read, so the new file was not compared with it" |
| 1340 | )]; |
| 1341 | }; |
| 1342 | let fps = parse::session_fps(s); |
| 1343 | let mut users: Vec<String> = Vec::new(); |
| 1344 | for lane in s.lanes() { |
| 1345 | for c in s.lane_clips(lane).iter().filter(|c| c.source == idx) { |
| 1346 | users.push(parse::addr(lane, c.start)); |
| 1347 | } |
| 1348 | } |
| 1349 | let names = match users.len() { |
| 1350 | 0 => "no clip is on it".to_string(), |
| 1351 | n if n > 6 => format!("{} and {} more", users[..6].join(", "), n - 6), |
| 1352 | _ => users.join(", "), |
| 1353 | }; |
| 1354 | shape_warnings(idx, &names, old, new, fps) |
| 1355 | } |
| 1356 | |
| 1357 | /// The rate and length warnings of a relink, given the clips already named (`names`). Pure, so the |
| 1358 | /// comparison is tested without a session. Longer and shorter are both a length difference. |
| 1359 | fn shape_warnings(idx: usize, names: &str, old: Shape, new: Shape, fps: f64) -> Vec<String> { |
| 1360 | let mut out = Vec::new(); |
| 1361 | if let (Some(was), Some(now)) = (old.fps, new.fps) |
| 1362 | && (was - now).abs() > 0.001 |
| 1363 | { |
| 1364 | out.push(format!( |
| 1365 | "{} fps against the {} fps file it replaces: src:{idx} plays at another rate, so its clips ({names}) may shift", |
| 1366 | fmt_fps(now), |
| 1367 | fmt_fps(was) |
| 1368 | )); |
| 1369 | } |
| 1370 | if let (Some(was), Some(now)) = (old.secs, new.secs) |
| 1371 | && (was - now).abs() > 1.0 / fps |
| 1372 | { |
| 1373 | out.push(format!( |
| 1374 | "{} long against the {} it replaces (more than a frame): the clips on src:{idx} ({names}) may shift or run past its end", |
| 1375 | clock_secs(now), |
| 1376 | clock_secs(was) |
| 1377 | )); |
| 1378 | } |
| 1379 | out |
| 1380 | } |
| 1381 | |
| 1382 | fn remove(server: &mut Server, args: &Value) -> Reply { |
| 1383 | let raw = match args.get("source") { |
| 1384 | Some(Value::String(s)) => s.trim().to_string(), |
| 1385 | Some(Value::Number(n)) => n.to_string(), |
| 1386 | _ => return Reply::err("argument `source` is required: a source as media_list names it, e.g. src:3"), |
| 1387 | }; |
| 1388 | let digits = raw.strip_prefix("src:").unwrap_or(&raw); |
| 1389 | let Ok(idx) = digits.parse::<usize>() else { |
| 1390 | return Reply::err(format!("`{raw}` is not a source: write src:<n>, e.g. src:3")); |
| 1391 | }; |
| 1392 | let force = args.get("force").and_then(Value::as_bool).unwrap_or(false); |
| 1393 | let s = tri!(server.session()); |
| 1394 | let Some(src) = s.sources().get(idx).cloned() else { |
| 1395 | return Reply::err(format!("there is no src:{idx}; media_list shows the sources")); |
| 1396 | }; |
| 1397 | let mut users: Vec<String> = Vec::new(); |
| 1398 | for lane in s.lanes() { |
| 1399 | for c in s.lane_clips(lane).iter().filter(|c| c.source == idx) { |
| 1400 | users.push(parse::addr(lane, c.start)); |
| 1401 | } |
| 1402 | } |
| 1403 | if !users.is_empty() { |
| 1404 | return Reply::err(format!( |
| 1405 | "src:{idx} {} still plays in {} clip(s): {}. Remove or move those clips first.", |
| 1406 | file_name(&src.path), |
| 1407 | users.len(), |
| 1408 | users.join(", ") |
| 1409 | )); |
| 1410 | } |
| 1411 | let name = file_name(&src.path); |
| 1412 | let last = s.sources().len() - 1; |
| 1413 | // The sources after it, named before the removal, so the reply can say which numbers moved. |
| 1414 | let shifted: Vec<(usize, String)> = |
| 1415 | s.sources().iter().enumerate().skip(idx + 1).map(|(j, o)| (j, file_name(&o.path))).collect(); |
| 1416 | let renumber = renumber_note(&shifted); |
| 1417 | // The last source, with no clip and no undo or redo step on it, goes with its history kept |
| 1418 | // (`remove_unused_source`, which changes nothing when it refuses). Any other source renumbers |
| 1419 | // the ones after it, which only `remove_source` does, and that retires the history; so does the |
| 1420 | // last one when an undo or redo step still names it. That clears undo, so it is refused unless |
| 1421 | // `force` is set, and the reply says why. |
| 1422 | let kept = s.remove_unused_source(&src.path, src.audio_stream).is_ok(); |
| 1423 | // A removal that renumbers with no undo or redo step to lose keeps nothing it needs to, so it |
| 1424 | // goes ahead without `force` and the reply says there was nothing to clear. |
| 1425 | let cleared = !kept && (s.undo_depth() > 0 || s.redo_depth() > 0); |
| 1426 | if !kept { |
| 1427 | if cleared && !force { |
| 1428 | let why = if idx == last { |
| 1429 | format!("src:{idx} {name} is named by an undo or redo step, so removing it clears the undo history") |
| 1430 | } else { |
| 1431 | format!( |
| 1432 | "removing src:{idx} renumbers src:{}.. , so the undo history is cleared; leave src:{idx} in place to keep undo", |
| 1433 | idx + 1 |
| 1434 | ) |
| 1435 | }; |
| 1436 | return Reply::err(format!("src:{idx} {name} not removed: {why}. Pass force:true to remove it and clear the undo history.")); |
| 1437 | } |
| 1438 | if let Err(e) = s.remove_source(&src.path, src.audio_stream) { |
| 1439 | return Reply::err(format!("could not remove src:{idx} {name}: {e}")); |
| 1440 | } |
| 1441 | // The engine retired its undo history with the source; the ledger goes with it. |
| 1442 | server.history_lost_on_open = false; |
| 1443 | server.ledger.clear(); |
| 1444 | server.redo_ledger.clear(); |
| 1445 | } |
| 1446 | // Not an undo step, so the depth may not move: force the unsaved state. |
| 1447 | server.saved_depth = None; |
| 1448 | let text = match (kept, cleared, idx == last) { |
| 1449 | (true, _, _) => format!("removed src:{idx} {name}; {renumber}; undo history is kept. project_save to keep the change."), |
| 1450 | (false, true, true) => format!("removed src:{idx} {name}; its undo and redo steps were cleared with it. project_save to keep the change."), |
| 1451 | (false, true, false) => format!( |
| 1452 | "removed src:{idx} {name}; {renumber}. Undo history is cleared because the renumbered sources cannot keep their steps; project_save to keep the change." |
| 1453 | ), |
| 1454 | (false, false, _) => format!( |
| 1455 | "removed src:{idx} {name}; {renumber}. There was no undo history to clear; project_save to keep the change." |
| 1456 | ), |
| 1457 | }; |
| 1458 | Reply::ok(text).with(json!({"removed": {"src": idx, "name": name, "path": src.path.display().to_string(), "undo_kept": kept}})) |
| 1459 | } |
| 1460 | |
| 1461 | /// What a removal says about the sources after it: each one with its old and new number, the |
| 1462 | /// first three shown and a count for the rest. With none after it, nothing was renumbered. |
| 1463 | fn renumber_note(shifted: &[(usize, String)]) -> String { |
| 1464 | if shifted.is_empty() { |
| 1465 | return "no other source was renumbered".to_string(); |
| 1466 | } |
| 1467 | let shown: Vec<String> = shifted |
| 1468 | .iter() |
| 1469 | .take(3) |
| 1470 | .map(|(j, name)| format!("src:{j} {name} is now src:{}", j - 1)) |
| 1471 | .collect(); |
| 1472 | let more = shifted.len().saturating_sub(3); |
| 1473 | let rest = if more > 0 { format!(", and {more} more") } else { String::new() }; |
| 1474 | format!("{}{rest} (media_list shows the numbers)", shown.join(", ")) |
| 1475 | } |
| 1476 | |
| 1477 | // ---- media_list ------------------------------------------------------------ |
| 1478 | |
| 1479 | /// ` · audio 1 (fra)` for a source placed on a sound track other than the first, so two sources of one |
| 1480 | /// file read apart. Empty for track 0, which a source is unless it was placed with `audio_track`. |
| 1481 | fn audio_choice_text(facts: &MediaFacts, audio_stream: usize) -> String { |
| 1482 | if audio_stream == 0 { |
| 1483 | return String::new(); |
| 1484 | } |
| 1485 | let language = facts |
| 1486 | .streams |
| 1487 | .iter() |
| 1488 | .find(|st| st.kind == engine::demux::StreamKind::Audio && st.index == audio_stream) |
| 1489 | .map(|st| language_of(st.language.as_deref(), "")) |
| 1490 | .unwrap_or_else(|| "und".to_string()); |
| 1491 | format!(" · audio {audio_stream} ({language})") |
| 1492 | } |
| 1493 | |
| 1494 | /// The bin `id` as a path: `Parent/Child` for a nested one. |
| 1495 | fn bin_path(bins: &[engine::Bin], id: u32) -> String { |
| 1496 | let Some(b) = bins.iter().find(|b| b.id == id) else { |
| 1497 | return String::new(); |
| 1498 | }; |
| 1499 | match b.parent { |
| 1500 | 0 => b.name.clone(), |
| 1501 | p => format!("{}/{}", bin_path(bins, p), b.name), |
| 1502 | } |
| 1503 | } |
| 1504 | |
| 1505 | /// A bin as the person wrote it: `bin:<n>`, a bare number, a name, or `Parent/Child`. |
| 1506 | fn resolve_bin(bins: &[engine::Bin], raw: &Value) -> Result<u32, String> { |
| 1507 | let text = match raw { |
| 1508 | Value::String(s) => s.trim().to_string(), |
| 1509 | Value::Number(n) => n.to_string(), |
| 1510 | _ => return Err("a bin is bin:<n> or its name".into()), |
| 1511 | }; |
| 1512 | let digits = text.strip_prefix("bin:").unwrap_or(&text); |
| 1513 | if let Ok(id) = digits.parse::<u32>() { |
| 1514 | return match bins.iter().any(|b| b.id == id) { |
| 1515 | true => Ok(id), |
| 1516 | false => Err(format!("there is no bin:{id}; media_list shows the bins")), |
| 1517 | }; |
| 1518 | } |
| 1519 | let hits: Vec<u32> = bins.iter().filter(|b| bin_path(bins, b.id).eq_ignore_ascii_case(&text) || (b.parent == 0 || !text.contains('/')) && b.name.eq_ignore_ascii_case(&text)).map(|b| b.id).collect(); |
| 1520 | match hits.as_slice() { |
| 1521 | [one] => Ok(*one), |
| 1522 | [] => Err(format!("there is no bin named {text}; media_list shows the bins")), |
| 1523 | many => Err(format!("{} bins are named {text}: use bin:{}", many.len(), many.iter().map(u32::to_string).collect::<Vec<_>>().join(" or bin:"))), |
| 1524 | } |
| 1525 | } |
| 1526 | |
| 1527 | /// Sources as a list of indexes: `src:<n>`, a number, a list of them, or "all". |
| 1528 | fn resolve_sources(count: usize, raw: Option<&Value>) -> Result<Vec<usize>, String> { |
| 1529 | let one = |v: &Value| -> Result<usize, String> { |
| 1530 | let text = match v { |
| 1531 | Value::String(s) => s.trim().to_string(), |
| 1532 | Value::Number(n) => n.to_string(), |
| 1533 | _ => return Err("a source is src:<n>".into()), |
| 1534 | }; |
| 1535 | let idx = text.strip_prefix("src:").unwrap_or(&text).parse::<usize>().map_err(|_| format!("`{text}` is not a source: write src:<n>, e.g. src:3"))?; |
| 1536 | match idx < count { |
| 1537 | true => Ok(idx), |
| 1538 | false => Err(format!("there is no src:{idx}; media_list shows the sources")), |
| 1539 | } |
| 1540 | }; |
| 1541 | match raw { |
| 1542 | None | Some(Value::Null) => Err("argument `sources` is required: src:<n>, a list of them, or \"all\"".into()), |
| 1543 | Some(Value::String(s)) if s.trim() == "all" => Ok((0..count).collect()), |
| 1544 | Some(Value::Array(a)) if !a.is_empty() => a.iter().map(one).collect(), |
| 1545 | Some(Value::Array(_)) => Err("`sources` is empty".into()), |
| 1546 | Some(v) => one(v).map(|i| vec![i]), |
| 1547 | } |
| 1548 | } |
| 1549 | |
| 1550 | // ---- proxies ---------------------------------------------------------------- |
| 1551 | |
| 1552 | /// One stand-in being made for a source. The header read (which decides whether the film needs |
| 1553 | /// one) runs on its own thread, then the encode is a [`engine::proxy::Job`] the status polls. |
| 1554 | pub struct ProxyRun { |
| 1555 | pub source: PathBuf, |
| 1556 | pub cancel: Arc<AtomicBool>, |
| 1557 | pub reading: Option<JoinHandle<Result<Option<engine::proxy::Job>, String>>>, |
| 1558 | pub job: Option<engine::proxy::Job>, |
| 1559 | /// How the run ended, once it has: ready, stopped, failed, or needs no stand-in. |
| 1560 | pub outcome: Option<String>, |
| 1561 | } |
| 1562 | |
| 1563 | impl ProxyRun { |
| 1564 | fn settled(&self) -> bool { |
| 1565 | self.reading.is_none() && self.job.is_none() |
| 1566 | } |
| 1567 | } |
| 1568 | |
| 1569 | fn proxies_schema() -> Value { |
| 1570 | schema( |
| 1571 | json!({ |
| 1572 | "action": {"type": "string", "enum": ["status", "make", "cancel", "delete"], "description": "What to do. Default status."}, |
| 1573 | "source": {"type": ["string", "array"], "items": {"type": "string"}, "description": "src:<n>, a list of them, or \"all\". status with none shows every source; make, cancel and delete need one."} |
| 1574 | }), |
| 1575 | &[], |
| 1576 | ) |
| 1577 | } |
| 1578 | |
| 1579 | /// Starts the stand-in of `source` in the background, unless one is already being made. The |
| 1580 | /// film's own switch is turned on first: the engine's check (`generate_if_wanted`) answers none |
| 1581 | /// for a film switched off by hand. |
| 1582 | fn start_run(srv: &mut Server, source: PathBuf) { |
| 1583 | if srv.proxy_runs.iter().any(|r| r.source == source && !r.settled()) { |
| 1584 | return; |
| 1585 | } |
| 1586 | engine::proxy::set_off(&source, false); |
| 1587 | srv.proxy_runs.retain(|r| r.source != source); |
| 1588 | let cancel = Arc::new(AtomicBool::new(false)); |
| 1589 | let (path, flag) = (source.clone(), cancel.clone()); |
| 1590 | let reading = thread::spawn(move || engine::proxy::generate_if_wanted(&path, &flag).map_err(|e| e.to_string())); |
| 1591 | srv.proxy_runs.push(ProxyRun { source, cancel, reading: Some(reading), job: None, outcome: None }); |
| 1592 | } |
| 1593 | |
| 1594 | /// Moves every run on: a finished header read starts its encode (or settles as needing none), a |
| 1595 | /// finished encode settles with its outcome. Called by the status and on every server tick. |
| 1596 | pub fn poll_proxies(srv: &mut Server) { |
| 1597 | for run in srv.proxy_runs.iter_mut() { |
| 1598 | if run.reading.as_ref().is_some_and(JoinHandle::is_finished) { |
| 1599 | let Some(handle) = run.reading.take() else { continue }; |
| 1600 | match handle.join() { |
| 1601 | Ok(Ok(Some(job))) => { |
| 1602 | // A stop asked while the header was read is carried into the encode at once. |
| 1603 | if run.cancel.load(Ordering::Acquire) { |
| 1604 | job.cancel(); |
| 1605 | } |
| 1606 | run.job = Some(job); |
| 1607 | } |
| 1608 | Ok(Ok(None)) => run.outcome = Some("needs no stand-in: it plays at speed here".into()), |
| 1609 | Ok(Err(e)) => run.outcome = Some(format!("failed: {e}")), |
| 1610 | Err(_) => run.outcome = Some("failed: the reader stopped unexpectedly".into()), |
| 1611 | } |
| 1612 | } |
| 1613 | if run.job.as_ref().is_some_and(engine::proxy::Job::is_finished) { |
| 1614 | let Some(job) = run.job.take() else { continue }; |
| 1615 | let stopped = run.cancel.load(Ordering::Acquire); |
| 1616 | run.outcome = Some(match job.outcome() { |
| 1617 | Some(Ok(_)) => "ready".into(), |
| 1618 | Some(Err(_)) if stopped => "stopped".into(), |
| 1619 | Some(Err(e)) => format!("failed: {e}"), |
| 1620 | None => "failed: the encoder returned no result".into(), |
| 1621 | }); |
| 1622 | } |
| 1623 | } |
| 1624 | } |
| 1625 | |
| 1626 | /// The unfinished run for `source`, if one is going. |
| 1627 | fn running_for(srv: &Server, source: &Path) -> Option<usize> { |
| 1628 | srv.proxy_runs.iter().position(|r| r.source == source && !r.settled()) |
| 1629 | } |
| 1630 | |
| 1631 | /// One source's proxy state in words, as the status shows it. |
| 1632 | fn proxy_state(srv: &Server, source: &Path) -> String { |
| 1633 | if let Some(run) = srv.proxy_runs.iter().find(|r| r.source == source && !r.settled()) { |
| 1634 | return if run.cancel.load(Ordering::Acquire) { |
| 1635 | "stopping".into() |
| 1636 | } else if let Some(job) = &run.job { |
| 1637 | format!("making, {:.0}% done", job.progress() * 100.0) |
| 1638 | } else { |
| 1639 | "reading the file".into() |
| 1640 | }; |
| 1641 | } |
| 1642 | if engine::proxy::cached(source).is_some() { |
| 1643 | return "ready: edited and played through the proxy".into(); |
| 1644 | } |
| 1645 | if engine::is_audio(source) || engine::is_image(source) { |
| 1646 | return "not needed: a sound or a still".into(); |
| 1647 | } |
| 1648 | if let Some(run) = srv.proxy_runs.iter().rev().find(|r| r.source == source) |
| 1649 | && let Some(outcome) = &run.outcome |
| 1650 | { |
| 1651 | return outcome.clone(); |
| 1652 | } |
| 1653 | if engine::proxy::is_off(source) { "off: the film itself plays".into() } else { "none made".into() } |
| 1654 | } |
| 1655 | |
| 1656 | /// `proxies {action, source}`: the status of each source's stand-in, or make, cancel or delete one. |
| 1657 | fn proxies(srv: &mut Server, args: &Value) -> Reply { |
| 1658 | poll_proxies(srv); |
| 1659 | let action = opt_str(args, "action").unwrap_or("status"); |
| 1660 | if !matches!(action, "status" | "make" | "cancel" | "delete") { |
| 1661 | return Reply::err(format!("action `{action}` is not one of status, make, cancel, delete")); |
| 1662 | } |
| 1663 | let s = tri!(srv.session_ref()); |
| 1664 | let count = s.sources().len(); |
| 1665 | let picked = match (action, args.get("source")) { |
| 1666 | ("status", None | Some(Value::Null)) => (0..count).collect(), |
| 1667 | (_, None | Some(Value::Null)) => return Reply::err(format!("{action} needs `source`: src:<n>, a list, or \"all\"")), |
| 1668 | (_, Some(v)) => match resolve_sources(count, Some(v)) { |
| 1669 | Ok(list) => list, |
| 1670 | Err(e) => return Reply::err(e), |
| 1671 | }, |
| 1672 | }; |
| 1673 | let paths: Vec<(usize, PathBuf)> = picked.iter().map(|&i| (i, s.sources()[i].path.clone())).collect(); |
| 1674 | let mut lines: Vec<String> = Vec::new(); |
| 1675 | for (i, path) in &paths { |
| 1676 | let name = file_name(path); |
| 1677 | match action { |
| 1678 | "make" => { |
| 1679 | if engine::is_audio(path) || engine::is_image(path) { |
| 1680 | lines.push(format!("src:{i} {name}: no stand-in needed (a sound or a still)")); |
| 1681 | } else if running_for(srv, path).is_some() { |
| 1682 | lines.push(format!("src:{i} {name}: already being made")); |
| 1683 | } else if engine::proxy::cached(path).is_some() { |
| 1684 | lines.push(format!("src:{i} {name}: already ready")); |
| 1685 | } else { |
| 1686 | start_run(srv, path.clone()); |
| 1687 | lines.push(format!("src:{i} {name}: making in the background; proxies status shows the progress")); |
| 1688 | } |
| 1689 | } |
| 1690 | "cancel" | "delete" => { |
| 1691 | if let Some(k) = running_for(srv, path) { |
| 1692 | let run = &srv.proxy_runs[k]; |
| 1693 | run.cancel.store(true, Ordering::Release); |
| 1694 | if let Some(job) = &run.job { |
| 1695 | job.cancel(); |
| 1696 | } |
| 1697 | engine::proxy::set_off(path, true); |
| 1698 | lines.push(format!("src:{i} {name}: stopping the stand-in; the film stays off")); |
| 1699 | } else if action == "cancel" { |
| 1700 | lines.push(format!("src:{i} {name}: no stand-in is being made")); |
| 1701 | } |
| 1702 | if action == "delete" { |
| 1703 | match engine::proxy::delete(path) { |
| 1704 | Ok(gone) => { |
| 1705 | engine::proxy::set_off(path, true); |
| 1706 | lines.push(match gone { |
| 1707 | true => format!("src:{i} {name}: stand-in deleted; the film stays off and plays original"), |
| 1708 | false => format!("src:{i} {name}: no stand-in to delete; the film stays off"), |
| 1709 | }); |
| 1710 | } |
| 1711 | Err(e) => lines.push(format!("src:{i} {name}: could not delete the stand-in, it is still in use: {e}")), |
| 1712 | } |
| 1713 | } |
| 1714 | } |
| 1715 | _ => lines.push(format!("src:{i} {name}: {}", proxy_state(srv, path))), |
| 1716 | } |
| 1717 | } |
| 1718 | let states: Vec<Value> = paths |
| 1719 | .iter() |
| 1720 | .map(|(i, path)| json!({"src": i, "path": path.display().to_string(), "state": proxy_state(srv, path)})) |
| 1721 | .collect(); |
| 1722 | let running = srv.proxy_runs.iter().filter(|r| !r.settled()).count(); |
| 1723 | let text = if lines.is_empty() { "no sources in the project".to_string() } else { format!("{}\n{running} stand-in(s) being made", lines.join("\n")) }; |
| 1724 | Reply::ok(text).with(json!({"sources": states, "making": running})) |
| 1725 | } |
| 1726 | |
| 1727 | /// `media_bin`: the library's bins and favourites. |
| 1728 | fn bin(server: &mut Server, args: &Value) -> Reply { |
| 1729 | let action: String = opt_str(args, "action").unwrap_or_default().to_owned(); |
| 1730 | let before = tri!(server.session_ref()).history_pushes(); |
| 1731 | let (text, label) = { |
| 1732 | let s = server.session.as_mut().expect("checked above"); |
| 1733 | let bins = s.bins().to_vec(); |
| 1734 | let result: Result<(String, String), String> = (|| match action.as_str() { |
| 1735 | "create" => { |
| 1736 | let name = opt_str(args, "name").ok_or("create needs `name`")?; |
| 1737 | let parent = match args.get("parent") { |
| 1738 | None | Some(Value::Null) => 0, |
| 1739 | Some(p) => resolve_bin(&bins, p)?, |
| 1740 | }; |
| 1741 | let id = s.create_bin(name, parent)?; |
| 1742 | let shown = bin_path(s.bins(), id); |
| 1743 | Ok((format!("bin:{id} {shown} created"), format!("media_bin create {shown}"))) |
| 1744 | } |
| 1745 | "rename" => { |
| 1746 | let id = resolve_bin(&bins, args.get("bin").ok_or("rename needs `bin`")?)?; |
| 1747 | let name = opt_str(args, "name").ok_or("rename needs `name`")?; |
| 1748 | let was = bin_path(&bins, id); |
| 1749 | let changed = s.rename_bin(id, name)?; |
| 1750 | let shown = bin_path(s.bins(), id); |
| 1751 | Ok((if changed { format!("bin:{id} {was} renamed to {shown}") } else { format!("bin:{id} is already named {shown}; nothing changed") }, format!("media_bin rename {shown}"))) |
| 1752 | } |
| 1753 | "remove" => { |
| 1754 | let id = resolve_bin(&bins, args.get("bin").ok_or("remove needs `bin`")?)?; |
| 1755 | let was = bin_path(&bins, id); |
| 1756 | let moved = s.remove_bin(id)?; |
| 1757 | Ok((format!("bin:{id} {was} removed; {moved} source{} moved up", if moved == 1 { "" } else { "s" }), format!("media_bin remove {was}"))) |
| 1758 | } |
| 1759 | "move" => { |
| 1760 | let srcs = resolve_sources(s.sources().len(), args.get("sources"))?; |
| 1761 | let target = match args.get("bin") { |
| 1762 | None | Some(Value::Null) => 0, |
| 1763 | Some(b) => resolve_bin(&bins, b)?, |
| 1764 | }; |
| 1765 | let moved = s.move_to_bin(&srcs, target)?; |
| 1766 | let where_ = if target == 0 { "out of every bin".to_string() } else { format!("into bin:{target} {}", bin_path(&bins, target)) }; |
| 1767 | Ok((if moved == 0 { format!("already {where_}; nothing changed") } else { format!("{moved} source{} moved {where_}", if moved == 1 { "" } else { "s" }) }, format!("media_bin move {where_}"))) |
| 1768 | } |
| 1769 | "favourite" => { |
| 1770 | let srcs = resolve_sources(s.sources().len(), args.get("sources"))?; |
| 1771 | let on = args.get("on").and_then(Value::as_bool).unwrap_or(true); |
| 1772 | let changed = s.set_favourite(&srcs, on)?; |
| 1773 | let verb = if on { "starred" } else { "unstarred" }; |
| 1774 | Ok((if changed == 0 { format!("already {verb}; nothing changed") } else { format!("{changed} source{} {verb}", if changed == 1 { "" } else { "s" }) }, format!("media_bin {verb}"))) |
| 1775 | } |
| 1776 | "" => Err("argument `action` is required: create, rename, remove, move or favourite".into()), |
| 1777 | other => Err(format!("unknown action `{other}`: create, rename, remove, move or favourite")), |
| 1778 | })(); |
| 1779 | match result { |
| 1780 | Ok(v) => v, |
| 1781 | Err(e) => return Reply::err(e), |
| 1782 | } |
| 1783 | }; |
| 1784 | if tri!(server.session_ref()).history_pushes() > before { |
| 1785 | crate::tools::project::note_pushes_as(server, before, &label); |
| 1786 | return Reply::ok(format!("{text}\nundo takes it back; unsaved until project_save")); |
| 1787 | } |
| 1788 | Reply::ok(text) |
| 1789 | } |
| 1790 | |
| 1791 | fn list(server: &mut Server, args: &Value) -> Reply { |
| 1792 | let s = tri!(server.session_ref()); |
| 1793 | let sources = s.sources(); |
| 1794 | let want = opt_str(args, "kind"); |
| 1795 | if let Some(k) = want.filter(|k| !["video", "audio", "image"].contains(k)) { |
| 1796 | return Reply::err(format!("kind `{k}` is not video, audio or image")); |
| 1797 | } |
| 1798 | if sources.is_empty() { |
| 1799 | return Reply::ok("no sources; media_import adds them").with(json!({"sources": [], "bins": []})); |
| 1800 | } |
| 1801 | let mut lines: Vec<String> = Vec::new(); |
| 1802 | let mut items: Vec<Value> = Vec::new(); |
| 1803 | // Each source's kind, parallel to `lines` and `items`, so `kind` can keep some of them. |
| 1804 | let mut kinds: Vec<&str> = Vec::new(); |
| 1805 | for (i, src) in sources.iter().enumerate() { |
| 1806 | let path = &src.path; |
| 1807 | let name = file_name(path); |
| 1808 | // A source whose file is gone says so; probing a missing path would call it audio only. |
| 1809 | if !engine::source_present(path) { |
| 1810 | lines.push(format!("src:{i} {name} · OFFLINE (moved or deleted: {})", path.display())); |
| 1811 | items.push(json!({"src": i, "name": name, "path": path.display().to_string(), "offline": true})); |
| 1812 | kinds.push(if engine::is_image(path) { "image" } else { "offline" }); |
| 1813 | continue; |
| 1814 | } |
| 1815 | // A generated clip's source has no file to probe: it is a picture made from numbers. |
| 1816 | if let Some(g) = engine::generate::Gen::parse(path) { |
| 1817 | lines.push(format!("src:{i} {} · generated, no file · {}x{}", super::generated::describe(&g), g.width, g.height)); |
| 1818 | items.push(json!({"src": i, "name": name, "generator": super::generated::describe(&g), "width": g.width, "height": g.height, "kind": "video"})); |
| 1819 | kinds.push("video"); |
| 1820 | continue; |
| 1821 | } |
| 1822 | let facts = probe_media(path); |
| 1823 | let duration_secs = facts.duration_secs; |
| 1824 | let dur = duration_text(path, &facts); |
| 1825 | let picture = match &facts.video { |
| 1826 | Some(v) => { |
| 1827 | let rate = v.frame_rate.map_or("@?".to_string(), |r| format!("@{}", fmt_fps(r))); |
| 1828 | format!("{}x{} {} {rate}", v.width, v.height, codec_phrase(v.codec, v.profile)) |
| 1829 | } |
| 1830 | None if engine::is_image(path) => "still image".to_string(), |
| 1831 | None => "audio only".to_string(), |
| 1832 | }; |
| 1833 | let audio = audio_choice_text(&facts, src.audio_stream); |
| 1834 | lines.push(format!("src:{i} {name} · {dur} · {picture}{audio}")); |
| 1835 | let kind = if engine::is_image(path) { |
| 1836 | "image" |
| 1837 | } else if facts.video.is_some() { |
| 1838 | "video" |
| 1839 | } else { |
| 1840 | "audio" |
| 1841 | }; |
| 1842 | kinds.push(kind); |
| 1843 | items.push(json!({ |
| 1844 | "src": i, |
| 1845 | "name": name, |
| 1846 | "kind": kind, |
| 1847 | "path": path.display().to_string(), |
| 1848 | "audio_stream": src.audio_stream, |
| 1849 | "duration_secs": duration_secs, |
| 1850 | "audio_duration_secs": audio_only_secs(path, &facts), |
| 1851 | "width": facts.video.map(|v| v.width), |
| 1852 | "height": facts.video.map(|v| v.height), |
| 1853 | "codec": facts.video.map(|v| v.codec.name()), |
| 1854 | "profile": facts.video.and_then(|v| v.profile), |
| 1855 | "interlaced": facts.video.and_then(|v| v.interlaced), |
| 1856 | "frame_rate": facts.video.and_then(|v| v.frame_rate), |
| 1857 | })); |
| 1858 | } |
| 1859 | // The library's shelves: each source's bin and star, then the bins themselves up front. |
| 1860 | let bins = s.bins(); |
| 1861 | for ((src, line), item) in sources.iter().zip(lines.iter_mut()).zip(items.iter_mut()) { |
| 1862 | let in_bin = bin_path(bins, src.bin); |
| 1863 | if src.bin != 0 { |
| 1864 | line.push_str(&format!(" · in bin:{} {in_bin}", src.bin)); |
| 1865 | } |
| 1866 | if src.fav { |
| 1867 | line.push_str(" · favourite"); |
| 1868 | } |
| 1869 | item["bin"] = if src.bin == 0 { Value::Null } else { json!(src.bin) }; |
| 1870 | item["bin_path"] = if src.bin == 0 { Value::Null } else { json!(in_bin) }; |
| 1871 | item["favourite"] = json!(src.fav); |
| 1872 | } |
| 1873 | // `kind` keeps the sources of that kind; the bins are listed whole, as before. |
| 1874 | if let Some(k) = want { |
| 1875 | let keep: Vec<bool> = kinds.iter().map(|x| *x == k).collect(); |
| 1876 | let mut keep_it = keep.iter(); |
| 1877 | items.retain(|_| *keep_it.next().unwrap_or(&false)); |
| 1878 | let mut keep_it = keep.iter(); |
| 1879 | lines.retain(|_| *keep_it.next().unwrap_or(&false)); |
| 1880 | if lines.is_empty() { |
| 1881 | return Reply::ok(format!("no {k} sources")).with(json!({"sources": [], "bins": []})); |
| 1882 | } |
| 1883 | } |
| 1884 | let bin_items: Vec<Value> = bins |
| 1885 | .iter() |
| 1886 | .map(|b| json!({"bin": b.id, "name": b.name, "parent": (b.parent != 0).then_some(b.parent), "path": bin_path(bins, b.id), "sources": sources.iter().filter(|x| x.bin == b.id).count()})) |
| 1887 | .collect(); |
| 1888 | let mut head: Vec<String> = bins.iter().map(|b| format!("bin:{} {} · {} source{}", b.id, bin_path(bins, b.id), sources.iter().filter(|x| x.bin == b.id).count(), if sources.iter().filter(|x| x.bin == b.id).count() == 1 { "" } else { "s" })).collect(); |
| 1889 | head.extend(lines); |
| 1890 | Reply::ok(head.join("\n")).with(json!({"sources": items, "bins": bin_items})) |
| 1891 | } |
| 1892 | |
| 1893 | #[cfg(test)] |
| 1894 | mod tests { |
| 1895 | use super::*; |
| 1896 | use crate::testutil::TestDir; |
| 1897 | use engine::PlaybackSession; |
| 1898 | |
| 1899 | fn asset(name: &str) -> PathBuf { |
| 1900 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 1901 | } |
| 1902 | |
| 1903 | fn quiet() { |
| 1904 | engine::ao::set_silent_output(); |
| 1905 | } |
| 1906 | |
| 1907 | /// An empty scratch directory unique to this test, removed when the guard drops. |
| 1908 | fn scratch_dir(test: &str) -> TestDir { |
| 1909 | TestDir::new(&format!("media-{test}")) |
| 1910 | } |
| 1911 | |
| 1912 | #[test] |
| 1913 | fn wildcard_matcher() { |
| 1914 | assert!(wild("*.mp4", "a.mp4")); |
| 1915 | assert!(wild("clip?.mp4", "clip1.mp4")); |
| 1916 | assert!(!wild("clip?.mp4", "clip12.mp4")); |
| 1917 | assert!(wild("c*p*4", "clip1.mp4")); |
| 1918 | assert!(!wild("*.mp4", "a.mov")); |
| 1919 | assert!(wild("*", "anything")); |
| 1920 | } |
| 1921 | |
| 1922 | #[test] |
| 1923 | fn glob_and_paths_expand_in_order() { |
| 1924 | quiet(); |
| 1925 | let dir = scratch_dir("glob"); |
| 1926 | for name in ["clip1.mp4", "clip2.mp4", "notes.txt"] { |
| 1927 | std::fs::copy(asset("test_av.mp4"), dir.join(name)).unwrap(); |
| 1928 | } |
| 1929 | let pattern = format!("{}/clip*.mp4", dir.display()); |
| 1930 | let found = expand_glob(&pattern).unwrap(); |
| 1931 | assert_eq!(found.len(), 2); |
| 1932 | assert_eq!(file_name(&found[0]), "clip1.mp4"); |
| 1933 | assert_eq!(expand_glob(&format!("{}/clip?.mp4", dir.display())).unwrap().len(), 2); |
| 1934 | assert_eq!(expand_glob(&format!("{}/*.txt", dir.display())).unwrap().len(), 1); |
| 1935 | assert!(expand_glob(&format!("{}/*.mkv", dir.display())).unwrap().is_empty()); |
| 1936 | |
| 1937 | let args = json!({"glob": format!("{}/*.mp4", dir.display()), "paths": [format!("{}/clip1.mp4", dir.display())]}); |
| 1938 | assert_eq!(gather(&args, true).ok().map(|v| v.len()), Some(2), "repeats are dropped"); |
| 1939 | } |
| 1940 | |
| 1941 | #[test] |
| 1942 | fn probe_glob_reports_each_file() { |
| 1943 | quiet(); |
| 1944 | let dir = scratch_dir("probe"); |
| 1945 | for name in ["clip1.mp4", "clip2.mp4"] { |
| 1946 | std::fs::copy(asset("test_av.mp4"), dir.join(name)).unwrap(); |
| 1947 | } |
| 1948 | std::fs::write(dir.join("broken.mp4"), b"not media at all").unwrap(); |
| 1949 | let mut server = Server::new(); |
| 1950 | let args = json!({"glob": format!("{}/*.mp4", dir.display())}); |
| 1951 | let r = probe(&mut server, &args); |
| 1952 | assert!(!r.is_error, "{}", r.text); |
| 1953 | let files = r.structured.as_ref().unwrap()["files"].as_array().unwrap().clone(); |
| 1954 | assert_eq!(files.len(), 3); |
| 1955 | let good = files.iter().find(|f| f["name"] == "clip1.mp4").unwrap(); |
| 1956 | assert!(good["width"].as_u64().unwrap() > 0); |
| 1957 | assert!(good["error"].is_null()); |
| 1958 | let bad = files.iter().find(|f| f["name"] == "broken.mp4").unwrap(); |
| 1959 | assert!(bad["error"].is_string()); |
| 1960 | assert!(r.text.contains("clip1.mp4"), "{}", r.text); |
| 1961 | assert!(r.text.contains("broken.mp4 looks truncated or is not a valid MP4"), "{}", r.text); |
| 1962 | } |
| 1963 | |
| 1964 | #[test] |
| 1965 | fn probe_missing_file_is_inline_error() { |
| 1966 | let mut server = Server::new(); |
| 1967 | let r = probe(&mut server, &json!({"paths": ["/definitely/not/here.mp4"]})); |
| 1968 | assert!(r.is_error); |
| 1969 | assert!(r.text.contains("not found"), "{}", r.text); |
| 1970 | assert!(probe(&mut server, &json!({})).is_error); |
| 1971 | } |
| 1972 | |
| 1973 | #[test] |
| 1974 | fn import_then_list_needs_a_project() { |
| 1975 | quiet(); |
| 1976 | let mut none = Server::new(); |
| 1977 | assert!(import(&mut none, &json!({"paths": [asset("test_av.mp4")]})).is_error); |
| 1978 | assert!(list(&mut none, &json!({})).is_error); |
| 1979 | |
| 1980 | let mut server = Server::new(); |
| 1981 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 1982 | let r = import(&mut server, &json!({"paths": [asset("test_av.mp4")]})); |
| 1983 | assert!(!r.is_error, "{}", r.text); |
| 1984 | assert!(r.text.contains("src:0 test_av.mp4"), "{}", r.text); |
| 1985 | assert!(server.ledger.is_empty(), "import is not an undo step"); |
| 1986 | |
| 1987 | let again = import(&mut server, &json!({"paths": [asset("test_av.mp4")]})); |
| 1988 | assert!(again.text.contains("src:0"), "importing twice registers once: {}", again.text); |
| 1989 | assert_eq!(server.session.as_ref().unwrap().sources().len(), 1); |
| 1990 | |
| 1991 | let l = list(&mut server, &json!({})); |
| 1992 | assert!(!l.is_error); |
| 1993 | assert!(l.text.contains("src:0 test_av.mp4"), "{}", l.text); |
| 1994 | assert_eq!(l.structured.as_ref().unwrap()["sources"][0]["src"], json!(0)); |
| 1995 | } |
| 1996 | |
| 1997 | #[test] |
| 1998 | fn import_refuses_missing_file_and_keeps_going() { |
| 1999 | quiet(); |
| 2000 | let mut server = Server::new(); |
| 2001 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2002 | let r = import( |
| 2003 | &mut server, |
| 2004 | &json!({"paths": ["/definitely/not/here.mp4", asset("test_av.mp4").display().to_string()]}), |
| 2005 | ); |
| 2006 | assert!(!r.is_error, "one good file makes the call a success: {}", r.text); |
| 2007 | assert!(r.text.contains("not found: /definitely/not/here.mp4"), "{}", r.text); |
| 2008 | assert!(r.text.contains("src:0"), "{}", r.text); |
| 2009 | } |
| 2010 | |
| 2011 | /// A matrix the file does not tag says so; a tagged one reads as before. |
| 2012 | #[test] |
| 2013 | fn an_untagged_matrix_says_it_is_assumed() { |
| 2014 | use engine::colorspace::{ColorDescription, Matrix, Transfer}; |
| 2015 | let bt709 = ColorDescription { matrix: Matrix::Bt709, ..ColorDescription::default() }; |
| 2016 | assert_eq!(colour_text(bt709, true), "BT.709 (assumed, untagged)"); |
| 2017 | assert_eq!(colour_text(bt709, false), "BT.709"); |
| 2018 | let pq = ColorDescription { transfer: Transfer::Pq, ..bt709 }; |
| 2019 | assert!(colour_text(pq, true).starts_with("BT.709 (assumed, untagged) PQ"), "{}", colour_text(pq, true)); |
| 2020 | assert_eq!(colour_text(pq, false).split(" (HDR").next(), Some("BT.709 PQ")); |
| 2021 | } |
| 2022 | |
| 2023 | /// ProRes, DNxHD/DNxHR and MJPEG are named in plain words, with the profile after the codec |
| 2024 | /// (Avid's profile names carry the family themselves). |
| 2025 | #[test] |
| 2026 | fn the_professional_codecs_are_named_with_their_profile() { |
| 2027 | use engine::demux::Codec; |
| 2028 | assert_eq!(codec_phrase(Codec::ProRes, Some("422 HQ")), "ProRes 422 HQ"); |
| 2029 | assert_eq!(codec_phrase(Codec::Dnxhd, Some("DNxHR HQX")), "DNxHR HQX"); |
| 2030 | assert_eq!(codec_phrase(Codec::Dnxhd, Some("DNxHD 145")), "DNxHD 145"); |
| 2031 | assert_eq!(codec_phrase(Codec::Dnxhd, None), "DNxHD"); |
| 2032 | assert_eq!(codec_phrase(Codec::Mjpeg, None), "MJPEG"); |
| 2033 | assert_eq!(plain_codec("apch"), "prores"); |
| 2034 | assert_eq!(plain_codec("AVdn"), "dnxhd"); |
| 2035 | assert_eq!(plain_codec("AVdh"), "dnxhr"); |
| 2036 | assert_eq!(plain_codec("V_MJPEG"), "mjpeg"); |
| 2037 | assert_eq!(plain_codec("mjpa"), "mjpeg"); |
| 2038 | assert_eq!(plain_codec("dvc "), "dv"); |
| 2039 | assert_eq!(plain_codec("dv5p"), "dv"); |
| 2040 | assert_eq!(plain_codec("mp4v"), "mpeg4"); |
| 2041 | assert_eq!(plain_codec("V_MPEG4/ISO/ASP"), "mpeg4"); |
| 2042 | assert_eq!(plain_codec("s263"), "h263"); |
| 2043 | assert_eq!(codec_phrase(Codec::Dv, Some("DVCPRO50")), "DV DVCPRO50"); |
| 2044 | assert_eq!(codec_phrase(Codec::Mpeg4, Some("Advanced Simple")), "MPEG-4 Advanced Simple"); |
| 2045 | assert_eq!(codec_phrase(Codec::Mpeg4, Some("H.263")), "H.263"); |
| 2046 | assert_eq!(codec_phrase(Codec::MsMpeg4, Some("v3")), "MS-MPEG4 v3"); |
| 2047 | assert_eq!(codec_phrase(Codec::Raw, Some("BGR24")), "Raw BGR24"); |
| 2048 | } |
| 2049 | |
| 2050 | /// The video profile follows the codec name in the picture phrase, in the probe line and the list, |
| 2051 | /// and the JSON row carries it with the matrix flag. |
| 2052 | #[test] |
| 2053 | fn the_video_profile_follows_the_codec_name() { |
| 2054 | let row = probe_one(&asset("test_hevc10.mkv")); |
| 2055 | let line = row_line(&row); |
| 2056 | assert!(line.starts_with("test_hevc10.mkv · mkv · HEVC Main 10 "), "{line}"); |
| 2057 | assert_eq!(row_json(&row)["profile"], json!("Main 10")); |
| 2058 | assert_eq!(row_json(&row)["matrix_assumed"], json!(true)); |
| 2059 | let gray = probe_one(&asset("test_av1_gray.mkv")); |
| 2060 | assert_eq!(row_json(&gray)["profile"], json!("Main")); |
| 2061 | assert_eq!(row_json(&gray)["matrix_assumed"], json!(true)); |
| 2062 | |
| 2063 | let mut server = Server::new(); |
| 2064 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2065 | let imported = import(&mut server, &json!({"paths": [asset("test_hevc10.mkv").display().to_string()]})); |
| 2066 | assert!(!imported.is_error, "{}", imported.text); |
| 2067 | let listed = list(&mut server, &json!({})); |
| 2068 | assert!(listed.text.contains("1280x720 HEVC Main 10 @30"), "{}", listed.text); |
| 2069 | assert_eq!(listed.structured.as_ref().unwrap()["sources"][0]["profile"], json!("Main 10")); |
| 2070 | } |
| 2071 | |
| 2072 | /// A lossless track says its depth after the codec: FLAC and PCM from the header, and a lossy |
| 2073 | /// track says none. The JSON row carries the depth as a number. |
| 2074 | #[test] |
| 2075 | fn a_lossless_track_says_its_bit_depth() { |
| 2076 | let text = |name: &str| -> Vec<String> { |
| 2077 | let path = asset(name); |
| 2078 | other_streams(&path, &probe_media(&path)).iter().map(stream_text).collect() |
| 2079 | }; |
| 2080 | assert_eq!(text("test_tone.flac"), vec!["audio track 0 flac 24-bit (und) stereo, 44.1 kHz"]); |
| 2081 | assert_eq!(text("test_tone.wav"), vec!["audio track 0 pcm_s16le 16-bit (und) stereo, 44.1 kHz"]); |
| 2082 | assert_eq!(text("test_tone.mp3"), vec!["audio track 0 mp3 (und) stereo, 44.1 kHz"]); |
| 2083 | let flac = asset("test_tone.flac"); |
| 2084 | let streams = other_streams(&flac, &probe_media(&flac)); |
| 2085 | assert_eq!(stream_json(&streams[0])["bit_depth"], json!(24)); |
| 2086 | let mp3 = asset("test_tone.mp3"); |
| 2087 | assert!(stream_json(&other_streams(&mp3, &probe_media(&mp3))[0])["bit_depth"].is_null()); |
| 2088 | } |
| 2089 | |
| 2090 | #[test] |
| 2091 | fn durations_come_from_the_header_and_stills_say_still() { |
| 2092 | quiet(); |
| 2093 | let dir = scratch_dir("durations"); |
| 2094 | std::fs::copy(asset("test_still.png"), dir.join("still.png")).unwrap(); |
| 2095 | let mut server = Server::new(); |
| 2096 | let probed = probe(&mut server, &json!({"paths": [asset("test_av.mp4").display().to_string(), dir.join("still.png").display().to_string()]})); |
| 2097 | assert!(!probed.is_error, "{}", probed.text); |
| 2098 | assert!(probed.text.contains("00:05.000"), "5 s clip read as 5 s: {}", probed.text); |
| 2099 | assert!(probed.text.contains("· still ·"), "a still has no playing time: {}", probed.text); |
| 2100 | assert!(!probed.text.contains("10:00"), "{}", probed.text); |
| 2101 | |
| 2102 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2103 | let imported = import(&mut server, &json!({"paths": [asset("test_av.mp4").display().to_string(), dir.join("still.png").display().to_string()]})); |
| 2104 | assert!(imported.text.contains("test_av.mp4 (00:05.000)"), "{}", imported.text); |
| 2105 | assert!(imported.text.contains("still.png (still)"), "{}", imported.text); |
| 2106 | let listed = list(&mut server, &json!({})); |
| 2107 | assert!(listed.text.contains("00:05.000"), "{}", listed.text); |
| 2108 | assert!(listed.text.contains("still"), "{}", listed.text); |
| 2109 | let still = &listed.structured.as_ref().unwrap()["sources"][1]; |
| 2110 | assert!(still["duration_secs"].is_null(), "{still}"); |
| 2111 | } |
| 2112 | |
| 2113 | #[test] |
| 2114 | fn missing_file_says_not_found_with_its_path() { |
| 2115 | quiet(); |
| 2116 | let missing = "/definitely/not/here.mp4"; |
| 2117 | let mut server = Server::new(); |
| 2118 | let probed = probe(&mut server, &json!({"paths": [missing]})); |
| 2119 | assert!(probed.text.contains(&format!("not found: {missing}")), "{}", probed.text); |
| 2120 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2121 | let imported = import(&mut server, &json!({"paths": [missing]})); |
| 2122 | assert!(imported.is_error); |
| 2123 | assert_eq!(imported.text, format!("not found: {missing}\nnothing was imported")); |
| 2124 | } |
| 2125 | |
| 2126 | /// A bulk import shows every refusal and warning in full, however many paths there are; |
| 2127 | /// only the plain successes are folded into a count. |
| 2128 | #[test] |
| 2129 | fn bulk_import_lists_every_refusal_and_folds_only_successes() { |
| 2130 | quiet(); |
| 2131 | let mut names: Vec<PathBuf> = std::fs::read_dir(asset("")).unwrap().map(|e| e.unwrap().path()).filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "mp4" || e == "wav" || e == "mkv")).collect(); |
| 2132 | names.sort(); |
| 2133 | assert!(names.len() >= 30, "enough assets for the bulk test: {}", names.len()); |
| 2134 | let mut paths: Vec<String> = names.iter().take(30).map(|p| p.display().to_string()).collect(); |
| 2135 | let missing = "/definitely/not/here-41.mp4".to_string(); |
| 2136 | paths.insert(3, missing.clone()); |
| 2137 | let folder = asset("fonts").display().to_string(); |
| 2138 | paths.insert(20, folder.clone()); |
| 2139 | assert_eq!(paths.len(), 32); |
| 2140 | let mut server = Server::new(); |
| 2141 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2142 | let r = import(&mut server, &json!({"paths": paths})); |
| 2143 | let imported = r.structured.as_ref().unwrap()["imported"].as_array().unwrap().len(); |
| 2144 | assert!(imported > 20, "more than the shown count imported: {imported}"); |
| 2145 | assert!(r.text.contains(&format!("not found: {missing}")), "the not-found line is in full: {}", r.text); |
| 2146 | assert!(r.text.contains(&folder), "the refused folder is in full: {}", r.text); |
| 2147 | let folded = imported - IMPORT_SHOWN; |
| 2148 | assert!(r.text.contains(&format!("…and {folded} more imported")), "the count is exact: {}", r.text); |
| 2149 | assert_eq!(r.text.lines().filter(|l| l.starts_with("src:")).count(), IMPORT_SHOWN, "{}", r.text); |
| 2150 | assert!(!r.is_error); |
| 2151 | } |
| 2152 | |
| 2153 | /// A picture the decoder refuses shows its reason and the streams the header names, together. |
| 2154 | /// (12-bit AV1 opens now; the display matrix is a refusal that remains.) |
| 2155 | #[test] |
| 2156 | fn a_refused_picture_shows_its_reason_and_its_streams() { |
| 2157 | quiet(); |
| 2158 | let row = probe_one(&asset("test_av1_12bit.mkv")); |
| 2159 | assert!(row.error.is_none(), "12-bit AV1 opens now: {:?}", row.error); |
| 2160 | let text = row_line(&row); |
| 2161 | assert!(!text.contains("refused:"), "{text}"); |
| 2162 | assert!(text.contains("picture: 12-bit 4:2:0"), "the picture is named: {text}"); |
| 2163 | assert!(row_json(&row)["error"].is_null()); |
| 2164 | let rot = probe_one(&asset("test_rotation45.mkv")); |
| 2165 | assert!(rot.error.is_some(), "the display matrix refusal is kept"); |
| 2166 | assert!(row_line(&rot).contains("streams: video #0"), "{}", row_line(&rot)); |
| 2167 | } |
| 2168 | |
| 2169 | /// A sound codec nothing decodes is named in probe, with the silence it causes, and an import |
| 2170 | /// of such a file comes in silent with the same warning: the length the header states holds |
| 2171 | /// the silence. DTS is decoded now, so the file is a WavPack one written here. |
| 2172 | #[test] |
| 2173 | fn an_unsupported_sound_codec_is_warned_in_probe_and_import() { |
| 2174 | quiet(); |
| 2175 | let td = crate::testutil::TestDir::new("unsupported-sound-codec"); |
| 2176 | let wv = td.path().join("wavpack.mkv"); |
| 2177 | let out = std::process::Command::new("ffmpeg") |
| 2178 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", "sine=duration=1", "-ar", "48000", "-ac", "2"]) |
| 2179 | .args(["-c:a", "wavpack"]) |
| 2180 | .arg(&wv) |
| 2181 | .output() |
| 2182 | .expect("ffmpeg runs"); |
| 2183 | assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); |
| 2184 | let row = probe_one(&wv); |
| 2185 | let want = "warning: audio: WavPack is not supported; this file's sound will be silent"; |
| 2186 | assert_eq!(row.warnings.len(), 1, "{:?}", row.warnings); |
| 2187 | assert_eq!(row.warnings[0], want, "{:?}", row.warnings); |
| 2188 | assert!(row_line(&row).contains(&row.warnings[0]), "{}", row_line(&row)); |
| 2189 | assert_eq!(row_json(&row)["warnings"][0], row.warnings[0].as_str()); |
| 2190 | // Import takes the file: its sound is silent for the length the header states, and the |
| 2191 | // same warning is said beside the file's name. |
| 2192 | let mut server = Server::new(); |
| 2193 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2194 | let imported = import(&mut server, &json!({"paths": [wv.display().to_string()]})); |
| 2195 | assert!(!imported.is_error, "{}", imported.text); |
| 2196 | assert!(!imported.text.contains("has no audio track"), "{}", imported.text); |
| 2197 | assert_eq!(imported.structured.as_ref().unwrap()["imported"].as_array().unwrap().len(), 1, "{}", imported.text); |
| 2198 | assert!(imported.text.contains(want), "{}", imported.text); |
| 2199 | // A file with decodable sound has no warning. |
| 2200 | assert!(probe_one(&asset("test_h264.mkv")).warnings.is_empty()); |
| 2201 | } |
| 2202 | |
| 2203 | #[test] |
| 2204 | fn codec_names_come_from_the_engine_reason() { |
| 2205 | // The engine's friendly names, as `codec_display_name` gives them. |
| 2206 | let wavpack = "the WavPack track of this Matroska file cannot be decoded — AAC, AC-3/E-AC-3, … are; \ |
| 2207 | this file's sound will be silent"; |
| 2208 | assert_eq!(codec_named_in(wavpack).as_deref(), Some("WavPack")); |
| 2209 | assert_eq!(codec_named_in("the DTS track of this Matroska file cannot be decoded: no XLL").as_deref(), Some("DTS")); |
| 2210 | assert_eq!(codec_named_in("the Musepack track of this Matroska file cannot be decoded").as_deref(), Some("Musepack")); |
| 2211 | assert_eq!(codec_named_in("the MP2 track of this Matroska file cannot be decoded").as_deref(), Some("MP2")); |
| 2212 | // A Matroska id still named in a reason falls back to its id. |
| 2213 | assert_eq!(codec_named_in("the A_DTS track of this file cannot be decoded").as_deref(), Some("DTS")); |
| 2214 | assert_eq!(codec_named_in("the A_AC3/ELD track").as_deref(), Some("AC3")); |
| 2215 | // Nothing named at all. |
| 2216 | assert_eq!(codec_named_in("the audio track cannot be decoded"), None); |
| 2217 | assert_eq!(codec_named_in("some other reason"), None); |
| 2218 | } |
| 2219 | |
| 2220 | #[test] |
| 2221 | fn import_cap_folds_successes_and_never_refusals() { |
| 2222 | let mut lines = vec![ImportLine::Imported("a".into())]; |
| 2223 | lines.extend((0..5).map(|i| ImportLine::Imported(format!("s{i}")))); |
| 2224 | lines.insert(2, ImportLine::Note("bad: refused".into())); |
| 2225 | lines.push(ImportLine::Note("warn: x".into())); |
| 2226 | let out = cap_successes(lines, 3); |
| 2227 | assert_eq!(out, vec!["a", "s0", "bad: refused", "s1", "warn: x", "…and 3 more imported"]); |
| 2228 | } |
| 2229 | |
| 2230 | #[test] |
| 2231 | fn a_short_picture_with_a_long_sound_reports_both_streams() { |
| 2232 | quiet(); |
| 2233 | let mut server = Server::new(); |
| 2234 | let probed = probe(&mut server, &json!({"paths": [asset("test_short_video_long_audio.mp4").display().to_string()]})); |
| 2235 | assert!(!probed.is_error, "{}", probed.text); |
| 2236 | assert!(probed.text.contains("2.000 s; audio "), "both lengths named: {}", probed.text); |
| 2237 | assert!(!probed.text.contains("(audio "), "no nested brackets: {}", probed.text); |
| 2238 | let facts = probed.structured.as_ref().unwrap(); |
| 2239 | let row = &facts["files"][0]; |
| 2240 | assert!((row["duration_secs"].as_f64().unwrap() - 2.0).abs() < 0.01, "{row}"); |
| 2241 | assert!(row["audio_duration_secs"].as_f64().unwrap() > 59.0, "{row}"); |
| 2242 | } |
| 2243 | |
| 2244 | #[test] |
| 2245 | fn media_remove_refuses_a_used_source_and_drops_an_unused_one() { |
| 2246 | quiet(); |
| 2247 | let mut server = Server::new(); |
| 2248 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2249 | let used = asset("test_av.mp4"); |
| 2250 | let spare = asset("test_av2.mp4"); |
| 2251 | let session = server.session.as_mut().unwrap(); |
| 2252 | session.import(&used).expect("import the placed file"); |
| 2253 | session.import(&spare).expect("import the spare"); |
| 2254 | assert!(session.place_stream_at(0.0, &used, 0, None).expect("place")); |
| 2255 | // src:0 is the placed file; src:1 is the spare, which nothing plays. |
| 2256 | let refused = remove(&mut server, &json!({"source": "src:0"})); |
| 2257 | assert!(refused.is_error, "{}", refused.text); |
| 2258 | assert!(refused.text.contains("still plays in"), "{}", refused.text); |
| 2259 | assert!(refused.text.contains("V1@"), "names the clip: {}", refused.text); |
| 2260 | assert_eq!(server.session.as_ref().unwrap().sources().len(), 2, "refusal changed nothing"); |
| 2261 | |
| 2262 | let dropped = remove(&mut server, &json!({"source": "src:1"})); |
| 2263 | assert!(!dropped.is_error, "{}", dropped.text); |
| 2264 | assert_eq!(server.session.as_ref().unwrap().sources().len(), 1); |
| 2265 | assert_eq!(server.saved_depth, None, "a removal leaves the project unsaved"); |
| 2266 | assert!(server.ledger.is_empty()); |
| 2267 | let bad = remove(&mut server, &json!({"source": "src:9"})); |
| 2268 | assert!(bad.is_error && bad.text.contains("there is no src:9"), "{}", bad.text); |
| 2269 | } |
| 2270 | |
| 2271 | #[test] |
| 2272 | fn a_still_is_a_picture_in_the_probe_and_the_list() { |
| 2273 | quiet(); |
| 2274 | let dir = scratch_dir("still-label"); |
| 2275 | let still = dir.join("still.png"); |
| 2276 | std::fs::copy(asset("test_still.png"), &still).unwrap(); |
| 2277 | let probed = probe(&mut Server::new(), &json!({"paths": [still.display().to_string()]})); |
| 2278 | assert!(probed.text.contains("still image"), "{}", probed.text); |
| 2279 | assert!(!probed.text.contains("no picture"), "{}", probed.text); |
| 2280 | let mut server = Server::new(); |
| 2281 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2282 | assert!(!import(&mut server, &json!({"paths": [still.display().to_string()]})).is_error); |
| 2283 | let listed = list(&mut server, &json!({})); |
| 2284 | assert!(listed.text.contains("still image"), "{}", listed.text); |
| 2285 | assert!(!listed.text.contains("audio only"), "{}", listed.text); |
| 2286 | } |
| 2287 | |
| 2288 | #[test] |
| 2289 | fn a_device_is_not_a_regular_file_and_a_refused_import_says_nothing_came_in() { |
| 2290 | quiet(); |
| 2291 | let dir = scratch_dir("refused-import"); |
| 2292 | let junk = dir.join("junk.mp4"); |
| 2293 | std::fs::write(&junk, b"not a movie at all").unwrap(); |
| 2294 | let mut server = Server::new(); |
| 2295 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2296 | let dev = import(&mut server, &json!({"paths": ["/dev/zero", "/dev/null"]})); |
| 2297 | assert!(dev.is_error, "{}", dev.text); |
| 2298 | assert!(dev.text.contains("is not a regular file: /dev/zero"), "{}", dev.text); |
| 2299 | assert!(!dev.text.contains("is a directory"), "{}", dev.text); |
| 2300 | assert!(dev.text.contains("nothing was imported"), "{}", dev.text); |
| 2301 | let probed = probe(&mut server, &json!({"paths": ["/dev/null"]})); |
| 2302 | assert!(probed.text.contains("is not a regular file: /dev/null"), "{}", probed.text); |
| 2303 | |
| 2304 | let refused = import(&mut server, &json!({"paths": [junk.display().to_string()]})); |
| 2305 | assert!(refused.is_error, "{}", refused.text); |
| 2306 | assert!(refused.text.contains("nothing was imported"), "{}", refused.text); |
| 2307 | let listed = list(&mut server, &json!({})); |
| 2308 | assert!(listed.text.contains("no sources"), "{}", listed.text); |
| 2309 | assert_eq!(listed.structured.as_ref().unwrap()["sources"], json!([])); |
| 2310 | } |
| 2311 | |
| 2312 | #[test] |
| 2313 | fn wildcard_sets_match_one_character() { |
| 2314 | assert!(wild("clip[0-9].mp4", "clip7.mp4")); |
| 2315 | assert!(!wild("clip[0-9].mp4", "clipa.mp4")); |
| 2316 | assert!(wild("clip[!0-9].mp4", "clipa.mp4")); |
| 2317 | assert!(!wild("clip[!0-9].mp4", "clip7.mp4")); |
| 2318 | assert!(wild("[ab]*", "beta")); |
| 2319 | assert!(!wild("[ab]*", "gamma")); |
| 2320 | assert!(wild("odd[", "odd["), "an unclosed [ is a plain character"); |
| 2321 | } |
| 2322 | |
| 2323 | #[test] |
| 2324 | fn paths_accepts_one_string_and_names_an_empty_list() { |
| 2325 | quiet(); |
| 2326 | let dir = scratch_dir("string-paths"); |
| 2327 | for name in ["clip1.mp4", "clip2.mp4"] { |
| 2328 | std::fs::copy(asset("test_av.mp4"), dir.join(name)).unwrap(); |
| 2329 | } |
| 2330 | let single = asset("test_av.mp4").display().to_string(); |
| 2331 | let mut server = Server::new(); |
| 2332 | let probed = probe(&mut server, &json!({"paths": single})); |
| 2333 | assert!(!probed.is_error, "{}", probed.text); |
| 2334 | assert!(probed.text.contains("test_av.mp4"), "{}", probed.text); |
| 2335 | |
| 2336 | let glob = format!("{}/clip[12].mp4", dir.display()); |
| 2337 | assert_eq!(gather(&json!({"paths": glob}), true).ok().map(|v| v.len()), Some(2), "a string with a glob expands"); |
| 2338 | assert_eq!(gather(&json!({"paths": [glob]}), true).ok().map(|v| v.len()), Some(2)); |
| 2339 | |
| 2340 | let empty = probe(&mut server, &json!({"paths": []})); |
| 2341 | assert!(empty.is_error); |
| 2342 | assert!(empty.text.contains("is empty"), "{}", empty.text); |
| 2343 | let blank = import(&mut server, &json!({"paths": " "})); |
| 2344 | assert!(blank.is_error && blank.text.contains("is empty"), "{}", blank.text); |
| 2345 | assert!(probe(&mut server, &json!({})).text.contains("give `paths` or `glob`")); |
| 2346 | } |
| 2347 | |
| 2348 | /// A blank language tag reads `und`, as a missing one does: test_qt.mov's sound has an empty tag. |
| 2349 | #[test] |
| 2350 | fn blank_language_reads_und() { |
| 2351 | assert_eq!(language_of(Some(""), ""), "und"); |
| 2352 | assert_eq!(language_of(Some(" "), ""), "und"); |
| 2353 | assert_eq!(language_of(None, ""), "und"); |
| 2354 | assert_eq!(language_of(Some("\u{7f}\u{7f}\u{7f}"), ""), "und", "an unset mdhd language"); |
| 2355 | assert_eq!(language_of(Some("\u{7f}\u{7f}\u{7f}"), "eng"), "eng"); |
| 2356 | assert_eq!(language_of(Some(""), "eng"), "eng", "a blank tag falls back to the walk's language"); |
| 2357 | assert_eq!(language_of(Some(" fra "), "eng"), "fra"); |
| 2358 | |
| 2359 | let qt = asset("test_qt.mov"); |
| 2360 | let streams = other_streams(&qt, &engine::probe_media(&qt)); |
| 2361 | let text: Vec<String> = streams.iter().map(stream_text).collect(); |
| 2362 | assert_eq!(text, vec!["audio track 0 aac (und) stereo, 44.1 kHz"], "{text:?}"); |
| 2363 | } |
| 2364 | |
| 2365 | /// A track's layout and rate are named where the header states them, and the surround |
| 2366 | /// note is given once per track of more than two channels, in media_probe only. |
| 2367 | #[test] |
| 2368 | fn channels_and_rate_are_listed_and_surround_is_noted_as_mixed() { |
| 2369 | let surround = asset("test_ac3_51.mp4"); |
| 2370 | let streams = other_streams(&surround, &engine::probe_media(&surround)); |
| 2371 | let text: Vec<String> = streams.iter().filter(|s| s.kind == "audio").map(stream_text).collect(); |
| 2372 | assert_eq!(text, vec!["audio track 0 ac3 (und) 5.1, 48 kHz"], "{text:?}"); |
| 2373 | assert_eq!( |
| 2374 | surround_notes(&streams), |
| 2375 | vec!["note: audio track 0 is 5.1; mixed to stereo on export"] |
| 2376 | ); |
| 2377 | let row = probe_one(&surround); |
| 2378 | assert!(row_line(&row).contains("\n note: audio track 0 is 5.1; mixed to stereo on export"), "{}", row_line(&row)); |
| 2379 | |
| 2380 | let stereo = asset("test_multilang.mp4"); |
| 2381 | let streams = other_streams(&stereo, &engine::probe_media(&stereo)); |
| 2382 | assert!(surround_notes(&streams).is_empty(), "stereo gets no note"); |
| 2383 | assert!(!row_line(&probe_one(&stereo)).contains("mixed to stereo")); |
| 2384 | } |
| 2385 | |
| 2386 | /// Two sources of one file read apart: a source on track 1 says which track and language. |
| 2387 | #[test] |
| 2388 | fn media_list_names_a_non_default_audio_track() { |
| 2389 | let path = asset("test_multilang.mp4"); |
| 2390 | let facts = engine::probe_media(&path); |
| 2391 | assert_eq!(audio_choice_text(&facts, 0), "", "track 0 is the default and says nothing"); |
| 2392 | assert_eq!(audio_choice_text(&facts, 1), " · audio 1 (fra)"); |
| 2393 | } |
| 2394 | |
| 2395 | /// media_list kind keeps one kind of source, says so when there is none, and refuses any other word. |
| 2396 | #[test] |
| 2397 | fn media_list_kind_keeps_one_kind_and_refuses_the_rest() { |
| 2398 | quiet(); |
| 2399 | let mut server = Server::new(); |
| 2400 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2401 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 2402 | let video = list(&mut server, &json!({"kind": "video"})); |
| 2403 | assert!(!video.is_error && video.text.contains("test_av"), "{}", video.text); |
| 2404 | let image = list(&mut server, &json!({"kind": "image"})); |
| 2405 | assert!(!image.is_error && image.text.contains("no image sources"), "{}", image.text); |
| 2406 | let movie = list(&mut server, &json!({"kind": "movie"})); |
| 2407 | assert!(movie.is_error && movie.text.contains("video, audio or image"), "{}", movie.text); |
| 2408 | } |
| 2409 | |
| 2410 | /// Bins and favourites: made, filed, starred, listed, refused by name, and one undo step each. |
| 2411 | #[test] |
| 2412 | fn media_bin_files_and_stars_sources_and_media_list_shows_it() { |
| 2413 | quiet(); |
| 2414 | let mut server = Server::new(); |
| 2415 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2416 | let s = server.session.as_mut().unwrap(); |
| 2417 | s.import(&asset("test_av.mp4")).expect("import"); |
| 2418 | s.import(&asset("test_av2.mp4")).expect("import"); |
| 2419 | let made = bin(&mut server, &json!({"action": "create", "name": "Interviews"})); |
| 2420 | assert!(!made.is_error, "{}", made.text); |
| 2421 | assert!(made.text.contains("bin:1 Interviews created") && made.text.contains("undo takes it back"), "{}", made.text); |
| 2422 | let inner = bin(&mut server, &json!({"action": "create", "name": "Day 1", "parent": "interviews"})); |
| 2423 | assert!(inner.text.contains("Interviews/Day 1"), "{}", inner.text); |
| 2424 | let twin = bin(&mut server, &json!({"action": "create", "name": "INTERVIEWS"})); |
| 2425 | assert!(twin.is_error && twin.text.contains("already a bin"), "{}", twin.text); |
| 2426 | let moved = bin(&mut server, &json!({"action": "move", "sources": ["src:1"], "bin": "Interviews/Day 1"})); |
| 2427 | assert!(moved.text.contains("1 source moved into bin:2"), "{}", moved.text); |
| 2428 | let starred = bin(&mut server, &json!({"action": "favourite", "sources": "all"})); |
| 2429 | assert!(starred.text.contains("2 sources starred"), "{}", starred.text); |
| 2430 | let again = bin(&mut server, &json!({"action": "favourite", "sources": "src:0"})); |
| 2431 | assert!(again.text.contains("nothing changed"), "{}", again.text); |
| 2432 | let listed = list(&mut server, &json!({})); |
| 2433 | assert!(listed.text.contains("bin:2 Interviews/Day 1 · 1 source"), "{}", listed.text); |
| 2434 | assert!(listed.text.contains("in bin:2 Interviews/Day 1 · favourite"), "{}", listed.text); |
| 2435 | let bad = bin(&mut server, &json!({"action": "move", "sources": "src:9", "bin": 1})); |
| 2436 | assert!(bad.is_error && bad.text.contains("no src:9"), "{}", bad.text); |
| 2437 | let gone = bin(&mut server, &json!({"action": "remove", "bin": "bin:1"})); |
| 2438 | assert!(gone.text.contains("removed; 0 sources moved up"), "{}", gone.text); |
| 2439 | let s = server.session.as_ref().unwrap(); |
| 2440 | assert_eq!(s.bins().len(), 1); |
| 2441 | assert_eq!(s.bins()[0].parent, 0); |
| 2442 | let s = server.session.as_mut().unwrap(); |
| 2443 | assert!(s.undo(), "the removal undoes"); |
| 2444 | assert_eq!(s.bins().len(), 2); |
| 2445 | } |
| 2446 | |
| 2447 | /// Removing the last unused source keeps the undo history; a source before others clears it. |
| 2448 | #[test] |
| 2449 | fn media_remove_keeps_undo_for_the_last_unused_source() { |
| 2450 | quiet(); |
| 2451 | let mut server = Server::new(); |
| 2452 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2453 | let used = asset("test_av.mp4"); |
| 2454 | let spare = asset("test_av2.mp4"); |
| 2455 | let session = server.session.as_mut().unwrap(); |
| 2456 | session.import(&used).expect("import the placed file"); |
| 2457 | session.import(&spare).expect("import the spare"); |
| 2458 | assert!(session.place_stream_at(0.0, &used, 0, None).expect("place")); |
| 2459 | let depth = session.undo_depth(); |
| 2460 | assert!(depth > 0, "placing pushed an undo step"); |
| 2461 | |
| 2462 | let dropped = remove(&mut server, &json!({"source": "src:1"})); |
| 2463 | assert!(!dropped.is_error, "{}", dropped.text); |
| 2464 | assert!(dropped.text.contains("undo history is kept"), "{}", dropped.text); |
| 2465 | let session = server.session.as_mut().unwrap(); |
| 2466 | assert_eq!(session.sources().len(), 1); |
| 2467 | assert_eq!(session.undo_depth(), depth, "the undo steps are still there"); |
| 2468 | assert!(session.undo(), "undo still works after the removal"); |
| 2469 | } |
| 2470 | |
| 2471 | #[test] |
| 2472 | fn media_remove_of_a_source_before_others_says_history_is_cleared() { |
| 2473 | quiet(); |
| 2474 | let mut server = Server::new(); |
| 2475 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2476 | let session = server.session.as_mut().unwrap(); |
| 2477 | // src:0 plays nothing; src:1 is placed, which is an undo step. |
| 2478 | session.import(&asset("test_av2.mp4")).expect("import the spare"); |
| 2479 | session.import(&asset("test_av.mp4")).expect("import the placed file"); |
| 2480 | assert!(session.place_stream_at(0.0, &asset("test_av.mp4"), 0, None).expect("place")); |
| 2481 | let depth = session.undo_depth(); |
| 2482 | assert!(depth > 0, "placing pushed an undo step"); |
| 2483 | // Refused without force: the reply says why and changes nothing. |
| 2484 | let refused = remove(&mut server, &json!({"source": "src:0"})); |
| 2485 | assert!(refused.is_error, "{}", refused.text); |
| 2486 | assert!(refused.text.contains("renumbers src:1"), "{}", refused.text); |
| 2487 | assert!(refused.text.contains("undo history is cleared"), "{}", refused.text); |
| 2488 | assert!(refused.text.contains("force:true"), "{}", refused.text); |
| 2489 | let session = server.session.as_ref().unwrap(); |
| 2490 | assert_eq!(session.sources().len(), 2); |
| 2491 | assert_eq!(session.undo_depth(), depth, "the undo steps are still there"); |
| 2492 | // With force the removal goes ahead and says the history was cleared. |
| 2493 | let dropped = remove(&mut server, &json!({"source": "src:0", "force": true})); |
| 2494 | assert!(!dropped.is_error, "{}", dropped.text); |
| 2495 | assert!(dropped.text.contains("Undo history is cleared"), "{}", dropped.text); |
| 2496 | assert_eq!(server.session.as_ref().unwrap().sources().len(), 1); |
| 2497 | } |
| 2498 | |
| 2499 | /// The empty-list refusal names only arguments media_import has. |
| 2500 | #[test] |
| 2501 | fn import_refusal_names_no_glob_argument() { |
| 2502 | quiet(); |
| 2503 | let mut server = Server::new(); |
| 2504 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2505 | let empty = import(&mut server, &json!({"paths": []})); |
| 2506 | assert!(empty.is_error); |
| 2507 | assert!(!empty.text.contains("`glob`"), "{}", empty.text); |
| 2508 | assert!(empty.text.contains("pattern such as ~/clips/*.mp4 inside it"), "{}", empty.text); |
| 2509 | let none = import(&mut server, &json!({})); |
| 2510 | assert!(!none.text.contains("`glob`"), "{}", none.text); |
| 2511 | assert!(none.text.contains("give `paths`:"), "{}", none.text); |
| 2512 | } |
| 2513 | } |
| 2514 | |
| 2515 | #[cfg(test)] |
| 2516 | mod agreement_tests { |
| 2517 | use super::*; |
| 2518 | use crate::testutil::TestDir; |
| 2519 | use engine::PlaybackSession; |
| 2520 | |
| 2521 | fn asset(name: &str) -> PathBuf { |
| 2522 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 2523 | } |
| 2524 | |
| 2525 | fn quiet() { |
| 2526 | engine::ao::set_silent_output(); |
| 2527 | } |
| 2528 | |
| 2529 | /// A truncated file is refused by `media_probe` in the same words `media_import` refuses it |
| 2530 | /// Probe and import give the same plain sentence for a truncated file: the name, that it may be |
| 2531 | /// truncated or not an MP4, the engine's detail, and the next step. |
| 2532 | #[test] |
| 2533 | fn a_truncated_file_gets_the_same_refusal_from_probe_and_import() { |
| 2534 | quiet(); |
| 2535 | let td = TestDir::new("probe-import-agree"); |
| 2536 | let full = std::fs::read(asset("test_av.mp4")).expect("read the fixture"); |
| 2537 | let cut = td.path().join("cut.mp4"); |
| 2538 | std::fs::write(&cut, &full[..full.len().min(4000)]).expect("write the truncated copy"); |
| 2539 | let probe = row_line(&probe_one(&cut)); |
| 2540 | let want = "cut.mp4 looks truncated or is not a valid MP4 ("; |
| 2541 | assert!(probe.contains(want) && probe.contains("re-copy or re-export"), "{probe}"); |
| 2542 | assert!(!probe.contains("refused: file contains"), "{probe}"); |
| 2543 | let mut server = Server::new(); |
| 2544 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2545 | let imported = import(&mut server, &json!({"paths": [cut.display().to_string()]})); |
| 2546 | assert!(imported.is_error, "{}", imported.text); |
| 2547 | assert!(imported.text.contains(want) && imported.text.contains("re-copy or re-export"), "{}", imported.text); |
| 2548 | } |
| 2549 | |
| 2550 | /// A text file renamed .mp4 and a zero-byte .mp4 each get their plain sentence, not the engine's. |
| 2551 | /// A subtitle file is named as one, with the tool that imports it, not as a truncated MP4, by |
| 2552 | /// both the probe and the import. |
| 2553 | #[test] |
| 2554 | fn a_subtitle_file_is_named_and_not_called_truncated() { |
| 2555 | quiet(); |
| 2556 | let td = TestDir::new("subtitle-file"); |
| 2557 | let srt = td.path().join("cues.srt"); |
| 2558 | std::fs::write(&srt, "1\n00:00:00,000 --> 00:00:01,000\nhello\n").expect("write the srt"); |
| 2559 | let line = row_line(&probe_one(&srt)); |
| 2560 | assert!(line.contains("cues.srt is a subtitle file: import it with subtitles_import"), "{line}"); |
| 2561 | assert!(!line.contains("truncated"), "{line}"); |
| 2562 | let mut server = Server::new(); |
| 2563 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2564 | let r = import(&mut server, &json!({"paths": [srt.display().to_string()]})); |
| 2565 | assert!(r.text.contains("cues.srt is a subtitle file: import it with subtitles_import"), "{}", r.text); |
| 2566 | assert!(!r.text.contains("truncated"), "{}", r.text); |
| 2567 | } |
| 2568 | |
| 2569 | /// One frame of a numbered PNG run imports the whole run as one clip, reported as an image |
| 2570 | /// sequence of its frames, not as a file of its own. |
| 2571 | #[test] |
| 2572 | fn a_numbered_png_run_imports_as_one_image_sequence() { |
| 2573 | quiet(); |
| 2574 | let td = TestDir::new("png-run-import"); |
| 2575 | let still = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../engine/tests/fixtures/fuzz/still.png")).expect("read the still"); |
| 2576 | for k in 1..=200 { |
| 2577 | std::fs::write(td.path().join(format!("frame_{k:04}.png")), &still).expect("write a frame"); |
| 2578 | } |
| 2579 | let mut server = Server::new(); |
| 2580 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2581 | let one = td.path().join("frame_0004.png"); |
| 2582 | let r = import(&mut server, &json!({"paths": [one.display().to_string()]})); |
| 2583 | assert!(!r.is_error, "{}", r.text); |
| 2584 | assert!(r.text.contains("image sequence, 200 frames"), "{}", r.text); |
| 2585 | assert!(r.text.contains("frame_[0001-0200].png"), "{}", r.text); |
| 2586 | let r = super::super::edit::run_edit(&mut server, &json!({"ops": [{"op": "append", "source": "src:0"}]})); |
| 2587 | assert!(!r.is_error && r.text.contains("(sequence)"), "{}", r.text); |
| 2588 | assert_eq!(server.session.as_ref().unwrap().lane_clips(engine::project::Lane::V1)[0].frames(), 200, "{}", r.text); |
| 2589 | } |
| 2590 | |
| 2591 | #[test] |
| 2592 | fn a_text_file_named_mp4_looks_truncated_and_an_empty_file_is_empty() { |
| 2593 | quiet(); |
| 2594 | let td = TestDir::new("corrupt-plain"); |
| 2595 | let text = td.path().join("notes.mp4"); |
| 2596 | std::fs::write(&text, "this is plain text, not a video\n").expect("write the text file"); |
| 2597 | let empty = td.path().join("blank.mp4"); |
| 2598 | std::fs::write(&empty, b"").expect("write the empty file"); |
| 2599 | let text_line = row_line(&probe_one(&text)); |
| 2600 | assert!(text_line.contains("notes.mp4 looks truncated or is not a valid MP4 ("), "{text_line}"); |
| 2601 | let empty_line = row_line(&probe_one(&empty)); |
| 2602 | assert!(empty_line.contains("blank.mp4 is empty (0 bytes)"), "{empty_line}"); |
| 2603 | assert!(!empty_line.contains("ftyp"), "{empty_line}"); |
| 2604 | let mut server = Server::new(); |
| 2605 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2606 | let r = import(&mut server, &json!({"paths": [empty.display().to_string()]})); |
| 2607 | assert!(r.text.contains("blank.mp4 is empty (0 bytes)"), "{}", r.text); |
| 2608 | assert!(server.session.as_ref().unwrap().sources().is_empty()); |
| 2609 | } |
| 2610 | |
| 2611 | /// Range-extensions HEVC (4:4:4, 4:0:0, 12-bit) is carried by the software seat, so the probe |
| 2612 | /// refuses nothing and states the real chroma format and depth, as it does for other codecs. |
| 2613 | #[test] |
| 2614 | fn range_extensions_hevc_probes_clean_with_its_real_chroma_and_depth() { |
| 2615 | quiet(); |
| 2616 | let td = TestDir::new("rext-hevc-probe"); |
| 2617 | for (pix, chroma, depth) in [ |
| 2618 | ("yuv444p", "4:4:4", 8), |
| 2619 | ("yuv444p10le", "4:4:4", 10), |
| 2620 | ("yuv422p12le", "4:2:2", 12), |
| 2621 | ("gray", "gray", 8), |
| 2622 | ] { |
| 2623 | let clip = td.path().join(format!("rext_{pix}.mp4")); |
| 2624 | let out = std::process::Command::new("ffmpeg") |
| 2625 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x64:rate=30:duration=0.1"]) |
| 2626 | .args(["-frames:v", "3", "-c:v", "libx265", "-pix_fmt", pix, "-x265-params", "log-level=error"]) |
| 2627 | .arg(&clip) |
| 2628 | .output() |
| 2629 | .expect("ffmpeg runs"); |
| 2630 | assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); |
| 2631 | let row = probe_one(&clip); |
| 2632 | assert_eq!(row.error, None, "{pix}"); |
| 2633 | let json = row_json(&row); |
| 2634 | assert_eq!(json["chroma"], json!(chroma), "{pix}"); |
| 2635 | assert_eq!(json["bit_depth"], json!(depth), "{pix}: {json}"); |
| 2636 | } |
| 2637 | } |
| 2638 | |
| 2639 | #[test] |
| 2640 | fn the_picture_line_names_depth_chroma_and_colour_only_where_known() { |
| 2641 | let hdr = row_line(&probe_one(&asset("test_pq.mp4"))); |
| 2642 | assert!(hdr.contains("\n picture: 4:2:0 · BT.2020 PQ (HDR: exports tone-mapped to 8-bit SDR)"), "{hdr}"); |
| 2643 | let ten = row_line(&probe_one(&asset("test_hevc10.mkv"))); |
| 2644 | assert!(ten.contains("\n picture: 10-bit 4:2:0 · BT.709 (assumed, untagged)"), "{ten}"); |
| 2645 | assert_eq!(row_json(&probe_one(&asset("test_hevc10.mkv")))["chroma"], json!("4:2:0")); |
| 2646 | // Every codec names its chroma now, monochrome included: AV1 gray has no chroma plane. |
| 2647 | let gray = row_line(&probe_one(&asset("test_av1_gray.mkv"))); |
| 2648 | assert!(gray.contains("\n picture: 8-bit gray · BT.601 (assumed, untagged) full range"), "{gray}"); |
| 2649 | assert_eq!(row_json(&probe_one(&asset("test_av1_gray.mkv")))["chroma"], json!("gray")); |
| 2650 | let vp9 = row_line(&probe_one(&asset("test_vp9_10.webm"))); |
| 2651 | assert!(vp9.contains("\n picture: 10-bit 4:2:0 "), "{vp9}"); |
| 2652 | } |
| 2653 | |
| 2654 | #[test] |
| 2655 | fn a_song_with_cover_art_says_so_and_has_no_picture_track() { |
| 2656 | quiet(); |
| 2657 | // An mp3 whose ID3 APIC frame carries the picture: the probe names it, and no picture track. |
| 2658 | let probed = probe_one(&asset("test_tone_cover.mpeg")); |
| 2659 | let line = row_line(&probed); |
| 2660 | assert!(line.contains("cover art only (not a picture track)"), "{line}"); |
| 2661 | assert!(!line.contains("no picture") && !line.contains("cover art attached"), "{line}"); |
| 2662 | } |
| 2663 | |
| 2664 | #[test] |
| 2665 | fn cover_art_beside_a_picture_track_is_said_after_the_picture() { |
| 2666 | quiet(); |
| 2667 | // A picture track with a cover attached as a Matroska image attachment. |
| 2668 | let td = crate::testutil::TestDir::new("cover-and-picture"); |
| 2669 | let mkv = td.path().join("cover.mkv"); |
| 2670 | let out = std::process::Command::new("ffmpeg") |
| 2671 | .args(["-v", "error", "-y", "-t", "1", "-i"]) |
| 2672 | .arg(asset("test_25fps.mp4")) |
| 2673 | .arg("-attach") |
| 2674 | .arg(asset("test_tone_cover.jpg")) |
| 2675 | .args(["-metadata:s:t", "mimetype=image/jpeg", "-c", "copy"]) |
| 2676 | .arg(&mkv) |
| 2677 | .output() |
| 2678 | .expect("ffmpeg runs"); |
| 2679 | assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); |
| 2680 | let line = row_line(&probe_one(&mkv)); |
| 2681 | assert!(line.contains("H.264") && line.contains("· cover art attached ·"), "{line}"); |
| 2682 | assert!(!line.contains("cover art only") && !line.contains("no picture"), "{line}"); |
| 2683 | } |
| 2684 | |
| 2685 | #[test] |
| 2686 | fn a_still_says_its_size_and_a_cover_jpeg_is_no_different() { |
| 2687 | assert!(row_line(&probe_one(&asset("test_still.png"))).contains("still image 640x360 · still")); |
| 2688 | assert!(row_line(&probe_one(&asset("test_tone_cover.jpg"))).contains("still image 64x64 · still")); |
| 2689 | assert_eq!(row_json(&probe_one(&asset("test_still.png")))["still_width"], json!(640)); |
| 2690 | } |
| 2691 | |
| 2692 | #[test] |
| 2693 | fn an_edith_project_is_named_as_one_in_probe_and_import() { |
| 2694 | quiet(); |
| 2695 | // A real project, saved by the tools into the test's own dir, so no fixture is needed on disk. |
| 2696 | let td = TestDir::new("edith-project"); |
| 2697 | let project = td.path().join("test_h264.edith"); |
| 2698 | let tools = crate::server::tools(); |
| 2699 | let mut maker = Server::new(); |
| 2700 | let mut run = |name: &str, args: Value| { |
| 2701 | let tool = tools.iter().find(|t| t.name == name).expect("tool"); |
| 2702 | (tool.run)(&mut maker, &args) |
| 2703 | }; |
| 2704 | assert!(!run("project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 2705 | let media = vec![asset("test_h264.mkv").display().to_string()]; |
| 2706 | assert!(!run("media_import", json!({"paths": media})).is_error); |
| 2707 | let saved = run("project_save", json!({})); |
| 2708 | assert!(!saved.is_error, "{}", saved.text); |
| 2709 | let path_arg = json!({"paths": [project.display().to_string()]}); |
| 2710 | |
| 2711 | let row = probe_one(&project); |
| 2712 | let line = row_line(&row); |
| 2713 | assert_eq!(line, "test_h264.edith · an edith project (open it with project_open)"); |
| 2714 | assert!(!line.contains("error"), "{line}"); |
| 2715 | assert!(!line.contains("truncated"), "{line}"); |
| 2716 | // Not a failed probe: the reply is not an error, and the row carries no error. |
| 2717 | let probed = probe(&mut Server::new(), &path_arg); |
| 2718 | assert!(!probed.is_error, "{}", probed.text); |
| 2719 | assert_eq!(probed.text, line); |
| 2720 | assert_eq!(row_json(&row)["error"], json!(null)); |
| 2721 | let mut server = Server::new(); |
| 2722 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2723 | let imported = import(&mut server, &path_arg); |
| 2724 | assert!(imported.is_error, "{}", imported.text); |
| 2725 | assert!( |
| 2726 | imported.text.contains("test_h264.edith is an edith project, not media: open it with project_open"), |
| 2727 | "{}", |
| 2728 | imported.text |
| 2729 | ); |
| 2730 | drop(td); |
| 2731 | } |
| 2732 | |
| 2733 | #[test] |
| 2734 | fn an_anamorphic_picture_names_its_coded_size_and_pixel_aspect() { |
| 2735 | let line = row_line(&probe_one(&asset("test_anamorphic.mp4"))); |
| 2736 | assert!(line.contains("1440x1080 (shown 1920x1080, pixel aspect 4:3)"), "{line}"); |
| 2737 | let row = probe_one(&asset("test_anamorphic.mkv")); |
| 2738 | assert!(row_line(&row).contains("1440x1080 (shown 1920x1080, pixel aspect 4:3)")); |
| 2739 | assert_eq!(row_json(&row)["coded_width"], json!(1440)); |
| 2740 | } |
| 2741 | |
| 2742 | #[test] |
| 2743 | fn square_pixels_show_the_size_alone() { |
| 2744 | let square = Coded { w: 1920, h: 1080, sar: (1, 1), turn: engine::demux::Rotation::None, colour: engine::colorspace::ColorDescription::default(), chroma: None }; |
| 2745 | assert_eq!(square.text((1920, 1080)), None); |
| 2746 | let unstated = Coded { w: 1920, h: 1080, sar: (0, 0), turn: engine::demux::Rotation::None, colour: engine::colorspace::ColorDescription::default(), chroma: None }; |
| 2747 | assert_eq!(unstated.text((1920, 1080)), None); |
| 2748 | let ratio = Coded { w: 1440, h: 1080, sar: (16, 12), turn: engine::demux::Rotation::None, colour: engine::colorspace::ColorDescription::default(), chroma: None }; |
| 2749 | assert_eq!(ratio.text((1920, 1080)).as_deref(), Some("1440x1080 (shown 1920x1080, pixel aspect 4:3)")); |
| 2750 | } |
| 2751 | |
| 2752 | /// A turned picture shows its displayed size and says what is stored and how far it turns. |
| 2753 | #[test] |
| 2754 | fn a_rotated_picture_says_how_it_is_stored() { |
| 2755 | quiet(); |
| 2756 | let tall = row_line(&probe_one(&asset("test_rotation90tall.mp4"))); |
| 2757 | assert!(tall.contains("640x1280 (stored 1280x640, turned 90° counter-clockwise to stand upright; ffprobe rotation 90)"), "{tall}"); |
| 2758 | let upright = row_line(&probe_one(&asset("test_av.mp4"))); |
| 2759 | assert!(!upright.contains("turned"), "{upright}"); |
| 2760 | } |
| 2761 | |
| 2762 | /// Each turn says the way edith turns the picture and ffprobe's `rotation` for the same file. |
| 2763 | #[test] |
| 2764 | fn turn_text_names_the_turn_and_ffprobes_tag() { |
| 2765 | let turned = |turn| Coded { w: 320, h: 180, sar: (1, 1), turn, colour: engine::colorspace::ColorDescription::default(), chroma: None }; |
| 2766 | use engine::demux::Rotation; |
| 2767 | assert_eq!(turned(Rotation::None).turn_text(), None); |
| 2768 | assert_eq!(turned(Rotation::Cw90).turn_text().as_deref(), Some("(stored 320x180, turned 90° clockwise to stand upright; ffprobe rotation -90)")); |
| 2769 | assert_eq!(turned(Rotation::Cw180).turn_text().as_deref(), Some("(stored 320x180, turned 180° to stand upright; ffprobe rotation 180)")); |
| 2770 | assert_eq!(turned(Rotation::Cw270).turn_text().as_deref(), Some("(stored 320x180, turned 90° counter-clockwise to stand upright; ffprobe rotation 90)")); |
| 2771 | } |
| 2772 | |
| 2773 | /// The AAC profile follows the codec in the stream phrase, and the JSON row carries it beside the codec. |
| 2774 | #[test] |
| 2775 | fn the_aac_profile_follows_the_codec() { |
| 2776 | let mut st = Stream { kind: "audio", index: 0, track: None, codec: Some("aac".into()), codec_id: Some("mp4a".into()), profile: Some("HE-AACv2".into()), bit_depth: None, language: "und".into(), channels: Some(2), sample_rate: Some(22050), name: String::new() }; |
| 2777 | assert_eq!(stream_text(&st), "audio track 0 aac HE-AACv2 (und) stereo, 22.05 kHz"); |
| 2778 | assert_eq!(stream_json(&st)["profile"], "HE-AACv2"); |
| 2779 | st.profile = None; |
| 2780 | assert_eq!(stream_text(&st), "audio track 0 aac (und) stereo, 22.05 kHz"); |
| 2781 | assert!(stream_json(&st)["profile"].is_null()); |
| 2782 | } |
| 2783 | |
| 2784 | /// The fixtures the engine reads an AAC profile from: LC and HE-AAC v1 made here, HE-AACv2 from |
| 2785 | /// edith_codecs. Each reads as its profile; the edith_codecs file is skipped where the checkout is not. |
| 2786 | #[test] |
| 2787 | fn an_aac_file_reports_its_profile() { |
| 2788 | let v2 = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../edith_codecs/crates/ec-aac/tests/data/he/he_v2_stereo.m4a"); |
| 2789 | if v2.exists() { |
| 2790 | let text: Vec<String> = other_streams(&v2, &engine::probe_media(&v2)).iter().map(stream_text).collect(); |
| 2791 | assert_eq!(text, vec!["audio track 0 aac HE-AACv2 (und) stereo, 22.05 kHz"], "{text:?}"); |
| 2792 | } else { |
| 2793 | eprintln!("skipped: no edith_codecs checkout beside this repo"); |
| 2794 | } |
| 2795 | } |
| 2796 | |
| 2797 | /// A file already on the timeline is not added again: the reply names the source it is. |
| 2798 | #[test] |
| 2799 | fn importing_a_file_twice_says_it_is_already_imported() { |
| 2800 | quiet(); |
| 2801 | let mut server = Server::new(); |
| 2802 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2803 | let file = asset("test_av.mp4").display().to_string(); |
| 2804 | let first = import(&mut server, &json!({"paths": [file.clone()]})); |
| 2805 | assert!(!first.is_error, "{}", first.text); |
| 2806 | let again = import(&mut server, &json!({"paths": [file]})); |
| 2807 | assert!(again.is_error, "{}", again.text); |
| 2808 | assert!(again.text.contains("test_av.mp4 is already imported as src:0"), "{}", again.text); |
| 2809 | assert!(again.text.contains("nothing was imported"), "{}", again.text); |
| 2810 | assert_eq!(server.session.as_ref().unwrap().sources().len(), 1, "no second source"); |
| 2811 | } |
| 2812 | |
| 2813 | /// A file named twice in one call is imported once, and the reply says the repeat was a duplicate. |
| 2814 | #[test] |
| 2815 | fn a_file_listed_twice_in_one_call_is_imported_once_and_said() { |
| 2816 | quiet(); |
| 2817 | let mut server = Server::new(); |
| 2818 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2819 | let file = asset("test_av.mp4").display().to_string(); |
| 2820 | let r = import(&mut server, &json!({"paths": [file.clone(), file]})); |
| 2821 | assert!(!r.is_error, "{}", r.text); |
| 2822 | assert_eq!(server.session.as_ref().unwrap().sources().len(), 1, "one source"); |
| 2823 | assert!( |
| 2824 | r.text.contains("test_av.mp4 is listed twice: the second entry is a duplicate and nothing was added"), |
| 2825 | "{}", |
| 2826 | r.text |
| 2827 | ); |
| 2828 | assert_eq!(r.structured.as_ref().unwrap()["failed"], 0); |
| 2829 | } |
| 2830 | |
| 2831 | /// A non-last source goes without force when no undo step can be lost, and the reply says so. |
| 2832 | #[test] |
| 2833 | fn removing_a_source_with_no_history_renumbers_without_force() { |
| 2834 | quiet(); |
| 2835 | let mut server = Server::new(); |
| 2836 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2837 | let session = server.session.as_mut().unwrap(); |
| 2838 | session.import(&asset("test_av2.mp4")).expect("import"); |
| 2839 | session.import(&asset("test_av.mp4")).expect("import"); |
| 2840 | assert_eq!(session.undo_depth(), 0, "a direct import leaves no undo step"); |
| 2841 | let dropped = remove(&mut server, &json!({"source": "src:0"})); |
| 2842 | assert!(!dropped.is_error, "{}", dropped.text); |
| 2843 | assert!(dropped.text.contains("There was no undo history to clear"), "{}", dropped.text); |
| 2844 | assert!(dropped.text.contains("src:1 test_av.mp4 is now src:0"), "{}", dropped.text); |
| 2845 | assert_eq!(server.session.as_ref().unwrap().sources().len(), 1); |
| 2846 | } |
| 2847 | |
| 2848 | /// The reply names each source whose number moved, and says so when the removed one was last. |
| 2849 | #[test] |
| 2850 | fn media_remove_names_the_sources_it_renumbers() { |
| 2851 | quiet(); |
| 2852 | let mut server = Server::new(); |
| 2853 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 2854 | let session = server.session.as_mut().unwrap(); |
| 2855 | session.import(&asset("test_av2.mp4")).expect("import"); |
| 2856 | session.import(&asset("test_av.mp4")).expect("import"); |
| 2857 | session.import(&asset("test_still.png")).expect("import the still"); |
| 2858 | // Removing the first of three renumbers the other two; the reply names both. |
| 2859 | let first = remove(&mut server, &json!({"source": "src:0"})); |
| 2860 | assert!(!first.is_error, "{}", first.text); |
| 2861 | assert!(first.text.contains("src:1 test_av.mp4 is now src:0"), "{}", first.text); |
| 2862 | assert!(first.text.contains("src:2 test_still.png is now src:1"), "{}", first.text); |
| 2863 | assert!(!first.text.contains("no other source was renumbered"), "{}", first.text); |
| 2864 | // Removing the last one renumbers nothing. |
| 2865 | let last = remove(&mut server, &json!({"source": "src:1"})); |
| 2866 | assert!(!last.is_error, "{}", last.text); |
| 2867 | assert!(last.text.contains("no other source was renumbered"), "{}", last.text); |
| 2868 | assert!(!last.text.contains("is now src:"), "{}", last.text); |
| 2869 | } |
| 2870 | } |
| 2871 | |
| 2872 | #[cfg(test)] |
| 2873 | mod relink_shift_tests { |
| 2874 | use super::*; |
| 2875 | use crate::testutil::TestDir; |
| 2876 | |
| 2877 | fn asset(name: &str) -> PathBuf { |
| 2878 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 2879 | } |
| 2880 | |
| 2881 | fn call(server: &mut Server, name: &str, args: Value) -> Reply { |
| 2882 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 2883 | (t.run)(server, &args) |
| 2884 | } |
| 2885 | |
| 2886 | /// A 25 fps source relinked to a 23.976 fps file of the same length: the rate is named and |
| 2887 | /// the clip on it. The length is under a frame apart, so no length warning. |
| 2888 | #[test] |
| 2889 | fn relink_to_another_frame_rate_names_the_clips_that_may_shift() { |
| 2890 | let td = TestDir::new("relink-shift"); |
| 2891 | let project = td.path().join("shift.edith"); |
| 2892 | let mut server = Server::new(); |
| 2893 | assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 2894 | assert!(!call(&mut server, "media_import", json!({"paths": [asset("test_25fps.mp4")]})).is_error); |
| 2895 | let placed = call(&mut server, "edit", json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": "0s"}]})); |
| 2896 | assert!(!placed.is_error, "{}", placed.text); |
| 2897 | let r = call(&mut server, "media_relink", json!({"source": "src:0", "path": asset("test_23976fps.mp4")})); |
| 2898 | assert!(!r.is_error, "{}", r.text); |
| 2899 | assert!(r.text.contains("23.976 fps against the 25 fps file it replaces"), "{}", r.text); |
| 2900 | assert!(r.text.contains("V1@0"), "{}", r.text); |
| 2901 | assert!(!r.text.contains("long against"), "a length under a frame is not warned: {}", r.text); |
| 2902 | } |
| 2903 | |
| 2904 | /// A relink is one undo step: the reply says undo takes it back, the ledger holds one entry for |
| 2905 | /// it, undo points the source at the old file again and redo points it at the new one. |
| 2906 | #[test] |
| 2907 | fn a_relink_is_one_undo_step_that_undo_and_redo_walk() { |
| 2908 | let td = TestDir::new("relink-undo"); |
| 2909 | let project = td.path().join("undo.edith"); |
| 2910 | let mut server = Server::new(); |
| 2911 | assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 2912 | assert!(!call(&mut server, "media_import", json!({"paths": [asset("test_av.mp4")]})).is_error); |
| 2913 | let old = server.session.as_ref().unwrap().sources()[0].path.clone(); |
| 2914 | let ledger = server.ledger.len(); |
| 2915 | let copy = td.path().join("moved.mp4"); |
| 2916 | std::fs::copy(asset("test_av.mp4"), ©).expect("a copy of the asset"); |
| 2917 | let new = std::fs::canonicalize(©).expect("the copy"); |
| 2918 | let r = call(&mut server, "media_relink", json!({"source": "src:0", "path": copy})); |
| 2919 | assert!(!r.is_error, "{}", r.text); |
| 2920 | assert!(r.text.contains("undo takes it back"), "{}", r.text); |
| 2921 | assert_eq!(server.ledger.len(), ledger + 1, "one entry for the relink"); |
| 2922 | let entry = server.ledger.last().expect("the entry"); |
| 2923 | assert_eq!(entry.steps, 1, "one engine step"); |
| 2924 | assert!(entry.label.starts_with("media_relink src:0"), "{}", entry.label); |
| 2925 | let u = call(&mut server, "undo", json!({})); |
| 2926 | assert!(!u.is_error, "{}", u.text); |
| 2927 | assert_eq!(server.session.as_ref().unwrap().sources()[0].path, old, "undo points back at the old file"); |
| 2928 | let d = call(&mut server, "redo", json!({})); |
| 2929 | assert!(!d.is_error, "{}", d.text); |
| 2930 | assert_eq!(server.session.as_ref().unwrap().sources()[0].path, new, "redo re-points it"); |
| 2931 | } |
| 2932 | |
| 2933 | /// project_collect copies the used files beside the project, relinks them in one undo step, |
| 2934 | /// and says what it skipped; a second run copies nothing. |
| 2935 | #[test] |
| 2936 | fn project_collect_copies_relinks_and_undoes_in_one_step() { |
| 2937 | let td = TestDir::new("collect"); |
| 2938 | let project = td.path().join("film.edith"); |
| 2939 | let mut server = Server::new(); |
| 2940 | assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 2941 | assert!(!call(&mut server, "media_import", json!({"paths": [asset("test_av.mp4")]})).is_error); |
| 2942 | let old = server.session.as_ref().unwrap().sources()[0].path.clone(); |
| 2943 | let ledger = server.ledger.len(); |
| 2944 | let r = call(&mut server, "project_collect", json!({})); |
| 2945 | assert!(!r.is_error, "{}", r.text); |
| 2946 | assert!(r.text.contains("1 file(s) copied") && r.text.contains("undo takes the relink back"), "{}", r.text); |
| 2947 | let now = server.session.as_ref().unwrap().sources()[0].path.clone(); |
| 2948 | assert_eq!(now.parent().unwrap().file_name().unwrap(), "film_media"); |
| 2949 | assert!(now.is_file()); |
| 2950 | assert_eq!(server.ledger.len(), ledger + 1); |
| 2951 | let again = call(&mut server, "project_collect", json!({})); |
| 2952 | assert!(again.text.contains("0 file(s) copied") && !again.text.contains("undo takes"), "{}", again.text); |
| 2953 | assert!(!call(&mut server, "undo", json!({})).is_error); |
| 2954 | assert_eq!(server.session.as_ref().unwrap().sources()[0].path, old); |
| 2955 | // Checkpoints use the functions the window uses. |
| 2956 | let c = call(&mut server, "checkpoint", json!({"name": "first-cut"})); |
| 2957 | assert!(!c.is_error, "{}", c.text); |
| 2958 | assert!(td.path().join("checkpoints/film/first-cut.edith").is_file()); |
| 2959 | } |
| 2960 | |
| 2961 | /// A relink to the file the source already plays is no change, so it is no undo step and the |
| 2962 | /// reply does not offer one. |
| 2963 | #[test] |
| 2964 | fn a_relink_to_the_same_file_is_no_step() { |
| 2965 | let td = TestDir::new("relink-same"); |
| 2966 | let project = td.path().join("same.edith"); |
| 2967 | let mut server = Server::new(); |
| 2968 | assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 2969 | assert!(!call(&mut server, "media_import", json!({"paths": [asset("test_av.mp4")]})).is_error); |
| 2970 | let r = call(&mut server, "media_relink", json!({"source": "src:0", "path": asset("test_av.mp4")})); |
| 2971 | assert!(!r.is_error, "{}", r.text); |
| 2972 | assert!(!r.text.contains("undo takes it back"), "{}", r.text); |
| 2973 | assert!(server.ledger.is_empty(), "a relink to the same file records no undo step"); |
| 2974 | } |
| 2975 | |
| 2976 | /// The length warning is the same for a file that is longer and one that is shorter, and a |
| 2977 | /// rate change is named apart from it: a 30 s 24 fps file for a 5 s 30 fps one, and back. |
| 2978 | #[test] |
| 2979 | fn a_longer_or_shorter_file_is_warned_both_ways() { |
| 2980 | let five = Shape { fps: Some(30.0), secs: Some(5.0) }; |
| 2981 | let longer = shape_warnings(0, "V1@0", five, Shape { fps: Some(24.0), secs: Some(30.0) }, 30.0); |
| 2982 | assert_eq!(longer.len(), 2, "{longer:?}"); |
| 2983 | assert!(longer[0].contains("24 fps against the 30 fps file it replaces"), "{longer:?}"); |
| 2984 | assert!(longer[1].contains("00:30.000 long against the 00:05.000"), "{longer:?}"); |
| 2985 | assert!(longer.iter().all(|w| w.contains("V1@0")), "{longer:?}"); |
| 2986 | let shorter = shape_warnings(0, "V1@0", Shape { fps: Some(24.0), secs: Some(30.0) }, five, 30.0); |
| 2987 | assert_eq!(shorter.len(), 2, "{shorter:?}"); |
| 2988 | assert!(shorter[0].contains("30 fps against the 24 fps file it replaces"), "{shorter:?}"); |
| 2989 | assert!(shorter[1].contains("00:05.000 long against the 00:30.000"), "{shorter:?}"); |
| 2990 | // The same rate and a length within a frame: nothing to say. |
| 2991 | let quiet = shape_warnings(0, "x", five, Shape { fps: Some(30.0), secs: Some(5.01) }, 30.0); |
| 2992 | assert!(quiet.is_empty(), "{quiet:?}"); |
| 2993 | } |
| 2994 | |
| 2995 | /// An offline source relinked to a longer file of another rate is warned against the length |
| 2996 | /// its file had when the project was opened: the old file is gone, so its shape is remembered. |
| 2997 | #[test] |
| 2998 | fn an_offline_source_is_compared_with_the_shape_its_file_had() { |
| 2999 | let td = TestDir::new("relink-offline-shape"); |
| 3000 | std::fs::copy(asset("test_25fps.mp4"), td.path().join("short.mp4")).expect("copy"); |
| 3001 | let project = td.path().join("offline-shape.edith"); |
| 3002 | let mut server = Server::new(); |
| 3003 | assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 3004 | assert!(!call(&mut server, "media_import", json!({"paths": [td.path().join("short.mp4")]})).is_error); |
| 3005 | let placed = call(&mut server, "edit", json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": "0s"}]})); |
| 3006 | assert!(!placed.is_error, "{}", placed.text); |
| 3007 | std::fs::remove_file(td.path().join("short.mp4")).expect("remove"); |
| 3008 | let r = call(&mut server, "media_relink", json!({"source": "src:0", "path": asset("test_av.mp4")})); |
| 3009 | assert!(!r.is_error, "{}", r.text); |
| 3010 | assert!(r.text.contains("30 fps against the 25 fps file it replaces"), "{}", r.text); |
| 3011 | assert!(r.text.contains("00:05.000 long against the 00:02.000"), "{}", r.text); |
| 3012 | } |
| 3013 | |
| 3014 | /// A source offline when its project was opened has no shape to compare with: the reply says |
| 3015 | /// so, and does not invent a comparison. |
| 3016 | #[test] |
| 3017 | fn an_offline_source_never_read_says_it_was_not_compared() { |
| 3018 | let td = TestDir::new("relink-never-read"); |
| 3019 | std::fs::copy(asset("test_25fps.mp4"), td.path().join("short.mp4")).expect("copy"); |
| 3020 | let project = td.path().join("never-read.edith"); |
| 3021 | let mut server = Server::new(); |
| 3022 | assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 3023 | assert!(!call(&mut server, "media_import", json!({"paths": [td.path().join("short.mp4")]})).is_error); |
| 3024 | let placed = call(&mut server, "edit", json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": "0s"}]})); |
| 3025 | assert!(!placed.is_error, "{}", placed.text); |
| 3026 | assert!(!call(&mut server, "project_save", json!({})).is_error); |
| 3027 | std::fs::remove_file(td.path().join("short.mp4")).expect("remove"); |
| 3028 | let mut fresh = Server::new(); |
| 3029 | assert!(!call(&mut fresh, "project_open", json!({"path": project})).is_error); |
| 3030 | let r = call(&mut fresh, "media_relink", json!({"source": "src:0", "path": asset("test_av.mp4")})); |
| 3031 | assert!(!r.is_error, "{}", r.text); |
| 3032 | assert!(r.text.contains("were never read, so the new file was not compared"), "{}", r.text); |
| 3033 | } |
| 3034 | |
| 3035 | /// A 5 s source of which a clip reads only its first 2 s relinks to a 2 s file: the clips |
| 3036 | /// read 60 source frames, so the file needs no more. |
| 3037 | #[test] |
| 3038 | fn a_clip_reading_part_of_a_source_relinks_to_a_file_of_that_part() { |
| 3039 | let td = TestDir::new("relink-part"); |
| 3040 | let project = td.path().join("part.edith"); |
| 3041 | let mut server = Server::new(); |
| 3042 | assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 3043 | assert!(!call(&mut server, "media_import", json!({"paths": [asset("test_av.mp4")]})).is_error); |
| 3044 | let placed = call(&mut server, "edit", json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": "0s", "length": "2s"}]})); |
| 3045 | assert!(!placed.is_error, "{}", placed.text); |
| 3046 | let r = call(&mut server, "media_relink", json!({"source": "src:0", "path": asset("test_hevc.mp4")})); |
| 3047 | assert!(!r.is_error, "{}", r.text); |
| 3048 | } |
| 3049 | } |
| 3050 | |
| 3051 | #[cfg(test)] |
| 3052 | mod stream_tests { |
| 3053 | use super::*; |
| 3054 | |
| 3055 | fn asset(name: &str) -> PathBuf { |
| 3056 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 3057 | } |
| 3058 | |
| 3059 | /// A subtitle-only Matroska is named as subtitles, with the way in, not as a refusal. |
| 3060 | #[test] |
| 3061 | fn a_subtitle_only_file_says_import_with_subtitles_import() { |
| 3062 | let mut server = Server::new(); |
| 3063 | let probed = probe(&mut server, &json!({"paths": [asset("test_subs.mks").display().to_string()]})); |
| 3064 | assert!(probed.text.contains("test_subs.mks · subtitles only: import with subtitles_import"), "{}", probed.text); |
| 3065 | assert!(!probed.is_error, "{}", probed.text); |
| 3066 | assert!(!probed.text.contains("refused"), "{}", probed.text); |
| 3067 | assert!(probed.text.contains("streams: subtitle #"), "{}", probed.text); |
| 3068 | } |
| 3069 | |
| 3070 | /// media_import of a subtitles-only file names subtitles_import, not an audio-track refusal. |
| 3071 | #[test] |
| 3072 | fn importing_a_subtitle_only_file_points_at_subtitles_import() { |
| 3073 | let td = crate::testutil::TestDir::new("media-subs-import"); |
| 3074 | let mut server = Server::new(); |
| 3075 | let run = |server: &mut Server, name: &str, args: Value| { |
| 3076 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 3077 | (t.run)(server, &args) |
| 3078 | }; |
| 3079 | let path = td.path().join("proj.edith"); |
| 3080 | assert!(!run(&mut server, "project_new", json!({"path": path.display().to_string()})).is_error); |
| 3081 | let r = run(&mut server, "media_import", json!({"paths": [asset("test_subs.mks").display().to_string()]})); |
| 3082 | assert!(r.is_error, "{}", r.text); |
| 3083 | assert!(r.text.contains("test_subs.mks · subtitles only: import with subtitles_import"), "{}", r.text); |
| 3084 | assert!(!r.text.contains("has no audio track"), "{}", r.text); |
| 3085 | } |
| 3086 | |
| 3087 | /// A Matroska file's subtitle tracks are listed with their kind, codec, language and title, |
| 3088 | /// in container order, beside the picture's line. |
| 3089 | #[test] |
| 3090 | fn subtitle_tracks_are_listed_with_codec_and_language() { |
| 3091 | let path = asset("test_subs.mkv"); |
| 3092 | let facts = engine::probe_media(&path); |
| 3093 | let streams = other_streams(&path, &facts); |
| 3094 | let subs: Vec<&Stream> = streams.iter().filter(|s| s.kind == "subtitle").collect(); |
| 3095 | assert_eq!(subs.len(), 2, "{streams:?}"); |
| 3096 | assert_eq!(subs[0].codec.as_deref(), Some("srt")); |
| 3097 | assert_eq!(subs[0].codec_id.as_deref(), Some("S_TEXT/UTF8")); |
| 3098 | assert_eq!(subs[0].language, "eng"); |
| 3099 | assert_eq!(subs[1].language, "fra"); |
| 3100 | assert_eq!(subs[1].name, "Signs"); |
| 3101 | let mut server = Server::new(); |
| 3102 | let probed = probe(&mut server, &json!({"paths": [path.display().to_string()]})); |
| 3103 | assert!(probed.text.contains("streams: subtitle #") && probed.text.contains("ass (fra) \"Signs\""), "{}", probed.text); |
| 3104 | let row = &probed.structured.as_ref().unwrap()["files"][0]; |
| 3105 | assert_eq!(row["streams"][0]["kind"], json!("subtitle")); |
| 3106 | assert_eq!(row["streams"][1]["language"], json!("fra")); |
| 3107 | } |
| 3108 | |
| 3109 | /// A still has no sound or subtitle tracks, so it lists nothing extra. |
| 3110 | #[test] |
| 3111 | fn a_still_lists_no_streams() { |
| 3112 | let still = asset("test_still.png"); |
| 3113 | let streams = other_streams(&still, &engine::probe_media(&still)); |
| 3114 | assert!(streams.is_empty(), "{streams:?}"); |
| 3115 | } |
| 3116 | |
| 3117 | /// An audio track without a codec or a title reads as `audio codec unknown (und)`. |
| 3118 | #[test] |
| 3119 | fn a_stream_without_codec_or_title_says_so() { |
| 3120 | let st = Stream { kind: "audio", index: 1, track: None, codec: None, codec_id: None, profile: None, bit_depth: None, language: "und".into(), channels: None, sample_rate: None, name: String::new() }; |
| 3121 | assert_eq!(stream_text(&st), "audio track 1 codec unknown (und)"); |
| 3122 | let named = Stream { |
| 3123 | kind: "subtitle", |
| 3124 | index: 3, |
| 3125 | track: Some(3), |
| 3126 | codec: Some("srt".into()), |
| 3127 | codec_id: Some("S_TEXT/UTF8".into()), |
| 3128 | profile: None, |
| 3129 | bit_depth: None, |
| 3130 | language: "eng".into(), |
| 3131 | channels: None, |
| 3132 | sample_rate: None, |
| 3133 | name: "Signs".into(), |
| 3134 | }; |
| 3135 | assert_eq!(stream_text(&named), "subtitle #3 srt (eng) \"Signs\""); |
| 3136 | } |
| 3137 | |
| 3138 | /// The codec spellings a file gives are named plainly; any other passes through as written. |
| 3139 | #[test] |
| 3140 | fn codec_ids_are_named_in_plain_words() { |
| 3141 | for (raw, plain) in [ |
| 3142 | ("A_OPUS", "opus"), |
| 3143 | ("Opus", "opus"), |
| 3144 | ("A_VORBIS", "vorbis"), |
| 3145 | ("A_AAC/MPEG4/LC", "aac"), |
| 3146 | ("mp4a", "aac"), |
| 3147 | ("fLaC", "flac"), |
| 3148 | ("A_PCM/INT/LIT", "pcm"), |
| 3149 | ("V_VP8", "vp8"), |
| 3150 | ("V_VP9", "vp9"), |
| 3151 | ("V_AV1", "av1"), |
| 3152 | ("V_MPEG4/ISO/AVC", "h264"), |
| 3153 | ("avc1", "h264"), |
| 3154 | ("V_MPEGH/ISO/HEVC", "hevc"), |
| 3155 | ("hvc1", "hevc"), |
| 3156 | ("S_TEXT/UTF8", "srt"), |
| 3157 | ("S_TEXT/ASS", "ass"), |
| 3158 | ("S_TEXT/WEBVTT", "webvtt"), |
| 3159 | ("tx3g", "mov_text"), |
| 3160 | ("S_HDMV/PGS", "pgs"), |
| 3161 | ("X_UNKNOWN", "X_UNKNOWN"), |
| 3162 | ] { |
| 3163 | assert_eq!(plain_codec(raw), plain, "{raw}"); |
| 3164 | } |
| 3165 | } |
| 3166 | |
| 3167 | /// Audio tracks are numbered from 0 in file order, the numbers `audio_track` takes, and each |
| 3168 | /// carries the language the engine's stream list states for it. |
| 3169 | #[test] |
| 3170 | fn audio_tracks_are_numbered_from_zero_with_their_language() { |
| 3171 | let mp4 = asset("test_multiaudio.mp4"); |
| 3172 | let tracks: Vec<(usize, String)> = other_streams(&mp4, &engine::probe_media(&mp4)) |
| 3173 | .iter() |
| 3174 | .filter(|s| s.kind == "audio") |
| 3175 | .map(|s| (s.index, s.language.clone())) |
| 3176 | .collect(); |
| 3177 | assert_eq!(tracks.len(), 3, "{tracks:?}"); |
| 3178 | assert_eq!(tracks.iter().map(|t| t.0).collect::<Vec<_>>(), vec![0, 1, 2]); |
| 3179 | assert_eq!(tracks[1].1, "fra", "track 1 is the French one (ffprobe's stream 2): {tracks:?}"); |
| 3180 | let mkv = asset("test_multiaudio.mkv"); |
| 3181 | let text: Vec<String> = other_streams(&mkv, &engine::probe_media(&mkv)).iter().filter(|s| s.kind == "audio").map(stream_text).collect(); |
| 3182 | assert_eq!(text, vec!["audio track 0 aac LC (eng) stereo, 44.1 kHz", "audio track 1 aac LC (fra) stereo, 44.1 kHz"], "{text:?}"); |
| 3183 | } |
| 3184 | |
| 3185 | /// An mp4's streams are numbered in file order, video included, and its audio is named by |
| 3186 | /// its sample entry. The picture is not listed. |
| 3187 | #[test] |
| 3188 | fn mp4_streams_use_ffprobe_order_and_fourcc_names() { |
| 3189 | let path = asset("test_av.mp4"); |
| 3190 | let facts = engine::probe_media(&path); |
| 3191 | let streams = other_streams(&path, &facts); |
| 3192 | assert!(streams.iter().all(|s| s.kind != "video")); |
| 3193 | let audio: Vec<&Stream> = streams.iter().filter(|s| s.kind == "audio").collect(); |
| 3194 | assert_eq!(audio.len(), 1, "{streams:?}"); |
| 3195 | assert_eq!(audio[0].codec_id.as_deref(), Some("mp4a"), "{streams:?}"); |
| 3196 | assert_eq!(audio[0].codec.as_deref(), Some("aac")); |
| 3197 | assert_eq!(audio[0].index, 0, "the first audio track is track 0"); |
| 3198 | assert!(!stream_text(audio[0]).contains("codec unknown"), "{}", stream_text(audio[0])); |
| 3199 | } |
| 3200 | } |