aboutsummaryrefslogtreecommitdiff
path: root/adapters/fparkan-platform-winit/src/intro_video.rs
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-03 12:19:38 +0300
committerValentin Popov <valentin@popov.link>2026-12-03 12:19:38 +0300
commite9ba4a3e0a039715fdf1c169edd7f56faa8570b1 (patch)
treea424ebdfd05a9bbe4e77f828b0e70933aa03166e /adapters/fparkan-platform-winit/src/intro_video.rs
parent3522319c1728e715741ac4b149c6e712fd900e73 (diff)
downloadfparkan-e9ba4a3e0a039715fdf1c169edd7f56faa8570b1.tar.xz
fparkan-e9ba4a3e0a039715fdf1c169edd7f56faa8570b1.zip
feat(ui): play the installed startup movies before the menu
Diffstat (limited to 'adapters/fparkan-platform-winit/src/intro_video.rs')
-rw-r--r--adapters/fparkan-platform-winit/src/intro_video.rs194
1 files changed, 194 insertions, 0 deletions
diff --git a/adapters/fparkan-platform-winit/src/intro_video.rs b/adapters/fparkan-platform-winit/src/intro_video.rs
new file mode 100644
index 00000000..37c9d19f
--- /dev/null
+++ b/adapters/fparkan-platform-winit/src/intro_video.rs
@@ -0,0 +1,194 @@
+//! DirectShow AVI playback inside the existing game window.
+
+use raw_window_handle::{HasWindowHandle, RawWindowHandle};
+use std::{io, marker::PhantomData, os::windows::ffi::OsStrExt, path::Path, rc::Rc};
+use windows::{
+ core::{Interface, PCWSTR},
+ Win32::{
+ Foundation::E_ABORT,
+ Media::DirectShow::{
+ FilgraphManager, IBasicVideo, IGraphBuilder, IMediaControl, IMediaEventEx,
+ IVideoWindow, EC_COMPLETE, EC_ERRORABORT, EC_USERABORT,
+ },
+ System::Com::{
+ CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_HANDLER,
+ CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED,
+ },
+ UI::WindowsAndMessaging::WS_CHILD,
+ },
+};
+use winit::window::Window;
+
+/// A clip whose DirectShow renderer is a child of the game window.
+pub struct IntroVideo {
+ control: IMediaControl,
+ events: IMediaEventEx,
+ video: IVideoWindow,
+ frame: [i32; 2],
+ // Drop the graph interfaces before leaving their COM apartment.
+ _apartment: Apartment,
+}
+
+impl IntroVideo {
+ /// Renders the original AVI's video and audio streams in the game window.
+ /// The player is opened, polled and dropped on the window thread.
+ pub fn play(window: &Window, path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
+ let handle = window.window_handle()?;
+ let RawWindowHandle::Win32(owner) = handle.as_raw() else {
+ return Err(io::Error::other("intro playback requires a Win32 window").into());
+ };
+ let owner = owner.hwnd.get();
+ let mut filename: Vec<u16> = path.as_os_str().encode_wide().collect();
+ if filename.contains(&0) {
+ return Err(
+ io::Error::new(io::ErrorKind::InvalidInput, "AVI path contains a NUL").into(),
+ );
+ }
+ filename.push(0);
+ let apartment = Apartment::enter()?;
+
+ // SAFETY: This is the window thread's initialized STA. The path stays
+ // valid through RenderFile, and DirectShow owns the graph and renderer.
+ let movie = unsafe {
+ let graph: IGraphBuilder = CoCreateInstance(
+ &FilgraphManager,
+ None,
+ CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER,
+ )?;
+ graph.RenderFile(PCWSTR(filename.as_ptr()), PCWSTR::null())?;
+ let control = graph.cast::<IMediaControl>()?;
+ let events = graph.cast::<IMediaEventEx>()?;
+ let video = graph.cast::<IVideoWindow>()?;
+ let dimensions = graph.cast::<IBasicVideo>()?;
+ let frame = [dimensions.SourceWidth()?, dimensions.SourceHeight()?];
+ Self {
+ control,
+ events,
+ video,
+ frame,
+ _apartment: apartment,
+ }
+ };
+ // SAFETY: The parent HWND is borrowed from the live Window above. The
+ // child is detached when playback ends, before the game window drops.
+ unsafe {
+ movie.video.SetOwner(owner)?;
+ movie.video.SetMessageDrain(owner)?;
+ movie.video.SetWindowStyle(WS_CHILD.0 as i32)?;
+ }
+ movie.resize(window)?;
+ // SAFETY: All graph interfaces are used on their creating STA.
+ unsafe { movie.control.Run()? };
+ Ok(movie)
+ }
+
+ /// Updates the child rectangle using the original movie fitting rule.
+ pub fn resize(&self, window: &Window) -> Result<(), Box<dyn std::error::Error>> {
+ let size = window.inner_size();
+ if size.width == 0 || size.height == 0 {
+ return Ok(());
+ }
+ let client = [i32::try_from(size.width)?, i32::try_from(size.height)?];
+ let [left, top, width, height] = content_rect(client, self.frame)?;
+ // SAFETY: The renderer belongs to the STA calling this method.
+ unsafe { self.video.SetWindowPosition(left, top, width, height)? };
+ Ok(())
+ }
+
+ /// Drains pending graph events without blocking the window thread.
+ pub fn finished(&self) -> Result<bool, Box<dyn std::error::Error>> {
+ // SAFETY: The event parameters are writable for the duration of the
+ // call and every successfully retrieved event is freed on this STA.
+ unsafe {
+ loop {
+ let (mut code, mut first, mut second) = (0, 0, 0);
+ match self.events.GetEvent(&mut code, &mut first, &mut second, 0) {
+ Ok(()) => self.events.FreeEventParams(code, first, second)?,
+ Err(error) if error.code() == E_ABORT => return Ok(false),
+ Err(error) => return Err(error.into()),
+ }
+ match code as u32 {
+ EC_COMPLETE | EC_USERABORT => return Ok(true),
+ EC_ERRORABORT => {
+ return Err(windows::core::Error::from_hresult(windows::core::HRESULT(
+ first as i32,
+ ))
+ .into());
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+}
+
+impl Drop for IntroVideo {
+ fn drop(&mut self) {
+ // SAFETY: Playback shuts down on the creating STA while its owner
+ // window still exists. The interfaces then release before COM exits.
+ unsafe {
+ let _ = self.control.Stop();
+ let _ = self.video.SetVisible(0);
+ let _ = self.video.SetMessageDrain(0);
+ let _ = self.video.SetOwner(0);
+ }
+ }
+}
+
+struct Apartment(PhantomData<Rc<()>>);
+
+impl Apartment {
+ fn enter() -> windows::core::Result<Self> {
+ // SAFETY: The reserved parameter is null. Each successful call,
+ // including S_FALSE, is balanced by Drop on the same thread.
+ unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok()? };
+ Ok(Self(PhantomData))
+ }
+}
+
+impl Drop for Apartment {
+ fn drop(&mut self) {
+ // SAFETY: enter acquired this thread's COM initialization count.
+ unsafe { CoUninitialize() };
+ }
+}
+
+fn content_rect(client: [i32; 2], video: [i32; 2]) -> io::Result<[i32; 4]> {
+ let [frame_width, frame_height] = video.map(i64::from);
+ if frame_width <= 0 || frame_height <= 0 {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "invalid AVI dimensions",
+ ));
+ }
+ let [client_width, client_height] = client.map(i64::from);
+ let (width, height) = if frame_height < frame_width {
+ (client_width, frame_height * client_width / frame_width)
+ } else {
+ (frame_width * client_height / frame_height, client_height)
+ };
+ let coordinate = |value| i32::try_from(value).map_err(io::Error::other);
+ Ok([
+ coordinate((client_width - width) / 2)?,
+ coordinate((client_height - height) / 2)?,
+ coordinate(width)?,
+ coordinate(height)?,
+ ])
+}
+
+#[cfg(test)]
+#[test]
+fn positions_movie_using_the_original_orientation_rule() {
+ assert_eq!(
+ content_rect([800, 600], [640, 480]).unwrap(),
+ [0, 0, 800, 600]
+ );
+ assert_eq!(
+ content_rect([1280, 720], [640, 480]).unwrap(),
+ [0, -120, 1280, 960]
+ );
+ assert_eq!(
+ content_rect([800, 600], [480, 640]).unwrap(),
+ [175, 0, 450, 600]
+ );
+}