mirror of
https://github.com/par274/sharpemu.git
synced 2026-07-30 06:29:46 +08:00
db4339f698
* fix(kernel): implement APR ResolveFilepathsWithPrefixToIdsAndFileSizes Resource streamers resolve relative paths against a shared prefix; without this HLE every call returned NOT_FOUND and assets never got real ids/sizes. * fix(remoteplay): stub Initialize and GetConnectionStatus as disconnected Titles probe Remote Play during pad/network bring-up; unresolved imports returned NOT_FOUND. Report initialized + disconnected so callers take the normal offline path. * fix(agc): accept Gen5 hull shaders that omit PGM_LO/HI in CreateShader Type-5 headers can start with RSRC1/RSRC2; rejecting them left null handles and Main Thread AVs. Scan the SH table and skip PGM patch when absent. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(kernel): reject getdents on file fds and emit . / .. for empty dirs Returning rax=0 for non-directory or empty listings looked like EOF and let GTA treat the fd as a pointer (fiWriteAsyncDataWorker AV at 0xB1). * fix(hle): enable GuestImageWriteTracker CPU sync on Windows Windows previously hard-disabled the tracker, so CPU-written guest planes never marked dirty and host textures stayed empty. Arm pages with VirtualProtect, handle write AVs in VEH, and warm/test on VirtualAlloc memory so protect cannot poison the CRT heap. * fix(agc): skip CB metadata draws for EliminateFastClear/Fmask/DCC CB_COLOR_CONTROL modes 2/5/6 are colour-buffer metadata ops; applying the bound shader as a normal colour draw corrupts subsequent composites. Decode MODE from bits [6:4] and return before translate. * fix(agc): merge Prospero attrib-table formats onto IR vertex inputs IR-discovered BufferLoadFormat often keeps a stale float sharp format; patch DataFormat/offset from the AGC attrib table (semantic index), allow offen fetches, and map quirks 113/121 through NarrowVk for host vertex input. * fix(audio): harden AudioOut2 stack out-buffer writes against canary smash Titles that stack-allocate AudioOut2 outs next to the frame canary were corrupted by oversized or mistyped HLE writes; keep ContextPush pacing. * Revert "fix(memory): reserve only large regions (#608)" This reverts commit8f9456229a. * fix(gpu): decode Gen5 R16 and RG32 render-target formats * fix(audio): AudioOut2 host beds, deeper waveOut queue, AJM MP3 GTA V Enhanced routes intro/menu audio through AudioOut2 and FMOD's AJM MP3 path. Wire PortCreate/PortSetAttributes/ContextPush to dual host stereo streams, deepen WinMM queue to 128KiB, and decode AJM codec 0 with a stateful NLayer helper so menu music is not silent. * fix(agc): map PS interpolants via SPI_PS_INPUT_CNTL semantics Identity ATTR→param wiring ignored hardware remapping, so UI draws got wrong (or empty) interpolants. Pack CNTL from matched PS/GS semantics, thread it into Vulkan/Metal as Location/Flat, and fingerprint it in the graphics shader cache key. * fix(agc): rect-list/NGG strips, Index8 expand, and GE_INDX_OFFSET NGG single-rect UI needs triangle-strip expansion; Prospero Index8 must expand to host u16; glyphs need base vertex from GE_INDX_OFFSET. Skip param-less rect-lists instead of inventing colour draws. * fix(np): report GTA Story Mode addcont entitlements as owned NpEntitlementAccess was returning an empty add-on list, so GTA V Enhanced offered Buy Story Mode. Publish the installed license labels and stub premium-event registration so offline sessions take the owned path. * fix(cpu): prefer native workers for all guest entry stubs Route thread entry, continuation, and main entry through RunGuestEntryStub so guest stubs are not invoked above CLR-managed frames (UnmanagedCallersOnly FailFast). Keep requireNativeWorker for tbb_thead; other paths prefer workers with calli fallback. * fix(agc): implement Rewind/Jump writers and IT_REWIND waits GTA Subrender AVs came from AcbJumpGetSize / DcbRewind returning NOT_FOUND as packet sizes. Add IT_REWIND and INDIRECT_BUFFER writers, patch SetRewindState into the GPU wait registry, and nest-parse 4-dword jumps. * fix(gpu): use AddrLib ExactXor for Gen5 Standard256B (mode 1) Mode 5 already had Standard4K ExactXor; mode 1 still used the generic StandardSwizzle block table, which mis-detiles Gen5 UI atlases. * Revert "fix(cpu): prefer native workers for all guest entry stubs" This reverts commit31c4db0d38. * fix(memory): commit-first large maps; reserve only on failure Replace the #608 always-reserve-only exact-map path with allocate-first and lazy reserve fallback when a huge non-exec commit cannot be satisfied. Prime and widen GetPointer commit so the fallback path is safer for native walkers. Drops the need for a hard #608 revert. * [Agc] Implement fused shader half exports * fix(agc): accept optional hull state in CreatePrimState Port the CreatePrimState hull-optional path from #583 so fused HS pipelines (GTA) are not rejected with INVALID_ARGUMENT. Geometry-derived CX/UC writes are unchanged; hull is traced only. * fix(videoout): restore thread-safe VulkanHostBufferPool (#564) The6db095ewipe dropped CasualcoderDev's lock-ordering-safe pool. Concurrent Return/TryTake without the gate races after the first present and can hang the submit path. * Revert "fix(agc): implement Rewind/Jump writers and IT_REWIND waits" This reverts commitbec77bf083. * test(memory): align lazy-commit expectations with commit-first policy Fake hosts must reject Allocate so reserve-only paths still run, and GetPointer asserts the 32 MiB prime range including AlignUp spill. * diag(gpu): log guest-queue backlog breakdown under backpressure Rate-limit top work types and ordered debugName prefixes when the Vulkan guest work queue stalls, so North Yankton logs show acquire/label vs draw traffic instead of only VulkanOrderedGuestAction. * perf(agc): coalesce acquire flushes and batch non-DMA label wakes Flush pending ACQUIRE_MEM invalidation at draw/dispatch/dma/flip boundaries instead of before every packet, and complete release/write-data producers in the same ordered action so load paths enqueue far fewer VulkanOrderedGuestAction items. * perf(gpu): wait for ordered-action fences and keep draining sync On Windows/Linux, block briefly for queue-visibility fences instead of deferring the whole logical queue for the tick. Prefer ordered sync/flip heads under backlog pressure, and keep macOS non-blocking defer behavior. * perf(gpu): raise sync-item ceiling above payload guest-work cap Apply SHARPEMU_PENDING_GUEST_WORK_ITEMS mainly to compute/draw/image payload work, and allow a higher SHARPEMU_PENDING_GUEST_SYNC_ITEMS ceiling for zero-payload ordered actions and flip markers. Keep the byte budget as the RAM safety valve. * fix(gta): stub Voice ports and implement sceKernelCheckReachability Resolve North Yankton-path Voice Create/Delete/Connect/Disconnect/End NIDs and EnumerationThread reachability checks so leftover unresolved imports are not on the critical path. * diag(gta): arm flip/present/wait probes after North Audio Rate-limited load_progress TRACE for flip submit, ordered flip enqueue, present taken/not-taken, and GPU wait backlog so North Yankton freezes can be classified without full AGC tracing. * fix(ampr): restore sequential offset=-1 reads for streamer packs Re-wire PakDirectoryTracker into sceAmprAprCommandBufferReadFile (dropped in #216) so RAGE sequential pack reads no longer fail while the North Yankton UI keeps flipping. Also rate-limit CheckReachability miss paths for EnumerationThread diagnosis. * fix(hle/videoout): Windows GuestImage opt-in and keep GTA intro without sync Default the tracker off on Windows to avoid VirtualProtect thrash, gate AGC texel-copy skips on Enabled so guest Bink planes keep shipping pixels, and drain CPU-written images on the present thread when sync is opted in. * fix(videoout): probe guest content when tracker off so UI can skip copies Restores upload-known/texture-cache skips for Dead Cells menus, and uses a sparse guest-memory fingerprint when GuestImageWriteTracker is disabled so CPU-updated Bink planes still force texel copies for GTA intro. * fix(audio): keep 128KiB host queue AudioOut2-only Restore the default 32 KiB (~171 ms) PCM bed for classic AudioOut so titles like Dreaming Sarah stay in sync; only AudioOut2 opens the deeper queue needed for bursty FMOD Push on GTA. --------- Co-authored-by: samto6 <123419830+samto6@users.noreply.github.com>
264 lines
8.0 KiB
C#
264 lines
8.0 KiB
C#
// Copyright (C) 2026 SharpEmu Emulator Project
|
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace SharpEmu.HLE.Host.Posix;
|
|
|
|
/// <summary>
|
|
/// AudioQueue-based playback for macOS. Buffers are enqueued as stereo PCM16
|
|
/// and returned by the queue's internal thread through the output callback;
|
|
/// Submit applies the same 32KB backpressure the WinMM backend uses so guest
|
|
/// pacing works identically.
|
|
/// </summary>
|
|
internal sealed unsafe class PosixCoreAudioStream : IHostAudioStream
|
|
{
|
|
private const uint FormatLinearPcm = 0x6C70636D; // 'lpcm'
|
|
private const uint FlagIsSignedInteger = 0x4;
|
|
private const uint FlagIsPacked = 0x8;
|
|
|
|
private readonly int _maximumQueuedPcmBytes;
|
|
private readonly object _gate = new();
|
|
private readonly AutoResetEvent _completion = new(false);
|
|
private readonly Queue<nint> _freeBuffers = new();
|
|
private GCHandle _selfHandle;
|
|
private nint _queue;
|
|
private int _queuedPcmBytes;
|
|
private bool _started;
|
|
private bool _disposed;
|
|
|
|
public PosixCoreAudioStream(uint sampleRate, int maxQueuedPcmBytes = 32 * 1024)
|
|
{
|
|
if (!OperatingSystem.IsMacOS())
|
|
{
|
|
throw new PlatformNotSupportedException("CoreAudio is only available on macOS.");
|
|
}
|
|
|
|
_maximumQueuedPcmBytes = Math.Max(maxQueuedPcmBytes, 4 * 1024);
|
|
|
|
var format = new AudioStreamBasicDescription
|
|
{
|
|
SampleRate = sampleRate,
|
|
FormatId = FormatLinearPcm,
|
|
FormatFlags = FlagIsSignedInteger | FlagIsPacked,
|
|
BytesPerPacket = 4,
|
|
FramesPerPacket = 1,
|
|
BytesPerFrame = 4,
|
|
ChannelsPerFrame = 2,
|
|
BitsPerChannel = 16,
|
|
};
|
|
|
|
_selfHandle = GCHandle.Alloc(this);
|
|
var status = AudioQueueNewOutput(
|
|
&format,
|
|
&OutputCallback,
|
|
GCHandle.ToIntPtr(_selfHandle),
|
|
0,
|
|
0,
|
|
0,
|
|
out _queue);
|
|
if (status != 0)
|
|
{
|
|
_selfHandle.Free();
|
|
throw new InvalidOperationException($"AudioQueueNewOutput failed with OSStatus {status}.");
|
|
}
|
|
}
|
|
|
|
public bool Submit(ReadOnlySpan<byte> stereoPcm16)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_disposed || _queue == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var outputLength = stereoPcm16.Length;
|
|
while (_queuedPcmBytes != 0 &&
|
|
_queuedPcmBytes + outputLength > _maximumQueuedPcmBytes)
|
|
{
|
|
Monitor.Exit(_gate);
|
|
try
|
|
{
|
|
// Dispose can free the event while this thread waits
|
|
// outside the gate; treat that like a timed-out wait.
|
|
if (!_completion.WaitOne(TimeSpan.FromSeconds(1)))
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
catch (ObjectDisposedException)
|
|
{
|
|
return false;
|
|
}
|
|
finally
|
|
{
|
|
Monitor.Enter(_gate);
|
|
}
|
|
|
|
if (_disposed)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
if (!TryTakeBuffer(outputLength, out var buffer))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var audioData = ((AudioQueueBuffer*)buffer)->AudioData;
|
|
stereoPcm16.CopyTo(new Span<byte>(audioData, outputLength));
|
|
|
|
((AudioQueueBuffer*)buffer)->AudioDataByteSize = (uint)outputLength;
|
|
if (AudioQueueEnqueueBuffer(_queue, buffer, 0, 0) != 0)
|
|
{
|
|
_freeBuffers.Enqueue(buffer);
|
|
return false;
|
|
}
|
|
|
|
_queuedPcmBytes += outputLength;
|
|
if (!_started)
|
|
{
|
|
if (AudioQueueStart(_queue, 0) != 0)
|
|
{
|
|
// A queue that never starts never drains, so later
|
|
// submits would block on backpressure until their
|
|
// timeout. Tear the queue down and fail fast instead.
|
|
_ = AudioQueueDispose(_queue, true);
|
|
_queue = 0;
|
|
_queuedPcmBytes = 0;
|
|
_freeBuffers.Clear();
|
|
return false;
|
|
}
|
|
|
|
_started = true;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_disposed = true;
|
|
if (_queue != 0)
|
|
{
|
|
// Synchronous dispose stops the queue, frees its buffers, and
|
|
// guarantees no further callbacks reference this instance.
|
|
_ = AudioQueueDispose(_queue, true);
|
|
_queue = 0;
|
|
}
|
|
|
|
_freeBuffers.Clear();
|
|
// Wake any submitter waiting on backpressure before the event
|
|
// goes away; a late waiter observes ObjectDisposedException and
|
|
// bails out in Submit.
|
|
_completion.Set();
|
|
_completion.Dispose();
|
|
if (_selfHandle.IsAllocated)
|
|
{
|
|
_selfHandle.Free();
|
|
}
|
|
}
|
|
}
|
|
|
|
private bool TryTakeBuffer(int length, out nint buffer)
|
|
{
|
|
while (_freeBuffers.TryDequeue(out buffer))
|
|
{
|
|
if (((AudioQueueBuffer*)buffer)->AudioDataBytesCapacity >= (uint)length)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
_ = AudioQueueFreeBuffer(_queue, buffer);
|
|
}
|
|
|
|
return AudioQueueAllocateBuffer(_queue, (uint)length, out buffer) == 0;
|
|
}
|
|
|
|
[UnmanagedCallersOnly]
|
|
private static void OutputCallback(nint userData, nint queue, nint buffer)
|
|
{
|
|
if (GCHandle.FromIntPtr(userData).Target is not PosixCoreAudioStream port)
|
|
{
|
|
return;
|
|
}
|
|
|
|
lock (port._gate)
|
|
{
|
|
if (port._disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
port._queuedPcmBytes -= checked((int)((AudioQueueBuffer*)buffer)->AudioDataByteSize);
|
|
port._freeBuffers.Enqueue(buffer);
|
|
}
|
|
|
|
port._completion.Set();
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct AudioStreamBasicDescription
|
|
{
|
|
public double SampleRate;
|
|
public uint FormatId;
|
|
public uint FormatFlags;
|
|
public uint BytesPerPacket;
|
|
public uint FramesPerPacket;
|
|
public uint BytesPerFrame;
|
|
public uint ChannelsPerFrame;
|
|
public uint BitsPerChannel;
|
|
public uint Reserved;
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct AudioQueueBuffer
|
|
{
|
|
public uint AudioDataBytesCapacity;
|
|
public void* AudioData;
|
|
public uint AudioDataByteSize;
|
|
public nint UserData;
|
|
public uint PacketDescriptionCapacity;
|
|
public nint PacketDescriptions;
|
|
public uint PacketDescriptionCount;
|
|
}
|
|
|
|
private const string AudioToolbox =
|
|
"/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox";
|
|
|
|
[DllImport(AudioToolbox)]
|
|
private static extern int AudioQueueNewOutput(
|
|
AudioStreamBasicDescription* format,
|
|
delegate* unmanaged<nint, nint, nint, void> callback,
|
|
nint userData,
|
|
nint callbackRunLoop,
|
|
nint runLoopMode,
|
|
uint flags,
|
|
out nint queue);
|
|
|
|
[DllImport(AudioToolbox)]
|
|
private static extern int AudioQueueAllocateBuffer(nint queue, uint bufferByteSize, out nint buffer);
|
|
|
|
[DllImport(AudioToolbox)]
|
|
private static extern int AudioQueueFreeBuffer(nint queue, nint buffer);
|
|
|
|
[DllImport(AudioToolbox)]
|
|
private static extern int AudioQueueEnqueueBuffer(nint queue, nint buffer, uint packetDescriptionCount, nint packetDescriptions);
|
|
|
|
[DllImport(AudioToolbox)]
|
|
private static extern int AudioQueueStart(nint queue, nint startTime);
|
|
|
|
[DllImport(AudioToolbox)]
|
|
private static extern int AudioQueueDispose(nint queue, [MarshalAs(UnmanagedType.I1)] bool immediate);
|
|
}
|