1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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]
);
}
|