Skip to content

armgit / BUI

Public Imported from GitHub
0

Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI

rust video

Preetham Pemmasani108baa821530
diff --git a/bindings/rust/blenderui-sys/Cargo.toml b/bindings/rust/blenderui-sys/Cargo.toml
index 208bad7..1113633 100644
--- a/bindings/rust/blenderui-sys/Cargo.toml
+++ b/bindings/rust/blenderui-sys/Cargo.toml
@@ -23,7 +23,26 @@ gdi-text = []
# GPU text drawn with Slug (glyph outlines in the pixel shader) by default;
# without it, the per-glyph atlas. Switchable at runtime either way.
slug = []
-default = ["slug"]
+default = ["slug", "png", "gif", "bmp", "tga", "qoi", "jpeg", "webp", "hdr", "pnm", "svg", "video", "gpu", "freetype", "filebrowser"]
+# The optional parts of the C kit: features.json (the one table CMake and
+# `bui build` read too; build.rs maps each to its CMake option and checks this
+# list has them all). Off, a part costs no binary size; its API stays.
+png = [] # PNG images
+gif = [] # GIF images and animations
+bmp = [] # BMP images
+tga = [] # TGA images
+qoi = [] # QOI images
+jpeg = [] # JPEG images
+webp = [] # WebP images and animations
+hdr = [] # Radiance HDR images
+pnm = [] # PNM (PGM, PPM) images
+svg = [] # SVG images
+video = [] # <video> through the OS decoders
+video-dav1d = ["video"] # AV1 video with dav1d
+video-ffmpeg = ["video"] # Every format FFmpeg reads (LGPL or GPL, by its build)
+gpu = [] # GPU renderers: Direct3D 11 (Windows), OpenGL 3.3 (Linux)
+freetype = [] # Text through the vendored FreeType like Blender's BLF
+filebrowser = [] # Blender's File Browser
# Deprecated no-op: the portable engine is the default everywhere.
portable-text = []
# Also build and link Dear ImGui on BUI and its C API (bindings/imgui: bui_cimgui,
diff --git a/bindings/rust/blenderui-sys/build.rs b/bindings/rust/blenderui-sys/build.rs
index 2e41627..97ea530 100644
--- a/bindings/rust/blenderui-sys/build.rs
+++ b/bindings/rust/blenderui-sys/build.rs
@@ -4,6 +4,15 @@
use std::path::PathBuf;
+/// One row of features.json (one feature per line): its name and CMake option.
+fn feature_row(line: &str) -> Option<(&str, &str)> {
+ let field = |key: &str| {
+ let at = line.find(&format!("\"{key}\": \""))? + key.len() + 5;
+ line[at..].split('"').next()
+ };
+ Some((field("name")?, field("option")?))
+}
+
fn main() {
// docs.rs: rustdoc links nothing, so skip the C build (its sandbox may lack
// the toolchain, and the build takes long)
@@ -28,7 +37,21 @@ fn main() {
println!("cargo:rerun-if-env-changed=BUI_TEXT_GDI");
// `imgui`: Dear ImGui on BUI + its C API (C++), built by the same CMake project
let imgui = std::env::var("CARGO_FEATURE_IMGUI").is_ok();
- let dst = cmake::Config::new(&root)
+ let mut config = cmake::Config::new(&root);
+ // The optional parts (features.json, the one table): each cargo feature is
+ // its CMake option, ON exactly when the feature is.
+ let table = std::fs::read_to_string(root.join("features.json")).expect("features.json");
+ let manifest_toml = std::fs::read_to_string(manifest.join("Cargo.toml")).expect("Cargo.toml");
+ for (name, option) in table.lines().filter_map(feature_row) {
+ assert!(
+ manifest_toml.lines().any(|l| l.starts_with(name) && l[name.len()..].trim_start().starts_with('=')),
+ "features.json has `{name}`: add it to blenderui-sys's (and blenderui's) [features]"
+ );
+ let on = std::env::var_os(format!("CARGO_FEATURE_{}", name.to_uppercase().replace('-', "_"))).is_some();
+ config.define(option, if on { "ON" } else { "OFF" });
+ }
+ println!("cargo:rerun-if-changed={}", root.join("features.json").display());
+ let dst = config
.define("BUI_TEXT_GDI", if gdi { "ON" } else { "OFF" })
.define("BUI_SLUG", if std::env::var("CARGO_FEATURE_SLUG").is_ok() { "ON" } else { "OFF" })
.define("BUI_BUILD_TESTS", "OFF")
@@ -36,7 +59,6 @@ fn main() {
.define("BUI_BUILD_PYTHON_BINDINGS", "OFF")
.define("BUI_BUILD_UI", "OFF")
.define("BUI_BUILD_QT_BACKEND", "OFF")
- .define("BUI_BUILD_IMGUI", if imgui { "ON" } else { "OFF" })
.define("BUI_IMGUI_BLENDER_WIDGETS", if std::env::var("CARGO_FEATURE_IMGUI_BLENDER_WIDGETS").is_ok() { "ON" } else { "OFF" })
// Always optimized; on MSVC also the release C runtime Rust links.
.profile("Release")
@@ -83,6 +105,12 @@ fn main() {
for fw in ["Cocoa", "CoreGraphics"] {
println!("cargo:rustc-link-lib=framework={fw}");
}
+ // video (movie_avf.m): weak, so a system without them still starts
+ if std::env::var_os("CARGO_FEATURE_VIDEO").is_some() {
+ for fw in ["AVFoundation", "CoreMedia", "CoreVideo"] {
+ println!("cargo:rustc-link-arg=-Wl,-weak_framework,{fw}");
+ }
+ }
println!("cargo:rustc-link-lib=objc");
}
println!("cargo:rustc-link-lib=m");
diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rs
index 8c7b161..dce5a05 100644
--- a/bindings/rust/blenderui-sys/src/lib.rs
+++ b/bindings/rust/blenderui-sys/src/lib.rs
@@ -114,8 +114,24 @@ pub struct BKCanvasItem {
pub fit: c_int,
/// Animated `src`: 0 plays; n > 0 shows frame n - 1 (paused).
pub frame: c_int,
+ /// Images: a video's current frame (borrowed, as `imbuf`).
+ pub video: *mut BKVideo,
}
+/// A `<video>` (`BKVideo`): the kit's player (OS decoders; frames in one GPU
+/// texture). UI-thread object.
+#[repr(C)]
+pub struct BKVideo {
+ _private: [u8; 0],
+}
+
+/// `BK_VIDEO_*` states.
+pub const BK_VIDEO_LOADING: c_int = 0;
+pub const BK_VIDEO_PLAYING: c_int = 1;
+pub const BK_VIDEO_PAUSED: c_int = 2;
+pub const BK_VIDEO_ENDED: c_int = 3;
+pub const BK_VIDEO_ERROR: c_int = 4;
+
/// An animation stepped by the caller (`BKAnim`): GIF, animated WebP.
#[repr(C)]
pub struct BKAnim {
@@ -252,6 +268,31 @@ unsafe extern "C" {
pub fn BK_image_poll() -> c_int;
pub fn BK_image_clear_cache();
pub fn BK_image_exit();
+
+ // video (kit/intern/image/video.c: one player for every binding)
+ pub fn BK_video_new(src: *const c_char) -> *mut BKVideo;
+ pub fn BK_video_free(v: *mut BKVideo);
+ pub fn BK_video_play(v: *mut BKVideo);
+ pub fn BK_video_pause(v: *mut BKVideo);
+ pub fn BK_video_seek(v: *mut BKVideo, seconds: c_double);
+ pub fn BK_video_set_rate(v: *mut BKVideo, rate: c_double);
+ pub fn BK_video_set_loop(v: *mut BKVideo, on: c_int);
+ pub fn BK_video_set_poster(v: *mut BKVideo, src: *const c_char);
+ pub fn BK_video_set_controls(v: *mut BKVideo, on: c_int);
+ pub fn BK_video_state(v: *const BKVideo) -> c_int;
+ pub fn BK_video_time(v: *const BKVideo) -> c_double;
+ pub fn BK_video_duration(v: *const BKVideo) -> c_double;
+ pub fn BK_video_size(v: *const BKVideo, r_w: *mut c_int, r_h: *mut c_int) -> c_int;
+ pub fn BK_video_set_listener(
+ v: *mut BKVideo,
+ f: Option<unsafe extern "C" fn(v: *mut BKVideo, state: c_int, data: *mut c_void)>,
+ data: *mut c_void,
+ );
+ pub fn BK_video_texture(v: *mut BKVideo, tex: c_int, max_w: c_int, max_h: c_int) -> c_int;
+ pub fn BK_node_set_video(node: *mut BKNode, v: *mut BKVideo, fit: c_int);
+ pub fn BK_video_backends() -> *const c_char;
+ /// Allocations made through MEM_* so far (allocations per frame, in benchmarks).
+ pub fn MEM_get_allocations_total() -> usize;
/// Blender's allocator counters (bui_core): bytes and blocks held through MEM_*.
pub fn MEM_get_memory_in_use() -> usize;
pub fn MEM_get_memory_blocks_in_use() -> u32;
diff --git a/bindings/rust/blenderui/Cargo.toml b/bindings/rust/blenderui/Cargo.toml
index bfd208b..514b82b 100644
--- a/bindings/rust/blenderui/Cargo.toml
+++ b/bindings/rust/blenderui/Cargo.toml
@@ -32,7 +32,25 @@ gdi-text = ["blenderui-sys/gdi-text"]
# GPU text with Slug by default (else the per-glyph atlas); see
# `Application::slug` / `blenderui::set_slug` to switch at runtime.
slug = ["blenderui-sys/slug"]
-default = ["slug"]
+default = ["slug", "png", "gif", "bmp", "tga", "qoi", "jpeg", "webp", "hdr", "pnm", "svg", "video", "gpu", "freetype", "filebrowser"]
+# The C kit's optional parts (features.json; see blenderui-sys): each costs
+# binary size only when on. tests/features.rs checks this list has them all.
+png = ["blenderui-sys/png"]
+gif = ["blenderui-sys/gif"]
+bmp = ["blenderui-sys/bmp"]
+tga = ["blenderui-sys/tga"]
+qoi = ["blenderui-sys/qoi"]
+jpeg = ["blenderui-sys/jpeg"]
+webp = ["blenderui-sys/webp"]
+hdr = ["blenderui-sys/hdr"]
+pnm = ["blenderui-sys/pnm"]
+svg = ["blenderui-sys/svg"]
+video = ["blenderui-sys/video"]
+video-dav1d = ["blenderui-sys/video-dav1d"]
+video-ffmpeg = ["blenderui-sys/video-ffmpeg"]
+gpu = ["blenderui-sys/gpu"]
+freetype = ["blenderui-sys/freetype"]
+filebrowser = ["blenderui-sys/filebrowser"]
# Deprecated no-op: the portable engine is the default everywhere.
portable-text = ["blenderui-sys/portable-text"]
diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rs
index 16e29f6..1ca6726 100644
--- a/bindings/rust/blenderui/src/element.rs
+++ b/bindings/rust/blenderui/src/element.rs
@@ -77,6 +77,7 @@ pub struct Div {
pub(crate) listeners: Option<Box<Listeners>>,
pub(crate) paint: Option<PaintFn>,
pub(crate) image: Option<Arc<crate::paint::Image>>,
+ pub(crate) video: Option<std::rc::Rc<crate::video::Video>>,
/// Runs before layout with the window and app (see [`Div::defer`]).
pub(crate) deferred: Option<Deferred>,
}
@@ -140,6 +141,7 @@ impl Div {
listeners: None,
paint: None,
image: None,
+ video: None,
deferred: None,
}
}
@@ -288,6 +290,13 @@ impl Div {
self
}
+ /// `<video>` with a player you keep (play, pause, seek, events): cheap
+ /// to pass every frame. Without it, `<video src>` makes its own.
+ pub fn video(mut self, video: std::rc::Rc<crate::video::Video>) -> Self {
+ self.video = Some(video);
+ self
+ }
+
// -- events ----------------------------------------------------------------------------
/// Click (press and release on this element); bubbles to ancestors.
pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rs
index 73d856f..84c52d3 100644
--- a/bindings/rust/blenderui/src/layout.rs
+++ b/bindings/rust/blenderui/src/layout.rs
@@ -237,6 +237,8 @@ pub(crate) enum Replaced {
/// `<img src>`: decoded on the kit's workers when shown; animations
/// play, or hold the frame of the `frame` attribute.
File(ImageFile, Option<u32>),
+ /// `<video>`: its player (yours, or the window's for `src`).
+ Video(std::rc::Rc<crate::video::Video>),
Painted(PaintFn),
Placeholder(&'static str),
}
@@ -802,6 +804,18 @@ impl<'a> Builder<'a> {
&self.styles[self.nodes[i].style]
}
+ /// `<video src>`'s player: muted autoplay unless `autoplay="false"`;
+ /// `loop`, `poster` (the HTML attributes).
+ fn video_src(&mut self, i: usize) -> Option<std::rc::Rc<crate::video::Video>> {
+ let attrs = crate::video::VideoAttrs {
+ autoplay: self.attr(i, "autoplay") != Some("false"),
+ looped: self.attr(i, "loop").is_some_and(|v| v != "false"),
+ poster: self.attr(i, "poster").map(str::to_owned),
+ };
+ let src = self.attr(i, "src")?.to_owned();
+ self.images.videos.get(&src, attrs)
+ }
+
fn attr(&self, i: usize, name: &str) -> Option<&str> {
el_attr(&self.nodes, &self.els, i, name)
}
@@ -1191,6 +1205,10 @@ impl<'a> Builder<'a> {
Replaced::Painted(f)
} else if let Some(img) = div.image.take() {
Replaced::Image(img)
+ } else if let Some(v) = div.video.take() {
+ Replaced::Video(v)
+ } else if div.tag == "video" && let Some(v) = self.video_src(i) {
+ Replaced::Video(v)
} else if let Some(file) = self.attr(i, "src").map(str::to_owned).and_then(|s| self.images.load(&s)) {
Replaced::File(file, self.attr(i, "frame").and_then(|v| v.trim().parse().ok()))
} else {
@@ -1750,6 +1768,7 @@ impl<'a> Builder<'a> {
let (iw, ih) = match r {
Replaced::Image(img) => (img.width as f32, img.height as f32),
Replaced::File(file, _) => (file.width as f32, file.height as f32),
+ Replaced::Video(v) => v.size().map_or((300.0, 150.0), |(w, h)| (w as f32, h as f32)),
_ => (300.0, 150.0),
};
let attr = |n: &str| self.attr(i, n).and_then(|v| v.trim_end_matches("px").parse::<f32>().ok());
diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rs
index eb1bea9..6312c63 100644
--- a/bindings/rust/blenderui/src/lib.rs
+++ b/bindings/rust/blenderui/src/lib.rs
@@ -112,6 +112,7 @@ pub(crate) mod sink;
pub mod vlist;
pub(crate) mod layout;
pub mod paint;
+pub mod video;
pub(crate) mod prof;
mod selector;
pub mod hooks;
@@ -132,6 +133,7 @@ pub use list::{uniform_list, UniformList};
pub use events::*;
pub use geometry::{point, px, relative, rems, size, Bounds, Length, Pixels, Point, Rems, Size};
pub use paint::{image_stats, set_image_budget, Animation, Image, Painter};
+pub use video::{Video, VideoState};
pub use styled::{FontWeight, StyleBlock, Styled};
pub use window::*;
diff --git a/bindings/rust/blenderui/src/paint.rs b/bindings/rust/blenderui/src/paint.rs
index e708de8..03b6e4c 100644
--- a/bindings/rust/blenderui/src/paint.rs
+++ b/bindings/rust/blenderui/src/paint.rs
@@ -205,6 +205,8 @@ impl ImageFile {
#[derive(Default)]
pub(crate) struct ImageCache {
files: HashMap<String, Option<ImageFile>>,
+ /// `<video src>` players
+ pub(crate) videos: crate::video::VideoCache,
}
impl ImageCache {
@@ -233,6 +235,8 @@ enum Kind {
/// into the box by `fit` (`sys::BK_FIT_*`); animations play (`frame` 0)
/// or hold frame `frame - 1`.
File { start: u32, fit: i32, frame: i32 },
+ /// A video's current frame, fitted by `fit`.
+ Video(std::rc::Rc<crate::video::Video>, i32),
}
/// Coordinates: up to four inline (rects, ovals, text, images), more on the heap.
@@ -400,6 +404,12 @@ impl Painter {
self.file(bounds, src, sys::BK_FIT_FILL, frame);
}
+ /// A video's current frame fitted into `bounds` (`fit`: `sys::BK_FIT_*`); it
+ /// plays while drawn, and nothing decodes while it isn't.
+ pub fn video(&mut self, bounds: Bounds<f32>, video: &std::rc::Rc<crate::video::Video>, fit: i32) {
+ self.push(Kind::Video(video.clone(), fit), Self::corners(bounds), Rgba::TRANSPARENT);
+ }
+
fn file(&mut self, bounds: Bounds<f32>, src: &str, fit: i32, frame: Option<u32>) {
if !src.is_empty() {
let start = self.text.len() as u32;
@@ -475,6 +485,11 @@ impl Painter {
ci.imbuf = img.as_ptr();
ci.fit = sys::BK_FIT_FILL;
}
+ Kind::Video(v, fit) => {
+ ci.type_ = sys::BK_ITEM_IMAGE;
+ ci.video = v.as_ptr();
+ ci.fit = *fit;
+ }
Kind::File { start, fit, frame } => {
ci.type_ = sys::BK_ITEM_IMAGE;
ci.fit = *fit;
@@ -567,6 +582,7 @@ impl Painter {
}
Kind::Image(img) => (6u8, Arc::as_ptr(img) as usize).hash(h),
Kind::File { start, fit, frame } => (7u8, self.arena_str(*start), fit, frame).hash(h),
+ Kind::Video(v, fit) => (8u8, std::rc::Rc::as_ptr(v) as usize, fit).hash(h),
}
if let Some(c) = it.clip {
(c.origin.x.to_bits(), c.origin.y.to_bits(), c.size.width.to_bits(), c.size.height.to_bits()).hash(h);
@@ -1090,6 +1106,8 @@ fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize,
}
_ => p.image_file_frame(inner, &file.src, *frame),
},
+ Replaced::Video(v) => p.with_clip(inner, |p| p.video(inner, v, c.images.as_ref().map_or(
+ sys::BK_FIT_CONTAIN, |st| st.object_fit.kit_video()))),
Replaced::Painted(f) => p.with_clip(inner, |p| f(inner, p, app)),
Replaced::Placeholder(tag) => {
p.fill(inner, crate::color::rgb(0x282828));
diff --git a/bindings/rust/blenderui/src/style.rs b/bindings/rust/blenderui/src/style.rs
index 87d4f7f..9064448 100644
--- a/bindings/rust/blenderui/src/style.rs
+++ b/bindings/rust/blenderui/src/style.rs
@@ -211,6 +211,18 @@ pub enum ObjectFit {
ScaleDown,
}
+impl ObjectFit {
+ /// The kit's `BK_FIT_*`; a video's default (fill) letterboxes, as browsers do.
+ pub(crate) const fn kit_video(self) -> i32 {
+ match self {
+ Self::Fill | Self::Contain => blenderui_sys::BK_FIT_CONTAIN,
+ Self::Cover => blenderui_sys::BK_FIT_COVER,
+ Self::None => blenderui_sys::BK_FIT_NONE,
+ Self::ScaleDown => blenderui_sys::BK_FIT_SCALE_DOWN,
+ }
+ }
+}
+
/// `background-size`: a size is a fraction of the box plus pixels; `None` = auto.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum BgSize {
diff --git a/bindings/rust/blenderui/src/video.rs b/bindings/rust/blenderui/src/video.rs
new file mode 100644
index 0000000..256ac10
--- /dev/null
+++ b/bindings/rust/blenderui/src/video.rs
@@ -0,0 +1,208 @@
+//! `<video>`: the kit's player (`BK_video_*`, kit/intern/image/video.c), the
+//! same one every binding uses. The OS decodes (Media Foundation,
+//! AVFoundation, GStreamer) at the size drawn, frames update one GPU texture
+//! in place, and nothing is decoded while the video isn't on screen.
+//!
+//! ```ignore
+//! let clip = Video::new("intro.mp4").unwrap();
+//! clip.set_loop(true);
+//! clip.on_state(|s| if s == VideoState::Ended { println!("done") });
+//! div().child(video().video(clip.clone()).w(px(640.0)));
+//! // or let the element own it: <video src="intro.mp4" loop muted poster="intro.jpg" />
+//! ```
+
+use std::collections::HashMap;
+use std::ffi::CString;
+use std::ptr::NonNull;
+use std::rc::Rc;
+use std::time::Duration;
+
+use crate::sys;
+
+/// What a video is doing (`BK_VIDEO_*`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum VideoState {
+ /// Not decoded yet (it loads when first drawn).
+ Loading,
+ Playing,
+ Paused,
+ /// The last frame shows (not looping).
+ Ended,
+ /// No backend reads the file (or it is not a video).
+ Error,
+}
+
+impl VideoState {
+ const fn from_raw(s: i32) -> Self {
+ match s {
+ sys::BK_VIDEO_LOADING => Self::Loading,
+ sys::BK_VIDEO_PLAYING => Self::Playing,
+ sys::BK_VIDEO_PAUSED => Self::Paused,
+ sys::BK_VIDEO_ENDED => Self::Ended,
+ _ => Self::Error,
+ }
+ }
+}
+
+type Listener = Box<dyn FnMut(VideoState)>;
+
+/// A video and its controls. UI thread only (`!Send`); share it with `Rc`.
+/// Muted autoplay by default (no audio yet).
+pub struct Video {
+ ptr: NonNull<sys::BKVideo>,
+ /// `on_state`'s callback, boxed twice so the kit holds a thin pointer.
+ listener: Option<Box<Listener>>,
+}
+
+unsafe extern "C" fn heard(_v: *mut sys::BKVideo, state: i32, data: *mut std::ffi::c_void) {
+ // SAFETY: `data` is the `Box<Listener>` this video owns (see `on_state`),
+ // alive until the video is dropped, which clears the listener first.
+ let f = unsafe { &mut *data.cast::<Listener>() };
+ f(VideoState::from_raw(state));
+}
+
+impl Video {
+ /// A video file. `None` for an empty path or one with a NUL byte.
+ pub fn new(src: &str) -> Option<Self> {
+ let path = CString::new(src).ok()?;
+ // SAFETY: `path` is NUL-terminated for the call (the kit copies it).
+ let ptr = NonNull::new(unsafe { sys::BK_video_new(path.as_ptr()) })?;
+ Some(Self { ptr, listener: None })
+ }
+
+ pub(crate) const fn as_ptr(&self) -> *mut sys::BKVideo {
+ self.ptr.as_ptr()
+ }
+
+ pub fn play(&self) {
+ // SAFETY: a live video (all methods below likewise).
+ unsafe { sys::BK_video_play(self.as_ptr()) };
+ }
+
+ pub fn pause(&self) {
+ unsafe { sys::BK_video_pause(self.as_ptr()) };
+ }
+
+ /// The frame at `t` shows, paused or not.
+ pub fn seek(&self, t: Duration) {
+ unsafe { sys::BK_video_seek(self.as_ptr(), t.as_secs_f64()) };
+ }
+
+ /// Playback speed (1/16 .. 16).
+ pub fn set_rate(&self, rate: f64) {
+ unsafe { sys::BK_video_set_rate(self.as_ptr(), rate) };
+ }
+
+ pub fn set_loop(&self, on: bool) {
+ unsafe { sys::BK_video_set_loop(self.as_ptr(), i32::from(on)) };
+ }
+
+ /// An image file shown until the first frame.
+ pub fn set_poster(&self, src: &str) {
+ if let Ok(path) = CString::new(src) {
+ unsafe { sys::BK_video_set_poster(self.as_ptr(), path.as_ptr()) };
+ }
+ }
+
+ pub fn state(&self) -> VideoState {
+ VideoState::from_raw(unsafe { sys::BK_video_state(self.as_ptr()) })
+ }
+
+ /// Where it is (the frame shown).
+ pub fn time(&self) -> Duration {
+ Duration::from_secs_f64(unsafe { sys::BK_video_time(self.as_ptr()) }.max(0.0))
+ }
+
+ /// `None` until loaded (or when the file doesn't say).
+ pub fn duration(&self) -> Option<Duration> {
+ let d = unsafe { sys::BK_video_duration(self.as_ptr()) };
+ (d > 0.0).then(|| Duration::from_secs_f64(d))
+ }
+
+ /// Intrinsic size, once loaded (or the poster's).
+ pub fn size(&self) -> Option<(u32, u32)> {
+ let (mut w, mut h) = (0, 0);
+ let ok = unsafe { sys::BK_video_size(self.as_ptr(), &raw mut w, &raw mut h) } != 0;
+ (ok && w > 0 && h > 0).then_some((w as u32, h as u32))
+ }
+
+ /// Called on every state change (loaded, playing, paused, ended, error).
+ pub fn on_state(&mut self, f: impl FnMut(VideoState) + 'static) {
+ let mut boxed: Box<Listener> = Box::new(Box::new(f));
+ let data: *mut Listener = &raw mut *boxed;
+ // SAFETY: the box stays at this address while `self` holds it.
+ unsafe { sys::BK_video_set_listener(self.as_ptr(), Some(heard), data.cast()) };
+ self.listener = Some(boxed);
+ }
+
+ /// The current frame in a BUI texture for Dear ImGui (`0`: make one; it is
+ /// updated in place after). Calling it each frame keeps the video playing.
+ pub fn texture(&self, tex: i32, max_w: u32, max_h: u32) -> i32 {
+ unsafe { sys::BK_video_texture(self.as_ptr(), tex, max_w as i32, max_h as i32) }
+ }
+
+ /// The video backends this build has (`"mf"`, `"gstreamer"`, ...).
+ pub fn backends() -> &'static str {
+ // SAFETY: a static NUL-terminated string.
+ unsafe { std::ffi::CStr::from_ptr(sys::BK_video_backends()) }.to_str().unwrap_or("")
+ }
+}
+
+impl Drop for Video {
+ fn drop(&mut self) {
+ // SAFETY: ours; the kit drops the listener with it (no call after this).
+ unsafe {
+ sys::BK_video_set_listener(self.as_ptr(), None, std::ptr::null_mut());
+ sys::BK_video_free(self.as_ptr());
+ }
+ }
+}
+
+impl std::fmt::Debug for Video {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Video").field("state", &self.state()).finish_non_exhaustive()
+ }
+}
+
+/// `<video src>` elements' players, kept by the window by `src` (one player
+/// per file and window) with the attributes last applied, so a re-render
+/// changes the player only when an attribute did.
+#[derive(Default)]
+pub(crate) struct VideoCache {
+ players: HashMap<String, (Rc<Video>, VideoAttrs)>,
+}
+
+#[derive(Clone, Default, PartialEq, Eq)]
+pub(crate) struct VideoAttrs {
+ pub autoplay: bool,
+ pub looped: bool,
+ pub poster: Option<String>,
+}
+
+impl VideoCache {
+ pub(crate) fn get(&mut self, src: &str, attrs: VideoAttrs) -> Option<Rc<Video>> {
+ if let Some((v, had)) = self.players.get_mut(src) {
+ if *had != attrs {
+ apply(v, had, &attrs);
+ *had = attrs;
+ }
+ return Some(v.clone());
+ }
+ let v = Rc::new(Video::new(src)?);
+ apply(&v, &VideoAttrs { autoplay: true, ..VideoAttrs::default() }, &attrs);
+ self.players.insert(src.to_owned(), (v.clone(), attrs));
+ Some(v)
+ }
+}
+
+fn apply(v: &Video, had: &VideoAttrs, now: &VideoAttrs) {
+ if had.autoplay != now.autoplay {
+ if now.autoplay { v.play() } else { v.pause() }
+ }
+ if had.looped != now.looped {
+ v.set_loop(now.looped);
+ }
+ if had.poster != now.poster {
+ v.set_poster(now.poster.as_deref().unwrap_or(""));
+ }
+}
diff --git a/bindings/rust/blenderui/tests/features.rs b/bindings/rust/blenderui/tests/features.rs
new file mode 100644
index 0000000..4b432bb
--- /dev/null
+++ b/bindings/rust/blenderui/tests/features.rs
@@ -0,0 +1,20 @@
+//! The feature table (features.json, read by CMake, cargo and `bui build`):
+//! blenderui forwards each optional part to blenderui-sys under its name.
+
+#[test]
+fn every_kit_feature_is_a_cargo_feature() {
+ let root = env!("CARGO_MANIFEST_DIR");
+ let table = std::fs::read_to_string(format!("{root}/../../../features.json")).unwrap();
+ let manifest = std::fs::read_to_string(format!("{root}/Cargo.toml")).unwrap();
+ let names = table.lines().filter(|l| l.contains("\"option\": \"")).filter_map(|l| {
+ let at = l.find("\"name\": \"")? + 9;
+ l[at..].split('"').next()
+ });
+ let mut n = 0;
+ for name in names.filter(|&n| n != "imgui") {
+ let row = format!("{name} = [\"blenderui-sys/{name}\"]");
+ assert!(manifest.lines().any(|l| l.trim() == row), "blenderui's Cargo.toml lacks `{row}`");
+ n += 1;
+ }
+ assert!(n >= 10, "read the table ({n} features)");
+}
diff --git a/bindings/rust/blenderui/tests/video.rs b/bindings/rust/blenderui/tests/video.rs
new file mode 100644
index 0000000..156ed74
--- /dev/null
+++ b/bindings/rust/blenderui/tests/video.rs
@@ -0,0 +1,118 @@
+//! `<video>`: it loads, plays and pauses in a window, and players come and go
+//! without leaks (a counting Rust allocator and the kit's MEM counters). One
+//! test: the counter is global. Skips where no backend decodes the clip.
+
+use std::alloc::{GlobalAlloc, Layout, System};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicIsize, Ordering};
+use std::time::Duration;
+
+use blenderui::prelude::*;
+use blenderui::{sys, Video, VideoState};
+
+struct Counting;
+static LIVE: AtomicIsize = AtomicIsize::new(0);
+
+// SAFETY: forwards to the system allocator; only counts.
+unsafe impl GlobalAlloc for Counting {
+ unsafe fn alloc(&self, l: Layout) -> *mut u8 {
+ LIVE.fetch_add(l.size() as isize, Ordering::Relaxed);
+ // SAFETY: same layout contract as the caller's.
+ unsafe { System.alloc(l) }
+ }
+ unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
+ LIVE.fetch_sub(l.size() as isize, Ordering::Relaxed);
+ // SAFETY: `p` came from `alloc` with `l`.
+ unsafe { System.dealloc(p, l) }
+ }
+ unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
+ LIVE.fetch_add(n as isize - l.size() as isize, Ordering::Relaxed);
+ // SAFETY: as `dealloc` + `alloc`.
+ unsafe { System.realloc(p, l, n) }
+ }
+}
+
+#[global_allocator]
+static A: Counting = Counting;
+
+fn clip() -> String {
+ format!("{}/../../../tests/videos/clip.mp4", env!("CARGO_MANIFEST_DIR")).replace('\\', "/")
+}
+
+struct Player(Rc<Video>);
+impl Render for Player {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ div()
+ .child(video().id("v").video(self.0.clone()).w(px(96.0)).h(px(54.0)))
+ .child(video().id("s").src(clip()).attr("autoplay", "false").w(px(96.0)).h(px(54.0)))
+ }
+}
+
+#[test]
+fn video_plays_and_players_free_everything() {
+ if Video::backends().is_empty() {
+ eprintln!("no video backend in this build: skipped");
+ return;
+ }
+ let v = Rc::new(Video::new(&clip()).unwrap());
+ let mut ok = true;
+ Application::headless().run(|cx| {
+ let opts = WindowOptions {
+ window_bounds: Some(WindowBounds::Windowed(Bounds { origin: point(px(0.0), px(0.0)), size: size(px(220.0), px(80.0)) })),
+ ..Default::default()
+ };
+ let win = cx.open_window(opts, |_, cx| cx.new(|_| Player(v.clone()))).unwrap();
+ let hash = |cx: &mut App| {
+ let b = cx.element_bounds(win.id, "v").unwrap();
+ let (pw, _, px) = cx.draw(win.id);
+ (0..40).fold(0u64, |h, k| h.wrapping_mul(31) ^ u64::from(px[(b.origin.y as usize + 10 + k % 30) * pw + b.origin.x as usize + 5 + k]))
+ };
+ for _ in 0..200 {
+ hash(cx);
+ if v.state() != VideoState::Loading {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ if v.state() == VideoState::Error {
+ ok = false; // no decoder for H.264 here
+ return;
+ }
+ assert_eq!(v.state(), VideoState::Playing);
+ assert_eq!(v.size(), Some((96, 54)));
+ let mut seen = vec![hash(cx)];
+ for _ in 0..8 {
+ std::thread::sleep(Duration::from_millis(60));
+ let h = hash(cx);
+ if !seen.contains(&h) {
+ seen.push(h);
+ }
+ }
+ assert!(seen.len() >= 3, "it plays: {} distinct frames", seen.len());
+ v.pause();
+ v.seek(Duration::from_millis(1500));
+ for _ in 0..30 {
+ hash(cx);
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert!((v.time().as_secs_f64() - 1.5).abs() < 0.11, "seek: {:?}", v.time());
+ assert_eq!(v.state(), VideoState::Paused);
+ });
+ if !ok {
+ eprintln!("this machine's backend doesn't decode H.264: skipped");
+ return;
+ }
+ drop(v);
+ // players come and go: every byte back (Rust and the kit's MEM)
+ let (rust0, mem0) = (LIVE.load(Ordering::Relaxed), unsafe { sys::MEM_get_memory_blocks_in_use() });
+ for _ in 0..200 {
+ let mut p = Video::new(&clip()).unwrap();
+ p.on_state(|_| {});
+ p.set_loop(true);
+ p.seek(Duration::from_millis(500));
+ drop(p);
+ }
+ assert_eq!(LIVE.load(Ordering::Relaxed), rust0, "Rust allocations returned");
+ // SAFETY: a counter read.
+ assert_eq!(unsafe { sys::MEM_get_memory_blocks_in_use() }, mem0, "C (MEM) blocks returned");
+}
diff --git a/bindings/rust/scripts/vendor_c.py b/bindings/rust/scripts/vendor_c.py
index f02f3ee..e1b438b 100644
--- a/bindings/rust/scripts/vendor_c.py
+++ b/bindings/rust/scripts/vendor_c.py
@@ -23,7 +23,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
DEST = ROOT / "bindings" / "rust" / "blenderui-sys" / "csrc"
DIRS = ["core", "types", "gpu", "compat", "kit", "api", "bindings/imgui"]
-FILES = ["CMakeLists.txt", "LICENSE", "bindings/python/bui/_version.py", "ui/CMakeLists.txt"]
+FILES = ["CMakeLists.txt", "features.json", "features.cmake", "LICENSE", "bindings/python/bui/_version.py", "ui/CMakeLists.txt"]
# relative directories (from ROOT) never needed by the crate's CMake configuration
SKIP_DIRS = {"core/tests", "gpu/tests", "bindings/imgui/gen"}
SKIP_NAMES = shutil.ignore_patterns("__pycache__", "*.pyc", "*.py", "build*", "*.o", "*.obj")
diff --git a/kit/intern/image/movie_mf.c b/kit/intern/image/movie_mf.c
index 502205a..8f1bc29 100644
--- a/kit/intern/image/movie_mf.c
+++ b/kit/intern/image/movie_mf.c
@@ -141,6 +141,12 @@ static bool mf_ready(void)
/** \name The codec
* \{ */
+/* declared without DEFINE_GUID by the Windows SDK's mfobjects.h: defined here */
+static const GUID k_IID_IMF2DBuffer = {
+ 0x7dc9d5f9, 0x9ed9, 0x44ec, {0x9b, 0xbf, 0x06, 0x00, 0xbb, 0x58, 0x9f, 0xbb}};
+static const GUID k_IID_IMFDXGIBuffer = {
+ 0xe7174cfa, 0x1c9e, 0x48b1, {0x88, 0x66, 0x62, 0x62, 0x26, 0xbf, 0xc2, 0x58}};
+
typedef struct MFMovie {
IMFSourceReader *reader;
int w, h; /* output frame (NV12) */
@@ -313,7 +319,7 @@ static bool copy_frame(MFMovie *m, IMFSample *sample, BKImBuf *dst)
LONG pitch = 0;
int plane_h = m->h;
bool locked2d = false;
- if (SUCCEEDED(IMFMediaBuffer_QueryInterface(buf, &IID_IMFDXGIBuffer, (void **)&dx))) {
+ if (SUCCEEDED(IMFMediaBuffer_QueryInterface(buf, &k_IID_IMFDXGIBuffer, (void **)&dx))) {
ID3D11Texture2D *tex = NULL;
if (SUCCEEDED(IMFDXGIBuffer_GetResource(dx, &IID_ID3D11Texture2D, (void **)&tex))) {
D3D11_TEXTURE2D_DESC td;
@@ -323,7 +329,7 @@ static bool copy_frame(MFMovie *m, IMFSample *sample, BKImBuf *dst)
}
IMFDXGIBuffer_Release(dx);
}
- if (SUCCEEDED(IMFMediaBuffer_QueryInterface(buf, &IID_IMF2DBuffer, (void **)&b2))) {
+ if (SUCCEEDED(IMFMediaBuffer_QueryInterface(buf, &k_IID_IMF2DBuffer, (void **)&b2))) {
locked2d = SUCCEEDED(IMF2DBuffer_Lock2D(b2, &scan0, &pitch));
}
DWORD len = 0;