Still images import and place as clips
Browse files at this commit30d430d8d028945be3a5063aeb3a0236aeb12f89Parent: b514187- feat
- still images import and place as clips
9 changed files +910 -23
- Cargo.lock +1 -0
- crates/app/src/main.rs +78 -9
- crates/engine/Cargo.toml +14 -0
- crates/engine/src/decode.rs +164 -0
- crates/engine/src/export.rs +16 -1
- crates/engine/src/lib.rs +36 -1
- crates/engine/src/playback.rs +251 -12
- crates/engine/tests/images.rs +341 -0
- scripts/gen_fixtures.sh +9 -0
Cargo.lockmodified+1 -0
| @@ -1632,6 +1632,7 @@ version = "0.1.0" | ||
| 1632 | 1632 | dependencies = [ |
| 1633 | 1633 | "flacenc", |
| 1634 | 1634 | "hound", |
| 1635 | + "image", | |
| 1635 | 1636 | "libloading", |
| 1636 | 1637 | "mp4", |
| 1637 | 1638 | "oxideav-ac3", |
crates/app/src/main.rsmodified+78 -9
| @@ -459,6 +459,12 @@ struct Player { | ||
| 459 | 459 | /// presence means "asked" -- and an empty list is a silent file, which is |
| 460 | 460 | /// exactly one row and no stream tags. |
| 461 | 461 | streams: HashMap<PathBuf, Vec<StreamInfo>>, |
| 462 | + /// How big each still source's picture is, read from its header once and | |
| 463 | + /// kept -- what a library row and its card say about a file that has no | |
| 464 | + /// streams to describe. Filled like `streams`: presence means "asked", and | |
| 465 | + /// `None` is a file with no picture to report (every source that is not an | |
| 466 | + /// image, and one whose header would not read). | |
| 467 | + sizes: HashMap<PathBuf, Option<(u32, u32)>>, | |
| 462 | 468 | /// The copied clip. Frame ranges only, so it survives the clip it was taken |
| 463 | 469 | /// from being deleted -- and it outlives the selection. |
| 464 | 470 | clipboard: Option<Clip>, |
| @@ -1286,6 +1292,15 @@ impl Player { | ||
| 1286 | 1292 | let Some(session) = &self.session else { |
| 1287 | 1293 | return; |
| 1288 | 1294 | }; |
| 1295 | + // How big each still is, for the row that has to say so. Inline, unlike | |
| 1296 | + // the two below: an image header is a few bytes off the front of the | |
| 1297 | + // file, where a sample table is a parse and a decode is a second. | |
| 1298 | + for path in unseen_paths(session.sources(), &self.sizes) { | |
| 1299 | + let size = engine::is_image(&path) | |
| 1300 | + .then(|| engine::image_size(&path).ok()) | |
| 1301 | + .flatten(); | |
| 1302 | + self.sizes.insert(path, size); | |
| 1303 | + } | |
| 1289 | 1304 | // Which audio streams each file has, for the library's rows. Header |
| 1290 | 1305 | // only, but a big file's sample tables are not free to parse, so it |
| 1291 | 1306 | // goes off the render thread like the peaks do. |
| @@ -1564,6 +1579,18 @@ impl Player { | ||
| 1564 | 1579 | cx.notify(); |
| 1565 | 1580 | return; |
| 1566 | 1581 | } |
| 1582 | + // ...and the mirror of it: a still is silent, so an audio lane is the | |
| 1583 | + // one place it cannot go. The engine puts it on `V1` regardless | |
| 1584 | + // (`place_stream_at`); this is the word that says why it moved. | |
| 1585 | + if engine::is_image(path) && onto.is_some_and(|lane| lane.kind == LaneKind::Audio) { | |
| 1586 | + let name = file_name(path); | |
| 1587 | + let lane = onto.expect("checked above").label(); | |
| 1588 | + self.notice = Some( | |
| 1589 | + format!("NOT ON {lane} — {name} is a still image; drop it on a video lane").into(), | |
| 1590 | + ); | |
| 1591 | + cx.notify(); | |
| 1592 | + return; | |
| 1593 | + } | |
| 1567 | 1594 | // The engine's own length for the file, noted when the import took it |
| 1568 | 1595 | // in: a row that has never been on a lane is placeable at its full |
| 1569 | 1596 | // length, which is the whole point of an import that only fills the |
| @@ -2561,6 +2588,17 @@ impl Player { | ||
| 2561 | 2588 | "{} — audio only · drag onto the audio lane, or Add at playhead", |
| 2562 | 2589 | row.path.display() |
| 2563 | 2590 | ), |
| 2591 | + // A still is the mirror: its own size (the timeline's meta | |
| 2592 | + // describes video, and a picture placed on that canvas is not | |
| 2593 | + // the same shape), no frame rate, and one kind of lane. | |
| 2594 | + (None, _) if engine::is_image(&row.path) => format!( | |
| 2595 | + "{} — still image{} · drag onto a video lane, or Add at playhead", | |
| 2596 | + row.path.display(), | |
| 2597 | + match self.sizes.get(&row.path).copied().flatten() { | |
| 2598 | + Some((w, h)) => format!(" · {w}x{h}"), | |
| 2599 | + None => String::new(), | |
| 2600 | + } | |
| 2601 | + ), | |
| 2564 | 2602 | (None, Some(meta)) => format!( |
| 2565 | 2603 | "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", |
| 2566 | 2604 | row.path.display(), |
| @@ -2578,6 +2616,16 @@ impl Player { | ||
| 2578 | 2616 | // the reason it cannot be used. |
| 2579 | 2617 | let under = match &row.unusable { |
| 2580 | 2618 | Some(why) => join_detail(&row.detail, why), |
| 2619 | + // A still has no length to report -- the ten minutes it is | |
| 2620 | + // *held* to is a wall, not a duration -- so the line says what | |
| 2621 | + // it is and how big it is instead. | |
| 2622 | + None if engine::is_image(&row.path) => join_detail( | |
| 2623 | + &row.detail, | |
| 2624 | + &match self.sizes.get(&row.path).copied().flatten() { | |
| 2625 | + Some((w, h)) => format!("still image · {w}x{h}"), | |
| 2626 | + None => "still image".to_string(), | |
| 2627 | + }, | |
| 2628 | + ), | |
| 2581 | 2629 | None => join_detail( |
| 2582 | 2630 | &row.detail, |
| 2583 | 2631 | &timecode(f64::from(row.frames) / self.fps, self.fps), |
| @@ -3829,14 +3877,32 @@ impl Player { | ||
| 3829 | 3877 | .count() |
| 3830 | 3878 | }) |
| 3831 | 3879 | }); |
| 3880 | + // A still is described by what it has -- a picture, a size, and a | |
| 3881 | + // longest it may be held for -- where a media file is described by | |
| 3882 | + // its streams and its length. Same card, the rows that mean | |
| 3883 | + // something for this kind of source. | |
| 3884 | + let image = engine::is_image(&path); | |
| 3885 | + let kind = match self.sizes.get(&path).copied().flatten() { | |
| 3886 | + Some((w, h)) => format!("still image · {w}x{h}"), | |
| 3887 | + None => "still image".to_string(), | |
| 3888 | + }; | |
| 3832 | 3889 | for (label, value) in [ |
| 3833 | 3890 | ("File", file_name(&path)), |
| 3834 | 3891 | ("Path", path.display().to_string()), |
| 3835 | - ( | |
| 3836 | - "Audio", | |
| 3837 | - info.map_or_else(|| "no track of its own".to_string(), stream_detail), | |
| 3838 | - ), | |
| 3839 | - ("Length", timecode(f64::from(frames) / self.fps, self.fps)), | |
| 3892 | + match image { | |
| 3893 | + true => ("Picture", kind), | |
| 3894 | + false => ( | |
| 3895 | + "Audio", | |
| 3896 | + info.map_or_else(|| "no track of its own".to_string(), stream_detail), | |
| 3897 | + ), | |
| 3898 | + }, | |
| 3899 | + match image { | |
| 3900 | + true => ( | |
| 3901 | + "Longest hold", | |
| 3902 | + timecode(f64::from(frames) / self.fps, self.fps), | |
| 3903 | + ), | |
| 3904 | + false => ("Length", timecode(f64::from(frames) / self.fps, self.fps)), | |
| 3905 | + }, | |
| 3840 | 3906 | ("On the timeline", format!("{placed} clips")), |
| 3841 | 3907 | ] { |
| 3842 | 3908 | rows.push( |
| @@ -4571,12 +4637,14 @@ fn unseen_sources( | ||
| 4571 | 4637 | .collect() |
| 4572 | 4638 | } |
| 4573 | 4639 | |
| 4574 | -/// The same, for the per-file stream probe: one entry per *file*, however many | |
| 4575 | -/// of its streams the timeline plays. | |
| 4576 | -fn unseen_paths(sources: &[Source], streams: &HashMap<PathBuf, Vec<StreamInfo>>) -> Vec<PathBuf> { | |
| 4640 | +/// The same, for the per-file caches: one entry per *file*, however many of its | |
| 4641 | +/// streams the timeline plays. Generic in the value, because the stream probe | |
| 4642 | +/// and the still's own size are both asked once per file and answered by | |
| 4643 | +/// presence in a map. | |
| 4644 | +fn unseen_paths<V>(sources: &[Source], seen: &HashMap<PathBuf, V>) -> Vec<PathBuf> { | |
| 4577 | 4645 | let mut out: Vec<PathBuf> = Vec::new(); |
| 4578 | 4646 | for s in sources { |
| 4579 | - if !streams.contains_key(&s.path) && !out.contains(&s.path) { | |
| 4647 | + if !seen.contains_key(&s.path) && !out.contains(&s.path) { | |
| 4580 | 4648 | out.push(s.path.clone()); |
| 4581 | 4649 | } |
| 4582 | 4650 | } |
| @@ -7453,6 +7521,7 @@ fn main() { | ||
| 7453 | 7521 | selected_asset: None, |
| 7454 | 7522 | waves: HashMap::new(), |
| 7455 | 7523 | streams: HashMap::new(), |
| 7524 | + sizes: HashMap::new(), | |
| 7456 | 7525 | clipboard: None, |
| 7457 | 7526 | scrubbing: false, |
| 7458 | 7527 | trim: None, |
crates/engine/Cargo.tomlmodified+14 -0
| @@ -12,6 +12,15 @@ edition.workspace = true | ||
| 12 | 12 | hound = "3.5.1" |
| 13 | 13 | flacenc = { version = "0.5.1", default-features = false } |
| 14 | 14 | libloading = "0.8" |
| 15 | +# Still images, decoded once per placed clip (`decode::Still`). Pure Rust like | |
| 16 | +# everything else here, and already in the app's tree (gpui pulls it), so this | |
| 17 | +# costs the build nothing new. Exactly the formats `crate::is_image` admits: no | |
| 18 | +# default features, which would drag in a dozen decoders nothing opens. | |
| 19 | +image = { version = "0.25", default-features = false, features = [ | |
| 20 | + "png", | |
| 21 | + "jpeg", | |
| 22 | + "webp", | |
| 23 | +] } | |
| 15 | 24 | mp4 = "0.14" |
| 16 | 25 | rusty_h264 = { version = "0.8", default-features = false } |
| 17 | 26 | symphonia-core = "0.6" |
| @@ -37,3 +46,8 @@ symphonia = { version = "0.6", default-features = false, features = [ | ||
| 37 | 46 | ] } |
| 38 | 47 | oxideav-ac3 = "=0.0.10" |
| 39 | 48 | oxideav-core = "0.1.34" |
| 49 | + | |
| 50 | +[dev-dependencies] | |
| 51 | +# The still-image suite compares what the timeline shows against the file's own | |
| 52 | +# pixels rather than against a constant. Already built for the engine itself. | |
| 53 | +image = { version = "0.25", default-features = false, features = ["png"] } |
crates/engine/src/decode.rsmodified+164 -0
| @@ -183,6 +183,71 @@ impl DecodeSession { | ||
| 183 | 183 | } |
| 184 | 184 | } |
| 185 | 185 | |
| 186 | + /// A worker for a still image ([`crate::is_image`]): the file is decoded | |
| 187 | + /// *once* and the same picture goes down the channel `len` times, indexed | |
| 188 | + /// from `start_frame` exactly as a decoder's pictures are -- so a placed | |
| 189 | + /// image is a clip like any other to everything downstream (`try_frame` | |
| 190 | + /// rewrites those indices, `next_clip` walks off the end of the range). | |
| 191 | + /// | |
| 192 | + /// Graded and placed on the canvas once too, before the repeat: a still is | |
| 193 | + /// the same pixels every frame, so the whole cost of one is one conversion | |
| 194 | + /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays. | |
| 195 | + pub(crate) fn open_still( | |
| 196 | + path: &Path, | |
| 197 | + start_frame: u32, | |
| 198 | + len: u32, | |
| 199 | + color: ColorParams, | |
| 200 | + canvas: Composer, | |
| 201 | + ) -> crate::Result<FrameStream> { | |
| 202 | + let still = Still::open(path)?; | |
| 203 | + let (tx, rx) = sync_channel(2); | |
| 204 | + let cancel = Arc::new(AtomicBool::new(false)); | |
| 205 | + if len == 0 { | |
| 206 | + return Ok(FrameStream { | |
| 207 | + frames: rx, | |
| 208 | + worker: Worker { | |
| 209 | + cancel, | |
| 210 | + handle: None, | |
| 211 | + }, | |
| 212 | + }); | |
| 213 | + } | |
| 214 | + // The one conversion, on this thread: it is a few milliseconds and the | |
| 215 | + // error it could raise has already been raised by `Still::open`. | |
| 216 | + let first = Render::new(color, canvas).frame( | |
| 217 | + start_frame, | |
| 218 | + &still.y, | |
| 219 | + &still.u, | |
| 220 | + &still.v, | |
| 221 | + still.width, | |
| 222 | + still.height, | |
| 223 | + ); | |
| 224 | + let worker_cancel = Arc::clone(&cancel); | |
| 225 | + let handle = thread::Builder::new() | |
| 226 | + .name("still".into()) | |
| 227 | + .spawn(move || { | |
| 228 | + let (width, height, bgra) = (first.width, first.height, first.bgra); | |
| 229 | + for index in 0..len { | |
| 230 | + if worker_cancel.load(Ordering::Relaxed) { | |
| 231 | + return; | |
| 232 | + } | |
| 233 | + let frame = Frame { | |
| 234 | + index: start_frame + index, | |
| 235 | + width, | |
| 236 | + height, | |
| 237 | + bgra: bgra.clone(), | |
| 238 | + }; | |
| 239 | + if tx.send(frame).is_err() { | |
| 240 | + return; // caller moved on | |
| 241 | + } | |
| 242 | + } | |
| 243 | + }) | |
| 244 | + .ok(); | |
| 245 | + Ok(FrameStream { | |
| 246 | + frames: rx, | |
| 247 | + worker: Worker { cancel, handle }, | |
| 248 | + }) | |
| 249 | + } | |
| 250 | + | |
| 186 | 251 | /// As [`DecodeSession::open_range`], but the caller gets the whole |
| 187 | 252 | /// [`Worker`] and can therefore *wait* for it, and the range is graded by |
| 188 | 253 | /// `color` -- the clip's own setting, folded into the conversion the frames |
| @@ -362,6 +427,105 @@ impl Render { | ||
| 362 | 427 | } |
| 363 | 428 | } |
| 364 | 429 | |
| 430 | +/// One still image, decoded to tightly packed I420 -- the shape every other | |
| 431 | +/// source arrives in, so a placed image goes through the same grade, the same | |
| 432 | +/// canvas and the same conversion as a decoded picture and there is no second | |
| 433 | +/// pixel path to keep in step. | |
| 434 | +/// | |
| 435 | +/// Held whole rather than streamed: an image *is* one picture, and the file is | |
| 436 | +/// read once per span that plays it. | |
| 437 | +pub(crate) struct Still { | |
| 438 | + pub(crate) y: Vec<u8>, | |
| 439 | + pub(crate) u: Vec<u8>, | |
| 440 | + pub(crate) v: Vec<u8>, | |
| 441 | + pub(crate) width: u32, | |
| 442 | + pub(crate) height: u32, | |
| 443 | +} | |
| 444 | + | |
| 445 | +impl Still { | |
| 446 | + /// Decodes `path`. Refused by name for a picture that is not one | |
| 447 | + /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project | |
| 448 | + /// file are both held to cannot be walked around by a 30000-pixel-wide PNG. | |
| 449 | + pub(crate) fn open(path: &Path) -> crate::Result<Self> { | |
| 450 | + let reader = image::ImageReader::open(path)?.with_guessed_format()?; | |
| 451 | + let rgb = reader | |
| 452 | + .decode() | |
| 453 | + .map_err(|e| format!("{}: {e}", path.display()))? | |
| 454 | + .to_rgb8(); | |
| 455 | + let (width, height) = rgb.dimensions(); | |
| 456 | + if !crate::is_resolution(width, height) { | |
| 457 | + return Err(format!( | |
| 458 | + "{} is {width}x{height}, which is not a picture this engine composes", | |
| 459 | + path.display() | |
| 460 | + ) | |
| 461 | + .into()); | |
| 462 | + } | |
| 463 | + let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize); | |
| 464 | + Ok(Self { | |
| 465 | + y, | |
| 466 | + u, | |
| 467 | + v, | |
| 468 | + width, | |
| 469 | + height, | |
| 470 | + }) | |
| 471 | + } | |
| 472 | + | |
| 473 | + /// The planes as an export's decoder hands them over, so a still and a | |
| 474 | + /// decoded picture are the same value to `export::run`. | |
| 475 | + pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { | |
| 476 | + (&self.y, &self.u, &self.v, self.width, self.height) | |
| 477 | + } | |
| 478 | +} | |
| 479 | + | |
| 480 | +/// How big the picture in `path` is, from its header alone -- what a library row | |
| 481 | +/// says about a file it has not placed anywhere. The whole file is not decoded. | |
| 482 | +pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> { | |
| 483 | + Ok(image::ImageReader::open(path)? | |
| 484 | + .with_guessed_format()? | |
| 485 | + .into_dimensions() | |
| 486 | + .map_err(|e| format!("{}: {e}", path.display()))?) | |
| 487 | +} | |
| 488 | + | |
| 489 | +/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse | |
| 490 | +/// of [`crate::convert::i420_to_bgra`], so a still round-trips to the colour it | |
| 491 | +/// was authored in (`images::still_pixels_match_the_source_image` measures it). | |
| 492 | +/// | |
| 493 | +/// Chroma is the 2x2 box average, and an odd edge averages the samples it has -- | |
| 494 | +/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape | |
| 495 | +/// [`crate::scale::Composer::place`] panics on anything else for. | |
| 496 | +fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) { | |
| 497 | + let (cw, ch) = crate::scale::chroma_dims(width, height); | |
| 498 | + let mut y = vec![0u8; width * height]; | |
| 499 | + let mut u = vec![0u8; cw * ch]; | |
| 500 | + let mut v = vec![0u8; cw * ch]; | |
| 501 | + for row in 0..height { | |
| 502 | + for col in 0..width { | |
| 503 | + let p = (row * width + col) * 3; | |
| 504 | + let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32); | |
| 505 | + y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8; | |
| 506 | + } | |
| 507 | + } | |
| 508 | + for crow in 0..ch { | |
| 509 | + for ccol in 0..cw { | |
| 510 | + let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32); | |
| 511 | + for row in crow * 2..(crow * 2 + 2).min(height) { | |
| 512 | + for col in ccol * 2..(ccol * 2 + 2).min(width) { | |
| 513 | + let p = (row * width + col) * 3; | |
| 514 | + sr += rgb[p] as i32; | |
| 515 | + sg += rgb[p + 1] as i32; | |
| 516 | + sb += rgb[p + 2] as i32; | |
| 517 | + n += 1; | |
| 518 | + } | |
| 519 | + } | |
| 520 | + let n = n.max(1); | |
| 521 | + let (r, g, b) = (sr / n, sg / n, sb / n); | |
| 522 | + u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8; | |
| 523 | + v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8; | |
| 524 | + } | |
| 525 | + } | |
| 526 | + (y, u, v) | |
| 527 | +} | |
| 528 | + | |
| 365 | 529 | /// `None` when the software path must be used: forced by `VE_SW=1`, or the |
| 366 | 530 | /// plugin is absent/broken/unable to open this particular file. |
| 367 | 531 | fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> { |
crates/engine/src/export.rsmodified+16 -1
| @@ -279,7 +279,11 @@ fn run( | ||
| 279 | 279 | .lane(lane) |
| 280 | 280 | .iter() |
| 281 | 281 | .enumerate() |
| 282 | - .find(|(idx, _)| project.eq_of(lane, *idx).is_some_and(|eq| !eq.is_identity())) | |
| 282 | + .find(|(idx, _)| { | |
| 283 | + project | |
| 284 | + .eq_of(lane, *idx) | |
| 285 | + .is_some_and(|eq| !eq.is_identity()) | |
| 286 | + }) | |
| 283 | 287 | .map(|(idx, clip)| (clip.start, idx)) |
| 284 | 288 | { |
| 285 | 289 | return Err(format!( |
| @@ -732,10 +736,20 @@ impl Enc { | ||
| 732 | 736 | enum ClipDecoder { |
| 733 | 737 | Hw(HwSession), |
| 734 | 738 | Sw(SwDecoder), |
| 739 | + /// A still image: one picture, handed out for as long as the span runs. | |
| 740 | + /// It is decoded here rather than in `run`'s loop for the same reason the | |
| 741 | + /// other two are opened there -- the span's pictures come from one place. | |
| 742 | + Still(crate::decode::Still), | |
| 735 | 743 | } |
| 736 | 744 | |
| 737 | 745 | impl ClipDecoder { |
| 738 | 746 | fn open(path: &Path, start_frame: u32) -> crate::Result<Self> { |
| 747 | + // Before either decoder: an image is not a stream, so `start_frame` | |
| 748 | + // means nothing to it -- every frame of a still span is the same | |
| 749 | + // picture, which is what playback shows for it too. | |
| 750 | + if crate::is_image(path) { | |
| 751 | + return Ok(Self::Still(crate::decode::Still::open(path)?)); | |
| 752 | + } | |
| 739 | 753 | if !forced("VE_SW") |
| 740 | 754 | && let Some(hw) = HwSession::open_at(path, start_frame) |
| 741 | 755 | { |
| @@ -747,6 +761,7 @@ impl ClipDecoder { | ||
| 747 | 761 | /// The next picture as tightly packed I420, borrowed until the call after. |
| 748 | 762 | fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> { |
| 749 | 763 | match self { |
| 764 | + Self::Still(still) => Ok(Some(still.picture())), | |
| 750 | 765 | Self::Hw(hw) => hw.next_frame(), |
| 751 | 766 | Self::Sw(sw) => { |
| 752 | 767 | if !sw.advance()? { |
crates/engine/src/lib.rsmodified+36 -1
| @@ -21,7 +21,7 @@ pub use audio::{ | ||
| 21 | 21 | AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession, StreamInfo, |
| 22 | 22 | }; |
| 23 | 23 | pub use clock::PlaybackClock; |
| 24 | -pub use decode::{DecodeSession, Frame}; | |
| 24 | +pub use decode::{DecodeSession, Frame, image_size}; | |
| 25 | 25 | pub use demux::{Codec, VideoMeta}; |
| 26 | 26 | pub use export::ExportHandle; |
| 27 | 27 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; |
| @@ -46,6 +46,23 @@ pub fn is_audio(path: &std::path::Path) -> bool { | ||
| 46 | 46 | }) |
| 47 | 47 | } |
| 48 | 48 | |
| 49 | +/// Whether a path names a still image -- a source with a picture and no sound | |
| 50 | +/// and no length of its own, which belongs on a video lane and nowhere else. | |
| 51 | +/// Extension only, lowercased, for [`is_audio`]'s reason: a front-end has to | |
| 52 | +/// know which lane a dropped file may land on before anything is opened. | |
| 53 | +/// | |
| 54 | +/// Exactly the formats `image` is built with here (see `Cargo.toml`): PNG, | |
| 55 | +/// JPEG and WebP. A `.gif` or a `.tif` is refused by the same door that refuses | |
| 56 | +/// a `.txt`, which is the honest answer until a decoder for it is compiled in. | |
| 57 | +pub fn is_image(path: &std::path::Path) -> bool { | |
| 58 | + path.extension().and_then(|e| e.to_str()).is_some_and(|e| { | |
| 59 | + matches!( | |
| 60 | + e.to_ascii_lowercase().as_str(), | |
| 61 | + "png" | "jpg" | "jpeg" | "webp" | |
| 62 | + ) | |
| 63 | + }) | |
| 64 | +} | |
| 65 | + | |
| 49 | 66 | /// The largest picture this engine composes onto, either way: 8K, which is where |
| 50 | 67 | /// a per-frame buffer stops being a sane thing to allocate. |
| 51 | 68 | pub const MAX_RESOLUTION: u32 = 7680; |
| @@ -90,4 +107,22 @@ mod tests { | ||
| 90 | 107 | assert!(!super::is_audio(Path::new(name)), "{name}"); |
| 91 | 108 | } |
| 92 | 109 | } |
| 110 | + | |
| 111 | + #[test] | |
| 112 | + fn is_image_admits_the_formats_the_decoder_is_built_with() { | |
| 113 | + for name in ["shot.png", "a.JPG", "b.jpeg", "c.webp"] { | |
| 114 | + assert!(super::is_image(Path::new(name)), "{name}"); | |
| 115 | + } | |
| 116 | + // Media, projects, the still formats no decoder is compiled in for, | |
| 117 | + // and a file with no extension: all of them go elsewhere. The two | |
| 118 | + // predicates never both hold -- which lane a file may land on is one | |
| 119 | + // answer, not two. | |
| 120 | + for name in ["clip.mp4", "song.mp3", "cut.edith", "d.gif", "e.tif", "png"] { | |
| 121 | + assert!(!super::is_image(Path::new(name)), "{name}"); | |
| 122 | + assert!( | |
| 123 | + !(super::is_image(Path::new(name)) && super::is_audio(Path::new(name))), | |
| 124 | + "{name}" | |
| 125 | + ); | |
| 126 | + } | |
| 127 | + } | |
| 93 | 128 | } |
crates/engine/src/playback.rsmodified+251 -12
| @@ -46,6 +46,28 @@ const RING_FULL_WAIT: Duration = Duration::from_millis(10); | ||
| 46 | 46 | /// placed in frames. |
| 47 | 47 | const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); |
| 48 | 48 | |
| 49 | +/// The frame rate a timeline scaffolded from a still image runs at, for | |
| 50 | +/// [`AUDIO_ONLY_CANVAS`]'s reason: nothing was shot on it. The *size* is not | |
| 51 | +/// invented the same way -- an image has a picture of its own, and that picture | |
| 52 | +/// is the canvas a later import meets. | |
| 53 | +const IMAGE_ONLY_RATE: f64 = 30.0; | |
| 54 | + | |
| 55 | +/// How long a still image *is*, in seconds: the wall a trim may drag its edge | |
| 56 | +/// out to, since an image has no length of its own to be walled by. Ten | |
| 57 | +/// minutes, which is a title card nobody will run out of and still a finite | |
| 58 | +/// number -- a `u32::MAX` sentinel here would make [`Self::trim_room`] hand a | |
| 59 | +/// drag a wall past what the timeline can hold. | |
| 60 | +/// | |
| 61 | +/// ponytail: a still cannot be held longer than this. Upgrade path is a | |
| 62 | +/// per-source length the project file carries, which every `counts` reader | |
| 63 | +/// would then have to take from the document rather than from the file. | |
| 64 | +const IMAGE_MAX_SECS: f64 = 600.0; | |
| 65 | + | |
| 66 | +/// How long a still image is *placed* for: five seconds, the length a picture | |
| 67 | +/// gets when nobody has said one -- trimmable either way up to | |
| 68 | +/// [`IMAGE_MAX_SECS`]. | |
| 69 | +const IMAGE_PLACE_SECS: f64 = 5.0; | |
| 70 | + | |
| 49 | 71 | /// The output half of a session: the device, plus what the feeder has handed it. |
| 50 | 72 | /// Cloned into the feeder thread; every field that matters is shared. |
| 51 | 73 | #[derive(Clone)] |
| @@ -175,6 +197,12 @@ impl PlaybackSession { | ||
| 175 | 197 | if crate::is_audio(&path) { |
| 176 | 198 | return Self::open_audio_only(&path); |
| 177 | 199 | } |
| 200 | + // A still is the other source with no timeline in it: it has a picture | |
| 201 | + // (which becomes the canvas) but no rate and no length, so it too | |
| 202 | + // scaffolds rather than describes. | |
| 203 | + if crate::is_image(&path) { | |
| 204 | + return Self::open_image_only(&path); | |
| 205 | + } | |
| 178 | 206 | // `open_worker` rather than `open` purely for the worker handle: the |
| 179 | 207 | // field has to exist from the start for the first seek to use it. |
| 180 | 208 | // Ungraded: a file just opened has one clip per lane and nothing has |
| @@ -316,6 +344,71 @@ impl PlaybackSession { | ||
| 316 | 344 | }) |
| 317 | 345 | } |
| 318 | 346 | |
| 347 | + /// Opens a still image ([`crate::is_image`]) as a timeline of its own: one | |
| 348 | + /// clip on `V1`, [`IMAGE_PLACE_SECS`] long, over silence. The *canvas* is | |
| 349 | + /// the image's own picture -- unlike a song, a still has one, and inventing | |
| 350 | + /// a 1080p canvas around a 640x360 PNG would letterbox it against nothing. | |
| 351 | + /// The frame rate is [`IMAGE_ONLY_RATE`], for the reason an audio-only | |
| 352 | + /// timeline has one at all: nothing was shot on it. | |
| 353 | + /// | |
| 354 | + /// Wall time keeps the clock, as it does for any silent source. | |
| 355 | + fn open_image_only(path: &Path) -> crate::Result<Self> { | |
| 356 | + // Decoded here rather than probed: this is the door a `.png` that is | |
| 357 | + // not one comes to, and the picture is wanted a line later anyway. | |
| 358 | + let still = crate::decode::Still::open(path)?; | |
| 359 | + let meta = VideoMeta { | |
| 360 | + width: still.width, | |
| 361 | + height: still.height, | |
| 362 | + frame_rate: IMAGE_ONLY_RATE, | |
| 363 | + // Its length is the wall a trim is held to, exactly as a song's | |
| 364 | + // playing time is -- see [`image_frames`]. | |
| 365 | + frame_count: image_frames(IMAGE_ONLY_RATE), | |
| 366 | + codec: Codec::H264, | |
| 367 | + }; | |
| 368 | + let clip = Clip { | |
| 369 | + start: 0, | |
| 370 | + in_frame: 0, | |
| 371 | + out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE), | |
| 372 | + source: 0, | |
| 373 | + link: None, | |
| 374 | + eq: None, | |
| 375 | + color: None, | |
| 376 | + fit: FitPolicy::default(), | |
| 377 | + }; | |
| 378 | + // No group and no audio clip: a still is silent, and a clip on `A1` | |
| 379 | + // playing from a PNG is a source the audio worker cannot open. | |
| 380 | + let project = Project::from_parts( | |
| 381 | + vec![Source::new(path, 0)], | |
| 382 | + vec![(LaneKind::Video, vec![clip]), (LaneKind::Audio, Vec::new())], | |
| 383 | + Vec::new(), | |
| 384 | + Vec::new(), | |
| 385 | + )?; | |
| 386 | + let span = project.composite_span_at(0); | |
| 387 | + // The placeholder the first seek supersedes, opened here for `open`'s | |
| 388 | + // reason: the field has to exist before anything can seek. | |
| 389 | + let stream = DecodeSession::open_still( | |
| 390 | + path, | |
| 391 | + 0, | |
| 392 | + span.map_or(1, |s| s.len), | |
| 393 | + ColorParams::default(), | |
| 394 | + Composer::passthrough(), | |
| 395 | + )?; | |
| 396 | + Ok(Self { | |
| 397 | + meta, | |
| 398 | + native: (meta.width, meta.height), | |
| 399 | + frames: stream.frames, | |
| 400 | + worker: stream.worker, | |
| 401 | + retired: Vec::new(), | |
| 402 | + clock: PlaybackClock::new(ClockSource::Wall), | |
| 403 | + audio: None, | |
| 404 | + audio_disabled: None, | |
| 405 | + project, | |
| 406 | + counts: vec![meta.frame_count], | |
| 407 | + span, | |
| 408 | + eos: false, | |
| 409 | + }) | |
| 410 | + } | |
| 411 | + | |
| 319 | 412 | /// Opens a project file written by [`save_project`](Self::save_project): |
| 320 | 413 | /// the whole timeline, restored to where its playhead stood, paused like |
| 321 | 414 | /// [`open`](Self::open). |
| @@ -367,6 +460,28 @@ impl PlaybackSession { | ||
| 367 | 460 | }; |
| 368 | 461 | (meta, DecodeSession::open_black(width, height, 1)) |
| 369 | 462 | } |
| 463 | + // ...and a still scaffolds its own picture as the canvas, exactly | |
| 464 | + // as a fresh `open_image_only` does, with the same placeholder | |
| 465 | + // stream the `seek` at the end supersedes. | |
| 466 | + false if crate::is_image(&first.path) => { | |
| 467 | + let still = crate::decode::Still::open(&first.path) | |
| 468 | + .map_err(|e| format!("source {}: {e}", first.path.display()))?; | |
| 469 | + let meta = VideoMeta { | |
| 470 | + width: still.width, | |
| 471 | + height: still.height, | |
| 472 | + frame_rate: IMAGE_ONLY_RATE, | |
| 473 | + frame_count: image_frames(IMAGE_ONLY_RATE), | |
| 474 | + codec: Codec::H264, | |
| 475 | + }; | |
| 476 | + let stream = DecodeSession::open_still( | |
| 477 | + &first.path, | |
| 478 | + 0, | |
| 479 | + 1, | |
| 480 | + ColorParams::default(), | |
| 481 | + Composer::passthrough(), | |
| 482 | + )?; | |
| 483 | + (meta, stream) | |
| 484 | + } | |
| 370 | 485 | false => DecodeSession::open_worker( |
| 371 | 486 | &first.path, |
| 372 | 487 | 0, |
| @@ -384,10 +499,20 @@ impl PlaybackSession { | ||
| 384 | 499 | meta.width = width; |
| 385 | 500 | meta.height = height; |
| 386 | 501 | } |
| 387 | - let first_audio = AudioSession::probe(&first.path, first.audio_stream)?; | |
| 502 | + let first_audio = first_audio_of(&doc.sources)?; | |
| 388 | 503 | |
| 389 | 504 | let mut counts = vec![meta.frame_count]; |
| 390 | 505 | for source in &doc.sources[1..] { |
| 506 | + // A still has neither a rate to match nor a track to match with: | |
| 507 | + // its length is the one it is held to, recomputed exactly as the | |
| 508 | + // import that first noted it did ([`image_frames`]), which is what | |
| 509 | + // makes the clip check below meaningful on a reload. | |
| 510 | + if crate::is_image(&source.path) { | |
| 511 | + crate::decode::image_size(&source.path) | |
| 512 | + .map_err(|e| format!("source {}: {e}", source.path.display()))?; | |
| 513 | + counts.push(image_frames(meta.frame_rate)); | |
| 514 | + continue; | |
| 515 | + } | |
| 391 | 516 | // A source with no picture is checked on what it does have, and |
| 392 | 517 | // its length is its playing time -- the same two answers `import` |
| 393 | 518 | // gave it when it first joined the timeline. |
| @@ -407,16 +532,27 @@ impl PlaybackSession { | ||
| 407 | 532 | // (or hand-edited) project files are the one door this can come in |
| 408 | 533 | // through, so it is refused by name here rather than becoming a clip |
| 409 | 534 | // that decodes to nothing. |
| 410 | - for clip in doc | |
| 535 | + for (kind, clip) in doc | |
| 411 | 536 | .lanes |
| 412 | 537 | .iter() |
| 413 | - .filter(|(kind, _)| *kind == LaneKind::Video) | |
| 414 | - .flat_map(|(_, clips)| clips) | |
| 538 | + .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip))) | |
| 415 | 539 | { |
| 416 | - if crate::is_audio(&doc.sources[clip.source].path) { | |
| 540 | + let path = &doc.sources[clip.source].path; | |
| 541 | + if kind == LaneKind::Video && crate::is_audio(path) { | |
| 417 | 542 | return Err(format!( |
| 418 | 543 | "{} has no picture: it can only play on an audio lane", |
| 419 | - doc.sources[clip.source].path.display() | |
| 544 | + path.display() | |
| 545 | + ) | |
| 546 | + .into()); | |
| 547 | + } | |
| 548 | + // ...and the mirror of it: a still is silent, so a clip playing one | |
| 549 | + // on an audio lane is a segment the audio worker would open a PNG | |
| 550 | + // for. Refused by name here, which is the one door it can arrive | |
| 551 | + // through (`place_stream_at` never puts one there). | |
| 552 | + if kind == LaneKind::Audio && crate::is_image(path) { | |
| 553 | + return Err(format!( | |
| 554 | + "{} is a still image: it can only play on a video lane", | |
| 555 | + path.display() | |
| 420 | 556 | ) |
| 421 | 557 | .into()); |
| 422 | 558 | } |
| @@ -595,6 +731,29 @@ impl PlaybackSession { | ||
| 595 | 731 | // The grade is the composite's at this frame -- the same clip the |
| 596 | 732 | // span itself came from -- and it is constant across the span, so |
| 597 | 733 | // the worker carries it and every frame it converts wears it. |
| 734 | + Some(Span { | |
| 735 | + start, | |
| 736 | + len, | |
| 737 | + from: Some((source, in_frame)), | |
| 738 | + }) if crate::is_image(&self.project.sources()[source].path) => { | |
| 739 | + // A still: the same grade and the same canvas as any other | |
| 740 | + // clip, over a picture decoded once and repeated for the span. | |
| 741 | + DecodeSession::open_still( | |
| 742 | + &self.project.sources()[source].path, | |
| 743 | + in_frame, | |
| 744 | + len, | |
| 745 | + self.project | |
| 746 | + .composite_color_at(start) | |
| 747 | + .copied() | |
| 748 | + .unwrap_or_default(), | |
| 749 | + Composer::new( | |
| 750 | + self.meta.width, | |
| 751 | + self.meta.height, | |
| 752 | + self.project.composite_fit_at(start), | |
| 753 | + ), | |
| 754 | + ) | |
| 755 | + .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}")) | |
| 756 | + } | |
| 598 | 757 | Some(Span { |
| 599 | 758 | start, |
| 600 | 759 | len, |
| @@ -964,7 +1123,10 @@ impl PlaybackSession { | ||
| 964 | 1123 | /// lane it is *placed* there alone, overwriting what it lands on and |
| 965 | 1124 | /// rippling nothing. A file with no picture ([`crate::is_audio`]) is placed |
| 966 | 1125 | /// on the audio lane it was asked for, or on `A1`, and never on a video |
| 967 | - /// lane. A caller never has to ask. | |
| 1126 | + /// lane. A still image ([`crate::is_image`]) is its mirror: the video lane | |
| 1127 | + /// it was asked for or `V1`, never an audio one, and it goes down | |
| 1128 | + /// [`IMAGE_PLACE_SECS`] long rather than at the length it is *allowed* to | |
| 1129 | + /// be trimmed out to. A caller never has to ask. | |
| 968 | 1130 | pub fn place_stream_at( |
| 969 | 1131 | &mut self, |
| 970 | 1132 | timeline_secs: f64, |
| @@ -982,14 +1144,23 @@ impl PlaybackSession { | ||
| 982 | 1144 | if frames == 0 { |
| 983 | 1145 | return Err(format!("{} is not on this timeline", path.display()).into()); |
| 984 | 1146 | } |
| 985 | - let first = self.first_audio()?; | |
| 986 | - audio_matches(&wanted, &first)?; | |
| 1147 | + // A still has no sound to hold to the timeline's -- and no length | |
| 1148 | + // either, so it goes down at [`IMAGE_PLACE_SECS`] rather than at the | |
| 1149 | + // ten minutes it is *allowed* to be dragged out to. | |
| 1150 | + let image = crate::is_image(path); | |
| 1151 | + if !image { | |
| 1152 | + let first = self.first_audio()?; | |
| 1153 | + audio_matches(&wanted, &first)?; | |
| 1154 | + } | |
| 987 | 1155 | let source = self.project.import(path, stream); |
| 988 | 1156 | self.note_frames(source, frames); |
| 989 | 1157 | let clip = Clip { |
| 990 | 1158 | start: 0, |
| 991 | 1159 | in_frame: 0, |
| 992 | - out_frame: frames.max(1), | |
| 1160 | + out_frame: match image { | |
| 1161 | + true => place_frames(frames, self.meta.frame_rate), | |
| 1162 | + false => frames.max(1), | |
| 1163 | + }, | |
| 993 | 1164 | source, |
| 994 | 1165 | link: None, |
| 995 | 1166 | eq: None, |
| @@ -1003,6 +1174,16 @@ impl PlaybackSession { | ||
| 1003 | 1174 | // with it. A lane of the source's own kind takes it as it is dropped; |
| 1004 | 1175 | // only `V1` means the grouped take, since that is the pair the paste |
| 1005 | 1176 | // spans and a second video lane is a layer of its own. |
| 1177 | + // ...and a still is the mirror of a song: a picture and no sound, so a | |
| 1178 | + // video lane and nothing else -- never the grouped take, which would | |
| 1179 | + // put a clip on `A1` for a source the audio worker cannot open. | |
| 1180 | + if image { | |
| 1181 | + let lane = match onto { | |
| 1182 | + Some(lane) if lane.kind == LaneKind::Video => lane, | |
| 1183 | + _ => Lane::V1, | |
| 1184 | + }; | |
| 1185 | + return Ok(self.place_at(lane, timeline_secs, clip)); | |
| 1186 | + } | |
| 1006 | 1187 | let onto = match (crate::is_audio(path), onto) { |
| 1007 | 1188 | // No picture: an audio lane and nothing else, whichever one was |
| 1008 | 1189 | // asked for -- `A1` when none was. |
| @@ -1055,8 +1236,7 @@ impl PlaybackSession { | ||
| 1055 | 1236 | /// What the timeline's audio *is*: source 0's chosen stream, probed. Every |
| 1056 | 1237 | /// other source is held to it. |
| 1057 | 1238 | fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> { |
| 1058 | - let first = &self.project.sources()[0]; | |
| 1059 | - AudioSession::probe(&first.path, first.audio_stream) | |
| 1239 | + first_audio_of(self.project.sources()) | |
| 1060 | 1240 | } |
| 1061 | 1241 | |
| 1062 | 1242 | /// Places `clip` on `lane` alone at the playhead, overwriting what it lands |
| @@ -1109,6 +1289,9 @@ impl PlaybackSession { | ||
| 1109 | 1289 | if crate::is_audio(path) { |
| 1110 | 1290 | return self.import_audio(path); |
| 1111 | 1291 | } |
| 1292 | + if crate::is_image(path) { | |
| 1293 | + return self.import_image(path); | |
| 1294 | + } | |
| 1112 | 1295 | let (meta, _) = Demuxer::open(path)?; |
| 1113 | 1296 | let first = self.first_audio()?; |
| 1114 | 1297 | // Stream 0: an import brings a file in on its first audio track, and |
| @@ -1140,6 +1323,30 @@ impl PlaybackSession { | ||
| 1140 | 1323 | Ok(source) |
| 1141 | 1324 | } |
| 1142 | 1325 | |
| 1326 | + /// The same registration for a still image, and the shortest of the three: | |
| 1327 | + /// a picture has nothing to agree with. No frame rate (it is one picture), | |
| 1328 | + /// no audio (it is silent), and a resolution of its own is what every | |
| 1329 | + /// import is allowed -- the clip is placed on the project canvas by its fit | |
| 1330 | + /// policy. The one refusal left is a file that is not a picture at all, or | |
| 1331 | + /// one too big to compose ([`crate::is_resolution`]), and the header alone | |
| 1332 | + /// answers both. | |
| 1333 | + /// | |
| 1334 | + /// The length noted is the wall a trim is held to, not a duration the file | |
| 1335 | + /// has: see [`image_frames`]. | |
| 1336 | + fn import_image(&mut self, path: &Path) -> crate::Result<usize> { | |
| 1337 | + let (width, height) = crate::decode::image_size(path)?; | |
| 1338 | + if !crate::is_resolution(width, height) { | |
| 1339 | + return Err(format!( | |
| 1340 | + "{} is {width}x{height}, which is not a picture this engine composes", | |
| 1341 | + path.display() | |
| 1342 | + ) | |
| 1343 | + .into()); | |
| 1344 | + } | |
| 1345 | + let source = self.project.import(path, 0); | |
| 1346 | + self.note_frames(source, image_frames(self.meta.frame_rate)); | |
| 1347 | + Ok(source) | |
| 1348 | + } | |
| 1349 | + | |
| 1143 | 1350 | /// Applies an edit and, if it took, reseeks onto the new mapping. `seek` |
| 1144 | 1351 | /// clamps to the new duration and keeps playing playing, so a delete that |
| 1145 | 1352 | /// shortens the timeline past the playhead lands on the last frame. |
| @@ -1428,6 +1635,18 @@ fn matches_timeline( | ||
| 1428 | 1635 | /// rate and layout plays alongside a timeline of mp4s perfectly well. What it |
| 1429 | 1636 | /// cannot do is be copied into an export, which is a refusal of its own, at |
| 1430 | 1637 | /// export time (`AudioSession::copy_multi_streams`). |
| 1638 | +/// What a timeline's audio is held to: the probe of the first source that could | |
| 1639 | +/// have any. A still image is never it -- a picture defines no rate and no | |
| 1640 | +/// layout, and taking its silence for the timeline's would refuse every sound | |
| 1641 | +/// imported after it. `Ok(None)` for a timeline of nothing but stills, which is | |
| 1642 | +/// a silent one. | |
| 1643 | +fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> { | |
| 1644 | + match sources.iter().find(|s| !crate::is_image(&s.path)) { | |
| 1645 | + Some(first) => AudioSession::probe(&first.path, first.audio_stream), | |
| 1646 | + None => Ok(None), | |
| 1647 | + } | |
| 1648 | +} | |
| 1649 | + | |
| 1431 | 1650 | fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> { |
| 1432 | 1651 | // Whole-probe equality: rate and layout, which the audio worker holds every |
| 1433 | 1652 | // source to anyway. Both silent is a match. |
| @@ -1446,6 +1665,26 @@ fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::R | ||
| 1446 | 1665 | .into()) |
| 1447 | 1666 | } |
| 1448 | 1667 | |
| 1668 | +/// How many timeline frames a still image is *held to*: [`IMAGE_MAX_SECS`] of | |
| 1669 | +/// them, since an image has no length of its own. The number a source's own | |
| 1670 | +/// entry in [`PlaybackSession::counts`] gets, so a trim may drag an image out | |
| 1671 | +/// to ten minutes and no further -- and so a saved project reloads, because | |
| 1672 | +/// [`PlaybackSession::open_project`] recomputes exactly this and refuses a clip | |
| 1673 | +/// that ends past it. | |
| 1674 | +fn image_frames(fps: f64) -> u32 { | |
| 1675 | + ((IMAGE_MAX_SECS * fps) | |
| 1676 | + .ceil() | |
| 1677 | + .clamp(1.0, f64::from(u32::MAX))) as u32 | |
| 1678 | +} | |
| 1679 | + | |
| 1680 | +/// How long a still is placed for: [`IMAGE_PLACE_SECS`], never past the length | |
| 1681 | +/// it is held to and never zero (a clip is never empty). | |
| 1682 | +fn place_frames(count: u32, fps: f64) -> u32 { | |
| 1683 | + ((IMAGE_PLACE_SECS * fps) | |
| 1684 | + .ceil() | |
| 1685 | + .clamp(1.0, f64::from(count.max(1)))) as u32 | |
| 1686 | +} | |
| 1687 | + | |
| 1449 | 1688 | /// How many timeline frames a standalone audio file occupies: its playing time |
| 1450 | 1689 | /// rounded *up*, so the last partial frame is still covered rather than cut off, |
| 1451 | 1690 | /// and never zero (a clip is never empty). |
crates/engine/tests/images.rsadded+341 -0
| @@ -0,0 +1,341 @@ | ||
| 1 | +//! Still images as clips: imported into the library, placed on a video lane, | |
| 2 | +//! shown at the project's resolution, trimmed against the length a still is | |
| 3 | +//! held to, saved, reopened and exported. | |
| 4 | +//! | |
| 5 | +//! Every picture assertion is against the *file's own pixels* (read here with | |
| 6 | +//! the `image` crate) rather than against a constant, so a channel swap, a | |
| 7 | +//! vertical flip and a wrong colour matrix all fail rather than agreeing with | |
| 8 | +//! a hard-coded red. | |
| 9 | +//! | |
| 10 | +//! ```text | |
| 11 | +//! cargo test -p engine --test images -- --test-threads=1 --nocapture | |
| 12 | +//! ``` | |
| 13 | + | |
| 14 | +use std::path::PathBuf; | |
| 15 | +use std::sync::Once; | |
| 16 | +use std::time::{Duration, Instant}; | |
| 17 | + | |
| 18 | +use engine::project::{Edge, Lane, LaneKind}; | |
| 19 | +use engine::{DecodeSession, ExportHandle, PlaybackSession}; | |
| 20 | + | |
| 21 | +/// test_av.mp4's rate, which every fixture here shares. | |
| 22 | +const FPS: f64 = 30.0; | |
| 23 | +/// [`playback::IMAGE_MAX_SECS`] at that rate: ten minutes. | |
| 24 | +const CAP: u32 = 18_000; | |
| 25 | +/// What a placed still is five seconds of. | |
| 26 | +const PLACED: u32 = 150; | |
| 27 | + | |
| 28 | +fn asset(name: &str) -> PathBuf { | |
| 29 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 30 | + .join("../../assets") | |
| 31 | + .join(name) | |
| 32 | +} | |
| 33 | + | |
| 34 | +/// Software everywhere, so the suite proves the path every machine has. | |
| 35 | +fn pin_software() { | |
| 36 | + static PIN: Once = Once::new(); | |
| 37 | + PIN.call_once(|| unsafe { | |
| 38 | + std::env::set_var("VE_SW", "1"); | |
| 39 | + std::env::set_var("VE_SW_ENC", "1"); | |
| 40 | + }); | |
| 41 | +} | |
| 42 | + | |
| 43 | +/// The fixture's own pixel at `(x, y)` as RGB -- what the timeline has to show | |
| 44 | +/// there, whatever it scaled the picture to on the way. | |
| 45 | +fn source_rgb(x: u32, y: u32) -> [u8; 3] { | |
| 46 | + let img = image::open(asset("test_still.png")) | |
| 47 | + .expect("the still fixture (scripts/gen_fixtures.sh)") | |
| 48 | + .to_rgb8(); | |
| 49 | + img.get_pixel(x, y).0 | |
| 50 | +} | |
| 51 | + | |
| 52 | +/// One BGRA pixel of a frame as RGB, so both sides of a comparison read alike. | |
| 53 | +fn frame_rgb(bgra: &[u8], width: u32, x: u32, y: u32) -> [u8; 3] { | |
| 54 | + let at = ((y * width + x) * 4) as usize; | |
| 55 | + [bgra[at + 2], bgra[at + 1], bgra[at]] | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// BT.601 is lossy in both directions and the chroma is subsampled, so a | |
| 59 | +/// colour survives to within a few counts rather than exactly. | |
| 60 | +fn close(got: [u8; 3], want: [u8; 3], what: &str) { | |
| 61 | + let off = got | |
| 62 | + .iter() | |
| 63 | + .zip(&want) | |
| 64 | + .map(|(a, b)| a.abs_diff(*b)) | |
| 65 | + .max() | |
| 66 | + .unwrap_or(0); | |
| 67 | + assert!(off <= 6, "{what}: showed {got:?}, the file has {want:?}"); | |
| 68 | +} | |
| 69 | + | |
| 70 | +/// The frame the playhead is on, decoded: a paused seek still decodes, so this | |
| 71 | +/// is what the viewer would be showing. | |
| 72 | +fn frame_at(session: &mut PlaybackSession, secs: f64) -> engine::Frame { | |
| 73 | + session.seek(secs); | |
| 74 | + let target = (secs * FPS) as u32; | |
| 75 | + let started = Instant::now(); | |
| 76 | + loop { | |
| 77 | + if let Some(frame) = session.try_frame() | |
| 78 | + && frame.index >= target | |
| 79 | + { | |
| 80 | + return frame; | |
| 81 | + } | |
| 82 | + assert!( | |
| 83 | + started.elapsed() < Duration::from_secs(20), | |
| 84 | + "no frame at {secs} s (timeline frame {target})" | |
| 85 | + ); | |
| 86 | + std::thread::sleep(Duration::from_millis(5)); | |
| 87 | + } | |
| 88 | +} | |
| 89 | + | |
| 90 | +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { | |
| 91 | + let started = Instant::now(); | |
| 92 | + while !handle.is_finished() { | |
| 93 | + assert!( | |
| 94 | + started.elapsed() < limit, | |
| 95 | + "export did not finish in {limit:?}" | |
| 96 | + ); | |
| 97 | + std::thread::sleep(Duration::from_millis(20)); | |
| 98 | + } | |
| 99 | + handle.result().expect("a finished export has an outcome") | |
| 100 | +} | |
| 101 | + | |
| 102 | +/// An import is a library entry and nothing else -- the same promise every | |
| 103 | +/// other source makes, kept by the one with no length of its own. | |
| 104 | +#[test] | |
| 105 | +fn importing_a_still_fills_the_library_and_places_nothing() { | |
| 106 | + pin_software(); | |
| 107 | + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); | |
| 108 | + session.set_gain(0.0); | |
| 109 | + let before = session.clip_spans(); | |
| 110 | + | |
| 111 | + let source = session.import(&asset("test_still.png")).expect("a picture"); | |
| 112 | + assert_eq!(source, 1, "a second source"); | |
| 113 | + assert_eq!(session.clip_spans(), before, "nothing was placed"); | |
| 114 | + // Ten minutes: the length a still is *held* to, which is what a trim is | |
| 115 | + // walled by and what a reload recomputes. | |
| 116 | + assert_eq!(session.file_frames(&asset("test_still.png")), CAP); | |
| 117 | + | |
| 118 | + // A file that is not a picture at all is refused at the same door, by name. | |
| 119 | + let broken = std::env::temp_dir().join(format!("ve_not_a_png_{}.png", std::process::id())); | |
| 120 | + std::fs::write(&broken, b"this is not a PNG").expect("write the decoy"); | |
| 121 | + let refused = session.import(&broken).expect_err("not a picture"); | |
| 122 | + assert!( | |
| 123 | + refused.to_string().contains("not_a_png"), | |
| 124 | + "the refusal names the file: {refused}" | |
| 125 | + ); | |
| 126 | + assert_eq!(session.sources().len(), 2, "a refusal registers nothing"); | |
| 127 | + let _ = std::fs::remove_file(&broken); | |
| 128 | +} | |
| 129 | + | |
| 130 | +/// The picture itself: placed on a canvas twice its size, the still comes back | |
| 131 | +/// scaled to that canvas with its own colours, the right way up. | |
| 132 | +#[test] | |
| 133 | +fn a_placed_still_shows_its_own_pixels_on_the_canvas() { | |
| 134 | + pin_software(); | |
| 135 | + let still = asset("test_still.png"); | |
| 136 | + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); | |
| 137 | + session.set_gain(0.0); | |
| 138 | + session.import(&still).expect("a picture"); | |
| 139 | + let end = session.timeline_duration(); | |
| 140 | + assert!( | |
| 141 | + session | |
| 142 | + .place_stream_at(end, &still, 0, Some(Lane::V1)) | |
| 143 | + .expect("a still joins any timeline") | |
| 144 | + ); | |
| 145 | + | |
| 146 | + // Placed for five seconds on the video lane, and on no other: a still is | |
| 147 | + // silent, so nothing of it belongs on an audio lane. | |
| 148 | + let placed = *session.lane_clips(Lane::V1).last().expect("the still clip"); | |
| 149 | + assert_eq!(placed.len(), PLACED, "five seconds at 30 fps"); | |
| 150 | + assert_eq!( | |
| 151 | + session.lane_clips(Lane::A1).len(), | |
| 152 | + 1, | |
| 153 | + "no audio clip for it" | |
| 154 | + ); | |
| 155 | + | |
| 156 | + // Half a second into the still, and the picture is the file's: the canvas | |
| 157 | + // is 1280x720 and the image 640x360, so this is also the scaler's answer. | |
| 158 | + let frame = frame_at(&mut session, end + 0.5); | |
| 159 | + assert_eq!((frame.width, frame.height), session.resolution()); | |
| 160 | + let (w, h) = (frame.width, frame.height); | |
| 161 | + close( | |
| 162 | + frame_rgb(&frame.bgra, w, w / 2, h / 4), | |
| 163 | + source_rgb(320, 90), | |
| 164 | + "the top band", | |
| 165 | + ); | |
| 166 | + close( | |
| 167 | + frame_rgb(&frame.bgra, w, w / 2, h * 3 / 4), | |
| 168 | + source_rgb(320, 270), | |
| 169 | + "the bottom band", | |
| 170 | + ); | |
| 171 | + | |
| 172 | + // ...and the frame before the cut is still the video, which is what makes | |
| 173 | + // this a cut rather than a still that swallowed the timeline. | |
| 174 | + let video = frame_at(&mut session, end - 1.0 / FPS); | |
| 175 | + assert_ne!( | |
| 176 | + frame_rgb(&video.bgra, w, w / 2, h / 4), | |
| 177 | + frame_rgb(&frame.bgra, w, w / 2, h / 4), | |
| 178 | + "the video frame before the cut is not the still" | |
| 179 | + ); | |
| 180 | +} | |
| 181 | + | |
| 182 | +/// A still has no length, so the wall is the one the engine gives it: a trim | |
| 183 | +/// may drag the tail out to ten minutes and not one frame further. | |
| 184 | +#[test] | |
| 185 | +fn a_still_trims_out_to_its_cap_and_no_further() { | |
| 186 | + pin_software(); | |
| 187 | + let still = asset("test_still.png"); | |
| 188 | + let mut session = PlaybackSession::open(&still).expect("open the still itself"); | |
| 189 | + // Opened on its own: its own picture is the canvas, and the clip is the | |
| 190 | + // same five seconds a placement makes. | |
| 191 | + assert_eq!(session.resolution(), (640, 360)); | |
| 192 | + assert_eq!(session.lane_clips(Lane::V1)[0].len(), PLACED); | |
| 193 | + assert!(session.lane_clips(Lane::A1).is_empty(), "silent"); | |
| 194 | + | |
| 195 | + let clip = session.lane_clips(Lane::V1)[0]; | |
| 196 | + assert_eq!( | |
| 197 | + session.trim_room(Lane::V1, 0, Edge::End), | |
| 198 | + Some((clip.start + 1, clip.start + CAP)), | |
| 199 | + "the tail may go out to the cap" | |
| 200 | + ); | |
| 201 | + assert!(session.trim_clip(Lane::V1, 0, Edge::End, clip.start + CAP)); | |
| 202 | + assert_eq!(session.lane_clips(Lane::V1)[0].len(), CAP); | |
| 203 | + assert!( | |
| 204 | + !session.trim_clip(Lane::V1, 0, Edge::End, clip.start + CAP + 1), | |
| 205 | + "past the cap is refused" | |
| 206 | + ); | |
| 207 | + // ...and back in, which is the half a five-second title card actually uses. | |
| 208 | + assert!(session.trim_clip(Lane::V1, 0, Edge::End, clip.start + 60)); | |
| 209 | + assert_eq!(session.lane_clips(Lane::V1)[0].len(), 60); | |
| 210 | +} | |
| 211 | + | |
| 212 | +/// Saved and reopened: the clip that comes back plays the same picture for the | |
| 213 | +/// same frames. The reload recomputes the still's length, so a clip trimmed out | |
| 214 | +/// to the cap has to still be inside it -- `open_project` refuses one that is | |
| 215 | +/// not, by name. | |
| 216 | +#[test] | |
| 217 | +fn a_still_survives_the_project_round_trip() { | |
| 218 | + pin_software(); | |
| 219 | + let dir = std::env::temp_dir().join(format!("ve_images_{}", std::process::id())); | |
| 220 | + let _ = std::fs::remove_dir_all(&dir); | |
| 221 | + std::fs::create_dir_all(&dir).expect("scratch dir"); | |
| 222 | + let media = dir.join("test_av.mp4"); | |
| 223 | + let still = dir.join("test_still.png"); | |
| 224 | + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the video"); | |
| 225 | + std::fs::copy(asset("test_still.png"), &still).expect("copy the still"); | |
| 226 | + | |
| 227 | + let mut session = PlaybackSession::open(&media).expect("open the fixture"); | |
| 228 | + session.set_gain(0.0); | |
| 229 | + session.import(&still).expect("a picture"); | |
| 230 | + let end = session.timeline_duration(); | |
| 231 | + assert!( | |
| 232 | + session | |
| 233 | + .place_stream_at(end, &still, 0, Some(Lane::V1)) | |
| 234 | + .expect("a still joins any timeline") | |
| 235 | + ); | |
| 236 | + // Trimmed well past the five seconds it went down as, so the reload's own | |
| 237 | + // length check has something to be wrong about. | |
| 238 | + let clip = *session.lane_clips(Lane::V1).last().expect("the still clip"); | |
| 239 | + let idx = session.lane_clips(Lane::V1).len() - 1; | |
| 240 | + assert!(session.trim_clip(Lane::V1, idx, Edge::End, clip.start + 900)); | |
| 241 | + let before: Vec<_> = session.lane_clips(Lane::V1).to_vec(); | |
| 242 | + | |
| 243 | + let project = dir.join("stills.edith"); | |
| 244 | + session.save_project(&project).expect("save"); | |
| 245 | + let reopened = PlaybackSession::open_project(&project).expect("reopen"); | |
| 246 | + assert_eq!(reopened.lane_clips(Lane::V1), &before[..]); | |
| 247 | + assert_eq!(reopened.file_frames(&still), CAP, "the cap came back"); | |
| 248 | + | |
| 249 | + // The one thing a hand-written project could say that no edit can: a still | |
| 250 | + // on an audio lane, which the audio worker would open a PNG for. | |
| 251 | + let text = std::fs::read_to_string(&project).expect("read the project"); | |
| 252 | + let hacked = text.replace("V1", "A2"); | |
| 253 | + let bad = dir.join("hacked.edith"); | |
| 254 | + std::fs::write(&bad, &hacked).expect("write the hacked project"); | |
| 255 | + if hacked != text { | |
| 256 | + let Err(refused) = PlaybackSession::open_project(&bad) else { | |
| 257 | + panic!("a still cannot be heard: the audio lane took it"); | |
| 258 | + }; | |
| 259 | + assert!( | |
| 260 | + refused.to_string().contains("still image"), | |
| 261 | + "the refusal says what it is: {refused}" | |
| 262 | + ); | |
| 263 | + } | |
| 264 | + let _ = std::fs::remove_dir_all(&dir); | |
| 265 | +} | |
| 266 | + | |
| 267 | +/// The export is what was watched: a timeline of video then still comes back | |
| 268 | +/// out of the mp4 as video then still, with the still's own colours in it. | |
| 269 | +#[test] | |
| 270 | +fn a_mixed_timeline_exports_the_still_at_the_cut() { | |
| 271 | + pin_software(); | |
| 272 | + let still = asset("test_still.png"); | |
| 273 | + // The silent 640x360 fixture: no AAC track to copy and no scaling to do, | |
| 274 | + // so what this measures is the still in the encoder and nothing else. | |
| 275 | + let mut session = PlaybackSession::open(asset("test_mismatch.mp4")).expect("open the fixture"); | |
| 276 | + session.import(&still).expect("a picture"); | |
| 277 | + // One second of video, then one second of still: 60 frames to encode. | |
| 278 | + assert!(session.trim_clip(Lane::V1, 0, Edge::End, 30)); | |
| 279 | + let end = session.timeline_duration(); | |
| 280 | + assert!( | |
| 281 | + session | |
| 282 | + .place_stream_at(end, &still, 0, Some(Lane::V1)) | |
| 283 | + .expect("a still joins any timeline") | |
| 284 | + ); | |
| 285 | + assert!(session.trim_clip(Lane::V1, 1, Edge::End, 60)); | |
| 286 | + assert_eq!(session.lane_clips(Lane::V1).len(), 2); | |
| 287 | + assert_eq!(session.resolution(), (640, 360)); | |
| 288 | + | |
| 289 | + let out = std::env::temp_dir().join(format!("ve_images_export_{}.mp4", std::process::id())); | |
| 290 | + let _ = std::fs::remove_file(&out); | |
| 291 | + wait(&session.export_to(&out), Duration::from_secs(300)).expect("export"); | |
| 292 | + | |
| 293 | + let (meta, frames) = DecodeSession::open(&out).expect("reopen the export"); | |
| 294 | + assert_eq!((meta.width, meta.height), (640, 360)); | |
| 295 | + let decoded: Vec<_> = frames.into_iter().collect(); | |
| 296 | + assert_eq!(decoded.len(), 60, "one second of video, one of still"); | |
| 297 | + // Well inside the still half, so no GOP smear from the cut reaches it. | |
| 298 | + let frame = &decoded[50]; | |
| 299 | + close( | |
| 300 | + frame_rgb(&frame.bgra, 640, 320, 90), | |
| 301 | + source_rgb(320, 90), | |
| 302 | + "the exported top band", | |
| 303 | + ); | |
| 304 | + close( | |
| 305 | + frame_rgb(&frame.bgra, 640, 320, 270), | |
| 306 | + source_rgb(320, 270), | |
| 307 | + "the exported bottom band", | |
| 308 | + ); | |
| 309 | + // ...and the video half is still the video: the cut is in the file. | |
| 310 | + assert_ne!( | |
| 311 | + frame_rgb(&decoded[10].bgra, 640, 320, 90), | |
| 312 | + frame_rgb(&frame.bgra, 640, 320, 90), | |
| 313 | + "the video half is not the still" | |
| 314 | + ); | |
| 315 | + let _ = std::fs::remove_file(&out); | |
| 316 | +} | |
| 317 | + | |
| 318 | +/// Which lane a still may land on is the engine's answer, not a caller's: a | |
| 319 | +/// picture asked for on an audio lane goes on the video one instead, exactly as | |
| 320 | +/// a song asked for on a video lane goes on `A1`. | |
| 321 | +#[test] | |
| 322 | +fn a_still_asked_for_on_an_audio_lane_lands_on_the_video_one() { | |
| 323 | + pin_software(); | |
| 324 | + let still = asset("test_still.png"); | |
| 325 | + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); | |
| 326 | + session.set_gain(0.0); | |
| 327 | + session.import(&still).expect("a picture"); | |
| 328 | + let a2 = session.add_lane(LaneKind::Audio); | |
| 329 | + let end = session.timeline_duration(); | |
| 330 | + assert!( | |
| 331 | + session | |
| 332 | + .place_stream_at(end, &still, 0, Some(a2)) | |
| 333 | + .expect("a still joins any timeline") | |
| 334 | + ); | |
| 335 | + assert!(session.lane_clips(a2).is_empty(), "not on the audio lane"); | |
| 336 | + assert_eq!( | |
| 337 | + session.lane_clips(Lane::V1).len(), | |
| 338 | + 2, | |
| 339 | + "on the video lane instead" | |
| 340 | + ); | |
| 341 | +} |
scripts/gen_fixtures.shmodified+9 -0
| @@ -148,6 +148,15 @@ for fmt in mp3 wav flac ogg m4a aac; do | ||
| 148 | 148 | -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ |
| 149 | 149 | "assets/test_tone.$fmt" |
| 150 | 150 | done |
| 151 | +# Still-image fixture: the source with a picture and no timeline in it. Two | |
| 152 | +# bands rather than one colour, so a test can tell top from bottom (a flipped | |
| 153 | +# decode) and red from blue (a swapped channel order); 640x360, which is 16:9 | |
| 154 | +# like the video fixtures, so a Fit onto 1280x720 covers the canvas with no | |
| 155 | +# bars and every pixel of the exported frame is the image. | |
| 156 | +ffmpeg -y -f lavfi -i "color=c=red:s=640x180,format=rgb24" \ | |
| 157 | + -f lavfi -i "color=c=blue:s=640x180,format=rgb24" \ | |
| 158 | + -filter_complex "[0:v][1:v]vstack=inputs=2,format=rgb24" \ | |
| 159 | + -frames:v 1 assets/test_still.png | |
| 151 | 160 | # The refusal fixture: same tone at 48k, which one output device cannot mix |
| 152 | 161 | # with a 44.1k timeline. |
| 153 | 162 | ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ |