Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Video with alpha (#113): a VP9 WebM's transparency and a ProRes 4444's are drawn, not refused or made opaque

shinyobjectze165d0c4a86b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1f073eb9..dad31ea4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -116,4 +116,4 @@ jobs:
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
env:
CARGO_PROFILE_TEST_DEBUG: "0"
- run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-bundle -p raea-app-check -p raea-app-check-flash -p raea-app-workspace -p raea-app-tools -p raea-app-targets
+ run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-bundle -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
diff --git a/Cargo.lock b/Cargo.lock
index d0505b4c..3efb88e3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13618,6 +13618,7 @@ dependencies = [
"raea-app-check-flash",
"raea-core-brief",
"raea-core-facts",
+ "raea-io-ffmpeg",
"raea-io-trace",
"raea-sys-measure",
"serde_json",
diff --git a/apps/check/Cargo.toml b/apps/check/Cargo.toml
index b6ebae0f..17340a20 100644
--- a/apps/check/Cargo.toml
+++ b/apps/check/Cargo.toml
@@ -13,6 +13,8 @@ raea-core-brief = { path = "../../core/brief" }
raea-core-facts = { path = "../../core/facts" }
# a check's record named by when it was (UTC, DR3)
raea-io-trace = { path = "../../io/trace" }
+# ffmpeg's flag for every decoded frame, by its version
+raea-io-ffmpeg = { path = "../../io/ffmpeg" }
# caption contrast and loudness, measured as `raea world` measures a render (DR2)
raea-sys-measure = { path = "../../systems/measure" }
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
diff --git a/apps/check/src/flash.rs b/apps/check/src/flash.rs
index 3a79f9a1..8a2477c7 100644
--- a/apps/check/src/flash.rs
+++ b/apps/check/src/flash.rs
@@ -5,17 +5,6 @@ use raea_app_check_flash::FlashScreen;
/// the area sample and the point sample side by side
const FLASH_W: usize = 192;
-/// Every decoded frame, once: -fps_mode from FFmpeg 5.1 on, -vsync before it.
-fn passthrough() -> [&'static str; 2] {
- let out = Command::new("ffmpeg").args(["-hide_banner", "-version"]).output().map(|o| o.stdout).unwrap_or_default();
- let head = String::from_utf8_lossy(&out);
- let version = head.split("version ").nth(1).and_then(|v| {
- let mut parts = v.trim_start_matches('n').split(|c: char| !c.is_ascii_digit());
- Some((parts.next()?.parse::<u32>().ok()?, parts.next()?.parse::<u32>().ok()?))
- });
- [if version.is_some_and(|v| v < (5, 1)) { "-vsync" } else { "-fps_mode" }, "passthrough"]
-}
-
/// A frame's number and time from showinfo's log, exact: its `pts` in ticks of the time base. `pts_time` is rounded to six
/// significant digits, which is enough to push a legal third flash across the one-second line.
pub(crate) fn showinfo_frame(line: &str, base: Option<(i64, i64)>) -> Option<(usize, f64)> {
@@ -46,7 +35,7 @@ pub(crate) fn flashing(video: &str, probe: &Probe, issues: &mut Vec<Issue>, pass
let w = FLASH_W;
let h = (((w as f64 * probe.h / probe.w.max(1.0)) / 2.0).round() as usize * 2).max(6);
let graph = format!("showinfo,split=2[area][point];[area]scale={w}:{h}:flags=area[a];[point]scale={w}:{h}:flags=neighbor[b];[a][b]hstack=inputs=2,format=rgb24");
- let sync = passthrough();
+ let sync = raea_io_ffmpeg::passthrough();
let mut child = Command::new("ffmpeg")
.args(["-hide_banner", "-nostats", "-nostdin", "-loglevel", "level+info", "-i", video, "-map", "0:v:0", "-vf", &graph, sync[0], sync[1], "-f", "rawvideo", "-"])
.stdin(std::process::Stdio::null())
diff --git a/engine/page/src/motion.rs b/engine/page/src/motion.rs
index 6b55d939..1f60682d 100644
--- a/engine/page/src/motion.rs
+++ b/engine/page/src/motion.rs
@@ -87,8 +87,11 @@ impl Videos {
/// frame (a looped or held clip run long) gives its last frame, as raea-runtime-js's page does.
pub fn frame(&mut self, v: &raea_core_wire::tree::VideoAt) -> R<Option<raea_io_media::Frame>> {
if !self.decoders.contains_key(&v.file) {
- let be = raea_io_media::backend(&std::env::var("RAEA_MEDIA").unwrap_or_else(|_| if cfg!(target_vendor = "apple") { "apple".into() } else { "soft".into() }))?;
- let d = be.open_video(&v.file).map_err(|e| format!("{}: {e}", v.file.display()))?;
+ // RAEA_MEDIA's, the platform's, the portable one, then the ffmpeg CLI, the first that opens it: a WebM is read
+ // by ffmpeg alone (#113: it was refused, "no video track", where the platform's was the only one asked)
+ let mut why = Vec::new();
+ let d = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(&v.file).map_err(|e| why.push(format!("{}: {e}", b.name()))).ok());
+ let d = d.ok_or_else(|| format!("{}: can't be decoded ({})", v.file.display(), why.join("; ")))?;
self.decoders.insert(v.file.clone(), d);
}
let d = self.decoders.get_mut(&v.file).unwrap();
diff --git a/io/apple/src/decode.rs b/io/apple/src/decode.rs
index 38c48ba0..d3c7e580 100644
--- a/io/apple/src/decode.rs
+++ b/io/apple/src/decode.rs
@@ -15,6 +15,8 @@ pub(crate) struct Decoder {
pub(crate) since_restart: usize,
/// VideoToolbox hands over NV12 planes (no conversion) instead of BGRA
pub(crate) nv12: bool,
+ /// the track's frames carry alpha (ProRes 4444, HEVC with alpha): BGRA's alpha kept, not made 255 (#113)
+ pub(crate) alpha: bool,
/// surface mode: NV12 left in VideoToolbox's IOSurface-backed, Metal-compatible buffers (no copy)
pub(crate) surface: bool,
/// the presentation times, read once from the compressed samples (for index_at)
@@ -216,7 +218,7 @@ impl Decoder {
dst[x * 4] = row[x * 4 + 2];
dst[x * 4 + 1] = row[x * 4 + 1];
dst[x * 4 + 2] = row[x * 4];
- dst[x * 4 + 3] = 255;
+ dst[x * 4 + 3] = if self.alpha { row[x * 4 + 3] } else { 255 };
}
}
rgba
diff --git a/io/apple/src/lib.rs b/io/apple/src/lib.rs
index 2ea6e148..25e83af4 100644
--- a/io/apple/src/lib.rs
+++ b/io/apple/src/lib.rs
@@ -104,6 +104,7 @@ fn open_decoder(path: &Path) -> R<Decoder> {
});
});
let a = asset(path);
+ let alpha;
let info = unsafe {
let media = AVMediaTypeVideo.ok_or("AVMediaTypeVideo")?;
#[allow(deprecated)]
@@ -117,6 +118,13 @@ fn open_decoder(path: &Path) -> R<Decoder> {
let fps = track.nominalFrameRate() as f64;
#[allow(deprecated)]
let duration = a.duration().seconds();
+ // whether its frames carry alpha (ProRes 4444 at depth 32, HEVC with alpha): the decoder keeps it (#113)
+ alpha = track.formatDescriptions().firstObject().is_some_and(|d| {
+ use objc2_core_foundation::{CFBoolean, CFNumber};
+ let fd = &*(Retained::as_ptr(&d) as *const objc2_core_media::CMFormatDescription);
+ let has = fd.extension(objc2_core_media::kCMFormatDescriptionExtension_ContainsAlphaChannel).is_some_and(|v| v.downcast_ref::<CFBoolean>().is_some_and(|b| b.as_bool()));
+ has || fd.extension(objc2_core_media::kCMFormatDescriptionExtension_Depth).and_then(|v| v.downcast_ref::<CFNumber>().and_then(|n| n.as_i32())) == Some(32)
+ });
// the codec, from the track's format description (a CMFormatDescription in the array)
let fourcc = {
let descs = track.formatDescriptions();
@@ -152,6 +160,7 @@ fn open_decoder(path: &Path) -> R<Decoder> {
next: None,
since_restart: 0,
nv12: false,
+ alpha,
surface: false,
sample_pts: None,
shift: None,
diff --git a/io/ffmpeg/src/lib.rs b/io/ffmpeg/src/lib.rs
index 6c5eb420..a0d8bb4c 100644
--- a/io/ffmpeg/src/lib.rs
+++ b/io/ffmpeg/src/lib.rs
@@ -11,8 +11,30 @@ use raea_io_codec::{
pub struct Ffmpeg;
-/// The facts, the presentation times, and whether the colour matrix is untagged.
-fn probe(path: &Path) -> R<(Info, Vec<f64>, bool)> {
+/// Every decoded frame, once: -fps_mode from FFmpeg 5.1 on, -vsync before it (FFmpeg 8 took -vsync out, and the decoder
+/// read nothing: #113).
+pub fn passthrough() -> [&'static str; 2] {
+ static FLAG: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
+ let flag = FLAG.get_or_init(|| {
+ let head = says("-version");
+ let version = head.split("version ").nth(1).and_then(|v| {
+ let mut parts = v.trim_start_matches('n').split(|c: char| !c.is_ascii_digit());
+ Some((parts.next()?.parse::<u32>().ok()?, parts.next()?.parse::<u32>().ok()?))
+ });
+ if version.is_some_and(|v| v < (5, 1)) { "-vsync" } else { "-fps_mode" }
+ });
+ [flag, "passthrough"]
+}
+
+/// What `ffmpeg -hide_banner OPTION` prints (nothing without ffmpeg).
+fn says(option: &str) -> String {
+ let out = Command::new("ffmpeg").args(["-hide_banner", option]).output().map(|o| o.stdout).unwrap_or_default();
+ String::from_utf8_lossy(&out).into_owned()
+}
+
+/// The facts, the presentation times, whether the colour matrix is untagged, and the decoder a VP8 or VP9 stream with
+/// alpha needs (libvpx: ffmpeg's own VP9 decoder drops the alpha WebM keeps beside the picture, #113).
+fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
let out = Command::new("ffprobe")
.args([
"-v",
@@ -20,7 +42,7 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool)> {
"-select_streams",
"v:0",
"-show_entries",
- "stream=codec_name,width,height,r_frame_rate,color_space:stream_side_data=rotation:format=duration",
+ "stream=codec_name,width,height,r_frame_rate,color_space:stream_tags=alpha_mode:stream_side_data=rotation:format=duration",
"-show_entries",
"packet=pts_time",
"-of",
@@ -60,6 +82,15 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool)> {
.and_then(|d| d.parse().ok())
.unwrap_or(0.0);
let untagged = !matches!(s["color_space"].as_str(), Some(c) if c != "unknown");
+ let alpha = match (s["codec_name"].as_str(), s["tags"]["alpha_mode"].as_str()) {
+ (Some("vp8"), Some("1")) => Some("libvpx"),
+ (Some("vp9"), Some("1")) => Some("libvpx-vp9"),
+ _ => None,
+ };
+ // an ffmpeg built without libvpx decodes the picture alone, as before
+ static DECODERS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
+ let have = DECODERS.get_or_init(|| says("-decoders"));
+ let alpha = alpha.filter(|c| have.split_whitespace().any(|w| w == *c));
Ok((
Info {
codec: s["codec_name"].as_str().unwrap_or("?").into(),
@@ -71,6 +102,7 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool)> {
},
pts,
untagged,
+ alpha,
))
}
@@ -82,6 +114,8 @@ struct Decoder {
/// untagged HD (720 lines or more) is read as BT.709, as Apple, browsers and our own decoders read it (swscale
/// would assume BT.601)
bt709: bool,
+ /// the decoder named before the input (libvpx for VP8/VP9 with alpha), else ffmpeg's choice
+ vpx: Option<&'static str>,
}
impl Decoder {
@@ -92,7 +126,7 @@ impl Decoder {
}
let start = self.pts[at] - self.pts[0];
let mut cmd = Command::new("ffmpeg");
- cmd.args(["-v", "error", "-ss", &format!("{start:.6}"), "-i"]).arg(&self.path);
+ cmd.args(["-v", "error"]).args(self.vpx.map(|c| ["-c:v", c]).into_iter().flatten()).args(["-ss", &format!("{start:.6}"), "-i"]).arg(&self.path);
if self.bt709 {
cmd.args(["-vf", "scale=in_color_matrix=bt709:in_range=tv"]);
}
@@ -103,11 +137,12 @@ impl Decoder {
"rawvideo",
"-pix_fmt",
"rgba",
- "-vsync",
- "passthrough",
- "-",
])
+ .args(passthrough())
+ .arg("-")
.stdout(Stdio::piped())
+ // kept for a read that fails (and out of the run's output: the pipe closed under it is "Broken pipe")
+ .stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("ffmpeg: {e}"))?;
self.pipe = Some((child, at));
@@ -132,12 +167,11 @@ impl VideoDecoder for Decoder {
let mut buf = vec![0u8; size];
loop {
let (child, next) = self.pipe.as_mut().unwrap();
- child
- .stdout
- .as_mut()
- .unwrap()
- .read_exact(&mut buf)
- .map_err(|e| format!("ffmpeg read: {e}"))?;
+ if let Err(e) = child.stdout.as_mut().unwrap().read_exact(&mut buf) {
+ let mut said = String::new();
+ let _ = child.stderr.as_mut().map(|s| s.read_to_string(&mut said));
+ return Err(format!("ffmpeg read: {e} {}", said.trim()));
+ }
*next += 1;
if *next - 1 == want {
return Ok(Frame {
@@ -240,7 +274,7 @@ impl Backend for Ffmpeg {
"ffmpeg"
}
fn open_video(&self, path: &Path) -> R<Box<dyn VideoDecoder>> {
- let (info, pts, untagged) = probe(path)?;
+ let (info, pts, untagged, vpx) = probe(path)?;
let bt709 = untagged && info.width.min(info.height) >= 720;
if pts.is_empty() {
return Err(format!("{}: no video frames", path.display()));
@@ -251,6 +285,7 @@ impl Backend for Ffmpeg {
pts,
pipe: None,
bt709,
+ vpx,
}))
}
fn decode_audio(&self, path: &Path) -> R<Audio> {
@@ -341,3 +376,6 @@ impl Backend for Ffmpeg {
}))
}
}
+
+#[cfg(test)]
+mod tests;
diff --git a/io/ffmpeg/src/tests.rs b/io/ffmpeg/src/tests.rs
new file mode 100644
index 00000000..f06d1056
--- /dev/null
+++ b/io/ffmpeg/src/tests.rs
@@ -0,0 +1,28 @@
+use super::*;
+
+/// A 64x64 VP9 WebM with alpha, a red square on nothing (#113), made by this machine's ffmpeg; None without ffmpeg or
+/// libvpx (the test then has nothing to read).
+fn alpha_webm(dir: &Path) -> Option<PathBuf> {
+ let p = dir.join("square.webm");
+ let made = Command::new("ffmpeg")
+ .args(["-v", "error", "-y", "-f", "lavfi", "-i", "[email protected]:s=64x64:d=0.4,format=rgba,geq=r=255:g=0:b=0:a='if(lt(abs(X-32),16)*lt(abs(Y-32),16),255,0)'"])
+ .args(["-c:v", "libvpx-vp9", "-pix_fmt", "yuva420p", "-auto-alt-ref", "0"])
+ .arg(&p)
+ .status()
+ .is_ok_and(|s| s.success());
+ made.then_some(p)
+}
+
+#[test]
+fn vp9_webm_keeps_its_alpha() {
+ let dir = std::env::temp_dir().join(format!("raea-ffmpeg-alpha-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let Some(webm) = alpha_webm(&dir) else { return eprintln!("skipped: no ffmpeg with libvpx-vp9 here") };
+ let mut d = Ffmpeg.open_video(&webm).expect("the ffmpeg backend opens a VP9 WebM");
+ for t in [0.0, 0.2] {
+ let f = d.frame_at(t).expect("a frame");
+ let at = |x: usize, y: usize| f.rgba[(y * f.width as usize + x) * 4 + 3];
+ assert_eq!((at(2, 2), at(32, 32)), (0, 255), "at {t} s: outside the square is transparent, inside opaque");
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+}