upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims/acphal.cpp
diff options
context:
space:
mode:
authorandretuta <andreviniciusmerlia@gmail.com>2026-11-24 01:44:00 -0300
committerandretuta <andreviniciusmerlia@gmail.com>2026-11-24 01:44:00 -0300
commit4750df6a06e68c05343c5895f1d6dcddf61e38c3 (patch)
tree7546846eaf91a7057fe22dde56c9f1fe4b0b85bb /runtime/shims/acphal.cpp
parentece4ba5b31ebc6f345c8e29eae1261f2f780057a (diff)
acphal: add portable XMA2 decoder, ACP message queue, and SHAPE XMA worker
- Add portable C++20 XMA2 packet parser and WMA Pro frame decoder (runtime/src/xma2_decoder.{h,cpp}, following FFmpeg wmaprodec.c / wmaprodata.h LGPL-2.1-or-later under Leonida's GPL-3.0-or-later) with cross-platform xma2_decoder_test. - Implement IAcpHal command/message queue protocol (REGISTER_MESSAGES, UNREGISTER_MESSAGES, LOAD_FLOWGRAPH, COMMAND_COMPLETED, DISCONNECTED, queue-full dropped counters, and APU notification word writes) in runtime/shims/acphal.cpp. - Wire a lazily-started, cleanly-joined background XMA2 decoder thread pumping enabled SHAPE_XMA_CONTEXT output rings in APU memory.
Diffstat (limited to 'runtime/shims/acphal.cpp')
-rw-r--r--runtime/shims/acphal.cpp693
1 files changed, 637 insertions, 56 deletions
diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp
index 5ead016d6..c1d375c1c 100644
--- a/runtime/shims/acphal.cpp
+++ b/runtime/shims/acphal.cpp
@@ -1,10 +1,12 @@
1// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine 1// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine
2// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series. 2// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series.
3// 3//
4// On a PC there is no SHAPE/ACP hardware and APU physical memory does not exist. 4// Provides:
5// This shim creates the APU heap from process memory and manages allocations within it. 5// - A VirtualAlloc-backed APU heap (cached + non-cached) with 32-bit device addresses;
6// The SHAPE context arrays are allocated on the process heap; the ACP interface 6// - SHAPE context arrays sized to the documented GDK strides;
7// accepts and acknowledges commands to allow audio bring-up to proceed cleanly. 7// - The IAcpHal command and message queue (registration, completion, disconnect,
8// flowgraph acknowledgement, and APU notification word writes);
9// - A background XMA2 decoder pumping enabled SHAPE_XMA_CONTEXT output rings.
8// 10//
9// Signatures from the public GDK reference (devdocs.xbox.com): 11// Signatures from the public GDK reference (devdocs.xbox.com):
10// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS. 12// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS.
@@ -14,21 +16,31 @@
14 16
15#include <windows.h> 17#include <windows.h>
16 18
17#include <atomic> 19#include <algorithm>
18#include <array> 20#include <array>
21#include <atomic>
22#include <chrono>
23#include <climits>
24#include <condition_variable>
19#include <cstddef> 25#include <cstddef>
20#include <cstdint> 26#include <cstdint>
21#include <cstdio> 27#include <cstdio>
22#include <cstdlib> 28#include <cstdlib>
23#include <cstring> 29#include <cstring>
30#include <deque>
24#include <map> 31#include <map>
32#include <memory>
25#include <mutex> 33#include <mutex>
34#include <optional>
26#include <set> 35#include <set>
36#include <shared_mutex>
27#include <string> 37#include <string>
38#include <thread>
28#include <vector> 39#include <vector>
29 40
30#include "shims.h" 41#include "shims.h"
31#include "startup_trace.h" 42#include "startup_trace.h"
43#include "../src/xma2_decoder.h"
32 44
33namespace { 45namespace {
34 46
@@ -241,6 +253,13 @@ struct ApuRegion {
241 return static_cast<uint8_t*>(base) + offset; 253 return static_cast<uint8_t*>(base) + offset;
242 } 254 }
243 255
256 uint8_t* span_from_offset(uint32_t offset, std::size_t len) const {
257 if (!base || len == 0 || offset >= size) return nullptr;
258 const uint64_t remaining = size - offset;
259 if (len > remaining) return nullptr;
260 return static_cast<uint8_t*>(base) + offset;
261 }
262
244 void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) { 263 void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) {
245 if (alloc_size == 0 || alignment == 0) return nullptr; 264 if (alloc_size == 0 || alignment == 0) return nullptr;
246 uint64_t at = 0; 265 uint64_t at = 0;
@@ -283,46 +302,596 @@ ApuRegion g_noncached_heap;
283// Tracked SHAPE context arrays 302// Tracked SHAPE context arrays
284std::vector<void*> g_active_shape_arrays; 303std::vector<void*> g_active_shape_arrays;
285 304
305// Resolves a contiguous [apu, apu + len) byte range inside the APU heap.
306uint8_t* apu_span(uint32_t apu, std::size_t len) {
307 if (apu < kApuBaseAddress || len == 0) return nullptr;
308 std::lock_guard lock(g_apu_mutex);
309 const uint32_t offset = apu - kApuBaseAddress;
310 if (g_cached_heap.base && offset < g_cached_heap.size) {
311 return g_cached_heap.span_from_offset(offset, len);
312 }
313 if (g_noncached_heap.base) {
314 const uint64_t cached_span = g_cached_heap.size;
315 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
316 return g_noncached_heap.span_from_offset(
317 static_cast<uint32_t>(offset - cached_span), len);
318 }
319 }
320 return nullptr;
321}
322
323// ---- ACP Command / Message Protocol Constants ----
324
325constexpr uint32_t kCmdLoadFlowgraph = 1;
326constexpr uint32_t kCmdRegisterMessages = 2;
327constexpr uint32_t kCmdUnregisterMessages = 3;
328constexpr uint32_t kCmdEnableXma = 5;
329constexpr uint32_t kCmdEnableXmas = 6;
330constexpr uint32_t kCmdDisableXma = 7;
331constexpr uint32_t kCmdDisableXmas = 8;
332constexpr uint32_t kCmdAdvanceXmaRead = 18;
333
334constexpr uint32_t kMsgFlowgraphCompleted = 0x02u;
335constexpr uint32_t kMsgCommandCompleted = 0x10u;
336constexpr uint32_t kMsgDisconnected = 0x80u;
337
338// 128 samples per audio frame at 48 kHz = 375 audio frames/second.
339constexpr uint64_t kAudioFramesPerSecond = 375;
340
341// ---- XMA2 Hardware Context Decoder Engine ----
342//
343// Each 64-byte SHAPE_XMA_CONTEXT holds 16 32-bit words shared with the title:
344// Word 0: input 0 packets (0..11), loop count (12..19, 255 = forever),
345// valid input bits (20..21), output ring blocks (22..26), write block (27..31).
346// Word 1: input 1 packets (0..11), loop end subframe (12..13), loop start skip subframes
347// (17..19), initial skip subframes (24..26), rate index (27..28: 24/32/44.1/48 kHz),
348// stereo (29), output writable (31).
349// Word 2: read bit offset (0..25), error status (26..30), error flag (31).
350// Word 3: loop start bit offset (0..25).
351// Word 4: loop end bit offset (0..25), current input buffer index (31).
352// Word 5: input 0 APU address.
353// Word 6: input 1 APU address.
354// Word 7: output ring APU address.
355// Word 8: overlap buffer APU address.
356// Word 9: output read block index (0..4).
357
358constexpr std::size_t kXmaBlockBytes = 256;
359constexpr std::size_t kXmaSamplesPerBlock = kXmaBlockBytes / 2;
360constexpr uint32_t kXmaErrorInputInvalid = 4;
361
362struct XmaContextView {
363 volatile uint32_t* words = nullptr;
364
365 uint32_t get(std::size_t index) const { return words[index]; }
366 void set(std::size_t index, uint32_t value) const { words[index] = value; }
367
368 uint32_t field(std::size_t index, uint32_t shift, uint32_t bits) const {
369 const uint32_t mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
370 return (get(index) >> shift) & mask;
371 }
372
373 void set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const {
374 const uint32_t raw_mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
375 const uint32_t mask = raw_mask << shift;
376 set(index, (get(index) & ~mask) | ((value << shift) & mask));
377 }
378
379 std::size_t channels() const { return 1u + static_cast<std::size_t>(field(1, 29, 1)); }
380};
381
382struct XmaVoice {
383 std::optional<leonida::xma2::Decoder> decoder;
384 std::deque<int16_t> pcm;
385 std::size_t skip = 0; // samples per channel to drop (start/loop subframe skip)
386 bool ended = false;
387 std::size_t produced = 0;
388 uint32_t frames = 0;
389 uint32_t bad_frames = 0;
390 int16_t peak = 0;
391};
392
393struct XmaVoiceSlot {
394 std::mutex mutex;
395 std::optional<XmaVoice> voice;
396};
397
398class XmaEngine {
399public:
400 ~XmaEngine() { unbind(); }
401
402 void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) {
403 stop_worker();
404 std::unique_lock lock(table_mutex_);
405 array_ = reinterpret_cast<volatile uint32_t*>(array);
406 voices_.clear();
407 voices_.reserve(count);
408 for (uint32_t i = 0; i < count; ++i) {
409 voices_.push_back(std::make_unique<XmaVoiceSlot>());
410 }
411 active_count_.store(0, std::memory_order_relaxed);
412 }
413
414 void unbind() {
415 stop_worker();
416 std::unique_lock lock(table_mutex_);
417 array_ = nullptr;
418 voices_.clear();
419 active_count_.store(0, std::memory_order_relaxed);
420 }
421
422 bool handle_command(uint32_t command, const void* config) {
423 auto read_word = [config](std::size_t index) -> uint32_t {
424 if (!config) return 0u;
425 uint32_t value = 0;
426 std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t),
427 sizeof(uint32_t));
428 return value;
429 };
430
431 switch (command) {
432 case kCmdEnableXma:
433 if (config) enable(read_word(0));
434 return true;
435 case kCmdDisableXma:
436 if (config) disable(read_word(0));
437 return true;
438 case kCmdEnableXmas:
439 case kCmdDisableXmas: {
440 std::shared_lock lock(table_mutex_);
441 const std::size_t count = voices_.size();
442 lock.unlock();
443 if (!config) return true;
444 for (std::size_t i = 0; i < count; ++i) {
445 const uint32_t bits = read_word(i / 32);
446 if ((bits & (1u << (i % 32))) != 0) {
447 if (command == kCmdEnableXmas) {
448 enable(static_cast<uint32_t>(i));
449 } else {
450 disable(static_cast<uint32_t>(i));
451 }
452 }
453 }
454 return true;
455 }
456 case kCmdAdvanceXmaRead:
457 if (config) advance_read(read_word(0), read_word(1));
458 return true;
459 default:
460 return false;
461 }
462 }
463
464 void enable(uint32_t index) {
465 {
466 std::shared_lock table_lock(table_mutex_);
467 XmaContextView ctx = context_locked(index);
468 if (!ctx.words) return;
469
470 std::lock_guard slot_lock(voices_[index]->mutex);
471 const bool was_active = voices_[index]->voice.has_value();
472 // Clear error_status (26..30) and error flag (31).
473 ctx.set_field(2, 26, 6, 0);
474
475 XmaVoice voice;
476 voice.skip = static_cast<std::size_t>(ctx.field(1, 24, 3)) *
477 leonida::xma2::kSubframeSamples;
478 voices_[index]->voice.emplace(std::move(voice));
479 if (!was_active) {
480 active_count_.fetch_add(1, std::memory_order_relaxed);
481 }
482 }
483 ensure_worker_and_wake();
484 }
485
486 void disable(uint32_t index) {
487 std::shared_lock table_lock(table_mutex_);
488 if (index >= voices_.size()) return;
489 std::lock_guard slot_lock(voices_[index]->mutex);
490 if (voices_[index]->voice.has_value()) {
491 voices_[index]->voice.reset();
492 active_count_.fetch_sub(1, std::memory_order_relaxed);
493 }
494 }
495
496 void advance_read(uint32_t index, uint32_t blocks) {
497 bool wake = false;
498 {
499 std::shared_lock table_lock(table_mutex_);
500 XmaContextView ctx = context_locked(index);
501 if (!ctx.words) return;
502
503 std::lock_guard slot_lock(voices_[index]->mutex);
504 const uint32_t raw_size = ctx.field(0, 22, 5);
505 const uint32_t size = raw_size ? raw_size : 1u;
506 const uint32_t read = (ctx.field(9, 0, 5) + blocks) % size;
507 ctx.set_field(9, 0, 5, read);
508 if (blocks > 0) {
509 ctx.set_field(1, 31, 1, 1);
510 }
511 wake = voices_[index]->voice.has_value();
512 }
513 if (wake) ensure_worker_and_wake();
514 }
515
516private:
517 XmaContextView context_locked(uint32_t index) const {
518 if (!array_ || index >= voices_.size()) return {};
519 return XmaContextView{array_ + static_cast<std::size_t>(index) * 16};
520 }
521
522 static bool decode_one_frame(XmaContextView ctx, XmaVoice& voice) {
523 if (voice.ended) return false;
524
525 const std::size_t channels = ctx.channels();
526 uint32_t current = ctx.field(4, 31, 1);
527 const uint32_t valid = ctx.field(0, 20, 2);
528
529 if ((valid & (1u << current)) == 0) {
530 const uint32_t other = 1u - current;
531 if ((valid & (1u << other)) == 0) {
532 // Both inputs exhausted: flush remaining overlap tail, then signal INPUT_INVALID.
533 if (voice.decoder.has_value()) {
534 std::vector<int16_t> tail;
535 voice.decoder->flush(tail);
536 voice.pcm.insert(voice.pcm.end(), tail.begin(), tail.end());
537 }
538 voice.ended = true;
539 ctx.set_field(2, 26, 5, kXmaErrorInputInvalid);
540 ctx.set_field(2, 31, 1, 1);
541 return !voice.pcm.empty();
542 }
543 current = other;
544 ctx.set_field(4, 31, 1, current);
545 ctx.set_field(2, 0, 26, 0);
546 }
547
548 const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6);
549 const uint32_t packets = (current == 0) ? ctx.field(0, 0, 12) : ctx.field(1, 0, 12);
550 const std::size_t input_bytes =
551 static_cast<std::size_t>(packets) * leonida::xma2::kPacketBytes;
552 const uint8_t* data = apu_span(address & ~0x7FFu, input_bytes);
553 if (!data) {
554 ctx.set_field(0, 20 + current, 1, 0);
555 return true;
556 }
557
558 std::size_t at = static_cast<std::size_t>(ctx.field(2, 0, 26));
559 if (at < leonida::xma2::kHeaderBits) {
560 const auto pkt = leonida::xma2::parse_packet(data, input_bytes, 0);
561 at = leonida::xma2::kHeaderBits + (pkt.has_value() ? pkt->first_frame_bit : 0u);
562 }
563
564 const auto frame = leonida::xma2::read_frame(data, input_bytes, at);
565 if (!frame.has_value()) {
566 ctx.set_field(0, 20 + current, 1, 0);
567 return true;
568 }
569
570 if (!voice.decoder.has_value()) {
571 static constexpr uint32_t kRates[4] = {24000, 32000, 44100, 48000};
572 const uint32_t rate_idx = ctx.field(1, 27, 2) & 3u;
573 voice.decoder.emplace(channels, kRates[rate_idx]);
574 }
575
576 std::vector<int16_t> pcm;
577 pcm.reserve(leonida::xma2::kFrameSamples * channels);
578 ++voice.frames;
579 if (!voice.decoder->decode(frame->data.data(), frame->bits, pcm)) {
580 ++voice.bad_frames;
581 }
582
583 std::size_t next = frame->next.value_or(0);
584 const uint32_t loops = ctx.field(0, 12, 8);
585 const std::size_t loop_end = static_cast<std::size_t>(ctx.field(4, 0, 26));
586 const bool ends_loop =
587 loop_end != 0 &&
588 (frame->start == loop_end ||
589 (frame->start < loop_end && (!frame->next.has_value() || loop_end < *frame->next)));
590 if (loops > 0 && ends_loop) {
591 const std::size_t keep =
592 (static_cast<std::size_t>(ctx.field(1, 12, 2)) + 1u) *
593 leonida::xma2::kSubframeSamples * channels;
594 if (keep < pcm.size()) pcm.resize(keep);
595 next = static_cast<std::size_t>(ctx.field(3, 0, 26));
596 voice.skip = static_cast<std::size_t>(ctx.field(1, 17, 3)) *
597 leonida::xma2::kSubframeSamples;
598 if (loops != 255u) {
599 ctx.set_field(0, 12, 8, loops - 1u);
600 }
601 }
602
603 const std::size_t skip_samples = std::min(voice.skip * channels, pcm.size());
604 voice.skip -= skip_samples / channels;
605 voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast<std::ptrdiff_t>(skip_samples),
606 pcm.end());
607
608 if (next == 0) {
609 ctx.set_field(0, 20 + current, 1, 0);
610 }
611 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next));
612 return true;
613 }
614
615 static void pump_voice(XmaContextView ctx, XmaVoice& voice) {
616 const uint32_t size = ctx.field(0, 22, 5);
617 if (size == 0) return;
618
619 while (ctx.field(1, 31, 1) == 1) {
620 int decode_guard = 0;
621 while (voice.pcm.size() < kXmaSamplesPerBlock && decode_guard++ < 16) {
622 if (!decode_one_frame(ctx, voice)) break;
623 }
624 if (voice.pcm.empty()) return;
625
626 const uint32_t write = ctx.field(0, 27, 5);
627 const uint32_t out_addr =
628 ctx.get(7) + write * static_cast<uint32_t>(kXmaBlockBytes);
629 uint8_t* out = apu_span(out_addr, kXmaBlockBytes);
630 if (!out) return;
631
632 for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) {
633 int16_t sample = 0;
634 if (!voice.pcm.empty()) {
635 sample = voice.pcm.front();
636 voice.pcm.pop_front();
637 }
638 const int32_t mag =
639 (sample == INT16_MIN) ? INT16_MAX : std::abs(static_cast<int32_t>(sample));
640 if (mag > voice.peak) voice.peak = static_cast<int16_t>(mag);
641 const uint16_t raw = static_cast<uint16_t>(sample);
642 out[2 * i] = static_cast<uint8_t>(raw & 0xFFu);
643 out[2 * i + 1] = static_cast<uint8_t>((raw >> 8) & 0xFFu);
644 }
645
646 voice.produced += kXmaSamplesPerBlock / ctx.channels();
647 const uint32_t next_write = (write + 1u) % size;
648 ctx.set_field(0, 27, 5, next_write);
649 if (next_write == ctx.field(9, 0, 5)) {
650 ctx.set_field(1, 31, 1, 0);
651 }
652 }
653 }
654
655 void pump_all() {
656 std::shared_lock table_lock(table_mutex_);
657 if (!array_) return;
658 for (std::size_t i = 0; i < voices_.size(); ++i) {
659 std::lock_guard slot_lock(voices_[i]->mutex);
660 if (voices_[i]->voice.has_value()) {
661 pump_voice(context_locked(static_cast<uint32_t>(i)), *voices_[i]->voice);
662 }
663 }
664 }
665
666 void ensure_worker_and_wake() {
667 std::lock_guard lock(worker_mutex_);
668 if (!worker_.joinable()) {
669 stopping_ = false;
670 worker_ = std::thread([this]() { worker_loop(); });
671 }
672 wake_requested_ = true;
673 worker_cv_.notify_one();
674 }
675
676 void stop_worker() {
677 std::thread to_join;
678 {
679 std::lock_guard lock(worker_mutex_);
680 if (!worker_.joinable()) return;
681 stopping_ = true;
682 wake_requested_ = true;
683 worker_cv_.notify_one();
684 to_join = std::move(worker_);
685 }
686 if (to_join.joinable()) to_join.join();
687 }
688
689 void worker_loop() {
690 for (;;) {
691 {
692 std::unique_lock lock(worker_mutex_);
693 if (stopping_) return;
694 if (active_count_.load(std::memory_order_relaxed) == 0 && !wake_requested_) {
695 worker_cv_.wait(lock, [this]() { return stopping_ || wake_requested_; });
696 if (stopping_) return;
697 }
698 wake_requested_ = false;
699 }
700
701 pump_all();
702
703 std::unique_lock lock(worker_mutex_);
704 if (stopping_) return;
705 if (!wake_requested_ && active_count_.load(std::memory_order_relaxed) > 0) {
706 // One 256-byte output block lasts ~2.67 ms at 48 kHz mono.
707 worker_cv_.wait_for(lock, std::chrono::milliseconds(2),
708 [this]() { return stopping_ || wake_requested_; });
709 }
710 }
711 }
712
713 mutable std::shared_mutex table_mutex_;
714 volatile uint32_t* array_ = nullptr;
715 std::vector<std::unique_ptr<XmaVoiceSlot>> voices_;
716 std::atomic<uint32_t> active_count_{0};
717
718 std::mutex worker_mutex_;
719 std::condition_variable worker_cv_;
720 std::thread worker_;
721 bool stopping_ = false;
722 bool wake_requested_ = false;
723};
724
725XmaEngine g_xma_engine;
726
286// ---- IAcpHal Interface Implementation ---- 727// ---- IAcpHal Interface Implementation ----
287 728
288struct AcpHalImpl { 729#pragma pack(push, 1)
730struct AcpMessage {
731 uint32_t kind = 0;
732 uint32_t dropped = 0;
733 uint32_t usec = 0;
734 uint8_t data[16]{};
735};
736#pragma pack(pop)
737static_assert(sizeof(AcpMessage) == 28, "AcpMessage is 28 bytes");
738
739void write_u32_le(uint8_t* dst, uint32_t value) {
740 dst[0] = static_cast<uint8_t>(value & 0xFFu);
741 dst[1] = static_cast<uint8_t>((value >> 8) & 0xFFu);
742 dst[2] = static_cast<uint8_t>((value >> 16) & 0xFFu);
743 dst[3] = static_cast<uint8_t>((value >> 24) & 0xFFu);
744}
745
746void write_u64_le(uint8_t* dst, uint64_t value) {
747 write_u32_le(dst, static_cast<uint32_t>(value & 0xFFFFFFFFu));
748 write_u32_le(dst + 4, static_cast<uint32_t>(value >> 32));
749}
750
751struct IAcpHal {
752 virtual HRESULT __stdcall connect(uint32_t commands, uint32_t messages) = 0;
753 virtual HRESULT __stdcall disconnect() = 0;
754 virtual HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
755 const void* config, uint32_t notification) = 0;
756 virtual uint32_t __stdcall pop_message(void* out) = 0;
757 virtual uint32_t __stdcall get_num_messages() = 0;
758 virtual HRESULT __stdcall release() = 0;
759};
760
761struct AcpHalImpl final : IAcpHal {
762 std::mutex mutex_;
763 bool connected_ = false;
764 uint32_t mask_ = 0;
765 std::deque<AcpMessage> messages_;
766 std::size_t capacity_ = 0;
767 uint32_t dropped_ = 0;
768 std::chrono::steady_clock::time_point since_ = std::chrono::steady_clock::now();
769
770 uint64_t elapsed_usec_locked() const {
771 const auto dt = std::chrono::steady_clock::now() - since_;
772 return static_cast<uint64_t>(
773 std::chrono::duration_cast<std::chrono::microseconds>(dt).count());
774 }
775
776 uint32_t audio_frame_locked() const {
777 return static_cast<uint32_t>((elapsed_usec_locked() * kAudioFramesPerSecond) / 1000000ull);
778 }
779
780 void post_locked(uint32_t kind, const uint8_t* payload, std::size_t len) {
781 if ((mask_ & kind) == 0) return;
782 if (messages_.size() >= capacity_) {
783 if (dropped_ < UINT32_MAX) ++dropped_;
784 return;
785 }
786 AcpMessage msg{};
787 msg.kind = kind;
788 msg.dropped = dropped_;
789 dropped_ = 0;
790 msg.usec = static_cast<uint32_t>(elapsed_usec_locked());
791 if (payload && len > 0) {
792 std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data)));
793 }
794 messages_.push_back(msg);
795 }
796
289 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) 797 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked)
290 virtual HRESULT __stdcall connect(uint32_t, uint32_t) { 798 HRESULT __stdcall connect(uint32_t commands, uint32_t messages) override {
291 trace_call("AcpHal::Connect", ""); 799 trace_call("AcpHal::Connect", "");
800 if (commands == 0) return E_INVALIDARG;
801 std::lock_guard lock(mutex_);
802 connected_ = true;
803 capacity_ = messages;
292 return S_OK; 804 return S_OK;
293 } 805 }
294 806
295 // Slot 1: Disconnect (called at shutdown) 807 // Slot 1: Disconnect (called at shutdown)
296 virtual HRESULT __stdcall disconnect() { 808 HRESULT __stdcall disconnect() override {
297 trace_call("AcpHal::Disconnect", ""); 809 trace_call("AcpHal::Disconnect", "");
810 std::lock_guard lock(mutex_);
811 if (!connected_) return E_FAIL;
812 post_locked(kMsgDisconnected, nullptr, 0);
813 connected_ = false;
298 return S_OK; 814 return S_OK;
299 } 815 }
300 816
301 // Slot 2: SubmitCommand 817 // Slot 2: SubmitCommand
302 // Critical: The title calls slot 2 as (2, 0xf0f0f0f0, -1, config, 0) and 818 // Acknowledges command completion, updates registered message masks, dispatches
303 // a negative result triggers a fatal int3 kernel panic (+0x43ad94e). 819 // XMA voice commands, and writes any requested APU notification word.
304 virtual HRESULT __stdcall submit_command(uint32_t cmd, uint32_t d1, uint32_t d2, 820 HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
305 const void* config, uint32_t d3) { 821 const void* config, uint32_t notification) override {
306 (void)cmd; 822 (void)frame;
307 (void)d1; 823 auto read_word = [config](std::size_t index) -> uint32_t {
308 (void)d2; 824 if (!config) return 0u;
309 (void)config; 825 uint32_t value = 0;
310 (void)d3; 826 std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t),
311 static std::atomic<bool> warned{false}; 827 sizeof(uint32_t));
312 if (!warned.exchange(true, std::memory_order_relaxed)) { 828 return value;
313 std::fprintf(stderr, 829 };
314 "[rt] acphal: command accepted and dropped: no audio DSP hardware on PC\n"); 830
831 const bool handled_xma = g_xma_engine.handle_command(cmd, config);
832 {
833 std::lock_guard lock(mutex_);
834 if (!handled_xma) {
835 switch (cmd) {
836 case kCmdRegisterMessages:
837 mask_ |= read_word(0);
838 break;
839 case kCmdUnregisterMessages:
840 mask_ &= ~read_word(0);
841 break;
842 case kCmdLoadFlowgraph: {
843 uint8_t payload[4];
844 write_u32_le(payload, read_word(1));
845 post_locked(kMsgFlowgraphCompleted, payload, sizeof(payload));
846 break;
847 }
848 default:
849 break;
850 }
851 }
852 if (id != 0) {
853 uint8_t done[16];
854 write_u32_le(done, cmd);
855 write_u64_le(done + 4, id);
856 write_u32_le(done + 12, audio_frame_locked());
857 post_locked(kMsgCommandCompleted, done, sizeof(done));
858 }
315 } 859 }
860
861 if (notification != 0) {
862 if (uint8_t* word_bytes = apu_span(notification, sizeof(uint32_t))) {
863 if ((reinterpret_cast<uintptr_t>(word_bytes) & 3u) == 0) {
864 *reinterpret_cast<volatile uint32_t*>(word_bytes) = 1u;
865 } else {
866 static constexpr uint8_t kOneLe[4] = {1, 0, 0, 0};
867 volatile uint8_t* dst = word_bytes;
868 for (std::size_t i = 0; i < 4; ++i) dst[i] = kOneLe[i];
869 }
870 }
871 }
872
316 trace_call("AcpHal::SubmitCommand", ""); 873 trace_call("AcpHal::SubmitCommand", "");
317 return S_OK; 874 return S_OK;
318 } 875 }
319 876
320 // Slots 3 and 4: PopMessage and GetNumMessages (message polling, not called by title) 877 // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty.
321 virtual uint32_t __stdcall pop_message() { return 0; } 878 uint32_t __stdcall pop_message(void* out) override {
322 virtual uint32_t __stdcall get_num_messages() { return 0; } 879 std::lock_guard lock(mutex_);
880 if (messages_.empty()) return 0u;
881 const AcpMessage msg = messages_.front();
882 messages_.pop_front();
883 if (out) std::memcpy(out, &msg, sizeof(msg));
884 return 1u;
885 }
886
887 // Slot 4: GetNumMessages
888 uint32_t __stdcall get_num_messages() override {
889 std::lock_guard lock(mutex_);
890 return static_cast<uint32_t>(messages_.size());
891 }
323 892
324 // Slot 5: Release 893 // Slot 5: Release
325 virtual HRESULT __stdcall release() { 894 HRESULT __stdcall release() override {
326 trace_call("AcpHal::Release", ""); 895 trace_call("AcpHal::Release", "");
327 delete this; 896 delete this;
328 return S_OK; 897 return S_OK;
@@ -343,36 +912,45 @@ HRESULT __stdcall AcpHalCreate(void** ppAcpHal) {
343HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { 912HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
344 if (!ctx) return E_POINTER; 913 if (!ctx) return E_POINTER;
345 914
346 std::lock_guard lock(g_apu_mutex); 915 SHAPE_XMA_CONTEXT* xma_array = nullptr;
916 uint32_t xma_count = 0;
917 {
918 std::lock_guard lock(g_apu_mutex);
919
920 auto alloc_array = [](uint32_t count, size_t elem_size) -> void* {
921 if (count == 0) return nullptr;
922 void* ptr = std::calloc(count, elem_size);
923 if (ptr) g_active_shape_arrays.push_back(ptr);
924 return ptr;
925 };
926
927 ctx->srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>(
928 alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT)));
929 ctx->eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>(
930 alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT)));
931 ctx->filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>(
932 alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT)));
933 ctx->dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>(
934 alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT)));
935 ctx->xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>(
936 alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT)));
937 ctx->pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>(
938 alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT)));
939
940 // On PC there is no physical APU address translation for host context arrays;
941 // assign unique synthetic addresses from the APU base.
942 ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0};
943 ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0};
944 ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0};
945 ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0};
946 ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0};
947 ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0};
948
949 xma_array = ctx->xmaContextArray;
950 xma_count = ctx->numXmaContexts;
951 }
347 952
348 auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { 953 g_xma_engine.bind(xma_array, xma_count);
349 if (count == 0) return nullptr;
350 void* ptr = std::calloc(count, elem_size);
351 if (ptr) g_active_shape_arrays.push_back(ptr);
352 return ptr;
353 };
354
355 ctx->srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>(
356 alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT)));
357 ctx->eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>(
358 alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT)));
359 ctx->filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>(
360 alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT)));
361 ctx->dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>(
362 alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT)));
363 ctx->xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>(
364 alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT)));
365 ctx->pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>(
366 alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT)));
367
368 // On PC there is no physical APU address translation for host context arrays;
369 // assign unique synthetic addresses from the APU base.
370 ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0};
371 ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0};
372 ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0};
373 ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0};
374 ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0};
375 ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0};
376 954
377 trace_call("AcpHalAllocateShapeContexts", 955 trace_call("AcpHalAllocateShapeContexts",
378 ",\"src\":" + std::to_string(ctx->numSrcContexts) + 956 ",\"src\":" + std::to_string(ctx->numSrcContexts) +
@@ -384,6 +962,9 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
384// ---- AcpHalReleaseShapeContexts ---- 962// ---- AcpHalReleaseShapeContexts ----
385 963
386HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { 964HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) {
965 // Stop and detach the XMA worker before freeing backing arrays.
966 g_xma_engine.unbind();
967
387 std::lock_guard lock(g_apu_mutex); 968 std::lock_guard lock(g_apu_mutex);
388 969
389 // Free all recorded context allocations 970 // Free all recorded context allocations
@@ -439,8 +1020,8 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
439// ---- ApuAlloc ---- 1020// ---- ApuAlloc ----
440 1021
441HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, 1022HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
442 uint32_t sizeInBytes, uint32_t alignmentInBytes, 1023 uint32_t sizeInBytes, uint32_t alignmentInBytes,
443 uint32_t flags) { 1024 uint32_t flags) {
444 if (!virtualAddress) return E_POINTER; 1025 if (!virtualAddress) return E_POINTER;
445 *virtualAddress = nullptr; 1026 *virtualAddress = nullptr;
446 if (physicalAddress) *physicalAddress = 0; 1027 if (physicalAddress) *physicalAddress = 0;