//! 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> { 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 = 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::()?; let events = graph.cast::()?; let video = graph.cast::()?; let dimensions = graph.cast::()?; 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> { 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> { // 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>); impl Apartment { fn enter() -> windows::core::Result { // 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] ); }