upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims/xapu_queue.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/shims/xapu_queue.cpp')
-rw-r--r--runtime/shims/xapu_queue.cpp438
1 files changed, 438 insertions, 0 deletions
diff --git a/runtime/shims/xapu_queue.cpp b/runtime/shims/xapu_queue.cpp
new file mode 100644
index 000000000..e754376ba
--- /dev/null
+++ b/runtime/shims/xapu_queue.cpp
@@ -0,0 +1,438 @@
1// xapu.dll: the console's audio processing unit (APU) command queue. No PC has one, so this keeps the queue the title
2// talks to - one result per accepted command, in command order, with the console's error codes. With
3// runtime/opus_decoder built (LEONIDA_HAVE_OPUS_DECODER) a process command decodes its Opus packet to PCM; without
4// it the result carries the frame count its table-of-contents byte gives and silence in its output.
5//
6// Read from the executable's call sites (counts in docs/runtime_imports.md, shapes in docs/audio_hal_exe_calls.md),
7// statically, never run:
8// XApuConnect(input24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte
9// output is read later as the base of a CPU-visible buffer: per-stream
10// input at base + slot * 0x280 and output at base + 0x14000 +
11// slot * 0x1E00. The first argument is a 24-byte global of the title
12// that other title code also addresses.
13// XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type
14// (1, 2 and 3 seen), the second a stream slot.
15// XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues.
16// XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative
17// HRESULT skips that result. The loop reads a type at +0, a stream slot
18// at +4 and a dword at +0x34. Its per-slot state machine takes a type 1
19// result as "opened" and returns the slot to the title's free list only
20// on a type 2 result, after the title enqueued a type 2 command.
21// XApuDisconnect(handle, 0x20) 1 site; the return value is never read.
22//
23// Where the layouts come from. The signatures, structure layouts, command kinds, option bits and error codes below
24// are facts recorded by Marvisak/VIctory (GPL-3.0-or-later, crates/victory-hle/src/modules/apu.rs at commit ffe310e),
25// whose runtime runs the retail executable through these calls; see docs/related_projects.md. Nothing of its code is
26// copied; this file is written from those facts. They agree with every shape above: the first argument of
27// XApuConnect is an input, the dword the title reads at +0x34 of a result is its output byte count, and a type 1
28// (activate) or type 2 (deactivate) command gives a result of the same kind for the same stream.
29// HRESULT XApuConnect(const ConnectInput*, ConnectOutput*, Connection** out)
30// HRESULT XApuDisconnect(Connection*, uint32_t) the second argument is not read
31// HRESULT XApuEnqueueCommand(Connection*, const void* command, uint32_t* accepted_so_far) may be null
32// HRESULT XApuDequeueResult(Connection*, Result* out) 0x8AC81001 while no result is ready
33// uint32_t XApuGetResultCount(Connection*, uint32_t* dequeued_so_far) may be null; returns the results ready
34// A connection is for one kind of processing; kind 1 is Opus decoding to 32-bit float PCM at 48 kHz, and any other
35// kind is E_NOTIMPL. Every command starts with the 24-byte CommandId. A command refused at once (unknown kind,
36// stream out of range, or the stream already holding `commands_per_stream` results not dequeued) gives no result;
37// every other command gives one, with its error, if any, in the result.
38//
39// Without runtime/opus_decoder a process command's frame count comes from the Opus packet's table-of-contents byte
40// (RFC 6716, section 3.1), clipped from first_frame, to frame_count and to what output_bytes holds, and that output
41// range is written with zeros, so the title sees streams advance at the right rate and the audio stays silent. With
42// the crate, fill() decodes the packet and writes its PCM instead.
43#include <windows.h>
44#include <intrin.h>
45
46#include <cstddef>
47#include <cstdint>
48#include <cstdio>
49#include <cstring>
50#include <deque>
51#include <mutex>
52#include <new>
53#include <set>
54#include <string>
55#include <vector>
56
57#if defined(LEONIDA_HAVE_OPUS_DECODER)
58#include "leonida_opus_decoder.h"
59#endif
60
61#include "shims.h"
62#include "startup_trace.h"
63
64namespace {
65
66constexpr HRESULT kNotImpl = static_cast<HRESULT>(rt::shims::kENotImpl);
67constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u);
68constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u);
69constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u);
70constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u);
71constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u);
72constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u);
73
74constexpr uint32_t kDecodeOpus = 1; // ConnectInput::processing
75
76constexpr uint32_t kActivate = 1; // CommandId::kind
77constexpr uint32_t kDeactivate = 2;
78constexpr uint32_t kProcess = 3;
79constexpr uint32_t kReset = 5; // 4 is notify; neither carries anything to do while nothing is decoded
80
81constexpr uint32_t kSignalWhenDone = 0x1; // CommandId::options: set the result event when the result is ready
82constexpr uint32_t kResultEvent = 0x8; // ConnectInput::options: create an auto-reset event and hand it out
83constexpr uint32_t kDeinterleavedOutput = 0x4; // ConnectInput::options: split stereo into two planes
84constexpr uint32_t kOpusSampleRate = 48000;
85
86constexpr uint32_t kMaxStreams = 500;
87constexpr uint32_t kMaxCommandsPerStream = 16;
88constexpr uint32_t kMaxFrames = 5760; // 120 ms at 48 kHz, the longest Opus packet (RFC 6716, section 3.2.5)
89
90#pragma pack(push, 1)
91struct ConnectInput {
92 uint32_t processing;
93 uint32_t streams;
94 uint32_t commands_per_stream;
95 uint32_t memory_bytes;
96 uint32_t frames_per_output; // 0 for decoding
97 uint32_t options;
98};
99struct ConnectOutput {
100 void* memory; // zeroed, for the title's packets and output
101 HANDLE result_event;
102};
103struct CommandId {
104 uint32_t kind;
105 uint32_t stream;
106 uint32_t sequence;
107 uint32_t options;
108 uint64_t context;
109};
110struct ActivateCommand {
111 CommandId id;
112 uint32_t channels; // 1 or 2
113 uint32_t init_bytes;
114 const void* init;
115 float start_pitch;
116 uint32_t processing_bytes;
117 void* processing;
118};
119struct ProcessCommand {
120 CommandId id;
121 float pitch_ramp;
122 float target_pitch;
123 uint32_t first_frame;
124 uint32_t frame_count;
125 uint32_t input_bytes;
126 const uint8_t* input;
127 uint32_t output_bytes;
128 uint8_t* output;
129};
130struct Result {
131 CommandId id;
132 uint32_t state;
133 uint64_t state_data;
134 uint64_t usec;
135 HRESULT error;
136 uint32_t frames;
137 uint32_t output_bytes;
138 uint8_t* output;
139 float pitch;
140 uint32_t input_bytes;
141 const uint8_t* input;
142};
143#pragma pack(pop)
144static_assert(sizeof(ConnectInput) == 24, "six dwords");
145static_assert(sizeof(ConnectOutput) == 16, "memory and event");
146static_assert(sizeof(CommandId) == 24, "kind, stream, sequence, options, context");
147static_assert(sizeof(ActivateCommand) == 56, "CommandId and the activate fields");
148static_assert(sizeof(ProcessCommand) == 64, "CommandId and the process fields");
149static_assert(sizeof(Result) == 0x50, "the result the title dequeues");
150static_assert(offsetof(Result, state) == 0x18 && offsetof(Result, error) == 0x2C &&
151 offsetof(Result, output_bytes) == 0x34 && offsetof(Result, pitch) == 0x40 &&
152 offsetof(Result, input) == 0x48,
153 "the offsets the title and the layout agree on");
154
155struct Stream {
156 bool active = false;
157 uint32_t channels = 0;
158 uint32_t pending = 0; // results queued and not dequeued
159#if defined(LEONIDA_HAVE_OPUS_DECODER)
160 LeonidaOpusDecoder* decoder = nullptr;
161#endif
162};
163
164struct Connection {
165 void* memory = nullptr;
166 HANDLE event = nullptr;
167 uint32_t commands_per_stream = 0;
168 bool deinterleaved = false;
169 std::mutex mutex;
170 std::vector<Stream> streams;
171 std::deque<Result> results;
172 uint32_t accepted = 0;
173 uint32_t dequeued = 0;
174};
175
176// gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command kind, with
177// the caller, so the first boot shows what the title sends without a line per call.
178void note(const char* api, uint64_t value, const void* caller) {
179 if (!rt::startup_trace::enabled()) return;
180 static std::mutex mutex;
181 static std::set<std::pair<std::string, uint64_t>> seen;
182 {
183 const std::lock_guard lock(mutex);
184 if (!seen.insert({api, value}).second) return;
185 }
186 rt::startup_trace::event(
187 "audio_queue", std::string("\"api\":") + rt::startup_trace::quote(api) +
188 ",\"value\":" + rt::startup_trace::quote(rt::startup_trace::hex(value)) + ",\"caller\":" +
189 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller))));
190}
191
192// Samples per channel at 48 kHz in one Opus packet, from its table-of-contents byte and frame count code (RFC 6716,
193// section 3.1); 0 for a packet that is not valid. The no-decoder path counts frames this way.
194uint32_t opus_packet_frames(const uint8_t* packet, uint32_t bytes) {
195 if (!packet || bytes == 0) return 0;
196 static constexpr uint32_t kSilk[4] = {480, 960, 1920, 2880}; // 10, 20, 40, 60 ms
197 static constexpr uint32_t kHybrid[2] = {480, 960}; // 10, 20 ms
198 static constexpr uint32_t kCelt[4] = {120, 240, 480, 960}; // 2.5, 5, 10, 20 ms
199 const uint32_t config = packet[0] >> 3;
200 const uint32_t per_frame = config < 12 ? kSilk[config & 3] : config < 16 ? kHybrid[config & 1] : kCelt[config & 3];
201 uint32_t count = 0;
202 switch (packet[0] & 3) {
203 case 0: count = 1; break;
204 case 1:
205 case 2: count = 2; break;
206 default:
207 if (bytes < 2) return 0;
208 count = packet[1] & 0x3F;
209 break;
210 }
211 if (count == 0 || count * per_frame > kMaxFrames) return 0;
212 return count * per_frame;
213}
214
215// Fills a process command's result: the packet's PCM when runtime/opus_decoder is built, silence (with the frame
216// count from the table-of-contents byte) otherwise.
217void fill(Connection& connection, Stream& stream, const ProcessCommand& c, Result& r) {
218 r.input = c.input;
219 r.input_bytes = c.input_bytes;
220 r.output = c.output;
221 if (!c.input || !c.output || c.input_bytes == 0) {
222 r.error = E_INVALIDARG;
223 return;
224 }
225#if defined(LEONIDA_HAVE_OPUS_DECODER)
226 if (stream.decoder) {
227 const uint32_t channels = leonida_opus_decoder_channels(stream.decoder);
228 if (channels == 0) {
229 r.error = kInvalidStream;
230 return;
231 }
232 std::vector<float> pcm;
233 try {
234 pcm.resize(size_t(kMaxFrames) * channels);
235 } catch (...) {
236 r.error = E_OUTOFMEMORY;
237 return;
238 }
239 uint32_t decoded = 0;
240 if (leonida_opus_decode_packet(stream.decoder, c.input, c.input_bytes, pcm.data(), kMaxFrames, &decoded) !=
241 LEONIDA_OPUS_OK) {
242 r.error = kBadPacket;
243 return;
244 }
245 const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded;
246 uint32_t frames = decoded - first;
247 if (frames > c.frame_count) frames = c.frame_count;
248 const uint32_t room = c.output_bytes / (4 * channels);
249 if (frames > room) frames = room;
250 const uint32_t bytes = frames * channels * 4;
251 if (connection.deinterleaved && channels == 2) {
252 float* out = reinterpret_cast<float*>(c.output);
253 for (uint32_t i = 0; i < frames; ++i) {
254 out[i] = pcm[(first + i) * 2];
255 out[frames + i] = pcm[(first + i) * 2 + 1];
256 }
257 } else if (bytes != 0) {
258 std::memcpy(c.output, pcm.data() + first * channels, bytes);
259 }
260 r.frames = frames;
261 r.output_bytes = bytes;
262 return;
263 }
264#endif
265 const uint32_t decoded = opus_packet_frames(c.input, c.input_bytes);
266 if (decoded == 0) {
267 r.error = kBadPacket;
268 return;
269 }
270 const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded;
271 uint32_t frames = decoded - first;
272 if (frames > c.frame_count) frames = c.frame_count;
273 const uint32_t room = c.output_bytes / (4 * stream.channels);
274 if (frames > room) frames = room;
275 const uint32_t bytes = frames * stream.channels * 4;
276 std::memset(c.output, 0, bytes); // interleaved or not, silence is zeros
277 r.frames = frames;
278 r.output_bytes = bytes;
279}
280
281HRESULT __stdcall XApuConnect(const ConnectInput* input, ConnectOutput* output, Connection** out) {
282 note("XApuConnect", input ? input->processing : ~0ull, _ReturnAddress());
283 if (!input || !output || !out) return E_INVALIDARG;
284 *out = nullptr;
285 ConnectInput in;
286 std::memcpy(&in, input, sizeof(in));
287 if (in.streams == 0 || in.streams > kMaxStreams || in.commands_per_stream == 0 ||
288 in.commands_per_stream > kMaxCommandsPerStream || in.memory_bytes == 0)
289 return E_INVALIDARG;
290 if (in.processing != kDecodeOpus) {
291 std::fprintf(stderr, "[rt] xapu: XApuConnect for processing kind %u: only Opus decoding (1); E_NOTIMPL\n",
292 in.processing);
293 return kNotImpl;
294 }
295 if (in.frames_per_output != 0) return E_INVALIDARG;
296
297 auto* c = new (std::nothrow) Connection; // a throwing new would unwind into the title
298 if (!c) return E_OUTOFMEMORY;
299 try {
300 c->streams.resize(in.streams);
301 } catch (...) {
302 delete c;
303 return E_OUTOFMEMORY;
304 }
305 c->memory = VirtualAlloc(nullptr, in.memory_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed
306 if (!c->memory) {
307 delete c;
308 return E_OUTOFMEMORY;
309 }
310 if (in.options & kResultEvent) {
311 c->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // auto-reset
312 if (!c->event) {
313 const HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
314 VirtualFree(c->memory, 0, MEM_RELEASE);
315 delete c;
316 return hr;
317 }
318 }
319 c->commands_per_stream = in.commands_per_stream;
320 c->deinterleaved = (in.options & kDeinterleavedOutput) != 0;
321 const ConnectOutput o{c->memory, c->event};
322 std::memcpy(output, &o, sizeof(o));
323 *out = c;
324#if defined(LEONIDA_HAVE_OPUS_DECODER)
325 std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets decoded\n", in.streams);
326#else
327 std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets counted, not decoded\n",
328 in.streams);
329#endif
330 return S_OK;
331}
332
333HRESULT __stdcall XApuDisconnect(Connection* c, uint32_t /*0x20 at the measured site*/) {
334 note("XApuDisconnect", 0, _ReturnAddress());
335 if (!c) return E_INVALIDARG;
336#if defined(LEONIDA_HAVE_OPUS_DECODER)
337 for (Stream& s : c->streams)
338 if (s.decoder) leonida_opus_decoder_destroy(s.decoder);
339#endif
340 if (c->event) CloseHandle(c->event);
341 VirtualFree(c->memory, 0, MEM_RELEASE);
342 delete c;
343 return S_OK;
344}
345
346HRESULT __stdcall XApuEnqueueCommand(Connection* c, const void* command, uint32_t* accepted_so_far) {
347 if (!c || !command) return E_INVALIDARG;
348 CommandId id;
349 std::memcpy(&id, command, sizeof(id));
350 note("XApuEnqueueCommand", id.kind, _ReturnAddress());
351 if (id.kind < kActivate || id.kind > kReset) return kInvalidCommand;
352
353 const std::lock_guard lock(c->mutex);
354 if (id.stream >= c->streams.size()) return kInvalidStream;
355 Stream& stream = c->streams[id.stream];
356 if (stream.pending >= c->commands_per_stream) return kQueueFull;
357
358 Result r{};
359 r.id = id;
360 r.pitch = 1.0f;
361 if (id.kind == kActivate) {
362 ActivateCommand a;
363 std::memcpy(&a, command, sizeof(a));
364 if (stream.active) {
365 r.error = kAlreadyActive;
366 } else if (a.channels < 1 || a.channels > 2) {
367 r.error = E_INVALIDARG;
368 } else {
369 stream.active = true;
370 stream.channels = a.channels;
371#if defined(LEONIDA_HAVE_OPUS_DECODER)
372 if (leonida_opus_decoder_create(kOpusSampleRate, a.channels, &stream.decoder) != LEONIDA_OPUS_OK) {
373 stream.active = false;
374 stream.channels = 0;
375 r.error = E_INVALIDARG;
376 }
377#endif
378 }
379 } else if (id.kind == kDeactivate) {
380 stream.active = false;
381#if defined(LEONIDA_HAVE_OPUS_DECODER)
382 if (stream.decoder) {
383 leonida_opus_decoder_destroy(stream.decoder);
384 stream.decoder = nullptr;
385 }
386#endif
387 } else if (id.kind == kReset) {
388#if defined(LEONIDA_HAVE_OPUS_DECODER)
389 if (stream.decoder) leonida_opus_decoder_reset(stream.decoder);
390#endif
391 } else if (id.kind == kProcess) {
392 ProcessCommand p;
393 std::memcpy(&p, command, sizeof(p));
394 if (!stream.active) r.error = kInvalidStream;
395 else fill(*c, stream, p, r);
396 }
397 try {
398 c->results.push_back(r);
399 } catch (...) { // out of memory: refuse the command, nothing may unwind into the title
400 return E_OUTOFMEMORY;
401 }
402 ++stream.pending;
403 ++c->accepted;
404 if (accepted_so_far) *accepted_so_far = c->accepted;
405 if ((id.options & kSignalWhenDone) && c->event) SetEvent(c->event);
406 return S_OK;
407}
408
409HRESULT __stdcall XApuDequeueResult(Connection* c, Result* out) {
410 note("XApuDequeueResult", 0, _ReturnAddress());
411 if (!c || !out) return E_INVALIDARG;
412 const std::lock_guard lock(c->mutex);
413 if (c->results.empty()) return kNoResult;
414 const Result r = c->results.front();
415 c->results.pop_front();
416 --c->streams[r.id.stream].pending;
417 ++c->dequeued;
418 std::memcpy(out, &r, sizeof(r));
419 return S_OK;
420}
421
422uint32_t __stdcall XApuGetResultCount(Connection* c, uint32_t* dequeued_so_far) {
423 note("XApuGetResultCount", 0, _ReturnAddress());
424 if (!c) return 0;
425 const std::lock_guard lock(c->mutex);
426 if (dequeued_so_far) *dequeued_so_far = c->dequeued;
427 return static_cast<uint32_t>(c->results.size());
428}
429
430} // namespace
431
432SHIM_TABLE(xapu,
433 {"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)},
434 {"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)},
435 {"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)},
436 {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)},
437 {"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)},
438);