Compare commits

..

1 Commits

Author SHA1 Message Date
ParantezTech da36a45bf3 [GUI] few stability patches for GUI 2026-08-01 14:56:19 +03:00
73 changed files with 411 additions and 7549 deletions
+1 -3
View File
@@ -42,6 +42,4 @@ ehthumbs.db
.vs/
.idea/
.vscode/
clean_test/
.debug/
.vscode/
+1 -1
View File
@@ -9,7 +9,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<SharpEmuVersion>0.0.3-release.3</SharpEmuVersion>
<SharpEmuVersion>0.0.3-hotfix-2</SharpEmuVersion>
<Version>$(SharpEmuVersion)</Version>
<RepoRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)'))</RepoRoot>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 656 KiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

+15 -19
View File
@@ -47,28 +47,24 @@ built against `ffmpeg-core` specifically.
## Supplying the FFmpeg libraries
Both `dotnet build` and `dotnet publish` fetch a prebuilt release of
`github.com/sharpemu/ffmpeg-core` (the tag is pinned in
`SharpEmu.CLI.csproj`'s `FfmpegRuntimeTag`, matched to the `FFmpeg.AutoGen`
package version in `Directory.Packages.props` -- both need to agree on the
same FFmpeg ABI) and copy its dynamically linked libraries into a `plugins`
folder next to the resulting executable (`artifacts/bin/...` for build,
`artifacts/publish/...` for publish). No C toolchain is required to build
SharpEmu; both just download a zip once (cached under
`$(BaseIntermediateOutputPath)ffmpeg-runtime/`, so later builds/publishes
reuse it instead of re-fetching). `plugins` is a loose, unpacked folder
rather than something embedded in the single-file bundle, so the OS loader
can resolve the libraries' own inter-dependencies (`avcodec` depends on
`avutil`, etc.) itself.
`dotnet publish` fetches a prebuilt release of `github.com/sharpemu/ffmpeg-core`
(the tag is pinned in `SharpEmu.CLI.csproj`'s `FfmpegRuntimeTag`, matched to
the `FFmpeg.AutoGen` package version in `Directory.Packages.props` -- both
need to agree on the same FFmpeg ABI) and copies its dynamically linked
libraries into a `plugins` folder next to the published executable. No C
toolchain is required to build SharpEmu; publishing just downloads a zip.
`plugins` is a loose, unpacked folder rather than something embedded in the
single-file bundle, so the OS loader can resolve the libraries' own
inter-dependencies (`avcodec` depends on `avutil`, etc.) itself.
A plain `dotnet build`/`dotnet publish` with no `-r` still works: it defaults
to the host machine's own RID (see `Directory.Build.props`), so it fetches
the matching `ffmpeg-core` archive and populates `plugins` without any extra
flags. Passing an explicit `-r <rid>` (e.g. to cross-publish `linux-x64` from
A plain `dotnet publish` with no `-r` still works: it defaults to the host
machine's own RID (see `Directory.Build.props`), so it fetches the matching
`ffmpeg-core` archive and populates `plugins` without any extra flags.
Passing an explicit `-r <rid>` (e.g. to cross-publish `linux-x64` from
Windows) still overrides that default normally.
To use a different set of FFmpeg libraries, drop them into the build or
published `plugins` folder yourself (matching FFmpeg's own file-naming and versioning
To use a different set of FFmpeg libraries, drop them into the published
`plugins` folder yourself (matching FFmpeg's own file-naming and versioning
conventions, e.g. `avformat-61.dll` / `libavformat.so.61` / matching
`.dylib`) -- `FfmpegNativeBinkFrameSource` points `ffmpeg.RootPath` at that
folder and does not otherwise care where the files came from.
-2
View File
@@ -48,8 +48,6 @@ internal static partial class Program
{
ConfigureManagedPluginResolution();
SharpEmu.Libs.VideoOut.RenderDocCapture.Initialize();
try
{
return Run(args);
+1 -20
View File
@@ -130,7 +130,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
</PropertyGroup>
<Target Name="FetchFfmpegRuntime"
BeforeTargets="Publish;Build"
BeforeTargets="Publish"
Condition="'$(RuntimeIdentifier)' != '' And '$(FfmpegRuntimePackage)' != ''">
<DownloadFile
SourceUrl="https://github.com/sharpemu/ffmpeg-core/releases/download/$(FfmpegRuntimeTag)/$(FfmpegRuntimePackage)"
@@ -161,23 +161,4 @@ SPDX-License-Identifier: GPL-2.0-or-later
SkipUnchangedFiles="true" />
</Target>
<!-- Mirrors PublishFfmpegRuntime for plain `dotnet build`: devs running
straight out of the build output directory (no publish step) still
need the FFmpeg plugins present, otherwise AvPlayer/Bink video probing
throws NotSupportedException the first time a guest opens a movie. -->
<Target Name="BuildFfmpegRuntime"
AfterTargets="Build"
DependsOnTargets="FetchFfmpegRuntime"
Condition="'$(RuntimeIdentifier)' != '' And '$(FfmpegRuntimePackage)' != ''">
<ItemGroup>
<_FfmpegRuntimeFiles Condition="$(RuntimeIdentifier.StartsWith('win'))"
Include="$(FfmpegRuntimeExtractDir)/bin/*.dll" />
<_FfmpegRuntimeFiles Condition="!$(RuntimeIdentifier.StartsWith('win'))"
Include="$(FfmpegRuntimeExtractDir)/lib/*.so;$(FfmpegRuntimeExtractDir)/lib/*.so.*;$(FfmpegRuntimeExtractDir)/lib/*.dylib" />
</ItemGroup>
<Copy SourceFiles="@(_FfmpegRuntimeFiles)"
DestinationFolder="$(OutDir)$(NativeLibraryFolderName)"
SkipUnchangedFiles="true" />
</Target>
</Project>
@@ -1453,7 +1453,6 @@ public sealed partial class DirectExecutionBackend
}
TryCommitRange(pageBase + 4096, 4096uL, commitProtect);
RescanTlsPatternsIfExecutable(committedBase, committedSize + 4096uL, commitProtect);
if (traceLazyCommit)
{
Console.Error.WriteLine($"[LOADER][TRACE] lazy-reserve-commit#{traceIndex}: addr=0x{committedBase:X16} size=0x{committedSize:X16} access={accessType} protect=0x{commitProtect:X8}");
@@ -1513,7 +1512,6 @@ public sealed partial class DirectExecutionBackend
}
TryCommitRange(pageBase + 4096, 4096uL, commitProtect);
RescanTlsPatternsIfExecutable(committedBase, committedSize + 4096uL, commitProtect);
if (traceLazyCommit)
{
Console.Error.WriteLine($"[LOADER][TRACE] lazy-commit#{traceIndex}: addr=0x{committedBase:X16} size=0x{committedSize:X16} access={accessType} protect=0x{commitProtect:X8}");
@@ -1615,18 +1613,6 @@ public sealed partial class DirectExecutionBackend
}
}
// Re-scans a just-committed window for FS:[0] TLS loads; skips non-executable commits.
private unsafe void RescanTlsPatternsIfExecutable(ulong committedBase, ulong committedSize, uint commitProtect)
{
const uint executableProtectionMask = PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
if ((commitProtect & executableProtectionMask) == 0 || committedSize == 0)
{
return;
}
PatchTlsPatternsInRange(committedBase, committedBase + committedSize, announce: false);
}
private static bool ShouldTraceLazyCommit(int traceIndex)
{
if (string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_LAZY_COMMIT"), "1", StringComparison.Ordinal))
@@ -3145,33 +3145,8 @@ public sealed unsafe partial class DirectExecutionBackend : INativeCpuBackend, I
// Large Gen5 executables can keep valid code well past the first 32 MiB.
// Astro Bot, for example, has an FS:[0] TLS load near +0x70A0000.
const ulong MaxScanBytes = 134217728uL;
// _entryPoint can be a separate bootstrap allocation, not the main module —
// always also scan the standard PS5/PS4 image base.
const ulong Ps5MainImageBase = 0x0000000800000000UL;
const ulong Ps4MainImageBase = 0x0000000000400000UL;
ulong scanStart = _entryPoint;
if (VirtualQuery((void*)_entryPoint, out var entryRegion, (nuint)sizeof(MEMORY_BASIC_INFORMATION64)) != 0 &&
entryRegion.AllocationBase != 0 &&
entryRegion.AllocationBase <= _entryPoint)
{
scanStart = entryRegion.AllocationBase;
}
PatchTlsPatternsInRange(scanStart, scanStart + MaxScanBytes, announce: true);
// Scan both windows unconditionally; overlap is safe, patched bytes just stop matching.
var mainImageBase = _entryPoint >= Ps5MainImageBase ? Ps5MainImageBase : Ps4MainImageBase;
if (mainImageBase < scanStart)
{
PatchTlsPatternsInRange(mainImageBase, mainImageBase + MaxScanBytes, announce: false);
}
}
private unsafe void PatchTlsPatternsInRange(ulong rangeStart, ulong rangeEnd, bool announce)
{
ulong num = rangeStart;
ulong num2 = rangeEnd;
ulong num = _entryPoint;
ulong num2 = num + MaxScanBytes;
int num3 = 0;
int num4 = 0;
int num9 = 0;
@@ -3220,11 +3195,7 @@ public sealed unsafe partial class DirectExecutionBackend : INativeCpuBackend, I
}
num = num6 > num ? num6 : num + 4096uL;
}
if (announce || num3 + num4 + num9 + sse4aPatchCount > 0)
{
Console.Error.WriteLine($"[LOADER][INFO] Patched {num3} TLS loads, {num9} TLS stores, {num4} stack-canary accesses, {sse4aPatchCount} SSE4a EXTRQ blends" +
(announce ? string.Empty : $" (lazy-commit rescan 0x{rangeStart:X16}-0x{rangeEnd:X16})"));
}
Console.Error.WriteLine($"[LOADER][INFO] Patched {num3} TLS loads, {num9} TLS stores, {num4} stack-canary accesses, {sse4aPatchCount} SSE4a EXTRQ blends");
}
private unsafe bool TryPatchSse4aExtrqBlend(nint address, byte* source)
+21 -287
View File
@@ -26,7 +26,6 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
private long _mappingGeneration;
private const ulong PageSize = 0x1000;
private const ulong HostAllocationGranularity = 0x10000;
private const ulong GuestAllocationArenaAddress = 0x00006000_0000_0000;
private const ulong GuestAllocationArenaSize = 0x0100_0000;
private const ulong GuestAllocationArenaStartOffset = PageSize;
@@ -118,9 +117,6 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
private const uint PAGE_READONLY = 0x02;
private readonly IHostMemory _hostMemory;
private readonly object _fixedAllocationGate = new();
private readonly HashSet<ulong> _fixedGranuleReservationBases = new();
private ulong _guestAllocationArenaBase;
private readonly SortedDictionary<ulong, ulong> _guestAllocationFreeRanges = new();
private readonly Dictionary<ulong, (ulong Offset, ulong Size)> _guestAllocations = new();
@@ -251,12 +247,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
// reserve-only + lazy commit only when a huge non-exec commit fails —
// that is the Poppy / large-reservation path #608 was aiming for.
var reservedOnly = false;
var result = TryAllocateFixedThroughGranules(desiredAddress, alignedSize, hostProtection, traceReject: false);
if (result == 0)
{
result = _hostMemory.Allocate(desiredAddress, alignedSize, hostProtection);
}
var result = _hostMemory.Allocate(desiredAddress, alignedSize, hostProtection);
if (result == 0 && allowLazyReserve)
{
result = _hostMemory.Reserve(desiredAddress, alignedSize, HostPageProtection.ReadWrite);
@@ -338,16 +329,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
// Prefer a full commit. Only fall back to reserve-only when a large
// non-executable commit cannot be satisfied (see TryAllocateAtExact).
ulong result = 0;
if (desiredAddress != 0)
{
result = TryAllocateFixedThroughGranules(desiredAddress, alignedSize, hostProtection, traceReject: false);
}
if (result == 0)
{
result = _hostMemory.Allocate(desiredAddress, alignedSize, hostProtection);
}
ulong result = _hostMemory.Allocate(desiredAddress, alignedSize, hostProtection);
if (result == 0)
{
@@ -454,183 +436,6 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
return $"fail:{primeBytes:X}";
}
private ulong TryAllocateFixedThroughGranules(
ulong desiredAddress,
ulong alignedSize,
HostPageProtection hostProtection,
bool traceReject = true)
{
if (!OperatingSystem.IsWindows() || desiredAddress == 0 || alignedSize == 0)
{
return 0;
}
var requestStart = AlignDown(desiredAddress, PageSize);
ulong requestEnd;
ulong granuleEnd;
try
{
requestEnd = AlignUp(desiredAddress + alignedSize, PageSize);
granuleEnd = AlignUp(requestEnd, HostAllocationGranularity);
}
catch (OverflowException)
{
return 0;
}
var granuleStart = AlignDown(requestStart, HostAllocationGranularity);
lock (_fixedAllocationGate)
{
var newReservations = new List<ulong>();
void Reject(ulong segmentAddress, string reason)
{
if (traceReject)
{
Log.Warn(
$"fixed-alloc reject: want=0x{desiredAddress:X16}+0x{alignedSize:X} segment=0x{segmentAddress:X16} {reason}");
}
foreach (var reservationBase in newReservations)
{
_hostMemory.Free(reservationBase);
_fixedGranuleReservationBases.Remove(reservationBase);
}
}
var cursor = granuleStart;
while (cursor < granuleEnd)
{
if (!_hostMemory.Query(cursor, out var info))
{
Reject(cursor, "query-failed");
return 0;
}
var segmentEnd = info.RegionSize > ulong.MaxValue - info.BaseAddress
? ulong.MaxValue
: info.BaseAddress + info.RegionSize;
segmentEnd = Math.Min(segmentEnd, granuleEnd);
if (segmentEnd <= cursor)
{
Reject(cursor, "query-no-progress");
return 0;
}
if (info.State == HostRegionState.Free)
{
var alignedReserveBase = AlignUp(cursor, HostAllocationGranularity);
var unreservableEnd = Math.Min(segmentEnd, alignedReserveBase);
if (unreservableEnd > cursor && cursor < requestEnd && unreservableEnd > requestStart)
{
Reject(cursor, $"free-but-unreservable head (granule base 0x{AlignDown(cursor, HostAllocationGranularity):X16} owned elsewhere)");
return 0;
}
if (alignedReserveBase < segmentEnd)
{
var reserved = _hostMemory.Reserve(alignedReserveBase, segmentEnd - alignedReserveBase, HostPageProtection.ReadWrite);
if (reserved != alignedReserveBase)
{
if (reserved != 0)
{
_hostMemory.Free(reserved);
}
Reject(alignedReserveBase, "reserve-failed");
return 0;
}
_fixedGranuleReservationBases.Add(alignedReserveBase);
newReservations.Add(alignedReserveBase);
}
}
else
{
var trusted = _fixedGranuleReservationBases.Contains(info.AllocationBase) ||
IsTrackedRegionBase(info.AllocationBase);
if (!trusted && cursor < requestEnd && segmentEnd > requestStart)
{
Reject(cursor, $"foreign {info.State} allocBase=0x{info.AllocationBase:X16} prot=0x{info.RawProtection:X}");
return 0;
}
}
cursor = segmentEnd;
}
var commitCursor = requestStart;
while (commitCursor < requestEnd)
{
if (!_hostMemory.Query(commitCursor, out var info))
{
Reject(commitCursor, "commit-query-failed");
return 0;
}
var segmentEnd = info.RegionSize > ulong.MaxValue - info.BaseAddress
? ulong.MaxValue
: info.BaseAddress + info.RegionSize;
segmentEnd = Math.Min(segmentEnd, requestEnd);
if (segmentEnd <= commitCursor)
{
Reject(commitCursor, "commit-no-progress");
return 0;
}
if (info.State != HostRegionState.Committed &&
!_hostMemory.Commit(commitCursor, segmentEnd - commitCursor, hostProtection))
{
Reject(commitCursor, "commit-failed");
return 0;
}
commitCursor = segmentEnd;
}
if (newReservations.Count == 0)
{
TraceVmem($"Fixed alloc committed into existing granule reservations: 0x{desiredAddress:X16}+0x{alignedSize:X}");
}
return desiredAddress;
}
}
private bool IsTrackedRegionBase(ulong allocationBase)
{
_gate.EnterReadLock();
try
{
var low = 0;
var high = _regions.Count - 1;
while (low <= high)
{
var middle = low + ((high - low) >> 1);
var address = _regions[middle].VirtualAddress;
if (address == allocationBase)
{
return true;
}
if (address < allocationBase)
{
low = middle + 1;
}
else
{
high = middle - 1;
}
}
return false;
}
finally
{
_gate.ExitReadLock();
}
}
public bool TryBackFixedRange(ulong address, ulong size, bool executable)
{
if (size == 0)
@@ -658,7 +463,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
// MemoryRegions are inserted only once every gap in the range has been
// backed. If any gap fails to back, every earlier host allocation is freed
// and no region is inserted, so the address space is left untouched.
var stagedAllocations = new List<(ulong Address, ulong Size, bool GranuleTracked)>();
var stagedAllocations = new List<(ulong Address, ulong Size)>();
var cursor = start;
while (cursor < end)
@@ -677,21 +482,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
goto Rollback;
}
var needsGranuleAwareBacking = OperatingSystem.IsWindows() &&
(info.State == HostRegionState.Free || info.State == HostRegionState.Reserved);
if (needsGranuleAwareBacking)
{
var runSize = runEnd - cursor;
if (TryAllocateFixedThroughGranules(cursor, runSize, hostProtection, traceReject: false) != cursor)
{
goto Rollback;
}
stagedAllocations.Add((cursor, runSize, true));
TraceVmem($"Backed fixed range gap: 0x{cursor:X16} - 0x{runEnd:X16} ({runSize} bytes)");
}
else if (info.State == HostRegionState.Free)
if (info.State == HostRegionState.Free)
{
var runSize = runEnd - cursor;
var allocated = _hostMemory.Allocate(cursor, runSize, hostProtection);
@@ -705,11 +496,10 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
goto Rollback;
}
stagedAllocations.Add((cursor, runSize, false));
stagedAllocations.Add((cursor, runSize));
TraceVmem($"Backed fixed range gap: 0x{cursor:X16} - 0x{runEnd:X16} ({runSize} bytes)");
}
cursor = runEnd;
}
@@ -723,7 +513,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
_gate.EnterWriteLock();
try
{
foreach (var (gapAddress, gapSize, _) in stagedAllocations)
foreach (var (gapAddress, gapSize) in stagedAllocations)
{
InsertRegionSorted(new MemoryRegion
{
@@ -743,12 +533,9 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
return true;
Rollback:
foreach (var (gapAddress, _, granuleTracked) in stagedAllocations)
foreach (var (gapAddress, _) in stagedAllocations)
{
if (!granuleTracked)
{
_hostMemory.Free(gapAddress);
}
_hostMemory.Free(gapAddress);
}
return false;
@@ -1004,41 +791,24 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
{
lock (_guestAllocationGate)
{
lock (_fixedAllocationGate)
_gate.EnterWriteLock();
try
{
_gate.EnterWriteLock();
try
foreach (var region in _regions)
{
var freedBases = new HashSet<ulong>();
foreach (var region in _regions)
{
if (freedBases.Add(region.VirtualAddress))
{
_hostMemory.Free(region.VirtualAddress);
}
}
foreach (var reservationBase in _fixedGranuleReservationBases)
{
if (freedBases.Add(reservationBase))
{
_hostMemory.Free(reservationBase);
}
}
_fixedGranuleReservationBases.Clear();
_regions.Clear();
_pageProtections.Clear();
lock (_allocationSearchHintGate)
{
_allocationSearchHints.Clear();
}
Interlocked.Increment(ref _mappingGeneration);
_hostMemory.Free(region.VirtualAddress);
}
finally
_regions.Clear();
_pageProtections.Clear();
lock (_allocationSearchHintGate)
{
_gate.ExitWriteLock();
_allocationSearchHints.Clear();
}
Interlocked.Increment(ref _mappingGeneration);
}
finally
{
_gate.ExitWriteLock();
}
_guestAllocationArenaBase = 0;
@@ -1632,42 +1402,6 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
}
}
if (OperatingSystem.IsWindows() && !region.IsReservedOnly)
{
var previous = low > 0 ? _regions[low - 1] : null;
var next = low < _regions.Count ? _regions[low] : null;
var mergePrevious = previous is not null &&
!previous.IsReservedOnly &&
previous.IsExecutable == region.IsExecutable &&
previous.Protection == region.Protection &&
previous.VirtualAddress + previous.Size == region.VirtualAddress;
var mergeNext = next is not null &&
!next.IsReservedOnly &&
next.IsExecutable == region.IsExecutable &&
next.Protection == region.Protection &&
region.VirtualAddress + region.Size == next.VirtualAddress;
if (mergePrevious && mergeNext)
{
previous!.Size += region.Size + next!.Size;
_regions.RemoveAt(low);
return;
}
if (mergePrevious)
{
previous!.Size += region.Size;
return;
}
if (mergeNext)
{
next!.VirtualAddress = region.VirtualAddress;
next.Size += region.Size;
return;
}
}
_regions.Insert(low, region);
}
-4
View File
@@ -145,11 +145,7 @@
"Options.Env.LogDirectMemory.Desc": "تسجيل تخصيصات الذاكرة المباشرة وإخفاقاتها في وحدة التحكم.\nاستخدمه عندما تنهار لعبة أو تُغلق أثناء الإقلاع.",
"Options.Env.LogIo.Desc": "تسجيل فتح الملفات وقراءتها وحلّ المسارات في وحدة التحكم.\nاستخدمه عندما لا تجد لعبة ملفات بياناتها أثناء الإقلاع.",
"Options.Env.LogNp.Desc": "تسجيل نداءات مكتبة NP (شبكة PlayStation) في وحدة التحكم.",
"Options.Env.Group.Debug": "تصحيح الأخطاء",
"Options.Env.Group.General": "عام",
"Options.Env.RenderDoc.Desc": "يحمّل واجهة RenderDoc داخل التطبيق حتى يمكن التقاط الإطارات من داخل المحاكي.\nاضغط F10 أثناء تشغيل اللعبة لالتقاط إطار واحد؛ تُحفظ اللقطات في user/logs/capture_logs/<TITLE_ID>.\nيتطلب تثبيت RenderDoc. يبطئ وحدة معالجة الرسوميات ويسبب تعليق بعض الألعاب، لذا اتركه معطلاً ما لم تكن تصحح الأخطاء.",
"Options.Env.GuestImageCpuSync.Desc": "إعادة رفع أسطح الضيف التي تعيد كتابتها شيفرة المعالج الخاصة باللعبة.\nاتركه مغلقًا عادة. شغّله للألعاب التي لا تصل أسطحها المرسومة بالمعالج إلى الشاشة.\nيكلّف أداءً ويسبب مشاكل في بعض الألعاب مثل GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "تسليم مقدّمات المخازن المؤقتة لأوامر GPU حتى عندما لا تلتقطها قائمة الانتظار المستهدفة أبدًا.\nاتركه مغلقًا عادة. شغّله للألعاب التي تتجمد أثناء انتظار حاجز GPU لا يُشار إليه أبدًا.",
"Common.Save": "حفظ",
"Common.Cancel": "إلغاء",
"Options.About": "حول",
-4
View File
@@ -39,11 +39,7 @@
"Options.Env.DumpSpirv.Desc": "Extrai os shaders AGC e suas traduções SPIR-V para a pasta shader-dumps.\nUse ao reportar bugs de shader ou renderização.",
"Options.Env.LogDirectMemory.Desc": "Registra alocações de memória direta e falhas no console.\nUse quando um jogo aborta ou fecha durante a inicialização (boot).",
"Options.Env.LogNp.Desc": "Registra chamadas da biblioteca NP (PlayStation Network) no console.",
"Options.Env.Group.Debug": "Depuração",
"Options.Env.Group.General": "Geral",
"Options.Env.RenderDoc.Desc": "Carrega a API in-application do RenderDoc para capturar frames de dentro do emulador.\nPressione F10 enquanto o jogo roda para capturar um frame; as capturas vão para user/logs/capture_logs/<TITLE_ID>.\nExige o RenderDoc instalado. Deixa a GPU mais lenta e trava alguns títulos, então mantenha desativado a menos que esteja depurando.",
"Options.Env.GuestImageCpuSync.Desc": "Recarrega as superfícies do convidado que o próprio código de CPU do jogo reescreve.\nDeixe desativado normalmente. Ative para títulos cujas superfícies desenhadas pela CPU nunca chegam à tela.\nCusta desempenho e causa regressões em alguns títulos, como GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Entrega os preâmbulos do buffer de comandos da GPU mesmo quando a fila de destino nunca os recolhe.\nDeixe desativado normalmente. Ative para títulos que travam esperando por uma fence de GPU que nunca sinaliza.",
"Options.Section.Emulation": "EMULAÇÃO",
"Options.Section.Logging": "LOGS",
"Options.Section.Launcher": "INICIALIZADOR",
-4
View File
@@ -145,11 +145,7 @@
"Options.Env.LogDirectMemory.Desc": "Direkte Speicherzuweisungen und Fehler in der Konsole protokollieren.\nVerwenden, wenn ein Spiel beim Start abbricht oder sich beendet.",
"Options.Env.LogIo.Desc": "Datei-Öffnen, -Lesen und Pfadauflösung in der Konsole protokollieren.\nVerwenden, wenn ein Spiel beim Start seine Datendateien nicht findet.",
"Options.Env.LogNp.Desc": "NP-Bibliotheksaufrufe (PlayStation Network) in der Konsole protokollieren.",
"Options.Env.Group.Debug": "Debug",
"Options.Env.Group.General": "Allgemein",
"Options.Env.RenderDoc.Desc": "Lädt die RenderDoc-In-Application-API, damit Frames aus dem Emulator heraus aufgezeichnet werden können.\nDrücke F10 während das Spiel läuft, um ein Frame aufzuzeichnen; Aufzeichnungen landen in user/logs/capture_logs/<TITLE_ID>.\nErfordert eine RenderDoc-Installation. Verlangsamt die GPU und lässt manche Titel hängen, lass es also aus, wenn du nicht debuggst.",
"Options.Env.GuestImageCpuSync.Desc": "Gast-Oberflächen neu hochladen, die der eigene CPU-Code des Spiels überschreibt.\nNormalerweise aus lassen. Für Titel aktivieren, deren CPU-gezeichnete Oberflächen nie auf dem Bildschirm erscheinen.\nKostet Leistung und verursacht bei einigen Titeln wie GTA V Regressionen.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Liefert GPU-Befehlspuffer-Präambeln auch dann aus, wenn die Zielwarteschlange sie nie abholt.\nNormalerweise aus lassen. Für Titel aktivieren, die beim Warten auf einen GPU-Fence hängen bleiben, der nie signalisiert.",
"Common.Save": "Speichern",
"Common.Cancel": "Abbrechen",
"Options.About": "Über",
-4
View File
@@ -145,11 +145,7 @@
"Options.Env.LogDirectMemory.Desc": "Log direkte hukommelsestildelinger og fejl til konsollen.\nBrug dette, når et spil afbryder eller lukker under opstart.",
"Options.Env.LogIo.Desc": "Log åbning og læsning af filer samt stiopslag til konsollen.\nBrug dette, når et spil ikke kan finde sine datafiler under opstart.",
"Options.Env.LogNp.Desc": "Log NP-bibliotekskald (PlayStation Network) til konsollen.",
"Options.Env.Group.Debug": "Fejlfinding",
"Options.Env.Group.General": "Generelt",
"Options.Env.RenderDoc.Desc": "Indlæser RenderDocs in-application-API, så frames kan optages inde fra emulatoren.\nTryk på F10 mens spillet kører for at optage ét frame; optagelser havner i user/logs/capture_logs/<TITLE_ID>.\nKræver at RenderDoc er installeret. Gør GPU'en langsommere og får nogle titler til at hænge, så lad den være slået fra, medmindre du fejlfinder.",
"Options.Env.GuestImageCpuSync.Desc": "Genindlæs gæsteoverflader, som spillets egen CPU-kode omskriver.\nLad den være slået fra normalt. Slå til for titler, hvis CPU-tegnede overflader aldrig når skærmen.\nKoster ydeevne og giver regressioner i nogle titler, såsom GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Leverer GPU-kommandobuffer-præambler, selv når målkøen aldrig henter dem.\nLad den være slået fra normalt. Slå til for titler, der hænger og venter på en GPU-fence, der aldrig signalerer.",
"Common.Save": "Gem",
"Common.Cancel": "Annuller",
"Options.About": "Om",
-4
View File
@@ -44,11 +44,7 @@
"Options.Env.LogDirectMemory.Desc": "Log direct memory allocations and failures to the console.\nUse when a game aborts or exits during boot.",
"Options.Env.LogIo.Desc": "Log file open, read, and path-resolve activity to the console.\nUse when a game cannot find its data files during boot.",
"Options.Env.LogNp.Desc": "Log NP (PlayStation Network) library calls to the console.",
"Options.Env.Group.Debug": "Debug",
"Options.Env.Group.General": "General",
"Options.Env.RenderDoc.Desc": "Load the RenderDoc in-application API so frames can be captured from inside the emulator.\nPress F10 while the game runs to capture one frame; captures land in user/logs/capture_logs/<TITLE_ID>.\nRequires RenderDoc to be installed. Slows the GPU down and hangs some titles, so leave it off unless you are debugging.",
"Options.Env.GuestImageCpuSync.Desc": "Re-upload guest surfaces the game's own CPU code rewrites.\nLeave off normally. Turn on for titles whose CPU-drawn surfaces never reach the screen.\nCosts performance and regresses some titles, such as GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Deliver GPU command-buffer preambles even when their target queue never picks them up.\nLeave off normally. Turn on for titles that hang waiting on a GPU fence that never signals.",
"Options.DefaultProfile.Label": "Default profile name",
"Options.DefaultProfile.Desc": "Name used when a game asks for text input. Defaults to Sharp.",
"Options.Section.Emulation": "EMULATION",
-4
View File
@@ -155,11 +155,7 @@
"Options.Env.LogDirectMemory.Desc": "Registrar en la consola las asignaciones de memoria directa y sus fallos.\nÚsalo cuando un juego se aborte o se cierre durante el arranque.",
"Options.Env.LogIo.Desc": "Registrar en la consola la apertura y lectura de archivos y la resolución de rutas.\nÚsalo cuando un juego no encuentre sus archivos de datos durante el arranque.",
"Options.Env.LogNp.Desc": "Registrar en la consola las llamadas a la biblioteca NP (PlayStation Network).",
"Options.Env.Group.Debug": "Depuración",
"Options.Env.Group.General": "General",
"Options.Env.RenderDoc.Desc": "Carga la API in-application de RenderDoc para poder capturar fotogramas desde el emulador.\nPulsa F10 mientras el juego se ejecuta para capturar un fotograma; las capturas se guardan en user/logs/capture_logs/<TITLE_ID>.\nRequiere tener RenderDoc instalado. Ralentiza la GPU y bloquea algunos títulos, así que déjalo desactivado salvo que estés depurando.",
"Options.Env.GuestImageCpuSync.Desc": "Volver a subir las superficies del invitado que reescribe el propio código de CPU del juego.\nDejar desactivado normalmente. Activar en títulos cuyas superficies dibujadas por CPU nunca llegan a la pantalla.\nCuesta rendimiento y causa regresiones en algunos títulos, como GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Entrega los preámbulos del búfer de comandos de la GPU incluso cuando la cola de destino nunca los recoge.\nDejar desactivado normalmente. Activar en títulos que se cuelgan esperando una fence de GPU que nunca se señaliza.",
"Common.Save": "Guardar",
"Common.Cancel": "Cancelar",
"Updater.Auto.Label": "Buscar actualizaciones al iniciar",
-4
View File
@@ -39,11 +39,7 @@
"Options.Env.DumpSpirv.Desc": "Exporter les shaders AGC et leurs traductions SPIR-V dans le dossier shader-dumps.\nÀ utiliser pour signaler des bugs de shader ou de rendu.",
"Options.Env.LogDirectMemory.Desc": "Journaliser les allocations de mémoire directe et les échecs dans la console.\nÀ utiliser quand un jeu plante ou se ferme pendant le démarrage.",
"Options.Env.LogNp.Desc": "Journaliser les appels de la bibliothèque NP (PlayStation Network) dans la console.",
"Options.Env.Group.Debug": "Débogage",
"Options.Env.Group.General": "Général",
"Options.Env.RenderDoc.Desc": "Charge l'API in-application de RenderDoc afin de capturer des images depuis l'émulateur.\nAppuyez sur F10 pendant le jeu pour capturer une image ; les captures sont écrites dans user/logs/capture_logs/<TITLE_ID>.\nNécessite l'installation de RenderDoc. Ralentit le GPU et bloque certains jeux : laissez cette option désactivée sauf en cas de débogage.",
"Options.Env.GuestImageCpuSync.Desc": "Recharger les surfaces invité que le code CPU du jeu réécrit lui-même.\nLaisser désactivé normalement. Activer pour les titres dont les surfaces dessinées par le CPU n'atteignent jamais l'écran.\nCoûte des performances et provoque des régressions sur certains titres, comme GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Soumettre les préambules de tampon de commandes GPU même quand leur file cible ne les récupère jamais.\nLaisser désactivé normalement. Activer pour les titres qui se figent en attendant une fence GPU qui ne se déclenche jamais.",
"Options.Section.Emulation": "ÉMULATION",
"Options.Section.Logging": "JOURNALISATION",
"Options.Section.Launcher": "LANCEUR",
-4
View File
@@ -39,11 +39,7 @@
"Options.Env.DumpSpirv.Desc": "Az AGC-shaderek és azok SPIR-V-fordításainak mentése a shader-dumps mappába.\nHasználd shader- vagy renderelési hibák jelentésekor.",
"Options.Env.LogDirectMemory.Desc": "A közvetlen memóriaallokációk és hibák naplózása a konzolra.\nHasználd, ha egy játék a rendszerindítás során megszakad vagy kilép.",
"Options.Env.LogNp.Desc": "Az NP (PlayStation Network) könyvtárhívásokat naplózza a konzolra.",
"Options.Env.Group.Debug": "Hibakeresés",
"Options.Env.Group.General": "Általános",
"Options.Env.RenderDoc.Desc": "Betölti a RenderDoc alkalmazáson belüli API-ját, így képkockák rögzíthetők az emulátorból.\nNyomd meg az F10-et futó játék közben egy képkocka rögzítéséhez; a felvételek a user/logs/capture_logs/<TITLE_ID> mappába kerülnek.\nTelepített RenderDocot igényel. Lassítja a GPU-t és egyes játékokat lefagyaszt, ezért hagyd kikapcsolva, hacsak nem hibakeresel.",
"Options.Env.GuestImageCpuSync.Desc": "Újratölti azokat a vendégfelületeket, amelyeket a játék saját CPU-kódja ír felül.\nNormál esetben hagyd kikapcsolva. Kapcsold be azoknál a címeknél, amelyek CPU-val rajzolt felületei sosem jutnak ki a képernyőre.\nTeljesítménybe kerül, és egyes címeknél, például a GTA V-nél regressziót okoz.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "GPU parancspuffer-előtagokat is kézbesít, ha a célsor sosem veszi fel őket.\nNormál esetben hagyd kikapcsolva. Kapcsold be azoknál a címeknél, amelyek egy sosem jelző GPU-fence-re várva lefagynak.",
"Options.Section.Emulation": "EMULÁCIÓ",
"Options.Section.Logging": "LOGOLÁS",
"Options.Section.Launcher": "INDITÓ",
-4
View File
@@ -150,11 +150,7 @@
"Options.Env.LogDirectMemory.Desc": "Registra in console le allocazioni di memoria diretta e i relativi errori.\nUsalo quando un gioco si interrompe o si chiude durante l'avvio.",
"Options.Env.LogIo.Desc": "Registra in console l'apertura e la lettura dei file e la risoluzione dei percorsi.\nUsalo quando un gioco non trova i propri file di dati durante l'avvio.",
"Options.Env.LogNp.Desc": "Registra in console le chiamate alla libreria NP (PlayStation Network).",
"Options.Env.Group.Debug": "Debug",
"Options.Env.Group.General": "Generale",
"Options.Env.RenderDoc.Desc": "Carica l'API in-application di RenderDoc per catturare i frame dall'interno dell'emulatore.\nPremi F10 mentre il gioco è in esecuzione per catturare un frame; le catture finiscono in user/logs/capture_logs/<TITLE_ID>.\nRichiede RenderDoc installato. Rallenta la GPU e blocca alcuni titoli, quindi lascialo disattivato se non stai facendo debug.",
"Options.Env.GuestImageCpuSync.Desc": "Ricarica le superfici guest riscritte dal codice CPU del gioco.\nLasciare disattivato normalmente. Attivare per i titoli le cui superfici disegnate dalla CPU non raggiungono mai lo schermo.\nCosta prestazioni e causa regressioni in alcuni titoli, come GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Consegna i preamboli del buffer di comandi GPU anche quando la coda di destinazione non li preleva mai.\nLasciare disattivato normalmente. Attivare per i titoli che si bloccano in attesa di una fence GPU che non segnala mai.",
"Common.Save": "Salva",
"Common.Cancel": "Annulla",
"Options.About": "Informazioni",
-4
View File
@@ -145,11 +145,7 @@
"Options.Env.LogDirectMemory.Desc": "ダイレクトメモリの割り当てと失敗をコンソールに記録します。\nゲームが起動中に中断・終了する場合に使用してください。",
"Options.Env.LogIo.Desc": "ファイルのオープン・読み込み・パス解決の動作をコンソールに記録します。\nゲームが起動中にデータファイルを見つけられない場合に使用してください。",
"Options.Env.LogNp.Desc": "NPPlayStation Network)ライブラリの呼び出しをコンソールに記録します。",
"Options.Env.Group.Debug": "デバッグ",
"Options.Env.Group.General": "一般",
"Options.Env.RenderDoc.Desc": "RenderDoc のアプリ内 API を読み込み、エミュレーター内からフレームをキャプチャできるようにします。\nゲーム実行中に F10 を押すと 1 フレームをキャプチャします。保存先は user/logs/capture_logs/<TITLE_ID> です。\nRenderDoc のインストールが必要です。GPU が遅くなり一部のタイトルはハングするため、デバッグ時以外はオフのままにしてください。",
"Options.Env.GuestImageCpuSync.Desc": "ゲーム自身の CPU コードが書き換えるゲスト表面を再アップロードします。\n通常はオフのままにしてください。CPU で描画した表面が画面に反映されないタイトルで有効にします。\n性能を犠牲にし、GTA V など一部のタイトルでは不具合が生じます。",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "対象キューが受け取らない場合でも GPU コマンドバッファのプリアンブルを配信します。\n通常はオフのままにしてください。決してシグナルされない GPU フェンスを待ってハングするタイトルで有効にします。",
"Common.Save": "保存",
"Common.Cancel": "キャンセル",
"Options.About": "情報",
-4
View File
@@ -145,11 +145,7 @@
"Options.Env.LogDirectMemory.Desc": "다이렉트 메모리 할당과 실패를 콘솔에 기록합니다.\n게임이 부팅 중 중단되거나 종료될 때 사용하세요.",
"Options.Env.LogIo.Desc": "파일 열기, 읽기, 경로 확인 동작을 콘솔에 기록합니다.\n게임이 부팅 중 데이터 파일을 찾지 못할 때 사용하세요.",
"Options.Env.LogNp.Desc": "NP(PlayStation Network) 라이브러리 호출을 콘솔에 기록합니다.",
"Options.Env.Group.Debug": "디버그",
"Options.Env.Group.General": "일반",
"Options.Env.RenderDoc.Desc": "RenderDoc의 인앱 API를 로드하여 에뮬레이터 내부에서 프레임을 캡처할 수 있게 합니다.\n게임 실행 중 F10을 누르면 한 프레임을 캡처하며, 캡처 파일은 user/logs/capture_logs/<TITLE_ID>에 저장됩니다.\nRenderDoc이 설치되어 있어야 합니다. GPU 속도가 느려지고 일부 타이틀은 멈추므로 디버깅할 때가 아니면 꺼 두세요.",
"Options.Env.GuestImageCpuSync.Desc": "게임의 자체 CPU 코드가 다시 쓰는 게스트 표면을 다시 업로드합니다.\n평소에는 꺼 두세요. CPU로 그린 표면이 화면에 나타나지 않는 타이틀에서 켜세요.\n성능을 소모하며 GTA V 등 일부 타이틀에서는 문제가 생깁니다.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "대상 큐가 절대 가져가지 않아도 GPU 명령 버퍼 프리앰블을 전달합니다.\n평소에는 꺼 두세요. 절대 신호를 보내지 않는 GPU 펜스를 기다리며 멈추는 타이틀에서 켜세요.",
"Common.Save": "저장",
"Common.Cancel": "취소",
"Options.About": "정보",
-4
View File
@@ -145,11 +145,7 @@
"Options.Env.LogDirectMemory.Desc": "Log directe geheugentoewijzingen en fouten naar de console.\nGebruik dit wanneer een game tijdens het opstarten afbreekt of afsluit.",
"Options.Env.LogIo.Desc": "Log het openen en lezen van bestanden en het oplossen van paden naar de console.\nGebruik dit wanneer een game zijn databestanden niet kan vinden tijdens het opstarten.",
"Options.Env.LogNp.Desc": "Log NP-bibliotheekaanroepen (PlayStation Network) naar de console.",
"Options.Env.Group.Debug": "Debuggen",
"Options.Env.Group.General": "Algemeen",
"Options.Env.RenderDoc.Desc": "Laadt de RenderDoc in-application-API zodat frames vanuit de emulator kunnen worden vastgelegd.\nDruk op F10 terwijl het spel draait om één frame vast te leggen; opnamen komen in user/logs/capture_logs/<TITLE_ID>.\nVereist een geïnstalleerde RenderDoc. Vertraagt de GPU en laat sommige games vastlopen, dus laat dit uit tenzij je aan het debuggen bent.",
"Options.Env.GuestImageCpuSync.Desc": "Gastoppervlakken opnieuw uploaden die de eigen CPU-code van de game herschrijft.\nNormaal uit laten. Inschakelen voor titels waarvan de door de CPU getekende oppervlakken nooit het scherm bereiken.\nKost prestaties en veroorzaakt regressies in sommige titels, zoals GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Levert GPU-commandobuffer-preambules af, zelfs wanneer de doelwachtrij ze nooit ophaalt.\nNormaal uit laten. Inschakelen voor titels die vasthangen in afwachting van een GPU-fence die nooit signaleert.",
"Common.Save": "Opslaan",
"Common.Cancel": "Annuleren",
"Options.About": "Over",
-4
View File
@@ -39,11 +39,7 @@
"Options.Env.DumpSpirv.Desc": "Extrai os shaders AGC e as respetivas traduções SPIR-V para a pasta shader-dumps.\nUtilize ao reportar problemas de shaders ou renderização.",
"Options.Env.LogDirectMemory.Desc": "Regista alocações de memória direta e falhas na consola.\nUtilize quando um jogo aborta ou fecha durante o arranque.",
"Options.Env.LogNp.Desc": "Regista chamadas da biblioteca NP (PlayStation Network) na consola.",
"Options.Env.Group.Debug": "Depuração",
"Options.Env.Group.General": "Geral",
"Options.Env.RenderDoc.Desc": "Carrega a API in-application do RenderDoc para capturar frames a partir do emulador.\nPrime F10 enquanto o jogo corre para capturar um frame; as capturas vão para user/logs/capture_logs/<TITLE_ID>.\nRequer o RenderDoc instalado. Torna a GPU mais lenta e bloqueia alguns títulos, por isso deixa desativado a menos que estejas a depurar.",
"Options.Env.GuestImageCpuSync.Desc": "Recarrega as superfícies do convidado que o próprio código de CPU do jogo reescreve.\nDeixar desativado normalmente. Ativar para títulos cujas superfícies desenhadas pela CPU nunca chegam ao ecrã.\nCusta desempenho e causa regressões em alguns títulos, como GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Entrega os preâmbulos do buffer de comandos da GPU mesmo quando a fila de destino nunca os recolhe.\nDeixar desativado normalmente. Ativar para títulos que bloqueiam à espera de uma fence de GPU que nunca sinaliza.",
"Options.Section.Emulation": "EMULAÇÃO",
"Options.Section.Logging": "REGISTOS",
"Options.Section.Launcher": "LANÇADOR",
-4
View File
@@ -42,11 +42,7 @@
"Options.Env.LogDirectMemory.Desc": "Выводить в консоль выделения прямой памяти и ошибки выделения.\nИспользуйте, если игра аварийно завершает работу или закрывается при запуске.",
"Options.Env.LogIo.Desc": "Выводить в консоль операции открытия и чтения файлов, а также разрешение путей.\nИспользуйте, если игра не может найти файлы данных при запуске.",
"Options.Env.LogNp.Desc": "Выводить в консоль вызовы библиотеки NP (PlayStation Network).",
"Options.Env.Group.Debug": "Отладка",
"Options.Env.Group.General": "Общие",
"Options.Env.RenderDoc.Desc": "Загружает внутренний API RenderDoc, чтобы кадры можно было захватывать из эмулятора.\nНажмите F10 во время игры, чтобы захватить один кадр; захваты сохраняются в user/logs/capture_logs/<TITLE_ID>.\nТребует установленного RenderDoc. Замедляет GPU и подвешивает некоторые игры, поэтому оставьте выключенным, если не занимаетесь отладкой.",
"Options.Env.GuestImageCpuSync.Desc": "Повторно загружать гостевые поверхности, которые переписывает собственный код ЦП игры.\nОбычно оставляйте выключенным. Включайте для игр, чьи отрисованные ЦП поверхности не попадают на экран.\nСнижает производительность и вызывает регрессии в некоторых играх, например в GTA V.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Доставляет преамбулы буфера команд GPU, даже если целевая очередь их так и не забирает.\nОбычно оставляйте выключенным. Включайте для игр, которые зависают в ожидании GPU-fence, который никогда не срабатывает.",
"Options.Section.Emulation": "ЭМУЛЯЦИЯ",
"Options.Section.Logging": "ЛОГГИРОВАНИЕ",
"Options.Section.Launcher": "ЛАУНЧЕР",
-4
View File
@@ -179,11 +179,7 @@
"Options.Env.LogDirectMemory.Desc": "Doğrudan bellek tahsislerini ve hatalarını konsola günlükle.\nBir oyun açılış sırasında çöküyor veya kapanıyorsa kullanın.",
"Options.Env.LogIo.Desc": "Dosya açma, okuma ve yol çözümleme etkinliğini konsola günlükle.\nBir oyun açılışta veri dosyalarını bulamıyorsa kullanın.",
"Options.Env.LogNp.Desc": "NP (PlayStation Network) kütüphane çağrılarını konsola günlükle.",
"Options.Env.Group.Debug": "Hata Ayıklama",
"Options.Env.Group.General": "Genel",
"Options.Env.RenderDoc.Desc": "RenderDoc uygulama içi API'sini yükler, böylece kareler emülatörün içinden yakalanabilir.\nOyun çalışırken F10'a basınca bir kare yakalanır; kayıtlar user/logs/capture_logs/<TITLE_ID> altına düşer.\nRenderDoc'un kurulu olmasını gerektirir. GPU'yu yavaşlatır ve bazı oyunları kilitler, hata ayıklamıyorsanız kapalı bırakın.",
"Options.Env.GuestImageCpuSync.Desc": "Oyunun kendi CPU kodunun yeniden yazdığı misafir yüzeyleri tekrar yükler.\nNormalde kapalı bırakın. CPU ile çizilen yüzeyleri ekrana ulaşmayan oyunlarda açın.\nPerformansa mal olur ve GTA V gibi bazı oyunlarda soruna yol açar.",
"Options.Env.ForceSubmitOrphanPreambles.Desc": "Hedef kuyruk onları asla almasa bile GPU komut arabelleği önsözlerini teslim eder.\nNormalde kapalı bırakın. Asla sinyal vermeyen bir GPU fence'ini bekleyerek takılan oyunlarda açın.",
"Options.DefaultProfile.Label": "Varsayilan profil adi",
"Options.DefaultProfile.Desc": "Oyun metin girisi istediginde kullanilacak ad. Varsayilan deger Sharp'tir.",
"Common.Save": "Kaydet",
@@ -22,7 +22,6 @@ public partial class MainWindow
"SHARPEMU_LOG_IO",
"SHARPEMU_LOG_NP",
"SHARPEMU_GUEST_IMAGE_CPU_SYNC",
"SHARPEMU_RENDERDOC",
];
private readonly List<string> _gameEnvironmentPassthrough = new();
@@ -483,8 +482,6 @@ public partial class MainWindow
("SHARPEMU_LOG_IO", GameEnvLogIoToggle),
("SHARPEMU_LOG_NP", GameEnvLogNpToggle),
("SHARPEMU_GUEST_IMAGE_CPU_SYNC", GameEnvGuestImageCpuSyncToggle),
("SHARPEMU_FORCE_SUBMIT_ORPHAN_PREAMBLES", GameEnvForceSubmitOrphanPreamblesToggle),
("SHARPEMU_RENDERDOC", GameEnvRenderDocToggle),
];
private static void SetGameOptionsOpenClass(Control control, bool active) =>
+44 -98
View File
@@ -892,13 +892,28 @@ SPDX-License-Identifier: GPL-2.0-or-later
<StackPanel>
<Border Classes="optionsGroup">
<StackPanel Spacing="8">
<TextBlock Classes="optionsGroupHeader" Text="{Binding [Options.Env.Group.Debug], Source={x:Static local:Localization.Instance}, x:CompileBindings=False}" />
<local:SettingRow Classes="optionRow"
Label="SHARPEMU_RENDERDOC"
Description="{Binding [Options.Env.RenderDoc.Desc],
Label="SHARPEMU_BTHID_UNAVAILABLE"
Description="{Binding [Options.Env.Bthid.Desc],
Source={x:Static local:Localization.Instance},
x:CompileBindings=False}">
<ToggleSwitch x:Name="GameEnvRenderDocToggle"
<ToggleSwitch x:Name="GameEnvBthidToggle"
Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow Classes="optionRow"
Label="SHARPEMU_DISABLE_IMPORT_LOOP_GUARD"
Description="{Binding [Options.Env.LoopGuard.Desc],
Source={x:Static local:Localization.Instance},
x:CompileBindings=False}">
<ToggleSwitch x:Name="GameEnvLoopGuardToggle"
Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow Classes="optionRow"
Label="SHARPEMU_WRITABLE_APP0"
Description="{Binding [Options.Env.WritableApp0.Desc],
Source={x:Static local:Localization.Instance},
x:CompileBindings=False}">
<ToggleSwitch x:Name="GameEnvWritableApp0Toggle"
Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow Classes="optionRow"
@@ -941,34 +956,6 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ToggleSwitch x:Name="GameEnvLogNpToggle"
Classes="optionToggle" />
</local:SettingRow>
<Border Classes="optionsGroupDivider" />
<TextBlock Classes="optionsGroupHeader" Text="{Binding [Options.Env.Group.General], Source={x:Static local:Localization.Instance}, x:CompileBindings=False}" />
<local:SettingRow Classes="optionRow"
Label="SHARPEMU_BTHID_UNAVAILABLE"
Description="{Binding [Options.Env.Bthid.Desc],
Source={x:Static local:Localization.Instance},
x:CompileBindings=False}">
<ToggleSwitch x:Name="GameEnvBthidToggle"
Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow Classes="optionRow"
Label="SHARPEMU_DISABLE_IMPORT_LOOP_GUARD"
Description="{Binding [Options.Env.LoopGuard.Desc],
Source={x:Static local:Localization.Instance},
x:CompileBindings=False}">
<ToggleSwitch x:Name="GameEnvLoopGuardToggle"
Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow Classes="optionRow"
Label="SHARPEMU_WRITABLE_APP0"
Description="{Binding [Options.Env.WritableApp0.Desc],
Source={x:Static local:Localization.Instance},
x:CompileBindings=False}">
<ToggleSwitch x:Name="GameEnvWritableApp0Toggle"
Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow Classes="optionRow"
Label="SHARPEMU_GUEST_IMAGE_CPU_SYNC"
Description="{Binding [Options.Env.GuestImageCpuSync.Desc],
@@ -977,14 +964,6 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ToggleSwitch x:Name="GameEnvGuestImageCpuSyncToggle"
Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow Classes="optionRow"
Label="SHARPEMU_FORCE_SUBMIT_ORPHAN_PREAMBLES"
Description="{Binding [Options.Env.ForceSubmitOrphanPreambles.Desc],
Source={x:Static local:Localization.Instance},
x:CompileBindings=False}">
<ToggleSwitch x:Name="GameEnvForceSubmitOrphanPreamblesToggle"
Classes="optionToggle" />
</local:SettingRow>
</StackPanel>
</Border>
</StackPanel>
@@ -1241,13 +1220,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
<StackPanel Spacing="8">
<!--Latest commit info-->
<Border Classes="optionsInfoRow">
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="18">
<Image Grid.Column="0"
Source="avares://SharpEmu.GUI/Assets/commit-icon.png"
Width="20" Height="20"
VerticalAlignment="Center"
Margin="0,0,12,0" />
<StackPanel Grid.Column="1" VerticalAlignment="Center">
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="18">
<StackPanel VerticalAlignment="Center">
<TextBlock x:Name="LatestCommitLabel"
Text="{Binding [About.Github.LatestCommitLabel], Source={x:Static local:Localization.Instance}}"
FontSize="14"
@@ -1258,7 +1232,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
Foreground="{StaticResource SettingsDescriptionBrush}"
TextWrapping="Wrap" />
</StackPanel>
<Button Grid.Column="2"
<Button Grid.Column="1"
x:Name="LatestCommitHashText"
Classes="optionAction"
Content="Loading…"
@@ -1271,13 +1245,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
<!--Update-->
<Border Classes="optionsInfoRow">
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="18">
<Image Grid.Column="0"
Source="avares://SharpEmu.GUI/Assets/update-icon.png"
Width="20" Height="20"
VerticalAlignment="Center"
Margin="0,0,12,0" />
<StackPanel Grid.Column="1" VerticalAlignment="Center">
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="18">
<StackPanel VerticalAlignment="Center">
<TextBlock x:Name="UpdateLabel"
Text="{Binding [Updater.Label], Source={x:Static local:Localization.Instance}}"
FontSize="14"
@@ -1288,7 +1257,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
Foreground="{StaticResource SettingsDescriptionBrush}"
TextWrapping="Wrap" />
</StackPanel>
<Button Grid.Column="2"
<Button Grid.Column="1"
x:Name="UpdateButton"
Classes="optionAction"
Content="Check for updates"
@@ -1298,13 +1267,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
<!--Github-->
<Border Classes="optionsInfoRow">
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="18">
<Image Grid.Column="0"
Source="avares://SharpEmu.GUI/Assets/github.png"
Width="20" Height="20"
VerticalAlignment="Center"
Margin="0,0,12,0" />
<StackPanel Grid.Column="1" VerticalAlignment="Center">
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="18">
<StackPanel VerticalAlignment="Center">
<TextBlock x:Name="GithubLabel"
Text="{Binding [About.Github.Label], Source={x:Static local:Localization.Instance}}"
FontSize="14"
@@ -1315,7 +1279,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
Foreground="{StaticResource SettingsDescriptionBrush}"
TextWrapping="Wrap" />
</StackPanel>
<Button Grid.Column="2"
<Button Grid.Column="1"
x:Name="GithubButton"
Classes="optionAction"
Content="{Binding [About.GithubButton], Source={x:Static local:Localization.Instance}}"
@@ -1325,13 +1289,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
<!--Discord-->
<Border Classes="optionsInfoRow">
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="18">
<Image Grid.Column="0"
Source="avares://SharpEmu.GUI/Assets/discord.png"
Width="20" Height="20"
VerticalAlignment="Center"
Margin="0,0,12,0" />
<StackPanel Grid.Column="1" VerticalAlignment="Center">
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="18">
<StackPanel VerticalAlignment="Center">
<TextBlock x:Name="DiscordServerLabel"
Text="{Binding [About.Discord.Label], Source={x:Static local:Localization.Instance}}"
FontSize="14"
@@ -1342,7 +1301,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
Foreground="{StaticResource SettingsDescriptionBrush}"
TextWrapping="Wrap" />
</StackPanel>
<TextBlock Grid.Column="2"
<TextBlock Grid.Column="1"
x:Name="DiscordComingSoonText"
Text="{Binding [About.DiscordComingSoon], Source={x:Static local:Localization.Instance}}"
FontSize="12"
@@ -1448,10 +1407,19 @@ SPDX-License-Identifier: GPL-2.0-or-later
<StackPanel>
<Border Classes="optionsGroup">
<StackPanel Spacing="8">
<TextBlock Classes="optionsGroupHeader" Text="{Binding [Options.Env.Group.Debug], Source={x:Static local:Localization.Instance}}" />
<local:SettingRow x:Name="EnvRenderDocRow" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_RENDERDOC"
Description="{Binding [Options.Env.RenderDoc.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvRenderDocToggle" Classes="optionToggle" />
<local:SettingRow x:Name="EnvBthidRow" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_BTHID_UNAVAILABLE"
Description="{Binding [Options.Env.Bthid.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvBthidToggle" Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow x:Name="EnvLoopGuardRow" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_DISABLE_IMPORT_LOOP_GUARD"
Description="{Binding [Options.Env.LoopGuard.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvLoopGuardToggle" Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow x:Name="EnvWritableApp0Row" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_WRITABLE_APP0"
Description="{Binding [Options.Env.WritableApp0.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvWritableApp0Toggle" Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow x:Name="EnvVkValidationRow" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_VK_VALIDATION"
@@ -1479,33 +1447,11 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ToggleSwitch x:Name="EnvLogNpToggle" Classes="optionToggle" />
</local:SettingRow>
<Border Classes="optionsGroupDivider" />
<TextBlock Classes="optionsGroupHeader" Text="{Binding [Options.Env.Group.General], Source={x:Static local:Localization.Instance}}" />
<local:SettingRow x:Name="EnvBthidRow" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_BTHID_UNAVAILABLE"
Description="{Binding [Options.Env.Bthid.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvBthidToggle" Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow x:Name="EnvLoopGuardRow" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_DISABLE_IMPORT_LOOP_GUARD"
Description="{Binding [Options.Env.LoopGuard.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvLoopGuardToggle" Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow x:Name="EnvWritableApp0Row" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_WRITABLE_APP0"
Description="{Binding [Options.Env.WritableApp0.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvWritableApp0Toggle" Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow x:Name="EnvGuestImageCpuSyncRow" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_GUEST_IMAGE_CPU_SYNC"
Description="{Binding [Options.Env.GuestImageCpuSync.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvGuestImageCpuSyncToggle" Classes="optionToggle" />
</local:SettingRow>
<local:SettingRow x:Name="EnvForceSubmitOrphanPreamblesRow" Classes="optionRow" LabelFontFamily="Consolas,monospace" Label="SHARPEMU_FORCE_SUBMIT_ORPHAN_PREAMBLES"
Description="{Binding [Options.Env.ForceSubmitOrphanPreambles.Desc], Source={x:Static local:Localization.Instance}}">
<ToggleSwitch x:Name="EnvForceSubmitOrphanPreamblesToggle" Classes="optionToggle" />
</local:SettingRow>
</StackPanel>
</Border>
-37
View File
@@ -290,39 +290,6 @@ public partial class MainWindow : Window
SetEnvironmentToggle(
"SHARPEMU_GUEST_IMAGE_CPU_SYNC",
EnvGuestImageCpuSyncToggle.IsChecked == true);
EnvForceSubmitOrphanPreamblesToggle.IsCheckedChanged += (_, _) =>
SetEnvironmentToggle(
"SHARPEMU_FORCE_SUBMIT_ORPHAN_PREAMBLES",
EnvForceSubmitOrphanPreamblesToggle.IsChecked == true);
DefaultProfileBox.TextChanged += (_, _) =>
_settings.DefaultProfile = GuiSettings.NormalizeDefaultProfile(DefaultProfileBox.Text);
LanguageBox.SelectionChanged += (_, _) => OnLanguageChanged();
GameList.AddHandler(ContextRequestedEvent, OnGameContextRequested, RoutingStrategies.Tunnel);
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
CtxLaunch.Click += (_, _) => LaunchSelected();
CtxOpenFolder.Click += (_, _) => OpenSelectedGameFolder();
CtxCopyPath.Click += async (_, _) =>
await CopyToClipboardAsync((GameList.SelectedItem as GameEntry)?.Path);
CtxCopyTitleId.Click += async (_, _) =>
await CopyToClipboardAsync((GameList.SelectedItem as GameEntry)?.TitleId);
CtxGameSettings.Click += (_, _) => OpenSelectedGameSettings();
CtxRemove.Click += (_, _) => RemoveSelectedFromLibrary();
Opened += async (_, _) => await OnOpenedAsync();
Closing += (_, _) => BeginWindowClosing();
Closed += (_, _) => CompleteWindowClosing();
SdlLauncherGamepad.EnsureStarted();
_gamepadTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(50),
};
EnvRenderDocToggle.IsCheckedChanged += (_, _) =>
SetEnvironmentToggle(
"SHARPEMU_RENDERDOC",
EnvRenderDocToggle.IsChecked == true);
DefaultProfileBox.TextChanged += (_, _) =>
_settings.DefaultProfile = GuiSettings.NormalizeDefaultProfile(DefaultProfileBox.Text);
LanguageBox.SelectionChanged += (_, _) => OnLanguageChanged();
@@ -1217,10 +1184,6 @@ public partial class MainWindow : Window
EnvLogNpToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_LOG_NP");
EnvGuestImageCpuSyncToggle.IsChecked =
_settings.EnvironmentToggles.Contains("SHARPEMU_GUEST_IMAGE_CPU_SYNC");
EnvForceSubmitOrphanPreamblesToggle.IsChecked =
_settings.EnvironmentToggles.Contains("SHARPEMU_FORCE_SUBMIT_ORPHAN_PREAMBLES");
EnvRenderDocToggle.IsChecked =
_settings.EnvironmentToggles.Contains("SHARPEMU_RENDERDOC");
DefaultProfileBox.Text = _settings.DefaultProfile;
WindowModeBox.SelectedIndex = ChoiceIndex(_settings.WindowMode, "Windowed", "Borderless", "Exclusive");
LoadHostDisplayOptions();
@@ -42,27 +42,6 @@ Options page section transitions and content layout
<Setter Property="Padding" Value="0" />
</Style>
<Style Selector="TextBlock.optionsGroupHeader">
<Setter Property="FontSize" Value="12" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="#8CFFFFFF" />
<Setter Property="Margin" Value="2,0,0,10" />
</Style>
<Style Selector="Border.optionsGroupDivider">
<Setter Property="Height" Value="1" />
<Setter Property="Margin" Value="0,18,0,18" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="Background">
<LinearGradientBrush StartPoint="0%,0%" EndPoint="100%,0%">
<GradientStop Offset="0" Color="#00FFFFFF" />
<GradientStop Offset="0.06" Color="#2EFFFFFF" />
<GradientStop Offset="0.55" Color="#14FFFFFF" />
<GradientStop Offset="1" Color="#00FFFFFF" />
</LinearGradientBrush>
</Setter>
</Style>
<Style Selector="Border.optionsInfoRow">
<Setter Property="MinHeight" Value="70" />
<Setter Property="Padding" Value="18,12" />
-44
View File
@@ -99,50 +99,6 @@ public static class AcmExports
return CompleteBatchStart(ctx, context, infoCount, errorAddress, batchAddress);
}
// DSP batch submission and synchronization. The emulator runs no ACM DSP
// jobs (FFT/panner/reverb output stays silent), but Scream's workers trap
// with int 0x41/0x42 asserts whenever a submission call reports failure,
// so the whole batch surface must report success.
[SysAbiExport(
Nid = "WeZOIm8+8WI",
ExportName = "sceAcmBatchInitialize",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceAcm")]
public static int AcmBatchInitialize(CpuContext ctx) =>
ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK);
[SysAbiExport(
Nid = "Mk1xvQXIdkk",
ExportName = "sceAcmBatchInitializeLite",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceAcm")]
public static int AcmBatchInitializeLite(CpuContext ctx) =>
ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK);
[SysAbiExport(
Nid = "A5NXCXK5Gfc",
ExportName = "sceAcmBatchStart",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceAcm")]
public static int AcmBatchStart(CpuContext ctx) =>
ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK);
[SysAbiExport(
Nid = "S3BPrjCfZ90",
ExportName = "sceAcmBatchStartMultiple",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceAcm")]
public static int AcmBatchStartMultiple(CpuContext ctx) =>
ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK);
[SysAbiExport(
Nid = "uqDIauipRbo",
ExportName = "sceAcmBatchProcess",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceAcm")]
public static int AcmBatchProcess(CpuContext ctx) =>
ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK);
[SysAbiExport(
Nid = "RLN3gRlXJLE",
ExportName = "sceAcmBatchWait",
File diff suppressed because it is too large Load Diff
+1 -88
View File
@@ -60,17 +60,6 @@ internal static class GpuWaitRegistry
// address) so distinct guest processes never alias.
private static readonly Dictionary<(object, ulong), ulong> _lastProduced = new();
private static object? Canonicalize(object? memory)
{
while (memory is SharpEmu.HLE.ICpuMemoryWrapper wrapper)
{
memory = wrapper.Inner;
}
return memory;
}
public static int Count
{
get
@@ -90,7 +79,6 @@ internal static class GpuWaitRegistry
public static int CountForMemory(object memory)
{
memory = Canonicalize(memory)!;
lock (_gate)
{
var total = 0;
@@ -118,7 +106,6 @@ internal static class GpuWaitRegistry
/// </summary>
public static OutstandingSnapshot SnapshotOutstanding(object? memory = null)
{
memory = Canonicalize(memory);
lock (_gate)
{
var outstanding = 0;
@@ -168,7 +155,6 @@ internal static class GpuWaitRegistry
public static void Register(ulong address, WaitingDcb waiter)
{
waiter.WaitAddress = address;
waiter.Memory = Canonicalize(waiter.Memory);
lock (_gate)
{
if (!_waiters.TryGetValue(address, out var list))
@@ -191,7 +177,6 @@ internal static class GpuWaitRegistry
object memory,
Func<ulong, bool, ulong?> readValue)
{
memory = Canonicalize(memory)!;
List<WaitingDcb>? woken = null;
lock (_gate)
{
@@ -252,7 +237,6 @@ internal static class GpuWaitRegistry
long nowTicks,
long maxAgeTicks)
{
memory = Canonicalize(memory)!;
List<WaitingDcb>? stale = null;
lock (_gate)
{
@@ -289,7 +273,6 @@ internal static class GpuWaitRegistry
ulong start,
ulong length)
{
memory = Canonicalize(memory)!;
var matches = new List<(ulong Address, int Count)>();
if (length == 0)
{
@@ -345,7 +328,6 @@ internal static class GpuWaitRegistry
/// </summary>
public static bool LatchSatisfiedByValue(object memory, ulong address, ulong value)
{
memory = Canonicalize(memory)!;
var latchedAny = false;
lock (_gate)
{
@@ -373,56 +355,6 @@ internal static class GpuWaitRegistry
return latchedAny;
}
/// <summary>
/// Every registered waiter, for the flip-stall watchdog. Not filtered by
/// memory identity — the watchdog wants a whole-process view.
/// </summary>
public static List<WaitingDcb> SnapshotAll()
{
var snapshot = new List<WaitingDcb>();
lock (_gate)
{
foreach (var (_, list) in _waiters)
{
snapshot.AddRange(list);
}
}
return snapshot;
}
/// <summary>
/// Removes the waiter at <paramref name="address"/> whose State is
/// <paramref name="state"/> — used when a new submission supersedes a
/// ring-tail park that would otherwise pin the queue forever.
/// </summary>
public static bool TryRemoveByState(object state, ulong address)
{
lock (_gate)
{
if (!_waiters.TryGetValue(address, out var list))
{
return false;
}
for (var i = list.Count - 1; i >= 0; i--)
{
if (ReferenceEquals(list[i].State, state))
{
list.RemoveAt(i);
if (list.Count == 0)
{
_waiters.Remove(address);
}
return true;
}
}
return false;
}
}
/// <summary>
/// Removes and returns waiters carrying a <see cref="WaitingDcb.RetryDeadlineTicks"/>
/// that has elapsed. Used for indirect-dispatch dimension retries: the caller
@@ -431,7 +363,6 @@ internal static class GpuWaitRegistry
/// </summary>
public static List<WaitingDcb>? CollectExpiredRetries(object memory, long nowTicks)
{
memory = Canonicalize(memory)!;
List<WaitingDcb>? expired = null;
lock (_gate)
{
@@ -474,7 +405,6 @@ internal static class GpuWaitRegistry
public static List<WaitingDcb>? CollectAllForMemory(object memory)
{
memory = Canonicalize(memory)!;
List<WaitingDcb>? collected = null;
lock (_gate)
{
@@ -560,7 +490,6 @@ internal static class GpuWaitRegistry
/// breaker. Also latches any already-waiting waiter it satisfies.</summary>
public static bool RecordProduced(object memory, ulong address, ulong value)
{
memory = Canonicalize(memory)!;
lock (_gate)
{
if (_lastProduced.Count >= 8192)
@@ -594,7 +523,6 @@ internal static class GpuWaitRegistry
long nowTicks,
long minAgeTicks)
{
memory = Canonicalize(memory)!;
List<WaitingDcb>? broken = null;
lock (_gate)
{
@@ -636,21 +564,6 @@ internal static class GpuWaitRegistry
return broken;
}
// Under orphan force-submit, producers can run ahead of waiter
// registration and pass an equal-compare value before it's ever seen.
// Treat == as "reached or passed" only in that mode, so other titles
// keep exact hardware semantics. SHARPEMU_GPU_WAIT_EQ_EXACT=1 restores
// strict equality for A/B.
private static readonly bool _equalCompareExact =
string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_GPU_WAIT_EQ_EXACT"),
"1",
StringComparison.Ordinal) ||
!string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_FORCE_SUBMIT_ORPHAN_PREAMBLES"),
"1",
StringComparison.Ordinal);
public static bool Compare(in WaitingDcb waiter, ulong value)
{
var masked = value & waiter.Mask;
@@ -660,7 +573,7 @@ internal static class GpuWaitRegistry
0 => true,
1 => masked < reference,
2 => masked <= reference,
3 => _equalCompareExact ? masked == reference : masked >= reference,
3 => masked == reference,
4 => masked != reference,
5 => masked >= reference,
6 => masked > reference,
+1 -1
View File
@@ -72,7 +72,7 @@ public static class AmprExports
private const int MaxCachedHostFiles = 1536;
private static readonly object _hostFileCacheGate = new();
private static readonly Dictionary<string, LinkedListNode<CachedHostFileEntry>> _hostFileByPath =
new(HostFsPath.Comparer);
new(StringComparer.OrdinalIgnoreCase);
private static readonly LinkedList<CachedHostFileEntry> _hostFileLru = new();
[SysAbiExport(
+16 -33
View File
@@ -111,7 +111,7 @@ internal static class AmprFileRegistry
{
while (true)
{
if (string.Equals(_indexedApp0Root, normalizedRoot, HostFsPath.Comparison))
if (string.Equals(_indexedApp0Root, normalizedRoot, StringComparison.OrdinalIgnoreCase))
{
return;
}
@@ -123,7 +123,7 @@ internal static class AmprFileRegistry
if (string.Equals(
_indexingApp0Root,
normalizedRoot,
HostFsPath.Comparison))
StringComparison.OrdinalIgnoreCase))
{
Monitor.Wait(_indexGate);
continue;
@@ -174,34 +174,20 @@ internal static class AmprFileRegistry
}
var relatives = new List<string>(256 * 1024);
try
foreach (var hostPath in Directory.EnumerateFiles(
normalizedRoot,
"*",
SearchOption.AllDirectories))
{
foreach (var hostPath in Directory.EnumerateFiles(
normalizedRoot,
"*",
SearchOption.AllDirectories))
var relative = Path.GetRelativePath(normalizedRoot, hostPath)
.Replace('\\', '/');
if (string.IsNullOrEmpty(relative) ||
relative.StartsWith("..", StringComparison.Ordinal))
{
var relative = Path.GetRelativePath(normalizedRoot, hostPath)
.Replace('\\', '/');
if (string.IsNullOrEmpty(relative) ||
relative.StartsWith("..", StringComparison.Ordinal))
{
continue;
}
relatives.Add(relative);
continue;
}
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// The walk is an opportunistic warm-up reached synchronously from
// sceAmprCommandBufferConstructor; a dump that moves or a mount
// that hiccups must not fault the guest export. The background
// preload already swallows this. Leave the root unindexed so a
// later call retries.
Console.Error.WriteLine(
$"[LOADER][WARN] ampr.app0_index_walk_failed root={normalizedRoot}: {exception.Message}");
return;
relatives.Add(relative);
}
// Hash + dictionary fill dominates under Rosetta once the walk is
@@ -329,10 +315,7 @@ internal static class AmprFileRegistry
"ampr-index");
Directory.CreateDirectory(cacheDir);
// Distinct roots must not share a cache file. Folding case is only
// correct where the host filesystem folds it too.
var rootKey = OperatingSystem.IsWindows() ? normalizedRoot.ToLowerInvariant() : normalizedRoot;
var rootHash = ComputeFileId(rootKey);
var rootHash = ComputeFileId(normalizedRoot.ToLowerInvariant());
return Path.Combine(cacheDir, $"app0-{rootHash:x8}.v{version}.idx");
}
@@ -377,7 +360,7 @@ internal static class AmprFileRegistry
}
var root = reader.ReadString();
if (!string.Equals(root, normalizedRoot, HostFsPath.Comparison))
if (!string.Equals(root, normalizedRoot, StringComparison.OrdinalIgnoreCase))
{
return false;
}
@@ -487,7 +470,7 @@ internal static class AmprFileRegistry
return;
}
var relatives = new HashSet<string>(HostFsPath.Comparer);
var relatives = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var hostPath in _hostPathsById.Values)
{
var relative = Path.GetRelativePath(normalizedRoot, hostPath)
+10 -37
View File
@@ -21,18 +21,7 @@ public static class AjmExports
private const int OrbisAjmErrorJobCreation = unchecked((int)0x80930012);
private const ulong MaxSilentPcmBytes = 1 << 20;
private const uint Atrac9CodecType = 1;
// instanceId packs codecType into the high bits and the instance slot
// into the low InstanceIdSlotBits bits (see AjmInstanceCreate's
// `(codecType << InstanceIdSlotBits) | instanceSlot` and the
// `& InstanceIdSlotMask` unpacks in AjmInstanceDestroy/GetError).
private const int InstanceIdSlotBits = 14;
private const uint InstanceIdSlotMask = (1u << InstanceIdSlotBits) - 1;
// Registration is pure bookkeeping (a HashSet.Add), so the only real
// constraint is that codecType must not overflow the 32-bit instanceId
// once shifted left by InstanceIdSlotBits -- not any hardcoded list of
// known Sony codec ids, which a retail title's Gen5 codec type (e.g. 24)
// can legitimately fall outside of.
private const uint MaxCodecType = 1u << (32 - InstanceIdSlotBits);
private const uint MaxCodecType = 25;
private const int MaxInstanceIndex = 0x2FFF;
private const int MaxDecodeBufferBytes = 64 * 1024 * 1024;
@@ -130,12 +119,9 @@ public static class AjmExports
LibraryName = "libSceAjm")]
public static int AjmFinalize(CpuContext ctx)
{
if (!Contexts.TryRemove(unchecked((uint)ctx[CpuRegister.Rdi]), out _))
{
return ctx.SetReturn(OrbisAjmErrorInvalidContext);
}
return ctx.SetReturn(0);
Contexts.TryRemove(unchecked((uint)ctx[CpuRegister.Rdi]), out _);
ctx[CpuRegister.Rax] = 0;
return 0;
}
[SysAbiExport(
@@ -287,7 +273,7 @@ public static class AjmExports
}
while (state.InstancesBySlot.ContainsKey(instanceSlot));
instanceId = (codecType << InstanceIdSlotBits) | instanceSlot;
instanceId = (codecType << 14) | instanceSlot;
Span<byte> value = stackalloc byte[sizeof(uint)];
BinaryPrimitives.WriteUInt32LittleEndian(value, instanceId);
if (!ctx.Memory.TryWrite(outputAddress, value))
@@ -328,7 +314,7 @@ public static class AjmExports
return ctx.SetReturn(OrbisAjmErrorInvalidContext);
}
var instanceSlot = instanceId & InstanceIdSlotMask;
var instanceSlot = instanceId & 0x3FFF;
lock (state.Gate)
{
if (instanceSlot == 0 || !state.InstancesBySlot.Remove(instanceSlot))
@@ -348,21 +334,8 @@ public static class AjmExports
LibraryName = "libSceAjm")]
public static int AjmModuleUnregister(CpuContext ctx)
{
var contextId = unchecked((uint)ctx[CpuRegister.Rdi]);
var codecType = unchecked((uint)ctx[CpuRegister.Rsi]);
if (!Contexts.TryGetValue(contextId, out var state))
{
return ctx.SetReturn(OrbisAjmErrorInvalidContext);
}
bool removed;
lock (state.Gate)
{
removed = state.RegisteredCodecs.Remove(codecType);
}
Trace($"module_unregister context={contextId} codec={codecType} was_registered={removed}");
return ctx.SetReturn(0);
ctx[CpuRegister.Rax] = 0;
return 0;
}
[SysAbiExport(
@@ -694,8 +667,8 @@ public static class AjmExports
private static bool TryGetInstance(uint instanceId, out AjmInstanceState instance)
{
instance = null!;
var codec = instanceId >> InstanceIdSlotBits;
var slot = instanceId & InstanceIdSlotMask;
var codec = instanceId >> 14;
var slot = instanceId & 0x3FFF;
if (slot == 0)
{
return false;
@@ -163,33 +163,6 @@ public static class AudioOut2Exports
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
// Ghost of Yotei calls this with flags=0 during Scream startup and never
// checks the result before continuing into its mastering path; the actual
// mastering chain lives in the host mixer, so accepting the request is
// sufficient.
[SysAbiExport(
Nid = "XHl38ZNknbs",
ExportName = "sceAudioOut2MasteringInit",
Target = Generation.Gen5,
LibraryName = "libSceAudioOut2")]
public static int AudioOut2MasteringInit(CpuContext ctx)
{
return SetReturn(ctx, 0);
}
// 3D-audio object latency hint; the host mixer has no object pipeline to
// tune, but failure here makes Yotei tear down its whole ACM context and
// abort audio arena bring-up.
[SysAbiExport(
Nid = "TViD1EZXkNI",
ExportName = "sceAudioOut2Set3DLatency",
Target = Generation.Gen5,
LibraryName = "libSceAudioOut2")]
public static int AudioOut2Set3DLatency(CpuContext ctx)
{
return SetReturn(ctx, 0);
}
[SysAbiExport(
Nid = "t5YrizufpQc",
ExportName = "sceAudioOut2ContextResetParam",
@@ -948,7 +921,6 @@ public static class AudioOut2Exports
if (mixedPorts == 0)
{
TraceSubmitSkipped(context, frames, "no-ports");
return false;
}
@@ -970,7 +942,6 @@ public static class AudioOut2Exports
var backend = ResolveContextBackend(context, out var backendName);
if (backend is null)
{
TraceSubmitSkipped(context, frames, "no-backend");
return false;
}
@@ -1241,14 +1212,4 @@ public static class AudioOut2Exports
Console.Error.WriteLine($"[LOADER][TRACE] audio_out2.{message}");
}
}
private static void TraceSubmitSkipped(ContextState context, int frames, string reason)
{
var n = Interlocked.Increment(ref _submitSkipTraceCount);
if (n <= 8 || n % 500 == 0)
{
TraceAudioOut2(
$"context-submit-skip#{n} handle=0x{context.Handle:X} frames={frames} reason={reason}");
}
}
}
+56 -671
View File
@@ -4,9 +4,7 @@
using SharpEmu.HLE;
using SharpEmu.Libs.Kernel;
using SharpEmu.Libs.Media;
using SharpEmu.Libs.VideoOut;
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Text;
@@ -24,213 +22,14 @@ public static class AvPlayerExports
private const int FrameHeightAlignment = 16;
private const int FrameInfoSize = 40;
private const int FrameInfoExSize = 104;
// The legacy destination is 40 bytes on Gen4 but only 32 bytes on Gen5.
// Writing the Gen4 layout into a Gen5 caller can overwrite its stack canary.
private const int Gen4StreamInfoSize = 40;
private const int Gen5StreamInfoSize = 32;
private const int StreamInfoExSize = 104;
// This structure is 32 bytes. A larger write can damage the guest stack.
private const int StreamInfoSize = 32;
private const int StreamInfoExSize = 32;
private const int MaxGuestPathLength = 4096;
private const int VideoPitchAlignment = 256;
private static readonly object StateGate = new();
private static readonly HashSet<string> TracedOnce = new();
private static readonly Dictionary<ulong, PlayerState> Players = new();
private static readonly ConcurrentDictionary<ulong, ulong> VideoBufferRanges = new();
private static readonly bool TraceVideoImages = string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_TRACE_AVPLAYER_IMAGES"),
"1",
StringComparison.Ordinal);
private static int _traceCount;
private static int _videoPayloadTraceCount;
private static long _fallbackPresentationSerial;
internal static bool TryGetFallbackPresentationFrame(
out byte[] pixels,
out uint width,
out uint height,
out long serial)
{
lock (StateGate)
{
PlayerState? latest = null;
foreach (var player in Players.Values)
{
if (player.FallbackPlayback is { } playback)
{
if (playback.TryGetFrame(
advanceClock: true,
out var playbackPixels,
out var advanced))
{
var skipFirstDecodedFrame =
player.SkipFirstFallbackPlaybackFrame;
if (ShouldPublishFallbackPlaybackFrame(
advanced,
player.FallbackPresentationPixels is not null,
ref skipFirstDecodedFrame))
{
player.FallbackPresentationPixels = playbackPixels;
player.FallbackPresentationWidth = playback.Width;
player.FallbackPresentationHeight = playback.Height;
player.FallbackPresentationSerial =
Interlocked.Increment(ref _fallbackPresentationSerial);
}
player.SkipFirstFallbackPlaybackFrame =
skipFirstDecodedFrame;
}
else if (playback.IsFinished)
{
playback.Dispose();
player.FallbackPlayback = null;
player.FallbackPlaybackCompleted = true;
player.FallbackPlaybackCompletedTicks = Stopwatch.GetTimestamp();
Trace(
$"host_fallback_finished handle=0x{player.Handle:X16} " +
"holding_last_frame=true");
}
}
// The host decoder can finish long before a heavily throttled
// guest AvPlayer reaches EOF. Keep its final image over the
// stale guest texture until the guest has actually consumed
// the stream; otherwise frame zero becomes visible again and
// the intro appears to start a second time. The hold is
// bounded: a title that pauses its player after the poster
// frame never reaches EOF, and an unbounded hold would pin the
// final movie image over everything the game renders next.
if (ShouldReleaseCompletedFallback(
player.FallbackPlaybackCompleted,
player.EndOfStream,
player.FallbackPlaybackCompletedTicks,
Stopwatch.GetTimestamp()))
{
ClearFallbackPresentation(player);
}
if (player.FallbackPresentationPixels is null ||
player.FallbackPresentationSerial <= 0 ||
latest is not null &&
player.FallbackPresentationSerial <= latest.FallbackPresentationSerial)
{
continue;
}
latest = player;
}
if (latest?.FallbackPresentationPixels is not { } frame)
{
pixels = [];
width = 0;
height = 0;
serial = 0;
return false;
}
pixels = frame;
width = latest.FallbackPresentationWidth;
height = latest.FallbackPresentationHeight;
serial = latest.FallbackPresentationSerial;
return IsValidBgraFrame(pixels, width, height);
}
}
internal static bool ShouldPublishFallbackPlaybackFrame(
bool advanced,
bool hasPresentation,
ref bool skipFirstDecodedFrame)
{
if (advanced && hasPresentation && skipFirstDecodedFrame)
{
skipFirstDecodedFrame = false;
return false;
}
return advanced || !hasPresentation;
}
/// <summary>
/// How long a finished host playback keeps its final image on screen while
/// waiting for the guest player to reach end of stream. Titles that pause
/// their AvPlayer after the first frame never do, so the hold expires.
/// </summary>
private static readonly long FallbackHoldGraceTicks = Stopwatch.Frequency;
internal static bool ShouldReleaseCompletedFallback(
bool fallbackPlaybackCompleted,
bool guestEndOfStream,
long completedTicks,
long nowTicks) =>
fallbackPlaybackCompleted &&
(guestEndOfStream ||
completedTicks != 0 && nowTicks - completedTicks >= FallbackHoldGraceTicks);
private static void ClearFallbackPresentation(PlayerState player)
{
player.FallbackPresentationPixels = null;
player.FallbackPresentationWidth = 0;
player.FallbackPresentationHeight = 0;
player.FallbackPresentationSerial = 0;
player.FallbackPlaybackCompleted = false;
player.FallbackPlaybackCompletedTicks = 0;
player.SkipFirstFallbackPlaybackFrame = false;
Trace(
$"host_fallback_released handle=0x{player.Handle:X16} " +
$"guest_eof={player.EndOfStream}");
}
internal static bool ShouldTraceVideoBufferAddress(ulong address)
{
if (!TraceVideoImages || address == 0)
{
return false;
}
foreach (var (start, length) in VideoBufferRanges)
{
if (address >= start && address - start < length)
{
return true;
}
}
return false;
}
internal static bool ShouldTraceVideoBufferRange(ulong address, ulong length)
{
if (!TraceVideoImages || address == 0 || length == 0)
{
return false;
}
foreach (var (start, rangeLength) in VideoBufferRanges)
{
if (address <= start
? start - address < length
: address - start < rangeLength)
{
return true;
}
}
return false;
}
private static void RegisterVideoBuffer(ulong address, int size, int index, string source)
{
if (address == 0 || size <= 0)
{
return;
}
VideoBufferRanges[address] = checked((ulong)size);
if (TraceVideoImages)
{
Console.Error.WriteLine(
$"[AVPLAYER][TRACE] video_buffer index={index} source={source} " +
$"data=0x{address:X16} size={size}");
}
}
private sealed class PlayerState : IDisposable
{
@@ -246,8 +45,6 @@ public static class AvPlayerExports
public int Height { get; set; }
public double FramesPerSecond { get; set; } = 30.0;
public ulong DurationMilliseconds { get; set; }
public bool HasAudio { get; set; }
public bool IsGen5 { get; init; }
public bool Started { get; set; }
public bool Paused { get; set; }
public bool Looping { get; set; }
@@ -264,20 +61,10 @@ public static class AvPlayerExports
public int GuestBufferStride { get; set; }
public int NextGuestBuffer { get; set; }
public ulong LastGuestBuffer { get; set; }
public ulong LastVideoTimestamp { get; set; }
public long NextFrameIndex { get; set; }
public ulong AudioBufferBase { get; set; }
public int NextAudioBuffer { get; set; }
public long NextAudioFrameIndex { get; set; }
public byte[]? FallbackPresentationPixels { get; set; }
public uint FallbackPresentationWidth { get; set; }
public uint FallbackPresentationHeight { get; set; }
public long FallbackPresentationSerial { get; set; }
public MediaFramePlayback? FallbackPlayback { get; set; }
public bool FallbackPlaybackAttempted { get; set; }
public bool FallbackPlaybackCompleted { get; set; }
public long FallbackPlaybackCompletedTicks { get; set; }
public bool SkipFirstFallbackPlaybackFrame { get; set; }
public void Dispose()
{
@@ -285,8 +72,6 @@ public static class AvPlayerExports
DecoderOutput = null;
AudioDecoderOutput?.Dispose();
AudioDecoderOutput = null;
FallbackPlayback?.Dispose();
FallbackPlayback = null;
}
public void ResetPlayback()
@@ -294,19 +79,9 @@ public static class AvPlayerExports
Dispose();
PlaybackClock.Reset();
NextFrameIndex = 0;
LastGuestBuffer = 0;
LastVideoTimestamp = 0;
NextAudioFrameIndex = 0;
SkippedFrameDebt = 0;
EndOfStream = false;
FallbackPresentationPixels = null;
FallbackPresentationWidth = 0;
FallbackPresentationHeight = 0;
FallbackPresentationSerial = 0;
FallbackPlaybackAttempted = false;
FallbackPlaybackCompleted = false;
FallbackPlaybackCompletedTicks = 0;
SkipFirstFallbackPlaybackFrame = false;
}
}
@@ -327,12 +102,10 @@ public static class AvPlayerExports
lock (StateGate)
{
var autoStartOffset = GetAutoStartOffset(ctx.TargetGeneration, extended: false);
Players.Add(handle, new PlayerState
{
Handle = handle,
IsGen5 = IsGen5Target(ctx.TargetGeneration),
AutoStart = TryReadByte(ctx, initDataAddress + autoStartOffset, out var autoStart) && autoStart != 0,
AutoStart = TryReadByte(ctx, initDataAddress + 108, out var autoStart) && autoStart != 0,
AllocatorObject = TryReadUInt64(ctx, initDataAddress, out var allocatorObject) ? allocatorObject : 0,
AllocateTextureCallback = TryReadUInt64(ctx, initDataAddress + 24, out var allocateTexture) ? allocateTexture : 0,
AllocateCallback = TryReadUInt64(ctx, initDataAddress + 8, out var allocate) ? allocate : 0,
@@ -384,12 +157,10 @@ public static class AvPlayerExports
lock (StateGate)
{
var autoStartOffset = GetAutoStartOffset(ctx.TargetGeneration, extended: true);
Players.Add(handle, new PlayerState
{
Handle = handle,
IsGen5 = IsGen5Target(ctx.TargetGeneration),
AutoStart = TryReadByte(ctx, initDataAddress + autoStartOffset, out var autoStart) && autoStart != 0,
AutoStart = TryReadByte(ctx, initDataAddress + 164, out var autoStart) && autoStart != 0,
AllocatorObject = TryReadUInt64(ctx, initDataAddress + 8, out var allocatorObject) ? allocatorObject : 0,
AllocateTextureCallback = TryReadUInt64(ctx, initDataAddress + 32, out var allocateTexture) ? allocateTexture : 0,
AllocateCallback = TryReadUInt64(ctx, initDataAddress + 16, out var allocate) ? allocate : 0,
@@ -550,24 +321,20 @@ public static class AvPlayerExports
LibraryName = "libSceAvPlayer")]
public static int AvPlayerResume(CpuContext ctx)
{
PlayerState player;
lock (StateGate)
{
if (!Players.TryGetValue(ctx[CpuRegister.Rdi], out var foundPlayer))
if (!Players.TryGetValue(ctx[CpuRegister.Rdi], out var player))
{
return SetReturn(ctx, InvalidParameters);
}
player = foundPlayer;
player.Paused = false;
if (player.DecoderOutput is not null)
{
player.PlaybackClock.Start();
}
return SetReturn(ctx, 0);
}
NotifyEvent(ctx, player, 3); // StatePlay
return SetReturn(ctx, 0);
}
[SysAbiExport(
@@ -618,33 +385,8 @@ public static class AvPlayerExports
ExportName = "sceAvPlayerGetStreamInfoEx",
Target = Generation.Gen5,
LibraryName = "libSceAvPlayer")]
public static int AvPlayerGetStreamInfoEx(CpuContext ctx)
{
var streamIndex = unchecked((uint)ctx[CpuRegister.Rsi]);
var infoAddress = ctx[CpuRegister.Rdx];
lock (StateGate)
{
if (!Players.TryGetValue(ctx[CpuRegister.Rdi], out var player) ||
streamIndex > (player.HasAudio ? 1u : 0u) ||
infoAddress == 0)
{
return SetReturn(ctx, InvalidParameters);
}
Span<byte> info = stackalloc byte[StreamInfoExSize];
info.Clear();
WriteGen5StreamInfoEx(
info,
GetStreamType(ctx.TargetGeneration, streamIndex),
streamIndex == 0 ? checked((uint)player.Width) : 0,
streamIndex == 0 ? checked((uint)player.Height) : 0,
streamIndex == 0 ? player.FramesPerSecond : 0,
player.DurationMilliseconds);
return SetReturn(
ctx,
ctx.Memory.TryWrite(infoAddress, info) ? 0 : InvalidParameters);
}
}
public static int AvPlayerGetStreamInfoEx(CpuContext ctx) =>
GetStreamInfoCore(ctx, StreamInfoExSize);
[SysAbiExport(
Nid = "XC9wM+xULz8",
@@ -718,15 +460,14 @@ public static class AvPlayerExports
{
var found = Players.TryGetValue(ctx[CpuRegister.Rdi], out var player);
if (!found || infoAddress == 0 || !player!.Started || player.Paused ||
player.EndOfStream || player.SourcePath is null ||
!player.HasAudio || !EnsureAudioDecoder(player))
player.EndOfStream || player.SourcePath is null || !EnsureAudioDecoder(player))
{
TraceOnce(
"audio_data_refused",
$"audio_data refused found={found} info=0x{infoAddress:X16} " +
$"started={(found && player!.Started)} paused={(found && player!.Paused)} " +
$"eos={(found && player!.EndOfStream)} " +
$"has_audio={(found && player!.HasAudio)}");
$"decoder={(found && player!.SourcePath is not null && EnsureAudioDecoder(player))}");
return SetReturn(ctx, 0);
}
@@ -809,11 +550,9 @@ public static class AvPlayerExports
{
lock (StateGate)
{
return SetReturn(
ctx,
Players.TryGetValue(ctx[CpuRegister.Rdi], out var player)
? player.HasAudio ? 2 : 1
: InvalidParameters);
var known = Players.ContainsKey(ctx[CpuRegister.Rdi]);
TraceOnce("stream_count", $"stream_count known={known} returned={(known ? 2 : -1)}");
return SetReturn(ctx, known ? 2 : InvalidParameters);
}
}
@@ -821,12 +560,7 @@ public static class AvPlayerExports
ulong handle,
int width,
int height,
ulong durationMilliseconds,
ulong allocateTextureCallback = 0,
ulong allocateCallback = 0,
bool hasAudio = false,
double framesPerSecond = 30.0,
bool isGen5 = true)
ulong durationMilliseconds)
{
PlayerState? previous;
lock (StateGate)
@@ -835,40 +569,15 @@ public static class AvPlayerExports
Players[handle] = new PlayerState
{
Handle = handle,
IsGen5 = isGen5,
Width = width,
Height = height,
DurationMilliseconds = durationMilliseconds,
HasAudio = hasAudio,
FramesPerSecond = framesPerSecond,
AllocateTextureCallback = allocateTextureCallback,
AllocateCallback = allocateCallback,
};
}
previous?.Dispose();
}
internal static bool AllocateGuestVideoBuffersForTest(
CpuContext ctx,
ulong handle,
out ulong firstBuffer)
{
lock (StateGate)
{
if (!Players.TryGetValue(handle, out var player))
{
firstBuffer = 0;
return false;
}
var bufferSize = GetVideoBufferSize(player);
var allocated = AllocateGuestVideoBuffers(ctx, player, bufferSize);
firstBuffer = player.GuestBuffers[0];
return allocated && firstBuffer != 0;
}
}
internal static void RemovePlayerForTest(ulong handle)
{
PlayerState? player;
@@ -886,27 +595,23 @@ public static class AvPlayerExports
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceAvPlayer")]
public static int AvPlayerGetStreamInfo(CpuContext ctx) =>
GetStreamInfoCore(ctx);
GetStreamInfoCore(ctx, StreamInfoSize);
private static int GetStreamInfoCore(CpuContext ctx)
private static int GetStreamInfoCore(CpuContext ctx, int infoSize)
{
var streamIndex = unchecked((uint)ctx[CpuRegister.Rsi]);
var infoAddress = ctx[CpuRegister.Rdx];
lock (StateGate)
{
if (!Players.TryGetValue(ctx[CpuRegister.Rdi], out var player) ||
streamIndex > (player.HasAudio ? 1u : 0u) ||
infoAddress == 0 || player.Width <= 0 || player.Height <= 0)
streamIndex > 1 || infoAddress == 0 || player.Width <= 0 || player.Height <= 0)
{
return SetReturn(ctx, InvalidParameters);
}
var infoSize = GetLegacyStreamInfoSize(ctx.TargetGeneration);
Span<byte> info = stackalloc byte[infoSize];
info.Clear();
BinaryPrimitives.WriteUInt32LittleEndian(
info[0..],
GetStreamType(ctx.TargetGeneration, streamIndex));
BinaryPrimitives.WriteUInt32LittleEndian(info[0..], streamIndex); // 0=video, 1=audio
if (streamIndex == 0)
{
BinaryPrimitives.WriteUInt32LittleEndian(info[8..], checked((uint)player.Width));
@@ -945,14 +650,7 @@ public static class AvPlayerExports
player = foundPlayer;
var hostPath = ResolveGuestPath(guestPath);
if (hostPath is null ||
!ProbeVideo(
hostPath,
out var width,
out var height,
out var fps,
out var duration,
out var hasAudio))
if (hostPath is null || !ProbeVideo(hostPath, out var width, out var height, out var fps, out var duration))
{
Console.Error.WriteLine($"[AVPLAYER][ERROR] Could not open guest video '{guestPath}' (resolved '{hostPath ?? "<none>"}').");
return SetReturn(ctx, OperationFailed);
@@ -964,13 +662,14 @@ public static class AvPlayerExports
player.Height = height;
player.FramesPerSecond = fps;
player.DurationMilliseconds = duration;
player.HasAudio = hasAudio;
player.Started = player.AutoStart;
autoStart = player.AutoStart;
Trace(
$"source guest='{guestPath}' host='{hostPath}' {width}x{height} " +
$"fps={fps:F3} duration_ms={duration} audio={hasAudio} auto_start={player.AutoStart}");
Trace($"source guest='{guestPath}' host='{hostPath}' {width}x{height} fps={fps:F3} duration_ms={duration} auto_start={player.AutoStart}");
}
EnsureGuestVideoBuffers(ctx, player);
NotifyEvent(ctx, player, 2); // StateReady
if (autoStart)
{
@@ -985,23 +684,12 @@ public static class AvPlayerExports
lock (StateGate)
{
if (!Players.TryGetValue(ctx[CpuRegister.Rdi], out var player) ||
infoAddress == 0 || !player.Started || player.EndOfStream ||
infoAddress == 0 || !player.Started || player.Paused || player.EndOfStream ||
player.SourcePath is null)
{
return SetReturn(ctx, 0);
}
if (player.Paused)
{
return SetReturn(
ctx,
player.IsGen5 &&
player.LastGuestBuffer != 0 &&
WriteHeldVideoFrameInfo(ctx, player, infoAddress, extended)
? 1
: 0);
}
if (!EnsureDecoder(player))
{
player.EndOfStream = true;
@@ -1043,7 +731,6 @@ public static class AvPlayerExports
{
return SetReturn(ctx, 0);
}
player.LastVideoTimestamp = timestamp;
Trace($"video_frame handle=0x{player.Handle:X16} ex={extended} ts={timestamp} data=0x{player.LastGuestBuffer:X16}");
return SetReturn(ctx, 1);
@@ -1169,10 +856,9 @@ public static class AvPlayerExports
return false;
}
var alignedWidth = AlignUp(player.Width, 16);
var alignedHeight = AlignUp(player.Height, 16);
var (pitch, bufferHeight) = GetFrameGeometry(player, extended);
var bufferStride = CalculateNv12BufferSize(pitch, bufferHeight);
var alignedWidth = AlignUp(player.Width, FramePitchAlignment);
var alignedHeight = AlignUp(player.Height, FrameHeightAlignment);
var bufferStride = GetVideoBufferSize(player);
if (player.GuestBuffers[0] == 0)
{
if (!AllocateGuestVideoBuffers(ctx, player, bufferStride))
@@ -1180,34 +866,12 @@ public static class AvPlayerExports
return false;
}
player.GuestBufferStride = bufferStride;
Trace(
$"video_layout ex={extended} width={player.Width} height={player.Height} " +
$"pitch={pitch} uv_offset={checked(pitch * bufferHeight)} size={bufferStride}");
}
var frameData = player.RawFrame;
if (extended)
if (!extended && (alignedWidth != player.Width || alignedHeight != player.Height))
{
if (player.PaddedFrame is null || player.PaddedFrame.Length != bufferStride)
{
player.PaddedFrame = new byte[bufferStride];
}
CopyNv12ToGuestBuffer(
player.RawFrame,
player.PaddedFrame,
player.Width,
player.Height,
player.Width,
player.Width,
pitch);
frameData = player.PaddedFrame;
}
else if (alignedWidth != player.Width || alignedHeight != player.Height)
{
if (player.PaddedFrame is null || player.PaddedFrame.Length != bufferStride)
{
player.PaddedFrame = new byte[bufferStride];
}
player.PaddedFrame ??= new byte[bufferStride];
player.PaddedFrame.AsSpan().Clear();
for (var row = 0; row < player.Height; row++)
{
@@ -1231,218 +895,44 @@ public static class AvPlayerExports
{
return false;
}
if (player.TextureAllocatorFailed)
{
EnsureFallbackPlayback(player);
if (player.FallbackPresentationPixels is null)
{
// Keep one immediate poster frame while the background decoder
// starts. Subsequent frames come from the bounded, scaled host
// playback; converting every 4K NV12 guest frame here would
// duplicate decoding work and dominate the emulation thread.
var bgra = GC.AllocateUninitializedArray<byte>(
checked(player.Width * player.Height * 4));
ConvertNv12ToBgra(
frameData,
pitch,
bufferHeight,
player.Width,
player.Height,
bgra);
player.FallbackPresentationPixels = bgra;
player.FallbackPresentationWidth = checked((uint)player.Width);
player.FallbackPresentationHeight = checked((uint)player.Height);
player.FallbackPresentationSerial =
Interlocked.Increment(ref _fallbackPresentationSerial);
player.SkipFirstFallbackPlaybackFrame =
player.FallbackPlayback is not null;
}
}
if (TraceVideoImages)
{
var traceIndex = Interlocked.Increment(ref _videoPayloadTraceCount);
if (traceIndex <= 16)
{
var summary = GuestImageUploadPayloadDiagnostics.Summarize(frameData);
Console.Error.WriteLine(
$"[AVPLAYER][TRACE] video_payload index={traceIndex - 1} " +
$"data=0x{bufferAddress:X16} bytes={frameData.Length} " +
$"pitch={pitch} uv_offset={checked(pitch * bufferHeight)} " +
$"nonzero_bytes={summary.NonzeroBytes}/{frameData.Length} " +
$"hash=0x{summary.Hash:X16}");
}
}
Span<byte> info = extended
? stackalloc byte[FrameInfoExSize]
: stackalloc byte[FrameInfoSize];
info.Clear();
WriteVideoFrameInfo(
info,
ctx.TargetGeneration,
extended,
bufferAddress,
timestamp,
checked((uint)pitch),
checked((uint)player.Width),
checked((uint)(extended ? player.Height : bufferHeight)),
checked((uint)pitch),
player.FramesPerSecond);
BinaryPrimitives.WriteUInt64LittleEndian(info[0..], bufferAddress);
BinaryPrimitives.WriteUInt64LittleEndian(info[16..], timestamp);
BinaryPrimitives.WriteUInt32LittleEndian(info[24..], checked((uint)(extended ? player.Width : alignedWidth)));
BinaryPrimitives.WriteUInt32LittleEndian(info[28..], checked((uint)(extended ? player.Height : alignedHeight)));
BinaryPrimitives.WriteSingleLittleEndian(info[32..], 1.0f);
if (extended)
{
BinaryPrimitives.WriteUInt32LittleEndian(info[60..], checked((uint)player.Width));
info[64] = 8;
info[65] = 8;
}
return ctx.Memory.TryWrite(infoAddress, info);
}
private static (int Pitch, int Height) GetFrameGeometry(
PlayerState player,
bool extended)
{
var gen5Extended = extended && player.IsGen5;
return (
gen5Extended ? CalculateNv12Pitch(player.Width) : AlignUp(player.Width, 16),
gen5Extended ? player.Height : AlignUp(player.Height, 16));
}
private static bool WriteHeldVideoFrameInfo(
CpuContext ctx,
PlayerState player,
ulong infoAddress,
bool extended)
{
var (pitch, bufferHeight) = GetFrameGeometry(player, extended);
Span<byte> info = extended
? stackalloc byte[FrameInfoExSize]
: stackalloc byte[FrameInfoSize];
info.Clear();
WriteVideoFrameInfo(
info,
ctx.TargetGeneration,
extended,
player.LastGuestBuffer,
player.LastVideoTimestamp,
checked((uint)pitch),
checked((uint)player.Width),
checked((uint)(extended ? player.Height : bufferHeight)),
checked((uint)pitch),
player.FramesPerSecond);
return ctx.Memory.TryWrite(infoAddress, info);
}
/// <summary>
/// The title-provided allocators can reject large decoded surfaces. In
/// that case the guest has no texture it can sample, and some titles pause
/// their AvPlayer after acquiring a poster frame. Keep that compatibility
/// path useful by running a separate, bounded host playback to completion.
/// MediaFramePlayback performs decode work off the Vulkan thread, advances
/// on the movie clock, drops frames when rendering is slow, and relinquishes
/// presentation automatically at EOF so normal guest rendering resumes.
/// </summary>
private static void EnsureFallbackPlayback(PlayerState player)
{
if (player.FallbackPlaybackAttempted || player.SourcePath is null)
{
return;
}
player.FallbackPlaybackAttempted = true;
var videoOptions = HostVideoHost.CurrentOptions;
var maximumWidth = checked((uint)videoOptions.Width);
var maximumHeight = checked((uint)videoOptions.Height);
if (!FfmpegVideoDecoder.TryOpen(
player.SourcePath,
maximumWidth,
maximumHeight,
out var decoder) ||
decoder is null)
{
Console.Error.WriteLine(
$"[AVPLAYER][WARN] Could not start host fallback playback for '{player.SourcePath}'.");
return;
}
player.FallbackPlayback = new MediaFramePlayback(decoder);
Trace(
$"host_fallback_started handle=0x{player.Handle:X16} " +
$"source={player.Width}x{player.Height} output={decoder.Width}x{decoder.Height} " +
$"host_limit={maximumWidth}x{maximumHeight} " +
$"fps={decoder.FramesPerSecondNumerator}/{decoder.FramesPerSecondDenominator}");
}
internal static int CalculateNv12Pitch(int width) =>
AlignUp(width, VideoPitchAlignment);
internal static int CalculateNv12BufferSize(int pitch, int height) =>
checked(pitch * height * 3 / 2);
internal static void ConvertNv12ToBgra(
ReadOnlySpan<byte> nv12,
int pitch,
int bufferHeight,
int width,
int height,
Span<byte> bgra)
{
var requiredNv12 = CalculateNv12BufferSize(pitch, bufferHeight);
var requiredBgra = checked(width * height * 4);
if (pitch < width || bufferHeight < height ||
nv12.Length < requiredNv12 || bgra.Length < requiredBgra)
{
throw new ArgumentException("NV12 frame dimensions do not match the supplied buffers.");
}
var chromaOffset = checked(pitch * bufferHeight);
for (var y = 0; y < height; y++)
{
var lumaRow = y * pitch;
var chromaRow = chromaOffset + ((y >> 1) * pitch);
var outputRow = y * width * 4;
for (var x = 0; x < width; x++)
{
var luma = nv12[lumaRow + x];
var chromaColumn = x & ~1;
var u = nv12[chromaRow + chromaColumn];
var v = nv12[chromaRow + chromaColumn + 1];
var c = Math.Max(0, luma - 16);
var d = u - 128;
var e = v - 128;
var output = outputRow + (x * 4);
bgra[output] = ClampToByte((298 * c + 516 * d + 128) >> 8);
bgra[output + 1] = ClampToByte((298 * c - 100 * d - 208 * e + 128) >> 8);
bgra[output + 2] = ClampToByte((298 * c + 409 * e + 128) >> 8);
bgra[output + 3] = byte.MaxValue;
}
}
}
private static byte ClampToByte(int value) =>
checked((byte)Math.Clamp(value, byte.MinValue, byte.MaxValue));
private static int GetVideoBufferSize(PlayerState player) =>
checked(
AlignUp(player.Width, FramePitchAlignment) *
AlignUp(player.Height, FrameHeightAlignment) * 3 / 2);
internal static void CopyNv12ToGuestBuffer(
ReadOnlySpan<byte> source,
Span<byte> destination,
int width,
int height,
int sourceLumaStride,
int sourceChromaStride,
int destinationPitch)
private static void EnsureGuestVideoBuffers(CpuContext ctx, PlayerState player)
{
var sourceChromaOffset = checked(sourceLumaStride * height);
var destinationChromaOffset = checked(destinationPitch * height);
var destinationSize = CalculateNv12BufferSize(destinationPitch, height);
destination[..destinationSize].Clear();
lock (StateGate)
{
if (player.GuestBuffers[0] != 0 || player.Width <= 0 || player.Height <= 0)
{
return;
}
for (var row = 0; row < height; row++)
{
source.Slice(row * sourceLumaStride, width)
.CopyTo(destination.Slice(row * destinationPitch, width));
}
for (var row = 0; row < height / 2; row++)
{
source.Slice(sourceChromaOffset + (row * sourceChromaStride), width)
.CopyTo(destination.Slice(destinationChromaOffset + (row * destinationPitch), width));
var bufferSize = GetVideoBufferSize(player);
if (AllocateGuestVideoBuffers(ctx, player, bufferSize))
{
player.GuestBufferStride = bufferSize;
}
}
}
@@ -1486,7 +976,6 @@ public static class AvPlayerExports
break;
}
player.GuestBuffers[index] = buffer;
RegisterVideoBuffer(buffer, bufferSize, index, "guest-callback");
Trace($"{kind}_buffer index={index} data=0x{buffer:X16} size={bufferSize}");
}
@@ -1495,6 +984,7 @@ public static class AvPlayerExports
return true;
}
}
player.TextureAllocatorFailed = true;
}
@@ -1509,7 +999,6 @@ public static class AvPlayerExports
for (var index = 0; index < player.GuestBuffers.Length; index++)
{
player.GuestBuffers[index] = bufferBase + checked((ulong)(index * bufferSize));
RegisterVideoBuffer(player.GuestBuffers[index], bufferSize, index, "hle-fallback");
}
Console.Error.WriteLine("[AVPLAYER][WARN] Guest texture allocator unavailable; using generic HLE memory.");
return true;
@@ -1520,14 +1009,12 @@ public static class AvPlayerExports
out int width,
out int height,
out double framesPerSecond,
out ulong durationMilliseconds,
out bool hasAudio)
out ulong durationMilliseconds)
{
width = 0;
height = 0;
framesPerSecond = 30.0;
durationMilliseconds = 0;
hasAudio = false;
if (!FfmpegMediaStream.TryProbe(path, out width, out height, out var rate, out var duration))
{
@@ -1544,10 +1031,6 @@ public static class AvPlayerExports
durationMilliseconds = checked((ulong)Math.Max(0, Math.Round(duration * 1000.0)));
}
hasAudio = FfmpegMediaStream.TryOpenAudio(path, out var audioStream) &&
audioStream is not null;
audioStream?.Dispose();
return width > 0 && height > 0 && framesPerSecond > 0;
}
@@ -1837,104 +1320,6 @@ public static class AvPlayerExports
return true;
}
internal static bool IsValidBgraFrame(
ReadOnlySpan<byte> pixels,
uint width,
uint height)
{
if (width == 0 || height == 0)
{
return false;
}
var requiredBytes = (ulong)width * height * 4;
return requiredBytes <= int.MaxValue &&
pixels.Length >= checked((int)requiredBytes);
}
internal static bool IsGen5Target(Generation generation) =>
(generation & Generation.Gen5) != 0;
internal static ulong GetAutoStartOffset(Generation generation, bool extended) =>
IsGen5Target(generation)
? extended ? 168UL : 112UL
: extended ? 164UL : 108UL;
internal static int GetLegacyStreamInfoSize(Generation generation) =>
IsGen5Target(generation)
? Gen5StreamInfoSize
: Gen4StreamInfoSize;
internal static uint GetStreamType(Generation generation, uint streamIndex) =>
IsGen5Target(generation)
? streamIndex + 1
: streamIndex;
internal static void WriteGen5StreamInfoEx(
Span<byte> info,
uint streamType,
uint width,
uint height,
double framesPerSecond,
ulong durationMilliseconds)
{
if (info.Length < StreamInfoExSize)
{
throw new ArgumentException(
$"Stream-info buffer must contain at least {StreamInfoExSize} bytes.",
nameof(info));
}
BinaryPrimitives.WriteUInt64LittleEndian(info[0..], StreamInfoExSize);
BinaryPrimitives.WriteUInt32LittleEndian(info[8..], streamType);
BinaryPrimitives.WriteUInt32LittleEndian(info[16..], width);
BinaryPrimitives.WriteUInt32LittleEndian(info[20..], height);
BinaryPrimitives.WriteDoubleLittleEndian(info[0x40..], framesPerSecond);
BinaryPrimitives.WriteUInt64LittleEndian(info[0x60..], durationMilliseconds);
}
internal static void WriteVideoFrameInfo(
Span<byte> info,
Generation generation,
bool extended,
ulong bufferAddress,
ulong timestamp,
uint width,
uint visibleWidth,
uint height,
uint pitch,
double framesPerSecond)
{
var requiredSize = extended ? FrameInfoExSize : FrameInfoSize;
if (info.Length < requiredSize)
{
throw new ArgumentException(
$"Frame-info buffer must contain at least {requiredSize} bytes.",
nameof(info));
}
BinaryPrimitives.WriteUInt64LittleEndian(info[0..], bufferAddress);
BinaryPrimitives.WriteUInt64LittleEndian(info[16..], timestamp);
BinaryPrimitives.WriteUInt32LittleEndian(info[24..], width);
BinaryPrimitives.WriteUInt32LittleEndian(info[28..], height);
BinaryPrimitives.WriteSingleLittleEndian(info[32..], 1.0f);
if (!extended)
{
return;
}
BinaryPrimitives.WriteUInt32LittleEndian(
info[48..],
width > visibleWidth ? width - visibleWidth : 0);
BinaryPrimitives.WriteUInt32LittleEndian(info[60..], pitch);
info[64] = 8;
info[65] = 8;
if (IsGen5Target(generation))
{
BinaryPrimitives.WriteDoubleLittleEndian(info[0x48..], framesPerSecond);
}
}
private static bool TryReadNullTerminatedUtf8(CpuContext ctx, ulong address, int maxLength, out string value)
{
value = string.Empty;
-567
View File
@@ -1,567 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Threading.Channels;
using FFmpeg.AutoGen;
using SharpEmu.Libs.VideoOut;
namespace SharpEmu.Libs.Codec;
/// <summary>
/// Owns one FFmpeg H.264 decode session for a single sceVideodec2 decoder
/// handle, feeding it pre-demuxed Annex-B access units from guest memory.
///
/// Three-stage pipeline, none of it on the guest thread:
/// Decode() -> AU queue -> decode worker -> frame queue -> scheduler -> Submit
///
/// The scheduler paces presentation to the stream's own framerate (no PTS
/// is available) instead of draining as fast as it decodes. Neither worker
/// thread may write to guest memory directly (the guest's stack slot may
/// already be reused by the time they finish), so readiness is reported via
/// TryConsumeProtocolReadySignal (metadata only) while pixels go straight
/// to VulkanVideoPresenter.Submit from the scheduler thread.
/// </summary>
internal sealed unsafe class Videodec2Decoder : IDisposable
{
// BGRA matches VulkanVideoPresenter.Submit; decode bypasses guest memory entirely.
private const AVPixelFormat OutputPixelFormat = AVPixelFormat.AV_PIX_FMT_BGRA;
// Enough lookahead to absorb decode jitter without adding visible latency.
private const int FrameQueueCapacity = 4;
// Fallback when the stream doesn't declare a usable framerate.
private const double FallbackFps = 30.0;
private static bool _rootPathInitialized;
private static readonly object InitGate = new();
private readonly object _gate = new();
private AVCodecContext* _codecContext;
private AVFrame* _frame;
private AVPacket* _packet;
private SwsContext* _swsContext;
private int _swsSourceWidth;
private int _swsSourceHeight;
private AVPixelFormat _swsSourceFormat = AVPixelFormat.AV_PIX_FMT_NONE;
private bool _disposed;
// Unbounded: access units are small, backpressure lives on the frame queue below.
private readonly Channel<byte[]?> _workChannel =
Channel.CreateUnbounded<byte[]?>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = true,
});
// Bounded and blocking-on-full: the backpressure that keeps decode paced to playback.
private readonly Channel<(byte[] Bgra, uint Width, uint Height)> _frameQueue =
Channel.CreateBounded<(byte[], uint, uint)>(new BoundedChannelOptions(FrameQueueCapacity)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = true,
});
private readonly Thread _worker;
private readonly Thread _scheduler;
// Cancelled (not just completed) on Dispose so both loops stop promptly instead of draining a backlog.
private readonly CancellationTokenSource _workerCts = new();
private readonly object _protocolGate = new();
private long _producedCount;
private long _reportedCount;
private uint _lastWidth;
private uint _lastHeight;
private Videodec2Decoder(AVCodecContext* codecContext, AVFrame* frame, AVPacket* packet)
{
_codecContext = codecContext;
_frame = frame;
_packet = packet;
_worker = new Thread(WorkerLoop)
{
IsBackground = true,
Name = "SharpEmu Videodec2 Worker",
};
_scheduler = new Thread(SchedulerLoop)
{
IsBackground = true,
Name = "SharpEmu Videodec2 Scheduler",
};
_worker.Start();
_scheduler.Start();
}
/// <summary>Opens a new H.264 session, or null if FFmpeg is unavailable or the decoder couldn't open.</summary>
public static Videodec2Decoder? TryCreate()
{
EnsureRootPathInitialized();
AVCodecContext* codecContext = null;
AVFrame* frame = null;
AVPacket* packet = null;
try
{
var codec = ffmpeg.avcodec_find_decoder(AVCodecID.AV_CODEC_ID_H264);
if (codec == null)
{
return null;
}
codecContext = ffmpeg.avcodec_alloc_context3(codec);
if (codecContext == null)
{
return null;
}
if (ffmpeg.avcodec_open2(codecContext, codec, null) < 0)
{
ffmpeg.avcodec_free_context(&codecContext);
return null;
}
frame = ffmpeg.av_frame_alloc();
packet = ffmpeg.av_packet_alloc();
if (frame == null || packet == null)
{
if (frame != null)
{
ffmpeg.av_frame_free(&frame);
}
if (packet != null)
{
ffmpeg.av_packet_free(&packet);
}
ffmpeg.avcodec_free_context(&codecContext);
return null;
}
return new Videodec2Decoder(codecContext, frame, packet);
}
catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException or TypeInitializationException)
{
// FFmpeg's native libraries are optional; missing ones degrade to the stub, not a crash.
if (codecContext != null)
{
ffmpeg.avcodec_free_context(&codecContext);
}
return null;
}
}
private static void EnsureRootPathInitialized()
{
if (_rootPathInitialized)
{
return;
}
lock (InitGate)
{
if (_rootPathInitialized)
{
return;
}
_rootPathInitialized = true;
// Must be set before any ffmpeg.* call, or bindings resolve against the empty default RootPath.
ffmpeg.RootPath = Path.Combine(AppContext.BaseDirectory, "plugins");
DynamicallyLoadedBindings.Initialize();
}
}
/// <summary>Hands one Annex-B access unit to the decode worker and returns immediately.</summary>
public void EnqueueAccessUnit(byte[] accessUnit)
{
_workChannel.Writer.TryWrite(accessUnit);
}
/// <summary>Queues an end-of-stream drain: flush FFmpeg and emit one more buffered picture, if any.</summary>
public void RequestDrain()
{
_workChannel.Writer.TryWrite(null);
}
/// <summary>Non-blocking: true exactly once per frame the worker has produced, in order.</summary>
public bool TryConsumeProtocolReadySignal(out uint width, out uint height)
{
lock (_protocolGate)
{
if (_reportedCount >= _producedCount)
{
width = 0;
height = 0;
return false;
}
_reportedCount++;
width = _lastWidth;
height = _lastHeight;
return true;
}
}
private void WorkerLoop()
{
var reader = _workChannel.Reader;
var token = _workerCts.Token;
while (true)
{
byte[]? item;
try
{
if (!reader.WaitToReadAsync(token).AsTask().GetAwaiter().GetResult())
{
return;
}
if (!reader.TryRead(out item))
{
continue;
}
}
catch (ChannelClosedException)
{
return;
}
catch (OperationCanceledException)
{
return;
}
var decodedOk = item is null
? DrainCoreLocked(out var bgraFrame, out var hasPicture, out var width, out var height)
: DecodeCoreLocked(item, out bgraFrame, out hasPicture, out width, out height);
if (!decodedOk || !hasPicture || bgraFrame is null)
{
continue;
}
try
{
// Blocks if the scheduler hasn't kept up; deliberate backpressure.
_frameQueue.Writer.WriteAsync((bgraFrame, width, height), token).AsTask().GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
return;
}
catch (ChannelClosedException)
{
return;
}
lock (_protocolGate)
{
_producedCount++;
_lastWidth = width;
_lastHeight = height;
}
}
}
private void SchedulerLoop()
{
var reader = _frameQueue.Reader;
var token = _workerCts.Token;
var haveDeadline = false;
var nextDeadline = DateTime.MinValue;
var frameInterval = TimeSpan.FromSeconds(1.0 / FallbackFps);
while (true)
{
(byte[] Bgra, uint Width, uint Height) item;
try
{
if (!reader.WaitToReadAsync(token).AsTask().GetAwaiter().GetResult())
{
return;
}
if (!reader.TryRead(out item))
{
continue;
}
}
catch (ChannelClosedException)
{
return;
}
catch (OperationCanceledException)
{
return;
}
if (!haveDeadline)
{
// Framerate isn't known until FFmpeg parses the first frame's SPS/VUI.
var rate = _codecContext->framerate;
var fps = rate.den > 0 && rate.num > 0
? (double)rate.num / rate.den
: FallbackFps;
frameInterval = TimeSpan.FromSeconds(1.0 / fps);
nextDeadline = DateTime.UtcNow;
haveDeadline = true;
}
var now = DateTime.UtcNow;
if (nextDeadline > now)
{
try
{
Task.Delay(nextDeadline - now, token).GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
return;
}
}
VulkanVideoPresenter.Submit(item.Bgra, item.Width, item.Height);
nextDeadline += frameInterval;
// Resync to "now" if we fell behind, instead of burning through a deadline backlog unpaced.
if (nextDeadline < DateTime.UtcNow)
{
nextDeadline = DateTime.UtcNow;
}
}
}
/// <summary>Feeds one access unit and converts the resulting picture to BGRA, if any. Decode-worker thread only.</summary>
private bool DecodeCoreLocked(
byte[] accessUnit,
out byte[]? bgraFrame,
out bool hasPicture,
out uint width,
out uint height)
{
bgraFrame = null;
hasPicture = false;
width = 0;
height = 0;
lock (_gate)
{
if (_disposed)
{
return false;
}
ffmpeg.av_packet_unref(_packet);
var buffer = ffmpeg.av_malloc((nuint)accessUnit.Length + (nuint)ffmpeg.AV_INPUT_BUFFER_PADDING_SIZE);
if (buffer == null)
{
return false;
}
fixed (byte* source = accessUnit)
{
Buffer.MemoryCopy(source, buffer, accessUnit.Length, accessUnit.Length);
}
new Span<byte>((byte*)buffer + accessUnit.Length, ffmpeg.AV_INPUT_BUFFER_PADDING_SIZE).Clear();
_packet->data = (byte*)buffer;
_packet->size = accessUnit.Length;
var sendResult = ffmpeg.avcodec_send_packet(_codecContext, _packet);
ffmpeg.av_freep(&buffer);
_packet->data = null;
_packet->size = 0;
if (sendResult < 0 && sendResult != ffmpeg.AVERROR(ffmpeg.EAGAIN))
{
return false;
}
var receiveResult = ffmpeg.avcodec_receive_frame(_codecContext, _frame);
if (receiveResult == ffmpeg.AVERROR(ffmpeg.EAGAIN) || receiveResult == ffmpeg.AVERROR_EOF)
{
return true;
}
if (receiveResult < 0)
{
return false;
}
try
{
bgraFrame = ConvertFrameToBgraLocked(out width, out height);
if (bgraFrame == null)
{
return false;
}
hasPicture = true;
return true;
}
finally
{
ffmpeg.av_frame_unref(_frame);
}
}
}
/// <summary>Signals end-of-stream and pulls one remaining buffered frame, if any. Decode-worker thread only.</summary>
private bool DrainCoreLocked(out byte[]? bgraFrame, out bool hasPicture, out uint width, out uint height)
{
bgraFrame = null;
hasPicture = false;
width = 0;
height = 0;
lock (_gate)
{
if (_disposed)
{
return false;
}
var sendResult = ffmpeg.avcodec_send_packet(_codecContext, null);
if (sendResult < 0 && sendResult != ffmpeg.AVERROR_EOF)
{
return false;
}
var receiveResult = ffmpeg.avcodec_receive_frame(_codecContext, _frame);
if (receiveResult == ffmpeg.AVERROR(ffmpeg.EAGAIN) || receiveResult == ffmpeg.AVERROR_EOF)
{
return true;
}
if (receiveResult < 0)
{
return false;
}
try
{
bgraFrame = ConvertFrameToBgraLocked(out width, out height);
if (bgraFrame == null)
{
return false;
}
hasPicture = true;
return true;
}
finally
{
ffmpeg.av_frame_unref(_frame);
}
}
}
/// <summary>Converts <see cref="_frame"/> to a tightly packed width*height*4 BGRA buffer, or null on failure.</summary>
private byte[]? ConvertFrameToBgraLocked(out uint width, out uint height)
{
width = (uint)_frame->width;
height = (uint)_frame->height;
var sourceFormat = (AVPixelFormat)_frame->format;
if (_swsContext == null ||
_swsSourceWidth != _frame->width ||
_swsSourceHeight != _frame->height ||
_swsSourceFormat != sourceFormat)
{
if (_swsContext != null)
{
ffmpeg.sws_freeContext(_swsContext);
}
_swsContext = ffmpeg.sws_getContext(
_frame->width, _frame->height, sourceFormat,
_frame->width, _frame->height, OutputPixelFormat,
ffmpeg.SWS_BILINEAR, null, null, null);
if (_swsContext == null)
{
return null;
}
_swsSourceWidth = _frame->width;
_swsSourceHeight = _frame->height;
_swsSourceFormat = sourceFormat;
}
var bgraFrame = new byte[checked((int)(width * height * 4))];
fixed (byte* destinationPtr = bgraFrame)
{
var dstData = new byte_ptrArray4();
var dstLinesize = new int_array4();
ffmpeg.av_image_fill_arrays(
ref dstData, ref dstLinesize, destinationPtr,
OutputPixelFormat, _frame->width, _frame->height, 1);
var srcData = new byte_ptrArray8();
var srcLinesize = new int_array8();
for (var i = 0; i < 4; i++)
{
srcData[(uint)i] = _frame->data[(uint)i];
srcLinesize[(uint)i] = _frame->linesize[(uint)i];
}
ffmpeg.sws_scale(
_swsContext, srcData, srcLinesize, 0, _frame->height,
dstData, dstLinesize);
}
return bgraFrame;
}
public void Dispose()
{
lock (_gate)
{
if (_disposed)
{
return;
}
_disposed = true;
}
// Outside _gate: the worker needs it to finish whatever item it's mid-call on.
_workerCts.Cancel();
_workChannel.Writer.TryComplete();
_frameQueue.Writer.TryComplete();
_worker.Join(TimeSpan.FromSeconds(2));
_scheduler.Join(TimeSpan.FromSeconds(2));
_workerCts.Dispose();
lock (_gate)
{
if (_swsContext != null)
{
ffmpeg.sws_freeContext(_swsContext);
_swsContext = null;
}
if (_packet != null)
{
var packet = _packet;
ffmpeg.av_packet_free(&packet);
_packet = null;
}
if (_frame != null)
{
var frame = _frame;
ffmpeg.av_frame_free(&frame);
_frame = null;
}
if (_codecContext != null)
{
var codecContext = _codecContext;
ffmpeg.avcodec_free_context(&codecContext);
_codecContext = null;
}
}
}
}
-246
View File
@@ -1,246 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Concurrent;
using SharpEmu.HLE;
namespace SharpEmu.Libs.Codec;
/// <summary>
/// libSceVideodec2 (hardware compute-based decoder). sceVideodec2Decode
/// feeds a real FFmpeg H.264 session (Videodec2Decoder) when one can be
/// opened, falling back to the original "no picture" stub otherwise.
/// </summary>
public static class Videodec2Exports
{
private const int Ok = 0;
// Null entry = TryCreate() failed; every export falls back to the stub for that handle.
private static readonly ConcurrentDictionary<ulong, Videodec2Decoder?> Decoders = new();
private static long _nextDecoderHandle = unchecked((long)DecoderToken);
[SysAbiExport(
Nid = "RnDibcGCPKw",
ExportName = "sceVideodec2QueryComputeMemoryInfo",
Target = Generation.Gen5,
LibraryName = "libSceVideodec2")]
public static int Videodec2QueryComputeMemoryInfo(CpuContext ctx)
{
var paramAddress = ctx[CpuRegister.Rdi];
if (paramAddress == 0)
{
return SetReturn(ctx, VideodecErrorInvalidArg);
}
// Success needs no memory writes; the game initializes from its own fields.
return SetReturn(ctx, Ok);
}
private const int VideodecErrorInvalidArg = unchecked((int)0x80620801);
// Reject garbage/not-yet-primed struct reads before they reach `new byte[...]`.
private const ulong MaxPlausibleAuBytes = 32UL * 1024 * 1024;
private const ulong MaxPlausibleSlotBytes = 64UL * 1024 * 1024;
// Opaque token the game hands back unmodified to later Videodec2 calls.
private const ulong ComputeQueueToken = 0x56D2_C0DE_0001UL;
[SysAbiExport(
Nid = "eD+X2SmxUt4",
ExportName = "sceVideodec2AllocateComputeQueue",
Target = Generation.Gen5,
LibraryName = "libSceVideodec2")]
public static int Videodec2AllocateComputeQueue(CpuContext ctx)
{
var queueAddress = ctx[CpuRegister.Rdi];
if (queueAddress == 0 || !ctx.TryWriteUInt64(queueAddress, ComputeQueueToken))
{
return SetReturn(ctx, VideodecErrorInvalidArg);
}
return SetReturn(ctx, Ok);
}
// A zero size at +0x08/+0x28 makes the game skip its own arena allocation cleanly.
[SysAbiExport(
Nid = "qqMCwlULR+E",
ExportName = "sceVideodec2QueryDecoderMemoryInfo",
Target = Generation.Gen5,
LibraryName = "libSceVideodec2")]
public static int Videodec2QueryDecoderMemoryInfo(CpuContext ctx)
{
var memoryInfoAddress = ctx[CpuRegister.Rsi];
if (memoryInfoAddress == 0 ||
!ctx.TryWriteUInt64(memoryInfoAddress + 0x08, 0) ||
!ctx.TryWriteUInt64(memoryInfoAddress + 0x28, 0) ||
// Frame-slot size: must be nonzero or the game divides its arena by zero.
!ctx.TryWriteUInt64(memoryInfoAddress + 0x38, 0x1000))
{
return SetReturn(ctx, VideodecErrorInvalidArg);
}
return SetReturn(ctx, Ok);
}
private const ulong DecoderToken = 0x56D2_C0DE_0002UL;
// Handle is opaque to the game; a monotonic counter seeded at the old fixed token.
[SysAbiExport(
Nid = "CNNRoRYd8XI",
ExportName = "sceVideodec2CreateDecoder",
Target = Generation.Gen5,
LibraryName = "libSceVideodec2")]
public static int Videodec2CreateDecoder(CpuContext ctx)
{
var decoderAddress = ctx[CpuRegister.Rdx];
if (decoderAddress == 0)
{
return SetReturn(ctx, VideodecErrorInvalidArg);
}
var handle = unchecked((ulong)Interlocked.Increment(ref _nextDecoderHandle));
Decoders[handle] = Videodec2Decoder.TryCreate();
if (!ctx.TryWriteUInt64(decoderAddress, handle))
{
Decoders.TryRemove(handle, out var created);
created?.Dispose();
return SetReturn(ctx, VideodecErrorInvalidArg);
}
return SetReturn(ctx, Ok);
}
// Clearing the picture-ready byte at [rdx] tells the player "no buffered pictures remain".
[SysAbiExport(
Nid = "l1hXwscLuCY",
ExportName = "sceVideodec2Flush",
Target = Generation.Gen5,
LibraryName = "libSceVideodec2")]
public static int Videodec2Flush(CpuContext ctx)
{
var handle = ctx[CpuRegister.Rdi];
var outputInfoAddress = ctx[CpuRegister.Rdx];
if (outputInfoAddress == 0 || !ctx.Memory.TryWrite(outputInfoAddress, NoPicture))
{
return SetReturn(ctx, VideodecErrorInvalidArg);
}
if (Decoders.TryGetValue(handle, out var decoder) && decoder is not null)
{
// Drain in order: report an already-finished frame before queuing a new drain request.
if (decoder.TryConsumeProtocolReadySignal(out var width, out var height))
{
if (ctx.TryWriteUInt64(outputInfoAddress + 0x08, width) &&
ctx.TryWriteUInt64(outputInfoAddress + 0x10, height))
{
_ = ctx.Memory.TryWrite(outputInfoAddress, PictureReady);
}
}
else
{
decoder.RequestDrain();
}
}
return SetReturn(ctx, Ok);
}
// No state to reset.
[SysAbiExport(
Nid = "wJXikG6QFN8",
ExportName = "sceVideodec2Reset",
Target = Generation.Gen5,
LibraryName = "libSceVideodec2")]
public static int Videodec2Reset(CpuContext ctx)
{
return SetReturn(ctx, Ok);
}
[SysAbiExport(
Nid = "jwImxXRGSKA",
ExportName = "sceVideodec2DeleteDecoder",
Target = Generation.Gen5,
LibraryName = "libSceVideodec2")]
public static int Videodec2DeleteDecoder(CpuContext ctx)
{
var handle = ctx[CpuRegister.Rdi];
if (Decoders.TryRemove(handle, out var decoder))
{
decoder?.Dispose();
}
return SetReturn(ctx, Ok);
}
// rcx[0] is the picture-ready flag (1 = frame published); it lives in
// uninitialized stack and must always be written explicitly.
[SysAbiExport(
Nid = "852F5+q6+iM",
ExportName = "sceVideodec2Decode",
Target = Generation.Gen5,
LibraryName = "libSceVideodec2")]
public static int Videodec2Decode(CpuContext ctx)
{
var handle = ctx[CpuRegister.Rdi];
var inputAuStruct = ctx[CpuRegister.Rsi];
var outputSlotObj = ctx[CpuRegister.Rdx];
var outputInfoAddress = ctx[CpuRegister.Rcx];
if (outputInfoAddress == 0 || !ctx.Memory.TryWrite(outputInfoAddress, NoPicture))
{
return SetReturn(ctx, VideodecErrorInvalidArg);
}
if (!Decoders.TryGetValue(handle, out var decoder) || decoder is null)
{
// No real decoder for this handle: stub behavior, "fed the AU, no picture".
return SetReturn(ctx, Ok);
}
if (inputAuStruct == 0 ||
!ctx.TryReadUInt64(inputAuStruct + 0x08, out var auDataPtr) ||
!ctx.TryReadUInt64(inputAuStruct + 0x10, out var auDataSize) ||
auDataPtr == 0 || auDataSize == 0 || auDataSize > MaxPlausibleAuBytes ||
outputSlotObj == 0 ||
!ctx.TryReadUInt64(outputSlotObj + 0x08, out var slotPtr) ||
!ctx.TryReadUInt64(outputSlotObj + 0x10, out var slotSize) ||
slotPtr == 0 || slotSize == 0 || slotSize > MaxPlausibleSlotBytes)
{
// Nothing sane to feed/fill this call; not an error.
return SetReturn(ctx, Ok);
}
var auBuffer = new byte[auDataSize];
if (!ctx.Memory.TryRead(auDataPtr, auBuffer))
{
return SetReturn(ctx, Ok);
}
// Queues the AU and returns immediately; decode/present happen on Videodec2Decoder's own threads.
decoder.EnqueueAccessUnit(auBuffer);
if (!decoder.TryConsumeProtocolReadySignal(out var width, out var height))
{
return SetReturn(ctx, Ok);
}
if (!ctx.TryWriteUInt64(outputInfoAddress + 0x08, width) ||
!ctx.TryWriteUInt64(outputInfoAddress + 0x10, height) ||
!ctx.Memory.TryWrite(outputInfoAddress, PictureReady))
{
return SetReturn(ctx, Ok);
}
return SetReturn(ctx, Ok);
}
private static readonly byte[] NoPicture = [0];
private static readonly byte[] PictureReady = [1];
private static int SetReturn(CpuContext ctx, int result)
{
ctx[CpuRegister.Rax] = unchecked((ulong)result);
return result;
}
}
-12
View File
@@ -23,10 +23,6 @@ internal static class GuestDataPool
public static void Trim() => ((BoundedByteArrayPool)Shared).Trim();
/// <summary>Outstanding lease count and idle cached bytes, for leak diagnostics.</summary>
public static (int LeaseCount, ulong CachedBytes) DiagnosticStats() =>
((BoundedByteArrayPool)Shared).Stats();
private sealed class BoundedByteArrayPool : ArrayPool<byte>
{
private readonly object _gate = new();
@@ -123,14 +119,6 @@ internal static class GuestDataPool
}
}
public (int LeaseCount, ulong CachedBytes) Stats()
{
lock (_gate)
{
return (_leases.Count, _cachedBytes);
}
}
private int GetAllocationLength(int minimumLength)
{
if (minimumLength <= 16)
-21
View File
@@ -1,21 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Libs;
/// <summary>
/// Key equivalence for caches and comparisons over <em>host</em> filesystem
/// paths. Windows resolves names case-insensitively, but Linux hosts are
/// case-sensitive and the guest filesystem is too, so a dump can legitimately
/// contain "DATA.BIN" alongside "Data.bin". An ignore-case cache aliases those
/// distinct files into one entry there, which silently serves the wrong bytes
/// or drops one of them entirely.
/// </summary>
internal static class HostFsPath
{
public static readonly StringComparer Comparer =
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
public static readonly StringComparison Comparison =
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
}
@@ -1070,29 +1070,15 @@ public static class KernelEventQueueCompatExports
_pendingEvents[handle] = queue;
}
// GPU interrupt events must not coalesce: the AGC driver's
// interrupt thread accounts exactly one completion per
// delivered kevent (it never reads the kevent payload), so
// merging N triggers into one pending entry silently drops
// N-1 completions and wedges its dependency counters. Queue
// a distinct entry per trigger, with a defensive cap so an
// undrained queue cannot grow without bound.
var queuedEvent = new KernelQueuedEvent(
registration.Ident,
registration.Filter,
registration.Flags,
1,
data,
registration.UserData);
if (CountPendingEvents(queue, registration.Ident, registration.Filter) < 256)
{
queue.AddLast(queuedEvent);
}
else
{
QueueOrUpdateEvent(queue, queuedEvent);
}
QueueOrUpdateEvent(
queue,
new KernelQueuedEvent(
registration.Ident,
registration.Filter,
registration.Flags,
1,
data,
registration.UserData));
(wakeQueues ??= []).Add(state);
triggeredCount++;
@@ -1318,24 +1304,6 @@ public static class KernelEventQueueCompatExports
}
}
private static int CountPendingEvents(
KernelEventDeque queue,
ulong ident,
short filter)
{
var count = 0;
for (var i = 0; i < queue.Count; i++)
{
var pending = queue[i];
if (pending.Ident == ident && pending.Filter == filter)
{
count++;
}
}
return count;
}
private static void QueueOrUpdateEvent(
KernelEventDeque queue,
KernelQueuedEvent queuedEvent)
-41
View File
@@ -466,45 +466,4 @@ public static class KernelExports
ctx[CpuRegister.Rax] = unchecked((ulong)(-1L));
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
[SysAbiExport(
Nid = "tU5e3f9gSiU",
ExportName = "sceKernelIsTrinityMode",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libKernel")]
public static int KernelIsTrinityMode(CpuContext ctx)
{
ctx[CpuRegister.Rax] = 0;
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
[SysAbiExport(
Nid = "DLORcroUqbc",
ExportName = "sceKernelGetOpenPsId",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libKernel")]
public static int KernelGetOpenPsId(CpuContext ctx)
{
ulong bufferPtr = ctx[CpuRegister.Rdi];
if (bufferPtr == 0)
{
ctx[CpuRegister.Rax] = unchecked((ulong)(int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
}
Span<byte> openPsId = stackalloc byte[16];
if (!ctx.Memory.TryWrite(bufferPtr, openPsId))
{
ctx[CpuRegister.Rax] = unchecked((ulong)(int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
}
ctx[CpuRegister.Rax] = 0;
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
}
@@ -117,12 +117,17 @@ public static partial class KernelMemoryCompatExports
private static readonly Dictionary<string, string> _guestMounts = new(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> _tracedStatResults = new(StringComparer.Ordinal);
// Both caches memoize host filesystem probe outcomes, so their key
// equivalence must match the host filesystem's — see HostFsPath. On a
// case-sensitive host an ignore-case cache aliases distinct paths: a
// cached miss for "/app0/DATA.BIN" keeps answering NOT_FOUND for
// "/app0/Data.bin" even though that file exists.
private static readonly HashSet<string> _negativeStatCache = new(HostFsPath.Comparer);
private static readonly ConcurrentDictionary<string, ulong> _aprFileSizeCache = new(HostFsPath.Comparer);
// equivalence must match the host filesystem's: Windows resolves names
// case-insensitively, but Linux hosts are case-sensitive, and an
// ignore-case cache there aliases distinct paths — a cached miss for
// "/app0/DATA.BIN" keeps answering NOT_FOUND for "/app0/Data.bin" even
// though that file exists and a fresh probe would find it.
private static readonly StringComparer HostFsPathComparer =
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
private static readonly StringComparison HostFsPathComparison =
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
private static readonly HashSet<string> _negativeStatCache = new(HostFsPathComparer);
private static readonly ConcurrentDictionary<string, ulong> _aprFileSizeCache = new(HostFsPathComparer);
private static long _nextFileDescriptor = 2;
private static string _applicationTitleId = "UNKNOWN";
@@ -5198,8 +5203,8 @@ public static partial class KernelMemoryCompatExports
// host would let a relative path escape into a sibling directory that
// differs from the mount root only by case (root ".../Save" vs
// sibling ".../save").
if (!string.Equals(candidate, matchedHostRoot, HostFsPath.Comparison) &&
!candidate.StartsWith(rootWithSeparator, HostFsPath.Comparison))
if (!string.Equals(candidate, matchedHostRoot, HostFsPathComparison) &&
!candidate.StartsWith(rootWithSeparator, HostFsPathComparison))
{
return false;
}
@@ -5300,8 +5305,8 @@ public static partial class KernelMemoryCompatExports
var rootWithSeparator =
Path.TrimEndingDirectorySeparator(fullRoot) + Path.DirectorySeparatorChar;
if (!string.Equals(candidate, fullRoot, HostFsPath.Comparison) &&
!candidate.StartsWith(rootWithSeparator, HostFsPath.Comparison))
if (!string.Equals(candidate, fullRoot, HostFsPathComparison) &&
!candidate.StartsWith(rootWithSeparator, HostFsPathComparison))
{
return string.Empty;
}
@@ -5327,7 +5332,7 @@ public static partial class KernelMemoryCompatExports
private static bool EscapesMountViaReparsePoint(string mountRoot, string candidate)
{
var rootTrimmed = Path.TrimEndingDirectorySeparator(mountRoot);
if (string.Equals(candidate, rootTrimmed, HostFsPath.Comparison))
if (string.Equals(candidate, rootTrimmed, HostFsPathComparison))
{
return false;
}
@@ -918,8 +918,15 @@ public static class KernelPthreadCompatExports
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_BUSY;
}
TracePthreadMutex(ctx, "lock", mutexAddress, resolvedAddress, state, currentThreadId, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_DEADLOCK);
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_DEADLOCK;
// Several Gen5 runtimes layer their own owner/count bookkeeping
// over a NORMAL kernel mutex. Returning EDEADLK here
// leaves that guest bookkeeping out of sync with the HLE owner and
// turns the wrapper into a permanent lock/unlock retry loop. Keep
// the compatibility recursion used by the original implementation;
// ERRORCHECK mutexes still take the strict EDEADLK path below.
state.RecursionCount++;
TracePthreadMutex(ctx, "lock", mutexAddress, resolvedAddress, state, currentThreadId, (int)OrbisGen2Result.ORBIS_GEN2_OK);
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
else
{
@@ -1257,15 +1264,15 @@ public static class KernelPthreadCompatExports
return CreateImplicitMutexState(ctx, mutexAddress, MutexTypeAdaptiveNp, out resolvedAddress, out state);
}
if (pointedHandle != 0 && pointedHandle != mutexAddress && _mutexStates.TryGetValue(pointedHandle, out state))
{
_mutexStates[mutexAddress] = state;
resolvedAddress = pointedHandle;
return true;
}
if (pointedHandle != 0)
{
if (_mutexStates.TryGetValue(pointedHandle, out state))
{
_mutexStates.TryAdd(mutexAddress, state);
resolvedAddress = pointedHandle;
return true;
}
resolvedAddress = pointedHandle;
return false;
}
-9
View File
@@ -99,15 +99,6 @@ public static class NpTrophy2Exports
public static int NpTrophy2GetTrophyInfo(CpuContext ctx) =>
SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND);
[SysAbiExport(
Nid = "y3zHpdZO6ME",
ExportName = "sceNpTrophy2GetTrophyInfoArray",
Target = Generation.Gen5,
LibraryName = "libSceNpTrophy2")]
public static int NpTrophy2GetTrophyInfoArray(CpuContext ctx) =>
SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND);
private static int WriteIdAndReturn(CpuContext ctx, ulong outAddress, ref int nextId)
{
if (outAddress == 0)
-1
View File
@@ -24,7 +24,6 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ItemGroup>
<InternalsVisibleTo Include="SharpEmu.Libs.Tests" />
<!-- SharpEmu.Core's stall watchdog reads GpuWaitRegistry for diagnostics. -->
<InternalsVisibleTo Include="SharpEmu.Core" />
</ItemGroup>
@@ -1,36 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Diagnostics;
using System.Threading;
namespace SharpEmu.Libs.VideoOut;
public static class FlipProgressTracker
{
private static long _lastFlipTimestamp;
private static long _lastFlipVersion;
private static int _hasFlipped;
public static void RecordFlip(long version)
{
Volatile.Write(ref _lastFlipVersion, version);
Volatile.Write(ref _lastFlipTimestamp, Stopwatch.GetTimestamp());
Volatile.Write(ref _hasFlipped, 1);
}
public static bool HasFlipped => Volatile.Read(ref _hasFlipped) != 0;
public static long LastFlipVersion => Volatile.Read(ref _lastFlipVersion);
public static double? SecondsSinceLastFlip()
{
if (Volatile.Read(ref _hasFlipped) == 0)
{
return null;
}
var elapsedTicks = Stopwatch.GetTimestamp() - Volatile.Read(ref _lastFlipTimestamp);
return elapsedTicks / (double)Stopwatch.Frequency;
}
}
@@ -1,23 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Libs.VideoOut;
internal static class GuestImageUploadPayloadDiagnostics
{
internal static (long NonzeroBytes, ulong Hash) Summarize(ReadOnlySpan<byte> pixels)
{
const ulong offsetBasis = 14695981039346656037UL;
const ulong prime = 1099511628211UL;
var nonzeroBytes = 0L;
var hash = offsetBasis;
foreach (var value in pixels)
{
nonzeroBytes += value == 0 ? 0 : 1;
hash = (hash ^ value) * prime;
}
return (nonzeroBytes, hash);
}
}
@@ -59,14 +59,9 @@ public sealed record HostVideoOptions
public static class HostVideoHost
{
private static HostVideoOptions _currentOptions = HostVideoOptions.Default;
public static HostVideoOptions CurrentOptions => Volatile.Read(ref _currentOptions);
public static bool TryConfigureVideo(HostVideoOptions options)
{
var normalized = options.Normalize();
Volatile.Write(ref _currentOptions, normalized);
return VulkanVideoPresenter.TryConfigureVideo(normalized) &
MetalVideoPresenter.TryConfigureVideo(normalized);
}
@@ -1,275 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Runtime.InteropServices;
namespace SharpEmu.Libs.VideoOut;
public static unsafe class RenderDocCapture
{
private const int ApiVersion1_4_2 = 10402;
private const int IndexUnloadCrashHandler = 10;
private const int IndexSetCaptureFilePathTemplate = 11;
private const int IndexGetNumCaptures = 13;
private const int IndexGetCapture = 14;
private const int IndexStartFrameCapture = 19;
private const int IndexIsFrameCapturing = 20;
private const int IndexEndFrameCapture = 21;
private const int StateIdle = 0;
private const int StateRequested = 1;
private const int StateCapturing = 2;
private static IntPtr* _api;
private static int _state = StateIdle;
private static bool _initialized;
public static bool IsAvailable => _api is not null;
public static void Initialize()
{
if (_initialized)
{
return;
}
_initialized = true;
if (!string.Equals(
Environment.GetEnvironmentVariable("SHARPEMU_RENDERDOC"),
"1",
StringComparison.Ordinal))
{
return;
}
if (!TryLoadLibrary(out var module))
{
Console.Error.WriteLine(
"[LOADER][WARN] renderdoc: SHARPEMU_RENDERDOC=1 was set but renderdoc.dll could not be loaded.");
return;
}
if (!NativeLibrary.TryGetExport(module, "RENDERDOC_GetAPI", out var getApiAddress))
{
Console.Error.WriteLine(
"[LOADER][WARN] renderdoc: RENDERDOC_GetAPI is missing; in-app capture disabled.");
return;
}
void* api = null;
var getApi = (delegate* unmanaged[Cdecl]<int, void**, int>)getApiAddress;
if (getApi(ApiVersion1_4_2, &api) != 1 || api is null)
{
Console.Error.WriteLine(
"[LOADER][WARN] renderdoc: API 1.4.2 unavailable; in-app capture disabled.");
return;
}
_api = (IntPtr*)api;
((delegate* unmanaged[Cdecl]<void>)_api[IndexUnloadCrashHandler])();
Console.Error.WriteLine(
"[LOADER][INFO] renderdoc: in-app capture ready. Press F10 to capture the next presented frame.");
}
public static void SetCaptureDirectory(string titleId)
{
if (_api is null)
{
return;
}
var safeTitleId = string.IsNullOrWhiteSpace(titleId) ? "UNKNOWN" : titleId.Trim();
foreach (var invalid in Path.GetInvalidFileNameChars())
{
safeTitleId = safeTitleId.Replace(invalid, '_');
}
try
{
var directory = Path.Combine(
AppContext.BaseDirectory,
"user",
"logs",
"capture_logs",
safeTitleId);
Directory.CreateDirectory(directory);
var template = Path.Combine(directory, safeTitleId);
var bytes = System.Text.Encoding.UTF8.GetBytes(template + "\0");
fixed (byte* pointer = bytes)
{
((delegate* unmanaged[Cdecl]<byte*, void>)_api[IndexSetCaptureFilePathTemplate])(
pointer);
}
Console.Error.WriteLine(
$"[LOADER][INFO] renderdoc: captures will be written under '{directory}'.");
}
catch (Exception exception)
{
Console.Error.WriteLine(
$"[LOADER][WARN] renderdoc: could not set the capture directory: {exception.Message}");
}
}
public static void RequestCapture()
{
if (_api is null)
{
return;
}
if (Interlocked.CompareExchange(ref _state, StateRequested, StateIdle) == StateIdle)
{
Console.Error.WriteLine(
"[LOADER][INFO] renderdoc: capture requested; the next complete presented frame will be captured.");
}
}
public static void OnPresent()
{
if (_api is null)
{
return;
}
switch (Volatile.Read(ref _state))
{
case StateIdle:
return;
case StateRequested:
if (IsFrameCapturing())
{
Volatile.Write(ref _state, StateIdle);
return;
}
StartFrameCapture();
if (!IsFrameCapturing())
{
Console.Error.WriteLine(
"[LOADER][WARN] renderdoc: StartFrameCapture did not begin a capture.");
Volatile.Write(ref _state, StateIdle);
return;
}
Volatile.Write(ref _state, StateCapturing);
return;
case StateCapturing:
var captured = EndFrameCapture() != 0;
Volatile.Write(ref _state, StateIdle);
if (captured)
{
LogNewestCapture();
}
else
{
Console.Error.WriteLine("[LOADER][WARN] renderdoc: EndFrameCapture failed.");
}
return;
}
}
private static void StartFrameCapture() =>
((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)_api[IndexStartFrameCapture])(
IntPtr.Zero,
IntPtr.Zero);
private static bool IsFrameCapturing() =>
((delegate* unmanaged[Cdecl]<uint>)_api[IndexIsFrameCapturing])() != 0;
private static uint EndFrameCapture() =>
((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint>)_api[IndexEndFrameCapture])(
IntPtr.Zero,
IntPtr.Zero);
private static void LogNewestCapture()
{
var count = ((delegate* unmanaged[Cdecl]<uint>)_api[IndexGetNumCaptures])();
if (count == 0)
{
return;
}
var getCapture =
(delegate* unmanaged[Cdecl]<uint, byte*, uint*, ulong*, uint>)_api[IndexGetCapture];
uint pathLength = 0;
if (getCapture(count - 1, null, &pathLength, null) == 0 || pathLength == 0)
{
return;
}
var buffer = new byte[pathLength];
fixed (byte* bufferPointer = buffer)
{
if (getCapture(count - 1, bufferPointer, &pathLength, null) == 0)
{
return;
}
}
var path = System.Text.Encoding.UTF8.GetString(buffer).TrimEnd('\0');
Console.Error.WriteLine($"[LOADER][INFO] renderdoc: capture written to '{path}'.");
}
private static bool TryLoadLibrary(out IntPtr module)
{
var configured = Environment.GetEnvironmentVariable("SHARPEMU_RENDERDOC_DLL");
if (!string.IsNullOrWhiteSpace(configured) &&
NativeLibrary.TryLoad(configured, out module))
{
return true;
}
var name = OperatingSystem.IsWindows() ? "renderdoc.dll" : "librenderdoc.so";
if (NativeLibrary.TryLoad(name, out module))
{
return true;
}
foreach (var candidate in KnownLibraryPaths(name))
{
if (File.Exists(candidate) && NativeLibrary.TryLoad(candidate, out module))
{
return true;
}
}
module = IntPtr.Zero;
return false;
}
private static IEnumerable<string> KnownLibraryPaths(string name)
{
if (!OperatingSystem.IsWindows())
{
yield return "/usr/lib/librenderdoc.so";
yield return "/usr/local/lib/librenderdoc.so";
yield break;
}
foreach (var variable in (string[])["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"])
{
var root = Environment.GetEnvironmentVariable(variable);
if (!string.IsNullOrWhiteSpace(root))
{
yield return Path.Combine(root, "RenderDoc", name);
}
}
var localAppData = Environment.GetEnvironmentVariable("LOCALAPPDATA");
if (!string.IsNullOrWhiteSpace(localAppData))
{
yield return Path.Combine(localAppData, "RenderDoc", name);
}
}
}
@@ -487,10 +487,6 @@ internal sealed unsafe class SdlHostWindow : IDisposable, IHostGamepadOutput
{
PerfOverlay.Toggle();
}
else if (keyEvent.key == SDL_Keycode.SDLK_F10)
{
RenderDocCapture.RequestCapture();
}
else if (keyEvent.key == SDL_Keycode.SDLK_F11)
{
ToggleFullscreen();
+2 -21
View File
@@ -122,8 +122,6 @@ public static class VideoOutExports
: titleId.Trim();
_applicationWindowTitle = $"{application}{versionSuffix}";
}
RenderDocCapture.SetCaptureDirectory(GetApplicationTitleId());
}
internal static string GetApplicationTitleId()
@@ -729,14 +727,6 @@ public static class VideoOutExports
KernelMemoryCompatExports.TryWriteUInt64Compat(ctx, statusAddress + 0x10, 0);
KernelMemoryCompatExports.TryWriteUInt64Compat(ctx, statusAddress + 0x18, 0);
KernelMemoryCompatExports.TryWriteUInt64Compat(ctx, statusAddress + 0x20, currentBuffer);
// Ghost of Yotei polls a flag past the classic 0x28-byte struct and
// spins on sceKernelUsleep(1) while it's nonzero; the caller never
// pre-zeroes that stack buffer, so an untouched field reads back as
// garbage. Flips complete synchronously in this emulator (see
// SubmitFlip/sceVideoOutIsFlipPending, always not-pending), so the
// extended region must read zero here too.
KernelMemoryCompatExports.TryWriteUInt64Compat(ctx, statusAddress + 0x28, 0);
KernelMemoryCompatExports.TryWriteUInt64Compat(ctx, statusAddress + 0x30, 0);
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
@@ -1122,14 +1112,7 @@ public static class VideoOutExports
if (category > 1 || option != 0)
{
// Ghost of Yotei registers its display buffers with a nonzero
// category/option pair; rejecting the registration guarantees the
// title can never flip. Treat unknown categories as the standard
// uncompressed layout instead of failing the whole registration.
TraceVideoOut(
$"register_buffers2 nonstandard category=0x{categoryRaw:X} " +
$"option=0x{option:X} handle={handle} set={setIndex} " +
$"start={bufferIndexStart} count={bufferNum}");
return OrbisVideoOutErrorInvalidValue;
}
if (!TryReadBufferAttribute(ctx, attributeAddress, true, out var attribute))
@@ -1315,12 +1298,10 @@ public static class VideoOutExports
var submitted = Interlocked.Exchange(ref _submittedFrameCount, 0);
var presentedCount = Interlocked.Exchange(ref _presentedFrameCount, 0);
var (draws, drawMs, pipelines, spirvCompiles) = GuestGpu.Current.ReadAndResetPerfCounters();
var (poolLeases, poolCachedBytes) = SharpEmu.Libs.Gpu.GuestDataPool.DiagnosticStats();
Console.Error.WriteLine(
$"[LOADER][PERF] videoout submitted_fps={submitted / elapsedSeconds:F1} " +
$"presented_fps={presentedCount / elapsedSeconds:F1} " +
$"draws={draws} draw_ms={drawMs:F0} pipelines={pipelines} spirv={spirvCompiles} " +
$"pool_leases={poolLeases} pool_cached_mb={poolCachedBytes / 1024.0 / 1024.0:F1}");
$"draws={draws} draw_ms={drawMs:F0} pipelines={pipelines} spirv={spirvCompiles}");
}
private static readonly bool _flipPacingDisabled = string.Equals(
File diff suppressed because it is too large Load Diff
@@ -101,12 +101,6 @@ public static partial class Gen5SpirvTranslator
return false;
}
if (instruction.Opcode is "VMovrelsB32" or "VMovreldB32" or
"VMovrelsdB32" or "VMovrelsd2B32")
{
return TryEmitMoveRelative(instruction, destination, out error);
}
uint result;
switch (instruction.Opcode)
{
@@ -1019,76 +1013,6 @@ public static partial class Gen5SpirvTranslator
return true;
}
// V_MOVREL*_B32: register-relative moves. M0 is added at run time to the
// source and/or destination register number encoded in the instruction,
// which is how shader compilers implement a dynamically indexed array
// that stayed in registers instead of being spilled to memory. Astro Bot
// ships pixel shaders that index a small register-resident table this
// way; without this the whole shader fails to translate.
//
// V_MOVRELS_B32 vdst = vgpr[src0 + M0]
// V_MOVRELD_B32 vgpr[vdst + M0] = src0
// V_MOVRELSD_B32 vgpr[vdst + M0] = vgpr[src0 + M0]
// V_MOVRELSD_2_B32 vgpr[vdst + M0[25:16]] = vgpr[src0 + M0[9:0]]
//
// The relative forms address the VGPR file relative to the wave's own
// allocation base, which is exactly what the private register array
// models, so the encoded number and M0 simply add.
private bool TryEmitMoveRelative(
Gen5ShaderInstruction instruction,
uint destination,
out string error)
{
error = string.Empty;
if (instruction.Sources.Count == 0)
{
error = $"missing source for {instruction.Opcode}";
return false;
}
var m0 = LoadS(M0ScalarRegister);
uint sourceOffset;
uint destinationOffset;
if (instruction.Opcode == "VMovrelsd2B32")
{
sourceOffset = BitwiseAnd(m0, UInt(0x3FF));
destinationOffset = BitwiseAnd(ShiftRightLogical(m0, UInt(16)), UInt(0x3FF));
}
else
{
sourceOffset = m0;
destinationOffset = m0;
}
uint value;
if (instruction.Opcode == "VMovreldB32")
{
// Only the destination is relative here; src0 is an ordinary
// operand and may be an SGPR or an inline/literal constant.
value = GetRawSource(instruction, 0);
}
else
{
var source = instruction.Sources[0];
if (source.Kind != Gen5OperandKind.VectorRegister)
{
error = $"{instruction.Opcode} source must be a vector register";
return false;
}
value = LoadVDynamic(IAdd(UInt(source.Value), sourceOffset));
}
if (instruction.Opcode == "VMovrelsB32")
{
StoreV(destination, value);
return true;
}
StoreVDynamic(IAdd(UInt(destination), destinationOffset), value);
return true;
}
// Packed f16 (VOP3P) arithmetic. Each source register holds two f16 values,
// one per result lane. Every f16<->f32 conversion is done with the explicit
// integer sequences below (EmitHalfToFloat / EmitFloatToHalf) instead of
@@ -176,11 +176,6 @@ public static partial class Gen5SpirvTranslator
private const uint ImageDescriptorDwords = 8;
private const uint SamplerDescriptorDwords = 4;
private const int ScalarRegisterCount = 128;
// M0. Used as the runtime index added to the register numbers encoded in
// the V_MOVREL* instructions, and as the LDS/GDS base elsewhere.
private const uint M0ScalarRegister = 124;
private const long InitialScalarDefinition = -1;
private const long ConflictingScalarDefinition = -2;
private const long UnreachableScalarDefinition = -3;
@@ -717,8 +712,6 @@ public static partial class Gen5SpirvTranslator
if (UsesSubgroupOperations())
{
_module.AddCapability(SpirvCapability.GroupNonUniform);
_module.AddCapability(SpirvCapability.GroupNonUniformBallot);
if (UsesSubgroupShuffle())
{
_module.AddCapability(SpirvCapability.GroupNonUniformShuffle);
@@ -729,6 +722,10 @@ public static partial class Gen5SpirvTranslator
_module.AddCapability(SpirvCapability.GroupNonUniformVote);
}
if (UsesSubgroupBroadcast() || UsesWaveControl())
{
_module.AddCapability(SpirvCapability.GroupNonUniformBallot);
}
}
_glsl = _module.ImportExtInst("GLSL.std.450");
@@ -1806,16 +1803,13 @@ public static partial class Gen5SpirvTranslator
if (instruction.Opcode == "SBarrier")
{
if (_stage == Gen5SpirvStage.Compute)
{
var workgroup = UInt(2);
var semantics = UInt(0x108);
_module.AddStatement(
SpirvOp.ControlBarrier,
workgroup,
workgroup,
semantics);
}
var workgroup = UInt(2);
var semantics = UInt(0x108);
_module.AddStatement(
SpirvOp.ControlBarrier,
workgroup,
workgroup,
semantics);
return true;
}
@@ -5095,33 +5089,6 @@ public static partial class Gen5SpirvTranslator
_vectorRegisters,
UInt(register));
// The V_MOVREL* opcodes address the VGPR file with a register number that
// is only known at run time (encoded number + M0), so the access chain
// takes a computed index instead of a constant. The index is masked to
// the array bounds: SPIR-V leaves an out-of-range Private access chain
// undefined, and a mask costs nothing next to the surrounding load.
private uint DynamicVectorPointer(uint registerIndex) =>
_module.AddInstruction(
SpirvOp.AccessChain,
_privateUintPointer,
_vectorRegisters,
BitwiseAnd(registerIndex, UInt(VectorRegisterCount - 1)));
private uint LoadVDynamic(uint registerIndex) =>
Load(_uintType, DynamicVectorPointer(registerIndex));
private void StoreVDynamic(uint registerIndex, uint value)
{
var pointer = DynamicVectorPointer(registerIndex);
value = _module.AddInstruction(
SpirvOp.Select,
_uintType,
Load(_boolType, _exec),
value,
Load(_uintType, pointer));
Store(pointer, value);
}
private uint PackedHalfPointer(uint register) =>
_module.AddInstruction(
SpirvOp.AccessChain,
@@ -947,7 +947,6 @@ public static class Gen5ShaderTranslator
0x42 => "VMovreldB32",
0x43 => "VMovrelsB32",
0x44 => "VMovrelsdB32",
0x48 => "VMovrelsd2B32",
_ => string.Empty,
};
@@ -1,215 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
using SharpEmu.HLE;
using SharpEmu.Libs.Agc;
using Xunit;
namespace SharpEmu.Libs.Tests.Agc;
/// <summary>
/// Coverage for the graphics context-register path in the PM4 parser. Draw
/// translation reads render state out of this dictionary (CB_TARGET_MASK
/// decides whether a draw writes alpha, CB_COLOR_CONTROL decides what the draw
/// means), so a write that lands under the wrong key, or fails to overwrite an
/// earlier one, silently changes what every later draw does. These drive real
/// PM4 packets through the public submit export and assert what the parser
/// retained.
/// </summary>
public sealed class AgcContextRegisterTests
{
private const ulong BaseAddress = 0x2_0000_0000;
private const ulong SubmitPacketAddress = BaseAddress + 0x40;
private const ulong CommandAddress = BaseAddress + 0x200;
private const ulong IndirectTableAddress = BaseAddress + 0x600;
private const uint ItNop = 0x10;
private const uint ItSetContextReg = 0x69;
private const uint RCxRegsIndirect = 0x12;
private const uint CbTargetMask = 0x8E;
private const uint CbColorControl = 0x202;
// PM4 type-3 header: 0xC0000000 | ((dwords - 2) << 16) | (opcode << 8), with the
// NOP sub-register in bits 2..7 — the parser reads it as (header >> 2) & 0x3F.
private static uint Pm4Header(uint dwords, uint opcode, uint register = 0) =>
0xC000_0000u | ((dwords - 2) << 16) | (opcode << 8) | ((register & 0x3Fu) << 2);
[Fact]
public void SetContextRegRetainsTargetMask()
{
var ctx = CreateContext(out var memory);
WriteDwords(
memory,
CommandAddress,
Pm4Header(3, ItSetContextReg),
CbTargetMask,
0x0000_0007u);
Submit(ctx, memory, dwordCount: 3);
Assert.True(
AgcExports.TryGetGraphicsContextRegisterForTests(ctx, CbTargetMask, out var value));
Assert.Equal(0x0000_0007u, value);
}
/// <summary>
/// The indirect form carries (offset, value) pairs out of guest memory
/// rather than inline dwords, so an offset-encoding mismatch here would
/// store the register under a key no reader looks at.
/// </summary>
[Fact]
public void IndirectRegisterWriteRetainsTargetMask()
{
var ctx = CreateContext(out var memory);
WriteIndirectRegisterCommand(memory, (CbTargetMask, 0xFFFF_FFFFu));
Submit(ctx, memory, dwordCount: 4);
Assert.True(
AgcExports.TryGetGraphicsContextRegisterForTests(ctx, CbTargetMask, out var value));
Assert.Equal(0xFFFF_FFFFu, value);
}
/// <summary>
/// Context registers persist across submissions on hardware until something
/// clears them, so a mask written in one submission has to still be there
/// for a draw in the next.
/// </summary>
[Fact]
public void TargetMaskSurvivesASecondSubmission()
{
var ctx = CreateContext(out var memory);
WriteIndirectRegisterCommand(memory, (CbTargetMask, 0x8888_8888u));
Submit(ctx, memory, dwordCount: 4);
// A second, unrelated submission: a bare NOP that touches no registers.
WriteDwords(memory, CommandAddress, Pm4Header(2, ItNop), 0);
Submit(ctx, memory, dwordCount: 2);
Assert.True(
AgcExports.TryGetGraphicsContextRegisterForTests(ctx, CbTargetMask, out var value));
Assert.Equal(0x8888_8888u, value);
}
/// <summary>
/// Both encodings must land on the same key, or a title that sets the
/// register one way and a reader that expects the other silently disagree.
/// </summary>
[Fact]
public void DirectAndIndirectWritesShareOneKey()
{
var ctx = CreateContext(out var memory);
WriteDwords(
memory,
CommandAddress,
Pm4Header(3, ItSetContextReg),
CbTargetMask,
0x0000_0007u);
Submit(ctx, memory, dwordCount: 3);
WriteIndirectRegisterCommand(memory, (CbTargetMask, 0x0000_000Fu));
Submit(ctx, memory, dwordCount: 4);
Assert.True(
AgcExports.TryGetGraphicsContextRegisterForTests(ctx, CbTargetMask, out var value));
Assert.Equal(0x0000_000Fu, value);
}
/// <summary>
/// CB_COLOR_CONTROL (0x202) MODE bits [6:4] give Normal=1,
/// EliminateFastClear=2, Resolve=3, FmaskDecompress=5, DccDecompress=6. The
/// value has to survive the parser intact, ROP3 bits and all, because the
/// mode decides whether a draw shades or resolves.
/// </summary>
[Theory]
[InlineData(0x0000_0010u, 1u)] // Normal
[InlineData(0x0000_0020u, 2u)] // EliminateFastClear
[InlineData(0x00CC_0060u, 6u)] // DccDecompress, with ROP3=0xCC alongside
public void ColorControlRetainsMode(uint written, uint expectedMode)
{
var ctx = CreateContext(out var memory);
WriteIndirectRegisterCommand(memory, (CbColorControl, written));
Submit(ctx, memory, dwordCount: 4);
Assert.True(
AgcExports.TryGetGraphicsContextRegisterForTests(ctx, CbColorControl, out var value));
Assert.Equal(written, value);
Assert.Equal(expectedMode, (value >> 4) & 0x7u);
}
/// <summary>
/// A later write must win. If the parser kept the first value, a draw that
/// sets EliminateFastClear after an earlier Normal would still read Normal
/// and the clear would be silently dropped.
/// </summary>
[Fact]
public void ColorControlLaterWriteOverwritesEarlier()
{
var ctx = CreateContext(out var memory);
WriteIndirectRegisterCommand(memory, (CbColorControl, 0x00CC_0010u));
Submit(ctx, memory, dwordCount: 4);
WriteIndirectRegisterCommand(memory, (CbColorControl, 0x00CC_0020u));
Submit(ctx, memory, dwordCount: 4);
Assert.True(
AgcExports.TryGetGraphicsContextRegisterForTests(ctx, CbColorControl, out var value));
Assert.Equal(0x00CC_0020u, value);
Assert.Equal(2u, (value >> 4) & 0x7u);
}
private static void WriteIndirectRegisterCommand(
FakeCpuMemory memory,
params (uint Offset, uint Value)[] registers)
{
WriteDwords(
memory,
CommandAddress,
Pm4Header(4, ItNop, RCxRegsIndirect),
(uint)registers.Length,
(uint)(IndirectTableAddress & 0xFFFF_FFFFu),
(uint)(IndirectTableAddress >> 32));
for (var index = 0; index < registers.Length; index++)
{
var entry = IndirectTableAddress + ((ulong)index * 8);
WriteUInt32(memory, entry, registers[index].Offset);
WriteUInt32(memory, entry + 4, registers[index].Value);
}
}
private static void Submit(CpuContext ctx, FakeCpuMemory memory, uint dwordCount)
{
WriteUInt64(memory, SubmitPacketAddress, CommandAddress);
WriteUInt32(memory, SubmitPacketAddress + 8, dwordCount);
ctx[CpuRegister.Rdi] = SubmitPacketAddress;
AgcExports.DriverSubmitDcb(ctx);
}
private static CpuContext CreateContext(out FakeCpuMemory memory)
{
memory = new FakeCpuMemory(BaseAddress, 0x1000);
return new CpuContext(memory, Generation.Gen5);
}
private static void WriteDwords(FakeCpuMemory memory, ulong address, params uint[] values)
{
for (var index = 0; index < values.Length; index++)
{
WriteUInt32(memory, address + ((ulong)index * sizeof(uint)), values[index]);
}
}
private static void WriteUInt32(FakeCpuMemory memory, ulong address, uint value)
{
Span<byte> buffer = stackalloc byte[sizeof(uint)];
BinaryPrimitives.WriteUInt32LittleEndian(buffer, value);
Assert.True(memory.TryWrite(address, buffer));
}
private static void WriteUInt64(FakeCpuMemory memory, ulong address, ulong value)
{
Span<byte> buffer = stackalloc byte[sizeof(ulong)];
BinaryPrimitives.WriteUInt64LittleEndian(buffer, value);
Assert.True(memory.TryWrite(address, buffer));
}
}
@@ -1,232 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
using SharpEmu.HLE;
using SharpEmu.Libs.Agc;
using Xunit;
namespace SharpEmu.Libs.Tests.Agc;
/// <summary>
/// Coverage for the SH-register path in the PM4 parser. A draw resolves its
/// vertex stage from SPI_SHADER_PGM_LO_ES/HI_ES and its pixel stage from
/// SPI_SHADER_PGM_LO_PS/HI_PS, both out of this dictionary, so a key that is
/// dropped or written under a different encoding pairs a current pixel shader
/// with a stale vertex shader — a failure that produces plausible-looking
/// garbage rather than an error. These drive real PM4 packets through the
/// public submit export and assert what the parser retained.
/// </summary>
public sealed class AgcShaderStageRegisterTests
{
private const ulong BaseAddress = 0x2_0000_0000;
private const ulong SubmitPacketAddress = BaseAddress + 0x40;
private const ulong CommandAddress = BaseAddress + 0x200;
private const ulong IndirectTableAddress = BaseAddress + 0x600;
private const uint ItNop = 0x10;
private const uint ItSetShReg = 0x76;
private const uint RShRegsIndirect = 0x11;
// SH register offsets. ES is the vertex stage on GFX10 — the standalone
// PGM_LO/HI_GS pair is dead post-GCN and the merged ES/GS stage is addressed
// through ES.
private const uint SpiShaderPgmLoPs = 0x8;
private const uint SpiShaderPgmLoEs = 0xC8;
private const uint SpiShaderPgmHiEs = 0xC9;
private static uint Pm4Header(uint dwords, uint opcode, uint register = 0) =>
0xC000_0000u | ((dwords - 2) << 16) | (opcode << 8) | ((register & 0x3Fu) << 2);
/// <summary>
/// The baseline: a direct SET_SH_REG write of the vertex stage address has
/// to be readable afterwards. If this fails, nothing downstream can pair
/// shaders correctly.
/// </summary>
[Fact]
public void SetShRegRetainsExportShaderAddress()
{
var ctx = CreateContext(out var memory);
WriteDwords(
memory,
CommandAddress,
Pm4Header(3, ItSetShReg),
SpiShaderPgmLoEs,
0x0044_8582u);
Submit(ctx, memory, dwordCount: 3);
Assert.True(
AgcExports.TryGetGraphicsShRegisterForTests(ctx, SpiShaderPgmLoEs, out var value));
Assert.Equal(0x0044_8582u, value);
}
/// <summary>
/// The indirect encoding must land on the same keys as the direct one. A
/// mismatch would store the stage address where the draw never reads it,
/// leaving the draw to see whatever a previous submission left behind.
/// </summary>
[Fact]
public void IndirectShRegisterWriteRetainsExportShaderAddress()
{
var ctx = CreateContext(out var memory);
WriteIndirectShRegisterCommand(memory, (SpiShaderPgmLoEs, 0x0044_8DD1u));
Submit(ctx, memory, dwordCount: 4);
Assert.True(
AgcExports.TryGetGraphicsShRegisterForTests(ctx, SpiShaderPgmLoEs, out var value));
Assert.Equal(0x0044_8DD1u, value);
}
/// <summary>
/// Both stages written in one submission must both read back as written. If
/// the vertex stage kept an older value while the pixel stage updated, every
/// draw after it would be mis-paired.
/// </summary>
[Fact]
public void BothStagesUpdateTogetherWithinOneSubmission()
{
var ctx = CreateContext(out var memory);
WriteIndirectShRegisterCommand(
memory,
(SpiShaderPgmLoEs, 0x0080_2933u),
(SpiShaderPgmLoPs, 0x0044_858Au));
Submit(ctx, memory, dwordCount: 4);
WriteIndirectShRegisterCommand(
memory,
(SpiShaderPgmLoEs, 0x0044_8581u),
(SpiShaderPgmLoPs, 0x0044_8719u));
Submit(ctx, memory, dwordCount: 4);
Assert.True(
AgcExports.TryGetGraphicsShRegisterForTests(ctx, SpiShaderPgmLoEs, out var es));
Assert.True(
AgcExports.TryGetGraphicsShRegisterForTests(ctx, SpiShaderPgmLoPs, out var ps));
Assert.Equal(0x0044_8581u, es);
Assert.Equal(0x0044_8719u, ps);
}
/// <summary>
/// Updating only the pixel stage must leave the vertex stage at its previous
/// value rather than dropping the key, or the draw falls back to whatever
/// default the resolver finds.
/// </summary>
[Fact]
public void PixelStageUpdateLeavesExportStageIntact()
{
var ctx = CreateContext(out var memory);
WriteIndirectShRegisterCommand(memory, (SpiShaderPgmLoEs, 0x0044_8582u));
Submit(ctx, memory, dwordCount: 4);
WriteIndirectShRegisterCommand(memory, (SpiShaderPgmLoPs, 0x0044_858Au));
Submit(ctx, memory, dwordCount: 4);
Assert.True(
AgcExports.TryGetGraphicsShRegisterForTests(ctx, SpiShaderPgmLoEs, out var es));
Assert.Equal(0x0044_8582u, es);
}
/// <summary>
/// Stage addresses are 64-bit: LO carries bits 39:8 and HI the top bits, and
/// the draw combines them. A HI retained from an earlier shader while LO
/// updates resolves to a splice of two different programs.
/// </summary>
[Fact]
public void HighAndLowHalvesUpdateTogether()
{
var ctx = CreateContext(out var memory);
WriteIndirectShRegisterCommand(
memory,
(SpiShaderPgmLoEs, 0x0080_2933u),
(SpiShaderPgmHiEs, 0x0000_0008u));
Submit(ctx, memory, dwordCount: 4);
WriteIndirectShRegisterCommand(
memory,
(SpiShaderPgmLoEs, 0x0044_8582u),
(SpiShaderPgmHiEs, 0x0000_0004u));
Submit(ctx, memory, dwordCount: 4);
Assert.True(
AgcExports.TryGetGraphicsShRegisterForTests(ctx, SpiShaderPgmLoEs, out var lo));
Assert.True(
AgcExports.TryGetGraphicsShRegisterForTests(ctx, SpiShaderPgmHiEs, out var hi));
Assert.Equal(0x0044_8582u, lo);
Assert.Equal(0x0000_0004u, hi);
}
/// <summary>
/// SH registers persist across submissions on hardware. A stage address set
/// in one submission must still be there for a draw in the next.
/// </summary>
[Fact]
public void ExportShaderAddressSurvivesASecondSubmission()
{
var ctx = CreateContext(out var memory);
WriteIndirectShRegisterCommand(memory, (SpiShaderPgmLoEs, 0x0044_8583u));
Submit(ctx, memory, dwordCount: 4);
WriteDwords(memory, CommandAddress, Pm4Header(2, ItNop), 0);
Submit(ctx, memory, dwordCount: 2);
Assert.True(
AgcExports.TryGetGraphicsShRegisterForTests(ctx, SpiShaderPgmLoEs, out var value));
Assert.Equal(0x0044_8583u, value);
}
private static void WriteIndirectShRegisterCommand(
FakeCpuMemory memory,
params (uint Offset, uint Value)[] registers)
{
WriteDwords(
memory,
CommandAddress,
Pm4Header(4, ItNop, RShRegsIndirect),
(uint)registers.Length,
(uint)(IndirectTableAddress & 0xFFFF_FFFFu),
(uint)(IndirectTableAddress >> 32));
for (var index = 0; index < registers.Length; index++)
{
var entry = IndirectTableAddress + ((ulong)index * 8);
WriteUInt32(memory, entry, registers[index].Offset);
WriteUInt32(memory, entry + 4, registers[index].Value);
}
}
private static void Submit(CpuContext ctx, FakeCpuMemory memory, uint dwordCount)
{
WriteUInt64(memory, SubmitPacketAddress, CommandAddress);
WriteUInt32(memory, SubmitPacketAddress + 8, dwordCount);
ctx[CpuRegister.Rdi] = SubmitPacketAddress;
AgcExports.DriverSubmitDcb(ctx);
}
private static CpuContext CreateContext(out FakeCpuMemory memory)
{
memory = new FakeCpuMemory(BaseAddress, 0x1000);
return new CpuContext(memory, Generation.Gen5);
}
private static void WriteDwords(FakeCpuMemory memory, ulong address, params uint[] values)
{
for (var index = 0; index < values.Length; index++)
{
WriteUInt32(memory, address + ((ulong)index * sizeof(uint)), values[index]);
}
}
private static void WriteUInt32(FakeCpuMemory memory, ulong address, uint value)
{
Span<byte> buffer = stackalloc byte[sizeof(uint)];
BinaryPrimitives.WriteUInt32LittleEndian(buffer, value);
Assert.True(memory.TryWrite(address, buffer));
}
private static void WriteUInt64(FakeCpuMemory memory, ulong address, ulong value)
{
Span<byte> buffer = stackalloc byte[sizeof(ulong)];
BinaryPrimitives.WriteUInt64LittleEndian(buffer, value);
Assert.True(memory.TryWrite(address, buffer));
}
}
@@ -1,210 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
using SharpEmu.HLE;
using SharpEmu.ShaderCompiler;
using SharpEmu.ShaderCompiler.Vulkan;
using Xunit;
namespace SharpEmu.Libs.Tests.Agc;
// Regression tests for the VOP1 register-relative moves V_MOVRELD_B32 /
// V_MOVRELS_B32 / V_MOVRELSD_B32 / V_MOVRELSD_2_B32 (opcodes 0x42/0x43/0x44/
// 0x48). These add M0 at run time to the source and/or destination register
// number encoded in the instruction, which is how a shader compiler implements
// a dynamically indexed array that stayed in registers. The decoder named them
// but nothing lowered them, so they hit the vector-ALU switch default and failed
// emission ("unsupported vector opcode"), dropping the whole shader — Astro Bot
// ships pixel shaders that use V_MOVRELS_B32.
//
// The register file is a private uint array, so the lowering is an OpAccessChain
// with a computed (non-constant) index. Each test therefore asserts both that
// the shader survives translation and that the relative operand really became a
// dynamic index rather than a constant one.
public sealed class Gen5MoveRelativeSpirvTests
{
private const ulong ShaderAddress = 0x1_0000_0000;
// VOP1: [31:25]=0b0111111, [24:17]=vdst, [16:9]=op, [8:0]=src0
// (src0 >= 256 selects a VGPR).
private const uint Vop1 = 0x7E000000;
// SOP1 s_mov_b32 m0, <inline 2>: [31:23]=0b101111101, [22:16]=sdst,
// [15:8]=op(0x03), [7:0]=ssrc0. m0 is SGPR 124, inline constant 2 is 130.
private const uint SMovM0 = 0xBE800000u | (124u << 16) | (0x03u << 8) | 130u;
[Fact]
public void MovrelsB32_ReadsTheSourceRegisterThroughADynamicIndex()
{
// s_mov_b32 m0, 2 ; v_movrels_b32 v5, v3 -> v5 = vgpr[3 + m0]
var spirv = Compile([SMovM0, Vop1 | (5u << 17) | (0x43u << 9) | (256u + 3u)]);
Assert.True(
HasDynamicVectorRegisterAccess(spirv),
"V_MOVRELS_B32 must index the VGPR array with a computed index");
}
[Fact]
public void MovreldB32_WritesTheDestinationRegisterThroughADynamicIndex()
{
// s_mov_b32 m0, 2 ; v_movreld_b32 v5, v3 -> vgpr[5 + m0] = v3
var spirv = Compile([SMovM0, Vop1 | (5u << 17) | (0x42u << 9) | (256u + 3u)]);
Assert.True(
HasDynamicVectorRegisterAccess(spirv),
"V_MOVRELD_B32 must index the VGPR array with a computed index");
}
[Fact]
public void MovrelsdB32_TranslatesWithoutDroppingShader()
{
// s_mov_b32 m0, 2 ; v_movrelsd_b32 v5, v3 -> vgpr[5 + m0] = vgpr[3 + m0]
var spirv = Compile([SMovM0, Vop1 | (5u << 17) | (0x44u << 9) | (256u + 3u)]);
Assert.True(
HasDynamicVectorRegisterAccess(spirv),
"V_MOVRELSD_B32 must index the VGPR array with a computed index");
}
[Fact]
public void Movrelsd2B32_TranslatesWithoutDroppingShader()
{
// s_mov_b32 m0, 2 ; v_movrelsd_2_b32 v5, v3, which splits m0 into two
// 10-bit halves (source index in [9:0], destination index in [25:16]).
var spirv = Compile([SMovM0, Vop1 | (5u << 17) | (0x48u << 9) | (256u + 3u)]);
Assert.True(
HasDynamicVectorRegisterAccess(spirv),
"V_MOVRELSD_2_B32 must index the VGPR array with a computed index");
}
[Fact]
public void MovrelsB32_RejectsANonVectorSource()
{
// v_movrels_b32 v5, s3. The relative source is architecturally a VGPR;
// an SGPR encoding is malformed and must fail translation rather than
// silently read the wrong register file.
Assert.False(
TryCompile(
[SMovM0, Vop1 | (5u << 17) | (0x43u << 9) | 3u],
out _,
out var error));
Assert.Contains("vector register", error, StringComparison.Ordinal);
}
// True when some OpAccessChain into the "vgpr" array uses an index that is
// not an OpConstant — i.e. a register number computed from M0.
private static bool HasDynamicVectorRegisterAccess(byte[] spirv)
{
var vectorRegisters = FindNamedId(spirv, "vgpr");
Assert.True(vectorRegisters != 0, "the module must name its VGPR array");
var constants = new HashSet<uint>();
foreach (var (op, wordCount, offset) in EnumerateInstructions(spirv))
{
// OpConstant = 43, OpConstantNull = 46: (opcode, resultType, resultId, ...).
if (op is 43 or 46 && wordCount >= 3)
{
constants.Add(ReadWord(spirv, offset + 8));
}
}
foreach (var (op, wordCount, offset) in EnumerateInstructions(spirv))
{
// OpAccessChain = 65: (opcode, resultType, resultId, base, index...).
if (op != 65 || wordCount < 5 || ReadWord(spirv, offset + 12) != vectorRegisters)
{
continue;
}
if (!constants.Contains(ReadWord(spirv, offset + 16)))
{
return true;
}
}
return false;
}
// Result id of the OpName whose literal string matches, or 0.
private static uint FindNamedId(byte[] spirv, string name)
{
foreach (var (op, wordCount, offset) in EnumerateInstructions(spirv))
{
// OpName = 5: (opcode, target, literal string...).
if (op != 5 || wordCount < 3)
{
continue;
}
var bytes = spirv.AsSpan(offset + 8, (wordCount - 2) * sizeof(uint));
var terminator = bytes.IndexOf((byte)0);
var text = System.Text.Encoding.UTF8.GetString(
terminator < 0 ? bytes : bytes[..terminator]);
if (text == name)
{
return ReadWord(spirv, offset + 4);
}
}
return 0;
}
private static IEnumerable<(ushort Op, int WordCount, int Offset)> EnumerateInstructions(
byte[] spirv)
{
// 5-word SPIR-V header, then (wordCount << 16 | opcode) packed instructions.
for (var offset = 5 * sizeof(uint); offset + sizeof(uint) <= spirv.Length;)
{
var word = ReadWord(spirv, offset);
var wordCount = (int)(word >> 16);
if (wordCount <= 0)
{
yield break;
}
yield return ((ushort)word, wordCount, offset);
offset += wordCount * sizeof(uint);
}
}
private static uint ReadWord(byte[] spirv, int offset) =>
BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset, sizeof(uint)));
private static byte[] Compile(uint[] programWords)
{
Assert.True(TryCompile(programWords, out var spirv, out var error), error);
return spirv;
}
private static bool TryCompile(uint[] programWords, out byte[] spirv, out string error)
{
spirv = [];
var memory = new FakeCpuMemory(ShaderAddress, 0x2000);
var ctx = new CpuContext(memory, Generation.Gen5);
Gen5ShaderAtomicDecodeTests.WriteProgram(memory, ShaderAddress, programWords);
var shaderRegisters = new Dictionary<uint, uint>
{
[Gen5ShaderAtomicDecodeTests.ComputePgmRsrc2Register] = 16u << 1,
};
if (!Gen5ShaderTranslator.TryCreateState(
ctx,
ShaderAddress,
0,
shaderRegisters,
Gen5ShaderAtomicDecodeTests.ComputeUserDataRegister,
out var state,
out error) ||
!Gen5ShaderScalarEvaluator.TryEvaluate(ctx, state, out var evaluation, out error) ||
!Gen5SpirvTranslator.TryCompileComputeShader(
state, evaluation, 1, 1, 1, out var shader, out error))
{
return false;
}
spirv = shader.Spirv;
return true;
}
}
@@ -6,9 +6,6 @@ using Xunit;
namespace SharpEmu.Libs.Tests.Ampr;
// AmprFileRegistry is process-global static state, so the classes that index
// or clear it must not run concurrently with each other.
[Collection("AmprFileRegistry")]
public class AmprFileRegistryTests
{
[Fact]
@@ -65,79 +62,6 @@ public class AmprFileRegistryTests
Assert.Equal(host, d);
}
[Fact]
public void App0_index_cache_keeps_files_that_differ_only_by_case()
{
var root = Path.Combine(Path.GetTempPath(), "sharpemu-ampr-case-" + Guid.NewGuid().ToString("N"));
var cacheDir = Path.Combine(root, "..", "sharpemu-ampr-cache-" + Guid.NewGuid().ToString("N"));
var upper = Path.Combine(root, "data", "ASSET.bin");
var lower = Path.Combine(root, "data", "asset.bin");
var previousCacheDir = Environment.GetEnvironmentVariable("SHARPEMU_AMPR_INDEX_CACHE");
try
{
Directory.CreateDirectory(Path.Combine(root, "sce_sys"));
Directory.CreateDirectory(Path.Combine(root, "data"));
File.WriteAllText(Path.Combine(root, "sce_sys", "param.json"), "{}");
File.WriteAllBytes(upper, [1, 2, 3]);
if (File.Exists(lower))
{
// Case-insensitive host: the two names are one file, so there is
// nothing for an ignore-case index to lose.
return;
}
File.WriteAllBytes(lower, [4, 5, 6]);
Environment.SetEnvironmentVariable("SHARPEMU_AMPR_INDEX_CACHE", cacheDir);
var normalizedRoot = Path.GetFullPath(root);
var expectedUpper = Path.Combine(normalizedRoot, "data", "ASSET.bin");
var expectedLower = Path.Combine(normalizedRoot, "data", "asset.bin");
// Fresh tree walk, which also writes the on-disk index cache.
AmprFileRegistry.ClearForTests();
AmprFileRegistry.EnsureApp0Indexed(root);
AssertResolves(expectedUpper, expectedLower);
// Second boot: served from the cache the walk just wrote.
AmprFileRegistry.ClearForTests();
AmprFileRegistry.EnsureApp0Indexed(root);
AssertResolves(expectedUpper, expectedLower);
}
finally
{
Environment.SetEnvironmentVariable("SHARPEMU_AMPR_INDEX_CACHE", previousCacheDir);
AmprFileRegistry.ClearForTests();
TryDeleteDirectory(cacheDir);
TryDeleteDirectory(root);
}
static void AssertResolves(string expectedUpper, string expectedLower)
{
Assert.True(
AmprFileRegistry.TryGetHostPath(
AmprFileRegistry.ComputeFileId("$/data/ASSET.bin"), out var actualUpper),
"data/ASSET.bin is missing from the app0 index.");
Assert.True(
AmprFileRegistry.TryGetHostPath(
AmprFileRegistry.ComputeFileId("$/data/asset.bin"), out var actualLower),
"data/asset.bin is missing from the app0 index.");
Assert.Equal(expectedUpper, actualUpper);
Assert.Equal(expectedLower, actualLower);
}
}
private static void TryDeleteDirectory(string path)
{
try
{
Directory.Delete(path, recursive: true);
}
catch (Exception)
{
// Temp cleanup is best-effort.
}
}
private static uint FnvUtf8(string text)
{
const uint offset = 2166136261;
@@ -8,7 +8,6 @@ using Xunit;
namespace SharpEmu.Libs.Tests.Ampr;
[Collection("AmprFileRegistry")]
public sealed class AmprWriteAddressTests
{
[Fact]
@@ -9,7 +9,6 @@ using Xunit;
namespace SharpEmu.Libs.Tests.Ampr;
[Collection("AmprFileRegistry")]
public sealed class AprStreamingContractTests
{
[Fact]
@@ -83,30 +83,6 @@ public sealed class AjmExportsTests : IDisposable
Assert.Equal(InvalidContext, RegisterCodec(contextId + 1, 1));
}
[Fact]
public void ModuleUnregister_RemovesRegisteredCodecAndRejectsUnknownContext()
{
var contextId = Initialize();
Assert.Equal(0, RegisterCodec(contextId, 1));
Assert.Equal(0, UnregisterCodec(contextId, 1));
// The codec is actually gone, not just a no-op stub: it's unusable
// for a new instance, and re-registering no longer hits
// CodecAlreadyRegistered.
Assert.Equal(CodecNotRegistered, CreateInstance(contextId, 1, 0x401, InstanceAddress));
Assert.Equal(0, RegisterCodec(contextId, 1));
Assert.Equal(InvalidContext, UnregisterCodec(contextId + 1, 1));
}
[Fact]
public void ModuleUnregister_UnknownCodecIsToleratedAsANoOp()
{
var contextId = Initialize();
Assert.Equal(0, UnregisterCodec(contextId, 1));
}
[Fact]
public void MemoryRegistration_TracksValidContextAndToleratesRepeatedUnregister()
{
@@ -377,13 +353,6 @@ public sealed class AjmExportsTests : IDisposable
return AjmExports.AjmModuleRegister(_ctx);
}
private int UnregisterCodec(uint contextId, uint codecType)
{
_ctx[CpuRegister.Rdi] = contextId;
_ctx[CpuRegister.Rsi] = codecType;
return AjmExports.AjmModuleUnregister(_ctx);
}
private int RegisterMemory(uint contextId, ulong address, ulong pages)
{
_ctx[CpuRegister.Rdi] = contextId;
@@ -1,147 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
using System.Diagnostics;
using SharpEmu.HLE;
using SharpEmu.Libs.AvPlayer;
using Xunit;
namespace SharpEmu.Libs.Tests.AvPlayer;
public sealed class AvPlayerAbiTests
{
[Theory]
[InlineData(Generation.Gen4, false, 108UL)]
[InlineData(Generation.Gen5, false, 112UL)]
[InlineData(Generation.Gen4, true, 164UL)]
[InlineData(Generation.Gen5, true, 168UL)]
public void InitAutoStartOffsetMatchesGeneration(
Generation generation,
bool extended,
ulong expected)
{
Assert.Equal(expected, AvPlayerExports.GetAutoStartOffset(generation, extended));
}
[Theory]
[InlineData(Generation.Gen4, 40)]
[InlineData(Generation.Gen5, 32)]
public void LegacyStreamInfoSizeMatchesGeneration(
Generation generation,
int expected)
{
Assert.Equal(expected, AvPlayerExports.GetLegacyStreamInfoSize(generation));
}
[Theory]
[InlineData(Generation.Gen4, 0u, 0u)]
[InlineData(Generation.Gen4, 1u, 1u)]
[InlineData(Generation.Gen5, 0u, 1u)]
[InlineData(Generation.Gen5, 1u, 2u)]
public void StreamTypeMatchesGeneration(
Generation generation,
uint streamIndex,
uint expected)
{
Assert.Equal(expected, AvPlayerExports.GetStreamType(generation, streamIndex));
}
[Fact]
public void Gen5FrameInfoExCarriesPitchCropAndFrameRate()
{
var info = new byte[104];
AvPlayerExports.WriteVideoFrameInfo(
info,
Generation.Gen5,
extended: true,
bufferAddress: 0x1234_5000,
timestamp: 2_903,
width: 512,
visibleWidth: 378,
height: 150,
pitch: 512,
framesPerSecond: 29.97);
Assert.Equal(0x1234_5000UL, BinaryPrimitives.ReadUInt64LittleEndian(info));
Assert.Equal(2_903UL, BinaryPrimitives.ReadUInt64LittleEndian(info.AsSpan(16)));
Assert.Equal(512u, BinaryPrimitives.ReadUInt32LittleEndian(info.AsSpan(24)));
Assert.Equal(150u, BinaryPrimitives.ReadUInt32LittleEndian(info.AsSpan(28)));
Assert.Equal(134u, BinaryPrimitives.ReadUInt32LittleEndian(info.AsSpan(48)));
Assert.Equal(512u, BinaryPrimitives.ReadUInt32LittleEndian(info.AsSpan(60)));
Assert.Equal(8, info[64]);
Assert.Equal(8, info[65]);
Assert.Equal(29.97, BinaryPrimitives.ReadDoubleLittleEndian(info.AsSpan(0x48)));
}
[Fact]
public void FallbackFrameValidationUsesTheDecodedDimensions()
{
var fullHdFrame = new byte[1920 * 1080 * 4];
Assert.True(AvPlayerExports.IsValidBgraFrame(fullHdFrame, 1920, 1080));
Assert.False(AvPlayerExports.IsValidBgraFrame(fullHdFrame, 3840, 2160));
Assert.False(AvPlayerExports.IsValidBgraFrame(fullHdFrame, 0, 1080));
}
[Fact]
public void PosterSuppressesTheDuplicateFirstHostDecodedFrame()
{
var skipFirstDecodedFrame = true;
Assert.False(AvPlayerExports.ShouldPublishFallbackPlaybackFrame(
advanced: true,
hasPresentation: true,
ref skipFirstDecodedFrame));
Assert.False(skipFirstDecodedFrame);
Assert.True(AvPlayerExports.ShouldPublishFallbackPlaybackFrame(
advanced: true,
hasPresentation: true,
ref skipFirstDecodedFrame));
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, true, false)]
[InlineData(true, false, false)]
[InlineData(true, true, true)]
public void CompletedFallbackIsReleasedAtGuestEndOfStream(
bool fallbackCompleted,
bool guestEndOfStream,
bool expected)
{
var completedTicks = Stopwatch.GetTimestamp();
Assert.Equal(
expected,
AvPlayerExports.ShouldReleaseCompletedFallback(
fallbackCompleted,
guestEndOfStream,
completedTicks,
completedTicks));
}
/// <summary>
/// A title that pauses its player after the poster frame never reaches end
/// of stream, so the hold must expire on its own; otherwise the last movie
/// image stays pinned over everything the game renders next.
/// </summary>
[Fact]
public void CompletedFallbackHoldExpiresWithoutGuestEndOfStream()
{
var completedTicks = Stopwatch.GetTimestamp();
Assert.False(
AvPlayerExports.ShouldReleaseCompletedFallback(
fallbackPlaybackCompleted: true,
guestEndOfStream: false,
completedTicks,
completedTicks + (Stopwatch.Frequency / 10)));
Assert.True(
AvPlayerExports.ShouldReleaseCompletedFallback(
fallbackPlaybackCompleted: true,
guestEndOfStream: false,
completedTicks,
completedTicks + (Stopwatch.Frequency * 2)));
}
}
@@ -1,142 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Core.Memory;
using SharpEmu.HLE;
using SharpEmu.Libs.AvPlayer;
using SharpEmu.Libs.Tests.Kernel;
using Xunit;
namespace SharpEmu.Libs.Tests.AvPlayer;
[Collection(KernelMemoryCompatStateCollection.Name)]
public sealed class AvPlayerAllocationTests : IDisposable
{
private const ulong Handle = 0xA0_0000_1000;
private readonly IGuestThreadScheduler? _previousScheduler = GuestThreadExecution.Scheduler;
[Fact]
public void FailedGuestAllocatorsFallBackToHleMemoryInTheSameAttempt()
{
using var memory = new PhysicalVirtualMemory();
var context = new CpuContext(memory, Generation.Gen5);
var scheduler = new FailingAllocatorScheduler();
GuestThreadExecution.Scheduler = scheduler;
AvPlayerExports.RegisterPlayerForTest(
Handle,
width: 16,
height: 16,
durationMilliseconds: 1,
allocateTextureCallback: 0x1000,
allocateCallback: 0x2000);
Assert.True(AvPlayerExports.AllocateGuestVideoBuffersForTest(
context,
Handle,
out var firstBuffer));
Assert.NotEqual(0UL, firstBuffer);
Assert.Equal(2, scheduler.CallCount);
}
public void Dispose()
{
AvPlayerExports.RemovePlayerForTest(Handle);
GuestThreadExecution.Scheduler = _previousScheduler;
}
private sealed class FailingAllocatorScheduler : IGuestThreadScheduler
{
public int CallCount { get; private set; }
public bool SupportsGuestContextTransfer => false;
public void RegisterGuestThreadContext(ulong threadHandle, CpuContext context)
{
}
public bool TryStartThread(
CpuContext creatorContext,
GuestThreadStartRequest request,
out string? error)
{
error = "not supported";
return false;
}
public bool TryJoinThread(
CpuContext callerContext,
ulong threadHandle,
out ulong returnValue,
out string? error)
{
returnValue = 0;
error = "not supported";
return false;
}
public void Pump(CpuContext callerContext, string reason)
{
}
public int WakeBlockedThreads(string wakeKey, int maxCount = int.MaxValue) => 0;
public bool TrySetGuestThreadPriority(ulong guestThreadHandle, int guestPriority) => false;
public bool TrySetGuestThreadAffinity(ulong guestThreadHandle, ulong affinityMask) => false;
public IReadOnlyList<GuestThreadSnapshot> SnapshotThreads() => [];
public bool TryCallGuestFunction(
CpuContext callerContext,
ulong entryPoint,
ulong arg0,
ulong arg1,
ulong stackAddress,
ulong stackSize,
string reason,
out string? error)
{
error = "not supported";
return false;
}
public bool TryCallGuestFunction(
CpuContext callerContext,
ulong entryPoint,
ulong arg0,
ulong arg1,
ulong arg2,
ulong stackAddress,
ulong stackSize,
string reason,
out ulong returnValue,
out string? error)
{
CallCount++;
returnValue = 0;
error = "allocator rejected the request";
return false;
}
public bool TryCallGuestContinuation(
CpuContext callerContext,
GuestCpuContinuation continuation,
string reason,
out string? error)
{
error = "not supported";
return false;
}
public bool TryRaiseGuestException(
CpuContext callerContext,
ulong threadHandle,
ulong handler,
int exceptionType,
out string? error)
{
error = "not supported";
return false;
}
}
}
@@ -1,106 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Libs.AvPlayer;
using Xunit;
namespace SharpEmu.Libs.Tests.AvPlayer;
public sealed class AvPlayerNv12LayoutTests
{
[Theory]
[InlineData(1920, 2048)]
[InlineData(3840, 3840)]
[InlineData(4097, 4352)]
public void CalculateNv12Pitch_AlignsTo256Bytes(int width, int expectedPitch)
{
Assert.Equal(expectedPitch, AvPlayerExports.CalculateNv12Pitch(width));
}
[Fact]
public void CalculateNv12BufferSize_IncludesBothPlanesAtTheAlignedPitch()
{
Assert.Equal(3_317_760, AvPlayerExports.CalculateNv12BufferSize(2048, 1080));
}
[Fact]
public void ConvertNv12ToBgra_UsesTheInterleavedChromaPlaneAndOpaqueAlpha()
{
byte[] nv12 =
[
16, 235,
81, 145,
128, 128,
];
var bgra = new byte[2 * 2 * 4];
AvPlayerExports.ConvertNv12ToBgra(
nv12,
pitch: 2,
bufferHeight: 2,
width: 2,
height: 2,
bgra);
Assert.Equal(
new byte[]
{
0, 0, 0, 255,
255, 255, 255, 255,
76, 76, 76, 255,
150, 150, 150, 255,
},
bgra);
}
[Fact]
public void CopyNv12ToGuestBuffer_UsesSourceStridesAndPitchedUvOffset()
{
const int width = 4;
const int height = 4;
const int sourceLumaStride = 6;
const int sourceChromaStride = 8;
const int destinationPitch = 8;
var source = Enumerable.Repeat((byte)0xEE, 40).ToArray();
for (var row = 0; row < height; row++)
{
for (var column = 0; column < width; column++)
{
source[(row * sourceLumaStride) + column] = checked((byte)(1 + (row * 10) + column));
}
}
var sourceChromaOffset = sourceLumaStride * height;
for (var row = 0; row < height / 2; row++)
{
for (var column = 0; column < width; column++)
{
source[sourceChromaOffset + (row * sourceChromaStride) + column] =
checked((byte)(101 + (row * 10) + column));
}
}
var destination = Enumerable.Repeat((byte)0xCC, 48).ToArray();
AvPlayerExports.CopyNv12ToGuestBuffer(
source,
destination,
width,
height,
sourceLumaStride,
sourceChromaStride,
destinationPitch);
var expected = new byte[48];
for (var row = 0; row < height; row++)
{
source.AsSpan(row * sourceLumaStride, width)
.CopyTo(expected.AsSpan(row * destinationPitch, width));
}
var destinationChromaOffset = destinationPitch * height;
for (var row = 0; row < height / 2; row++)
{
source.AsSpan(sourceChromaOffset + (row * sourceChromaStride), width)
.CopyTo(expected.AsSpan(destinationChromaOffset + (row * destinationPitch), width));
}
Assert.Equal(expected, destination);
}
}
@@ -19,39 +19,36 @@ public sealed class AvPlayerStreamInfoTests
private const byte Sentinel = 0xAB;
[Theory]
[InlineData(Generation.Gen5, 0u, 32, 1u)]
[InlineData(Generation.Gen5, 1u, 32, 2u)]
[InlineData(Generation.Gen4, 0u, 40, 0u)]
[InlineData(Generation.Gen4, 1u, 40, 1u)]
public void GetStreamInfoUsesTheGenerationSpecificLayout(
Generation generation,
uint streamIndex,
int structureSize,
uint expectedStreamType)
[InlineData(false, 0u)]
[InlineData(true, 0u)]
[InlineData(false, 1u)]
[InlineData(true, 1u)]
public void GetStreamInfoFunctionsDoNotWritePastThe32ByteStructure(
bool useExtendedFunction,
uint streamIndex)
{
var memory = new FakeCpuMemory(BaseAddress, MemorySize);
var context = new CpuContext(memory, generation);
AvPlayerExports.RegisterPlayerForTest(
Handle,
1280,
720,
DurationMilliseconds,
hasAudio: true);
var context = new CpuContext(memory, Generation.Gen5);
AvPlayerExports.RegisterPlayerForTest(Handle, 1280, 720, DurationMilliseconds);
try
{
Span<byte> window = stackalloc byte[48];
Span<byte> window = stackalloc byte[40];
window.Fill(Sentinel);
Assert.True(memory.TryWrite(InfoAddress, window));
context[CpuRegister.Rdi] = Handle;
context[CpuRegister.Rsi] = streamIndex;
context[CpuRegister.Rdx] = InfoAddress;
Assert.Equal(0, AvPlayerExports.AvPlayerGetStreamInfo(context));
Span<byte> result = stackalloc byte[48];
var resultCode = useExtendedFunction
? AvPlayerExports.AvPlayerGetStreamInfoEx(context)
: AvPlayerExports.AvPlayerGetStreamInfo(context);
Assert.Equal(0, resultCode);
Span<byte> result = stackalloc byte[40];
Assert.True(memory.TryRead(InfoAddress, result));
Assert.Equal(expectedStreamType, BinaryPrimitives.ReadUInt32LittleEndian(result));
Assert.Equal(streamIndex, BinaryPrimitives.ReadUInt32LittleEndian(result));
if (streamIndex == 0)
{
Assert.Equal(1280u, BinaryPrimitives.ReadUInt32LittleEndian(result[8..]));
@@ -64,71 +61,7 @@ public sealed class AvPlayerStreamInfoTests
}
Assert.Equal(DurationMilliseconds, BinaryPrimitives.ReadUInt64LittleEndian(result[24..]));
for (var index = structureSize; index < result.Length; index++)
{
Assert.Equal(Sentinel, result[index]);
}
}
finally
{
AvPlayerExports.RemovePlayerForTest(Handle);
}
}
[Fact]
public void StreamInfoRejectsAudioIndexForVideoOnlyMedia()
{
var memory = new FakeCpuMemory(BaseAddress, MemorySize);
var context = new CpuContext(memory, Generation.Gen5);
AvPlayerExports.RegisterPlayerForTest(Handle, 1280, 720, DurationMilliseconds);
try
{
context[CpuRegister.Rdi] = Handle;
context[CpuRegister.Rsi] = 1;
context[CpuRegister.Rdx] = InfoAddress;
Assert.NotEqual(0, AvPlayerExports.AvPlayerGetStreamInfo(context));
Assert.NotEqual(0, AvPlayerExports.AvPlayerGetStreamInfoEx(context));
}
finally
{
AvPlayerExports.RemovePlayerForTest(Handle);
}
}
[Fact]
public void GetStreamInfoExWritesThe104ByteGen5Descriptor()
{
var memory = new FakeCpuMemory(BaseAddress, MemorySize);
var context = new CpuContext(memory, Generation.Gen5);
AvPlayerExports.RegisterPlayerForTest(
Handle,
378,
150,
DurationMilliseconds,
framesPerSecond: 29.97);
try
{
Span<byte> window = stackalloc byte[120];
window.Fill(Sentinel);
Assert.True(memory.TryWrite(InfoAddress, window));
context[CpuRegister.Rdi] = Handle;
context[CpuRegister.Rsi] = 0;
context[CpuRegister.Rdx] = InfoAddress;
Assert.Equal(0, AvPlayerExports.AvPlayerGetStreamInfoEx(context));
Span<byte> result = stackalloc byte[120];
Assert.True(memory.TryRead(InfoAddress, result));
Assert.Equal(104UL, BinaryPrimitives.ReadUInt64LittleEndian(result));
Assert.Equal(1u, BinaryPrimitives.ReadUInt32LittleEndian(result[8..]));
Assert.Equal(378u, BinaryPrimitives.ReadUInt32LittleEndian(result[16..]));
Assert.Equal(150u, BinaryPrimitives.ReadUInt32LittleEndian(result[20..]));
Assert.Equal(29.97, BinaryPrimitives.ReadDoubleLittleEndian(result[0x40..]));
Assert.Equal(DurationMilliseconds, BinaryPrimitives.ReadUInt64LittleEndian(result[0x60..]));
for (var index = 104; index < result.Length; index++)
for (var index = 32; index < result.Length; index++)
{
Assert.Equal(Sentinel, result[index]);
}
@@ -146,12 +79,7 @@ public sealed class AvPlayerStreamInfoTests
{
var memory = new FakeCpuMemory(BaseAddress, MemorySize);
var context = new CpuContext(memory, Generation.Gen5);
AvPlayerExports.RegisterPlayerForTest(
Handle,
1280,
720,
DurationMilliseconds,
hasAudio: true);
AvPlayerExports.RegisterPlayerForTest(Handle, 1280, 720, DurationMilliseconds);
try
{
@@ -1,192 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
using System.Diagnostics;
using System.Runtime.InteropServices;
using SharpEmu.Core.Cpu;
using SharpEmu.Core.Cpu.Native;
using SharpEmu.Core.Loader;
using SharpEmu.Core.Memory;
using SharpEmu.HLE;
using Xunit;
namespace SharpEmu.Libs.Tests.Cpu;
public sealed class Gen5NativeReturnSmokeTests
{
private const string WorkerEnvironmentVariable = "SHARPEMU_NATIVE_RETURN_SMOKE_WORKER";
private static readonly TimeSpan WorkerTimeout = TimeSpan.FromSeconds(30);
[Fact]
public async Task SyntheticGen5Entry_ReturnsToHost()
{
if (!IsSupportedHost)
{
return;
}
if (string.Equals(
Environment.GetEnvironmentVariable(WorkerEnvironmentVariable),
"1",
StringComparison.Ordinal))
{
ExecuteSyntheticGuest();
return;
}
var result = await RunIsolatedWorker();
Assert.True(
result.Completed,
$"native return worker did not exit within {WorkerTimeout.TotalSeconds:F0} seconds\n{result.Output}");
Assert.True(
result.ExitCode == 0,
$"native return worker exited with code {result.ExitCode}\n{result.Output}");
}
private static bool IsSupportedHost =>
RuntimeInformation.ProcessArchitecture == Architecture.X64 &&
(OperatingSystem.IsWindows() || OperatingSystem.IsLinux() || OperatingSystem.IsMacOS());
private static void ExecuteSyntheticGuest()
{
using var memory = new PhysicalVirtualMemory();
var image = new SelfLoader().Load(BuildSyntheticElf(), memory);
Assert.Equal((byte)2, image.ElfHeader.AbiVersion);
Assert.Equal(0x0000_0008_0000_1000UL, image.EntryPoint);
var moduleManager = new ModuleManager();
moduleManager.Freeze();
var backend = new DirectExecutionBackend(moduleManager);
using var dispatcher = new CpuDispatcher(memory, moduleManager, backend);
var result = dispatcher.DispatchEntry(
image.EntryPoint,
Generation.Gen5,
image.ImportStubs,
image.RuntimeSymbols,
"synthetic-native-return",
new CpuExecutionOptions
{
CpuEngine = CpuExecutionEngine.NativeOnly,
EnableDisasmDiagnostics = false,
StrictDynlibResolution = true,
ImportTraceLimit = 0,
DebugHook = null
});
Assert.Equal(OrbisGen2Result.ORBIS_GEN2_OK, result);
Assert.Equal(OrbisGen2Result.ORBIS_GEN2_OK, dispatcher.LastSessionSummary.Result);
Assert.Equal(CpuExitReason.ReturnedToHost, dispatcher.LastSessionSummary.Reason);
Assert.Equal(0, dispatcher.LastSessionSummary.ImportsHit);
Assert.Equal(0, dispatcher.LastSessionSummary.UniqueNidsHit);
Assert.Null(dispatcher.LastTrapInfo);
Assert.Null(dispatcher.LastMemoryFaultInfo);
Assert.Null(dispatcher.LastNotImplementedInfo);
}
private static async Task<WorkerResult> RunIsolatedWorker()
{
var startInfo = new ProcessStartInfo
{
FileName = ResolveDotnetHost(),
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
startInfo.ArgumentList.Add("test");
startInfo.ArgumentList.Add(typeof(Gen5NativeReturnSmokeTests).Assembly.Location);
startInfo.ArgumentList.Add("--filter");
startInfo.ArgumentList.Add(
$"FullyQualifiedName={typeof(Gen5NativeReturnSmokeTests).FullName}.{nameof(SyntheticGen5Entry_ReturnsToHost)}");
startInfo.Environment[WorkerEnvironmentVariable] = "1";
startInfo.Environment["SHARPEMU_SENTINEL_PROBE"] = null;
using var process = Process.Start(startInfo) ??
throw new InvalidOperationException("Could not start the isolated native return worker.");
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
try
{
await process.WaitForExitAsync().WaitAsync(WorkerTimeout);
}
catch (TimeoutException)
{
process.Kill(entireProcessTree: true);
await process.WaitForExitAsync();
return new WorkerResult(false, process.ExitCode, await ReadOutput(stdout, stderr));
}
return new WorkerResult(true, process.ExitCode, await ReadOutput(stdout, stderr));
}
private static string ResolveDotnetHost()
{
var configuredHost = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH");
if (!string.IsNullOrWhiteSpace(configuredHost))
{
return configuredHost;
}
var processPath = Environment.ProcessPath;
if (processPath is not null &&
string.Equals(
Path.GetFileNameWithoutExtension(processPath),
"dotnet",
StringComparison.OrdinalIgnoreCase))
{
return processPath;
}
return "dotnet";
}
private static async Task<string> ReadOutput(Task<string> stdout, Task<string> stderr) =>
await stdout + await stderr;
private static byte[] BuildSyntheticElf()
{
const int elfHeaderSize = 0x40;
const int programHeaderSize = 0x38;
const int fileOffset = 0x1000;
const ulong entryPoint = 0x1000;
ReadOnlySpan<byte> payload = [0x31, 0xC0, 0xC3]; // xor eax, eax; ret
var image = new byte[fileOffset + payload.Length];
image[0] = 0x7F;
image[1] = (byte)'E';
image[2] = (byte)'L';
image[3] = (byte)'F';
image[4] = 2;
image[5] = 1;
image[6] = 1;
image[7] = 9;
image[8] = 2;
BinaryPrimitives.WriteUInt16LittleEndian(image.AsSpan(0x10), 3);
BinaryPrimitives.WriteUInt16LittleEndian(image.AsSpan(0x12), 0x3E);
BinaryPrimitives.WriteUInt32LittleEndian(image.AsSpan(0x14), 1);
BinaryPrimitives.WriteUInt64LittleEndian(image.AsSpan(0x18), entryPoint);
BinaryPrimitives.WriteUInt64LittleEndian(image.AsSpan(0x20), elfHeaderSize);
BinaryPrimitives.WriteUInt16LittleEndian(image.AsSpan(0x34), elfHeaderSize);
BinaryPrimitives.WriteUInt16LittleEndian(image.AsSpan(0x36), programHeaderSize);
BinaryPrimitives.WriteUInt16LittleEndian(image.AsSpan(0x38), 1);
var programHeader = image.AsSpan(elfHeaderSize, programHeaderSize);
BinaryPrimitives.WriteUInt32LittleEndian(programHeader, 1);
BinaryPrimitives.WriteUInt32LittleEndian(programHeader[0x04..], 5);
BinaryPrimitives.WriteUInt64LittleEndian(programHeader[0x08..], fileOffset);
BinaryPrimitives.WriteUInt64LittleEndian(programHeader[0x10..], entryPoint);
BinaryPrimitives.WriteUInt64LittleEndian(programHeader[0x18..], entryPoint);
BinaryPrimitives.WriteUInt64LittleEndian(programHeader[0x20..], (ulong)payload.Length);
BinaryPrimitives.WriteUInt64LittleEndian(programHeader[0x28..], (ulong)payload.Length);
BinaryPrimitives.WriteUInt64LittleEndian(programHeader[0x30..], 0x1000);
payload.CopyTo(image.AsSpan(fileOffset));
return image;
}
private sealed record WorkerResult(bool Completed, int ExitCode, string Output);
}
@@ -104,45 +104,6 @@ public sealed class GuestMemoryAllocatorTests
Assert.Equal(0UL, (ulong)memory.GetPointer(address));
}
[Fact]
public void AdjacentFixedGuestPageMappingsShareAHostGranule()
{
if (!OperatingSystem.IsWindows())
{
return;
}
using var memory = new PhysicalVirtualMemory(new GranularityAwareHostMemory());
const ulong baseAddress = 0x0000008001600000;
Assert.Equal(baseAddress, memory.AllocateAt(baseAddress, 0x4000, executable: false, allowAlternative: false));
Assert.Equal(
baseAddress + 0x4000,
memory.AllocateAt(baseAddress + 0x4000, 0x4000, executable: false, allowAlternative: false));
Assert.Equal(
baseAddress + 0x8000,
memory.AllocateAt(baseAddress + 0x8000, 0x8000, executable: false, allowAlternative: false));
Assert.True(memory.IsAccessible(baseAddress, 0x10000));
}
[Fact]
public void TryBackFixedRangeSharesAHostGranuleAcrossCallsOnWindows()
{
if (!OperatingSystem.IsWindows())
{
return;
}
using var memory = new PhysicalVirtualMemory(new GranularityAwareHostMemory());
const ulong baseAddress = 0x0000008001600000;
Assert.True(memory.TryBackFixedRange(baseAddress, 0x4000, executable: false));
Assert.True(memory.TryBackFixedRange(baseAddress + 0x4000, 0x4000, executable: false));
Assert.True(memory.IsAccessible(baseAddress, 0x8000));
}
[Fact]
public void AlignedAllocationDoesNotRetainOverallocatedMappingsOutsideMacOS()
{
@@ -172,11 +133,6 @@ public sealed class GuestMemoryAllocatorTests
[Fact]
public void TryBackFixedRangeRollsBackEarlierGapsWhenLaterGapCannotBeBacked()
{
if (OperatingSystem.IsWindows())
{
return;
}
// Layout: committed | free | committed | free
// First free gap allocates successfully, second fails.
// The first allocation must be freed — nothing should leak.
@@ -198,11 +154,6 @@ public sealed class GuestMemoryAllocatorTests
[Fact]
public void TryBackFixedRangeFillsOnlyTheFreePagesOfAPartiallyOccupiedRange()
{
if (OperatingSystem.IsWindows())
{
return;
}
const ulong rangeBase = 0x0000_0020_2F00_0000;
const ulong rangeSize = 0x40_0000;
const ulong occupiedSize = 0x4_0000;
@@ -568,154 +519,6 @@ public sealed class GuestMemoryAllocatorTests
}
}
private sealed class GranularityAwareHostMemory : IHostMemory
{
private const ulong Granularity = 0x10000;
private const ulong Page = 0x1000;
private readonly SortedDictionary<ulong, (ulong Size, SortedSet<ulong> CommittedPages)> _allocations = new();
public ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection)
{
var reservedBase = Reserve(desiredAddress, size, protection);
if (reservedBase != 0)
{
var start = desiredAddress == 0 ? reservedBase : AlignDown(desiredAddress, Page);
Commit(start, size, protection);
}
return reservedBase;
}
public ulong Reserve(ulong desiredAddress, ulong size, HostPageProtection protection)
{
if (desiredAddress == 0)
{
return 0;
}
var allocationBase = AlignDown(desiredAddress, Granularity);
var end = AlignUp(desiredAddress + size, Page);
foreach (var (existingBase, existing) in _allocations)
{
if (allocationBase < existingBase + existing.Size && existingBase < end)
{
return 0;
}
}
_allocations[allocationBase] = (end - allocationBase, new SortedSet<ulong>());
return allocationBase;
}
public bool Commit(ulong address, ulong size, HostPageProtection protection)
{
var start = AlignDown(address, Page);
var end = AlignUp(address + size, Page);
if (!TryFindAllocation(start, out var allocationBase, out var allocation) ||
end > allocationBase + allocation.Size)
{
return false;
}
for (var page = start; page < end; page += Page)
{
allocation.CommittedPages.Add(page);
}
return true;
}
public bool Free(ulong address) => _allocations.Remove(address);
public bool Protect(ulong address, ulong size, HostPageProtection protection, out uint rawOldProtection)
{
rawOldProtection = 0;
return true;
}
public bool ProtectRaw(ulong address, ulong size, uint rawProtection, out uint rawOldProtection)
{
rawOldProtection = 0;
return true;
}
public bool Query(ulong address, out HostRegionInfo info)
{
var page = AlignDown(address, Page);
if (TryFindAllocation(page, out var allocationBase, out var allocation))
{
var committed = allocation.CommittedPages.Contains(page);
var runEnd = page + Page;
while (runEnd < allocationBase + allocation.Size &&
allocation.CommittedPages.Contains(runEnd) == committed)
{
runEnd += Page;
}
info = new HostRegionInfo(
page,
allocationBase,
runEnd - page,
committed ? HostRegionState.Committed : HostRegionState.Reserved,
0,
committed ? HostPageProtection.ReadWrite : HostPageProtection.NoAccess,
0,
0);
return true;
}
var freeEnd = ulong.MaxValue;
foreach (var existingBase in _allocations.Keys)
{
if (existingBase > page)
{
freeEnd = existingBase;
break;
}
}
info = new HostRegionInfo(
page,
0,
freeEnd - page,
HostRegionState.Free,
0,
HostPageProtection.NoAccess,
0,
0);
return true;
}
public void FlushInstructionCache(ulong address, ulong size)
{
}
private bool TryFindAllocation(
ulong address,
out ulong allocationBase,
out (ulong Size, SortedSet<ulong> CommittedPages) allocation)
{
foreach (var (existingBase, existing) in _allocations)
{
if (address >= existingBase && address < existingBase + existing.Size)
{
allocationBase = existingBase;
allocation = existing;
return true;
}
}
allocationBase = 0;
allocation = default;
return false;
}
private static ulong AlignDown(ulong value, ulong alignment) => value & ~(alignment - 1);
private static ulong AlignUp(ulong value, ulong alignment) => (value + alignment - 1) & ~(alignment - 1);
}
private sealed class LazyHostMemory(ulong address) : IHostMemory, IDisposable
{
public bool CommitSucceeds { get; set; } = true;
@@ -1,56 +0,0 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using Silk.NET.Vulkan;
using SharpEmu.Libs.VideoOut;
using Xunit;
namespace SharpEmu.Libs.Tests.VideoOut;
public sealed class VulkanFormatConversionTests
{
[Theory]
[InlineData(Format.R8G8B8A8Unorm, Format.A2R10G10B10UnormPack32, true)]
[InlineData(Format.R8G8B8A8Unorm, Format.A2B10G10R10UnormPack32, true)]
[InlineData(Format.A2R10G10B10UnormPack32, Format.R8G8B8A8Unorm, true)]
[InlineData(Format.A2B10G10R10UnormPack32, Format.R8G8B8A8Unorm, true)]
public void RequiresRealFormatConversion_FlagsTheBitIncompatiblePair(
Format from,
Format to,
bool expected)
{
Assert.Equal(expected, VulkanVideoPresenter.RequiresRealFormatConversion(from, to));
}
[Theory]
[InlineData(Format.R8G8B8A8Unorm, Format.B8G8R8A8Unorm)]
[InlineData(Format.R8G8B8A8Unorm, Format.R8G8B8A8Srgb)]
[InlineData(Format.R8G8B8A8Unorm, Format.R8G8B8A8Unorm)]
[InlineData(Format.A2R10G10B10UnormPack32, Format.A2B10G10R10UnormPack32)]
[InlineData(Format.R16G16B16A16Sfloat, Format.R32G32Sfloat)]
public void RequiresRealFormatConversion_LeavesEveryOtherPairAlone(Format from, Format to)
{
Assert.False(VulkanVideoPresenter.RequiresRealFormatConversion(from, to));
}
[Fact]
public void BitCastOfOpaqueBlackRgba8AsA2r10g10b10_ProducesTheObservedRed()
{
const uint opaqueBlackRgba8 = 0xFF000000u; // bytes 00 00 00 FF, little-endian
var alpha2Bit = (opaqueBlackRgba8 >> 30) & 0x3u;
var red10Bit = (opaqueBlackRgba8 >> 20) & 0x3FFu;
var green10Bit = (opaqueBlackRgba8 >> 10) & 0x3FFu;
var blue10Bit = opaqueBlackRgba8 & 0x3FFu;
Assert.Equal(3u, alpha2Bit);
Assert.Equal(1008u, red10Bit);
Assert.Equal(0u, green10Bit);
Assert.Equal(0u, blue10Bit);
var redAsFloat = red10Bit / 1023.0;
Assert.True(
Math.Abs(redAsFloat - 0.9853372434443793) < 0.0001,
$"expected ~0.9853 (matches the red observed live), got {redAsFloat}");
}
}
@@ -53,6 +53,7 @@ public sealed class VulkanGuestImageAliasTests
}
[Theory]
[InlineData(Format.R8Srgb, Format.R8Unorm)]
[InlineData(Format.BC3SrgbBlock, Format.BC3UnormBlock)]
public void CounterpartsOutsideTheViewClassTableAreNotAliased(
Format existing,
@@ -67,15 +68,6 @@ public sealed class VulkanGuestImageAliasTests
VulkanVideoPresenter.IsAliasableGuestImageFormat(existing, requested));
}
[Fact]
public void R8SrgbAndR8UnormShareOneCompatibilityClass()
{
Assert.True(
VulkanVideoPresenter.IsCompatibleGuestImageViewFormat(
Format.R8Srgb,
Format.R8Unorm));
}
[Fact]
public void AliasedPairStaysWithinOneCompatibilityClass()
{