From 30d430d8d028945be3a5063aeb3a0236aeb12f89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 18:35:15 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(timeline):=20still=20images=20?= =?UTF-8?q?import=20and=20place=20as=20clips?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A PNG, JPEG or WebP is a source like any other: it imports into the library, drags onto a video lane, shows at the playhead, trims, saves and exports. `engine::is_image` is the door, beside `is_audio`, and every choice it forces is made in one place. The decisions, spelled out: - Extensions: png, jpg, jpeg, webp -- exactly what the `image` crate is built with here. Anything else is refused by the door that refuses a .txt. - Length: an image has none, so it is *held to* ten minutes (600 s at the timeline's rate) and *placed* at five seconds. The cap is finite on purpose -- a u32::MAX sentinel would hand a trim drag a wall past anything the timeline can hold -- and it is recomputed identically at load, so a clip trimmed out to it reopens. - Image-first project: its own picture is the canvas (a still *has* a resolution, unlike a song) at 30 fps, silent, one 5 s clip on V1. The A2 audio-only precedent for everything else. - Scaling: none of its own. The still is decoded once to I420 and goes through the same grade, the same `Composer` and the same conversion a decoded picture does, so a 640x360 image on a 1280x720 canvas is letterboxed by its fit policy and never stretched. - Lanes: the mirror of a song. A still goes on the video lane it was asked for or on V1, never on an audio one, and never as a grouped take -- a clip on A1 playing a PNG is a segment the audio worker cannot open. Hand-written projects are refused by name. - The timeline's audio parameters are now the first source that *could* have any, so an image as source 0 no longer holds every later import to its silence. Playback opens a still worker (one conversion, then a memcpy per frame, as the black-gap worker does); the export's `ClipDecoder` hands the same planes out for as long as the span runs, so a mixed video/still timeline encodes at the cut. tests: engine/tests/images.rs -- import registers only, placed pixels match the file's own (top/bottom bands catch a flip, RGB order catches a swap), trim walls at the cap, .edith round trip incl. the audio-lane refusal, mp4 export pixel-checked at the cut, audio-lane placement lands on V1. Fixture: scripts/gen_fixtures.sh writes assets/test_still.png. --- Cargo.lock | 1 + crates/app/src/main.rs | 87 ++++++++- crates/engine/Cargo.toml | 14 ++ crates/engine/src/decode.rs | 164 ++++++++++++++++ crates/engine/src/export.rs | 17 +- crates/engine/src/lib.rs | 37 +++- crates/engine/src/playback.rs | 263 ++++++++++++++++++++++++-- crates/engine/tests/images.rs | 341 ++++++++++++++++++++++++++++++++++ scripts/gen_fixtures.sh | 9 + 9 files changed, 910 insertions(+), 23 deletions(-) create mode 100644 crates/engine/tests/images.rs diff --git a/Cargo.lock b/Cargo.lock index b0c5af7..8f6d6d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1632,6 +1632,7 @@ version = "0.1.0" dependencies = [ "flacenc", "hound", + "image", "libloading", "mp4", "oxideav-ac3", diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index edd4b06..32c184b 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -459,6 +459,12 @@ struct Player { /// presence means "asked" -- and an empty list is a silent file, which is /// exactly one row and no stream tags. streams: HashMap>, + /// How big each still source's picture is, read from its header once and + /// kept -- what a library row and its card say about a file that has no + /// streams to describe. Filled like `streams`: presence means "asked", and + /// `None` is a file with no picture to report (every source that is not an + /// image, and one whose header would not read). + sizes: HashMap>, /// The copied clip. Frame ranges only, so it survives the clip it was taken /// from being deleted -- and it outlives the selection. clipboard: Option, @@ -1286,6 +1292,15 @@ impl Player { let Some(session) = &self.session else { return; }; + // How big each still is, for the row that has to say so. Inline, unlike + // the two below: an image header is a few bytes off the front of the + // file, where a sample table is a parse and a decode is a second. + for path in unseen_paths(session.sources(), &self.sizes) { + let size = engine::is_image(&path) + .then(|| engine::image_size(&path).ok()) + .flatten(); + self.sizes.insert(path, size); + } // Which audio streams each file has, for the library's rows. Header // only, but a big file's sample tables are not free to parse, so it // goes off the render thread like the peaks do. @@ -1564,6 +1579,18 @@ impl Player { cx.notify(); return; } + // ...and the mirror of it: a still is silent, so an audio lane is the + // one place it cannot go. The engine puts it on `V1` regardless + // (`place_stream_at`); this is the word that says why it moved. + if engine::is_image(path) && onto.is_some_and(|lane| lane.kind == LaneKind::Audio) { + let name = file_name(path); + let lane = onto.expect("checked above").label(); + self.notice = Some( + format!("NOT ON {lane} — {name} is a still image; drop it on a video lane").into(), + ); + cx.notify(); + return; + } // The engine's own length for the file, noted when the import took it // in: a row that has never been on a lane is placeable at its full // length, which is the whole point of an import that only fills the @@ -2561,6 +2588,17 @@ impl Player { "{} — audio only · drag onto the audio lane, or Add at playhead", row.path.display() ), + // A still is the mirror: its own size (the timeline's meta + // describes video, and a picture placed on that canvas is not + // the same shape), no frame rate, and one kind of lane. + (None, _) if engine::is_image(&row.path) => format!( + "{} — still image{} · drag onto a video lane, or Add at playhead", + row.path.display(), + match self.sizes.get(&row.path).copied().flatten() { + Some((w, h)) => format!(" · {w}x{h}"), + None => String::new(), + } + ), (None, Some(meta)) => format!( "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", row.path.display(), @@ -2578,6 +2616,16 @@ impl Player { // the reason it cannot be used. let under = match &row.unusable { Some(why) => join_detail(&row.detail, why), + // A still has no length to report -- the ten minutes it is + // *held* to is a wall, not a duration -- so the line says what + // it is and how big it is instead. + None if engine::is_image(&row.path) => join_detail( + &row.detail, + &match self.sizes.get(&row.path).copied().flatten() { + Some((w, h)) => format!("still image · {w}x{h}"), + None => "still image".to_string(), + }, + ), None => join_detail( &row.detail, &timecode(f64::from(row.frames) / self.fps, self.fps), @@ -3829,14 +3877,32 @@ impl Player { .count() }) }); + // A still is described by what it has -- a picture, a size, and a + // longest it may be held for -- where a media file is described by + // its streams and its length. Same card, the rows that mean + // something for this kind of source. + let image = engine::is_image(&path); + let kind = match self.sizes.get(&path).copied().flatten() { + Some((w, h)) => format!("still image · {w}x{h}"), + None => "still image".to_string(), + }; for (label, value) in [ ("File", file_name(&path)), ("Path", path.display().to_string()), - ( - "Audio", - info.map_or_else(|| "no track of its own".to_string(), stream_detail), - ), - ("Length", timecode(f64::from(frames) / self.fps, self.fps)), + match image { + true => ("Picture", kind), + false => ( + "Audio", + info.map_or_else(|| "no track of its own".to_string(), stream_detail), + ), + }, + match image { + true => ( + "Longest hold", + timecode(f64::from(frames) / self.fps, self.fps), + ), + false => ("Length", timecode(f64::from(frames) / self.fps, self.fps)), + }, ("On the timeline", format!("{placed} clips")), ] { rows.push( @@ -4571,12 +4637,14 @@ fn unseen_sources( .collect() } -/// The same, for the per-file stream probe: one entry per *file*, however many -/// of its streams the timeline plays. -fn unseen_paths(sources: &[Source], streams: &HashMap>) -> Vec { +/// The same, for the per-file caches: one entry per *file*, however many of its +/// streams the timeline plays. Generic in the value, because the stream probe +/// and the still's own size are both asked once per file and answered by +/// presence in a map. +fn unseen_paths(sources: &[Source], seen: &HashMap) -> Vec { let mut out: Vec = Vec::new(); for s in sources { - if !streams.contains_key(&s.path) && !out.contains(&s.path) { + if !seen.contains_key(&s.path) && !out.contains(&s.path) { out.push(s.path.clone()); } } @@ -7453,6 +7521,7 @@ fn main() { selected_asset: None, waves: HashMap::new(), streams: HashMap::new(), + sizes: HashMap::new(), clipboard: None, scrubbing: false, trim: None, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 8baefda..f271111 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -12,6 +12,15 @@ edition.workspace = true hound = "3.5.1" flacenc = { version = "0.5.1", default-features = false } libloading = "0.8" +# Still images, decoded once per placed clip (`decode::Still`). Pure Rust like +# everything else here, and already in the app's tree (gpui pulls it), so this +# costs the build nothing new. Exactly the formats `crate::is_image` admits: no +# default features, which would drag in a dozen decoders nothing opens. +image = { version = "0.25", default-features = false, features = [ + "png", + "jpeg", + "webp", +] } mp4 = "0.14" rusty_h264 = { version = "0.8", default-features = false } symphonia-core = "0.6" @@ -37,3 +46,8 @@ symphonia = { version = "0.6", default-features = false, features = [ ] } oxideav-ac3 = "=0.0.10" oxideav-core = "0.1.34" + +[dev-dependencies] +# The still-image suite compares what the timeline shows against the file's own +# pixels rather than against a constant. Already built for the engine itself. +image = { version = "0.25", default-features = false, features = ["png"] } diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 7643e51..3433ab3 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -183,6 +183,71 @@ impl DecodeSession { } } + /// A worker for a still image ([`crate::is_image`]): the file is decoded + /// *once* and the same picture goes down the channel `len` times, indexed + /// from `start_frame` exactly as a decoder's pictures are -- so a placed + /// image is a clip like any other to everything downstream (`try_frame` + /// rewrites those indices, `next_clip` walks off the end of the range). + /// + /// Graded and placed on the canvas once too, before the repeat: a still is + /// the same pixels every frame, so the whole cost of one is one conversion + /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays. + pub(crate) fn open_still( + path: &Path, + start_frame: u32, + len: u32, + color: ColorParams, + canvas: Composer, + ) -> crate::Result { + let still = Still::open(path)?; + let (tx, rx) = sync_channel(2); + let cancel = Arc::new(AtomicBool::new(false)); + if len == 0 { + return Ok(FrameStream { + frames: rx, + worker: Worker { + cancel, + handle: None, + }, + }); + } + // The one conversion, on this thread: it is a few milliseconds and the + // error it could raise has already been raised by `Still::open`. + let first = Render::new(color, canvas).frame( + start_frame, + &still.y, + &still.u, + &still.v, + still.width, + still.height, + ); + let worker_cancel = Arc::clone(&cancel); + let handle = thread::Builder::new() + .name("still".into()) + .spawn(move || { + let (width, height, bgra) = (first.width, first.height, first.bgra); + for index in 0..len { + if worker_cancel.load(Ordering::Relaxed) { + return; + } + let frame = Frame { + index: start_frame + index, + width, + height, + bgra: bgra.clone(), + }; + if tx.send(frame).is_err() { + return; // caller moved on + } + } + }) + .ok(); + Ok(FrameStream { + frames: rx, + worker: Worker { cancel, handle }, + }) + } + /// As [`DecodeSession::open_range`], but the caller gets the whole /// [`Worker`] and can therefore *wait* for it, and the range is graded by /// `color` -- the clip's own setting, folded into the conversion the frames @@ -362,6 +427,105 @@ impl Render { } } +/// One still image, decoded to tightly packed I420 -- the shape every other +/// source arrives in, so a placed image goes through the same grade, the same +/// canvas and the same conversion as a decoded picture and there is no second +/// pixel path to keep in step. +/// +/// Held whole rather than streamed: an image *is* one picture, and the file is +/// read once per span that plays it. +pub(crate) struct Still { + pub(crate) y: Vec, + pub(crate) u: Vec, + pub(crate) v: Vec, + pub(crate) width: u32, + pub(crate) height: u32, +} + +impl Still { + /// Decodes `path`. Refused by name for a picture that is not one + /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project + /// file are both held to cannot be walked around by a 30000-pixel-wide PNG. + pub(crate) fn open(path: &Path) -> crate::Result { + let reader = image::ImageReader::open(path)?.with_guessed_format()?; + let rgb = reader + .decode() + .map_err(|e| format!("{}: {e}", path.display()))? + .to_rgb8(); + let (width, height) = rgb.dimensions(); + if !crate::is_resolution(width, height) { + return Err(format!( + "{} is {width}x{height}, which is not a picture this engine composes", + path.display() + ) + .into()); + } + let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize); + Ok(Self { + y, + u, + v, + width, + height, + }) + } + + /// The planes as an export's decoder hands them over, so a still and a + /// decoded picture are the same value to `export::run`. + pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { + (&self.y, &self.u, &self.v, self.width, self.height) + } +} + +/// How big the picture in `path` is, from its header alone -- what a library row +/// says about a file it has not placed anywhere. The whole file is not decoded. +pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> { + Ok(image::ImageReader::open(path)? + .with_guessed_format()? + .into_dimensions() + .map_err(|e| format!("{}: {e}", path.display()))?) +} + +/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse +/// of [`crate::convert::i420_to_bgra`], so a still round-trips to the colour it +/// was authored in (`images::still_pixels_match_the_source_image` measures it). +/// +/// Chroma is the 2x2 box average, and an odd edge averages the samples it has -- +/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape +/// [`crate::scale::Composer::place`] panics on anything else for. +fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec, Vec, Vec) { + let (cw, ch) = crate::scale::chroma_dims(width, height); + let mut y = vec![0u8; width * height]; + let mut u = vec![0u8; cw * ch]; + let mut v = vec![0u8; cw * ch]; + for row in 0..height { + for col in 0..width { + let p = (row * width + col) * 3; + let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32); + y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8; + } + } + for crow in 0..ch { + for ccol in 0..cw { + let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32); + for row in crow * 2..(crow * 2 + 2).min(height) { + for col in ccol * 2..(ccol * 2 + 2).min(width) { + let p = (row * width + col) * 3; + sr += rgb[p] as i32; + sg += rgb[p + 1] as i32; + sb += rgb[p + 2] as i32; + n += 1; + } + } + let n = n.max(1); + let (r, g, b) = (sr / n, sg / n, sb / n); + u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8; + v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8; + } + } + (y, u, v) +} + /// `None` when the software path must be used: forced by `VE_SW=1`, or the /// plugin is absent/broken/unable to open this particular file. fn open_hw(path: &PathBuf, start_frame: u32) -> Option { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index c85eda6..73c049a 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -279,7 +279,11 @@ fn run( .lane(lane) .iter() .enumerate() - .find(|(idx, _)| project.eq_of(lane, *idx).is_some_and(|eq| !eq.is_identity())) + .find(|(idx, _)| { + project + .eq_of(lane, *idx) + .is_some_and(|eq| !eq.is_identity()) + }) .map(|(idx, clip)| (clip.start, idx)) { return Err(format!( @@ -732,10 +736,20 @@ impl Enc { enum ClipDecoder { Hw(HwSession), Sw(SwDecoder), + /// A still image: one picture, handed out for as long as the span runs. + /// It is decoded here rather than in `run`'s loop for the same reason the + /// other two are opened there -- the span's pictures come from one place. + Still(crate::decode::Still), } impl ClipDecoder { fn open(path: &Path, start_frame: u32) -> crate::Result { + // Before either decoder: an image is not a stream, so `start_frame` + // means nothing to it -- every frame of a still span is the same + // picture, which is what playback shows for it too. + if crate::is_image(path) { + return Ok(Self::Still(crate::decode::Still::open(path)?)); + } if !forced("VE_SW") && let Some(hw) = HwSession::open_at(path, start_frame) { @@ -747,6 +761,7 @@ impl ClipDecoder { /// The next picture as tightly packed I420, borrowed until the call after. fn next(&mut self) -> crate::Result> { match self { + Self::Still(still) => Ok(Some(still.picture())), Self::Hw(hw) => hw.next_frame(), Self::Sw(sw) => { if !sw.advance()? { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 87b4314..1aa7b84 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -21,7 +21,7 @@ pub use audio::{ AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioProbe, AudioSession, StreamInfo, }; pub use clock::PlaybackClock; -pub use decode::{DecodeSession, Frame}; +pub use decode::{DecodeSession, Frame, image_size}; pub use demux::{Codec, VideoMeta}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; @@ -46,6 +46,23 @@ pub fn is_audio(path: &std::path::Path) -> bool { }) } +/// Whether a path names a still image -- a source with a picture and no sound +/// and no length of its own, which belongs on a video lane and nowhere else. +/// Extension only, lowercased, for [`is_audio`]'s reason: a front-end has to +/// know which lane a dropped file may land on before anything is opened. +/// +/// Exactly the formats `image` is built with here (see `Cargo.toml`): PNG, +/// JPEG and WebP. A `.gif` or a `.tif` is refused by the same door that refuses +/// a `.txt`, which is the honest answer until a decoder for it is compiled in. +pub fn is_image(path: &std::path::Path) -> bool { + path.extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!( + e.to_ascii_lowercase().as_str(), + "png" | "jpg" | "jpeg" | "webp" + ) + }) +} + /// The largest picture this engine composes onto, either way: 8K, which is where /// a per-frame buffer stops being a sane thing to allocate. pub const MAX_RESOLUTION: u32 = 7680; @@ -90,4 +107,22 @@ mod tests { assert!(!super::is_audio(Path::new(name)), "{name}"); } } + + #[test] + fn is_image_admits_the_formats_the_decoder_is_built_with() { + for name in ["shot.png", "a.JPG", "b.jpeg", "c.webp"] { + assert!(super::is_image(Path::new(name)), "{name}"); + } + // Media, projects, the still formats no decoder is compiled in for, + // and a file with no extension: all of them go elsewhere. The two + // predicates never both hold -- which lane a file may land on is one + // answer, not two. + for name in ["clip.mp4", "song.mp3", "cut.edith", "d.gif", "e.tif", "png"] { + assert!(!super::is_image(Path::new(name)), "{name}"); + assert!( + !(super::is_image(Path::new(name)) && super::is_audio(Path::new(name))), + "{name}" + ); + } + } } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 09a3a52..cc4fa79 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -46,6 +46,28 @@ const RING_FULL_WAIT: Duration = Duration::from_millis(10); /// placed in frames. const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); +/// The frame rate a timeline scaffolded from a still image runs at, for +/// [`AUDIO_ONLY_CANVAS`]'s reason: nothing was shot on it. The *size* is not +/// invented the same way -- an image has a picture of its own, and that picture +/// is the canvas a later import meets. +const IMAGE_ONLY_RATE: f64 = 30.0; + +/// How long a still image *is*, in seconds: the wall a trim may drag its edge +/// out to, since an image has no length of its own to be walled by. Ten +/// minutes, which is a title card nobody will run out of and still a finite +/// number -- a `u32::MAX` sentinel here would make [`Self::trim_room`] hand a +/// drag a wall past what the timeline can hold. +/// +/// ponytail: a still cannot be held longer than this. Upgrade path is a +/// per-source length the project file carries, which every `counts` reader +/// would then have to take from the document rather than from the file. +const IMAGE_MAX_SECS: f64 = 600.0; + +/// How long a still image is *placed* for: five seconds, the length a picture +/// gets when nobody has said one -- trimmable either way up to +/// [`IMAGE_MAX_SECS`]. +const IMAGE_PLACE_SECS: f64 = 5.0; + /// The output half of a session: the device, plus what the feeder has handed it. /// Cloned into the feeder thread; every field that matters is shared. #[derive(Clone)] @@ -175,6 +197,12 @@ impl PlaybackSession { if crate::is_audio(&path) { return Self::open_audio_only(&path); } + // A still is the other source with no timeline in it: it has a picture + // (which becomes the canvas) but no rate and no length, so it too + // scaffolds rather than describes. + if crate::is_image(&path) { + return Self::open_image_only(&path); + } // `open_worker` rather than `open` purely for the worker handle: the // field has to exist from the start for the first seek to use it. // Ungraded: a file just opened has one clip per lane and nothing has @@ -316,6 +344,71 @@ impl PlaybackSession { }) } + /// Opens a still image ([`crate::is_image`]) as a timeline of its own: one + /// clip on `V1`, [`IMAGE_PLACE_SECS`] long, over silence. The *canvas* is + /// the image's own picture -- unlike a song, a still has one, and inventing + /// a 1080p canvas around a 640x360 PNG would letterbox it against nothing. + /// The frame rate is [`IMAGE_ONLY_RATE`], for the reason an audio-only + /// timeline has one at all: nothing was shot on it. + /// + /// Wall time keeps the clock, as it does for any silent source. + fn open_image_only(path: &Path) -> crate::Result { + // Decoded here rather than probed: this is the door a `.png` that is + // not one comes to, and the picture is wanted a line later anyway. + let still = crate::decode::Still::open(path)?; + let meta = VideoMeta { + width: still.width, + height: still.height, + frame_rate: IMAGE_ONLY_RATE, + // Its length is the wall a trim is held to, exactly as a song's + // playing time is -- see [`image_frames`]. + frame_count: image_frames(IMAGE_ONLY_RATE), + codec: Codec::H264, + }; + let clip = Clip { + start: 0, + in_frame: 0, + out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE), + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + }; + // No group and no audio clip: a still is silent, and a clip on `A1` + // playing from a PNG is a source the audio worker cannot open. + let project = Project::from_parts( + vec![Source::new(path, 0)], + vec![(LaneKind::Video, vec![clip]), (LaneKind::Audio, Vec::new())], + Vec::new(), + Vec::new(), + )?; + let span = project.composite_span_at(0); + // The placeholder the first seek supersedes, opened here for `open`'s + // reason: the field has to exist before anything can seek. + let stream = DecodeSession::open_still( + path, + 0, + span.map_or(1, |s| s.len), + ColorParams::default(), + Composer::passthrough(), + )?; + Ok(Self { + meta, + native: (meta.width, meta.height), + frames: stream.frames, + worker: stream.worker, + retired: Vec::new(), + clock: PlaybackClock::new(ClockSource::Wall), + audio: None, + audio_disabled: None, + project, + counts: vec![meta.frame_count], + span, + eos: false, + }) + } + /// Opens a project file written by [`save_project`](Self::save_project): /// the whole timeline, restored to where its playhead stood, paused like /// [`open`](Self::open). @@ -367,6 +460,28 @@ impl PlaybackSession { }; (meta, DecodeSession::open_black(width, height, 1)) } + // ...and a still scaffolds its own picture as the canvas, exactly + // as a fresh `open_image_only` does, with the same placeholder + // stream the `seek` at the end supersedes. + false if crate::is_image(&first.path) => { + let still = crate::decode::Still::open(&first.path) + .map_err(|e| format!("source {}: {e}", first.path.display()))?; + let meta = VideoMeta { + width: still.width, + height: still.height, + frame_rate: IMAGE_ONLY_RATE, + frame_count: image_frames(IMAGE_ONLY_RATE), + codec: Codec::H264, + }; + let stream = DecodeSession::open_still( + &first.path, + 0, + 1, + ColorParams::default(), + Composer::passthrough(), + )?; + (meta, stream) + } false => DecodeSession::open_worker( &first.path, 0, @@ -384,10 +499,20 @@ impl PlaybackSession { meta.width = width; meta.height = height; } - let first_audio = AudioSession::probe(&first.path, first.audio_stream)?; + let first_audio = first_audio_of(&doc.sources)?; let mut counts = vec![meta.frame_count]; for source in &doc.sources[1..] { + // A still has neither a rate to match nor a track to match with: + // its length is the one it is held to, recomputed exactly as the + // import that first noted it did ([`image_frames`]), which is what + // makes the clip check below meaningful on a reload. + if crate::is_image(&source.path) { + crate::decode::image_size(&source.path) + .map_err(|e| format!("source {}: {e}", source.path.display()))?; + counts.push(image_frames(meta.frame_rate)); + continue; + } // A source with no picture is checked on what it does have, and // its length is its playing time -- the same two answers `import` // gave it when it first joined the timeline. @@ -407,16 +532,27 @@ impl PlaybackSession { // (or hand-edited) project files are the one door this can come in // through, so it is refused by name here rather than becoming a clip // that decodes to nothing. - for clip in doc + for (kind, clip) in doc .lanes .iter() - .filter(|(kind, _)| *kind == LaneKind::Video) - .flat_map(|(_, clips)| clips) + .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip))) { - if crate::is_audio(&doc.sources[clip.source].path) { + let path = &doc.sources[clip.source].path; + if kind == LaneKind::Video && crate::is_audio(path) { return Err(format!( "{} has no picture: it can only play on an audio lane", - doc.sources[clip.source].path.display() + path.display() + ) + .into()); + } + // ...and the mirror of it: a still is silent, so a clip playing one + // on an audio lane is a segment the audio worker would open a PNG + // for. Refused by name here, which is the one door it can arrive + // through (`place_stream_at` never puts one there). + if kind == LaneKind::Audio && crate::is_image(path) { + return Err(format!( + "{} is a still image: it can only play on a video lane", + path.display() ) .into()); } @@ -595,6 +731,29 @@ impl PlaybackSession { // The grade is the composite's at this frame -- the same clip the // span itself came from -- and it is constant across the span, so // the worker carries it and every frame it converts wears it. + Some(Span { + start, + len, + from: Some((source, in_frame)), + }) if crate::is_image(&self.project.sources()[source].path) => { + // A still: the same grade and the same canvas as any other + // clip, over a picture decoded once and repeated for the span. + DecodeSession::open_still( + &self.project.sources()[source].path, + in_frame, + len, + self.project + .composite_color_at(start) + .copied() + .unwrap_or_default(), + Composer::new( + self.meta.width, + self.meta.height, + self.project.composite_fit_at(start), + ), + ) + .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}")) + } Some(Span { start, len, @@ -964,7 +1123,10 @@ impl PlaybackSession { /// lane it is *placed* there alone, overwriting what it lands on and /// rippling nothing. A file with no picture ([`crate::is_audio`]) is placed /// on the audio lane it was asked for, or on `A1`, and never on a video - /// lane. A caller never has to ask. + /// lane. A still image ([`crate::is_image`]) is its mirror: the video lane + /// it was asked for or `V1`, never an audio one, and it goes down + /// [`IMAGE_PLACE_SECS`] long rather than at the length it is *allowed* to + /// be trimmed out to. A caller never has to ask. pub fn place_stream_at( &mut self, timeline_secs: f64, @@ -982,14 +1144,23 @@ impl PlaybackSession { if frames == 0 { return Err(format!("{} is not on this timeline", path.display()).into()); } - let first = self.first_audio()?; - audio_matches(&wanted, &first)?; + // A still has no sound to hold to the timeline's -- and no length + // either, so it goes down at [`IMAGE_PLACE_SECS`] rather than at the + // ten minutes it is *allowed* to be dragged out to. + let image = crate::is_image(path); + if !image { + let first = self.first_audio()?; + audio_matches(&wanted, &first)?; + } let source = self.project.import(path, stream); self.note_frames(source, frames); let clip = Clip { start: 0, in_frame: 0, - out_frame: frames.max(1), + out_frame: match image { + true => place_frames(frames, self.meta.frame_rate), + false => frames.max(1), + }, source, link: None, eq: None, @@ -1003,6 +1174,16 @@ impl PlaybackSession { // with it. A lane of the source's own kind takes it as it is dropped; // only `V1` means the grouped take, since that is the pair the paste // spans and a second video lane is a layer of its own. + // ...and a still is the mirror of a song: a picture and no sound, so a + // video lane and nothing else -- never the grouped take, which would + // put a clip on `A1` for a source the audio worker cannot open. + if image { + let lane = match onto { + Some(lane) if lane.kind == LaneKind::Video => lane, + _ => Lane::V1, + }; + return Ok(self.place_at(lane, timeline_secs, clip)); + } let onto = match (crate::is_audio(path), onto) { // No picture: an audio lane and nothing else, whichever one was // asked for -- `A1` when none was. @@ -1055,8 +1236,7 @@ impl PlaybackSession { /// What the timeline's audio *is*: source 0's chosen stream, probed. Every /// other source is held to it. fn first_audio(&self) -> crate::Result> { - let first = &self.project.sources()[0]; - AudioSession::probe(&first.path, first.audio_stream) + first_audio_of(self.project.sources()) } /// Places `clip` on `lane` alone at the playhead, overwriting what it lands @@ -1109,6 +1289,9 @@ impl PlaybackSession { if crate::is_audio(path) { return self.import_audio(path); } + if crate::is_image(path) { + return self.import_image(path); + } let (meta, _) = Demuxer::open(path)?; let first = self.first_audio()?; // Stream 0: an import brings a file in on its first audio track, and @@ -1140,6 +1323,30 @@ impl PlaybackSession { Ok(source) } + /// The same registration for a still image, and the shortest of the three: + /// a picture has nothing to agree with. No frame rate (it is one picture), + /// no audio (it is silent), and a resolution of its own is what every + /// import is allowed -- the clip is placed on the project canvas by its fit + /// policy. The one refusal left is a file that is not a picture at all, or + /// one too big to compose ([`crate::is_resolution`]), and the header alone + /// answers both. + /// + /// The length noted is the wall a trim is held to, not a duration the file + /// has: see [`image_frames`]. + fn import_image(&mut self, path: &Path) -> crate::Result { + let (width, height) = crate::decode::image_size(path)?; + if !crate::is_resolution(width, height) { + return Err(format!( + "{} is {width}x{height}, which is not a picture this engine composes", + path.display() + ) + .into()); + } + let source = self.project.import(path, 0); + self.note_frames(source, image_frames(self.meta.frame_rate)); + Ok(source) + } + /// Applies an edit and, if it took, reseeks onto the new mapping. `seek` /// clamps to the new duration and keeps playing playing, so a delete that /// shortens the timeline past the playhead lands on the last frame. @@ -1428,6 +1635,18 @@ fn matches_timeline( /// rate and layout plays alongside a timeline of mp4s perfectly well. What it /// cannot do is be copied into an export, which is a refusal of its own, at /// export time (`AudioSession::copy_multi_streams`). +/// What a timeline's audio is held to: the probe of the first source that could +/// have any. A still image is never it -- a picture defines no rate and no +/// layout, and taking its silence for the timeline's would refuse every sound +/// imported after it. `Ok(None)` for a timeline of nothing but stills, which is +/// a silent one. +fn first_audio_of(sources: &[Source]) -> crate::Result> { + match sources.iter().find(|s| !crate::is_image(&s.path)) { + Some(first) => AudioSession::probe(&first.path, first.audio_stream), + None => Ok(None), + } +} + fn audio_matches(source: &Source, first: &Option) -> crate::Result<()> { // Whole-probe equality: rate and layout, which the audio worker holds every // source to anyway. Both silent is a match. @@ -1446,6 +1665,26 @@ fn audio_matches(source: &Source, first: &Option) -> crate::R .into()) } +/// How many timeline frames a still image is *held to*: [`IMAGE_MAX_SECS`] of +/// them, since an image has no length of its own. The number a source's own +/// entry in [`PlaybackSession::counts`] gets, so a trim may drag an image out +/// to ten minutes and no further -- and so a saved project reloads, because +/// [`PlaybackSession::open_project`] recomputes exactly this and refuses a clip +/// that ends past it. +fn image_frames(fps: f64) -> u32 { + ((IMAGE_MAX_SECS * fps) + .ceil() + .clamp(1.0, f64::from(u32::MAX))) as u32 +} + +/// How long a still is placed for: [`IMAGE_PLACE_SECS`], never past the length +/// it is held to and never zero (a clip is never empty). +fn place_frames(count: u32, fps: f64) -> u32 { + ((IMAGE_PLACE_SECS * fps) + .ceil() + .clamp(1.0, f64::from(count.max(1)))) as u32 +} + /// How many timeline frames a standalone audio file occupies: its playing time /// rounded *up*, so the last partial frame is still covered rather than cut off, /// and never zero (a clip is never empty). diff --git a/crates/engine/tests/images.rs b/crates/engine/tests/images.rs new file mode 100644 index 0000000..e7b17d8 --- /dev/null +++ b/crates/engine/tests/images.rs @@ -0,0 +1,341 @@ +//! Still images as clips: imported into the library, placed on a video lane, +//! shown at the project's resolution, trimmed against the length a still is +//! held to, saved, reopened and exported. +//! +//! Every picture assertion is against the *file's own pixels* (read here with +//! the `image` crate) rather than against a constant, so a channel swap, a +//! vertical flip and a wrong colour matrix all fail rather than agreeing with +//! a hard-coded red. +//! +//! ```text +//! cargo test -p engine --test images -- --test-threads=1 --nocapture +//! ``` + +use std::path::PathBuf; +use std::sync::Once; +use std::time::{Duration, Instant}; + +use engine::project::{Edge, Lane, LaneKind}; +use engine::{DecodeSession, ExportHandle, PlaybackSession}; + +/// test_av.mp4's rate, which every fixture here shares. +const FPS: f64 = 30.0; +/// [`playback::IMAGE_MAX_SECS`] at that rate: ten minutes. +const CAP: u32 = 18_000; +/// What a placed still is five seconds of. +const PLACED: u32 = 150; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Software everywhere, so the suite proves the path every machine has. +fn pin_software() { + static PIN: Once = Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +/// The fixture's own pixel at `(x, y)` as RGB -- what the timeline has to show +/// there, whatever it scaled the picture to on the way. +fn source_rgb(x: u32, y: u32) -> [u8; 3] { + let img = image::open(asset("test_still.png")) + .expect("the still fixture (scripts/gen_fixtures.sh)") + .to_rgb8(); + img.get_pixel(x, y).0 +} + +/// One BGRA pixel of a frame as RGB, so both sides of a comparison read alike. +fn frame_rgb(bgra: &[u8], width: u32, x: u32, y: u32) -> [u8; 3] { + let at = ((y * width + x) * 4) as usize; + [bgra[at + 2], bgra[at + 1], bgra[at]] +} + +/// BT.601 is lossy in both directions and the chroma is subsampled, so a +/// colour survives to within a few counts rather than exactly. +fn close(got: [u8; 3], want: [u8; 3], what: &str) { + let off = got + .iter() + .zip(&want) + .map(|(a, b)| a.abs_diff(*b)) + .max() + .unwrap_or(0); + assert!(off <= 6, "{what}: showed {got:?}, the file has {want:?}"); +} + +/// The frame the playhead is on, decoded: a paused seek still decodes, so this +/// is what the viewer would be showing. +fn frame_at(session: &mut PlaybackSession, secs: f64) -> engine::Frame { + session.seek(secs); + let target = (secs * FPS) as u32; + let started = Instant::now(); + loop { + if let Some(frame) = session.try_frame() + && frame.index >= target + { + return frame; + } + assert!( + started.elapsed() < Duration::from_secs(20), + "no frame at {secs} s (timeline frame {target})" + ); + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +/// An import is a library entry and nothing else -- the same promise every +/// other source makes, kept by the one with no length of its own. +#[test] +fn importing_a_still_fills_the_library_and_places_nothing() { + pin_software(); + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let before = session.clip_spans(); + + let source = session.import(&asset("test_still.png")).expect("a picture"); + assert_eq!(source, 1, "a second source"); + assert_eq!(session.clip_spans(), before, "nothing was placed"); + // Ten minutes: the length a still is *held* to, which is what a trim is + // walled by and what a reload recomputes. + assert_eq!(session.file_frames(&asset("test_still.png")), CAP); + + // A file that is not a picture at all is refused at the same door, by name. + let broken = std::env::temp_dir().join(format!("ve_not_a_png_{}.png", std::process::id())); + std::fs::write(&broken, b"this is not a PNG").expect("write the decoy"); + let refused = session.import(&broken).expect_err("not a picture"); + assert!( + refused.to_string().contains("not_a_png"), + "the refusal names the file: {refused}" + ); + assert_eq!(session.sources().len(), 2, "a refusal registers nothing"); + let _ = std::fs::remove_file(&broken); +} + +/// The picture itself: placed on a canvas twice its size, the still comes back +/// scaled to that canvas with its own colours, the right way up. +#[test] +fn a_placed_still_shows_its_own_pixels_on_the_canvas() { + pin_software(); + let still = asset("test_still.png"); + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + session.import(&still).expect("a picture"); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &still, 0, Some(Lane::V1)) + .expect("a still joins any timeline") + ); + + // Placed for five seconds on the video lane, and on no other: a still is + // silent, so nothing of it belongs on an audio lane. + let placed = *session.lane_clips(Lane::V1).last().expect("the still clip"); + assert_eq!(placed.len(), PLACED, "five seconds at 30 fps"); + assert_eq!( + session.lane_clips(Lane::A1).len(), + 1, + "no audio clip for it" + ); + + // Half a second into the still, and the picture is the file's: the canvas + // is 1280x720 and the image 640x360, so this is also the scaler's answer. + let frame = frame_at(&mut session, end + 0.5); + assert_eq!((frame.width, frame.height), session.resolution()); + let (w, h) = (frame.width, frame.height); + close( + frame_rgb(&frame.bgra, w, w / 2, h / 4), + source_rgb(320, 90), + "the top band", + ); + close( + frame_rgb(&frame.bgra, w, w / 2, h * 3 / 4), + source_rgb(320, 270), + "the bottom band", + ); + + // ...and the frame before the cut is still the video, which is what makes + // this a cut rather than a still that swallowed the timeline. + let video = frame_at(&mut session, end - 1.0 / FPS); + assert_ne!( + frame_rgb(&video.bgra, w, w / 2, h / 4), + frame_rgb(&frame.bgra, w, w / 2, h / 4), + "the video frame before the cut is not the still" + ); +} + +/// A still has no length, so the wall is the one the engine gives it: a trim +/// may drag the tail out to ten minutes and not one frame further. +#[test] +fn a_still_trims_out_to_its_cap_and_no_further() { + pin_software(); + let still = asset("test_still.png"); + let mut session = PlaybackSession::open(&still).expect("open the still itself"); + // Opened on its own: its own picture is the canvas, and the clip is the + // same five seconds a placement makes. + assert_eq!(session.resolution(), (640, 360)); + assert_eq!(session.lane_clips(Lane::V1)[0].len(), PLACED); + assert!(session.lane_clips(Lane::A1).is_empty(), "silent"); + + let clip = session.lane_clips(Lane::V1)[0]; + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::End), + Some((clip.start + 1, clip.start + CAP)), + "the tail may go out to the cap" + ); + assert!(session.trim_clip(Lane::V1, 0, Edge::End, clip.start + CAP)); + assert_eq!(session.lane_clips(Lane::V1)[0].len(), CAP); + assert!( + !session.trim_clip(Lane::V1, 0, Edge::End, clip.start + CAP + 1), + "past the cap is refused" + ); + // ...and back in, which is the half a five-second title card actually uses. + assert!(session.trim_clip(Lane::V1, 0, Edge::End, clip.start + 60)); + assert_eq!(session.lane_clips(Lane::V1)[0].len(), 60); +} + +/// Saved and reopened: the clip that comes back plays the same picture for the +/// same frames. The reload recomputes the still's length, so a clip trimmed out +/// to the cap has to still be inside it -- `open_project` refuses one that is +/// not, by name. +#[test] +fn a_still_survives_the_project_round_trip() { + pin_software(); + let dir = std::env::temp_dir().join(format!("ve_images_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let media = dir.join("test_av.mp4"); + let still = dir.join("test_still.png"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the video"); + std::fs::copy(asset("test_still.png"), &still).expect("copy the still"); + + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + session.import(&still).expect("a picture"); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &still, 0, Some(Lane::V1)) + .expect("a still joins any timeline") + ); + // Trimmed well past the five seconds it went down as, so the reload's own + // length check has something to be wrong about. + let clip = *session.lane_clips(Lane::V1).last().expect("the still clip"); + let idx = session.lane_clips(Lane::V1).len() - 1; + assert!(session.trim_clip(Lane::V1, idx, Edge::End, clip.start + 900)); + let before: Vec<_> = session.lane_clips(Lane::V1).to_vec(); + + let project = dir.join("stills.edith"); + session.save_project(&project).expect("save"); + let reopened = PlaybackSession::open_project(&project).expect("reopen"); + assert_eq!(reopened.lane_clips(Lane::V1), &before[..]); + assert_eq!(reopened.file_frames(&still), CAP, "the cap came back"); + + // The one thing a hand-written project could say that no edit can: a still + // on an audio lane, which the audio worker would open a PNG for. + let text = std::fs::read_to_string(&project).expect("read the project"); + let hacked = text.replace("V1", "A2"); + let bad = dir.join("hacked.edith"); + std::fs::write(&bad, &hacked).expect("write the hacked project"); + if hacked != text { + let Err(refused) = PlaybackSession::open_project(&bad) else { + panic!("a still cannot be heard: the audio lane took it"); + }; + assert!( + refused.to_string().contains("still image"), + "the refusal says what it is: {refused}" + ); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// The export is what was watched: a timeline of video then still comes back +/// out of the mp4 as video then still, with the still's own colours in it. +#[test] +fn a_mixed_timeline_exports_the_still_at_the_cut() { + pin_software(); + let still = asset("test_still.png"); + // The silent 640x360 fixture: no AAC track to copy and no scaling to do, + // so what this measures is the still in the encoder and nothing else. + let mut session = PlaybackSession::open(asset("test_mismatch.mp4")).expect("open the fixture"); + session.import(&still).expect("a picture"); + // One second of video, then one second of still: 60 frames to encode. + assert!(session.trim_clip(Lane::V1, 0, Edge::End, 30)); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &still, 0, Some(Lane::V1)) + .expect("a still joins any timeline") + ); + assert!(session.trim_clip(Lane::V1, 1, Edge::End, 60)); + assert_eq!(session.lane_clips(Lane::V1).len(), 2); + assert_eq!(session.resolution(), (640, 360)); + + let out = std::env::temp_dir().join(format!("ve_images_export_{}.mp4", std::process::id())); + let _ = std::fs::remove_file(&out); + wait(&session.export_to(&out), Duration::from_secs(300)).expect("export"); + + let (meta, frames) = DecodeSession::open(&out).expect("reopen the export"); + assert_eq!((meta.width, meta.height), (640, 360)); + let decoded: Vec<_> = frames.into_iter().collect(); + assert_eq!(decoded.len(), 60, "one second of video, one of still"); + // Well inside the still half, so no GOP smear from the cut reaches it. + let frame = &decoded[50]; + close( + frame_rgb(&frame.bgra, 640, 320, 90), + source_rgb(320, 90), + "the exported top band", + ); + close( + frame_rgb(&frame.bgra, 640, 320, 270), + source_rgb(320, 270), + "the exported bottom band", + ); + // ...and the video half is still the video: the cut is in the file. + assert_ne!( + frame_rgb(&decoded[10].bgra, 640, 320, 90), + frame_rgb(&frame.bgra, 640, 320, 90), + "the video half is not the still" + ); + let _ = std::fs::remove_file(&out); +} + +/// Which lane a still may land on is the engine's answer, not a caller's: a +/// picture asked for on an audio lane goes on the video one instead, exactly as +/// a song asked for on a video lane goes on `A1`. +#[test] +fn a_still_asked_for_on_an_audio_lane_lands_on_the_video_one() { + pin_software(); + let still = asset("test_still.png"); + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + session.import(&still).expect("a picture"); + let a2 = session.add_lane(LaneKind::Audio); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &still, 0, Some(a2)) + .expect("a still joins any timeline") + ); + assert!(session.lane_clips(a2).is_empty(), "not on the audio lane"); + assert_eq!( + session.lane_clips(Lane::V1).len(), + 2, + "on the video lane instead" + ); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 2de9fe9..fdeaa59 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -148,6 +148,15 @@ for fmt in mp3 wav flac ogg m4a aac; do -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ "assets/test_tone.$fmt" done +# Still-image fixture: the source with a picture and no timeline in it. Two +# bands rather than one colour, so a test can tell top from bottom (a flipped +# decode) and red from blue (a swapped channel order); 640x360, which is 16:9 +# like the video fixtures, so a Fit onto 1280x720 covers the canvas with no +# bars and every pixel of the exported frame is the image. +ffmpeg -y -f lavfi -i "color=c=red:s=640x180,format=rgb24" \ + -f lavfi -i "color=c=blue:s=640x180,format=rgb24" \ + -filter_complex "[0:v][1:v]vstack=inputs=2,format=rgb24" \ + -frames:v 1 assets/test_still.png # The refusal fixture: same tone at 48k, which one output device cannot mix # with a 44.1k timeline. ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \