upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/test/bink_play.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/test/bink_play.cpp')
-rw-r--r--runtime/test/bink_play.cpp487
1 files changed, 487 insertions, 0 deletions
diff --git a/runtime/test/bink_play.cpp b/runtime/test/bink_play.cpp
new file mode 100644
index 000000000..da9360e2a
--- /dev/null
+++ b/runtime/test/bink_play.cpp
@@ -0,0 +1,487 @@
1// bink_play: play a Bink 2 stream in a window through the package's own Bink2Scarlett.dll, mapped by rt::Loader (the
2// same path bink_decode_test checks). A local viewing tool for movies carved from your own copy; nothing it reads or
3// shows is written anywhere.
4//
5// bink_play [NAME | movie.bk2 | archive.rpf@OFFSET] [--game-dir DIR] [--frames N] [--headless] [--loop]
6//
7// NAME is a movie's path in the game (Stinger/RSG_STINGER.bk2) or any unique part of it (stinger), looked up in the
8// name table tools/bink_play.py keeps (%LOCALAPPDATA%\Leonida\bink_names.csv); if there is none yet, bink_play runs
9// that tool once to build it. With no movie at all a windowed run plays the Rockstar stinger, so double-clicking
10// the executable plays it. The game folder comes from --game-dir, LEONIDA_GAME_DIR, or the archive the name table
11// was built from.
12//
13// A movie inside an archive plays where it is: `movies.rpf@OFFSET` hands BinkOpen the archive with
14// BinkSetFileOffset, so nothing is extracted (tools/bink_play.py finds the offset from the movie's name). A relative
15// archive path is taken from the game folder.
16//
17// --game-dir defaults to LEONIDA_GAME_DIR, the movie to LEONIDA_MOVIE. Without a package or a movie it prints
18// "SKIP (no package/movie)" and exits 77 (CTest skip). --headless decodes without a window (as fast as it can) and
19// prints the decode rate, so CTest can run it; --frames stops after N frames.
20//
21// Keys: Space pause/resume, Left/Right one second back/forward, Home restart, L loop on/off, Esc or closing the
22// window quits. The frame is scaled to the window, keeping its aspect ratio.
23#include <windows.h>
24
25#include <algorithm>
26#include <cctype>
27#include <chrono>
28#include <cstdint>
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <filesystem>
33#include <fstream>
34#include <stdexcept>
35#include <string>
36#include <thread>
37#include <vector>
38
39#include "../shims/shims.h"
40#include "../src/pe_loader.h"
41
42namespace {
43
44// A windowed run is often started by double-click, where a console line vanishes with its window: say it in a box.
45bool g_windowed = false;
46
47[[noreturn]] void fatal(const std::string& what) {
48 std::fprintf(stderr, "FAIL %s\n", what.c_str());
49 if (g_windowed) MessageBoxA(nullptr, what.c_str(), "bink_play", MB_OK | MB_ICONERROR);
50 std::exit(1);
51}
52
53std::string env(const char* name) {
54 const char* v = std::getenv(name);
55 return v ? v : "";
56}
57
58uint32_t read_u32(const uint8_t* p) {
59 return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
60}
61
62struct MovieHeader {
63 uint32_t frames = 0, width = 0, height = 0, fps_num = 0, fps_den = 0;
64};
65
66// The fixed Bink 2 header (docs/movies.md): frame count at 0x08, size at 0x14/0x18, frame rate at 0x1C/0x20.
67MovieHeader read_movie_header(const std::filesystem::path& path, uint64_t offset) {
68 std::ifstream f(path, std::ios::binary);
69 if (!f) fatal("cannot open movie " + path.string());
70 f.seekg((std::streamoff)offset);
71 uint8_t h[0x2C]{};
72 f.read(reinterpret_cast<char*>(h), sizeof(h));
73 if (f.gcount() != (std::streamsize)sizeof(h)) fatal("movie is shorter than the 44-byte Bink 2 header");
74 if (h[0] != 'K' || h[1] != 'B' || h[2] != '2' || h[3] < 'a' || h[3] > 'z')
75 fatal("movie does not start with KB2[a-z]");
76 MovieHeader out;
77 out.frames = read_u32(h + 0x08);
78 out.width = read_u32(h + 0x14);
79 out.height = read_u32(h + 0x18);
80 out.fps_num = read_u32(h + 0x1C);
81 out.fps_den = read_u32(h + 0x20);
82 if (!out.frames || !out.width || !out.height || !out.fps_num || !out.fps_den)
83 fatal("movie header has a zero frame count, size or fps");
84 if (out.width > 16384 || out.height > 16384) fatal("movie header has an implausible frame size");
85 return out;
86}
87
88struct BinkApi {
89 void* (*open)(const char*, uint32_t) = nullptr;
90 uint32_t (*do_frame)(void*) = nullptr;
91 uint32_t (*copy)(void*, void*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) = nullptr;
92 void (*next)(void*) = nullptr;
93 void (*go_to)(void*, uint32_t, uint32_t) = nullptr;
94 void (*close)(void*) = nullptr;
95 const char* (*get_error)() = nullptr;
96 void (*set_file_offset)(uint64_t) = nullptr; // applies to the next BinkOpen
97};
98
99template <class F> void bind(rt::Module& m, const char* name, F& out) {
100 auto it = m.exports.find(name);
101 if (it == m.exports.end()) fatal(std::string("Bink2Scarlett.dll does not export ") + name);
102 out = reinterpret_cast<F>(it->second);
103}
104
105constexpr uint32_t kCopyBgra32 = 3; // the BinkCopyToBuffer format bink_decode_test measured as 32-bit BGRA
106constexpr uint32_t kFileOffset = 0x20; // BinkOpen flag: start at the offset BinkSetFileOffset gave
107
108struct Player {
109 BinkApi api;
110 void* bink = nullptr;
111 MovieHeader header;
112 std::vector<uint8_t> frame;
113 uint32_t index = 0; // the frame in `frame`
114 bool paused = false;
115 bool loop = false;
116 bool quit = false;
117 bool seek_pending = false;
118 uint32_t seek_to = 0;
119
120 void decode() {
121 api.do_frame(bink);
122 api.copy(bink, frame.data(), header.width * 4, header.height, 0, 0, kCopyBgra32);
123 }
124 // Bink frame numbers in BinkGoto are 1-based.
125 void go_to(uint32_t target) {
126 index = std::min(target, header.frames - 1);
127 api.go_to(bink, index + 1, 0);
128 decode();
129 }
130 uint32_t fps_frames(double seconds) const {
131 return (uint32_t)(seconds * header.fps_num / header.fps_den);
132 }
133};
134
135Player* g_player = nullptr;
136
137void paint(HWND hwnd) {
138 PAINTSTRUCT ps;
139 HDC dc = BeginPaint(hwnd, &ps);
140 RECT rc;
141 GetClientRect(hwnd, &rc);
142 const int cw = rc.right - rc.left, ch = rc.bottom - rc.top;
143 const Player& p = *g_player;
144 // Fit the frame in the client area, keeping its aspect ratio, and black out the bars.
145 int w = cw, h = (int)((int64_t)cw * p.header.height / p.header.width);
146 if (h > ch) {
147 h = ch;
148 w = (int)((int64_t)ch * p.header.width / p.header.height);
149 }
150 const int x = (cw - w) / 2, y = (ch - h) / 2;
151 HBRUSH black = (HBRUSH)GetStockObject(BLACK_BRUSH);
152 RECT bars[] = {{0, 0, cw, y}, {0, y + h, cw, ch}, {0, y, x, y + h}, {x + w, y, cw, y + h}};
153 for (const RECT& b : bars) FillRect(dc, &b, black);
154 BITMAPINFO bi{};
155 bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
156 bi.bmiHeader.biWidth = (LONG)p.header.width;
157 bi.bmiHeader.biHeight = -(LONG)p.header.height; // top-down
158 bi.bmiHeader.biPlanes = 1;
159 bi.bmiHeader.biBitCount = 32;
160 bi.bmiHeader.biCompression = BI_RGB;
161 SetStretchBltMode(dc, COLORONCOLOR);
162 StretchDIBits(dc, x, y, w, h, 0, 0, (int)p.header.width, (int)p.header.height, p.frame.data(), &bi,
163 DIB_RGB_COLORS, SRCCOPY);
164 EndPaint(hwnd, &ps);
165}
166
167LRESULT CALLBACK window_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
168 Player& p = *g_player;
169 switch (msg) {
170 case WM_PAINT: paint(hwnd); return 0;
171 case WM_ERASEBKGND: return 1;
172 case WM_KEYDOWN:
173 switch (wp) {
174 case VK_ESCAPE: DestroyWindow(hwnd); return 0;
175 case VK_SPACE: p.paused = !p.paused; return 0;
176 case 'L': p.loop = !p.loop; return 0;
177 case VK_HOME: p.seek_pending = true; p.seek_to = 0; return 0;
178 case VK_LEFT: {
179 const uint32_t back = p.fps_frames(1.0);
180 p.seek_pending = true;
181 p.seek_to = p.index > back ? p.index - back : 0;
182 return 0;
183 }
184 case VK_RIGHT:
185 p.seek_pending = true;
186 p.seek_to = std::min(p.index + p.fps_frames(1.0), p.header.frames - 1);
187 return 0;
188 }
189 break;
190 case WM_DESTROY: p.quit = true; PostQuitMessage(0); return 0;
191 }
192 return DefWindowProcW(hwnd, msg, wp, lp);
193}
194
195void set_title(HWND hwnd, const Player& p, const std::wstring& name, double rate) {
196 wchar_t title[256];
197 swprintf(title, 256, L"bink_play - %s - frame %u/%u - decode %.1f fps%s%s", name.c_str(), p.index + 1,
198 p.header.frames, rate, p.paused ? L" - paused" : L"", p.loop ? L" - loop" : L"");
199 SetWindowTextW(hwnd, title);
200}
201
202constexpr const char* kDefaultMovie = "Stinger/RSG_STINGER.bk2";
203
204std::string lower_ascii(std::string v) {
205 for (char& c : v) c = (char)std::tolower((unsigned char)c);
206 std::replace(v.begin(), v.end(), '\\', '/');
207 return v;
208}
209
210struct NamedMovie {
211 std::string path;
212 uint64_t offset = 0;
213};
214
215struct NameTable {
216 std::filesystem::path archive; // the archive the table was built from (its first line)
217 std::vector<NamedMovie> movies;
218};
219
220std::filesystem::path name_table_path() {
221 const std::string base = env("LOCALAPPDATA");
222 return base.empty() ? std::filesystem::path() : std::filesystem::path(base) / "Leonida" / "bink_names.csv";
223}
224
225// tools/bink_play.py's table: "# <archive>|<size>|<mtime>", then a header and path,offset,width,height,frames rows.
226// Stale when the archive's size changed. Paths in the table have no commas (they are game file paths).
227bool read_name_table(NameTable& out) {
228 const std::filesystem::path p = name_table_path();
229 std::ifstream f(p);
230 std::string line;
231 if (p.empty() || !f || !std::getline(f, line) || line.rfind("# ", 0) != 0) return false;
232 const std::string stamp = line.substr(2);
233 const size_t bar1 = stamp.find('|'), bar2 = stamp.find('|', bar1 + 1);
234 if (bar1 == std::string::npos || bar2 == std::string::npos) return false;
235 out.archive = std::filesystem::path(stamp.substr(0, bar1));
236 std::error_code ec;
237 const auto size = std::filesystem::file_size(out.archive, ec);
238 if (ec || std::to_string(size) != stamp.substr(bar1 + 1, bar2 - bar1 - 1)) return false;
239 std::getline(f, line); // header
240 out.movies.clear();
241 while (std::getline(f, line)) {
242 if (!line.empty() && line.back() == '\r') line.pop_back();
243 const size_t c1 = line.find(','), c2 = line.find(',', c1 + 1);
244 if (c1 == std::string::npos || c2 == std::string::npos) continue;
245 out.movies.push_back({line.substr(0, c1), std::strtoull(line.substr(c1 + 1, c2 - c1 - 1).c_str(), nullptr, 10)});
246 }
247 return !out.movies.empty();
248}
249
250// Builds the table with tools/bink_play.py (the repository's copy, two folders up from runtime/build), once.
251bool build_name_table(const std::filesystem::path& game_dir) {
252 wchar_t exe[MAX_PATH];
253 GetModuleFileNameW(nullptr, exe, MAX_PATH);
254 std::filesystem::path tool;
255 for (std::filesystem::path d = std::filesystem::path(exe).parent_path(); !d.empty() && d != d.root_path();
256 d = d.parent_path())
257 if (std::filesystem::is_regular_file(d / "tools" / "bink_play.py")) {
258 tool = d / "tools" / "bink_play.py";
259 break;
260 }
261 if (tool.empty() || game_dir.empty()) return false;
262 std::printf("naming the movies in movies.rpf (about half a minute, once)...\n");
263 std::fflush(stdout);
264 const std::wstring cmd = L"python \"" + tool.wstring() + L"\" --list --game-dir \"" + game_dir.wstring() + L"\"";
265 STARTUPINFOW si{sizeof(si)};
266 si.dwFlags = STARTF_USESTDHANDLES;
267 HANDLE nul = CreateFileW(L"NUL", GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
268 si.hStdOutput = nul; // the list itself isn't wanted, only the table it leaves behind
269 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
270 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
271 PROCESS_INFORMATION pi{};
272 std::vector<wchar_t> line(cmd.begin(), cmd.end());
273 line.push_back(0);
274 const bool ok = CreateProcessW(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi);
275 if (ok) {
276 WaitForSingleObject(pi.hProcess, INFINITE);
277 CloseHandle(pi.hThread);
278 CloseHandle(pi.hProcess);
279 }
280 if (nul != INVALID_HANDLE_VALUE) CloseHandle(nul);
281 return ok;
282}
283
284// The movie a NAME means: exactly that path (case-insensitive), else the only path containing it.
285NamedMovie find_named(const NameTable& table, const std::string& name) {
286 const std::string want = lower_ascii(name);
287 std::vector<const NamedMovie*> part;
288 for (const NamedMovie& m : table.movies) {
289 const std::string have = lower_ascii(m.path);
290 if (have == want) return m;
291 if (have.find(want) != std::string::npos) part.push_back(&m);
292 }
293 if (part.size() == 1) return *part[0];
294 std::string why = part.empty() ? "no movie is named like \"" + name + "\"" :
295 std::to_string(part.size()) + " movies match \"" + name + "\"; be more specific:";
296 for (size_t i = 0; i < part.size() && i < 20; ++i) why += "\n " + part[i]->path;
297 if (part.empty()) why += " (python tools\\bink_play.py --list shows the names)";
298 fatal(why);
299}
300
301} // namespace
302
303int main(int argc, char** argv) {
304 std::string game_dir_arg = env("LEONIDA_GAME_DIR"), movie_arg = env("LEONIDA_MOVIE");
305 long max_frames = -1;
306 bool headless = false, loop = false;
307 for (int i = 1; i < argc; ++i) {
308 const std::string a = argv[i];
309 if (a == "--game-dir" && i + 1 < argc) game_dir_arg = argv[++i];
310 else if (a == "--frames" && i + 1 < argc) {
311 char* end = nullptr;
312 max_frames = std::strtol(argv[++i], &end, 10);
313 if (!end || *end || max_frames <= 0) fatal("--frames takes a positive count");
314 } else if (a == "--headless") headless = true;
315 else if (a == "--loop") loop = true;
316 else if (!a.empty() && a[0] != '-') movie_arg = a;
317 else {
318 std::fprintf(stderr, "usage: bink_play [NAME | movie.bk2 | archive.rpf@OFFSET] [--game-dir DIR] "
319 "[--frames N] [--headless] [--loop]\n");
320 return 2;
321 }
322 }
323 g_windowed = !headless;
324 // CTest's headless smoke run gives no movie: that is a skip, not a request for the default one.
325 if (movie_arg.empty() && headless) {
326 std::printf("SKIP (no package/movie)\n");
327 return 77;
328 }
329 if (movie_arg.empty()) movie_arg = kDefaultMovie;
330
331 // A name (not a file, not archive@OFFSET) goes through the name table, which also knows the game folder.
332 std::error_code ec;
333 const bool is_name = movie_arg.find('@') == std::string::npos && !std::filesystem::is_regular_file(movie_arg, ec);
334 if (is_name) {
335 NameTable table;
336 if (!read_name_table(table)) {
337 if (game_dir_arg.empty())
338 fatal("bink_play needs the game folder once, to name the movies:\n\n"
339 " bink_play " + movie_arg + " --game-dir <package folder>\n\n"
340 "After that, double-clicking bink_play.exe plays the stinger.");
341 build_name_table(game_dir_arg);
342 if (!read_name_table(table)) fatal("could not build the movie name table with tools\\bink_play.py");
343 }
344 const NamedMovie m = find_named(table, movie_arg);
345 std::printf("%s\n", m.path.c_str());
346 if (game_dir_arg.empty()) game_dir_arg = table.archive.parent_path().string();
347 movie_arg = table.archive.string() + "@" + std::to_string(m.offset);
348 }
349 if (game_dir_arg.empty()) fatal("no game folder: pass --game-dir or set LEONIDA_GAME_DIR");
350
351 const std::filesystem::path game_dir = game_dir_arg;
352 std::filesystem::path movie = movie_arg;
353 uint64_t offset = 0;
354 if (const size_t at = movie_arg.rfind('@'); at != std::string::npos) {
355 char* end = nullptr;
356 offset = std::strtoull(movie_arg.c_str() + at + 1, &end, 0);
357 if (at + 1 == movie_arg.size() || !end || *end) fatal("the movie's @OFFSET is not a number");
358 movie = movie_arg.substr(0, at);
359 if (movie.is_relative() && !std::filesystem::exists(movie)) movie = game_dir / movie;
360 }
361 if (!std::filesystem::is_regular_file(game_dir / "Bink2Scarlett.dll", ec))
362 fatal("the game folder does not contain Bink2Scarlett.dll");
363 if (!std::filesystem::is_regular_file(movie, ec)) fatal("the movie is not a file");
364
365 Player player;
366 g_player = &player;
367 player.header = read_movie_header(movie, offset);
368 player.loop = loop;
369 const MovieHeader& h = player.header;
370 std::printf("movie: %ux%u, %u frames, %u/%u fps\n", h.width, h.height, h.frames, h.fps_num, h.fps_den);
371
372 try {
373 rt::Loader loader(game_dir);
374 rt::Module& dll = loader.load(game_dir / "Bink2Scarlett.dll");
375 for (auto& r : dll.imports)
376 if (r.binding == rt::Binding::Unimplemented && rt::lower(r.dll).find("xaudio") == std::string::npos)
377 fatal("Bink2Scarlett.dll import " + r.dll + "!" + r.name + " is unimplemented");
378 BinkApi& api = player.api;
379 bind(dll, "BinkOpen", api.open);
380 bind(dll, "BinkDoFrame", api.do_frame);
381 bind(dll, "BinkCopyToBuffer", api.copy);
382 bind(dll, "BinkNextFrame", api.next);
383 bind(dll, "BinkGoto", api.go_to);
384 bind(dll, "BinkClose", api.close);
385 bind(dll, "BinkGetError", api.get_error);
386 if (offset) {
387 bind(dll, "BinkSetFileOffset", api.set_file_offset);
388 api.set_file_offset(offset);
389 }
390
391 player.bink = api.open(movie.string().c_str(), offset ? kFileOffset : 0);
392 if (!player.bink) {
393 const char* e = api.get_error ? api.get_error() : nullptr;
394 fatal(std::string("BinkOpen failed: ") + (e && *e ? e : "(no BinkGetError text)"));
395 }
396 player.frame.assign((size_t)h.width * 4 * h.height, 0);
397 player.decode();
398
399 using clock = std::chrono::steady_clock;
400 const auto frame_time = std::chrono::duration<double>((double)h.fps_den / h.fps_num);
401 const uint32_t last = max_frames > 0 ? (uint32_t)std::min<long>(max_frames, (long)h.frames) : h.frames;
402
403 if (headless) {
404 const auto start = clock::now();
405 uint32_t decoded = 1;
406 while (decoded < last) {
407 api.next(player.bink);
408 player.decode();
409 ++decoded;
410 }
411 const double s = std::chrono::duration<double>(clock::now() - start).count();
412 std::printf("decoded %u frames in %.2f s (%.1f fps; the movie runs at %.2f fps)\n", decoded, s,
413 s > 0 ? decoded / s : 0.0, (double)h.fps_num / h.fps_den);
414 api.close(player.bink);
415 std::printf("RESULT PASS\n");
416 return 0;
417 }
418
419 WNDCLASSW wc{};
420 wc.lpfnWndProc = window_proc;
421 wc.hInstance = GetModuleHandleW(nullptr);
422 wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
423 wc.lpszClassName = L"LeonidaBinkPlay";
424 RegisterClassW(&wc);
425 // Start at up to 1280 wide (or the movie's size if smaller), the movie's aspect ratio.
426 const int start_w = (int)std::min<uint32_t>(h.width, 1280);
427 RECT r{0, 0, start_w, (int)((int64_t)start_w * h.height / h.width)};
428 AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);
429 HWND hwnd = CreateWindowW(wc.lpszClassName, L"bink_play", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT,
430 CW_USEDEFAULT, r.right - r.left, r.bottom - r.top, nullptr, nullptr, wc.hInstance,
431 nullptr);
432 if (!hwnd) fatal("CreateWindow failed");
433 const std::wstring name = movie.filename().wstring() + (offset ? L"@" + std::to_wstring(offset) : L"");
434
435 auto due = clock::now() + frame_time;
436 auto rate_start = clock::now();
437 uint32_t rate_frames = 0, shown = 1;
438 double rate = 0;
439 while (!player.quit) {
440 MSG msg;
441 while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
442 TranslateMessage(&msg);
443 DispatchMessageW(&msg);
444 }
445 if (player.quit) break;
446 if (player.seek_pending) {
447 player.seek_pending = false;
448 player.go_to(player.seek_to);
449 InvalidateRect(hwnd, nullptr, FALSE);
450 due = clock::now() + frame_time;
451 }
452 if (player.paused || clock::now() < due) {
453 set_title(hwnd, player, name, rate);
454 std::this_thread::sleep_for(std::chrono::milliseconds(1));
455 continue;
456 }
457 if (player.index + 1 >= h.frames || (max_frames > 0 && shown >= last)) {
458 if (!player.loop) break;
459 player.go_to(0);
460 } else {
461 api.next(player.bink);
462 player.decode();
463 ++player.index;
464 }
465 ++shown;
466 InvalidateRect(hwnd, nullptr, FALSE);
467 UpdateWindow(hwnd);
468 ++rate_frames;
469 const double elapsed = std::chrono::duration<double>(clock::now() - rate_start).count();
470 if (elapsed >= 1.0) {
471 rate = rate_frames / elapsed;
472 rate_frames = 0;
473 rate_start = clock::now();
474 }
475 set_title(hwnd, player, name, rate);
476 // Hold the movie's frame rate; when decoding falls behind, don't try to catch up in a burst.
477 due += std::chrono::duration_cast<clock::duration>(frame_time);
478 if (clock::now() > due + std::chrono::duration_cast<clock::duration>(frame_time * 4)) due = clock::now();
479 }
480 if (IsWindow(hwnd)) DestroyWindow(hwnd);
481 api.close(player.bink);
482 std::printf("played %u frames\n", shown);
483 return 0;
484 } catch (const std::exception& e) {
485 fatal(e.what());
486 }
487}